branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># Simpo SDK for Android ## Installation Installation of the SDK done through JitPack. For instructions go to https://jitpack.io/#simpoio/android-sdk And follow the instructions. ## Documentation - #### init(ucid: string, options: SimpoOptions) options(SimpoUser user, String uuid, boolean showWidget, SimpoWidgetPosition position, int widgetWidth, int widgetHeight) - user: <optional>:SimpoUser(String email, String name) - uuid - unique client id - showWiget: show or hide the widget - position: can receive one of the below values: * BOTTOM_LEFT * BOTTOM_RIGHT * TOP_LEFT * TOP_RIGHT - #### open() must be called after init, will open Simpo interface ### Example of usage ``` import io.simpo.simpobutton.model.SimpoInstance; import io.simpo.simpobutton.model.SimpoOptions; import io.simpo.simpobutton.model.SimpoPlatform; import io.simpo.simpobutton.model.SimpoUser; import io.simpo.simpobutton.model.SimpoGeneral; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SimpoPlatform.init("exampleUCIDNumber", new SimpoOptions(new SimpoUser("", ""), "myclientuuid", true, SimpoGeneral.SimpoWidgetPosition.BOTTOM_RIGHT, 60 , 60), this); ``` <file_sep>include ':app', ':simpobutton' <file_sep>package io.simpo.simpobutton.fragment; import android.view.View; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import io.simpo.simpobutton.model.SimpoConfig; import io.simpo.simpobutton.model.SimpoPlatform; import io.simpo.simpobutton.model.SimpoGeneral; public class WebViewClientForWidgetClick extends WebViewClient { private final String TAG = "WebViewClientForWidgetClick"; private SimpoPlatform simpoPlatform; public WebViewClientForWidgetClick(SimpoPlatform simpo) { simpoPlatform = simpo; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { super.shouldOverrideUrlLoading(view, url); if(url.equalsIgnoreCase(SimpoConfig.LINK_WIDGET_TAP)) { SimpoGeneral.SimpoLog(TAG, "Simpo SDK: received simpo message: " + SimpoConfig.LINK_WIDGET_TAP); simpoPlatform.open(); } return true; } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); view.setVisibility(View.GONE); } } <file_sep>package io.simpo.simpobutton.fragment; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatDialogFragment; import androidx.fragment.app.FragmentActivity; import io.simpo.simpobutton.R; import io.simpo.simpobutton.model.SimpoPlatform; public class SimpoInterface extends AppCompatDialogFragment { private static final String URL_ARG = "url"; private final WebViewClientForInterfaceClose webViewClient = new WebViewClientForInterfaceClose(); private SimpoPlatform simpo; private View view; public WebView webView; private boolean isFirstStart = true; private boolean isShowed; private static final String TAG = "SimpoInterface"; public static SimpoInterface newInstance(String url) { SimpoInterface simpoInterface = new SimpoInterface(); Bundle args = new Bundle(); args.putString(URL_ARG, url); simpoInterface.setArguments(args); return simpoInterface; } public void setSimpo(SimpoPlatform simpo) { this.simpo = simpo; webViewClient.simpoPlatform = simpo; webViewClient.simpoInterface = this; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(AppCompatDialogFragment.STYLE_NO_FRAME, android.R.style.Theme); } @NonNull @SuppressLint("SetJavaScriptEnabled") @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.simpo_fragment, null); alertDialogBuilder.setView(view); AlertDialog alertDialog = alertDialogBuilder.create(); webView = view.findViewById(R.id.dialogWebView); webView.getSettings().setDomStorageEnabled(true); webView.setBackgroundColor(Color.TRANSPARENT); webView.getSettings().setJavaScriptEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } webView.setWebViewClient(webViewClient); webView.loadUrl(getArguments().getString(URL_ARG)); alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); return alertDialog; } @Override public void onStart() { super.onStart(); if(isFirstStart) { Dialog dialog = getDialog(); if (dialog != null) { int width = ViewGroup.LayoutParams.MATCH_PARENT; int height = ViewGroup.LayoutParams.MATCH_PARENT; dialog.getWindow().setLayout(width, height); } if(getDialog() != null) getDialog().hide(); isFirstStart = false; } if(!isShowed && getDialog() != null) getDialog().hide(); } public void open(boolean calJSSimpoOpen) { if(getDialog() != null) getDialog().show(); if(calJSSimpoOpen) { webView.loadUrl("javascript:(function(){if(window.simpo && window.simpo.open) {window.simpo.open();} else {counter = 10; var interval = setInterval(function() {if(window.simpo && window.simpo.open) {window.simpo.open();clearInterval(interval)}counter--;if(!counter){clearInterval();}}, 1000)}})();"); } isShowed = true; } public void close() { if(getDialog() != null) { getDialog().hide(); } isShowed = false; } public void deinitialize(FragmentActivity activity) { simpo.deinitialize(activity); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onDismiss(@NonNull DialogInterface dialog) { if(simpo != null) { simpo.close(); } } } <file_sep>package io.simpo.simpobutton.model; import android.util.Log; import io.simpo.simpobutton.BuildConfig; public class SimpoGeneral { public static void SimpoLog(String tag, String text) { if(SimpoConfig.IS_PROD) { } else { Log.e(tag, text); } } public enum SimpoWidgetPosition { BOTTOM_LEFT(0), BOTTOM_RIGHT(1), TOP_LEFT(2), TOP_RIGHT(3); private final int value; private SimpoWidgetPosition(int value) { this.value = value; } public int getValue() { return value; } } }
92388bf82185475318c261e26ae66bbc6458aefe
[ "Markdown", "Java", "Gradle" ]
5
Markdown
simpoio/android-sdk
d0c67927e974d00cc70a2dac65203061fe643e44
d7f236534ff7006d095e4e3d0e8323cbd260a082
refs/heads/master
<file_sep><?php namespace Inori\TwitterAppBundle\DependencyInjection; use Symfony\Component\Config\Definition\Processor; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; class InoriTwitterAppExtension extends Extension { protected $resources = array( 'twitter_app' => 'twitter_app.xml', ); public function load(array $configs, ContainerBuilder $container) { $processor = new Processor(); $configuration = new Configuration(); $config = $processor->processConfiguration($configuration, $configs); $this->loadDefaults($container); if (isset($config['alias'])) { $container->setAlias($config['alias'], 'inori_twitter_app'); } foreach (array('file', 'consumer_key', 'consumer_secret', 'oauth_token', 'oauth_token_secret') as $attribute) { if (isset($config[$attribute])) { $container->setParameter('inori_twitter_app.'.$attribute, $config[$attribute]); } } } protected function loadDefaults($container) { $loader = new XmlFileLoader($container, new FileLocator(array(__DIR__.'/../Resources/config', __DIR__.'/Resources/config'))); foreach ($this->resources as $resource) { $loader->load($resource); } } }
f05e7a9f4e8cbb1d0a505819c0c5e7cdbffec17d
[ "PHP" ]
1
PHP
Inoryy/InoriTwitterAppBundle
36b934256027db5ad37401de7249a6bb1f586aae
b7ede6b71585dae1a368242df9bee9a64791050f
refs/heads/main
<file_sep>import React from "react"; import { Link } from "react-router-dom"; import logo from "../../images/logos/logo.png"; //** Import FontAwesome */ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faShoppingBag } from "@fortawesome/free-solid-svg-icons"; import { faPlus } from "@fortawesome/free-solid-svg-icons"; import { faUserPlus } from "@fortawesome/free-solid-svg-icons"; const AdminSidebar = () => { return ( <div className="col-md-3"> <div className="sidebar"> {/* <!-- Sidebar Logo --!> */} <Link to="/"> <div className="sidebar-img"> <img src={logo} alt="" /> </div> </Link> {/* <!-- Sidebar Route --!> */} <div className="sidebar-route"> <Link to="/allUser"> <button> <FontAwesomeIcon icon={faShoppingBag} /> Service List </button> </Link> <Link to="/addService"> <button> <FontAwesomeIcon icon={faPlus} /> Add Service </button> </Link> <Link to="/makeAdmin"> <button> <FontAwesomeIcon icon={faUserPlus} /> Make Admin </button> </Link> </div> </div> </div> ); }; export default AdminSidebar; <file_sep>import React from "react"; const Footer = () => { return ( <div className="footer-section input-box-bg"> <div className="container"> <div className="row"> <div className="col-md-6 col-sm-6 col-12"> {/** Footer Content **/} <div className="footer-title"> <h2> Let us handle your <br /> project, professionally. </h2> <p> With well written codes, we build amazing apps for all platforms, mobile and web apps in general. </p> </div> </div> <div className="col-md-6 col-sm-6 col-12"> {/** Footer Form Box **/} <form> <div class="form-group"> <input type="email" required class="form-control" aria-describedby="emailHelp" placeholder="Your email address" /> </div> <div class="form-group"> <input type="text" required class="form-control" placeholder="Your name / company’s name" /> </div> <div class="form-group"> <textarea class="form-control" rows="3" required placeholder="Your message" ></textarea> </div> <button type="submit" class="section-btn"> Send </button> </form> </div> </div> <div className="row"> <div className="col-md-10 offset-md-1 col-sm-12 col-12 text-center footer-bottom"> <p>copyright Orange labs {`${new Date().getFullYear()}`}</p> </div> </div> </div> </div> ); }; export default Footer; <file_sep>import React, { useContext, useState } from "react"; import { Link } from "react-router-dom"; import { UserContext } from "../../App"; //** Import Popup Modal */ import Modal from "react-modal"; import { signOutHandler } from "./LoginManager"; //** Custom Styles Popup Modal */ const customStyles = { content: { top: "50%", left: "50%", right: "auto", bottom: "auto", marginRight: "-50%", transform: "translate(-50%, -50%)", }, }; //** Root set Popup Modal */ Modal.setAppElement("#root"); const ModalLogin = () => { //** Data Come Form Context API */ const { loggedInUser, setLoggedInUser } = useContext(UserContext); const [modalIsOpen, setIsOpen] = useState(false); const openModal = () => { setIsOpen(true); }; const closeModal = () => { setIsOpen(false); }; //** Google Sign Out Handler */ const googleSignOut = () => { signOutHandler().then((res) => { setLoggedInUser(res); }); }; return ( <> {loggedInUser.email ? ( <button onClick={googleSignOut} className="section-btn btn-danger"> Logout </button> ) : ( <button onClick={openModal} className="section-btn"> Login </button> )} {/** Popup Modal **/} <Modal isOpen={modalIsOpen} onRequestClose={closeModal} style={customStyles} contentLabel="Example Modal" > <button className="btn btn-danger px-2" onClick={closeModal}> close </button> <h2 className="text-center mb-4"> Login Here </h2> <div className="modal-login d-flex justify-content-around mb-4"> <Link to="/adminLogin"> <button onClick={openModal} className="section-btn bg-warning mr-4" > Login as a Admin </button> </Link> <Link to="/userLogin"> <button onClick={openModal} className="section-btn"> Login as a User </button> </Link> </div> </Modal> </> ); }; export default ModalLogin; <file_sep>import React from "react"; import { Link } from "react-router-dom"; import logo from "../../../images/logos/logo.png"; import ModalLogin from "../../Auth/ModalLogin"; const Navbar = () => { return ( <div className="row navbar"> <div className="col-md-3 col-sm-12 col-12"> <Link to="/"> <div className="logo"> <img src={logo} alt="" /> </div> </Link> </div> <div className="col-md-9 col-sm-12 col-12"> <div className="main-menu d-flex justify-content-end"> <ul> <Link to="/"> Home </Link> <Link to="/ourPortfolio"> Our Portfolio </Link> <Link to="/ourTeam"> Our Team </Link> <Link to="/contactUs"> Contact Us </Link> {/** Popup Modal **/} <ModalLogin></ModalLogin> </ul> </div> </div> </div> ); }; export default Navbar; <file_sep>import React, { useContext } from "react"; import { Link, useHistory, useLocation } from "react-router-dom"; import logo from "../../images/logos/logo.png"; import googleLogo from "../../images/logos/google-icon.png"; import { UserContext } from "../../App"; //** Fire Base */ import * as firebase from "firebase/app"; import firebaseConfig from "./firebase.config"; import "firebase/auth"; //** Login Manager */ import { googleSignINHandler } from "./LoginManager.js"; import { useState } from "react"; const UserLogin = () => { //** Data Come Form Context API */ const { loggedInUser, setLoggedInUser } = useContext(UserContext); //** Firebase Config */ if (firebase.apps.length === 0) { firebase.initializeApp(firebaseConfig); } //** useState Hook */ const [newUser, setNewUser] = useState(false); //** useHistory & useLocation for state location */ let history = useHistory(); let location = useLocation(); const { from } = location.state || { from: { pathname: "/" } }; // //** useState Hook */ const [user, setUser] = useState({ isSignedIn: false, fastName: "", lastName: "", email: "", password: "", photo: "", error: "", successful: false, }); //** Google SignIN Handler */ const googleSignIn = () => { googleSignINHandler() .then((res) => { setUser(res); setLoggedInUser(res); // storeAuthToken(); history.replace(from); }) .catch((error) => { console.log(error); console.log(error.message); setUser(error.message); }); }; return ( <div className="container"> <div className="row text-center"> <div className="col-md-6 offset-md-3"> {/* <!-- Root Logo --!> */} <div className="root-logo"> <Link to="/"> <img src={logo} alt="" /> </Link> </div> {/* <!-- Login Box --!> */} <div className="login-box"> {newUser ? ( <h2>Create an account</h2> ) : ( <h2> Login as a User </h2> )} {/* <!-- Google SignIN --!> */} <button onClick={googleSignIn} className="btn"> <img src={googleLogo} alt="" /> Continue with Google </button> <p> Don’ t have an account ? <span onClick={() => setNewUser(!newUser)} name="newUser"> {newUser ? " login" : " Create an account"} </span> </p> </div> </div> </div> </div> ); }; export default UserLogin; <file_sep>import React from "react"; import Navbar from "./Navbar"; import headerImage from "../../../images/logos/header-img.png"; const Headers = () => { return ( <div className="header-section"> <div className="container"> {/** Navbar **/} <Navbar></Navbar> <div className="header-content"> <div className="row"> <div className="col-md-5 col-sm-12 col-12"> <div className="header-content"> <h1> Let’s Grow Your <br /> Brand To The <br /> Next Level </h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Purus commodo ipsum duis laoreet maecenas. Feugiat </p> <button className="section-btn">Hire Us</button> </div> </div> <div className="col-md-7 col-sm-12 col-12"> <div className="header-image"> <img className="img-fluid" src={headerImage} alt="" /> </div> </div> </div> </div> </div> </div> ); }; export default Headers; <file_sep>import React from "react"; const SingleFeedback = ({ feedBack }) => { return ( <div className="col-md-4 col-sm-6 col-12 "> <div className="single-feedback"> <div className="feedback-img d-inline-flex"> <img src={feedBack.photo} alt="" /> <div className="feedback-content"> <h3>{feedBack.fastName}</h3> <h5>{feedBack.companyName}</h5> </div> </div> <div className="feedback-comments"></div> <p>{feedBack.personalDescription}</p> </div> </div> ); }; export default SingleFeedback; <file_sep>import React from "react"; import Feedback from "../TemplateParts/Feedback/Feedback"; import Footer from "../TemplateParts/Footer/Footer"; //** Import Template Parts */ import Headers from "../TemplateParts/Headers/Headers"; import OurWorks from "../TemplateParts/OurWorks/OurWorks"; import Services from "../TemplateParts/Services/Services"; import Sponsored from "../TemplateParts/Sponsored/Sponsored"; const Home = () => { return ( <> <Headers></Headers> <div className="container"> <Sponsored></Sponsored> <Services></Services> </div> <OurWorks></OurWorks> <div className="container"> <Feedback></Feedback> </div> <Footer></Footer> </> ); }; export default Home; <file_sep>const firebaseConfig = { apiKey: "<KEY>", authDomain: "creative-agency-react-app.firebaseapp.com", databaseURL: "https://creative-agency-react-app.firebaseio.com", projectId: "creative-agency-react-app", storageBucket: "creative-agency-react-app.appspot.com", messagingSenderId: "136692327568", appId: "1:136692327568:web:ea5d4c1a6223d6666ce415", }; export default firebaseConfig; <file_sep>import React from "react"; const SingleUser = ({ userIn }) => { return ( <tbody> <tr> <td> {userIn.fastName} </td> <td> {userIn.email} </td> <td> {userIn.title} </td> <td> {userIn.description} </td> <td> <select class="custom-select" id="inputGroupSelect01"> <option value="1">Pending</option> <option value="2">Done</option> <option value="3">On going</option> </select> </td> </tr> </tbody> ); }; export default SingleUser; <file_sep>import React from "react"; import slack from "../../../images/logos/slack.png"; import google from "../../../images/logos/google.png"; import uber from "../../../images/logos/uber.png"; import netflix from "../../../images/logos/netflix.png"; import airbnb from "../../../images/logos/airbnb.png"; const Sponsored = () => { return ( <div className="sponsored-section"> <div className="row"> <div className="col-md-12 col-sm-12 col-12"> {/** Sponsored Logo **/} <div className="sponsored-image d-flex justify-content-center"> <img className="img-fluid" src={slack} alt="" /> <img className="img-fluid" src={google} alt="" /> <img className="img-fluid" src={uber} alt="" /> <img className="img-fluid" src={netflix} alt="" /> <img className="img-fluid" src={airbnb} alt="" /> </div> </div> </div> </div> ); }; export default Sponsored; <file_sep>import React, { useContext, useEffect, useState } from "react"; import { UserContext } from "../../App"; import { Link, useParams } from "react-router-dom"; import UserSidebar from "./UserSidebar"; import uploadIcon from "../../images/icons/cloud-upload-outline 1.png"; const Order = () => { //** Data Come Form Context API */ const { loggedInUser, setLoggedInUser, singleData, setSingleData, } = useContext(UserContext); //** Logged User Info */ const loggedName = loggedInUser.email && loggedInUser.fastName; const loggedEmail = loggedInUser.email && loggedInUser.email; //** Description & Price Value */ const [info, setInfo] = useState({}); const handleBlur = (e) => { const newInfo = { ...info }; newInfo[e.target.name] = e.target.value; setInfo(newInfo); }; //** Single Service Data Come From Server */ const [singlePostData, setSinglePostData] = useState([]); useEffect(() => { fetch("http://localhost:7000/service") .then((res) => res.json()) .then((data) => setSinglePostData(data)); }, []); //** Dynamic Key Single Place */ const [register, setRegister] = useState({}); const { SingleOrderKey } = useParams(); useEffect(() => { if (singlePostData.length > 0) { const card = singlePostData.find( (sinData) => sinData._id === SingleOrderKey ); setRegister(card); } }, [singlePostData]); //** Data Submit in DataBase */ const submitHandler = () => { const newService = { ...loggedInUser, ...register, ...info }; fetch("http://localhost:7000/singleService", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newService), }) .then((res) => res.json()) .then((data) => { console.log(data); }); }; return ( <div className="board-bg"> <div className="container-fluid"> <div className="row"> {/** Sudebar */} <UserSidebar></UserSidebar> <div className="col-md-9"> <div className="admin-content"> <div className="upper-bar d-flex justify-content-between"> <h3 className="admin-page-title">Order</h3> {loggedInUser.email && ( <h6> <img className="rounded-circle" src={loggedInUser.photo} alt="" /> {loggedInUser.fastName} </h6> )} </div> <div className="admin-content auth-bg"> <div className="all-user-box"> <div className="user-table order-bg"> <div className="footer-section"> <div className="container"> <div className="row"> <div className="col-md-8 col-sm-6 col-12"> {/** Footer Form Box **/} <form> <div class="form-group"> <input type="text" required class="form-control" aria-describedby="emailHelp" placeholder="Your name / company’s name" value={loggedName} /> </div> <div class="form-group"> <input type="email" required class="form-control" aria-describedby="emailHelp" placeholder="Your email address" value={loggedEmail} /> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="Graphic Design" value={register.title} /> </div> <div class="form-group"> <textarea style={{ height: "112px" }} class="form-control" rows="3" required placeholder="Project Details" name="details" onBlur={handleBlur} ></textarea> </div> <div className="price_upload d-flex justify-content-between"> <div class="form-group"> <input type="number" required class="form-control" placeholder="Price" name="price" onBlur={handleBlur} /> </div> {/** Image Upload */} <div className="form-group"> <input type="file" name="file-2[]" id="file-2" class="inputfile inputfile-2" data-multiple-caption="{count} files selected" multiple="" /> <label className="image-upload" for="file-2" > <img src={uploadIcon} alt="" /> <span> Upload project file{" "} </span> </label> </div> </div> <Link to="/serviceList"> <button onClick={submitHandler} type="submit" class="section-btn" > Send </button> </Link> </form> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> ); }; export default Order; <file_sep>import React, { useContext, useEffect, useState } from "react"; import { Link, useParams } from "react-router-dom"; import { UserContext } from "../../App"; import UserSidebar from "./UserSidebar"; const Review = () => { //** Data Come Form Context API */ const { loggedInUser, setLoggedInUser } = useContext(UserContext); //** Description & Price Value */ const [info, setInfo] = useState({}); const handleBlur = (e) => { const newInfo = { ...info }; newInfo[e.target.name] = e.target.value; setInfo(newInfo); }; //** Data Submit in DataBase */ const submitHandler = () => { const newService = { ...loggedInUser, ...info }; fetch("http://localhost:7000/review", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(newService), }) .then((res) => res.json()) .then((data) => { console.log(data); }); setInfo({}); }; return ( <div className="board-bg"> <div className="container-fluid"> <div className="row"> {/** Sudebar */} <UserSidebar></UserSidebar> <div className="col-md-9"> <div className="admin-content"> <div className="upper-bar d-flex justify-content-between"> <h3 className="admin-page-title">Review</h3> {loggedInUser.email && ( <h6> <img className="rounded-circle" src={loggedInUser.photo} alt="" /> {loggedInUser.fastName} </h6> )} </div> <div className="admin-content auth-bg"> <div className="all-user-box"> <div className="user-table order-bg"> <div className="footer-section"> <div className="container"> <div className="row"> <div className="col-md-8 col-sm-6 col-12"> {/** Footer Form Box **/} <form> <div class="form-group"> <input type="text" required class="form-control" aria-describedby="emailHelp" placeholder="Your name" value={loggedInUser.fastName} /> </div> <div class="form-group"> <input type="text" onBlur={handleBlur} required class="form-control" name="companyName" aria-describedby="emailHelp" placeholder="Company’s name, Designation" /> </div> <div class="form-group"> <textarea style={{ height: "112px" }} onBlur={handleBlur} class="form-control" rows="3" name="personalDescription" required placeholder="Description" ></textarea> </div> <Link to="/"> <button onClick={submitHandler} type="submit" class="section-btn" > Submit </button> </Link> </form> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> ); }; export default Review; <file_sep>import React, { useContext, useEffect } from "react"; import { UserContext } from "../../App"; import AdminSidebar from "./AdminSidebar"; import uploadIcon from "../../images/icons/cloud-upload-outline 1.png"; import { useState } from "react"; const AddService = () => { //** Data Come Form Context API */ const { loggedInUser, setLoggedInUser } = useContext(UserContext); //** input value */ const [info, setInfo] = useState({}); const handleBlur = (e) => { const newInfo = { ...info }; newInfo[e.target.name] = e.target.value; setInfo(newInfo); }; //** Upload Image Data */ const [file, setFile] = useState(null); const handlerFileChange = (e) => { const newFile = e.target.files[0]; setFile(newFile); }; //** Data Send In Server */ const handleSubmit = () => { const formData = new FormData(); formData.append("files", file); formData.append("title", info.title); formData.append("description", info.description); fetch("http://localhost:7000/addService", { method: "POST", body: formData, }) .then((response) => response.json()) .then((data) => { console.log(data); }) .catch((error) => { console.error(error); }); }; //** Get Data Come From Server */ const [admin, setAdmin] = useState([]); useEffect(() => { fetch("http://localhost:7000/admin") .then((res) => res.json()) .then((data) => { setAdmin(data); }); }, []); const pureAdmin = admin.map((add) => add.email); const originalAdmin = pureAdmin.toString(); return ( <div className="board-bg"> <div className="container-fluid"> <div className="row"> {/** SideBar */} <AdminSidebar></AdminSidebar> {loggedInUser.email != originalAdmin ? ( <div className="col-md-9"> <div className="admin-content"> <div className="admin-content auth-bg"> <div className="all-user-box"> <div className="user-table text-center"> <div className="jumbotron jumbotron-fluid"> <div className="container"> <h1 className="display-4"> You Are Not a Admin </h1> <p className="lead"> Only admin can enter the secret page. No one but admin can access this page, Admin can make you administrator </p> </div> </div> </div> </div> </div> </div> </div> ) : ( <div className="col-md-9"> <div className="admin-content"> <div className="upper-bar d-flex justify-content-between"> <h3 className="admin-page-title">Add Service</h3> {loggedInUser.email && ( <h6> <img className="rounded-circle" src={loggedInUser.photo} alt="" /> {loggedInUser.fastName} </h6> )} </div> <div className="admin-content auth-bg"> <div className="all-user-box"> <div className="user-table"> {/** Table Form */} <form> <div className="form-row"> <div className="form-group col-md-6"> <label htmlFor="inputEmail4"> Service Title </label> <input type="text" required onBlur={handleBlur} name="title" className="form-control" placeholder="Enter Title" /> </div> {/** Image Upload */} <div className="form-group col-md-6"> <label htmlFor="inputPassword4"> Icon </label> <br /> <input type="file" onChange={handlerFileChange} required name="file-2[]" id="file-2" className="inputfile inputfile-2" data-multiple-caption="{count} files selected" multiple="" /> <label className="image-upload" htmlFor="file-2" > <img src={uploadIcon} alt="" /> <span>Upload Icon </span> </label> </div> </div> <div className="form-row"> <div className="form-group col-md-6"> <label htmlFor="inputAddress"> Description </label> <textarea style={{ height: "121px" }} type="textarea" required onBlur={handleBlur} className="form-control" name="description" placeholder="Enter Description" /> </div> </div> </form> </div> {/** Submit Button */} <button onClick={() => handleSubmit()} type="submit" className="add-submit btn btn-primary ml-auto" > Submit </button> </div> </div> </div> </div> )} </div> </div> </div> ); }; export default AddService; <file_sep>import React, { createContext, useEffect, useState } from "react"; import "./App.css"; import { BrowserRouter, Switch, Route } from "react-router-dom"; //** Import Components */ import Home from "./Components/Pages/Home"; import OurPortfolio from "./Components/Pages/OurPortfolio"; import OurTeam from "./Components/Pages/OurTeam"; import ContactUs from "./Components/Pages/ContactUs"; import NotFound from "./Components/Pages/NotFound"; import AdminLogin from "./Components/Auth/AdminLogin"; import UserLogin from "./Components/Auth/UserLogin"; import PrivateRoute from "./Components/Pages/PrivateRoute"; import PrivateRouteAdmin from "./Components/Pages/PrivateRouteAdmin"; import Order from "./Components/UserBoard/Order"; import ServiceList from "./Components/UserBoard/ServiceList"; import Review from "./Components/UserBoard/Review"; import AllUser from "./Components/AdminBoard/AllUser"; import AddService from "./Components/AdminBoard/AddService"; import MakeAdmin from "./Components/AdminBoard/MakeAdmin"; //** Context API */ export const UserContext = createContext(); const App = ({ children }) => { //** Single Service Data Come From Server */ const [singleData, setSingleData] = useState([]); const [user, setUser] = useState({}); useEffect(() => { fetch("http://localhost:7000/service") .then((res) => res.json()) .then((data) => setSingleData(data)); }, []); //** Multiple ContextAPI */ const [loggedInUser, setLoggedInUser] = useState({}); return ( <UserContext.Provider value={{ loggedInUser, setLoggedInUser, singleData, setSingleData, user, setUser, }} > <div className="App"> <BrowserRouter> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/ourPortfolio" component={OurPortfolio} /> <Route exact path="/ourTeam" component={OurTeam} /> <Route exact path="/contactUs" component={ContactUs} /> <Route exact path="/adminLogin" component={AdminLogin} /> <Route exact path="/userLogin" component={UserLogin} /> <PrivateRoute path="/order/:SingleOrderKey"> <Order></Order> </PrivateRoute> <PrivateRoute path="/serviceList"> <ServiceList></ServiceList> </PrivateRoute> <PrivateRoute path="/review"> <Review></Review> </PrivateRoute> {/** Admin PrivateRouteAdmin */} <PrivateRouteAdmin path="/allUser"> <AllUser></AllUser> </PrivateRouteAdmin> <PrivateRouteAdmin path="/addService"> <AddService></AddService> </PrivateRouteAdmin> <PrivateRouteAdmin path="/makeAdmin"> <MakeAdmin></MakeAdmin> </PrivateRouteAdmin> <Route path="*" component={NotFound} /> </Switch> </BrowserRouter> </div> </UserContext.Provider> ); }; export default App; <file_sep>import React, { useEffect, useState } from "react"; import SingleService from "./SingleService"; const Services = () => { //** Service Data Come From Server */ const [serviceAllData, setServiceAllData] = useState([]); useEffect(() => { fetch("http://localhost:7000/service") .then((res) => res.json()) .then((data) => { setServiceAllData(data); }); }, []); return ( <div className="services-section"> <div className="row"> <div className="col-md-10 offset-md-1 col-sm-12 col-12 text-center"> {/** Section Title **/} <div className="section-title"> <h2> Provide awesome <span> services </span> </h2> </div> </div> {serviceAllData.map((service) => ( <SingleService key={service._id} service={service} ></SingleService> ))} </div> </div> ); }; export default Services; <file_sep>import React, { useContext } from "react"; import { useState } from "react"; import { UserContext } from "../../App"; import SingleServiceList from "./SingleServiceList"; import UserSidebar from "./UserSidebar"; import { useEffect } from "react"; const ServiceList = () => { //** Data Come Form Context API */ const { loggedInUser, setLoggedInUser } = useContext(UserContext); //** Get Data Come From Server */ const [serviceData, setServiceData] = useState([]); useEffect(() => { fetch("http://localhost:7000/sService?email=" + loggedInUser.email) .then((res) => res.json()) .then((data) => { setServiceData(data); }); }, [serviceData]); return ( <div className="board-bg"> <div className="container-fluid"> <div className="row"> {/** Sudebar */} <UserSidebar></UserSidebar> <div className="col-md-9"> <div className="admin-content"> <div className="upper-bar d-flex justify-content-between"> <h3 className="admin-page-title">Service List</h3> {loggedInUser.email && ( <h6> <img className="rounded-circle" src={loggedInUser.photo} alt="" /> {loggedInUser.fastName} </h6> )} </div> <div className="admin-content auth-bg"> <div className="all-user-box"> <div className="row"> {serviceData.map((service) => ( <SingleServiceList service={service} ></SingleServiceList> ))} </div> </div> </div> </div> </div> </div> </div> </div> ); }; export default ServiceList; <file_sep>import React from "react"; import { useState } from "react"; import Carousel from "react-elastic-carousel"; //** Import Slider Image */ import carousel01 from "../../../images/carousel-1.png"; import carousel02 from "../../../images/carousel-2.png"; import carousel03 from "../../../images/carousel-3.png"; import carousel04 from "../../../images/carousel-4.png"; import carousel05 from "../../../images/carousel-5.png"; import Slider from "./Slider"; //** Slider Temporary Data */ const sliderData = [ { img: carousel01, }, { img: carousel02, }, { img: carousel03, }, { img: carousel04, }, { img: carousel05, }, ]; const OurWorks = () => { const [carouselSlide, setCarouselSlide] = useState([ { img: carousel01, }, { img: carousel02, }, { img: carousel03, }, { img: carousel04, }, { img: carousel05, }, ]); return ( <div className="ourWorks-section"> <div className="container"> <div className="row"> <div className="col-md-10 offset-md-1 col-sm-12 col-12 text-center"> <div className="section-title"> <h2> Here are some of <span> our works </span> </h2> </div> </div> </div> <div className="row"> <div className="col-md-12 col-sm-12 col-12"> <Carousel itemsToShow={3}> {carouselSlide.map((slide) => ( <Slider slide={slide}></Slider> ))} </Carousel> </div> </div> </div> </div> ); }; export default OurWorks;
a9987563b4940a63ee913299241ceed078c31692
[ "JavaScript" ]
18
JavaScript
LancerAbir/creative-agency-client
5e38c141f8c45377479b40caa22d8d66728667ef
909d2241c39e5a295a60a9986efefb317bd0964f
refs/heads/master
<file_sep>import * as Express from 'express'; import {Controller, All, Get, Response} from "@decorators/express"; import {Auth} from '../Middleware/Auth'; @Controller('') export class GeneralController { @Get('/') public getRoutes(@Response() res: Express.Response) { res.status(200).json({ routes: { '/': [ 'get', ], '/clients': [ 'get', 'post', ], '/client/:id': [ 'get', 'put', 'delete', ] } }); } @Get('/handshake', [Auth]) public handShake(@Response() res: Express.Response) { res.status(200).json({ message: `You're logged in as ${res.locals.user.email} with Firebase UID: ${res.locals.user.user_id}` }); } @All('*') public notFound(@Response() res: Express.Response) { res.status(404).json({error: 'Not Found!'}); } }<file_sep># Firebase Firestore ExpressJs API with Typescript A REST API using firebase, firestore as database, express js and typescript. ### Prerequisites 1. The latest copy of the `firebase-tools`. Get the Firebase Tools by running the following command: ```bash npm i -g firebase-tools ``` 2. The latest version of `firebase-admin` and `firebase-functions` ### Configuration To start just configure your .firebaserc with your project name ```javascript { "projects": { "default": "[YOUR-PROJECT]" } } ``` Install packages under root and inside functions folder: ```bash npm install cd functions npm install ``` To watch typescript for changes: ```bash cd functions npm run watch ``` To run a local server run (on project root folder): ```bash firebase serve ``` OBS: You will have to restart the local server every time you make some changes. Also, the typescript watcher must run alognside so the changes may take effect. All routes are mapped to webAPI function, you can check all logs on firebase console. <file_sep>import * as Express from 'express'; import * as admin from 'firebase-admin'; import {Middleware} from '@decorators/express'; export class Auth implements Middleware { async use(req: Express.Request, res: Express.Response, next: Express.NextFunction) { if (req.header('Authorization')) { try { res.locals.user = await admin.auth().verifyIdToken(req.header('Authorization')); next(); } catch (err) { res.status(401).json(err); } } else { res.status(401).json({error: 'Authorization header is not found'}); } } }<file_sep>import {firestore} from 'firebase-admin'; import {Injectable} from "@decorators/di"; @Injectable() class ClientRepository { create(client: Object) { return firestore().collection('clients').add(client); } read() { return firestore().collection('clients').get(); } update(id: string, client: Object) { return firestore().collection('clients').doc(id).update(client); } delete(id: string) { return firestore().collection('clients').doc(id).delete(); } find(id: string) { return firestore().collection('clients').doc(id).get(); } } export default new ClientRepository();<file_sep>import * as Express from 'express'; import { Controller, Body, Params, Get, Put, Post, Delete, Response } from "@decorators/express"; import {Auth} from '../Middleware/Auth'; import ClientRepository from '../Repositories/Clients'; @Controller('/clients', [Auth]) export class ClientController { @Post('/') async create(@Body() body: Object, @Response() res: Express.Response) { try { const client = await ClientRepository.create(body); res.status(200).json(client.id); } catch (err) { res.status(500).json(err); } } @Get('/') async read(@Response() res: Express.Response) { try { let clients = await ClientRepository.read(); let results = []; if (!results.length) { res.status(404).json({detail: 'No records found'}); } else { clients.forEach(client => results.push({id: client.id, data: client.data()})); res.status(200).json(results); } } catch (err) { res.status(500).json(err); } } @Put('/:id') async update(@Response() res: Express.Response, @Body() body: Object, @Params('id') id: string) { try { const client = await ClientRepository.update(id, body); res.status(201).json(client); } catch (err) { res.status(500).json(err); } } @Delete('/:id') async delete(@Response() res: Express.Response, @Params('id') id: string) { try { await ClientRepository.delete(id); res.status(200).json({detail: `Client id: ${id} deleted!`}); } catch (err) { res.status(500).json(err); } } @Get('/:id') async find(@Response() res: Express.Response, @Params('id') id: string) { try { const client = await ClientRepository.find(id); if (client.exists) { res.status(200).json(client.data()); } else { res.status(404).json({detail: 'lol!'}); } } catch (err) { res.status(500).json(err); } } }<file_sep>import * as cors from 'cors'; import * as express from 'express'; import * as admin from 'firebase-admin'; import * as bodyParser from 'body-parser'; import * as functions from 'firebase-functions'; import {Application} from "express"; import {attachControllers} from '@decorators/express'; import {ClientController} from './Controllers/ClientController'; import {GeneralController} from './Controllers/GeneralController'; const api: Application = express(); const appV1: Application = express(); appV1.use(cors({origin: true})); api.use(bodyParser.urlencoded({extended: false})); api.use(bodyParser.json()); api.use('/api/v1', appV1); admin.initializeApp({ credential: admin.credential.applicationDefault(), databaseURL: 'https://estudo-b21f1.firebaseio.com' }); admin.firestore().settings({timestampsInSnapshots: true}); attachControllers(appV1, [ClientController, GeneralController]); // webApi is your functions name, and you will pass this.api as a parameter export const webApiV1 = functions.https.onRequest(api);
75aac0e7f4ecc5d86f3008d73d3c58655c852d87
[ "Markdown", "TypeScript" ]
6
TypeScript
jhorlima/Firestore-Express-API-Typescript
50f727d47a1da8cf2920d7a330b32149fd2726c3
9a296c90d78f94586305fff53d5c55f1f8a7f3e3
refs/heads/master
<file_sep>/* * 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. */ mModule.controller('itemController', itemController); function itemController($scope, $routeParams, $sce, $rootScope) { $scope.itemId = $routeParams.itemId; $scope.getLinkAboutItem = function () { return $sce.trustAsResourceUrl("http://beacons.apes-at-work.com/admin/items/ibeacons/tamplate.html"); }; $scope.urlTemplate = $scope.getLinkAboutItem(); }<file_sep>package com.aaw.beaconsmanager; import android.annotation.TargetApi; import android.content.*; import android.nfc.Tag; import android.os.Build; import android.os.IBinder; import android.util.Log; import org.altbeacon.beacon.BeaconManager; import org.altbeacon.beacon.logging.LogManager; import java.util.List; //import android.annotation.TargetApi; //import android.content.BroadcastReceiver; //import android.content.Context; //import android.content.Intent; //import android.os.Build.VERSION; //import org.altbeacon.beacon.BeaconManager; //import org.altbeacon.beacon.logging.LogManager; @TargetApi(4) public class StartupMonitoringReceiver extends BroadcastReceiver { private static final String TAG = "StartupMonitoring"; public StartupMonitoringReceiver() { } public void onReceive(Context context, Intent intent) { LogManager.d(TAG, "onReceive called in startup broadcast receiver", new Object[0]); if(Build.VERSION.SDK_INT < 18) { LogManager.w(TAG, "Not starting up beacon service because we do not have API version 18 (Android 4.3). We have: %s", new Object[]{Integer.valueOf(Build.VERSION.SDK_INT)}); } else { // BeaconManager beaconManager = BeaconManager.getInstanceForApplication(context.getApplicationContext()); // if(beaconManager.isAnyConsumerBound()) { // if(intent.getBooleanExtra("wakeup", false)) { // LogManager.d("StartupBroadcastReceiver", "got wake up intent", new Object[0]); // } else { // LogManager.d("StartupBroadcastReceiver", "Already started. Ignoring intent: %s of type: %s", new Object[]{intent, intent.getStringExtra("wakeup")}); // } // } String monitoringRunning = BeaconsUtils.readStringVariableFromAppContext("monitoringRunning"); Log.d(TAG, "monitoringRunning: "+monitoringRunning); if(monitoringRunning != null && monitoringRunning.equals("true") ){ BeaconsManagerPlugin beaconsManagerPlugin = new BeaconsManagerPlugin(); Intent altMonitoringService = new Intent(MainApplication.getContext(), AltMonitoring.class); beaconsManagerPlugin.altMonitoringService = altMonitoringService; beaconsManagerPlugin.startMonitoring(null, null); } } } } <file_sep>/* * 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. */ //curr items mModule.controller('currEventController', currEventController); function currEventController($scope, $routeParams, $sce, $rootScope) { // $scope.templates = [{ // name: 'site', // url: 'http://beacons.apes-at-work.com/backend/web/events/ibeacons/index.html' //}]; //$scope.template = $scope.templates[0]; stopRanging(); stopMonitoring(); $scope.eventId = $routeParams.eventId; $scope.styleOver = {'height': $(window).height() - $('header').height() - $('.mInf').height() - $('.mainTopMenu').height() - 10,'width':'90%','margin-left':'5%','padding-bottom':'60px'}; $scope.mapStl={'height': $(window).height() - $('header').height() - $('.mInf').height() - $('.mainTopMenu').height() - 10,'width':'90%','margin-left':'5%'}; $rootScope.currentMarker.CurrentEventPageIsActive=true; $rootScope.currentMarker.link=$routeParams.eventId; // $scope.template = { name: 'template1', url: 'http://beacons.apes-at-work.com/backend/web/events/ibeacons/index.html'}; $scope.getLinkAboutItem = function () { return $sce.trustAsResourceUrl("http://beacons.apes-at-work.com/backend/web/events/ibeacons/tamplate.html"); }; $scope.urlTemplate = $scope.getLinkAboutItem(); // $scope.curItemLink = $scope.getLinkAboutItem(); // $scope.itemLink="http://beacons.apes-at-work.com/backend/web/events/ibeacons/index.html"; //тут делаем запрос в сервак и показываем что надо при нахождении биакона console.log('currEventController'); $scope.zoomInit = function () { $("#contain").panzoom({ enablePan: true, minScale: 0.5, maxScale: 5, transition: true, // contain: 'invert', duration: 800, easing: "linear", increment: 1, onPan: function (e, g) { // if (e.currentTarget.id === 'marker') { // $scope.showFullInfo(e.currentTarget.attributes['data-number'].nodeValue); // } // else if (e.currentTarget.id === 'shortInfo') { // $scope.openFullInfo(e.currentTarget.attributes['data-number'].nodeValue); // } e.preventDefault(); } }); /*Zoom END*/ }; $scope.searhBeaconInArr = function (currBeacn) { for (var i in $rootScope.ibeaconInfo.ibeaconArr) { var obj = $rootScope.ibeaconInfo.ibeaconArr[i]; if (JSON.parse(obj.data).eventId) { return {'lat': obj.lat, 'lng': obj.lng}; } } }; $scope.mapLoad = function () { $scope.mapAddress=$rootScope.mapAddress; $scope.zoomInit(); var planX = $(".ibeacMap").width() / buildPlan.x; var planY = $(".ibeacMap").height() / buildPlan.y; var currBcn = $scope.searhBeaconInArr($scope.eventId); $scope.styleShortInfo = {'display': 'block', 'top': ((planY * currBcn.lat) + $('#marker').height()) * -1, 'left': (planX * currBcn.lng) - 100}; $scope.styleMarker = {'display': 'block', 'top': (planY * currBcn.lat) * -1, 'left': planX * currBcn.lng}; $scope.styleIfame = {'height': '300px', 'width': $(window).width()}; // $('#marker').css({'display': 'block', 'top': (planY * currBcn.lat) * -1, 'left': planX * currBcn.lng}); }; // $scope.mapLoad(); var iframe = document.getElementById('itemInfo'); iframe.onload = function () { var iframeWindow = iframe.contentWindow; var iframeDoc = iframeWindow.document; setTimeout(function () { var h = $(iframeWindow.document).children().height(); $('iframe').height(h); }, 300); }; /* $('iframe').load(function () { });*/ // $scope.iframeLoaded = function () { // var iframeWindow = (document.getElementById('itemInfo')).contentWindow; // var iframeDoc = iframeWindow.document; // }; }<file_sep>/* * 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. */ mModule.controller('LocationController', LocationController); function LocationController($rootScope, $scope, $http) { $rootScope.markersArr = []; $rootScope.$watch('currentLocation', function () { $scope.currentLocation = $rootScope.currentLocation; $scope.map = new google.maps.Map(document.getElementById('gmaps'), { center: {lat: 9, lng: 9}, zoom: 4, maxZoom: 5, minZoom: 4, streetViewControl: false, zoomControl: true, mapTypeControlOptions: { mapTypeIds: ['iBeacons'] } }); }); $rootScope.isLocationActivate = true; var h = {'height': $(window).height() - $('header').height() - $('.mainTopMenu').height()}; $('#gmaps').css({height: (h.height)}); $scope.getPlaces = function (map) { //получаем список зон. $('.loading').show(); $http.get('http://beacons.apes-at-work.com/api/web/mobilev1/places/get-places?locationId=' + $scope.currentLocation).then(function (result) { $rootScope.placesList = result.data.places;//список всех мест которые есть на данной локации $('.loading').hide(); $scope.items = result.data.items; for (var i in result.data.places) { var html = ''; var infowindow = new InfoBubble({ shadowStyle: 1, padding: 0, arrowSize: 8, borderRadius: 0, backgroundColor: '#f3f3f3', backgroundClassName: 'bubble-box' }); var obj = result.data.places[i]; var bounds = { north: parseInt(obj.crd_north), south: parseInt(obj.crd_south), east: parseInt(obj.crd_east), west: parseInt(obj.crd_west) }; var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; for (var i in $scope.items) { var it = $scope.items[i]; if (it.place_id === obj.id) { var eventDate = new Date(it.date); var day = eventDate.getDate(); var monthIndex = eventDate.getMonth(); var year = eventDate.getFullYear(); html += '<div class="date-box"><i class="fa fa-calendar-o" aria-hidden="true"></i>' + day + ' ' + monthNames[monthIndex] + ' ' + year + '</div>' + '<div class="divider"></div>' + '<div class="event-info-box"><div class="time-box"><i class="fa fa-clock-o" aria-hidden="true"></i>13:00 - 13:30</div>' + '<div class="info-box">' + '<a class="title-info" href=#/items/' + it.id + '>' + it.title + '</a>' + '</div>' + '<div class="place-box">' + it.place_name + '</div></div>' + '<div class="divider">&nbsp;</div>' + '<div>&nbsp;</div>' } } var marker = new google.maps.Marker({ position: {lat: bounds.south + (bounds.north - (bounds.south)) / 2, lng: bounds.west + (bounds.east - (bounds.west)) / 2}, map: map, items: html, icon: 'img/marker-icon.png' }); marker.addListener('click', function () { console.log(infowindow); infowindow.setContent(this.items); infowindow.open(map, this); var iwOuter = $('.gm-style-iw'); iwOuter.parent().addClass('pomouka'); var iwBackground = iwOuter.prev(); iwBackground.children('div:nth-child(1)').css({'display': 'none'}); iwBackground.children('div:nth-child(2)').css({'display': 'none'}); iwBackground.children('div:nth-child(3)').addClass('arrow'); iwBackground.children('div:nth-child(4)').css({'display': 'none'}); console.log('click' + this.rectangleId); }); marker.setMap(map); } }, function (err) { console.log(err); }); }; var circleArr = []; $rootScope.updateIndoorMap = function (PlaceObj) { for (var i in $rootScope.placesList) { var obj = $rootScope.placesList[i]; if (obj.id === PlaceObj.place) { bounds = { north: parseFloat(obj.crd_north), south: parseFloat(obj.crd_south), east: parseFloat(obj.crd_east), west: parseFloat(obj.crd_west) }; } } var map = $scope.map; var places = $rootScope.currentPlace; if (typeof rectangle !== 'undefined') { rectangle.setMap(null); } rectangle = new google.maps.Rectangle({ bounds: bounds, editable: false, draggable: false, optimized: false // items: html, // rectangleId: obj.id, // rectangleName: obj.name //html: 'Click right button mouse for edit location' }); rectangle.setMap(map); // console.log('lat: ' + realPos.lat + 'lng: ' + realPos.lng); // var icon = 'img/user_position.png'; // // for (var i in circleArr) { // circleArr[i].setMap(null); // // } // circleArr = []; // for (var i in beaconsWithRadius) // { // var obj = beaconsWithRadius[i]; // var circle = new google.maps.Circle({ // strokeColor: '#FF0000', // strokeOpacity: 0.8, // strokeWeight: 2, // fillColor: '#FF0000', // fillOpacity: 0.35, // map: map, // center: {lat: parseFloat(obj.lat), lng: parseFloat(obj.lng)}, // radius: obj.radius * scaleFactor // }); // circleArr.push(circle); // circle.setMap(map); // } // // if (typeof marker !== 'undefined') { // marker.setMap(null); // } // marker = new google.maps.Marker({ // position: {lat: parseFloat(realPos.lat), lng: parseFloat(realPos.lng)}, // map: map, //// icon: icon // }); //// marker.setMap(null); // marker.setMap(map); }; console.log('LocationController started'); } mModule.directive('myMap', function () { var link = function (scope, element, attrs) { scope.$watch('currentLocation', function () { console.log('new map'); scope.mapStl = {'height': $(window).height() - $('header').height() - $('.mainTopMenu').height()}; /*This is our map */ var map = scope.map; /*Now we can zoom max 1. Custom type iBeacons*/ SERVERURL = 'http://beacons.apes-at-work.com'; var tmrl = SERVERURL + '/backend/web/maps/templates/bg.jpg'; var iBeacons = new google.maps.ImageMapType({ /*Get tile url in the backend*/ getTileUrl: function (coord, zoom) { var locId = scope.currentLocation; var normalizedCoord = getNormalizedCoord(coord, zoom); if (!normalizedCoord) { return null; } var bound = Math.pow(2, zoom); switch (zoom) { case 4: if ((normalizedCoord.x === 8) && ((bound - normalizedCoord.y - 1) === 8)) { res = SERVERURL + '/backend/web/maps/' + locId + '/' + zoom + '/' + normalizedCoord.x + '/' + (bound - normalizedCoord.y - 1) + '.jpg'; } else { res = tmrl; } ; break; case 5: if (((normalizedCoord.x === 16) && ((bound - normalizedCoord.y - 1) === 16)) || ((normalizedCoord.x === 16) && ((bound - normalizedCoord.y - 1) === 17)) || ((normalizedCoord.x === 17) && ((bound - normalizedCoord.y - 1) === 16)) || ((normalizedCoord.x === 17) && ((bound - normalizedCoord.y - 1) === 17))) { res = SERVERURL + '/backend/web/maps/' + locId + '/' + zoom + '/' + normalizedCoord.x + '/' + (bound - normalizedCoord.y - 1) + '.jpg'; } else { res = tmrl; } break; } console.log('http://beacons.apes-at-work.com/backend/web/maps/' + locId + '/' + zoom + '/' + normalizedCoord.x + '/' + (bound - normalizedCoord.y - 1) + '.jpg'); return res; }, /*not nessessary*/ tilesloaded: function (e) { console.log(e); }, /*Tile params*/ center: {lat: 9, lng: 9}, tileSize: new google.maps.Size(256, 256), zoom: 5, maxZoom: 5, minZoom: 4, //radius: 155555, optimized: false }); map.mapTypes.set('iBeacons', iBeacons); map.setMapTypeId('iBeacons'); scope.places = scope.getPlaces(map); /*Maps creating END*/ }); }; // // function searchLocationCoordsByMarker(link) { // for (var i in LocationsArr) { // var obj = LocationsArr[i]; // for (var j in obj.markers) { // var obj1 = obj.markers[j]; // if (obj1.link === link) { // return {lat: obj.lat, lng: obj.lng}; // } // } // } // } // Normalizes the coords that tiles repeat across the x axis (horizontally) // like the standard Google map tiles. function getNormalizedCoord(coord, zoom) { var y = coord.y; var x = coord.x; // tile range in one direction range is dependent on zoom level // 0 = 1 tile, 1 = 2 tiles, 2 = 4 tiles, 3 = 8 tiles, etc // var tileRange = 1; var tileRange = 1 << zoom; // don't repeat across y-axis (vertically) if (y < 0 || y >= tileRange) { // y = (y % tileRange + tileRange) % tileRange; return null; } //do repeat across x-axis if (x < 0 || x >= tileRange) { x = (x % tileRange + tileRange) % tileRange; // console.log(x); // return null; } console.log({x: x, y: y}); return {x: x, y: y}; } ; return { restrict: 'A', template: '<div id="gmaps" class=\'google-map\' ng-style="mapStl"></div>', // replace: true, // controller: dirCtrl, link: link, // controller: 'LocationController' }; }); <file_sep> var exec = require('cordova/exec'), channel = require('cordova/channel'); function BeaconsManager() { }; if (!window.plugins) { window.plugins = {}; } if (!window.plugins.BeaconsManager) { window.plugins.BeaconsManager = new BeaconsManager(); } //================= SERVICE =================== BeaconsManager.prototype.startService = function (successCallback, errorCallback) { cordova.exec(successCallback, errorCallback, "BeaconsManagerPlugin", "startService", []); }; BeaconsManager.prototype.stopService = function (successCallback, errorCallback) { cordova.exec(successCallback, errorCallback, "BeaconsManagerPlugin", "stopService", []); }; //================= MONITORING =================== BeaconsManager.prototype.startMonitoring = function (successCallback, errorCallback, array) { cordova.exec(successCallback, errorCallback, "BeaconsManagerPlugin", "startMonitoring", [array]); }; BeaconsManager.prototype.stopMonitoring = function (successCallback, errorCallback) { cordova.exec(successCallback, errorCallback, "BeaconsManagerPlugin", "stopMonitoring", []); }; //=================== RANGING ==================== BeaconsManager.prototype.startRanging = function (successCallback, errorCallback, array) { cordova.exec(successCallback, errorCallback, "BeaconsManagerPlugin", "startRanging", [array]); }; BeaconsManager.prototype.stopRanging = function (successCallback, errorCallback) { cordova.exec(successCallback, errorCallback, "BeaconsManagerPlugin", "stopRanging", []); }; //===== BeaconsManager.prototype.applyParameters = function (successCallback, errorCallback, params) { cordova.exec(successCallback, errorCallback, "BeaconsManagerPlugin", "applyParameters", [params]); }; //var monitoringAsyncFunc; // //monitoringAsyncFunc = function (result){ // console.log('result: '+JSON.stringify(result) ); //} BeaconsManager.prototype.setMonitoringFunction = function(func){ //monitoringAsyncFunc = func; cordova.exec( func,//function(res){}, function(e){alert('error sent onDeviceReady: '+e);}, 'BeaconsManagerPlugin', 'setMonitoringFunction', []); } channel.deviceready.subscribe(function () { // Device is ready now, the listeners are registered // and all queued events can be executed. cordova.exec( function(res){console.log('deviceReady for plugin called')}, function(e){console.error('error sent onDeviceReady: '+e);}, 'BeaconsManagerPlugin', 'onDeviceReady', []); }); module.exports = BeaconsManager; <file_sep>/* * 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. */ function avgFromArray(arr) { var sum = 0; var count = 0; for (var i in arr) { sum += arr[i]; count++; } if (count > 0) { return sum / count; } return 0; } function findBeaconInArr(scannedBeaconsArr, beacon) { var count = scannedBeaconsArr.length; //var beaconObj={uuid:uuid,minor:minor,major:major}; for (var i = 0; i < count; i++) { var currScannedBeacon = scannedBeaconsArr[i]; if ((beacon.uuid === currScannedBeacon.uuid) && (beacon.minor === currScannedBeacon.minor) && (beacon.major === currScannedBeacon.major)) { return scannedBeaconsArr[i]; } } return null; } function updateIndoorMap(beaconsWithRadiuses, userPosition) { // var planX = $(".ibeacMap").width() / buildPlan.x; // var planY = $(".ibeacMap").height() / buildPlan.y; // userPositionGlobal = userPosition; sessionStorage.setItem("userPosition", JSON.stringify(userPosition)); // document.cookie = "userPosition=" + userPositionGlobal; // Session["userPosition"] = userPositionGlobal; // $("#positionobj").css({'top': (planY * userPosition.lat) * -1, 'left': planX * userPosition.lng}); } function searchInBeaconsArr(eventId) { for (var i in monitoredBeaconsArr) { var obj = monitoredBeaconsArr[i]; if (JSON.parse(obj.data).eventId === eventId) { return obj; } } }<file_sep>cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/cordova-plugin-device/www/device.js", "id": "cordova-plugin-device.device", "clobbers": [ "device" ] }, { "file": "plugins/com.aaw.bmplugin/www/beacons-manager.js", "id": "com.aaw.bmplugin.BeaconsManagerPlugin", "clobbers": [ "plugin.BeaconsManagerPlugin" ] }, { "file": "plugins/com.phonegap.plugins.barcodescanner/www/barcodescanner.js", "id": "com.phonegap.plugins.barcodescanner.BarcodeScanner", "clobbers": [ "cordova.plugins.barcodeScanner" ] } ]; module.exports.metadata = // TOP OF METADATA { "cordova-plugin-device": "1.1.2-dev", "com.aaw.bmplugin": "0.7.5", "com.phonegap.plugins.barcodescanner": "1.2.0", "cordova-plugin-whitelist": "1.2.2" } // BOTTOM OF METADATA });<file_sep>package com.aaw.beaconsmanager; import android.Manifest; import android.content.*; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import org.altbeacon.beacon.Beacon; import org.altbeacon.beacon.Identifier; import org.altbeacon.beacon.RangeNotifier; import org.altbeacon.beacon.Region; import org.apache.cordova.*; import org.json.JSONArray; import org.json.JSONException; import android.util.Log; import org.json.JSONObject; import java.util.*; public class BeaconsManagerPlugin extends CordovaPlugin { public static final String TAG = "BeaconsManager"; public Intent altMonitoringService; //public Intent altBeaconService; public AltMonitoring altMonitoringInstance = null; private ServiceConnection serviceConnection; private CallbackContext monitoringCallbackContext; private CallbackContext rangingCallbackContext; private boolean monitoringFunctionSet = false; @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); Log.w(TAG, "=======onNewIntent====" ); try { Bundle b = intent.getExtras(); if(b!=null) { Log.w(TAG, "=======saved extras====" + b.size() + "========" + b.toString()); //sendNotifyToJavascript(b); addObjectToCallbackQueue(b); } } catch (Throwable t) { t.printStackTrace(); } } @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); //AltMonitoring.applicationContext = this.cordova.getActivity();//.getApplicationContext(); altMonitoringService = new Intent(this.cordova.getActivity()/*.getApplicationContext()*/, AltMonitoring.class); //================== try { // Intent launchIntent = this.cordova.getActivity().getPackageManager().getLaunchIntentForPackage("com.appplg2.MainActivity"); // MainApplication.getContext().getPackageManager().getLaunchIntentForPackage("com.appplg2.MainActivity"); // Intent launchIntent = this.cordova.getActivity().getPackageManager().getLaunchIntentForPackage(MainApplication.getContext().getPackageName()); Bundle cordovaIntentBundle = this.cordova.getActivity().getIntent().getExtras(); if(cordovaIntentBundle!=null){ Log.w(TAG, "=======cordovaIntentBundle:" + cordovaIntentBundle.size()); //sendNotifyToJavascript(cordovaIntentBundle); addObjectToCallbackQueue(cordovaIntentBundle); } // Bundle b = launchIntent.getExtras(); // if(b!=null) { // Log.w(TAG, "=======initialize plugin extras====" + b.size() + "========" + b.toString()); // } }catch (Exception e){ Log.e(TAG, e.getMessage()); } } @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { //=== service if(action.equals("startService")){ this.startService(new Callback()); return true; } else if(action.equals("stopService")){ this.stopService(); return true; } //=== monitoring else if (action.equals("startMonitoring")) { try { JSONArray extBeacons = data.getJSONArray(0); this.startMonitoring(extBeacons, callbackContext); } catch (JSONException e) { Log.e(TAG, action + " execute: Got JSON Exception " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (action.equals("stopMonitoring")) { try { this.stopMonitoring(callbackContext); } catch (Exception e) { Log.e(TAG, action + " execute: Got JSON Exception " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } //===ranging else if (action.equals("startRanging")) { try { JSONArray extBeacons = new JSONArray(); if(data.getJSONArray(0)!=null){ extBeacons = data.getJSONArray(0); } this.startRanging(extBeacons, callbackContext); } catch (JSONException e) { Log.e(TAG, action + " execute: Got JSON Exception " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } else if (action.equals("stopRanging")) { try { this.stopRanging(callbackContext); } catch (Exception e) { Log.e(TAG, action + " " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } //=== setParameters else if (action.equals("applyParameters")) { try { Map<String, String> map = new HashMap<String, String>(); JSONObject jso = data.getJSONObject(0); Iterator names = jso.keys(); while(names.hasNext()){ String key = (String) names.next(); String value = jso.get(key).toString(); map.put(key, value); } //Map<String, String> map = (Map<String, String>) data.getJSONObject(0).nameValuePairs[0]; this.applyParameters(callbackContext, map); } catch (Exception e) { Log.e(TAG, action + " " + e.getMessage()); callbackContext.error(e.getMessage()); } return true; } // else // if(action.equals("readLaunchData")){ // this.readLaunchData(); // return true; // } else if (action.equals("onDeviceReady")) { onDeviceReady(); return true; } else if(action.equals("setMonitoringFunction")) { monitoringCallbackContext = callbackContext; monitoringFunctionSet = true; sendBundles(); return true; } return false; } private void startService(final Callback callback){ Context appContext = getMainAppContext(); // getContext() //String thisAppPackageName = appContext.getPackageName(); //List thisAppServices = BeaconsUtils.getRunningServices(thisAppPackageName); boolean altMonitoringRunning = isServiceRunning(); if( AltMonitoring.monitoringCallbackContext==null){ AltMonitoring.monitoringCallbackContext = monitoringCallbackContext; } if(!altMonitoringRunning){ AltMonitoring.runInForeground = true; ComponentName cn = appContext.startService(altMonitoringService); } if(serviceConnection == null) { serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder serviceBinder) { altMonitoringInstance = ((AltMonitoring.LocalBinder) serviceBinder).getService(); Log.w(TAG, "service connected " + name.getClassName()); callback.call(); } @Override public void onServiceDisconnected(ComponentName name) { Log.w(TAG, "service disconnected " + name.getClassName()); } }; boolean connected = appContext.bindService(altMonitoringService, serviceConnection, Context.BIND_AUTO_CREATE); if (connected) { asyncSuccess(monitoringCallbackContext, "Connected to service success "); } else { asyncSuccess(monitoringCallbackContext, "Service already running. Not connected to service "); } }else{ asyncSuccess(monitoringCallbackContext, "Service already started and bound"); callback.call(); } } private void stopService(){ boolean altMonitoringRunning = isServiceRunning(); if(altMonitoringRunning){ if(serviceConnection!=null) { getMainAppContext().unbindService(serviceConnection); serviceConnection = null; } boolean stopped = getMainAppContext().stopService(altMonitoringService); asyncSuccess(monitoringCallbackContext, "Service has been stopped success: "+stopped); }else{ asyncSuccess(monitoringCallbackContext, "Service is not running"); } } public void startMonitoring(JSONArray extBeaconsArr, final CallbackContext callbackContext) { // AltMonitoring.monitoringCallbackContext = monitoringCallbackContext;//callbackContext; // AltMonitoring.runInForeground = true; if(extBeaconsArr != null){ ArrayList<ExtBeacon> extBeaconsList = new ArrayList(); try { for (int i = 0; i < extBeaconsArr.length(); i++) { JSONObject extBcnJso = extBeaconsArr.getJSONObject(i); ExtBeacon incBeacon = new ExtBeacon(); incBeacon.setId(extBcnJso.getInt("id")); incBeacon.setUuid(extBcnJso.getString("uuid")); incBeacon.setMajor(extBcnJso.getString("major")); incBeacon.setMinor(extBcnJso.getString("minor")); //incBeacon.setActionType(extBcnJso.getInt("actionType")); //incBeacon.setMsg(extBcnJso.getString("msg")); incBeacon.setData(extBcnJso.getString("data")); JSONObject msgForEnterJso = extBcnJso.getJSONObject("msgForEnter"); incBeacon.setMsgForEnter(new ExtBeacon.MsgForType( msgForEnterJso.getString("msg"), msgForEnterJso.getBoolean("show"), ExtBeacon.ActionType.enter )); JSONObject msgForExitJso = extBcnJso.getJSONObject("msgForExit"); incBeacon.setMsgForExit(new ExtBeacon.MsgForType( msgForExitJso.getString("msg"), msgForExitJso.getBoolean("show"), ExtBeacon.ActionType.exit )); extBeaconsList.add(incBeacon); } }catch (Exception e){ Log.e(TAG, e.getMessage()); callbackContext.error(e.getMessage()); } String extBeaconsListStr = BeaconsUtils.objectToString(extBeaconsList); BeaconsUtils.writeStringVariableToAppContext("extBeaconsListStr", extBeaconsListStr); } //======================= Callback callback = new Callback(){ @Override public void call(){ try { altMonitoringInstance.startMonitoring(); if(callbackContext!=null) { asyncSuccess(callbackContext, "Monitoring started"); } BeaconsUtils.writeStringVariableToAppContext("monitoringRunning", "true"); }catch (Exception e){ if(callbackContext != null) { callbackContext.error(e.getMessage()); } } } }; startServiceIfNotRunning(callback); } private void stopMonitoring(CallbackContext callbackContext) { try{ altMonitoringInstance.stopMonitoring(); callbackContext.success("Monitoring was stopped"); BeaconsUtils.writeStringVariableToAppContext("monitoringRunning", "false"); }catch (Exception e){ callbackContext.error(e.getMessage()); } } private void startRanging(JSONArray extBeaconsArr, final CallbackContext callbackContext){ Callback callback = new Callback(){ @Override public void call(){ RangeNotifier rangeNotifier = new RangeNotifier() { @Override public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) { for (Beacon beacon: beacons) { Log.w(TAG, "=== didRangeBeaconsInRegion ===size:"+beacons.size()); //showNotification( "=== didRangeBeaconsInRegion ===size: "+beacons.size(), new HashMap<String, String>()); //if (beacon.getServiceUuid() == 0xfeaa && beacon.getBeaconTypeCode() == 0x00) { // This is a Eddystone-UID frame Identifier namespaceId = beacon.getId1(); Identifier instanceId = beacon.getId2(); Log.d(TAG, "I see a beacon transmitting namespace id: "+namespaceId+ " and instance id: "+instanceId+ " approximately "+beacon.getDistance()+" meters away."); } if(callbackContext!=null){ PluginResult result; try{ JSONObject data = new JSONObject(); JSONArray beaconData = new JSONArray(); for (Beacon beacon : beacons) { beaconData.put(BeaconsUtils.mapOfBeacon(beacon)); } data.put("eventType", "didRangeBeaconsInRegion"); //data.put("region", mapOfRegion(region)); data.put("beacons", beaconData); //send and keep reference to callback result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); }catch (Exception je){ result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, je.getMessage()); } callbackContext.sendPluginResult(result); } } }; // altMonitoringInstance.getAltBeaconManagerInstance().setRangeNotifier(new RangeNotifier() { // @Override // public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) { // for (Beacon beacon: beacons) { // // Log.w(TAG, "=== didRangeBeaconsInRegion ===size:"+beacons.size()); // //showNotification( "=== didRangeBeaconsInRegion ===size: "+beacons.size(), new HashMap<String, String>()); // // //if (beacon.getServiceUuid() == 0xfeaa && beacon.getBeaconTypeCode() == 0x00) { // // This is a Eddystone-UID frame // Identifier namespaceId = beacon.getId1(); // Identifier instanceId = beacon.getId2(); // Log.d(TAG, "I see a beacon transmitting namespace id: "+namespaceId+ // " and instance id: "+instanceId+ // " approximately "+beacon.getDistance()+" meters away."); // // } // // if(callbackContext!=null){ // PluginResult result; // try{ // JSONObject data = new JSONObject(); // JSONArray beaconData = new JSONArray(); // for (Beacon beacon : beacons) { // beaconData.put(BeaconsUtils.mapOfBeacon(beacon)); // } // data.put("eventType", "didRangeBeaconsInRegion"); // //data.put("region", mapOfRegion(region)); // data.put("beacons", beaconData); // // // //send and keep reference to callback // result = new PluginResult(PluginResult.Status.OK, data); // result.setKeepCallback(true); // }catch (Exception je){ // result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, je.getMessage()); // // } // callbackContext.sendPluginResult(result); // // } // } // }); altMonitoringInstance.startRanging(callbackContext, rangeNotifier); asyncSuccess(monitoringCallbackContext, "Ranging started"); } }; startServiceIfNotRunning(callback); } private void stopRanging(CallbackContext callbackContext){ try{ altMonitoringInstance.stopRanging(); asyncSuccess(monitoringCallbackContext, "Ranging stopped"); }catch(Exception e){ callbackContext.error(e.getMessage()); } } // public void readLaunchData(){ // //IntegetContext().getPackageManager().getLaunchIntentForPackage(MainApplication.getContext().getPackageName()); // this.cordova.getActivity().getIntent().getExtras(); // // } public Context getContext(){ return this.cordova.getActivity();//.getApplicationContext(); } public Context getMainAppContext(){ return MainApplication.getContext(); } public void onDestroy() { Log.w(TAG, "Main Activity destroyed!!!"); //Activity activity = this.cordova.getActivity(); AltMonitoring.monitoringCallbackContext = null; // todo experimental AltMonitoring.runInForeground = false; AltMonitoring.setBackgroundMode(true); if(serviceConnection!=null) { getMainAppContext().unbindService(serviceConnection); } stopRanging(null); } //================================= private void applyParameters(CallbackContext callbackContext, Map<String, String> map){ Set<String> keySet = map.keySet(); for(String key: keySet ) { String val = map.get(key); if (key.equals("backgroundMode")) { if (val.equals("true")) { AltMonitoring.altBeaconManager.setBackgroundMode(true); } else if (val.equals("false")) { AltMonitoring.altBeaconManager.setBackgroundMode(false); } else { callbackContext.error("Unknown action for val: " + val + " on key: " + key); } } else if (key.equals("foregroundScanPeriod")) { long period = Long.parseLong(val); AltMonitoring.altBeaconManager.setForegroundScanPeriod(period); } else if (key.equals("foregroundBetweenScanPeriod")) { long period = Long.parseLong(val); AltMonitoring.altBeaconManager.setForegroundBetweenScanPeriod(period); } else if (key.equals("backgroundScanPeriod")) { long period = Long.parseLong(val); AltMonitoring.altBeaconManager.setBackgroundScanPeriod(period); } else if (key.equals("backgroundBetweenScanPeriod")) { long period = Long.parseLong(val); AltMonitoring.altBeaconManager.setBackgroundBetweenScanPeriod(period); } else { callbackContext.error("Unknown action for key:" + key); } } asyncSuccess(callbackContext, "OK"); } //============== bluetooth listener ============== private void initBluetoothListener() { //check access if (!hasBlueToothPermission()) { Log.w(TAG, "Cannot listen to Bluetooth service when BLUETOOTH permission is not added"); return; } //check device support // try { // altBeaconManager.checkAvailability(); // } catch (Exception e) { // //if device does not support iBeacons an error is thrown // debugWarn("Cannot listen to Bluetooth service: "+e.getMessage()); // return; // } // Register for broadcasts on BluetoothAdapter state change // IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); // cordova.getActivity().registerReceiver(broadcastReceiver, filter); } private boolean hasBlueToothPermission() { Context context = cordova.getActivity(); int access = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH); int adminAccess = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH_ADMIN); return (access == PackageManager.PERMISSION_GRANTED) && (adminAccess == PackageManager.PERMISSION_GRANTED); } /*================================= sending event ===============================*/ static boolean deviceReady = false; ArrayList<JSONObject> eventQueue = new ArrayList(); private synchronized void addObjectToCallbackQueue(Bundle b){ String backParams = b.getString("backParams"); HashMap<String, Object> paramsMap = (HashMap<String, Object>) BeaconsUtils.stringToObject(backParams); JSONObject jso = BeaconsUtils.bundleToJsonObject(paramsMap); eventQueue.add(jso); sendBundles(); } private synchronized void sendBundles(){ if(deviceReady && monitoringFunctionSet && monitoringCallbackContext!=null){ for (JSONObject msgObject : eventQueue) { asyncSuccess(monitoringCallbackContext, msgObject); } eventQueue.clear(); } } private synchronized void onDeviceReady() { Log.w(TAG, "=============onDeviceReady=======eventQueue.size: "+eventQueue.size()); //isInBackground = false; deviceReady = true; sendBundles(); // for (String js : eventQueue) { // sendJavascript(js); // } // // eventQueue.clear(); } // private synchronized void sendJavascript(final String js) { // Log.w(TAG, "====== sendJavascript Called ======="+js); // // if (!deviceReady) { // Log.w(TAG, "====== device not ready ====== add to queue next:"+js); // eventQueue.add(js); // return; // } // Runnable jsLoader = new Runnable() { // public void run() { // webView.loadUrl("javascript:" + js); // } // }; // try { // Method post = webView.getClass().getMethod("post",Runnable.class); // post.invoke(webView,jsLoader); // } catch(Exception e) { // // ((Activity)(webView.getContext())).runOnUiThread(jsLoader); // } // } // public void sendNotifyToJavascript(Bundle b){ // Log.w(TAG, "=============sendNotifyToJavascript=======Bundle b.size: "+b.size()); // Object beaconData = ""; // Object actionLocationType =""; // for(String key: b.keySet()){ // if(key.equals("data")){ // beaconData = b.get(key); // } // if(key.equals("actionLocationType")){ // actionLocationType = b.get(key); // } // // } // String jsStr = "if(handleIncomingNotification){handleIncomingNotification('"+actionLocationType+"', "+beaconData+")}"; // sendJavascript(jsStr); // } public void asyncSuccess(CallbackContext callbackContext, JSONObject msgObject){ if(callbackContext == null){ return; } PluginResult pluginResult = new KeepPluginResult(PluginResult.Status.OK, msgObject); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } public void asyncSuccess(CallbackContext callbackContext, String msgObject){ if(callbackContext == null){ return; } JSONObject jso = new JSONObject(); try { jso.put("eventType", "log"); jso.put("msg", msgObject); } catch (JSONException e) { e.printStackTrace(); } PluginResult pluginResult = new KeepPluginResult(PluginResult.Status.OK, jso); pluginResult.setKeepCallback(true); callbackContext.sendPluginResult(pluginResult); } private boolean isServiceRunning(){ return BeaconsUtils.isServiceRunning("com.aaw.beaconsmanager.AltMonitoring"); } private void startServiceIfNotRunning(Callback callback){ //if(isServiceRunning() == false){ startService(callback); // }else{ // callback.call(); // } } } class KeepPluginResult extends PluginResult{ { super.setKeepCallback(true); } public KeepPluginResult(Status status) { super(status); } public KeepPluginResult(Status status, String message) { super(status, message); } public KeepPluginResult(Status status, JSONArray message) { super(status, message); } public KeepPluginResult(Status status, JSONObject message) { super(status, message); } } class Callback{ public void call(){} } <file_sep>/* * 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. */ mModule.controller('qrController', qrController); function qrController($scope, $cordovaDevice) { var uuid = $cordovaDevice.getUUID(); $scope.myId = uuid; }<file_sep>angular.module('navigation', []) .directive('navigation', function ($rootScope, $location) { return { template: '<a ng-class="{active: isActive(option)}" ng-repeat="option in options" add-button ng-href="{{option.href}}"><div class="tri-menu"></div><img src="{{option.src}}" class="TopMenuList"><span class="nav-item-name">{{option.label}}</span></a>', link: function (scope, element, attr) { scope.options = [ {label: "Location", href: "#/navMap", src: "img/POSITION.png"}, {label: "Items", href: "#/itemlist", src: "img/ITEM.png"}, {label: "Registration", href: "#/qr", src: "img/QRCODE.png"} ]; scope.isActive = function (option) { if ($location.path() === '/') { return } return option.href.indexOf(scope.location) === 1; }; $rootScope.$on("$locationChangeSuccess", function (event, next, current) { scope.location = $location.path(); }); } }; });<file_sep># Cordova iBeacons Plugin It is a test plugin . ## Supported Platforms * iOS 7+ * Android 4.3+ (Work in progress...) ### General TODO: - Better handling of local notifications. - Handle modals in the cordova app. <file_sep>auxiliary.org-netbeans-modules-cordova.cordova_5f_build_5f_script_5f_version=50 auxiliary.org-netbeans-modules-cordova.phonegap=true auxiliary.org-netbeans-modules-web-clientproject-api.js_2e_libs_2e_folder=js/libs file.reference.ibeaconTech-test=test file.reference.ibeaconTech-www=www files.encoding=UTF-8 site.root.folder=${file.reference.ibeaconTech-www} test.folder=${file.reference.ibeaconTech-test} <file_sep>/* * 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. */ //var myLatlng = new google.maps.LatLng(-34.397, 150.644); function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 0, lng: 0}, zoom: 0, streetViewControl: false, mapTypeControlOptions: { mapTypeIds: ['iBeacons'] } }); map.addListener('zoom_changed', function () { // switch (map.getZoom()) { // case 1: // size = 512; // case 2: // size = 768; // case 3: // size = 1024; // case 4: // size = 1280; // case 5: // size = 1536; // } ReinitMap(map.getZoom(), map); console.log(map.getZoom()); // return false; }); var iBeacons = new google.maps.ImageMapType({ getTileUrl: function (coord, zoom) { var normalizedCoord = getNormalizedCoord(coord, zoom); if (!normalizedCoord) { return null; } var bound = Math.pow(2, zoom); return 'http://beacons.apes-at-work.com/admin/maps/26.svg'; }, tileSize: new google.maps.Size(256, 256), maxZoom: 5, minZoom: 0, radius: 1738000, name: 'iBeacons' }); map.mapTypes.set('iBeacons', iBeacons); map.setMapTypeId('iBeacons'); } function ReinitMap(zoom, map) { var size; switch (zoom) { case 0: size = 256; break; case 1: size = 512; break; case 2: size = 768; break; case 3: size = 1024; break; case 4: size = 1280; break; case 5: size = 1536; break; default: 1536; break; } var iBeacons = new google.maps.ImageMapType({ getTileUrl: function (coord, zoom) { var normalizedCoord = getNormalizedCoord(coord, zoom); if (!normalizedCoord) { return null; } var bound = Math.pow(2, zoom); return 'http://beacons.apes-at-work.com/admin/maps/26.svg'; }, tileSize: new google.maps.Size(size, size), maxZoom: 9, minZoom: 0, radius: 1738000, name: 'iBeacons' }); map.mapTypes.set('iBeacons', iBeacons); map.setMapTypeId('iBeacons'); } // Normalizes the coords that tiles repeat across the x axis (horizontally) // like the standard Google map tiles. function getNormalizedCoord(coord, zoom) { var y = coord.y; var x = coord.x; // tile range in one direction range is dependent on zoom level // 0 = 1 tile, 1 = 2 tiles, 2 = 4 tiles, 3 = 8 tiles, etc var tileRange = 1; // var tileRange = 1 << zoom; // don't repeat across y-axis (vertically) if (y < 0 || y >= tileRange) { return null; } //don't repeat across x-axis if (x < 0 || x >= tileRange) { // x = (x % tileRange + tileRange) % tileRange; return null; } return {x: x, y: y}; }
ccf66b20f13a49dcba584bc96e2cbe9ee5d99b5e
[ "JavaScript", "Java", "Markdown", "INI" ]
13
JavaScript
vista-54/ibTech
85d6c858fb993944f4e786542e0404f2726ff931
fc288baf6931245895dedbc65e5e94344bcde995
refs/heads/master
<file_sep>global port port = 8022 <file_sep>import socket import ssl import threading from src.port import port import os s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = port local = os.getcwd() CLIENT_CERT = os.path.join(local, 'client_data/client2/client.pem') CLIENT_KEY = os.path.join(local, 'client_data/client2/client.key') SERVER_CERT = os.path.join(local, 'server_data/server.pem') uname = input("Enter user name::") ip = '127.0.1.1' s.setblocking(1) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(SERVER_CERT) context.load_cert_chain(certfile=CLIENT_CERT, keyfile=CLIENT_KEY) if ssl.HAS_SNI: secure_sock = context.wrap_socket(s, server_side=False, server_hostname=ip) else: secure_sock = context.wrap_socket(s, server_side=False) secure_sock.connect((ip, port)) secure_sock.send(uname.encode('ascii')) clientRunning = True def receiveMsg(sock): server_down = False while clientRunning and (not server_down): try: msg = sock.read(1024).decode('ascii') print(msg) except: print('Server is Down. You are now Disconnected. Press enter to exit...') server_down = True threading.Thread(target=receiveMsg, args=(secure_sock,)).start() while clientRunning: tempMsg = input() msg = uname + '>>' + tempMsg if '\quit' in msg: clientRunning = False secure_sock.write(r'\quit'.encode('ascii')) else: secure_sock.write(msg.encode('ascii')) <file_sep># cryptography-project This is a simple chat between users connected to server. <file_sep>import socket import ssl import threading import os from src.port import port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverRunning = True ip = '127.0.1.1' local = os.getcwd() SERVER_CERT = os.path.join(local, 'server_data/server.pem') SERVER_KEY = os.path.join(local, 'server_data/server.key') CLIENT_CERT = os.path.join(local, 'client_data/client1/client.pem') clients = {} s.bind((ip, port)) s.listen() print('Server Ready...') print('Ip Address of the Server::%s' % ip) def handle_client(client, uname): client_connected = True keys = clients.keys() help = 'There are four commands in Messenger\n' \ '1::\chatlist=>gives you the list of the people currently online\n' \ '2::\quit=>To end your session\n' \ '3::\\broadcast=>To broadcast your message to each and every person currently present online\n' \ '4::Write \\[name] on the beggining of your message to send it to someone called [name]' while client_connected: try: msg = client.recv(1024).decode('ascii') response = '' found = False if r'\chatlist' in msg: clientNo = 0 for name in keys: clientNo += 1 response = response + str(clientNo) + '::' + name + '\n' client.send(response.encode('ascii')) elif r'\help' in msg: client.send(help.encode('ascii')) elif r'\broadcast' in msg: msg = msg.replace(r'\broadcast', '') for k, v in clients.items(): v.send(msg.encode('ascii')) elif r'\quit' in msg: response = 'Stopping Session and exiting...' client.send(response.encode('ascii')) clients.pop(uname) print(uname + ' has been logged out') client_connected = False else: for name in keys: if ('\\' + name) in msg: msg = msg.replace('\\' + name, '') clients.get(name).send(msg.encode('ascii')) found = True if not found: client.write('Trying to send message to invalid person.'.encode('ascii')) except: clients.pop(uname) print(uname + ' has been logged out') client_connected = False while serverRunning: client, address = s.accept() secure_sock = ssl.wrap_socket(client, server_side=True, certfile=SERVER_CERT, keyfile=SERVER_KEY, ca_certs=CLIENT_CERT, cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1) uname = secure_sock.read(1024).decode('ascii') print('%s connected to the server' % str(uname)) secure_sock.write(r'Welcome to Messenger. Type \help to know all the commands'.encode('ascii')) if secure_sock not in clients: clients[uname] = secure_sock threading.Thread(target=handle_client, args=(secure_sock, uname,)).start()
484f1710ad6acddea80a31cb4b14f684ce5a8ee1
[ "Markdown", "Python" ]
4
Python
kornel45/cryptography-project
cdd7959071c43d152e4ea4db2aa19ebf4700fa5b
5156887adce04882ad4adc8876ab7dfd0667ad69
refs/heads/master
<repo_name>crowdbotics-apps/taj-resources-4452<file_sep>/backend/.env.example DEBUG=True DATABASE_URL=postgres://taj_resources_4452:taj_resources_4452@localhost/taj_resources_4452 SECRET_KEY=
0215c2528b77cc21cfb2412a17bcaac9c027b0c4
[ "Shell" ]
1
Shell
crowdbotics-apps/taj-resources-4452
fb87081e8ceb64a601165315bcfad02e9202c2e9
048b40fc31c9bdb94870b48b0da3b1a0b3ba459c
refs/heads/master
<file_sep>export * from './answers/answers.component'; export * from './questions/questions.component'; export * from './review/review.component';<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { QuestionsComponent, ReviewComponent, AnswersComponent } from './components'; const appRoutes: Routes = [ { path: '', redirectTo: 'questions', pathMatch: 'full' }, { path: 'questions', component: QuestionsComponent }, { path: 'review', component: ReviewComponent }, { path: 'answers', component: AnswersComponent } ]; export let appRouterComponents = [QuestionsComponent, ReviewComponent, AnswersComponent]; @NgModule({ imports: [ RouterModule.forRoot(appRoutes) ] }) export class AppRoutingModule {}
9e76b34778722bea783ab0ad2d6f77799334e17e
[ "TypeScript" ]
2
TypeScript
LilyaSidorenko/angular-project
0cc73c587cf39601c83e633956ef01e31d95fe41
a9e145b7285cfe3a48c47d1766e8225b5ab92a35
refs/heads/master
<repo_name>fakki/OS_Lab<file_sep>/lab3/lab3_2/pipe.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <semaphore.h> #include <assert.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #define TEXT_SIZE 1024 int main() { char buf[TEXT_SIZE]; int fd[2], child, byte_write = 0, byte_read = 0; assert(pipe(fd) != -1); sem_t *write_ok = sem_open("write_ok", O_CREAT | O_RDWR, 0666, 0); sem_t *next_test = sem_open("next_test", O_CREAT | O_RDWR, 0666, 0); child = fork(); assert(child != -1); if(child == 0) { close(fd[0]); int flag = fcntl(fd[1], F_GETFL); fcntl(fd[1], F_SETFL, flag|O_NONBLOCK); while(write(fd[1], "A", 1) != -1) { byte_write++; } printf("test1: content of pipe is %dKB.\n", byte_write/1024); sem_post(write_ok); exit(0); } child = fork(); assert(child != -1); if(child == 0) { sem_wait(next_test); close(fd[0]); strcpy(buf, "This is the second son."); write(fd[1], buf, strlen(buf)); printf("p2: write %dB\n", (int)strlen(buf)); sem_post(write_ok); exit(0); } child = fork(); assert(child != -1); if(child == 0) { sem_wait(next_test); close(fd[0]); strcpy(buf, "This is the third son."); write(fd[1], buf, strlen(buf)); printf("p3: write %dB\n", (int)strlen(buf)); sem_post(write_ok); exit(0); } //clear pipe sem_wait(write_ok); close(fd[1]); byte_write = 64*1024; while(byte_write--) read(fd[0], buf, 1); sem_post(next_test); sem_wait(write_ok); close(fd[1]); byte_read = read(fd[0], buf, strlen("This is the second son.")); printf("test2: try to read %dB and read %dB.\n", (int)strlen("This is the second son."), byte_read); sem_post(next_test); sem_wait(write_ok); close(fd[1]); byte_read = read(fd[0], buf, 200); printf("test3: try to read %dB and read %dB.\n", 200, byte_read); sem_post(next_test); sem_close(write_ok); sem_close(next_test); sem_unlink("write_ok"); sem_unlink("next_test"); return 0; } <file_sep>/lab2/lab2_1/mypinfo.c #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/init_task.h> static int pinfo_init(void) { struct task_struct *p; p = &init_task; printk(KERN_ALERT"NAME PID STAT PRIO PPID\n"); for_each_process(p){ if(p->mm ==NULL) printk(KERN_ALERT"%s\t%d\t%ld\t%d\t%d\n", p->comm, p->pid, p->state, p->normal_prio, p->parent->pid); } return 0; } static void pinfo_exit(void) { printk(KERN_ALERT"Goodbye!(module pinfo)\n"); } module_init(pinfo_init); module_exit(pinfo_exit); MODULE_LICENSE("GPL"); <file_sep>/lab3/lab3_3/sender1.c #include <pthread.h> #include <stdio.h> #include <semaphore.h> #include <string.h> #include <sys/msg.h> #include <sys/ipc.h> #include <fcntl.h> #include <sys/types.h> #include <errno.h> #define TEXT_SIZE 1024 struct msgbuf { long mtype; char mtext[TEXT_SIZE]; }; pthread_t p; void *sender(void *args) { key_t key = ftok(".", 12); int msgid = msgget(key, IPC_CREAT); printf("msgid: %d\n", msgid); if(msgid < 0) { printf("msgget error!\n"); return 0; } printf("--------sender1---------\n"); while(1) { char input[TEXT_SIZE]; printf("please input something to sender1: \n"); //scanf("%s", input); gets(input); struct msgbuf msg, msg_receive; msg.mtype = 3; if(strcmp(input, "exit") == 0) { strcpy(msg.mtext, "end1"); int s = msgsnd(msgid, &msg, TEXT_SIZE, 0); int r = msgrcv(msgid, &msg_receive, TEXT_SIZE, 1, 0); printf("sender1 received \"%s\"\n", msg_receive.mtext); printf("Goodbye!\n"); pthread_exit((void*)"sender1 exit!\n"); } else { strcpy(msg.mtext, input); int s = msgsnd(msgid, &msg, TEXT_SIZE, 0); } } } int main() { pthread_create(&p, NULL, sender, NULL); pthread_join(p, NULL); }<file_sep>/README.md # OS_Lab 操作系统课程设计 <file_sep>/lab1_1/setnice.c #define _GNU_SOURCE #include <unistd.h> #include <sys/syscall.h> #include <stdlib.h> #include <stdio.h> int main() { pid_t pid; int nicevalue; int flag; int p = 0, n = 0; int * prio = &p; int * nice = &n; printf("please enter pid: "); scanf("%d", &pid); printf("please enter flag: \n"); scanf("%d", &flag); printf("please enter value of nice: \n"); scanf("%d", &nicevalue); syscall(333, pid, flag, nicevalue, prio, nice); printf("%d(pid)'s nice and prio now are %d, %d\n", pid, n, p); return 0; } <file_sep>/lab2/lab2_2/mypinfo_param.c #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/moduleparam.h> #include <linux/pid.h> #include <linux/sched.h> MODULE_LICENSE("GPL"); static int pid; module_param(pid, int, 0644); static int __init mypinfo_param_init(void) { struct pid* ppid; struct task_struct *task, *parent; struct list_head *list; int isibling, ichildren; ppid = find_get_pid(pid); task = pid_task(ppid, PIDTYPE_PID); printk(KERN_ALERT"Start!(pinfo_param pid=%d)", pid); parent = task->parent; printk(KERN_ALERT"Parent\t%s\t%d\t%ld", parent->comm, parent->pid, parent->state); isibling = 0; ichildren = 0; //get info of siblings from parent's children list list_for_each(list, &parent->children) { struct task_struct *p; p = list_entry(list, struct task_struct, sibling); if(p->pid != pid) isibling++; printk(KERN_ALERT"Sibling\t%s\t%d\t%ld", p->comm, p->pid, p->state); } printk(KERN_ALERT"%d siblings", isibling); //get info of children list_for_each(list, &task->children) { struct task_struct *p; p = list_entry(list, struct task_struct, sibling); ichildren++; printk(KERN_ALERT"Child\t%s\t%d\t%ld", p->comm, p->pid, p->state); } printk(KERN_ALERT"%d children", ichildren); return 0; } static void __exit mypinfo_param_exit(void) { printk(KERN_ALERT"Goodbye!(pinfo_param)\n"); } module_init(mypinfo_param_init); module_exit(mypinfo_param_exit); <file_sep>/lab3/lab3_3/receiver.c #include <pthread.h> #include <stdio.h> #include <semaphore.h> #include <string.h> #include <sys/msg.h> #include <sys/ipc.h> #include <fcntl.h> #include <sys/types.h> #include <errno.h> #define TEXT_SIZE 1024 struct msgbuf { long mtype; char mtext[TEXT_SIZE]; }; pthread_t p; void *receiver(void *args) { key_t key = ftok(".", 12); int msgid = msgget(key, IPC_CREAT); printf("msgid: %d\n", msgid); if(msgid < 0) { printf("msgget error!\n"); return 0; } int count = 0; while(1) { struct msgbuf msg; msgrcv(msgid, &msg, TEXT_SIZE, 3, 0); if(strcmp(msg.mtext, "end1") == 0) { printf("receiver received \"%s\"\n", msg.mtext); msg.mtype = 1; strcpy(msg.mtext, "over1"); msgsnd(msgid, &msg, TEXT_SIZE, 0); sleep(1); count++; printf("--------sender1 exits!---------\n"); } else if(strcmp(msg.mtext, "end2") == 0) { printf("receiver received \"%s\"\n", msg.mtext); msg.mtype = 2; strcpy(msg.mtext, "over2"); msgsnd(msgid, &msg, TEXT_SIZE, 0); sleep(1); count++; printf("--------sender2 exits!---------\n"); } else printf("receiver received \"%s\"\n", msg.mtext); if(count >= 2) { printf("--------receiver exits!---------\n"); msgctl(msgid, IPC_RMID, NULL); pthread_exit((void*)"receiver exit!\n"); } } } int main() { pthread_create(&p, NULL, receiver, NULL); pthread_join(p, NULL); }<file_sep>/lab3/lab3_4/shm.c #include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #include <semaphore.h> #include <pthread.h> #include <string.h> #define TEXT_SIZE 1024 sem_t sem_sender, sem_receiver; pthread_t sender_t, receiver_t; struct msg_block { char msg[TEXT_SIZE]; }; struct msg_block *msg_send; void *sender(void *args) { printf("------------------sender: \"please input words to receiver.\"--------------------\n"); char input[TEXT_SIZE]; scanf("%s", input); strcpy(msg_send->msg, input); sem_post(&sem_sender); printf("sender is waiting....\n"); sem_wait(&sem_receiver); printf("------------------sender received: \"%s\"--------------------\n", msg_send->msg); printf("------------------sender: \"Exit, goodBye!\"--------------------\n"); pthread_cancel(sender_t); } void *receiver(void *args) { printf("receiver is waiting....\n"); sem_wait(&sem_sender); printf("------------------receiver received: \"%s\"--------------------\n", msg_send->msg); strcpy(msg_send->msg, "over"); sem_post(&sem_receiver); printf("------------------receiver: \"Exit, goodBye!\"--------------------\n"); pthread_cancel(receiver_t); } int main() { sem_init(&sem_sender, 0, 0); sem_init(&sem_receiver, 0, 0); int shmid = shmget(ftok("/home", 123671), sizeof(struct msg_block), IPC_CREAT); if(shmid == -1) perror("shmget"); void *shm = shmat(shmid, 0, 0); if(shm == (void*)-1) perror("shmat"); msg_send = (struct msg_block *)shm; pthread_create(&sender_t, NULL, sender, NULL); pthread_create(&receiver_t, NULL, receiver, NULL); pthread_join(sender_t, NULL); pthread_join(receiver_t, NULL); return 0; }<file_sep>/lab4/filesys.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <assert.h> #define BLOCKSIZE 1024 #define SIZE 1024000 #define END 65535 #define FREE 0 #define ROOTBLOCKNUM 2 #define MAXOPENFILE 10 typedef struct FCB{ char filename[8]; //file name char exname[3]; //file extension unsigned char attribute; //0 : directory. 1: data file. char time[30]; //create time unsigned short first; //start block number unsigned long length; //file size(Byte) char free; //to label the directory empty or not. 0: empty, 1: not empty; }fcb; typedef struct FAT{ unsigned short id; }fat; typedef struct USEROPEN{ fcb ffcb; //dynamic info of the file is below int count; int dirno; int diroff; char dir[80]; char fcbstate; //1: modified. 0: not. char topenfile; // }useropen; typedef struct BLOCK0{ char info[200]; //store some discription info, block size, block num and so on unsigned short root; //root dir start index of blocks unsigned char *startblock; //virtual disk start position }block0; unsigned char *myvhead; //virtual disk start address useropen openfilelist[MAXOPENFILE]; //open file list array int curdir; //current directory disc character fd char currentdir[80]; //current directory name unsigned char *startp; //v d data area start position FILE *file; // = fopen("/home/hondor/Desktop/filesys1.txt", "w"); fcb *getfcbposition(fcb *fcbcursor, int *dirno, int *diroff, char *filename); fcb *getfcb(int fd); char * makedirpath(char *dirname, char *filename); char *gettime(); int freeblk(int blkno); int nextblkno(int blkno); int addblk(int blkno); void my_format(); void startsys(); int do_read(int fd, int len, char *text); int do_write(int fd, char *text, int len, char wstyle); void my_mkdir(char *dirname); void my_exitsys(); int my_open(char *filename); int my_close(int fd); void my_cd(char *dirname); void my_ls(); void my_rmdir(char *dirname); int my_create(char *filename); int my_read(int fd, int len); int my_write(int fd); int getfd(char *filename); int main() { startsys(); char order[20], filename[20], dirname[20]; printf("%s> ", openfilelist[curdir].dir); while(1) { scanf("%s", order); if(strcmp(order, "ls") == 0) my_ls(); else if(strcmp(order, "cd") == 0) { scanf("%s", dirname); my_cd(dirname); } else if(strcmp(order, "mkdir") == 0) { scanf("%s", dirname); my_mkdir(dirname); } else if(strcmp(order, "rmdir") == 0) { scanf("%s", dirname); my_rmdir(dirname); } else if(strcmp(order, "exit") == 0) { my_exitsys(); } else if(strcmp(order, "create") == 0) { scanf("%s", filename); my_create(filename); } else if(strcmp(order, "read") == 0) { int fd, len; scanf("%s %d", filename, &len); fd = my_open(filename); my_read(fd, len); my_close(fd); } else if(strcmp(order, "write") == 0) { int fd, len; scanf("%s", filename); fd = my_open(filename); my_write(fd); my_close(fd); } else { printf("command not found.\n"); } printf("%s> ", openfilelist[curdir].dir); } //my_exitsys(); return 0; } int my_create(char *filename) { int fcbslen = openfilelist[curdir].ffcb.length * sizeof(fcb); char fcbs[fcbslen+1+sizeof(fcb)]; fcb *fcbcursor = (fcb *)fcbs + 3, *fcbobj = NULL; do_read(curdir, fcbslen, fcbs); for(int i = 3; i < openfilelist[curdir].ffcb.length;fcbcursor++) { if(fcbcursor->free == 0 && fcbobj == NULL) fcbobj = fcbcursor; else { if(strcmp(fcbcursor->filename, filename) == 0) { printf("file already exist.\n"); return 0; } i++; } } //file is not created and this directory has no empty struct pcb if(fcbobj == NULL) { fcbslen += sizeof(fcb); fcbobj = fcbcursor; } if(fcbobj) { fcbobj->free = 1; strcpy(fcbobj->filename, filename); fcbobj->first = addblk(0); fcbobj->length = 0; fcbobj->attribute = 1; strcpy(fcbobj->time, gettime()); //while((*filename) != '.') filename++; //strcpy(fcbobj->exname, filename); } openfilelist[curdir].ffcb.length++; if(do_write(curdir, fcbs, fcbslen, 2) == -1) printf("create failed.\n"); } int my_write(int fd) { if(fd >= MAXOPENFILE || fd < 0) { printf("file description invalid.\n"); return -1; } assert(openfilelist[fd].ffcb.attribute == 1); int wstyle, blkno, nextblk, len; char buf[BLOCKSIZE]; printf("please input your way to write:\n"); scanf("%d", &wstyle); if(wstyle == 1) { blkno = nextblkno(openfilelist[fd].ffcb.first); while(blkno != END) { nextblk = nextblkno(blkno); freeblk(blkno); blkno = nextblk; } openfilelist[fd].count = 0; openfilelist[fd].ffcb.length = 0; } else if(wstyle == 3) { openfilelist[fd].count = openfilelist[fd].ffcb.length; } getchar(); while(fgets(buf, BLOCKSIZE, stdin)) { //printf("my_write line230:%d\n", strlen(buf)); int buflen = strlen(buf); if(buflen == 1) break; assert(do_write(fd, buf, buflen, wstyle) == buflen); openfilelist[fd].ffcb.length += buflen; openfilelist[fd].fcbstate = 1; } //while(scanf("%s")) } int my_read(int fd, int len) { char text[len+1]; if(fd >= MAXOPENFILE || fd < 0) { printf("file description invalid.\n"); return -1; } text[len] = 0; if(do_read(fd, len, text) == len) { printf("%s\n", text); return len; } else return -1; return 0; } fcb *getfcbposition(fcb *fcbcursor, int *dirno, int *diroff, char *filename) { *dirno = fcbcursor->first, *diroff = 1; int openfdlen = fcbcursor->length; fcbcursor = (fcb *)(myvhead + BLOCKSIZE*(fcbcursor->first-1)); fcbcursor->length = openfdlen; int plen = fcbcursor->length, i; if(plen <= 3) { printf("no such file\n"); return NULL; } fcbcursor += 3; for(i = 4; i <= plen; i++, fcbcursor++, (*diroff)++) { if(strcmp(fcbcursor->filename, filename) == 0) break; else if(i == plen) { printf("no such file.\n"); return NULL; } if(i%16 == 0) { *diroff = 0; *dirno = nextblkno(*dirno); fcbcursor = (fcb *)(myvhead + (*dirno-1)*BLOCKSIZE); } } if(fcbcursor->attribute == 0) return (fcb *)(myvhead + BLOCKSIZE*(fcbcursor->first-1)); else return fcbcursor; } fcb *getfcb(int fd) { return (fcb *)(myvhead + BLOCKSIZE*(openfilelist[fd].ffcb.first-1)); } char * makedirpath(char *dirname, char *filename) { char *buf = (char *)malloc(80); strcpy(buf, dirname); strcat(buf, "/"); strcat(buf, filename); } char *gettime() { time_t timep; time(&timep); return ctime(&timep); } int nextblkno(int blkno) { fat *fat1 = (fat *)(myvhead + BLOCKSIZE) + (blkno-1); return fat1->id; } //blkno is the block which need a free block to add behind int addblk(int blkno) { fat *fat1 = (fat *)(myvhead + BLOCKSIZE), *fat2 = (fat *)(myvhead + 3*BLOCKSIZE); for(int i = 1; i <= SIZE/BLOCKSIZE; i++, fat1++, fat2++) { if(fat1->id == FREE) { fat1->id = END; fat2->id = END; if(blkno != 0) { fat1 = (fat *)(myvhead + BLOCKSIZE) + (blkno-1); fat2 = (fat *)(myvhead + 3*BLOCKSIZE) + (blkno-1); fat1->id = i; fat2->id = i; } return i; } } return -1; } int freeblk(int blkno) { fat *fat1 = (fat *)(myvhead + BLOCKSIZE) + (blkno-1), *fat2 = (fat *)(myvhead + 3*BLOCKSIZE) + (blkno-1); fat1->id = END; fat2->id = END; return 1; } void my_format() { printf("\nwaiting to initialized fs...\n"); int i; myvhead = (unsigned char *)malloc(SIZE); startp = myvhead + 5*BLOCKSIZE; //initialize block0 here... //... char *magicnum = "10101010"; memcpy(myvhead, magicnum, 8); unsigned char *fat1 = (unsigned char *)(myvhead + BLOCKSIZE), *fat2 = (unsigned char *)(myvhead + 3*BLOCKSIZE); fat *fat_init = (fat *)malloc(1000*sizeof(fat)); fat *cursor = fat_init; for(i = 0; i < 5; i++, cursor++) cursor->id = END; //? for(;i < 1000; i++, cursor++) cursor->id = FREE; cursor = fat_init + 5; cursor->id = END; fcb *fcbroot = (fcb *)malloc(sizeof(fcb)); strcpy(fcbroot->filename, "root"); strcpy(fcbroot->exname, "dir"); strcpy(fcbroot->time, gettime()); fcbroot->first = 6; fcbroot->attribute = 0; fcbroot->length = 1; //? fcbroot->free = 1; //. and .. directory fcb *onep = (fcb *)malloc(sizeof(fcb)), *twop = (fcb *)malloc(sizeof(fcb)); memcpy(onep, fcbroot, sizeof(fcb)); memcpy(twop, fcbroot, sizeof(fcb)); strcpy(onep->filename, "."); strcpy(twop->filename, ".."); memcpy(startp+sizeof(fcb), onep, sizeof(fcb)); memcpy(startp+2*sizeof(fcb), twop, sizeof(fcb)); fcbroot->length += 2; printf("%d\n", (int)fcbroot->length); memcpy(startp, fcbroot, sizeof(fcb)); memcpy(fat1, fat_init, 1000*sizeof(fat)); memcpy(fat2, fat_init, 1000*sizeof(fat)); free(onep); free(twop); free(fcbroot); free(fat_init); printf("initialized successfully!\n"); } void startsys() { int i; file = fopen("/home/hondor/Desktop/filesys1.txt", "r"); char magicnum[8]; fread(magicnum, 8, 1, file); fseek(file, 0, SEEK_SET); if(strcmp(magicnum, "10101010") != 0) my_format(); else { myvhead = (unsigned char *)malloc(SIZE); fread(myvhead, SIZE, 1, file); } startp = myvhead + 5*BLOCKSIZE; //initialize openfilelist for(i = 0; i < MAXOPENFILE; i++) openfilelist[i].topenfile = 0; //open root dir fcb *fcbroot = (fcb *)malloc(sizeof(fcb)); memcpy(fcbroot, startp, sizeof(fcb)); curdir = 0; openfilelist[0].ffcb = *fcbroot; openfilelist[0].count = 0; //? openfilelist[0].dirno = openfilelist[0].diroff = -1; //? openfilelist[0].topenfile = 1; openfilelist[0].fcbstate = 0; strcpy(openfilelist[0].dir, "/root"); free(fcbroot); fclose(file); } int do_read(int fd, int len, char *text) { //char *texttmp = text; //printf("do_read line447:%d\n", openfilelist[fd].ffcb.length); if((openfilelist[fd].ffcb.attribute == 1 && len > openfilelist[fd].ffcb.length) || (openfilelist[fd].ffcb.attribute == 0 && len > openfilelist[fd].ffcb.length*sizeof(fcb))) { printf("the file is not such large.\n"); return -1; } int read_byte = 0; useropen file = openfilelist[fd]; int blocknum = file.ffcb.first; unsigned char *off, *buf = (unsigned char *)malloc(1024), *start; assert(buf); fat *fat1 = (fat *)(myvhead + BLOCKSIZE); fat *blockpos = fat1 + (blocknum-1); int blkno = file.count/1024; for(int i = 1; i <= blkno; i++) { blocknum = blockpos->id; blockpos = fat1 + (blocknum-1); if(blockpos->id == END) { printf("In do_read: count reach out of range.\n"); return -1; } } while(len > 0) { start = myvhead + (blocknum-1)*BLOCKSIZE; blockpos = fat1 + (blocknum-1); off = start + file.count%1024; memcpy(buf, start, 1024); if(len <= start+1024-off) { read_byte += len; memcpy(text, off, len); file.count += len; text += len; len = 0; } else { int temp = start+1024-off; read_byte += temp; len -= temp; memcpy(text, off, temp); file.count += temp; text += temp; } if(len > 0) { assert(blockpos->id != END); blocknum = blockpos->id; } } free(buf); return read_byte; } int do_write(int fd, char *text, int len, char wstyle) { unsigned char *buf = (unsigned char*)malloc(1024), *start, *off; assert(buf); int blocknum = openfilelist[fd].ffcb.first; fat *fat1 = (fat *)(myvhead + BLOCKSIZE); fat *blockpos = fat1 + (blocknum-1); int blkno = openfilelist[fd].count/1024; for(int i = 1; i <= blkno; i++) { if(blockpos->id == END) { if((blocknum = addblk(blockpos-fat1+1)) == -1) { printf("In do_write: no more block to allocate.\n"); return -1; } } } int write_byte = 0; while(len > 0) { int tmplen = 0; start = myvhead + (blocknum-1)*BLOCKSIZE; blockpos = fat1 + (blocknum-1); off = buf + openfilelist[fd].count%1024; if(wstyle == 2 || start != off) memcpy(buf, start, 1024); else memset(buf, 0, 1024); if(len <= start+1024-off) { tmplen = len; write_byte += len; memcpy(off, text, len); memcpy(start, buf, BLOCKSIZE); text += len; len=0; } else { int tmplen = start+1024-off; write_byte += tmplen; len -= tmplen; memcpy(off, text, tmplen); memcpy(start, buf, BLOCKSIZE); text += tmplen; } openfilelist[fd].count += tmplen; if(len > 0 && blockpos->id == END) { if((blocknum = addblk(blockpos-fat1+1)) == -1) { printf("In do_write: no more block to allocate.\n"); return -1; } } } free(buf); return write_byte; } void my_mkdir(char *dirname) { int i, newdir, temp; fat *fat1 = (fat *)(startp + BLOCKSIZE); int len = openfilelist[curdir].ffcb.length * sizeof(fcb); char *fcbs = (char *)malloc(len); fcb *fcbcursor; fcb *fcbnew = (fcb *)malloc(sizeof(fcb)); assert(fcbs); assert(do_read(curdir, len, fcbs) == len); for(i = 1, fcbcursor = (fcb *)fcbs; i <= len/sizeof(fcb); i++, fcbcursor++) { //printf("%s\n", fcbcursor->filename); //printf("%s\n", dirname); //printf("%d %d\n", strcmp(dirname, fcbcursor->filename), fcbcursor->attribute == 0); if(fcbcursor->attribute == 0 && strcmp(dirname, fcbcursor->filename) == 0) { printf("directory %s has already exist!\n", dirname); return; } } for(i = 0; i < MAXOPENFILE; i++) { if(openfilelist[i].topenfile == 0) { openfilelist[i].topenfile = 1; openfilelist[i].fcbstate = 0; openfilelist[i].count = 0; strcpy(openfilelist[i].dir, openfilelist[curdir].dir); strcat(openfilelist[i].dir, "/"); strcat(openfilelist[i].dir, dirname); newdir = i; break; } else if(i == MAXOPENFILE-1) { printf("In function my_mkdir(): can't open more file.\n"); free(fcbs); return; } } //printf("newdir:%d\n", newdir); if((temp = addblk(0)) == -1) { printf("In my_mkdir(): no more block to allocate.\n"); openfilelist[newdir].topenfile = 0; return; } else fcbnew->first = temp; int blkno = openfilelist[curdir].ffcb.first, diroff; fcbcursor = (fcb *)(myvhead + (blkno-1)*BLOCKSIZE); for(i = 1, diroff = 1; i <= len/sizeof(fcb); fcbcursor++, i++, diroff++) { if(fcbcursor->free == 0) break; if(i%16 == 0) { diroff = 0; blkno = nextblkno(blkno); if(blkno == END) blkno = addblk(blkno); fcbcursor = (fcb *)(myvhead + (blkno-1)*BLOCKSIZE); } } openfilelist[curdir].ffcb.length++; openfilelist[curdir].fcbstate = 1; openfilelist[newdir].dirno = blkno; openfilelist[newdir].diroff = diroff; strcpy(fcbnew->exname, "dir"); strcpy(fcbnew->filename, dirname); fcbnew->attribute = 0; strcpy(fcbnew->time, gettime()); fcbnew->length = 1; fcbnew->free = 1; openfilelist[newdir].ffcb = *fcbnew; fcb *onep = (fcb *)malloc(sizeof(fcb)), *twop = (fcb *)malloc(sizeof(fcb)); memcpy(onep, fcbnew, sizeof(fcb)); memcpy(twop, &openfilelist[curdir].ffcb, sizeof(fcb)); strcpy(onep->filename, "."); strcpy(twop->filename, ".."); fcbnew->length += 2; openfilelist[newdir].ffcb = *fcbnew; memcpy(fcbcursor, fcbnew, sizeof(fcb)); fcbcursor = (fcb *)(myvhead + (openfilelist[newdir].ffcb.first-1)*BLOCKSIZE); memcpy(fcbcursor++, fcbnew, sizeof(fcb)); memcpy(fcbcursor++, onep, sizeof(fcb)); memcpy(fcbcursor, twop, sizeof(fcb)); free(onep); free(twop); free(fcbnew); free(fcbs); if(openfilelist[curdir].fcbstate == 1) { openfilelist[curdir].count = 0; assert(do_write(curdir, (char *)(&openfilelist[curdir].ffcb), sizeof(fcb), 2) == sizeof(fcb)); fcbcursor = (fcb *)(myvhead+(openfilelist[curdir].ffcb.first-1)*BLOCKSIZE); } my_close(newdir); } void my_exitsys() { file = fopen("/home/hondor/Desktop/filesys1.txt", "w"); fwrite(myvhead, SIZE, 1, file); fclose(file); exit(0); } int my_open(char *filename) { int i, plen = openfilelist[curdir].ffcb.length; for(i = 0;i < MAXOPENFILE; i++) { if(openfilelist[i].topenfile == 1 && strcmp(filename, openfilelist[i].ffcb.filename) == 0) { printf("file already opened.\n"); return i; } } int dirno, diroff; fcb *fcbcursor = getfcbposition(&(openfilelist[curdir].ffcb), &dirno, &diroff, filename); if(fcbcursor == NULL) { printf("not found such file.\n"); return -1; } int fd = -1; for(i =0; i < MAXOPENFILE; i++) { if(openfilelist[i].topenfile == 0) { fd = i; break; } else if(i == MAXOPENFILE-1) { printf("can't open more files.\n"); return -1; } } openfilelist[fd].topenfile = 1; openfilelist[fd].count = 0; openfilelist[fd].fcbstate = 0; openfilelist[fd].dirno = dirno; openfilelist[fd].diroff = diroff; openfilelist[fd].ffcb = *fcbcursor; strcpy(openfilelist[fd].dir, makedirpath(openfilelist[curdir].dir, filename)); return fd; } int my_close(int fd) { //if(curdir == fd) if(fd == 0) return 0; if(fd >= MAXOPENFILE) { printf("file description invalid.\n"); return -1; } if(openfilelist[fd].fcbstate == 1) { openfilelist[fd].count = 0; if(openfilelist[fd].ffcb.attribute == 0) assert(do_write(fd, (char *)(&openfilelist[fd].ffcb), sizeof(fcb), 2) == sizeof(fcb)); else { int dirno = openfilelist[fd].dirno, diroff = openfilelist[fd].diroff; fcb *fcbcursor = (fcb *)(myvhead + (dirno-1)*BLOCKSIZE); while(nextblkno(dirno) != END) { dirno = nextblkno(dirno); fcbcursor = (fcb *)(myvhead + (dirno-1)*BLOCKSIZE); } fcbcursor += (diroff+3-1); memcpy(fcbcursor, &openfilelist[fd].ffcb, sizeof(fcb)); } } openfilelist[fd].topenfile = 0; return fd; } void my_cd(char *dirname) { if(strcmp(dirname, "/root") == 0 || strcmp(dirname, "root") == 0) { my_close(curdir); curdir = 0; return; } int newdir = my_open(dirname); if(newdir == -1) { printf("no such directory.\n"); return; } my_close(curdir); curdir = newdir; } void my_ls() { int i, len = openfilelist[curdir].ffcb.length-3; fcb *fcbcursor = getfcb(curdir) + 3; while(len > 0) { if(fcbcursor->free == 0) fcbcursor++; else { printf("%s ", fcbcursor->filename); len--; fcbcursor++; } } printf("\n"); } void my_rmdir(char *dirname) { int i, plen = openfilelist[curdir].ffcb.length; char *fcbs = (char *)malloc(sizeof(fcb)*plen); openfilelist[curdir].count = 0; assert(do_read(curdir, plen*sizeof(fcb), fcbs) == plen*sizeof(fcb)); fcb *fcbcursor = (fcb *)fcbs; for(i = 1; i <= plen; i++, fcbcursor++) { if(fcbcursor->free == 1 && fcbcursor->attribute == 0 && strcmp(fcbcursor->filename, dirname) == 0) break; else if(i == plen) { printf("no such directory.\n"); return; } } fcb *rfcb = (fcb *)(myvhead + BLOCKSIZE*(fcbcursor->first-1)); if(rfcb->length > 3) { printf("this directory is not empty.\n"); return; } for(i = 0; i < MAXOPENFILE; i++) { if(openfilelist[i].topenfile == 1 && strcpy(openfilelist[i].ffcb.filename, dirname) == 0) { my_close(i); break; } } freeblk(rfcb->first); fcbcursor->free = 0; openfilelist[curdir].count = 0; assert(do_write(curdir, fcbs, plen*sizeof(fcb), 2) == plen*sizeof(fcb)); openfilelist[curdir].ffcb.length--; openfilelist[curdir].fcbstate = 1; }
223bf5927dc3c64fede37e23a3996ddf207a9aad
[ "Markdown", "C" ]
9
C
fakki/OS_Lab
1b404d9dd4489f75e0238db8c9dcf189acbe47e2
84d4241c21321cb989dc6fc3dd37df54ac79c48a
refs/heads/master
<repo_name>jinpingyang/springbootdemo<file_sep>/demo/src/main/java/com/example/demo/entity/User.java package com.example.demo.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Data @Entity @Table(name="ts_user") public class User implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column(name="no") private String no; @Column(name="name") private String name; @Column(name="address") private String address; } <file_sep>/demo/src/main/java/com/example/demo/utils/XmlUtil.java package com.example.demo.utils; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import com.example.demo.User; public class XmlUtil { public static void main(String[] args) { xmlForObject(); // objectForXml(); } public static void xmlForObject() { try { String xml =System.getProperty("user.dir").replaceAll("\\\\", "/")+"/src/main/resources/user.xml"; // String xml="C:/work/user.xml"; JAXBContext context = JAXBContext.newInstance(User.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Object object = unmarshaller.unmarshal(new File(xml)); User user = (User) object; System.out.println(user.toString()); } catch (Exception e) { e.getStackTrace(); } } public static void objectForXml() { try { User user = new User(); user.setId(1); user.setNo("001"); user.setName("zhansna"); user.setAddress("shanghai"); JAXBContext context = JAXBContext.newInstance(User.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); StringWriter writer = new StringWriter(); marshaller.marshal(user, writer); System.out.println(writer.toString()); } catch (Exception e) { e.getStackTrace(); } } } <file_sep>/demo/src/main/java/com/example/demo/SchedulingConfig.java package com.example.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; @Configuration @EnableScheduling//开启对定时任务支持 @Async //每个任务在不同的线程中 public class SchedulingConfig { private final Logger log = LoggerFactory.getLogger(getClass()); @Scheduled(cron = "0/5 * * * * *") public void scheduled(){ log.info("=====>>>>>使用cron {}",System.currentTimeMillis()); } @Scheduled(fixedRate = 5000) public void scheduled1() { log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis()); } @Scheduled(fixedDelay = 5000) public void scheduled2() { log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis()); } } <file_sep>/demo/src/main/java/com/example/demo/token/TokenUtil.java package com.example.demo.token; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.example.demo.entity.User; import com.example.demo.redis.RedisUtil; import com.example.demo.utils.UUIDUtil; @Component public class TokenUtil { @Autowired private RedisUtil redisUtil; /** * //认证之后用UUID生成token * @param user * @return */ public String getToken(User user) { String token=UUIDUtil.uuid(); redisUtil.set(token, user); return token; } /** * 刷新token * @param token * @return */ public Boolean refreshToken(String token) { return redisUtil.expire(token); } /** * 退出,删除token * @param token * @return */ public Boolean logoff(String token) { return redisUtil.del(token); } /** * 根据token,获取用户 * @param token * @return */ public User getUser(String token) { return (User)redisUtil.get(token); } public boolean existsToken(String token) { return redisUtil.hasKey(token); } } <file_sep>/demo/src/main/java/com/example/demo/annotation/User.java package com.example.demo.annotation; import com.example.demo.annotation.FieldCase.Color; public class User { @FieldCase(id=1,des="id",fruitColor=Color.RED) private int id; @FieldCase(id=2,des="name",fruitColor=Color.GREEN) private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/demo/src/main/java/com/example/demo/annotation/FieldCase.java package com.example.demo.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface FieldCase { int id() default 0; String des() default ""; enum Color{ BULE,RED,GREEN}; Color fruitColor() default Color.GREEN; } <file_sep>/demo/src/main/java/com/example/demo/repository/UserRepository.java package com.example.demo.repository; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.example.demo.entity.User; import com.example.demo.vo.UserVo; @Repository public interface UserRepository extends BaseRepository<User,Integer>{ @Query("select new com.example.demo.vo.UserVo(u.id,u.no,u.name,u.address) from User u") public List<UserVo> findByAll(); public Optional<User> findById(int id); } <file_sep>/demo/src/main/java/com/example/demo/service/UserService.java package com.example.demo.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import com.example.demo.repository.UserRepository; import com.example.demo.vo.UserVo; import com.github.pagehelper.PageHelper; @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private UserMapper userMapper; @Cacheable(cacheNames="user",key="#id") public User findById(int id) { return userRepository.findById(id).isPresent()?userRepository.findById(id).get():null; } public List<UserVo> findByAll(){ return userRepository.findByAll(); } public Page<User> findByAll(int page,int size){ // Pageable pageable=new PageRequest(page, size, Sort.Direction.DESC, "id"); PageRequest pageRequest = PageRequest.of(page, size,Sort.Direction.DESC, "id"); return userRepository.findAll(pageRequest); } public Page<User> findByAll(Map<String, Object> params,Pageable pageable){ Page<User> page = userRepository.findAll((root, query, criteriaBuilder)->{ List<Predicate> list = new ArrayList<>(); Predicate[] p = new Predicate[list.size()]; if(params!=null) { params.forEach((k, v) -> list.add(criteriaBuilder.equal(root.get(k), params.get(k)))); } return criteriaBuilder.and(list.toArray(p)); } ,pageable); return page; } public Page<User> findCriteria(int page,int size,User user){ // Pageable pageable=new PageRequest(page, size, Sort.Direction.DESC, "id"); PageRequest pageRequest = PageRequest.of(page, size,Sort.Direction.DESC, "id"); return userRepository.findAll(new Specification<User>() { @Override public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { List<Predicate> list = new ArrayList<Predicate>(); if(user.getNo()!=null&&!user.getNo().equals("")) { list.add(criteriaBuilder.equal(root.get("no").as(String.class), user.getNo())); } Predicate[] p = new Predicate[list.size()]; return criteriaBuilder.and(list.toArray(p)); } },pageRequest); } public List<User> selectAll(){ com.github.pagehelper.Page<User> page= PageHelper.startPage(1, 1); return userMapper.selectAll(); } } <file_sep>/demo/src/test/java/com/example/demo/DemoApplicationTests.java package com.example.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.example.demo.entity.User; import com.example.demo.redis.RedisUtil; import com.example.demo.service.UserService; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class DemoApplicationTests { @Autowired private RedisUtil redisUtil; @Autowired private UserService userService; @Test public void contextLoads() { // User user=userService.findById(1); // boolean b=redisUtil.set("user", user); // System.out.println(b); // boolean b=redisUtil.expire("user"); // System.out.println(b); boolean b=redisUtil.hasKey("user"); System.out.println(b); // Object object=redisUtil.get("user"); // User user=(User)object; // System.out.println(user.getId()); } } <file_sep>/demo/src/main/java/com/example/demo/config/SecurityConfiguration.java package com.example.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.example.demo.utils.MyPasswordEncoder; @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter{ protected void configure(AuthenticationManagerBuilder auth) throws Exception { //5版本后密码支持多种加密格式 auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()) .withUser("admin") .password("1") .roles("ADMIN"); auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("user").password(new BCryptPasswordEncoder().encode("1")) .roles("USRE"); // auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } /** * 具体的权限控制规则配置 */ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(HttpMethod.OPTIONS).permitAll() //任何用户可以访问 .anyRequest().authenticated() //任何没有匹配上的其他的url请求,只需要用户被验证。 .and().formLogin()/**.loginPage("/login")//指定登陆页面,不指定跳转spring登陆页面*/ // .failureForwardUrl("/login") //登录失败后以登录时的请求转发到该链接 // .successHandler(successHandler) //登录成功后调用该处理器 // .successForwardUrl("/test") .permitAll() .and().logout().permitAll() // .logoutSuccessUrl("/login") //退出后访问URL .and().httpBasic() .and().csrf().disable(); } /** * 全局请求忽略规则配置 */ @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers(HttpMethod.OPTIONS, "/**") .antMatchers( "/v2/api-docs","/swagger-resources/**","/swagger-ui.html**","/webjars/**") .antMatchers("/signin"); } } <file_sep>/demo/src/main/java/com/example/demo/utils/FileUtils.java package com.example.demo.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Permission; public final class FileUtils { public static final SecurityManager SECURITYMANAGER = new SecurityManager() { public void checkPermission(Permission perm) { } }; public static final SecurityManager SYSSECURITYMANAGER = System .getSecurityManager(); /** * * @param filePath * 相对路径 * @param content * 保存内容 * @return 返回相对路径 * @throws IOException */ public static String writeFile(String filePath, byte[] content) throws IOException { if (content == null) { return null; } System.setSecurityManager(SECURITYMANAGER); FileOutputStream fos = null; try { File infoFile = new File(filePath); infoFile = infoFile.getCanonicalFile(); if (!infoFile.exists()) { File dir = infoFile.getParentFile(); if (dir != null && !dir.exists()) { dir.mkdirs(); } } fos = new FileOutputStream(infoFile); fos.write(content); fos.flush(); fos.close(); return filePath; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (SYSSECURITYMANAGER != null) { System.setSecurityManager(SYSSECURITYMANAGER); } } } public static String storeFile(String filePath, byte[] content) throws IOException { if (content == null) { return null; } System.setSecurityManager(SECURITYMANAGER); FileOutputStream fos = null; try { File infoFile = new File(filePath); infoFile = infoFile.getCanonicalFile(); if (!infoFile.exists()) { File dir = infoFile.getParentFile(); if (dir != null && !dir.exists()) { dir.mkdirs(); } } fos = new FileOutputStream(infoFile); fos.write(content); fos.flush(); fos.close(); return filePath; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (SYSSECURITYMANAGER != null) { System.setSecurityManager(SYSSECURITYMANAGER); } } } public static boolean deleteFile(String file) { System.setSecurityManager(SECURITYMANAGER); boolean isDeleted; File aFile = new File(file); if (aFile.exists() && aFile.isFile()) { isDeleted = aFile.delete(); } else { isDeleted = false; } System.setSecurityManager(SECURITYMANAGER); return isDeleted; } public static byte[] readFile(String filePath) { File infoFile = new File(filePath); byte[] result = null; if (infoFile.exists()) { result = new byte[(int) infoFile.length()]; try { FileInputStream fis = new FileInputStream(infoFile); fis.read(result); fis.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } /** * 顺序读取文本文件的内容 * @param file * @param encoding * @return */ public static String readToString(File file, String encoding) { Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, encoding); } catch (UnsupportedEncodingException e) { System.err.println("The OS does not support " + encoding); e.printStackTrace(); return null; } } }
7bdca3de94a21062cb6ae8be6180eb54325b1c04
[ "Java" ]
11
Java
jinpingyang/springbootdemo
8a75af73c87f0689f201ec2292bcec65b5f9982f
bb159eaec15b370ce1d83d87cc4d3619e0572a9e
refs/heads/master
<file_sep>package module type ApiResp struct { Errno int64 `json:"errno"` Errmsg string `json:"errmsg"` Data interface{} `json:"data,omitempty"` }<file_sep>package cache import ( "bytes" "encoding/json" "github.com/BlockABC/cache_module/memche" "github.com/BlockABC/cache_module/module" "github.com/BlockABC/cache_module/util" "github.com/go-redis/redis" "io/ioutil" "log" "net/http" "os" "fmt" gouache "github.com/bradfitz/gomemcache/memcache" "github.com/gin-gonic/gin" "strconv" "time" ) var logger = log.New(os.Stdout, "eth_client: ", log.Lshortfile|log.LstdFlags) const ( Salt = "salt" RequestUnlock = "0" RequestLock = "1" MemCache = 1 Redis = 2 LOCK = "lock:" RequestCacheTime = "request_cache_time:" ) type cacheKeyGetter = func(c *gin.Context) string type shouldCacheHandler = func(apiResp *module.ApiResp) bool type Middleware struct { cacheClientMemCache *memche.Client cacheClientRedis *redis.Client enableCache bool } func NewCacheMiddleware(memCache *memche.Client, redisCache *redis.Client, enableCache bool) *Middleware { middleware := Middleware{ cacheClientMemCache: memCache, cacheClientRedis: redisCache, enableCache: enableCache, } return &middleware } /* ** cacheTime:接口过期时间,过期后会重新从DB拿数据并更新到缓存 ** redisTime:redis内容过期时间,避免redis溢出问题 */ func (m *Middleware) CacheGet(cacheTime, cacheType int32, redisTime time.Duration) gin.HandlerFunc { switch cacheType { case MemCache: return cacheGetByMemCache(cacheTime, m) case Redis: return cacheGetByRedis(m, cacheTime, redisTime) default: return cachePostByRedis(m, cacheTime, redisTime) } } /* ** cacheTime:接口过期时间,过期后会重新从DB拿数据并更新到缓存 ** redisTime:redis内容过期时间,避免redis溢出问题 */ func (m *Middleware) CachePost(cacheTime, cacheType int32, redisTime time.Duration) gin.HandlerFunc { switch cacheType { case MemCache: return cachePostByMemCache(cacheTime, m) case Redis: return cachePostByRedis(m, cacheTime, redisTime) default: return cachePostByRedis(m, cacheTime, redisTime) } } func cacheGetByMemCache(cacheTime int32, m *Middleware) gin.HandlerFunc { return func(c *gin.Context) { if c.Request.Method != http.MethodGet { return } cacheRequestByMemCache(m, cacheTime, c, func(c *gin.Context) string { url := c.Request.URL.String() return util.GetMd5([]byte(url)) }, DefaultApiRespShouldCacheHandler) } } func cachePostByMemCache(cacheTime int32, m *Middleware) gin.HandlerFunc { return func(c *gin.Context) { if c.Request.Method != http.MethodPost || c.Request.Body == nil { return } cacheRequestByMemCache(m, cacheTime, c, func(c *gin.Context) string { bodyBytes, _ := ioutil.ReadAll(c.Request.Body) urlBytes := []byte(c.Request.URL.String()) return util.GetMd5(append(bodyBytes, urlBytes...)) }, DefaultApiRespShouldCacheHandler) } } func cacheGetByRedis(m *Middleware, cacheTime int32, redisTime time.Duration) gin.HandlerFunc { return func(c *gin.Context) { if c.Request.Method != http.MethodGet { return } cacheRequestByRedis(m, redisTime, cacheTime, c, func(c *gin.Context) string { cook, _ := json.Marshal(c.Request.Cookies()) //加入cookie的部分 url := c.Request.URL.String() + c.GetString(Salt) + string(cook) return url }, DefaultApiRespShouldCacheHandler) } } func cachePostByRedis(m *Middleware, cacheTime int32, redisTime time.Duration) gin.HandlerFunc { return func(c *gin.Context) { if c.Request.Method != http.MethodPost || c.Request.Body == nil { return } cacheRequestByRedis(m, redisTime, cacheTime, c, func(c *gin.Context) string { bodyBytes, _ := c.GetRawData() cook, _ := json.Marshal(c.Request.Cookies()) urlBytes := append([]byte(c.Request.URL.String()), cook...) c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // 关键点 return string(append(urlBytes, bodyBytes...)) }, DefaultApiRespShouldCacheHandler) } } func DefaultApiRespShouldCacheHandler(apiResp *module.ApiResp) bool { return apiResp.Errno == util.SUCCESS_CODE } func cacheRequestByMemCache(m *Middleware, cacheTime int32, c *gin.Context, keyGetter cacheKeyGetter, shouldCache shouldCacheHandler) { if !m.enableCache { return } //请求key key := keyGetter(c) //锁定key isLockKey := util.GetMd5([]byte(LOCK + key)) //请求缓存时间 isLockTimeKey := util.GetMd5([]byte(RequestCacheTime + key)) //缓存结果 resp, err := m.cacheClientMemCache.Get(key) //是否锁定 isLock, errCache := m.cacheClientMemCache.Get(isLockKey) //锁定时间 lockTime, _ := m.cacheClientMemCache.Get(isLockTimeKey) // cache 中存在对应的条目 if err == nil { var respMap map[string]interface{} _ = json.Unmarshal(resp, &respMap) c.AbortWithStatusJSON(http.StatusOK, respMap) //是否强制更新缓存 isUpdate := false // 缓存时间和缓存有效时间可以找到 并且 没有被锁定 if string(isLock) == RequestUnlock || errCache == gouache.ErrCacheMiss { // 缓存设置的时间 生成时间 lockTimeInt, _ := strconv.Atoi(string(lockTime)) if lockTimeInt > 0 { // 如果当前时间 - 缓存设置的时间 >= 缓存时间 我们要强制更新缓存 if (time.Now().Unix() - int64(lockTimeInt)) >= int64(cacheTime) { isUpdate = true } } else { isUpdate = true } log.Printf("There is a cache, forcing updates to the cache %s----%v----%t:", c.Request.RequestURI, lockTimeInt, isUpdate) } if !isUpdate { return } } // 锁定了并且没有缓存 直接返回空 if string(isLock) == RequestLock { //直接返回空 c.AbortWithStatusJSON(http.StatusOK, module.ApiResp{ Errno: util.RequestLock, Errmsg: "Try again later", Data: []interface{}{}, }) return } // 没有锁定 锁定相同的请求 if errCache == gouache.ErrCacheMiss || string(isLock) == RequestUnlock { //锁定 if err := m.cacheClientMemCache.Set(isLockKey, []byte(RequestLock), 600); err != nil { log.Println("lock err:", isLockKey, isLock, err, cacheTime) } } // cache 中没有对应的条目,继续后续执行 blw := &bufferedWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} c.Writer = blw c.Next() statusCode := c.Writer.Status() // 不缓存失败的请求 if statusCode != http.StatusOK { return } if blw.body.String() == "" { return } // 获取 api 执行结果 var apiResp module.ApiResp body := blw.body.Bytes() if err := json.Unmarshal(body, &apiResp); err != nil { return } if shouldCache(&apiResp) { // 缓存结果 不过期 if err := m.cacheClientMemCache.Set(key, body, 0); err != nil { log.Println("The cache interface failed err:", isLockKey, isLock, err) } // 缓存返回结果的时间和接口执行的时间 if err := m.cacheClientMemCache.Set(isLockTimeKey, []byte(fmt.Sprintf("%d", time.Now().Unix())), 0); err != nil { log.Println("Cache lock time and cache time failed err:", isLockKey, isLock, err) } //解锁 if err := m.cacheClientMemCache.Set(isLockKey, []byte(RequestUnlock), 600); err != nil { log.Println("Unlock err:", isLockKey, isLock, err, cacheTime) } } else { // 缓存返回结果的时间和接口执行的时间 if err := m.cacheClientMemCache.Set(isLockTimeKey, []byte(fmt.Sprintf("%d", time.Now().Unix())), 0); err != nil { log.Println("Cache lock time and cache time failed err:", isLockKey, isLock, err) } //解锁 if err := m.cacheClientMemCache.Set(isLockKey, []byte(RequestUnlock), 600); err != nil { log.Println("Unlock err:", isLockKey, isLock, err, cacheTime) } } } /* ** redis缓存接口,为了避免同一请求在无缓存时同时下放到DB,需要先锁定接口,再请求数据,在请求返回之前,同样的请求只能拉取到上一次缓存的数据,同时设置一个redis过期时间,避免缓存溢出问题 */ func cacheRequestByRedis(m *Middleware, redisTime time.Duration, cacheTime int32, c *gin.Context, keyGetter cacheKeyGetter, shouldCache shouldCacheHandler) { if !m.enableCache { return } /*如果程序异常挂掉,需要清空lock,否则进入此接口就会一直走锁定逻辑, 这里的问题点是每十分钟会有一次自动解锁,可能会造成新的请求下放到DB, 之所以不设置更短时间,是为了防止接口迟迟不返回导致请求下放到DB的问题,TIDB经常会因为这个挂掉*/ lockTime := 10 * time.Minute key := keyGetter(c) //请求key lockKey := LOCK + key //锁定key updateTimeKey := RequestCacheTime + key //接口更新时间 defer m.cacheClientRedis.Set(lockKey, RequestUnlock, lockTime) defer func() { //发生异常时,解除锁定,便于定位问题 if r := recover(); r != nil { if err := m.cacheClientRedis.Set(lockKey, RequestUnlock, lockTime).Err(); err != nil { logger.Println("Unlock err:", lockKey, err, cacheTime) } //有返回解锁 } }() isLock, _ := m.cacheClientRedis.Get(lockKey).Result() //是否锁定,当缓存为空,isLock将返回空,err可以忽略 if isLock == RequestUnlock { _ = m.cacheClientRedis.Set(lockKey, RequestLock, lockTime).Err() //立即锁定接口,保证只能有一个相同请求进入 } if isLock == RequestLock { //锁定,当接口锁定,即这个接口已被进入,此时相同请求不能透传到数据库,如果缓存有数据,走缓存,缓存无数据返回空 if resp, err := m.cacheClientRedis.Get(key).Result(); err == nil { var respMap map[string]interface{} if err := json.Unmarshal([]byte(resp), &respMap); err == nil { c.AbortWithStatusJSON(http.StatusOK, respMap) return } } //缓存数据取不到时,返回空 c.AbortWithStatusJSON(http.StatusOK, module.ApiResp{Errno: util.RequestLock, Errmsg: "Try again later", Data: []interface{}{}}) return } //接口没有被锁定,那么执行过期检测,如果过期,更新缓存,没有过期,返回缓存 lastTime, _ := m.cacheClientRedis.Get(updateTimeKey).Int64() //更新时间,如果出错,lockTime为0,肯定会超出缓存时间,因此可以不检查 if (time.Now().Unix() - lastTime) <= int64(cacheTime) { //缓存还未过期,走缓存 if resp, err := m.cacheClientRedis.Get(key).Result(); err == nil { var respMap map[string]interface{} if err := json.Unmarshal([]byte(resp), &respMap); err == nil { c.AbortWithStatusJSON(http.StatusOK, respMap) return } } } //接口未锁定,且缓存过期,则下放接口到数据库 blw := &bufferedWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} c.Writer = blw c.Next() statusCode := c.Writer.Status() // 不缓存失败的请求 if statusCode != http.StatusOK { return } if blw.body.String() == "" { return } // 获取 api 执行结果 var apiResp module.ApiResp body := blw.body.Bytes() if err := json.Unmarshal(body, &apiResp); err != nil { return } if shouldCache(&apiResp) { if err := m.cacheClientRedis.Set(key, string(body), redisTime).Err(); err != nil { logger.Println("The cache interface failed err:", lockKey, isLock, err) return } // 更新缓存中返回结果的时间和接口执行的时间 if err := m.cacheClientRedis.Set(updateTimeKey, time.Now().Unix(), time.Hour*24).Err(); err != nil { log.Println("Cache lock time and cache time failed err:", lockKey, isLock, err) return } } } <file_sep>package redis import ( "fmt" "github.com/go-redis/redis" "time" ) func New(addr, pass string, db int, timeOut ...time.Duration) *redis.Client { opt := &redis.Options{ Addr: addr, Password: <PASSWORD>, DB: db, PoolSize: 10, PoolTimeout: 30 * time.Second, } switch len(timeOut) { case 3: fmt.Println("init write timeout:", timeOut[2]) opt.WriteTimeout = timeOut[2] fallthrough case 2: fmt.Println("init read timeout:", timeOut[1]) opt.ReadTimeout = timeOut[1] fallthrough case 1: fmt.Println("init dial timeout:", timeOut[0]) opt.DialTimeout = timeOut[0] } return redis.NewClient(opt) } func NewOptions(options *redis.Options) *redis.Client { return redis.NewClient(options) } func IsAlive(r *redis.Client) bool { select { case <-time.After(time.Millisecond * 100): return false default: ret := r.Ping() return ret.Err() == nil } } <file_sep>package util import ( "crypto/md5" "encoding/hex" "time" ) const ( SUCCESS_CODE = 0 RequestLock = 255 ) var NowFunc = func() time.Time { return time.Now() } func GetMd5(message []byte) (tmp string) { md5Ctx := md5.New() md5Ctx.Write(message) cipherStr := md5Ctx.Sum(nil) tmp = hex.EncodeToString(cipherStr) return tmp } <file_sep>package main import ( "github.com/BlockABC/cache_module" "github.com/BlockABC/cache_module/redis" "github.com/gin-gonic/gin" "net/http" "time" ) func main() { cacheClient := redis.New("127.0.0.1:6379", "", 0, time.Millisecond*100) router := gin.New() cacheMiddleware := cache.NewCacheMiddleware(nil, cacheClient, true) router.GET("/test", cacheMiddleware.CacheGet(30, cache.Redis, time.Hour*24*7), func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"errno": 0, "errmsg": "Success", "data": gin.H{"symbol_list": gin.H{"symbol": "EOS", "code": "eosio.token", "balance": "2.7937"}}}) }) _ = router.Run(":8080") } <file_sep># cache ## 使用 ```sh go get github.com/BlockABC/cache_module ``` ## Demo main.go ```go package main import ( "github.com/BlockABC/cache" "github.com/BlockABC/cache/redis" "github.com/gin-gonic/gin" "net/http" ) func main() { //初始化redis cacheClient := redis.New("127.0.0.1:6379", "", 0) //gin 相关 router := gin.New() // 初始化缓存中间件 1,MemCache client 2,RedisCache 3,Whether to use default false cacheMiddleware := cache.NewCacheMiddleware(nil, cacheClient, true) // cacheMiddleware.CacheGET(30, cache.Redis) 1,缓存时间 2,缓存类型Redis or MemCache router.GET("/test", cacheMiddleware.CacheGET(30, cache.Redis), func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"errno": 0, "errmsg": "Success", "data": gin.H{"symbol_list": gin.H{"symbol": "EOS", "code": "eosio.token", "balance": "2.7937"}}}) }) router.Run(":8080") } ``` ![](./cache.jpg) ## 使用12个线程运行30秒, 400个http并发 ```sh wrk -t12 -c400 -d30s http://127.0.0.1:8080/test Running 30s test @ http://127.0.0.1:8080/test 12 threads and 400 connections Thread Stats Avg Stdev Max +/- Stdev Latency 25.16ms 6.88ms 98.51ms 89.21% Req/Sec 803.18 575.34 2.77k 41.18% 287745 requests in 30.10s, 64.21MB read Socket errors: connect 155, read 0, write 0, timeout 0 Requests/sec: 9560.67 Transfer/sec: 2.13MB ``` <file_sep>package memche import ( "github.com/bradfitz/gomemcache/memcache" ) type Client struct { Client *memcache.Client } func New(cacheSvrList []string) *Client { cache := Client{} cache.Client = memcache.New(cacheSvrList...) return &cache } func (cache *Client) Set(key string, value []byte, expiration int32) error { return cache.Client.Set(&memcache.Item{Key: key, Value: value, Expiration: expiration}) } func (cache *Client) Get(key string) ([]byte, error) { item, err := cache.Client.Get(key) if err != nil { return nil, err } return item.Value, nil } <file_sep>package redis import ( "fmt" "testing" "time" ) func TestPing(t *testing.T) { r := New("127.0.0.1:6379", "", 0, time.Millisecond*100, time.Millisecond*500) r1 := New("eosaprk-web.redis.rds.aliyuncs.com:6379", "", 0, time.Millisecond*100) fmt.Println("ret:", IsAlive(r)) fmt.Println("ret:", IsAlive(r1)) } <file_sep>module github.com/BlockABC/cache_module go 1.12 require ( github.com/bradfitz/gomemcache v0.0.0-20190329173943-551aad21a668 github.com/gin-gonic/gin v1.4.0 github.com/go-redis/redis v6.15.2+incompatible github.com/onsi/ginkgo v1.8.0 // indirect github.com/onsi/gomega v1.5.0 // indirect )
157b07a294994d40bc777489db0424e9c78d9939
[ "Markdown", "Go Module", "Go" ]
9
Go
BlockABC/cache_module
803e4af839dcc7a499a9f3de168908b766a69776
9480c1ee6a0acc74d5c8b57960727ffbfd705ccb
refs/heads/master
<repo_name>Sflynn5/tutoring<file_sep>/SignupActivity.java package com.ark.my_app_firebase; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.database.FirebaseDatabase; public class SignupActivity extends AppCompatActivity implements View.OnClickListener { //variable views for the signup activity private Button button_signup; private EditText email ; private EditText pass ; private EditText name ; private EditText phone ; private EditText type ; private ProgressBar progressBar2; //declaring instance of firebase auth private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); //Initializing views for this activity email = (EditText)findViewById(R.id.editText_signup_email); pass = (EditText)findViewById(R.id.editText2_signup_pass); name = (EditText)findViewById(R.id.editText); phone = (EditText)findViewById(R.id.editText2_signup_phone); type = (EditText)findViewById(R.id.editText3_signup_op); button_signup=(Button)findViewById(R.id.button_signup_page); progressBar2 = (ProgressBar)findViewById(R.id.progressBar_signup); // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance(); button_signup.setOnClickListener(this); } public void registerUser(){ final String name1 =name.getText().toString().trim(); final String phone1 = phone.getText().toString().trim(); final String type1 = type.getText().toString().trim(); final String mail= email.getText().toString(); String password = pass.getText().toString(); if(mail.isEmpty()){ email.setError("Email is required!"); email.requestFocus(); return; } /* if(Patterns.EMAIL_ADDRESS.matcher(mail).matches()){ email.setError("Email is Invalid!"); email.requestFocus(); return; }*/ if(password.length() < 6){ pass.setError("Password should be atleast 6 characters long!"); pass.requestFocus(); return; } if(password.isEmpty()){ pass.setError("Passwod is required!"); pass.requestFocus(); return; } progressBar2.setVisibility(View.VISIBLE); mAuth.createUserWithEmailAndPassword(mail,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressBar2.setVisibility(View.GONE); if(task.isSuccessful()) { //string additional fields like name, type ,phone number User user = new User(name1,mail,phone1,type1); FirebaseDatabase.getInstance().getReference("Users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ //Toast.makeText(getApplicationContext(), "Successfully registered!", Toast.LENGTH_LONG).show(); finish(); Intent intent = new Intent(SignupActivity.this,profileActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//CLEARS ALL ACTIVITIES ON TOP OF STACK startActivity(intent); }else{ //display any other msg Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_LONG).show(); } } }); //CODE FOR INTENT TO THE NEXT PAGE->DASH BOARD FOR STUDENT/TUTOR }else if (task.getException() instanceof FirebaseAuthUserCollisionException){ Toast.makeText(getApplicationContext(), "You are already registered!", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_LONG).show(); } } }); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.button_signup_page: registerUser(); break; /* case R.id.button_login:finish(); startActivity(new Intent(this,MainActivity.class)); break;*/ } } } <file_sep>/app/java/tutorPost.java package com.example.tutoringapp; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; public class tutorPost extends AppCompatActivity { Button addInfo; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tutor_post); addInfo = findViewById(R.id.btnAdd); addInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addTutorInfo(); } }); } public void addTutorInfo(){ Intent intent = new Intent(this, tutorView.class); startActivity(intent); } }<file_sep>/MainActivity.java package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Spinner; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Spinner mySpinner = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.Subjects)); myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mySpinner.setAdapter(myAdapter); Spinner upvotesSpinner = (Spinner) findViewById(R.id.spinner2); ArrayAdapter<String> upvoteAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.UpVotes)); upvoteAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); upvotesSpinner.setAdapter(upvoteAdapter); Spinner courseLevelSpinner = (Spinner) findViewById(R.id.spinner3); ArrayAdapter<String> courseLevelAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.CourseLevel)); courseLevelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); courseLevelSpinner.setAdapter(courseLevelAdapter); } } <file_sep>/app/java/Login.java package com.example.tutoringapp; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Login extends AppCompatActivity { Button login; TextView email; TextView password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); login = findViewById(R.id.btnLogin); email = findViewById(R.id.etEmail); password = findViewById(R.id.etPassword); /* login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (student) { openStudentView(); }else { openTutorView(); } } });*/ } public void openStudentView(){ //Intent intent = new Intent(this, studentView.class); //startActivity(intent); } public void openTutorView(){ Intent intent = new Intent(this, tutorView.class); startActivity(intent); } }
d4b040bca02a342fac498a1d1cd47241362529ec
[ "Java" ]
4
Java
Sflynn5/tutoring
e897f95f48effaa61603b86ebbdfe3ddf489bbe8
80daeaaeb6c9d44141a8acd52767c3747171a229
refs/heads/master
<file_sep>public class DZ { public static void main (String [] args){ System.out.println("Task #1"); int a1 =2; int b1=5; int c1=10; System.out.println(a1+b1*c1/2); System.out.println("Task #2"); int a2=1; int b2=3; int c2=2; System.out.println((Math.pow(a2,c2)+Math.pow(b2,c2))/2); System.out.println("Task #3"); double a3=7; double b3=6; double c3=8; System.out.println((a3+b3)/12*c3%4+b3); System.out.println("Task #4"); double a4=12; double b4=9; double c4=11; System.out.println((a4-b4*c4)/(a4+b4)%c4); System.out.println("Task 5"); int a5=2,b5=3,c5=4; System.out.println(Math.abs(a5-b5)/Math.pow((a5+b5),3)-Math.cos(c5)); System.out.println ("Task 6"); double a6=12,b6=15; System.out.println(("Гипотенуза=")+Math.sqrt(Math.pow(a6,2)+Math.pow(b6,2))); double c6=19.209372712298546; System.out.println(("Sтреугольника=")+((a6*b6)/2)); System.out.println(("Pтреугольника=")+(a6+b6+c6)); System.out.println("Task 7"); int x1=3,y1=1; int x2=-3,y2=-1; System.out.println(("ширина прямоугольника=")+(Math.abs(y1)+Math.abs(y2))); System.out.println(("длина прямоугольника=")+(Math.abs(x1)+Math.abs(x2))); System.out.println(("Pпрямоугольника=")+(Math.abs(y1)+Math.abs(y2)+Math.abs(x1)+Math.abs(x2))*2); System.out.println(("Sпрямоугольника=")+ (Math.abs(y1)+Math.abs(y2))*(Math.abs(x1)+Math.abs(x2))); System.out.println ("Task 8"); double a8=5,b8=6; double a8Lb8=30; System.out.println(("a8Lb8Radians=")+(Math.toRadians(a8Lb8))); System.out.println(Math.cos(Math.toRadians(a8Lb8))); System.out.println(("с8=")+Math.sqrt(Math.pow(a8,2)+Math.pow(b8,2)-2*a8*b8*Math.cos(Math.toRadians(a8Lb8)))); double c8=3.0064057897984564; System.out.println(("PТреугольника=")+(a8+b8+c8)); double P=14.006405789798457; System.out.println(("Sтреугольника по формуле Герона=")+((P/2*(P/2-a8)*(P/2-b8)*(P/2-c8))/2)); System.out.println ("Task 10 результат1=" + Task1(a1,b1,c1)); System.out.println ("Task 10 результат2=" +Task2(a2, b2, c2)); System.out.println ("Task 10 результат3=" +Task3(a3, b3, c3)); System.out.println ("Task 10 результат4=" +Task4(a4, b4, c4)); System.out.println ("Task 10 результат5=" +Task5(a5, b5, c5)); System.out.println ("Task 11 результат6S=" +Task6(a6, b6, c6)); System.out.println ("Task 11 результат6P=" +Task6_1(a6, b6, c6)); System.out.println ("Task 11 результат7P=" +Task7(x1, x2, y2,y1)); System.out.println ("Task 11 результат7S=" +Task7_1(x1, x2, y2,y1)); System.out.println ("Task 11 результатc8=" +Task8(a8,b8,a8Lb8)); System.out.println ("Task 11 результатP=" +Task8_1(a8,b8,c8)); System.out.println ("Task 11 результатS=" +Task8_2(a8,b8,c8,P)); System.out.println ("Task 12"); double UAH=1000; double USD=50; double kurs1=27.3; double kurs2=26.5; System.out.println ("Task 12 USD за 1000 UAH="+Task12(UAH, kurs1)); System.out.println ("Task 12 UAH за 50 USD="+Task12_1(USD, kurs2)); System.out.println ("Task 13"); int day=11; int month =9; int year =24; System.out.println ("Task 13 количество дней="+Task13(day,month,year)); System.out.println ("Task 14"); int kill=527; System.out.println ("Task 14 всего километров="+Task14(kill)); } public static int Task1(int a1, int b1, int c1) { int IO = a1 + b1 * c1 / 2; return IO; } public static double Task2(double a2,double b2,double c2){ double I02=(Math.pow(a2,c2)+Math.pow(b2,c2))/2; return I02; } public static double Task3 (double a3, double b3, double c3){ double IO3=(a3+b3)/12*c3%4+b3; return IO3; } public static double Task4 (double a4, double b4, double c4){ double IO4=(a4-b4*c4)/(a4+b4)%c4; return IO4; } public static double Task5 (double a5, double b5, double c5){ double IO5=(Math.abs(a5-b5)/Math.pow((a5+b5),3)-Math.cos(c5)); return IO5; } public static double Task6 (double a6, double b6, double c6){ double IO6=(a6*b6)/2; return IO6; } public static double Task6_1 (double a6, double b6, double c6){ double IO6_1=a6+b6+c6; return IO6_1; } public static double Task7 (int x1, int x2, int y2, int y1){ int IO7=(Math.abs(y1)+Math.abs(y2)+Math.abs(x1)+Math.abs(x2))*2; return IO7; } public static double Task7_1 (int x1, int x2, int y2, int y1){ int IO7_1=(Math.abs(y1)+Math.abs(y2))*(Math.abs(x1)+Math.abs(x2)); return IO7_1; } public static double Task8 (double a8, double b8, double a8Lb8){ double IO8=Math.sqrt(Math.pow(a8,2)+Math.pow(b8,2)-2*a8*b8*Math.cos(Math.toRadians(a8Lb8))); return IO8; } public static double Task8_1(double a8, double b8, double c8){ double IO8_1=a8+b8+c8; return IO8_1; } public static double Task8_2(double a8, double b8, double c8, double P){ double IO8_2=((P/2*(P/2-a8)*(P/2-b8)*(P/2-c8))/2); return IO8_2; } public static double Task12(double UAH, double kurs1){ double Obmen_USD=UAH/kurs1; return Obmen_USD; } public static double Task12_1(double USD, double kurs2){ double Obmen_UAH=USD*kurs2; return Obmen_UAH; } public static int Task13 (int day, int month, int year){ int koldney=(year-1)*420+(month-1)*42+day; return koldney; } public static int Task14 (int kill){ int first =kill/100; int second =kill/10; int second2=second - first*10; int third= kill%10; int vsego = first+second2+third; return vsego; } }
f5f5a94336d563c517bd3a83e86391fc0a014677
[ "Java" ]
1
Java
lippi1991/New
b9075dda3f0e0f604b98dd3d2a13c823798b8803
55c0f50a107d05f373242b6b0d62f05c4018690b
refs/heads/main
<repo_name>PerhapsS44/Music_Playlist<file_sep>/main.c /* Copyright 2020 <NAME> 312CA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "./structuri.h" #include "./playlist.h" void process(char *comm, char *song, struct list *l, struct song **curs, FILE *output) { struct song *new, *del; union record meta; if (strcmp(comm, "ADD_FIRST") == 0) { meta = get_meta(song); new = create_song(meta, song); add_first(l, new, curs, output); } if (strcmp(comm, "ADD_LAST") == 0) { meta = get_meta(song); new = create_song(meta, song); add_last(l, new, curs, output); } if (strcmp(comm, "ADD_AFTER") == 0) { meta = get_meta(song); new = create_song(meta, song); add_after(l, new, curs, output); } if (strcmp(comm, "DEL_FIRST") == 0) { del = remove_first(l, curs, output); free_song(del); } if (strcmp(comm, "DEL_LAST") == 0) { del = remove_last(l, curs, output); free_song(del); } if (strcmp(comm, "DEL_CURR") == 0) { del = remove_curr(l, curs, output); free_song(del); } if (strcmp(comm, "DEL_SONG") == 0) { struct song *m; meta = get_meta(song); m = find_song(l, meta.data); del = remove_song(l, m, curs, output); free_song(del); } if (strcmp(comm, "MOVE_NEXT") == 0) { move_next(l, curs, output); } if (strcmp(comm, "MOVE_PREV") == 0) { move_prev(l, curs, output); } if (strcmp(comm, "SHOW_FIRST") == 0) { show_first(l, output); } if (strcmp(comm, "SHOW_LAST") == 0) { show_last(l, output); } if (strcmp(comm, "SHOW_CURR") == 0) { show_curr(curs, output); } if (strcmp(comm, "SHOW_PLAYLIST") == 0) { show_playlist(l, output); } } int main(int argc, char *argv[]) { struct list *playlist; struct song *cursor; FILE *input, *output; char command[20], song_name[100], song[120]; int no_commands, i; playlist = define_list(); cursor = NULL; if (argc != 3) { printf("Nu sunt date ca parametrii fisierele de in/out!\n"); return -1; } input = fopen(argv[1], "rt"); output = fopen(argv[2], "wt"); fscanf(input, " %d ", &no_commands); for (i = 0; i < no_commands; i++) { fscanf(input, "%s ", command); if (command[0] == 'A' || strcmp(command, "DEL_SONG") == 0) { fgets(song_name, 100, input); clean_name(song_name); snprintf(song, sizeof(song), "./songs/%s", song_name); } process(command, song, playlist, &cursor, output); } free_list(playlist); fclose(output); fclose(input); return 0; } <file_sep>/structuri.c #include "./structuri.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void clean_name(char *string) { int i, l; l = strlen(string); for (i = 0; i < l; i++) { if (string[i] == '\n' || string[i] == '\r' || string[i] == '\t') { string[i] = '\0'; } } } struct list *define_list() { struct list *l; l = (struct list *)malloc(sizeof(struct list)); l->size = 0; l->head = NULL; l->tail = NULL; return l; } struct song *create_song(union record meta, char *nume) { struct song *m; m = (struct song *)malloc(sizeof(struct song)); m->metadata = meta; m->nume = nume; m->next = NULL; m->prev = NULL; return m; } union record get_meta(char *filename) { FILE *f; union record meta; f = fopen(filename, "rb"); fseek(f, -ID3_SIZE, SEEK_END); fread(meta.data, ID3_SIZE, 1, f); fclose(f); return meta; } struct song *find_song(struct list *l, char data[ID3_SIZE]) { /* functia intoarce pointer la melodia gasita sau NULL, care va fi folosit ca sa se afiseze mesaje/steagra elementele */ struct song *c; int i; if (l->size == 0) { return NULL; } c = l->head; for (i = 0; i < l->size; i++) { if (strncmp(data, c->metadata.data, ID3_SIZE - 1) == 0) { return c; } c = c->next; } return NULL; } void free_song(struct song *m) { free(m); return; } void free_list(struct list *l) { struct song *c, *d; int i; if (l->size == 0) { free(l); return; } c = l->head; for (i = 0; i < l->size; i++) { d = c; c = c->next; free_song(d); } free(l); return; }<file_sep>/playlist.c #include "./structuri.h" #include "./playlist.h" #include <stdlib.h> #include <stdio.h> #include <string.h> void add_first(struct list *l, struct song *m, struct song **curs, FILE *output) { struct song *del; if (l->head == NULL) { /* l->size==0 */ l->head = m; l->tail = m; l->head->next = NULL; l->tail->next = NULL; l->head->prev = NULL; l->tail->prev = NULL; l->size++; (*curs) = m; return; } if (find_song(l, m->metadata.data)) { /* este in lista, deci clar size>0 */ del = remove_song(l, m, curs, output); free_song(del); } m->next = l->head; l->head->prev = m; l->head = m; m->prev = NULL; l->size++; return; } void add_last(struct list *l, struct song *m, struct song **curs, FILE *output) { struct song *del; if (l->head == NULL) { /* l->size==0 */ l->head = m; l->tail = m; l->head->next = NULL; l->tail->next = NULL; l->head->prev = NULL; l->tail->prev = NULL; l->size++; (*curs) = m; return; } if (find_song(l, m->metadata.data)) { /* este in lista, deci clar size>0 */ del = remove_song(l, m, curs, output); free_song(del); } m->prev = l->tail; l->tail->next = m; l->tail = m; m->next = NULL; l->size++; return; } void add_after(struct list *l, struct song *m, struct song **curs, FILE *output) { struct song *s, *del; if ((*curs) == NULL) { free_song(m); return; } s = find_song(l, m->metadata.data); if (s) { /* este in lista, deci clar size>0 */ if (*curs == s) { free_song(m); return; } del = remove_song(l, m, curs, output); free_song(del); } if (l->tail == (*curs)) { add_last(l, m, curs, output); return; } m->next = (*curs)->next; m->prev = (*curs); (*curs)->next->prev = m; (*curs)->next = m; l->size++; return; } struct song *remove_first(struct list *l, struct song **curs, FILE *output) { struct song *current; if (l->head == NULL) { fprintf(output, "Error: delete from empty playlist\n"); return NULL; } current = l->head; if (l->head == l->tail) { l->head = NULL; l->tail = NULL; l->size--; (*curs) = NULL; return current; } if ((*curs) == l->head) (*curs) = l->head->next; l->head = l->head->next; l->head->prev = NULL; l->size--; return current; } struct song *remove_last(struct list *l, struct song **curs, FILE *output) { struct song *current; if (l->tail == NULL) { fprintf(output, "Error: delete from empty playlist\n"); return NULL; } current = l->tail; if (l->tail == l->head) { l->tail = NULL; l->head = NULL; l->size--; (*curs) = NULL; return current; } if ((*curs) == l->tail) (*curs) = l->tail->prev; l->tail = l->tail->prev; l->tail->next = NULL; l->size--; return current; } struct song *remove_curr(struct list *l, struct song **curs, FILE *output) { struct song *c; if ((*curs) == NULL) { fprintf(output, "Error: no track playing\n"); return NULL; } c = (*curs); if (c == l->head) { remove_first(l, curs, output); } else if (c == l->tail) { remove_last(l, curs, output); } else { c->prev->next = c->next; c->next->prev = c->prev; l->size--; (*curs) = c->next; if ((*curs) == NULL) (*curs) = c->prev; } return c; } struct song *remove_song(struct list *l, struct song *m, struct song **curs, FILE *output) { struct song *c; if (m == NULL) { fprintf(output, "Error: no song found to delete\n"); return NULL; } if (l->size == 0) { fprintf(output, "Error: delete from empty playlist\n"); return NULL; } c = find_song(l, m->metadata.data); if (c == l->head) { remove_first(l, curs, output); } else if (c == l->tail) { remove_last(l, curs, output); } else { c->prev->next = c->next; c->next->prev = c->prev; l->size--; } if ((*curs) == c) { (*curs) = c->next; if ((*curs) == NULL) (*curs) = c->prev; } return c; } void move_next(struct list *l, struct song **curs, FILE *output) { if ((*curs) == NULL) { fprintf(output, "Error: no track playing\n"); } if ((*curs) != l->tail) (*curs) = (*curs)->next; return; } void move_prev(struct list *l, struct song **curs, FILE *output) { if ((*curs) == NULL) { fprintf(output, "Error: no track playing\n"); } if ((*curs) != l->head) (*curs) = (*curs)->prev; return; } void show_first(struct list *l, FILE *output) { struct song *s; s = l->head; if (s == NULL) { fprintf(output, "Error: show empty playlist\n"); return; } fprintf(output, "Title: %.*s\n", 30, s->metadata.id3.titlu); fprintf(output, "Artist: %.*s\n", 30, s->metadata.id3.artist); fprintf(output, "Album: %.*s\n", 30, s->metadata.id3.album); fprintf(output, "Year: %.*s\n", 4, s->metadata.id3.an); return; } void show_last(struct list *l, FILE *output) { struct song *s; s = l->tail; if (s == NULL) { fprintf(output, "Error: show empty playlist\n"); return; } fprintf(output, "Title: %.*s\n", 30, s->metadata.id3.titlu); fprintf(output, "Artist: %.*s\n", 30, s->metadata.id3.artist); fprintf(output, "Album: %.*s\n", 30, s->metadata.id3.album); fprintf(output, "Year: %.*s\n", 4, s->metadata.id3.an); return; } void show_curr(struct song **curs, FILE *output) { struct song *s; s = (*curs); if (s == NULL) { fprintf(output, "Error: show empty playlist\n"); return; } fprintf(output, "Title: %.*s\n", 30, s->metadata.id3.titlu); fprintf(output, "Artist: %.*s\n", 30, s->metadata.id3.artist); fprintf(output, "Album: %.*s\n", 30, s->metadata.id3.album); fprintf(output, "Year: %.*s\n", 4, s->metadata.id3.an); return; } void show_playlist(struct list *l, FILE *output) { struct song *c; int i; if (l->size == 0) { fprintf(output, "[]\n"); return; } c = l->head; fprintf(output, "[%.*s", 30, c->metadata.id3.titlu); c = c->next; for (i = 1; i < l->size; i++) { fprintf(output, "; %.*s", 30, c->metadata.id3.titlu); c = c->next; } fprintf(output, "]\n"); return; }<file_sep>/playlist.h #ifndef __PLAYLIST__ #define __PLAYLIST__ #include <stdio.h> /* functiile de baza din programul meu, care vor realiza cerintele temei */ void add_first(struct list *l, struct song *m, struct song **curs, FILE *output); void add_last(struct list *l, struct song *m, struct song **curs, FILE *output); void add_after(struct list *l, struct song *m, struct song **curs, FILE *output); struct song *remove_first(struct list *l, struct song **curs, FILE *output); struct song *remove_last(struct list *l, struct song **curs, FILE *output); struct song *remove_curr(struct list *l, struct song **curs, FILE *output); struct song *remove_song(struct list *l, struct song *m, struct song **curs, FILE *output); void move_next(struct list *l, struct song **curs, FILE *output); void move_prev(struct list *l, struct song **curs, FILE *output); void show_playlist(struct list *l, FILE *output); void show_first(struct list *l, FILE *output); void show_last(struct list *l, FILE *output); void show_curr(struct song **curs, FILE *output); /* TODO: -- sa testez functiile -- sa rulez testele oficiale */ #endif<file_sep>/structuri.h #ifndef __STRUCTURI__ #define __STRUCTURI__ #define ID3_SIZE 97 union record { char data[ID3_SIZE]; struct ID3 { char antet[3]; char titlu[30]; char artist[30]; char album[30]; char an[4]; } id3; }; struct song { char *nume; union record metadata; struct song *next; struct song *prev; }; struct list { struct song *head; struct song *tail; int size; }; void clean_name(char *string); struct list *define_list(); union record get_meta(); struct song *create_song(union record meta, char *nume); struct song *find_song(struct list *l, char data[ID3_SIZE]); /* TODO: */ void free_song(struct song *m); void free_list(struct list *l); #endif<file_sep>/Makefile CC=gcc CFLAGS=-Wall -Wextra -std=c99 DEBUG=-g -ggdb -march=native build: structuri.o main.o playlist.o $(CC) $(CFLAGS) $(DEBUG) structuri.o playlist.o main.o -o tema1 playlist.o: $(CC) $(CFLAGS) $(DEBUG) -c ./playlist.c structuri.o: $(CC) $(CFLAGS) $(DEBUG) -c ./structuri.c main.o: $(CC) $(CFLAGS) $(DEBUG) -c main.c cb: make clean make build run: make clean make build ./tema1 file.in file.out clear cat file.out clean: rm *.o rm tema1
81a3eb48a512774b04803d351d44ccf7c05b4adf
[ "C", "Makefile" ]
6
C
PerhapsS44/Music_Playlist
94c67622f1f31630b732142205786757bcf3d160
a219a775ff1b7c6e029acadb8ae4781ac67feb95
refs/heads/master
<repo_name>smkelson/react-4-mini<file_sep>/src/Route1.js import React from 'react'; class Route1 extends React.Component { render(){ return ( <div> We are route 1 </div> ) } } export default Route1<file_sep>/src/Route2.js import React from 'react'; class Route2 extends React.Component { render(){ return ( <div> We are route 2 </div> ) } } export default Route2<file_sep>/src/Route3.js import React from 'react'; class Route3 extends React.Component { render(){ const words = this.props.match.params.words; return ( <div> We are route 3 -----{words} </div> ) } } export default Route3
7da3e38181f9696c76503e122d6c928e0c18925d
[ "JavaScript" ]
3
JavaScript
smkelson/react-4-mini
4904828fba20229c3a6648e7cd9002bf0abd4ca4
371ae91f9e5b26320c0e4b9ae791f3edb6b58ed3
refs/heads/master
<repo_name>kullerkeks/drupalentwicklertheme<file_sep>/js/custom.js (function ($) { Drupal.behaviors.customOmegaSubthemeJS = { attach: function(context, settings) { // you can implement your custom javascript/jquery here, // and also create other attached behaviors // find skype status button and add random url paramter for quick image refresh $('img[src*="mystatus.skype.com"]').each(function() { var skypebutton_url = $(this).attr("src"); skypebutton_url = skypebutton_url + '?' + Math.floor(Math.random()*1000); $(this).attr('src', skypebutton_url); }); // end if skype button } }; })(jQuery); <file_sep>/template.php <?php /** * @file * This file is empty by default because the base theme chain (Alpha & Omega) provides * all the basic functionality. However, in case you wish to customize the output that Drupal * generates through Alpha & Omega this file is a good place to do so. * * Alpha comes with a neat solution for keeping this file as clean as possible while the code * for your subtheme grows. Please read the README.txt in the /preprocess and /process subfolders * for more information on this topic. */ /** * by Simon: Adds Site-Slogan as Meta Tag description only to front-page * Adds Google Webmaster Tools Google Site Verification */ function drupalentwickler_page_alter($page) { if (drupal_is_front_page()) { $meta_desc = array( '#type' => 'html_tag', '#tag' => 'meta', '#attributes' => array( 'name' => 'description', 'content' => variable_get("site_slogan"), ) // end array ); // end array drupal_add_html_head( $meta_desc, 'meta_description' ); // Google Webmasters Tools Verification Code $meta_desc = array( '#type' => 'html_tag', '#tag' => 'meta', '#attributes' => array( 'name' => 'google-site-verification', 'content' => 'EM1UDU-1FsQ07JVIMWW-Eh0_K_7Bh8G9WWYuXPBUcE4', ) ); drupal_add_html_head( $meta_desc, 'google-site-verification' ); } // endif is_frontpage } // end page alter
c807645f130d9788ec7b0670a34b405303a90c9e
[ "JavaScript", "PHP" ]
2
JavaScript
kullerkeks/drupalentwicklertheme
8c68406b245f9e24705c2b2baa093186327632a6
d53bc4a95311a79a2e1b70cc2f1d2285e4ab72ce
refs/heads/master
<repo_name>caramorelli/fetch-intro-dog-ceo-challenge-nyc-web-100818<file_sep>/src/index.js console.log('%c HI', 'color: firebrick') document.addEventListener('DOMContentLoaded', function() { const imgUrl = "https://dog.ceo/api/breeds/image/random/4"; const breedUrl = "https://dog.ceo/api/breeds/list/all"; const selectFilter = document.getElementById('breed-dropdown') const breedList = document.getElementById('dog-breeds') const dogs = breedList.getElementsByTagName('LI') fetch(imgUrl) .then(response => response.json()) .then(json => addImage(json.message)); fetch(breedUrl) .then(response => response.json()) .then(json => addBreed(json.message) ); selectFilter.addEventListener('change', function(event) { displayFilterList(event.target.value); }) function addBreed(breedInfo) { for (key in breedInfo) { let listItem = document.createElement('LI'); listItem.innerHTML = key; breedList.append(listItem); listItem.addEventListener('click', function(event) { if (event.target) { event.target.style.color = randomColor(); } }) } } function displayFilterList(letter) { for (var i = 0; i < dogs.length; i++) { var breedName = dogs[i].innerHTML; console.log(breedName); if (breedName[0] !== letter) { (dogs[i]).style.visibility = 'hidden' } } } }) function addImage(picture) { let container = document.getElementById('dog-image-container'); picture.forEach(function(picURL) { let makeImg = document.createElement('img'); makeImg.src = picURL; container.append(makeImg); }) } function randomColor() { return 'rgb(' + randomNum() + ',' + randomNum() + ',' + randomNum() + ')'; } function randomNum() { return Math.floor(Math.random() * 256) } // console.log('%c HI', 'color: firebrick') // // // document.addEventListener('DOMContentLoaded', function() { // const imgUrl = "https://dog.ceo/api/breeds/image/random/4"; // const breedUrl = "https://dog.ceo/api/breeds/list/all"; // let breedList = document.getElementById('dog-breeds') // // // fetch(imgUrl) // .then(response => response.json()) // .then(json => addImage(json.message)); // // fetch(breedUrl) // .then(response => response.json()) // .then(json => addBreed(json.message) ); // // // let selectFilter = document.getElementById('breed-dropdown') // selectFilter.addEventListener('change', function(event) { // var letter = event.target.value // displayFilterList(letter) // event.target.value // }) // // }) // // function addImage(picture) { // let container = document.getElementById('dog-image-container'); // picture.forEach(function(picURL) { // let makeImg = document.createElement('img'); // makeImg.src = picURL; // container.append(makeImg); // }) // } // // function addBreed(breedInfo) { // let ulContainer = document.getElementById('dog-breeds'); // for (key in breedInfo) { // let listItem = document.createElement('LI'); // listItem.innerHTML = key; // ulContainer.append(listItem); // listItem.addEventListener('click', function(event) { // // if (event.target) { // event.target.style.color = randomColor(); // } // }) // } // } // // ## Challenge 4 // // Once we are able to load _all_ of the dog breeds onto the page, add javascript so that the user can filter breeds that start with a particular letter using a dropdown. // // For example, if the user selects 'a' in the dropdown, only show the breeds with names that start with the letter a. For simplicity, the dropdown only includes the letters a-d. However, we can imagine expanding this to include the entire alphabet
ef08a14de43dc7f4c102b6a9ce298658eb333a9a
[ "JavaScript" ]
1
JavaScript
caramorelli/fetch-intro-dog-ceo-challenge-nyc-web-100818
86817abe558178cb54b104a766777787eff4df14
14895d7c7364e71397bcdfc87a38f6cc0960eb5b
refs/heads/master
<file_sep>'use strict'; // var turtle = { // legs: 4, // shell: true, // age: 115, // colors: ['turquoise'], // weight: 25, // ninja: true, // snap: function() { // console.log('cowabunga!'); // }, // }; var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; var ulEl = document.createElement('ul'); for(var i = 0; i < months.length; i++) { var liEl = document.createElement('li'); liEl.textContent = months[i]; ulEl.appendChild(liEl); } var monthsSection = document.getElementById('months'); monthsSection.appendChild(ulEl); <file_sep>var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]; for(start, stop, step) {} for (var i = 0; i < nums.length; i+=3) { console.log('index: ', i) console.log('value: ', nums[i]) } var multi = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for (var i = 0; i < multi.length; i++) { for (var j = 0; j < multi[i].length; j++) { console.log(multi[i][j]) } } var count = 0; while (count < 10) { var x = 5 console.log('count', count); x++; console.log(x) count++; } console.log('done'); console.log(x) // Don't do this... // while (true) { // var x = 5 // console.log('count', count); // count++; // } // do something once, then while true...continue do { // do something } while(true) <file_sep>'use strict'; var productNames = ['bag', 'banana', 'bathroom', 'boots', 'breakfast', 'bubblegum', 'chair', 'cthulhu', 'dog-duck', 'dragon', 'pen', 'pet-sweep', 'scissors', 'shark', 'sweep', 'tauntaun', 'unicorn', 'usb', 'water-can', 'wine-glass']; var allProducts = []; var left = document.getElementById('left'); var center = document.getElementById('center'); var right = document.getElementById('right'); var container = document.getElementById('container'); var totalClicks = 0; function Product(name) { this.name = name; // this.path = 'img/' + name + '.jpg'; this.path = `img/${name}.jpg`; this.views = 0; this.votes = 0; allProducts.push(this); } // this loop creates all of my Product instances for (var i = 0; i < productNames.length; i++) { new Product(productNames[i]); } function rando() { return Math.floor(Math.random() * allProducts.length); } function threeRandomImages() { var randomIndexes = []; randomIndexes[0] = (rando()); randomIndexes[1] = (rando()); while (randomIndexes[0] === randomIndexes[1]) { randomIndexes[1] = rando(); console.log('duplicate prevented'); } randomIndexes[2] = rando(); while (randomIndexes[2] === randomIndexes[0] || randomIndexes[2] === randomIndexes[1]) { randomIndexes[2] = rando(); console.log('duplicate checker #2 caught a dupe') } // console.log(randomIndexes); left.src = allProducts[randomIndexes[0]].path; center.src = allProducts[randomIndexes[1]].path; right.src = allProducts[randomIndexes[2]].path; left.title = allProducts[randomIndexes[0]].name; center.title = allProducts[randomIndexes[1]].name; right.title = allProducts[randomIndexes[2]].name; allProducts[randomIndexes[0]].views++; allProducts[randomIndexes[1]].views++; allProducts[randomIndexes[2]].views++; } function handleClick(event) { // captures and chastizes a click not on an image if (event.target.id === 'container') { return alert('Click on images, please!!!!'); } console.log(event.target.title); for (var i = 0; i < allProducts.length; i++) { if (event.target.title === allProducts[i].name) { allProducts[i].votes++; } } totalClicks++; console.log(totalClicks, 'total clicks'); if (totalClicks > 4) { alert('You are out of clicks, yo.'); container.removeEventListener('click', handleClick); // show results } // console.log(event.target, 'was clicked'); threeRandomImages(); } threeRandomImages(); container.addEventListener('click', handleClick); <file_sep># Class 13: Local Storage and UI/UX Concepts <a id="top"></a> ## Lecture 13 ## Today's Schedule - Announcements - Code Review *[45 minutes]* - [UI/UX Discussion](#uiux) *[30 minutes]* - [Go over the assigned readings](#readings) *[30 minutes]* - Local Storage Code demo *[45 minutes]* **Learning Objectives** As a result of completing Lecture 13 of Code 201, students will: - Be able to understand concepts in persistence and the JavaScript commands needed to read/write to/from local storage, as measured by successful completion of the daily code assignment and a quiz administered in Canvas. - Demonstrate knowledge and command of JSON syntax and structure, as measured by successful completion of the daily code assignment and a quiz administered in Canvas. <a id="uiux"></a> ## UI & UX discussion Let's have a discussion on UI/UX, and also look at a few websites (some awesome, some kind of randomly chosen) relating to design and interaction. - [All Websites Look the Same](http://www.zeldman.com/2015/09/10/all-websites-look-the-same/) - [5 Ridiculously Common Misconceptions about UX](https://www.sitepoint.com/5-ridiculously-common-misconceptions-about-ux/) - [The A11Y Project](http://a11yproject.com/) - [10 Web design trends you can expect to see on websites in 2015](http://thenextweb.com/dd/2015/01/02/10-web-design-trends-can-expect-see-2015/) - [40 Stunning Website Designs with Great Color Schemes](http://www.onextrapixel.com/2013/10/25/40-stunning-website-designs-with-great-color-schemes/) - [Practical Typography](http://practicaltypography.com/) - [Seattle Times project on the Ehlwa River](https://github.com/seattletimes/elwha) When you start with your own projects, one of the things you will be fully responsible for is UI and UX. Be thoughtful. Find a design or layout you like and build something that mimics it. ALWAYS try to view your project from the perspective of someone who has never seen it before. Does the user need instructions? Are the user interactions clear to a new user? <a id="readings"></a> ## Readings **Read this article on local storage** - [Read this article on local storage](http://diveintohtml5.info/storage.html) - Local storage is the gateway to understanding basic concepts of persistence [-top-](#top) <file_sep>Team 1: Team 2: Team 3: Team 4: Team 5: <file_sep># about-me Lab project where we used prompts and conditional statements to make interactive responses using alerts. I ask 5 questions of the user and give them their score out of 5 at the end of the quiz. prompt structure into alert is as follows: if the user answers y/yes (not case-sensitive), then they will recieve a certain outcome alert which is either 'Correct!' or 'Incorrect!', and the same happens if the user types in n/no. if the user types in any other response, the user will recieve an alert with text 'Wrong input.' The user is given a point for each correct answer and is given the total of their points at the end of the quiz. in addition, in console there are messages that update the score for each question as well as provide the answer after the user has already answered the question. <file_sep>[To see our code review, look at this Pull Request!]() <file_sep># cookie-stand Week2 Lab "Salmon Cookie Stand" is my project in week2 for Code 201.<file_sep>// assignment prep demo given from the Google Chrome console var imgs = ['cat.png', 'hat.png']; var imgObjs = []; function ImageTracker(img) { this.name = img.split('.')[0]; this.path = img; this.totalClicks = 0; } for( var i=0; i < imgs.length; i++) { imgObjs.push(new ImageTracker(imgs[i])); }<file_sep>'use strict'; var video = document.getElementById('lecture-video'); var start = document.getElementById('video-start'); var pause = document.getElementById('video-pause'); function handleStartVideo() { video.play(); } function handlePauseVideo() { video.pause(); } start.addEventListener('click', handleStartVideo); pause.addEventListener('click', handlePauseVideo);<file_sep># Class 7: Object-Oriented Programming with Constructor Functions; HTML Tables ## Daily Plan - Notes: - Anything top of mind? - Feedback notes... - Code Review - Constructor functions - Tables - Lab preview ### 1:1 Schedules for this week! | Name | 7/17 | 7/18 | 7/19 | |---|---|---|---| | <NAME> | 2:00p | | <NAME> | 2:20p | | <NAME> | 2:40p | | <NAME> | 3:00p | | <NAME> | 3:20p | | <NAME> | 3:40p | | <NAME> | | 2:00p | | <NAME> | | 2:20p | | <NAME> | | 2:40p | | <NAME> | | 3:00p | | <NAME> | | 3:20p | | <NAME> | | 3:40p | | <NAME> | | | 1:40p | | <NAME> | | | 2:00p | | <NAME> | | | 2:20p | | <NAME> | | | 2:40p | | <NAME> | | | 3:00p | | <NAME> | | | 3:20p | | <NAME> | | | 3:40p | <a id="top"></a> ## Lecture 7 ## Today's Schedule - Announcements - Code Review *[30 minutes]* - [Go over the assigned readings](#readings) *[60 minutes]* - Code demo *[90 minutes]* **Learning Objectives** As a result of completing Lecture 7 of Code 201, students will: - Be able to translate an object literal into a constructor function, as measured by successful completion of the daily code assignment - Be able to use the ‘prototype’ property to extend the inheritable properties and methods of a constructor function, as measured by successful completion of the daily code assignment - Be able to dynamically build an HTML table with JavaScript and render it to the DOM, as measured by successful completion of the daily code assignment <a id="readings"></a> ## Readings **HTML Chapter 6: "Tables"** - p.131: Basic table structure - p.132: Table headings - p.133: Spanning columns & rows <file_sep>'use strict'; var allDogs = []; function Dog(name, color, breed, nickName) { this.name = name; this.color = color; this.breed = breed; this.nick = nickName; // Avoid defining instance methods inside the constructor // this.bark = function() { // console.log(this.name); // } allDogs.push(this) } Dog.prototype.bark = function() { console.log(this.name); } // new keyword does a few things... most importantly // 1. {} (creates a new object literal) // 2. assigns context to `this` // console.log(demi) => Dog { // name: 'Demi', // color: 'black and white', // breed: 'border collie', // nick: undefined, // } new Dog('Demi', 'black and white', 'border collie'); new Dog('Izzy', 'brown', 'pit bull', 'pork chop'); new Dog('Chief', 'black', 'bernese mtn dog', 'cheeze'); new Dog('Zina', 'brown', 'german shephard'); new Dog('Pepper', 'black, white, brown', 'cattle dog', 'pep'); // Create the document <file_sep>'use strict'; alert('Hello, user. My name is <NAME>, and this is my Program. If you want, you can answer these yes/no questions about me.'); alert('remember, yes/no or y/n works all the same.'); var score = 0; console.log('score at start of game should be 0.', score); var questionOne = prompt('Do I wear glasses?').toUpperCase(); if (questionOne === 'Y' || questionOne === 'YES' ) { alert('Correct!'); score++; } else if (questionOne === 'N' || questionOne === 'NO') { alert('Incorrect!'); } else { alert('Wrong input!'); } console.log('question one answer about glasses, correct answer is yes.', questionOne); console.log('current score: possible points at this stage is 1.', score); var questionTwo = prompt('Is my nickname Peter?'); if (questionTwo.toUpperCase() === 'Y' || questionTwo.toUpperCase() === 'YES') { alert('Incorrect!'); } else if (questionTwo.toUpperCase() === 'N' || questionTwo.toUpperCase() === 'NO') { alert('Correct!'); score++; } else { alert('Wrong input!'); } console.log('question two answer about nickname, correct answer is no.', questionTwo); console.log('current score: possible points at this stage is 2.', score); var questionThree = prompt('Do I go to the Seattle Campus for CodeFellows?'); if (questionThree.toUpperCase() === 'Y' || questionThree.toUpperCase() === 'YES') { alert('Correct!'); score++; } else if (questionThree.toUpperCase() === 'N' || questionThree.toUpperCase() === 'NO') { alert('Incorrect!'); } else { alert('Wrong input!'); } console.log('question three answer about school, correct answer is yes.', questionThree); console.log('current score: possible points at this stage is 3.', score); var questionFour = prompt('Do I like sweets/candy?'); if (questionFour.toUpperCase() === 'Y' || questionFour.toUpperCase() === 'YES') { alert('Incorrect!'); } else if (questionFour.toUpperCase() === 'N' || questionFour.toUpperCase() === 'NO') { alert('Correct!'); score++; } else { alert('Wrong input!'); } console.log('question four answer about food, correct answer is no.', questionFour); console.log('current score: possible points at this stage is 4.', score); var questionFive = prompt('Is Street Fighter 5 My favorite game?'); if (questionFive.toUpperCase() === 'Y' || questionFive.toUpperCase() === 'YES') { alert('Incorrect!'); } else if (questionFive.toUpperCase() === 'N' || questionFive.toUpperCase() === 'NO') { alert('Correct!'); score++; } else { alert('Wrong input!'); } console.log('question five answer about games, correct answer is no.', questionFive); console.log('current score: possible points at this stage is 5.', score); alert('your score was ' + score + ' out of 5.'); <file_sep>// Functions // 1. Set of steps; returns a value // 2. takes in data // 3. Like box; takes inputs; does a thing; outputs something var nums = [] var doubles = [] // Function expression // Try to avoid this pattern for now. // var getRandomNums = function() { // }; // Function definition function getRandomNums() { for(var i = 0; i < 1001; i++) { var randNum = Math.floor(Math.random() * 100) nums.push(randNum) } } getRandomNums() function duplicateNum(number) { var output = number * 2 return output } // for(var j = 0; j < nums.length; j++) { // var duplicate = duplicateNum(nums[j]) // doubles.push(duplicate) // } <file_sep>'use strict'; var questions = ['one?', 'two?', 'three?']; var answers = ['y', 'n', 'y']; for (var i = 0; i < questions.length; i++) { game(questions[i], answers[i]); } function game(question, answer) { // game('one?', 'y') // var userInput = prompt(question); // 'N' // userInput.toLowerCase(); // => 'n' (this will not save state) // userInput = userInput.toLowerCase(); // => 'n' (this will save state) // console.log(userInput); // => 'N' var userInput = prompt(question).toLowerCase(); // 'n' console.log(userInput); // => 'n' if (userInput === answer) { console.log('congrats!'); } else { console.error('danger will robinson'); } } <file_sep># Class 14: Advanced JS Topics and CSS Animations ## Daily Plan - Notes: - Anything top of mind? - Resubmits - reminders... - Catch up - What's new? - MLOs from other instructors? - Code Review - Local Storage workflow? - Review all the things - Admissions Visit - Discussion on Final Projects! - Some prior 201 projects - [Welcome to Seattle](https://peterbreen.github.io/welcome-to-seattle) - [Note Fellows](https://clee46.github.io/note-fellows) - [Slash Whooo?](http://wohlfea.github.io/cup-game) - [Algorithms](https://ztaylor2.github.io/algorithm-teacher) - [Casino War](https://http://casinowar.fun) - [BroNacho](http://bronacho.com) - [Banana Beat](https://skyfriends.github.io/Banana-Beat) - Lab Preview <a id="top"></a> ## Lecture 14 **Learning Objectives** As a result of completing Lecture 14 of Code 201, students will: - Be able to demonstrate understanding of JavaScript inheritance, as measured by a quiz administered in Canvas and the Code 301 entrance exam. - Be able to integrate CSS animations into a code project, measured through inclusion in this week’s project or the final project. <a id="readings"></a> ## Readings **CSS Transforms, Transitions, & Animations** - [Read this article on CSS Transforms](http://learn.shayhowe.com/advanced-html-css/css-transforms/) - [Read this article on CSS Transitions & Animations](http://learn.shayhowe.com/advanced-html-css/transitions-animations/) - [8 simple CSS3 transitions that will wow your users](http://www.webdesignerdepot.com/2014/05/8-simple-css3-transitions-that-will-wow-your-users) - [6 Buttons animated](http://codepen.io/retyui/pen/ByoaXV) - [CSS3 Animations: Keyframes](http://codepen.io/akshaychauhan/pen/oAfae) - [ANIMATE!](http://codepen.io/ryansobol/pen/NPZrNw) - [404](http://codepen.io/kieranfivestars/pen/MYdQxX) - [Pure CSS Bounce Animation](http://codepen.io/dp_lewis/pen/gCfBv) <a id="advanced"></a> ## Advanced JS Topics * [The State of JS](http://stateofjs.com) * [2018 Stack Overflow Developer Survey](https://insights.stackoverflow.com/survey/2018) * [How it Feels to Learn JS in 2016](https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.ygr5pmdqy) * [String methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) * [Array methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) * IIFEs * D.R.Y. * [Basics of "pass by value" vs. "pass by reference"](https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0) * Prototypal inheritance * Scopes & closures * Node * Suggested JS readings * [Eloquent JavaScript](http://eloquentjavascript.net/) * [JS, the Good Parts](http://shop.oreilly.com/product/9780596517748.do) * [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) * [Eric Elliott's articles on Medium](https://medium.com/@_ericelliott) * [this](http://rainsoft.io/gentle-explanation-of-this-in-javascript)
4daf8b791d9f2787b13190aa7365d9ec0a0d4785
[ "JavaScript", "Markdown" ]
16
JavaScript
codefellows/seattle-201d37
7e418cf60416ee422d2044f4fe2f63e32bce2b0a
aeae97c0f15dbb0ebfca10f4bb3b4e28fd4ba6ce
refs/heads/master
<repo_name>Katayounb/class-work<file_sep>/testinng2.py mylist = [1,2,3,4,5,6,7,8,9] newlist = mylist[4:8] print(newlist) for n in newlist: n *= 2 print(n) myevenlist = [] myoddlist = [] list1=mylist[0:5] print(list1) list2=mylist[5:9] print(list2) print(list1, '',list2) for n in mylist: if n % 2 == 0: myevenlist.append(n) else: myoddlist.append(n) print(myoddlist, myevenlist)
cffe1678e74fcfbeee6f61915829b1d81472fe8e
[ "Python" ]
1
Python
Katayounb/class-work
2dad71965edee692a6e6f32399d8bbc46758c4dd
4d1c78e11c85e098072d7dceb9c376a46c7c5cc6
refs/heads/main
<repo_name>altonelli/ARFirstStepsDup<file_sep>/Assets/Demo/Scripts/PlaceObjectController.cs using System.Collections; using System.Collections.Generic; using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; using UnityEngine.Experimental.XR; using UnityEngine; using System; public class PlaceObjectController : MonoBehaviour { // Start is called before the first frame update public GameObject firstObjectToPlace; public GameObject secondObjectToPlace; public String firstObjName; public String secondObjName; private ARPlaceObjectInteraction placementDelegate; private bool firstObjectIsPlaced; private bool secondObjectIsPlaced; void Start() { placementDelegate = FindObjectOfType<ARPlaceObjectInteraction>(); firstObjectIsPlaced = false; secondObjectIsPlaced = false; // firstObjName = "ConyInst"; // secondObjName = "CylinderInst"; } // Update is called once per frame void Update() { } public void PlaceObject() { if (!firstObjectIsPlaced) { placementDelegate.PlaceObject(firstObjectToPlace, firstObjName); firstObjectIsPlaced = true; } else if (!secondObjectIsPlaced) { placementDelegate.PlaceObject(secondObjectToPlace, secondObjName); secondObjectIsPlaced = true; } } } <file_sep>/Assets/Demo/Scripts/ButtonInteractionController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine; using UnityEngine.UIElements; using System; // using UnityEngine.UI; public class ButtonInteractionController : MonoBehaviour { // Start is called before the first frame update public GameObject controlPointObj; public String coneName; public String cylinderName; public String ParentObjectName; public String EmptyObjectName; public Button playButton; public GameObject rotatingObj; public int handlePointScale; private GameObject parentObj; private GameObject emptyObj; private BezierPathManager pathManager; void Start () { Debug.Log("Here is your button"); playButton = GameObject.FindGameObjectWithTag("PlayButton").GetComponent<Button>(); pathManager = FindObjectOfType<BezierPathManager>(); // Debug.Log(playButton); // Debug.Log(playButton.text); // Button btn = playButton; // playButton.clicked += TaskOnClick; // playButton.onClicked += TaskOnClick; } public void TaskOnClick() { Debug.Log ("You have clicked the button!"); GameObject cone = GameObject.Find(coneName); GameObject cylinder = GameObject.Find(cylinderName); Vector3 centroid = getCentroid(cone, cylinder); this.parentObj = Instantiate(rotatingObj, centroid, Quaternion.identity); this.parentObj.name = ParentObjectName; Debug.Log("Parent obj from ButtonInteraction"); Debug.Log(this.parentObj); Debug.Log(this.parentObj.name); this.emptyObj = Instantiate(new GameObject(), centroid, Quaternion.identity); this.emptyObj.name = EmptyObjectName; cone.transform.SetParent(parentObj.transform); cylinder.transform.SetParent(parentObj.transform); // parentObj.transform.Rotate(0.0f, 90.0f, 0.0f, Space.Self); // parentObj.st Animator coneAnimator = cone.GetComponent<Animator>(); coneAnimator.SetTrigger("StartBouncy"); Animator cylinderAnimator = cylinder.GetComponent<Animator>(); cylinderAnimator.SetTrigger("StartFloat"); this.parentObj.transform.SetParent(this.emptyObj.transform); var endPlacement = Camera.current.transform.position; var normalRelUp = getNormalRelativeToUp(centroid, endPlacement); var centToEndUnit = (endPlacement - centroid).normalized + centroid; var centroidControl = handlePointScale * (centToEndUnit + normalRelUp); var endToCentUnit = endPlacement + (centroid - endPlacement).normalized; var endPlacementControl = handlePointScale * (endToCentUnit + normalRelUp); // endPlacementControl += (1 * Vector3.back); Instantiate(controlPointObj, centroidControl, Quaternion.identity); Instantiate(controlPointObj, endPlacementControl, Quaternion.identity); pathManager.setPoints(new PointCluster(centroid,centroidControl), new PointCluster(endPlacement, endPlacementControl)); pathManager.retrieveParentObj(EmptyObjectName); pathManager.startRunning(); } private Vector3 getNormalRelativeToUp(Vector3 start, Vector3 end) { return Vector3.Cross(end - start, Vector3.up).normalized; } private Vector3 getCentroid(GameObject obj1, GameObject obj2) { var centroid = Vector3.zero; centroid += obj1.transform.position; centroid += obj2.transform.position; centroid /= 2; return centroid; } public void StaticButtonPressed() { Debug.Log("Printing from extra function"); Debug.Log("Object Names: " + coneName + " " + cylinderName); } public GameObject getParentObj() { return this.parentObj; } // Update is called once per frame void Update() { } } <file_sep>/Assets/Demo/Scripts/BezierPathManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class BezierPathManager : MonoBehaviour { public float TimeToRun; private GameObject obj; private PointCluster startPoint; private PointCluster endPoint; private Vector3 prevPosition; // private Vector3 wayPoint; private delegate Vector3 GetPointAtTimeFunction(float time); private GetPointAtTimeFunction getPointAtTime; private bool isRunning; private float startTime; private float currTime; private ButtonInteractionController playButtonController; // Start is called before the first frame update void Start() { isRunning = false; playButtonController = FindObjectOfType<ButtonInteractionController>(); createPathFunction(); } public void setPoints(PointCluster start, PointCluster end) { startPoint = start; endPoint = end; } public void retrieveParentObj(String name) { obj = GameObject.Find(name); Debug.Log("Printing from Path Manager"); Debug.Log(obj); prevPosition = startPoint.wayPoint; } void createPathFunction() { // F(t) = (1−t)^3P1 + 3(1−t)^2tP2 +3(1−t)t^2P3 + t^3P4 getPointAtTime = delegate(float time) { Debug.Log(time); var oneMinus = 1.0f - time; return Mathf.Pow(oneMinus, 3.0f) * startPoint.wayPoint + Mathf.Pow(oneMinus, 2.0f) * time * startPoint.controlPoint + oneMinus * Mathf.Pow(time, 2.0f) * endPoint.controlPoint + Mathf.Pow(time, 2.0f) * time * endPoint.wayPoint; }; } public void startRunning() { startTime = Time.time; Debug.Log(startTime); isRunning = true; } // Update is called once per frame void Update() { currTime = Time.time; // Debug.Log(isRunning); if (isRunning && currTime - startTime > 1.0f) { Debug.Log("Getting Time"); currTime = Time.time; var timeAsPercent = (currTime - startTime - 1.0f) / TimeToRun; Debug.Log("Getting position"); var currLocation = getPointAtTime(timeAsPercent); Debug.Log("Setting Position"); var step = currLocation - prevPosition; obj.transform.position += step; prevPosition = currLocation; if (timeAsPercent >= 1.0f) { isRunning = false; } } } } public class PointCluster { public Vector3 wayPoint; public Vector3 controlPoint; public PointCluster(Vector3 wayPoint, Vector3 controlPoint) { this.wayPoint = wayPoint; this.controlPoint = controlPoint; } } <file_sep>/Assets/Editor/ButtonInteractionEditor.cs // using UnityEditor; // [CustomEditor(typeof(ButtonInteractionController))] // public class ButtonInteractionControllerEditor : Editor // { // public override void OnInspectorGUI() // { // // ButtonInteraction targetInteraction = (ButtonInteraction)target; // // targetInteraction.playButton = EditorGUILayout.TextField("Play Button", targetInteraction.playButton); // // // Show default inspector property editor // // DrawDefaultInspector(); // base.OnInspectorGUI(); // } // }
106292ed061a733015f6ea5d7a6ba6239743cfad
[ "C#" ]
4
C#
altonelli/ARFirstStepsDup
ba8e7aa5c57839c83516297c248e586e55de0e85
2b82c4d2d0f0d2f921bbdd82c343bb74940cde84
refs/heads/master
<file_sep># Transarietmator ------ ([Click Here for Indonesian Readme](https://github.com/Lidilidian/Transarietmator/README_ID.md)) Python checker for Untranslated Gettext (.po) file and recommendation for the unstranslated `msgstr` tool. this program using Python v.2.7 and [Microsoft Translator Text API][1] as backend translation. when You run this program, the program will run automatically looking for untranslated `msgstr` in the po file and provide recommendation's to You on the results of translation then You can use the result for fixing your untranslated po file whether it's possible to use the weblate and pootle service or even by manual translating. ## How use: - $ git clone https://github.com/Lidilidian/Transarietmator.git - $ cd Transariemator - $ python2.7 transariemator.py - Insert Source Language : en // Insert the language code of Your source po file. - Insert Your translation language : id // insert the language you want to be your translate recommendation - [Click here][6] for check all supported langguge code. note : this program default is use `administration.po` from [Bauble Project][2] , You should change it in `transarietmator.py` with your own .po file >### Library Requierement's : - [x] [lxml 2.2.8][3] for python2.7 - [x] [msti][4] (include in this repo) - [x] [polib][5] for python2.7 (also include in this repo) - [x] json - [x] urllib and urlllib2 >### a list of which should be further developed : - [x] Translate suggestion's - [ ] Auto detect source language - [ ] Create argparse for simplify the option - [ ] Save output to new .po file - [ ] Improve program interface [1]: https://www.microsoft.com/en-us/translator/translatorapi.aspx "Microsoft Translator Text API" [2]: https://github.com/Bauble "Bauble Project" [3]: https://pypi.python.org/pypi/lxml/2.2.8 "lxml v.2.2.8 library for python2.7" [4]: https://github.com/Lidilidian/Transarietmator/blob/master/msti.py "Microsoft Translation API connector" [5]: https://github.com/Lidilidian/Transarietmator/blob/master/polib.py "polib library python2.7" [6]: https://msdn.microsoft.com/en-us/library/hh456380.aspx "Language Code" >### License This program using the MIT License - https://github.com/Lidilidian/Transarietmator/blob/master/LICENSE >### Contirbuting and suggestions if you would like to contribute to this project, any help would be very-very helpful even if it's just a warning for a typo, and please don't be shy to contact me at ([<EMAIL>](mailto:<EMAIL>)). >### Thanks to - <NAME> and My Family. - ([@jayvdb](https://github.com/jayvdb) - Mentor of Besutkode who always give support - ([@edawine](https://github.com/edawine)) & ([@chocochino](https://github.com/chocochino))- which give Me suggestion. - Every participant of Besutkode and of course all my Friend's in University of Muhammadiyah Jakarta <file_sep>``` arietmatika@linux-2t91:~/Transarietmator> python transariemator.py Insert Your source language: en Insert Your translation language: id 1 Untranslated words found UNTRANSLATED : Administration RECOMMENDATION : Administrasi 2 Untranslated words found UNTRANSLATED : If you are using a real DBMS to hold your botanic data, then you need do something about database administration. While database adnimistration is far beyond the scope of this document, we make our users aware of it. RECOMMENDATION : Jika Anda menggunakan DBMS nyata untuk menyimpan data botanic Anda, maka Anda perlu melakukan sesuatu tentang administrasi database. Sementara database adnimistration jauh melampaui lingkup dokumen ini, kami membuat pengguna kami menyadari hal itu. 3 Untranslated words found UNTRANSLATED : SQLite RECOMMENDATION : SQLite 4 Untranslated words found UNTRANSLATED : SQLite is not what one would consider a real DBMS: each SQLite database is just in one file. Make safety copies and you will be fine. If you don't know where to look for your database files, consider that, per default, bauble puts its data in the ``~/.bauble/`` directory (in Windows it is somewhere in your ``AppData`` directory). RECOMMENDATION : SQLite bukanlah apa yang akan mempertimbangkan sebuah DBMS yang nyata: setiap database SQLite adalah hanya dalam satu file. Membuat salinan keamanan dan Anda akan baik-baik saja. Jika Anda tidak tahu di mana untuk mencari file database Anda, pertimbangkan bahwa, per standar, perhiasan menempatkan data dalam direktori '' ~/.bauble/'' (pada Windows itu adalah suatu tempat di direktori '' AppData''). 5 Untranslated words found UNTRANSLATED : MySQL RECOMMENDATION : MySQL 6 Untranslated words found UNTRANSLATED : Please refer to the official documentation. RECOMMENDATION : Silakan merujuk ke dokumentasi resmi. 7 Untranslated words found UNTRANSLATED : PostgreSQL RECOMMENDATION : PostgreSQL 8 Untranslated words found UNTRANSLATED : Please refer to the official documentation. A very thorough discussion of your backup options starts at `chapter_24`_. RECOMMENDATION : Silakan merujuk ke dokumentasi resmi. Diskusi yang sangat teliti mengenai pilihan cadangan dimulai pada _ 'chapter_24'. ``` <file_sep>#!/usr/bin/python import sys import os.path import polib import msti from lxml import etree token = msti.get_access_token('<PASSWORD>', '<KEY> def get_text_from_msmt_xml(xml): """Parse the xml string returned by the MS machine translation API, and return just the text""" text = [] doc = etree.fromstring(xml) for elem in doc.xpath('/foo:string', namespaces={'foo': 'http://schemas.microsoft.com/2003/10/Serialization/'}): if elem.text: elem_text = ' '.join(elem.text.split()) if len(elem_text) > 0: text.append(elem_text) return ' '.join(text) source_language = raw_input("Insert Your source language: ") translate_language = raw_input("Insert Your translation language: ") po = polib.pofile('administration.po') #po_valid_entries = [e for e in po if not e.obsolete] // if you want to make entries obsolete UNTRANSLATED = 0 for untr in po.untranslated_entries(): UNTRANSLATED += 1 print("\n") print("{} Untranslated words found".format(UNTRANSLATED)) print("UNTRANSLATED : {}".format(untr.msgid)) translation_process = msti.translate(token, untr.msgid, translate_language, source_language) print("RECOMMENDATION : {}".format(get_text_from_msmt_xml(translation_process))) print("\n") if UNTRANSLATED == 0: print("Process Complete!")
6e2b3d817023d8b6784eea17c71163160ab13d6e
[ "Markdown", "Python" ]
3
Markdown
jayvdb/Transarietmator
3dbaddf903d43e19624b0e28417a7b4244515c0b
774dc133923625adcad49e6d85c64db3ca2ce0bd
refs/heads/master
<repo_name>attitute/Promise<file_sep>/dist/bundle.js 'use strict'; // 1.每个promise 都有三个状态 pennding等待态 resolve 标识变成成功态 fulfilled reject 标识变成失败态 REJECTED // 2.每个promise 需要有一个then方法 , 传入两个参数 一个是成功的回调另一个是失败的回调 // 3.new Promise会立即执行 // 4.一旦成功就不能失败 一旦失败不能成功 // 5.当promise抛出异常后 也会走失败态 var isObject = function (target) { return typeof target === 'object' && target !== null; }; function resolvePromise(promise2, x, resolve, reject) { if (x == promise2) { // 如果x和promise2是一个状态 那就返回类型错误 return reject(new TypeError('出错了')); } if (isObject(x) || typeof x === 'function') { // x是一个对象或者是一个函数 var called_1 = false; // 保证只返回一个状态 try { var then = x.then; // 获取函数或对象的then方法 if (typeof then == 'function') { // 判断是不是一个promise函数 规范认为有then方法就是promise then.call(x, function (y) { if (called_1) return; called_1 = true; resolvePromise(promise2, y, resolve, reject); // 再次判断是不是promise }, function (r) { if (called_1) return; called_1 = true; reject(r); }); } else { // 不是函数直接返回即可 resolve(x); } } catch (e) { if (called_1) return; called_1 = true; reject(e); // 走失败逻辑 } } else { // 如果不是那就是一个普通值 resolve(x); } } var Promise = /** @class */ (function () { function Promise(executor) { var _this = this; this.status = "PENDING" /* pending */; this.value = undefined; this.reason = undefined; this.onResloveCallbacks = []; this.onRejectCallbacks = []; var resolve = function (value) { if (value instanceof Promise) { return value.then(resolve, reject); // 循环调用resolve 防止返回还是promise } if (_this.status == "PENDING" /* pending */) { // 只有pengding状态才能修改状态 _this.status = "FULFILLED" /* fulfilled */; _this.value = value; // 订阅未完成的成功回调 _this.onResloveCallbacks.forEach(function (fn) { return fn(); }); } }; var reject = function (reason) { if (_this.status == "PENDING" /* pending */) { _this.status = "REJECTED" /* rejected */; _this.reason = reason; // 订阅未完成的失败回调 _this.onRejectCallbacks.forEach(function (fn) { return fn(); }); } }; try { executor(resolve, reject); // 初始化执行函数 } catch (e) { reject(e); } } Promise.resolve = function (value) { return new Promise(function (resolve, reject) { resolve(value); }); }; Promise.reject = function (err) { return new Promise(function (resolve, reject) { reject(err); }); }; Promise.prototype.then = function (onFulfilled, onRejected) { var _this = this; // 判断是不是函数 不是则重置返回一个函数 使不传参数的then也有返回值 .then().then(data=>data) onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : function (x) { return x; }; onRejected = typeof onRejected == 'function' ? onRejected : function (err) { throw err; }; // 返回一个promise 支持链式调用 var promise2 = new Promise(function (resolve, reject) { if (_this.status == "PENDING" /* pending */) { // 如果resolve 或者reject是异步的 那么就是pending状态 // 发布所有的成功或者失败回调 _this.onResloveCallbacks.push(function () { setTimeout(function () { try { var x = onFulfilled(_this.value); // 传入promise2 主要是想拿到resolve reject方法 // promise2.resolve = resolve // promise2.reject = reject // 或者直接传入方法 resolvePromise(promise2, x, resolve, reject); // 返回参数可能是一个promise 对参数进行判断 } catch (error) { reject(error); } }, 0); }); _this.onRejectCallbacks.push(function () { setTimeout(function () { try { var x = onRejected(_this.reason); resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); }); } if (_this.status == "FULFILLED" /* fulfilled */) { // 状态时fulfilled时 setTimeout(function () { try { var x = onFulfilled(_this.value); // 接收成功处理函数返回值 resolvePromise(promise2, x, resolve, reject); } catch (error) { // 只要运行出错就reject reject(error); } }, 0); } if (_this.status == "REJECTED" /* rejected */) { setTimeout(function () { try { var x = onRejected(_this.reason); // 执行失败处理函数 接收其返回值 resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }, 0); } }); return promise2; }; Promise.prototype.catch = function (errFn) { this.then(null, errFn); }; return Promise; }()); // 延迟函数 不写这个 promise测试通不过 // npm i promises-aplus-tests -g promise测试 // promises-aplus-tests [js文件名] 即可验证你的Promise的规范。 Promise.deferred = function () { var df = {}; df.promise = new Promise(function (resolve, reject) { df.resolve = resolve; df.reject = reject; }); return df; }; var isPromise = function (target) { if (isObject(target) || typeof target == 'function') { if (typeof target.then == 'function') { return true; } } return false; }; // 执行数组中所有的promise 并且将结果按照顺序存入数组 Promise.all = function (values) { return new Promise(function (resolve, reject) { var arr = []; var times = 0; function collectResult(value, key) { arr[key] = value; if (++times == values.length) { resolve(arr); } } values.forEach(function (value, key) { if (isPromise(value)) { value.then(function (y) { collectResult(y, key); }, reject); } else { collectResult(value, key); } }); }); }; // 不管什么情况都会触发 // finally规则 resolve只返回自己的Promise // resolve情况 finally中resolve返回不修改最初值 // reject 情况 finally中reject返回会修改最初值 如果返回resolve则不影响 Promise.prototype.finally = function (callback) { return this.then(function (data) { return Promise.resolve(callback()).then(function () { return data; }); }, function (err) { return Promise.resolve(callback()).then(function () { throw err; }); }); }; // promise.race() 返回第一个结果 跟all差不多 Promise.race = function (values) { return new Promise(function (resolve, reject) { function collectResult(value) { resolve(value); } values.forEach(function (v) { if (v && isPromise(v)) { v.then(function (data) { collectResult(v); }, reject); } else { collectResult(v); } }); }); }; // promise.allSettled 无论成功失败执行完毕 按顺序返回所有结果(就是all方法一样) Promise.allSettled = function (values) { return new Promise(function (resolve, reject) { var arr = [], times = 0; function collectResult(value, key, status) { arr[key] = status == 'fulfilled' ? { value: value, status: status } : { reason: value, status: status }; if (++times == values.length) { resolve(arr); } } values.forEach(function (v, key) { if (v && isPromise(v)) { v.then(function (data) { collectResult(data, key, 'fulfilled'); }, function (reason) { collectResult(reason, key, 'rejected'); }); } else { collectResult(v, key, 'noStatus'); } }); }); }; module.exports = Promise; <file_sep>/src/js高级函数/观察者模式.ts // 首先了解发布订阅与 观察者模式的区别 // 1. 发布订阅 是通过中间的第三方arr变量 使发布订阅产生关系 // 2. 观察模式 被观察者自身就能够通知观察者 (内部还是发布订阅) class Subject { // 被观察者 say:string = '我给你画画' observers!:Observe[] // 非空断言 constructor(public name:string){} attach(o:Observe){ this.observers.push(o) } setSay(newsay:string){ this.say = newsay this.observers.forEach(v=>v.update(this)) } } class Observe { // 观察者 constructor(public name:string){ } update(jack:Subject){ console.log(jack.name+ '对' +this.name + '说:' + jack.say) } } let jack = new Subject('jack') let rose = new Observe('rose') jack.attach(rose) jack.setSay('You jump! I jump!')<file_sep>/src/js高级函数/generator.js // 浏览器最早解决 异步方式 回调=>promise => generator => asyn + await // generator在 开发中基本不用 react saga中有使用 // 使用generator 函数内部蛇形 第一步到yield 第二步 赋值a 再yield2 第三步赋值b 再return false function * read() { let a = yield 1 console.log('a',a) let b = yield 2 return false } const t = read() let {value} = t.next() console.log(t.next(value)) // 传入value就是给上一个a赋值 { value: 2, done: false } console.log(t.next(value)) // 传入value就是给上一个b赋值 后面没有内容 done为true{ value: false, done: true }<file_sep>/src/js高级函数/解决并发得高级函数.ts // promise 最重要就是解决了 1.回调地狱 2.异步并发 const fs = require('fs') interface Iperson { a:string, b:number } function after(times:number, callback:(obj:Iperson)=>void){ // 调用到规定的次数时 就触发callback函数 let obj = {} as any; return function(key:string, val:number|string) { obj[key] = val // 每次触发函数 就把触发信息存起来 --times == 0 && callback(obj) } } let fn = after(2,(obj)=>{ console.log(obj) }) fs.readFile('./a.txt', 'utf8', (err:string,data:string)=>{ fn('a',data) }) fs.readFile('./b.txt', 'utf8', (err:string,data:number)=>{ fn('b',data) }) export {} <file_sep>/src/js高级函数/generator源码.js "use strict"; // 该还原不考虑编译层 class Context { constructor() { this.next = 0; this.done = false; } stop() { this.done = true; } abrupt(v1,v2){ this.done = true return v2 } } let regeneratorRuntime = { mark(genFunc) { return genFunc; // 最外层generator函数 }, wrap(innerFn, outerFn) { let it = {}; let context = new Context(); it.next = function (v) { context.send = v let value = innerFn(context); // 函数返回值就是yiled后面的值 return { value, done:context.done, }; }; return it; }, }; var _marked = /*#__PURE__*/ regeneratorRuntime.mark(read); // read就是刚刚写的generator function read() { var a, b; return regeneratorRuntime.wrap(function read$(_context) { while (1) { switch ((_context.prev = _context.next)) { case 0: _context.next = 2; return 1; case 2: a = _context.sent; console.log("a", a); _context.next = 6; return 2; case 6: b = _context.sent; return _context.abrupt("return", false); case 8: case "end": return _context.stop(); } } }, _marked); } var t = read(); var _t$next = t.next(), value = _t$next.value; console.log(t.next(value)); console.log(t.next(value)); <file_sep>/src/index.ts // 1.每个promise 都有三个状态 pennding等待态 resolve 标识变成成功态 fulfilled reject 标识变成失败态 REJECTED // 2.每个promise 需要有一个then方法 , 传入两个参数 一个是成功的回调另一个是失败的回调 // 3.new Promise会立即执行 // 4.一旦成功就不能失败 一旦失败不能成功 // 5.当promise抛出异常后 也会走失败态 import { rejects } from "assert" import { promises } from "fs" import { resolve } from "path" //Program 是支持链式调用的 /** * 无论是成功还是失败 都可以返回结果(1.出错了走错误2.返回一个普通值(非promise),就会作为下一次then的成功结果) * 如果是返回promise的情况(会采用返回的promise的状态) 用promise解析后的结果传递给下一个 * */ const enum STATUS { pending = 'PENDING', fulfilled = 'FULFILLED', rejected = 'REJECTED' } const isObject = (target:unknown):target is object => typeof target === 'object' && target !== null function resolvePromise(promise2:Promise,x:any,resolve:(x:unknown)=>void,reject:Function) { if(x == promise2){ // 如果x和promise2是一个状态 那就返回类型错误 return reject(new TypeError('出错了')) } if(isObject(x) || typeof x === 'function') { // x是一个对象或者是一个函数 let called = false // 保证只返回一个状态 try{ let then = x.then // 获取函数或对象的then方法 if(typeof then == 'function') { // 判断是不是一个promise函数 规范认为有then方法就是promise then.call(x,(y: unknown)=>{ if(called) return called = true resolvePromise(promise2, y, resolve, reject) // 再次判断是不是promise }, (r:unknown) =>{ if(called)return called = true reject(r) }) } else { // 不是函数直接返回即可 resolve(x) } } catch (e) { if (called) return called = true reject(e) // 走失败逻辑 } }else { // 如果不是那就是一个普通值 resolve(x) } } class Promise { status: STATUS value:any reason:any onResloveCallbacks: Array<Function> onRejectCallbacks: Function[] static deferred:any static all:any static allSettled?: (values: any[]) => Promise finally!: (callback: any) => Promise static race: (values: any) => Promise constructor (executor:(resolve:(value:unknown)=>void,reject:(reason:any)=>void)=>void){ this.status = STATUS.pending this.value = undefined this.reason = undefined this.onResloveCallbacks = [] this.onRejectCallbacks = [] const resolve = (value?:any)=>{ if (value instanceof Promise){ return value.then(resolve,reject) // 循环调用resolve 防止返回还是promise } if(this.status == STATUS.pending){ // 只有pengding状态才能修改状态 this.status = STATUS.fulfilled this.value = value // 订阅未完成的成功回调 this.onResloveCallbacks.forEach(fn=>fn()) } } const reject = (reason?: any)=>{ if (this.status == STATUS.pending){ this.status = STATUS.rejected this.reason = reason // 订阅未完成的失败回调 this.onRejectCallbacks.forEach(fn=>fn()) } } try { executor(resolve,reject) // 初始化执行函数 }catch(e){ reject(e) } } static resolve (value:unknown){ return new Promise((resolve,reject)=>{ resolve(value) }) } static reject (err:unknown){ return new Promise((resolve,reject)=>{ reject(err) }) } then(onFulfilled?:any, onRejected?:any){ // 判断是不是函数 不是则重置返回一个函数 使不传参数的then也有返回值 .then().then(data=>data) onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : (x:unknown) => x onRejected = typeof onRejected == 'function' ? onRejected : (err:unknown) => {throw err} // 返回一个promise 支持链式调用 let promise2 = new Promise((resolve,reject)=>{ if(this.status == STATUS.pending){ // 如果resolve 或者reject是异步的 那么就是pending状态 // 发布所有的成功或者失败回调 this.onResloveCallbacks.push(()=>{ setTimeout(() => { // 异步的好处在于能够获取到promise2 try { let x = onFulfilled(this.value) // 传入promise2 主要是想拿到resolve reject方法 // promise2.resolve = resolve // promise2.reject = reject // 或者直接传入方法 resolvePromise(promise2,x,resolve,reject) // 返回参数可能是一个promise 对参数进行判断 } catch (error) { reject(error) } }, 0); }) this.onRejectCallbacks.push(()=>{ setTimeout(() => { try { let x = onRejected(this.reason) resolvePromise(promise2,x,resolve,reject) } catch (error) { reject(error) } }, 0); }) } if (this.status == STATUS.fulfilled){ // 状态时fulfilled时 setTimeout(() => { try { let x = onFulfilled(this.value) // 接收成功处理函数返回值 resolvePromise(promise2,x,resolve,reject) } catch (error) { // 只要运行出错就reject reject(error) } }, 0); } if (this.status == STATUS.rejected){ setTimeout(() => { try { let x = onRejected(this.reason) // 执行失败处理函数 接收其返回值 resolvePromise(promise2,x,resolve,reject) } catch (error) { reject(error) } }, 0); } }) return promise2 } catch(errFn: Function){ // 只有错误返回的then方法 this.then(null, errFn) } } // 延迟函数 不写这个 promise测试通不过 // npm i promises-aplus-tests -g promise测试 // promises-aplus-tests [js文件名] 即可验证你的Promise的规范。 Promise.deferred = function () { let df = {} as any df.promise = new Promise((resolve, reject) => { df.resolve = resolve df.reject = reject }) return df } const isPromise = function(target:any){ if(isObject(target) || typeof target == 'function'){ if(typeof target.then == 'function'){ return true } } return false } // 执行数组中所有的promise 并且将结果按照顺序存入数组 Promise.all = function(values:any[]){ return new Promise((resolve,reject)=>{ let arr = [] as any[] let times:number = 0 function collectResult(value:any,key:number){ arr[key] = value if (++times == values.length){ resolve(arr) } } values.forEach((value:any,key:number)=>{ if(isPromise(value)){ value.then((y:unknown)=>{ collectResult(y, key) },reject) }else { collectResult(value,key) } }) }) } // 不管什么情况都会触发 // finally规则 resolve只返回自己的Promise // resolve情况 finally中resolve返回不修改最初值 // reject 情况 finally中reject返回会修改最初值 如果返回resolve则不影响 Promise.prototype.finally = function(callback){ return this.then((data: any)=>{ return Promise.resolve(callback()).then(()=>data) },(err: any)=>{ return Promise.resolve(callback()).then(()=>{throw err}) }) } // promise.race() 返回第一个结果 跟all差不多 Promise.race = function(values){ return new Promise((resolve,reject)=>{ function collectResult(value:unknown){ resolve(value) } values.forEach((v:any)=>{ if(v && isPromise(v)) { v.then((data:unknown)=>{ collectResult(v) },reject) }else { collectResult(v) } }) }) } // promise.allSettled 无论成功失败执行完毕 按顺序返回所有结果(就是all方法一样) Promise.allSettled = function(values:any[]){ return new Promise((resolve,reject)=>{ let arr = [] as any[],times = 0; function collectResult(value: any, key: number, status: string){ arr[key] = status == 'fulfilled' ? {value,status} : {reason:value,status} if (++times == values.length){ resolve(arr) } } values.forEach((v:any,key:number)=>{ if(v && isPromise(v)){ v.then((data: any)=>{ collectResult(data,key,'fulfilled') },(reason: any)=>{ collectResult(reason,key,'rejected') }) }else { collectResult(v,key,'noStatus') } }) }) } export default Promise<file_sep>/src/js高级函数/函数柯里化.ts // 柯里化函数 // 柯里化的功能就是让函数功能更加具体(保留参数) // 反柯里化 就是让函数范围更大 // 1.typeof(判断不了object null 数组对象) 2.constructor(由谁构造出来的) 3.intanceof(谁是谁的实例) 4.Object.prototype.toString.call(判断出具体类型 判断不来谁是谁实例 [obejct 类型]) // 实列: 判断一个变量得类型 function isType(val:unknown,type:string) { return Object.prototype.toString.call(val) == `[object ${type}]` } let isString = isType('sss','string') let isNumber = isType('sss','number') // 柯里化之后 type ReturnFn = (val:unknown) => boolean // let utils:Record<'isString' | 'isNumber' | 'isBoolean',ReturnFn> = {} as any; let utils:any = {} function isTypeLevel(typing:string){ // 高阶函数可以用于保存参数 return function (val:unknown) { return Object.prototype.toString.call(val) == `[object ${typing}]` } } ['String','Number','Boolean'].forEach(type=>{ utils['is'+type] = isTypeLevel(type); // 闭包 }) console.log(utils.isString('123')); console.log(utils.isNumber(123)); // 实例: 实现一个通用的柯里化函数,可以自动得将一个函数转换成多次传递参数 const curring = (fn: Function) => { const exec = (sumArgs: any[] = []) => { // 判断参数大于或等于当前函数所需参数 条件成立函数执行 条件不成立返回一个函数 函数调用时当前参数(sumArgs)与传入参数(args)传给exec函数 return sumArgs.length >= fn.length ? fn(...sumArgs) : (...args: any[]) => exec([...sumArgs, ...args]) } return exec() // 收集每次执行时传入得参数 第一次默认为空 } curring(isType)('ss')('sting') export {} <file_sep>/src/js高级函数/发布订阅模式.ts // 发布订阅模式 把需要做的事情 放到一个数组中 等事情发生了让订阅的事情依次执行 const fs = require('fs') interface events { arr:Array<Function>, on:(fn:Function)=>void, // on(fn:Function):void, // emit: ()=>void emit():void } let events:events = { arr: [], on(fn){ this.arr.push(fn) }, emit () { this.arr.forEach(fn=>fn()) } } interface Person { a: string, b: number } let person = {} as Person events.on(()=>{ if(Object.keys(person).length == 2) { console.log(person) } }) events.on(()=>{ console.log('一次') }) fs.readFile('./a.txt','utf8', (err:unknown, data:string)=>{ person.a = data events.emit() }) fs.readFile('./b.txt','utf8', (err:unknown, data:number)=>{ person.b = data events.emit() }) <file_sep>/src/js高级函数/反柯里化.js // 反柯里化 让范围变大 柯里化就是范围变小 // let toString = Object.prototype.toString // toString 原型方法 // console.log(toString.call(123)) // toSting this指向变了 // Function.prototype.unCurrying = function () { // return (...args) => { // // Function.prototype.call好处在于 调用的一定是原型的call方法 而不是用户定义的call // // apply改了this指向 call方法中this就指向了toString 所以就是toString.call 并且传入了参数 // return Function.prototype.call.apply(this, args) // } // } // let toString = Object.prototype.toString.unCurrying() // 私有的toString方法 // console.log(toString(123)) <file_sep>/src/index1.ts import { type } from "os" const enum STATUS { pending = 'PENDING', fulfilled = 'FULFILLED', reject = 'REJECT', } const isObject = (target: unknown) => typeof target == 'object' && target != null function resolvePromise(promise: Promise, x: any, resolve: any, reject: any) { if (x == promise) reject(new TypeError('类型错误')) if (isObject(x) || typeof x == 'function') { let called = false try { let then = x.then if (typeof then == 'function') { then.call( x, (y: any) => { if (called) return called = true resolvePromise(promise, y, resolve, reject) }, (r: any) => { if (called) return called = true reject(r) } ) } else { if (called) return called = true resolve(x) } } catch (error) { if (called) return called = true reject(error) } } else { resolve(x) } } class Promise { status: STATUS value?: any reason?: any onResolveCallbacks: Array<Function> onRejectCallbacks: Array<Function> static deferred?: any static all?: any constructor(exector: (resolve: (value: unknown)=>void, reject: (reason:unknown)=>void) => void) { this.status = STATUS.pending this.value = undefined this.reason = undefined this.onResolveCallbacks = [] this.onRejectCallbacks = [] const resolve = (value: unknown) => { if (this.status == STATUS.pending) { this.status = STATUS.fulfilled this.value = value this.onResolveCallbacks.forEach((fn) => fn()) } } const reject = (reason: unknown) => { if (this.status == STATUS.pending) { this.status = STATUS.reject this.reason = reason this.onRejectCallbacks.forEach((fn) => fn()) } } try { exector(resolve, reject) } catch (error) { reject(error) } } then(onFulfilled?: any, onRejected?: any) { onFulfilled = typeof onFulfilled == 'function' ? onFulfilled : (x: unknown) => x onRejected = typeof onRejected == 'function' ? onRejected : (err: unknown) => { throw err } let promise2 = new Promise((resolve: any, reject: any) => { if (this.status == STATUS.pending) { this.onResolveCallbacks.push(() => { setTimeout(() => { try { let x = onFulfilled(this.value) resolvePromise(promise2, x, resolve, reject) } catch (error) { reject(error) } }, 0) }) this.onRejectCallbacks.push(() => { setTimeout(() => { try { let x = onRejected(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (error) { reject(error) } }, 0) }) } if (this.status == STATUS.fulfilled) { setTimeout(() => { try { let x = onFulfilled(this.value) resolvePromise(promise2, x, resolve, reject) } catch (error) { reject(error) } }, 0) } if (this.status == STATUS.reject) { setTimeout(() => { try { let x = onRejected(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (error) { reject(error) } }, 0) } }) return promise2 } catch(errFn: () => void) { return this.then(null, errFn) } } Promise.deferred = function () { let df = {} as any df.promise = new Promise((resolve, reject) => { df.resolve = resolve df.reject = reject }) return df } const isPromise = function(target:any){ if(isObject(target) || typeof target == 'function'){ if(typeof target.then == 'function'){ return true } } return false } Promise.all = function(values:any[]){ return new Promise((resolve,reject)=>{ let arr = [] as any[] let times:number = 0 function collectResult(value:any,key:number){ arr[key] = value if (++times == values.length){ resolve(arr) } } values.forEach((value:any,key:number)=>{ if(isPromise(value)){ value.then((y:unknown)=>{ collectResult(y, key) },reject) }else { collectResult(value,key) } }) }) } export default Promise <file_sep>/.md npm install typescript rollup @rollup/plugin-node-resolve rollup-plugin-typescript2 -D npm install ts-node -g vs 插件 run code npm i promises-aplus-tests -g // promise测试 promises-aplus-tests [js文件名] 即可验证你的Promise的规范。 <file_sep>/src/js高级函数/高阶函数概念.ts // promise 都是基于回调模式的 // 高阶函数 如果你的函数参数是一个函数或者一个函数返回一个函数就是高阶函数 // 基于代码做扩展 给core方法扩展一个before方法 type Callback = ()=> void type ReturnFn = (...args:any[]) => void declare global { interface Function{ before(fn:Callback):ReturnFn } } Function.prototype.before = function(fn){ return (...args) =>{ fn() this(...args) // 调用原有的core方法 } } function core(...args: any[]){ console.log('core', ...args) } let fn = core.before(()=>{ console.log('before core...') }) fn() export {}
7d9a73c91ebdbe2ded559f4983502129c2492730
[ "JavaScript", "TypeScript", "Markdown" ]
12
JavaScript
attitute/Promise
b147c58d74d8640cb9e03308ac7a460299f63252
4e13f4b901a67f86fc04fdea9b234c12bcb01d45
refs/heads/master
<repo_name>Avadh09/CMPE280<file_sep>/src/App.js import React, { Component} from "react"; import {hot} from "react-hot-loader"; import "./App.css"; import Search from './components/searchBar' class App extends Component{ render(){ return( <div className="App"> <h1> Logo </h1> <p>CMPE 280</p> <Search/> </div> ); } } export default hot(module)(App);
b1ba9da02a42e05a9eb07fad12743772f7e93023
[ "JavaScript" ]
1
JavaScript
Avadh09/CMPE280
6695de45b7d8bd21dc0ac699d16495f9b1573718
b2db24927e6f9a85d26bf0fa3bb3dc705b5f87f4
refs/heads/master
<repo_name>anavalo/Gmail_unsubscribe_links<file_sep>/get_mails.py from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import email import base64 from apiclient import errors # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def main(): def getMimeMessage(service, user_id, msg_id): try: message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute() msg_bytes = base64.urlsafe_b64decode(message['raw'].encode('ASCII')) mime_msg = email.message_from_bytes(msg_bytes) messageMainType = mime_msg.get_content_maintype() if messageMainType == 'multipart': for part in mime_msg.get_payload(): if part.get_content_maintype() == 'text': return part.get_payload() return "" elif messageMainType == 'text': return mime_msg.get_payload() except errors.HttpError as error: print('An error occurred: %s' % error) creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('gmail', 'v1', credentials=creds) msg_list_params = { 'userId': 'me' } # Call the Gmail API results = service.users().messages() messages_request = results.list(**msg_list_params) with open('mail.txt', 'w') as f: while messages_request is not None: gmail_msg_list = messages_request.execute() for gmail_msg in gmail_msg_list['messages']: f.write(getMimeMessage(service, 'me', gmail_msg['id'])) if __name__ == '__main__': main()<file_sep>/get_unsub_links.py import re import pprint def get_unsub_links(txt_file): text = open(txt_file).read() pp = pprint.PrettyPrinter(indent=4) urls = re.findall(r'(https?://\S+)',text) duplicates = {} print('Got ' + str(len(urls)) + ' URLs.') for url in urls: duplicates[url] = True print('Got ' + str(len(duplicates)) + ' Unsubscribe URLs. (duplicates included)') for k, v in duplicates.items(): if any(re.findall(r'(U|u)nsub', k)): print(k) def main(): file = 'mail.txt' get_unsub_links(file) if __name__ == '__main__': main()
9491955b0a93d4b8f1d17f4a92ebd1aad379039d
[ "Python" ]
2
Python
anavalo/Gmail_unsubscribe_links
8a35b9568e561bf598187def391e2683f3b33daf
3c355ccc53c86ab04a242168d805cbac3047cad8
refs/heads/main
<file_sep><?php $hari = array("Senin","Selasa", "Rabu"); $bulan = ["Januari", "Februari", "Maret"]; $array = [123, "tulisan", false]; var_dump($hari); echo "<br>"; print_r($bulan); echo "<br>"; echo $array[0]; echo "<br>"; echo $bulan[1]; echo "<br>"; var_dump($hari); $hari[] = "Kamis"; $hari[] = "Jum'at"; $hari[] = "Sabtu"; $hari[] = "Minggu"; echo "<br>"; var_dump($hari); ?> <file_sep><?php echo date("l, d-M-Y"); echo time(); echo date("l", time()-60*60*24*100); echo date("l", mktime(0,0,0,8,25,1985)); echo date("l", mktime(0,0,0,10,1,2021)); echo date("l", strtotime("25 aug 1985")); ?>
c50ba6badfcc379e0423846326c4a902f91ecc6b
[ "PHP" ]
2
PHP
Surinameretat/PHP-Projects
4dea615dfb7d2f7ff997508df88c7cb294e2580c
11f6f6954e84411c8d46f42a45e81bb0e3e97557
refs/heads/master
<file_sep>package ru.alexandertsebenko.shoplist2.utils; /** * Created by avtseben on 06.11.2016. */ public class Reform { private static final String FIRST_PREFIX = "8"; private static final int LENGTH_ELEVEN = 11; /** * Приоводим номера телефонов к единому формату * напрмер в списке контактов телефонной книге номера * могут быть: * +7(913)-504-33-44 * 89033433256 * 8-4215-345023 * * метод приводит номера к единому формату * 89133166336 * 11 цыфр, первая 8, нет пробелов дефисов и скобок * @param inNumber * @return */ public static String normalizeNumber(String inNumber) { StringBuilder sb = new StringBuilder(); sb.append(inNumber.replaceAll("\\D", "")); if(sb.length() == 10){ sb.insert(0,FIRST_PREFIX); } else if (sb.length() == 11 && !(sb.substring(0,1).equals(FIRST_PREFIX))){ sb.replace(0,1,FIRST_PREFIX); } return sb.toString(); } } <file_sep>package ru.alexandertsebenko.shoplist2.ui.adapter; import com.bignerdranch.expandablerecyclerview.Model.ParentListItem; import java.util.ArrayList; import java.util.List; import ru.alexandertsebenko.shoplist2.datamodel.ProductInstance; public class ParentItem implements ParentListItem { List<ProductInstance> mProductInstanceList; String mName; String mDrawableIdName; public ParentItem(String name, String drawableIdName, ProductInstance productInstance) { mName = name; mDrawableIdName = drawableIdName; mProductInstanceList = new ArrayList<>(); addChild(productInstance); } /* public ParentItem(List productList) { mProductList = productList; }*/ public void addChild(ProductInstance productInstance) { mProductInstanceList.add(productInstance); } public void removeChildFromParent(ProductInstance productInstance){ mProductInstanceList.remove(productInstance); } public String getName() { return mName; } public String getImageName(){ return mDrawableIdName; } @Override public List<ProductInstance> getChildItemList() { return mProductInstanceList; } @Override public boolean isInitiallyExpanded() { return true; } } <file_sep>package ru.alexandertsebenko.shoplist2.datamodel; import java.util.HashMap; import java.util.Map; /** * Класс экземпляра покупки для передачи json * */ public class Pinstance { private String globalId; private String product; private float quantity; private String measure; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); public Pinstance() { } /** * * @param product * @param measure * @param quantity * @param globalId */ public Pinstance(String globalId, String product, float quantity, String measure) { this.globalId = globalId; this.product = product; this.quantity = quantity; this.measure = measure; } /** * * @return * The globalId */ public String getGlobalId() { return globalId; } /** * * @param globalId * The globalId */ public void setGlobalId(String globalId) { this.globalId = globalId; } /** * * @return * The product */ public String getProduct() { return product; } /** * * @param product * The product */ public void setProduct(String product) { this.product = product; } /** * * @return * The quantity */ public float getQuantity() { return quantity; } /** * * @param quantity * The quantity */ public void setQuantity(float quantity) { this.quantity = quantity; } /** * * @return * The measure */ public String getMeasure() { return measure; } /** * * @param measure * The measure */ public void setMeasure(String measure) { this.measure = measure; } public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>package ru.alexandertsebenko.shoplist2.ui.fragment; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.UUID; import ru.alexandertsebenko.shoplist2.R; import ru.alexandertsebenko.shoplist2.datamodel.ProductInstance; import ru.alexandertsebenko.shoplist2.datamodel.ShopList; import ru.alexandertsebenko.shoplist2.db.DataSource; import ru.alexandertsebenko.shoplist2.ui.activity.ShopListActivity; import ru.alexandertsebenko.shoplist2.ui.adapter.ChildProductViewHolder; import ru.alexandertsebenko.shoplist2.ui.adapter.ParentItem; import ru.alexandertsebenko.shoplist2.datamodel.Product; import ru.alexandertsebenko.shoplist2.ui.adapter.ShopListAdapter; public class ProductListFragment extends Fragment { public static final int LIST_PREPARE_STATE = 1; public static final int DO_SHOPPING_STATE = 2; public static final String SHOP_LIST_POJO = "slpojo"; RecyclerView mRecyclerView; List<ParentItem> mParentItemList; ShopListAdapter mAdapter; ShopList mShopList; DataSource mDataSource; public static int mState; public static ProductListFragment newInstance(ShopList ShopListPOJO) { ProductListFragment plf = new ProductListFragment(); Bundle args = new Bundle(); args.putParcelable(SHOP_LIST_POJO, ShopListPOJO); plf.setArguments(args); return plf; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDataSource = new DataSource(getContext()); mDataSource.open(); mParentItemList = new ArrayList<>(); //Есть ли в аргументах готовый списко продуктов ил составляем новый ShopList ShopListPojo = getArguments().getParcelable(SHOP_LIST_POJO); if(ShopListPojo != null){ restoreListFromDb(ShopListPojo); } else { createNewShopList();//TODO создавать список только если добавили продукт. И удалять списко если в нём не осталось продуктов (все удалили) } } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_product_list,container, false); setUpRecyclerView(view); setUpItemTouchHelper(ShopListActivity.LIST_PREPARE_STATE); setupSendButton(view); // setupFab(view); return view; } private void createNewShopList(){ long date = System.currentTimeMillis(); String listName = getResources().getString(R.string.defaultListName); long id = mDataSource.addNewShopList(listName,date); mShopList = new ShopList(id,date,listName); } private void setUpRecyclerView(View view){ mRecyclerView = (RecyclerView)view.findViewById(R.id.rv_product_list); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mAdapter = new ShopListAdapter(getContext(),mParentItemList); mRecyclerView.setAdapter(mAdapter); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); } private void restoreListFromDb(ShopList ShopListPojo) { mShopList = ShopListPojo; List<ProductInstance> pil = mDataSource.getProductInstancesByShopListId(mShopList.getId()); for(ProductInstance pinst : pil) { //Добавляем в список только экземпляры у которых статус "в списке" if(pinst.getState() == ProductInstance.IN_LIST) { smartAdd(pinst); } } } //Формируем списко для адаптера //TODO:сохранять список при изменении ориентации private void addProductToList(Product product) { smartAdd(createProductInstance(product)); } private void smartAdd(ProductInstance pinst){ String category = pinst.getProduct().getCategory(); String imageName = pinst.getProduct().getImage(); boolean productAdded = false; for(ParentItem pi : mParentItemList){ //Если продукты такой категории уже есть в списке if(pi.getName().equals(category)) { pi.addChild(pinst); productAdded = true; break; } } //Если в предыдущем цыкле не нашлось в списке катаегории куда "положить" //продукт то создаём эту категорию и кладём в неё продукт if(!productAdded) { mParentItemList.add(new ParentItem(category,imageName,pinst)); } } private ProductInstance createProductInstance(Product product){ int quantity = 1; String measure = "штука"; String uuid = UUID.randomUUID().toString(); int state = ProductInstance.IN_LIST; long id = mDataSource.addProductInstance( mShopList.getId(), product.getId(), quantity,measure,state,uuid); return new ProductInstance(id,product,quantity,measure,state);//TODO: хардкод заглушка //экземпляр покупки 1 штука } public void addProduct(Product product) { addProductToList(product); mAdapter = new ShopListAdapter(getContext(),mParentItemList); mRecyclerView.setAdapter(mAdapter); } public void setUpItemTouchHelper(final int state){ ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback( 0/*drag drop не нужен*/, ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT /*задаём направление свайпа которое слушаем*/) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { //Нам не нужен Drag&Prop return false; } @Override public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { if (!viewHolder.getClass().equals(ChildProductViewHolder.class)) { return 0;//Если это не ChildItem тоесть не сам продукт //то никаких свайпов. Свайп разрешен только для продуктов } return super.getSwipeDirs(recyclerView, viewHolder); } @Override public void onSwiped (RecyclerView.ViewHolder viewHolder, int direction) { if(viewHolder.getClass().equals(ChildProductViewHolder.class)) { int position = viewHolder.getAdapterPosition(); ProductInstance pi = ((ProductInstance)mAdapter.getListItem(position)); if(direction == ItemTouchHelper.RIGHT) { mAdapter.deleteProductInstance(position); pi.setState(ProductInstance.BOUGHT); mDataSource.updateProductInstanceState(pi.getId(), ProductInstance.BOUGHT); } else if(direction == ItemTouchHelper.LEFT) { mAdapter.deleteProductInstance(position); pi.setState(ProductInstance.DELETED);//TODO возможно state DELETED не нужен - просто удалять mDataSource.deleteProductInstanceById(pi.getId()); } } } }; ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); mItemTouchHelper.attachToRecyclerView(mRecyclerView); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } private void setupSendButton(View view){ Button btn = (Button) view.findViewById(R.id.send_button); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(listener != null){ listener.onSendButtonClicked(mShopList); } } }); } private OnSendButtonClickListener listener; public interface OnSendButtonClickListener { void onSendButtonClicked(ShopList shopListPojo); } @Override public void onAttach(Context context) { super.onAttach(context); this.listener = (OnSendButtonClickListener) context; } } <file_sep>package ru.alexandertsebenko.shoplist2.datamodel; public class Product{ int id; String category; String name; String image;//TODO вынести в Класс ProdCategory public Product(String name) { this.name = name; } public Product(String category, String name, String image) { this.category = category; this.name = name; this.image = name; } public Product(int id, String category, String name, String image) { this.id = id; this.category = category; this.name = name; this.image = image; } public String getCategory() { return category; } public String getName() { return name; } public String getImage() { return image; } public int getId() { return id; } public void setId(int id) { this.id = id; } } <file_sep>package ru.alexandertsebenko.shoplist2.net; import android.annotation.TargetApi; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.app.TaskStackBuilder; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; import ru.alexandertsebenko.shoplist2.R; import ru.alexandertsebenko.shoplist2.datamodel.People; import ru.alexandertsebenko.shoplist2.datamodel.PeoplePleaseBuy; import ru.alexandertsebenko.shoplist2.datamodel.Pinstance; import ru.alexandertsebenko.shoplist2.datamodel.Ppb; import ru.alexandertsebenko.shoplist2.datamodel.ProductInstance; import ru.alexandertsebenko.shoplist2.db.DataSource; import ru.alexandertsebenko.shoplist2.ui.activity.ShopListActivity; import ru.alexandertsebenko.shoplist2.ui.fragment.ProductListFragment; import ru.alexandertsebenko.shoplist2.utils.MyApplication; /** * Created by avtseben on 23.10.2016. */ public class Client { public static final String BASE_URL = "http://yrsoft.cu.cc:8080/"; public static final int NOTIFICATION_ID = 5453; Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); ApiEndpointInterface apiService = retrofit.create(ApiEndpointInterface.class); private Ppb newPpb() { String from = "9133166336"; List<String> to = Arrays.asList("9139209220", "9161112020"); List pil = new ArrayList<Pinstance>(); pil.add(new Pinstance("2342mlkmdc2", "Картошка", 1.5f, "кг")); pil.add(new Pinstance("23d2mlkgdc2", "Сметана", 2.0f, "пачка")); pil.add(new Pinstance("2342mlkfdc2", "Хлеб Бородинский", 1.0f, "булка")); Ppb ppb = new Ppb(from, to, pil); return ppb; } public void postPpb(PeoplePleaseBuy ppb) { Call<PeoplePleaseBuy> call = apiService.createPeoplePleaseBuy(ppb); call.enqueue(new Callback<PeoplePleaseBuy>() { @Override public void onResponse(Call<PeoplePleaseBuy> call, Response<PeoplePleaseBuy> response) { System.out.println("Async post" + response.body().getPil().get(0).getProduct()); } @Override public void onFailure(Call<PeoplePleaseBuy> call, Throwable t) { System.out.println("Fail!!!"); } }); } public void getPpb(final String number) { Call<PeoplePleaseBuy> call = apiService.getPeoplePleaseBuy(number); call.enqueue(new Callback<PeoplePleaseBuy>() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onResponse(Call<PeoplePleaseBuy> call, Response<PeoplePleaseBuy> response) { if (response.body() != null) { catchListFromCloud(response.body()); } } @Override public void onFailure(Call<PeoplePleaseBuy> call, Throwable t) { System.out.println("Fail!!!"); } }); } private void catchListFromCloud(PeoplePleaseBuy ppb) { Toast.makeText(MyApplication.getAppContext(), "Client gets list from:" + ppb.getFromWho(), Toast.LENGTH_SHORT).show(); DataSource dataSource = new DataSource(MyApplication.getAppContext()); dataSource.open(); dataSource.saveNewListFromPpb(ppb); } } /* { "from" : "9133166336", "to" : [ "9139209220", "9139209221", "9139209222" ], "pil" : [ {"globalId" : "32342dewd3423dwdee32e", "product" : "Картошка", "quantity" : 1.5, "measure" : "кг"}, {"globalId" : "32343dewd3423dwdee32e", "product" : "Сметана", "quantity" : 1.0, "measure" : "пачка"}, {"globalId" : "32342fdwd3423dwdee32e", "product" : "Хлеб Бородинский", "quantity" : 2.0, "measure" : "булка"} ] } */ <file_sep>package ru.alexandertsebenko.shoplist2.datamodel; /** * Класс описывает одну покупку, например: * - Молоко 2 пачки в Ленте * - Килограмм рыбы на рынке * TODO заменить поле Product на поле String */ public class ProductInstance { public static final int DELETED = 0; public static final int IN_LIST = 1; public static final int IN_BASKET = 2; public static final int BOUGHT = 3; private long id; private String globalId; private Product product; private float quantity; private String measure; private int state; public String getGlobalId() { return globalId; } public void setGlobalId(String globalId) { this.globalId = globalId; } public ProductInstance(long id, Product product, float quantity, String measure, int state) { this.id = id; this.product = product; this.quantity = quantity; this.measure = measure; this.state = state; } public ProductInstance(String globalId, Product product, float quantity, String measure, int state) { this.globalId = globalId; this.product = product; this.quantity = quantity; this.measure = measure; this.state = state; } public ProductInstance(){} public long getId() { return id; } public void setId(long id) { this.id = id; } public int getState() { return state; } public void setState(int state) { this.state = state; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public float getQuantity() { return quantity; } public void setQuantity(float quantity) { this.quantity = quantity; } public String getMeasure() { return measure; } public void setMeasure(String measure) { this.measure = measure; } } <file_sep>package ru.alexandertsebenko.shoplist2.ui.fragment; import android.content.ContentResolver; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.telephony.SmsManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import ru.alexandertsebenko.shoplist2.R; import ru.alexandertsebenko.shoplist2.datamodel.People; import ru.alexandertsebenko.shoplist2.datamodel.PeoplePleaseBuy; import ru.alexandertsebenko.shoplist2.datamodel.Pinstance; import ru.alexandertsebenko.shoplist2.datamodel.ShopList; import ru.alexandertsebenko.shoplist2.db.DataSource; import ru.alexandertsebenko.shoplist2.net.Client; import ru.alexandertsebenko.shoplist2.ui.adapter.ContactsAdapter; import ru.alexandertsebenko.shoplist2.utils.DateBuilder; import ru.alexandertsebenko.shoplist2.utils.Reform; /** * Фрагмент со списком контактов */ public class SendFragment extends Fragment { private List<People> mPeoples; private ListView mPeoplesListView; private ContactsAdapter mAdapter; private Button mSendButton; private TextView mShopListName; private TextView mShopListDate; private ShopList mShopList; public SendFragment() {} public static SendFragment newInstance(ShopList ShopListPOJO) { SendFragment sf = new SendFragment(); Bundle args = new Bundle(); args.putParcelable(ProductListFragment.SHOP_LIST_POJO, ShopListPOJO); sf.setArguments(args); return sf; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_send,container, false); mSendButton = (Button) view.findViewById(R.id.send_button2); mShopListName = (TextView) view.findViewById(R.id.tv_list_name2); mShopListDate = (TextView) view.findViewById(R.id.tv_list_date2); mPeoplesListView = (ListView) view.findViewById(R.id.contact_list); mPeoples = readContacts(); mAdapter = new ContactsAdapter(mPeoples,view.getContext()); mAdapter.setListener(new ContactsAdapter.OnContactClickListener() { @Override public void onContactClicked(People peopleObj) { if(!peopleObj.isSelected()) { peopleObj.setSelected(true); mSendButton.setVisibility(View.VISIBLE); } else { peopleObj.setSelected(false); } mAdapter.notifyDataSetChanged(); } }); mPeoplesListView.setAdapter(mAdapter); mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { People me = new People("ShopList User","89133166336"); PeoplePleaseBuy ppb = new PeoplePleaseBuy( me.getNumber(), getNumbersOfSelectedPeoples(mPeoples), getProdList(mShopList)); System.out.println(ppbToString(ppb)); //Test code Client c = new Client(); c.postPpb(ppb); // sendSms(ppbToString(ppb),ppb.getToWho());//TODO uncomment in future } }); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ShopList ShopListPojo = getArguments().getParcelable(ProductListFragment.SHOP_LIST_POJO); if(ShopListPojo != null){ mShopList = ShopListPojo; mShopListName.setText(mShopList.getName()); mShopListDate.setText(DateBuilder.timeTitleBuilder(mShopList.getDateMilis())); } } public List<People> readContacts(){ List<People> peoples = new ArrayList<>(); ContentResolver cr = getActivity().getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() > 0) { while (cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { // get the phone number Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null); while (pCur.moveToNext()) { String phone = pCur.getString( pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); peoples.add(new People(name, Reform.normalizeNumber(phone))); } pCur.close(); } } } return peoples; } private List<People> getSelectedPeoples(List<People> peopleList){ ArrayList selectedPeoples = new ArrayList<People>(); for(People p : peopleList) { if(p.isSelected()) { selectedPeoples.add(p); } } return selectedPeoples; } private List<String> getNumbersOfSelectedPeoples(List<People> peopleList){ ArrayList numbers = new ArrayList<String>(); for(People p : peopleList) { if(p.isSelected()) { numbers.add(p.getNumber()); } } return numbers; } /** * Возвращает все покупки в списке * TODO нужно добавлять в Объект ShopList список ProductInstanes * а не доставать его из БД * @param shopList * @return */ private List<Pinstance> getProdList(ShopList shopList){ DataSource dataSource = new DataSource(getContext()); dataSource.open(); return dataSource.getPinstancesByShopListId(shopList.getId()); } /** * Возвращает тескт для SMS сообщения * @param ppb * @return */ private String ppbToString(PeoplePleaseBuy ppb){ StringBuilder sb = new StringBuilder(); sb.append(getResources().getString(R.string.sms_head) + "\n"); sb.append("\n"); for (Pinstance pi : ppb.getPil()){ sb.append(pi.getProduct() + ", " + pi.getQuantity() + " " + pi.getMeasure() + "\n"); } return sb.toString(); } private void sendSms(String msg, List<String> numberList){ SmsManager smsManager = SmsManager.getDefault(); for (String n : numberList) { try { smsManager.sendTextMessage(n, null, msg, null, null); } catch (Exception e) { Toast.makeText(getContext(),"SMS send failed",Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } } } <file_sep>package ru.alexandertsebenko.shoplist2.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import ru.alexandertsebenko.shoplist2.datamodel.PeoplePleaseBuy; import ru.alexandertsebenko.shoplist2.net.Client; public class NetworkChangeReceiver extends BroadcastReceiver { boolean mIsConnected; @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); mIsConnected = (netInfo != null && netInfo.isConnected()); if(mIsConnected) { Client c = new Client(); c.getPpb("9139209220"); } else { Toast.makeText(context, getClass().getSimpleName() + ": Disconnected", Toast.LENGTH_SHORT).show(); } } } <file_sep>package ru.alexandertsebenko.shoplist2.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.widget.CursorAdapter; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; import ru.alexandertsebenko.shoplist2.datamodel.PeoplePleaseBuy; import ru.alexandertsebenko.shoplist2.datamodel.Pinstance; import ru.alexandertsebenko.shoplist2.datamodel.Product; import ru.alexandertsebenko.shoplist2.datamodel.ProductInstance; import ru.alexandertsebenko.shoplist2.datamodel.ShopList; public class DataSource { private SQLiteDatabase mDataBase; private DbHelper mDbHelper; private final String TABLE = DbHelper.TABLE_PRODUCTS; private final String SL_TABLE = DbHelper.TABLE_SHOP_LISTS; private final String PNAME = DbHelper.COLUMN_NAME; private final String PCATEG = DbHelper.COLUMN_CATEGORY; private final String PCATEGIMG = DbHelper.COLUMN_CAT_IMAGE; private final String ID = DbHelper.COLUMN_ID; public DataSource (Context context) { mDbHelper = new DbHelper(context); } public void open() throws SQLException { if((mDataBase = mDbHelper.getWritableDatabase()) == null) mDataBase = mDbHelper.getReadableDatabase(); Log.d(getClass().getSimpleName(), "DataSource opened"); } public void close() { mDbHelper.close(); } public Cursor getMatches(String query){ return mDataBase.query(TABLE, new String[]{ID,PNAME},//Для CursorAdapter обязательно нужен ID DbHelper.COLUMN_NAME + " LIKE " + "'%" + query + "%'", null,null,null,null); } public Cursor getAllProducts(){ return mDataBase.query(TABLE, new String[]{ID,PNAME,PCATEG}, null,null,null,null,null); } public List<Product> getProductByNameMatches(String query) { ArrayList<Product> list = new ArrayList<>(); String queryFistCharUpperCase = query.substring(0,1).toUpperCase() + query.substring(1); Cursor cursor = mDataBase.query( TABLE, new String[]{ DbHelper.COLUMN_ID, DbHelper.COLUMN_CATEGORY, DbHelper.COLUMN_NAME, DbHelper.COLUMN_CAT_IMAGE}, DbHelper.COLUMN_NAME + " LIKE " + "'%" + query + "%' OR " + DbHelper.COLUMN_NAME + " LIKE " + "'%" + queryFistCharUpperCase + "%'", null,null,null,null); cursor.moveToFirst(); while (!cursor.isAfterLast()){ list.add(new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3))); cursor.moveToNext(); } return list; } public Product getProductById (long id) { Cursor cursor = mDataBase.query(DbHelper.TABLE_PRODUCTS, new String[]{DbHelper.COLUMN_ID, DbHelper.COLUMN_CATEGORY, DbHelper.COLUMN_NAME, DbHelper.COLUMN_CAT_IMAGE}, DbHelper.COLUMN_ID + " = " + id, null,null,null,null); cursor.moveToFirst(); int c = cursor.getColumnCount(); System.out.println("count " + c); return new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3)); } public String getMeasureById(long id) { Cursor cursor = mDataBase.query(DbHelper.TABLE_MEASURES, new String[]{DbHelper.COLUMN_NAME}, DbHelper.COLUMN_ID + " = " + id, null,null,null,null); cursor.moveToFirst(); return cursor.getString(0); } //TODO переделать всё на AsyncTask public long addNewShopList(String listName,long date){ ContentValues values = new ContentValues(); values.put(DbHelper.COLUMN_NAME,listName); values.put(DbHelper.COLUMN_DATE,date); return mDataBase.insert(SL_TABLE,null,values); } public long addProductInstance(long listId, long productId, int quantity, String measure, int state, String uuid){ ContentValues values = new ContentValues(); values.put(DbHelper.COLUMN_SHOPLIST_ID,listId); values.put(DbHelper.COLUMN_PRODUCT_ID,productId); values.put(DbHelper.COLUMN_QUANTITY,quantity); values.put(DbHelper.COLUMN_MEASURE_ID,1);//TODO заглушка - убрать values.put(DbHelper.COLUMN_STATE,state); values.put(DbHelper.COLUMN_GLOBAL_UUID,uuid); return mDataBase.insert(DbHelper.TABLE_PRODUCT_INSTANCES,null,values); } public void updateProductInstanceState(long id, int state) { ContentValues values = new ContentValues(); values.put(DbHelper.COLUMN_STATE,state); mDataBase.update(DbHelper.TABLE_PRODUCT_INSTANCES, values,DbHelper.COLUMN_ID + " = " + id, null); } public void deleteProductInstanceById(long id) { mDataBase.delete(DbHelper.TABLE_PRODUCT_INSTANCES, DbHelper.COLUMN_ID + " = " + id, null); } public List<ShopList> getAllLists() { List<ShopList> list = new ArrayList<>(); Cursor cursor = mDataBase.query(DbHelper.TABLE_SHOP_LISTS, new String[]{DbHelper.COLUMN_ID,DbHelper.COLUMN_DATE,DbHelper.COLUMN_NAME}, null,null,null,null,null); cursor.moveToFirst(); while (!cursor.isAfterLast()){ list.add(new ShopList( cursor.getLong(0), cursor.getLong(1), cursor.getString(2))); cursor.moveToNext(); } return list; } public void deleteShopListById(long id) { mDataBase.delete(DbHelper.TABLE_SHOP_LISTS, DbHelper.COLUMN_ID + " = " + id,null); } public List<ProductInstance> getProductInstancesByShopListId(long id) { ArrayList<ProductInstance> list = new ArrayList<>(); Cursor cursor = mDataBase.query(DbHelper.TABLE_PRODUCT_INSTANCES, new String[]{DbHelper.COLUMN_ID, DbHelper.COLUMN_PRODUCT_ID, DbHelper.COLUMN_QUANTITY, DbHelper.COLUMN_MEASURE_ID, DbHelper.COLUMN_STATE}, DbHelper.COLUMN_SHOPLIST_ID+ " = " + id, null,null,null,null); cursor.moveToFirst(); while (!cursor.isAfterLast()){ list.add(new ProductInstance( cursor.getLong(0), getProductById(cursor.getLong(1)), cursor.getFloat(2), getMeasureById(cursor.getLong(3)), cursor.getInt(4))); cursor.moveToNext(); } return list; } public List<Pinstance> getPinstancesByShopListId(long id) { ArrayList<Pinstance> list = new ArrayList<>(); Cursor cursor = mDataBase.query(DbHelper.TABLE_PRODUCT_INSTANCES, new String[]{ DbHelper.COLUMN_GLOBAL_UUID, DbHelper.COLUMN_PRODUCT_ID, DbHelper.COLUMN_QUANTITY, DbHelper.COLUMN_MEASURE_ID}, DbHelper.COLUMN_SHOPLIST_ID + " = " + id, null,null,null,null); cursor.moveToFirst(); while (!cursor.isAfterLast()){ list.add(new Pinstance( cursor.getString(0), getProductById(cursor.getLong(1)).getName(), cursor.getFloat(2), getMeasureById(cursor.getLong(3)))); cursor.moveToNext(); } return list; } public long getProductIdByProductName(String name){ Cursor cursor = mDataBase.query(DbHelper.TABLE_PRODUCTS, new String[]{DbHelper.COLUMN_ID}, DbHelper.COLUMN_NAME + " = " + "'" + name + "'", null,null,null,null); cursor.moveToFirst(); return cursor.getLong(0); } public void saveNewListFromPpb(PeoplePleaseBuy ppb) { long shopListId = addNewShopList("От " + ppb.getFromWho(), System.currentTimeMillis()); for (Pinstance pi : ppb.getPil()){ addProductInstance(shopListId, getProductIdByProductName(pi.getProduct()), 1,//TODO в срочном порядке !!! Какого фига я здесь в базе делал INT. Переделать на Float pi.getMeasure(), ProductInstance.IN_LIST, pi.getGlobalId()); } } } <file_sep>package ru.alexandertsebenko.shoplist2.datamodel; import java.util.HashMap; /** * Класс запрос на обновление покупок. Содержит информацию о том * кто что купил или удалил из списка * piUpdatesMap; - Мар в котором ключ - GlobalId покупки а значение - новый статус */ public class PiUpdate { People whoUpdate; HashMap<String,String> piUpdatesMap; public PiUpdate(People whoUpdate, HashMap<String, String> piUpdatesMap) { this.whoUpdate = whoUpdate; this.piUpdatesMap = piUpdatesMap; } }
8e1680d26a45d72eab86c1e50b3e3363b0aa3ba5
[ "Java" ]
11
Java
avtseben/ShopList2
ea6adf8a887f8006b4658f770d9583b41c4a66ff
aeb1f5295b6293d95c23a3ae3e142cf48b24f60c
refs/heads/master
<repo_name>MariusLutz/Shutdown7<file_sep>/Message.cs using System; using System.Threading; using System.Windows; using Microsoft.WindowsAPICodePack.Dialogs; namespace Shutdown7 { class Message { public static void Show(double Text) { Show(Text.ToString()); } public static void Show(bool Text) { Show(Text.ToString()); } public static void Show(string Text) { _Show(Text, "Shutdown7", ""); } public static void Show(string Text, string Icon) { _Show(Text, "Shutdown7", Icon); } public static void Show(string Text, string Title, string Icon) { _Show(Text, Title, Icon); } static void _Show(string Text, string Title, string Icon) { try { TaskDialog td = new TaskDialog(); td.Caption = "Shutdown7"; td.InstructionText = Title; td.Text = Text; switch (Icon) { case "Information": td.Icon = TaskDialogStandardIcon.Information; break; case "Warning": td.Icon = TaskDialogStandardIcon.Warning; break; case "Error": td.Icon = TaskDialogStandardIcon.Error; break; case "Shield": td.Icon = TaskDialogStandardIcon.Shield; break; default: td.Icon = TaskDialogStandardIcon.None; break; } td.Show(); } catch// (NotSupportedException) { MessageBoxImage icon; switch (Icon) { case "Information": icon = MessageBoxImage.Information; break; case "Warning": icon = MessageBoxImage.Warning; break; case "Error": icon = MessageBoxImage.Error; break; default: icon = MessageBoxImage.None; break; } MessageBox.Show(Text, Title, MessageBoxButton.OK, icon); } } } } <file_sep>/Autostart.cs using Microsoft.Win32; namespace Shutdown7 { class Autostart { public static void SetAutoStart(string keyName, string assemblyLocation) { RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); key.SetValue(keyName, assemblyLocation); } public static bool IsAutoStartEnabled(string keyName, string assemblyLocation) { RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); if (key == null) return false; string value = (string)key.GetValue(keyName); if (value == null) return false; return (value == assemblyLocation); } public static void UnSetAutoStart(string keyName) { RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); key.DeleteValue(keyName); } } } <file_sep>/Data.cs using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Windows; namespace Shutdown7 { class Data { #region Deklarationen public static Dictionary<string, string> L = new Dictionary<string, string>(); public static Dictionary<string, bool> S = new Dictionary<string, bool>(); public static Dictionary<string, Dictionary<string, string>> W = new Dictionary<string, Dictionary<string, string>>(); public static string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); public static Version CurVersion = Assembly.GetExecutingAssembly().GetName().Version; public static Version LastVersion = new Version(1, 0, 0, 0); public static string Lang = CultureInfo.CurrentCulture.Name.Substring(0, 2); public static TimeSpan t = new TimeSpan(); public static string EXE = Assembly.GetExecutingAssembly().Location; public static string WOSBPath = Path.GetDirectoryName(EXE) + "\\wosb.exe"; public static string NoisePath = Path.GetDirectoryName(EXE) + "\\White Noise.mp3"; public static string[] RemoteServers = new string[0]; public static string[] RemoteMacs = new string[0]; public static string RemotePassword = ""; public static int RemotePort = 0; public static string ProcessName = "", FileName = "", LaunchFile = "", NetworkAdapter = ""; public static int Network = 0, CpuValue = 90; public static bool CpuMode; public static string curProfile; public static string ArgsServer = ""; public static string ArgsPassword = ""; public static int ArgsPort = 0; public static bool LocalByArgs = false; public static bool RemoteByArgs = false; public static string[] News, Bugs; public enum Modes { None, Shutdown, Restart, Logoff, Lock, Standby, StandbyWOSB, Hibernate, HibernateWOSB, HibernateWOSBIni, HibernateWOSBTime, WakeOnLan, Launch, RestartAndroid, Abort, } public enum Conditions { None, Now, Time, Process, File, Music, Idle, Cpu, Network } public static Modes Mode; public static Conditions Condition; public static Modes orgMode; #endregion #region Debug-Vars public static bool debug_beta = true; public static bool debug_expire = false; public static DateTime Expiration = new DateTime(2016, 06, 25); public static bool debug_verbose = false; public static bool debug_noexecute = true; public static bool debug_stopwatch = false; public static bool debug_mute = false; public static bool debug_debugging = true; #endregion public static void Init() { if (System.Diagnostics.Debugger.IsAttached) debug_debugging = true; #region Lang //CommandLabel.Content = rm.GetString("Message"); if (!L.ContainsKey("Shutdown")) { switch (Lang) { case "de": //Updates News = new string[] { "Neue Einstellung: Merke Fensterposition" }; Bugs = new string[] { "Verbesserung der Zuverlässigkeit des Trayicons" }; //App L.Add("DLLMissing", "Eine oder mehrere der erforderlichen dll-Dateien fehlen.\nBitte installieren Sie Shutdown7 neu oder kopieren Sie die dll-Dateien in den gleichen Ordner."); L.Add("BetaExpired", "Ihre Beta-Version ist abgelaufen. Bitte fordern Sie eine neue Version vom Entwickler an oder warten Sie auf die finale Version."); L.Add("Crash", "Ein schwerwiegender Fehler ist aufgetreten, der Shutdown7 abstürzen ließ. Dieser Fehler wurde in der Datei {0} protokolliert und sollte dem Entwickler gemeldet werden.\n\n"); L.Add("Error", "Fehlermeldung"); L.Add("ConfirmMail", "Den Fehlerbericht an den Entwickler zu senden?\nAlle Daten sind anonymisiert und werden nur zur Diagnose des Fehlers verwendet.\n"); L.Add("ThankYou", "Vielen Dank für Ihre Unterstützung."); L.Add("SendLogToDeveloper", "Bitte senden Sie dieses Log zusammen mit einer kurzen Fehlerbeschreibung an <EMAIL>."); //MainWindow L.Add("Shutdown", "Herunterfahren"); L.Add("Restart", "Neustart"); L.Add("Logoff", "Abmelden"); L.Add("Lock", "Sperren"); L.Add("Standby", "Standby"); L.Add("Hibernate", "Ruhezustand"); L.Add("WakeOnLan", "Wake on Lan"); L.Add("LaunchFile", "Programm starten"); L.Add("RestartAndroid", "Android neustarten"); L.Add("Abort", "Abbrechen"); L.Add("HibernateWOSBIni", "Plane WakeUp (Konfiguration)"); L.Add("HibernateWOSBTime", "Plane WakeUp"); L.Add("Condition", "Bedingung"); L.Add("ModeNow", "Jetzt"); L.Add("ModeTime", "Zeit abgelaufen"); L.Add("ModeWindowClosed", "Fenster geschlossen"); L.Add("ModeProcessClosed", "Prozess geschlossen"); L.Add("ModeFileDeleted", "Datei gelöscht"); L.Add("ModeMusicPlayed", "Musik abgespielt"); L.Add("ModeIdle", "Keine Benutzeraktivität"); L.Add("ModeCpu", "CPU Auslastung"); L.Add("ModeNetwork", "Netzwerk Auslastung"); L.Add("At", "Um"); L.Add("In", "In"); L.Add("AskShutdown", "Herunterfahren?"); L.Add("AskReboot", "Neustarten?"); L.Add("AskLogoff", "Abmelden?"); L.Add("AskLock", "Sperren?"); L.Add("AskStandby", "Computer in Standby versetzen?"); L.Add("AskHibernate", "Computer in den Ruhezustand versetzen?"); L.Add("CMD", "Kommandozeilenbefehle"); L.Add("GO!", "GO!"); L.Add("Restore", "Wiederherstellen"); L.Add("Hide", "Verstecken"); L.Add("Autostart", "Autostart"); L.Add("Settings", "Einstellungen"); L.Add("Exit", "Beenden"); L.Add("BalloontipAbort", "Geplante Aktion abgebrochen."); L.Add("BalloontipTimeShutdown", "Der PC wird in {0} heruntergefahren."); L.Add("BalloontipTimeRestart", "Der PC wird in {0} neugestartet."); L.Add("BalloontipTimeLogoff", "Sie werden in {0} abgemeldet."); L.Add("BalloontipTimeLock", "Der PC wird in {0} gesperrt."); L.Add("BalloontipTimeStandby", "Der PC wird in {0} in den Standby versetzt."); L.Add("BalloontipTimeHibernate", "Der PC wird in {0} in den Ruhezustand versetzt."); L.Add("BalloontipTimeStandbyWOSB", L["BalloontipTimeStandby"]); L.Add("BalloontipTimeHibernateWOSB", L["BalloontipTimeHibernate"]); //HibernateWOSBTime,Ini nicht gebraucht L.Add("BalloontipTimeWakeOnLan", "Der PC wird in {0} aufgeweckt."); L.Add("BalloontipTimeLaunch", "Datei/Programm wird in {0} gestartet."); L.Add("BalloontipTimeRestartAndroid", "Smartphone wird in {0} neugestartet."); L.Add("BalloontipProcessShutdown", "Der PC wird heruntergefahren, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessRestart", "Der PC wird neugestartet, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessLogoff", "Der PC wird abgemeldet, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessLock", "Der PC wird gesperrt, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessStandby", "Der PC wird in den Standby versetzt, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessHibernate", "Der PC wird in den Ruhezustand versetzt, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessStandbyWOSB", L["BalloontipProcessStandby"]); L.Add("BalloontipProcessHibernateWOSB", L["BalloontipProcessHibernate"]); L.Add("BalloontipProcessWakeOnLan", "Der PC wird aufgeweckt, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessRestartAndroid", "Smartphone wird neugestartet, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipProcessLaunch", "Datei/Programm wird gestartet, sobald Prozess {0} geschlossen wird."); L.Add("BalloontipWindowShutdown", "Der PC wird heruntergefahren, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowRestart", "Der PC wird neugestartet, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowLogoff", "Der PC wird abgemeldet, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowLock", "Der PC wird gesperrt, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowStandby", "Der PC wird in den Standby versetzt, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowHibernate", "Der PC wird in den Ruhezustand versetzt, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowStandbyWOSB", L["BalloontipWindowStandby"]); L.Add("BalloontipWindowHibernateWOSB", L["BalloontipWindowHibernate"]); L.Add("BalloontipWindowWakeOnLan", "Der PC wird aufgeweckt, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowLaunch", "Datei/Programm wird gestartet, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipWindowRestartAndroid", "Smartphone wird neugestartet, sobald Fenster {0} geschlossen wird."); L.Add("BalloontipFileShutdown", "Der PC wird heruntergefahren, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileRestart", "Der PC wird neugestartet, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileLogoff", "Der PC wird abgemeldet, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileLock", "Der PC wird gesperrt, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileStandby", "Der PC wird in den Standby versetzt, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileHibernate", "Der PC wird in den Ruhezustand versetzt, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileStandbyWOSB", L["BalloontipFileStandby"]); L.Add("BalloontipFileHibernateWOSB", L["BalloontipFileHibernate"]); L.Add("BalloontipFileWakeOnLan", "Der PC wird aufgeweckt, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileLaunch", "Datei/Programm wird gestartet, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipFileRestartAndroid", "Smartphone wird neugestartet, sobald die Datei {0} gelöscht wurde."); L.Add("BalloontipMusicShutdown", "Der PC wird heruntergefahren, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicRestart", "Der PC wird neugestartet, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicLogoff", "Der PC wird abgemeldet, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicLock", "Der PC wird gesperrt, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicStandby", "Der PC wird in den Standby versetzt, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicHibernate", "Der PC wird in den Ruhezustand versetzt, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicStandbyWOSB", L["BalloontipMusicStandby"]); L.Add("BalloontipMusicHibernateWOSB", L["BalloontipMusicHibernate"]); L.Add("BalloontipMusicWakeOnLan", "Der PC wird aufgeweckt, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicLaunch", "Datei/Programm wird gestartet, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipMusicRestartAndroid", "Smartphone wird neugestartet, sobald die Datei(en) {0} abgespielt wurde(n)."); L.Add("BalloontipIdleShutdown", "Der PC wird bei {0} Inaktivität heruntergefahren."); L.Add("BalloontipIdleRestart", "Der PC wird bei {0} Inaktivität neugestartet."); L.Add("BalloontipIdleLogoff", "Sie werden bei {0} Inaktivität abgemeldet."); L.Add("BalloontipIdleLock", "Der PC wird bei {0} Inaktivität gesperrt."); L.Add("BalloontipIdleStandby", "Der PC wird bei {0} Inaktivität in den Standby versetzt."); L.Add("BalloontipIdleHibernate", "Der PC wird bei {0} Inaktivität in den Ruhezustand versetzt."); L.Add("BalloontipIdleStandbyWOSB", L["BalloontipIdleStandby"]); L.Add("BalloontipIdleHibernateWOSB", L["BalloontipIdleHibernate"]); L.Add("BalloontipIdleWakeOnLan", "Der PC wird bei {0} Inaktivität aufgeweckt."); L.Add("BalloontipIdleLaunch", "Datei/Programm wird bei {0} Inaktivität gestartet."); L.Add("BalloontipIdleRestartAndroid", "Smartphone wird wird bei {0} Inaktivität neugestartet."); L.Add("BalloontipCpuShutdown", "Der PC wird heruntergefahren, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuRestart", "Der PC wird neugestartet, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuLogoff", "Sie werden abgemeldet, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuLock", "Der PC wird gesperrt, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuStandby", "Der PC wird in den Standby versetzt, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuHibernate", "Der PC wird in den Ruhezustand versetzt, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuStandbyWOSB", L["BalloontipTimeStandby"]); L.Add("BalloontipCpuHibernateWOSB", L["BalloontipTimeHibernate"]); L.Add("BalloontipCpuWakeOnLan", "Der PC wird aufgeweckt, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuLaunch", "Datei/Programm wird gestartet, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipCpuRestartAndroid", "Smartphone wird wird neugestartet, sobald die CPU Auslastung {0} {1} % für {2} ist."); L.Add("BalloontipNetworkShutdown", "Der PC wird heruntergefahren, sobald die Netzwerk Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkRestart", "Der PC wird neugestartet, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkLogoff", "Sie werden abgemeldet, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkLock", "Der PC wird gesperrt, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkStandby", "Der PC wird in den Standby versetzt, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkHibernate", "Der PC wird in den Ruhezustand versetzt, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkStandbyWOSB", L["BalloontipTimeStandby"]); L.Add("BalloontipNetworkHibernateWOSB", L["BalloontipTimeHibernate"]); L.Add("BalloontipNetworkWakeOnLan", "Der PC wird aufgeweckt, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkLaunch", "Datei/Programm wird gestartet, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("BalloontipNetworkRestartAndroid", "Smartphone wird wird neugestartet, sobald die Network Auslastung {0} {1} kbps für {2} ist."); L.Add("FiveSecs", "5 Sekunden"); L.Add("XmlReadError_1", "Fehler beim Lesen der Konfigurationsdatei, achten Sie auf Systaxfehler."); L.Add("XmlReadError_2", "\n\nGenauer Fehler:\n\n{0}\n\nBitte Anwendung neustarten."); L.Add("WOSBIniFileDone", "WOSB-Inidatei erfolgreich geschrieben.Bitte Anwendung neustarten."); L.Add("NoWakeUpSheduled", "Kein Wakeup eingetragen."); //L.Add("RequireAdmin", "Shutdown7 funktioniert nur mit Adminrechten.\nBitte mit Adminrechten neustarten."); L.Add("RequireAdmin", "Shutdown7 funktioniert nur mit Adminrechten.\nEs wird mit Adminrechten neugestartet."); L.Add("Updated", "Erfolgreich aktualisiert."); L.Add("SelectFile", "Wähle eine Datei"); L.Add("SelectFiles", "Wähle Datei(en)"); L.Add("AllFiles", "Alle Dateien"); L.Add("MusicFiles", "Musikstücke"); L.Add("ExeFiles", "Anwendungen"); L.Add("PlayLists", "Playlisten"); L.Add("Browse", "Durchsuchen"); L.Add("Add", "Hinzufügen"); L.Add("Remove", "Entfernen"); L.Add("Above", "Über"); L.Add("Below", "Unter"); L.Add("Down", "Downstream"); L.Add("Up", "Upstream"); L.Add("ScreenOff", "Monitor ausschalten"); L.Add("MusicFadeout", "Musiklautstärke absenken"); L.Add("MusicOrgVolume", "Anfangslautstärke"); L.Add("FadeStart", "Senke ab nach % der Gesamtlänge"); L.Add("FadeEndVolume", "Endlautstärke (0 = Stille)"); L.Add("PlayNoise", "Spiele weißes Rauschen"); L.Add("Password", "<PASSWORD>"); L.Add("ResumeLastAction", "Letzten Auftrag fortsetzen"); L.Add("StartShutdownError", "Fehler aufgetreten beim Starten des Shutdowns."); L.Add("NoAndroidFound", "Kein angeschlossenes Android-Gerät gefunden."); L.Add("RemoteConnect", "Verbinde"); L.Add("RemoteSend", "Sende"); L.Add("RemoteErrorRequest", "Ungültiger Befehl gesendet"); L.Add("RemoteErrorBrowser", "Sie haben Shutdown7 im Webbrowser aufgerufen.<br />\nUm Ihren PC auszuschalten, besuchen Sie bitte die <span id=\"WebUI\"><a href=\"{0}\">WebUI</a></span> oder benutzen Sie Shutdown7 im Client-Mode.<br />\n"); L.Add("RemoteWrongPass", "Jemand versuchte Ihren PC herunterzufahren, benutzte aber das falsche Passwort.\nWenn Sie das nicht waren, ändern Sie aus Sicherheitsgründen den Port und/oder das Passwort."); L.Add("RemoteWrongPassShort", "Falsches Passwort"); L.Add("RemoteBusy", "Shutdown7 führt bereits eine Aktion auf diesem PC aus.\nWenn Sie einen weiteren Auftrag durchführen möchten, müssen Sie den vorherigen abbrechen."); L.Add("RemoteServerTimeout", "Server nicht erreichbar"); L.Add("RemoteBusyShort", "Shutdown läuft bereits"); L.Add("RemoteError", "Unbekannter Fehler"); L.Add("RemotePortMissing", "Bitte wählen Sie einen freie Portnummer zwischen 1024 und 65535."); L.Add("WebUIStatus", "<br /><b>Status:</b><br />\n"); L.Add("WebUIProcssClosed", ", wenn der Prozess '{0}.exe' geschlossen wurde."); L.Add("WebUIWindowClosed", ", wenn das Fenster '{0}' geschlossen wurde."); L.Add("WebUIFileDeleted", ", wenn die Datei '{0}' gel&ouml;scht wird."); L.Add("WebUIMusicPlayed_1", ", wenn "); L.Add("WebUIMusicPlayed_2a", " abgespielt wurde."); L.Add("WebUIMusicPlayed_2b", " abgespielt wurden."); L.Add("WebUIIdle", ", wenn der PC f&uuml;r {0} nicht benutzt wird."); L.Add("Ready", "Bereit"); L.Add("Receive", "Empfange"); L.Add("Sucessful", "Erfolgreich"); L.Add("Aborted", "Abgebrochen"); L.Add("and", "und"); L.Add("UpdateisAvaiable", "Update verf&uuml;gbar"); //Settings L.Add("Monday", "Montag"); L.Add("Tuesday", "Dienstag"); L.Add("Wednesday", "Mittwoch"); L.Add("Thursday", "Donnerstag"); L.Add("Friday", "Freitag"); L.Add("Saturday", "Samstag"); L.Add("Sunday", "Sonntag"); L.Add("RemoteServerHelp", "Benötigen Sie Hilfe bei Einrichtung der Portweiterleitung?"); L.Add("SystrayNotSupported", "Die Systray-Funktion ist zur Zeit sehr fehleranfällig.\nMöchten Sie diese Funktion wirklich aktivieren?"); L.Add("PortCheckErrPort", "Port ist bereits belegt, bitte anderen Port wählen."); L.Add("PortCheckErrLocal", "Kann nicht lokal verbinden\nÜberprüfen Sie die Firewalleinstellungen.\nIP-Adresse: "); L.Add("PortCheckErrNetwork", "Kann nicht lokal übers Netzwerk verbinden\nÜberprüfen Sie die Firewalleinstellungen.\nIP-Adresse: "); L.Add("PortCheckErrRemote", "Kann nicht über das Internet verbinden\nÜberprüfen Sie die Firewalleinstellungen.\nIP-Adresse: "); L.Add("PortCheckOK", "Portweiterleitung funktioniert."); L.Add("RemotePasswordMissing", "Bitte Passwort eingeben."); L.Add("FirewallOK", "Firewallausnahme eingetragen."); L.Add("FirewallError", "Fehler beim Eintragen der Firewallausnahme.\nBitte schauen Sie in der Web-Hilfe nach, wie sie die Ausnahme manuell einrichten.\nFehler: "); L.Add("LastProfile", "Dies ist Ihr letztes Profil. Es kann nicht gelöscht werden, bis Sie ein neues erstellen."); //About L.Add("Help", "Hilfe"); //Welcome L.Add("PinText", "An Taskleiste anheften"); break; default: //Updates News = new string[] { "New Setting: Remember window position" }; Bugs = new string[] { "Systray stability improvements" }; //App L.Add("DDLMissing", "One of the required ddl-files are missing.\nPlease reinstall Shutdown7 or copy the dll-files in the same folder."); L.Add("BetaExpired", "Your beta-version is expired. Please demand a newer built from the developer or wait for the final version."); L.Add("Crash", "The application encountered a fatal error and must exit. This error has been logged in the file {0} and should be reported to the developer."); L.Add("Error", "Error"); L.Add("ConfirmMail", "Do you allow to send a crash report to the developer?\nAll data are anonymized and will only be used for diagnosis of the error.\n"); L.Add("ThankYou", "Thank you for your support."); L.Add("SendLogToDeveloper", "Please send this log with a short error description to <EMAIL>."); //MainWindow L.Add("Shutdown", "Shutdown"); L.Add("Restart", "Restart"); L.Add("Logoff", "Logoff"); L.Add("Lock", "Lock"); L.Add("Standby", "Standby"); L.Add("Hibernate", "Hibernate"); L.Add("WakeOnLan", "Wake on Lan"); L.Add("LaunchFile", "Start application"); L.Add("RestartAndroid", "Reboot Android device"); L.Add("Abort", "Abort"); L.Add("HibernateWOSBIni", "Schedule wake up (Configuration)"); L.Add("HibernateWOSBTime", "Shedule wake up"); L.Add("Condition", "Condition"); L.Add("ModeNow", "Now"); L.Add("ModeTime", "Time is up"); L.Add("ModeWindowClosed", "Window closed"); L.Add("ModeProcessClosed", "Process closed"); L.Add("ModeFileDeleted", "File deleted"); L.Add("ModeMusicPlayed", "Music played"); L.Add("ModeIdle", "No user input"); L.Add("ModeCpu", "CPU usage"); L.Add("ModeNetwork", "Network usage"); L.Add("At", "At"); L.Add("In", "In"); L.Add("AskShutdown", "Shutdown?"); L.Add("AskReboot", "Restart?"); L.Add("AskLogoff", "Log off?"); L.Add("AskLock", "Lock?"); L.Add("AskHibernate", "Hibernate?"); L.Add("CMD", "Commandline arguments"); L.Add("GO!", "GO!"); L.Add("Restore", "Restore"); L.Add("Hide", "Hide"); L.Add("Autostart", "Autostart"); L.Add("Settings", "Settings"); L.Add("Exit", "Exit"); L.Add("BalloontipAbort", "Planned action cancelled."); //TODO: Translate Android L.Add("BalloontipTimeShutdown", "The PC will shutdown in {0}."); L.Add("BalloontipTimeRestart", "The PC will restart in {0}."); L.Add("BalloontipTimeLogoff", "You will be logged off in {0}."); L.Add("BalloontipTimeLock", "The PC will be locked in {0}."); L.Add("BalloontipTimeStandby", "The PC will go to standby in {0}."); L.Add("BalloontipTimeHibernate", "The PC will hibernate in {0}."); L.Add("BalloontipTimeStandbyWOSB", L["BalloontipTimeStandby"]); L.Add("BalloontipTimeHibernateWOSB", L["BalloontipTimeHibernate"]); L.Add("BalloontipTimeWakeOnLan", "The PC is waked up in {0}."); L.Add("BalloontipTimeLaunch", "File/program is run in {0}."); L.Add("BalloontipProcessShutdown", "The PC will shutdown when process {0} is closed."); L.Add("BalloontipProcessRestart", "The PC will restart when process {0} is closed"); L.Add("BalloontipProcessLogoff", "You will be logged off when process {0} is closed."); L.Add("BalloontipProcessLock", "The PC will be locked when process {0} is closed."); L.Add("BalloontipProcessStandby", "The PC will go to standby when process {0} is closed."); L.Add("BalloontipProcessHibernate", "The PC will hibernate when process {0} is closed."); L.Add("BalloontipProcessStandbyWOSB", L["BalloontipProcessStandby"]); L.Add("BalloontipProcessHibernateWOSB", L["BalloontipProcessHibernate"]); L.Add("BalloontipProcessWakeOnLan", "The PC is waked up when process {0} is closed."); L.Add("BalloontipProcessLaunch", "File/program is run when process {0} is closed."); L.Add("BalloontipWindowShutdown", "The PC will shutdown when window {0} is closed."); L.Add("BalloontipWindowRestart", "The PC will restart when window {0} is closed."); L.Add("BalloontipWindowLogoff", "You will be logged off when window {0} is closed."); L.Add("BalloontipWindowLock", "The PC will be locked when window {0} is closed."); L.Add("BalloontipWindowStandby", "The PC will go to standby when window {0} is closed."); L.Add("BalloontipWindowHibernate", "The PC will hibernate when window {0} is closed."); L.Add("BalloontipWindowStandbyWOSB", L["BalloontipWindowStandby"]); L.Add("BalloontipWindowHibernateWOSB", L["BalloontipWindowHibernate"]); L.Add("BalloontipWindowWakeOnLan", "The PC is waked up when window {0} is closed."); L.Add("BalloontipWindowLaunch", "File/program is run when window {0} is closed."); L.Add("BalloontipFileShutdown", "The PC will shutdown when file {0} is deleted."); L.Add("BalloontipFileRestart", "The PC will restart when file {0} is deleted."); L.Add("BalloontipFileLogoff", "You will be logged off when file {0} is deleted."); L.Add("BalloontipFileLock", "The PC will be locked when file {0} is deleted."); L.Add("BalloontipFileStandby", "The PC will go to standby when file {0} is deleted."); L.Add("BalloontipFileHibernate", "The PC will hibernate when file {0} is deleted."); L.Add("BalloontipFileStandbyWOSB", L["BalloontipFileStandby"]); L.Add("BalloontipFileHibernateWOSB", L["BalloontipFileHibernate"]); L.Add("BalloontipFileWakeOnLan", "The PC is waked up when file {0} is deleted."); L.Add("BalloontipFileLaunch", "File/program is run when file {0} is deleted."); L.Add("BalloontipMusicShutdown", "The PC will shutdown when file(s) {0} was/were played."); L.Add("BalloontipMusicRestart", "The PC will restart when file(s) {0} was/were played."); L.Add("BalloontipMusicLogoff", "You will be logged off when file(s) {0} was/were played."); L.Add("BalloontipMusicLock", "The PC will be locked when file(s) {0} was/were played."); L.Add("BalloontipMusicStandby", "The PC will go to standby when file(s) {0} was/were played."); L.Add("BalloontipMusicHibernate", "The PC will hibernate when file(s) {0} was/were played."); L.Add("BalloontipMusicStandbyWOSB", L["BalloontipMusicStandby"]); L.Add("BalloontipMusicHibernateWOSB", L["BalloontipMusicHibernate"]); L.Add("BalloontipMusicWakeOnLan", "The PC is waked up when file(s) {0} was/were played."); L.Add("BalloontipMusicLaunch", "File/program is run when file(s) {0} was/were played."); L.Add("BalloontipIdleShutdown", "The PC will shutdown at {0} idle time."); L.Add("BalloontipIdleRestart", "The PC will restart at {0} idle time."); L.Add("BalloontipIdleLogoff", "You will be logged off at {0} idle time."); L.Add("BalloontipIdleLock", "The PC will be locked at {0} idle time."); L.Add("BalloontipIdleStandby", "The PC will go to standby at {0} idle time."); L.Add("BalloontipIdleHibernate", "The PC will hibernate at {0} idle time."); L.Add("BalloontipIdleStandbyWOSB", L["BalloontipIdleStandby"]); L.Add("BalloontipIdleHibernateWOSB", L["BalloontipIdleHibernate"]); L.Add("BalloontipIdleWakeOnLan", "The PC is waked up at {0} idle time."); L.Add("BalloontipIdleLaunch", "File/program is run at {0} idle time."); L.Add("BalloontipIdleRestartAndroid", "Smartphone is restarted at {0} idle time."); // L.Add("BalloontipCpuShutdown", "The PC will shutdown when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuRestart", "The PC will restart when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuLogoff", "You will be logged off when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuLock", "The PC will be locked when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuStandby", "he PC will go to standby when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuHibernate", "he PC will hibernate when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuStandbyWOSB", L["BalloontipTimeStandby"]); L.Add("BalloontipCpuHibernateWOSB", L["BalloontipTimeHibernate"]); L.Add("BalloontipCpuWakeOnLan", "The PC is waked up when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuLaunch", "File/program is run when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipCpuRestartAndroid", "Smartphone is restarted when cpu usage is {0} {1} % for {2}."); L.Add("BalloontipNetworkShutdown", "The PC will shutdown when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkRestart", "The PC will restart when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkLogoff", "You will be logged off when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkLock", "The PC will be locked when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkStandby", "he PC will go to standby when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkHibernate", "he PC will hibernate when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkStandbyWOSB", L["BalloontipTimeStandby"]); L.Add("BalloontipNetworkHibernateWOSB", L["BalloontipTimeHibernate"]); L.Add("BalloontipNetworkWakeOnLan", "The PC is waked up when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkLaunch", "File/program is run when network usage is {0} {1} kbps for {2}."); L.Add("BalloontipNetworkRestartAndroid", "Smartphone is restarted when network usage is {0} {1} kbps for {2}."); L.Add("FiveSecs", "5 seconds"); L.Add("XmlReadError_1", "Couldn't read configuration file."); L.Add("XmlReadError_2", "\n\nPlease check syntax errors. Error:\n\n{0}\n\nPlease restart this program."); L.Add("WOSBIniFileDone", "WOSB-inifile sucessfull written.\nPlease restart this program."); L.Add("NoWakeUpSheduled", "No wakeup sheduled."); L.Add("RequireAdmin", "Shutdown7 works with admin rights only.\nPlease restart with admin rights."); L.Add("Updated", "Update complete."); L.Add("SelectFile", "Select a file"); L.Add("SelectFiles", "Select file(s)"); L.Add("AllFiles", "All files"); L.Add("MusicFiles", "Music files"); L.Add("ExeFiles", "Executables"); L.Add("PlayLists", "Playlists"); L.Add("Browse", "Browse"); L.Add("Add", "Add"); L.Add("Remove", "Remove"); L.Add("Above", "Above"); L.Add("Below", "Below"); L.Add("Down", "Downstream"); L.Add("Up", "Upstream"); L.Add("Password", "<PASSWORD>"); L.Add("ScreenOff", "Turn screen off"); L.Add("MusicFadeout", "Fade out music volume"); L.Add("MusicOrgVolume", "Initial volume"); L.Add("FadeStart", "Start fading after % of total duration"); L.Add("FadeEndVolume", "End volume (0 = silent)"); L.Add("PlayNoise", "Play white noise"); L.Add("ResumeLastAction", "Resume last action"); L.Add("StartShutdownError", "Error occured while shutting down your computer."); L.Add("NoAndroidFound", "No connected Android device found."); L.Add("RemoteConnect", "Connecting"); L.Add("RemoteSend", "Sending"); L.Add("RemoteErrorRequest", "Invalid command sent"); L.Add("RemoteErrorBrowser", "You visited Shutdown7 via the webbrowser.<br />\nTo shutdown your PC over the internet you have to visit the <span id=\"WebUI\"><a href=\"{0}\">WebUI</a></span> or use Shutdown7 in client-mode.<br />\n"); L.Add("RemoteWrongPass", "Someone tried to shutdown this PC, but used the wrong password.\nIf it wasn't you, change because of security reasons your port number and/or yout password."); L.Add("RemoteWrongPassShort", "<PASSWORD> password"); L.Add("RemoteServerTimeout", "Server not reachable (timeout)."); L.Add("RemoteBusy", "Shutdown7 is executing already. If you want to execute another command, you have to abort the previous one."); L.Add("RemoteBusyShort", "Shutdown already running"); L.Add("RemoteError", "Unknown Error"); L.Add("WebUIStatus", "<br /><b>Status:</b><br />\n"); L.Add("WebUIProcssClosed", " when process '{0}.exe' is closed. "); L.Add("WebUIWindowClosed", " when window '{0}' is closed. "); L.Add("WebUIFileDeleted", " when file '{0}' is deleted. "); L.Add("WebUIMusicPlayed_1", " when "); L.Add("WebUIMusicPlayed_2a", " has been played."); L.Add("WebUIMusicPlayed_2b", " have been played."); L.Add("WebUIIdle", ", when the computer isn't used for {0}."); L.Add("Ready", "Ready"); L.Add("Receive", "Receive"); L.Add("Sucessful", "Sucessful"); L.Add("Aborted", "Aborted"); L.Add("and", "and"); L.Add("UpdateisAvaiable", "Update available"); //Settings L.Add("Monday", "Monday"); L.Add("Tuesday", "Tuesday"); L.Add("Wednesday", "Wednesday"); L.Add("Thursday", "Thursday"); L.Add("Friday", "Friday"); L.Add("Saturday", "Saturday"); L.Add("Sunday", "Sunday"); L.Add("RemotePortMissing", "Please specifiy a free port number between 1024 and 65535."); L.Add("RemotePasswordMissing", "Please enter password"); L.Add("RemoteServerHelp", "Do you need help setting up port forwarding?"); L.Add("PortCheckErrPort", "Port is already in use. Please choose another one."); L.Add("PortCheckErrLocal", "Can't connect over localhost\nPlease check firewall settings.\nIP adress: "); L.Add("PortCheckErrNetwork", "Can't connect over local network\nPlease check firewall settings.\nIP adress: "); L.Add("PortCheckErrRemote", "Can't connect over internet\nPlease check firewall settings.\nIP adress: "); L.Add("PortCheckOK", "Port forwarding works."); L.Add("FirewallOK", "Firewall exception added."); L.Add("FirewallError", "Couldn't add firewall exception.\nPlease refer to the web-help to add the exception manually.\nError: "); L.Add("LastProfile", "This is your last profile. You can't delete this one until you created a new one."); //About L.Add("Help", "Help"); //Welcome L.Add("PinText", "Pin to Taskbar"); break; } } #endregion #region Settings if (!S.ContainsKey("Force")) //Default Values { S.Add("AllProcesses", false); S.Add("Ask", false); S.Add("Autostart", false); S.Add("Force", false); S.Add("Glass", false); S.Add("IPv4", true); S.Add("Jumplist", true); S.Add("ModusIcons", true); S.Add("Overlay", true); S.Add("RemoteClient", false); S.Add("RemoteServer", false); S.Add("ResumeLastAction", false); S.Add("SaveWindowState", false); S.Add("SendFeedback", false); S.Add("StayAfterShutdown", false); S.Add("SysIcon", false); S.Add("ThumbnailToolbar", false); S.Add("WakeOnLan", false); S.Add("Win8Hybrid", Win7.IsWin8); S.Add("WOSB", false); } if (!File.Exists(Ini.Path) & !File.Exists(Xml.Path)) { Welcome.welcome = true; //new Welcome().ShowDialog(); } else { if (File.Exists(Xml.Path)) Xml.Read(); else Xml.MigrateIni(); if (Data.S["WOSB"] & !File.Exists(Xml.WOSBPath)) { Xml.MigrateWOSBIni(); } } if (!File.Exists(WOSBPath)) S["WOSB"] = false; /*if (S["WOSB"]) { if (!W.ContainsKey("File")) { W.Add("File", ""); W.Add("Params", ""); W.Add("AwFile", ""); W.Add("AwParams", ""); W.Add("Extra", "/psbh /ptowu"); Xml.ReadWOSB(); } }*/ #endregion } } } <file_sep>/About.xaml.cs using System; using System.Diagnostics; using System.Media; using System.Windows; using System.Windows.Input; namespace Shutdown7 { public partial class About : Window { public About() { InitializeComponent(); #region Lang HelpLabel.Text = Data.L["Help"]; #endregion Versionx.Content = "Version " + Data.Version; } #region Aero protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); Win7.Glass(this); } #endregion #region Websites private void WebsiteLabel_Click(object sender, RoutedEventArgs e) { Process.Start("http://shutdown7.com/?lang=" + Data.Lang.ToLower()); } private void FeedbackLabel_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.shutdown7.com/kontakt.php?lang=" + Data.Lang.ToLower()); } private void HelpLabel_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.shutdown7.com/faq.php?lang=" + Data.Lang.ToLower()); } #endregion #region Eastereggs PacMan pacman = new PacMan(); private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key.ToString().ToUpper() == "S" && !Rika.IsVisible) { if (!Shana.IsVisible) { this.Title = "Shana"; this.Top = 0; Shana.Visibility = Visibility.Visible; SoundPlayer Sound = new SoundPlayer(Shutdown7.Properties.Resources.Urusai); Sound.Play(); } else { this.Title = "About"; Shana.Visibility = Visibility.Collapsed; } } else if (e.Key.ToString().ToUpper() == "N" && !Shana.IsVisible) { if (!Rika.IsVisible) { this.Title = "Nipah~"; this.Top = 0; Rika.Visibility = Visibility.Visible; SoundPlayer Sound = new SoundPlayer(Shutdown7.Properties.Resources.Nipah); Sound.Play(); } else { this.Title = "About"; Rika.Visibility = Visibility.Collapsed; } } else if (e.Key.ToString().ToUpper() == "P" && !Shana.IsVisible && !Rika.IsVisible) { new PacMan().Show(); } } #endregion #region Buttons private void Donate_MouseUp(object sender, MouseButtonEventArgs e) { Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=10883669"); } private void Like_MouseUp(object sender, MouseButtonEventArgs e) { Process.Start("http://www.facebook.com/Shutdown7/"); } private void Tweet_MouseUp(object sender, MouseButtonEventArgs e) { Process.Start("http://twitter.com/share?_=1285003415520&count=none&original_referer=http%3A%2F%2Fwww.shutdown7.com&text=Shutdown7&url=http%3A%2F%2Fwww.shutdown7.com&via=ShutdownSeven"); } #endregion } } <file_sep>/Welcome.xaml.cs using System; using System.Diagnostics; using System.IO; using System.Net.NetworkInformation; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; using System.Windows.Shapes; using Microsoft.WindowsAPICodePack.Dialogs; using System.Collections.Generic; namespace Shutdown7 { /// <summary> /// Interaktionslogik für Welcome.xaml /// </summary> public partial class Welcome : Window { public static bool welcome, update; int curscreen; bool done, skip; string[] Titles, Instructions; TextBlock labelBugs = new TextBlock(); public Welcome() { InitializeComponent(); #region Lang switch (Data.Lang) { case "de": Titles = new string[] { "Willkommen bei Shutdown7", "Neues in Version " + Data.Version, "Autostart", "Einstellungen", "Windows 7-Features", "Remote-Funktionen", "Remote-Server Einstellungen", "WOSB", "WOSB Einstellungen", "User-Feedback", "Abgeschlossen", }; Instructions = new string[] { "Dieser Assistent hilft Ihnen, Shutdown7 für den ersten Gebrauch zu konfigurieren.", "Neue Funktionen in dieser Version", "Wenn Sie möchten, lädt Shutdown7 jeden Windowsstart mit, um sofort bereit zu sein. Dies empfiehlt sich insbesondere, wenn Sie die Remote-Server-Option benutzen möchten.", "Hier können Sie das Verhalten von Shutdown7 festlegen.", "Diese Funktionen sind teilweise erst ab Windows 7 verfügbar.", "Indem Sie diese Funktionen aktivieren, können Sie Shutdown7 über das Internet steuern.", "Bitte konfigurieren Sie Shutdown7 für die Serverfunktion.", "Hier können Sie die Integration mit Wakeup from Standby and Hibernate (WOSB) aktivieren. Mit diesem Programm können Sie ihren PC zu beliebigen Zeiten aus dem Standby oder Ruhezustand automatisch aufwecken lassen.\n\nLaden Sie hierzu WOSB von der Website des Entwicklers herunter und legen Sie die wosb.exe in das gleiche Verzeichnis wie Shutdown7.", "Stellen Sie die Aufwach-Zeiten für WOSB im Format hh:mm:ss ein.\nSie können Sie auch leer lassen.", "Erlauben Sie Shutdown7, anonymer Nutzungsstatistiken an den Entwickler zu senden.", "Die Einrichtung ist hiermit abgeschlossen.\nIch wünsche Ihnen viel Spaß mit Shutdown7.\n\nBitte senden Sie mir eine E-Mail, falls Shutdown7 nicht so funktionieren sollte,\nwie es sollte und erwägen Sie, eine kleine Spende für dieses kostenlose Programm zu entrichten.", }; checkAutostart.Content = "Benutze Autostart"; //checkAsk.Content = "Abfrage vor Shutdown"; checkForce.Content = "Shutdown erzwingen"; checkPinTaskbar.Content = "An Taskleiste anheften"; checkRemoteClient.Content = "Client-Funktionen"; checkRemoteServer.Content = "Server-Funktionen"; checkSendFeedback.Content = "Sende Nutzerstatistiken"; checkStayAfterShutdown.Content = "Bleibe Aktiv nach Ausführung"; checkWOSB.Content = "Benutze WOSB"; labelWOSBAM.Content = "Vormittag"; labelWOSBPM.Content = "Nachmittag"; labelWOSBTime2.Content = "Montag"; labelWOSBTime4.Content = "Dienstag"; labelWOSBTime6.Content = "Mittwoch"; labelWOSBTime8.Content = "Donnerstag"; labelWOSBTime10.Content = "Freitag"; labelWOSBTime12.Content = "Samstag"; labelWOSBTime14.Content = "Sonntag"; labelBugs.Text = "Behobene Bugs in dieser Version"; labelRemotePassword.Content = "Passwort:"; buttonPortCheck.Content = "Portweiterleitung testen"; buttonFirewallException.Content = "Windows Firewallausnahme"; buttonDownloadWOSB.Content = "Lade WOSB herunter"; buttonCheckWOSB.Content = "Prüfe, ob verfügbar"; buttonSendMail.Content = "Nachricht an den Entwickler"; buttonHelp.Content = "Online-Hilfe"; buttonDonate.Content = "Spenden"; //TTAsk.Text = "Abfrage vor Herunterfahren, Neustart, Logoff, Sperren, Standby und Hibernate, wenn kein Timeout angegeben wurde.\nNur über GUI wenn kein Countdown angegeben wurde,\nnicht über Jumplist oder Parametern"; TTForce.Text = "Erzwingt das Schließen aller offenen Programme.\nUngespeicherte Daten können verloren gehen."; //TTGlass.Text = "Alle Fenster sind semi-transparent.\nNur bei Windows Vista und Windows 7."; TTJumplist.Text = "Aktiviert die Jumplist (Rechtsklick auf Taskbar-Icon).\nVerfügbar ab Windows 7."; TTOverlay.Text = "Zeigt beim Countdown die letzten Zahlen im Taskbar-Icon an.\nVerfügbar ab Windows 7."; TTPinTaskbar.Text = "Heftet Shutdown7 für Schnellzugriffe an die Taskleiste an.\nVerfügbar ab Windows 7."; TTRemoteClient.Text = "Ermöglicht, andere Rechner mit Shutdown7 über das Internet zu steuern."; TTRemoteServer.Text = "Ermöglicht, über das Internet gesteuert zu werden.\nErfordert Ausnahme in der Firewall"; TTRemotePort.Text = "Auf diesem Port wird Shutdown7 später erreichbar sein."; TTRemotePassword.Text = "Zu Ihrer Sicherheit muss man ein Passwort eingeben, um eine Aktion über das Internet auszuführen."; TTSendFeedback.Text = "Die Daten sind anonymisiert und dienen nur Statistik-Zwecken.\nEs handelt sich hierbei nur um Informationen wie Betriebssystem, Sprache und Nutzungsweise."; TTStayAfterShutdown.Text = "Shutdown7 beendet sich nicht nach Ausführen einer Aktion."; TTSysicon.Text = "Zeigt ein Icon im Systray (unten rechts in der Taskleiste) an.\nDas Hauptfenster wird ins Systray minimiert."; Data.L["Skip"] = "Überspringen"; Data.L["Abort"] = "Abbrechen"; Data.L["Next"] = "Weiter"; Data.L["Complete"] = "Fertig stellen"; Data.L["ConfirmAbortWelcomeScreen"] = "Möchten Sie diesen Assistenten wirklich abbrechen?"; buttonAbort.Content = Data.L["Abort"]; buttonNext.Content = Data.L["Next"]; buttonBack.Content = "Zurück"; break; default: Titles = new string[] { "Welcome to Shutdown7", "New in version " + Data.Version, "Autostart", "Settings", "Windows 7 features", "Remote functions", "Remote-server settings", "WOSB", "WOSB settings", "User feedback", "Completed", }; Instructions = new string[] { "This wizard will help you to setup Shutdown7 for first use.", "New features in this version.", "If you like to, Shutdown7 starts everytime with Windows, so it's ready immediately. That's recommandable if you want to use the remote-server option.", "Here you can customize the behaviour of Shutdown7.", "Some of these features are shipped with Windows 7 only.", "If you activate these functions you can control Shutdown7 over the internet.", "Please configure the connection settings for the server-function.", "You can enable interaction with Wakeup from Standby and Hibernate (WOSB) here. This application allows you to automatically wake up your PC from standby or hibenation.\n\nTo do so, download WOSB from the developer's website and put the exe-file in the same directory as Shutdown7.", "Specify the wake-up times for WOSB in the format hh:mm:ss.\nYou can let them empty as well.", "Allow Shutdown7 to send anonymous user statistics to the developer.", "The setup is completed now.\nEnjoy Shutdown7.\n\nPlease send me an e-mail if Shutdown7 shouldn't work as expected\nand consider to donate a small amount for this free application.", }; checkAutostart.Content = "Use Autostart"; //checkAsk.Content = "Ask before shutdown"; checkForce.Content = "Force shutdown"; checkPinTaskbar.Content = "Pin to taskbar"; checkRemoteClient.Content = "Client-functions"; checkRemoteServer.Content = "Server-functions"; checkSendFeedback.Content = "Send usage statistics"; checkWOSB.Content = "Use WOSB"; labelWOSBAM.Content = "A.M."; labelWOSBPM.Content = "P.M."; labelWOSBTime2.Content = "Monday"; labelWOSBTime4.Content = "Tuesday"; labelWOSBTime6.Content = "Wednesday"; labelWOSBTime8.Content = "Thursday"; labelWOSBTime10.Content = "Friday"; labelWOSBTime12.Content = "Saturday"; labelWOSBTime14.Content = "Sunday"; labelBugs.Text = "Fixed bugs in this version"; labelRemotePassword.Content = "Password:"; buttonPortCheck.Content = "Test port-forwarding"; buttonFirewallException.Content = "Windows firewall exception"; buttonDownloadWOSB.Content = "Download WOSB"; buttonCheckWOSB.Content = "Check again"; buttonSendMail.Content = "Contact the developer"; buttonHelp.Content = "Online help"; buttonDonate.Content = "Donate"; //TTAsk.Text = "Confirm before shutdown, reboot, log off, lock, standby and hibernate, if no timeout is specified.\nGUI only, not via jumplist or parameters"; TTForce.Text = "Forces the closure of all open applications.\nUnsaved data may be lost."; //TTGlass.Text = "All windows are semi-transparent.\nWindows Vista and Windows 7 only."; TTJumplist.Text = "Activates the Jumplist (right click on the taskbar icon).\nAvailable from Windows 7."; TTOverlay.Text = "Shows the last countdown numbers in the taskbar icon.\nAvailable from Windows 7."; TTPinTaskbar.Text = "Pins Shutdown7 to your taskbar for quick access.\nAvailable from Windows 7."; TTRemoteClient.Text = "Control other computers with Shutdown7 via the internet."; TTRemoteServer.Text = "Enable control over the internet.\nRequires an exception in your firewall."; TTRemotePort.Text = "Shutdown7 will listen on this port."; TTRemotePassword.Text = "For your safety a password has to be entered to execute an action via the internet."; TTSendFeedback.Text = "The data will be anonymized and serves statistics only.\nIt will contain information like os version, language, usage type."; TTStayAfterShutdown.Text = "Shutdown does not close after execution."; TTSysicon.Text = "Shows an icon in the systray (on the right corner in the taskbar) .\nAlso the main window will be minimized into the systray."; Data.L["Next"] = "Next"; Data.L["Complete"] = "Complete"; Data.L["Skip"] = "Skip"; Data.L["Abort"] = "Cancel"; Data.L["ConfirmAbortWelcomeScreen"] = "Do you really want to cancel this wizard?"; buttonAbort.Content = Data.L["Abort"]; buttonNext.Content = Data.L["Next"]; buttonBack.Content = "Back"; break; } #endregion #region Changelog if (Data.News.Length > 0) { foreach (string curNews in Data.News) { TextBlock curTex = new TextBlock(); curTex.Text = curNews; curTex.TextWrapping = TextWrapping.Wrap; curTex.Padding = new Thickness(5, 0, 0, 0); Label curLab = new Label(); curLab.Content = curTex; Ellipse curEl = new Ellipse(); curEl.Height = 6; curEl.Width = 6; curEl.Margin = new Thickness(4, 0, 0, 0); curEl.Fill = Brushes.Black; curEl.Stroke = Brushes.Black; BulletDecorator curBullet = new BulletDecorator(); curBullet.Bullet = curEl; curBullet.Child = curLab; stackStep1.Children.Add(curBullet); } } if (Data.News.Length > 0 && Data.Bugs.Length > 0) { labelBugs.FontStyle = new FontStyle(); labelBugs.FontSize = 14; labelBugs.TextDecorations = TextDecorations.Underline; stackStep1.Children.Add(labelBugs); } else if (Data.News.Length == 0 && Data.Bugs.Length > 0) { Instructions[1] = (string)labelBugs.Text; } if (Data.Bugs.Length > 0) { foreach (string curBug in Data.Bugs) { TextBlock curTex = new TextBlock(); curTex.Text = curBug; curTex.TextWrapping = TextWrapping.Wrap; curTex.Padding = new Thickness(5, 0, 0, 0); Label curLab = new Label(); curLab.Content = curTex; Ellipse curEl = new Ellipse(); curEl.Height = 6; curEl.Width = 6; curEl.Margin = new Thickness(4, 0, 0, 0); curEl.Fill = Brushes.Black; curEl.Stroke = Brushes.Black; BulletDecorator curBullet = new BulletDecorator(); curBullet.Bullet = curEl; curBullet.Child = curLab; stackStep1.Children.Add(curBullet); } } #endregion if (welcome) ChangeScreen(0); else if (update) { if (File.Exists("Shutdown7.zip")) File.Delete("Shutdown7.zip"); if (File.Exists("UpdateHelper.exe")) File.Delete("UpdateHelper.exe"); if (File.Exists("Ionic.Zip.dll")) File.Delete("Ionic.Zip.dll"); ChangeScreen(1); } else Close(); } #region ChangeScreen void ChangeScreen(int curscreen) { //Message.Show(curscreen + ""); buttonNext.IsEnabled = true; buttonBack.IsEnabled = (curscreen != 0); labelTitle.Text = Titles[curscreen]; labelInstruction.Text = Instructions[curscreen]; if (curscreen == 0) { buttonAbort.Content = Data.L["Skip"]; skip = true; } else { buttonAbort.Content = Data.L["Abort"]; skip = false; } if (curscreen == 1) { if (Data.News.Length == 0 && Data.Bugs.Length == 0) { if (update) Close(); else curscreen++; } else { labelInstruction.TextDecorations = TextDecorations.Underline; stackStep1.Visibility = Visibility.Visible; } } else { labelInstruction.TextDecorations = null; stackStep1.Visibility = Visibility.Collapsed; } if (curscreen == 2) stackStep2.Visibility = Visibility.Visible; else stackStep2.Visibility = Visibility.Collapsed; if (curscreen == 3) stackStep3.Visibility = Visibility.Visible; else stackStep3.Visibility = Visibility.Collapsed; if (curscreen == 4) { /*if (Environment.OSVersion.Version.Major < 6) checkGlass.IsEnabled = false;*/ if (!Win7.IsWin7) { checkJumplist.IsEnabled = false; checkOverlay.IsEnabled = false; checkPinTaskbar.IsEnabled = false; } else { checkJumplist.IsEnabled = true; checkJumplist.IsChecked = true; checkOverlay.IsEnabled = true; checkOverlay.IsChecked = true; checkPinTaskbar.IsEnabled = true; if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Shutdown7.lnk")) checkPinTaskbar.IsChecked = true; else { checkPinTaskbar.IsEnabled = false; checkPinTaskbar.IsChecked = false; } } stackStep4.Visibility = Visibility.Visible; } else stackStep4.Visibility = Visibility.Collapsed; if (curscreen == 5) stackStep5.Visibility = Visibility.Visible; else stackStep5.Visibility = Visibility.Collapsed; if (curscreen == 6) { if (textRemotePort.Text.Length == 0 | textRemotePassword.Password.Length == 0) buttonNext.IsEnabled = false; stackStep6.Visibility = Visibility.Visible; } else stackStep6.Visibility = Visibility.Collapsed; if (curscreen == 7) { if (File.Exists(Data.WOSBPath)) { checkWOSB.IsEnabled = true; } else { checkWOSB.IsChecked = false; checkWOSB.IsEnabled = false; } stackStep7.Visibility = Visibility.Visible; } else stackStep7.Visibility = Visibility.Collapsed; if (curscreen == 8) stackStep8.Visibility = Visibility.Visible; else stackStep8.Visibility = Visibility.Collapsed; if (curscreen == 9) stackStep9.Visibility = Visibility.Visible; else stackStep9.Visibility = Visibility.Collapsed; if (curscreen == 10) stackStep10.Visibility = Visibility.Visible; else stackStep10.Visibility = Visibility.Collapsed; if (curscreen == Titles.Length - 1) { buttonNext.Content = Data.L["Complete"]; buttonAbort.IsEnabled = false; done = true; } else if (update & !welcome) { buttonNext.Content = Data.L["Complete"]; buttonBack.IsEnabled = false; buttonAbort.IsEnabled = false; done = true; } else { buttonNext.Content = Data.L["Next"]; buttonAbort.IsEnabled = true; done = false; } } private void buttonBack_Click(object sender, RoutedEventArgs e) { if (curscreen == 2 && Data.News.Length == 0 && Data.Bugs.Length == 0) curscreen--; if (curscreen == 7 && !(bool)checkRemoteServer.IsChecked) curscreen--; if (curscreen == 9 && !(bool)checkWOSB.IsChecked) curscreen--; curscreen--; ChangeScreen(curscreen); } private void buttonNext_Click(object sender, RoutedEventArgs e) { if (update) Close(); switch (curscreen) { case 2: Data.S["Autostart"] = (bool)checkAutostart.IsChecked; break; case 3: //Data.S["Ask"] = (bool)checkAsk.IsChecked; Data.S["Force"] = (bool)checkForce.IsChecked; Data.S["StayAfterShutdown"] = (bool)checkStayAfterShutdown.IsChecked; Data.S["SysIcon"] = (bool)checkSysicon.IsChecked; break; case 4: Data.S["Jumplist"] = (bool)checkJumplist.IsChecked; Data.S["Overlay"] = (bool)checkOverlay.IsChecked; //Data.S["Glass"] = (bool)checkGlass.IsChecked; if ((bool)checkPinTaskbar.IsChecked) { new Thread(Win7.PinToTaskbar).Start(); } break; case 5: Data.S["RemoteClient"] = (bool)checkRemoteClient.IsChecked; Data.S["RemoteServer"] = (bool)checkRemoteServer.IsChecked; if (!(bool)checkRemoteServer.IsChecked) curscreen++; break; case 6: if (!Int32.TryParse(textRemotePort.Text, out Data.RemotePort) | (Data.RemotePort < 1024 | Data.RemotePort > 65535)) { MessageBox.Show(Data.L["RemotePortMissing"], "Shutdown7", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } if (textRemotePassword.Password.Length == 0) { MessageBox.Show(Data.L["RemotePasswordMissing"], "Shutdown7", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } Data.RemotePassword = Remote.md5(textRemotePassword.Password); break; case 7: Data.S["WOSB"] = (bool)checkWOSB.IsChecked; if (!(bool)checkWOSB.IsChecked) curscreen++; else { Data.W.Add("Default", new Dictionary<string, string>()); Data.curProfile = "Default"; } break; case 8: Data.W["Default"]["Mo1"] = textWOSBTime1.Text; Data.W["Default"]["Mo2"] = textWOSBTime2.Text; Data.W["Default"]["Th1"] = textWOSBTime3.Text; Data.W["Default"]["Th2"] = textWOSBTime4.Text; Data.W["Default"]["We1"] = textWOSBTime5.Text; Data.W["Default"]["We2"] = textWOSBTime6.Text; Data.W["Default"]["Th1"] = textWOSBTime7.Text; Data.W["Default"]["Th2"] = textWOSBTime8.Text; Data.W["Default"]["Fr1"] = textWOSBTime9.Text; Data.W["Default"]["Fr2"] = textWOSBTime10.Text; Data.W["Default"]["Sa1"] = textWOSBTime11.Text; Data.W["Default"]["Sa2"] = textWOSBTime12.Text; Data.W["Default"]["Su1"] = textWOSBTime13.Text; Data.W["Default"]["Su2"] = textWOSBTime14.Text; Data.W["Default"]["File"] = ""; Data.W["Default"]["Params"] = ""; Data.W["Default"]["AwFile"] = ""; Data.W["Default"]["AwParams"] = ""; Data.W["Default"]["Extra"] = ""; break; case 9: Data.S["SendFeedback"] = (bool)checkSendFeedback.IsChecked; break; default: break; } if (curscreen == Titles.Length - 1) { Data.RemoteServers = new string[] { "127.0.0.1" }; Data.RemoteMacs = new string[] { }; foreach (NetworkInterface CurMac in NetworkInterface.GetAllNetworkInterfaces()) if (CurMac.OperationalStatus == OperationalStatus.Up) if (CurMac.GetPhysicalAddress().ToString().Length > 0) { Array.Resize(ref Data.RemoteMacs, Data.RemoteMacs.Length + 1); Data.RemoteMacs[Data.RemoteMacs.Length - 1] = CurMac.GetPhysicalAddress().ToString(); } Xml.Write(); if ((bool)checkWOSB.IsChecked) Xml.WriteWOSB(); Close(); } else { curscreen++; ChangeScreen(curscreen); } } #endregion #region Close private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (!done & !skip) { try { TaskDialog td = new TaskDialog(); td.Caption = "Shutdown7"; td.InstructionText = Data.L["Cancel"]; td.Text = Data.L["ConfirmAbortWelcomeScreen"]; td.Icon = TaskDialogStandardIcon.Warning; td.StandardButtons = TaskDialogStandardButtons.No | TaskDialogStandardButtons.Cancel; td.Cancelable = true; if (td.Show() == TaskDialogResult.No) { e.Cancel = true; return; } } catch { if (MessageBox.Show(Data.L["ConfirmAbortWelcomeScreen"], "Shutdown7", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No) { e.Cancel = true; return; } } } Xml.Write(); ProcessStartInfo p = new ProcessStartInfo(); p.FileName = Data.EXE; p.WorkingDirectory = Directory.GetCurrentDirectory(); p.Verb = "runas"; Process.Start(p); //Message.Show(L["RequireAdmin"], "Error"); Environment.Exit(0); } #endregion #region Events private void buttonAbort_Click(object sender, RoutedEventArgs e) { this.Close(); } #region Remote private void textRemotePort_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) { e.Handled = !Char.IsDigit(Convert.ToChar(e.Text)); } private void textRemotePort_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if (stackStep6.Visibility != Visibility.Visible) return; int y; if (!Int32.TryParse(textRemotePort.Text, out y) | (y < 1024 | y > 65535) | textRemotePassword.Password.Length == 0) buttonNext.IsEnabled = false; else buttonNext.IsEnabled = true; } private void textRemotePassword_PasswordChanged(object sender, RoutedEventArgs e) { int y; if (!Int32.TryParse(textRemotePort.Text, out y) | (y < 1024 | y > 65535) | textRemotePassword.Password.Length == 0) buttonNext.IsEnabled = false; else buttonNext.IsEnabled = true; } private void textRemotePassword_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { textRemotePassword.Password = ""; } private void buttonPortCheck_Click(object sender, RoutedEventArgs e) { buttonPortCheck.IsEnabled = false; Thread t = new Thread(new ParameterizedThreadStart(new Settings().Portcheck)); t.Start(textRemotePort.Text); new Thread(new ParameterizedThreadStart(WaiterHelper)).Start(t); } void WaiterHelper(object _t) { Thread t = (Thread)_t; while (t.IsAlive) { Thread.Sleep(100); } Dispatcher.Invoke((Action)delegate { buttonPortCheck.IsEnabled = true; }); } private void buttonFirewallException_Click(object sender, RoutedEventArgs e) { buttonFirewallException.IsEnabled = false; new Settings().FirewallException(); buttonFirewallException.IsEnabled = true; } #endregion #region WOSB private void buttonDownloadWOSB_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.dennisbabkin.com/php/download.php?what=WOSB"); } private void buttonCheckWOSB_Click(object sender, RoutedEventArgs e) { if (File.Exists(Data.WOSBPath)) { checkWOSB.IsEnabled = true; } else { checkWOSB.IsChecked = false; checkWOSB.IsEnabled = false; } } #endregion #region Websites private void buttonSendMail_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.shutdown7.com/kontakt.php?lang=" + Data.Lang); } private void buttonHelp_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.shutdown7.com/help.php?lang=" + Data.Lang); } private void buttonDonate_Click(object sender, RoutedEventArgs e) { Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=10883669"); } #endregion #endregion #region Aero protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); Win7.Glass(this); } #endregion } } <file_sep>/Xml.cs using System; using System.Collections.Generic; using System.IO; using System.Windows; using System.Xml; namespace Shutdown7 { class Xml { public static string Path = System.IO.Path.GetDirectoryName(Data.EXE) + "\\Shutdown7.xml"; public static string WOSBPath = System.IO.Path.GetDirectoryName(Data.EXE) + "\\wosb.xml"; public static void Read() { try { if (!File.Exists(Path)) throw new FileNotFoundException(); XmlTextReader Reader = new XmlTextReader(Path); Reader.Read(); Reader.Read(); //xml Deklaration überspringen XmlNodeType curType; string curName = "", curValue = ""; while (Reader.Read()) { Reader.MoveToElement(); curType = Reader.NodeType; curName = Reader.Name; switch (curType) { case XmlNodeType.Element: break; case XmlNodeType.Text: curValue = Reader.Value; break; case XmlNodeType.EndElement: //if (Data.debug_verbose) //Message.Show(curName + "\n" + curValue); switch (curName) { case "Server": Array.Resize(ref Data.RemoteServers, Data.RemoteServers.Length + 1); Data.RemoteServers[Data.RemoteServers.Length - 1] = curValue; break; case "Mac": Array.Resize(ref Data.RemoteMacs, Data.RemoteMacs.Length + 1); Data.RemoteMacs[Data.RemoteMacs.Length - 1] = curValue; break; case "RemotePort": Data.RemotePort = Int32.Parse(curValue); break; case "RemotePassword": Data.RemotePassword = <PASSWORD>; break; case "LastVersion": try { Data.LastVersion = new Version(curValue); } catch { Data.LastVersion = new Version(1, 0, 0, 0); } break; case "Shutdown7": case "LastAction": case "Parameters": Reader.Read(); break; case "Mode": Data.Mode = (Data.Modes) Enum.Parse(typeof(Data.Modes), curValue); break; case "Condition": Data.Condition = (Data.Conditions) Enum.Parse(typeof(Data.Conditions), curValue); break; case "t": Data.t = TimeSpan.FromSeconds(Int32.Parse(curValue)); break; case "ProcessName": Data.ProcessName = curValue; break; case "FileName": Data.FileName = curValue; break; case "LaunchFile": Data.LaunchFile = curValue; break; case "NetworkAdapter": Data.NetworkAdapter = curValue; break; case "Network": Data.NetworkAdapter = curValue; break; case "CpuValue": Data.CpuValue = Int32.Parse(curValue); break; case "CpuMode": Data.CpuMode = Boolean.Parse(curValue); break; default: if (Data.S.ContainsKey(curName)) Data.S.Remove(curName); Data.S.Add(curName, Convert.ToBoolean(curValue)); break; } curValue = ""; break; default: Reader.Read(); break; } } Reader.Close(); } catch (Exception e) { Message.Show(Data.L["XmlReadError_1"] + String.Format(Data.L["XmlReadError_2"], e.Message), "Error", "Error"); Environment.Exit(0); } } public static void Write() { XmlTextWriter Writer = new XmlTextWriter(Path, null); Writer.Formatting = Formatting.Indented; Writer.WriteStartDocument(); Writer.WriteStartElement("Shutdown7"); foreach (KeyValuePair<string, bool> kvp in Data.S) { //Message.Show(kvp.Key + kvp.Value.ToString()); Writer.WriteStartElement(kvp.Key); Writer.WriteValue(kvp.Value); Writer.WriteEndElement(); } Writer.WriteStartElement("RemoteServers"); foreach (string RemoteServer in Data.RemoteServers) { Writer.WriteStartElement("Server"); Writer.WriteValue(RemoteServer); Writer.WriteEndElement(); } Writer.WriteEndElement(); Writer.WriteStartElement("RemoteMacs"); foreach (string RemoteMac in Data.RemoteMacs) { Writer.WriteStartElement("Mac"); Writer.WriteValue(RemoteMac); Writer.WriteEndElement(); } Writer.WriteEndElement(); Writer.WriteStartElement("RemotePort"); Writer.WriteValue(Data.RemotePort); Writer.WriteEndElement(); Writer.WriteStartElement("RemotePassword"); Writer.WriteValue(Data.RemotePassword); Writer.WriteEndElement(); Writer.WriteStartElement("LastVersion"); Writer.WriteValue(Data.CurVersion.ToString()); Writer.WriteEndElement(); // *** Writer.WriteStartElement("LastAction"); if (Data.S["ResumeLastAction"]) { Writer.WriteStartElement("Mode"); Writer.WriteValue(Data.Mode.ToString()); Writer.WriteEndElement(); Writer.WriteStartElement("Condition"); Writer.WriteValue(Data.Condition.ToString()); Writer.WriteEndElement(); Writer.WriteStartElement("Parameters"); Writer.WriteStartElement("t"); Writer.WriteValue(Data.t.TotalSeconds); Writer.WriteEndElement(); Writer.WriteStartElement("ProcessName"); Writer.WriteValue(Data.ProcessName); Writer.WriteEndElement(); Writer.WriteStartElement("FileName"); Writer.WriteValue(Data.FileName); Writer.WriteEndElement(); Writer.WriteStartElement("LaunchFile"); Writer.WriteValue(Data.LaunchFile); Writer.WriteEndElement(); Writer.WriteStartElement("NetworkAdapter"); Writer.WriteValue(Data.NetworkAdapter); Writer.WriteEndElement(); Writer.WriteStartElement("Network"); Writer.WriteValue(Data.Network); Writer.WriteEndElement(); Writer.WriteStartElement("CpuValue"); Writer.WriteValue(Data.CpuValue); Writer.WriteEndElement(); Writer.WriteStartElement("CpuMode"); Writer.WriteValue(Data.CpuMode); Writer.WriteEndElement(); Writer.WriteEndElement(); Writer.WriteEndElement(); } Writer.WriteEndElement(); Writer.WriteEndDocument(); Writer.Close(); } public static void ReadWOSB() { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(WOSBPath); XmlNode Profiles = xmlDoc.DocumentElement.ChildNodes[0]; foreach (XmlNode _curProfile in Profiles.ChildNodes) { string curProfile = _curProfile.Attributes[0].Value; bool isActive = Convert.ToBoolean(_curProfile.Attributes[1].Value); if (Data.W.ContainsKey(curProfile)) Data.W.Remove(curProfile); Data.W.Add(curProfile, new Dictionary<string, string>()); foreach (XmlElement curDay in _curProfile.ChildNodes[0].ChildNodes) { ReadWakeupTimes(curProfile, curDay.ChildNodes); } foreach (XmlElement curSetting in _curProfile.ChildNodes) { //Times-Element ignorieren if (Data.W[curProfile].ContainsKey(curSetting.Name)) Data.W[curProfile].Remove(curSetting.Name); Data.W[curProfile].Add(curSetting.Name, curSetting.InnerText); } if (isActive) Data.curProfile = curProfile; //sichert, dass ein Profil aktiviert wird, wenn alle auf inaktiv stehen if (String.IsNullOrEmpty(Data.curProfile)) Data.curProfile = curProfile; } //es existiert keine wosb.xml if (String.IsNullOrEmpty(Data.curProfile)) { Data.W.Add("Default", new Dictionary<string, string>()); Data.curProfile = "Default"; } /*if (Data.debug_verbose) { foreach (KeyValuePair<Dictionary, string> kvp in Data.W) { Message.Show(kvp.Key + " " + kvp.Value); } }*/ } catch (Exception e) { Message.Show(Data.L["XmlReadError_1"] + String.Format(Data.L["XmlReadError_2"], e.Message + e.StackTrace + e.GetType()), "Error"); Application.Current.Shutdown(); } } static void ReadWakeupTimes(string curProfile, XmlNodeList curDay) { try { string curWeekday = "", curTime = ""; for (int i = 0; i < curDay.Count; i++) { curWeekday = curDay[i].ParentNode.Name.Substring(0, 2) + (i + 1); curTime = curDay[i].InnerText; //if (Data.debug_verbose) Message.Show(curWeekday + " " + curTime); if (Data.W[curProfile].ContainsKey(curWeekday)) Data.W[curProfile].Remove(curWeekday); Data.W[curProfile].Add(curWeekday, curTime); } } catch (Exception e) { Message.Show(Data.L["XmlReadError_1"] + String.Format(Data.L["XmlReadError_2"], e.Message + e.StackTrace + e.GetType()), "Error"); Application.Current.Shutdown(); } } public static void WriteWOSB() { XmlTextWriter Writer = new XmlTextWriter(WOSBPath, null); Writer.Formatting = Formatting.Indented; Writer.WriteStartDocument(); Writer.WriteStartElement("Shutdown7"); Writer.WriteStartElement("Profiles"); foreach (KeyValuePair<string, Dictionary<string, string>> curProfile in Data.W) { Writer.WriteStartElement("Profile"); Writer.WriteAttributeString("Name", curProfile.Key); Writer.WriteAttributeString("Active", (Data.curProfile == curProfile.Key).ToString()); /*foreach (DayOfWeek DayofWeek in Enum.GetValues(typeof(DayOfWeek))) { //Beginnt mit Sonntag! Message.Show(DayofWeek.ToString()); WriteWakeupTimes(Writer, DayofWeek); }*/ Writer.WriteStartElement("Times"); WriteWakeupTimes(Writer, curProfile.Key, "Monday"); WriteWakeupTimes(Writer, curProfile.Key, "Tuesday"); WriteWakeupTimes(Writer, curProfile.Key, "Wednesday"); WriteWakeupTimes(Writer, curProfile.Key, "Thursday"); WriteWakeupTimes(Writer, curProfile.Key, "Friday"); WriteWakeupTimes(Writer, curProfile.Key, "Saturday"); WriteWakeupTimes(Writer, curProfile.Key, "Sunday"); Writer.WriteEndElement(); Writer.WriteStartElement("File"); Writer.WriteValue(Data.W[curProfile.Key]["File"]); Writer.WriteEndElement(); Writer.WriteStartElement("Params"); Writer.WriteValue(Data.W[curProfile.Key]["Params"]); Writer.WriteEndElement(); Writer.WriteStartElement("AwFile"); Writer.WriteValue(Data.W[curProfile.Key]["AwFile"]); Writer.WriteEndElement(); Writer.WriteStartElement("AwParams"); Writer.WriteValue(Data.W[curProfile.Key]["AwParams"]); Writer.WriteEndElement(); Writer.WriteStartElement("Extra"); Writer.WriteValue(Data.W[curProfile.Key]["Extra"]); Writer.WriteEndElement(); Writer.WriteEndElement(); } Writer.WriteEndElement(); Writer.WriteEndElement(); Writer.WriteEndDocument(); Writer.Close(); } static void WriteWakeupTimes(XmlWriter Writer, string curProfile, string Day) { Writer.WriteStartElement(Day); foreach (KeyValuePair<string, string> kvp in Data.W[curProfile]) { if (kvp.Key.StartsWith(Day.Substring(0, 2)) & kvp.Value != "") { Writer.WriteStartElement("Time"); Writer.WriteValue(kvp.Value); Writer.WriteEndElement(); } } Writer.WriteEndElement(); } public static void MigrateIni() { Ini.Read(); Xml.Write(); System.IO.File.Delete(Ini.Path); } public static void MigrateWOSBIni() { Data.W.Add("Default", new Dictionary<string, string>()); Data.W["Default"]["Mo1"] = ""; Data.W["Default"]["Mo2"] = ""; Data.W["Default"]["Mo3"] = ""; Data.W["Default"]["Mo4"] = ""; Data.W["Default"]["Tu1"] = ""; Data.W["Default"]["Tu2"] = ""; Data.W["Default"]["Tu3"] = ""; Data.W["Default"]["Tu4"] = ""; Data.W["Default"]["We1"] = ""; Data.W["Default"]["We2"] = ""; Data.W["Default"]["We3"] = ""; Data.W["Default"]["We4"] = ""; Data.W["Default"]["Th1"] = ""; Data.W["Default"]["Th2"] = ""; Data.W["Default"]["Th3"] = ""; Data.W["Default"]["Th4"] = ""; Data.W["Default"]["Fr1"] = ""; Data.W["Default"]["Fr2"] = ""; Data.W["Default"]["Fr3"] = ""; Data.W["Default"]["Fr4"] = ""; Data.W["Default"]["Sa1"] = ""; Data.W["Default"]["Sa2"] = ""; Data.W["Default"]["Sa3"] = ""; Data.W["Default"]["Sa4"] = ""; Data.W["Default"]["Su1"] = ""; Data.W["Default"]["Su2"] = ""; Data.W["Default"]["Su3"] = ""; Data.W["Default"]["Su4"] = ""; Data.W["Default"]["File"] = ""; Data.W["Default"]["Params"] = ""; Data.W["Default"]["AwFile"] = ""; Data.W["Default"]["AwParams"] = ""; Data.W["Default"]["Extra"] = ""; Data.curProfile = "Default"; Ini.ReadWOSB(); Xml.WriteWOSB(); System.IO.File.Delete(Ini.WOSBPath); } } } <file_sep>/PacMan.xaml.cs using System; using System.Windows; namespace Shutdown7 { /// <summary> /// Interaktionslogik für PacMan.xaml /// </summary> public partial class PacMan : Window { public PacMan() { InitializeComponent(); webbrowser.Navigate(new Uri("http://old.mariuslutz.de/pacman/")); } #region Aero protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); Win7.Glass(this, new Thickness(2)); } #endregion private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { webbrowser.Dispose(); } } } <file_sep>/Settings.xaml.cs using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using Microsoft.Win32; using Microsoft.WindowsAPICodePack.Dialogs; using Microsoft.WindowsAPICodePack.Shell; using System.Collections.Generic; using Microsoft.Win32.TaskScheduler; namespace Shutdown7 { public partial class Settings : Window { public Settings() { InitializeComponent(); #region Settings checkAllProcesses.IsChecked = Data.S["AllProcesses"]; checkAsk.IsChecked = Data.S["Ask"]; checkAutostart.IsChecked = Autostart.IsAutoStartEnabled("Shutdown", Assembly.GetExecutingAssembly().Location + " /Run"); checkForce.IsChecked = Data.S["Force"]; checkGlass.IsChecked = Data.S["Glass"]; checkHybrid.IsChecked = Data.S["Win8Hybrid"]; checkIPv4.IsChecked = Data.S["IPv4"]; checkJumplist.IsChecked = Data.S["Jumplist"]; checkOverlay.IsChecked = Data.S["Overlay"]; checkModusIcons.IsChecked = Data.S["ModusIcons"]; checkRemoteClient.IsChecked = Data.S["RemoteClient"]; checkRemoteServer.IsChecked = Data.S["RemoteServer"]; checkSaveWindowState.IsChecked = Data.S["SaveWindowState"]; checkSendFeedback.IsChecked = Data.S["SendFeedback"]; checkStay.IsChecked = Data.S["StayAfterShutdown"]; checkSystray.IsChecked = Data.S["SysIcon"]; checkThumbnailToolbar.IsChecked = Data.S["ThumbnailToolbar"]; checkWakeOnLan.IsChecked = Data.S["WakeOnLan"]; checkWOSB.IsChecked = Data.S["WOSB"]; if (Data.RemotePort > 1024 && Data.RemotePort < 65535) textRemotePort.Items.Add(Data.RemotePort.ToString()); if (Data.RemotePort != 5556) textRemotePort.Items.Add("5556"); if (Data.RemotePort != 80) textRemotePort.Items.Add("80"); if (Data.RemotePort != 8080) textRemotePort.Items.Add("8080"); textRemotePort.SelectedItem = textRemotePort.Items[0]; textRemotePassword.Password = <PASSWORD>; #endregion #region Checkboxen if (Environment.OSVersion.Version.Major >= 6 & Environment.OSVersion.Version.Minor >= 2) checkHybrid.IsEnabled = true; else { checkHybrid.IsEnabled = false; checkHybrid.IsChecked = false; } if (File.Exists(Data.WOSBPath)) { checkWOSB.IsEnabled = true; } else { checkWOSB.IsEnabled = false; checkWOSB.IsChecked = false; } if ((bool)checkWOSB.IsChecked) ActivateWOSBUI(); else DeactivateWOSBUI(); if (Win7.IsWin7) { checkJumplist.IsEnabled = true; checkOverlay.IsEnabled = true; checkThumbnailToolbar.IsEnabled = true; } else { checkJumplist.IsChecked = false; checkJumplist.IsEnabled = false; checkOverlay.IsChecked = false; checkOverlay.IsEnabled = false; checkThumbnailToolbar.IsChecked = false; checkThumbnailToolbar.IsEnabled = false; } if (Environment.OSVersion.Version.Major >= 6) checkGlass.IsEnabled = true; else checkGlass.IsEnabled = false; if (Data.S["RemoteClient"]) { checkWakeOnLan.IsEnabled = true; checkIPv4.IsEnabled = true; } else { checkWakeOnLan.IsChecked = false; checkWakeOnLan.IsEnabled = false; checkIPv4.IsChecked = false; checkIPv4.IsEnabled = false; } if (Data.S["RemoteServer"]) { textRemotePort.IsEnabled = true; textRemotePassword.IsEnabled = true; buttonPortCheck.IsEnabled = true; buttonFirewallException.IsEnabled = true; } else { textRemotePort.IsEnabled = false; textRemotePassword.IsEnabled = false; buttonPortCheck.IsEnabled = false; buttonFirewallException.IsEnabled = false; } #endregion #region WOSB if (File.Exists(Xml.WOSBPath)) { Xml.ReadWOSB(); foreach (KeyValuePair<string, Dictionary<string, string>> kvp in Data.W) { comboProfiles.Items.Add(kvp.Key); } comboProfiles.SelectedItem = Data.curProfile; } #endregion #region Lang this.Title = Data.L["Settings"]; switch (Data.Lang) { case "de": TabAppearance.Header = "Aussehen"; TabWOSB.Header = "WOSB"; TabMiscellaneous.Header = "Sonstiges"; checkAllProcesses.Content = "Alle Prozesse anzeigen"; checkAsk.Content = "Abfrage vor Shutdown"; checkForce.Content = "Shutdown erzwingen"; checkHybrid.Content = "Hybrid-Shutdown"; checkStay.Content = "Bleibe nach Ausführen aktiv"; checkIPv4.Content = "IPv4 Kompatibilität"; checkModusIcons.Content = "Icons in Modus-Auswahl"; checkSendFeedback.Content = "Sende Nutzerstatistiken"; checkSaveWindowState.Content = "Speichere Fensterposition"; checkWOSB.Content = "Benutze WOSB"; labelRestart.Content = "Ein Neustart ist erforderlich, damit alle Einstellungen wirksam werden."; labelProfiles.Content = "Profile"; labelWOSBTimes.Header = "Weckzeiten"; labelWOSBDay1.Content = "Montag"; labelWOSBDay2.Content = "Dienstag"; labelWOSBDay3.Content = "Mittwoch"; labelWOSBDay4.Content = "Donnerstag"; labelWOSBDay5.Content = "Freitag"; labelWOSBDay6.Content = "Samstag"; labelWOSBDay7.Content = "Sonntag"; labelWOSBProg1.Content = "Programm1"; labelWOSBProg2.Content = "Programm2"; labelWOSBArgs1.Content = "Argumente"; labelWOSBArgs2.Content = "Argumente"; labelWOSBExtra.Content = "Extra-Args"; labelRemotePassword.Content = "<PASSWORD>:"; buttonPortCheck.Content = "Portweiterleitung testen"; buttonFirewallException.Content = "Windows Firewallausnahme"; buttonAddProfile.Content = "Hinzufügen"; buttonDeleteProfile.Content = "Löschen"; buttonWOSBProg1.Content = Data.L["Browse"]; buttonWOSBProg2.Content = Data.L["Browse"]; TTHForce.Text = (string)checkForce.Content; TTForce.Text = "Erzwingt das Schließen aller offenen Programme. Ungespeicherte Daten können verloren gehen."; TTHAsk.Text = "Abfrage vor Shutdown"; TTAsk.Text = "Abfrage vor Herunterfahren, Neustart, Logoff, Sperren, Standby und Hibernate, wenn kein Timeout angegeben wurde.\nNur über GUI, nicht über Jumplist oder Parametern"; TTHHybrid.Text = (string)checkHybrid.Content; TTHybrid.Text = "Benutze Hybridshutdown. Erst ab Windows 8."; TTHStay.Text = (string)checkStay.Content; TTStay.Text = "Shutdown7 beendet sich nicht nach Ausführen einer Aktion"; TTHAllProcesses.Text = (string)checkAllProcesses.Content; TTAllProcesses.Text = "Es werden alle Prozesse aufgelistet, auch die nicht sichtbaren."; TTHWOSB.Text = "Benutze WOSB"; TTWOSB.Text = "Schaltet Integrationsfeatures mit WOSB (Wakeup from Standby and Hibernate) frei.\nwosb.exe muss im gleichen Verzeichnis liegen."; TTHSystray.Text = "Systrayicon"; TTSystray.Text = "Zeigt ein Icon im Systray (unten rechts in der Taskleiste) an."; TTHSaveWindowState.Text = (string)checkSaveWindowState.Content; TTSaveWindowState.Text = "Speichert die Fensterposition zwischen Sessionen."; TTHModusIcons.Text = "Modus Icons"; TTModusIcons.Text = "Zeigt Icons in Modus-Auswahlbox an."; TTHGlass.Text = "Aero Glass"; TTGlass.Text = "Alle Fenster sind transparent.\nVerfügbar ab Windows Vista."; TTHOverlay.Text = "Overlayicon"; TTOverlay.Text = "Zeigt beim Countdown die letzten Zahlen im Taskbaricon an.\nVerfügbar ab Windows 7."; TTHJumplist.Text = "Jumplist"; TTJumplist.Text = "Aktiviert die Jumplist (Rechtsklick auf Taskbar-Icon).\nVerfügbar ab Windows 7."; TTHThumbnailToolbar.Text = "Thumbnail Toolbar"; TTThumbnailToolbar.Text = "Zeigt in der Fenstervorschau in der Taskleiste Icons zum schnellen Ausführen der Aktionen.\nVerfügbar ab Windows 7."; TTHRemoteClient.Text = "Client"; TTRemoteClient.Text = "Client-Funktionen"; TTHRemoteServer.Text = "Server"; TTRemoteServer.Text = "Server-Funktionen"; TTHWakeOnLan.Text = (string)checkWakeOnLan.Content; TTWakeOnLan.Text = "Aktiviert die Wake on Lan-Funktion."; TTHIPv4.Text = (string)checkIPv4.Content; TTIPv4.Text = "Aktivieren Sie diese Option, wenn Remoteshutdown nicht funktioniert oder Ihr PC IPv6 nicht unterstützt."; TTHAutostart.Text = (string)checkAutostart.Content; TTAutostart.Text = "Lädt dieses Programm bei jedem Start von Windows."; TTHSendFeedback.Text = "Sende Nutzungsstatistiken"; TTSendFeedback.Text = "Sende anonyme Nutzungsstatistiken an den Entwickler.\nDie Daten sind anonymisiert und dienen nur Statistik-Zwecken.\nEs handelt sich hierbei nur um Informationen wie Betriebssystem, Sprache und Nutzungsdauer und -art."; AbortButton.Content = "Abbrechen"; ApplyButton.Content = "Übernehmen"; break; default: TabAppearance.Header = "Appearance"; TabWOSB.Header = "WOSB"; TabMiscellaneous.Header = "Miscellaneous"; checkAllProcesses.Content = "Show all processes"; checkAsk.Content = "Ask before shutdown"; checkForce.Content = "Force shutdown"; checkHybrid.Content = "Use hybrid shutdown. Only for Windows 8."; checkStay.Content = "Stay active after execution"; checkIPv4.Content = "IPv4 Compatibility"; checkModusIcons.Content = "Icons in modus selector"; checkSendFeedback.Content = "Send usage statistics"; checkSaveWindowState.Content = "Save window position"; checkWOSB.Content = "Use WOSB"; labelRestart.Content = "A restart is required to apply all settings."; labelProfiles.Content = "Profiles"; labelWOSBTimes.Header = "Wakeup Times"; labelWOSBDay1.Content = "Monday"; labelWOSBDay2.Content = "Tuesday"; labelWOSBDay3.Content = "Wednesday"; labelWOSBDay4.Content = "Thursday"; labelWOSBDay5.Content = "Friday"; labelWOSBDay6.Content = "Saturday"; labelWOSBDay7.Content = "Sunday"; labelWOSBProg1.Content = "Application1"; labelWOSBProg2.Content = "Application2"; labelWOSBArgs1.Content = "Arguments"; labelWOSBArgs2.Content = "Arguments"; labelWOSBExtra.Content = "Additional Arguments"; labelRemotePassword.Content = "Password:"; buttonPortCheck.Content = "Test port-forwarding"; buttonFirewallException.Content = "Windows firewall exception"; buttonAddProfile.Content = "Add"; buttonDeleteProfile.Content = "Delete"; buttonWOSBProg1.Content = Data.L["Browse"]; buttonWOSBProg2.Content = Data.L["Browse"]; TTHForce.Text = (string)checkForce.Content; TTForce.Text = "Forces closure of all open programs. Unsaved data may be lost."; TTHAsk.Text = "Ask before shutdown"; TTAsk.Text = "Confirm before shutdown, reboot, log off, lock, standby and hibernate, if no timeout is specified.\nGUI only, not via jumplist or parameters."; TTHHybrid.Text = (string)checkHybrid.Content; TTHybrid.Text = "Hybrid shutdown"; TTHStay.Text = (string)checkStay.Content; TTStay.Text = "Shutdown does not close after execution."; TTHAllProcesses.Text = (string)checkAllProcesses.Content; TTAllProcesses.Text = "List all processes, invisible too."; TTHWOSB.Text = "Use WOSB"; TTWOSB.Text = "Activate intigration with WOSB (Wakeup from Standby and Hibernate).\nwosb.exe has to be in same directory."; TTHSystray.Text = "Systrayicon"; TTSystray.Text = "Shows a systray icon (bottom right in the taskbar)."; TTHSaveWindowState.Text = (string) checkSaveWindowState.Content; TTSaveWindowState.Text = "Save window position between sessions."; TTHGlass.Text = "Aero Glass"; TTGlass.Text = "All windows are semi-transparent.\nAvailbale from Windows Vistay."; TTHModusIcons.Text = "Mode icons"; TTModusIcons.Text = "Display icons in the modus selector."; TTHOverlay.Text = "Overlayicon"; TTOverlay.Text = "Shows the last 10 seconds the countdown in the taskbar while counting down.\nAvailbale from Windows 7."; TTHJumplist.Text = "Jumplist"; TTJumplist.Text = "Activates jumplist (Right click on taskbar icon).\nAvailbale from Windows 7."; TTHThumbnailToolbar.Text = "Thumbnail Toolbar"; TTThumbnailToolbar.Text = "Shows shutdown icons in window preview to access functions faster.\nAvailbale from Windows 7."; TTHRemoteClient.Text = "Client"; TTRemoteClient.Text = "Client-functions"; TTHRemoteServer.Text = "Server"; TTRemoteServer.Text = "Server-functions"; TTHWakeOnLan.Text = (string)checkWakeOnLan.Content; TTWakeOnLan.Text = "Activates Wake on Lan function."; TTHIPv4.Text = (string)checkIPv4.Content; TTIPv4.Text = "Activate if Remote Shutdown doesn't work or your PC doesn't support IPv6."; TTHAutostart.Text = (string)checkAutostart.Content; TTAutostart.Text = "Loads this program every time Windows boots."; TTHSendFeedback.Text = "Send usage statistics"; TTSendFeedback.Text = "Allow Shutdown7 to send anonymous user statistics to the developer.\nThe data will be anonymized and serves statistics only.\nIt will contain information like os version, language, usage time and -type."; AbortButton.Content = "Abort"; ApplyButton.Content = "Apply"; break; } #endregion } void LoadWakeupTimes(string curProfile) { textWOSBTimeMo1.Value = null; textWOSBTimeMo2.Value = null; textWOSBTimeMo3.Value = null; textWOSBTimeMo4.Value = null; textWOSBTimeTu1.Value = null; textWOSBTimeTu2.Value = null; textWOSBTimeTu3.Value = null; textWOSBTimeTu4.Value = null; textWOSBTimeWe1.Value = null; textWOSBTimeWe2.Value = null; textWOSBTimeWe3.Value = null; textWOSBTimeWe4.Value = null; textWOSBTimeTh1.Value = null; textWOSBTimeTh2.Value = null; textWOSBTimeTh3.Value = null; textWOSBTimeTh4.Value = null; textWOSBTimeFr1.Value = null; textWOSBTimeFr2.Value = null; textWOSBTimeFr3.Value = null; textWOSBTimeFr4.Value = null; textWOSBTimeSa1.Value = null; textWOSBTimeSa2.Value = null; textWOSBTimeSa3.Value = null; textWOSBTimeSa4.Value = null; textWOSBTimeSu1.Value = null; textWOSBTimeSu2.Value = null; textWOSBTimeSu3.Value = null; textWOSBTimeSu4.Value = null; textWOSBProg1.Text = ""; textWOSBArgs1.Text = ""; textWOSBProg2.Text = ""; textWOSBArgs2.Text = ""; textWOSBExtra.Text = ""; if (Data.W[curProfile].ContainsKey("Mo1")) textWOSBTimeMo1.Value = DateTime.Parse(Data.W[curProfile]["Mo1"]); if (Data.W[curProfile].ContainsKey("Mo2")) textWOSBTimeMo2.Value = DateTime.Parse(Data.W[curProfile]["Mo2"]); if (Data.W[curProfile].ContainsKey("Mo3")) textWOSBTimeMo3.Value = DateTime.Parse(Data.W[curProfile]["Mo3"]); if (Data.W[curProfile].ContainsKey("Mo4")) textWOSBTimeMo4.Value = DateTime.Parse(Data.W[curProfile]["Mo4"]); if (Data.W[curProfile].ContainsKey("Tu1")) textWOSBTimeTu1.Value = DateTime.Parse(Data.W[curProfile]["Tu1"]); if (Data.W[curProfile].ContainsKey("Tu2")) textWOSBTimeTu2.Value = DateTime.Parse(Data.W[curProfile]["Tu2"]); if (Data.W[curProfile].ContainsKey("Tu3")) textWOSBTimeTu3.Value = DateTime.Parse(Data.W[curProfile]["Tu3"]); if (Data.W[curProfile].ContainsKey("Tu4")) textWOSBTimeTu4.Value = DateTime.Parse(Data.W[curProfile]["Tu4"]); if (Data.W[curProfile].ContainsKey("We1")) textWOSBTimeWe1.Value = DateTime.Parse(Data.W[curProfile]["We1"]); if (Data.W[curProfile].ContainsKey("We2")) textWOSBTimeWe2.Value = DateTime.Parse(Data.W[curProfile]["We2"]); if (Data.W[curProfile].ContainsKey("We3")) textWOSBTimeWe3.Value = DateTime.Parse(Data.W[curProfile]["We3"]); if (Data.W[curProfile].ContainsKey("We4")) textWOSBTimeWe4.Value = DateTime.Parse(Data.W[curProfile]["We4"]); if (Data.W[curProfile].ContainsKey("Th1")) textWOSBTimeTh1.Value = DateTime.Parse(Data.W[curProfile]["Th1"]); if (Data.W[curProfile].ContainsKey("Th2")) textWOSBTimeTh2.Value = DateTime.Parse(Data.W[curProfile]["Th2"]); if (Data.W[curProfile].ContainsKey("Th3")) textWOSBTimeTh3.Value = DateTime.Parse(Data.W[curProfile]["Th3"]); if (Data.W[curProfile].ContainsKey("Th4")) textWOSBTimeTh4.Value = DateTime.Parse(Data.W[curProfile]["Th4"]); if (Data.W[curProfile].ContainsKey("Fr1")) textWOSBTimeFr1.Value = DateTime.Parse(Data.W[curProfile]["Fr1"]); if (Data.W[curProfile].ContainsKey("Fr2")) textWOSBTimeFr2.Value = DateTime.Parse(Data.W[curProfile]["Fr2"]); if (Data.W[curProfile].ContainsKey("Fr3")) textWOSBTimeFr3.Value = DateTime.Parse(Data.W[curProfile]["Fr3"]); if (Data.W[curProfile].ContainsKey("Fr4")) textWOSBTimeFr4.Value = DateTime.Parse(Data.W[curProfile]["Fr4"]); if (Data.W[curProfile].ContainsKey("Sa1")) textWOSBTimeSa1.Value = DateTime.Parse(Data.W[curProfile]["Sa1"]); if (Data.W[curProfile].ContainsKey("Sa2")) textWOSBTimeSa2.Value = DateTime.Parse(Data.W[curProfile]["Sa2"]); if (Data.W[curProfile].ContainsKey("Sa3")) textWOSBTimeSa3.Value = DateTime.Parse(Data.W[curProfile]["Sa3"]); if (Data.W[curProfile].ContainsKey("Sa4")) textWOSBTimeSu4.Value = DateTime.Parse(Data.W[curProfile]["Su4"]); if (Data.W[curProfile].ContainsKey("Su1")) textWOSBTimeSu1.Value = DateTime.Parse(Data.W[curProfile]["Su1"]); if (Data.W[curProfile].ContainsKey("Su2")) textWOSBTimeSu2.Value = DateTime.Parse(Data.W[curProfile]["Su2"]); if (Data.W[curProfile].ContainsKey("Su3")) textWOSBTimeSu3.Value = DateTime.Parse(Data.W[curProfile]["Su3"]); if (Data.W[curProfile].ContainsKey("Su4")) textWOSBTimeSu4.Value = DateTime.Parse(Data.W[curProfile]["Su4"]); if (Data.W[curProfile].ContainsKey("File")) textWOSBProg1.Text = Data.W[curProfile]["File"]; if (Data.W[curProfile].ContainsKey("Params")) textWOSBArgs1.Text = Data.W[curProfile]["Params"]; if (Data.W[curProfile].ContainsKey("AwFile")) textWOSBProg2.Text = Data.W[curProfile]["AwFile"]; if (Data.W[curProfile].ContainsKey("AwParams")) textWOSBArgs2.Text = Data.W[curProfile]["AwParams"]; if (Data.W[curProfile].ContainsKey("Extra")) textWOSBExtra.Text = Data.W[curProfile]["Extra"]; } #region Apply void Apply() { Data.S["AllProcesses"] = (bool)checkAllProcesses.IsChecked; Data.S["Ask"] = (bool)checkAsk.IsChecked; Data.S["Autostart"] = (bool)checkAutostart.IsChecked && checkAutostart.IsEnabled; Data.S["Force"] = (bool)checkForce.IsChecked; Data.S["Glass"] = (bool)checkGlass.IsChecked && checkGlass.IsEnabled; Data.S["Win8Hybrid"] = (bool)checkHybrid.IsChecked && checkHybrid.IsEnabled; Data.S["IPv4"] = (bool)checkIPv4.IsChecked; Data.S["Jumplist"] = (bool)checkJumplist.IsChecked && checkJumplist.IsEnabled; Data.S["ModusIcons"] = (bool)checkModusIcons.IsChecked; Data.S["Overlay"] = (bool)checkOverlay.IsChecked && checkOverlay.IsEnabled; Data.S["RemoteClient"] = (bool)checkRemoteClient.IsChecked && checkRemoteClient.IsEnabled; Data.S["RemoteServer"] = (bool)checkRemoteServer.IsChecked && checkRemoteServer.IsEnabled; Data.S["SaveWindowState"] = (bool)checkSaveWindowState.IsChecked; Data.S["SendFeedback"] = (bool)checkSendFeedback.IsChecked; Data.S["StayAfterShutdown"] = (bool)checkStay.IsChecked; Data.S["SysIcon"] = (bool)checkSystray.IsChecked; Data.S["ThumbnailToolbar"] = (bool)checkThumbnailToolbar.IsChecked && checkThumbnailToolbar.IsEnabled; Data.S["WakeOnLan"] = (bool)checkWakeOnLan.IsChecked && checkWakeOnLan.IsEnabled; Data.S["WOSB"] = (bool)checkWOSB.IsChecked && checkWOSB.IsEnabled; int y; if (Int32.TryParse(textRemotePort.Text, out y) & (y > 1024 & y < 65535)) Data.RemotePort = Int32.Parse(textRemotePort.Text); if (textRemotePassword.Password != "") Data.RemotePassword = <PASSWORD>; Xml.Write(); if (Data.S["WOSB"]) { string curProfile = (string)comboProfiles.SelectedItem; if (textWOSBTimeMo1.Value != null) Data.W[curProfile]["Mo1"] = textWOSBTimeMo1.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Mo1"] = ""; if (textWOSBTimeMo2.Value != null) Data.W[curProfile]["Mo2"] = textWOSBTimeMo2.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Mo2"] = ""; if (textWOSBTimeMo3.Value != null) Data.W[curProfile]["Mo3"] = textWOSBTimeMo3.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Mo3"] = ""; if (textWOSBTimeMo4.Value != null) Data.W[curProfile]["Mo4"] = textWOSBTimeMo4.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Mo4"] = ""; if (textWOSBTimeTu1.Value != null) Data.W[curProfile]["Tu1"] = textWOSBTimeTu1.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Tu1"] = ""; if (textWOSBTimeTu2.Value != null) Data.W[curProfile]["Tu2"] = textWOSBTimeTu2.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Tu2"] = ""; if (textWOSBTimeTu3.Value != null) Data.W[curProfile]["Tu3"] = textWOSBTimeTu3.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Tu3"] = ""; if (textWOSBTimeTu4.Value != null) Data.W[curProfile]["Tu4"] = textWOSBTimeTu4.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Tu4"] = ""; if (textWOSBTimeWe1.Value != null) Data.W[curProfile]["We1"] = textWOSBTimeWe1.Value.Value.ToLongTimeString(); else Data.W[curProfile]["We1"] = ""; if (textWOSBTimeWe2.Value != null) Data.W[curProfile]["We2"] = textWOSBTimeWe2.Value.Value.ToLongTimeString(); else Data.W[curProfile]["We2"] = ""; if (textWOSBTimeWe3.Value != null) Data.W[curProfile]["We3"] = textWOSBTimeWe3.Value.Value.ToLongTimeString(); else Data.W[curProfile]["We3"] = ""; if (textWOSBTimeWe4.Value != null) Data.W[curProfile]["We4"] = textWOSBTimeWe4.Value.Value.ToLongTimeString(); else Data.W[curProfile]["We4"] = ""; if (textWOSBTimeTh1.Value != null) Data.W[curProfile]["Th1"] = textWOSBTimeTh1.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Th1"] = ""; if (textWOSBTimeTh2.Value != null) Data.W[curProfile]["Th2"] = textWOSBTimeTh2.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Th2"] = ""; if (textWOSBTimeTh3.Value != null) Data.W[curProfile]["Th3"] = textWOSBTimeTh3.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Th3"] = ""; if (textWOSBTimeTh4.Value != null) Data.W[curProfile]["Th4"] = textWOSBTimeTh4.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Th4"] = ""; if (textWOSBTimeFr1.Value != null) Data.W[curProfile]["Fr1"] = textWOSBTimeFr1.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Fr1"] = ""; if (textWOSBTimeFr2.Value != null) Data.W[curProfile]["Fr2"] = textWOSBTimeFr2.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Fr2"] = ""; if (textWOSBTimeFr3.Value != null) Data.W[curProfile]["Fr3"] = textWOSBTimeFr3.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Fr3"] = ""; if (textWOSBTimeFr4.Value != null) Data.W[curProfile]["Fr4"] = textWOSBTimeFr4.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Fr4"] = ""; if (textWOSBTimeSa1.Value != null) Data.W[curProfile]["Sa1"] = textWOSBTimeSa1.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Sa1"] = ""; if (textWOSBTimeSa2.Value != null) Data.W[curProfile]["Sa2"] = textWOSBTimeSa2.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Sa2"] = ""; if (textWOSBTimeSa3.Value != null) Data.W[curProfile]["Sa3"] = textWOSBTimeSa3.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Sa3"] = ""; if (textWOSBTimeSa4.Value != null) Data.W[curProfile]["Sa4"] = textWOSBTimeSa4.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Sa4"] = ""; if (textWOSBTimeSu1.Value != null) Data.W[curProfile]["Su1"] = textWOSBTimeSu1.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Su1"] = ""; if (textWOSBTimeSu2.Value != null) Data.W[curProfile]["Su2"] = textWOSBTimeSu2.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Su2"] = ""; if (textWOSBTimeSu3.Value != null) Data.W[curProfile]["Su3"] = textWOSBTimeSu3.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Su3"] = ""; if (textWOSBTimeSu4.Value != null) Data.W[curProfile]["Su4"] = textWOSBTimeSu4.Value.Value.ToLongTimeString(); else Data.W[curProfile]["Su4"] = ""; Data.W[curProfile]["File"] = textWOSBProg1.Text; Data.W[curProfile]["Params"] = textWOSBArgs1.Text; Data.W[curProfile]["AwFile"] = textWOSBProg2.Text; Data.W[curProfile]["AwParams"] = textWOSBArgs2.Text; Data.W[curProfile]["Extra"] = textWOSBExtra.Text; Xml.WriteWOSB(); } if (Data.S["Autostart"]) { if (!Autostart.IsAutoStartEnabled("Shutdown", Assembly.GetExecutingAssembly().Location + " /Run")) Autostart.SetAutoStart("Shutdown", Assembly.GetExecutingAssembly().Location + " /Run"); } else { if (Autostart.IsAutoStartEnabled("Shutdown", Assembly.GetExecutingAssembly().Location + " /Run")) Autostart.UnSetAutoStart("Shutdown"); } if (Data.S["Jumplist"]) Win7.Jumplist(); else Win7.ClearJumplist(); //MainWindow mainwindow = new MainWindow(); if (Data.S["SysIcon"]) App.mainwindow.CreateSystray(); else App.mainwindow.DisposeSystray(); if (Data.S["ThumbnailToolbar"]) App.mainwindow.ShowThumbnailToolbar(); else App.mainwindow.HideThumbnailToolbar(); if (Data.S["RemoteServer"]) new Thread(new ThreadStart(App.mainwindow.StartRemoteServer)).Start(); else App.mainwindow.StopRemoteServer(); //doesn't work App.mainwindow.UpdateModus(); } #endregion #region Aero protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); Win7.Glass(this); } #endregion #region Events private void comboProfiles_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (String.IsNullOrEmpty((string)comboProfiles.SelectedItem)) return; LoadWakeupTimes((string)comboProfiles.SelectedItem); Data.curProfile = (string)comboProfiles.SelectedItem; } #region Buttons private void OKButton_Click(object sender, RoutedEventArgs e) { Apply(); Close(); } private void ApplyButton_Click(object sender, RoutedEventArgs e) { Apply(); } private void AbortButton_Click(object sender, RoutedEventArgs e) { Close(); } private void WOSB_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.dennisbabkin.com/php/download.php?what=WOSB"); } private void buttonWOSBProg1_Click(object sender, RoutedEventArgs e) { try { if (ShellLibrary.IsPlatformSupported) { CommonOpenFileDialog fd = new CommonOpenFileDialog(Data.L["SelectFile"]); fd.Filters.Add(new CommonFileDialogFilter(Data.L["ExeFiles"], "*.exe")); fd.EnsureFileExists = true; if (fd.ShowDialog() == CommonFileDialogResult.Ok) textWOSBProg1.Text = fd.FileName; } else { OpenFileDialog fd = new OpenFileDialog(); fd.Filter = Data.L["ExeFiles"] + "|*.exe"; fd.Title = Data.L["SelectFile"]; fd.Multiselect = true; fd.CheckFileExists = true; if ((bool)fd.ShowDialog()) { textWOSBProg1.Text = fd.FileName; } } } catch (Exception ex) { Message.Show(ex.Message, "Shutdown7", "Error"); } } private void buttonWOSBProg2_Click(object sender, RoutedEventArgs e) { try { if (ShellLibrary.IsPlatformSupported) { CommonOpenFileDialog fd = new CommonOpenFileDialog(Data.L["SelectFile"]); fd.Filters.Add(new CommonFileDialogFilter(Data.L["ExeFiles"], "*.exe")); fd.EnsureFileExists = true; if (fd.ShowDialog() == CommonFileDialogResult.Ok) textWOSBProg2.Text = fd.FileName; } else { OpenFileDialog fd = new OpenFileDialog(); fd.Filter = Data.L["ExeFiles"] + "|*.exe"; fd.Title = Data.L["SelectFile"]; fd.Multiselect = true; fd.CheckFileExists = true; if ((bool)fd.ShowDialog()) { textWOSBProg2.Text = fd.FileName; } } } catch (Exception ex) { Message.Show(ex.Message, "Shutdown7", "Error"); } } private void buttonAddProfile_Click(object sender, RoutedEventArgs e) { if (Data.W.ContainsKey(textNewProfile.Text) | String.IsNullOrEmpty(textNewProfile.Text)) return; Data.W.Add(textNewProfile.Text, new Dictionary<string, string>()); comboProfiles.Items.Add(textNewProfile.Text); comboProfiles.SelectedItem = textNewProfile.Text; textNewProfile.Text = ""; } private void buttonDeleteProfile_Click(object sender, RoutedEventArgs e) { if (comboProfiles.Items.Count == 1) { Message.Show(Data.L["LastProfile"], "Warning"); return; } Data.W.Remove((string)comboProfiles.SelectedItem); comboProfiles.Items.Remove(comboProfiles.SelectedItem); comboProfiles.SelectedIndex = 0; } #endregion #region CheckBoxen private void checkWOSB_Click(object sender, RoutedEventArgs e) { if ((bool)checkWOSB.IsChecked) ActivateWOSBUI(); else DeactivateWOSBUI(); } void ActivateWOSBUI() { panelProfiles.IsEnabled = true; labelWOSBTimes.IsEnabled = true; } void DeactivateWOSBUI() { panelProfiles.IsEnabled = false; labelWOSBTimes.IsEnabled = false; } #endregion #endregion #region Remote private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (Data.S["RemoteServer"] | (bool)checkRemoteServer.IsChecked) { int y; if (!Int32.TryParse(textRemotePort.Text, out y) | (y < 1024 | y > 65535)) { Message.Show(Data.L["RemotePortMissing"], "Error"); e.Cancel = true; } if (textRemotePassword.Password == "") { Message.Show(Data.L["RemotePasswordMissing"], "Error"); e.Cancel = true; } } } private void checkRemoteClient_Checked(object sender, RoutedEventArgs e) { checkWakeOnLan.IsEnabled = true; checkIPv4.IsEnabled = true; } private void checkRemoteClient_Unchecked(object sender, RoutedEventArgs e) { checkWakeOnLan.IsChecked = false; checkWakeOnLan.IsEnabled = false; checkIPv4.IsEnabled = false; } private void checkRemoteServer_Checked(object sender, RoutedEventArgs e) { textRemotePort.IsEnabled = true; textRemotePassword.IsEnabled = true; buttonPortCheck.IsEnabled = true; buttonFirewallException.IsEnabled = true; if (Visibility != Visibility.Collapsed) { try { TaskDialog td = new TaskDialog(); td.Caption = "Shutdown7"; td.InstructionText = "Remote-Server"; td.Text = Data.L["RemoteServerHelp"]; td.Icon = TaskDialogStandardIcon.Information; td.StandardButtons = TaskDialogStandardButtons.Yes | TaskDialogStandardButtons.No; if (td.Show() == TaskDialogResult.Yes) Process.Start("http://www.shutdown7.com/faq.php?lang=" + Data.Lang); } catch { if (MessageBox.Show(Data.L["RemoteServerHelp"], "Shutdown7", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) Process.Start("http://www.shutdown7.com/faq.php?lang=" + Data.Lang); } } } private void checkRemoteServer_Unchecked(object sender, RoutedEventArgs e) { textRemotePort.IsEnabled = false; textRemotePassword.IsEnabled = false; buttonPortCheck.IsEnabled = false; buttonFirewallException.IsEnabled = false; } #region RemotePW private void textRemotePassword_LostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { textRemotePassword.Password = <PASSWORD>(textRemotePassword.Password); } private void textRemotePassword_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { textRemotePassword.Password = ""; } #endregion #region Portcheck private void buttonPortCheck_Click(object sender, RoutedEventArgs e) { buttonPortCheck.IsEnabled = false; Thread t = new Thread(new ParameterizedThreadStart(Portcheck)); t.Start(textRemotePort.Text); new Thread(new ParameterizedThreadStart(WaiterHelper)).Start(t); } void WaiterHelper(object _t) { Thread t = (Thread)_t; while (t.IsAlive) { Thread.Sleep(100); } Dispatcher.Invoke((System.Action)delegate { buttonPortCheck.IsEnabled = true; }); } int _Port; public void Portcheck(object _param) { _Port = Convert.ToInt32(_param); //Port try { TcpListener tcpListener = new TcpListener(Dns.GetHostEntry("127.0.0.1").AddressList[0], _Port); tcpListener.Start(); tcpListener.Stop(); } catch (Exception ex) { if (Data.debug_verbose) Message.Show(ex.Message, "Shutdown7", "Error"); Message.Show(Data.L["PortCheckErrPort"], "Shutdown7", "Error"); return; } //Lokal string answer; try { TcpClient tcpClient = new TcpClient(Remote.GetIP("127.0.0.1"), _Port); NetworkStream clientStream = tcpClient.GetStream(); byte[] buffer = new ASCIIEncoding().GetBytes("Ping"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); byte[] message = new byte[32]; answer = new ASCIIEncoding().GetString(message, 0, clientStream.Read(message, 0, 32)); tcpClient.Close(); } catch (Exception ex) { if (Data.debug_verbose) Message.Show(ex.Message, "Shutdown7", "Error"); answer = ""; } if (answer != "Pong") { Message.Show(Data.L["PortCheckErrLocal"] + Remote.GetIP(Dns.GetHostName()), "Shutdown7", "Error"); return; } //Network answer = ""; try { TcpClient tcpClient = new TcpClient(Remote.GetIP(Dns.GetHostName()), _Port); NetworkStream clientStream = tcpClient.GetStream(); byte[] buffer = new ASCIIEncoding().GetBytes("Ping"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); byte[] message = new byte[32]; answer = new ASCIIEncoding().GetString(message, 0, clientStream.Read(message, 0, 32)); if (Data.debug_verbose) Message.Show(answer, "Shutdown7", "Information"); tcpClient.Close(); } catch (Exception ex) { if (Data.debug_verbose) Message.Show(ex.Message, "Shutdown7", "Information"); answer = ""; } if (answer != "Pong") { Message.Show(Data.L["PortCheckErrNetwork"] + Remote.GetIP(Dns.GetHostName()), "Shutdown7", "Error"); return; } //Remote answer = ""; string RemoteIP = new WebClient().DownloadString("http://automation.whatismyip.com/n09230945.asp").Trim(); try { TcpClient tcpClient = new TcpClient(RemoteIP, _Port); NetworkStream clientStream = tcpClient.GetStream(); byte[] buffer = new ASCIIEncoding().GetBytes("Ping"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); byte[] message = new byte[32]; answer = new ASCIIEncoding().GetString(message, 0, clientStream.Read(message, 0, 32)); if (Data.debug_verbose) Message.Show(answer, "Shutdown7", "Information"); if (answer != "Pong") { Message.Show(Data.L["PortCheckErrRemote"] + Remote.GetIP("127.0.0.1"), "Shutdown7", "Error"); return; } tcpClient.Close(); } catch (Exception ex) { if (Data.debug_verbose) Message.Show(ex.Message, "Shutdown7", "Information"); answer = ""; } if (answer != "Pong") { Message.Show(Data.L["PortCheckErrNetwork"] + Remote.GetIP(Dns.GetHostName()), "Shutdown7", "Error"); return; } Message.Show(Data.L["PortCheckOK"], "Shutdown7", "Information"); } #endregion #region Firewall private void buttonFirewallException_Click(object sender, RoutedEventArgs e) { buttonFirewallException.IsEnabled = false; FirewallException(); buttonFirewallException.IsEnabled = true; } public void FirewallException() { Process p = new Process(); if (Environment.OSVersion.Version.Major >= 6) { p.StartInfo.FileName = "netsh"; p.StartInfo.Arguments = "advfirewall firewall add rule name=Shutdown7 dir=in action=allow profile=any protocol=tcp localport=" + textRemotePort.Text; } else { p.StartInfo.FileName = "netsh"; p.StartInfo.Arguments = "firewall add portopening protocol=tcp port=" + textRemotePort.Text + " name=Shutdown7 profile=all"; } p.StartInfo.Verb = "runas"; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.Start(); string ok = p.StandardOutput.ReadLine(); p.WaitForExit(); if (ok == "OK.") Message.Show(Data.L["FirewallOK"], "Shutdown7", "Information"); else Message.Show(Data.L["FirewallError"] + ok, "Shutdown7", "Error"); } #endregion private void _Click(object sender, RoutedEventArgs e) { } #endregion #region Taskschedule void CreateTask() { /// Documentation: https://taskscheduler.codeplex.com/documentation /// Trigger: https://taskscheduler.codeplex.com/wikipage?title=TriggerSamples&referringTitle=Documentation // Get the service on the local machine using (TaskService ts = new TaskService()) { // Create a new task definition and assign properties TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = "Launch Shutdown7"; // Create a trigger that will fire the task at this time every other day td.Triggers.Add(new DailyTrigger { DaysInterval = 1 }); // Create an action that will launch Shutdown7 whenever the trigger fires td.Actions.Add(new ExecAction(Data.EXE, "-lo", null)); // Register the task in the root folder ts.RootFolder.RegisterTaskDefinition(@"Shutdown7", td); // Remove the task we just created ts.RootFolder.DeleteTask("Shutdown7"); } } #endregion } } <file_sep>/Win7.cs using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using Microsoft.WindowsAPICodePack.Shell; using Microsoft.WindowsAPICodePack.Taskbar; namespace Shutdown7 { class Win7 { public static JumpList jumplist; public static bool IsWin7 { get { return TaskbarManager.IsPlatformSupported; } } public static bool IsWin8 { get { //return TaskbarManager.IsPlatformSupported; return Environment.OSVersion.Version >= new Version(6, 2); } } #region Taskbar public static void Progress(int cur, Window window) { if (!IsWin7) return; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) return; TaskbarManager.Instance.SetProgressValue(cur, 100); } public static void Progress(int cur, int max, Window window) { if (!IsWin7) return; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) return; TaskbarManager.Instance.SetProgressValue(cur, max); } public static void ProgressType(string Type, Window window) { if (!IsWin7) return; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) return; switch (Type) { case "Normal": TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal); break; case "Paused": TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Paused); break; case "Error": TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Error); break; case "Indeterminate": TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Indeterminate); break; default: TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress); break; } } public static void Overlay(System.Drawing.Icon Icon, string Title, Window window) { if (!IsWin7) return; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) return; TaskbarManager.Instance.SetOverlayIcon(Icon, Title); } public static void ThumbnailToolbar(IntPtr handle, ThumbnailToolBarButton[] Buttons, Window window) { if (!Win7.IsWin7) return; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) return; TaskbarManager.Instance.ThumbnailToolBars.AddButtons(handle, Buttons); } public static void Jumplist() { if (!Win7.IsWin7) return; try { jumplist = JumpList.CreateJumpList(); jumplist.ClearAllUserTasks(); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Shutdown"]) { IconReference = new IconReference(Data.EXE, 1), Arguments = "-s" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Restart"]) { IconReference = new IconReference(Data.EXE, 2), Arguments = "-r" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Logoff"]) { IconReference = new IconReference(Data.EXE, 3), Arguments = "-l" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Lock"]) { IconReference = new IconReference(Data.EXE, 3), Arguments = "-lo" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Standby"]) { IconReference = new IconReference(Data.EXE, 4), Arguments = "-sb" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Hibernate"]) { IconReference = new IconReference(Data.EXE, 4), Arguments = "-h" }); if (Data.S["WOSB"]) { jumplist.AddUserTasks(new JumpListSeparator()); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["HibernateWOSBIni"]) { IconReference = new IconReference(Data.EXE, 5), Arguments = "-hi" }); //jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["HibernateWOSBTime"]) { IconReference = new IconReference(Data.EXE, 5), Arguments = "-ht" }); } //jumplist.AddUserTasks(new JumpListSeparator()); //jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Abort"]) { IconReference = new IconReference(EXE, 6), Arguments = "-a", WorkingDirectory = Path.GetDirectoryName(EXE) }); jumplist.Refresh(); } catch { } } public static void ClearJumplist() { if (!Win7.IsWin7) return; jumplist = JumpList.CreateJumpList(); jumplist.ClearAllUserTasks(); jumplist.Refresh(); } #region Pin public static void PinToTaskbar() { if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Shutdown7.lnk")) { try { StreamWriter file = new StreamWriter(Environment.ExpandEnvironmentVariables("%Temp%") + "\\pin.vbs"); file.WriteLine("strlPath = \"" + Data.EXE + "\""); file.Write("On Error Resume Next\r\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\r\nSet objShell = CreateObject(\"Shell.Application\")\r\nIf Not objFSO.FileExists(strlPath) Then Wscript.Quit\r\nstrFolder = objFSO.GetParentFolderName(strlPath)\r\nstrFile = objFSO.GetFileName(strlPath)\r\nSet objFolder = objShell.Namespace(strFolder)\r\nSet objFolderItem = objFolder.ParseName(strFile)\r\nSet colVerbs = objFolderItem.Verbs\r\nFor each itemverb in objFolderItem.verbs\r\n"); file.WriteLine("If Replace(itemverb.name, \"&\", \"\") = \"" + Data.L["PinText"] + "\" Then itemverb.DoIt"); file.WriteLine("Next"); file.Close(); Process p = new Process(); p.StartInfo.FileName = Environment.ExpandEnvironmentVariables("%Temp%") + "\\pin.vbs"; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.Start(); p.WaitForExit(); File.Delete(Environment.ExpandEnvironmentVariables("%Temp%") + "\\pin.vbs"); } catch (Exception ex) { if (Data.debug_verbose) Message.Show(ex.Message, "Shutdown7", "Error"); } } } #endregion #endregion #region Aero [DllImport("dwmapi.dll", PreserveSig = false)] public static extern bool DwmIsCompositionEnabled(); [DllImport("dwmapi.dll", PreserveSig = false)] static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins); public static bool Glass(Window window) { if (Environment.OSVersion.Version.Major < 6) return false; if (Data.S["Glass"] & DwmIsCompositionEnabled()) return ExtendGlassFrame(window, new Thickness(-1)); else return false; } public static bool Glass(Window window, Thickness thickness) { if (Environment.OSVersion.Version.Major < 6) return false; if (Data.S["Glass"] & DwmIsCompositionEnabled()) return ExtendGlassFrame(window, thickness); else return false; } static bool ExtendGlassFrame(Window window, Thickness margin) { try { if (!DwmIsCompositionEnabled()) return false; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) return false; //The Window must be shown before extending glass // Set the background to transparent from both the WPF and Win32 perspectives window.Background = Brushes.Transparent; HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent; MARGINS margins = new MARGINS(margin); DwmExtendFrameIntoClientArea(hwnd, ref margins); return true; } catch (DllNotFoundException) { return false; } } struct MARGINS { public MARGINS(Thickness t) { Left = (int)t.Left; Right = (int)t.Right; Top = (int)t.Top; Bottom = (int)t.Bottom; } public int Left; public int Right; public int Top; public int Bottom; } #endregion } } <file_sep>/App.xaml.cs using Microsoft.Shell; using Microsoft.WindowsAPICodePack.Dialogs; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Mail; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; using System.Threading; using System.Windows; using System.Windows.Threading; namespace Shutdown7 { public partial class App : Application, ISingleInstanceApp { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); public static MainWindow mainwindow; public static Stopwatch stopwatch; /// <summary> /// Interaktionslogik für "App.xaml" /// </summary> [STAThread] public static void Main() { //Load Language Variables & Settings Data.Init(); //Crash Win XP #region Stopwatch if (Data.debug_stopwatch) { stopwatch = new Stopwatch(); stopwatch.Start(); } #endregion //Single Instance if (SingleInstance<App>.InitializeAsFirstInstance(Assembly.GetExecutingAssembly().GetName().Name)) { var application = new App(); application.InitializeComponent(); application.Run(); // Allow single instance code to perform cleanup operations SingleInstance<App>.Cleanup(); } else { IntPtr hWnd = FindWindow(null, "Shutdown7"); if (!Data.S["SysIcon"]) ShowWindow(hWnd, 1); SetForegroundWindow(hWnd); } } /// <summary> /// Raises the <see cref="E:System.Windows.Application.Startup"/> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs"/> that contains the event data.</param> protected override void OnStartup(StartupEventArgs e) { //ErrorReporting #if !DEBUG AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException); //From all threads in the AppDomain //Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(DispatcherUnhandledException); //From the main UI dispatcher thread in your WPF application. #endif //if (Data.debug_verbose) // Message.Show("IsAdmin?\nAlt: " + new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator) + "\nNeu: " + isAdmin(), "Information"); //Admin if (!Data.debug_debugging & !isAdmin()) { if (Data.debug_verbose) Message.Show(Data.L["RequireAdmin"], "Start", "Warning"); ProcessStartInfo p = new ProcessStartInfo(); p.FileName = Data.EXE; p.WorkingDirectory = Directory.GetCurrentDirectory(); p.Verb = "runas"; p.Arguments = String.Join(" ", e.Args); Process.Start(p); Environment.Exit(0); } //Check dll's if (!File.Exists(Path.GetDirectoryName(Data.EXE) + "\\Hardcodet.Wpf.TaskbarNotification.dll") | !File.Exists(Path.GetDirectoryName(Data.EXE) + "\\Microsoft.WindowsAPICodePack.dll") | !File.Exists(Path.GetDirectoryName(Data.EXE) + "\\Microsoft.WindowsAPICodePack.Shell.dll") | !File.Exists(Path.GetDirectoryName(Data.EXE) + "\\taglib-sharp.dll") | !File.Exists(Path.GetDirectoryName(Data.EXE) + "\\WPFToolkit.Extended.dll") | !File.Exists(Path.GetDirectoryName(Data.EXE) + "\\AndroidLib.dll")) { MessageBox.Show(Data.L["DLLMissing"], "Shutdown7", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(0); } //Beta if (Data.debug_beta) { Data.Version += " Beta"; } //Expiration if (Data.debug_expire) { if (DateTime.Now >= Data.Expiration) { Message.Show(Data.L["BetaExpired"], "Error"); Environment.Exit(0); } } //Welcome if (Welcome.welcome) new Welcome().ShowDialog(); if (Data.CurVersion.CompareTo(Data.LastVersion) > 0) Welcome.update = true; if (Welcome.update && !Welcome.welcome) new Welcome().ShowDialog(); mainwindow = new MainWindow(); // Change in 2.3.3 if (Data.S["SysIcon"]) mainwindow.CreateSystray(); //Check Args if (e.Args.Length > 0) { if (!CheckArgs(e.Args)) Environment.Exit(0); } else { /*if (Data.S["SysIcon"]) mainwindow.CreateSystray();*/ //Remote-Server if (Data.S["RemoteServer"]) new Thread(new ThreadStart(mainwindow.StartRemoteServer)).Start(); mainwindow.Show(); } base.OnStartup(e); } public bool SignalExternalCommandLineArgs(IList<string> args) { if (Data.debug_verbose) Message.Show("Instanz läuft bereits.", "Start", "Information"); string[] Args = new string[args.Count]; args.CopyTo(Args, 0); CheckArgs(Args); return true; } #region ErrorReporting void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs ex) { Exception e = ex.Exception as Exception; #if DEBUG // In debug mode do not custom-handle the exception, let Visual Studio handle it ex.Handled = false; #else ErrorReporting(e); //ex.Handled = true; //Environment.Exit(1); #endif } void UnhandledException(object sender, UnhandledExceptionEventArgs ex) { Exception e = ex.ExceptionObject as Exception; ErrorReporting(e); Environment.Exit(1); } static void ErrorReporting(Exception e) { if (e.TargetSite != null) { if (e.TargetSite.Name.ToString() == "GetPixelFormat" | e.TargetSite.Name.ToString() == "StartWithShellExecuteEx" | e.TargetSite.Name.ToString() == "GetPixelFormat" | e.GetType().ToString() == "System.UnauthorizedAccessException" ) return; } string log; log = "==============================================================================\r\n"; log += Assembly.GetEntryAssembly() + "\r\n"; log += "------------------------------------------------------------------------------\r\n"; log += "Application Information \r\n"; log += "------------------------------------------------------------------------------\r\n"; log += "Program : " + Assembly.GetEntryAssembly().Location + "\r\n"; log += "Time : " + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "\r\n"; //log += "User : " + Environment.UserName + "\r\n"; //log += "Computer : " + Environment.MachineName + "\r\n"; log += "OS : " + Environment.OSVersion.ToString() + "\r\n"; log += "Culture : " + CultureInfo.CurrentCulture.Name + "\r\n"; //log += "Processors : " + Environment.ProcessorCount + "\r\n"; //log += "Working Set : " + Environment.WorkingSet + "\r\n"; log += "Framework : " + Environment.Version + "\r\n"; log += "Run Time : " + (DateTime.Now - Process.GetCurrentProcess().StartTime).ToString() + "\r\n"; log += "------------------------------------------------------------------------------\r\n"; log += "Exception Information\r\n"; log += "------------------------------------------------------------------------------\r\n"; log += "Source : " + e.Source.ToString().Trim() + "\r\n"; log += "Method : " + e.TargetSite.Name.ToString() + "\r\n"; log += "Type : " + e.GetType().ToString() + "\r\n"; log += "Error : " + GetExceptionStack(e) + "\r\n"; log += "Stack Trace : " + e.StackTrace.ToString().Trim() + "\r\n"; log += "------------------------------------------------------------------------------\r\n"; log += "\r\n"; //Logfile string filename = AppDomain.CurrentDomain.BaseDirectory + "ErrorLog.txt"; FileStream fs; FileMode fm; StringBuilder sb = new StringBuilder(); Byte[] byt; if (!File.Exists(filename)) { fm = FileMode.Create; fs = new FileStream(filename, fm); byt = Encoding.ASCII.GetBytes(Data.L["SendLogToDeveloper"] + "\r\n\r\n\r\n"); fs.Write(byt, 0, byt.Length); fs.Close(); } fm = FileMode.Append; fs = new FileStream(filename, fm); byt = Encoding.ASCII.GetBytes(log); fs.Write(byt, 0, byt.Length); fs.Close(); MessageBox.Show(String.Format(Data.L["Crash"], filename) + Data.L["Error"] + ":\n" + e.Message/* + "\n" + e.InnerException*/, Data.L["Error"], MessageBoxButton.OK, MessageBoxImage.Error); //E-Mail if (MessageBox.Show(Data.L["ConfirmMail"], "Report Crash", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK) { var fromAddress = new MailAddress("<EMAIL>", "Shutdown7"); var toAddress = new MailAddress("<EMAIL>", "Shutdown7"); const string fromPsord = "Shutdown7"; const string subject = "Crashreport Shutdown7"; var smtp = new SmtpClient { //Host = "smtp.gmail.com", Host = "smtp.strato.de", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPsord) }; MailMessage message = new MailMessage(fromAddress, toAddress); message.Subject = subject; message.Body = log; smtp.Send(message); Message.Show(Data.L["ThankYou"], "Information"); } } private static string GetExceptionStack(Exception e) { StringBuilder message = new StringBuilder(); message.Append(e.Message); while (e.InnerException != null) { e = e.InnerException; message.Append(Environment.NewLine); message.Append(e.Message); } return message.ToString(); } #endregion #region Args public bool CheckArgs(string[] Args) { if (Data.debug_verbose) Message.Show(string.Join(" ", Args).Trim(), "Argumente", "Information"); //if (Data.debug_verbose) for (int i = 0; i < Args.Length; i++) Message.Show(Args[i], "Argumente", "Information"); Debug.WriteLine(string.Join(" ", Args).Trim(), "Arguments"); //if (mainwindow == null) mainwindow = new MainWindow(); Arguments CommandLine = new Arguments(Args); if (CommandLine["updated"] != null) { mainwindow.Show(); return true; } if (CommandLine["a"] != null) { mainwindow.StopShutdown(); return true; } if (CommandLine["t"] != null) { Data.Condition = Data.Conditions.Time; try { Data.t = TimeSpan.FromSeconds(Convert.ToInt32(CommandLine["t"])); } catch { Data.t = TimeSpan.FromSeconds(0); }; } if (CommandLine["server"] != null) { Data.ArgsServer = CommandLine["server"]; } if (CommandLine["port"] != null) { Data.ArgsPort = Convert.ToInt32(CommandLine["port"]); } if (CommandLine["password"] != null) { Data.ArgsPassword = CommandLine["password"]; } Data.orgMode = Data.Mode; Data.Mode = Data.Modes.None; if (CommandLine["s"] != null) Data.Mode = Data.Modes.Shutdown; else if (CommandLine["r"] != null) Data.Mode = Data.Modes.Restart; else if (CommandLine["l"] != null) Data.Mode = Data.Modes.Logoff; else if (CommandLine["lo"] != null) Data.Mode = Data.Modes.Lock; else if (CommandLine["sb"] != null) { if (Data.S["WOSB"]) Data.Mode = Data.Modes.StandbyWOSB; else Data.Mode = Data.Modes.Standby; } else if (CommandLine["h"] != null) { if (Data.S["WOSB"]) Data.Mode = Data.Modes.HibernateWOSB; else Data.Mode = Data.Modes.Hibernate; } else if (CommandLine["ht"] != null && Data.S["WOSB"]) Data.Mode = Data.Modes.HibernateWOSBTime; else if (CommandLine["hi"] != null && Data.S["WOSB"]) Data.Mode = Data.Modes.HibernateWOSBIni; if (CommandLine["e"] != null) { if (Data.debug_verbose) Message.Show(CommandLine["e"] + "\nVorhanden: " + File.Exists(CommandLine["e"]), "Args", "Information"); if (File.Exists(CommandLine["e"])) { Data.Mode = Data.Modes.Launch; Data.LaunchFile = CommandLine["e"]; } else if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\" + CommandLine["e"])) { Data.Mode = Data.Modes.Launch; Data.LaunchFile = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\" + CommandLine["e"]; } } if ((Data.Mode != Data.Modes.None)/* & (Data.Mode != Data.orgMode)*/) { if (Data.ArgsServer != "" & Data.ArgsPort > 0 & Data.ArgsPassword != "") { Data.RemoteByArgs = true; ConsoleManager.Show(); Console.WriteLine("Shutdown7"); Console.WriteLine(""); Console.WriteLine(Data.L["Condition"] + ": " + Data.L[Data.Mode.ToString()]); Console.WriteLine("Server: " + Data.ArgsServer); Console.WriteLine("Port: " + Data.ArgsPort); new MainWindow(); } else { //Data.S["StayAfterShutdown"] = false; //TODO: workaround verbessern Data.LocalByArgs = true; mainwindow.Execute(); } //Data.Mode = Data.orgMode; //Data.orgMode = Data.Modes.None; return true; } if (CommandLine["Run"] != null) { //Do the same as normal startup //Remote-Server if (Data.S["RemoteServer"]) new Thread(new ThreadStart(mainwindow.StartRemoteServer)).Start(); if (Data.S["SysIcon"]) { mainwindow.CreateSystray(); //MainWindow.WindowState = WindowState.Minimized; MainWindow.Visibility = Visibility.Hidden; } else { MainWindow.WindowState = WindowState.Minimized; mainwindow.Show(); } return true; } //keine brauchbaren Args return false; //Application.Current.Shutdown(); //Environment.Exit(0); } #endregion #region isAdmin [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength); /// <summary> /// Passed to <see cref="GetTokenInformation"/> to specify what /// information about the token to return. /// </summary> enum TokenInformationClass { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUiAccess, TokenMandatoryPolicy, TokenLogonSid, MaxTokenInfoClass } /// <summary> /// The elevation type for a user token. /// </summary> enum TokenElevationType { TokenElevationTypeDefault = 1, TokenElevationTypeFull, TokenElevationTypeLimited } bool isAdmin() { var identity = WindowsIdentity.GetCurrent(); if (identity == null) throw new InvalidOperationException("Couldn't get the current user identity"); var principal = new WindowsPrincipal(identity); // Check if this user has the Administrator role. If they do, return immediately. // If UAC is on, and the process is not elevated, then this will actually return false. if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return true; // If we're not running in Vista onwards, we don't have to worry about checking for UAC. if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6) { // Operating system does not support UAC; skipping elevation check. return false; } int tokenInfLength = Marshal.SizeOf(typeof(int)); IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength); try { var token = identity.Token; var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength); if (!result) { var exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); throw new InvalidOperationException("Couldn't get token information", exception); } var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation); switch (elevationType) { case TokenElevationType.TokenElevationTypeDefault: // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate. return false; case TokenElevationType.TokenElevationTypeFull: // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator. return true; case TokenElevationType.TokenElevationTypeLimited: // TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator. return true; default: // Unknown token elevation type. return false; } } finally { if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation); } } #endregion } } <file_sep>/CodeItem.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Shutdown7 { public class CodeItem { #region " Properties/Constants... " public string Text { get; set; } public string Image { get; set; } #endregion #region " Constructors... " public CodeItem() { } public CodeItem(string text, string image) { Text = text; Image = image; } #endregion #region " Overrides... " public override string ToString() { return Text; } #endregion } } <file_sep>/Updater.xaml.cs /// <summary> /// Updater /// (c) <NAME> /// Individueller Programmupdater (WPF) /// Version 1.3 /// 1.0 Initial Release /// 1.1 Win7-Progress /// 1.2 Multi-Lang /// Aero /// 1.3 Fix: GUI hängt bei Prüfung der Version /// Windows XP, Windows Vista, Windows 7 /// 2010-2011 /// www.shutdown7.com /// </summary> using System; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Threading; using System.Windows; using System.Windows.Interop; using System.Windows.Media; namespace Shutdown7 { public partial class Updater : Window { Version OldVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; Version NewVersion; System.Collections.Generic.Dictionary<string, string> L = new System.Collections.Generic.Dictionary<string, string>(); Uri VersionURL = new Uri("http://www.shutdown7.com/download.php?cmd=version&file=Shutdown"); Uri ChangelogURL = new Uri("http://www.shutdown7.com/download.php?cmd=changelog&file=Shutdown&mode=text"); Uri DownloadPortableURL = new Uri("http://www.shutdown7.com/download.php?cmd=download&file=Shutdown7Zip"); Uri DownloadSetupURL = new Uri("http://www.shutdown7.com/download.php?cmd=download&file=Shutdown7Setup"); Uri UnzipURL = new Uri("http://www.shutdown7.com/download.php?cmd=download&file=Unzip"); Uri HelperURL = new Uri("http://www.shutdown7.com/download.php?cmd=download&file=UpdateHelper"); Uri DownloadURL; string PortableFileName = "Shutdown7.zip"; string SetupFileName = "Shutdown7_Setup.exe"; string HelperFileName = "UpdateHelper.exe"; string ZipDllFileName = "Ionic.Zip.dll"; string FileName = ""; bool IsPortable = true; bool IsInstaller = true; bool Aero = Data.S["Glass"]; #region Suche void CheckInternet() { label1.Content = L["CheckConnection"]; button1.IsEnabled = false; progressBar1.IsIndeterminate = true; Win7Progress("Indeterminate", 0); new Thread(new ThreadStart(CheckInternetCon)).Start(); return; } void CheckInternetCon() { try { Dns.GetHostEntry("www.google.com"); /*Dispatcher.BeginInvoke((Action)delegate { */SearchUpdate();/* });*/ } catch (Exception e) { MessageBox.Show(e.Message.ToString(), "Updater", MessageBoxButton.OK, MessageBoxImage.Error); Dispatcher.BeginInvoke((Action)delegate { label1.Content = L["NoConnection"]; button1.IsEnabled = false; progressBar1.IsIndeterminate = false; }); Win7Progress("None", 0); } } void SearchUpdate() { Dispatcher.Invoke((Action)delegate { label1.Content = L["SearchUpdates"]; progressBar1.IsIndeterminate = true; Win7Progress("Indeterminate", 0); }); WebClient w = new WebClient(); w.DownloadStringCompleted += new DownloadStringCompletedEventHandler(CheckUpdate); w.DownloadStringAsync(VersionURL); } void CheckUpdate(object sender, DownloadStringCompletedEventArgs e) { Dispatcher.Invoke((Action)delegate { progressBar1.IsIndeterminate = false; Win7Progress("None", 0); }); NewVersion = new Version(e.Result); if (OldVersion.CompareTo(NewVersion) < 0) { //Update verfügbar Dispatcher.Invoke((Action)delegate { label1.Content = L["UpdateAvaiable"] + ": Version " + NewVersion.ToString(); button1.Content = "Download"; button1.IsEnabled = false; expanderChangelog.Visibility = Visibility.Visible; radioInstaller.Visibility = Visibility.Visible; radioPortable.Visibility = Visibility.Visible; }); } else { //Kein Update Dispatcher.Invoke((Action)delegate { label1.Content = L["NoUpdateAvaiable"]; }); } } #endregion #region Download void DownloadUpdate() { label1.Content = L["DownloadUpdate"]; button1.IsEnabled = false; radioPortable.IsEnabled = false; radioInstaller.IsEnabled = false; WebClient w = new WebClient(); w.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Update_DownloadProgressChanged); w.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Update_DownloadComplete); w.DownloadFileAsync(DownloadURL, FileName); } void Update_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; Win7Progress("Normal", e.ProgressPercentage); } void Update_DownloadComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if ((bool)radioPortable.IsChecked) DownloadHelper(); else { label1.Content = L["DownloadComplete"]; button1.Content = L["Install"]; button1.IsEnabled = true; } } #region Helper void DownloadHelper() { label1.Content = L["DownloadHelper"] + " 1"; progressBar1.Value = 0; WebClient w = new WebClient(); w.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Helper_DownloadProgressChanged); w.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Helper_DownloadComplete); w.DownloadFileAsync(UnzipURL, ZipDllFileName); } void Helper_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; } void Helper_DownloadComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { DownloadHelper_2(); } void DownloadHelper_2() { label1.Content = L["DownloadHelper"] + " 2"; progressBar1.Value = 0; WebClient w = new WebClient(); w.DownloadFileAsync(HelperURL, HelperFileName); w.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Helper_2_DownloadProgressChanged); w.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Helper_2_DownloadComplete); } void Helper_2_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; } void Helper_2_DownloadComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { label1.Content = L["DownloadComplete"]; button1.Content = L["Install"]; button1.IsEnabled = true; } #endregion #endregion #region Install void InstallUpdate() { progressBar1.IsIndeterminate = true; Win7Progress("Indeterminate", 0); button1.IsEnabled = false; if (File.Exists(FileName)) { if ((bool)radioPortable.IsChecked) { //Portable label1.Content = L["Install"]; Process.Start(HelperFileName, "-update -Zip " + FileName); Application.Current.Shutdown(); } else { //Installer label1.Content = L["Install"]; Process.Start(FileName); Application.Current.Shutdown(); } } else { label1.Content = L["ErrFileMissing"]; } } #endregion #region Changelog private void expanderChangelog_Expanded(object sender, RoutedEventArgs e) { if (Changelog.Text == "" | Changelog.Text == L["LoadChangelog"]) { WebClient w = new WebClient(); w.DownloadStringAsync(ChangelogURL); w.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Changelog_Completed); } } void Changelog_Completed(object sender, DownloadStringCompletedEventArgs e) { Changelog.Text = e.Result.Replace("&nbsp;", " "); } #endregion #region Form public Updater() { InitializeComponent(); if (!IsPortable) radioPortable.Visibility = Visibility.Collapsed; if (!IsInstaller) radioInstaller.Visibility = Visibility.Collapsed; #region Lang switch (Data.Lang) { case "de": L.Add("Ready", "Bereit"); L.Add("LoadChangelog", "Lade Changelog"); L.Add("SearchUpdates", "Suche Updates"); L.Add("CheckConnection", "Überprüfe Internetverbindung"); L.Add("NoConnection", "Keine Internetverbindung"); L.Add("UpdateAvaiable", "Update verfügbar"); L.Add("NoUpdateAvaiable", "Kein Update verfügbar"); L.Add("DownloadUpdate", "Lade Update herunter"); L.Add("DownloadHelper", "Lade Helper"); L.Add("DownloadComplete", "Erfolgreich heruntergeladen"); L.Add("Install", "Installieren"); L.Add("ErrFileMissing", "Fehler: Datei wurde nicht gefunden"); break; default: L.Add("Ready", "Ready"); L.Add("LoadChangelog", "Load changelog"); L.Add("SearchUpdates", "Search Updates"); L.Add("CheckConnection", "Check internet-connection"); L.Add("NoConnection", "No internet-connection"); L.Add("UpdateAvaiable", "Update avaiable"); L.Add("NoUpdateAvaiable", "No update avaiable"); L.Add("DownloadUpdate", "Download update"); L.Add("DownloadHelper", "Download helper"); L.Add("DownloadComplete", "Download complete"); L.Add("Install", "Install"); L.Add("ErrFileMissing", "Error: File not found"); break; } label1.Content = L["Ready"]; button1.Content = L["SearchUpdates"]; #endregion } #region Aero protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); // This can't be done any earlier than the SourceInitialized event: if ((int)Environment.OSVersion.Version.Major >= 6) { if (Aero && DwmIsCompositionEnabled()) { ExtendGlassFrame(this, new Thickness(-1)); } } } [DllImport("dwmapi.dll", PreserveSig = false)] public static extern bool DwmIsCompositionEnabled(); [DllImport("dwmapi.dll", PreserveSig = false)] static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins); public static bool ExtendGlassFrame(Window window, Thickness margin) { try { if (!DwmIsCompositionEnabled()) return false; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) throw new InvalidOperationException("The Window must be shown before extending glass."); // Set the background to transparent from both the WPF and Win32 perspectives window.Background = Brushes.Transparent; HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent; MARGINS margins = new MARGINS(margin); DwmExtendFrameIntoClientArea(hwnd, ref margins); return true; } catch (DllNotFoundException) { return false; } } struct MARGINS { public MARGINS(Thickness t) { Left = (int)t.Left; Right = (int)t.Right; Top = (int)t.Top; Bottom = (int)t.Bottom; } public int Left; public int Right; public int Top; public int Bottom; } #endregion void button1_Click(object sender, RoutedEventArgs e) { switch ((string)button1.Content) { case "Suche Updates": CheckInternet(); break; case "Search Updates": CheckInternet(); break; case "Download": DownloadUpdate(); break; case "Installieren": InstallUpdate(); break; case "Install": InstallUpdate(); break; } } private void radioInstaller_Click(object sender, RoutedEventArgs e) { DownloadURL = DownloadSetupURL; FileName = SetupFileName; button1.IsEnabled = true; } private void radioPortable_Click(object sender, RoutedEventArgs e) { DownloadURL = DownloadPortableURL; FileName = PortableFileName; button1.IsEnabled = true; } #endregion #region Win7 void Win7Progress(string Mode, int Value) { if (!File.Exists("Microsoft.WindowsAPICodePack.Shell.dll")) return; if (!Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.IsPlatformSupported) return; switch (Mode) { case "Indeterminate": Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Indeterminate); break; case "Normal": Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressValue(Value, 100); Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Normal); break; case "Error": Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressValue(Value, 100); Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Error); break; case "None": Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressValue(Value, 100); Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.NoProgress); break; } } #endregion } } <file_sep>/Ini.cs using System; using System.Collections.Generic; using System.IO; using System.Windows; namespace Shutdown7 { class Ini { public static string Path = System.IO.Path.GetDirectoryName(Data.EXE) + "\\Settings.ini"; public static string WOSBPath = System.IO.Path.GetDirectoryName(Data.EXE) + "\\wosb.ini"; public static void Read() { try { StreamReader Fil = new StreamReader(Path); while (!Fil.EndOfStream) { string Txt = Fil.ReadLine(); if (Txt.IndexOf("=") > 0) { string[] y = Txt.Split('='); if (y[0] == "RemoteServers" | y[0] == "RemoteMacs" | y[0] == "RemotePort" | y[0] == "RemotePassword" | y[0] == "LastVersion") { if (y[1].EndsWith(";")) y[1] = y[1].Substring(0, y[1].Length - 1); if (y[0] == "RemoteServers") Data.RemoteServers = y[1].Split(';'); if (y[0] == "RemoteMacs") Data.RemoteMacs = y[1].Split(';'); if (y[0] == "RemotePort") Data.RemotePort = Int32.Parse(y[1]); if (y[0] == "RemotePassword") Data.RemotePassword = y[1]; if (y[0] == "LastVersion") { try { Data.LastVersion = new Version(y[1]); } catch { Data.LastVersion = new Version(1, 0, 0, 0); } } } else { if (Data.S.ContainsKey(y[0])) Data.S.Remove(y[0]); y[1] = y[1].Replace("1", "true").Replace("0", "false"); Data.S.Add(y[0], Convert.ToBoolean(y[1])); } } } Fil.Close(); } catch (Exception e) { Message.Show(Data.L["XmlReadError_1"] + Data.L["XmlReadError_2"] + "\n" + e.Message + e.StackTrace + e.GetType(), "Error"); Application.Current.Shutdown(); } } public static void Write() { StreamWriter Fil = new StreamWriter(Path); foreach (KeyValuePair<string, bool> kvp in Data.S) { Fil.WriteLine(kvp.Key + "=" + kvp.Value); } try { Fil.WriteLine("RemoteServers=" + String.Join(";", Data.RemoteServers)); } catch { Fil.WriteLine("RemoteServers="); } try { Fil.WriteLine("RemoteMacs=" + String.Join(";", Data.RemoteMacs)); } catch { Fil.WriteLine("RemoteMacs="); } Fil.WriteLine("RemotePort=" + Data.RemotePort); Fil.WriteLine("RemotePassword=" + Data.RemotePassword); Fil.WriteLine("LastVersion=" + Data.CurVersion); Fil.Close(); } public static void ReadWOSB() { if (!File.Exists(WOSBPath)) { WriteWOSB(); } StreamReader Fil = new StreamReader(WOSBPath); try { while (!Fil.EndOfStream) { string Txt = Fil.ReadLine(); if (Txt.IndexOf("=") > 0) { string[] y = Txt.Split('='); if (Data.W["Default"].ContainsKey(y[0])) Data.W["Default"].Remove(y[0]); Data.W["Default"].Add(y[0], y[1]); } } } catch (Exception e) { Message.Show(Data.L["XmlReadError_1"] + Data.L["XmlReadError_2"] + "\n" + e.Message, "Error"); Environment.Exit(0); } Fil.Close(); } public static void WriteWOSB() { try { StreamWriter Fil = new StreamWriter(WOSBPath); foreach (KeyValuePair<string, string> kvp in Data.W["Default"]) { Fil.WriteLine(kvp.Key + "=" + kvp.Value); } Fil.Close(); } catch (Exception e) { Message.Show(/*L["IniWriteError"] + "\n" +*/e.Message, "Error"); } } } } <file_sep>/MainWindow.xaml.cs /// <summary> /// Shutdown7 /// (c) <NAME> /// Fährt Computer mit Unterstütztung der Windows 7 Features herunter. /// Version 2.3.X /// Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10 /// Oct 2009 - Jun 2017 /// www.shutdown7.com /// /// Changelog: /// 1.0 10.2009 /// Initial Release /// Taskbarprogress /// Jumplist /// Taskbaroverlay /// Timeout /// Parameter /// <NAME> /// 1.1 2009 /// Inimanagment /// Settings /// Globale Variablen /// Spenden /// Autostart /// Systray /// Balloontips /// Installer /// 1.2 2010 /// Verbessertes Kontextmenu /// UAC Verbesserungen /// Einstellungen Tooltips /// Aero Glass /// WOSB Integration /// Pictureboxen Transparent /// Progressbar Updatecheck Indeterminate /// <NAME> /// 1.3 2010 /// Umbenennung in Shutdown7 /// Complete Rewrite WPF /// Shutdown zu bestimmter Zeit /// ThumbnailToolbar (Win7) /// Jumplist Option /// Overlayicon transparentr (Win7) /// Settings Layout Update /// Single Instance /// <NAME>eregg /// Systray Verbesserungen /// 1.4 2010 /// Neuer Updater /// -WPF /// -Async /// -Autoupdate /// -Portable oder Installer /// Remote-Shutdown /// -Settings /// -WebUI (http://shutdown7.com/webui.php?lang=xx) /// -Portforward-Test /// -PW MD5-Crypt /// -Hilfe (s.u.) /// -Serverauswahl aus Ini /// Systray Verbesserungen /// About Layout Update /// F1: Web-Hilfe (http://shutdown7.com/help.php?lang=xx) /// Aero Glow /// Settings Tooltips Translate /// Wait Background Thread /// Settings Stackpanel /// Shutdown Lock intern statt externer /// Language Detection Change Localized (de, en) /// DLL-Check /// Auto Firewall-Exception (XP, Vista/7) /// ShutdownStart/Stop getrennt von GoButton_Click /// Komprimierung der Eastereggs->Filesize um 0,7 MB geschrumpft /// UAC-Manifest included in Resource-File /// Hibernate Timeout Fix /// HibernateWOSB Monat/Tag Fix /// hh, mm, ss Fix größer als 23, 59 /// 1.4.1 2010 /// Fix Windows XP Settings Overlayicon Checkbox /// Fix Windows XP Settings Save Crash /// Fix Crash Updater Falscher Lang-String /// Fix Start Shutdown runas, Crash /// 1.4.2 2010 /// Fix Remote Client Password Textfeld /// Fix Autostart Systray Minimieren /// Fix Double Instance Parameter /// 1.4.3 01.01.2011 /// Settings Layoutupdate /// Fix Updater Crash NoConnection /// Fix GoButton Remote /// WakeOnLan Beta /// 1.5 23.02.2011 /// Neue Shutdown-Optionen /// -Prozess geschlossen /// -Datei gelöscht /// -Musik abgespielt /// -Playlist /// -Fadeout /// Bildschirm ausschalten Option /// Main & Settings Layout Update /// -Expander /// Single Instance /// -Parameter-Weiterleitung /// Windows 7: Neuer FileOpenDialog und TaskDialoge (Win7API) /// -Fallback /// Neuer Timer (DispatchTimer) /// WebUI Abbrechen (Get) /// Aero-Glow heruntergesetzt /// Systray nicht mehr unterstützt /// 1.5.1 23.02.2011 /// Fix Crash TaskDialog /// 1.6 23.03.2011 /// Neuer Modus: IdleTime /// Play Music Playlists (m3u, wpl, xspf) /// Integer t, h, m, s ersetzt durch TimeSpan t /// Fix: Play Music Restzeit falsch kalkuliert wenn Gesamtlänge der Stücke über 24h /// Fix: Argumente /// 1.6.1 23.03.2011 /// Fix: Time: At Falsche Kalkulation /// Fix: Time: Progress Falsche Kalkulation /// 1.7 20.08.2011 /// Neue Icons /// Erster Start (keine Ini): WelcomeScreen /// -Neue Version: Changelog (WelcomeScreen) /// Modus-Auswahl mit Icons (CustomControl, Textbox als Workaround für SelectedItem) /// Neuer Modus: Programm starten /// Neue Bedingung: Sofort /// NumericUpDown-Control /// Music: /// -Start Volume /// -Fadeout End Volume /// Systray Icon verbessert /// -jetzt in Code satt XAML; nur geladen, wenn nötig /// -Tooltips verbessert /// WOSB Settings /// WakeOnLan mit IP-Adresse /// ThumbnailToolbar & Systray Abbrechen hinzugefügt; aktiviert, wenn nötig /// Jumplist WOSBTime entfent /// SendFeedback Option /// -Sende RemoteClient-Daten an WebUI /// IPv4 Kompatibilität-Option /// PacMan Easteregg: Autostart /// Funktionen aus MainWindow ausgelagert in Klassen /// SingleInstance verbessert (neue Methode, keine DLL mehr) /// Argumente Handling vereinfacht und ausgelagert /// TaskDialoge + Fallback MessageBox /// Debug-Vars /// Fix: Jumplist wird nicht angezeigt /// Fix: Wenn Modus WOSBIni, GoButton deaktiviert /// Fix: Falsche Anzeige der Restzeit /// Fix: WOL-Bug /// Fix: Shutdown7 wird nicht beendet, wenn RemoteServer an /// Fix: Remote-Server Bug /// Fix: MusicUpDown Buttons werden unter XP nicht angezeigt (fehlende Zeichen in Tahoma Font) /// 1.8 24.11.11 /// Unterstützung für neue WebUI /// -Status Abfrage /// Neue lokale WebUI /// -STATUS Abfrage, Codeänderungen /// -jQuery dynamischer Updatecheck /// XML-Format statt INI /// WOSB-Profile /// Beliebig viele WOSB-Zeiten pro Tag /// -Bis zu 4 in UI /// WOSB-Shutdown ausführbar wenn Countdown läuft /// Modus-Box Update ohne Neustart /// File Textbox Drag n' Drop /// Process Liste alphabetisch (Linq) /// Umbenannt Fenster/Prozess /// Drop NyanCat Easteregg /// 1.8.1 06.12.11 /// Fix Welcomescreen EN: fehlende Übersetzung /// Fix WOSB Time /// 1.9 21.02.12 /// Neues Icon /// Fadeout Start und Endvolume Sliderskalierung angepasst /// Musik Fadeout Polygon zur Veranschaulichung /// 2.0 24.03.13 /// Neue WebUI (Beta) /// Initialization verbessert /// -UAC Check/Admin verbessert /// UAC Manifest eingebaut /// IPv4 Standard /// UI: At: Sekunde bei 0 /// UI: Musik-Fadeout Polygon Layoutupdates /// UI: About: Linkupdates /// Fix: Miscalculation Time At /// Fix: Crash at WOSBIni /// 2.1 19.01.14 /// Option: Aktiv bleiben nach Aktion /// Option: Support Hybrid-Shutdown (Win8) /// Crash-Reporting /// Minimiert bei Autostart /// Fix: Wakeup Skip Sunday (vorläufig) /// Fix: Autostart /// 2.1.1 28.09.14 /// Systray Verbesserungen /// -Tooltips für alle Bedingungen /// -Kontextmenü umorganisiert /// Fix: Timer läuft weiter wenn Stop gedrückt wurde /// 2.1.2 28.09.14 /// Fix: ? /// 2.2 17.01.15 /// Neuer Modus: Android Reboot (Beta) /// Neue Bedingung: Cpu Auslastung /// Neue Bedingung: Netzwerk Auslastung (deaktiviert) /// Fix: Wait function counts to -1 /// Fix: Crash bei Systray + Launch (fehlender Eintrag) /// Fix: Modus/Conditions UI /// 2.3 27.07.15 /// Remote Shutdown über Argumente möglich /// Remote: Status übermittelt Mode Launch, Android; Conditions Cpu /// Error Reporting Filter /// Fix: Shutdown7 bleibt an bei gesetzter Option auch bei Argumenten /// Fix: Server startete nicht wenn Start über Autostart /// Fix: Systray brauchte zwei Doppelklicks beim ersten Start zum öffnen des Fensters /// Fix: URLs angepasst /// 2.3.1 10.04.16 /// Fix: UAC (Manifest eingebunden) /// Test Build: Debug Message for shutdown /// Wakeup (Ini) umbenannt /// 2.3.2 18.06.16 /// Remember Window Position (optional) /// Focus existing window if Second Instance called /// WPF NotifyIcon updated to 1.0.8 /// -resolved tooltip bug /// -systray disposed after execute /// 2.3.X XX /// New: Separate Data.t and twait Timespans for better handling /// New: Music Player Handling improved by introducing a Timer instead of a sleeping thread /// -does it fix the time calculation error? /// Fix: First Tick in Conditions Now, Time, Idle, Music immediately, not after 1 s /// X.Y xx.yy.zz /// /// TODO: /// -revisit shutdown procudure, is closing enough? /// /// Bugs: /// -Args + laufender Shutdown: Timer wurde schon überschrieben, also wird neuer Countdown gesetzt und die Warnung kommt /// -Music Time Calculation ~5-10s zu viel <überprüfen> /// -Noise Volume + Fadeout /// -Bei Status:Music wird immer Gesamtdauer angezeigt, korrigiere mit aktuellem Countdown /// -Status Launch: Programm ähnlich wie Music angeben /// /// Features: /// -Task Scheduling (PoC implemented in Settings) http://support.microsoft.com/kb/814596/de /// -Scheduling wie bei WOSB das automatisiert Start/Shutdown /// -Screensaver option http://www.codeproject.com/Questions/116918/Turn-on-screensaver-programmatically-in-C /// -Autostart ohne admin? /// -Framework 4.0 ohne APIPack (geht nicht sehr gut) /// -Single Instance überarbeiten? https://code.msdn.microsoft.com/Windows-7-Taskbar-Single-4120eafd/sourcecode?fileId=18659&pathId=1728260600 /// </summary> using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Web; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Threading; using System.Xml; using Hardcodet.Wpf.TaskbarNotification; using Microsoft.Win32; using Microsoft.WindowsAPICodePack.Dialogs; using Microsoft.WindowsAPICodePack.Shell; using Microsoft.WindowsAPICodePack.Taskbar; using RegawMOD.Android; using System.Net.NetworkInformation; namespace Shutdown7 { public partial class MainWindow : Window { #region Deklarationen [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ExitWindowsEx(uint uFlags, uint dwReason); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool LockWorkStation(); [DllImport("powrprof.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetSuspendState(bool Hibernate, bool ForceCritical, bool DisableWakeEvent); [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool AbortSystemShutdown(string lpMachineName); [DllImport("user32.dll")] private static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam); [DllImport("User32.dll")] //IdleTime private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); string WOSBZeit; int FadeTotalRunTime, startfade, /*length,*/ curSong; bool AtChecked, /*CpuMode, */NetworkMode, ScreenOffChecked, PlayNoiseChecked; double orgVolume, endVolume, percent; public static string curRemoteServer, curRemoteIP, curRemotePassword, curRemoteMac; public static int curRemotePort, /*Cpu, Network,*/ cpuHits, networkHits; public static bool remote; TimeSpan twait; TcpListener tcpListener; TcpClient client; ArrayList MusicFiles = new ArrayList(); DispatcherTimer Timer = new DispatcherTimer(); DispatcherTimer MusicTimer; Thread NoiseThread; //obsolete MediaPlayer mp3, noise; TaskbarIcon sysicon; MenuItem contextRestore, contextAbort, contextShutdown, contextShutdown1, contextShutdown2, contextShutdown3, contextShutdown4, contextShutdown5, contextShutdown6, contextShutdown7, contextExit; public static List<CodeItem> list; static ThumbnailToolBarButton tt1, tt2, tt3, tt4, tt5, tt6, /*tt7, */tt8; PerformanceCounter cpuCounter; #endregion #region Form #region Events public MainWindow() { InitializeComponent(); } private void Main_Initialized(object sender, EventArgs e) { #region Layout expanderMode.Header = Data.L["Condition"]; expanderSettings.Header = Data.L["Settings"]; buttonBrowseLaunchFile.Content = Data.L["Add"]; buttonDeleteLaunchFile.Content = Data.L["Remove"]; radioNow.Content = Data.L["ModeNow"]; radioTime.Content = Data.L["ModeTime"]; radioProcessClose.Content = (Data.S["AllProcesses"]) ? Data.L["ModeProcessClosed"] : Data.L["ModeWindowClosed"]; radioFileDelete.Content = Data.L["ModeFileDeleted"]; radioPlayMusic.Content = Data.L["ModeMusicPlayed"]; radioIdle.Content = Data.L["ModeIdle"]; radioCpu.Content = Data.L["ModeCpu"]; radioNetwork.Content = Data.L["ModeNetwork"]; At.Content = Data.L["At"]; In.Content = Data.L["In"]; buttonBrowseDeleteFile.Content = Data.L["Add"]; buttonDeleteDeleteFile.Content = Data.L["Remove"]; buttonBrowseMusicFile.Content = Data.L["Browse"]; buttonDeleteMusicFile.Content = Data.L["Remove"]; comboCpu.Items.Add(Data.L["Above"]); comboCpu.Items.Add(Data.L["Below"]); comboNetwork.Items.Add(Data.L["Down"]); comboNetwork.Items.Add(Data.L["Up"]); //labelNetworkBelow.Content = Data.L["Below"]; labelRemotePassword.Content = Data.L["Password"] + ": "; checkResumeLastAction.Content = Data.L["ResumeLastAction"]; checkScreenOff.Content = Data.L["ScreenOff"]; checkMusicFadeout.Content = Data.L["MusicFadeout"]; labelFade.Content = Data.L["FadeStart"]; labelOrgVol.Content = Data.L["MusicOrgVolume"]; labelEndVol.Content = Data.L["FadeEndVolume"]; checkPlayNoise.Content = Data.L["PlayNoise"]; SettingsLabel.Text = Data.L["Settings"]; UpdateModus(); //MusicUpDown Buttons Fix für XP buttonUpMusicFile.FontFamily = new FontFamily("Arial"); buttonDownMusicFile.FontFamily = new FontFamily("Arial"); //Music Scroll scrollMusicFiles.MaxHeight = SystemParameters.VirtualScreenHeight / 2; //Network Adapters comboNetworkAdapters.ItemsSource = GetNetworkAdapters(); if (Data.S["RemoteClient"]) { expanderRemote.Visibility = Visibility.Visible; foreach (string CurServer in Data.RemoteServers) textRemoteServer.Items.Add(CurServer); if (Data.S["WakeOnLan"]) { foreach (string CurMac in Data.RemoteMacs) textRemoteMac.Items.Add(CurMac); } } //Noise if (File.Exists(Data.NoisePath)) checkPlayNoise.IsEnabled = true; else checkPlayNoise.IsEnabled = false; #endregion if (Data.RemoteByArgs) { Hide(); curRemoteServer = Data.ArgsServer; curRemotePort = Data.ArgsPort; curRemotePassword = Data.ArgsPassword; RemoteClientStart(); } if (Data.S["ResumeLastAction"]) { if (LastActionisValid()) { ApplyActiontoUI(); StartShutdown(); } else Message.Show("Last action not valid anymore.", "Error"); } } bool LastActionisValid() { switch (Data.Condition) { case Data.Conditions.Time: case Data.Conditions.Idle: if (Data.t.TotalSeconds <= 3) return false; break; case Data.Conditions.Process: // make sure process is running bool stop = true; if (Data.S["AllProcesses"]) { foreach (Process p in Process.GetProcessesByName(Data.ProcessName)) { if (p.ProcessName == Data.ProcessName) { stop = false; break; } } } else { foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle == Data.ProcessName) { stop = false; break; } } } if (!stop) comboProcesses.SelectedValue = Data.ProcessName; else return false; break; case Data.Conditions.File: //make sure file exists if (!File.Exists(Data.FileName)) return false; break; case Data.Conditions.Cpu: break; case Data.Conditions.Music: default: return false; } return true; } void ApplyActiontoUI() { //comboModus.SelectedIndex = Convert.ToInt32(Data.Mode) - 1; switch (Data.Mode) { case Data.Modes.Shutdown: comboModus.SelectedIndex = 0; break; case Data.Modes.Restart: comboModus.SelectedIndex = 1; break; case Data.Modes.Logoff: comboModus.SelectedIndex = 2; break; case Data.Modes.Lock: comboModus.SelectedIndex = 3; break; case Data.Modes.Standby: case Data.Modes.StandbyWOSB: comboModus.SelectedIndex = 4; break; case Data.Modes.Hibernate: case Data.Modes.HibernateWOSB: comboModus.SelectedIndex = 5; break; case Data.Modes.Launch: textLaunchFile.Text = Data.LaunchFile; if (Data.S["WOSB"]) comboModus.SelectedIndex = 8; else comboModus.SelectedIndex = 6; break; case Data.Modes.HibernateWOSBIni: comboModus.SelectedIndex = 6; break; case Data.Modes.HibernateWOSBTime: comboModus.SelectedIndex = 7; break; case Data.Modes.WakeOnLan: if (Data.S["WOSB"]) comboModus.SelectedIndex = 9; else comboModus.SelectedIndex = 7; break; case Data.Modes.RestartAndroid: default: comboModus.SelectedIndex = -1; break; } switch (Data.Condition) { case Data.Conditions.Time: radioTime.IsChecked = true; In.IsChecked = true; hh.Value = Data.t.Hours; mm.Value = Data.t.Minutes; ss.Value = Data.t.Seconds; // can you skip it since startshutdown/execute? break; case Data.Conditions.Process: radioProcessClose.IsChecked = true; break; case Data.Conditions.File: radioFileDelete.IsChecked = true; textDeleteFile.Text = Data.FileName; break; case Data.Conditions.Music: radioPlayMusic.IsChecked = true; Message.Show("Not supported (yet).", "Warning"); break; case Data.Conditions.Idle: radioIdle.IsChecked = true; hh.Value = Data.t.Hours; mm.Value = Data.t.Minutes; ss.Value = Data.t.Seconds; break; case Data.Conditions.Cpu: radioCpu.IsChecked = true; cpu.Value = Data.CpuValue; comboCpu.SelectedIndex = Data.CpuMode ? 0 : 1; break; //case Data.Conditions.None: //case Data.Conditions.Now: //case Data.Conditions.Network: default: Message.Show("Nothing to do."); return; } } #region Aero protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); Win7.Glass(this); } #endregion #region Checkboxen private void radioNow_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.Now; if (Visibility != Visibility.Visible) return; stackTime.Visibility = Visibility.Collapsed; stackProcess.Visibility = Visibility.Collapsed; stackFile.Visibility = Visibility.Collapsed; stackMusic.Visibility = Visibility.Collapsed; stackCpu.Visibility = Visibility.Collapsed; stackNetwork.Visibility = Visibility.Collapsed; stackMusicVol.IsEnabled = false; checkMusicFadeout.IsEnabled = false; checkMusicFadeout.IsChecked = false; checkPlayNoise.IsEnabled = false; checkPlayNoise.IsChecked = false; GoButton_Enabled(); } private void radioTime_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.Time; stackTime.Visibility = Visibility.Visible; stackProcess.Visibility = Visibility.Collapsed; stackFile.Visibility = Visibility.Collapsed; stackMusic.Visibility = Visibility.Collapsed; stackCpu.Visibility = Visibility.Collapsed; stackNetwork.Visibility = Visibility.Collapsed; At.IsEnabled = true; In.IsEnabled = true; stackMusicVol.IsEnabled = false; checkMusicFadeout.IsEnabled = false; checkMusicFadeout.IsChecked = false; if (!expanderRemote.IsExpanded && File.Exists(Data.NoisePath)) checkPlayNoise.IsEnabled = true; GoButton_Enabled(); } private void radioProcess_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.Process; stackTime.Visibility = Visibility.Collapsed; stackProcess.Visibility = Visibility.Visible; stackFile.Visibility = Visibility.Collapsed; stackMusic.Visibility = Visibility.Collapsed; stackCpu.Visibility = Visibility.Collapsed; stackNetwork.Visibility = Visibility.Collapsed; if (Data.S["AllProcesses"]) { //comboProcesses.DisplayMemberPath = "ProcessName"; comboProcesses.ItemsSource = from x in Process.GetProcesses() where (x.ProcessName.Length > 0) orderby x.ProcessName select x.ProcessName + ".exe"; } else { //comboProcesses.DisplayMemberPath = "MainWindowTitle"; comboProcesses.ItemsSource = from x in Process.GetProcesses() where (x.MainWindowTitle.Length > 0) orderby x.MainWindowTitle select x.MainWindowTitle; } stackMusicVol.IsEnabled = false; checkMusicFadeout.IsEnabled = false; checkMusicFadeout.IsChecked = false; if (File.Exists(Data.NoisePath)) checkPlayNoise.IsEnabled = true; GoButton_Enabled(); } private void radioFile_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.File; stackTime.Visibility = Visibility.Collapsed; stackProcess.Visibility = Visibility.Collapsed; stackFile.Visibility = Visibility.Visible; stackMusic.Visibility = Visibility.Collapsed; stackCpu.Visibility = Visibility.Collapsed; stackNetwork.Visibility = Visibility.Collapsed; stackMusicVol.IsEnabled = false; checkMusicFadeout.IsEnabled = false; checkMusicFadeout.IsChecked = false; if (File.Exists(Data.NoisePath)) checkPlayNoise.IsEnabled = true; GoButton_Enabled(); } private void radioMusic_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.Music; stackTime.Visibility = Visibility.Collapsed; stackProcess.Visibility = Visibility.Collapsed; stackFile.Visibility = Visibility.Collapsed; stackMusic.Visibility = Visibility.Visible; stackCpu.Visibility = Visibility.Collapsed; stackNetwork.Visibility = Visibility.Collapsed; stackMusicVol.IsEnabled = true; checkMusicFadeout.IsEnabled = true; checkPlayNoise.IsEnabled = false; checkPlayNoise.IsChecked = false; GoButton_Enabled(); } private void radioIdle_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.Idle; stackTime.Visibility = Visibility.Visible; stackProcess.Visibility = Visibility.Collapsed; stackFile.Visibility = Visibility.Collapsed; stackMusic.Visibility = Visibility.Collapsed; stackCpu.Visibility = Visibility.Collapsed; stackNetwork.Visibility = Visibility.Collapsed; In.IsChecked = true; At.IsEnabled = false; In.IsEnabled = false; stackMusicVol.IsEnabled = false; checkMusicFadeout.IsEnabled = false; checkMusicFadeout.IsChecked = false; checkPlayNoise.IsEnabled = true; GoButton_Enabled(); } private void radioCpu_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.Cpu; stackTime.Visibility = Visibility.Visible; stackProcess.Visibility = Visibility.Collapsed; stackFile.Visibility = Visibility.Collapsed; stackMusic.Visibility = Visibility.Collapsed; stackCpu.Visibility = Visibility.Visible; stackNetwork.Visibility = Visibility.Collapsed; In.IsChecked = true; At.IsEnabled = false; In.IsEnabled = false; stackMusicVol.IsEnabled = false; checkMusicFadeout.IsEnabled = false; checkMusicFadeout.IsChecked = false; if (File.Exists(Data.NoisePath)) checkPlayNoise.IsEnabled = true; GoButton_Enabled(); } private void radioNetwork_Checked(object sender, RoutedEventArgs e) { Data.Condition = Data.Conditions.Network; stackTime.Visibility = Visibility.Visible; stackProcess.Visibility = Visibility.Collapsed; stackFile.Visibility = Visibility.Collapsed; stackMusic.Visibility = Visibility.Collapsed; stackCpu.Visibility = Visibility.Collapsed; stackNetwork.Visibility = Visibility.Visible; In.IsChecked = true; At.IsEnabled = false; In.IsEnabled = false; stackMusicVol.IsEnabled = false; checkMusicFadeout.IsEnabled = false; checkMusicFadeout.IsChecked = false; if (File.Exists(Data.NoisePath)) checkPlayNoise.IsEnabled = true; GoButton_Enabled(); } private void In_Checked(object sender, RoutedEventArgs e) { hh.Value = Data.t.Hours; mm.Value = Data.t.Minutes; ss.Value = Data.t.Seconds; } private void At_Checked(object sender, RoutedEventArgs e) { Data.t = TimeSpan.Parse(hh.Value + ":" + mm.Value + ":" + ss.Value); hh.Value = DateTime.Now.Hour; mm.Value = DateTime.Now.Minute; ss.Value = 0/*DateTime.Now.Second*/; } private void checkPlayNoise_Checked(object sender, RoutedEventArgs e) { radioPlayMusic.IsEnabled = false; if (Data.Condition == Data.Conditions.Music) { radioTime.IsChecked = true; Data.Condition = Data.Conditions.Time; } } private void checkPlayNoise_Unchecked(object sender, RoutedEventArgs e) { radioPlayMusic.IsEnabled = true; } private void checkMusicFadeout_Checked(object sender, RoutedEventArgs e) { updateCanvas(); stackMusicFadeout.Visibility = Visibility.Visible; } private void checkMusicFadeout_Unchecked(object sender, RoutedEventArgs e) { stackMusicFadeout.Visibility = Visibility.Collapsed; } private void checkResumeLastAction_Checked(object sender, RoutedEventArgs e) { Data.t = TimeSpan.Parse(hh.Value + ":" + mm.Value + ":" + ss.Value); if (!LastActionisValid()) { checkResumeLastAction.Checked -= checkResumeLastAction_Checked; checkResumeLastAction.IsChecked = false; Message.Show("Not valid"); checkResumeLastAction.Checked += checkResumeLastAction_Checked; } } #endregion #region Modus public void UpdateModus() { list = new List<CodeItem>(); list.Clear(); if (Data.S["ModusIcons"]) { list.Add(new CodeItem(Data.L["Shutdown"], "pack://application:,,,/Shutdown7;component/Resources/Shutdown.ico")); list.Add(new CodeItem(Data.L["Restart"], "pack://application:,,,/Shutdown7;component/Resources/Reboot.ico")); list.Add(new CodeItem(Data.L["Logoff"], "pack://application:,,,/Shutdown7;component/Resources/Logoff.ico")); list.Add(new CodeItem(Data.L["Lock"], "pack://application:,,,/Shutdown7;component/Resources/Logoff.ico")); list.Add(new CodeItem(Data.L["Standby"], "pack://application:,,,/Shutdown7;component/Resources/Standby.ico")); list.Add(new CodeItem(Data.L["Hibernate"], "pack://application:,,,/Shutdown7;component/Resources/Standby.ico")); if (Data.S["WOSB"]) { list.Add(new CodeItem(Data.L["HibernateWOSBTime"], "pack://application:,,,/Shutdown7;component/Resources/WOSB.ico")); list.Add(new CodeItem(Data.L["HibernateWOSBIni"], "pack://application:,,,/Shutdown7;component/Resources/WOSB.ico")); } if (Data.S["WakeOnLan"]) list.Add(new CodeItem(Data.L["WakeOnLan"], "pack://application:,,,/Shutdown7;component/Resources/WakeOnLan.ico")); list.Add(new CodeItem(Data.L["LaunchFile"], "pack://application:,,,/Shutdown7;component/Resources/EXE.ico")); if (Data.debug_beta) list.Add(new CodeItem(Data.L["RestartAndroid"], "pack://application:,,,/Shutdown7;component/Resources/Android.ico")); } else { list.Add(new CodeItem(Data.L["Shutdown"], "")); list.Add(new CodeItem(Data.L["Restart"], "")); list.Add(new CodeItem(Data.L["Logoff"], "")); list.Add(new CodeItem(Data.L["Lock"], "")); list.Add(new CodeItem(Data.L["Standby"], "")); list.Add(new CodeItem(Data.L["Hibernate"], "")); if (Data.S["WakeOnLan"]) list.Add(new CodeItem(Data.L["WakeOnLan"], "")); if (Data.S["WOSB"]) { list.Add(new CodeItem(Data.L["HibernateWOSBTime"], "")); list.Add(new CodeItem(Data.L["HibernateWOSBIni"], "")); } list.Add(new CodeItem(Data.L["LaunchFile"], "")); if (Data.debug_beta) list.Add(new CodeItem(Data.L["RestartAndroid"], "")); } int curSelectionI = comboModus.SelectedIndex; comboModus.ItemsSource = list; if (curSelectionI < 6) comboModus.SelectedIndex = curSelectionI; } private void Modus_TextChanged(object sender, TextChangedEventArgs e) { GoButton_Enabled(); if (Modus.Text == Data.L["WakeOnLan"]) Data.Mode = Data.Modes.WakeOnLan; else if (Modus.Text == Data.L["HibernateWOSBIni"]) Data.Mode = Data.Modes.HibernateWOSBIni; else if (Modus.Text == Data.L["HibernateWOSBTime"]) Data.Mode = Data.Modes.HibernateWOSBTime; else if (Modus.Text == Data.L["LaunchFile"]) Data.Mode = Data.Modes.Launch; else if (Modus.Text == Data.L["RestartAndroid"]) Data.Mode = Data.Modes.RestartAndroid; else { switch (comboModus.SelectedIndex) { case 0: Data.Mode = Data.Modes.Shutdown; break; case 1: Data.Mode = Data.Modes.Restart; break; case 2: Data.Mode = Data.Modes.Logoff; break; case 3: Data.Mode = Data.Modes.Lock; break; case 4: if (Data.S["WOSB"]) Data.Mode = Data.Modes.StandbyWOSB; else Data.Mode = Data.Modes.Standby; break; case 5: if (Data.S["WOSB"]) Data.Mode = Data.Modes.HibernateWOSB; else Data.Mode = Data.Modes.Hibernate; break; } } if (Modus.Text == Data.L["HibernateWOSBIni"] | Modus.Text == Data.L["HibernateWOSBTime"] | Modus.Text == Data.L["LaunchFile"]) { expanderRemote.IsEnabled = false; expanderRemote.IsExpanded = false; } else { expanderRemote.IsEnabled = true; } if (Modus.Text != Data.L["WakeOnLan"]) { labelRemoteMac.Visibility = Visibility.Collapsed; textRemoteMac.Visibility = Visibility.Collapsed; labelRemotePassword.Visibility = Visibility.Visible; textRemotePassword.Visibility = Visibility.Visible; } else { expanderRemote.IsExpanded = true; labelRemoteMac.Visibility = Visibility.Visible; textRemoteMac.Visibility = Visibility.Visible; textRemoteServer.Text = IPAddress.Broadcast.ToString(); labelRemotePassword.Visibility = Visibility.Collapsed; textRemotePassword.Visibility = Visibility.Collapsed; } if (Modus.Text == Data.L["HibernateWOSBTime"]) { radioNow.IsEnabled = false; radioProcessClose.IsEnabled = false; radioFileDelete.IsEnabled = false; radioPlayMusic.IsEnabled = false; radioIdle.IsEnabled = false; radioTime.IsChecked = true; radioCpu.IsEnabled = false; At.IsChecked = true; In.IsEnabled = false; } else { radioNow.IsEnabled = true; radioProcessClose.IsEnabled = true; radioFileDelete.IsEnabled = true; radioPlayMusic.IsEnabled = true; radioIdle.IsEnabled = true; radioCpu.IsEnabled = true; In.IsEnabled = true; } if (Modus.Text == Data.L["HibernateWOSBIni"]) { radioNow.IsChecked = true; expanderMode.IsEnabled = false; expanderMode.IsExpanded = false; } else { expanderMode.IsEnabled = true; expanderMode.IsExpanded = true; } if (Modus.Text == Data.L["LaunchFile"]) stackLaunchFile.Visibility = Visibility.Visible; else stackLaunchFile.Visibility = Visibility.Collapsed; } #region LaunchFile private void buttonBrowseLaunchFile_Click(object sender, RoutedEventArgs e) { try { if (ShellLibrary.IsPlatformSupported) { CommonOpenFileDialog fd = new CommonOpenFileDialog(Data.L["SelectFile"]); fd.Filters.Add(new CommonFileDialogFilter(Data.L["AllFiles"], "*.*")); fd.EnsureFileExists = true; if (fd.ShowDialog() == CommonFileDialogResult.Ok) { textLaunchFile.Text = fd.FileName; Data.LaunchFile = fd.FileName; buttonBrowseLaunchFile.IsEnabled = false; buttonDeleteLaunchFile.IsEnabled = true; } } else { OpenFileDialog fd = new OpenFileDialog(); fd.Filter = Data.L["AllFiles"] + "|*.*"; fd.Title = Data.L["SelectFile"]; fd.Multiselect = true; fd.CheckFileExists = true; if ((bool)fd.ShowDialog()) { textLaunchFile.Text = fd.FileName; Data.LaunchFile = fd.FileName; buttonBrowseLaunchFile.IsEnabled = false; buttonDeleteLaunchFile.IsEnabled = true; } } } catch (Exception ex) { Message.Show(ex.Message, "Shutdown7", "Error"); } } private void buttonDeleteLaunchFile_Click(object sender, RoutedEventArgs e) { textLaunchFile.Text = ""; Data.LaunchFile = ""; buttonBrowseLaunchFile.IsEnabled = true; buttonDeleteLaunchFile.IsEnabled = false; } void textLaunchFile_TextChanged(object sender, TextChangedEventArgs e) { GoButton_Enabled(); } #endregion #endregion #region Conditions #region Time /*private void hh_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !Char.IsDigit(Convert.ToChar(e.Text)); } private void mm_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !Char.IsDigit(Convert.ToChar(e.Text)); if (Int32.Parse(mm.Text) > 59) { mm.Text = (Int32.Parse(e.Text) - 60).ToString(); hh.Text = (Int32.Parse(hh.Text) + 1).ToString(); if (hh.Text.Length == 1) hh.Text = "0" + hh.Text; if (mm.Text.Length == 1) mm.Text = "0" + mm.Text; if (ss.Text.Length == 1) ss.Text = "0" + ss.Text; } } private void ss_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !Char.IsDigit(Convert.ToChar(e.Text)); } private void hh_KeyUp(object sender, KeyEventArgs e) { try { if (Int32.Parse(hh.Text) > 23) { hh.Text = "23"; if (hh.Text.Length == 1) hh.Text = "0" + hh.Text; if (mm.Text.Length == 1) mm.Text = "0" + mm.Text; if (ss.Text.Length == 1) ss.Text = "0" + ss.Text; } } catch { } } private void mm_KeyUp(object sender, KeyEventArgs e) { try { if (Int32.Parse(mm.Text) > 59) { mm.Text = (Int32.Parse(mm.Text) - 60).ToString(); hh.Text = (Int32.Parse(hh.Text) + 1).ToString(); if (hh.Text.Length == 1) hh.Text = "0" + hh.Text; if (mm.Text.Length == 1) mm.Text = "0" + mm.Text; if (ss.Text.Length == 1) ss.Text = "0" + ss.Text; } } catch { } } private void ss_KeyUp(object sender, KeyEventArgs e) { try { if (Int32.Parse(ss.Text) > 59) { ss.Text = (Int32.Parse(ss.Text) - 60).ToString(); mm.Text = (Int32.Parse(mm.Text) + 1).ToString(); if (hh.Text.Length == 1) hh.Text = "0" + hh.Text; if (mm.Text.Length == 1) mm.Text = "0" + mm.Text; if (ss.Text.Length == 1) ss.Text = "0" + ss.Text; } } catch { } }*/ #endregion #region Process void comboProcesses_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.Invoke((Action)delegate { comboProcesses_SelectionChanged(sender, e); }); return; } GoButton_Enabled(); try { if ((string)comboProcesses.SelectedItem != "") Data.ProcessName = e.AddedItems[0].ToString().Replace(".exe", ""); } catch { } } #endregion #region File private void buttonBrowseDeleteFile_Click(object sender, RoutedEventArgs e) { try { if (ShellLibrary.IsPlatformSupported) { CommonOpenFileDialog fd = new CommonOpenFileDialog(Data.L["SelectFile"]); fd.Filters.Add(new CommonFileDialogFilter(Data.L["AllFiles"], "*.*")); fd.EnsureFileExists = true; if (fd.ShowDialog() == CommonFileDialogResult.Ok) { textDeleteFile.Text = fd.FileName; Data.FileName = fd.FileName; buttonBrowseDeleteFile.IsEnabled = false; buttonDeleteDeleteFile.IsEnabled = true; } } else { OpenFileDialog fd = new OpenFileDialog(); fd.Filter = Data.L["AllFiles"] + "|*.*"; fd.Title = Data.L["SelectFile"]; fd.Multiselect = true; fd.CheckFileExists = true; if ((bool)fd.ShowDialog()) { textDeleteFile.Text = fd.FileName; Data.FileName = fd.FileName; buttonBrowseDeleteFile.IsEnabled = false; buttonDeleteDeleteFile.IsEnabled = true; } } } catch (Exception ex) { Message.Show(ex.Message, "Error"); } } private void buttonDeleteDeleteFile_Click(object sender, RoutedEventArgs e) { textDeleteFile.Text = ""; Data.FileName = ""; buttonBrowseDeleteFile.IsEnabled = true; buttonDeleteDeleteFile.IsEnabled = false; } void textDeleteFile_TextChanged(object sender, TextChangedEventArgs e) { GoButton_Enabled(); } private void textDeleteFile_PreviewDragEnter(object sender, DragEventArgs e) { string f = null; object text = e.Data.GetData(DataFormats.FileDrop); TextBox tb = sender as TextBox; if (tb != null) { if (text != null) f = string.Format("{0}", ((string[])text)[0]); if (File.Exists(f) | Directory.Exists(f)) { e.Effects = DragDropEffects.Copy; e.Handled = true; } } } private void textDeleteFile_PreviewDrop(object sender, DragEventArgs e) { string f = null; object text = e.Data.GetData(DataFormats.FileDrop); TextBox tb = sender as TextBox; if (tb != null) { if (text != null) f = string.Format("{0}", ((string[])text)[0]); if (File.Exists(f) | Directory.Exists(f)) { tb.Text = f; buttonBrowseDeleteFile.IsEnabled = false; buttonDeleteDeleteFile.IsEnabled = true; } } } #endregion #region Music private void buttonBrowseMusicFile_Click(object sender, RoutedEventArgs e) { try { if (ShellLibrary.IsPlatformSupported) { CommonOpenFileDialog fd = new CommonOpenFileDialog(Data.L["SelectFiles"]); fd.Filters.Add(new CommonFileDialogFilter(Data.L["MusicFiles"], "*.mp3,*.wma,*.wav,*.m4a,*.aac")); fd.Filters.Add(new CommonFileDialogFilter(Data.L["PlayLists"], "*.m3u,*.wpl,*.xspf")); fd.Multiselect = true; fd.EnsureFileExists = true; fd.InitialDirectory = KnownFolders.Music.Path; if (fd.ShowDialog() == CommonFileDialogResult.Ok) { foreach (string filename in fd.FileNames) { MusicFilesToList(filename); } } } else { OpenFileDialog fd = new OpenFileDialog(); fd.Filter = Data.L["MusicFiles"] + "|*.mp3;*.wma;*.wav;*.m4a;*.aac;" + "|" + Data.L["PlayLists"] + "|*.m3u,*.wpl,*.xspf"; fd.Title = Data.L["SelectFiles"]; fd.Multiselect = true; fd.CheckFileExists = true; if ((bool)fd.ShowDialog()) { foreach (string filename in fd.FileNames) { MusicFilesToList(filename); } } } } catch (Exception ex) { Message.Show(ex.Message, "Error"); } if (listMusicFiles.Items.Count > 0) listMusicFiles.Visibility = Visibility.Visible; GoButton_Enabled(); } void MusicFilesToList(string filename) { if (Path.GetExtension(filename) == ".m3u") { string[] m3u = File.ReadAllLines(filename); foreach (string f in m3u) { try { string _filename; if (f.Substring(1, 1) == ":") //Anderes Laufwerk _filename = Path.GetFullPath(f); else _filename = Path.GetFullPath(Path.GetDirectoryName(filename) + "\\" + f); if (Data.debug_verbose) Message.Show(_filename, "Information"); MusicFiles.Add(_filename); listMusicFiles.Items.Add(Path.GetFileName(f).Replace(Path.GetExtension(_filename), "")); } catch { } } } else if (Path.GetExtension(filename) == ".wpl") { XmlTextReader readList = new XmlTextReader(filename); while (readList.Read()) { if (readList.NodeType == XmlNodeType.Element) { if (readList.LocalName.Equals("media")) { try { string _filename; if (readList.GetAttribute(0).ToString().Substring(1, 1) == ":") //Anderes Laufwerk _filename = Path.GetFullPath(readList.GetAttribute(0).ToString()); else _filename = Path.GetFullPath(Path.GetDirectoryName(filename) + "\\" + readList.GetAttribute(0).ToString()); if (Data.debug_verbose) Message.Show(_filename, "Information"); MusicFiles.Add(_filename); listMusicFiles.Items.Add(Path.GetFileName(readList.GetAttribute(0).ToString()).Replace(Path.GetExtension(_filename), "")); } catch { } } } } } else if (Path.GetExtension(filename) == ".xspf") { XmlTextReader readList = new XmlTextReader(filename); while (readList.Read()) { if (readList.LocalName.Equals("location")) { readList.Read(); //Springe zu nächstem Element try { if (!String.IsNullOrEmpty(readList.Value.Trim())) { string _filename = new Uri(readList.Value.Trim()).LocalPath; if (Data.debug_verbose) Message.Show(_filename, "Information"); MusicFiles.Add(_filename); listMusicFiles.Items.Add(Path.GetFileName(_filename).Replace(Path.GetExtension(_filename), "")); } } catch { } } } } else { MusicFiles.Add(filename); listMusicFiles.Items.Add(Path.GetFileName(filename).Replace(Path.GetExtension(filename), "")); } } private void buttonDeleteMusicFile_Click(object sender, RoutedEventArgs e) { if (listMusicFiles.SelectedIndex == -1) return; MusicFiles.RemoveAt(listMusicFiles.SelectedIndex); listMusicFiles.Items.RemoveAt(listMusicFiles.SelectedIndex); if (listMusicFiles.Items.Count == 0) { buttonDeleteMusicFile.IsEnabled = false; buttonUpMusicFile.IsEnabled = false; buttonDownMusicFile.IsEnabled = false; } GoButton_Enabled(); } private void listMusicFiles_SelectionChanged(object sender, SelectionChangedEventArgs e) { buttonDeleteMusicFile.IsEnabled = true; buttonUpMusicFile.IsEnabled = true; buttonDownMusicFile.IsEnabled = true; GoButton_Enabled(); } private void buttonUpMusicFile_Click(object sender, RoutedEventArgs e) { if (listMusicFiles.SelectedIndex == -1) return; int iIndexSel = listMusicFiles.SelectedIndex; int iIndexFirst = 0; if ((iIndexSel != -1) && (iIndexSel - 1 >= iIndexFirst)) { Object oItem = MusicFiles[iIndexSel]; MusicFiles.RemoveAt(iIndexSel); MusicFiles.Insert(iIndexSel - 1, oItem); oItem = listMusicFiles.Items.GetItemAt(iIndexSel); listMusicFiles.Items.RemoveAt(iIndexSel); listMusicFiles.Items.Insert(iIndexSel - 1, oItem); listMusicFiles.SelectedIndex = listMusicFiles.Items.IndexOf(oItem); listMusicFiles.ScrollIntoView(listMusicFiles.SelectedItem); } } private void buttonDownMusicFile_Click(object sender, RoutedEventArgs e) { if (listMusicFiles.SelectedIndex == -1) return; int iIndexSel = listMusicFiles.SelectedIndex; int iIndexLast = listMusicFiles.Items.Count - 1; if ((iIndexSel != -1) && (iIndexSel + 1 <= iIndexLast)) { Object oItem = MusicFiles[iIndexSel]; MusicFiles.RemoveAt(iIndexSel); MusicFiles.Insert(iIndexSel + 1, oItem); oItem = listMusicFiles.Items.GetItemAt(iIndexSel); listMusicFiles.Items.RemoveAt(iIndexSel); listMusicFiles.Items.Insert(iIndexSel + 1, oItem); listMusicFiles.SelectedIndex = listMusicFiles.Items.IndexOf(oItem); listMusicFiles.ScrollIntoView(listMusicFiles.SelectedItem); } } private void sliderFade_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { labelFadeSlider.Content = ((e.NewValue < 10) ? " " : "") + e.NewValue + " %"; if (canvasMusicFadeout != null) updateCanvas(); } private void sliderOrgVol_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { labelOrgVolSlider.Content = ((e.NewValue < 100) ? " " : "") + e.NewValue + " %"; if (canvasMusicFadeout != null) updateCanvas(); } private void sliderEndVol_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { labelEndVolSlider.Content = ((e.NewValue < 10) ? " " : "") + e.NewValue + " %"; if (canvasMusicFadeout != null) updateCanvas(); } void updateCanvas() { PointCollection p = new PointCollection(); p.Add(new Point(0, canvasMusicFadeout.ActualHeight - canvasMusicFadeout.ActualHeight * (sliderOrgVol.Value / 100))); p.Add(new Point(0, canvasMusicFadeout.ActualHeight)); p.Add(new Point(canvasMusicFadeout.ActualWidth, canvasMusicFadeout.ActualHeight)); p.Add(new Point(canvasMusicFadeout.ActualWidth, canvasMusicFadeout.ActualHeight - canvasMusicFadeout.ActualHeight * (sliderOrgVol.Value / 100) * (sliderEndVol.Value / 100))); p.Add(new Point(canvasMusicFadeout.ActualWidth * (sliderFade.Value / 100), canvasMusicFadeout.ActualHeight - canvasMusicFadeout.ActualHeight * (sliderOrgVol.Value / 100))); polygonMusicFadeout.Points = p; } #endregion #endregion #region Remote private void expanderRemote_Expanded(object sender, RoutedEventArgs e) { if (Data.Mode == Data.Modes.WakeOnLan) return; //radioTime.IsEnabled = true; if (!(bool)radioNow.IsChecked) radioTime.IsChecked = true; radioProcessClose.IsEnabled = false; radioFileDelete.IsEnabled = false; radioPlayMusic.IsEnabled = false; radioIdle.IsEnabled = false; radioCpu.IsEnabled = false; radioNetwork.IsEnabled = false; checkPlayNoise.IsEnabled = false; checkPlayNoise.IsChecked = false; GoButton_Enabled(); } private void expanderRemote_Collapsed(object sender, RoutedEventArgs e) { radioProcessClose.IsEnabled = true; radioFileDelete.IsEnabled = true; radioPlayMusic.IsEnabled = true; radioIdle.IsEnabled = true; radioCpu.IsEnabled = true; radioNetwork.IsEnabled = true; checkPlayNoise.IsEnabled = true; GoButton_Enabled(); } private void textRemotePassword_PasswordChanged(object sender, RoutedEventArgs e) { GoButton_Enabled(); } private void textRemoteServerPortMac_TextChanged(object sender, TextChangedEventArgs e) { GoButton_Enabled(); } private void textRemotePort_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !Char.IsDigit(Convert.ToChar(e.Text)); } #endregion #region GoButton void GoButton_Enabled() { if (this.Visibility != Visibility.Visible) return; GoButton.IsEnabled = true; #region Modus if (Modus.Text == "") GoButton.IsEnabled = false; if (((bool)!radioNow.IsChecked && (bool)!radioTime.IsChecked && (bool)!radioProcessClose.IsChecked && (bool)!radioFileDelete.IsChecked && (bool)!radioPlayMusic.IsChecked && (bool)!radioIdle.IsChecked && (bool)!radioCpu.IsChecked && (bool)!radioNetwork.IsChecked) && Modus.Text != Data.L["HibernateWOSBIni"]) GoButton.IsEnabled = false; if (Modus.Text == Data.L["LaunchFile"]) { if (textLaunchFile.Text == "") GoButton.IsEnabled = false; } #endregion #region Processs if ((bool)radioProcessClose.IsChecked) { if ((string)comboProcesses.SelectedItem == null) GoButton.IsEnabled = false; } #endregion #region File if ((bool)radioFileDelete.IsChecked) { if (textDeleteFile.Text == "") GoButton.IsEnabled = false; } #endregion #region Music if ((bool)radioPlayMusic.IsChecked) { if (listMusicFiles.Items.Count == 0) GoButton.IsEnabled = false; } #endregion #region Remote if (expanderRemote.IsExpanded | Data.Mode == Data.Modes.WakeOnLan) { if (Modus.Text == Data.L["WakeOnLan"]) { if (textRemoteServer.Text == "" | textRemotePort.Text == "" | textRemoteMac.Text == "") GoButton.IsEnabled = false; } else { if (textRemoteServer.Text == "" | textRemotePort.Text == "" | textRemotePassword.Password == "") GoButton.IsEnabled = false; } } #endregion } private void GoButton_Click(object sender, RoutedEventArgs e) { if ((string)GoButton.Content == Data.L["Abort"]) StopShutdown(); else StartShutdown(); } #endregion #region Keydown private void Main_KeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.F1: Process.Start("http://www.shutdown7.com/faq.php?lang=" + Data.Lang.ToLower()); break; } } #endregion #region OpenWindows private void Updates_Click(object sender, RoutedEventArgs e) { new Updater().Show(); //if (Data.debug_debugging) // throw new ArgumentException("The parameter was invalid."); } private void About_Click(object sender, RoutedEventArgs e) { new About().Show(); } private void Settings_Click(object sender, RoutedEventArgs e) { new Settings().Show(); } #endregion #region Close protected override void OnClosing(CancelEventArgs e) { Remote.ExitRemoteServer = true; if (Data.S["SaveWindowState"]) Properties.Settings.Default.Save(); else Properties.Settings.Default.Reset(); DisposeSystray(); Xml.Write(); base.OnClosing(e); Environment.Exit(0); } /// <summary> /// Called when the window is closed /// </summary> /*private void Main_Closed(object sender, EventArgs e) { // save the property settings Properties.Settings.Default.Save(); }*/ #endregion #region Win7 private void Main_ContentRendered(object sender, EventArgs e) { if (Data.S["Jumplist"]) Win7.Jumplist(); if (Data.S["ThumbnailToolbar"]) ThumbnailToolbar(); if (Data.debug_stopwatch) { if (Environment.GetCommandLineArgs().Length <= 1) { App.stopwatch.Stop(); Message.Show("Startzeit: " + App.stopwatch.Elapsed.TotalMilliseconds, "Start", "Information"); } } } #region ThumbnailToolbar void ThumbnailToolbar() { tt1 = new ThumbnailToolBarButton(Properties.Resources.Shutdown, Data.L["Shutdown"]); tt2 = new ThumbnailToolBarButton(Properties.Resources.Reboot, Data.L["Restart"]); tt3 = new ThumbnailToolBarButton(Properties.Resources.Logoff, Data.L["Logoff"]); tt4 = new ThumbnailToolBarButton(Properties.Resources.Logoff, Data.L["Lock"]); tt5 = new ThumbnailToolBarButton(Properties.Resources.Standby, Data.L["Standby"]); tt6 = new ThumbnailToolBarButton(Properties.Resources.Standby, Data.L["Hibernate"]); //tt7 = new ThumbnailToolBarButton(Properties.Resources.WOSB, Data.L["HibernateWOSBIni"]); tt8 = new ThumbnailToolBarButton(Properties.Resources.Abort, Data.L["Abort"]); tt1.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt1_Click); tt2.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt2_Click); tt3.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt3_Click); tt4.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt4_Click); tt5.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt5_Click); tt6.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt6_Click); //tt7.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt7_Click); tt8.Click += new EventHandler<ThumbnailButtonClickedEventArgs>(tt8_Click); tt8.Enabled = false; //Win7.ThumbnailToolbar(null , Data.L["Shutdown"], "Shutdown"); Win7.ThumbnailToolbar(new WindowInteropHelper(Application.Current.MainWindow).Handle, new ThumbnailToolBarButton[] { tt1, tt2, tt3, tt4, tt5, tt6, /*tt7, */tt8 }, this); } public void ShowThumbnailToolbar() { if (tt1 == null) { ThumbnailToolbar(); return; } tt1.Visible = true; tt2.Visible = true; tt3.Visible = true; tt4.Visible = true; tt5.Visible = true; tt6.Visible = true; //tt7.Visible = true; tt8.Visible = true; } public void HideThumbnailToolbar() { if (tt1 == null) { return; } tt1.Visible = false; tt2.Visible = false; tt3.Visible = false; tt4.Visible = false; tt5.Visible = false; tt6.Visible = false; //tt7.Visible = false; tt8.Visible = false; } void tt1_Click(object sender, ThumbnailButtonClickedEventArgs e) { Data.t = TimeSpan.FromSeconds(5); Data.Mode = Data.Modes.Shutdown; Execute(); } void tt2_Click(object sender, ThumbnailButtonClickedEventArgs e) { Data.t = TimeSpan.FromSeconds(5); Data.Mode = Data.Modes.Restart; Execute(); } void tt3_Click(object sender, ThumbnailButtonClickedEventArgs e) { Data.t = TimeSpan.FromSeconds(5); Data.Mode = Data.Modes.Logoff; Execute(); } void tt4_Click(object sender, ThumbnailButtonClickedEventArgs e) { Data.t = TimeSpan.FromSeconds(5); Data.Mode = Data.Modes.Lock; Execute(); } void tt5_Click(object sender, ThumbnailButtonClickedEventArgs e) { Data.t = TimeSpan.FromSeconds(5); Data.Mode = Data.Modes.Standby; Execute(); } void tt6_Click(object sender, ThumbnailButtonClickedEventArgs e) { Data.t = TimeSpan.FromSeconds(5); Data.Mode = Data.Modes.Hibernate; Execute(); } /*void tt7_Click(object sender, ThumbnailButtonClickedEventArgs e) { Data.t = TimeSpan.FromSeconds(0); Data.Mode = Data.Modes.HibernateWOSBIni; Execute(); }*/ void tt8_Click(object sender, ThumbnailButtonClickedEventArgs e) { StopShutdown(); } #endregion #endregion #endregion #region Fade void Fadein(double seconds, string objname) { if (Dispatcher.Thread != Thread.CurrentThread) Dispatcher.Invoke((Action)delegate { Fade(true, seconds, objname); }); else Fade(true, seconds, objname); } void Fadeout(double seconds, string objname) { if (Dispatcher.Thread != Thread.CurrentThread) Dispatcher.Invoke((Action)delegate { Fade(false, seconds, objname); }); else Fade(false, seconds, objname); } void Fade(bool state, double seconds, string objname) { Storyboard storyboard = new Storyboard(); TimeSpan duration = TimeSpan.FromSeconds(seconds); DoubleAnimation animation = new DoubleAnimation(); if (state) //Fadein { animation.From = 0.0; animation.To = 1.0; } else //Fadeout { animation.From = 1.0; animation.To = 0.0; } animation.Duration = new Duration(duration); Storyboard.SetTargetName(animation, objname); Storyboard.SetTargetProperty(animation, new PropertyPath(Control.OpacityProperty)); storyboard.Children.Add(animation); storyboard.Begin(this); } #endregion #endregion #region Shutdown #region StartShutdown /// <summary> /// Initiates the shutdown process. /// </summary> void StartShutdown() { if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.Invoke((Action)delegate { StartShutdown(); }); return; } if (Timer != null) { Timer.Stop(); Timer = null; Timer = new DispatcherTimer(); } LockUI(); //TODO: systray hide? AtChecked = (bool)At.IsChecked; Data.S["ResumeLastAction"] = (bool)checkResumeLastAction.IsChecked; ScreenOffChecked = (bool)checkScreenOff.IsChecked; PlayNoiseChecked = (bool)checkPlayNoise.IsChecked; if (remote) { curRemoteServer = textRemoteServer.Text; curRemoteMac = textRemoteMac.Text; curRemotePort = Int32.Parse(textRemotePort.Text); curRemotePassword = textRemotePassword.Password; } #region Ask if (Data.S["Ask"]/*not remote*/) { string msg = ""; switch (comboModus.SelectedIndex) { case 0: msg = Data.L["AskShutdown"]; break; case 1: msg = Data.L["AskReboot"]; break; case 2: msg = Data.L["AskLogoff"]; break; case 3: msg = Data.L["AskLock"]; break; case 4: msg = Data.L["AskStandby"]; break; case 5: msg = Data.L["AskHibernate"]; break; } if (msg != "") { if (MessageBox.Show(msg, "Shutdown7", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { StopShutdown(); return; } } } #endregion if (!remote) switch (Data.Condition) { case Data.Conditions.Time: case Data.Conditions.Idle: case Data.Conditions.Cpu: case Data.Conditions.Network: if (AtChecked && Data.Mode != Data.Modes.HibernateWOSBTime) { Data.t = (DateTime.Parse(hh.Value + ":" + mm.Value + ":" + ss.Value) - DateTime.Now); if (Data.t.TotalSeconds < 0) Data.t = Data.t.Add(TimeSpan.FromDays(1)); Data.t = new TimeSpan(Data.t.Ticks - (Data.t.Ticks % 10000000)); //Round milliseconds In.IsChecked = true; } else Data.t = TimeSpan.Parse(hh.Value + ":" + mm.Value + ":" + ss.Value); if (Data.Condition == Data.Conditions.Cpu) { Data.CpuMode = (comboCpu.SelectedIndex == 0); //True: Above, False: Below Data.CpuValue = (int)cpu.Value; } else if (Data.Condition == Data.Conditions.Network) { NetworkMode = (comboNetwork.SelectedIndex == 0); //True: Down, False: Up Data.Network = (int)network.Value; Data.NetworkAdapter = (string)comboNetworkAdapters.SelectedItem; } break; default: break; } #region ThumbnailToolbar if (Data.S["ThumbnailToolbar"]) { tt1.Enabled = false; tt2.Enabled = false; tt3.Enabled = false; tt4.Enabled = false; tt5.Enabled = false; tt6.Enabled = false; //tt7.Enabled = false; tt8.Enabled = true; } #endregion Execute(); } void LockUI() { if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.Invoke((Action)delegate { LockUI(); }); return; } remote = (expanderRemote.IsExpanded && Data.Mode != Data.Modes.WakeOnLan); GoButton.IsEnabled = true; //Workaround RemoteServer Request eingehend GoButton.Content = Data.L["Abort"]; Modus.IsEnabled = false; comboModus.IsEnabled = false; expanderMode.IsExpanded = false; expanderMode.IsEnabled = false; stackLaunchFile.Visibility = Visibility.Collapsed; expanderRemote.IsExpanded = false; expanderRemote.IsEnabled = false; expanderSettings.IsExpanded = false; expanderSettings.IsEnabled = false; #region Systray if (Data.S["SysIcon"] && sysicon != null) { Dispatcher.BeginInvoke((Action)delegate { sysicon.Icon = Shutdown7.Properties.Resources.ShutdownWait; contextRestore.Header = Data.L["Restore"]; contextAbort.IsEnabled = true; contextShutdown.IsEnabled = false; }); } #endregion } #endregion #region StopShutdown /// <summary> /// Stops the shutdown process /// </summary> public void StopShutdown() { if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.Invoke((Action)delegate { StopShutdown(); }); return; } bool pok = AbortSystemShutdown(null); /*if (!pok) Message.Show(Data.L["StartShutdownError"], "Error");*/ //Moved to StartShutdown() /WIESO??!!!! Rückgängig gemacht 2.1.1 if (Timer != null) { Timer.Stop(); Timer = null; Timer = new DispatcherTimer(); } //Delete values from Condition variables twait = TimeSpan.FromSeconds(0); Data.ProcessName = ""; Data.FileName = ""; Data.LaunchFile = ""; Data.NetworkAdapter = ""; Data.Network = 0; //Beende Musik if (mp3 != null) { mp3.Stop(); mp3 = null; } if (noise != null) { noise.Stop(); noise = null; } /*if (MusicThread != null) MusicThread.Abort();*/ if (NoiseThread != null) NoiseThread.Abort(); #region Systray if (Data.S["SysIcon"]) sysicon.ShowBalloonTip("Shutdown7", Data.L["BalloontipAbort"], BalloonIcon.Info); #endregion UnlockUI(); #region ThumbnailToolbar if (Data.S["ThumbnailToolbar"]) { tt1.Enabled = true; tt2.Enabled = true; tt3.Enabled = true; tt4.Enabled = true; tt5.Enabled = true; tt6.Enabled = true; //tt7.Enabled = true; tt8.Enabled = false; } #endregion Win7.Progress(0, this); Win7.ProgressType("No", this); Win7.Overlay(null, null, this); } void UnlockUI() { //if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.Invoke((Action)delegate { UnlockUI(); }); return; } Title = "Shutdown7"; GoButton.Content = Data.L["GO!"]; Modus.IsEnabled = true; comboModus.IsEnabled = true; expanderMode.IsEnabled = true; expanderMode.IsExpanded = true; if (Data.Mode == Data.Modes.Launch) stackLaunchFile.Visibility = Visibility.Visible; expanderRemote.IsEnabled = true; if (remote) expanderRemote.IsExpanded = true; expanderSettings.IsEnabled = true; progressBar.Value = 0; progressBar.IsIndeterminate = false; labelStatus.Content = ""; //Restore original timespan to UI hh.Value = Data.t.Hours; mm.Value = Data.t.Minutes; ss.Value = Data.t.Seconds; #region Systray if (Data.S["SysIcon"] & sysicon != null) { sysicon.Icon = Shutdown7.Properties.Resources.Shutdown7; sysicon.ToolTipText = Title; contextAbort.IsEnabled = false; contextShutdown.IsEnabled = true; } #endregion } #endregion Stopwatch w1 = new Stopwatch(); Stopwatch w2 = new Stopwatch(); Stopwatch w3 = new Stopwatch(); Stopwatch w5 = new Stopwatch(); #region Execute public void Execute() { if (Data.LocalByArgs) { #region Form Dispatcher.Invoke((Action)delegate { LockUI(); //TODO: test robustness comboModus.SelectedIndex = Convert.ToInt32(Data.Mode) - 1; /*switch (Data.Mode) { case Data.Modes.Shutdown: comboModus.SelectedIndex = 0; break; case Data.Modes.Restart: comboModus.SelectedIndex = 1; break; case Data.Modes.Logoff: comboModus.SelectedIndex = 2; break; case Data.Modes.Lock: comboModus.SelectedIndex = 3; break; case Data.Modes.Standby: case Data.Modes.StandbyWOSB: comboModus.SelectedIndex = 4; break; case Data.Modes.Hibernate: case Data.Modes.HibernateWOSB: comboModus.SelectedIndex = 5; break; case Data.Modes.HibernateWOSBIni: case Data.Modes.HibernateWOSBTime: case Data.Modes.WakeOnLan: case Data.Modes.Launch: case Data.Modes.RestartAndroid: default: break; }*/ //Workaround expanderMode.IsExpanded = false; expanderMode.IsEnabled = false; expanderRemote.IsExpanded = false; expanderRemote.IsEnabled = false; }); #endregion } if (!remote | Data.Mode == Data.Modes.WakeOnLan) { #region Lokal //Prevent crash if (Timer != null) { if (Timer.IsEnabled) { //Führe WOSB-Aktionen trotzdem aus, da unabhängig if (Data.Mode == Data.Modes.HibernateWOSBIni | Data.Mode == Data.Modes.HibernateWOSBTime) { Shutdown(); Data.Mode = Data.orgMode; return; } //Aktuellen beenden Message.Show(Data.L["RemoteBusy"], "Warning"); return; /// TODO: Timer wurde schon überschrieben, also wird neuer Countdown gesetzt und die Warnung kommt //Diesen anhalten /*Timer.Stop(); Timer = null;*/ } } if (Timer != null) Timer.Stop(); Timer = new DispatcherTimer(); Timer.Interval = TimeSpan.FromSeconds(1); switch (Data.Condition) { case Data.Conditions.Process: progressBar.IsIndeterminate = true; Win7.ProgressType("Indeterminate", this); Timer.Tick += new EventHandler(WaitProcessClose); #region Systray if (Data.S["SysIcon"]) { Dispatcher.BeginInvoke((Action)delegate { string Baloontiptext = ""; if (Data.S["AllProcesses"]) Baloontiptext = Data.L["BalloontipProcess" + Data.Mode.ToString()]; else Baloontiptext = Data.L["BalloontipWindow" + Data.Mode.ToString()]; sysicon.ShowBalloonTip("Shutdown7", String.Format(Baloontiptext, Data.ProcessName + (Data.S["AllProcesses"] ? ".exe" : "")), BalloonIcon.Info); }); } #endregion break; case Data.Conditions.File: progressBar.IsIndeterminate = true; Win7.ProgressType("Indeterminate", this); Timer.Tick += new EventHandler(WaitFileDelete); #region Systray if (Data.S["SysIcon"]) { Dispatcher.BeginInvoke((Action)delegate { string Baloontiptext = Data.L["BalloontipFile" + Data.Mode.ToString()]; sysicon.ShowBalloonTip("Shutdown7", String.Format(Baloontiptext, Data.FileName), BalloonIcon.Info); }); } #endregion break; case Data.Conditions.Music: Dispatcher.Invoke((Action)delegate { orgVolume = sliderOrgVol.Value / 100; if ((bool)checkMusicFadeout.IsChecked) { startfade = (int)sliderFade.Value; endVolume = sliderEndVol.Value / 100; } else { startfade = 100; endVolume = orgVolume; } }); mp3 = new MediaPlayer(); mp3.Volume = orgVolume; Data.t = TimeSpan.FromTicks(0); foreach (string fn in MusicFiles) { try { Data.t = Data.t.Add(TagLib.File.Create(fn).Properties.Duration); } catch (Exception ex) { Message.Show(ex.Message + "\n" + fn, "Music", "Error"); } } Data.t = new TimeSpan(Data.t.Ticks - (Data.t.Ticks % 10000000)); //Round milliseconds twait = Data.t; Timer.Tick += new EventHandler(WaitMusicPlaying); //tick before wait Dispatcher.Invoke((Action)delegate { Title = Data.t.ToString(); }); //Setup additional timer that manages music playback MusicTimer = new DispatcherTimer(); curSong = 0; MusicTimer.Interval = TimeSpan.FromSeconds(0); MusicTimer.Tick += new EventHandler(WaitMusicPlayNextSong); MusicTimer.Start(); w2.Start(); #region Systray if (Data.S["SysIcon"]) { Dispatcher.BeginInvoke((Action)delegate { string Baloontiptext = Data.L["BalloontipMusic" + Data.Mode.ToString()]; //String.Format(Baloontiptext, "test.mp3"); //Message.Show(String.Format(Baloontiptext, "test.mp3")); String musicfiles = ""; foreach (string fn in MusicFiles.ToArray(typeof(string))) { musicfiles += Path.GetFileName(fn) + ", "; } musicfiles = musicfiles.Substring(0, musicfiles.Length - 2); sysicon.ShowBalloonTip("Shutdown7", String.Format(Baloontiptext, musicfiles), BalloonIcon.Info); }); } #endregion break; case Data.Conditions.Idle: progressBar.IsIndeterminate = true; Win7.ProgressType("Indeterminate", this); Timer.Tick += new EventHandler(WaitIdle); GetIdleTime(); #region Systray if (Data.S["SysIcon"]) { Dispatcher.BeginInvoke((Action)delegate { string Baloontiptext = Data.L["BalloontipIdle" + Data.Mode.ToString()]; sysicon.ShowBalloonTip("Shutdown7", String.Format(Baloontiptext, ((Data.t.Hours < 10) ? "0" : "") + Data.t.Hours + ":" + ((Data.t.Minutes < 10) ? "0" : "") + Data.t.Minutes + ":" + ((Data.t.Seconds < 10) ? "0" : "") + Data.t.Seconds), BalloonIcon.Info); }); } #endregion break; case Data.Conditions.Cpu: if (Data.t.TotalSeconds > 0 && Data.Mode != Data.Modes.HibernateWOSBTime) { progressBar.IsIndeterminate = true; Win7.ProgressType("Indeterminate", this); cpuCounter = new PerformanceCounter(); cpuCounter.CategoryName = "Processor"; cpuCounter.CounterName = "% Processor Time"; cpuCounter.InstanceName = "_Total"; cpuCounter.NextValue(); //Initialize cpuHits = 0; Timer.Tick += new EventHandler(WaitCpu); #region Systray if (Data.S["SysIcon"]) { Dispatcher.BeginInvoke((Action)delegate { string Baloontiptext = Data.L["BalloontipCpu" + Data.Mode.ToString()]; sysicon.ShowBalloonTip("Shutdown7", String.Format(Baloontiptext, (Data.CpuMode ? Data.L["Above"] : Data.L["Below"]).ToLower(), Data.CpuValue, ((Data.t.Hours < 10) ? "0" : "") + Data.t.Hours + ":" + ((Data.t.Minutes < 10) ? "0" : "") + Data.t.Minutes + ":" + ((Data.t.Seconds < 10) ? "0" : "") + Data.t.Seconds), BalloonIcon.Info); }); } #endregion } else Shutdown(); break; case Data.Conditions.Network: progressBar.IsIndeterminate = true; Win7.ProgressType("Indeterminate", this); networkHits = 0; Timer.Tick += new EventHandler(WaitNetwork); #region Systray if (Data.S["SysIcon"]) { Dispatcher.BeginInvoke((Action)delegate { string Baloontiptext = Data.L["BalloontipNetwork" + Data.Mode.ToString()]; sysicon.ShowBalloonTip("Shutdown7", String.Format(Baloontiptext, (NetworkMode ? Data.L["Down"] : Data.L["Up"]).ToLower(), Data.Network, ((Data.t.Hours < 10) ? "0" : "") + Data.t.Hours + ":" + ((Data.t.Minutes < 10) ? "0" : "") + Data.t.Minutes + ":" + ((Data.t.Seconds < 10) ? "0" : "") + Data.t.Seconds), BalloonIcon.Info); }); } #endregion break; case Data.Conditions.Time: twait = Data.t; if (Data.t.TotalSeconds > 0 && Data.Mode != Data.Modes.HibernateWOSBTime) { Timer.Tick += new EventHandler(WaitTime); //tick before wait Dispatcher.Invoke((Action)delegate { Title = Data.t.ToString(); }); #region Systray if (Data.S["SysIcon"] && sysicon != null) { Dispatcher.BeginInvoke((Action)delegate { string Baloontiptext = Data.L["BalloontipTime" + Data.Mode.ToString()]; sysicon.ShowBalloonTip("Shutdown7", String.Format(Baloontiptext, ((Data.t.Hours < 10) ? "0" : "") + Data.t.Hours + ":" + ((Data.t.Minutes < 10) ? "0" : "") + Data.t.Minutes + ":" + ((Data.t.Seconds < 10) ? "0" : "") + Data.t.Seconds), BalloonIcon.Info); }); } #endregion } else { Dispatcher.Invoke((Action)delegate { Title = Data.t.ToString(); progressBar.Value = 100; }); Shutdown(); } break; default: //ModeNow Data.t = TimeSpan.FromSeconds(0); twait = Data.t; Timer = null; Shutdown(); return; } #region Systray if (Data.S["SysIcon"]) { //WindowState = WindowState.Minimized; //Visibility = Visibility.Hidden; Hide(); //contextRestore.Header = Data.L["Restore"]; /*Dispatcher.Invoke((Action)delegate { WindowState = WindowState.Minimized; Hide(); });*/ } #endregion if (Data.debug_verbose) new Thread(new ThreadStart(delegate { Message.Show("Wartezeit:\n" + Data.t.Hours + ":" + Data.t.Minutes + ":" + Data.t.Seconds, "Wait", "Information"); })).Start(); w3.Start(); Timer.Start(); if (PlayNoiseChecked) { NoiseThread = new Thread(new ThreadStart(PlayNoise)); NoiseThread.Start(); } if (ScreenOffChecked) { Thread.Sleep(500); Dispatcher.BeginInvoke((Action)delegate { SendMessage((int)new WindowInteropHelper(this).Handle, 0x0112, 0xF170, 2); }); } #endregion } else { #region Remote progressBar.IsIndeterminate = true; Win7.ProgressType("Indeterminate", this); if (AtChecked && Data.Mode != Data.Modes.HibernateWOSBTime) { Data.t = DateTime.Parse(hh.Value + ":" + mm.Value + ":" + ss.Value) - DateTime.Now; //Data.t = DateTime.Parse(hh.Text + ":" + mm.Text + ":" + ss.Text) - DateTime.Now; twait = Data.t; In.IsChecked = true; } else Data.t = TimeSpan.Parse(hh.Value + ":" + mm.Value + ":" + ss.Value); twait = Data.t; //Data.t = TimeSpan.Parse(hh.Text + ":" + mm.Text + ":" + ss.Text); new Thread(RemoteClientStart).Start(); #endregion } //For Arguments if (Data.orgMode != Data.Modes.None) { Data.Mode = Data.orgMode; Data.orgMode = Data.Modes.None; } } /// <summary> /// Starts the shutdown process. /// </summary> /// public void Shutdown() { if (Data.debug_noexecute) { if (Data.debug_debugging) Message.Show("Would start execution here."); if (!Data.S["StayAfterShutdown"]) { if (!Timer.IsEnabled) Close();//Environment.Exit(0); //killt nur aktuellen Prozess //Application.Current.Shutdown(); //killt alle Prozesse return; } else { Timer.Stop(); StopShutdown(); return; } } Process Shutdown = new Process(); Shutdown.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; Shutdown.StartInfo.FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\shutdown.exe"; Shutdown.StartInfo.Verb = "runas"; switch (Data.Mode) { case Data.Modes.Shutdown: if (Data.S["Force"]) { //ExitWindowsEx(5, 0); if (Data.S["Win8Hybrid"]) Shutdown.StartInfo.Arguments = "-s -hybrid -f -t 0"; else Shutdown.StartInfo.Arguments = "-s -f -t 0"; } else { //ExitWindowsEx(1, 0); if (Data.S["Win8Hybrid"]) Shutdown.StartInfo.Arguments = "-s -hybrid -t 0"; else Shutdown.StartInfo.Arguments = "-s -t 0"; } try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } /*catch (FileNotFoundException ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message, "Error"); }*/ catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ((Data.debug_verbose) ? "\n" + ex.Message : ""), "Error"); } break; case Data.Modes.Restart: if (Data.S["Force"]) { //bool pok = ExitWindowsEx(6, 0); Shutdown.StartInfo.Arguments = "-r -f -t 0"; } else { //bool pok = ExitWindowsEx(2, 0); Shutdown.StartInfo.Arguments = "-r -t 0"; } try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.Logoff: if (Data.S["Force"]) { //bool pok = ExitWindowsEx(4, 0); Shutdown.StartInfo.Arguments = "-l -f"; } else { //bool pok = ExitWindowsEx(0, 0); Shutdown.StartInfo.Arguments = "-l"; } try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.Lock: try { bool pok = LockWorkStation(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.Standby: try { bool pok = SetSuspendState(false, Data.S["Force"], false); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.StandbyWOSB: Shutdown.StartInfo.FileName = Data.WOSBPath; Shutdown.StartInfo.Verb = ""; Shutdown.StartInfo.Arguments = "/run /ami /standby"; if (Data.S["Force"]) Shutdown.StartInfo.Arguments += "/force"; try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.Hibernate: try { bool pok = SetSuspendState(true, Data.S["Force"], false); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.HibernateWOSB: Shutdown.StartInfo.FileName = Data.WOSBPath; Shutdown.StartInfo.Verb = ""; Shutdown.StartInfo.Arguments = "/run /ami /hibernate"; if (Data.S["Force"]) Shutdown.StartInfo.Arguments += "/force"; try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.HibernateWOSBIni: Shutdown.StartInfo.FileName = Data.WOSBPath; Shutdown.StartInfo.Verb = ""; WOSBZeit = GetWZeit().ToLongTimeString(); Shutdown.StartInfo.Arguments = "/run /ami /systray " + "tm=\"" + WOSBZeit + "\" file=\"" + Data.W[Data.curProfile]["File"] + "\" params=\"" + Data.W[Data.curProfile]["Params"] + "\" awfile=\"" + Data.W[Data.curProfile]["AwFile"] + "\" awparams=\"" + Data.W[Data.curProfile]["AwParams"] + "\" " + Data.W[Data.curProfile]["Extra"]; if (Data.S["Force"]) Shutdown.StartInfo.Arguments += " /force"; try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.HibernateWOSBTime: Xml.ReadWOSB(); if (this.Visibility == Visibility.Visible) { try { WOSBZeit = DateTime.Parse(Data.t.Hours + ":" + Data.t.Minutes + ":" + Data.t.Seconds).ToLongTimeString(); } catch { DateTime Time = DateTime.Now.AddHours(1); WOSBZeit = Time.Hour + ":" + Time.Minute + ":" + Time.Second; } } else WOSBZeit = DateTime.Now.AddHours(1).ToLongTimeString(); // WOSBZeit = DateTime.Parse(Microsoft.VisualBasic.Interaction.InputBox("Zeit eingeben")).ToLongTimeString(); Shutdown.StartInfo.FileName = Data.WOSBPath; Shutdown.StartInfo.Arguments = "/run /ami /systray " + "tm=\"" + WOSBZeit + "\" file=\"" + Data.W[Data.curProfile]["File"] + "\" params=\"" + Data.W[Data.curProfile]["Params"] + "\" awfile=\"" + Data.W[Data.curProfile]["AwFile"] + "\" awparams=\"" + Data.W[Data.curProfile]["AwParams"] + "\" " + Data.W[Data.curProfile]["Extra"]; if (Data.S["Force"]) Shutdown.StartInfo.Arguments += " /force"; try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.WakeOnLan: try { if (curRemoteMac.Contains(".")) //IP-Adresse curRemoteMac = Remote.IpToMacAddress(IPAddress.Parse(curRemoteMac)); if (curRemoteMac == null) { RemoteDisplayMsg(Data.L["RemoteServerTimeout"]); StopShutdown(); return; } curRemoteMac = curRemoteMac.Replace("-", "").Replace(":", ""); int counter = 0; byte[] packet = new byte[17 * 6]; for (int y = 0; y < 6; y++) packet[counter++] = 0xFF; for (int y = 0; y < 16; y++) { int i = 0; for (int z = 0; z < 6; z++) { packet[counter++] = byte.Parse(curRemoteMac.Substring(i, 2), NumberStyles.HexNumber); i += 2; } } if (Data.debug_verbose) Message.Show("Mac-Adresse: " + curRemoteMac + "\nBroadcast-IP: " + IPAddress.Broadcast + "\nPort: " + curRemotePort + "\nPacket: " + BitConverter.ToString(packet), "Shutdown7", "Information"); UdpClient client = new UdpClient(); client.EnableBroadcast = true; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 0); client.Send(packet, packet.Length, new IPEndPoint(Dns.GetHostEntry(curRemoteServer).AddressList[0],curRemotePort)); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.Launch: Shutdown.StartInfo.FileName = Data.LaunchFile; Shutdown.StartInfo.WindowStyle = ProcessWindowStyle.Normal; Shutdown.StartInfo.Verb = ""; try { bool pok = Shutdown.Start(); if (!pok) Message.Show(Data.L["StartShutdownError"], "Error"); } catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ex.Message /* ((Data.debug_verbose) ? "\n" + ex.Message : "") */, "Error"); } break; case Data.Modes.RestartAndroid: new Thread(new ThreadStart(RestartAndroid)).Start(); //RestartAndroid(); break; default: Message.Show(Data.L["StartShutdownError"], "Error"); break; } if (Data.debug_stopwatch & Environment.GetCommandLineArgs().Length > 1) Message.Show("Gesamtzeit: " + App.stopwatch.Elapsed.TotalMilliseconds, "Start", "Information"); if (!Data.S["StayAfterShutdown"]) //TODO: Workaround App.cs verbessern { // 2.3.1: Obsolete /*if (Timer == null) //TODO: Workaround App.cs verbessern Timer = new DispatcherTimer();*/ //Crash if WOSBTime if (Timer != null) { if (!Timer.IsEnabled) { DisposeSystray(); Environment.Exit(0); //killt nur aktuellen Prozess //Application.Current.Shutdown(); //killt alle Prozesse } } else { DisposeSystray(); Environment.Exit(0); //killt nur aktuellen Prozess //Application.Current.Shutdown(); //killt alle Prozesse } } else { if (Timer != null) Timer.Stop(); else Timer = new DispatcherTimer(); //StopShutdown(); UnlockUI(); } } void RestartAndroid() { //try //{ Dispatcher.Invoke((Action)delegate { LockUI(); progressBar.IsIndeterminate = true; labelStatus.Content = "Waiting for device"; //Data.L["WaitingForAndroid"] }); AndroidController android = AndroidController.Instance; Device device; string serialNumber; if (!android.HasConnectedDevices) { Dispatcher.Invoke((Action)delegate { UnlockUI(); //labelStatus.Content = Data.L["NoAndroidFound"]; }); Message.Show(Data.L["NoAndroidFound"], "Error"); android.Dispose(); return; } else if (Data.debug_verbose) Message.Show(String.Join(";", android.ConnectedDevices.ToArray())); Dispatcher.BeginInvoke((Action)delegate { progressBar.IsIndeterminate = true; labelStatus.Content = "Rebooting"; }); android.WaitForDevice(); serialNumber = android.ConnectedDevices[0]; device = android.GetConnectedDevice(serialNumber); if (Data.debug_verbose) Message.Show("Connected Device - " + device.SerialNumber + "\nBattery: " + device.Battery.Level + " Root: " + device.HasRoot, "Information"); device.Reboot(); android.Dispose(); Dispatcher.Invoke((Action)delegate { UnlockUI(); }); /*} catch (Exception ex) { Message.Show(Data.L["StartShutdownError"] + ((Data.debug_verbose) ? "\n" + ex.Message : ""), "Error"); }*/ } #endregion #region Wait void WaitTime(object sender, EventArgs e) { if (twait.TotalSeconds.Equals(0)) //if ((int)Data.t.TotalSeconds == 0) { Timer.Stop(); if (Visibility == Visibility.Visible) { Win7.Progress(100, this); Dispatcher.BeginInvoke((Action)delegate { progressBar.Value = 100; }); } Shutdown(); return; } twait = twait.Subtract(TimeSpan.FromSeconds(1)); //Data.t = Data.t.Subtract(TimeSpan.FromSeconds(1)); percent = 100 - (twait.TotalSeconds / Data.t.TotalSeconds) * 100; #region Form Dispatcher.Invoke((Action)delegate { Title = twait.ToString(); progressBar.Value = percent; ss.Value = twait.Seconds; mm.Value = twait.Minutes; hh.Value = twait.Hours; /*Title = Data.t.ToString(); progressBar.Value = percent; ss.Value = Data.t.Seconds; mm.Value = Data.t.Minutes; hh.Value = Data.t.Hours;*/ /*ss.Text = t.Seconds.ToString(); mm.Text = t.Minutes.ToString(); hh.Text = t.Hours.ToString(); if (hh.Text.Length == 1) hh.Text = "0" + hh.Text; if (mm.Text.Length == 1) mm.Text = "0" + mm.Text; if (ss.Text.Length == 1) ss.Text = "0" + ss.Text;*/ }); #endregion if (Visibility == Visibility.Visible) { #region Win7 #region Taskbar Win7.Progress((int)percent, this); if (percent >= 90) Win7.ProgressType("Error", this); else if (percent >= 80) Win7.ProgressType("Paused", this); else Win7.ProgressType("Normal", this); #endregion #region Overlay if (Data.S["Overlay"]) { switch ((int)Data.t.TotalSeconds) { case 1: Win7.Overlay(Properties.Resources._1, "1", this); break; case 2: Win7.Overlay(Properties.Resources._2, "2", this); break; case 3: Win7.Overlay(Properties.Resources._3, "3", this); break; case 4: Win7.Overlay(Properties.Resources._4, "4", this); break; case 5: Win7.Overlay(Properties.Resources._5, "5", this); break; case 6: Win7.Overlay(Properties.Resources._6, "6", this); break; case 7: Win7.Overlay(Properties.Resources._7, "7", this); break; case 8: Win7.Overlay(Properties.Resources._8, "8", this); break; case 9: Win7.Overlay(Properties.Resources._9, "9", this); break; case 0: Win7.Overlay(Properties.Resources._0, "0", this); break; default: Win7.Overlay(null, null, this); break; } } #endregion #endregion } #region Systray if (Data.S["SysIcon"] && sysicon != null) sysicon.ToolTipText = ((twait.Hours < 10) ? "0" : "") + twait.Hours + ":" + ((twait.Minutes < 10) ? "0" : "") + twait.Minutes + ":" + ((twait.Seconds < 10) ? "0" : "") + twait.Seconds; //sysicon.ToolTipText = ((Data.t.Hours < 10) ? "0" : "") + Data.t.Hours + ":" + ((Data.t.Minutes < 10) ? "0" : "") + Data.t.Minutes + ":" + ((Data.t.Seconds < 10) ? "0" : "") + Data.t.Seconds; #endregion } void WaitProcessClose(object sender, EventArgs e) { bool stop = true; if (Data.S["AllProcesses"]) { foreach (Process p in Process.GetProcessesByName(Data.ProcessName)) { if (p.ProcessName == Data.ProcessName) { stop = false; break; } } } else { foreach (Process p in Process.GetProcesses()) { if (p.MainWindowTitle == Data.ProcessName) { stop = false; break; } } } if (stop) { Timer.Stop(); if (Visibility == Visibility.Visible) { Win7.Progress(100, this); Dispatcher.BeginInvoke((Action)delegate { progressBar.Value = 100; }); } Shutdown(); } } void WaitFileDelete(object sender, EventArgs e) { if (!File.Exists(Data.FileName)) { Timer.Stop(); if (Visibility == Visibility.Visible) { Win7.Progress(100, this); Dispatcher.BeginInvoke((Action)delegate { progressBar.Value = 100; }); } Shutdown(); } } void WaitMusicPlaying(object sender, EventArgs e) { if (twait.TotalSeconds.Equals(0)) { w3.Stop(); w5.Stop(); Timer.Stop(); if (Visibility == Visibility.Visible) { Win7.Progress(100, this); Dispatcher.BeginInvoke((Action)delegate { progressBar.Value = 100; }); } if (Data.debug_verbose) Message.Show("Songlängen total: " + Data.t.ToString() + "\nPlaythread:" + (int)w2.Elapsed.TotalSeconds + "\nWaitthread:" + (int)w3.Elapsed.TotalSeconds + "\nUnterschied:" + (int)w5.Elapsed.TotalSeconds); Shutdown(); } twait = twait.Subtract(TimeSpan.FromSeconds(1)); TimeSpan _t = Data.t.Subtract(twait); percent = (_t.TotalSeconds / Data.t.TotalSeconds) * 100; if (Visibility == Visibility.Visible) { #region Form Dispatcher.BeginInvoke((Action)delegate { Title = twait.ToString(); progressBar.Value = percent; hh.Value = Data.t.Hours; ss.Value = Data.t.Seconds; mm.Value = Data.t.Minutes; }); #endregion #region Win7 #region Taskbar Win7.Progress((int)percent, this); if (percent >= 90) Win7.ProgressType("Error", this); else if (percent >= 80) Win7.ProgressType("Paused", this); else Win7.ProgressType("Normal", this); #endregion #region Overlay if (Data.S["Overlay"]) { switch ((int)Data.t.TotalSeconds) { case 1: Win7.Overlay(Properties.Resources._1, "1", this); break; case 2: Win7.Overlay(Properties.Resources._2, "2", this); break; case 3: Win7.Overlay(Properties.Resources._3, "3", this); break; case 4: Win7.Overlay(Properties.Resources._4, "4", this); break; case 5: Win7.Overlay(Properties.Resources._5, "5", this); break; case 6: Win7.Overlay(Properties.Resources._6, "6", this); break; case 7: Win7.Overlay(Properties.Resources._7, "7", this); break; case 8: Win7.Overlay(Properties.Resources._8, "8", this); break; case 9: Win7.Overlay(Properties.Resources._9, "9", this); break; case 0: Win7.Overlay(Properties.Resources._0, "0", this); break; default: Win7.Overlay(null, null, this); break; } } #endregion #endregion } #region Systray if (Data.S["SysIcon"] && sysicon != null) sysicon.ToolTipText = ((Data.t.Hours < 10) ? "0" : "") + Data.t.Hours + ":" + ((Data.t.Minutes < 10) ? "0" : "") + Data.t.Minutes + ":" + ((Data.t.Seconds < 10) ? "0" : "") + Data.t.Seconds; #endregion #region Musik-Fadeout if ((bool)checkMusicFadeout.IsChecked) { if (percent >= startfade & !Data.debug_mute) { FadeTotalRunTime++; double FadeTime = Data.t.TotalSeconds - Data.t.TotalSeconds * startfade / 100; double FadeVolumeAdj = (orgVolume - endVolume) / FadeTime; double NewVol = orgVolume - (FadeVolumeAdj * FadeTotalRunTime); /*if (Data.debug_verbose & percent >= 95) Message.Show("Stück-Länge: " + length + "\nSeit Begin-Fade: " + FadeTotalRunTime + "\nVoladj: " + FadeVolumeAdj + "\nFadetime: " + FadeTime + "\nOld-Volume: " + orgVolume + "\nEnd-Volume: " + endVolume + "\nVolume: " + NewVol, "Shutdown7", "Information"); */ if (Data.debug_verbose & percent >= 95) Debug.WriteLine("\nVoladj: " + FadeVolumeAdj + "\nFadetime: " + FadeTime + "\nOld-Volume: " + orgVolume + "\nEnd-Volume: " + endVolume + "\nVolume: " + NewVol + "\n"); Dispatcher.Invoke((Action)delegate { mp3.Volume = NewVol; }); //MMDevice defaultDevice = new MMDeviceEnumerator().GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia).AudioEndpointVolume.MasterVolumeLevel = NewVol; } } #endregion } #region Musik-Hilfsfunktion void WaitMusicPlayNextSong(object sender, EventArgs e) { //Softer transition Thread.Sleep(500); ((DispatcherTimer)sender).Stop(); mp3.Stop(); mp3.Close(); if (Data.debug_mute) mp3.Volume = 0; mp3.Open(new Uri((string)MusicFiles[curSong])); mp3.Play(); curSong++; //This was the last song if (curSong == MusicFiles.Count) return; ((DispatcherTimer)sender).Interval = TagLib.File.Create((string)MusicFiles[curSong]).Properties.Duration; ((DispatcherTimer)sender).Start(); } void PlayNoise() { do { //if (!Timer.IsEnabled) return; Dispatcher.Invoke((Action)delegate { noise = new MediaPlayer(); if (Data.debug_mute) noise.Volume = 0; noise.Open(new Uri(Data.NoisePath)); noise.Play(); }); Thread.Sleep((int)TagLib.File.Create(Data.NoisePath).Properties.Duration.TotalMilliseconds); //if (!Timer.IsEnabled) return; Dispatcher.Invoke((Action)delegate { if (noise != null) { noise.Stop(); noise.Close(); } }); } while (Timer.IsEnabled); } #endregion void WaitIdle(object sender, EventArgs e) { if ((GetIdleTime() / 1000) > Data.t.TotalSeconds) { if (Data.debug_verbose) Message.Show(GetIdleTime() / 1000 + " " + Data.t.TotalSeconds, "Wait - Idle", "Information"); Timer.Stop(); if (Visibility == Visibility.Visible) { Win7.Progress(100, this); Dispatcher.Invoke((Action)delegate { progressBar.Value = 100; }); } Shutdown(); } } #region Idle-Hilfsfunktionen public static uint GetIdleTime() { LASTINPUTINFO lastInPut = new LASTINPUTINFO(); lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut); GetLastInputInfo(ref lastInPut); return ((uint)Environment.TickCount - lastInPut.dwTime); } internal struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } #endregion void WaitCpu(object sender, EventArgs e) { int cpuusage = GetCpu(); bool conditionCpu; if (Data.CpuMode) conditionCpu = cpuusage > Data.CpuValue; else conditionCpu = cpuusage < Data.CpuValue; //bool conditionCpu = CpuMode ? cpuusage > Cpu : cpuusage < Cpu; //Geht nicht :( if (conditionCpu) { cpuHits++; if (cpuHits == Data.t.TotalSeconds) { if (Data.debug_verbose) Message.Show(cpuusage + "% Erfüllt: " + conditionCpu + " " + cpuHits + " " + Data.t.TotalSeconds, "Wait - Cpu", "Information"); Timer.Stop(); cpuHits = 0; if (Visibility == Visibility.Visible) { Win7.Progress(100, this); Dispatcher.Invoke((Action)delegate { progressBar.Value = 100; }); } Shutdown(); } } else { cpuHits = 0; } } #region Cpu-Hilfsfunktionen //https://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c int GetCpu() { int secondValue = (int)cpuCounter.NextValue(); return secondValue; } #endregion void WaitNetwork(object sender, EventArgs e) { int networkusage = GetNetwork(NetworkMode); if (networkusage < Data.Network) { networkHits++; if (networkHits == Data.t.TotalSeconds) { if (Data.debug_verbose) Message.Show(networkusage + " kbps " + " Mode:" + NetworkMode + " Hits: " + networkHits + " " + Data.t.TotalSeconds, "Wait - Network", "Information"); Timer.Stop(); cpuHits = 0; if (Visibility == Visibility.Visible) { Win7.Progress(100, this); Dispatcher.Invoke((Action)delegate { progressBar.Value = 100; }); } Shutdown(); } } else { cpuHits = 0; } } #region Network-Hilfsfunktionen int GetNetwork(bool mode) { if (!NetworkInterface.GetIsNetworkAvailable()) return 0; NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); long b = 0; foreach (NetworkInterface ni in interfaces) { if (ni.Name != Data.NetworkAdapter) continue; IPv4InterfaceStatistics s = ni.GetIPv4Statistics(); if (mode) b += s.BytesReceived / 1000; else b += s.BytesSent / 1000; } return (int)b; } String[] GetNetworkAdapters() { //TODO: Check counting if (!NetworkInterface.GetIsNetworkAvailable()) return null; NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); List<string> adapters = new List<string>(); foreach (NetworkInterface ni in interfaces) { adapters.Add(ni.Name); } return adapters.ToArray(); } #endregion #endregion #region WOSB DateTime GetWZeit() {//Bug: Sonntag selektiert Zeit von Montag Xml.ReadWOSB(); string WZeit = null; DayOfWeek curWeekday; int diff; if (Data.debug_verbose) Message.Show("Aktuelles Profil: " + Data.curProfile, "WOSB Ini", "Information"); foreach (KeyValuePair<string, string> kvp in Data.W[Data.curProfile]) { if (kvp.Key.Length > 3) continue; DateTime dtime; curWeekday = GetDayOfWeek(kvp.Key.Substring(0, 2)); diff = curWeekday - DateTime.Now.DayOfWeek; if (diff == -6) diff += 7; //Workaround - test! //Message.Show(DateTime.Now.AddDays(diff).Day + "." + DateTime.Now.AddDays(diff).Month + "." + DateTime.Now.AddDays(diff).Year + " " + kvp.Value); if (!DateTime.TryParse(DateTime.Now.AddDays(diff).Day + "." + DateTime.Now.AddDays(diff).Month + "." + DateTime.Now.AddDays(diff).Year + " " + kvp.Value, out dtime)) { Message.Show(Data.L["XmlReadError_1"], "Error"); Application.Current.Shutdown(); } if (Data.debug_verbose) Message.Show(kvp.Key + "\nDifferenz: " + (dtime - DateTime.Now).Days + "d " + (dtime - DateTime.Now).Hours + "h ", "WOSB Ini", "Information"); if (dtime < DateTime.Now) continue; //if (Data.debug_verbose) Message.Show(kvp.Key + " " + kvp.Value, "WOSB Ini", "Information"); if (Data.debug_verbose) Message.Show("Treffer!\nDann: " + curWeekday.ToString() + "\nHeute: " + DateTime.Now.DayOfWeek + "\nDifferenz: " + diff, "WOSB Ini", "Information"); if (dtime > DateTime.Now) { WZeit = kvp.Value; if (Data.debug_verbose) Message.Show("Wakeup-Time: " + curWeekday + " " + kvp.Value, "WOSB Ini", "Information"); break; } } if (!String.IsNullOrEmpty(WZeit)) { return DateTime.Parse(WZeit); } else { Message.Show(Data.L["NoWakeUpSheduled"], "Warning"); Environment.Exit(0); return DateTime.Now; } } DayOfWeek GetDayOfWeek(string Day) { switch(Day) { case "Mo": return DayOfWeek.Monday; case "Tu": return DayOfWeek.Tuesday; case "We": return DayOfWeek.Wednesday; case "Th": return DayOfWeek.Thursday; case "Fr": return DayOfWeek.Friday; case "Sa": return DayOfWeek.Saturday; case "So": return DayOfWeek.Sunday; case "Su": return DayOfWeek.Sunday; default: return DayOfWeek.Monday; } } #endregion #region Remote #region Server public void StartRemoteServer() { if (tcpListener != null) return; try { tcpListener = new TcpListener(IPAddress.Any, Data.RemotePort); tcpListener.Start(); } catch// (Exception ex) { //if (Data.debug_verbose) // Message.Show(ex.Message, "RemoteServer", "Error"); return; } Thread.Sleep(1000); while (!Remote.ExitRemoteServer) { if (tcpListener.Pending()) { client = tcpListener.AcceptTcpClient(); Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(client); } Thread.Sleep(100); } tcpListener.Stop(); } public void StopRemoteServer() { Remote.ExitRemoteServer = true; } public void HandleClientComm(object client) { TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; RemoteDisplayMsg(""); while (!Remote.ExitRemoteServer) { //Lese Nachricht bytesRead = 0; try { bytesRead = clientStream.Read(message, 0, 1024); } catch { break; } if (bytesRead == 0) break; string Input = new ASCIIEncoding().GetString(message, 0, bytesRead); //if (Data.debug_verbose) // Message.Show("Input: " + Input, "Remote Server", "Information"); if (Input.StartsWith("GET")) //Webbrowser { StopShutdown(); byte[] buffer = null; if (Input.StartsWith("GET /?abort")) { StopShutdown(); buffer = new ASCIIEncoding().GetBytes(Remote.GetWebUI(Timer, Data.ProcessName, Data.FileName, listMusicFiles.Items, true)); } else { buffer = new ASCIIEncoding().GetBytes(Remote.GetWebUI(Timer, Data.ProcessName, Data.FileName, listMusicFiles.Items, false)); } clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); tcpClient.Close(); return; } if (Input.ToUpper() == "PING") //Porttest { RemoteDisplayMsg(""); byte[] buffer = new ASCIIEncoding().GetBytes("Pong"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); tcpClient.Close(); return; } if (Input.ToUpper() == "STATUS") //Porttest { RemoteDisplayMsg(""); byte[] buffer = null; if (Timer.IsEnabled) Dispatcher.Invoke((Action)delegate { buffer = new ASCIIEncoding().GetBytes(Data.Mode + "|" + Data.Condition + "|" + GetParamFromCondition(Data.Condition)); }); else buffer = new ASCIIEncoding().GetBytes("IDLE"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); tcpClient.Close(); return; } RemoteDisplayMsg(Data.L["Receive"]); //Shutdown7 Client / WebUI string[] ShutdownString = Input.Split('|'); //Modi|Time|PW if (ShutdownString.Length != 3) { RemoteDisplayMsg(Data.L["RemoteErrorRequest"]); byte[] buffer = new ASCIIEncoding().GetBytes("ERRORREQUEST"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); tcpClient.Close(); Message.Show(Data.L["RemoteErrorRequest"], "Error"); Thread.Sleep(2000); RemoteDisplayMsg(""); return; } //Falsches Passwort if (ShutdownString[2] != Data.RemotePassword) { RemoteDisplayMsg(Data.L["RemoteWrongPassShort"]); byte[] buffer = new ASCIIEncoding().GetBytes("WRONGPW"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); tcpClient.Close(); if (Data.S["SysIcon"]) { sysicon.ShowBalloonTip("Shutdown7", Data.L["RemoteWrongPass"], BalloonIcon.Warning); } else { Message.Show(Data.L["RemoteWrongPass"], "Warning"); } Thread.Sleep(2000); RemoteDisplayMsg(""); return; } //Abbrechen if (ShutdownString[0] == Data.Modes.Abort.ToString()) { byte[] buffer; if (Timer.IsEnabled) { RemoteDisplayMsg(Data.L["Aborted"]); buffer = new ASCIIEncoding().GetBytes("OK"); clientStream.Write(buffer, 0, buffer.Length); StopShutdown(); } else { buffer = new ASCIIEncoding().GetBytes("IDLE"); clientStream.Write(buffer, 0, buffer.Length); } clientStream.Flush(); clientStream.Close(); tcpClient.Close(); Thread.Sleep(2000); RemoteDisplayMsg(""); return; } //Shutdown läuft bereits if (Timer.IsEnabled) { RemoteDisplayMsg(Data.L["RemoteBusyShort"]); byte[] buffer = new ASCIIEncoding().GetBytes("BUSY"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); clientStream.Close(); tcpClient.Close(); Thread.Sleep(2000); RemoteDisplayMsg(""); return; } //OK byte[] bufferOK = new ASCIIEncoding().GetBytes("OK"); clientStream.Write(bufferOK, 0, bufferOK.Length); clientStream.Flush(); clientStream.Close(); tcpClient.Close(); RemoteDisplayMsg(Data.L["Sucessful"]); StopShutdown(); Data.Condition = Data.Conditions.Time; Data.t = TimeSpan.FromSeconds(Double.Parse(ShutdownString[1])); remote = false; #region Form Dispatcher.Invoke((Action)delegate { hh.Value = Data.t.Hours; mm.Value = Data.t.Minutes; ss.Value = Data.t.Seconds; switch (ShutdownString[0]) { case "Shutdown": comboModus.SelectedIndex = 0; break; case "Restart": comboModus.SelectedIndex = 1; break; case "Logoff": comboModus.SelectedIndex = 2; break; case "Lock": comboModus.SelectedIndex = 3; break; case "Standby": comboModus.SelectedIndex = 4; break; case "Hibernate": comboModus.SelectedIndex = 5; break; } }); #endregion bool Askold = Data.S["Ask"]; Data.S["Ask"] = false; StartShutdown(); Data.S["Ask"] = Askold; } Thread.Sleep(3000); RemoteDisplayMsg(""); } private string GetParamFromMode(Data.Modes mode) { switch (mode) { case Data.Modes.Launch: return Data.LaunchFile; default: return null; } } private string GetParamFromCondition(Data.Conditions condition) { switch (condition) { case Data.Conditions.Now: case Data.Conditions.None: return "0"; case Data.Conditions.Time: case Data.Conditions.Idle: return Data.t.TotalSeconds.ToString(); case Data.Conditions.File: return Data.FileName; case Data.Conditions.Process: return Data.ProcessName + (Data.S["AllProcesses"] ? ".exe" : ""); case Data.Conditions.Music: string files = ""; foreach (string curfile in MusicFiles) files += curfile.Substring(curfile.LastIndexOf("\\") + 1) + "?"; return (int)Data.t.TotalSeconds + "*" + files; case Data.Conditions.Cpu: return Data.t.TotalSeconds.ToString() + "?" + Data.CpuValue.ToString() + "?" + Data.CpuMode; default: return null; } } #endregion #region Client void RemoteClientStart() { string statusmsg = ""; try { RemoteDisplayMsg(Data.L["RemoteConnect"]); curRemoteIP = Remote.GetIP(curRemoteServer); TcpClient client = new TcpClient(); client.Connect(new IPEndPoint(IPAddress.Parse(curRemoteIP), curRemotePort)); NetworkStream clientStream = client.GetStream(); RemoteDisplayMsg(Data.L["RemoteSend"]); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = encoder.GetBytes(Data.Mode + "|" + Data.t.TotalSeconds + "|" + Remote.md5(curRemotePassword)); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); byte[] message = new byte[32]; statusmsg = new ASCIIEncoding().GetString(message, 0, clientStream.Read(message, 0, message.Length)); } catch (SocketException ex) { Debug.WriteLine(ex.Message); if (Data.debug_verbose) Message.Show(ex.Message, "Remote Server", "Error"); if (ex.SocketErrorCode == SocketError.TimedOut) statusmsg = "TIMEOUT"; } catch (Exception ex) { Debug.WriteLine(ex.Message); if (Data.debug_verbose) Message.Show(ex.Message, "Remote Server", "Error"); } if (Data.debug_verbose) Message.Show("Antwort von Server: " + statusmsg, "Remote Server", "Information"); if (Data.S["SendFeedback"]) { //Send Data to WebUI new Thread(new ParameterizedThreadStart(SendFeedback)).Start(statusmsg); } if (statusmsg == "OK") RemoteDisplayMsg(Data.L["Sucessful"]); else if (statusmsg == "TIMEOUT") RemoteDisplayMsg(Data.L["RemoteServerTimeout"]); else if (statusmsg == "WRONGPW") RemoteDisplayMsg(Data.L["RemoteWrongPassShort"]); else if (statusmsg == "BUSY") { RemoteDisplayMsg(Data.L["RemoteBusyShort"]); if (!Data.RemoteByArgs) Message.Show(Data.L["RemoteBusy"], "Warning"); } else RemoteDisplayMsg(Data.L["RemoteError"]); if (Data.RemoteByArgs) { Thread.Sleep(1000); Environment.Exit((statusmsg == "OK") ? 1 : 0); return; } StopShutdown(); Thread.Sleep(2000); RemoteDisplayMsg(""); } #region SendFeedback void SendFeedback(object statusmsg) { try { string postData = "logonly=true&url=" + curRemoteServer + "&mac=" + curRemoteMac + "&port=" + curRemotePort + "&modi=" + Data.Mode + "&client=Shutdown7 " + Data.Version + "&msg=" + (string)statusmsg + "&ok=" + ((string)statusmsg == "OK"); if (Data.debug_verbose) Message.Show(postData, "RemoteClient - SendFeedback", "Information"); byte[] byteArray = Encoding.UTF8.GetBytes(postData); WebRequest request = WebRequest.Create("http://www.shutdown7.com/webui.php"); request.Method = "POST"; request.ContentLength = byteArray.Length; request.ContentType = "application/x-www-form-urlencoded"; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); } catch (Exception ex) { if (Data.debug_verbose) Message.Show(ex.Message, "RemoteClient - SendFeedback", "Error"); } } #endregion void RemoteDisplayMsg(string txt) { //if (this.Visibility != Visibility.Visible) return; if (Data.RemoteByArgs) { Console.WriteLine(txt); return; } if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.BeginInvoke((Action)delegate { RemoteDisplayMsg(txt); }); return; } Fadein(0.5, labelStatus.Name); if (txt != "") { labelStatus.Content = txt; } else { Fadeout(0.5, labelStatus.Name); //labelStatus.Content = ""; } } #endregion #endregion #endregion #region Systray static bool hiding = false; public void CreateSystray() { if (sysicon != null) return; sysicon = new TaskbarIcon(); sysicon.TrayMouseDoubleClick += new RoutedEventHandler(sysicon_Click); StateChanged += new EventHandler(MainWindow_StateChanged); sysicon.Icon = Shutdown7.Properties.Resources.Shutdown7; sysicon.ToolTipText = Title; ContextMenu menu = new ContextMenu(); contextRestore = new MenuItem(); contextRestore.Header = Data.L["Hide"]; contextRestore.Click += new RoutedEventHandler(contextRestore_Click); contextRestore.FontWeight = FontWeights.Bold; menu.Items.Add(contextRestore); contextAbort = new MenuItem(); contextAbort.Header = Data.L["Abort"]; contextAbort.Click += new RoutedEventHandler(contextAbort_Click); contextAbort.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Abort.ico")), Width = 16, Height = 16 }; menu.Items.Add(contextAbort); /*contextAutostart = new MenuItem(); contextAutostart.Header = Data.L["Autostart"]; contextAutostart.IsCheckable = true; contextAutostart.IsChecked = Data.S["Autostart"]; contextAutostart.Click += new RoutedEventHandler(contextAutostart_Click); menu.Items.Add(contextAutostart);*/ contextShutdown = new MenuItem(); contextShutdown.Header = Data.L["Shutdown"]; menu.Items.Add(contextShutdown); contextShutdown1 = new MenuItem(); contextShutdown1.Header = Data.L["Shutdown"]; contextShutdown1.Click += new RoutedEventHandler(contextShutdown1_Click); contextShutdown1.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Shutdown.ico")), Width = 16, Height = 16 }; contextShutdown.Items.Add(contextShutdown1); contextShutdown2 = new MenuItem(); contextShutdown2.Header = Data.L["Restart"]; contextShutdown2.Click += new RoutedEventHandler(contextShutdown2_Click); contextShutdown2.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Reboot.ico")), Width = 16, Height = 16 }; contextShutdown.Items.Add(contextShutdown2); contextShutdown3 = new MenuItem(); contextShutdown3.Header = Data.L["Logoff"]; contextShutdown3.Click += new RoutedEventHandler(contextShutdown3_Click); contextShutdown3.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Logoff.ico")), Width = 16, Height = 16 }; contextShutdown.Items.Add(contextShutdown3); contextShutdown4 = new MenuItem(); contextShutdown4.Header = Data.L["Lock"]; contextShutdown4.Click += new RoutedEventHandler(contextShutdown4_Click); contextShutdown4.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Logoff.ico")), Width = 16, Height = 16 }; contextShutdown.Items.Add(contextShutdown4); contextShutdown5 = new MenuItem(); contextShutdown5.Header = Data.L["Standby"]; contextShutdown5.Click += new RoutedEventHandler(contextShutdown5_Click); contextShutdown5.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Standby.ico")), Width = 16, Height = 16 }; contextShutdown.Items.Add(contextShutdown5); contextShutdown6 = new MenuItem(); contextShutdown6.Header = Data.L["Hibernate"]; contextShutdown6.Click += new RoutedEventHandler(contextShutdown6_Click); contextShutdown6.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Standby.ico")), Width = 16, Height = 16 }; contextShutdown.Items.Add(contextShutdown6); contextShutdown7 = new MenuItem(); contextShutdown7.Header = Data.L["HibernateWOSBIni"]; contextShutdown7.Click += new RoutedEventHandler(contextShutdown7_Click); contextShutdown7.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/WOSB.ico")), Width = 16, Height = 16 }; if (!Data.S["WOSB"]) contextShutdown7.Visibility = Visibility.Collapsed; contextShutdown.Items.Add(contextShutdown7); /*contextShutdown8 = new MenuItem(); contextShutdown8.Header = Data.L["Abort"]; contextShutdown8.Click += new RoutedEventHandler(contextShutdown8_Click); contextShutdown8.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Shutdown7;component/Resources/Abort.ico")), Width = 16, Height = 16 }; contextShutdown.Items.Add(contextShutdown8);*/ if (Timer.IsEnabled) { contextAbort.IsEnabled = true; contextShutdown.IsEnabled = false; /*contextShutdown1.IsEnabled = false; contextShutdown2.IsEnabled = false; contextShutdown3.IsEnabled = false; contextShutdown4.IsEnabled = false; contextShutdown5.IsEnabled = false; contextShutdown6.IsEnabled = false; contextShutdown7.IsEnabled = false; contextShutdown8.IsEnabled = true;*/ } else { contextAbort.IsEnabled = false; contextShutdown.IsEnabled = true; /*contextShutdown1.IsEnabled = true; contextShutdown2.IsEnabled = true; contextShutdown3.IsEnabled = true; contextShutdown4.IsEnabled = true; contextShutdown5.IsEnabled = true; contextShutdown6.IsEnabled = true; contextShutdown7.IsEnabled = true; contextShutdown8.IsEnabled = false;*/ } menu.Items.Add(new Separator()); contextExit = new MenuItem(); contextExit.Header = Data.L["Exit"]; contextExit.Click += new RoutedEventHandler(contextExit_Click); menu.Items.Add(contextExit); sysicon.ContextMenu = menu; sysicon.Visibility = Visibility.Visible; } public void DisposeSystray() { if (sysicon != null) { sysicon.Visibility = Visibility.Collapsed; sysicon.Dispose(); } } #region Events void MainWindow_StateChanged(object sender, EventArgs e) { if (Data.S["SysIcon"] & !hiding) { switch (WindowState) { case WindowState.Minimized: Visibility = Visibility.Hidden; Hide(); contextRestore.Header = Data.L["Restore"]; break; case WindowState.Normal: Activate(); Focus(); contextRestore.Header = Data.L["Hide"]; break; } } } public void sysicon_Click(object sender, RoutedEventArgs e) { if (Visibility == Visibility.Hidden) { Show(); WindowState = WindowState.Normal; Activate(); Focus(); contextRestore.Header = Data.L["Hide"]; } else { hiding = true; WindowState = WindowState.Minimized; hiding = false; Hide(); contextRestore.Header = Data.L["Restore"]; } } #endregion #region Contextmenu public void contextRestore_Click(object sender, EventArgs e) { if (WindowState == WindowState.Minimized) { contextRestore.Header = Data.L["Hide"]; this.Visibility = Visibility.Visible; this.Show(); this.WindowState = WindowState.Normal; this.Focus(); } else { contextRestore.Header = Data.L["Restore"]; hiding = true; this.WindowState = WindowState.Minimized; this.Visibility = Visibility.Hidden; this.Hide(); hiding = false; } } /*public void contextAutostart_Click(object sender, EventArgs e) { if (contextAutostart.IsChecked) { Autostart.SetAutoStart("Shutdown", Data.EXE + " /Run"); Data.S["Autostart"] = true; contextAutostart.IsChecked = true; } else { Autostart.UnSetAutoStart("Shutdown"); Data.S["Autostart"] = false; contextAutostart.IsChecked = false; } Xml.Write(); }*/ public void contextExit_Click(object sender, EventArgs e) { sysicon.Dispose(); Application.Current.Shutdown(); } public void contextShutdown1_Click(object sender, EventArgs e) { sysicon.ShowBalloonTip("Shutdown7", String.Format(Data.L["BalloontipTimeShutdown"], Data.L["FiveSecs"]), BalloonIcon.Info); Data.Mode = Data.Modes.Lock; Data.Condition = Data.Conditions.Time; Data.t = TimeSpan.FromSeconds(5); comboModus.SelectedIndex = 0; LockUI(); Execute(); } public void contextShutdown2_Click(object sender, EventArgs e) { sysicon.ShowBalloonTip("Shutdown7", String.Format(Data.L["BalloontipTimeRestart"], Data.L["FiveSecs"]), BalloonIcon.Info); Data.Mode = Data.Modes.Lock; Data.Condition = Data.Conditions.Time; Data.t = TimeSpan.FromSeconds(5); comboModus.SelectedIndex = 1; LockUI(); Execute(); } public void contextShutdown3_Click(object sender, EventArgs e) { sysicon.ShowBalloonTip("Shutdown7", String.Format(Data.L["BalloontipTimeLogoff"], Data.L["FiveSecs"]), BalloonIcon.Info); Data.Mode = Data.Modes.Lock; Data.Condition = Data.Conditions.Time; Data.t = TimeSpan.FromSeconds(5); comboModus.SelectedIndex = 2; LockUI(); Execute(); } public void contextShutdown4_Click(object sender, EventArgs e) { sysicon.ShowBalloonTip("Shutdown7", String.Format(Data.L["BalloontipTimeLock"], Data.L["FiveSecs"]), BalloonIcon.Info); Data.Mode = Data.Modes.Lock; Data.Condition = Data.Conditions.Time; Data.t = TimeSpan.FromSeconds(5); comboModus.SelectedIndex = 3; LockUI(); Execute(); } public void contextShutdown5_Click(object sender, EventArgs e) { sysicon.ShowBalloonTip("Shutdown7", String.Format(Data.L["BalloontipTimeStandby"], Data.L["FiveSecs"]), BalloonIcon.Info); Data.Mode = Data.Modes.Lock; Data.Condition = Data.Conditions.Time; Data.t = TimeSpan.FromSeconds(5); comboModus.SelectedIndex = 4; LockUI(); Execute(); } public void contextShutdown6_Click(object sender, EventArgs e) { sysicon.ShowBalloonTip("Shutdown7", String.Format(Data.L["BalloontipTimeHibernate"], Data.L["FiveSecs"]), BalloonIcon.Info); Data.Mode = Data.Modes.Lock; Data.Condition = Data.Conditions.Time; Data.t = TimeSpan.FromSeconds(5); comboModus.SelectedIndex = 5; LockUI(); Execute(); } public void contextShutdown7_Click(object sender, EventArgs e) { Data.Mode = Data.Modes.HibernateWOSBIni; expanderMode.IsEnabled = false; expanderMode.IsExpanded = false; expanderRemote.IsEnabled = false; expanderRemote.IsExpanded = false; Execute(); } public void contextAbort_Click(object sender, EventArgs e) { sysicon.ShowBalloonTip("Shutdown7", Data.L["BalloontipAbort"], BalloonIcon.Info); StopShutdown(); } #endregion #endregion } } <file_sep>/Win7Franework4.cs using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Shell; namespace Shutdown7 { class Win7Framework4 { public static JumpList jumpList; private static TaskbarItemInfo taskbar = new TaskbarItemInfo(); public static bool IsWin7 { get { //return TaskbarManager.IsPlatformSupported; return Environment.OSVersion.Version >= new Version(6, 1); } } public static bool IsWin8 { get { //return TaskbarManager.IsPlatformSupported; return Environment.OSVersion.Version >= new Version(6, 2); } } #region Taskbar public static void Progress(int cur) { if (!IsWin7) return; taskbar.ProgressValue = (double)(cur / 100); } public static void Progress(int cur, int max) { if (!IsWin7) return; taskbar.ProgressValue = (double)(cur / max); } public static void ProgressType(string Type) { if (!IsWin7) return; switch (Type) { case "Normal": taskbar.ProgressState = TaskbarItemProgressState.Normal; break; case "Paused": taskbar.ProgressState = TaskbarItemProgressState.Paused; break; case "Error": taskbar.ProgressState = TaskbarItemProgressState.Error; break; case "Indeterminate": taskbar.ProgressState = TaskbarItemProgressState.Indeterminate; break; default: taskbar.ProgressState = TaskbarItemProgressState.None; break; } } public static void Overlay(System.Drawing.Icon Icon, string Title) { if (!IsWin7) return; try { object resource = Application.Current.FindResource(Title); taskbar.Overlay = (DrawingImage)resource; } catch (ResourceReferenceKeyNotFoundException ex) { MessageBox.Show("Resource not found."); taskbar.Overlay = null; } } public static void ThumbnailToolbar(String Command, String Description, String Image) { if (!Win7.IsWin7) return; ThumbButtonInfo Button = new ThumbButtonInfo(); //Button.Command = Command; Button.Description = Description; Button.ImageSource = (DrawingImage) Application.Current.FindResource(Image); taskbar.ThumbButtonInfos.Add(Button); } public static void ThumbnailToolbar(IntPtr handle, ThumbButtonInfo Button) { if (!Win7.IsWin7) return; //Button.ImageSource = ; taskbar.ThumbButtonInfos.Add(Button); } public static void Jumplist() { if (!Win7.IsWin7) return; try { //jumplist = JumpList.GetJumpList(App.Current); //jumplist.JumpItems.Clear(); JumpTask jumpTask1 = new JumpTask(); jumpTask1.ApplicationPath = Data.EXE; jumpTask1.IconResourcePath = Data.EXE; jumpTask1.IconResourceIndex = 1; jumpTask1.Arguments = "-s"; jumpList.JumpItems.Add(jumpTask1); JumpList.SetJumpList(App.Current, jumpList); /*jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Restart"]) { IconReference = new IconReference(Data.EXE, 2), Arguments = "-r" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Logoff"]) { IconReference = new IconReference(Data.EXE, 3), Arguments = "-l" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Lock"]) { IconReference = new IconReference(Data.EXE, 3), Arguments = "-lo" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Standby"]) { IconReference = new IconReference(Data.EXE, 4), Arguments = "-sb" }); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Hibernate"]) { IconReference = new IconReference(Data.EXE, 4), Arguments = "-h" }); if (Data.S["WOSB"]) { jumplist.AddUserTasks(new JumpListSeparator()); jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["HibernateWOSBIni"]) { IconReference = new IconReference(Data.EXE, 5), Arguments = "-hi" }); //jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["HibernateWOSBTime"]) { IconReference = new IconReference(Data.EXE, 5), Arguments = "-ht" }); } //jumplist.AddUserTasks(new JumpListSeparator()); //jumplist.AddUserTasks(new JumpListLink(Data.EXE, Data.L["Abort"]) { IconReference = new IconReference(EXE, 6), Arguments = "-a", WorkingDirectory = Path.GetDirectoryName(EXE) }); jumplist.Refresh();*/ } catch { } } public static void ClearJumplist() { if (!Win7.IsWin7) return; JumpList jumpList = JumpList.GetJumpList(App.Current); jumpList.JumpItems.Clear(); jumpList.Apply(); } #region Pin public static void PinToTaskbar() { if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Shutdown7.lnk")) { try { StreamWriter file = new StreamWriter(Environment.ExpandEnvironmentVariables("%Temp%") + "\\pin.vbs"); file.WriteLine("strlPath = \"" + Data.EXE + "\""); file.Write("On Error Resume Next\r\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\r\nSet objShell = CreateObject(\"Shell.Application\")\r\nIf Not objFSO.FileExists(strlPath) Then Wscript.Quit\r\nstrFolder = objFSO.GetParentFolderName(strlPath)\r\nstrFile = objFSO.GetFileName(strlPath)\r\nSet objFolder = objShell.Namespace(strFolder)\r\nSet objFolderItem = objFolder.ParseName(strFile)\r\nSet colVerbs = objFolderItem.Verbs\r\nFor each itemverb in objFolderItem.verbs\r\n"); file.WriteLine("If Replace(itemverb.name, \"&\", \"\") = \"" + Data.L["PinText"] + "\" Then itemverb.DoIt"); file.WriteLine("Next"); file.Close(); Process p = new Process(); p.StartInfo.FileName = Environment.ExpandEnvironmentVariables("%Temp%") + "\\pin.vbs"; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.Start(); p.WaitForExit(); File.Delete(Environment.ExpandEnvironmentVariables("%Temp%") + "\\pin.vbs"); } catch (Exception ex) { if (Data.debug_verbose) Message.Show(ex.Message, "Shutdown7", "Error"); } } } #endregion #endregion #region Aero [DllImport("dwmapi.dll", PreserveSig = false)] public static extern bool DwmIsCompositionEnabled(); [DllImport("dwmapi.dll", PreserveSig = false)] static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins); public static bool Glass(Window window) { if (Environment.OSVersion.Version.Major < 6) return false; if (Data.S["Glass"] & DwmIsCompositionEnabled()) return ExtendGlassFrame(window, new Thickness(-1)); else return false; } public static bool Glass(Window window, Thickness thickness) { if (Environment.OSVersion.Version.Major < 6) return false; if (Data.S["Glass"] & DwmIsCompositionEnabled()) return ExtendGlassFrame(window, thickness); else return false; } static bool ExtendGlassFrame(Window window, Thickness margin) { try { if (!DwmIsCompositionEnabled()) return false; IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) return false; //The Window must be shown before extending glass // Set the background to transparent from both the WPF and Win32 perspectives window.Background = Brushes.Transparent; HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent; MARGINS margins = new MARGINS(margin); DwmExtendFrameIntoClientArea(hwnd, ref margins); return true; } catch (DllNotFoundException) { return false; } } struct MARGINS { public MARGINS(Thickness t) { Left = (int)t.Left; Right = (int)t.Right; Top = (int)t.Top; Bottom = (int)t.Bottom; } public int Left; public int Right; public int Top; public int Bottom; } #endregion } }
d8f26f0e92940e375eb79fac71affd8f799b41fe
[ "C#" ]
15
C#
MariusLutz/Shutdown7
8bf0efd72be8509f68b5659f5561e720dc5062a8
83ab154669541447f3c4d6bef5fc87b841fc5502
refs/heads/master
<file_sep>def main(): encode_dict = {"A": "00", "C": "11", "G": "01", "T": "10"} seq = input("Seq: ").upper() encode_seq = [encode_dict[nuc] for nuc in seq] print("".join(encode_seq)) main()
1aa802dbb6fdd117e16e364acae3d2885573ec92
[ "Python" ]
1
Python
BramUt-Afvinkopdrachten/Blok6-Afvinkopdracht4
3684b318c5eaf865b59596b871bc1e60d873459a
0704cab258b4b518ddf6620ada1ca2d18eaf1523
refs/heads/master
<repo_name>pquiroza/liguerosAdmin<file_sep>/src/app/detallecampeonato/detallecampeonato.component.ts import { Component, OnInit } from '@angular/core'; import { MENU_ITEMS } from '../colaborador-menu'; import { NbWindowService } from '@nebular/theme'; import { NoticiasComponent } from '../noticias/noticias.component'; import { AngularFireStorage } from '@angular/fire/storage'; import { auth } from 'firebase/app'; import { AngularFireAuth} from 'angularfire2/auth'; import * as firebase from 'firebase'; import { HttpClient, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http'; import { environment } from '../../environments/environment'; import { NbToastrService } from '@nebular/theme'; import { Router } from '@angular/router'; @Component({ selector: 'ngx-detallecampeonato', templateUrl: './detallecampeonato.component.html', styleUrls: ['./detallecampeonato.component.scss'] }) export class DetallecampeonatoComponent implements OnInit { menu = MENU_ITEMS; idc: any; noticias: any; constructor(private windowService: NbWindowService, private storage: AngularFireStorage, private http: HttpClient) { this.ngOnInit(); } ngOnInit(): void { this.idc = localStorage.getItem("sel"); console.log(this.idc) this.getNoticias(this.idc).then(a => { console.log(a) this.noticias = a; }) } nuevaNoticia(){ let windowRef = this.windowService.open(NoticiasComponent, { title: `Nueva Noticia` }); this.getNoticias(this.idc).then(a => { this.noticias = a; }) } onClose(){ } getNoticias(idc){ return new Promise((resolve, reject) => { firebase.auth().onAuthStateChanged(usuario => { if (usuario){ this.http.get(environment.server+'/noticias?IdCampeonato='+idc).subscribe((noticias: any) => { console.log(noticias) resolve(noticias) }) } }) }) } } <file_sep>/src/app/colaborador-menu.ts import { NbMenuItem } from '@nebular/theme'; export const MENU_ITEMS: NbMenuItem[] = [ { title: 'Home ', icon: 'home-outline', link: '/colhome', home: true, }, { title: 'FEATURES', group: true, }, { title: 'Noticias', icon: 'cast-outline', link: '/noticias' }, { title: 'Equipos', icon: 'people-outline', link: '/colequipos' }, { title: 'Fases', icon: 'options-2-outline', link: '/fases' }, { title: 'Amonestados', icon: 'square-outline', link: '/amonestados' }, { title: 'Suspendidos', icon: 'square-outline', link: '/suspendidos' }, { title: 'Logs', icon: 'file-text-outline', link: '/logs' }, ]; <file_sep>/gobrandom.py import random for i in range(1,14): num1 = random.randint(1,14) print(num1) <file_sep>/src/app/@theme/layouts/login/login.layout.ts import { Component } from '@angular/core'; @Component({ selector: 'login-layout', styleUrls: ['./login.layout.scss'], template: ` <nb-layout windowMode> <nb-layout-column> <ng-content select="router-outlet"></ng-content> </nb-layout-column> </nb-layout> `, }) export class LoginLayoutComponent {} <file_sep>/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { auth } from 'firebase/app'; import { AngularFireAuth} from 'angularfire2/auth'; import * as firebase from 'firebase'; import { HttpClient, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http'; import { environment } from '../../environments/environment'; import { NbToastrService } from '@nebular/theme'; import { Router } from '@angular/router'; @Component({ selector: 'ngx-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { constructor(public firebaseAuth: AngularFireAuth, private toastrService: NbToastrService, private router: Router, private http: HttpClient) { } ngOnInit(): void { } login(email, password){ console.log(email, password); this.firebaseAuth.auth.signInWithEmailAndPassword(email,password).then((result) =>{ firebase.auth().onAuthStateChanged(usuario => { this.http.get(environment.server+'/usuario?IdGoogle='+usuario.uid).subscribe((tipo:any) => { console.log(tipo[0]) console.log(tipo[0].TIPO); if (tipo[0].TIPO==="Administrador"){ this.router.navigate(['colhome']); } else{ this.router.navigate(['admhome']) } }) }) }).catch(error => { console.log("ACA NO"); let position: any = 'top-right'; let status: any = 'danger'; this.toastrService.show("Nombre de usuario o password incorrecto p<PASSWORD>","Error",{position,status}); }) } } <file_sep>/src/app/app.module.ts /** * @license * Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { CoreModule } from './@core/core.module'; import { ThemeModule } from './@theme/theme.module'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { AngularFireModule } from 'angularfire2'; import { AngularFireAuthModule } from 'angularfire2/auth'; import { Ng2SmartTableModule } from 'ng2-smart-table'; import { NgxFileHelpersModule } from 'ngx-file-helpers'; import { NbChatModule, NbDatepickerModule, NbDialogModule, NbMenuModule, NbSidebarModule, NbToastrModule, NbWindowModule, NbButtonModule, NbCardModule, NbAccordionModule, NbInputModule } from '@nebular/theme'; import { LoginComponent } from './login/login.component'; import { environment } from '../environments/environment'; import { ColhomeComponent } from './colhome/colhome.component'; import { DetallecampeonatoComponent } from './detallecampeonato/detallecampeonato.component'; import { NoticiasComponent } from './noticias/noticias.component'; import { AngularFireStorageModule } from '@angular/fire/storage'; import { ColequiposComponent } from './colequipos/colequipos.component'; @NgModule({ declarations: [AppComponent, LoginComponent, ColhomeComponent, DetallecampeonatoComponent, NoticiasComponent, ColequiposComponent], imports: [ BrowserModule, BrowserAnimationsModule, HttpClientModule, AppRoutingModule, NbButtonModule, Ng2SmartTableModule, NbCardModule, NbInputModule, NbAccordionModule, NgxFileHelpersModule, NbWindowModule, ThemeModule.forRoot(), AngularFireModule.initializeApp(environment.firebase), AngularFireStorageModule, AngularFireAuthModule, NbSidebarModule.forRoot(), NbMenuModule.forRoot(), NbDatepickerModule.forRoot(), NbDialogModule.forRoot(), NbWindowModule.forRoot(), NbToastrModule.forRoot(), NbChatModule.forRoot({ messageGoogleMapKey: '<KEY>', }), CoreModule.forRoot(), ], bootstrap: [AppComponent], }) export class AppModule { } <file_sep>/src/environments/environment.ts /** * @license * Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ // The file contents for the current environment will overwrite these during build. // The build system defaults to the dev environment which uses `environment.ts`, but if you do // `ng build --env=prod` then `environment.prod.ts` will be used instead. // The list of which env maps to which file can be found in `.angular-cli.json`. export const environment = { production:false, server: "http://172.16.31.10:5002/ligueros/api", firebase:{ apiKey: "<KEY>", authDomain: "ligueros-af5b3.firebaseapp.com", databaseURL: "https://ligueros-af5b3.firebaseio.com", projectId: "ligueros-af5b3", storageBucket: "ligueros-af5b3.appspot.com", messagingSenderId: "290557695821", appId: "1:290557695821:web:62d5f7e53cc626b0648904", measurementId: "G-VFK6CNBKME" } }; <file_sep>/src/app/colequipos/colequipos.component.ts import { Component, OnInit } from '@angular/core'; import { MENU_ITEMS } from '../colaborador-menu'; import { auth } from 'firebase/app'; import { AngularFireAuth} from 'angularfire2/auth'; import * as firebase from 'firebase'; import { HttpClient, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http'; import { environment } from '../../environments/environment'; import { NbToastrService } from '@nebular/theme'; import { Router } from '@angular/router'; @Component({ selector: 'ngx-colequipos', templateUrl: './colequipos.component.html', styleUrls: ['./colequipos.component.scss'] }) export class ColequiposComponent implements OnInit { menu = MENU_ITEMS; equipos: any; settings = { actions: {delete: false}, add: { confirmCreate: true, addButtonContent: '<i class="nb-plus"></i>', createButtonContent: '<i class="nb-checkmark"></i>', cancelButtonContent: '<i class="nb-close"></i>', }, edit: { editButtonContent: '<i class="nb-edit"></i>' }, columns: { id: { title: 'ID', editable: false }, nombre: { title: 'Equipo' }, descripcion: { title: 'Descripcion' } } }; data: any; datos: any; idc: any; constructor(private router: Router, private http: HttpClient) { this.idc = localStorage.getItem("sel"); this.getEquipos(this.idc).then((a:any) => { this.equipos = a; a.forEach(c => { this.datos = a.map( c => { return { id: c.IDEQUIPO, nombre: c.NOMBRE, descripcion: c.DESCRIPCION, } }) }) }) } getEquipos(idc){ return new Promise((resolve, reject) => { firebase.auth().onAuthStateChanged(usuario => { if (usuario){ this.http.get(environment.server+'/equipos?IdCampeonato='+this.idc).subscribe((equipos: any) => { console.log(equipos) this.equipos = equipos; equipos.forEach(c => { this.datos = equipos.map( c => { return { id: c.IDEQUIPO, nombre: c.NOMBRE, descripcion: c.DESCRIPCION, } }) }) resolve(equipos) }) } }) }) } onEdit(event){ } onCreateConfirm(event){ console.log(event) let datos = [{ "Nombre": event.newData.nombre, "Descripcion": event.newData.descripcion, "Logo": "logo dummy", "IdCampeonato": this.idc }] firebase.auth().onAuthStateChanged(usuario => { if(usuario){ this.http.post(environment.server+'/equipo',datos,{observe:'response'}).subscribe((result: any) => { console.log(result) event.confirm.resolve(event.newData) }) } }) } llamada(){ console.log("LLAMADA") } ngOnInit(): void { } } <file_sep>/src/app/colhome/colhome.component.ts import { Component, OnInit } from '@angular/core'; import { auth } from 'firebase/app'; import { AngularFireAuth} from 'angularfire2/auth'; import * as firebase from 'firebase'; import { HttpClient, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http'; import { environment } from '../../environments/environment'; import { NbToastrService } from '@nebular/theme'; import { Router } from '@angular/router'; @Component({ selector: 'ngx-colhome', templateUrl: './colhome.component.html', styleUrls: ['./colhome.component.scss'] }) export class ColhomeComponent implements OnInit { settings = { mode: 'external', actions: {delete: false ,add:false}, add: { confirmCreate: true, addButtonContent: '<i class="nb-plus"></i>', createButtonContent: '<i class="nb-checkmark"></i>', cancelButtonContent: '<i class="nb-close"></i>', }, edit: { editButtonContent: '<i class="nb-edit"></i>' }, columns: { id: { title: 'ID', editable: false }, name: { title: 'Campeonato' }, tipo: { title: 'Tipo' }, sexo: { title: 'Sexo' }, ubicacion:{ title: 'Ubicacion' }, categoria: { title: 'Categoria' } } }; data: any; datos: any; constructor(private router: Router, private http: HttpClient) { this.datos = new Array(); console.log("LLEGANDO AL DASHBOARD") firebase.auth().onAuthStateChanged(usuario => { if (usuario){ console.log(usuario.uid) this.http.get(environment.server+'/campeonatos?idUsuario='+usuario.uid).subscribe((campeonatos: any) => { localStorage.setItem("campeonatos",JSON.stringify(campeonatos)); campeonatos.forEach(c => { this.datos =campeonatos.map( c => { return { id: c.IDCAMPEONATO, name: c.NOMBRECAMPEONATO, tipo: c.TIPO, sexo: c.SEXO, ubicacion: c.UBICACION, categoria: c.CATEGORIA, detalle: c.IDCAMPEONATO } }) }) }) } }) } onEdit(event){ console.log(event); localStorage.setItem("sel",event.data.id); this.router.navigate(['/detallecampeonato']); } ngOnInit(): void { } } <file_sep>/src/app/@theme/layouts/home/home.layout.ts import { Component } from '@angular/core'; @Component({ selector: 'home-layout', styleUrls: ['./home.layout.scss'], template: ` <nb-layout windowMode> <nb-layout-column> <ng-content select="router-outlet"></ng-content> </nb-layout-column> <nb-layout-footer fixed> <ngx-footer></ngx-footer> </nb-layout-footer> </nb-layout> `, }) export class HomeLayoutComponent {} <file_sep>/src/app/noticias/noticias.component.ts import { Component, OnInit } from '@angular/core'; import { AngularFireStorage } from '@angular/fire/storage'; import { auth } from 'firebase/app'; import { AngularFireAuth} from 'angularfire2/auth'; import * as firebase from 'firebase'; import { HttpClient, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http'; import { environment } from '../../environments/environment'; import { NbToastrService } from '@nebular/theme'; import { NbWindowRef } from '@nebular/theme'; import { Router } from '@angular/router'; @Component({ selector: 'ngx-noticias', templateUrl: './noticias.component.html', styleUrls: ['./noticias.component.scss'] }) export class NoticiasComponent implements OnInit { idc: any; archivo: any; constructor(private storage: AngularFireStorage, private http: HttpClient, protected windowRef: NbWindowRef, public router: Router) { this.idc = localStorage.getItem("sel"); } ngOnInit(): void { } onFilePicked(event){ this.archivo = event._underlyingFile; } guardaNoticia(titulo,detalle){ firebase.auth().onAuthStateChanged(usuario => { if (usuario){ var n = Date.now(); let nombre = n+"-"+this.idc let ruta = `fotos/${nombre}`; let referencia = this.storage.ref(ruta); console.log(this.archivo) this.storage.upload(`fotos/${nombre}`,this.archivo).percentageChanges().subscribe((subida: any) => { console.log(subida); referencia.getDownloadURL().subscribe(url => { console.log(url); let datos = [{ "IdCampeonato": this.idc, "Titulo": titulo, "Descripcion": detalle, "URLFoto": url }] this.http.post(environment.server+'/noticia',datos,{observe:'response'}).subscribe((d:any) => { console.log(d); this.router.navigate(['/detallecampeonato']) this.windowRef.close(); }) }) }); } }) } }
f93742e403892de2f32cd0222741c764fad25a7c
[ "Python", "TypeScript" ]
11
TypeScript
pquiroza/liguerosAdmin
2d27b75bc68b4a55f3e34f069e87daa5d7f2b904
c8ab135d500589cf7808f96163b6629763b10743
refs/heads/master
<file_sep>OpenWrt LuCI for Shadowsocks(R)-libev, gfwpress === 恩山乌卡卡版本的升级版,已在[HG255D][O1] & [WNDR4300][O2]中应用 简介 --- 本软件包是 [shadowsocks(R)-libev][openwrt-shadowsocks(R)][openwrt-gfwpress] 的 LuCI 控制界面,自带GFWList,国内路由表等分流功能。支持一键智能配置 特性 1、支持基于GFWList的智能分流 2、支持基于国内路由表的智能分流 3、支持国外翻回国内看优酷等视频网站 4、支持基于GFWList的智能DNS解析 5、支持`auth_sha1_v4`,`auth_aes128_md5`,`auth_aes128_sha1`等新型混淆协议 6、支持混淆参数和协议参数 7、支持游戏模式(全局+国内分流UDP转发) 8、支持Adbyby和KoolProxy兼容模式 9、支持GFWlist黑名单和国内路由表手动更新 10、支持ssr-tunnel和pdnsd的DNS解析 11、支持填写服务器域名或者服务器IP 12、可配合HAProxy实现多服务器负载均衡,也可以设置多个备用服务器实现高可用,[详情][haproxy] 13、可配合KCPTUN提高网络质量,[详情][kcptun] 14、支持LAN访问控制(Adbyby/KoolProxy模式需要配合以上二者自己的访问控制功能使用,否则会冲突) 依赖 --- 软件包的正常使用需要依赖 `iptables` 和 `ipset`用于流量重定向 `pdnsd`用于TCP协议请求DNS便于转发至SSR服务器 `ip-full` `iptables-mod-tproxy` `kmod-ipt-tproxy` `iptables-mod-nat-extra` 用于实现UDP转发 配置 --- 软件包的配置文件路径: `/etc/config/shadowsocks` 一般情况下,只需填写服务器IP或者域名,端口,密码,加密方式,混淆,协议即可使用默认的只能模式科学上网,兼顾国内外分流。无需其他复杂操作 编译 --- 从 OpenWrt 的 [SDK][openwrt-sdk] 编译 ```bash # 解压下载好的 SDK tar xjf OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.8-linaro_uClibc-0.9.33.2.tar.bz2 cd OpenWrt-SDK-ar71xx-* # Clone 项目 git clone https://github.com/peter-tank/luci-app-shadowsocks.git package/luci-app-shadowsocks # 编译 po2lmo (如果有po2lmo可跳过) pushd package/luci-app-shadowsocks/tools/po2lmo make && sudo make install popd # 选择要编译的包 NetWork -> LuCI -> luci-app-shadowsocks make menuconfig # 开始编译 make package/luci-app-shadowsocks/compile V=99 ``` 软件截图 --- ![demo](https://github.com/peter-tank/luci-app-shadowsocks/raw/master/screenshots.png) [O1]: http://www.right.com.cn/forum/thread-198649-1-1.html [O2]: http://www.right.com.cn/forum/thread-205639-1-1.html [openwrt-shadowsocks(R)]: https://github.com/AlexZhuo/openwrt-shadowsocksR [openwrt-gfwpress]: https://github.com/peter-tank/openwrt-gfwpress [openwrt-sdk]: https://wiki.openwrt.org/doc/howto/obtain.firmware.sdk [haproxy]: https://github.com/AlexZhuo/luci-app-haproxy-tcp [kcptun]: https://github.com/AlexZhuo/luci-app-kcptun <file_sep>#!/bin/sh /etc/init.d/shadowsocks disable /etc/init.d/shadowsocks stop /etc/init.d/shadowsocks stop <file_sep>local disp=require"luci.dispatcher" local NXFS=require"nixio.fs" local n=require("luci.model.ipkg") local s=luci.model.uci.cursor() local i="shadowsocks" local a,t,e,o local _cgfw=luci.sys.exec("cat /etc/dnsmasq.d/gfwlist.conf|grep -c ipset") function is_installed(e) return n.installed(e) end local n={} s:foreach(i,"servers",function(e) if e.server and e.remarks then n[e[".name"]]="%s:%s"%{e.remarks,e.server} end end) a=Map(i,translate("ShadowSocks"),translate("A lightweight secured SOCKS5 proxy")) a.template="shadowsocks/index" t=a:section(NamedSection,"shadowsocks","global",translate("Global Setting")) -- section might not exist function t.cfgvalue(self, section) if not self.map:get(section) then self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end t.anonymous=true -- Part of GLOBAL t:tab("_global_setting", translate("Global Setting")) e=t:taboption("_global_setting", ListValue,"global_server",translate("Current Server")) e.default="nil" e.rmempty=false e:value("nil",translate("Disable")) for a,t in pairs(n)do e:value(a,t)end e=t:taboption("_global_setting", ListValue,"proxy_mode",translate("Default")..translate("Proxy Mode")) e.default="gfwlist" e.rmempty=false e:value("disable",translate("No Proxy")) e:value("global",translate("Global Proxy")) e:value("gfwlist",translate("GFW List")) e:value("chnroute",translate("China WhiteList")) e:value("gamemode",translate("Game Mode")) e:value("returnhome",translate("Return Home")) e=t:taboption("_global_setting", ListValue,"dns_mode",translate("DNS Forward Mode")) e.default="dns2socks" e.rmempty=false e:reset_values() if is_installed("dns2socks")then e:value("dns2socks","dns2socks") end if is_installed("pcap-dnsproxy")then e:value("pcap-dnsproxy","pcap-dnsproxy") end if is_installed("pdnsd")then e:value("pdnsd","pdnsd") end if is_installed("cdns")then e:value("cdns","cdns") end if is_installed("ChinaDNS")then e:value("chinadns","chinadns") end if is_installed("dnscrypt-proxy")then e:value("dnscrypt-proxy","dnscrypt-proxy") end e:value("ssr-tunnel","ssr-tunnel") e=t:taboption("_global_setting", Value,"dns_forward",translate("DNS Forward Address")) e.default="8.8.8.8:53" e.rmempty=false e=t:taboption("_global_setting", Value,"start_delay",translate("Delay Start")) e:value(0, translate("Not enabled")) for _, o in ipairs({5, 10, 15, 25, 40}) do e:value(o, translate("%u seconds") %{o}) end e.datatype = "uinteger" e.rmempty=true e=t:taboption("_global_setting", Flag,"auto_on",translate("Open and close automatically")) e.default=0 e.rmempty=false e=t:taboption("_global_setting", ListValue,"time_on",translate("Automatically turn on time")) for o=0,23 do e:value(o,o .. " " .. translate("oclock")) end e.default=8 e:depends("auto_on","1") e=t:taboption("_global_setting", ListValue,"time_off",translate("Automatically turn off time")) for o=0,23 do e:value(o,o .. " " .. translate("oclock")) end e.default=2 e:depends("auto_on","1") -- Part of GLOBAL t:tab("_global_mwan", translate("Multi WAN")) e=t:taboption("_global_mwan", Value,"dns_1",translate("Mainland DNS Sever 1")) e.default="172.16.31.10" e:value("172.16.31.10",translate("172.16.31.10(Ali)")) e:value("172.16.58.3",translate("172.16.58.3(Ali)")) e:value("172.16.31.10",translate("172.16.31.10(114DNS)")) e:value("192.168.3.11",translate("192.168.3.11(114DNS)")) e:value("172.16.58.3",translate("172.16.58.3(DNSPOD)")) e:value("172.16.17.32",translate("172.16.17.32(DNSPOD)")) e:value("192.168.127.12",translate("192.168.127.12(CNNIC)")) e:value("172.16.17.32",translate("172.16.17.32(CNNIC)")) e:value("172.16.31.10",translate("172.16.31.10(BAIDU)")) e:value("8.8.8.8",translate("8.8.8.8(GOOGLE)")) e:value("8.8.4.4",translate("8.8.4.4(GOOGLE)")) e.rmempty=false e=t:taboption("_global_mwan", Value,"dns_2",translate("Mainland DNS Sever 2")) e.default="172.16.58.3" e:value("172.16.31.10",translate("172.16.31.10(Ali)")) e:value("172.16.58.3",translate("172.16.58.3(Ali)")) e:value("172.16.31.10",translate("172.16.31.10(114DNS)")) e:value("192.168.3.11",translate("192.168.3.11(114DNS)")) e:value("172.16.58.3",translate("172.16.58.3(DNSPOD)")) e:value("172.16.17.32",translate("172.16.17.32(DNSPOD)")) e:value("192.168.127.12",translate("1.2.4.8(CNNIC)")) e:value("172.16.17.32",translate("172.16.17.32(CNNIC)")) e:value("172.16.31.10",translate("172.16.31.10(BAIDU)")) e:value("8.8.8.8",translate("8.8.8.8(GOOGLE)")) e:value("8.8.4.4",translate("8.8.4.4(GOOGLE)")) e.rmempty=false local o=luci.sys.exec("ip route|grep default|wc -l") e=t:taboption("_global_mwan", ListValue,"dns_port",translate("DNS Export Of Multi WAN")) for o=0,o do if o==0 then e:value(o,translate("Not Specify")) else local s=luci.sys.exec("ip route|grep default|sed -n %qp|awk -F' ' {'print $5'}"%{o}) local s=luci.sys.exec("cat /var/state/network|grep -w %q|awk -F'.' '{print $2}'"%{s}) e:value(o,translate("%s"%{s})) end end e.default=0 e.rmempty=false e=t:taboption("_global_mwan", Flag,"dns_53",translate("DNS Hijack"),"UDP/53->LAN Interface") e.default=0 e.rmempty=false local e=luci.sys.exec("ip route|grep default|wc -l") e=t:taboption("_global_mwan", ListValue,"wan_port",translate("Export Of Multi WAN")) for o=0,o do if o==0 then e:value(o,translate("Not Specify")) else local s=luci.sys.exec("ip route|grep default|sed -n %qp|awk -F' ' {'print $5'}"%{o}) local s=luci.sys.exec("cat /var/state/network|grep -w %q|awk -F'.' '{print $2}'"%{s}) e:value(o,translate("%s"%{s})) end end e.default=0 e.rmempty=false -- Part of GLOBAL t:tab("_global_gfwupdate", translate("Rule Update"),"<a href='https://raw.githubusercontent.com/koolshare/koolshare.github.io/acelan_softcenter_ui/maintain_files/version1'>New Date Versions Fetching From Here...</a>To: /etc/dnsmasq.d/(gfwlist|chnroute|adblock|cdn).conf") e=t:taboption("_global_gfwupdate", DummyValue,"gfwlist_version",translate("gfwlist lines:") .. _cgfw,"Date Version") e=t:taboption("_global_gfwupdate", Button,"_start",translate("Manually update rules"),"Check online.") e.inputstyle="apply" function e.write(o,o) luci.sys.call("/usr/share/shadowsocks/ssruleupdate") luci.http.redirect(disp.build_url("admin","services","shadowsocks","settings")) end e=t:taboption("_global_gfwupdate", Flag,"auto_update",translate("Enable auto update rules")) e.default=0 e.rmempty=false e=t:taboption("_global_gfwupdate", ListValue,"week_update",translate("Week update rules")) e:value(7,translate("everyday")) for o=1,6 do e:value(o,translate("weekday") .. " " .. o) end e:value(0,translate("Sunday")) e.default=0 e.rmempty=false e=t:taboption("_global_gfwupdate", ListValue,"time_update",translate("Day update rules")) for o=0,23 do e:value(o,o .. " " .. translate("oclock")) end e.default=0 e.rmempty=false -- Part of GLOBAL t:tab("_global_status", translate("Running Status")) button_update = t:taboption("_global_status", Button, "_button3", translate("Force startup")) button_update.inputtitle = translate("Force startup") button_update.inputstyle = "apply" function button_update.write(self, section) os.execute('/etc/sh/ss_start &') self.inputtitle = translate("Force startup") end button_update = t:taboption("_global_status", Button, "_button4", translate("Force close")) button_update.inputtitle = translate("Force close") button_update.inputstyle = "apply" function button_update.write(self, section) os.execute('/etc/sh/ss_stop &') self.inputtitle = translate("Force close") end -------------- e=t:taboption("_global_status", DummyValue,"ss_redir_status",translate("Transparent Proxy")) e.template="shadowsocks/dvalue" e.value=translate("Collecting data...") e=t:taboption("_global_status", DummyValue,"haproxy_status",translate("Load Balancing")) e.template="shadowsocks/haproxy" e.value=translate("Collecting data...") e=t:taboption("_global_status", DummyValue,"kcp_status",translate("KCP Client")) e.template="shadowsocks/kcp" e.value=translate("Collecting data...") e=t:taboption("_global_status", DummyValue,"china_china",translate("China Connection")) e.template="shadowsocks/china" e.value=translate("Collecting data...") e=t:taboption("_global_status", DummyValue,"foreign_foreign",translate("Foreign Connection")) e.template="shadowsocks/foreign" e.value=translate("Collecting data...") -- Part of GLOBAL t:tab("_global_logs", translate("Log File Viewer"),translate("These is shadowsocks start logs.") .. "/var/log/shadowsocks.log") local o="/var/log/shadowsocks.log" e = t:taboption("_global_logs", DummyValue, "_logview") e.template = "shadowsocks/logview" e.inputtitle = translate("Read / Reread log file") e.rows = 20 e.wrap="off" function e.cfgvalue(self, section) local lfile="/var/log/" .. section .. ".log" if NXFS.access(lfile) then return lfile .. "\n" .. translate("Please press [Read] button") end return lfile .. "\n" .. translate("File not found or empty") end t=a:section(TypedSection,"servers",translate("Servers List")) t.anonymous=true t.addremove=true t.template="cbi/tblsection" t.extedit=disp.build_url("admin","services","shadowsocks","serverconfig","%s") function t.create(e,t) local e=TypedSection.create(e,t) luci.http.redirect(disp.build_url("admin","services","shadowsocks","serverconfig",e)) end function t.remove(t,a) t.map.proceed=true t.map:del(a) luci.http.redirect(disp.build_url("admin","services","shadowsocks")) end e=t:option(DummyValue,"remarks",translate("Node Remarks")) e.width="30%" e=t:option(DummyValue,"server_type",translate("Server Type")) e.width="15%" e=t:option(DummyValue,"server",translate("Server Address")) e.width="20%" e=t:option(DummyValue,"server_port",translate("Server Port")) e.width="10%" e=t:option(DummyValue,"encrypt_method",translate("Encrypt Method")) e.width="15%" e=t:option(DummyValue,"server",translate("Ping Latency")) e.template="shadowsocks/ping" e.width="10%" ------------- local apply = luci.http.formvalue("cbi.apply") if apply then os.execute("/etc/init.d/shadowsocks restart >/dev/null 2>&1 &") end -------------- return a <file_sep>include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-shadowsocks PKG_VERSION:=2.5.6 PKG_RELEASE:=2 PKG_MAINTAINER:=monokoo <<EMAIL>> PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME) #PKG_USE_MIPS16:=0 include $(INCLUDE_DIR)/package.mk define Package/$(PKG_NAME) SECTION:=luci CATEGORY:=LuCI SUBMENU:=3. Applications TITLE:=LuCI for shadowsocks(R) & gfwpress PKGARCH:=all DEPENDS:=+dnsmasq-full +ipset +ip-full +iptables-mod-tproxy +kmod-ipt-compat-xtables \ +kmod-ipt-tproxy +iptables-mod-nat-extra +iptables-mod-geoip \ +libustream-openssl +ca-certificates +curl +resolveip \ +haproxy +cdns +dns2socks +pcap-dnsproxy +pdnsd endef define Package/$(PKG_NAME)/description A luci app for shadowsocks(R) & gfwpress endef define Package/$(PKG_NAME)/preinst endef define Package/$(PKG_NAME)/postinst #!/bin/sh if [ -z "$${IPKG_INSTROOT}" ]; then if [ ! -f "/usr/sbin/ip" ]; then if [ -f "/usr/bin/ip" ]; then rm -f /usr/bin/ip fi if [ -f "/sbin/ip-full" ]; then ln -s /sbin/ip-full /usr/sbin/ip ln -s /sbin/ip-full /usr/bin/ip else ln -s /sbin/ip /usr/sbin/ip ln -s /sbin/ip /usr/bin/ip fi fi fi if [ -z "$${IPKG_INSTROOT}" ]; then if [ -f /etc/uci-defaults/luci-shadowsocks ]; then ( . /etc/uci-defaults/luci-shadowsocks ) && rm -f /etc/uci-defaults/luci-shadowsocks fi rm -rf /tmp/luci-indexcache fi if [ -z "$${IPKG_INSTROOT}" ]; then if [ -f "/usr/sbin/haproxy" ]; then haproxypid=$$(pidof haproxy) if [ -n "$$haproxypid" ]; then echo haproxy stopped... /etc/init.d/haproxy stop fi echo haproxy disabled... /etc/init.d/haproxy disable fi fi if [ -z "$${IPKG_INSTROOT}" ]; then if [ -f "/etc/init.d/chinadns" ]; then chinadnspid=$$(pidof chinadns) if [ -n "$$chinadnspid" ]; then echo chinadns stopped... /etc/init.d/chinadns stop fi echo chinadns init script disabled... /etc/init.d/chinadns disable fi if [ -f "/etc/init.d/dns-forwarder" ]; then dnsforwarderpid=$$(pidof dns-forwarder) if [ -n "$$dnsforwarderpid" ]; then echo dns-forwarder stopped... /etc/init.d/dns-forwarder stop fi echo dns-forwarder init script disabled... /etc/init.d/dns-forwarder disable fi fi exit 0 endef define Package/$(PKG_NAME)/prerm endef define Package/$(PKG_NAME)/postrm endef define Build/Prepare $(foreach po,$(wildcard ${CURDIR}/files/usr/lib/lua/luci/i18n/*.po), \ po2lmo $(po) $(PKG_BUILD_DIR)/$(patsubst %.po,%.lmo,$(notdir $(po)));) $(foreach pa,$(wildcard ${CURDIR}/files/usr/lib/luci/i18n/*.pa), \ lmotool ${CURDIR}/files/usr/lib/luci/i18n/$(patsubst %.pa,%.lmo,$(notdir $(pa))) $(pa) $(PKG_BUILD_DIR)/$(patsubst %.pa,%.lmo,$(notdir $(pa)));) endef define Build/Configure endef define Build/Compile endef define Package/$(PKG_NAME)/conffiles /etc/config/shadowsocks /etc/config/kcptun /etc/cdns.json /etc/dnsmasq.conf endef define Package/$(PKG_NAME)/install $(INSTALL_DIR) $(1)/ $(CP) -R ./files/etc $(1)/etc $(INSTALL_DIR) $(1)/ $(CP) -R ./files/usr $(1)/usr $(INSTALL_DIR) $(1)/etc/config $(INSTALL_CONF) ./files/config/shadowsocks $(1)/etc/config/ $(INSTALL_CONF) ./files/config/kcptun $(1)/etc/config/ $(INSTALL_DIR) $(1)/etc/config $(INSTALL_CONF) ./files/config/cdns.json $(1)/etc/ $(INSTALL_CONF) ./files/config/dnsmasq.conf $(1)/etc/ $(INSTALL_DIR) $(1)/usr/lib/lua/luci/i18n $(INSTALL_DATA) $(PKG_BUILD_DIR)/shadowsocks.*.lmo $(1)/usr/lib/lua/luci/i18n/ # $(INSTALL_DIR) $(1)/usr/bin # $(INSTALL_BIN) ./files/bin/kcpclient/client_linux_$(ARCH) $(1)/usr/bin/kcpclient # $(INSTALL_DIR) $(1)/usr/sbin # $(INSTALL_BIN) ./files/bin/$(ARCH) $(1)/usr/sbin/addroute endef $(eval $(call BuildPackage,$(PKG_NAME))) <file_sep>#!/bin/sh /etc/rc.common # # Copyright (C) 2015 OpenWrt-dist # Copyright (C) 2016 fw867 <<EMAIL>> # Copyright (C) 2016 <NAME> <<EMAIL>> # # This is free software, licensed under the GNU General Public License v3. # See /LICENSE for more information. # START=90 STOP=15 CONFIG=shadowsocks CONFIG_FILE=/var/etc/$CONFIG.json LOCK_FILE=/var/lock/$CONFIG.lock lb_FILE=/var/etc/haproxy.cfg LOG_FILE=/var/log/$CONFIG.log Route_FILE=/tmp/ssroute lanip=$(uci show network.lan.ipaddr|cut -d'=' -f 2|sed -e "s/'//g") config_n_get() { local ret=$(uci get $CONFIG.$1.$2 2>/dev/null) echo ${ret:=$3} } config_t_get() { local index=0 [ -n "$4" ] && index=$4 local ret=$(uci get $CONFIG.@$1[$index].$2 2>/dev/null) echo ${ret:=$3} } factor(){ if [ -z "$1" ] || [ -z "$2" ]; then echo "" else echo "$2 $1" fi } get_jump_mode(){ case "$1" in disable) echo "j" ;; *) echo "g" ;; esac } get_comp_mode(){ case "$1" in 0) echo "--nocomp" ;; 1) echo "" ;; esac } start_kcptun() { compmode=$(config_t_get kcp compon) echo "$(date): 运行kcpclient..." >> $LOG_FILE /usr/bin/kcpclient -l 127.0.0.1:11183 -r $(config_t_get kcp kcp_server):$(config_t_get kcp kcp_port) \ --key $(config_t_get kcp password) \ --crypt $(config_t_get kcp crypt) \ --mode $(config_t_get kcp mode) $(config_t_get kcp kcpconfig) \ --conn $(config_t_get kcp conn) \ --mtu $(config_t_get kcp mtu) \ --sndwnd $(config_t_get kcp sndwnd) \ --rcvwnd $(config_t_get kcp rcvwnd) \ $(get_comp_mode $compmode) \ >/dev/null 2>&1 & } GLOBAL_SERVER=$(config_t_get global global_server nil) get_plugin_config() { local plugin=$(config_get $1 plugin) local plugin_opts=$(config_get $1 plugin_opts) if [ -n "$plugin" -a -n "$plugin_opts" ]; then echo $plugin >>/var/run/ss-plugin echo " \"plugin\": \"$plugin\", \"plugin_opts\": \"$plugin_opts\"," fi } gen_config_file() { echo "$(date): =============================================================================================" >> $LOG_FILE echo "$(date): 开始运行Shadowsocks(Shell by fw867)" >> $LOG_FILE echo "$(date): =============================================================================================" >> $LOG_FILE echo "$(date): 载入模式:$PROXY_MODE" >> $LOG_FILE local SSTYPE config_get SSTYPE $1 server_type 0 config_get LOCAL_PORT $1 local_port 1080 let SOCKS_PORT=LOCAL_PORT+1 configprotocol=$(config_get $1 protocol) configobfs=$(config_get $1 obfs) kcpon=$(config_t_get kcp kcpon) if [ "$kcpon" = "1" ];then if [ $SSTYPE = "ss" ]; then echo "$(date): 生成KCP加速shadowsocks(R)配置文件[ss-kcp_11183]" >> $LOG_FILE ssbin="ss" cat <<-EOF >$CONFIG_FILE { "server": "127.0.0.1", "server_port": 11183, "local_address": "0.0.0.0",$(get_plugin_config $1) "local_port": $LOCAL_PORT, "password": "$(config_get $1 password)", "timeout": $(config_get $1 timeout), "method": "$(config_get $1 encrypt_method)", "fast_open": $(config_get $1 fast_open) } EOF elif [ $SSTYPE = "gfw" ]; then echo "$(date): 生成KCP加速shadowsocks(R)配置文件[gfw-kcp_11183]" >> $LOG_FILE ssbin="gfw" cat <<-EOF >$CONFIG_FILE { "server": "127.0.0.1", "server_port": 11183, "local_port": $LOCAL_PORT, "password": "$(config_get $1 password)", "timeout": $(config_get $1 timeout), "local_address": "0.0.0.0", "method": "$(config_get $1 encrypt_method)", "protocol": "$(config_get $1 protocol)", "protocol_param": "$(config_get $1 protocol_param)", "obfs": "$(config_get $1 obfs)", "obfs_param": "$(config_get $1 obfs_param)", "fast_open": $(config_get $1 fast_open) } EOF else echo "$(date): 生成KCP加速shadowsocks(R)配置文件[ssr-kcp_11183]" >> $LOG_FILE ssbin="ssr" cat <<-EOF >$CONFIG_FILE { "server": "127.0.0.1", "server_port": 11183, "local_address": "0.0.0.0", "local_port": $LOCAL_PORT, "password": "$(config_get $1 password)", "timeout": $(config_get $1 timeout), "method": "$(config_get $1 encrypt_method)", "protocol": "$(config_get $1 protocol)", "protocol_param": "$(config_get $1 protocol_param)", "obfs": "$(config_get $1 obfs)", "obfs_param": "$(config_get $1 obfs_param)", "fast_open": $(config_get $1 fast_open) } EOF fi start_kcptun else if [ $SSTYPE = "ss" ]; then echo "$(date): 生成shadowsocks(R)配置文件[ss]" >> $LOG_FILE ssbin="ss" cat <<-EOF >$CONFIG_FILE { "server": "$(config_get $1 server)", "server_port": $(config_get $1 server_port), "local_address": "0.0.0.0",$(get_plugin_config $1) "local_port": $LOCAL_PORT, "password": "$(config_get $1 password)", "timeout": $(config_get $1 timeout), "method": "$(config_get $1 encrypt_method)", "fast_open": $(config_get $1 fast_open) } EOF elif [ $SSTYPE = "gfw" ]; then echo "$(date): 生成shadowsocks(R)配置文件[gfw]" >> $LOG_FILE ssbin="gfw" cat <<-EOF >$CONFIG_FILE { "server": "$(config_get $1 server)", "server_port": $(config_get $1 server_port), "local_port": $LOCAL_PORT, "password": "$(config_get $1 password)", "timeout": $(config_get $1 timeout), "local_address": "0.0.0.0", "method": "$(config_get $1 encrypt_method)", "protocol": "$(config_get $1 protocol)", "protocol_param": "$(config_get $1 protocol_param)", "obfs": "$(config_get $1 obfs)", "obfs_param": "$(config_get $1 obfs_param)", "fast_open": $(config_get $1 fast_open) } EOF else echo "$(date): 生成shadowsocks(R)配置文件[ssr]" >> $LOG_FILE ssbin="ssr" cat <<-EOF >$CONFIG_FILE { "server": "$(config_get $1 server)", "server_port": $(config_get $1 server_port), "local_address": "0.0.0.0", "local_port": $LOCAL_PORT, "password": "$(config_get $1 password)", "timeout": $(config_get $1 timeout), "method": "$(config_get $1 encrypt_method)", "protocol": "$(config_get $1 protocol)", "protocol_param": "$(config_get $1 protocol_param)", "obfs": "$(config_get $1 obfs)", "obfs_param": "$(config_get $1 obfs_param)", "fast_open": $(config_get $1 fast_open) } EOF fi fi vpsip=$(config_get $1 server) s=`echo $vpsip|grep -E "([0-9]{1,3}[\.]){3}[0-9]{1,3}"` if [ -z $s ];then echo "$(date): 检测到你的服务器为域名,尝试解析...">> $LOG_FILE vpsip=`resolveip -4 -t 2 $vpsip|awk 'NR==1{print}'` fi echo "$(date): Shadowsocks服务器ip地址:$vpsip">> $LOG_FILE } load_config() { if [ $GLOBAL_SERVER == "nil" ]; then echo "$(date): Shadowsocks没有开启!" >> $LOG_FILE return 1 fi PROXY_MODE=$(config_t_get global proxy_mode gfwlist) DNS_MODE=$(config_t_get global dns_mode ssr-tunnel) DNS_FORWARD=$(config_t_get global dns_forward 8.8.8.8:53) config_load $CONFIG gen_config_file $GLOBAL_SERVER return 0 } start_redir() { mkdir -p /var/run /var/etc while [ -x "/usr/bin/$ssbin-redir" -a -f "$CONFIG_FILE" -a -z $(pidof $ssbin-redir) ]; do /usr/bin/$ssbin-redir \ -c $CONFIG_FILE \ -u \ -f /var/run/$ssbin-redir.pid & sleep 3 [ $ssbin = "gfw" ] && pidof gfw-redir > /var/run/$ssbin-redir.pid done echo "$(date): 运行 $ssbin-redir pid=[$(cat /var/run/$ssbin-redir.pid)]" >> $LOG_FILE } clean_log() { logsnum=$(cat $LOG_FILE|grep -c .) if [ $logsnum -gt 200 ];then rm -f $LOG_FILE >/dev/null 2>&1 & echo "$(date): 日志文件过长,清空处理!" >> $LOG_FILE fi } stop_cru() { sed -i '/ssruleupdate/d' /etc/crontabs/root >/dev/null 2>&1 & echo "$(date): 清理自动更新规则。" >> $LOG_FILE } set_cru() { autoupdate=$(config_t_get global auto_update) weekupdate=$(config_t_get global week_update) dayupdate=$(config_t_get global time_update) if [ "$autoupdate" = "1" ];then if [ "$weekupdate" = "7" ];then echo "0 $dayupdate * * * /usr/share/shadowsocks/ssruleupdate" >> /etc/crontabs/root echo "$(date): 设置自动更新规则在每天 $dayupdate 点。" >> $LOG_FILE else echo "0 $dayupdate * * $weekupdate /usr/share/shadowsocks/ssruleupdate" >> /etc/crontabs/root echo "$(date): 设置自动更新规则在星期 $weekupdate 的 $dayupdate 点。" >> $LOG_FILE fi else stop_cru fi } auto_stop() { autoon=$(config_t_get global auto_on) if [ "$autoon" = "0" ];then sed -i '/shadowsocks start/d' /etc/crontabs/root >/dev/null 2>&1 & echo "$(date): 清理定时自动开关设置。" >> $LOG_FILE fi } auto_start() { autoon=$(config_t_get global auto_on) sed -i '/shadowsocks/d' /etc/crontabs/root >/dev/null 2>&1 & if [ "$autoon" = "1" ];then timeon=$(config_t_get global time_on) timeoff=$(config_t_get global time_off) echo "0 $timeon * * * /etc/init.d/shadowsocks start" >> /etc/crontabs/root echo "0 $timeoff * * * /etc/init.d/shadowsocks stop" >> /etc/crontabs/root echo "$(date): 设置自动开启在每天 $timeon 点。" >> $LOG_FILE echo "$(date): 设置自动关闭在每天 $timeoff 点。" >> $LOG_FILE fi } start_dns() { case "$DNS_MODE" in $ssbin-tunnel) /usr/bin/$ssbin-tunnel \ -c $CONFIG_FILE \ -u \ -l 1053 \ -L $DNS_FORWARD \ -f /var/run/$ssbin-tunnel.pid echo "$(date): 运行DNS转发方案:$ssbin-tunnel [$?]1053->" >> $LOG_FILE ;; dns2socks) /usr/bin/$ssbin-local \ -c $CONFIG_FILE \ -l $SOCKS_PORT \ -f /var/run/$ssbin-local.pid echo "$(date): 运行DNS转发方案:dns2socks->$ssbin-local [$?]" >> $LOG_FILE /usr/bin/dns2socks \ 127.0.0.1:$SOCKS_PORT \ $DNS_FORWARD \ 127.0.0.1:1053 \ >/dev/null 2>&1 & echo "$(date): 运行DNS转发方案:dns2socks [$?]1053->${SOCKS_PORT}" >> $LOG_FILE ;; pcap-dnsproxy) /usr/sbin/Pcap_DNSProxy \ -c /etc/pcap-dnsproxy echo "$(date): 运行DNS转发方案:Pcap-dnsproxy [$?]" >> $LOG_FILE ;; dnscrypt-proxy) /etc/init.d/dnscrypt-proxy start echo "$(date): 运行DNS转发方案:dnscrypt-proxy [$?]" >> $LOG_FILE ;; chinadns) /etc/init.d/chinadns start echo "$(date): 运行DNS转发方案:ChinaDNS [$?]" >> $LOG_FILE ;; pdnsd) start_pdnsd echo "$(date): 运行DNS转发方案:Pdnsd [$?]" >> $LOG_FILE ;; cdns) /usr/bin/cdns \ -c /etc/cdns.json echo "$(date): 运行DNS转发方案:cdns...[$?]" >> $LOG_FILE ;; esac } add_dnsmasq() { local dns1 dns2 wirteconf dnsconf dnsport dns1=$(config_t_get global dns_1) dns2=$(config_t_get global dns_2) dnsport=$(config_t_get global dns_port) wirteconf=$(cat /etc/dnsmasq.conf | grep "server=$dns1") dnsconf=$(cat /etc/dnsmasq.conf | grep "server=$dns2") #[ $dnsport -ne 0 ] && /usr/sbin/addroute "$dnsport" "$dns1" "$Route_FILE" >> $LOG_FILE && addroute "$dnsport" "$dns2" "$Route_FILE" >> $LOG_FILE if [ -z "$wirteconf" ] || [ -z "$dnsconf" ];then cat > /etc/dnsmasq.conf <<EOF no-poll no-resolv server=$dns1 server=$dns2 cache-size=1024 local-ttl=60 neg-ttl=3600 max-cache-ttl=1200 EOF echo "$(date): 生成Dnsmasq配置文件。" >> $LOG_FILE fi if [ ! -f "/tmp/dnsmasq.d/gfwlist.conf" ];then ln -s /etc/dnsmasq.d/gfwlist.conf /tmp/dnsmasq.d/gfwlist.conf restdns=1 fi if [ ! -f "/tmp/dnsmasq.d/custom.conf" ];then cat /etc/gfwlist/gfwlist | awk '{print "server=/"$1"/127.0.0.1#1053\nipset=/"$1"/gfwlist"}' >> /tmp/dnsmasq.d/custom.conf restdns=1 fi #to port 1053 sed -i "s:\(^server=.*[^#]#\)[0-9]*$:\11053:" /tmp/dnsmasq.d/gfwlist.conf if [ ! -f "/tmp/dnsmasq.d/sscdn.conf" ];then cat /etc/dnsmasq.d/cdn.conf | sed "s/^/ipset=&\/./g" | sed "s/$/\/&cdn/g" | sort | awk '{if ($0!=line) print;line=$0}' >/tmp/dnsmasq.d/sscdn.conf restdns=1 fi userconf=$(grep -c "" /etc/dnsmasq.d/user.conf) if [ $userconf -gt 0 ];then ln -s /etc/dnsmasq.d/user.conf /tmp/dnsmasq.d/user.conf restdns=1 fi backhome=$(config_t_get global proxy_mode gfwlist) if [ "$backhome" == "returnhome" ];then rm -rf /tmp/dnsmasq.d/gfwlist.conf rm -rf /tmp/dnsmasq.d/custom.conf rm -rf /tmp/dnsmasq.d/sscdn.conf cat /etc/gfwlist/adblock | awk '{print "server=/"$1"/127.0.0.1#1053"}' >> /tmp/dnsmasq.d/home.conf restdns=1 echo "$(date): 生成回国模式Dnsmasq配置文件。[:1053]" >> $LOG_FILE fi #if [ $restdns -eq 1 ];then echo "$(date): 重启Dnsmasq。。。" >> $LOG_FILE /etc/init.d/dnsmasq restart 2>/dev/null #fi } start_pdnsd() { if ! test -f "/var/pdnsd/pdnsd.cache"; then mkdir -p `dirname /var/pdnsd/pdnsd.cache` dd if=/dev/zero of="/var/pdnsd/pdnsd.cache" bs=1 count=4 2> /dev/null chown -R nobody.nogroup /var/pdnsd fi /usr/sbin/pdnsd --daemon -p /var/run/pdnsd.pid } stop_dnsmasq() { if [ $GLOBAL_SERVER == "nil" ]; then rm -rf /tmp/dnsmasq.d/gfwlist.conf #add rm -rf /tmp/dnsmasq.d/gfwlist #add /etc/init.d/dnsmasq restart 2>/dev/null echo "$(date): Shadowsocks未开启!" >> $LOG_FILE fi } gen_basecfg(){ bport=$(config_t_get global haproxy_port) cat <<-EOF >$lb_FILE global log 127.0.0.1 local2 chroot /usr/bin pidfile /var/run/haproxy.pid maxconn 60000 stats socket /var/run/haproxy.sock user root daemon defaults mode tcp log global option tcplog option dontlognull option http-server-close #option forwardfor except 127.0.0.0/8 option redispatch retries 2 timeout http-request 10s timeout queue 1m timeout connect 10s timeout client 1m timeout server 1m timeout http-keep-alive 10s timeout check 10s maxconn 3000 listen shadowsocks bind 0.0.0.0:$bport mode tcp EOF } gen_lbsscfg(){ echo "$(date): 负载均衡服务启动中..." >> $LOG_FILE for i in $(seq 0 100) do bips=$(config_t_get balancing lbss '' $i) bports=$(config_t_get balancing lbort '' $i) bweight=$(config_t_get balancing lbweight '' $i) exports=$(config_t_get balancing export '' $i) bbackup=$(config_t_get balancing backup '' $i) if [ -z $bips ] || [ -z $bports ] ; then break fi if [ "$bbackup" = "1" ] ; then bbackup=" backup" echo "$(date): 添加故障转移备服务器$bips" >> $LOG_FILE else bbackup="" echo "$(date): 添加负载均衡主服务器$bips" >> $LOG_FILE fi si=`echo $bips|grep -E "([0-9]{1,3}[\.]){3}[0-9]{1,3}"` if [ -z $si ];then echo "$(date): 检测到你的服务器为域名:$bips ,尝试解析...">> $LOG_FILE bips=`resolveip -4 -t 2 $bips|awk 'NR==1{print}'` if [ -z $bips ];then echo "$(date): 解析失败,更换方案再次尝试!">> $LOG_FILE bips=`nslookup $bips localhost | sed '1,4d' | awk '{print $3}' | grep -v :|awk 'NR==1{print}'` fi echo "$(date): 解析到服务器IP为:$bips">> $LOG_FILE fi echo " server ss$i $bips:$bports weight $bweight check inter 1500 rise 1 fall 3 $bbackup" >> $lb_FILE [ $exports -gt 0 ] && /usr/sbin/addroute "$exports" "$bips" "$Route_FILE" >> $LOG_FILE done } gen_lbadmincfg(){ adminstatus=$(config_t_get global admin_enable) if [ "$adminstatus" = "1" ];then adminport=$(config_t_get global admin_port) adminuser=$(config_t_get global admin_user) adminpassword=$(config_t_get global admin_password) cat <<-EOF >>$lb_FILE listen status bind 0.0.0.0:$adminport mode http stats refresh 30s stats uri / stats auth $adminuser:$adminpassword #stats hide-version stats admin if TRUE EOF fi } remove_fwmark_rule(){ ip_rule_exist=`/usr/sbin/ip rule show | grep "fwmark 0x1/0x1 lookup 310" | grep -c 310` if [ ! -z "$ip_rule_exist" ];then until [ "$ip_rule_exist" = 0 ] do /usr/sbin/ip rule del fwmark 0x01/0x01 table 310 ip_rule_exist=`expr $ip_rule_exist - 1` done fi } start_sslb(){ lbenabled=$(config_t_get global balancing_enable 0) if [ "$lbenabled" = "1" ];then gen_basecfg gen_lbsscfg gen_lbadmincfg /usr/bin/haproxy -f $lb_FILE echo "$(date): 负载均衡服务运行成功!" >> $LOG_FILE else echo "$(date): 负载均衡服务未启用!" >> $LOG_FILE fi } get_action_chain() { case "$1" in disable) echo "RETURN" ;; global) echo "SHADOWSOCKS_GLO" ;; gfwlist) echo "SHADOWSOCKS_GFW" ;; chnroute) echo "SHADOWSOCKS_CHN" ;; gamemode) echo "SHADOWSOCKS_GAM" ;; returnhome) echo "SHADOWSOCKS_HOME" ;; esac } add_vps_port() { multiwan=$(config_t_get global wan_port 0) lbenabled=$(config_t_get global balancing_enable 0) [ $lbenabled = 0 ] && /usr/sbin/addroute "$multiwan" "$vpsip" "$Route_FILE" >> $LOG_FILE } stop_kcptun() { kcptun=$(uci get kcptun.@global[0].global_server) if [ $kcptun != "nil" ]; then uci set kcptun.@global[0].global_server="nil" uci commit /etc/init.d/kcptun stop fi } del_vps_port() { source $Route_FILE >/dev/null 2>&1 & rm -f $Route_FILE >/dev/null 2>&1 & } dns_hijack(){ dnshijack=$(config_t_get global dns_53) if [ "$dnshijack" = "1" ];then iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to $lanip 2>/dev/null echo "$(date): 添加接管局域网DNS解析规则..." >> $LOG_FILE fi } load_acl(){ local ipaddr local proxy_mode local ports config_get ipaddr $1 ipaddr config_get proxy_mode $1 proxy_mode config_get ports $1 ports if [ -n "$proxy_mode" ] && [ -n "$ipaddr" ] || [ -n "$ports" ]; then echo "$(date): 加载ACL规则:$ipaddr$ports模式为$proxy_mode" >> $LOG_FILE iptables -t nat -A SHADOWSOCKS $(factor $ipaddr "-s") $(factor $ports "-p tcp -m multiport --dport") -$(get_jump_mode $proxy_mode) $(get_action_chain $proxy_mode) [ "$proxy_mode" == "gamemode" ] && iptables -t mangle -A SHADOWSOCKS $(factor $ipaddr "-s") $(factor $ports "-p udp -m multiport --dport") -$(get_jump_mode $proxy_mode) $(get_action_chain $proxy_mode) fi } add_rule() { echo "$(date): 开始加载防火墙规则..." >> $LOG_FILE #创建所需的ipset IPSET_GFW="gfwlist" IPSET_CHN="chnroute" IPSET_CDN="cdn" IPSET_HOME="cnhome" ipset -! create $IPSET_GFW nethash && ipset flush $IPSET_GFW ipset -! create $IPSET_CDN iphash && ipset flush $IPSET_CDN #ipset -! create $IPSET_CHN nethash && ipset flush $IPSET_CHN #sed -e "s/^/add $IPSET_CHN &/g" /etc/gfwlist/chnroute | awk '{print $0} END{print "COMMIT"}' | ipset -R sed -e "s/^/add $IPSET_GFW &/g" /etc/gfwlist/custom | awk '{print $0} END{print "COMMIT"}' | ipset -R sed -e "s/^/add $IPSET_CDN &/g" /etc/gfwlist/whiteip | awk '{print $0} END{print "COMMIT"}' | ipset -R #生成代理规则 # 忽略特殊IP段 iptables -t nat -N SHADOWSOCKS iptables -t nat -I PREROUTING -p tcp -j SHADOWSOCKS iptables -t nat -A SHADOWSOCKS -d 0.0.0.0/8 -j RETURN iptables -t nat -A SHADOWSOCKS -d 10.0.0.0/8 -j RETURN iptables -t nat -A SHADOWSOCKS -d 127.0.0.0/8 -j RETURN iptables -t nat -A SHADOWSOCKS -d 169.254.0.0/16 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.0.0/12 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.0.0/16 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.58.3/4 -j RETURN iptables -t nat -A SHADOWSOCKS -d 240.0.0.0/4 -j RETURN [ ! -z "$vpsip" ] && iptables -t nat -A SHADOWSOCKS -d $vpsip -j RETURN # 生成对应CHAIN iptables -t nat -N SHADOWSOCKS_GLO iptables -t nat -A SHADOWSOCKS_GLO -p tcp -j REDIRECT --to $LOCAL_PORT iptables -t nat -N SHADOWSOCKS_GFW iptables -t nat -A SHADOWSOCKS_GFW -p tcp -m set --match-set $IPSET_GFW dst -m set ! --match-set $IPSET_CDN dst -j REDIRECT --to $LOCAL_PORT iptables -t nat -N SHADOWSOCKS_CHN iptables -t nat -A SHADOWSOCKS_CHN -p tcp -m set --match-set $IPSET_GFW dst -j REDIRECT --to $LOCAL_PORT iptables -t nat -A SHADOWSOCKS_CHN -p tcp -m set ! --match-set $IPSET_CDN dst -m geoip ! --destination-country CN -j REDIRECT --to $LOCAL_PORT iptables -t nat -N SHADOWSOCKS_HOME iptables -t nat -A SHADOWSOCKS_HOME -p tcp -m geoip --destination-country CN -j REDIRECT --to $LOCAL_PORT # Apply the rules for router self iptables -t nat -A OUTPUT -p tcp -m set --match-set $IPSET_GFW dst -j REDIRECT --to-ports $LOCAL_PORT # 游戏模式 iptables -t nat -N SHADOWSOCKS_GAM iptables -t nat -A SHADOWSOCKS_GAM -p tcp -m set ! --match-set $IPSET_CDN dst -m geoip ! --destination-country CN -j REDIRECT --to $LOCAL_PORT /usr/sbin/ip rule add fwmark 0x01/0x01 table 310 pref 789 /usr/sbin/ip route add local 0.0.0.0/0 dev lo table 310 iptables -t mangle -N SHADOWSOCKS iptables -t mangle -I PREROUTING -p udp -j SHADOWSOCKS iptables -t mangle -A SHADOWSOCKS -d 0.0.0.0/8 -j RETURN iptables -t mangle -A SHADOWSOCKS -d 10.0.0.0/8 -j RETURN iptables -t mangle -A SHADOWSOCKS -d 127.0.0.0/8 -j RETURN iptables -t mangle -A SHADOWSOCKS -d 169.254.0.0/16 -j RETURN iptables -t mangle -A SHADOWSOCKS -d 172.16.0.0/12 -j RETURN iptables -t mangle -A SHADOWSOCKS -d 192.168.0.0/16 -j RETURN iptables -t mangle -A SHADOWSOCKS -d 172.16.58.3/4 -j RETURN iptables -t mangle -A SHADOWSOCKS -d 240.0.0.0/4 -j RETURN [ -n "$vpsip" ] && iptables -t mangle -A SHADOWSOCKS -d $vpsip -j RETURN #iptables -t mangle -A SHADOWSOCKS -p udp -j RETURN iptables -t mangle -N SHADOWSOCKS_GAM iptables -t mangle -A SHADOWSOCKS_GAM -p udp -m set --match-set $IPSET_GFW dst -j TPROXY --on-port $LOCAL_PORT --tproxy-mark 0x01/0x01 iptables -t mangle -A SHADOWSOCKS_GAM -p udp -m set ! --match-set $IPSET_CDN dst -m geoip ! --destination-country CN -j TPROXY --on-port $LOCAL_PORT --tproxy-mark 0x01/0x01 # 加载ACLS config_foreach load_acl acl_rule # 加载默认代理模式 iptables -t nat -A SHADOWSOCKS -j $(get_action_chain $PROXY_MODE) [ "$PROXY_MODE" == "gamemode" ] && iptables -t mangle -A SHADOWSOCKS -j $(get_action_chain $PROXY_MODE) echo "$(date): 所有防火墙规则加载完成!" >> $LOG_FILE } clean_firewall_rule() { ib_nat_exist=`iptables -t nat -L PREROUTING | grep -c SHADOWSOCKS` if [ ! -z "$ib_nat_exist" ];then until [ "$ib_nat_exist" = 0 ] do iptables -t nat -D OUTPUT -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-ports 1080 2>/dev/null iptables -t nat -D PREROUTING -p tcp -j SHADOWSOCKS 2>/dev/null iptables -t nat -D PREROUTING -p udp --dport 53 -j DNAT --to $lanip 2>/dev/null iptables -t mangle -D PREROUTING -p udp -j SHADOWSOCKS 2>/dev/null ib_nat_exist=`expr $ib_nat_exist - 1` done fi } del_firewall_rule() { clean_firewall_rule iptables -t nat -F SHADOWSOCKS 2>/dev/null && iptables -t nat -X SHADOWSOCKS 2>/dev/null iptables -t nat -F SHADOWSOCKS_GLO 2>/dev/null && iptables -t nat -X SHADOWSOCKS_GLO 2>/dev/null iptables -t nat -F SHADOWSOCKS_GFW 2>/dev/null && iptables -t nat -X SHADOWSOCKS_GFW 2>/dev/null iptables -t nat -F SHADOWSOCKS_CHN 2>/dev/null && iptables -t nat -X SHADOWSOCKS_CHN 2>/dev/null iptables -t nat -F SHADOWSOCKS_GAM 2>/dev/null && iptables -t nat -X SHADOWSOCKS_GAM 2>/dev/null iptables -t nat -F SHADOWSOCKS_HOME 2>/dev/null && iptables -t nat -X SHADOWSOCKS_HOME 2>/dev/null iptables -t mangle -F SHADOWSOCKS 2>/dev/null && iptables -t mangle -X SHADOWSOCKS 2>/dev/null iptables -t mangle -F SHADOWSOCKS_GAM 2>/dev/null && iptables -t mangle -X SHADOWSOCKS_GAM 2>/dev/null remove_fwmark_rule 2>/dev/null /usr/sbin/ip route del local 0.0.0.0/0 table 310 2>/dev/null } kill_all() { kill -9 $(pidof $@) >/dev/null 2>&1 } delay_start() { (sleep $1 && start >/dev/null 2>&1) & } boot() { local delay=$(config_t_get global start_delay 0) if [ "$delay" -gt 0 ]; then delay_start $delay echo "$(date): 执行启动延时 $delay 秒在第一次启动!" >> $LOG_FILE else start fi return 0 } start() { ! load_config && return 1 iptables -t nat -C PREROUTING -p tcp -j SHADOWSOCKS 2>/dev/null && [ $? -eq 0 ] && exit 0; stop_kcptun add_vps_port start_sslb #防止并发开启服务 [ -f "$LOCK_FILE" ] && return 3 touch "$LOCK_FILE" start_redir start_dns add_dnsmasq add_rule dns_hijack auto_start set_cru rm -f "$LOCK_FILE" echo "$(date): ---------------------------------- Shadowsocks运行成功! ------------------------------------" >> $LOG_FILE echo "$(date): " >> $LOG_FILE echo "$(date): ---------------- Across the Great Wall, We can reach every corner in the world! ----------------" >> $LOG_FILE return 0 } stop() { while [ -f "$LOCK_FILE" ]; do sleep 5s done clean_log echo "$(date): =============================================================================================" >> $LOG_FILE echo "$(date): 开始关闭Shadowsocks(Shell by fw867)" >> $LOG_FILE echo "$(date): =============================================================================================" >> $LOG_FILE echo "$(date): 删除所有防火墙规则..." >> $LOG_FILE del_firewall_rule del_vps_port ipset -F cdn >/dev/null 2>&1 & ipset -X cdn >/dev/null 2>&1 & ipset -F gfwlist >/dev/null 2>&1 & ipset -X gfwlist >/dev/null 2>&1 & echo "$(date): 关闭Shadowsocks相关服务..." >> $LOG_FILE kill_all kcpclient cdns Pcap_DNSProxy ss-redir ss-tunnel ss-local ssr-redir ssr-tunnel ssr-local dns2socks pdnsd haproxy gfw-redir dnscrypt-proxy chinadns echo "$(date): 清理相关文件或缓存..." >> $LOG_FILE unset $ssbin rm -rf /tmp/dnsmasq.d/home.conf rm -rf /var/run/pdnsd.pid rm -rf /var/run/chinadns.pid rm -rf /var/pdnsd/pdnsd.cache rm -rf /var/run/dnscrypt-proxy.pid rm -rf /var/run/haproxy.pid if [ -f /var/run/ss-plugin ]; then kill -9 $(pidof $(cat /var/run/ss-plugin | sort | uniq)) >/dev/null 2>&1 rm -f /var/run/ss-plugin fi stop_dnsmasq stop_cru auto_stop echo "$(date): Shadowsocks已成功关闭!" >> $LOG_FILE } <file_sep>#!/bin/sh /etc/rc.common # # Copyright (C) 2015 OpenWrt-dist # Copyright (C) 2016 <NAME> <<EMAIL>> # Copyright (C) 2016 fw867 <<EMAIL>> # # This is free software, licensed under the GNU General Public License v3. # See /LICENSE for more information. # START=90 STOP=15 CONFIG=kcptun CONFIG_FILE=/var/etc/$CONFIG.json lanip=$(uci show network.lan.ipaddr|cut -d'=' -f 2|sed -e "s/'//g") #local vpsip uci_get_by_name() { local ret=$(uci get $CONFIG.$1.$2 2>/dev/null) echo ${ret:=$3} } uci_get_by_type() { local index=0 if [ -n $4 ]; then index=$4 fi local ret=$(uci get $CONFIG.@$1[$index].$2 2>/dev/null) echo ${ret:=$3} } gen_config_file() { cat <<-EOF >$CONFIG_FILE { "server": "$(uci_get_by_name $1 server)", "server_port": $(uci_get_by_name $1 server_port), "password": "$(uci_get_by_name $1 password)", "redir_port": $(uci_get_by_name $1 redir_port 1080), "socks5_port": $(uci_get_by_name $1 socks5_port 1081), "mode": "$(uci_get_by_name $1 mode fast)", "crypt": "$(uci_get_by_name $1 crypt aes)", "mtu": $(uci_get_by_name $1 mtu), "conn": $(uci_get_by_name $1 conn), "sndwnd": $(uci_get_by_name $1 sndwnd), "rcvwnd": $(uci_get_by_name $1 rcvwnd), "nocomp": $(uci_get_by_name $1 nocomp) } EOF vpsip=$(nslookup $(uci_get_by_name $1 server) 172.16.58.3 | sed '1,4d' | awk '{print $3}' | grep -v :|awk 'NR==1{print}') } load_config() { GLOBAL_SERVER=$(uci_get_by_type global global_server nil) if [ $GLOBAL_SERVER == "nil" ]; then return 1 fi PROXY_MODE=$(uci_get_by_type global proxy_mode gfwlist) DNS_MODE=$(uci_get_by_type global dns_mode ss-tunnel) DNS_FORWARD=$(uci_get_by_type global dns_forward 8.8.8.8:53) REDIR_PORT=$(uci_get_by_name $GLOBAL_SERVER redir_port 1080) SOCKS_PORT=$(uci_get_by_name $GLOBAL_SERVER socks5_port 1081) gen_config_file $GLOBAL_SERVER return 0 } start_redir() { mkdir -p /var/run /var/etc /usr/bin/kcpclientplus \ -c $CONFIG_FILE \ >/dev/null 2>&1 & } start_dns() { case "$DNS_MODE" in dns2socks) /usr/bin/dns2socks \ 127.0.0.1:$SOCKS_PORT \ $DNS_FORWARD \ 127.0.0.1:1053 \ >/dev/null 2>&1 & ;; pcap-dnsproxy) /usr/sbin/Pcap_DNSProxy \ -c /etc/pcap-dnsproxy ;; pdnsd) start_pdnsd ;; cdns) /usr/bin/cdns \ -c /etc/cdns.json ;; esac } add_dnsmasq() { dns1=$(uci_get_by_type global dns_1) dns2=$(uci_get_by_type global dns_2) wirteconf=$(cat /etc/dnsmasq.conf | grep "server=$dns1") dnsconf=$(cat /etc/dnsmasq.conf | grep "server=$dns2") if [ -z "$wirteconf" ] || [ -z "$dnsconf" ];then cat > /etc/dnsmasq.conf <<EOF no-poll no-resolv bogus-priv domain-needed server=$dns1 server=$dns2 cache-size=1024 local-ttl=60 neg-ttl=3600 max-cache-ttl=1200 EOF fi if [ ! -f "/tmp/dnsmasq.d/gfwlist.conf" ]; then ln -s /etc/dnsmasq.d/gfwlist.conf /tmp/dnsmasq.d/gfwlist.conf fi /etc/init.d/dnsmasq restart } stop_dnsmasq() { ssoff=$(uci_get_by_type global global_server nil) if [ $ssoff == "nil" ]; then rm /tmp/dnsmasq/gfwlist /etc/init.d/dnsmasq restart fi } add_vps_port() { multiwan=$(uci_get_by_type global wan_port 0) if [ $multiwan > 0 ];then np=$multiwan"p" gateway=$(ip route show|grep default|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|sed -n "$np") ip route add $vpsip via $gateway >/dev/null 2>&1 cat > /tmp/kcproute.sh <<EOF #!/bin/sh ip route del $vpsip via $gateway EOF chmod 775 /tmp/kcproute.sh fi } start_pdnsd() { if ! test -f "/var/pdnsd/pdnsd.cache"; then mkdir -p `dirname /var/pdnsd/pdnsd.cache` dd if=/dev/zero of="/var/pdnsd/pdnsd.cache" bs=1 count=4 2> /dev/null chown -R nobody.nogroup /var/pdnsd fi /usr/sbin/pdnsd --daemon -p /var/run/pdnsd.pid } stop_shadowsocks() { shadowsocks=$(uci get shadowsocks.@global[0].global_server) if [ $shadowsocks != "nil" ]; then uci set shadowsocks.@global[0].global_server='nil' uci commit /etc/init.d/shadowsocks stop fi } del_vps_port() { /tmp/kcproute.sh >/dev/null 2>&1 rm /tmp/kcproute.sh >/dev/null 2>&1 } dns_hijack(){ dnshijack=$(uci_get_by_type global dns_53 0) if [ $dnshijack = 1 ];then iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to $lanip 2>/dev/null fi } get_action_chain() { case "$1" in disable) echo "RETURN" ;; global) echo "KCPTUN_GLO" ;; gfwlist) echo "KCPTUN_GFW" add_dnsmasq ;; chnroute) echo "KCPTUN_CHN" ;; esac } add_rule() { #创建所需的ipset IPSET_GFW="gfwlist" IPSET_CDN="cdn" ipset -! create $IPSET_GFW nethash ipset -! create $IPSET_CDN iphash sed -e "s/^/add $IPSET_GFW &/g" /etc/gfwlist/custom | awk '{print $0} END{print "COMMIT"}' | ipset -R sed -e "s/^/add $IPSET_CDN &/g" /etc/gfwlist/whiteip | awk '{print $0} END{print "COMMIT"}' | ipset -R #生成代理规则 # 忽略特殊IP段 iptables -t nat -N KCPTUN iptables -t nat -I PREROUTING -j KCPTUN iptables -t nat -A KCPTUN -d 0.0.0.0/8 -j RETURN iptables -t nat -A KCPTUN -d 10.0.0.0/8 -j RETURN iptables -t nat -A KCPTUN -d 127.0.0.0/8 -j RETURN iptables -t nat -A KCPTUN -d 169.254.0.0/16 -j RETURN iptables -t nat -A KCPTUN -d 172.16.0.0/12 -j RETURN iptables -t nat -A KCPTUN -d 192.168.0.0/16 -j RETURN iptables -t nat -A KCPTUN -d 172.16.58.3/4 -j RETURN iptables -t nat -A KCPTUN -d 240.0.0.0/4 -j RETURN [ ! -z "$vpsip" ] && iptables -t nat -A KCPTUN -d $vpsip -j RETURN # Apply the rules for router self iptables -t nat -A OUTPUT -p tcp -m set --match-set $IPSET_GFW dst -j REDIRECT --to-ports $REDIR_PORT # 生成对应CHAIN iptables -t nat -N KCPTUN_GLO iptables -t nat -A KCPTUN_GLO -p tcp -j REDIRECT --to $REDIR_PORT iptables -t nat -N KCPTUN_GFW iptables -t nat -A KCPTUN_GFW -p tcp -m set --match-set $IPSET_GFW dst -m set ! --match-set $IPSET_CDN dst -j REDIRECT --to $REDIR_PORT iptables -t nat -N KCPTUN_CHN iptables -t nat -A KCPTUN_CHN -p tcp -m set --match-set $IPSET_GFW dst -j REDIRECT --to $REDIR_PORT iptables -t nat -A KCPTUN_CHN -p tcp -m set ! --match-set $IPSET_CDN dst -m geoip ! --destination-country CN -j REDIRECT --to $REDIR_PORT # 加载ACLS for i in $(seq 0 100) do local ip=$(uci_get_by_type acl_rule ipaddr '' $i) local mode=$(uci_get_by_type acl_rule proxy_mode '' $i) if [ -z $ip ] || [ -z $mode ]; then break fi iptables -t nat -A KCPTUN -s $ip -j $(get_action_chain $mode) iptables -t nat -A KCPTUN -s $ip -j RETURN done # 加载默认代理模式 iptables -t nat -A KCPTUN -j $(get_action_chain $PROXY_MODE) } del_rule() { iptables -t nat -D OUTPUT -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-ports 1080 2>/dev/null iptables -t nat -D PREROUTING -j KCPTUN 2>/dev/null iptables -t nat -F KCPTUN 2>/dev/null && iptables -t nat -X KCPTUN 2>/dev/null iptables -t nat -F KCPTUN_GLO 2>/dev/null && iptables -t nat -X KCPTUN_GLO 2>/dev/null iptables -t nat -F KCPTUN_GFW 2>/dev/null && iptables -t nat -X KCPTUN_GFW 2>/dev/null iptables -t nat -F KCPTUN_CHN 2>/dev/null && iptables -t nat -X KCPTUN_CHN 2>/dev/null iptables -t nat -F KCPTUN_GAM 2>/dev/null && iptables -t nat -X KCPTUN_GAM 2>/dev/null iptables -t nat -D PREROUTING -p udp --dport 53 -j DNAT --to $lanip 2>/dev/null } start() { ! load_config && exit 0 stop_shadowsocks add_vps_port start_redir start_dns add_rule dns_hijack } stop() { if [ $(iptables -t nat -L KCPTUN | grep RETURN | wc -l) -gt 0 ]; then del_rule del_vps_port ipset -F cdn >/dev/null 2>&1 & ipset -X cdn >/dev/null 2>&1 & ipset -F gfwlist >/dev/null 2>&1 & ipset -X gfwlist >/dev/null 2>&1 & killall -q -9 cdns killall -q -9 pcap-dnsproxy killall -q -9 kcpclientplus killall -q -9 dns2socks killall -q -9 pdnsd rm -rf /var/run/pdnsd.pid > /dev/null 2>&1 stop_dnsmasq fi } <file_sep>module("luci.controller.shadowsocks",package.seeall) function index() if not nixio.fs.access("/etc/config/shadowsocks")then return end entry({"admin","services","shadowsocks"},alias("admin","services","shadowsocks","settings"),_("ShadowSocks"),2).dependent=true entry({"admin","services","shadowsocks","settings"},cbi("shadowsocks/global"),_("Basic Settings"),1).dependent=true entry({"admin","services","shadowsocks","other"},cbi("shadowsocks/other"),_("Other Settings"),2).leaf=true entry({"admin","services","shadowsocks","balancing"},cbi("shadowsocks/balancing"),_("Load Balancing"),3).leaf=true if nixio.fs.access("/usr/sbin/dnscrypt-proxy") then entry({"admin", "services", "shadowsocks", "dnscrypt-proxy"},cbi("dnscrypt-proxy/dnscrypt-proxy"),_("DNSCrypt Settings"), 4).leaf = true entry({"admin", "services", "shadowsocks", "dnscrypt-servers"},cbi("dnscrypt-proxy/dnscrypt-servers"),_("DNSCrypt Servers"), 5).leaf = true entry({"admin", "services", "shadowsocks", "dnscrypt-servers"},arcombine(cbi("dnscrypt-proxy/dnscrypt-servers"), cbi("dnscrypt-proxy/dnscrypt-servers-config")),_("DNSCrypt Servers"), 5).leaf = true end entry({"admin","services","shadowsocks","kcp"},cbi("shadowsocks/kcp"),_("KCP Settings"),6).leaf=true entry({"admin","services","shadowsocks","serverconfig"},cbi("shadowsocks/serverconfig")).leaf=true entry({"admin","services","shadowsocks","status"},call("act_status")).leaf=true entry({"admin","services","shadowsocks","kcpstatus"},call("kcp_status")).leaf=true entry({"admin","services","shadowsocks","hrstatus"},call("hr_status")).leaf=true entry({"admin","services","shadowsocks","ping"},call("act_ping")).leaf=true entry({"admin","services","shadowsocks","china"},call("china_status")).leaf=true entry({"admin","services","shadowsocks","foreign"},call("foreign_status")).leaf=true entry({"admin","services","shadowsocks","logview"}, call("logread")).leaf=true end function act_status() local e={} e.ss_redir=luci.sys.call("ps | grep redir |grep -v grep >/dev/null")==0 luci.http.prepare_content("application/json") luci.http.write_json(e) end function hr_status() local e={} e.hrstatus=luci.sys.call("pidof %s >/dev/null"%"haproxy")==0 luci.http.prepare_content("application/json") luci.http.write_json(e) end function kcp_status() local e={} e.kcpstatus=luci.sys.call("pidof %s >/dev/null"%"kcpclient")==0 luci.http.prepare_content("application/json") luci.http.write_json(e) end function china_status() local e={} e.china=luci.sys.call("echo `curl -o /dev/null -s -m 10 --connect-timeout 2 -w %{http_code} 'http://www.baidu.com'`|grep 200 >/dev/null")==0 luci.http.prepare_content("application/json") luci.http.write_json(e) end function foreign_status() local e={} e.foreign=luci.sys.call("echo `curl -o /dev/null -s -m 30 --connect-timeout 30 -w %{http_code} 'https://www.google.com.tw'`|grep 200 >/dev/null")==0 luci.http.prepare_content("application/json") luci.http.write_json(e) end function act_ping() local e={} e.index=luci.http.formvalue("index") e.ping=luci.sys.exec("ping -c 1 -W 1 %q 2>&1|grep -o 'time=[0-9]*.[0-9]'|awk -F '=' '{print$2}'"%luci.http.formvalue("domain")) luci.http.prepare_content("application/json") luci.http.write_json(e) end -- called by XHR.get from logview.htm function logread(section) -- read application settings local lfile = "/var/log/" .. section .. ".log" local ldata = nixio.fs.readfile(lfile) if not ldata or #ldata == 0 then ldata="_nodata_" .. lfile end luci.http.write(ldata) end <file_sep>local e=require"nixio.fs" local sys=require"luci.sys" local m,s,o,t m=Map("shadowsocks") s=m:section(TypedSection,"global",translate("Other Settings")) s.anonymous=true s.addremove=false s:tab("_global_custdnsmasq", translate("Custom Dnsmasq")) local t="/etc/dnsmasq.d/user.conf" o=s:taboption("_global_custdnsmasq", TextValue,"userconf") o.description=translate("Setting a parameter error will cause dnsmasq fail to start.") .. "/etc/dnsmasq.d/user.conf" o.rows=8 o.wrap="off" o.cfgvalue=function(a,a) return e.readfile(t)or"" end o.write=function(o,o,a) e.writefile("/tmp/usr.conf",a:gsub("\r\n","\n")) if(luci.sys.call("cmp -s /tmp/usr.conf /etc/dnsmasq.d/user.conf")==1)then e.writefile(t,a:gsub("\r\n","\n")) luci.sys.call("rm -f /etc/dnsmasq.d/user.conf >/dev/null") end e.remove("/tmp/usr.conf") end s:tab("_global_whitelist", translate("Set Whitelist")) local t="/etc/dnsmasq.d/cdn.conf" o=s:taboption("_global_whitelist", TextValue,"whitelist") o.description=translate("Join the white list of domain names will not go agent.") .. "/etc/dnsmasq.d/cdn.conf" o.rows=9 o.wrap="off" o.cfgvalue=function(a,a) return e.readfile(t)or"" end o.write=function(o,o,a) e.writefile("/tmp/cdn",a:gsub("\r\n","\n")) if(luci.sys.call("cmp -s /tmp/cdn /etc/dnsmasq.d/cdn.conf")==1)then e.writefile(t,a:gsub("\r\n","\n")) luci.sys.call("rm -f /tmp/dnsmasq.d/sscdn.conf") end e.remove("/tmp/cdn") end local t="/etc/gfwlist/whiteip" o=s:taboption("_global_whitelist", TextValue,"wiplist") o.description=translate("These had been joined ip addresses will not use proxy.Please input the ip address or ip address segment,every line can input only one ip address.For example,192.168.127.12/24 or 192.168.127.12.") .. "/etc/gfwlist/whiteip" o.rows=9 o.wrap="off" o.cfgvalue=function(a,a) return e.readfile(t)or"" end o.write=function(o,o,a) e.writefile(t,a:gsub("\r\n","\n")) end s:tab("_global_blacklist", translate("Set Blacklist")) local t="/etc/gfwlist/gfwlist" o=s:taboption("_global_blacklist", TextValue,"weblist") o.description=translate("These had been joined websites will use proxy,but only GFW model.Please input the domain names of websites,every line can input only one website domain.For example,google.com.") .. "/etc/gfwlist/gfwlist" o.rows=9 o.wrap="off" o.cfgvalue=function(a,a) return e.readfile(t)or"" end o.write=function(o,o,a) e.writefile("/tmp/gfwlist",a:gsub("\r\n","\n")) if(luci.sys.call("cmp -s /tmp/gfwlist /etc/gfwlist/gfwlist")==1)then e.writefile(t,a:gsub("\r\n","\n")) luci.sys.call("rm -f /tmp/dnsmasq.d/custom.conf >/dev/null") end e.remove("/tmp/gfwlist") end local t="/etc/gfwlist/custom" o=s:taboption("_global_blacklist", TextValue,"iplist") o.description=translate("These had been joined ip addresses will use proxy,but only GFW model.Please input the ip address or ip address segment,every line can input only one ip address.For example,192.168.127.12/24 or 192.168.127.12.") .. "/etc/gfwlist/custom" o.rows=9 o.wrap="off" o.cfgvalue=function(a,a) return e.readfile(t)or"" end o.write=function(o,o,a) e.writefile(t,a:gsub("\r\n","\n")) end s=m:section(TypedSection,"acl_rule",translate("ShadowSocks ACLs"), translate("ACLs is a tools which used to designate specific IP proxy mode")) s.template="cbi/tblsection" s.sortable=true s.anonymous=true s.addremove=true o=s:option(Value,"aclremarks",translate("ACL Remarks")) o.width="30%" o.rmempty=true o=s:option(Value,"ipaddr",translate("IP Address")) o.width="20%" o.datatype="ip4addr" o.rmempty=false sys.net.arptable(function(e) o:value(e["IP address"]) end) o=s:option(ListValue,"proxy_mode",translate("Proxy Mode")) o.width="20%" o.default="disable" o.rmempty=false o:value("disable",translate("No Proxy")) o:value("global",translate("Global Proxy")) o:value("gfwlist",translate("GFW List")) o:value("chnroute",translate("China WhiteList")) o:value("gamemode",translate("Game Mode")) o=s:option(Value,"ports",translate("Dest Ports")) o.width="30%" o.placeholder="80,443" return m <file_sep>#!/bin/sh #file version1 #2017-08-25 # de6e087679c77be5e5e2f133ff28985d gfwlist #2017-08-25 # 3a21e12f36c7fa4eb76e8aaf90c6ae23 chnroute #2016-02-26 # 7c8569e96bc6893a146d5e093a3b0434 adblock #2017-08-25 # 9c961692089631b8d730b8d86594779a cdn LOGTIME=$(date "+%Y-%m-%d %H:%M:%S") CONFIG=shadowsocks uci_get_by_type() { local index=0 if [ -n $4 ]; then index=$4 fi local ret=$(uci get $CONFIG.@$1[$index].$2 2>/dev/null) echo ${ret:=$3} } echo ========================================================================================================== >> /var/log/shadowsocks.log echo $(date): 开始更新shadowsocks规则,请等待... > /var/log/shadowsocks.log wget --no-check-certificate -O - https://raw.githubusercontent.com/koolshare/koolshare.github.io/acelan_softcenter_ui/maintain_files/version1 > /tmp/version1 online_content=$(cat /tmp/version1) if [ -z "$online_content" ];then rm -rf /tmp/version1 echo $(date): 没有检测到在线版本欸(https://raw.githubusercontent.com/koolshare/koolshare.github.io/acelan_softcenter_ui/maintain_files/version1),可能是访问github有问题,去大陆白名单模式试试吧! >> /var/log/shadowsocks.log exit fi # detect ss version #3.6.0 #820bac3c8cec9cec8fcf9db4ba894a6e ss_basic_version_web1=`curl -s https://raw.githubusercontent.com/koolshare/koolshare.github.io/acelan_softcenter_ui/shadowsocks/version | sed -n 1p` while [ 1 ] read git_line1 # git_line1=$(cat /tmp/version1 | sed -n 1p) # version_gfwlist2=$(echo $git_line1 | sed 's/ /\n/g'| sed -n 1p) # md5sum_gfwlist2=$(echo $git_line1 | sed 's/ /\n/g'| tail -n 2 | head -n 1) version_gfwlist2=$(echo $git_line1 | awk -F' ' '{print $1}') md5sum_gfwlist2=$(echo $git_line1 | awk -F' ' '{print $3}') list_name=$(echo $git_line1 | awk -F' ' '{print $4}') [ "$git_line1"x = "x" || "$liset_name"x = "x" || "$md5sum_gfwlist2"x = "x" ] && break # version dectet version_gfwlist1=$(uci_get_by_type global ${list_name}_version) # update gfwlist if [ ! -z "$version_gfwlist2" ];then if [ "$version_gfwlist1" != "$version_gfwlist2" ];then echo $(date): 检测到新版本${list_name},开始更新... >> /var/log/shadowsocks.log echo $(date): 下载${list_name}到临时文件... >> /var/log/shadowsocks.log wget --no-check-certificate --timeout=15 -qO - https://raw.githubusercontent.com/koolshare/koolshare.github.io/acelan_softcenter_ui/maintain_files/${list_name}.conf > /tmp/${list_name}.conf md5sum_gfwlist1=$(md5sum /tmp/${list_name}.conf | sed 's/ /\n/g'| sed -n 1p) if [ "$md5sum_gfwlist1"x = "$md5sum_gfwlist2"x ];then echo $(date): ${list_name}.conf 下载完成,校验通过,将临时文件覆盖到原始${list_name}文件 >> /var/log/shadowsocks.log mv /tmp/${list_name}.conf /etc/dnsmasq.d/${list_name}.conf uci set shadowsocks.@global[0].${list_name}_version=$version_gfwlist2 rm -rf /tmp/dnsmasq.d/${list_name}.conf reboot="1" echo $(date): 你的${list_name}已经更新到最新了哦~$(cat /tmp/${list_name}.conf |grep -xom1 -e "^server=\/.*\/.*$") >> /var/log/shadowsocks.log else echo $(date): 下载完成,但是校验没有通过! >> /var/log/shadowsocks.log fi else echo $(date): 检测到${list_name}本地版本号和在线版本号相同,那还更新个毛啊! >> /var/log/shadowsocks.log fi else echo $(date): ${list_name}文件下载失败! >> /var/log/shadowsocks.log fi rm -rf /tmp/${list_name}.conf done < /tmp/version1 echo $(date): Shadowsocks更新进程运行完毕! >> /var/log/shadowsocks.log # write number uci commit shadowsocks # reboot ss if [ "$reboot" == "1" ];then echo $(date): 自动重启Shadowsocks,以应用新的规则文件!请稍后! >> /var/log/shadowsocks.log /etc/init.d/shadowsocks restart fi echo ========================================================================================================== >> /var/log/shadowsocks.log exit <file_sep>#!/bin/sh /etc/init.d/shadowsocks enable /etc/init.d/shadowsocks restart #/etc/init.d/shadowsocks restart
0a50e506b1e50ff3b9ec0df2af5c13cd5ac26438
[ "Markdown", "Makefile", "Shell", "Lua" ]
10
Markdown
peter-tank/luci-app-shadowsocks
9b0a76f993b6db249e5734ff4736758073d7b1e1
e5dbcf0877ff7cbbbd172a90191b166ddcc2faf0
refs/heads/master
<repo_name>WPPlugins/category-clouds-widget<file_sep>/readme.txt === Category Clouds Widget === Contributors: hugh.bassett-jones Tags: category, cloud, widget Requires at least: 2.8 Tested up to: 3.1 Stable tag: 2.0 Display selected categories as a tag cloud using a sidebar widget or shortcode. == Description == This plugin allows you to add a category cloud widget to your sidebar or use a shortcode to show a tag cloud. You can select the minimum- and maximum- font sizes, the minimum number of posts in a category to show and which catgories to include or exclude. See [www.bassett-jones.com/category-clouds-wordpress-widget/](http://www.bassett-jones.com/category-clouds-wordpress-widget/) for more details and options. = Features = * Use as a widget or shortcode * Configurable minimum and maximum font sizes * Configurable font units as pt, px, em or percentage * Order by number of posts in each category or alphabetically * Specify the minimum number of posts that a category has to have before it shows * Specify categories to include or exclude, or use them all = Usage = **Shortcode** Optionally enter [categoryclouds] in a page or post to show the category cloud. See the FAQ for examples. **Title** This is the usual widget title that will appear in your theme's sidebar. **Category font size** The minimum and maximum font sizes you want the cloud to show and their unit of measurement. For example, min: 50 max: 200 unit: % would show the smallest category at half your normal text size and the largest at double. **Order by** Choose between ordering by number of posts in a category, or alphabetically by category name. **Show by** Either the category with the most posts first or the category with the fewest posts first if using Order by: count, or A-Z or Z-A if Order by: name. **Minimum number of posts** Categories where the total number of posts is less than this number will not be shown. Set to 1 to hide empty categories. **Comma separated category IDs** If you only want to include specific categories, enter their IDs in a list. If you want to exclude a category, enter its ID as a negative number. Leave blank for all categories. * Example: 1,4,9,36,37,38 This will create a category cloud with only categories 1,4,9,36,37,38 in it. * Example: -1,-3 This will create a category cloud hiding categories 1 and 3. == Installation == Installing the plugin: 1. Download Category Clouds and unzip 2. Upload category_clouds folder to the /wp-content/plugins/ directory 3. Activate the plugin through the ‘Plugins’ menu in WordPress 4. Add the widget to your sidebar through the ‘Appearance > Widgets’ menu == Frequently Asked Questions == = How to I hide empty categories? = Set the minimum number of posts to 1. = How do I exclude a category? = Enter its ID as a negative in the 'Comma separated category IDs' field e.g. to exlude category 5, enter -5 = How do I specify options when using the shortcode? = Override the following defaults: * min_size: 50 * max_size: 150 * unit: % * orderby: name * order: ASC * min_count: 1 * cats_inc_exc Examples * [categoryclouds] * [categoryclouds order="DESC"] * [categoryclouds min_size="8" max_size="24" unit="px"] == Screenshots == 1. Example category cloud 2. Widget options == Changelog == = 2.0 = * Added [categoryclouds] shortcode = 1.0 = * Initial version of the plugin == Upgrade Notice == Version 2 supports [categoryclouds] shortcode. == Credits == This plugin is based on [Category Cloud widget](http://leekelleher.com/wordpress/plugins/category-cloud-widget/) by <NAME><file_sep>/category_clouds.php <?php /* Plugin Name: Category Clouds Widget Plugin URI: http://www.bassett-jones.com/category-clouds-wordpress-widget/ Description: Adds a sidebar widget or shortcode to display selected categories as a tag cloud. Author: <NAME> Author URI: http://hugh.bassett-jones.com Version: 2.0 Based on Category Cloud widget by <a href="http://leekelleher.com/wordpress/plugins/category-cloud-widget/">Lee Kelleher</a>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software */ class widget_categoryclouds extends WP_Widget { // declares the widget_categoryclouds class function widget_categoryclouds(){ $widget_ops = array('classname' => 'widget_categoryclouds', 'description' => __( "Displays selected categories as a tag cloud") ); $this->WP_Widget('catcloud', __('Category clouds'), $widget_ops); } // widget output function widget($args, $instance){ extract($args); echo $before_widget; // omit title if not specified if ($instance['title'] != '') echo $before_title . $instance['title'] . $after_title; // build query $query = 'show_option_all=1&style=cloud&show_count=1&use_desc_for_title=0&hierarchical=0'; $query .= '&order=' . $instance['order']; $query .= '&orderby=' . $instance['orderby']; if($instance['min_count'] > 0) { $query .= '&hide_empty=1';} // specified categories $inc_cats = array(); $exc_cats = array(); foreach (explode("," ,$instance['cats_inc_exc']) as $spec_cat) { if ($spec_cat < 0) { $exc_cats[] = abs($spec_cat); } elseif ( $spec_cat > 0) { $inc_cats[] = abs($spec_cat); } } if(count($inc_cats) > 0) { $query .= '&include=' . implode(",", $inc_cats); } if(count($exc_cats) > 0) { $query .= '&exclude=' . implode(",", $exc_cats); } // ensure minimum post count $cats = get_categories($query); foreach ($cats as $cat) { $catlink = get_category_link( $cat->cat_ID ); $catname = $cat->cat_name; $count = $cat->category_count; if ($count >= $instance['min_count']) { $counts{$catname} = $count; $catlinks{$catname} = $catlink; } } // font size calculation $spread = max($counts) - min($counts); if ($spread <= 0) { $spread = 1; }; $fontspread = $instance['max_size'] - $instance['min_size']; $fontstep = $spread / $fontspread; if ($fontspread <= 0) { $fontspread = 1; } echo '<p class="catcloud">'; foreach ($counts as $catname => $count) { $catlink = $catlinks{$catname}; echo "\n<a href=\"$catlink\" title=\"see $count posts in $catname\" style=\"font-size:". ($instance['min_size'] + ceil($count/$fontstep)).$instance['unit']."\">$catname</a> "; } echo '</p>' . $after_widget; } // Creates the edit form for the widget. function form($instance){ //Defaults $instance = wp_parse_args( (array) $instance, array('min_size' => 50, 'max_size' => 150, 'unit' => '%', 'orderby' => 'name', 'order' => 'ASC', 'min' => 1, 'exclude'=>'') ); ?> <p> <label><?php echo __('Title:') ?> <input class="widefat" id="<?php echo $this->get_field_id('title') ?>" name="<?php echo $this->get_field_name('title') ?>" type="text" value="<?php echo htmlspecialchars($instance['title']) ?>" /> </label> </p> <p> <?php echo __('Category font size:') ?><br> <label><?php echo __('Min: ') ?><input size="2" id="<?php echo $this->get_field_id('min_size') ?>" name="<?php echo $this->get_field_name('min_size') ?>" type="text" value="<?php echo htmlspecialchars($instance['min_size']) ?>"></label> <label><?php echo __('Max: ') ?><input size="2" id="<?php echo $this->get_field_id('max_size') ?>" name="<?php echo $this->get_field_name('max_size') ?>" type="text" value="<?php echo htmlspecialchars($instance['max_size']) ?>"></label> <label><?php echo __('Unit: ') ?> <select id="<?php echo $this->get_field_id( 'unit' ); ?>" name="<?php echo $this->get_field_name( 'unit' ); ?>"> <option <?php if ( 'pt' == $instance['unit'] ) echo 'selected="selected"'; ?>>pt</option> <option <?php if ( 'px' == $instance['unit'] ) echo 'selected="selected"'; ?>>px</option> <option <?php if ( 'em' == $instance['unit'] ) echo 'selected="selected"'; ?>>em</option> <option <?php if ( '%' == $instance['unit'] ) echo 'selected="selected"'; ?>>%</option> </select> </p> <p><?php echo __('Order by: '); ?> <label><input class="radio" type="radio" <?php if ( 'count' == $instance['orderby'] ) echo 'checked'; ?> name="<?php echo $this->get_field_name('orderby') ?>" id="<?php echo $this->get_field_id('orderby') ?>" value="count">&thinsp;<?php echo __('Count') ?></label> <label><input class="radio" type="radio" <?php if ( 'name' == $instance['orderby'] ) echo 'checked'; ?> name="<?php echo $this->get_field_name('orderby') ?>" id="<?php echo $this->get_field_id('orderby') ?>" value="name">&thinsp;<?php echo __('Name') ?></label> </p> <p><?php echo __('Show by: ') ?> <label><input class="radio" type="radio" <?php if ( 'ASC' == $instance['order'] ) echo 'checked'; ?> name="<?php echo $this->get_field_name('order') ?>" id="<?php echo $this->get_field_id('order') ?>" value="ASC">&thinsp;<?php echo __('Acending') ?></label> <label><input class="radio" type="radio" <?php if ( 'DESC' == $instance['order'] ) echo 'checked'; ?> name="<?php echo $this->get_field_name('order') ?>" id="<?php echo $this->get_field_id('order') ?>" value="DESC">&thinsp;<?php echo __('Decending') ?></label> </p> <p><label for="<?php echo $this->get_field_name('min_count') ?>"><?php echo __('Minimum number of posts:') ?><input size="3" id="<?php echo $this->get_field_id('min_count') ?>" name="<?php echo $this->get_field_name('min_count') ?>" type="text" value="<?php echo htmlspecialchars($instance['min_count']) ?>" /></label></p> <p> <label> <?php echo __('Comma separated category IDs (leave blank for all, to exclude a category use a negative categoryID numbers):') ?> <input class="widefat" id="<?php echo $this->get_field_id('cats_inc_exc') ?>" name="<?php echo $this->get_field_name('cats_inc_exc') ?>" type="text" value="<?php echo htmlspecialchars($instance['cats_inc_exc']) ?>" /> </label> </p> <?php } // Saves the widgets settings. function update($new_instance, $old_instance){ $instance = $old_instance; $instance['title'] = strip_tags(stripslashes($new_instance['title'])); $instance['min_size'] = ($new_instance['min_size'] != '') ? (int) $new_instance['min_size'] : 50; $instance['max_size'] = ($new_instance['max_size'] != '') ? (int) $new_instance['max_size'] : 150; $instance['unit'] = ($new_instance['unit'] != '') ? $new_instance['unit'] : '%'; $instance['orderby'] = ($new_instance['orderby'] != '') ? $new_instance['orderby'] : 'name'; $instance['order'] = ($new_instance['order'] != '') ? $new_instance['order'] : 'ASC'; $instance['min_count'] = ($new_instance['min_count'] != '') ? (int) $new_instance['min_count'] : 1; $instance['cats_inc_exc'] = strip_tags(stripslashes($new_instance['cats_inc_exc'])); return $instance; } } // end class // Register widget. Calls 'widgets_init' action after the widget has been registered. function widget_categoryclouds_init() { register_widget('widget_categoryclouds'); } add_action('widgets_init', 'widget_categoryclouds_init'); // shortcode for use outside widgets // TODO: refactor so it doesn't repeat the above function categoryclouds_func( $atts ) { // defaults extract( shortcode_atts( array( 'min_size' => 50, 'max_size' => 150, 'unit' => '%', 'orderby' => 'name', 'order' => 'ASC', 'min_count' => 1, 'cats_inc_exc' => '', ), $atts ) ); // holder $holder = ''; // build query $query = 'show_option_all=1&style=cloud&show_count=1&use_desc_for_title=0&hierarchical=0'; $query .= '&order=' . $order; $query .= '&orderby=' . $orderby; if($min_count > 0) { $query .= '&hide_empty=1';} // specified categories $inc_cats = array(); $exc_cats = array(); foreach (explode("," ,$cats_inc_exc) as $spec_cat) { if ($spec_cat < 0) { $exc_cats[] = abs($spec_cat); } elseif ( $spec_cat > 0) { $inc_cats[] = abs($spec_cat); } } if(count($inc_cats) > 0) { $query .= '&include=' . implode(",", $inc_cats); } if(count($exc_cats) > 0) { $query .= '&exclude=' . implode(",", $exc_cats); } // ensure minimum post count $cats = get_categories($query); foreach ($cats as $cat) { $catlink = get_category_link( $cat->cat_ID ); $catname = $cat->cat_name; $count = $cat->category_count; if ($count >= $min_count) { $counts{$catname} = $count; $catlinks{$catname} = $catlink; } } // font size calculation $spread = max($counts) - min($counts); if ($spread <= 0) { $spread = 1; }; $fontspread = $max_size - $min_size; $fontstep = $spread / $fontspread; if ($fontspread <= 0) { $fontspread = 1; } $holder .= '<p class="catcloud">'; foreach ($counts as $catname => $count) { $catlink = $catlinks{$catname}; $holder .= '<a href="' . $catlink .'" title="see ' . $count . ' posts in ' . $catname . '" style="font-size:' . ($min_size + ceil($count/$fontstep)) . $unit . '">' . $catname . '</a> '; } $holder .= '</p>'; return $holder; } add_shortcode( 'categoryclouds', 'categoryclouds_func' ); ?>
5b46197613219f419c00fafb21b7a544713181aa
[ "Text", "PHP" ]
2
Text
WPPlugins/category-clouds-widget
64cd763b36fb6ff10fe78b48dff09989fed18272
8dc8dc1bbef3ecd600924cb693f9f2111c10cdbe
refs/heads/master
<file_sep>'use strict'; var isPerfectSquare = require('./isPerfectSquare'); /** * Determines whether or not a number is a fibonacci number. (A number is a * fibonacci number if either `5 * n * n + 4` or `5 * n * n + 4` is a perfect * square.) * * @param {number} n The number to verify. * @return {boolean} Whether or not the number is a fibonacci number. */ module.exports = function isFib(n) { return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4); }; <file_sep>'use strict'; var R = require('ramda'); R.mixin(rootRequire('lib/ramda-contrib')); var isFib = rootRequire('lib/utils/math/isFib'); describe('utils.isFib', function() { var fibs, nonFibs; before(function() { fibs = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]; nonFibs = R.difference(R.range(0, R.last(fibs)), fibs); }); /** * Tests */ it('should return true if the number is a fibonacci number', function() { R.each(function(fib) { expect(isFib(fib)).to.be.true; }, fibs); }); it('should return false if the number is not a fibonacci number', function() { R.each(function(nonFib) { expect(isFib(nonFib)).to.be.false; }, nonFibs); }); }); <file_sep>'use strict'; var R = require('ramda'); R.mixin(require('../../ramda-contrib')); var square = require('./square'); // Determines whether or not a number is a perfect square. // // isPerfectSquare :: number -> boolean module.exports = function isPerfectSquare(number) { return R.compose(R.eq(number), square, Math.floor, Math.sqrt)(number); }; <file_sep>#!/usr/bin/env node /** * Author: <NAME> * * https://projecteuler.net/problem=2 */ 'use strict'; var r = require('ramda'); r.mixin(require('./lib/ramda-contrib')); var _ = require('lodash'); _.mixin(require('lodash-contrib')); var utils = require('./lib/utils'); var isEven = utils.math.isEven; var isFib = utils.math.isFib; /** * functionalEvenFibSum * * Returns the sum of all even fibonacci numbers whose value does not exceed `max`. * * Doesn't do memoization and suffers from performance problems related to * calling filter functions repeatedly (up to two calls per number). * * @param {number} The maximum value of any given fibonacci number. * @return {number} The sum of all fibonacci numbers whose value is between 0 and `max`. */ var functionalEvenFibSum = r.compose( r.sum, r.filter(r.andFn(isEven, isFib)), r.range(0), // `range`'s second argument is exclusive r.add(1) ); /** * stackFib * * Returns the nth fibonacci number. Memoizes previously computed results and * lazily calculates new fibonacci numbers. * * @param {number} n The nth fibonacci number * @return {number} The value of the nth fibonacci number */ var stackFib = (function() { var fibs = [0, 1]; return function stackFib(n) { var i; if (!fibs.hasOwnProperty(n)) { for (i = fibs.length; i <= n; i++) { fibs[i] = fibs[i - 1] + fibs[i - 2]; } } return fibs[n]; }; }()); /** * fibSum * * Returns the sum of all even fibonacci numbers whose value does not exceed `max`. * * @param {number} max The maximum value of any given fibonacci number. * @return {number} The sum of all fibonacci numbers whose value is between 0 and `max`. */ var evenFibSum = function fibSum(max) { var i; var current = 0; var total = 0; for (i = 2; current <= max; i += 1) { current = stackFib(i); if (current % 2 === 0) { total += current; } } return total; }; //console.log(functionalEvenFibSum(4000000)); console.log(evenFibSum(4000000)); <file_sep>'use strict'; var R = require('ramda'); R.mixin(rootRequire('lib/ramda-contrib')); var isEven = rootRequire('lib/utils').math.isOdd; describe('utils.isOdd', function() { /** * Setup */ var odds, evens; before(function() { odds = R.filter(function(num) { return num % 2 !== 0; }, R.range(2, 101)); evens = R.filter(function(num) { return num % 2 === 0; }, R.range(2, 101)); }); /** * Tests */ it('should return true for any odd number', function() { R.each(function(odd) { expect(isEven(odd)).to.be.true; }, odds); }); it('should return false for any even number', function() { R.each(function(even) { expect(isEven(even)).to.be.false; }, evens); }); }); <file_sep>'use strict'; var R = require('ramda'); R.mixin(rootRequire('lib/ramda-contrib')); var isPrime = rootRequire('lib/utils').math.isPrime; describe('utils.isPrime', function() { /** * Setup */ var primes, notPrimes; before(function() { primes = rootRequire('lib/data/1000primes.json'); notPrimes = R.difference(R.range(0, R.last(primes)), primes); }); /** * Tests */ // TODO: Profile against iterative version it('should return true for any prime number', function() { R.each(function(prime) { expect(isPrime(prime)).to.be.true; }, primes); }); it('should return false for any non-prime number', function() { R.each(function(notPrime) { expect(isPrime(notPrime)).to.be.false; }, notPrimes); }); }); <file_sep>'use strict'; var R = require('ramda'); R.mixin(rootRequire('lib/ramda-contrib')); var isNatural = rootRequire('lib/utils').math.isNatural; describe('utils.isNatural', function() { /** * Tests */ it('should return true for any natural number', function() { expect(isNatural(1)).to.be.true; expect(isNatural(3)).to.be.true; expect(isNatural(4)).to.be.true; expect(isNatural(100000)).to.be.true; }); it('should return false for any non-natural number', function() { expect(isNatural(0)).to.be.false; expect(isNatural(9.1)).to.be.false; expect(isNatural(16.4)).to.be.false; expect(isNatural(-1)).to.be.false; }); }); <file_sep>test: @./node_modules/.bin/mocha \ -u bdd \ -R list \ test/config \ test/unit/**/*.test.js .PHONY: test <file_sep>'use strict'; var R = require('ramda'); R.mixin(require('../../ramda-contrib')); // Determines whether a number is a multiple of another number. // // isMultipleOf :: number -> boolean module.exports = R.curry(function(x, y) { return y % x === 0; }); <file_sep>'use strict'; var path = require('path'); var chai = global.chai = require('chai'); global.expect = chai.expect; global.sinon = require('sinon'); // Chai plugins chai.use(require('sinon-chai')); global.rootRequire = function(dest) { return require(path.join('../..', dest)); }; <file_sep>%: %.hs ghc --make -O2 -rtsopts $< clean: rm -rf *.o *.hi *.~ .PHONY: clean <file_sep>'use strict'; var R = require('ramda'); R.mixin(rootRequire('lib/ramda-contrib')); var isMultipleOf = rootRequire('lib/utils').math.isMultipleOf; describe('utils.isMultipleOf', function() { /** * Tests */ it('should return true when the first argument is a multiple of the second', function() { expect(isMultipleOf(1)(1)).to.be.true; expect(isMultipleOf(2)(4)).to.be.true; expect(isMultipleOf(5)(25)).to.be.true; expect(isMultipleOf(4)(16)).to.be.true; }); it('should return false when the first argument is not a multiple of the second', function() { expect(isMultipleOf(0)(1)).to.be.false; expect(isMultipleOf(7)(4)).to.be.false; expect(isMultipleOf(2)(25)).to.be.false; expect(isMultipleOf(3)(16)).to.be.false; }); }); <file_sep>'use strict'; var R = require('ramda'); R.mixin(require('../../ramda-contrib')); var isEven = require('./isEven'); // Determines whether or not a number is odd. // // isOdd :: number -> boolean module.exports = R.compose(R.not, isEven); <file_sep>'use strict'; var R = require('ramda'); R.mixin(require('../../ramda-contrib')); var isNatural = require('./isNatural'); module.exports = function isPrime(n) { // If `n` is: // - Not a number // - Is not finite // - Not a natural number // - Is less than 2 (cannot be prime) if (isNaN(n) || !isFinite(n) || !isNatural(n) || n < 2) { return false; } var possibleFactors = R.filter( function(num) { return num === 2 || num === 3 || num === 5 || num === 7 || num % 2 !== 0; }, // Generate a range of numbers <= sqrt(n) R.range(2, Math.floor(Math.sqrt(n)) + 1) ); // TODO: Can I remove the null check here? return R.isEmpty(possibleFactors) || R.all(function(num) { return n % num !== 0; }, possibleFactors); };
87b6415c9bfee7281defa6441f889391ea471182
[ "JavaScript", "Makefile" ]
14
JavaScript
ndhoule/project-euler
2042b1a9bcd77cf1ca70df4b5e29b7b87dbe84c5
9a848cd895a22443780aad6d4ca8d39e237f8c6a
refs/heads/master
<repo_name>ThishenP/finger-counting<file_sep>/finger_counting.py import cv2 as cv import numpy as np from skimage import morphology import glob #convexity defect method for finger counting def hull_count(f): #finding contours contours, hierarchy = cv.findContours(f, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) f = cv.cvtColor(f, cv.COLOR_GRAY2RGB) #finding the contour taht surrounds the largest area max_idx = 0 max_area = 0 for i in range(len(contours)): contour_area = cv.contourArea(contours[i]) if contour_area > max_area: max_idx = i max_area = contour_area max_contour = contours[max_idx] #find convex hull hull = cv.convexHull(max_contour, returnPoints = False) defects = cv.convexityDefects(max_contour, hull) #find the largest defects corresponding to space between fingers large_defects = defects[defects[:,0,3]>4500] #return num fingers return len(large_defects)+1 #crop The image to a square def square_crop(f): #finds longest side and crops that side to the size of shorter side to create square image if f.shape[0] > f.shape[1]: cut_size = int((f.shape[0] - f.shape[1])/2) cropped = f[cut_size : cut_size + f.shape[1]] elif f.shape[0] > f.shape[1]: cut_size = int((f.shape[1] - f.shape[0])/2) cropped = f[:,cut_size : cut_size + f.shape[0]] else: return f return cropped def preprocess_image(f): #crops image cropped = square_crop(f) #scales image down to 128x128 small = cv.resize(cropped,[128,128], interpolation = cv.INTER_AREA) #converts image to hsv hsv_hand = cv.cvtColor(small, cv.COLOR_BGR2HSV) return hsv_hand #returns the most common value in a box at the center of the image def center_vals(f): center = [int(f.shape[0]/2)+20,int(f.shape[1]/2)] box = f[center[0]-5:center[0]+5,center[1]-5:center[1]+5] flat = box.flatten() values, counts = np.unique(flat, return_counts=True) idx = np.argmax(counts) return values[idx] #segments and thresholds the hand out of the hand image def colour_image_thresholding(f): saturation = f[:,:,1] #blur to reduce noise and benefit thresholding blur = cv.GaussianBlur(saturation,(5,5),0) #otsu thresholding _ ,binary_hand = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU) #if inverted if center_vals(binary_hand)==0: binary_hand = ~binary_hand return binary_hand #find final count def count_fingers(f): hand = preprocess_image(f) binary_hand = colour_image_thresholding(hand) count = hull_count(binary_hand) return count input_folder = "input" #read and display result for all images in input folder hands =[] for file in glob.glob(f"{input_folder}/*.jpg"): hand = cv.imread(file) print(f"image: {file[len(input_folder)+1:]}, num fingers: {count_fingers(hand)}") <file_sep>/experimentation/finger_count_testing.py import cv2 as cv import matplotlib.pyplot as plt import numpy as np import glob from skimage import morphology from scipy import ndimage from skimage import measure plt.rcParams["figure.figsize"] = (15, 10) def morph_count(f, save_process = False, plot_save_name = None): binary_hand = morphology.closing(f) binary_hand = morphology.opening(binary_hand) palm_small = morphology.binary_erosion(binary_hand,np.ones([10,10])) palm_large = morphology.binary_dilation(palm_small, np.ones([31,31])) fingers = np.bitwise_and(binary_hand,np.invert(palm_large)) _,num_fingers = measure.label(fingers,return_num=True) if save_process: fig, ax = plt.subplots(1, 4) ax[0].imshow(binary_hand,cmap='gray') ax[0].set_title("Binarised Image", fontsize=25) ax[1].imshow(palm_small,cmap='gray') ax[1].set_title("Erosion", fontsize=25) ax[2].imshow(palm_large,cmap='gray') ax[2].set_title("Dilation", fontsize=25) ax[3].imshow( fingers,cmap='gray') ax[3].set_title("Extracted Fingers", fontsize=25) fig.savefig(f"{plot_save_name}", dpi=fig.dpi) return num_fingers def hull_count(f, save_process = False,plot_save_name = None): contours, hierarchy = cv.findContours(f, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) f = cv.cvtColor(f, cv.COLOR_GRAY2RGB) max_idx = 0 max_area = 0 for i in range(len(contours)): contour_area = cv.contourArea(contours[i]) if contour_area > max_area: max_idx = i max_area = contour_area max_contour = contours[max_idx] hull = cv.convexHull(max_contour, returnPoints = False) hull_points = max_contour[hull][:,0] defects = cv.convexityDefects(max_contour, hull) large_defects = defects[defects[:,0,3]>4500] if save_process: fig, ax = plt.subplots(1, 4) ax[0].imshow(f) ax[0].set_title("Binarised Image", fontsize=25) f1 = f.copy() cv.drawContours(f1, [max_contour], -1, (255,0,0), 2) ax[1].imshow(f1) ax[1].set_title("Contours", fontsize=25) f2 = f.copy() cv.drawContours(f2, [hull_points], -1, (0,255,0), 2) ax[2].imshow(f2) ax[2].set_title("Convex Hull", fontsize=25) f3 = f.copy() for defect in large_defects: furthest = max_contour[defect[0][-2]][0] cv.circle(f3,furthest,4,[255,0,255],-1) cv.drawContours(f, [hull_points], -1, (0,255,0), 2) ax[3].imshow(f3) ax[3].set_title("Defects", fontsize=25) fig.savefig(f"{plot_save_name}", dpi=fig.dpi) return len(large_defects)+1 def square_crop(f): if f.shape[0] > f.shape[1]: cut_size = int((f.shape[0] - f.shape[1])/2) cropped = f[cut_size : cut_size + f.shape[1]] elif f.shape[0] > f.shape[1]: cut_size = int((f.shape[1] - f.shape[0])/2) cropped = f[:,cut_size : cut_size + f.shape[0]] else: return f return cropped def center_vals(f): center = [int(f.shape[0]/2)+20,int(f.shape[1]/2)] box = f[center[0]-5:center[0]+5,center[1]-5:center[1]+5] flat = box.flatten() values, counts = np.unique(flat, return_counts=True) idx = np.argmax(counts) return values[idx] def gray_image_thresholding(f): _,binary_hand = cv.threshold(f, 90, 255, cv.THRESH_BINARY) binary_hand = morphology.closing(binary_hand) binary_hand = morphology.opening(binary_hand) return binary_hand def preprocess_image(f): cropped = square_crop(f) small = cv.resize(cropped,[128,128], interpolation = cv.INTER_AREA) hsv_hand = cv.cvtColor(small, cv.COLOR_BGR2HSV) return hsv_hand def colour_image_thresholding(f): saturation = f[:,:,1] blur = cv.GaussianBlur(saturation,(5,5),0) _ ,binary_hand = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU) if center_vals(binary_hand)==0: binary_hand = ~binary_hand return binary_hand def count_fingers(f, count_func, save_process=False, plot_save_name = None): hand = preprocess_image(f) binary_hand = colour_image_thresholding(hand) count = count_func(binary_hand, save_process, plot_save_name) return count gray_hands = [] gray_labels = [] for file in sorted(glob.glob("gray_hands/*.png")): hand = cv.imread(file , cv.COLOR_BGR2GRAY) binary_hand = gray_image_thresholding(hand) gray_hands.append(binary_hand) gray_labels.append(int(file[len(file)-6])) colour_hands = [] colour_labels = [] for file in sorted(glob.glob("colour_hands/*.jpg")): hand = cv.imread(file) colour_hands.append(hand) colour_labels.append(int(file[len(file)-5])) n = len(gray_hands) right_morph = 0 right_hull = 0 for i in range(n): if morph_count(gray_hands[i]) == gray_labels[i]: right_morph += 1 if hull_count(gray_hands[i]) == gray_labels[i]: right_hull += 1 gray_morph_accuracy = (right_morph/n)*100 gray_hull_accuracy = (right_hull/n)*100 n = len(colour_hands) right_morph = 0 right_hull = 0 for i in range(n): if count_fingers(colour_hands[i], morph_count) == colour_labels[i]: right_morph += 1 if count_fingers(colour_hands[i], hull_count) == colour_labels[i]: right_hull += 1 colour_morph_accuracy = (right_morph/n)*100 colour_hull_accuracy = (right_hull/n)*100 print('percentage accuracies:') print('gray:') print('morph: ', gray_morph_accuracy) print('hull: ', gray_hull_accuracy) print('colour:') print('morph: ', colour_morph_accuracy) print('hull: ', colour_hull_accuracy) hsv = preprocess_image(colour_hands[14]) fig, ax = plt.subplots(1, 3) ax[0].imshow(hsv[:,:,0], cmap = 'hsv') ax[0].set_title("Hue", fontsize=20) ax[1].imshow(hsv[:,:,1], cmap='hsv') ax[1].set_title("Saturation", fontsize=20) ax[2].imshow(hsv[:,:,2], cmap='hsv') ax[2].set_title("Value", fontsize=20) fig.savefig("hsv.png", dpi=fig.dpi) hsv = preprocess_image(colour_hands[13]) seg = colour_image_thresholding(hsv) fig, ax = plt.subplots(1, 2) ax[0].imshow(colour_hands[13]) ax[0].set_title("Input", fontsize=20) ax[1].imshow(seg, cmap='gray') ax[1].set_title("Segmented and Binarised", fontsize=20) fig.savefig("segmentation.png", dpi=fig.dpi) count_fingers(colour_hands[10], hull_count,True, 'convexity_defects_example') count_fingers(colour_hands[3], morph_count,True, 'morph_example') count_fingers(colour_hands[13], hull_count,True, 'noise_conv') count_fingers(colour_hands[12], morph_count, True, "scale_morph_fail") count_fingers(colour_hands[13], morph_count, True, "noise_morph_fail") fig, ax = plt.subplots(1, 3) for i in range(3): num = count_fingers(colour_hands[8+i], hull_count) ax[i].imshow(colour_hands[8+i],cmap='hsv') ax[i].set_title(f"num fingers (output): {num}", fontsize=20) fig.savefig("io.png", dpi=fig.dpi)<file_sep>/README.md # finger-counting Image Processing project to find the number of fingers held up given a colour image of a hand. Experimentation was conducted using different methods and the convexity defect method performed best. ![convexity_defects_example](https://user-images.githubusercontent.com/60894050/129353563-b1d880ee-6149-497d-9f7a-ba41e565ce35.png)
7c6e5ae81eb5669a809dd25a0e88db4b68ccd793
[ "Markdown", "Python" ]
3
Python
ThishenP/finger-counting
333f2071cd2037eed6743556ddaa5c08e174f2b9
d81bae6eac204613dd6e531e2cdd0c6ae2be6d34
refs/heads/master
<file_sep>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name = 'my_index'), url(r'^user/create$', views.create, name = "my_create"), url(r'^travels$', views.login, name = 'my_home'), url(r'^travels/add$',views.addtravel,name = "my_travel"), url(r'^travels/submit/$',views.submittravel, name = "my_submit"), url(r'^travels/destination/(?P<id>\d+)$',views.destination, name = "my_destination"), url(r'^travels/join/(?P<id>\d+)$',views.join, name = "my_join"), url(r'^logout$',views.logout, name = "my_logout"), ] <file_sep>from django.shortcuts import render, redirect from .models import User,Trip from django.core.urlresolvers import reverse import re import bcrypt # Create your views here. def index(request): context = { "users" : User.objects.all() } return render(request, 'travel/index.html', context) request.session['loggedin']='' def create(request): if validate(request): User.objects.create(name=request.POST['name'],username=request.POST['username'],password=request.POST['password']) return redirect('/') else: print "invalid" return redirect('/') def login(request): if request.session['loggedin'] == True: user = User.objects.get(id=request.session['user']) context={ 'users' : user, 'trips' : Trip.objects.all().exclude(user=user), 'usertrips':Trip.objects.filter(user=user) } return render(request, 'travel/travels.html', context) else: if len(User.objects.filter(username=request.POST['username']))==0: return render(request,'travel/index.html') else: user = User.objects.get(username=request.POST['username']) password = request.POST['<PASSWORD>'] ##make Session for user if user.password == <PASSWORD>: request.session['user']=user.id context={ 'users' : user, 'trips' : Trip.objects.all(), 'usertrips':Trip.objects.filter(user=user) } request.session['loggedin']=True return render(request, 'travel/travels.html', context) def addtravel (request): # Trip.objects.create(destiantion=request.POST['destiantion'],description=request.POST['description'],password=req return render(request,'travel/addtravel.html') def submittravel(request): user=User.objects.get(id=request.session['user']) Trip.objects.create(destination=request.POST['destination'],description=request.POST['description'],travel_from=request.POST['travel_from'],travel_to=request.POST['travel_to'],user=user) return redirect(reverse("my_home")) def destination (request,id): trip=Trip.objects.get(id=id) ##person going to user= Trip.objects.filter(user=trip.user) creator=User.objects.get(id=trip.user.id) otheruser=Trip.objects.filter(user=trip.user).exclude(user=creator) context = { 'trip':trip, 'otherusers':otheruser } return render(request, 'travel/viewdestination.html', context) def join (request,id): user=User.objects.get(id=request.session['user']) trip =Trip.objects.get(id=id) Trip.objects.create(destination=trip.destination,description=trip.description,travel_from=trip.travel_from,travel_to=trip.travel_to,user=user) return redirect(reverse("my_home")) def logout (request): request.session.pop('user') request.session['loggedin'] = False return redirect('/') def validate(request): #check email if len(request.POST['username'])<3: print "too short" return False # check firstname elif len(request.POST['name'])<3: return False # Check password elif len(request.POST['password'])<8: return False elif request.POST['password'] == '': print ('Password cannot be blank', 'passwordError') return False elif len(request.POST['password']) < 8: print('Password must be greater than 8 characters', 'passwordError') return False # check confirmation elif len(request.POST['conpassword']) < 8: print('Please confirm password', 'confirmPasswordError') return False elif request.POST['password'] != request.POST['conpassword']: print('Passwords do not match', 'confirmPasswordError') return False return True <file_sep>from __future__ import unicode_literals from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=100) username= models.CharField(max_length=100) password = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now= True) class Trip(models.Model): destination = models.CharField(max_length=100) description = models.CharField(max_length=100) user = models.ForeignKey(User,default='') travel_from = models.CharField(max_length=100) travel_to = models.CharField(max_length=100)
c2d14a86a56cfcc687ecef6ede0c0e73f1b17b1b
[ "Python" ]
3
Python
myang0202/travel
b71eb1100739a6f3a68095612b33bf65161cf8f7
129f6f85b8fff761a2a26e7c11f8625d2236e836
refs/heads/master
<repo_name>relatai/categoryTest<file_sep>/src/pages/mapa-categoria2/mapa-categoria2.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import 'rxjs/add/operator/map'; import L from "leaflet"; import { DadosProvider } from '../../providers/dados/dados'; @IonicPage() @Component({ selector: 'page-mapa-categoria2', templateUrl: 'mapa-categoria2.html', providers:[ DadosProvider ] }) export class MapaCategoria2Page { public obj:any; private overlayMaps; public map; public report; constructor(public navCtrl: NavController, public navParams: NavParams, private dadosprovider: DadosProvider) { } ionViewDidLoad() { this.dadosprovider.getData2().subscribe(data => { this.obj = data; }, err => console.log("error is "+err), // error () => this.leafletMap() ); } leafletMap(){ this.map = L.map('mapId').setView([-22.545287, -44.069668], 4); for(let i in this.obj ){ //carregando variável categoria com o nomme das categoria let categoria = this.obj[i].name; //carregando a variável report com todos os reports dessa categoria this.report = this.obj[i].reports; //criando os markers dessa categoria e guardando em overlayMaps for(let r in this.report){ this.overlayMaps= {categoria : new L.marker(this.report[r].lat, this.report[r].long).bindPopup(this.report[r].desc)}; } } L.control.layers(this.overlayMaps).addTo(this.map); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 30, id: 'mapbox.satellite', accessToken: '<KEY>' }).addTo(this.map); } } <file_sep>/src/pages/mapa-categoria2/controller.ts import { Component } from '@angular/core'; import { DadosProvider } from '../../providers/dados/dados'; @Component({ providers:[ DadosProvider ] }) export class controllerPage { overlaysMakers:any; obj:any; }<file_sep>/src/pages/home/home.ts import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import 'rxjs/add/operator/map'; import L from "leaflet"; import { DadosProvider } from '../../providers/dados/dados'; @Component({ selector: 'page-home', templateUrl: 'home.html', providers:[ DadosProvider ] }) export class HomePage { propertyList = []; center: L.PointTuple; map; constructor(public navCtrl: NavController, private dadosprovider: DadosProvider) { } ionViewDidLoad() { this.dadosprovider.getData().subscribe(data => { //this.propertyList = data.properties; //const response = (data as any); this.propertyList = (data as any).properties; console.log(this.propertyList); }, err => console.log("error is "+err), // error () => this.leafletMap() ); } leafletMap(){ this.map = L.map('mapId').setView([42.35663, -71.1109], 16); console.log("property" + this.propertyList.length); for (let property of this.propertyList) { console.log("Lat: " + property.lat + " Lon: " + property.long + " Cidade: " + property.city); L.marker([property.lat, property.long]).addTo(this.map) .bindPopup("Cidade: "+ property.city+"<br>Estado: "+property.state+"<br><img src='https://imagepng.org/wp-content/uploads/2017/05/botao-facebook-like-icone-1022x1024.png' style='width: 30px; height: 30px;'><img src='https://cdn.iconscout.com/public/images/icon/premium/png-512/unlike-bad-poor-326b9a6a7188c486-512x512.png' style='width: 32px; height: 32px;'>") .openPopup().on("dblclick",this.onMapClick); } L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 30, id: 'mapbox.satellite', accessToken: '<KEY>' }).addTo(this.map); } onMapClick(e) { alert("Essas são suas coordenadas: " + e.latlng); } } <file_sep>/src/pages/mapa-categoria2/mapa-categoria2.module.ts import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { MapaCategoria2Page } from './mapa-categoria2'; @NgModule({ declarations: [ MapaCategoria2Page, ], imports: [ IonicPageModule.forChild(MapaCategoria2Page), ], }) export class MapaCategoria2PageModule {}
bc3cbb84103d6d93ac36327de8f701b099c4687f
[ "TypeScript" ]
4
TypeScript
relatai/categoryTest
592bd03366180dcd4d4bca984ed479b4c73b76a9
5683a9481b281f327843d3b8c48d43b49b051a63
refs/heads/master
<repo_name>jimmyherrerah/EX1fa973006a<file_sep>/routes/api/api.js var express = require('express'); var router = express.Router(); //aqui exportamos el archivo personas var personaRoutes = require('./recetas'); router.use('/recetas', personaRoutes); module.exports = router;
172bd6fce0966be234f334dbd24004af8c9690e3
[ "JavaScript" ]
1
JavaScript
jimmyherrerah/EX1fa973006a
b2e855a2dd7d93bd18b2e46a32f61792d6b819dd
66a3767e0693d3a871f8edeed915af6476dc91d9
refs/heads/master
<file_sep>package projection_test import ( "testing" "github.com/inklabs/rangedb/provider/inmemorystore" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/inklabs/goauth2" "github.com/inklabs/goauth2/projection" ) func TestEmailToUserID_Accept(t *testing.T) { // Given const ( userID = "881d60f1905d4457a611d596ae55d964" userID2 = "e0d0f5d7a72b432e8d553a0ac5c3d9b1" email = "<EMAIL>" ) t.Run("can get userID from email", func(t *testing.T) { // Given store := inmemorystore.New() goauth2.BindEvents(store) emailToUserID := projection.NewEmailToUserID() store.Subscribe(emailToUserID) require.NoError(t, store.Save(goauth2.UserWasOnBoarded{ UserID: userID, Username: email, }, nil)) // When actualUserID, err := emailToUserID.GetUserID(email) // Then require.NoError(t, err) assert.Equal(t, userID, actualUserID) }) t.Run("returns error for missing email", func(t *testing.T) { // Given store := inmemorystore.New() goauth2.BindEvents(store) emailToUserID := projection.NewEmailToUserID() store.Subscribe(emailToUserID) require.NoError(t, store.Save(goauth2.UserWasOnBoarded{ UserID: userID, Username: email, }, nil)) // When actualUserID, err := emailToUserID.GetUserID("<EMAIL>") // Then assert.Equal(t, "", actualUserID) assert.Equal(t, err, projection.UserNotFound) }) t.Run("can get userID from email with duplicate email", func(t *testing.T) { // Given store := inmemorystore.New() goauth2.BindEvents(store) emailToUserID := projection.NewEmailToUserID() store.Subscribe(emailToUserID) require.NoError(t, store.Save(goauth2.UserWasOnBoarded{ UserID: userID, Username: email, }, nil)) require.NoError(t, store.Save(goauth2.UserWasOnBoarded{ UserID: userID2, Username: email, }, nil)) // When actualUserID, err := emailToUserID.GetUserID(email) // Then require.NoError(t, err) assert.Equal(t, userID2, actualUserID) }) } <file_sep>package goauth2 import ( "context" "log" "github.com/inklabs/rangedb" "github.com/inklabs/rangedb/pkg/clock" "github.com/inklabs/rangedb/pkg/clock/provider/systemclock" "github.com/inklabs/rangedb/provider/inmemorystore" "github.com/inklabs/goauth2/provider/uuidtoken" ) //App is the OAuth2 CQRS application. type App struct { clock clock.Clock store rangedb.Store tokenGenerator TokenGenerator preCommandHandlers map[string][]PreCommandHandler commandHandlerFactories map[string]CommandHandlerFactory logger *log.Logger } // Option defines functional option parameters for App. type Option func(*App) //WithClock is a functional option to inject a clock. func WithClock(clock clock.Clock) Option { return func(app *App) { app.clock = clock } } //WithStore is a functional option to inject a RangeDB Event Store. func WithStore(store rangedb.Store) Option { return func(app *App) { app.store = store } } //WithTokenGenerator is a functional option to inject a token generator. func WithTokenGenerator(generator TokenGenerator) Option { return func(app *App) { app.tokenGenerator = generator } } // WithLogger is a functional option to inject a Logger. func WithLogger(logger *log.Logger) Option { return func(app *App) { app.logger = logger } } //New constructs an OAuth2 CQRS application. func New(options ...Option) *App { app := &App{ store: inmemorystore.New(), tokenGenerator: uuidtoken.NewGenerator(), clock: systemclock.New(), commandHandlerFactories: make(map[string]CommandHandlerFactory), preCommandHandlers: make(map[string][]PreCommandHandler), } for _, option := range options { option(app) } BindEvents(app.store) app.registerPreCommandHandler(newClientApplicationCommandAuthorization(app.store)) app.registerPreCommandHandler(newResourceOwnerCommandAuthorization(app.store, app.tokenGenerator, app.clock)) app.registerCommandHandler(ResourceOwnerCommandTypes(), app.newResourceOwnerAggregate) app.registerCommandHandler(ClientApplicationCommandTypes(), app.newClientApplicationAggregate) app.registerCommandHandler(AuthorizationCodeCommandTypes(), app.newAuthorizationCodeAggregate) app.registerCommandHandler(RefreshTokenCommandTypes(), app.newRefreshTokenAggregate) authorizationCodeRefreshTokens := NewAuthorizationCodeRefreshTokens() app.SubscribeAndReplay(authorizationCodeRefreshTokens) app.store.Subscribe( newRefreshTokenProcessManager(app.Dispatch, authorizationCodeRefreshTokens), newAuthorizationCodeProcessManager(app.Dispatch), ) return app } func (a *App) registerPreCommandHandler(handler PreCommandHandler) { for _, commandType := range handler.CommandTypes() { a.preCommandHandlers[commandType] = append(a.preCommandHandlers[commandType], handler) } } func (a *App) registerCommandHandler(commandTypes []string, factory CommandHandlerFactory) { for _, commandType := range commandTypes { a.commandHandlerFactories[commandType] = factory } } func (a *App) Dispatch(command Command) []rangedb.Event { var preHandlerEvents []rangedb.Event preCommandHandlers, ok := a.preCommandHandlers[command.CommandType()] if ok { for _, handler := range preCommandHandlers { shouldContinue := handler.Handle(command) preHandlerEvents = append(preHandlerEvents, a.savePendingEvents(handler)...) if !shouldContinue { return preHandlerEvents } } } newCommandHandler, ok := a.commandHandlerFactories[command.CommandType()] if !ok { a.logger.Printf("command handler not found") return preHandlerEvents } handler := newCommandHandler(command) handler.Handle(command) handlerEvents := a.savePendingEvents(handler) return append(preHandlerEvents, handlerEvents...) } func (a *App) newClientApplicationAggregate(command Command) CommandHandler { return newClientApplication(a.eventsByStream(rangedb.GetEventStream(command))) } func (a *App) newResourceOwnerAggregate(command Command) CommandHandler { return newResourceOwner( a.eventsByStream(rangedb.GetEventStream(command)), a.tokenGenerator, a.clock, ) } func (a *App) newAuthorizationCodeAggregate(command Command) CommandHandler { return newAuthorizationCode( a.eventsByStream(rangedb.GetEventStream(command)), a.tokenGenerator, a.clock, ) } func (a *App) newRefreshTokenAggregate(command Command) CommandHandler { return newRefreshToken( a.eventsByStream(rangedb.GetEventStream(command)), a.tokenGenerator, ) } func (a *App) eventsByStream(streamName string) <-chan *rangedb.Record { return a.store.EventsByStreamStartingWith(context.Background(), 0, streamName) } func (a *App) savePendingEvents(events PendingEvents) []rangedb.Event { pendingEvents := events.GetPendingEvents() for _, event := range pendingEvents { err := a.store.Save(event, nil) if err != nil { a.logger.Printf("unable to save event: %v", err) } } return pendingEvents } func (a *App) SubscribeAndReplay(subscribers ...rangedb.RecordSubscriber) { a.store.SubscribeStartingWith(context.Background(), 0, subscribers...) } func resourceOwnerStream(userID string) string { return rangedb.GetEventStream(UserWasOnBoarded{UserID: userID}) } func clientApplicationStream(clientID string) string { return rangedb.GetEventStream(ClientApplicationWasOnBoarded{ClientID: clientID}) } <file_sep>package templatemanager import ( "errors" "html/template" "io" "io/ioutil" "net/http" ) //TemplateManager holds templates that can be rendered via the html/template package type TemplateManager struct { templateLoader http.FileSystem } //New constructs a template manager. func New(templateLoader http.FileSystem) *TemplateManager { return &TemplateManager{templateLoader: templateLoader} } func (t *TemplateManager) RenderTemplate(w io.Writer, templateName string, data interface{}) error { templateReader, err := t.templateLoader.Open(templateName) if err != nil { return TemplateNotFound } bytes, err := ioutil.ReadAll(templateReader) if err != nil { return IOReadError } tmpl, err := template.New("").Funcs(FuncMap).Parse(string(bytes)) if err != nil { return MalformedTemplate } return tmpl.Execute(w, data) } var TemplateNotFound = errors.New("template not found") var IOReadError = errors.New("IO read error") var MalformedTemplate = errors.New("malformed template") <file_sep>package goauth2 import ( "time" "github.com/inklabs/rangedb" "github.com/inklabs/rangedb/pkg/clock" "github.com/inklabs/goauth2/pkg/securepass" ) const authorizationCodeLifetime = 10 * time.Minute func ResourceOwnerCommandTypes() []string { return []string{ GrantUserAdministratorRole{}.CommandType(), OnBoardUser{}.CommandType(), AuthorizeUserToOnBoardClientApplications{}.CommandType(), RequestAccessTokenViaImplicitGrant{}.CommandType(), RequestAccessTokenViaROPCGrant{}.CommandType(), RequestAuthorizationCodeViaAuthorizationCodeGrant{}.CommandType(), } } type resourceOwner struct { IsOnBoarded bool Username string PasswordHash string PendingEvents []rangedb.Event IsAdministrator bool IsAuthorizedToOnboardClientApplications bool tokenGenerator TokenGenerator clock clock.Clock } func newResourceOwner(records <-chan *rangedb.Record, tokenGenerator TokenGenerator, clock clock.Clock) *resourceOwner { aggregate := &resourceOwner{ tokenGenerator: tokenGenerator, clock: clock, } for record := range records { if event, ok := record.Data.(rangedb.Event); ok { aggregate.apply(event) } } return aggregate } func (a *resourceOwner) apply(event rangedb.Event) { switch e := event.(type) { case *UserWasOnBoarded: a.IsOnBoarded = true a.Username = e.Username a.PasswordHash = e.PasswordHash case *UserWasAuthorizedToOnBoardClientApplications: a.IsAuthorizedToOnboardClientApplications = true case *UserWasGrantedAdministratorRole: a.IsAdministrator = true } } func (a *resourceOwner) GetPendingEvents() []rangedb.Event { return a.PendingEvents } func (a *resourceOwner) Handle(command Command) { switch c := command.(type) { case OnBoardUser: a.OnBoardUser(c) case GrantUserAdministratorRole: a.GrantUserAdministratorRole(c) case AuthorizeUserToOnBoardClientApplications: a.AuthorizeUserToOnBoardClientApplications(c) case RequestAccessTokenViaImplicitGrant: a.RequestAccessTokenViaImplicitGrant(c) case RequestAccessTokenViaROPCGrant: a.RequestAccessTokenViaROPCGrant(c) case RequestAuthorizationCodeViaAuthorizationCodeGrant: a.RequestAuthorizationCodeViaAuthorizationCodeGrant(c) } } func (a *resourceOwner) OnBoardUser(c OnBoardUser) { if a.IsOnBoarded { a.emit(OnBoardUserWasRejectedDueToExistingUser{ UserID: c.UserID, }) return } if securepass.IsInsecure(c.Password) { a.emit(OnBoardUserWasRejectedDueToInsecurePassword{ UserID: c.UserID, }) return } a.emit(UserWasOnBoarded{ UserID: c.UserID, Username: c.Username, PasswordHash: GeneratePasswordHash(c.Password), }) } func (a *resourceOwner) GrantUserAdministratorRole(c GrantUserAdministratorRole) { if !a.IsOnBoarded { a.emit(GrantUserAdministratorRoleWasRejectedDueToMissingTargetUser{ UserID: c.UserID, GrantingUserID: c.GrantingUserID, }) return } a.emit(UserWasGrantedAdministratorRole{ UserID: c.UserID, GrantingUserID: c.GrantingUserID, }) } func (a *resourceOwner) AuthorizeUserToOnBoardClientApplications(c AuthorizeUserToOnBoardClientApplications) { if !a.IsOnBoarded { a.emit(AuthorizeUserToOnBoardClientApplicationsWasRejectedDueToMissingTargetUser{ UserID: c.UserID, AuthorizingUserID: c.AuthorizingUserID, }) return } a.emit(UserWasAuthorizedToOnBoardClientApplications{ UserID: c.UserID, AuthorizingUserID: c.AuthorizingUserID, }) } func (a *resourceOwner) RequestAccessTokenViaImplicitGrant(c RequestAccessTokenViaImplicitGrant) { if !a.IsOnBoarded { a.emit(RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidUser{ UserID: c.UserID, ClientID: c.ClientID, }) return } if !a.isPasswordValid(c.Password) { a.emit(RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidUserPassword{ UserID: c.UserID, ClientID: c.ClientID, }) return } a.emit(AccessTokenWasIssuedToUserViaImplicitGrant{ UserID: c.UserID, ClientID: c.ClientID, }) } func (a *resourceOwner) RequestAccessTokenViaROPCGrant(c RequestAccessTokenViaROPCGrant) { if !a.IsOnBoarded { a.emit(RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidUser{ UserID: c.UserID, ClientID: c.ClientID, }) return } if !a.isPasswordValid(c.Password) { a.emit(RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidUserPassword{ UserID: c.UserID, ClientID: c.ClientID, }) return } token := a.tokenGenerator.New() a.emit( AccessTokenWasIssuedToUserViaROPCGrant{ UserID: c.UserID, ClientID: c.ClientID, }, RefreshTokenWasIssuedToUserViaROPCGrant{ UserID: c.UserID, ClientID: c.ClientID, RefreshToken: token, Scope: c.Scope, }, ) } func (a *resourceOwner) RequestAuthorizationCodeViaAuthorizationCodeGrant(c RequestAuthorizationCodeViaAuthorizationCodeGrant) { if !a.IsOnBoarded { a.emit(RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidUser{ UserID: c.UserID, ClientID: c.ClientID, }) return } if !a.isPasswordValid(c.Password) { a.emit(RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidUserPassword{ UserID: c.UserID, ClientID: c.ClientID, }) return } authorizationCode := a.tokenGenerator.New() expiresAt := a.clock.Now().Add(authorizationCodeLifetime).Unix() a.emit(AuthorizationCodeWasIssuedToUserViaAuthorizationCodeGrant{ UserID: c.UserID, ClientID: c.ClientID, AuthorizationCode: authorizationCode, ExpiresAt: expiresAt, Scope: c.Scope, }) } func (a *resourceOwner) isPasswordValid(password string) bool { return VerifyPassword(a.PasswordHash, password) } func (a *resourceOwner) emit(events ...rangedb.Event) { for _, event := range events { a.apply(event) } a.PendingEvents = append(a.PendingEvents, events...) } <file_sep>// +build dev package web import ( "net/http" ) //TemplateAssets contains project assets. var TemplateAssets http.FileSystem = http.Dir("./templates") <file_sep>package goauth2 //go:generate go run gen/eventgenerator/main.go -package goauth2 -id RefreshToken -methodName CommandType -aggregateType refresh-token -inFile refresh_token_commands.go -outFile refresh_token_commands_gen.go type RequestAccessTokenViaRefreshTokenGrant struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` ClientSecret string `json:"clientSecret"` Scope string `json:"scope"` } type IssueRefreshTokenToUser struct { RefreshToken string `json:"refreshToken"` UserID string `json:"userID"` ClientID string `json:"clientID"` Scope string `json:"scope"` } type RevokeRefreshTokenFromUser struct { RefreshToken string `json:"refreshToken"` UserID string `json:"userID"` ClientID string `json:"clientID"` } <file_sep>package bdd import ( "context" "reflect" "testing" "github.com/inklabs/rangedb" "github.com/stretchr/testify/assert" ) type Command interface { rangedb.AggregateMessage CommandType() string } type CommandDispatcher func(command Command) type TestCase struct { store rangedb.Store dispatch CommandDispatcher previousEvents []rangedb.Event command Command } func New(store rangedb.Store, commandDispatcher CommandDispatcher) *TestCase { return &TestCase{ store: store, dispatch: commandDispatcher, } } func (c *TestCase) Given(events ...rangedb.Event) *TestCase { c.previousEvents = events return c } func (c *TestCase) When(command Command) *TestCase { c.command = command return c } func (c *TestCase) Then(expectedEvents ...rangedb.Event) func(*testing.T) { return func(t *testing.T) { t.Helper() streamPreviousEventCounts := make(map[string]uint64) for _, event := range c.previousEvents { streamPreviousEventCounts[rangedb.GetEventStream(event)]++ err := c.store.Save(event, nil) if err != nil { t.Errorf("unable to save event: %v", err) } } c.dispatch(c.command) streamExpectedEvents := make(map[string][]rangedb.Event) for _, event := range expectedEvents { stream := rangedb.GetEventStream(event) streamExpectedEvents[stream] = append(streamExpectedEvents[stream], event) } ctx := context.Background() for stream, expectedEventsInStream := range streamExpectedEvents { eventNumber := streamPreviousEventCounts[stream] actualEvents := eventChannelToSlice(c.store.EventsByStreamStartingWith(ctx, eventNumber, stream)) assert.Equal(t, expectedEventsInStream, actualEvents, "stream: %s", stream) } } } func (c *TestCase) ThenInspectEvents(f func(t *testing.T, events []rangedb.Event)) func(t *testing.T) { return func(t *testing.T) { t.Helper() streamPreviousEventCounts := make(map[string]uint64) for _, event := range c.previousEvents { streamPreviousEventCounts[rangedb.GetEventStream(event)]++ err := c.store.Save(event, nil) if err != nil { t.Errorf("unable to save event: %v", err) } } c.dispatch(c.command) ctx := context.Background() var events []rangedb.Event for _, stream := range getStreamsFromStore(c.store) { eventNumber := streamPreviousEventCounts[stream] actualEvents := eventChannelToSlice(c.store.EventsByStreamStartingWith(ctx, eventNumber, stream)) events = append(events, actualEvents...) } f(t, events) } } func getStreamsFromStore(store rangedb.Store) []string { streams := make(map[string]struct{}) for record := range store.EventsStartingWith(context.Background(), 0) { streams[rangedb.GetStream(record.AggregateType, record.AggregateID)] = struct{}{} } keys := make([]string, 0, len(streams)) for k := range streams { keys = append(keys, k) } return keys } func eventChannelToSlice(records <-chan *rangedb.Record) []rangedb.Event { var events []rangedb.Event for record := range records { events = append(events, eventAsValue(record.Data)) } return events } func eventAsValue(inputEvent interface{}) rangedb.Event { var event rangedb.Event reflectedValue := reflect.ValueOf(inputEvent) if reflectedValue.Kind() == reflect.Ptr { event = reflectedValue.Elem().Interface().(rangedb.Event) } else { event = inputEvent.(rangedb.Event) } return event } <file_sep>package goauth2 import ( "context" "github.com/inklabs/rangedb" ) type clientApplicationCommandAuthorization struct { store rangedb.Store pendingEvents []rangedb.Event } func newClientApplicationCommandAuthorization(store rangedb.Store) *clientApplicationCommandAuthorization { return &clientApplicationCommandAuthorization{ store: store, } } func (h *clientApplicationCommandAuthorization) GetPendingEvents() []rangedb.Event { return h.pendingEvents } func (h *clientApplicationCommandAuthorization) CommandTypes() []string { return []string{ RequestAccessTokenViaImplicitGrant{}.CommandType(), RequestAccessTokenViaROPCGrant{}.CommandType(), RequestAccessTokenViaRefreshTokenGrant{}.CommandType(), RequestAuthorizationCodeViaAuthorizationCodeGrant{}.CommandType(), RequestAccessTokenViaAuthorizationCodeGrant{}.CommandType(), } } func (h *clientApplicationCommandAuthorization) Handle(command Command) bool { switch c := command.(type) { case RequestAccessTokenViaImplicitGrant: return h.RequestAccessTokenViaImplicitGrant(c) case RequestAccessTokenViaROPCGrant: return h.RequestAccessTokenViaROPCGrant(c) case RequestAccessTokenViaRefreshTokenGrant: return h.RequestAccessTokenViaRefreshTokenGrant(c) case RequestAuthorizationCodeViaAuthorizationCodeGrant: return h.RequestAuthorizationCodeViaAuthorizationCodeGrant(c) case RequestAccessTokenViaAuthorizationCodeGrant: return h.RequestAccessTokenViaAuthorizationCodeGrant(c) } return true } func (h *clientApplicationCommandAuthorization) RequestAccessTokenViaImplicitGrant(c RequestAccessTokenViaImplicitGrant) bool { clientApplication := h.loadClientApplicationAggregate(c.ClientID) if !clientApplication.IsOnBoarded { h.emit(RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidClientApplicationID{ UserID: c.UserID, ClientID: c.ClientID, }) return false } if clientApplication.RedirectURI != c.RedirectURI { h.emit(RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidClientApplicationRedirectURI{ UserID: c.UserID, ClientID: c.ClientID, RedirectURI: c.RedirectURI, }) return false } return true } func (h *clientApplicationCommandAuthorization) RequestAccessTokenViaROPCGrant(c RequestAccessTokenViaROPCGrant) bool { clientApplication := h.loadClientApplicationAggregate(c.ClientID) if !clientApplication.IsOnBoarded { h.emit(RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidClientApplicationCredentials{ UserID: c.UserID, ClientID: c.ClientID, }) return false } if clientApplication.ClientSecret != c.ClientSecret { h.emit(RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidClientApplicationCredentials{ UserID: c.UserID, ClientID: c.ClientID, }) return false } return true } func (h *clientApplicationCommandAuthorization) RequestAccessTokenViaRefreshTokenGrant(c RequestAccessTokenViaRefreshTokenGrant) bool { clientApplication := h.loadClientApplicationAggregate(c.ClientID) if !clientApplication.IsOnBoarded { h.emit(RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToInvalidClientApplicationCredentials{ RefreshToken: c.RefreshToken, ClientID: c.ClientID, }) return false } if clientApplication.ClientSecret != c.ClientSecret { h.emit(RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToInvalidClientApplicationCredentials{ RefreshToken: c.RefreshToken, ClientID: c.ClientID, }) return false } return true } func (h *clientApplicationCommandAuthorization) RequestAuthorizationCodeViaAuthorizationCodeGrant(c RequestAuthorizationCodeViaAuthorizationCodeGrant) bool { clientApplication := h.loadClientApplicationAggregate(c.ClientID) if !clientApplication.IsOnBoarded { h.emit(RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationID{ UserID: c.UserID, ClientID: c.ClientID, }) return false } if clientApplication.RedirectURI != c.RedirectURI { h.emit(RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationRedirectURI{ UserID: c.UserID, ClientID: c.ClientID, RedirectURI: c.RedirectURI, }) return false } return true } func (h *clientApplicationCommandAuthorization) RequestAccessTokenViaAuthorizationCodeGrant(c RequestAccessTokenViaAuthorizationCodeGrant) bool { clientApplication := h.loadClientApplicationAggregate(c.ClientID) if !clientApplication.IsOnBoarded { h.emit(RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationID{ AuthorizationCode: c.AuthorizationCode, ClientID: c.ClientID, }) return false } if clientApplication.ClientSecret != c.ClientSecret { h.emit(RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationSecret{ AuthorizationCode: c.AuthorizationCode, ClientID: c.ClientID, }) return false } if clientApplication.RedirectURI != c.RedirectURI { h.emit(RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationRedirectURI{ AuthorizationCode: c.AuthorizationCode, ClientID: c.ClientID, RedirectURI: c.RedirectURI, }) return false } return true } func (h *clientApplicationCommandAuthorization) loadClientApplicationAggregate(clientID string) *clientApplication { ctx := context.Background() return newClientApplication(h.store.EventsByStreamStartingWith(ctx, 0, clientApplicationStream(clientID))) } func (h *clientApplicationCommandAuthorization) emit(events ...rangedb.Event) { h.pendingEvents = append(h.pendingEvents, events...) } <file_sep>package goauth2 import ( "github.com/inklabs/rangedb" ) func RefreshTokenCommandTypes() []string { return []string{ RequestAccessTokenViaRefreshTokenGrant{}.CommandType(), IssueRefreshTokenToUser{}.CommandType(), RevokeRefreshTokenFromUser{}.CommandType(), } } type refreshToken struct { tokenGenerator TokenGenerator Token string Scope string PendingEvents []rangedb.Event Username string IsLoaded bool HasBeenPreviouslyUsed bool HasBeenRevoked bool IsForUser bool UserID string IsForClientApplication bool ClientID string } func newRefreshToken(records <-chan *rangedb.Record, generator TokenGenerator) *refreshToken { aggregate := &refreshToken{ tokenGenerator: generator, } for record := range records { if event, ok := record.Data.(rangedb.Event); ok { aggregate.apply(event) } } return aggregate } func (a *refreshToken) apply(event rangedb.Event) { switch e := event.(type) { case *RefreshTokenWasIssuedToUser: a.IsLoaded = true a.IsForUser = true a.UserID = e.UserID a.Scope = e.Scope case *RefreshTokenWasIssuedToClientApplication: a.IsLoaded = true a.IsForClientApplication = true a.ClientID = e.ClientID case *RefreshTokenWasIssuedToUserViaRefreshTokenGrant: a.HasBeenPreviouslyUsed = true case *RefreshTokenWasRevokedFromUser: a.HasBeenRevoked = true } } func (a *refreshToken) Handle(command Command) { switch c := command.(type) { case RequestAccessTokenViaRefreshTokenGrant: a.RequestAccessTokenViaRefreshTokenGrant(c) case IssueRefreshTokenToUser: a.IssueRefreshTokenToUser(c) case RevokeRefreshTokenFromUser: a.RevokeRefreshTokenFromUser(c) } } func (a *refreshToken) GetPendingEvents() []rangedb.Event { return a.PendingEvents } func (a *refreshToken) emit(events ...rangedb.Event) { for _, event := range events { a.apply(event) } a.PendingEvents = append(a.PendingEvents, events...) } func (a *refreshToken) RequestAccessTokenViaRefreshTokenGrant(c RequestAccessTokenViaRefreshTokenGrant) { if !a.IsLoaded { a.emit(RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToInvalidRefreshToken{ RefreshToken: c.RefreshToken, ClientID: c.ClientID, }) return } if a.HasBeenPreviouslyUsed { a.emit(RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToPreviouslyUsedRefreshToken{ RefreshToken: c.RefreshToken, }) return } if a.HasBeenRevoked { a.emit(RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToRevokedRefreshToken{ RefreshToken: c.RefreshToken, ClientID: c.ClientID, }) return } if c.Scope != "" && a.Scope != c.Scope { a.emit(RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToInvalidScope{ RefreshToken: c.RefreshToken, ClientID: c.ClientID, Scope: a.Scope, RequestedScope: c.Scope, }) return } nextRefreshToken := a.tokenGenerator.New() if a.IsForUser { a.emit( AccessTokenWasIssuedToUserViaRefreshTokenGrant{ RefreshToken: c.RefreshToken, UserID: a.UserID, ClientID: c.ClientID, }, RefreshTokenWasIssuedToUserViaRefreshTokenGrant{ RefreshToken: c.RefreshToken, UserID: a.UserID, ClientID: c.ClientID, NextRefreshToken: nextRefreshToken, Scope: a.Scope, }, ) } else if a.IsForClientApplication { a.emit( AccessTokenWasIssuedToClientApplicationViaRefreshTokenGrant{ RefreshToken: c.RefreshToken, ClientID: c.ClientID, }, RefreshTokenWasIssuedToClientApplicationViaRefreshTokenGrant{ RefreshToken: c.RefreshToken, ClientID: a.ClientID, NextRefreshToken: nextRefreshToken, }, ) } } func (a *refreshToken) IssueRefreshTokenToUser(c IssueRefreshTokenToUser) { a.emit(RefreshTokenWasIssuedToUser{ RefreshToken: c.RefreshToken, UserID: c.UserID, ClientID: c.ClientID, Scope: c.Scope, }) } func (a *refreshToken) RevokeRefreshTokenFromUser(c RevokeRefreshTokenFromUser) { a.emit(RefreshTokenWasRevokedFromUser{ RefreshToken: c.RefreshToken, ClientID: c.ClientID, UserID: c.UserID, }) } <file_sep>package templatemanager_test import ( "bytes" "fmt" "net/http" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/inklabs/goauth2/web/pkg/templatemanager" ) var TemplateAssets = http.Dir("./testdata") func TestTemplateManager_RenderTemplate(t *testing.T) { t.Run("succeeds", func(t *testing.T) { // Given var buf bytes.Buffer manager := templatemanager.New(TemplateAssets) // When err := manager.RenderTemplate(&buf, "hello.html", struct { Name string }{ Name: "World", }) // Then require.NoError(t, err) assert.Equal(t, "Hello, World!\n", buf.String()) }) t.Run("fails with template not found", func(t *testing.T) { // Given var buf bytes.Buffer manager := templatemanager.New(TemplateAssets) // When err := manager.RenderTemplate(&buf, "not-found.html", nil) // Then assert.Equal(t, templatemanager.TemplateNotFound, err) }) t.Run("fails with io read error", func(t *testing.T) { // Given var buf bytes.Buffer manager := templatemanager.New(fileSystemWithFailingFileReader{}) // When err := manager.RenderTemplate(&buf, "hello.html", struct { Name string }{ Name: "World", }) // Then assert.Equal(t, templatemanager.IOReadError, err) }) t.Run("fails with invalid template", func(t *testing.T) { // Given var buf bytes.Buffer manager := templatemanager.New(TemplateAssets) // When err := manager.RenderTemplate(&buf, "invalid-hello.html", nil) // Then assert.Equal(t, templatemanager.MalformedTemplate, err) }) } type fileSystemWithFailingFileReader struct{} func (f fileSystemWithFailingFileReader) Open(_ string) (http.File, error) { return failReader{}, nil } type failReader struct{} func (w failReader) Close() error { return fmt.Errorf("failReader:Close") } func (w failReader) Seek(_ int64, _ int) (int64, error) { return 0, fmt.Errorf("failReader:Seek") } func (w failReader) Readdir(_ int) ([]os.FileInfo, error) { return nil, fmt.Errorf("failReader:Readdir") } func (w failReader) Stat() (os.FileInfo, error) { return nil, fmt.Errorf("failReader:Stat") } func (w failReader) Read(_ []byte) (n int, err error) { return 0, fmt.Errorf("failReader:Read") // return 0, io.ErrShortBuffer } <file_sep>package projection_test import ( "testing" "time" "github.com/inklabs/rangedb/pkg/clock/provider/seededclock" "github.com/inklabs/rangedb/provider/inmemorystore" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/inklabs/goauth2" "github.com/inklabs/goauth2/projection" ) func TestClientApplications_Accept(t *testing.T) { // Given const ( clientID = "f9236197e7f24ef994cbe2e06e026f24" clientSecret = "5970aca5e64d4f5e9e7842db8796619f" userID = "<KEY>" redirectURI = "http://example.com/oauth2/callback" ) issueTime := time.Date(2020, 05, 11, 8, 0, 0, 0, time.UTC) t.Run("can get all client applications", func(t *testing.T) { // Given store := inmemorystore.New( inmemorystore.WithClock(seededclock.New(issueTime)), ) goauth2.BindEvents(store) clientApplications := projection.NewClientApplications() store.Subscribe(clientApplications) require.NoError(t, store.Save(goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, UserID: userID, }, nil)) // When actualClientApplications := clientApplications.GetAll() // Then assert.Len(t, actualClientApplications, 1) assert.Equal(t, clientID, actualClientApplications[0].ClientID) assert.Equal(t, clientSecret, actualClientApplications[0].ClientSecret) assert.Equal(t, uint64(issueTime.Unix()), actualClientApplications[0].CreateTimestamp) }) t.Run("returns empty list", func(t *testing.T) { // Given clientApplications := projection.NewClientApplications() // When actualClientApplications := clientApplications.GetAll() // Then assert.Len(t, actualClientApplications, 0) }) } <file_sep>package main import ( "flag" "fmt" "log" "net/http" "os" "github.com/inklabs/rangedb" "github.com/inklabs/rangedb/pkg/rangedbapi" "github.com/inklabs/rangedb/pkg/rangedbui" "github.com/inklabs/rangedb/pkg/rangedbui/pkg/templatemanager/provider/memorytemplate" "github.com/inklabs/rangedb/pkg/shortuuid" "github.com/inklabs/rangedb/provider/inmemorystore" "github.com/inklabs/goauth2" "github.com/inklabs/goauth2/web" ) func main() { fmt.Println("OAuth2 Server") flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) port := flag.Int("port", 8080, "port") store := inmemorystore.New( inmemorystore.WithLogger(log.New(os.Stderr, "", 0)), ) goauth2App := goauth2.New(goauth2.WithStore(store)) webApp := web.New( web.WithGoauth2App(goauth2App), ) initDB(goauth2App, store) go func() { rangedbPort := 8081 baseUri := fmt.Sprintf("http://0.0.0.0:%d/api", rangedbPort) templateManager, _ := memorytemplate.New(rangedbui.GetTemplates()) api := rangedbapi.New(rangedbapi.WithStore(store), rangedbapi.WithBaseUri(baseUri)) ui := rangedbui.New(templateManager, api.AggregateTypeStatsProjection(), store) server := http.NewServeMux() server.Handle("/", ui) server.Handle("/api/", http.StripPrefix("/api", api)) fmt.Printf("RangeDB UI: http://0.0.0.0:%d/\n", rangedbPort) log.Fatal(http.ListenAndServe(":8081", server)) }() fmt.Printf("Go OAuth2 Server: http://0.0.0.0:%d/\n", *port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), webApp)) } func initDB(goauth2App *goauth2.App, store rangedb.Store) { const ( userID = "445a57a41b7b43e285b51e99bba10a79" email = "<EMAIL>" password = "<PASSWORD>" ) shortuuid.SetRand(100) goauth2App.Dispatch(goauth2.OnBoardUser{ UserID: userID, Username: email, Password: <PASSWORD>, }) _ = store.Save(goauth2.UserWasGrantedAdministratorRole{ UserID: userID, GrantingUserID: userID, }, map[string]string{ "message": "epoch event", }) goauth2App.Dispatch(goauth2.AuthorizeUserToOnBoardClientApplications{ UserID: userID, AuthorizingUserID: userID, }) goauth2App.Dispatch(goauth2.OnBoardClientApplication{ ClientID: "8895e1e5f06644ebb41c26ea5740b246", ClientSecret: "c1e847aef925467290b4302e64f3de4e", RedirectURI: "https://example.com/oauth2/callback", UserID: userID, }) fmt.Println("Example commands to test grant flows:") fmt.Println("# Client Credentials") fmt.Println(`curl localhost:8080/token \ -u 8<PASSWORD>6<PASSWORD>1c26ea5740<PASSWORD>:c1e847aef92<PASSWORD> \ -d "grant_type=client_credentials" \ -d "scope=read_write" -s | jq`) fmt.Println("# Resource Owner Password Credentials") fmt.Println(`curl localhost:8080/token \ -u <PASSWORD>:<PASSWORD> \ -d "grant_type=password" \ -d "username=<EMAIL>" \ -d "password=<PASSWORD>" \ -d "scope=read_write" -s | jq`) fmt.Println("# Refresh Token") fmt.Println(`curl localhost:8080/token \ -u <PASSWORD>:<PASSWORD> \ -d "grant_type=refresh_token" \ -d "refresh_token=<PASSWORD>" -s | jq`) fmt.Println("# Refresh Token x2") fmt.Println(`curl localhost:8080/token \ -u <PASSWORD>:c1e847aef925467290b4302e64f3de4e \ -d "grant_type=refresh_token" \ -d "refresh_token=<PASSWORD>" -s | jq`) fmt.Println("# Authorization Code") fmt.Println(`http://0.0.0.0:8080/login?client_id=8895e1e5f06644ebb41c26ea5740b246&redirect_uri=https://example.com/oauth2/callback&response_type=code&state=somestate&scope=read_write`) fmt.Println("user: <EMAIL>") fmt.Println("pass: <PASSWORD>") fmt.Println("# Authorization Code Token") fmt.Println(`curl localhost:8080/token \ -u 8895e1e5f06644ebb41c26ea5740b246:c1e847aef925467290b4302e64f3de4e \ -d "grant_type=authorization_code" \ -d "code=3cc6fa5b470642b081e3ebd29aa9b43c" \ -d "redirect_uri=https://example.com/oauth2/callback" -s | jq`) fmt.Println("\n# Implicit") fmt.Println(`http://0.0.0.0:8080/login?client_id=8895e1e5f06644ebb41c26ea5740b246&redirect_uri=https://example.com/oauth2/callback&response_type=token&state=somestate&scope=read_write`) fmt.Println("user: <EMAIL>") fmt.Println("pass: <PASSWORD>") } <file_sep>package goauth2 type TokenGenerator interface { New() string } <file_sep>package goauth2 //go:generate go run gen/eventgenerator/main.go -package goauth2 -id ClientID -methodName CommandType -aggregateType client-application -inFile client_application_commands.go -outFile client_application_commands_gen.go type OnBoardClientApplication struct { ClientID string `json:"clientID"` ClientSecret string `json:"clientSecret"` RedirectURI string `json:"redirectURI"` UserID string `json:"userID"` } type RequestAccessTokenViaClientCredentialsGrant struct { ClientID string `json:"clientID"` ClientSecret string `json:"clientSecret"` } <file_sep>package main import ( "flag" "io" "log" "os" "text/template" "time" "github.com/inklabs/rangedb/pkg/structparser" ) func main() { pkg := flag.String("package", "String", "package") id := flag.String("id", "String", "id") methodName := flag.String("methodName", "String", "method name") aggregateType := flag.String("aggregateType", "", "stream identifier") inFilePath := flag.String("inFile", "", "input filename containing structs") outFilePath := flag.String("outFile", "", "output filename containing generated struct methods") flag.Parse() file, err := os.Open(*inFilePath) if err != nil { log.Fatalf("unable to open (%s): %v", *inFilePath, err) } eventNames, err := structparser.GetStructNames(file) if err != nil { log.Fatalf("unable to extract events: %v", err) } _ = file.Close() outFile, err := os.Create(*outFilePath) if err != nil { log.Fatalf("unable to create events file: %v", err) } writeEvents(*pkg, *id, *methodName, *aggregateType, eventNames, outFile) _ = outFile.Close() } func writeEvents(pkg, id, methodName, aggregateType string, eventNames []string, file io.Writer) { err := fileTemplate.Execute(file, templateData{ Timestamp: time.Now(), EventNames: eventNames, MethodName: methodName, AggregateType: aggregateType, ID: id, Package: pkg, }) if err != nil { log.Fatalf("unable to write to events file: %v", err) } } type templateData struct { Timestamp time.Time EventNames []string MethodName string AggregateType string ID string Package string } var fileTemplate = template.Must(template.New("").Parse(`// Code generated by go generate // This file was generated at: // {{ .Timestamp }} package {{ $.Package }} {{ range .EventNames }} func (e {{ . }}) {{ $.MethodName }}() string { return "{{ . }}" } func (e {{ . }}) AggregateType() string { return "{{ $.AggregateType }}" } func (e {{ . }}) AggregateID() string { return e.{{ $.ID }} } {{ end }}`)) <file_sep>package web_test import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "github.com/inklabs/rangedb" "github.com/inklabs/rangedb/pkg/clock/provider/seededclock" "github.com/inklabs/rangedb/pkg/clock/provider/sequentialclock" "github.com/inklabs/rangedb/provider/inmemorystore" "github.com/inklabs/rangedb/provider/jsonrecordserializer" "github.com/inklabs/rangedb/rangedbtest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/inklabs/goauth2" "github.com/inklabs/goauth2/goauth2test" "github.com/inklabs/goauth2/web" ) const ( clientID = "fe3c986043cd4a0ebe5e181ba2baa500" clientSecret = "f29a2881e697403395e53ca173caa217" clientID2 = "da975f24538942a1872915d0982a9b50" clientSecret2 = "977c8a5726e148c0aa1b48ebd435a02c" userID = "25c807edd664438985401b2282678b13" adminUserID = "873aeb9386724213b4c1410bce9f838c" email = "<EMAIL>" password = "<PASSWORD>!" passwordHash = <PASSWORD>ej0p2d9Y8OO2635R7l/O4oEBvxgc9o6gCaQ1wjMZ77dr4qGl8nu" redirectURI = "https://example.com/oauth2/callback" codeResponseType = "code" state = "some-state" scope = "read_write" accessToken = "<KEY>" nextAccessToken = "<KEY>" refreshToken = "<PASSWORD>" nextRefreshToken = "<PASSWORD>" authorizationCode = "<KEY>" clientCredentialsGrant = "client_credentials" ROPCGrant = "<PASSWORD>" RefreshTokenGrant = "refresh_token" ImplicitGrant = "token" AuthorizationCodeGrant = "authorization_code" ) var ( issueTime = time.Date(2020, 05, 1, 8, 0, 0, 0, time.UTC) issueTimePlus10Minutes = issueTime.Add(10 * time.Minute) issueTimePlus11Minutes = issueTime.Add(11 * time.Minute) TemplateAssets = http.Dir("./templates") ) func Test_Login(t *testing.T) { t.Run("serves login form", func(t *testing.T) { // Given app := web.New( web.WithTemplateFilesystem(TemplateAssets), ) params := getAuthorizeParams() uri := fmt.Sprintf("/login?%s", params.Encode()) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, uri, nil) // When app.ServeHTTP(w, r) // Then body := w.Body.String() require.Equal(t, http.StatusOK, w.Result().StatusCode) assert.Equal(t, "HTTP/1.1", w.Result().Proto) assert.Contains(t, body, "form") assert.Contains(t, body, clientID) assert.Contains(t, body, redirectURI) assert.Contains(t, body, codeResponseType) assert.Contains(t, body, scope) assert.Contains(t, body, state) }) t.Run("fails to serve login form", func(t *testing.T) { // Given app := web.New( web.WithTemplateFilesystem(failingFilesystem{}), ) params := getAuthorizeParams() uri := fmt.Sprintf("/login?%s", params.Encode()) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, uri, nil) // When app.ServeHTTP(w, r) // Then body := w.Body.String() require.Equal(t, http.StatusInternalServerError, w.Result().StatusCode) assert.Equal(t, "HTTP/1.1", w.Result().Proto) assert.Contains(t, body, "internal error") }) } func TestListClientApplications(t *testing.T) { // Given eventStore := getStoreWithEvents(t, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, UserID: adminUserID, }, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID2, ClientSecret: clientSecret2, RedirectURI: redirectURI, UserID: adminUserID, }, ) app := web.New( web.WithGoauth2App(goauth2.New(goauth2.WithStore(eventStore))), web.WithTemplateFilesystem(TemplateAssets), ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/client-applications", nil) // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusOK, w.Result().StatusCode) assert.Equal(t, "HTTP/1.1", w.Result().Proto) body := w.Body.String() assert.Contains(t, body, clientID) } func Test_TokenEndpoint(t *testing.T) { const tokenURI = "/token" t.Run("Client Credentials Grant Type with client application on-boarded", func(t *testing.T) { // Given eventStore := getStoreWithEvents(t, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, UserID: adminUserID, }, ) app := web.New( web.WithGoauth2App(goauth2.New(goauth2.WithStore(eventStore))), ) params := &url.Values{} params.Set("grant_type", clientCredentialsGrant) params.Set("scope", scope) t.Run("issues access and refresh token", func(t *testing.T) { // Given w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") expiresAt := 1574371565 expectedBody := fmt.Sprintf(`{ "access_token": "%s", "expires_at": %d, "token_type": "Bearer", "scope": "%s" }`, accessToken, expiresAt, scope) // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusOK, w.Result().StatusCode) assertJsonHeaders(t, w) assert.JSONEq(t, expectedBody, w.Body.String()) }) t.Run("fails with missing clientID and clientSecret", func(t *testing.T) { // Given w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_client"}`, w.Body.String()) }) t.Run("fails with invalid client application id", func(t *testing.T) { // Given w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth("invalid-client-id", clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_client"}`, w.Body.String()) }) t.Run("fails with invalid client application secret", func(t *testing.T) { // Given w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, "invalid-client-secret") r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_client"}`, w.Body.String()) }) }) t.Run("ROPC Grant Type with client application and user on-boarded", func(t *testing.T) { // Given params := &url.Values{} params.Set("grant_type", ROPCGrant) params.Set("username", email) params.Set("password", <PASSWORD>) params.Set("scope", scope) t.Run("issues access and refresh token", func(t *testing.T) { // Given goAuth2App := goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), ) app := web.New(web.WithGoauth2App(goAuth2App)) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") expiresAt := 1574371565 expectedBody := fmt.Sprintf(`{ "access_token": "%s", "expires_at": %d, "token_type": "Bearer", "scope": "%s", "refresh_token": "%s" }`, accessToken, expiresAt, scope, refreshToken) // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusOK, w.Result().StatusCode) assertJsonHeaders(t, w) assert.JSONEq(t, expectedBody, w.Body.String()) }) t.Run("fails with invalid client application id", func(t *testing.T) { // Given goAuth2App := goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), ) app := web.New(web.WithGoauth2App(goAuth2App)) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth("invalid-client-id", clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_client"}`, w.Body.String()) }) t.Run("fails with invalid client application secret", func(t *testing.T) { // Given goAuth2App := goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), ) app := web.New(web.WithGoauth2App(goAuth2App)) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, "invalid-client-secret") r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_client"}`, w.Body.String()) }) t.Run("fails with missing user", func(t *testing.T) { // Given goAuth2App := goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), ) app := web.New(web.WithGoauth2App(goAuth2App)) params := &url.Values{} params.Set("grant_type", ROPCGrant) params.Set("username", "<EMAIL>") params.Set("password", <PASSWORD>) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_grant"}`, w.Body.String()) }) t.Run("fails with invalid user password", func(t *testing.T) { // Given goAuth2App := goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), ) app := web.New(web.WithGoauth2App(goAuth2App)) params := &url.Values{} params.Set("grant_type", ROPCGrant) params.Set("username", email) params.Set("password", "<PASSWORD>") params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_grant"}`, w.Body.String()) }) }) t.Run("Authorization Code Grant Type", func(t *testing.T) { t.Run("issues access and refresh token", func(t *testing.T) { // Given app := getAppWithAuthorizationCodeIssued(t) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", authorizationCode) params.Set("redirect_uri", redirectURI) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") expiresAt := 1574371565 expectedBody := fmt.Sprintf(`{ "access_token": "%s", "expires_at": %d, "token_type": "Bearer", "scope": "%s", "refresh_token": "%s" }`, accessToken, expiresAt, scope, refreshToken) // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusOK, w.Result().StatusCode) assertJsonHeaders(t, w) assert.JSONEq(t, expectedBody, w.Body.String()) }) t.Run("fails with invalid client application id", func(t *testing.T) { // Given app := getAppWithAuthorizationCodeIssued(t) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", authorizationCode) params.Set("redirect_uri", redirectURI) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth("invalid-client-id", clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_client"}`, w.Body.String()) }) t.Run("fails with invalid client application secret", func(t *testing.T) { // Given app := getAppWithAuthorizationCodeIssued(t) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", authorizationCode) params.Set("redirect_uri", redirectURI) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, "invalid-client-secret") r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_client"}`, w.Body.String()) }) t.Run("fails with invalid redirect URI", func(t *testing.T) { // Given app := getAppWithAuthorizationCodeIssued(t) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", authorizationCode) params.Set("redirect_uri", "https://wrong.example.com") params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_grant"}`, w.Body.String()) }) t.Run("fails with invalid authorization code", func(t *testing.T) { // Given app := getAppWithAuthorizationCodeIssued(t) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", "invalid-code") params.Set("redirect_uri", redirectURI) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_grant"}`, w.Body.String()) }) t.Run("fails with expired authorization code", func(t *testing.T) { // Given app := getAppWithAuthorizationCodeIssued(t, goauth2.WithClock(seededclock.New(issueTimePlus11Minutes)), ) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", authorizationCode) params.Set("redirect_uri", redirectURI) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_grant"}`, w.Body.String()) }) t.Run("fails with authorization code for wrong client application id", func(t *testing.T) { // Given eventStore := getStoreWithEvents(t, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, UserID: adminUserID, }, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID2, ClientSecret: clientSecret2, RedirectURI: redirectURI, UserID: adminUserID, }, goauth2.AuthorizationCodeWasIssuedToUser{ AuthorizationCode: authorizationCode, UserID: userID, ClientID: clientID2, ExpiresAt: issueTimePlus10Minutes.Unix(), Scope: scope, }, ) app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(eventStore), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), goauth2.WithClock(seededclock.New(issueTime)), ))) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", authorizationCode) params.Set("redirect_uri", redirectURI) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_grant"}`, w.Body.String()) }) t.Run("fails with previously used authorization code", func(t *testing.T) { // Given eventStore := getStoreWithEvents(t, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, UserID: adminUserID, }, goauth2.AuthorizationCodeWasIssuedToUser{ AuthorizationCode: authorizationCode, UserID: userID, ClientID: clientID, ExpiresAt: issueTimePlus10Minutes.Unix(), Scope: scope, }, goauth2.AccessTokenWasIssuedToUserViaAuthorizationCodeGrant{ AuthorizationCode: authorizationCode, UserID: userID, ClientID: clientID, Scope: scope, }, ) app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(eventStore), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), goauth2.WithClock(seededclock.New(issueTime)), ))) params := &url.Values{} params.Set("grant_type", AuthorizationCodeGrant) params.Set("code", authorizationCode) params.Set("redirect_uri", redirectURI) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"invalid_grant"}`, w.Body.String()) }) }) t.Run("Refresh Token Grant Type", func(t *testing.T) { t.Run("issues access and refresh token from refresh token request", func(t *testing.T) { // Given goAuth2App := goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken, nextRefreshToken)), ) app := web.New(web.WithGoauth2App(goAuth2App)) params := &url.Values{} params.Set("grant_type", ROPCGrant) params.Set("username", email) params.Set("password", <PASSWORD>) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") app.ServeHTTP(w, r) require.Equal(t, http.StatusOK, w.Result().StatusCode) var accessTokenResponse web.AccessTokenResponse err := json.Unmarshal(w.Body.Bytes(), &accessTokenResponse) require.NoError(t, err) refreshParams := &url.Values{} refreshParams.Set("grant_type", RefreshTokenGrant) refreshParams.Set("refresh_token", accessTokenResponse.RefreshToken) w = httptest.NewRecorder() r = httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(refreshParams.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") expiresAt := 1574371565 expectedBody := fmt.Sprintf(`{ "access_token": "%s", "expires_at": %d, "token_type": "Bearer", "scope": "%s", "refresh_token": "%s" }`, nextAccessToken, expiresAt, scope, nextRefreshToken) // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusOK, w.Result().StatusCode) assertJsonHeaders(t, w) assert.JSONEq(t, expectedBody, w.Body.String()) }) t.Run("refresh token grant fails from invalid refresh token", func(t *testing.T) { // Given goAuth2App := goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), ) app := web.New(web.WithGoauth2App(goAuth2App)) params := &url.Values{} params.Set("grant_type", ROPCGrant) params.Set("username", email) params.Set("password", <PASSWORD>) params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") app.ServeHTTP(w, r) require.Equal(t, http.StatusOK, w.Result().StatusCode) var accessTokenResponse web.AccessTokenResponse err := json.Unmarshal(w.Body.Bytes(), &accessTokenResponse) require.NoError(t, err) refreshParams := &url.Values{} refreshParams.Set("grant_type", RefreshTokenGrant) refreshParams.Set("refresh_token", "<PASSWORD>") w = httptest.NewRecorder() r = httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(refreshParams.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusUnauthorized, w.Result().StatusCode) assertJsonHeaders(t, w) assert.JSONEq(t, `{"error":"invalid_grant"}`, w.Body.String()) }) }) t.Run("fails with invalid HTTP form request", func(t *testing.T) { // Given app := web.New() w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader("%invalid-form")) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) assert.Contains(t, w.Body.String(), "invalid request") }) t.Run("fails with unsupported grant type", func(t *testing.T) { // Given app := web.New() params := &url.Values{} params.Set("grant_type", "invalid-grant-type") params.Set("scope", scope) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, tokenURI, strings.NewReader(params.Encode())) r.SetBasicAuth(clientID, clientSecret) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) assertJsonHeaders(t, w) assert.Equal(t, `{"error":"unsupported_grant_type"}`, w.Body.String()) }) } func Test_AuthorizeEndpoint(t *testing.T) { const authorizeURI = "/authorize" t.Run("authorization code grant", func(t *testing.T) { t.Run("grants authorization code and redirects", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithClock(sequentialclock.New()), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(authorizationCode)), ))) params := getAuthorizeParams() w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) assert.Equal(t, "", w.Body.String()) expectedLocation := "https://example.com/oauth2/callback?code=2441fd0e215f4568b67c872d39f95a3f&state=some-state" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) t.Run("fails with missing user", func(t *testing.T) { // Given app := web.New() params := getAuthorizeParams() params.Set("username", "<EMAIL>") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) assert.Equal(t, "", w.Body.String()) expectedLocation := "https://example.com/oauth2/callback?error=access_denied&state=some-state" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) t.Run("fails with invalid client id", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithClock(sequentialclock.New()), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(authorizationCode)), ))) params := getAuthorizeParams() params.Set("client_id", "invalid-client-id") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) assert.Contains(t, w.Body.String(), "invalid request") }) t.Run("fails with invalid redirect uri", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithClock(sequentialclock.New()), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(authorizationCode)), ))) params := getAuthorizeParams() params.Set("redirect_uri", "https://wrong.example.com") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) assert.Contains(t, w.Body.String(), "invalid request") }) t.Run("fails with missing user", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithClock(sequentialclock.New()), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(authorizationCode)), ))) params := getAuthorizeParams() params.Set("username", "<EMAIL>") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) expectedLocation := "https://example.com/oauth2/callback?error=access_denied&state=some-state" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) t.Run("fails with invalid user password", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), ))) params := getAuthorizeParams() params.Set("password", "<PASSWORD>") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) expectedLocation := "https://example.com/oauth2/callback?error=access_denied&state=some-state" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) }) t.Run("implicit grant", func(t *testing.T) { t.Run("grants access token via implicit grant and redirects with URI fragment", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithClock(sequentialclock.New()), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(accessToken)), ))) params := getAuthorizeParams() params.Set("response_type", ImplicitGrant) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) assert.Equal(t, "", w.Body.String()) expectedLocation := "https://example.com/oauth2/callback#access_token=<KEY>&expires_at=1574371565&scope=read_write&state=some-state&token_type=Bearer" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) t.Run("fails with invalid client id", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithClock(sequentialclock.New()), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(accessToken)), ))) params := getAuthorizeParams() params.Set("response_type", ImplicitGrant) params.Set("client_id", "invalid-client-id") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) assert.Contains(t, w.Body.String(), "invalid request") }) t.Run("fails with invalid redirect uri", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), goauth2.WithClock(sequentialclock.New()), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(accessToken)), ))) params := getAuthorizeParams() params.Set("response_type", ImplicitGrant) params.Set("redirect_uri", "https://wrong.example.com") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) assert.Contains(t, w.Body.String(), "invalid request") }) t.Run("fails with missing user", func(t *testing.T) { // Given app := web.New() params := getAuthorizeParams() params.Set("response_type", ImplicitGrant) params.Set("username", "<EMAIL>") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) expectedLocation := "https://example.com/oauth2/callback?error=access_denied&state=some-state" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) t.Run("fails with invalid user password", func(t *testing.T) { // Given app := web.New(web.WithGoauth2App(goauth2.New( goauth2.WithStore(getStoreWithClientApplicationAndUserOnBoarded(t)), ))) params := getAuthorizeParams() params.Set("response_type", ImplicitGrant) params.Set("password", "<PASSWORD>") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) expectedLocation := "https://example.com/oauth2/callback?error=access_denied&state=some-state" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) }) t.Run("fails with invalid HTTP form request", func(t *testing.T) { // Given app := web.New() w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader("%invalid-form")) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusBadRequest, w.Result().StatusCode) assert.Contains(t, w.Body.String(), "invalid request") }) t.Run("fails with unsupported response type", func(t *testing.T) { // Given app := web.New() params := getAuthorizeParams() params.Set("response_type", "invalid-response-type") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, authorizeURI, strings.NewReader(params.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // When app.ServeHTTP(w, r) // Then require.Equal(t, http.StatusFound, w.Result().StatusCode) assert.Equal(t, "", w.Body.String()) expectedLocation := "https://example.com/oauth2/callback?error=unsupported_response_type&state=some-state" assert.Equal(t, expectedLocation, w.Header().Get("Location")) }) } func Test_SavedEvents(t *testing.T) { // Given thingWasDone := &rangedbtest.ThingWasDone{ ID: "abc", Number: 123, } thatWasDone := &rangedbtest.ThatWasDone{ ID: "xyz", } events := web.SavedEvents{ thingWasDone, thatWasDone, } t.Run("contains", func(t *testing.T) { // Then assert.True(t, events.Contains(&rangedbtest.ThingWasDone{})) assert.True(t, events.Contains(&rangedbtest.ThingWasDone{}, &rangedbtest.ThatWasDone{})) assert.False(t, events.Contains(&rangedbtest.AnotherWasComplete{})) assert.False(t, events.Contains(&rangedbtest.AnotherWasComplete{}, &rangedbtest.ThingWasDone{})) }) t.Run("contains any", func(t *testing.T) { // Then assert.True(t, events.ContainsAny(&rangedbtest.AnotherWasComplete{}, &rangedbtest.ThingWasDone{})) assert.True(t, events.ContainsAny(&rangedbtest.ThingWasDone{}, &rangedbtest.ThatWasDone{})) }) t.Run("get finds an event from a list of pointer events", func(t *testing.T) { // Given var event rangedbtest.ThingWasDone // When isFound := events.Get(&event) // Then require.True(t, isFound) assert.Equal(t, *thingWasDone, event) }) t.Run("get finds an event from a list of value events", func(t *testing.T) { // Given thingWasDone := rangedbtest.ThingWasDone{ ID: "abc", Number: 123, } thatWasDone := rangedbtest.ThatWasDone{ ID: "xyz", } events := web.SavedEvents{ thingWasDone, thatWasDone, } var event rangedbtest.ThingWasDone // When isFound := events.Get(&event) // Then require.True(t, isFound) assert.Equal(t, thingWasDone, event) }) t.Run("get does not find an event", func(t *testing.T) { // Given var event rangedbtest.AnotherWasComplete // When isFound := events.Get(&event) // Then require.False(t, isFound) assert.Equal(t, rangedbtest.AnotherWasComplete{}, event) }) } func getAppWithAuthorizationCodeIssued(t *testing.T, options ...goauth2.Option) http.Handler { eventStore := getStoreWithEvents(t, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, UserID: adminUserID, }, goauth2.AuthorizationCodeWasIssuedToUser{ AuthorizationCode: authorizationCode, UserID: userID, ClientID: clientID, ExpiresAt: issueTimePlus10Minutes.Unix(), Scope: scope, }, ) options = append([]goauth2.Option{ goauth2.WithStore(eventStore), goauth2.WithTokenGenerator(goauth2test.NewSeededTokenGenerator(refreshToken)), goauth2.WithClock(seededclock.New(issueTime)), }, options...) return web.New(web.WithGoauth2App(goauth2.New(options...))) } func getAuthorizeParams() *url.Values { params := &url.Values{} params.Set("username", email) params.Set("password", <PASSWORD>) params.Set("client_id", clientID) params.Set("redirect_uri", redirectURI) params.Set("response_type", codeResponseType) params.Set("scope", scope) params.Set("state", state) return params } func assertJsonHeaders(t *testing.T, w *httptest.ResponseRecorder) { assert.Equal(t, "application/json;charset=UTF-8", w.Header().Get("Content-Type")) assert.Equal(t, "no-store", w.Header().Get("Cache-Control")) assert.Equal(t, "no-cache", w.Header().Get("Pragma")) } func getStoreWithEvents(t *testing.T, events ...rangedb.Event) rangedb.Store { serializer := jsonrecordserializer.New() goauth2.BindEvents(serializer) eventStore := inmemorystore.New(inmemorystore.WithSerializer(serializer)) for _, event := range events { err := eventStore.Save(event, nil) if err != nil { t.Errorf("unable to save event: %v", err) } } return eventStore } func getStoreWithClientApplicationAndUserOnBoarded(t *testing.T) rangedb.Store { return getStoreWithEvents(t, goauth2.ClientApplicationWasOnBoarded{ ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, UserID: adminUserID, }, goauth2.UserWasOnBoarded{ UserID: userID, Username: email, PasswordHash: <PASSWORD>, }, ) } type failingFilesystem struct{} func (f failingFilesystem) Open(_ string) (http.File, error) { return nil, fmt.Errorf("failingFilesystem:Open") } <file_sep>package goauth2 //go:generate go run gen/eventgenerator/main.go -package goauth2 -id ClientID -methodName EventType -aggregateType client-application -inFile client_application_events.go -outFile client_application_events_gen.go // OnBoardClientApplication Events type ClientApplicationWasOnBoarded struct { ClientID string `json:"clientID"` ClientSecret string `json:"clientSecret"` RedirectURI string `json:"redirectURI"` UserID string `json:"userID"` } type OnBoardClientApplicationWasRejectedDueToUnAuthorizeUser struct { ClientID string `json:"clientID"` UserID string `json:"userID"` } type OnBoardClientApplicationWasRejectedDueToInsecureRedirectURI struct { ClientID string `json:"clientID"` RedirectURI string `json:"redirectURI"` } type OnBoardClientApplicationWasRejectedDueToInvalidRedirectURI struct { ClientID string `json:"clientID"` RedirectURI string `json:"redirectURI"` } // RequestAccessTokenViaClientCredentialsGrant Events type AccessTokenWasIssuedToClientApplicationViaClientCredentialsGrant struct { ClientID string `json:"clientID"` } type RequestAccessTokenViaClientCredentialsGrantWasRejectedDueToInvalidClientApplicationID struct { ClientID string `json:"clientID"` } type RequestAccessTokenViaClientCredentialsGrantWasRejectedDueToInvalidClientApplicationSecret struct { ClientID string `json:"clientID"` } <file_sep>package goauth2 import ( "net/url" "github.com/inklabs/rangedb" ) func ClientApplicationCommandTypes() []string { return []string{ OnBoardClientApplication{}.CommandType(), RequestAccessTokenViaClientCredentialsGrant{}.CommandType(), } } type clientApplication struct { IsOnBoarded bool ClientID string ClientSecret string RedirectURI string pendingEvents []rangedb.Event } func newClientApplication(records <-chan *rangedb.Record) *clientApplication { aggregate := &clientApplication{} for record := range records { if event, ok := record.Data.(rangedb.Event); ok { aggregate.apply(event) } } return aggregate } func (a *clientApplication) apply(event rangedb.Event) { switch e := event.(type) { case *ClientApplicationWasOnBoarded: a.IsOnBoarded = true a.ClientID = e.ClientID a.ClientSecret = e.ClientSecret a.RedirectURI = e.RedirectURI } } func (a *clientApplication) GetPendingEvents() []rangedb.Event { return a.pendingEvents } func (a *clientApplication) Handle(command Command) { switch c := command.(type) { case OnBoardClientApplication: a.OnBoardClientApplication(c) case RequestAccessTokenViaClientCredentialsGrant: a.RequestAccessTokenViaClientCredentialsGrant(c) } } func (a *clientApplication) OnBoardClientApplication(c OnBoardClientApplication) { uri, err := url.Parse(c.RedirectURI) if err != nil { a.emit(OnBoardClientApplicationWasRejectedDueToInvalidRedirectURI{ ClientID: c.ClientID, RedirectURI: c.RedirectURI, }) return } if uri.Scheme != "https" { a.emit(OnBoardClientApplicationWasRejectedDueToInsecureRedirectURI{ ClientID: c.ClientID, RedirectURI: c.RedirectURI, }) return } a.emit(ClientApplicationWasOnBoarded{ ClientID: c.ClientID, ClientSecret: c.ClientSecret, RedirectURI: c.RedirectURI, UserID: c.UserID, }) } func (a *clientApplication) RequestAccessTokenViaClientCredentialsGrant(c RequestAccessTokenViaClientCredentialsGrant) { if !a.IsOnBoarded { a.emit(RequestAccessTokenViaClientCredentialsGrantWasRejectedDueToInvalidClientApplicationID{ ClientID: c.ClientID, }) return } if a.ClientSecret != c.ClientSecret { a.emit(RequestAccessTokenViaClientCredentialsGrantWasRejectedDueToInvalidClientApplicationSecret{ ClientID: c.ClientID, }) return } a.emit(AccessTokenWasIssuedToClientApplicationViaClientCredentialsGrant{ ClientID: c.ClientID, }) } func (a *clientApplication) emit(events ...rangedb.Event) { for _, event := range events { a.apply(event) } a.pendingEvents = append(a.pendingEvents, events...) } <file_sep>package goauth2 //go:generate go run gen/eventgenerator/main.go -package goauth2 -id RefreshToken -methodName EventType -aggregateType refresh-token -inFile refresh_token_events.go -outFile refresh_token_events_gen.go // RequestAccessTokenViaRefreshTokenGrant Events type RefreshTokenWasIssuedToUser struct { RefreshToken string `json:"refreshToken"` UserID string `json:"userID"` ClientID string `json:"clientID"` Scope string `json:"scope"` } type RefreshTokenWasIssuedToClientApplication struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` } type RefreshTokenWasRevokedFromUser struct { RefreshToken string `json:"refreshToken"` UserID string `json:"userID"` ClientID string `json:"clientID"` } type AccessTokenWasIssuedToUserViaRefreshTokenGrant struct { RefreshToken string `json:"refreshToken"` UserID string `json:"userID"` ClientID string `json:"clientID"` } type AccessTokenWasIssuedToClientApplicationViaRefreshTokenGrant struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` } type RefreshTokenWasIssuedToUserViaRefreshTokenGrant struct { RefreshToken string `json:"refreshToken"` UserID string `json:"userID"` ClientID string `json:"clientID"` NextRefreshToken string `json:"nextRefreshToken"` Scope string `json:"scope"` } type RefreshTokenWasIssuedToClientApplicationViaRefreshTokenGrant struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` NextRefreshToken string `json:"nextRefreshToken"` } type RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToInvalidRefreshToken struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` } type RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToInvalidScope struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` Scope string `json:"scope"` RequestedScope string `json:"requestedScope"` } type RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToInvalidClientApplicationCredentials struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` } type RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToPreviouslyUsedRefreshToken struct { RefreshToken string `json:"refreshToken"` } type RequestAccessTokenViaRefreshTokenGrantWasRejectedDueToRevokedRefreshToken struct { RefreshToken string `json:"refreshToken"` ClientID string `json:"clientID"` } type AccessTokenWasRevokedDueToPreviouslyUsedRefreshToken struct { RefreshToken string `json:"refreshToken"` } <file_sep>package web import ( "encoding/json" "fmt" "log" "net/http" "net/url" "reflect" "strconv" "github.com/gorilla/mux" "github.com/inklabs/rangedb" "github.com/inklabs/goauth2" "github.com/inklabs/goauth2/projection" "github.com/inklabs/goauth2/web/pkg/templatemanager" ) const ( accessTokenTODO = "<KEY>" expiresAtTODO = 1574371565 ) //go:generate go run github.com/shurcooL/vfsgen/cmd/vfsgendev -source="github.com/inklabs/goauth2/web".TemplateAssets type app struct { router *mux.Router templateManager *templatemanager.TemplateManager goauth2App *goauth2.App projections struct { emailToUserID *projection.EmailToUserID clientApplications *projection.ClientApplications } } //Option defines functional option parameters for app. type Option func(*app) //WithTemplateFilesystem is a functional option to inject a template loader. func WithTemplateFilesystem(fileSystem http.FileSystem) Option { return func(app *app) { app.templateManager = templatemanager.New(fileSystem) } } //WithGoauth2App is a functional option to inject a goauth2 application. func WithGoauth2App(goauth2App *goauth2.App) Option { return func(app *app) { app.goauth2App = goauth2App } } //New constructs an app. func New(options ...Option) *app { app := &app{ templateManager: templatemanager.New(TemplateAssets), goauth2App: goauth2.New(), } for _, option := range options { option(app) } app.initRoutes() app.initProjections() return app } func (a *app) initRoutes() { a.router = mux.NewRouter().StrictSlash(true) a.router.HandleFunc("/authorize", a.authorize) a.router.HandleFunc("/login", a.login) a.router.HandleFunc("/token", a.token) a.router.HandleFunc("/client-applications", a.listClientApplications) } func (a *app) initProjections() { a.projections.emailToUserID = projection.NewEmailToUserID() a.projections.clientApplications = projection.NewClientApplications() a.goauth2App.SubscribeAndReplay( a.projections.emailToUserID, a.projections.clientApplications, ) } func (a *app) ServeHTTP(w http.ResponseWriter, r *http.Request) { a.router.ServeHTTP(w, r) } func (a *app) login(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() clientId := params.Get("client_id") redirectURI := params.Get("redirect_uri") responseType := params.Get("response_type") state := params.Get("state") scope := params.Get("scope") a.renderTemplate(w, "login.html", struct { ClientId string RedirectURI string ResponseType string Scope string State string }{ ClientId: clientId, RedirectURI: redirectURI, ResponseType: responseType, Scope: scope, State: state, }) } func (a *app) listClientApplications(w http.ResponseWriter, _ *http.Request) { type ClientApplication struct { ClientID string ClientSecret string CreateTimestamp uint64 } var clientApplications []ClientApplication for _, clientApplication := range a.projections.clientApplications.GetAll() { clientApplications = append(clientApplications, ClientApplication{ ClientID: clientApplication.ClientID, ClientSecret: clientApplication.ClientSecret, CreateTimestamp: clientApplication.CreateTimestamp, }) } a.renderTemplate(w, "client-applications.html", struct { ClientApplications []ClientApplication }{ ClientApplications: clientApplications, }) } func (a *app) authorize(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { writeInvalidRequestResponse(w) return } redirectURI := r.Form.Get("redirect_uri") responseType := r.Form.Get("response_type") state := r.Form.Get("state") switch responseType { case "code": a.handleAuthorizationCodeGrant(w, r) case "token": a.handleImplicitGrant(w, r) default: errorRedirect(w, r, redirectURI, "unsupported_response_type", state) } } func (a *app) handleAuthorizationCodeGrant(w http.ResponseWriter, r *http.Request) { username := r.Form.Get("username") password := r.Form.Get("<PASSWORD>") clientID := r.Form.Get("client_id") redirectURI := r.Form.Get("redirect_uri") state := r.Form.Get("state") scope := r.Form.Get("scope") userID, err := a.projections.emailToUserID.GetUserID(username) if err != nil { errorRedirect(w, r, redirectURI, "access_denied", state) return } events := SavedEvents(a.goauth2App.Dispatch(goauth2.RequestAuthorizationCodeViaAuthorizationCodeGrant{ UserID: userID, ClientID: clientID, RedirectURI: redirectURI, Username: username, Password: <PASSWORD>, Scope: scope, })) var issuedEvent goauth2.AuthorizationCodeWasIssuedToUserViaAuthorizationCodeGrant if !events.Get(&issuedEvent) { if events.ContainsAny( &goauth2.RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationID{}, &goauth2.RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationRedirectURI{}, ) { writeInvalidRequestResponse(w) return } errorRedirect(w, r, redirectURI, "access_denied", state) return } newParams := url.Values{} if state != "" { newParams.Set("state", state) } newParams.Set("code", issuedEvent.AuthorizationCode) uri := fmt.Sprintf("%s?%s", redirectURI, newParams.Encode()) http.Redirect(w, r, uri, http.StatusFound) } func (a *app) handleImplicitGrant(w http.ResponseWriter, r *http.Request) { username := r.Form.Get("username") password := r.Form.Get("<PASSWORD>") clientID := r.Form.Get("client_id") redirectURI := r.Form.Get("redirect_uri") state := r.Form.Get("state") scope := r.Form.Get("scope") userID, err := a.projections.emailToUserID.GetUserID(username) if err != nil { errorRedirect(w, r, redirectURI, "access_denied", state) return } events := SavedEvents(a.goauth2App.Dispatch(goauth2.RequestAccessTokenViaImplicitGrant{ UserID: userID, ClientID: clientID, RedirectURI: redirectURI, Username: username, Password: <PASSWORD>, })) var issuedEvent goauth2.AccessTokenWasIssuedToUserViaImplicitGrant if !events.Get(&issuedEvent) { if events.ContainsAny( &goauth2.RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidClientApplicationID{}, &goauth2.RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidClientApplicationRedirectURI{}, ) { writeInvalidRequestResponse(w) return } errorRedirect(w, r, redirectURI, "access_denied", state) return } newParams := url.Values{} if state != "" { newParams.Set("state", state) } newParams.Set("access_token", accessTokenTODO) newParams.Set("expires_at", strconv.Itoa(expiresAtTODO)) newParams.Set("scope", scope) newParams.Set("token_type", "Bearer") uri := fmt.Sprintf("%s#%s", redirectURI, newParams.Encode()) http.Redirect(w, r, uri, http.StatusFound) } type AccessTokenResponse struct { AccessToken string `json:"access_token"` ExpiresAt int `json:"expires_at"` TokenType string `json:"token_type"` RefreshToken string `json:"refresh_token,omitempty"` Scope string `json:"scope,omitempty"` } func (a *app) token(w http.ResponseWriter, r *http.Request) { clientID, clientSecret, ok := r.BasicAuth() if !ok { writeInvalidClientResponse(w) return } err := r.ParseForm() if err != nil { writeInvalidRequestResponse(w) return } grantType := r.Form.Get("grant_type") scope := r.Form.Get("scope") switch grantType { case "client_credentials": a.handleClientCredentialsGrant(w, clientID, clientSecret, scope) case "password": a.handleROPCGrant(w, r, clientID, clientSecret, scope) case "refresh_token": a.handleRefreshTokenGrant(w, r, clientID, clientSecret, scope) case "authorization_code": a.handleAuthorizationCodeTokenGrant(w, r, clientID, clientSecret) default: writeUnsupportedGrantTypeResponse(w) } } func (a *app) handleRefreshTokenGrant(w http.ResponseWriter, r *http.Request, clientID, clientSecret, scope string) { refreshToken := r.Form.Get("refresh_token") events := SavedEvents(a.goauth2App.Dispatch(goauth2.RequestAccessTokenViaRefreshTokenGrant{ RefreshToken: refreshToken, ClientID: clientID, ClientSecret: clientSecret, Scope: scope, })) var issuedEvent goauth2.RefreshTokenWasIssuedToUserViaRefreshTokenGrant if !events.Get(&issuedEvent) { writeInvalidGrantResponse(w) return } writeJsonResponse(w, AccessTokenResponse{ AccessToken: "<KEY>", ExpiresAt: expiresAtTODO, TokenType: "Bearer", RefreshToken: issuedEvent.NextRefreshToken, Scope: issuedEvent.Scope, }) return } func (a *app) handleROPCGrant(w http.ResponseWriter, r *http.Request, clientID, clientSecret, scope string) { username := r.Form.Get("username") password := r.Form.Get("<PASSWORD>") userID, err := a.projections.emailToUserID.GetUserID(username) if err != nil { writeInvalidGrantResponse(w) return } events := SavedEvents(a.goauth2App.Dispatch(goauth2.RequestAccessTokenViaROPCGrant{ UserID: userID, ClientID: clientID, ClientSecret: clientSecret, Username: username, Password: <PASSWORD>, Scope: scope, })) if !events.Contains(&goauth2.AccessTokenWasIssuedToUserViaROPCGrant{}) { if events.Contains(&goauth2.RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidClientApplicationCredentials{}) { writeInvalidClientResponse(w) return } writeInvalidGrantResponse(w) return } var refreshToken string var refreshTokenEvent goauth2.RefreshTokenWasIssuedToUserViaROPCGrant if events.Get(&refreshTokenEvent) { refreshToken = refreshTokenEvent.RefreshToken } writeJsonResponse(w, AccessTokenResponse{ AccessToken: accessTokenTODO, ExpiresAt: expiresAtTODO, TokenType: "Bearer", RefreshToken: refreshToken, Scope: scope, }) return } func (a *app) handleClientCredentialsGrant(w http.ResponseWriter, clientID, clientSecret, scope string) { events := SavedEvents(a.goauth2App.Dispatch(goauth2.RequestAccessTokenViaClientCredentialsGrant{ ClientID: clientID, ClientSecret: clientSecret, })) if !events.Contains(&goauth2.AccessTokenWasIssuedToClientApplicationViaClientCredentialsGrant{}) { writeInvalidClientResponse(w) return } writeJsonResponse(w, AccessTokenResponse{ AccessToken: accessTokenTODO, ExpiresAt: expiresAtTODO, TokenType: "Bearer", Scope: scope, }) return } func (a *app) handleAuthorizationCodeTokenGrant(w http.ResponseWriter, r *http.Request, clientID, clientSecret string) { authorizationCode := r.Form.Get("code") redirectURI := r.Form.Get("redirect_uri") events := SavedEvents(a.goauth2App.Dispatch(goauth2.RequestAccessTokenViaAuthorizationCodeGrant{ AuthorizationCode: authorizationCode, ClientID: clientID, ClientSecret: clientSecret, RedirectURI: redirectURI, })) var accessTokenIssuedEvent goauth2.AccessTokenWasIssuedToUserViaAuthorizationCodeGrant if !events.Get(&accessTokenIssuedEvent) { if events.ContainsAny( &goauth2.RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationID{}, &goauth2.RequestAccessTokenViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationSecret{}, ) { writeInvalidClientResponse(w) return } writeInvalidGrantResponse(w) return } scope := accessTokenIssuedEvent.Scope var refreshToken string var refreshTokenIssuedEvent goauth2.RefreshTokenWasIssuedToUserViaAuthorizationCodeGrant if events.Get(&refreshTokenIssuedEvent) { refreshToken = refreshTokenIssuedEvent.RefreshToken } writeJsonResponse(w, AccessTokenResponse{ AccessToken: accessTokenTODO, ExpiresAt: expiresAtTODO, TokenType: "Bearer", Scope: scope, RefreshToken: refreshToken, }) return } func (a *app) renderTemplate(w http.ResponseWriter, templateName string, data interface{}) { err := a.templateManager.RenderTemplate(w, templateName, data) if err != nil { log.Println(err) http.Error(w, "internal error", http.StatusInternalServerError) } } type errorResponse struct { Error string `json:"error"` } func writeInvalidRequestResponse(w http.ResponseWriter) { http.Error(w, "invalid request", http.StatusBadRequest) } func writeInvalidClientResponse(w http.ResponseWriter) { w.WriteHeader(http.StatusUnauthorized) writeJsonResponse(w, errorResponse{Error: "invalid_client"}) } func writeInvalidGrantResponse(w http.ResponseWriter) { w.WriteHeader(http.StatusUnauthorized) writeJsonResponse(w, errorResponse{Error: "invalid_grant"}) } func writeUnsupportedGrantTypeResponse(w http.ResponseWriter) { w.WriteHeader(http.StatusBadRequest) writeJsonResponse(w, errorResponse{Error: "unsupported_grant_type"}) } func writeJsonResponse(w http.ResponseWriter, jsonBody interface{}) { bytes, err := json.Marshal(jsonBody) if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json;charset=UTF-8") w.Header().Set("Cache-Control", "no-store") w.Header().Set("Pragma", "no-cache") _, _ = w.Write(bytes) } func errorRedirect(w http.ResponseWriter, r *http.Request, redirectURI, errorMessage, state string) { query := url.Values{} query.Set("error", errorMessage) if state != "" { query.Set("state", state) } uri := fmt.Sprintf("%s?%s", redirectURI, query.Encode()) http.Redirect(w, r, uri, http.StatusFound) } //SavedEvents contains events that have been persisted to the event store. type SavedEvents []rangedb.Event // Contains returns true if all events are found. func (l *SavedEvents) Contains(events ...rangedb.Event) bool { var totalFound int for _, event := range events { for _, savedEvent := range *l { if event.EventType() == savedEvent.EventType() { totalFound++ break } } } return len(events) == totalFound } // ContainsAny returns true if any events are found. func (l *SavedEvents) ContainsAny(events ...rangedb.Event) bool { for _, event := range events { for _, savedEvent := range *l { if event.EventType() == savedEvent.EventType() { return true } } } return false } // Get returns true if the event was found and stores the result // in the value pointed to by event. If it is not found, Get // returns false. func (l *SavedEvents) Get(event rangedb.Event) bool { for _, savedEvent := range *l { if event.EventType() == savedEvent.EventType() { eventVal := reflect.ValueOf(event) savedEventVal := reflect.ValueOf(savedEvent) if savedEventVal.Kind() == reflect.Ptr { savedEventVal = savedEventVal.Elem() } if savedEventVal.Type().AssignableTo(eventVal.Type().Elem()) { eventVal.Elem().Set(savedEventVal) return true } } } return false } <file_sep>package templatemanager import ( "testing" "github.com/stretchr/testify/assert" ) func TestFuncMap_formatDate(t *testing.T) { // When actual := formatDate(1589260539, "Jan 02, 2006 15:04:05 UTC") // Then assert.Equal(t, "May 12, 2020 05:15:39 UTC", actual) } <file_sep>module github.com/inklabs/goauth2 go 1.14 require ( github.com/google/uuid v1.1.1 github.com/gorilla/mux v1.7.4 github.com/inklabs/rangedb v0.3.1 github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 // indirect github.com/shurcooL/vfsgen v0.0.0-20181202132449-6a9ea43bcacd // indirect github.com/stretchr/objx v0.2.0 // indirect github.com/stretchr/testify v1.6.0 golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 gopkg.in/yaml.v3 v3.0.0-20200506231410-2ff61e1afc86 // indirect ) <file_sep>package goauth2 //go:generate go run gen/eventgenerator/main.go -package goauth2 -id UserID -methodName EventType -aggregateType resource-owner -inFile resource_owner_events.go -outFile resource_owner_events_gen.go // OnBoardUser Events type UserWasOnBoarded struct { UserID string `json:"userID"` Username string `json:"username"` PasswordHash string `json:"passwordHash"` } type OnBoardUserWasRejectedDueToExistingUser struct { UserID string `json:"userID"` } type OnBoardUserWasRejectedDueToInsecurePassword struct { UserID string `json:"userID"` } // GrantUserAdministratorRole Events type UserWasGrantedAdministratorRole struct { UserID string `json:"userID"` GrantingUserID string `json:"grantingUserID"` } type GrantUserAdministratorRoleWasRejectedDueToMissingGrantingUser struct { UserID string `json:"userID"` GrantingUserID string `json:"grantingUserID"` } type GrantUserAdministratorRoleWasRejectedDueToMissingTargetUser struct { UserID string `json:"userID"` GrantingUserID string `json:"grantingUserID"` } type GrantUserAdministratorRoleWasRejectedDueToNonAdministrator struct { UserID string `json:"userID"` GrantingUserID string `json:"grantingUserID"` } // AuthorizeUserToOnBoardClientApplications Events type UserWasAuthorizedToOnBoardClientApplications struct { UserID string `json:"userID"` AuthorizingUserID string `json:"authorizingUserID"` } type AuthorizeUserToOnBoardClientApplicationsWasRejectedDueToMissingAuthorizingUser struct { UserID string `json:"userID"` AuthorizingUserID string `json:"authorizingUserID"` } type AuthorizeUserToOnBoardClientApplicationsWasRejectedDueToMissingTargetUser struct { UserID string `json:"userID"` AuthorizingUserID string `json:"authorizingUserID"` } type AuthorizeUserToOnBoardClientApplicationsWasRejectedDueToNonAdministrator struct { UserID string `json:"userID"` AuthorizingUserID string `json:"authorizingUserID"` } // RequestAccessTokenViaImplicitGrant Events type AccessTokenWasIssuedToUserViaImplicitGrant struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidClientApplicationID struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidClientApplicationRedirectURI struct { UserID string `json:"userID"` ClientID string `json:"clientID"` RedirectURI string `json:"redirectURI"` } type RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidUser struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RequestAccessTokenViaImplicitGrantWasRejectedDueToInvalidUserPassword struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } // RequestAccessTokenViaROPCGrant Events type AccessTokenWasIssuedToUserViaROPCGrant struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RefreshTokenWasIssuedToUserViaROPCGrant struct { UserID string `json:"userID"` ClientID string `json:"clientID"` RefreshToken string `json:"refreshToken"` Scope string `json:"scope"` } type RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidUser struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidUserPassword struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RequestAccessTokenViaROPCGrantWasRejectedDueToInvalidClientApplicationCredentials struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } // RequestAuthorizationCodeViaAuthorizationCodeGrant Events type AuthorizationCodeWasIssuedToUserViaAuthorizationCodeGrant struct { UserID string `json:"userID"` ClientID string `json:"clientID"` AuthorizationCode string `json:"authorizationCode"` ExpiresAt int64 `json:"expiresAt"` Scope string `json:"scope"` } type RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationID struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidClientApplicationRedirectURI struct { UserID string `json:"userID"` ClientID string `json:"clientID"` RedirectURI string `json:"redirectURI"` } type RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidUser struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } type RequestAuthorizationCodeViaAuthorizationCodeGrantWasRejectedDueToInvalidUserPassword struct { UserID string `json:"userID"` ClientID string `json:"clientID"` } <file_sep>package projection import ( "github.com/inklabs/rangedb" "github.com/inklabs/goauth2" ) type clientApplication struct { ClientID string ClientSecret string CreateTimestamp uint64 } type ClientApplications struct { clientApplications map[string]*clientApplication } func NewClientApplications() *ClientApplications { return &ClientApplications{ clientApplications: make(map[string]*clientApplication), } } func (a *ClientApplications) Accept(record *rangedb.Record) { event, ok := record.Data.(*goauth2.ClientApplicationWasOnBoarded) if ok { a.clientApplications[event.ClientID] = &clientApplication{ ClientID: event.ClientID, ClientSecret: event.ClientSecret, CreateTimestamp: record.InsertTimestamp, } } } func (a *ClientApplications) GetAll() []*clientApplication { var clientApplications []*clientApplication for _, clientApplication := range a.clientApplications { clientApplications = append(clientApplications, clientApplication) } return clientApplications }
520b4709e89314bfd2211e9eb9d470551fd4b475
[ "Go Module", "Go" ]
24
Go
steeleprice/goauth2
d18aa4566f4cb8f31da7e8f94e99af96c59cb050
4cd912fbcae7670de701e917b8faaf6dff438982
refs/heads/master
<file_sep>/* * Copyright (c) 2016, Uber Technologies, Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.uber.jaeger.senders; import com.uber.jaeger.thriftjava.Batch; import com.uber.jaeger.thriftjava.Process; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.thrift.TException; import org.apache.thrift.TSerializer; import org.apache.thrift.protocol.TBinaryProtocol.Factory; import org.apache.thrift.protocol.TProtocolFactory; public class HttpSender extends ThriftSender { private static final String HTTP_COLLECTOR_JAEGER_THRIFT_FORMAT_PARAM = "format=jaeger.thrift"; private static final TProtocolFactory PROTOCOL_FACTORY = new Factory(); private static final TSerializer SERIALIZER = new TSerializer(PROTOCOL_FACTORY); private final HttpClient httpClient = new DefaultHttpClient(); private final URI collectorUri; /** * @param endpoint Jaeger REST endpoint consuming jaeger.thrift, e.g http://localhost:14268/api/traces * @param maxPacketSize max packet size */ public HttpSender(String endpoint, int maxPacketSize) { super(PROTOCOL_FACTORY, maxPacketSize); this.collectorUri = constructCollectorUri(endpoint); } @Override public void send(Process process, List<com.uber.jaeger.thriftjava.Span> spans) throws TException { Batch batch = new Batch(process, spans); byte[] bytes = SERIALIZER.serialize(batch); try { HttpPost httpPost = new HttpPost(this.collectorUri); httpPost.setEntity(new ByteArrayEntity(bytes)); HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new TException("Could not send " + spans.size() + " spans, response " + response.getStatusLine().getStatusCode()); } } catch (IOException e) { throw new TException("Could not send " + spans.size() + ", spans", e); } } private URI constructCollectorUri(String endpoint) { try { return new URI(String.format("%s?%s", endpoint, HTTP_COLLECTOR_JAEGER_THRIFT_FORMAT_PARAM)); } catch (URISyntaxException e) { throw new IllegalArgumentException("Wrong collector host", e); } } }
7de9fdc4a1b9485c1d74ca64a32bf9dc1e414f4c
[ "Java" ]
1
Java
vinaysen/jaeger-client-java
8784904110dda7a7c8a3ffb02541dcc76aa45c38
5355748a18b0190804290a813de6cadb0ffea427
refs/heads/master
<repo_name>hongji3354/time-manager-api-server<file_sep>/src/main/java/kr/healthcare/timemanagerapi/util/JwtTokenUtil.java package kr.healthcare.timemanagerapi.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.Map; public class JwtTokenUtil { private static final String secretKey = "healthcare"; //JWT 생성 public static String deGenerateToken(){ return Jwts.builder() .setHeaderParam("typ","jwt") .setIssuer("unist_healthcare") .setIssuedAt(new Date(System.currentTimeMillis())) .signWith(SignatureAlgorithm.HS512,secretKey) .compact(); } //JWT 생성 public static String deGenerateToken(Map<String, Object> claim){ return Jwts.builder() .setHeaderParam("typ","jwt") .setClaims(claim) .setIssuer("unist_healthcare") .setIssuedAt(new Date(System.currentTimeMillis())) .signWith(SignatureAlgorithm.HS512,secretKey) .compact(); } //JWT에서 Claim 파싱 public static Claims getAllClaimsFromToken(String token){ return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody(); } } <file_sep>/src/main/java/kr/healthcare/timemanagerapi/exception/TokenEmptyException.java package kr.healthcare.timemanagerapi.exception; public class TokenEmptyException extends Exception { public TokenEmptyException(String message) { super(message); } } <file_sep>/src/main/java/kr/healthcare/timemanagerapi/interceptor/TokenValidInterceptor.java package kr.healthcare.timemanagerapi.interceptor; import io.jsonwebtoken.MalformedJwtException; import kr.healthcare.timemanagerapi.constant.Authority; import kr.healthcare.timemanagerapi.domain.member.MemberEntity; import kr.healthcare.timemanagerapi.domain.member.MemberRepositroy; import kr.healthcare.timemanagerapi.exception.TokenEmptyException; import kr.healthcare.timemanagerapi.exception.UnApprovalException; import kr.healthcare.timemanagerapi.exception.UnauthorizedException; import kr.healthcare.timemanagerapi.util.JwtTokenUtil; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component @AllArgsConstructor public class TokenValidInterceptor extends HandlerInterceptorAdapter { @NonNull private MemberRepositroy memberRepositroy; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("Authentication"); if(token == null || "".equals(token)){ throw new TokenEmptyException("Token 값이 비어있다."); }else{ // Token이 해당 서버에서 발급했는지 확인. 만약 Token이 올바르지 않다면 MalformedJwtException 발생. JwtTokenUtil.getAllClaimsFromToken(token); } if(memberRepositroy.existsByToken(token)){ String[] urlSplit = request.getServletPath().split("/"); MemberEntity memberEntity = memberRepositroy.findByToken(token); if("admin".equals(urlSplit[2])){ if(Authority.U.toString().equals(memberEntity.getAuth())){ throw new UnauthorizedException("접근 권한이 없다."); }else{ return true; } }else if("sadmin".equals(urlSplit[2])){ if(Authority.U.toString().equals(memberEntity.getAuth()) || Authority.A.toString().equals(memberEntity.getAuth())){ throw new UnauthorizedException("접근 권한이 없다."); }else{ return true; } }else{ if("N".equals(memberEntity.getAuth())){ throw new UnApprovalException("회원가입 승인이 되지 않은 회원"); }else{ return true; } } }else{ throw new MalformedJwtException("Token은 서버에서 발급한게 맞지만 일치하는 Token이 존재하지 않는다!"); } } } <file_sep>/src/main/java/kr/healthcare/timemanagerapi/domain/consulting/manage/CounselingManageEntity.java package kr.healthcare.timemanagerapi.domain.consulting.manage; import kr.healthcare.timemanagerapi.domain.BaseTimeEntity; import kr.healthcare.timemanagerapi.domain.member.MemberEntity; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDate; import java.time.LocalDateTime; @Entity @Table(name = "COUNSELING_TBL") @NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter public class CounselingManageEntity extends BaseTimeEntity { @Id private String idx; @Column(length = 8) private String adminNum; @Column(nullable = false) private LocalDate startDate; @Column(nullable = false) private LocalDate endDate; @Column(length = 1, nullable = false) private String forceEndYn; private LocalDateTime deleteDate; @Column(length = 1) private String deleteYn; @ManyToOne @JoinColumn(name = "admin_number") private MemberEntity member; @Transient private String semester; @PrePersist public void defaultValueCheck(){ this.deleteYn = (this.deleteYn == null) ? this.deleteYn = "N" : this.deleteYn; this.forceEndYn = (this.forceEndYn == null) ? this.forceEndYn = "N" : this.forceEndYn; } @PreUpdate public void defaultValueUpdateCheck(){ this.deleteYn = (this.deleteYn == null) ? this.deleteYn = "N" : this.deleteYn; this.forceEndYn = (this.forceEndYn == null) ? this.forceEndYn = "N" : this.forceEndYn; } @Builder public CounselingManageEntity(LocalDate startDate, LocalDate endDate, String semester, String adminNum, String forceEndYn, LocalDateTime deleteDate, String deleteYn, MemberEntity member){ this.idx = semester+adminNum; this.startDate = startDate; this.endDate = endDate; this.semester=semester; this.adminNum=adminNum; this.forceEndYn = forceEndYn; this.deleteDate = deleteDate; this.deleteYn = deleteYn; this.member = member; } } <file_sep>/src/main/java/kr/healthcare/timemanagerapi/dto/admin/MemberMngDTO.java package kr.healthcare.timemanagerapi.dto.admin; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Pattern; import java.time.LocalDateTime; import java.util.List; public class MemberMngDTO { @Getter @Setter @ToString public static class MemberInformation { private String stdNum; private String email; private String name; private String nickname; private String acceptYn; private LocalDateTime createdDate; } @Getter @Setter @ToString public static class MemberListResponse { private int searchCount; private List<MemberInformation> memberList; } @Getter @Setter @ToString public static class MemberPermissionApprovalRequest { @NotEmpty(message = "학번은 필수값 입니다.") @Pattern(regexp = "(^[0-9]{8}$)", message = "학번은 8자리 입니다.") private String studentNumber; } @Getter @Setter @ToString public static class MemberPermissionApprovalResponse { private String resultCode; private String resultMessage; } } <file_sep>/src/main/java/kr/healthcare/timemanagerapi/domain/member/MemberEntity.java package kr.healthcare.timemanagerapi.domain.member; import kr.healthcare.timemanagerapi.domain.BaseTimeEntity; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDateTime; @Entity @Table(name = "MEMBER_TBL") @NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter public class MemberEntity extends BaseTimeEntity { @Id @Column(length = 8) private String stdNum; @Column(length = 45, unique = true, nullable = false) private String email; @Column(length = 500, nullable = false) private String password; @Column(length = 45, nullable = false) private String name; @Column(length = 45) private String nickname; @Column(nullable = false, columnDefinition = "varchar(1) default 'U'") private String auth; private LocalDateTime deleteDate; @Column(nullable = false, columnDefinition = "varchar(1) default 'N'") private String deleteYn; private String imagePath; private String imageKey; private String imageFilename; @Column(length = 500) private String token; @Column(length = 1, columnDefinition = "varchar(1) default 'N'") private String acceptYn; private LocalDateTime acceptTime; @Column(length = 45) private String accpetMember; @PrePersist public void defaultValueCheck(){ this.auth = (this.auth == null) ? this.auth = "U" : this.auth; this.deleteYn = (this.deleteYn == null) ? this.deleteYn = "N" : this.deleteYn; this.acceptYn = (this.acceptYn == null) ? this.acceptYn = "N" : this.acceptYn; } @Builder public MemberEntity(String stdNum, String email, String password, String name, String nickname, String imagePath, String imageKey, String imageFilename, String token, String auth){ this.stdNum=stdNum; this.email=email; this.password=<PASSWORD>; this.name=name; this.nickname=nickname; this.imagePath=imagePath; this.imageKey=imageKey; this.imageFilename=imageFilename; this.token=token; this.auth=auth; } } <file_sep>/src/main/java/kr/healthcare/timemanagerapi/controller/admin/CounselingMngController.java package kr.healthcare.timemanagerapi.controller.admin; import kr.healthcare.timemanagerapi.constant.ResponseFailMessage; import kr.healthcare.timemanagerapi.domain.consulting.manage.CounselingManageEntity; import kr.healthcare.timemanagerapi.domain.consulting.manage.CounselingManageRepository; import kr.healthcare.timemanagerapi.domain.member.MemberEntity; import kr.healthcare.timemanagerapi.domain.member.MemberRepositroy; import kr.healthcare.timemanagerapi.dto.admin.CounselingMngDTO; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.time.LocalDate; @RestController @AllArgsConstructor @RequestMapping("/api/admin") public class CounselingMngController { @NonNull MemberRepositroy memberRepositroy; @NonNull CounselingManageRepository counselingManageRepository; @PostMapping("/counseling/register") public ResponseEntity counselingRegister(@Valid @RequestBody CounselingMngDTO.counselingRegisterRequest counselingRegisterRequest, BindingResult bindingResult, @RequestHeader(value = "Authentication") String token){ CounselingMngDTO.counselingRegisterResponse response = new CounselingMngDTO.counselingRegisterResponse(); if(bindingResult.hasErrors()){ response.setResultCode(ResponseFailMessage.FAIL.toString()); response.setResultMessage(bindingResult.getAllErrors().get(0).getDefaultMessage()); return new ResponseEntity<CounselingMngDTO.counselingRegisterResponse>(response, HttpStatus.OK); }else{ MemberEntity memberEntity = memberRepositroy.findByToken(token); CounselingManageEntity counselingManageEntity = CounselingManageEntity .builder() .adminNum(memberEntity.getStdNum()) .semester(counselingRegisterRequest.getSemester()) .startDate(LocalDate.parse(counselingRegisterRequest.getStartDate())) .endDate(LocalDate.parse(counselingRegisterRequest.getEndDate())) .member(memberEntity) .build(); counselingManageRepository.save(counselingManageEntity); response.setResultCode(ResponseFailMessage.SUCCESS.toString()); return new ResponseEntity<CounselingMngDTO.counselingRegisterResponse>(response, HttpStatus.OK); } } }
6baa3d19737d9ca24ec51107501bebca401377c5
[ "Java" ]
7
Java
hongji3354/time-manager-api-server
9e3b8509a6f1e0908807efd29dc0dc38b687b7a7
76eabd9d613b5664194f170e335a49d1deb3995f
refs/heads/master
<repo_name>mkhemir/immobilier<file_sep>/audit-service/src/main/java/com/immoapp/audits/enums/TypePinel.java package com.immoapp.audits.enums; import com.immoapp.audits.utile.PinelConstants; public enum TypePinel { PINEL6ANS(PinelConstants.duree6), PINEL9ANS(PinelConstants.duree9), PINEL12ANS(PinelConstants.duree12); private int duree; private TypePinel(int duree) { this.duree = duree; } public int getDiscount() { switch (this) { case PINEL6ANS: return PinelConstants.discount12; case PINEL9ANS: return PinelConstants.discount18; case PINEL12ANS: return PinelConstants.discount21; default: return 0; } } public int getDuree(){ return this.duree; } } <file_sep>/audit-service/src/main/docker/Dockerfile FROM openjdk:8-jre-alpine RUN apk update && apk upgrade && apk add netcat-openbsd RUN mkdir -p /usr/local/auditservice ADD @project.build.finalName@.jar /usr/local/auditservice/ ADD run.sh run.sh RUN chmod +x run.sh CMD ./run.sh <file_sep>/db-service/src/main/java/com/immoapp/db/controllers/ProduitImmobilierController.java package com.immoapp.db.controllers; import com.immoapp.db.dtos.ProduitImmobilierDTO; import com.immoapp.db.services.ProduitImmobilierService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class ProduitImmobilierController { @Autowired ProduitImmobilierService produitImmobilierService; private static final Logger logger = LoggerFactory.getLogger(ProduitImmobilierController.class); @CrossOrigin @GetMapping({"/produits"}) public List<ProduitImmobilierDTO> findAll(){ return produitImmobilierService.findAllProducts(); } @PostMapping({"/ajout"}) public void addProduct(@RequestBody ProduitImmobilierDTO produitImmobilierDTO){ produitImmobilierService.saveProduct(produitImmobilierDTO); } @CrossOrigin @GetMapping({"/produit/{id}"}) public ProduitImmobilierDTO findProduit(@PathVariable(value = "id") Long id){ logger.info("///////////////////.............................. db a recu l'appel : "+id); ProduitImmobilierDTO p= produitImmobilierService.getProduitImmobilier(id); logger.info("/////////////////// retournr : "+p); return p; } } <file_sep>/db-service/src/main/java/com/immoapp/db/services/ProduitImmobilierService.java package com.immoapp.db.services; import com.immoapp.db.dtos.ProduitImmobilierDTO; import com.immoapp.db.models.ImageProduit; import com.immoapp.db.models.ProduitImmobilier; import com.immoapp.db.repository.ProduitImmobilierRepository; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @Service public class ProduitImmobilierService { @Autowired ProduitImmobilierRepository produitImmobilierRepository; @Autowired ModelMapper modelMapper; private static final Logger logger = LoggerFactory.getLogger(ProduitImmobilierService.class); public List<ProduitImmobilierDTO> findAllProducts() { return StreamSupport.stream(produitImmobilierRepository.findAll().spliterator(), false) .map(p -> modelMapper.map(p, ProduitImmobilierDTO.class)) .collect(Collectors.toList()); } public void saveProduct(ProduitImmobilierDTO produitImmobilierDTO){ ProduitImmobilier produitImmobilier = modelMapper.map(produitImmobilierDTO , ProduitImmobilier.class); /* produitImmobilier.setImages(new ArrayList<ImageProduit>()); Arrays.stream(produitImmobilierDTO.getFiles()).forEach(f -> { ImageProduit image = new ImageProduit(); image.setName(f.getName()); try { image.setFile(f.getBytes()); } catch (IOException e){}; produitImmobilier.getImages().add(image); });*/ produitImmobilierRepository.save(produitImmobilier); } public ProduitImmobilierDTO getProduitImmobilier(long id){ ProduitImmobilier produitImmobilier = produitImmobilierRepository.findById(id); logger.info("++++++++++++++"+produitImmobilier.getAdresse()); return modelMapper.map(produitImmobilier , ProduitImmobilierDTO.class); } } <file_sep>/audit-service/src/main/java/com/immoapp/audits/dtos/ResultatLoiPinel6DTO.java package com.immoapp.audits.dtos; public class ResultatLoiPinel6DTO extends ResultatLoiPinelDTO { } <file_sep>/audit-service/src/main/java/com/immoapp/audits/utile/PinelConstants.java package com.immoapp.audits.utile; public class PinelConstants { public final static int duree6 = 6; public final static int duree9 = 9; public final static int duree12 = 12; public final static int discount12 = 12; public final static int discount18 = 18; public final static int discount21 = 21; public final static int COEF_PINEL_MULP = 19; public final static double COEF_PINEL_ADDITIF = 0.7; public final static int surfaceAnnexMax = 8; public final static double COEF_MULT_MAX = 1.2; public final static double BAREME_PINEL_A = 12.59; // TO INSERT IN DATABASE public final static double TAEG = 0.015; public final static double COEF_ASS = 0.0025; public final static double COEFF_FN = 0.025; public final static int DEFAULT_DUREE_CREDIT = 300; public final static double COEFF_APPORT_DEFAULT = 0.1; public final static int NBR_ANNEE = 5; } <file_sep>/produit-immobilier-service/src/main/java/com/immoapp/produit/controllers/ProduitImmobilierController.java package com.immoapp.produit.controllers; import com.immoapp.produit.dtos.ProduitImmobilierDTO; import com.immoapp.produit.dtos.Search; import com.immoapp.produit.services.DbService; import com.immoapp.produit.services.ProduitImmobilierService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class ProduitImmobilierController { @Autowired ProduitImmobilierService produitImmobilierService; @Autowired DbService dbService; private static final Logger logger = LoggerFactory.getLogger(ProduitImmobilierController.class); @PostMapping(value = "/produits",consumes = {"text/plain;charset=UTF-8", MediaType.APPLICATION_JSON_VALUE}) @CrossOrigin(origins = "*", allowedHeaders = "*") public Search welcome(@RequestBody Search search){ logger.info("...................................................CONTROLLER PRODUITIMMOBILIERSERVICE CA PASSE"); int page = 1; int pageSize = 10; List<ProduitImmobilierDTO> result = dbService.getProduitImmobilier(); ProduitImmobilierDTO[] array = result.toArray(new ProduitImmobilierDTO[result.size()]); search.setResult(array); return search; } @PostMapping(value = "/ajout") @CrossOrigin(origins = "*", allowedHeaders = "*") public void saveProduct(@RequestBody ProduitImmobilierDTO produitImmobilierDTO){ logger.info("++++++++++++++++++++++++++++++++++++++++++++reaching it"); dbService.saveProduitImmobilier(produitImmobilierDTO); } } <file_sep>/audit-service/src/main/java/com/immoapp/audits/utile/MalrauxConstants.java package com.immoapp.audits.utile; public class MalrauxConstants { public final static double TAUX_PSMV= 0.3; public final static double TAUX_PVAP = 0.22; public final static int DUREE_TRAVAUX_MAX = 4; } <file_sep>/optimisation-fiscale-service/src/main/java/com/immoapp/tax/controllers/BanqueController.java package com.immoapp.tax.controllers; import com.immoapp.tax.dtos.InformationBanqueDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class BanqueController { private static final Logger logger = LoggerFactory.getLogger(BanqueController.class); @CrossOrigin(origins = "*", allowedHeaders = "*") @GetMapping(value = "/banques") public List<InformationBanqueDTO> getImmobilierMessage() { List<InformationBanqueDTO> listBanques = new ArrayList<>(); InformationBanqueDTO informationBanqueDTO = new InformationBanqueDTO(); informationBanqueDTO.setNom("SOCIETE GENERALE"); informationBanqueDTO.setTaeg(0.015); listBanques.add(informationBanqueDTO); return listBanques; } } <file_sep>/audit-service/src/main/java/com/immoapp/audits/dtos/ResultatBouvardDTO.java package com.immoapp.audits.dtos; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ResultatBouvardDTO { private double montantTvaRecuperee; private double EconomyImpots; private double effortEpargne; private double effortEpargneTvaIncluse; } <file_sep>/audit-service/src/main/java/com/immoapp/audits/calculs/LoiDfCalcul.java package com.immoapp.audits.calculs; import com.immoapp.audits.dtos.DeficitFoncierDTO; import com.immoapp.audits.utile.CommonConstants; public class LoiDfCalcul { private double reportSurRevenus; private double tmi; public LoiDfCalcul(double salaire) { this.tmi = CommonConstants.getTmi(salaire); } public Double calculerDeficitFoncier(double revenusLoyer, double interetEmprunt, double chargesNonFinanciere) { if ((revenusLoyer - interetEmprunt - chargesNonFinanciere) > 0) { return calculerDfCase1(revenusLoyer, interetEmprunt, chargesNonFinanciere); } else if ((revenusLoyer - interetEmprunt) > 0 && (revenusLoyer - interetEmprunt - chargesNonFinanciere) <= 0 && (revenusLoyer - interetEmprunt - chargesNonFinanciere) >= -10700) { return calculerDfCase2(revenusLoyer, interetEmprunt, chargesNonFinanciere); } else if ((revenusLoyer - interetEmprunt) <= 0 && (revenusLoyer - interetEmprunt - chargesNonFinanciere) >= -10700) { return calculerDfCase3(revenusLoyer, interetEmprunt, chargesNonFinanciere); } else if ((revenusLoyer - interetEmprunt) > 0 && (revenusLoyer - interetEmprunt - chargesNonFinanciere) < -10700) { return calculerDfCase4(revenusLoyer, interetEmprunt, chargesNonFinanciere); } else { return null; } } public double calculerDfCase1(double revenusLoyer, double interetEmprunt, double chargesNonFinanciere) { if ((chargesNonFinanciere + interetEmprunt + this.reportSurRevenus) < revenusLoyer) { double oldRevenusFoncier = this.reportSurRevenus; this.reportSurRevenus = 0; return (this.tmi + CommonConstants.PRELEVEMENT_SOCIAUX) * oldRevenusFoncier; } else { this.reportSurRevenus = interetEmprunt + chargesNonFinanciere + this.reportSurRevenus - revenusLoyer; return (this.tmi + CommonConstants.PRELEVEMENT_SOCIAUX) * (interetEmprunt + chargesNonFinanciere - revenusLoyer); } } public double calculerDfCase2(double revenusLoyer, double interetEmprunt, double chargesNonFinanciere) { return (revenusLoyer - chargesNonFinanciere - interetEmprunt) * this.tmi; } public double calculerDfCase3(double revenusLoyer, double interetEmprunt, double chargesNonFinanciere) { this.reportSurRevenus += interetEmprunt - revenusLoyer; return chargesNonFinanciere * this.tmi; } public double calculerDfCase4(double revenusLoyer, double interetEmprunt, double chargesNonFinanciere) { double deficit = chargesNonFinanciere + interetEmprunt - revenusLoyer; this.reportSurRevenus += deficit - 10700; return 10700 * this.tmi; } } <file_sep>/audit-service/src/main/java/com/immoapp/audits/dtos/AdresseDTO.java package com.immoapp.audits.dtos; import lombok.Getter; import lombok.Setter; @Getter @Setter public class AdresseDTO { /** * THE PRODUCT ADDRESS. */ private String adresse; private String codePostal; private String ville; private boolean estSitePSMV; private boolean estSitePVAR; } <file_sep>/audit-service/src/main/java/com/immoapp/audits/services/AuditService.java package com.immoapp.audits.services; import com.immoapp.audits.calculs.*; import com.immoapp.audits.dtos.*; import com.immoapp.audits.enums.LoyerEstimation; import com.immoapp.audits.enums.TypePinel; import com.immoapp.audits.utile.CommonConstants; import com.immoapp.audits.utile.PinelConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class AuditService { @Autowired OptimisationFiscaleService optimisationFiscaleService; private double taeg; private LoiLmnpCalcul lmnpCalcul; public AuditService() { this.lmnpCalcul = new LoiLmnpCalcul(); } public ResultatLoiPinelDTO getPinel(TypePinel typePinel, ProduitImmobilierDTO p, Double apport, Integer dureeCredit, Double taeg) { ResultatLoiPinelDTO resultatLoiPinelDTO = new ResultatLoiPinelDTO(); LoiPinelCalcul loiPinelCalcul = new LoiPinelCalcul(); resultatLoiPinelDTO.setLoyerMaximum(loiPinelCalcul.calculerLoyerMax(p)); resultatLoiPinelDTO.setReductionImpots(loiPinelCalcul.calculerReductionImpots(p, typePinel).doubleValue()); resultatLoiPinelDTO.setMontantEmprunt(loiPinelCalcul.calculerMontantEmprunt(p.getPrix().doubleValue(), apport)); resultatLoiPinelDTO.setEconomyImpots(loiPinelCalcul.calculerEconomieImpot(p.getPrix().doubleValue(), typePinel, PinelConstants.NBR_ANNEE)); resultatLoiPinelDTO.setMensualiteCredit(loiPinelCalcul.calculerMensulaiteCredit(resultatLoiPinelDTO.getMontantEmprunt(), dureeCredit, checkTaeg(taeg))); resultatLoiPinelDTO.setFraisAnnexe(loiPinelCalcul.calculerFraisAnnexes(p)); resultatLoiPinelDTO.setEffortEpargne(loiPinelCalcul.calculerEffortEpargne(p, typePinel, dureeCredit, apport, checkTaeg(taeg), PinelConstants.NBR_ANNEE)); return resultatLoiPinelDTO; } public ResultatBouvardDTO getBouvard(ProduitImmobilierDTO produitImmobilierDTO, Integer dureeCredit, double taeg) { LoiBouvardCalcul loiBouvardCalcul = new LoiBouvardCalcul(); ResultatBouvardDTO resultatBouvardDTO = new ResultatBouvardDTO(); resultatBouvardDTO.setEconomyImpots(loiBouvardCalcul.calculerEconomyImpots(produitImmobilierDTO.getPrix().doubleValue())); resultatBouvardDTO.setMontantTvaRecuperee(loiBouvardCalcul.calculerTvaRecuperee(produitImmobilierDTO.getPrix().doubleValue())); resultatBouvardDTO.setEffortEpargne(loiBouvardCalcul.calculerEffortEpagne(produitImmobilierDTO, dureeCredit, checkTaeg(taeg))); resultatBouvardDTO.setEffortEpargneTvaIncluse(loiBouvardCalcul.calculerEffortEpagne(produitImmobilierDTO, dureeCredit, checkTaeg(taeg))); return resultatBouvardDTO; } public ResultatLmnpDto getLmnpReel(ProduitImmobilierDTO produitImmobilierDTO) { return lmnpCalcul.getRegimeReel(produitImmobilierDTO.getLoyerEstime() != 0 ? produitImmobilierDTO.getLoyerEstime() : LoyerEstimation.getLoyer(produitImmobilierDTO.getNbrPiece()), produitImmobilierDTO.getPrix().doubleValue(), checkTaeg(this.taeg)); } public ResultatLmnpDto getLmnpMicro(ProduitImmobilierDTO produitImmobilierDTO) { return lmnpCalcul.getRegimeMicro(produitImmobilierDTO.getLoyerEstime() != 0 ? produitImmobilierDTO.getLoyerEstime() : LoyerEstimation.getLoyer(produitImmobilierDTO.getNbrPiece()), produitImmobilierDTO.getPrix().doubleValue(), checkTaeg(this.taeg)); } public ResultatMalrauxDTO getMalraux(ProduitImmobilierDTO produitImmobilierDTO, int duree, double taeg) { LoiMalrauxCalcul loiMalraux = new LoiMalrauxCalcul(); return loiMalraux.calculerLoiMalraux(produitImmobilierDTO, duree, taeg); } public ResultatMhDTO getMh(ProduitImmobilierDTO produitImmobilierDTO, int duree, double taeg, double salaire) { LoiMhCalcul loiMh = new LoiMhCalcul(); return loiMh.calculerLoiMh(produitImmobilierDTO, duree, taeg, salaire); } public DeficitFoncierDTO getDeficitFincier(ProduitImmobilierDTO produitImmobilierDTO){ DeficitFoncierDTO deficitFoncierDTO = new DeficitFoncierDTO(); LoiDfCalcul loiDf = new LoiDfCalcul(CommonConstants.SALAIRE_DEFAUT); Map<Integer, Double> mapDeficits = new HashMap<>(); int currentYear = CommonConstants.getCurrentYear(); deficitFoncierDTO.setChargesNonFinanciere(CommonConstants.getChargesNonFinancieres(produitImmobilierDTO)); deficitFoncierDTO.setInteretEmprunt(CommonConstants.getInteretEmprunt(produitImmobilierDTO)); deficitFoncierDTO.setRevenusLoyer(CommonConstants.estimerMontantLoyer(produitImmobilierDTO) * 12); for (int i = currentYear; i < currentYear +5 ; i++ ){ mapDeficits.put(i, loiDf.calculerDeficitFoncier(deficitFoncierDTO.getRevenusLoyer(), deficitFoncierDTO.getInteretEmprunt(), deficitFoncierDTO.getChargesNonFinanciere())); } deficitFoncierDTO.setGainImpots(mapDeficits); return deficitFoncierDTO; } private double checkTaeg(double taeg){ this.taeg = taeg; if(this.taeg == 0){ this.taeg = 1.5;//optimisationFiscaleService.getInfoBanques().stream().findFirst().get().getTaeg(); } return this.taeg; } } <file_sep>/audit-service/src/main/java/com/immoapp/audits/dtos/InformationBanqueDTO.java package com.immoapp.audits.dtos; import lombok.Getter; import lombok.Setter; @Getter @Setter public class InformationBanqueDTO { private String nom; private double taeg; } <file_sep>/db-service/src/main/resources/schema.sql DROP TABLE IF EXISTS PRODUIT_IMMOBILIER; CREATE TABLE IF NOT EXISTS PRODUIT_IMMOBILIER ( ID SERIAL NOT NULL , TYPE character varying(100) COLLATE pg_catalog."default", TELEPHONE character varying(50) COLLATE pg_catalog."default", NOMBRE_LOTS smallint, PARKING boolean, ASCENCEUR boolean, NBR_PIECES numeric, NBR_CHAMBRES numeric, DPE "char", CHARGES_COPROP numeric, TAXES_FONCIAIRES character varying COLLATE pg_catalog."default", ANNEE_CONSTRUCTION date, ADRESSE character varying(250) COLLATE pg_catalog."default", CODEPOSTALE numeric, VILLE character varying(100) COLLATE pg_catalog."default", PRIX numeric, SURFACE double precision, SURFACE_BALCON double precision, SURFACE_TERRASSE double precision, SURFACE_VERANDAS double precision, SURFACE_SOUS_SOL double precision, SURFACE_CAVE double precision, SURFACE_LOGIAS double precision, AUTRE_SURFACE_ANNEXE double precision, LOYER_ESTIME numeric, CONSTRAINT "PRODUIT_IMMOBILIER_pkey" PRIMARY KEY (ID) ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; ALTER TABLE PRODUIT_IMMOBILIER OWNER to postgres; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (1, 'APPARTEMENT NEUF', '065646847',3,TRUE, TRUE, 4 ,3, 'A',4300,'11%','01-01-2020','blvd <NAME>',94800, 'VILLEJUIF', 340000, 54, 6, 4 , null , null, 4 , 6, null,1500) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (2, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','rue de la lune',93900, 'Noisy le grand', 310000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (3, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','rue de la caverne',92900, 'Noisy le grand', 340000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (4, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','rue de la citadelle',75005, 'Paris', 760000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (5, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','rue de la peste',750018, 'Paris', 810000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (6, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','rue de la meduse',750010, 'Paris', 790000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (7, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','10 rue de la chapelle',750020, 'Paris', 870000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (8, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','10 rue de la lune',750019, 'Paris', 710000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (9, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','10 rue du canabis',750020, 'Paris', 650000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; INSERT INTO PRODUIT_IMMOBILIER (ID , TYPE, TELEPHONE, NOMBRE_LOTS, PARKING, ASCENCEUR ,NBR_PIECES, NBR_CHAMBRES , DPE , CHARGES_COPROP , TAXES_FONCIAIRES, ANNEE_CONSTRUCTION , ADRESSE , CODEPOSTALE, VILLE,PRIX, SURFACE, SURFACE_BALCON,SURFACE_TERRASSE, SURFACE_VERANDAS, SURFACE_SOUS_SOL, SURFACE_CAVE, SURFACE_LOGIAS, AUTRE_SURFACE_ANNEXE, LOYER_ESTIME) VALUES (10, 'APPARTEMENT NEUF', '078646817',3,TRUE, TRUE, 3 ,2, 'A',3800,'11%','01-01-2021','chatelet',750001, 'Paris', 980000, 50, 6, 4 , null , null, 4 , 6, null,1200) ON CONFLICT (ID) DO NOTHING; commit; <file_sep>/audit-service/src/main/java/com/immoapp/audits/dtos/ResultatLmnpDto.java package com.immoapp.audits.dtos; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ResultatLmnpDto { private double loyerAnnuel; private double amortissementImmobilier; private double amortissementMobilier; private double InteretEmprunt; private double autresCharges; private double abbatement50; private double impots; private double totalCharges; private double totalImpots; private double Resultat; private double effort; } <file_sep>/audit-service/src/main/java/com/immoapp/audits/utile/LmnpConstants.java package com.immoapp.audits.utile; public class LmnpConstants { public final static double COUT_MOBILIER = 5000; public final static double COEFF_VALEUR_TERRAIN = 0.15; public final static double DUREE_MOBILIER = 5; public final static double AUTRES_CHARGES = 500; public final static double COEFF_CSG = 0.15; public final static double TAUX_IMPOSITION = 0.3; } <file_sep>/produit-immobilier-service/src/main/java/com/immoapp/produit/Application.java package com.immoapp.produit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication @EnableEurekaClient public class Application { @Bean public RestTemplate getRestTemplate(){ RestTemplate template = new RestTemplate(); return template; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS") .allowedHeaders("x-requested-with", "Content-Type", "accept", "Authorization") .exposedHeaders("Authorization") .allowCredentials(true); } }; } } <file_sep>/produit-immobilier-service/src/main/docker/Dockerfile FROM openjdk:8-jre-alpine RUN apk update && apk upgrade && apk add netcat-openbsd RUN mkdir -p /usr/local/produitimmobilierservice ADD @project.build.finalName@.jar /usr/local/produitimmobilierservice/ ADD run.sh run.sh RUN chmod +x run.sh CMD ./run.sh<file_sep>/optimisation-fiscale-service/src/main/java/com/immoapp/tax/dtos/DossierPinelDTO.java package com.immoapp.tax.dtos; public class DossierPinelDTO { } <file_sep>/audit-service/src/main/java/com/immoapp/audits/dtos/ResultatLoiPinelDTO.java package com.immoapp.audits.dtos; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; @Getter @Setter public class ResultatLoiPinelDTO { private double loyerMaximum; private double reductionImpots; private double montantEmprunt; private double economyImpots; private double mensualiteCredit; private double fraisAnnexe; private double effortEpargne; }
caf6bfdecf558d4b12af241685d3ffff1ce77244
[ "Java", "Dockerfile", "SQL" ]
21
Java
mkhemir/immobilier
7102599836d1aee2c22cf6bcc43217e4394f1969
e6c4df5d8ba1c7025c2bd343fc0091b791b87fbd
refs/heads/main
<file_sep>import React from "react" import "./styles.scss" import Logo from "./../../assets/chelsea-logo.webp" const Header = (props) => { return ( <header className="header"> <div className="wrap"> <div className="logo"> <img src={Logo} alt="Chelsea LOGO" /> </div> <div className="logotext">The Unofficial Online Store</div> </div> </header> ) } export default Header
9ac07a7dbfa1d55b98d307f75bb9e5fcefb824a7
[ "JavaScript" ]
1
JavaScript
solveproblemswithcode/react-webshop
c08ec3cc178256d5f8fb8618641918ebdfb33700
371dbbb80624dadc96bb4ce475329f349c21ea36
refs/heads/master
<repo_name>hfxjd9527/go-shortlink<file_sep>/hanlders.go package main import ( "encoding/json" "fmt" "net/http" "shortlink/utils" "github.com/gorilla/mux" "gopkg.in/go-playground/validator.v9" ) //ShortRequest for request: url, expiration_in_minutes type ShortRequest struct { URL string `json:"url" validate:"required"` ExpirationInMinutes int64 `json:"expiration_in_minutes" validate:"min=0"` } //ShortlinkRequest :shortlink type ShortlinkRequest struct { Shortlink string `json:"shortlink"` } func (a *App) createShortLink(w http.ResponseWriter, r *http.Request) { var req ShortRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { respondWithError(w, utils.StatusError{Code: http.StatusBadRequest, Err: fmt.Errorf("json decode err %v", r.Body)}) return } validate := validator.New() if err := validate.Struct(req); err != nil { respondWithError(w, utils.StatusError{Code: http.StatusBadRequest, Err: fmt.Errorf("json validate err %v", req)}) return } defer r.Body.Close() s, err := a.Config.S.Shorten(req.URL, req.ExpirationInMinutes) if err != nil { respondWithError(w, err) } else { respondWithJSON(w, http.StatusCreated, ShortlinkRequest{Shortlink: s}) } } func (a *App) getShortLinkInfo(w http.ResponseWriter, r *http.Request) { url := r.URL.Query() s := url.Get("shortlink") d, err := a.Config.S.ShortLinkInfo(s) if err != nil { respondWithError(w, err) } else { respondWithJSON(w, http.StatusOK, d) } } func (a *App) redirect(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) u, err := a.Config.S.Unshorten(vars["shortlink"]) if err != nil { respondWithError(w, err) } else { http.Redirect(w, r, u, http.StatusTemporaryRedirect) return } } <file_sep>/app.go package main import ( "log" "net/http" "shortlink/middleware" "github.com/gorilla/mux" "github.com/justinas/alice" ) //App ... type App struct { Router *mux.Router Middlewares *middleware.Middleware Config *Env } //Initialize ... func (a *App) Initialize(e *Env) { log.SetFlags(log.LstdFlags | log.Lshortfile) a.Config = e a.Router = mux.NewRouter() a.Middlewares = &middleware.Middleware{} a.InitializeRoter() } //InitializeRoter ... func (a *App) InitializeRoter() { m := alice.New(a.Middlewares.LoggingHanlder, a.Middlewares.RecoverHanlder) a.Router.Handle("/api/shorten", m.ThenFunc(a.createShortLink)).Methods("POST") a.Router.Handle("/api/info", m.ThenFunc(a.getShortLinkInfo)).Methods("GET") a.Router.Handle("/{shortlink:[a-zA-Z0-9]{1,11}}", m.ThenFunc(a.redirect)).Methods("GET") } //Run ... func (a *App) Run(addr string) { log.Fatal(http.ListenAndServe(addr, a.Router)) } <file_sep>/middleware/recover.go package middleware import ( "log" "net/http" ) //RecoverHanlder recover for panic func (m Middleware) RecoverHanlder(h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { defer func () { if err := recover(); err != nil { log.Printf("recover from panic %v", err) http.Error(w, http.StatusText(500),500) } }() h.ServeHTTP(w, r) } return http.HandlerFunc(fn) }<file_sep>/README.md # go-shortlink ### clone 本项目 ``` git clone https://github.com/hiningmeng/go-shortlink.git shortlink ``` - 创建短链接口: http://127.0.0.1:8000/api/shorten ``` { "url": "http://www.hiningmeng.cn", "expiration_in_minutes": 30 } ``` - 短链详细信息:http://127.0.0.1:8000/api/info?shortlink=1 - 短链跳转真实长链地址: http://127.0.0.1:8000/1 <file_sep>/env.go package main import ( "shortlink/api" "shortlink/utils" ) //Env ... type Env struct { S api.Storage } func getEnv() *Env { r := utils.NewRedisCli("10.40.0.200:6379", "", 1) return &Env{S: r} } <file_sep>/api/storage.go package api //Storage : utils.RedisCli have the method ,so is the interface type Storage interface { Shorten(url string, exp int64) (string, error) ShortLinkInfo(eid string) (interface{}, error) Unshorten(eid string) (string, error) }
0eae67ddcd6e3c6d28a6e7aeb19c773a03f15487
[ "Markdown", "Go" ]
6
Go
hfxjd9527/go-shortlink
e125e0d1df66f2828102b465203d52231304bd84
1751e259282ef2af7a7e41e4303d355e613bf87a
refs/heads/master
<repo_name>HacxS/Chat-App<file_sep>/chat/migrations/0003_auto_20200808_0045.py # Generated by Django 2.2.2 on 2020-08-07 19:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ('chat', '0002_auto_20200807_2018'), ] operations = [ migrations.CreateModel( name='SingleChatMessage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('is_media', models.BooleanField(default=False)), ('message', models.TextField(blank=True, default='', max_length=65000)), ('timestamp', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], ), migrations.AlterField( model_name='chatmessagemedia', name='media_url', field=models.FileField(upload_to='uploads/chatmedia/'), ), migrations.CreateModel( name='SingleChatRoom', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('is_blocked', models.BooleanField(default=False)), ('timestamp', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('blocked_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blocked_by', to='accounts.UserInfo')), ('fuser', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='first_user', to='accounts.UserInfo')), ('suser', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='second_user', to='accounts.UserInfo')), ], ), migrations.CreateModel( name='SingleChatMessageMedia', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('media_url', models.FileField(upload_to='uploads/schatmedia/')), ('chatm', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat.SingleChatMessage')), ], ), migrations.AddField( model_name='singlechatmessage', name='croom', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat.SingleChatRoom'), ), migrations.AddField( model_name='singlechatmessage', name='cuser', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.UserInfo'), ), ] <file_sep>/chat/migrations/0001_initial.py # Generated by Django 2.2.2 on 2020-08-07 14:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.CreateModel( name='ChatMessage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('is_media', models.BooleanField(default=False)), ('message', models.TextField(blank=True, default='', max_length=65000)), ('timestamp', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='ChatRoom', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('room_name', models.CharField(max_length=65000)), ('timestamp', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('room_admin', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.UserInfo')), ], ), migrations.CreateModel( name='ChatUserInRoom', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('croom', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat.ChatRoom')), ('cuser', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.UserInfo')), ], ), migrations.CreateModel( name='ChatMessageMedia', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('media_url', models.FileField(upload_to='uplaods/chatmedia/')), ('chatm', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat.ChatMessage')), ], ), migrations.AddField( model_name='chatmessage', name='croom', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='chat.ChatRoom'), ), migrations.AddField( model_name='chatmessage', name='cuser', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.UserInfo'), ), ] <file_sep>/chat/consumers.py from django.contrib.auth import get_user_model from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json from django.conf import settings import time class ChatConsumer(WebsocketConsumer): def connect(self): if self.scope["user"].is_anonymous: self.accept() self.send(json.dumps({ "status": "error", 'message': f"Please authenticate by passing token in GET method" })) time.sleep(10) self.close() else: self.group_name = str(self.scope["user"].pk) async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name) self.accept() self.send(json.dumps({ "status": "success", 'message': f"Hey {self.scope['user'].username}, Welcome To Chat" })) def disconnect(self, close_code): self.close() def send_message(self, event): self.send(text_data=json.dumps({"status": "success","command": "new_message","type": event["message_type"], "data": event["text"]})) def delete_message(self,event): self.send(text_data=json.dumps({"status": "success","command": "deleted_message","type": event["message_type"], "deleted_id": event["text"]})) <file_sep>/chat/migrations/0002_auto_20200807_2018.py # Generated by Django 2.2.2 on 2020-08-07 14:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ('chat', '0001_initial'), ] operations = [ migrations.AlterUniqueTogether( name='chatuserinroom', unique_together={('croom', 'cuser')}, ), ] <file_sep>/chat/admin.py from django.contrib import admin from chat.models import ChatUserInRoom admin.site.register(ChatUserInRoom)
7592fabc2b0a2e311058b80f80d5d3746f015f59
[ "Python" ]
5
Python
HacxS/Chat-App
60640dc805be1a2047ae374153b26cd22f4a42dd
0b153e1942e35b3fd798a1c3d528b85b0e71d35b
refs/heads/master
<repo_name>luthita/Deli_project_210901<file_sep>/src/main/java/com/luthita/user/dao/UserDAO.java package com.luthita.user.dao; import org.springframework.stereotype.Repository; import com.luthita.user.model.User; @Repository public interface UserDAO { public User selectUserByLoginId(String loginId); } <file_sep>/README.md # Deli_project(배달 앱 PC 버전) #### Spring Boot 를 사용한 개인 프로젝트입니다. startDate : 2021/09/01 (~ 진행중) * 프로젝트 기획서 * [일정/기획 Link!](https://docs.google.com/spreadsheets/d/1QjXubuThmLomBp4M6U_rc2xGJV8dZ16J1i2C2SKwbBw/edit#gid=2054002035, "프로젝트 기획서") * 프로젝트 DB 설계 * [DB 설계 Link!](https://docs.google.com/spreadsheets/d/1QjXubuThmLomBp4M6U_rc2xGJV8dZ16J1i2C2SKwbBw/edit#gid=1368487158, "DB 설계") * 프로젝트 URL 설계 * [URL 설계 Link!](https://docs.google.com/spreadsheets/d/1QjXubuThmLomBp4M6U_rc2xGJV8dZ16J1i2C2SKwbBw/edit#gid=606285945, "URL 설계") * 프로젝트 프로토타이핑 * [화면 정의 Link!](https://ovenapp.io/view/j7fKK6JcomnQl3GcgcwKNDQ5509fwhbl/,"프로토타이핑") <hr> <file_sep>/settings.gradle rootProject.name = 'Delieats' <file_sep>/src/main/java/com/luthita/DelieatsApplication.java package com.luthita; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DelieatsApplication { public static void main(String[] args) { SpringApplication.run(DelieatsApplication.class, args); } } <file_sep>/src/main/java/com/luthita/test/dao/TestDAO.java package com.luthita.test.dao; import java.util.List; import com.luthita.test.model.Like; public interface TestDAO { public List<Like> selectLikeList(); }
b84624f68156ff8cb18918a308557ae079a94f57
[ "Markdown", "Java", "Gradle" ]
5
Java
luthita/Deli_project_210901
36c2326e1b32e8c08d9310441f9f8dea2916477d
d2a82a9945bf7194cd0ceb1c9036d66a964eefba
refs/heads/master
<repo_name>m1771vw/FAQPlayground<file_sep>/js/javascript_wilb.js // Script to read the JSOn $.getJSON("faq.json", function(data){ $.each(data.posts, function(i ,data){ // u needed to create the outer div with class 'faq' to trigger line 22’s if statement, otherwise // it would go to line 26 because there was no parent that had class 'open' var faq = "<div class='faq'><div class='faq_question'>" + data.title + "</div><div class='faq_answer_container'>" +"<div class='faq_answer'>" + data.answer + "</div></div></div>"; // $(faq).appendTo(".faq_container"); console.log('asdf'); $('.faq_container').append(faq); }); }); // Script to animate the FAQ // $(document).ready(function() { // $('.faq_question').click(function() { // console.log("FAQ Question was clicked"); // if ($(this).parent().is('.open')){ // $(this).closest('.faq').find('.faq_answer_container').animate({'height':'0'},500); // $(this).closest('.faq').removeClass('open'); // }else{ // var newHeight =$(this).closest('.faq').find('.faq_answer').height() +'px'; // $(this).closest('.faq').find('.faq_answer_container').animate({'height':newHeight},500); // $(this).closest('.faq').addClass('open'); // } // }); // }); // you need to use this syntax (instead of $('.faq_question').click(function(){blah} // because that doesnt work on dynamically created elements // so u need to do $(document).on(event, selector, function(){}) // instead. $(document).on('click', '.faq_question', function(e){ console.log(this); if ($(this).parent().is('.open')){ console.log('1'); $(this).closest('.faq').find('.faq_answer_container').animate({'height':'0'},500); $(this).closest('.faq').removeClass('open'); }else{ console.log('2'); var newHeight =$(this).closest('.faq').find('.faq_answer').height() +'px'; $(this).closest('.faq').find('.faq_answer_container').animate({'height':newHeight},500); $(this).closest('.faq').addClass('open'); } } ); <file_sep>/README.md # FAQPlayground Playground for creating an FAQ Webpage
4d9ed6ab3745061cd3d4d11e15ce7374544fd153
[ "JavaScript", "Markdown" ]
2
JavaScript
m1771vw/FAQPlayground
221581592afba99f77026e750ff02c84aaee5be9
0223993a425b8b0b9e969c4b5af84e89aacafbe6
refs/heads/master
<repo_name>mrnixe/leetcode-1<file_sep>/src/GroupAnagrams.cpp #include "GroupAnagrams.hpp" #include <unordered_map> #include <algorithm> using namespace std; vector<vector<string>> GroupAnagrams::groupAnagrams(vector<string>& strs) { vector<vector<string>> ret; unordered_map<string, vector<string>> rec; for (auto s : strs) { string key = s; sort(key.begin(), key.end()); rec[key].push_back(s); } for (auto p : rec) { sort(p.second.begin(), p.second.end()); ret.push_back(p.second); } return ret; } <file_sep>/src/BalancedBinaryTree.cpp #include "BalancedBinaryTree.hpp" #include <algorithm> #include <cstdlib> using namespace std; bool BalancedBinaryTree::isBalanced(TreeNode* root) { if (root == nullptr) { return true; } int leftHeight = depth(root->left); int rightHeight = depth(root->right); if (leftHeight == -1 || rightHeight == -1) { return false; } return abs(leftHeight - rightHeight) <= 1; } int BalancedBinaryTree::depth(TreeNode* root) { if (root == nullptr) { return 0; } int leftHeight = depth(root->left); int rightHeight = depth(root->right); if (leftHeight == -1 || rightHeight == -1) { return -1; } if (abs(leftHeight - rightHeight) > 1) { return -1; } return max(leftHeight, rightHeight) + 1; } <file_sep>/src/UniquePathsII.cpp #include "UniquePathsII.hpp" int UniquePathsII::uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<int> pre(m, 0); vector<int> cur(m, 0); for (int i = 0; i < m; i++) { if (!obstacleGrid[i][0]) { pre[i] = 1; } else { break; } } for (int j = 1; j < n; j++) { if (!obstacleGrid[0][j]) { cur[0] = pre[0]; } else { cur[0] = 0; } for (int i = 1; i < m; i++) { if (!obstacleGrid[i][j]) { cur[i] = cur[i - 1] + pre[i]; } else { cur[i] = 0; } } swap(pre, cur); } return pre[m - 1]; } <file_sep>/src/WildcardMatching.cpp #include "WildcardMatching.hpp" #include <vector> using namespace std; bool WildcardMatching::isMatch(string s, string p) { return isMatch_Greedy(s, p); } bool WildcardMatching::isMatch_DynamicProgramming(string s, string p) { int m = s.size(); int n = p.size(); vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false)); dp[0][0] = true; for (int i = 1; i <= m; i++) { dp[i][0] = false; } for (int j = 1; j <= n; j++) { dp[0][j] = dp[0][j - 1] && p[j - 1] == '*'; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (p[j - 1] != '*') { dp[i][j] = dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?'); } else { dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; } } } return dp[m][n]; } bool WildcardMatching::isMatch_Greedy(string s, string p) { int m = s.size(), n = p.size(); int i = 0, j = 0, asterisk = -1, match; while (i < m) { if (j < n && p[j] == '*') { match = i; asterisk = j++; } else if (j < n && (s[i] == p[j] || p[j] == '?')) { i++; j++; } else if (asterisk >= 0) { i = ++match; j = asterisk + 1; } else { return false; } } while (j < n && p[j] == '*') { j++; } return j == n; } <file_sep>/src/InterleavingString.cpp #include "InterleavingString.hpp" #include <vector> using namespace std; bool InterleavingString::isInterleave(string s1, string s2, string s3) { int sz1 = s1.size(); int sz2 = s2.size(); int sz3 = s3.size(); // fast path if (sz1 + sz2 != sz3) { return false; } vector<vector<bool>> dp(sz1 + 1, vector<bool>(sz2 + 1, false)); dp[0][0] = true; for (int i = 1; i <= sz1; i++) { dp[i][0] = (s1[i - 1] == s3[i - 1]) ? dp[i - 1][0] : false; } for (int j = 1; j <= sz2; j++) { dp[0][j] = (s2[j - 1] == s3[j - 1]) ? dp[0][j - 1] : false; } for (int i = 1; i <= sz1; i++) { for (int j = 1; j <= sz2; j++) { dp[i][j] = ((s1[i - 1] == s3[i + j - 1] && dp[i - 1][j]) || (s2[j - 1] == s3[i + j - 1] && dp[i][j - 1])); } } return dp[sz1][sz2]; } <file_sep>/include/HouseRobberII.hpp #ifndef HOUSE_ROBBER_II_HPP_ #define HOUSE_ROBBER_II_HPP_ #include <vector> using namespace std; class HouseRobberII { public: int rob(vector<int>& nums); private: int helper(vector<int>& nums, int a, int b); }; #endif // HOUSE_ROBBER_II_HPP_ <file_sep>/include/LowestCommonAncestorOfABinaryTree.hpp #ifndef LOWEST_COMMON_ANCESTOR_OF_A_BINARY_TREE_HPP_ #define LOWEST_COMMON_ANCESTOR_OF_A_BINARY_TREE_HPP_ #include "TreeNode.hpp" class LowestCommonAncestorOfABinaryTree { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q); }; #endif // LOWEST_COMMON_ANCESTOR_OF_A_BINARY_TREE_HPP_<file_sep>/include/SymmetricTree.hpp #ifndef SYMMETRIC_TREE_HPP_ #define SYMMETRIC_TREE_HPP_ #include "TreeNode.hpp" class SymmetricTree { public: bool isSymmetric(TreeNode* root); private: bool isSymmetric(TreeNode* l, TreeNode* r); }; #endif // SYMMETRIC_TREE_HPP_ <file_sep>/src/PerfectSquares.cpp #include "PerfectSquares.hpp" #include <vector> #include <queue> using namespace std; int PerfectSquares::numSquares(int n) { queue<int> q; vector<bool> visited(n + 1, false); int level = 0; // initialize the queue and visited vector int d = 1; while (d * d <= n) { if (d * d == n) { return level + 1; } q.push(n - d * d); visited[d * d] = true; d++; } level++; while (!q.empty()) { int sz = q.size(); for (int i = 0; i < sz; i++) { int d = 1; int t = q.front(); q.pop(); while (d * d <= t) { if (d * d == t) { return level + 1; } if (!visited[n - t + d * d]) { q.push(t - d * d); visited[n - t + d * d] = true; } d++; } } level++; } return n; } <file_sep>/src/KthSmallestElementInABST.cpp #include "KthSmallestElementInABST.hpp" int KthSmallestElementInABST::kthSmallest(TreeNode* root, int k) { cnt = 0; result = 0; inOrderSearch(root, k); return result; } void KthSmallestElementInABST::inOrderSearch(TreeNode* root, int k) { if (root == NULL) { return; } inOrderSearch(root->left, k); cnt++; if (cnt == k) { result = root->val; } inOrderSearch(root->right, k); } <file_sep>/tests/TheSkylineProblemTest.cpp #include "catch.hpp" #include "TheSkylineProblem.hpp" TEST_CASE("The Skyline Problem") { TheSkylineProblem s; SECTION("Sample test") { vector<vector<int>> buildings { {2, 9, 10}, {3, 7, 15}, {5, 12, 12}, {15, 20, 10}, {19, 24, 8} }; vector<pair<int, int>> expected { {2, 10}, {3, 15}, {7, 12}, {12, 0}, {15, 10}, {20, 8}, {24, 0} }; vector<pair<int, int>> result = s.getSkyline(buildings); REQUIRE(expected.size() == result.size()); for (int i = 0; i < result.size(); i++) { REQUIRE(result[i].first == expected[i].first); REQUIRE(result[i].second == expected[i].second); } } } <file_sep>/include/InterleavingString.hpp #ifndef INTERLEAVING_STRING_HPP_ #define INTERLEAVING_STRING_HPP_ #include <string> using namespace std; class InterleavingString { public: bool isInterleave(string s1, string s2, string s3); }; #endif // INTERLEAVING_STRING_HPP_ <file_sep>/src/MaximumSubarray.cpp #include "MaximumSubarray.hpp" #include <algorithm> using namespace std; int MaximumSubarray::maxSubArray(vector<int>& nums) { return maxSubArray_Array(nums); } int MaximumSubarray::maxSubArray_DynamicProgramming(vector<int>& nums) { vector<int> dp(nums.size(), 0); dp[0] = nums[0]; int max = nums[0]; for (int i = 1; i < nums.size(); i++) { dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); max = dp[i] > max ? dp[i] : max; } return max; } int MaximumSubarray::maxSubArray_Array(vector<int>& nums) { int max = nums[0]; int maxEnding = nums[0]; for (int i = 1; i < nums.size(); i++) { maxEnding = nums[i] + (maxEnding > 0 ? maxEnding : 0); max = maxEnding > max ? maxEnding : max; } return max; } int MaximumSubarray::maxSubArray_DivideAndConquer(vector<int>& nums) { return helper(nums, 0, nums.size() - 1); } int MaximumSubarray::helper(vector<int>& nums, int left, int right) { if (right == left) { return nums[left]; } int middle = (left + right) / 2; int leftans = helper(nums, left, middle); int rightans = helper(nums, middle + 1, right); int leftmax = nums[middle]; int rightmax = nums[middle + 1]; int temp = 0; for(int i = middle; i >= left; i--) { temp += nums[i]; if(temp > leftmax) { leftmax = temp; } } temp = 0; for(int i = middle + 1; i <= right; i++) { temp += nums[i]; if(temp > rightmax) { rightmax = temp; } } return max(max(leftans, rightans), leftmax + rightmax); }<file_sep>/src/SerializeAndDeserializeBinaryTree.cpp #include "SerializeAndDeserializeBinaryTree.hpp" #include <vector> #include <queue> using namespace std; string Codec::serialize(TreeNode* root) { vector<string> vec; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* node = q.front(); if (node == nullptr) { vec.push_back("null"); } else { vec.push_back(to_string(node->val)); q.push(node->left); q.push(node->right); } q.pop(); } string ret = vec[0]; if (vec.size() == 1) { return ret; } else { for (int i = 1; i < vec.size(); i++) { ret += "," + vec[i]; } } return ret; } TreeNode* Codec::deserialize(string data) { istringstream ss(data); string token; queue<TreeNode*> q; TreeNode* root = fetch(ss); q.push(root); while (!q.empty()) { TreeNode* node = q.front(); if (node != nullptr) { node->left = fetch(ss); node->right = fetch(ss); q.push(node->left); q.push(node->right); } q.pop(); } return root; } TreeNode* Codec::fetch(istringstream& ss) { string token; if (getline(ss, token, ',') && token != "null") { return new TreeNode(stoi(token)); } else { return nullptr; } }<file_sep>/src/ValidateBinarySearchTree.cpp #include "ValidateBinarySearchTree.hpp" bool ValidateBinarySearchTree::isValidBST(TreeNode* root) { if (root == nullptr) { return true; } if (root->left == nullptr && root->right == nullptr) { return true; } if (root->left == nullptr) { return isValidBST(root->right) && root->val < minNodeVal(root->right); } if (root->right == nullptr) { return isValidBST(root->left) && root->val > maxNodeVal(root->left); } return isValidBST(root->left) && root->val > maxNodeVal(root->left) && isValidBST(root->right) && root->val < minNodeVal(root->right); } // NOTE: This function assumes root is not null. int ValidateBinarySearchTree::minNodeVal(TreeNode* root) { while (root->left != nullptr) { root = root->left; } return root->val; } // NOTE: This function assumes root is not null. int ValidateBinarySearchTree::maxNodeVal(TreeNode* root) { while (root->right != nullptr) { root = root->right; } return root->val; } <file_sep>/src/BinarySearchTreeIterator.cpp #include "BinarySearchTreeIterator.hpp" BSTIterator::BSTIterator(TreeNode* root) { this->root = root; while (root != nullptr) { s.push(root); root = root->left; } } bool BSTIterator::hasNext() { return !s.empty(); } int BSTIterator::next() { TreeNode* n = s.top(); s.pop(); int ret = n->val; n = n->right; while (n != nullptr) { s.push(n); n = n->left; } return ret; } <file_sep>/src/PopulatingNextRightPointersInEachNode.cpp #include "PopulatingNextRightPointersInEachNode.hpp" #include <queue> using namespace std; void PopulatingNextRightPointersInEachNode::connect(TreeLinkNode* root) { if (root == nullptr) { return; } queue<TreeLinkNode*> q; q.push(root); while (!q.empty()) { int k = q.size(); // number of nodes in this level for (int i = 0; i < k; i++) { TreeLinkNode* front = q.front(); q.pop(); if (i + 1 < k) { front->next = q.front(); } if (front->left != nullptr) { q.push(front->left); } if (front->right != nullptr) { q.push(front->right); } } } } <file_sep>/src/CountPrimes.cpp #include "CountPrimes.hpp" #include <vector> using namespace std; int CountPrimes::countPrimes(int n) { int result = 0; vector<bool> notPrime(n, false); notPrime[1] = true; int base = 2; while (base * base < n) { // marking for (int i = base; i * base < n; i++) { notPrime[i * base] = true; } // update new base int i = base + 1; while (i < n && notPrime[i]) { i++; } base = i; } for (int i = 1; i < n; i++) if (!notPrime[i]) { result++; } return result; } <file_sep>/src/BinaryTreeLevelOrderTraversalII.cpp #include "BinaryTreeLevelOrderTraversalII.hpp" #include <algorithm> #include <queue> using namespace std; vector<vector<int>> BinaryTreeLevelOrderTraversalII::levelOrderBottom( TreeNode* root) { /* * Create a tree like this: * 3 * / \ * 9 20 * / \ * 15 7 */ // push 3 (level 1), pop 3 push 9 push 20 (level 2), pop 9, pop 20 push 15 push 7(level 3), pop 15, pop 7 vector<vector<int>> ret; if (root == nullptr) { return ret; } queue<TreeNode*> nodes; nodes.push(root); ret.push_back({}); int level = 0; // this level index int thisLevel = 1; // number of nodes at this level int nextLevel = 0; // number of nodes at next level while (!nodes.empty()) { TreeNode* front = nodes.front(); if (thisLevel > 0) { ret[level].push_back(front->val); thisLevel--; } else { thisLevel = nextLevel; nextLevel = 0; level++; ret.push_back({}); ret[level].push_back(front->val); thisLevel--; } if (front->left != nullptr) { nodes.push(front->left); nextLevel++; } if (front->right != nullptr) { nodes.push(front->right); nextLevel++; } nodes.pop(); } reverse(ret.begin(), ret.end()); return ret; } <file_sep>/include/ValidateBinarySearchTree.hpp #ifndef VALIDATE_BINARY_SEARCH_TREE_HPP_ #define VALIDATE_BINARY_SEARCH_TREE_HPP_ #include "TreeNode.hpp" class ValidateBinarySearchTree { public: bool isValidBST(TreeNode* root); private: int minNodeVal(TreeNode* root); int maxNodeVal(TreeNode* root); }; #endif // VALIDATE_BINARY_SEARCH_TREE_HPP_ <file_sep>/src/Triangle.cpp #include "Triangle.hpp" int Triangle::minimumTotal(vector<vector<int>>& triangle) { int m = triangle.size(); if (m == 0) { return 0; } vector<vector<int>> dp(m, vector<int>(m, 0)); dp[0][0] = triangle[0][0]; for (int i = 1; i < m; i++) { dp[i][0] = dp[i - 1][0] + triangle[i][0]; for (int j = 1; j < i; j++) dp[i][j] = ((dp[i - 1][j] < dp[i - 1][j - 1]) ? dp[i - 1][j] : dp[i - 1][j - 1]) + triangle[i][j]; dp[i][i] = dp[i - 1][i - 1] + triangle[i][i]; } int ret = dp[m - 1][0]; for (int j = 1; j < m; j++) { ret = (ret > dp[m - 1][j]) ? dp[m - 1][j] : ret; } return ret; } <file_sep>/include/FirstMissingPositive.hpp #ifndef FIRST_MISSING_POSITIVE_HPP_ #define FIRST_MISSING_POSITIVE_HPP_ #include <vector> using namespace std; class FirstMissingPositive { public: int firstMissingPositive(vector<int>& nums); }; #endif // FIRST_MISSING_POSITIVE_HPP_ <file_sep>/src/SumRootToLeafNumbers.cpp #include "SumRootToLeafNumbers.hpp" int SumRootToLeafNumbers::sumNumbers(TreeNode* root) { vector<TreeNode*> path; vector<vector<int>> result; int ret = 0; if (root == nullptr) { return 0; } dfs(path, result, root); for (const auto& num : result) { ret += getNumberVal(num); } return ret; } void SumRootToLeafNumbers::dfs(vector<TreeNode*>& path, vector<vector<int>>& result, TreeNode* start) { if (start->left == nullptr && start->right == nullptr) { vector<int> r; for (auto n : path) { r.push_back(n->val); } r.push_back(start->val); result.push_back(r); return; } if (start->left != nullptr) { path.push_back(start); dfs(path, result, start->left); path.pop_back(); } if (start->right != nullptr) { path.push_back(start); dfs(path, result, start->right); path.pop_back(); } } int SumRootToLeafNumbers::getNumberVal(const vector<int>& num) { int result = 0; for (auto d : num) { result = result * 10 + d; } return result; } <file_sep>/src/BinaryTreeMaximumPathSum.cpp #include "BinaryTreeMaximumPathSum.hpp" #include <climits> using namespace std; int BinaryTreeMaximumPathSum::maxPathSum(TreeNode* root) { max_sum = INT_MIN; dfs(root); return max_sum; } int BinaryTreeMaximumPathSum::dfs(const TreeNode* root) { if (root == nullptr) { return 0; } int l = dfs(root->left); int r = dfs(root->right); int sum = root->val; if (l > 0) { sum += l; } if (r > 0) { sum += r; } max_sum = max(max_sum, sum); return max(r, l) > 0 ? max(r, l) + root->val : root->val; } <file_sep>/src/CountCompleteTreeNodes.cpp #include "CountCompleteTreeNodes.hpp" int CountCompleteTreeNodes::countNodes(TreeNode* root) { if (root == nullptr) { return 0; } if (root->left == nullptr) { return 1; } if (root->right == nullptr) { return 2; } TreeNode* ln = root; int ld = 0; while (ln != nullptr) { ld++; ln = ln->left; } TreeNode* rn = root; int rd = 0; while (rn != nullptr) { rd++; rn = rn->right; } if (ld == rd) { return (1 << ld) - 1; } else { return 1 + countNodes(root->left) + countNodes(root->right); } } <file_sep>/tests/PlusOneTest.cpp #include "catch.hpp" #include "PlusOne.hpp" TEST_CASE("Plus One") { PlusOne s; SECTION("Sample tests") { vector<int> num1 {1}; vector<int> res1 {2}; REQUIRE(s.plusOne(num1) == res1); vector<int> num2 {9}; vector<int> res2 {1, 0}; REQUIRE(s.plusOne(num2) == res2); vector<int> num3 {9, 9, 9}; vector<int> res3 {1, 0, 0, 0}; REQUIRE(s.plusOne(num3) == res3); vector<int> num4 {4, 6, 8}; vector<int> res4 {4, 6, 9}; REQUIRE(s.plusOne(num4) == res4); } } <file_sep>/src/DecodeWays.cpp #include "DecodeWays.hpp" #include <vector> using namespace std; int DecodeWays::numDecodings(string s) { int sz = s.size(); if (sz == 0) { return 0; } vector<int> dp(sz + 1, 0); dp[0] = 1; dp[1] = valid(s.substr(0, 1)) ? 1 : 0; for (int i = 2; i <= sz; i++) { if (dp[i - 2] && s[i - 2] != '0' && valid(s.substr(i - 2, 2))) { dp[i] += dp[i - 2]; } if (dp[i - 1] && valid(s.substr(i - 1, 1))) { dp[i] += dp[i - 1]; } } return dp[sz]; } bool DecodeWays::valid(string s) { int val = stoi(s); return 1 <= val && val <= 26; } <file_sep>/include/RangeSumQuery2DImmutable.hpp #ifndef RANGE_SUM_QUERY_2D_IMMUTABLE_HPP_ #define RANGE_SUM_QUERY_2D_IMMUTABLE_HPP_ #include <vector> using namespace std; class NumMatrix { public: NumMatrix(vector<vector<int>>& matrix); int sumRegion(int row1, int col1, int row2, int col2); private: vector<vector<int>> sum; }; #endif // RANGE_SUM_QUERY_2D_IMMUTABLE_HPP_<file_sep>/src/WordBreakII.cpp #include "WordBreakII.hpp" vector<string> WordBreakII::wordBreak(string s, unordered_set<string>& wordDict) { if (s.size() == 0) { return vector<string>(); } unordered_map<string, vector<string>> map; return dfs(s, wordDict, map); } vector<string> WordBreakII::dfs(string s, unordered_set<string>& dict, unordered_map<string, vector<string>>& map) { if (map.find(s) != map.end()) { return map[s]; } vector<string> ans; if (s.size() == 0) { ans.push_back(""); } else { for (int i = 1; i <= s.size(); i++) { string l = s.substr(0, i); if (dict.find(l) == dict.end()) { continue; } vector<string> rans = dfs(s.substr(i), dict, map); for (auto r : rans) { string lr = l; if (i != s.size()) { lr += " "; } lr += r; ans.push_back(lr); } } } map[s] = ans; return ans; } <file_sep>/src/CreateMaximumNumber.cpp #include "CreateMaximumNumber.hpp" vector<int> CreateMaximumNumber::maxNumber(vector<int>& nums1, vector<int>& nums2, int k) { int sz1 = nums1.size(); int sz2 = nums2.size(); if (sz1 + sz2 == k) { return mergeNums(nums1, nums2); } vector<int> ret; for (int a = 0; a <= k; a++) { int b = k - a; if (a > sz1 || b > sz2) { continue; } vector<int> va = maxNumber(nums1, a); vector<int> vb = maxNumber(nums2, b); vector<int> t = mergeNums(va, vb); if (greaterThan(t, 0, ret, 0)) { ret = t; } } return ret; } vector<int> CreateMaximumNumber::maxNumber(vector<int>& nums, int k) { int sz = nums.size(); if (sz == 0 || sz <= k) { return nums; } vector<int> ret; int i = 0; while (k > 0) { int j = sz - k; int idx = maxNumIdx(nums, i, j); ret.push_back(nums[idx]); i = idx + 1; k--; } return ret; } int CreateMaximumNumber::maxNumIdx(vector<int>& nums, int i, int j) { int ret = i; for (int k = i + 1; k <= j; k++) { if (nums[k] > nums[ret]) { ret = k; } } return ret; } vector<int> CreateMaximumNumber::mergeNums(vector<int>& nums1, vector<int>& nums2) { int sz1 = nums1.size(); int sz2 = nums2.size(); int sz = sz1 + sz2; vector<int> nums(sz, 0); for (int i = 0, j = 0, r = 0; r < sz; r++) { nums[r] = greaterThan(nums1, i, nums2, j) ? nums1[i++] : nums2[j++]; } return nums; } bool CreateMaximumNumber::greaterThan(vector<int>& nums1, int i, vector<int>& nums2, int j) { while (i < nums1.size() && j < nums2.size() && nums1[i] == nums2[j]) { i++; j++; } return j == nums2.size() || (i < nums1.size() && nums1[i] > nums2[j]); } <file_sep>/src/BinaryTreeInorderTraversal.cpp #include "BinaryTreeInorderTraversal.hpp" vector<int> BinaryTreeInorderTraversal::inorderTraversal(TreeNode* root) { if (root != nullptr) { inorderTraversal(root->left); res.push_back(root->val); inorderTraversal(root->right); } return res; } <file_sep>/src/FlattenBinaryTreeToLinkedList.cpp #include "FlattenBinaryTreeToLinkedList.hpp" void FlattenBinaryTreeToLinkedList::flatten(TreeNode* root) { if (root == nullptr) { return; } // flatten left subtree if (root->left != nullptr) { flatten(root->left); } // flatten right subtree if (root->right != nullptr) { flatten(root->right); } if (root->left != nullptr) { // make left subtree as the right node of root // and empty root's left node TreeNode* rt = root->right; root->right = root->left; root->left = nullptr; // 1. find the tail node of the first list (head at root) TreeNode* tail = root->right; while (tail->right != nullptr) { tail = tail->right; } // 2. link two lists (head at root and rt) together tail->right = rt; } } <file_sep>/tests/MaximalRectangleTest.cpp #include "catch.hpp" #include "MaximalRectangle.hpp" TEST_CASE("Maximal Rectangle") { MaximalRectangle s; SECTION("Sample test") { vector<vector<char>> matrix { {'0', '0', '1', '0'}, {'0', '0', '0', '1'}, {'0', '1', '1', '1'}, {'0', '0', '1', '1'} }; REQUIRE(s.maximalRectangle(matrix) == 4); } SECTION("Corner test") { vector<vector<char>> matrix { {'0'} }; REQUIRE(s.maximalRectangle(matrix) == 0); } } <file_sep>/include/SumRootToLeafNumbers.hpp #ifndef SUM_ROOT_TO_LEAF_NUMBERS_HPP_ #define SUM_ROOT_TO_LEAF_NUMBERS_HPP_ #include "TreeNode.hpp" #include <vector> using namespace std; class SumRootToLeafNumbers { public: int sumNumbers(TreeNode* root); private: void dfs(vector<TreeNode*>& path, vector<vector<int>>& result, TreeNode* start); int getNumberVal(const vector<int>& num); }; #endif // SUM_ROOT_TO_LEAF_NUMBERS_HPP_ <file_sep>/tests/SearchA2DMatrixIITest.cpp #include "catch.hpp" #include "SearchA2DMatrixII.hpp" TEST_CASE("Search a 2D Matrix II") { SearchA2DMatrixII s; SECTION("Sample test") { vector<vector<int>> matrix { {1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30} }; REQUIRE(s.searchMatrix(matrix, 5)); REQUIRE_FALSE(s.searchMatrix(matrix, 20)); } } <file_sep>/include/ConvertSortedArrayToBinarySearchTree.hpp #ifndef CONVERT_SORTED_ARRAY_TO_BINARY_SEARCH_TREE_HPP_ #define CONVERT_SORTED_ARRAY_TO_BINARY_SEARCH_TREE_HPP_ #include "TreeNode.hpp" #include <vector> using namespace std; class ConvertSortedArrayToBinarySearchTree { public: TreeNode* sortedArrayToBST(vector<int>& nums); private: TreeNode* sortedArrayTOBST(vector<int>& nums, int begin, int end); }; #endif // CONVERT_SORTED_ARRAY_TO_BINARY_SEARCH_TREE_HPP_ <file_sep>/src/DistinctSubsequences.cpp #include "DistinctSubsequences.hpp" #include <vector> using namespace std; int DistinctSubsequences::numDistinct(string s, string t) { // match `t` to subsequence of `s` int tlen = t.size(); int slen = s.size(); if (tlen == 0) { return 1; } if (slen == 0) { return (tlen == 0) ? 1 : 0; } vector<vector<int>> dp(tlen + 1, vector<int>(slen + 1, 0)); for (int j = 0; j <= slen; j++) { dp[0][j] = 1; } for (int i = 1; i <= tlen; i++) { for (int j = 1; j <= slen; j++) { dp[i][j] = dp[i][j - 1]; if (t[i - 1] == s[j - 1]) { dp[i][j] += dp[i - 1][j - 1]; } } } return dp[tlen][slen]; } <file_sep>/include/DecodeWays.hpp #ifndef DECODE_WAYS_HPP_ #define DECODE_WAYS_HPP_ #include <string> using namespace std; class DecodeWays { public: int numDecodings(string s); private: bool valid(string s); }; #endif // DECODE_WAYS_HPP_ <file_sep>/src/DungeonGame.cpp #include "DungeonGame.hpp" #include <algorithm> using namespace std; int DungeonGame::calculateMinimumHP(vector<vector<int>>& dungeon) { int m = dungeon.size(); if (m == 0) { return 0; } int n = dungeon[0].size(); if (n == 0) { return 0; } vector<vector<int>> dp(m, vector<int>(n, 0)); dp[m - 1][n - 1] = (dungeon[m - 1][n - 1] >= 0) ? 1 : (1 - dungeon[m - 1][n - 1]); for (int i = m - 2; i >= 0; i--) { if (dp[i + 1][n - 1] - dungeon[i][n - 1] <= 0) { dp[i][n - 1] = 1; } else { dp[i][n - 1] = dp[i + 1][n - 1] - dungeon[i][n - 1]; } } for (int j = n - 2; j >= 0; j--) { if (dp[m - 1][j + 1] - dungeon[m - 1][j] <= 0) { dp[m - 1][j] = 1; } else { dp[m - 1][j] = dp[m - 1][j + 1] - dungeon[m - 1][j]; } } for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { int base = min(dp[i + 1][j], dp[i][j + 1]); if (base - dungeon[i][j] <= 0) { dp[i][j] = 1; } else { dp[i][j] = base - dungeon[i][j]; } } } return dp[0][0]; } <file_sep>/src/UniqueBinarySearchTrees.cpp #include "UniqueBinarySearchTrees.hpp" #include <vector> using namespace std; int UniqueBinarySearchTrees::numTrees(int n) { if (n < 0) { return 0; } vector<int> dp(n + 1, 0); dp[0] = 1; for (int i = 1; i <= n; i++) for (int r = 1; r <= i; r++) { dp[i] += dp[r - 1] * dp[i - r]; } return dp[n]; } <file_sep>/src/MaximumDepthOfBinaryTree.cpp #include "MaximumDepthOfBinaryTree.hpp" #include <algorithm> using namespace std; int MaximumDepthOfBinaryTree::maxDepth(TreeNode* root) { if (root == nullptr) { return 0; } int ldepth = maxDepth(root->left); int rdepth = maxDepth(root->right); return max(ldepth, rdepth) + 1; } <file_sep>/include/FlattenBinaryTreeToLinkedList.hpp #ifndef FLATTEN_BINARY_TREE_TO_LINKED_LIST_HPP_ #define FLATTEN_BINARY_TREE_TO_LINKED_LIST_HPP_ #include "TreeNode.hpp" class FlattenBinaryTreeToLinkedList { public: void flatten(TreeNode* root); }; #endif // FLATTEN_BINARY_TREE_TO_LINKED_LIST_HPP_ <file_sep>/include/ExpressionAddOperators.hpp #ifndef EXPRESSION_ADD_OPERATORS_HPP_ #define EXPRESSION_ADD_OPERATORS_HPP_ #include <vector> #include <string> using namespace std; class ExpressionAddOperators { public: vector<string>addOperators(string num, int target); private: void dfs(string num, int target, string expr, long currRes, long prevNum, vector<string>& res); }; #endif // EXPRESSION_ADD_OPERATORS_HPP_ <file_sep>/include/SerializeAndDeserializeBinaryTree.hpp #ifndef SERIALIZE_AND_DESERIALIZE_BINARY_TREE_HPP_ #define SERIALIZE_AND_DESERIALIZE_BINARY_TREE_HPP_ #include <string> #include <sstream> #include "TreeNode.hpp" using namespace std; class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root); // Decodes your encoded data to tree. TreeNode* deserialize(string data); private: TreeNode* fetch(istringstream& ss); }; #endif // SERIALIZE_AND_DESERIALIZE_BINARY_TREE_HPP_<file_sep>/src/MaximumProductSubarray.cpp #include "MaximumProductSubarray.hpp" #include <algorithm> using namespace std; int MaximumProductSubarray::maxProduct(vector<int>& nums) { int sz = nums.size(); if (sz == 0) { return 0; } int minNow, maxNow, maxGlobal; minNow = maxNow = maxGlobal = nums[0]; for (int i = 1; i < sz; i++) { if (nums[i] >= 0) { maxNow = max(maxNow * nums[i], nums[i]); minNow = min(minNow * nums[i], nums[i]); } else { int _maxNow = maxNow; maxNow = minNow * nums[i]; minNow = min(_maxNow * nums[i], nums[i]); } maxGlobal = max(maxGlobal, maxNow); } return maxGlobal; } <file_sep>/include/BestTimeToBuyAndSellStockIV.hpp #ifndef BEST_TIME_TO_BUY_AND_SELL_STOCK_IV_HPP_ #define BEST_TIME_TO_BUY_AND_SELL_STOCK_IV_HPP_ #include <vector> using namespace std; class BestTimeToBuyAndSellStockIV { public: int maxProfit(int k, vector<int>& prices); private: int maxProfitNoLimits(vector<int>& prices); }; #endif // BEST_TIME_TO_BUY_AND_SELL_STOCK_IV_HPP_ <file_sep>/include/CreateMaximumNumber.hpp #ifndef CREATE_MAXIMUM_NUMBER_HPP_ #define CREATE_MAXIMUM_NUMBER_HPP_ #include <vector> using namespace std; class CreateMaximumNumber { public: vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k); private: vector<int> maxNumber(vector<int>& nums, int k); int maxNumIdx(vector<int>& nums, int i, int j); vector<int> mergeNums(vector<int>& nums1, vector<int>& nums2); bool greaterThan(vector<int>& nums1, int i, vector<int>& nums2, int j); }; #endif // CREATE_MAXIMUM_NUMBER_HPP_ <file_sep>/src/ValidAnagram.cpp #include "ValidAnagram.hpp" bool ValidAnagram::isAnagram(string s, string t) { if (s.size() != t.size()) { return false; } int cnts[256]; for (int i = 0; i < 256; i++) { cnts[i] = 0; } for (int i = 0; i < s.size(); i++) { cnts[s[i]]++; } for (int i = 0; i < t.size(); i++) { if (cnts[t[i]] == 0) { return false; } cnts[t[i]]--; } return true; }<file_sep>/src/MinimumDepthOfBinaryTree.cpp #include "MinimumDepthOfBinaryTree.hpp" #include <queue> using namespace std; int MinimumDepthOfBinaryTree::minDepth(TreeNode* root) { if (root == nullptr) { return 0; } queue<TreeNode*> q; q.push(root); int depth = 0; while (!q.empty()) { depth++; // scanning level `depth` now int k = q.size(); // number of nodes in level `depth` for (int i = 0; i < k; i++) { TreeNode* front = q.front(); q.pop(); if (front->left == nullptr && front->right == nullptr) { // we have reach the leaf node return depth; } if (front->left != nullptr) { q.push(front->left); } if (front->right != nullptr) { q.push(front->right); } } } return depth; } <file_sep>/src/UglyNumberII.cpp #include "UglyNumberII.hpp" #include <algorithm> #include <queue> #include <cstdint> using namespace std; int UglyNumberII::nthUglyNumber(int n) { if (n == 1) { return 1; } queue<uint64_t> q2; queue<uint64_t> q3; queue<uint64_t> q5; int count = 1; int next; q2.push(2); q3.push(3); q5.push(5); while (count < n) { next = std::min(q2.front(), min(q3.front(), q5.front())); if (next == q2.front()) { int val = q2.front(); q2.push(val * 2); q3.push(val * 3); q5.push(val * 5); q2.pop(); } else if (next == q3.front()) { int val = q3.front(); q3.push(val * 3); q5.push(val * 5); q3.pop(); } else { int val = q5.front(); q5.push(val * 5); q5.pop(); } count++; } return next; } <file_sep>/tests/WordBreakIITest.cpp #include "catch.hpp" #include "WordBreakII.hpp" #include <algorithm> using namespace std; TEST_CASE("Word Break II") { WordBreakII s; SECTION("Sample test") { unordered_set<string> dict {"cat", "cats", "and", "sand", "dog"}; vector<string> expected {"cats and dog", "cat sand dog"}; vector<string> result = s.wordBreak("catsanddog", dict); REQUIRE(result.size() == 2); for (int i = 0; i < 2; i++) { REQUIRE_FALSE(find(expected.begin(), expected.end(), result[i]) == expected.end()); } } } <file_sep>/tests/NextPermutationTest.cpp #include "catch.hpp" #include "NextPermutation.hpp" TEST_CASE("Next Permutation") { NextPermutation s; SECTION("Sample tests") { vector<int> nums_1 {1, 2, 3}; vector<int> expected_1 {1, 3, 2}; s.nextPermutation(nums_1); REQUIRE(nums_1 == expected_1); vector<int> nums_2 {3, 2, 1}; vector<int> expected_2 {1, 2, 3}; s.nextPermutation(nums_2); REQUIRE(nums_2 == expected_2); vector<int> nums_3 {1, 1, 5}; vector<int> expected_3 {1, 5, 1}; s.nextPermutation(nums_3); REQUIRE(nums_3 == expected_3); } SECTION("All identicals but one") { vector<int> nums_1 {0, 0, 1}; vector<int> expected_1 {0, 1, 0}; s.nextPermutation(nums_1); REQUIRE(nums_1 == expected_1); vector<int> nums_2 {0, 1, 0}; vector<int> expected_2 {1, 0, 0}; s.nextPermutation(nums_2); REQUIRE(nums_2 == expected_2); vector<int> nums_3 {1, 0, 0}; vector<int> expected_3 {0, 0, 1}; s.nextPermutation(nums_3); REQUIRE(nums_3 == expected_3); } } <file_sep>/include/MaximumGap.hpp #ifndef MAXIMUM_GAP_HPP_ #define MAXIMUM_GAP_HPP_ #include <vector> using namespace std; class MaximumGap { public: int maximumGap(vector<int>& nums); private: int getNthDigit(int num, int n); }; #endif // MAXIMUM_GAP_HPP_ <file_sep>/include/ContainsDuplicate.hpp #ifndef CONTAINS_DUPLICATE_HPP_ #define CONTAINS_DUPLICATE_HPP_ #include <vector> using namespace std; class ContainsDuplicate { public: bool containsDuplicate(vector<int>& nums); }; #endif // CONTAINS_DUPLICATE_HPP_ <file_sep>/include/UniqueBinarySearchTreesII.hpp #ifndef UNIQUE_BINARY_SEARCH_TREES_II_HPP_ #define UNIQUE_BINARY_SEARCH_TREES_II_HPP_ #include "TreeNode.hpp" #include <vector> using namespace std; class UniqueBinarySearchTreesII { public: vector<TreeNode*> generateTrees(int n); private: TreeNode* clone(TreeNode* root, int offset); }; #endif // UNIQUE_BINARY_SEARCH_TREES_II_HPP_ <file_sep>/include/MaximumDepthOfBinaryTree.hpp #ifndef MAXIMUM_DEPTH_OF_BINARY_TREE_HPP_ #define MAXIMUM_DEPTH_OF_BINARY_TREE_HPP_ #include "TreeNode.hpp" class MaximumDepthOfBinaryTree { public: int maxDepth(TreeNode* root); }; #endif // MAXIMUM_DEPTH_OF_BINARY_TREE_HPP_ <file_sep>/src/IsomorphicStrings.cpp #include "IsomorphicStrings.hpp" #include <unordered_map> using namespace std; bool IsomorphicStrings::isIsomorphic(string s, string t) { if (s.size() != t.size()) { return false; } remap(s); remap(t); return s == t; } void IsomorphicStrings::remap(string& s) { unordered_map<char, char> mappings; char c = '0'; for (int i = 0; i < s.size(); i++) { if (mappings.find(s[i]) == mappings.end()) { mappings[s[i]] = c; s[i] = c; c++; } else { s[i] = mappings[s[i]]; } } } <file_sep>/include/SortColors.hpp #ifndef SORT_COLORS_HPP_ #define SORT_COLORS_HPP_ #include <vector> using namespace std; class SortColors { public: void sortColors(vector<int>& nums); }; #endif // SORT_COLORS_HPP_ <file_sep>/include/HappyNumber.hpp #ifndef HAPPY_NUMBER_HPP_ #define HAPPY_NUMBER_HPP_ class HappyNumber { public: bool isHappy(int n); }; #endif // HAPPY_NUMBER_HPP_ <file_sep>/src/BinaryTreeZigzagLevelOrderTraversal.cpp #include "BinaryTreeZigzagLevelOrderTraversal.hpp" #include <queue> #include <algorithm> using namespace std; vector<vector<int>> BinaryTreeZigzagLevelOrderTraversal::zigzagLevelOrder( TreeNode* root) { queue<TreeNode*> q; vector<vector<int>> ret; if (root == nullptr) { return ret; } q.push(root); ret.push_back({}); int curLevel = 1; int nextLevel = 0; TreeNode* top; while (!q.empty()) { if (curLevel == 0) { ret.push_back({}); curLevel = nextLevel; nextLevel = 0; } top = q.front(); q.pop(); curLevel--; if (top->left != nullptr) { q.push(top->left); nextLevel++; } if (top->right != nullptr) { q.push(top->right); nextLevel++; } ret.back().push_back(top->val); } bool r = false; for (int i = 0; i < ret.size(); i++, r = !r) if (r) { reverse(ret[i].begin(), ret[i].end()); } return ret; } <file_sep>/include/ListNode.hpp #ifndef LIST_NODE_HPP_ #define LIST_NODE_HPP_ #include <string> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {} }; int list_len(ListNode* head); string list_serialize(ListNode* head); void list_free(ListNode* head); #endif // LIST_NODE_HPP_ <file_sep>/tests/BestTimeToBuyAndSellStockIVTest.cpp #include "catch.hpp" #include "BestTimeToBuyAndSellStockIV.hpp" TEST_CASE("Best Time to Buy and Sell Stock IV") { BestTimeToBuyAndSellStockIV s; SECTION("Sample test") { vector<int> prices {10, 11, 7, 10, 6}; REQUIRE(s.maxProfit(1, prices) == 3); REQUIRE(s.maxProfit(2, prices) == 4); } } <file_sep>/src/BullsAndCows.cpp #include "BullsAndCows.hpp" #include <unordered_map> using namespace std; string BullsAndCows::getHint(string secret, string guess) { int bulls = 0; int cows = 0; unordered_map<char, int> m; for (int i = 0; i < secret.size(); i++) { if (secret[i] == guess[i]) { bulls++; } else { m[secret[i]]++; } } for (int i = 0; i < guess.size(); i++) { if (secret[i] != guess[i] && m[guess[i]] > 0) { cows++; m[guess[i]]--; } } return to_string(bulls) + "A" + to_string(cows) + "B"; }<file_sep>/include/ExcelSheetColumnTitle.hpp #ifndef EXCEL_SHEET_COLUMN_TITLE_HPP_ #define EXCEL_SHEET_COLUMN_TITLE_HPP_ #include <string> using namespace std; class ExcelSheetColumnTitle { public: string convertToTitle(int n); }; #endif // EXCEL_SHEET_COLUMN_TITLE_HPP_ <file_sep>/include/InvertBinaryTree.hpp #ifndef INVERT_BINARY_TREE_HPP_ #define INVERT_BINARY_TREE_HPP_ #include "TreeNode.hpp" class InvertBinaryTree { public: TreeNode* invertTree(TreeNode* root); }; #endif // INVERT_BINARY_TREE_HPP_ <file_sep>/include/LongestPalindromicSubstring.hpp #ifndef LONGEST_PALINDROMIC_SUBSTRING_HPP_ #define LONGEST_PALINDROMIC_SUBSTRING_HPP_ #include <string> using namespace std; class LongestPalindromicSubstring { public: string longestPalindrome(string s); private: string expandAroundCenter(string s, int c1, int c2); }; #endif // LONGEST_PALINDROMIC_SUBSTRING_HPP_ <file_sep>/src/UniquePaths.cpp #include "UniquePaths.hpp" #include <vector> #include <algorithm> using namespace std; int UniquePaths::uniquePaths(int m, int n) { return uniquePaths_Optimized(m, n); } int UniquePaths::uniquePaths_Raw(int m, int n) { vector<vector<int>> dp(m, vector<int>(n, 1)); for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; } int UniquePaths::uniquePaths_Optimized(int m, int n) { if (m > n) { return uniquePaths_Optimized(n, m); } vector<int> pre(m, 1); vector<int> cur(m, 1); for (int j = 1; j < n; j++) { for (int i = 1; i < m; i++) { cur[i] = cur[i - 1] + pre[i]; } swap(pre, cur); } return pre[m - 1]; } <file_sep>/src/HIndex.cpp #include "HIndex.hpp" #include <algorithm> using namespace std; int HIndex::hIndex(vector<int>& citations) { int n = citations.size(); vector<int> count(n + 1, 0); for (auto cite : citations) { if (cite <= n) { count[cite]++; } else { count[n]++; } } int h = n; int acc = 0; while (acc + count[h] < h) { acc += count[h]; h--; } return h; } <file_sep>/include/PermutationsII.hpp #ifndef PERMUTATIONS_II_HPP_ #define PERMUTATIONS_II_HPP_ #include <vector> using namespace std; class PermutationsII { public: vector<vector<int>> permuteUnique(vector<int>& nums); private: void helper(vector<int> nums, int begin, vector<vector<int>>& result); }; #endif // PERMUTATIONS_II_HPP_ <file_sep>/src/MaximalRectangle.cpp #include "MaximalRectangle.hpp" #include "LargestRectangleInHistogram.hpp" int MaximalRectangle::maximalRectangle(vector<vector<char>>& matrix) { int height = matrix.size(); if (height == 0) { return 0; } int width = matrix[0].size(); if (width == 0) { return 0; } vector<int> cols(width, 0); LargestRectangleInHistogram helper; int res = 0; for (int i = 0; i < height; i++) { // prepare cols for (int j = 0; j < width; j++) { if (matrix[i][j] == '0') { cols[j] = 0; } else { cols[j]++; } } // calculate maximal rectangle at this level int area = helper.largestRectangleArea(cols); // update global value if (area > res) { res = area; } } return res; } <file_sep>/include/BinaryTreeMaximumPathSum.hpp #ifndef BINARY_TREE_MAXIMUM_PATH_SUM_HPP_ #define BINARY_TREE_MAXIMUM_PATH_SUM_HPP_ #include "TreeNode.hpp" class BinaryTreeMaximumPathSum { public: int maxPathSum(TreeNode* root); private: int max_sum; int dfs(const TreeNode* root); }; #endif // BINARY_TREE_MAXIMUM_PATH_SUM_HPP_ <file_sep>/include/IsomorphicStrings.hpp #ifndef ISOMORPHIC_STRINGS_HPP_ #define ISOMORPHIC_STRINGS_HPP_ #include <string> using namespace std; class IsomorphicStrings { public: bool isIsomorphic(string s, string t); private: void remap(string& s); }; #endif // ISOMORPHIC_STRINGS_HPP_ <file_sep>/include/WiggleSortII.hpp #ifndef WIGGLE_SORT_II_HPP_ #define WIGGLE_SORT_II_HPP_ #include <vector> using namespace std; class WiggleSortII { public: void wiggleSort(vector<int>& nums); private: int m(int idx, int n); }; #endif // WIGGLE_SORT_II_HPP_<file_sep>/include/FractionToRecurringDecimal.hpp #ifndef FRACTION_TO_RECURRING_DECIMAL_HPP_ #define FRACTION_TO_RECURRING_DECIMAL_HPP_ #include <string> using namespace std; class FractionToRecurringDecimal { public: string fractionToDecimal(int numerator, int denominator); private: string helper(long numerator, long denominator); }; #endif // FRACTION_TO_RECURRING_DECIMAL_HPP_ <file_sep>/src/WordPattern.cpp #include "WordPattern.hpp" #include <vector> #include <unordered_map> using namespace std; bool WordPattern::wordPattern(string pattern, string str) { vector<string> ptable(256, ""); unordered_map<string, char> wtable; int i = 0; int j = 0; for (auto c : pattern) { if (j >= str.size()) { return false; } while (j < str.size() && str[j] != ' ') { j++; } string w = str.substr(i, j - i); if (ptable[c] == "") { ptable[c] = w; } else if (ptable[c] != w) { return false; } if (wtable.find(w) == wtable.end()) { wtable[w] = c; } else if (wtable[w] != c) { return false; } i = j + 1; j = i; } return j >= str.size(); }<file_sep>/include/RegularExpressionMatching.hpp #ifndef REGULAR_EXPRESSION_MATCHING_HPP_ #define REGULAR_EXPRESSION_MATCHING_HPP_ #include <string> using namespace std; class RegularExpressionMatching { public: bool isMatch(string s, string p); private: bool isMatch(char _s, char _p); }; #endif // REGULAR_EXPRESSION_MATCHING_HPP_ <file_sep>/README.md # LeetCode ## Getting Started ### Prerequisites * Unix-based operating system (OS X or Linux). I haven't test on Windows. * C++ compiler: g++ (v4.2 or more recent) or clang (v3.0 or more recent). * [CMake](https://cmake.org/) (v3.1.0 or more recent). ### Basic Installation Navigate to the root of the project and issue the following commands: ``` mkdir build cd build cmake .. && make tests/Test ``` Expected output: ``` =============================================================================== All tests passed (xxxx assertions in xxx test cases) ``` ## Table of Contents | | # | Title | Difficulty | |---|---|-------|------------| | :white_check_mark: | 324 | [Wiggle Sort II](https://leetcode.com/problems/wiggle-sort-ii/) | Medium | | :white_check_mark: | 322 | [Coin Change](https://leetcode.com/problems/coin-change/) | Medium | | :white_check_mark: | 321 | [Create Maximum Number](https://leetcode.com/problems/create-maximum-number/) | Hard | | :white_check_mark: | 319 | [Bulb Switcher](https://leetcode.com/problems/bulb-switcher/) | Medium | | :white_check_mark: | 318 | [Maximum Product of Word Lengths](https://leetcode.com/problems/maximum-product-of-word-lengths/) | Medium | | :white_check_mark: | 316 | [Remove Duplicate Letters](https://leetcode.com/problems/remove-duplicate-letters/) | Hard | | :white_check_mark: | 315 | [Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | Hard | | :white_check_mark: | 313 | [Super Ugly Number](https://leetcode.com/problems/super-ugly-number/) | Medium | | :white_check_mark: | 312 | [Burst Balloons](https://leetcode.com/problems/burst-balloons/) | Hard | | :white_check_mark: | 310 | [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | Medium | | :white_check_mark: | 304 | [Range Sum Query 2D - Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) | Medium | | :white_check_mark: | 303 | [Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/) | Easy | | :lock: | 302 | Smallest Rectangle Enclosing Black Pixels | Hard | | :white_check_mark: | 301 | [Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/) | Hard | | :white_check_mark: | 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | Medium | | :white_check_mark: | 299 | [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) | Easy | | :lock: | 298 | Binary Tree Longest Consecutive Sequence | Medium | | :white_check_mark: | 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | Medium | | :lock: | 296 | Best Meeting Point | Hard | | :white_check_mark: | 295 | [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) | Hard | | :lock: | 294 | Flip Game II | Medium | | :lock: | 293 | Flip Game | Easy | | :white_check_mark: | 292 | [Nim Game](https://leetcode.com/problems/nim-game/) | Easy | | :lock: | 291 | Word Pattern II | Hard | | :white_check_mark: | 290 | [Word Pattern](https://leetcode.com/problems/word-pattern/) | Easy | | :white_check_mark: | 289 | [Game of Life](https://leetcode.com/problems/game-of-life/) | Medium | | :lock: | 288 | Unique Word Abbreviation | Easy | | :white_check_mark: | 287 | [Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | Hard | | :lock: | 286 | Walls and Gates | Medium | | :lock: | 285 | Inorder Successor in BST | Medium | | :white_check_mark: | 284 | [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/) | Medium | | :white_check_mark: | 283 | [Move Zeros](https://leetcode.com/problems/move-zeroes/) | Easy | | :white_check_mark: | 282 | [Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | Hard | | :lock: | 281 | Zigzag Iterator | Medium | | :lock: | 280 | Wiggle Sort | Medium | | :white_check_mark: | 279 | [Perfect Squares](https://leetcode.com/problems/perfect-squares/) | Medium | | :white_check_mark: | 278 | [First Bad Version](https://leetcode.com/problems/first-bad-version/) | Easy | | :lock: | 277 | Find the Celebrity | Medium | | :lock: | 276 | Paint Fence | Easy | | :white_check_mark: | 275 | [H-Index II](https://leetcode.com/problems/h-index-ii/) | Medium | | :white_check_mark: | 274 | [H-Index](https://leetcode.com/problems/h-index/) | Medium | | :white_check_mark: | 273 | [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/) | Medium | | :lock: | 272 | Closest Binary Search Tree Value II | Hard | | :lock: | 271 | Encode and Decode Strings | Medium | | :lock: | 270 | Closest Binary Search Tree Value | Easy | | :lock: | 269 | Alien Dictionary | Hard | | :white_check_mark: | 268 | [Missing Number](https://leetcode.com/problems/missing-number/) | Medium | | :lock: | 267 | Palindrome Permutation II | Medium | | :lock: | 266 | Palindrome Permutation | Easy | | :lock: | 265 | Paint House II | Hard | | :white_check_mark: | 264 | [Ugly Number II](https://leetcode.com/problems/ugly-number-ii/) | Medium | | :white_check_mark: | 263 | [Ugly Number](https://leetcode.com/problems/ugly-number/) | Easy | | :lock: | 261 | Graph Valid Tree | Medium | | :white_check_mark: | 260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | Medium | | :lock: | 259 | 3Sum Smaller | Medium | | :white_check_mark: | 258 | [Add Digits](https://leetcode.com/problems/add-digits/) | Easy | | :white_check_mark: | 257 | [Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/) | Easy | | :lock: | 256 | Paint House | Medium | | :lock: | 255 | Verify Preorder Sequence in Binary Search Tree | Medium | | :lock: | 254 | Factor Combinations | Medium | | :lock: | 253 | Meeting Rooms II | Medium | | :lock: | 252 | Meeting Rooms | Easy | | :lock: | 251 | Flatten 2D Vector | Medium | | :lock: | 250 | Count Univalue Subtrees | Medium | | :lock: | 249 | Group Shifted Strings | Easy | | :lock: | 248 | Strobogrammatic Number III | Hard | | :lock: | 247 | Strobogrammatic Number II | Medium | | :lock: | 246 | Strobogrammatic Number | Easy | | :lock: | 245 | Shortest Word Distance III | Medium | | :lock: | 244 | Shortest Word Distance II | Medium | | :lock: | 243 | Shortest Word Distance | Easy | | :white_check_mark: | 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | Easy | | :white_check_mark: | 241 | [Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/) | Medium | | :white_check_mark: | 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | Medium | | :white_check_mark: | 239 | [Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) | Hard | | :white_check_mark: | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | Medium | | :white_check_mark: | 237 | [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/) | Easy | | :white_check_mark: | 236 | [Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | Medium | | :white_check_mark: | 235 | [Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | Easy | | :white_check_mark: | 234 | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) | Easy | | :white_check_mark: | 233 | [Number of Digit One](https://leetcode.com/problems/number-of-digit-one/) | Medium | | :white_check_mark: | 232 | [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | Easy | | :white_check_mark: | 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | Easy | | :white_check_mark: | 230 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | Medium | | :white_check_mark: | 229 | [Majority Element II](https://leetcode.com/problems/majority-element-ii/) | Medium | | :white_check_mark: | 228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | Easy | | :white_check_mark: | 227 | [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | Medium | | :white_check_mark: | 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | Easy | | :white_check_mark: | 225 | [Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | Easy | | :white_check_mark: | 224 | [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | Medium | | :white_check_mark: | 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | Easy | | :white_check_mark: | 222 | [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | Medium | | :white_check_mark: | 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | Medium | | :white_check_mark: | 220 | [Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) | Medium | | :white_check_mark: | 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | Easy | | :white_check_mark: | 218 | [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | Hard | | :white_check_mark: | 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | Easy | | :white_check_mark: | 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/) | Medium | | :white_check_mark: | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | Medium | | :white_check_mark: | 214 | [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | Hard | | :white_check_mark: | 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii/) | Medium | | :white_check_mark: | 212 | [Word Search II](https://leetcode.com/problems/word-search-ii/) | Hard | | :white_check_mark: | 211 | [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/) | Medium | | :white_check_mark: | 210 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) | Medium | | :white_check_mark: | 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | Medium | | :white_check_mark: | 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | Medium | | :white_check_mark: | 207 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | Medium | | :white_check_mark: | 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | Easy | | :white_check_mark: | 205 | [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | Easy | | :white_check_mark: | 204 | [Count Primes](https://leetcode.com/problems/count-primes/) | Easy | | :white_check_mark: | 203 | [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) | Easy | | :white_check_mark: | 202 | [Happy Number](https://leetcode.com/problems/happy-number/) | Easy | | :white_check_mark: | 201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | Medium | | :white_check_mark: | 200 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | Medium | | :white_check_mark: | 199 | [Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | Medium | | :white_check_mark: | 198 | [House Robber](https://leetcode.com/problems/house-robber/) | Easy | | :white_check_mark: | 191 | [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | Easy | | :white_check_mark: | 190 | [Reverse Bits](https://leetcode.com/problems/reverse-bits/) | Easy | | :white_check_mark: | 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | Easy | | :white_check_mark: | 188 | [Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/) | Hard | | :white_check_mark: | 187 | [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | Medium | | :lock: | 186 | Reverse Words in a String II | Medium | | :white_check_mark: | 179 | [Largest Number](https://leetcode.com/problems/largest-number/) | Medium | | :white_check_mark: | 174 | [Dungeon Game](https://leetcode.com/problems/dungeon-game/) | Hard | | :white_check_mark: | 173 | [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | Medium | | :white_check_mark: | 172 | [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | Easy | | :white_check_mark: | 171 | [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | Easy | | :lock: | 170 | Two Sum III - Data structure design | Easy | | :white_check_mark: | 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | Easy | | :white_check_mark: | 168 | [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | Easy | | :lock: | 167 | Two Sum II - Input array is sorted | Medium | | :white_check_mark: | 166 | [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | Medium | | :white_check_mark: | 165 | [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | Easy | | :white_check_mark: | 164 | [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | Hard | | :lock: | 163 | Missing Ranges | Medium | | :white_check_mark: | 162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | Medium | | :lock: | 161 | One Edit Distance | Medium | | :white_check_mark: | 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) | Easy | | :lock: | 159 | Longest Substring with At Most Two Distinct Characters | Hard | | :lock: | 158 | Read N Characters Given Read4 II - Call multiple times | Hard | | :lock: | 157 | Read N Characters Given Read4 | Easy | | :lock: | 156 | Binary Tree Upside Down | Medium | | :white_check_mark: | 155 | [Min Stack](https://leetcode.com/problems/min-stack/) | Easy | | :white_check_mark: | 154 | [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) | Hard | | :white_check_mark: | 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | Medium | | :white_check_mark: | 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | Medium | | :white_check_mark: | 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | Medium | | | 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) | Medium | | | 149 | [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | Hard | | | 148 | [Sort List](https://leetcode.com/problems/sort-list/) | Medium | | | 147 | [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) | Medium | | | 146 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | Hard | | | 145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | Hard | | | 144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | Medium | | | 143 | [Reorder List](https://leetcode.com/problems/reorder-list/) | Medium | | | 142 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) | Medium | | | 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | Medium | | :white_check_mark: | 140 | [Word Break II](https://leetcode.com/problems/word-break-ii/) | Hard | | :white_check_mark: | 139 | [Word Break](https://leetcode.com/problems/word-break/) | Medium | | | 138 | [Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) | Hard | | | 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | Medium | | | 136 | [Single Number](https://leetcode.com/problems/single-number/) | Medium | | | 135 | [Candy](https://leetcode.com/problems/candy/) | Hard | | | 134 | [Gas Station](https://leetcode.com/problems/gas-station/) | Medium | | | 133 | [Clone Graph](https://leetcode.com/problems/clone-graph/) | Medium | | :white_check_mark: | 132 | [Palindrome Partitioning II](https://leetcode.com/problems/surrounded-regions/) | Hard | | :white_check_mark: | 131 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | Medium | | :white_check_mark: | 130 | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | Medium | | :white_check_mark: | 129 | [Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | Medium | | :white_check_mark: | 128 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) | Hard | | :white_check_mark: | 127 | [Word Ladder](https://leetcode.com/problems/word-ladder/) | Medium | | :white_check_mark: | 126 | [Word Ladder II](https://leetcode.com/problems/word-ladder-ii/) | Hard | | :white_check_mark: | 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | Easy | | :white_check_mark: | 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | Hard | | :white_check_mark: | 123 | [Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/) | Hard | | :white_check_mark: | 122 | [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) | Medium | | :white_check_mark: | 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | Medium | | :white_check_mark: | 120 | [Triangle](https://leetcode.com/problems/triangle/) | Medium | | :white_check_mark: | 119 | [Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/) | Easy | | :white_check_mark: | 118 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/) | Easy | | :white_check_mark: | 117 | [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/) | Hard | | :white_check_mark: | 116 | [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) | Medium | | :white_check_mark: | 115 | [Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/) | Hard | | :white_check_mark: | 114 | [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/) | Medium | | :white_check_mark: | 113 | [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | Medium | | :white_check_mark: | 112 | [Path Sum](https://leetcode.com/problems/path-sum/) | Easy | | :white_check_mark: | 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/) | Easy | | :white_check_mark: | 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | Easy | | :white_check_mark: | 109 | [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | Medium | | :white_check_mark: | 108 | [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | Medium | | :white_check_mark: | 107 | [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/) | Easy | | :white_check_mark: | 106 | [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | Medium | | :white_check_mark: | 105 | [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | Medium | | :white_check_mark: | 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | Easy | | :white_check_mark: | 103 | [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) | Medium | | :white_check_mark: | 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) | Easy | | :white_check_mark: | 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) | Easy | | :white_check_mark: | 100 | [Same Tree](https://leetcode.com/problems/same-tree/) | Easy | | :white_check_mark: | 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | Hard | | :white_check_mark: | 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | Medium | | :white_check_mark: | 97 | [Interleaving String](https://leetcode.com/problems/interleaving-string/) | Hard | | :white_check_mark: | 96 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | Medium | | :white_check_mark: | 95 | [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | Medium | | :white_check_mark: | 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | Medium | | :white_check_mark: | 93 | [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | Medium | | :white_check_mark: | 92 | [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) | Medium | | :white_check_mark: | 91 | [Decode Ways](https://leetcode.com/problems/decode-ways/) | Medium | | :white_check_mark: | 90 | [Subsets II](https://leetcode.com/problems/subsets-ii/) | Medium | | :white_check_mark: | 89 | [Gray Code](https://leetcode.com/problems/gray-code/) | Medium | | :white_check_mark: | 88 | [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) | Easy | | :white_check_mark: | 87 | [Scramble String](https://leetcode.com/problems/scramble-string/) | Hard | | :white_check_mark: | 86 | [Partition List](https://leetcode.com/problems/partition-list/) | Medium | | :white_check_mark: | 85 | [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) | Hard | | :white_check_mark: | 84 | [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | Hard | | :white_check_mark: | 83 | [Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | Easy | | :white_check_mark: | 82 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) | Medium | | :white_check_mark: | 81 | [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | Medium | | :white_check_mark: | 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) | Medium | | :white_check_mark: | 79 | [Word Search](https://leetcode.com/problems/word-search/) | Medium | | :white_check_mark: | 78 | [Subsets](https://leetcode.com/problems/subsets/) | Medium | | :white_check_mark: | 77 | [Combinations](https://leetcode.com/problems/combinations/) | Medium | | :white_check_mark: | 76 | [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | Hard | | :white_check_mark: | 75 | [Sort Colors](https://leetcode.com/problems/sort-colors/) | Medium | | :white_check_mark: | 74 | [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | Medium | | :white_check_mark: | 73 | [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) | Medium | | :white_check_mark: | 72 | [Edit Distance](https://leetcode.com/problems/edit-distance/) | Hard | | :white_check_mark: | 71 | [Simplify Path](https://leetcode.com/problems/simplify-path/) | Medium | | :white_check_mark: | 70 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | Easy | | :white_check_mark: | 69 | [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | Medium | | | 68 | [Text Justification](https://leetcode.com/problems/text-justification/) | Hard | | :white_check_mark: | 67 | [Add Binary](https://leetcode.com/problems/add-binary/) | Easy | | :white_check_mark: | 66 | [Plus One](https://leetcode.com/problems/plus-one/) | Easy | | :white_check_mark: | 65 | [Valid Number](https://leetcode.com/problems/valid-number/) | Hard | | :white_check_mark: | 64 | [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) | Medium | | :white_check_mark: | 63 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | Medium | | :white_check_mark: | 62 | [Unique Paths](https://leetcode.com/problems/unique-paths/) | Medium | | :white_check_mark: | 61 | [Rotate List](https://leetcode.com/problems/rotate-list/) | Medium | | :white_check_mark: | 60 | [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | Medium | | :white_check_mark: | 59 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/) | Medium | | :white_check_mark: | 58 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word/) | Easy | | :white_check_mark: | 57 | [Insert Interval](https://leetcode.com/problems/insert-interval/) | Hard | | :white_check_mark: | 56 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/) | Hard | | :white_check_mark: | 55 | [Jump Game](https://leetcode.com/problems/jump-game/) | Medium | | :white_check_mark: | 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | Medium | | :white_check_mark: | 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | Medium | | :white_check_mark: | 52 | [N-Queens II](https://leetcode.com/problems/n-queens-ii/) | Hard | | :white_check_mark: | 51 | [N-Queens](https://leetcode.com/problems/n-queens/) | Hard | | :white_check_mark: | 50 | [Pow(x, n)](https://leetcode.com/problems/powx-n/) | Medium | | :white_check_mark: | 49 | [Group Anagrams](https://leetcode.com/problems/anagrams/) | Medium | | :white_check_mark: | 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | Medium | | :white_check_mark: | 47 | [Permutations II](https://leetcode.com/problems/permutations-ii/) | Medium | | :white_check_mark: | 46 | [Permutations](https://leetcode.com/problems/permutations/) | Medium | | :white_check_mark: | 45 | [Jump Game II](https://leetcode.com/problems/jump-game-ii/) | Hard | | :white_check_mark: | 44 | [Wildcard Matching](https://leetcode.com/problems/wildcard-matching/) | Hard | | :white_check_mark: | 43 | [Multiply Strings](https://leetcode.com/problems/multiply-strings/) | Medium | | :white_check_mark: | 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | Hard | | :white_check_mark: | 41 | [First Missing Positive](https://leetcode.com/problems/first-missing-positive/) | Hard | | :white_check_mark: | 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) | Medium | | :white_check_mark: | 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/) | Medium | | :white_check_mark: | 38 | [Count and Say](https://leetcode.com/problems/count-and-say/) | Easy | | :white_check_mark: | 37 | [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | Hard | | :white_check_mark: | 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | Easy | | :white_check_mark: | 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | Medium | | :white_check_mark: | 34 | [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | Medium | | :white_check_mark: | 33 | [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | Hard | | :white_check_mark: | 32 | [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/) | Hard | | :white_check_mark: | 31 | [Next Permutation](https://leetcode.com/problems/next-permutation/) | Medium | | :white_check_mark: | 30 | [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | Hard | | :white_check_mark: | 29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | Medium | | :white_check_mark: | 28 | [Implement strStr()](https://leetcode.com/problems/implement-strstr/) | Easy | | :white_check_mark: | 27 | [Remove Element](https://leetcode.com/problems/remove-element/) | Easy | | :white_check_mark: | 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | Easy | | :white_check_mark: | 25 | [Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) | Hard | | :white_check_mark: | 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | Medium | | :white_check_mark: | 23 | [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | Hard | | :white_check_mark: | 22 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) | Medium | | :white_check_mark: | 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | Easy | | :white_check_mark: | 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | Easy | | :white_check_mark: | 19 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | Easy | | :white_check_mark: | 18 | [4Sum](https://leetcode.com/problems/4sum/) | Medium | | :white_check_mark: | 17 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) | Medium | | :white_check_mark: | 16 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/) | Medium | | :white_check_mark: | 15 | [3Sum](https://leetcode.com/problems/3sum/) | Medium | | :white_check_mark: | 14 | [Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) | Easy | | :white_check_mark: | 13 | [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | Easy | | :white_check_mark: | 12 | [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | Medium | | :white_check_mark: | 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | Medium | | :white_check_mark: | 10 | [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | Hard | | :white_check_mark: | 9 | [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | Easy | | :white_check_mark: | 8 | [String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/) | Easy | | :white_check_mark: | 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | Easy | | :white_check_mark: | 6 | [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | Easy | | :white_check_mark: | 5 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | Medium | | :white_check_mark: | 4 | [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | Hard | | :white_check_mark: | 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | Medium | | :white_check_mark: | 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | Medium | | :white_check_mark: | 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Medium | <file_sep>/include/KthSmallestElementInABST.hpp #ifndef KTH_SMALLEST_ELEMENT_IN_A_BST_HPP_ #define KTH_SMALLEST_ELEMENT_IN_A_BST_HPP_ #include "TreeNode.hpp" class KthSmallestElementInABST { public: int kthSmallest(TreeNode* root, int k); private: void inOrderSearch(TreeNode* root, int k); int cnt; int result; }; #endif // KTH_SMALLEST_ELEMENT_IN_A_BST_HPP_ <file_sep>/src/HappyNumber.cpp #include "HappyNumber.hpp" #include <unordered_set> using namespace std; bool HappyNumber::isHappy(int n) { unordered_set<int> records; while (n != 1 && records.count(n) == 0) { records.insert(n); int next = 0; while (n > 0) { int d = n % 10; n = n / 10; next += d * d; } n = next; } return n == 1; } <file_sep>/tests/LongestIncreasingSubsequenceTest.cpp #include "catch.hpp" #include "LongestIncreasingSubsequence.hpp" TEST_CASE("Longest Increasing Subsequence") { LongestIncreasingSubsequence s; SECTION("Sample test") { vector<int> nums {10, 9, 2, 5, 3, 7, 101, 18}; REQUIRE(s.lengthOfLIS(nums) == 4); } } <file_sep>/scripts/fmt #!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" ROOT="$( dirname $DIR )" command -v astyle >/dev/null 2>&1 || { echo >&2 "astyle required. aborting."; exit 1; } astyle --options="$ROOT/.astylerc" --recursive "$ROOT/include/*.hpp" "$ROOT/src/*.cpp" "$ROOT/tests/*.cpp" --exclude="$ROOT/tests/catch.hpp" --ignore-exclude-errors<file_sep>/tests/DistinctSubsequencesTest.cpp #include "catch.hpp" #include "DistinctSubsequences.hpp" TEST_CASE("Distinct Subsequences") { DistinctSubsequences s; SECTION("Sample test") { REQUIRE(s.numDistinct("rabbbit", "rabbit") == 3); } } <file_sep>/include/RangeSumQueryImmutable.hpp #ifndef RANGE_SUM_QUERY_IMMUTABLE_HPP_ #define RANGE_SUM_QUERY_IMMUTABLE_HPP_ #include <vector> using namespace std; class NumArray { public: NumArray(vector<int>& nums); int sumRange(int i, int j); private: vector<int> accs; }; #endif // RANGE_SUM_QUERY_IMMUTABLE_HPP_ <file_sep>/src/ScrambleString.cpp #include "ScrambleString.hpp" // #include <vector> #include <algorithm> using namespace std; bool ScrambleString::isScramble(string s1, string s2) { if (s1.size() != s2.size()) { return false; } int sz = s1.size(); if (sz == 0) { return true; } // vector<vector<vector<bool>>> dp(sz, vector<vector<bool>>(sz, vector<bool>(sz, false))); // for speed reason, do not use vectors bool dp[sz][sz][sz]; fill_n(&dp[0][0][0], sz * sz * sz, false); for (int i = 0; i < sz; i++) for (int j = 0; j < sz; j++) { dp[0][i][j] = s1[i] == s2[j]; } for (int k = 1; k < sz; k++) { for (int i = 0; i < sz - k; i++) { for (int j = 0; j < sz - k; j++) { // consider dp[k][i][j] => [i ... i+k] & [j ... j+k] // split it to the following two parts: // @ PART I @ // <[i], [j+k]> && <[i+1, i+k], [j, j+k-1]> // <[i, i+1], [j+k-1, j+k]> && <[i+2, j+k], [j, j+k-2]> // ... // <[i, i+k-1], [j+1, j+k]> && <[i+k], [j]> // @ PART II @ // <[i], [j]> && <[i+1, i+k], [j+1, j+k]> // <[i, i+1], [j, j+1]> && <[i+2, j+k], [j+2, j+k]> // ... // <[i, i+k-1], [j, j+k-1]> && <[i+k], [j+k]> for (int l = 0; l < k; l++) { if ((dp[l][i][j + k - l] && dp[k - l - 1][i + l + 1][j]) || (dp[l][i][j] && dp[k - l - 1][i + l + 1][j + l + 1])) { dp[k][i][j] = true; break; } } } } } return dp[sz - 1][0][0]; } <file_sep>/src/RecoverBinarySearchTree.cpp #include "RecoverBinarySearchTree.hpp" #include <algorithm> using namespace std; void RecoverBinarySearchTree::recoverTree(TreeNode* root) { inOrderTraversal(root); sort(nodeVals.begin(), nodeVals.end()); for (int i = 0; i < nodePtrs.size(); i++) { nodePtrs[i]->val = nodeVals[i]; } } void RecoverBinarySearchTree::inOrderTraversal(TreeNode* root) { if (root == nullptr) { return; } inOrderTraversal(root->left); nodePtrs.push_back(root); nodeVals.push_back(root->val); inOrderTraversal(root->right); } <file_sep>/src/BestTimeToBuyAndSellStockIV.cpp #include "BestTimeToBuyAndSellStockIV.hpp" #include <algorithm> using namespace std; int BestTimeToBuyAndSellStockIV::maxProfit(int k, vector<int>& prices) { /** * local[i][j]: i day, j txn, jth txn happened at day i * global[i][j]: i day, j txn * * diff = prices[i] - prices[i-1] * local[i][j] = max(global[i-1][j-1] + max(diff, 0), local[i-1][j] + diff) * global[i][j] = max(global[i-1][j], local[i][j]) */ int days = prices.size(); if (days <= 1) { return 0; } if (k >= days) { return maxProfitNoLimits(prices); } vector<int> local(k + 1, 0); vector<int> global(k + 1, 0); for (int i = 1; i < days; i++) { for (int j = k; j >= 1; j--) { int diff = prices[i] - prices[i - 1]; local[j] = max(global[j - 1] + max(diff, 0), local[j] + diff); global[j] = max(global[j], local[j]); } } return global[k]; } int BestTimeToBuyAndSellStockIV::maxProfitNoLimits(vector<int>& prices) { int result = 0; for (int i = 1; i < prices.size(); i++) { int diff = prices[i] - prices[i - 1]; if (diff > 0) { result += diff; } } return result; } <file_sep>/src/EditDistance.cpp #include "EditDistance.hpp" #include <vector> #include <algorithm> using namespace std; int EditDistance::minDistance(string word1, string word2) { return minDistance_Optimized(word1, word2); } int EditDistance::minDistance_Raw(string word1, string word2) { int m = word1.length(), n = word2.length(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (int i = 1; i <= m; i++) { dp[i][0] = i; } for (int j = 1; j <= n; j++) { dp[0][j] = j; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = min(dp[i - 1][j - 1] + 1, min(dp[i][j - 1] + 1, dp[i - 1][j] + 1)); } } } return dp[m][n]; } int EditDistance::minDistance_Optimized(string word1, string word2) { int m = word1.length(), n = word2.length(); vector<int> pre(m + 1, 0); vector<int> cur(m + 1, 0); for (int i = 1; i <= m; i++) { pre[i] = i; } for (int j = 1; j <= n; j++) { cur[0] = j; for (int i = 1; i <= m; i++) { if (word1[i - 1] == word2[j - 1]) { cur[i] = pre[i - 1]; } else { cur[i] = min(pre[i - 1] + 1, min(pre[i] + 1, cur[i - 1] + 1)); } } swap(pre, cur); } return pre[m]; }<file_sep>/src/SymmetricTree.cpp #include "SymmetricTree.hpp" bool SymmetricTree::isSymmetric(TreeNode* root) { if (root == nullptr) { return true; } return isSymmetric(root->left, root->right); } bool SymmetricTree::isSymmetric(TreeNode* l, TreeNode* r) { if (l == nullptr && r == nullptr) { return true; } if (l == nullptr || r == nullptr) { return false; } return (l->val == r->val) && isSymmetric(l->left, r->right) && isSymmetric(l->right, r->left); } <file_sep>/include/NumberOfIslands.hpp #ifndef NUMBER_OF_ISLANDS_HPP_ #define NUMBER_OF_ISLANDS_HPP_ #include <vector> using namespace std; class NumberOfIslands { public: int numIslands(vector<vector<char>>& grid); private: void bfs(vector<vector<char>>& grid, int i, int j); }; #endif // NUMBER_OF_ISLANDS_HPP_ <file_sep>/include/BinaryTreeRightSideView.hpp #ifndef BINARY_TREE_RIGHT_SIDE_VIEW_HPP_ #define BINARY_TREE_RIGHT_SIDE_VIEW_HPP_ #include "TreeNode.hpp" #include <vector> using namespace std; class BinaryTreeRightSideView { public: vector<int> rightSideView(TreeNode* root); private: void bfs(TreeNode* root, vector<int>& result); }; #endif // BINARY_TREE_RIGHT_SIDE_VIEW_HPP_ <file_sep>/src/RangeSumQuery2DImmutable.cpp #include "RangeSumQuery2DImmutable.hpp" NumMatrix::NumMatrix(vector<vector<int>>& matrix) { int nrows = matrix.size(); if (nrows == 0) { return; } int ncols = matrix[0].size(); sum.resize(nrows); for (int i = 0; i < nrows; i++) { sum[i].resize(ncols); int acc = 0; for (int j = 0; j < ncols; j++) { acc += matrix[i][j]; sum[i][j] = acc; } } } int NumMatrix::sumRegion(int row1, int col1, int row2, int col2) { int acc = 0; for (int i = row1; i <= row2; i++) { if (col1 == 0) { acc += sum[i][col2]; } else { acc += (sum[i][col2] - sum[i][col1 - 1]); } } return acc; }<file_sep>/src/BinaryTreeRightSideView.cpp #include "BinaryTreeRightSideView.hpp" #include <queue> using namespace std; vector<int> BinaryTreeRightSideView::rightSideView(TreeNode* root) { vector<int> result; bfs(root, result); return result; } void BinaryTreeRightSideView::bfs(TreeNode* root, vector<int>& result) { if (root == nullptr) { return; } queue<TreeNode*> q; q.push(root); while (!q.empty()) { int num = q.size(); // number of nodes at this level for (int i = 0; i < num; i++) { TreeNode* n = q.front(); q.pop(); if (n->left != nullptr) { q.push(n->left); } if (n->right != nullptr) { q.push(n->right); } if (i == num - 1) { result.push_back(n->val); } } } } <file_sep>/src/UniqueBinarySearchTreesII.cpp #include "UniqueBinarySearchTreesII.hpp" vector<TreeNode*> UniqueBinarySearchTreesII::generateTrees(int n) { vector<vector<TreeNode*>> dp(n + 1); dp[0].push_back(nullptr); for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { for (auto l : dp[j - 1]) { for (auto r : dp[i - j]) { TreeNode* root = new TreeNode(j); // FIXME: // No need to clone left subtree // Tradeoff for correctly freeing all the trees root->left = clone(l, 0); root->right = clone(r, j); dp[i].push_back(root); } } } } return dp[n]; } TreeNode* UniqueBinarySearchTreesII::clone(TreeNode* root, int offset) { TreeNode* nroot = nullptr; if (root != nullptr) { nroot = new TreeNode(root->val + offset); nroot->left = clone(root->left, offset); nroot->right = clone(root->right, offset); } return nroot; } <file_sep>/src/LongestIncreasingSubsequence.cpp #include "LongestIncreasingSubsequence.hpp" int LongestIncreasingSubsequence::lengthOfLIS(vector<int>& nums) { int sz = nums.size(); if (sz == 0) { return 0; } int ret = 1; vector<int> dp(sz, 1); for (int i = 1; i < sz; i++) { for (int j = 0; j < i; j++) { if (nums[i] > nums[j] && dp[j] + 1 > dp[i]) { dp[i] = dp[j] + 1; if (ret < dp[i]) { ret = dp[i]; } } } } return ret; }<file_sep>/include/RecoverBinarySearchTree.hpp #ifndef RECOVER_BINARY_SEARCH_TREE_HPP_ #define RECOVER_BINARY_SEARCH_TREE_HPP_ #include "TreeNode.hpp" #include <vector> using namespace std; class RecoverBinarySearchTree { private: vector<TreeNode*> nodePtrs; vector<int> nodeVals; public: void recoverTree(TreeNode* root); private: void inOrderTraversal(TreeNode* root); }; #endif // RECOVER_BINARY_SEARCH_TREE_HPP_ <file_sep>/src/MinimumPathSum.cpp #include "MinimumPathSum.hpp" #include <algorithm> using namespace std; int MinimumPathSum::minPathSum(vector<vector<int>>& grid) { return minPathSum_Optimized(grid); } int MinimumPathSum::minPathSum_Raw(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); dp[0][0] = grid[0][0]; for (int i = 1; i < m; i++) { dp[i][0] = dp[i - 1][0] + grid[i][0]; } for (int j = 1; j < n; j++) { dp[0][j] = dp[0][j - 1] + grid[0][j]; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; } } return dp[m - 1][n - 1]; } int MinimumPathSum::minPathSum_Optimized(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); vector<int> pre(m, 0); vector<int> cur(m, 0); pre[0] = grid[0][0]; for (int i = 1; i < m; i++) { pre[i] = pre[i - 1] + grid[i][0]; } for (int j = 1; j < n; j++) { cur[0] = pre[0] + grid[0][j]; for (int i = 1; i < m; i++) { cur[i] = min(pre[i], cur[i - 1]) + grid[i][j]; } swap(pre, cur); } return pre[m - 1]; }<file_sep>/include/MaximumSubarray.hpp #ifndef MAXIMUM_SUBARRAY_HPP_ #define MAXIMUM_SUBARRAY_HPP_ #include <vector> using namespace std; class MaximumSubarray { public: int maxSubArray(vector<int>& nums); private: int maxSubArray_DynamicProgramming(vector<int>& nums); int maxSubArray_Array(vector<int>& nums); int maxSubArray_DivideAndConquer(vector<int>& nums); int helper(vector<int>& nums, int left, int right); }; #endif // MAXIMUM_SUBARRAY_HPP_ <file_sep>/src/CoinChange.cpp #include "CoinChange.hpp" #include <climits> using namespace std; int CoinChange::coinChange(vector<int>& coins, int amount) { if (amount <= 0) { return 0; } vector<int> items; for (auto c : coins) { if (c < amount) { items.push_back(c); } else if (c == amount) { return 1; } } vector<int> dp(amount + 1, INT_MAX); dp[0] = 0; for (int i = 0; i < items.size(); i++) { for (int v = items[i]; v <= amount; v++) { dp[v] = min(dp[v], (dp[v - items[i]] == INT_MAX) ? INT_MAX : dp[v - items[i]] + 1); } } return dp[amount] == INT_MAX ? -1 : dp[amount]; }
30d743f22bd26feec0c9fc430be80dcbc8d31f9f
[ "Markdown", "C++", "Shell" ]
98
C++
mrnixe/leetcode-1
66ca79a58cbdf7f291e059bfabc7d8b71ac9e000
985ce1d034dec119613852785920181e679f5404
refs/heads/master
<repo_name>AmaryllisLee/AAI-V1A-SP<file_sep>/Opdracht 1.py import pymongo import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from pymongo import MongoClient import pprint #Connect to Mongodb databse def connection(): 'connect to Mongo db ' client = MongoClient() db = client.database_shopping_minds return db #---------------------------------------------------------------------------------------- def table_product(db_name): 'create tables in Postgresql' con = psycopg2.connect(dbname=db_name, user='postgres',password='<PASSWORD>') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() try: cur.execute('CREATE TABLE Products(' 'product_id int, ' 'brand varchar(255) ,' 'category varchar(255),' 'gender varchar(255),' 'price decimal(10,2),' 'has_sale bool,' 'PRIMARY KEY(product_id))') print('worked') except: pass cur.close() con.close() def table_klant(db_name): 'create table Klant in Postgres' con = psycopg2.connect(dbname=db_name, user='postgres', password='<PASSWORD>') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() try: cur.execute('CREATE TABLE Klant(' 'klant_id int, ' 'segment varchar(255) ,' 'has_mail bool,' 'session_start date, ' 'session_ends date,' 'PRIMARY KEY (klant_id))') except: pass cur.close() con.close() def transfer_product(db_name): 'Transfer from mongo db in to Table product ' db = connection() products = db['products'] lst_1 = [] for x in products.find({},{'brand':1,'category':1,'gender':1, 'price.selling_price':1}): lst_1.append(x) print(x) klant = db['sessions'] for i in klant.find({}, {'has_sale':1}): lst_1.append(i) print(lst_1) con = psycopg2.connect(dbname=db_name, user='postgres', password='<PASSWORD>') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() try: for atr in lst_1: print(atr) cur.execute('Insert into Product(object_id, brand, category,gender, price, has_sale) ' 'VALUES (\'{},{},{},{},{},{}\')'.format(atr['_id'],atr['brand'],atr['category'],atr['gender'],atr['price']['selling_price'],atr['has_sale'])) print('it worked') except: print('Keep trying') cur.close() con.close() def transfer_klant(db_name): 'Transfer from mongo db in to Table klant ' db = connection('database_shopping_minds') visitors = db ['visitors'] lst_2 = [] for item in visitors.find({},{'recommendations.segment' : 1,'meta.has_mail':1}): lst_2.append(item) klant = db['sessions'] for iets in klant.find({}, {'user_agent.session_start':1,'user_agent.session_end':1 }): lst_2.append(iets) con = psycopg2.connect(dbname=db_name, user='postgres', password='<PASSWORD>') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() try: for atrib in lst_2: cur.execute('Insert into Klant(klant_id, segment, has_mail, session_start, session_ends) ' 'VALUES (\'{},{},{},{},{}\')'.format(atrib['_id'],atrib['reommendations']['segment'],atrib['meta']['has_mail'],atrib['session_start'],atrib['session_end'])) print('it worked') except: print('Keep trying') cur.close() con.close() #---------------------------------------------------- connection() sql_db = 'transfer_db' table_product(sql_db) table_klant(sql_db) transfer_product(sql_db) transfer_klant(sql_db) <file_sep>/EngineAPI-session/koppeling_databases.py from pymongo import MongoClient import psycopg2 #Koppeling maken met SQL database def sql_connect(sql_db, us,pw): 'Connect to SQl db' connection = psycopg2.connect(dbname=sql_db, user='postgres', password='<PASSWORD>') return connection #Koppeling maken met MOngodb database def mongodb_connect(mongo_db, collection): 'Connect to Mongodb db' mongoclient = MongoClient() mongodb = mongoclient['{}'].format(mongo_db) collection_connected = mongodb['{}'].format(collection) return collection_connected <file_sep>/EngineAPI-session/products.py from typing import List, Any from koppeling_databases import sql_connect, mongodb_connect import psycopg2 #Connection with Mongodb database mongo_db,collection = 'database_shopping_minds','product' #------------------------------------------------------------------------------------- def getPopularProducts(db_name, us,pw,table, g): 'Haal bepaalde fields ' con = 'recommendable == true' #vb conditionals limit=3 id_pp = sql(db_name, us,pw,g, table, con, limit) return lst_mongo(id_pp,mongo_db,collection) def getSimilarproducts(db_name, us,pw,table, g): 'Haal bepaalde fields' con = 'price=179' limit = 3 id_sp = sql(db_name, us,pw,g, table, con, limit) return lst_mongo(id_sp, mongo_db, collection) def getPersonalProducts(session): print("Recommendations for session: {}".format(session['_id'])) return [ {"_id": "23978", "brand": "8x4", "category": "Gezond & verzorging", "deeplink": "https://www.opisopvoordeelshop.nl/8x4-men-men-beast-deospray-150ml"}, {"_id": "22309", "brand": "Agfa", "category": "Elektronica & media", "deeplink": "https://www.opisopvoordeelshop.nl/afgaphoto-alkaline-power-batterijen-aa-4-stuks"} ] #---------------------------------------------------------------------- # Function for lijst van de product uit SQL def sql(db_name, us,pw, g, table, condition, limit): 'Lijst van ids weergeven met bepaalde conditionals' con = sql_connect(db_name,us,pw) #Connect with the SQL db query = 'Select {} from {} where {} limit {}'.format(g,table, condition,limit)#Query that get 3 of the product id\'s that is tue with the condition' cur = con.cursor() cur.execute(query) cur.close() con.commit() return def lst_mongo(s, mongo_db, collection): 'Field in mongo van de ids in lst_sql in een lijst zetten' collection= mongodb_connect(mongo_db, collection) # connect to mongodb db mongo_lst = [] for i in s: for x in collection({},{'{}':1,'category':1, 'price.selling_price':1, 'deeplink':1}).format(i): mongo_lst.append(x) return mongo_lst print(getPopularProducts())
de93a4f7590fd7fb523db3413c9e2b44b24faae8
[ "Python" ]
3
Python
AmaryllisLee/AAI-V1A-SP
ac343c888f9eeebb53da9411a7c9402e892a52d3
10b35b2a443cc16dd500bc6e1f0e993624184a40
refs/heads/master
<repo_name>Max00355/ByteMail<file_sep>/message.py import db import ssl import json import uuid from rsa import * import base64 import antispam import aes def message(obj, ip, data): addr = db.data.find("data", "all")[0]['addr'] msg = data['message'] from_ = data['from'] title = data['title'] to = data['to'] id = data['id'] as_nonce = data['nonce'] as_num = data['num'] key = data['key'] if antispam.check_antispam(to,from_,msg,as_num,as_nonce,antispam.get_required_difficulty(msg)): if len(from_) == 32 and len(to) == 32: db.messages.insert("messages", {"id":id, "message":msg, "from":from_, "title":title, "to":to,"as_num":as_num,"as_nonce":as_nonce,"key":key}) if to == addr: print "\nYou have a new message from", from_ def send_msg(msg, title, to, addr): try: data = db.nodes.find("nodes", {"addr":to})[0] except: return "Address doesn't exist" if data['publickey'].startswith("PublicKey(") and data['publickey'].endswith(")"): # msg = encrypt(msg, eval(data['publickey'])) <--- Old encryption code aeskey = str(uuid.uuid4().hex) # Generate new AES Key key = encrypt(aeskey, eval(data['publickey'])) # Encrypt AES key with target's RSA Public Key key = base64.b64encode(key) # Base64 encode the key msg = aes.encryptData(aeskey,msg) # Encrypt Message with AES Key msg = base64.b64encode(msg) # Base64 encode the message as_num, as_nonce = antispam.find_antispam(to,addr,msg,antispam.get_required_difficulty(msg)) else: return "Invalid public key for", addr id = "" while True: id = uuid.uuid4().hex if db.messages.find("messages", {"id":id}): continue else: break print "Sending message ID " + id + " with key " + key nodes = db.nodes.find("nodes", "all") for x in nodes: s = ssl.socket() try: s.settimeout(1) s.connect((x['ip'], x['port'])) s.send(json.dumps({"cmd":"message", "id":id, "message":msg, "title":title, "to":to, "from":addr,"num":as_num,"nonce":as_nonce,"key":key})) s.close() except Exception, error: db.unsent.insert("unsent", {"to":[x['ip'], x['port']], "message":{"cmd":"message", "id":id, "message":msg, "title":title, "to":to, "from":addr,"num":as_num,"nonce":as_nonce,"key":key}}) return "Message Sent!" <file_sep>/bytemail.py import socket import db import checkin import message import read import check import json import threading import os import uuid import cmd import thread import unsent import delete import ssl import get_messages import get_nodes import time import random import rsa import addressbook __version__ = "0.2.82" class ByteMail: def __init__(self, addr, pubkey): self.cmds = { "delete":delete.delete, "checkin":checkin.checkin, "message":message.message, "get_messages":get_messages.get_messages, "get_nodes":get_nodes.get_nodes, } self.broker = ("172.16.31.10", 4321) self.addr = addr self.pubkey = pubkey self.port = 5333 self.host = "0.0.0.0" self.open_port = False self.config = { "relay":False } def main(self): if not db.nodes.find("nodes", "all"): check = self.config['relay'] if check: self.open_port = True print "You are running as a relay node." db.data.insert("data", {"port":self.port}) print "Downloading Nodes..." self.get_nodes() print "Checking in to nodes..." self.send_checkin() print "Done!" check = self.config['relay'] if check: self.open_port = True print "You are running as a relay node." else: print "You are not running as a relay node." if self.open_port: sock = ssl.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((self.host, self.port)) sock.listen(5) while True: obj, conn = sock.accept() threading.Thread(target=self.handle, args=(obj, conn[0])).start() else: while True: check = db.nodes.find("nodes", "all") random.shuffle(check) node = None for x in check: s = ssl.socket() try: s.connect((x['ip'], x['port'])) except: s.close() continue else: node = (x['ip'], x['port']) s.close() break sock = ssl.socket() try: sock.connect(node) except: continue else: while True: try: get_messages.send_get_messages(x['ip'], x['port']) get_nodes.send_get_nodes(x['ip'], x['port']) time.sleep(10) except Exception, error: sock.close() break def handle(self, obj, ip): data = obj.recv(102400) if data: data = json.loads(data) self.cmds[data['cmd']](obj, ip, data) def send_checkin(self): nodes = db.nodes.find("nodes", "all") for x in nodes: s = ssl.socket() try: s.settimeout(1) s.connect((x['ip'], x['port'])) s.send(json.dumps({"cmd":"checkin", "addr":self.addr, "port":self.port, "publickey":self.pubkey})) s.close() except Exception, error: s.close() db.unsent.insert("unsent", {"to":[x['ip'], x['port']], "message":{"cmd":"checkin", "addr":self.addr, "port":self.port, "publickey":self.pubkey}}) def get_nodes(self): send = {"addr":self.addr, "port":self.port, "publickey":self.pubkey} s = ssl.socket() s.connect(self.broker) s.send(json.dumps(send)) with open("nodes.db", 'wb') as file: while True: data = s.recv(1024) if data: file.write(data) else: break print "Downloaded Nodes!" class Prompt(cmd.Cmd): prompt = "ByteMail$ " def do_send(self, line): addr = db.data.find("data", "all")[0]['addr'] to = raw_input("To: ") if len(to) != 32: if len(str(addressbook.check_entry(to))) != 32: print "Address Invalid." return else: to = str(addressbook.check_entry(to)) title = raw_input("Title: ") msg = raw_input("Message: ") if not to or not title or not msg: print "You need to fill out all the fields." else: print message.send_msg(msg, title, to, addr) def do_check(self, line): addr = db.data.find("data", "all")[0]['addr'] check_ = check.check(addr) if not check_: print "You have no messages." else: for x in check_: print x def do_read(self, id): addr = db.data.find("data", "all")[0]['addr'] print read.read(id, addr) def do_addr(self, line): addr = db.data.find("data", "all")[0]['addr'] print "Your address is:", addr def do_add_address(self, line): name = raw_input("Name: ") address = raw_input("Address: ") addressbook.add_entry(name,address) def do_delete(self, line): addr = db.data.find("data", "all")[0]['addr'] print delete.send_delete(line, addr) def do_exit(self, line): print "Bye!" exit() if __name__ == "__main__": exists = db.data.find("data", "all") if not exists: print "First time running ByteMail" print "Generating new keys... This could take a while." publickey, privatekey = rsa.newkeys(512) db.data.insert("data", {"addr":uuid.uuid4().hex, "publickey":str(publickey), "privatekey":str(privatekey)}) db.messages.insert("messages", {}) data = db.data.find("data", "all")[0] addr = data['addr'] pubkey = data['publickey'] else: data = db.data.find("data", "all")[0] addr = data['addr'] pubkey = data['publickey'] b = ByteMail(addr, pubkey) c = Prompt() thread.start_new_thread(b.main, ()) thread.start_new_thread(unsent.unsent, ()) while True: try: c.cmdloop() except KeyboardInterrupt: continue <file_sep>/README.md Development has been moved to an organization https://github.com/ByteMail/ByteMail <file_sep>/delete.py import db import ssl import json def delete(obj, ip, data): message = db.messages.find("messages", {"id":data['id']}) try: db.messages.remove("messages", message[0]) except IndexError: pass def send_delete(id, addr): message = db.messages.find("messages", {"id":id}) if not message: return "Message with that ID doesn't exist." else: db.messages.remove("messages", message[0]) nodes = db.nodes.find("nodes", "all") for x in nodes: try: sock = ssl.socket() sock.settimeout(1) sock.connect((x['ip'], x['port'])) sock.send(json.dumps({"cmd":"delete", "to":addr, "id":id})) except: db.unsent.insert("unsent", {"to":[x['ip'], x['port']], "message":{"cmd":"delete", "addr":addr, "id":id}}) sock.close() return "Message Removed!" <file_sep>/addressbook.py import db def check_entry(entryname): ourdb = db.addressdb.find("addresses","all") for x in ourdb: try: return x[entryname] except Exception, error: pass return None def add_entry(entryname,address): db.addressdb.insert("addresses",{entryname:address})
1b9819236d51d586608290eeb27eacf44f2eb61a
[ "Markdown", "Python" ]
5
Python
Max00355/ByteMail
8d450ce959448f20f7e0d1dc6a0c81e6316b14aa
0e9f4ed87a2a5885686e07abf970b7251a6205dc
refs/heads/master
<file_sep>package com.example.android.muse; import android.os.Parcel; import android.os.Parcelable; //Learned how to add the Parcelable interface from here: http://www.vogella.com/tutorials/AndroidParcelable/article.html public class Song implements Parcelable { //Name of the title of each song object private String mSongTitle; //Name of the artist of each song object private String mArtistName; //Drawable resource ID for song art/album cover for each song object; private int mImageResourceId; /** * Create a new song object: * * @param songTitle is the title of the song provided in the arrayList * @param artistName is the artist of the song that corresponds to the song * @param imageResourceId is drawable reference ID that corresponds to the song **/ //Create a song constructor public Song(String songTitle, String artistName, int imageResourceId) { mSongTitle = songTitle; mArtistName = artistName; mImageResourceId = imageResourceId; } //For reconstructing the parceled data back into a Song object protected Song(Parcel in) { mSongTitle = in.readString(); mArtistName = in.readString(); mImageResourceId = in.readInt(); } //Parcelable Creator method for implementing the interface public static final Creator<Song> CREATOR = new Creator<Song>() { @Override public Song createFromParcel(Parcel in) { return new Song(in); } @Override public Song[] newArray(int size) { return new Song[size]; } }; //Song getter and setter methods public String getSongTitle() { return mSongTitle; } public void setSongTitle(String songName) { mSongTitle = songName; } public String getArtistName() { return mArtistName; } public void setArtistName(String artistName) { mArtistName = artistName; } public int getImageResourceId() { return mImageResourceId; } public void setImageResourceId(int imageResourceId) { mImageResourceId = imageResourceId; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mSongTitle); dest.writeString(mArtistName); dest.writeInt(mImageResourceId); } @Override public String toString() { return "Song{" + "title='" + mSongTitle + '\'' + ", artist='" + mArtistName + '\'' + ", cover='" + mImageResourceId + '\'' + '}'; } } <file_sep>package com.example.android.muse; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class SongAdapter extends ArrayAdapter<Song> { private ArrayList<Song> songs; Context mContext; public SongAdapter(Activity context, ArrayList<Song> songs) { super(context, 0, songs); } /** * Override code received through code --> Override methods * Overriding getView method to provide new layout for the listView */ @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { final View listItemView = getWorkingView(convertView); final ViewHolder viewHolder = getViewHolder(listItemView); //Get the Word object located at the current position in the list final Song currentSong = getItem(position); //Get the title associated with current Song object in the ArrayList and set it on the TextView stored in viewHolder viewHolder.title_text_view.setText(currentSong.getSongTitle()); //Get the artist associated with the current Song object in the ArrayList and set it on the TextView stored in viewHolder viewHolder.artist_text_view.setText(currentSong.getArtistName()); //Get the resource ID associated with current Song object and set it on the ImageView stored in viewHolder viewHolder.song_image_view.setImageResource(currentSong.getImageResourceId()); //Set the ImageResourceID as a tag for passing in Parcelable extra in the SongActivity viewHolder.song_image_view.setTag(currentSong.getImageResourceId()); //Return the list item layout for implementation by the ListView return listItemView; } //Method for recycling view or inflating a new one private View getWorkingView(final View convertView) { View workingView = null; if (null == convertView) { final Context context = getContext(); final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); workingView = inflater.inflate(R.layout.song_list_item, null); } else { workingView = convertView; } return workingView; } ////Added viewHolder in adapter learned via http://www.learn-android.com/2011/11/22/lots-of-lists-custom-adapter/3/ /// Create a new ViewHolder to keep track of necessary references for optimized performance private static class ViewHolder { public TextView title_text_view; public TextView artist_text_view; public ImageView song_image_view; } private ViewHolder getViewHolder(final View workingView) { final Object tag = workingView.getTag(); ViewHolder viewHolder = null; if (null == tag || !(tag instanceof ViewHolder)) { viewHolder = new ViewHolder(); //Locate the TextView in the song_list_item.xml that holds the song title for Song object via findViewByID viewHolder.title_text_view = (TextView) workingView.findViewById(R.id.title_text_view); //Locate the TextView in the song_list_item_item.xml that holds the artist for the Song object via findViewByID viewHolder.artist_text_view = (TextView) workingView.findViewById(R.id.artist_text_view); //Locate the ImageView int the song_list_item_item.xml that holds the album/artist art for the Song Object viewHolder.song_image_view = (ImageView) workingView.findViewById(R.id.song_image_view); workingView.setTag(viewHolder); } else { viewHolder = (ViewHolder) tag; } return viewHolder; } }
d133ccacdba26d5a5b913d3112f504d18a112943
[ "Java" ]
2
Java
kangarruu/Muse
1a602a746c555aaa920c6873d6733f34a9786f94
49932aa9277f319c72e47e4f5f76b35573d009dd
refs/heads/master
<file_sep>const NodeMediaServer = require("node-media-server"), config = require("./config/index").rtmp_server, User = require("./database/Schema").User, helpers = require("./helpers/helpers"); nms = new NodeMediaServer(config); nms.on("prePublish", async (id, StreamPath, args) => { let stream_key = getStreamKeyFromStreamPath(StreamPath); console.log( "[NodeEvent on prePublich]", `id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}` ); User.findOne({ stream_key: stream_key }, (err, user) => { if (!err) { if (!user) { let session = nms.getSession(id); session.reject(); } else { helpers.generateStreamThumbnail(stream_key); } } }); }); const getStreamKeyFromStreamPath = path => { let parts = path.split("/"); return parts[parts.length - 1]; }; module.exports = nms; <file_sep>const TimeCard = require("../models/Timecard"); module.exports = { async show(req, res) { const { user_id } = req.headers; const timecard = await TimeCard.find({ user: user_id }); return res.json(timecard); } }; <file_sep>const User = require("../models/User"); const Timecard = require("../models/Timecard"); module.exports = { async index(req, res) { const { date, user_id } = req.query; const timecard = await Timecard.find({ date: date, user: user_id }); return res.json(timecard); }, async store(req, res) { const { filename } = req.file; const { date, hours } = req.body; const { user_id } = req.headers; const user = await User.findById(user_id); if (!user) { return res.status(400).json({ error: "USER DOES NOT EXIST" }); } const timecard = await Timecard.create({ user: user_id, thumbnail: filename, date, hours: hours.split(",").map(hours => hours.trim()) }); return res.json(timecard); }, async update(req, res) { const user = await User.findById(user_id); const timecard = await Timecard.updateOne({ user: user_id, thumbnail: filename, date, hours: hours.split(",").map(hours => hours.trim()) }); return res.json(timecard); } }; <file_sep># Pongo Projeto de Nuvem para diferentes serviços <file_sep>const passport = require("passport"), LocalStrategy = require("passport-local").Strategy, User = require("../database/Schema").User, shortid = require("shortid"); passport.serializeUser((user, cb) => { cb(null, user); }); passport.deserializeUser((obj, cb) => { cb(null, obj); }); // Passport strategy for handling user registration passport.use( "localRegister", new LocalStrategy( { usernameField: "email", passwordField: "<PASSWORD>", passReqToCallback: true }, (req, email, password, done) => { User.findOne( { $or: [{ email: email }, { username: req.body.username }] }, (err, user) => { if (err) return done(err); if (user) { if (user.email === email) { req.flash("email", "Email is already taken"); } if (user.username === req.body.username) { req.flash("username", "Username is already taken"); } return done(null, false); } else { let user = new User(); user.email = email; user.password = <PASSWORD>); user.username = req.body.username; user.stream_key = shortid.generate(); user.save(err => { if (err) throw err; return done(null, user); }); } } ); } ) ); passport.use( "localLogin", new LocalStrategy( { usernameField: "email", passwordField: "<PASSWORD>", passReqToCallback: true }, (req, email, password, done) => { User.findOne({ email: email }, (err, user) => { if (err) return done(err); if (!user) return done(null, false, req.flash("email", "Email doesn't exist.")); if (!user.validPassword(password)) return done( null, false, req.flash("password", "<PASSWORD>.") ); console.log("entrou por aqui"); return done(null, user); }); } ) ); module.exports = passport; <file_sep>const express = require("express"), route = express.Router(), User = require("../database/Schema").User; route.get( "/info", require("connect-ensure-login").ensureLoggedIn(), (req, res) => { if (req.query.streams) { let streams = JSON.parse(req.query.streams); let query = { $or: [] }; for (let stream in streams) { if (!streams.hasOwnProperty(stream)) continue; query.$or.push({ stream_key: stream }); } User.find(query, (err, users) => { if (err) return; if (users) { res.json(users); } }); } } ); module.exports = route; <file_sep>import React from "react"; import axios from "axios"; export default class Navbar extends React.Component { constructor(props) { super(props); this.state = { stream_key: "" }; this.generateStreamKey = this.generateStreamKey.bing(this); } componentDidMount() { this.getStreamKey(); } generateStreamKey(e) { axios.post("/settings/stream_key").then(res => { this.setState({ stream_key: res.data.stream_key }); }); } render() { return ( <React.Fragment> <div className="container mt-5"> <h4>Streaming Key</h4> <hr className="my-4" /> <div className="col-xl-12 col-sm-12 col-md-8 col-lg-6"> <div className="row"> <h5>{this.state.stream_key}</h5> </div> <div className="row"> <button className="btn btn-dark mt-2" onClick={this.generateStreamKey} > Gerar uma nova chave </button> </div> </div> </div> <div className="container mt-5"> <h4>How to Stream</h4> <hr className="my-4" /> <div className="col-12"> <div className="row"> <p> Pode acessar isso aqui{" "} <a target="_blank" href="https://obsproject.com/pt-br"> OBS </a> ou{" "} <a target="_blank" href="https://www.xsplit.com/pt-br/"> Xplits </a> to Live Stream. Se você estiver usando o OBS, vá para Configurações> Fluxo e selecione Personalizado no menu suspenso. Digite <b> rtmp: //127.0.0.1: 1935 / live </b> no campo de entrada do servidor. Além disso, adicione sua chave de fluxo. Clique em Aplicar para salvar. </p> </div> </div> </div> </React.Fragment> ); } } <file_sep>const express = require("express"); const multer = require("multer"); const uploadConfig = require("./config/upload"); const SessionController = require("./controller/SessionController"); const TimeCardController = require("./controller/TimeCardController"); const DashboardController = require("./controller/DashboardController"); const routes = express.Router(); const upload = multer(uploadConfig); routes.get("/"); routes.post("/sessions", SessionController.store); routes.get("/timecards", TimeCardController.index); routes.post("/timecards", upload.single("thumbnail"), TimeCardController.store); routes.get("/dashboard", DashboardController.show); routes.post("/timecards/:timecard_id/booking"); module.exports = routes; <file_sep>const CronJob = require("cron").CronJob, request = require("request"), helpers = require("../helpers/helpers"), config = require("../config/index"), port = config.rtmp_server.http.port; const job = new CronJob( "*/5 * * * * *", function() { request.get("http://127.0.0.1:" + port + "/api/streams", function( error, response, body ) { let streams = JSON.parse(body); if (typeof (streams["live"] !== undefined)) { let live_stream = stream["live"]; for (let stream in live_stream) { if (!live_stream.hasOwnProperty(stream)) continue; helpers.generateStreamThumbnail(stream); } } }); }, null, true ); module.exports = job; <file_sep>const path = require("path"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; const webpack = require("webpack"); module.exports = { entry: "./client/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname, "public") }, module: { rules: [ { test: /\.s?[ac]ss$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { url: false, sourceMap: true } }, { loader: "sass-loader", options: { sourceMap: true } } ] }, { test: /\.js$/, exclude: /node_modules/, use: "babel-loader" }, { test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, loader: "url-loader" }, { test: /\.(png|jpg|gif)$/, use: [ { loader: "file-loader", options: { outputPath: "/" } } ] } ] }, devtool: "source-map", plugins: [ new MiniCssExtractPlugin({ filename: "style.css" }), new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" }) ], mode: devMode ? "development" : "production", watch: devMode, performance: { hints: process.env.NODE_ENV === "production" ? "warning" : false } }; <file_sep>import React from "react"; import { Route, Router } from "react-router-dom"; import Navbar from "./Navbar"; import LiveStreams from "./LiveStreams"; import Settings from "./Settings"; import VideoPlayer from "./VideoPlayer"; const customHistory = require("history").createBrowserHistory(); export default class Root extends React.Component { constructor(props) { super(props); } render() { return ( <Router history={customHistory}> <div> <Navbar /> <Route exact path="/" render={props => { <LiveStreams {...props} />; }} /> <Route exact path="/stream/:username" render={props => { <VideoPlayer {...props} />; }} /> <Route exact path="/settings" render={props => { <Settings {...props} />; }} /> </div> </Router> ); } }
b0663cf62e74e5b1e345fe6d2d7f93aab4a9632c
[ "JavaScript", "Markdown" ]
11
JavaScript
Bugvoid/Pongo
414087a4ae5b8f4dc21de46e26232c26a86f831e
b3ed6a89706a5c37eb2f690df20cad8a9bc9c828
refs/heads/master
<file_sep>/** * Created by Kay on 2016/3/8. */ function login() { var token = document.getElementById("token"); if (token.value == "") { alert("请输入验证码"); } else { window.location.assign("http://192.168.20.1:2060/wifidog/auth?token=" + token.value); } } <file_sep>import sys import time import json import urllib import io, shutil import subprocess import urlparse import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" whitelist = ['backgrd.jpg', 'functions.js', 'login.html', 'style.css', 'swat.png', 'trylater.html'] MAX_FAIL = 3 redirect_script = '<script language="javascript" type="text/javascript">window.location.assign("http://192.168.20.1:2060/wifidog/auth?token=");</script>' class LoginUser(): def __init__(self, mac, ip): self.mac = mac self.ip = ip self.failtimes = 0 self.firstfailtime = 0 self.islogedin = False def getmac(self): return self.mac def getip(self): return self.ip def getfailtimes(self): return self.failtimes def addfail(self, lasttime): if self.failtimes > MAX_FAIL: self.failtimes = 0 self.firstfailtime = 0 self.failtimes = self.failtimes + 1 if self.firstfailtime == 0: self.firstfailtime = lasttime print "addfail:" + self.mac print "ip:" + self.ip + " times:" + str(self.failtimes) def getfirstfailtime(self): return self.firstfailtime def setLogedin(self): self.islogedin = True self.failtimes = 0 self.firstfailtime = 0 def isLogedin(self): return self.islogedin class UserAdmin(): def __init__(self): self.list = [] def userValidate(self, mac, ip): global MAX_FAIL for user in self.list: if user.getmac() == mac and user.getip() == ip: print "FailTimes:" + str(user.getfailtimes()) print "Time:" + str(time.time() - user.getfirstfailtime()) if user.getfailtimes() > MAX_FAIL and time.time() - user.getfirstfailtime() < 60 : return False #too many retries return True #user is normal def addFailUser(self, mac, ip): for user in self.list: if user.getmac() == mac and user.getip() == ip: user.addfail(time.time()) return newUser = LoginUser(mac, ip) newUser.addfail(time.time()) self.list.append(newUser) def addLogedUser(self, mac, ip): for user in self.list: if user.getmac() == mac and user.getip() == ip: user.setLogedin() return def isLogedin(self, mac, ip): for user in self.list: if user.getmac() == mac and user.getip() == ip: return user.isLogedin() return False users = UserAdmin() class MyHandler(SimpleHTTPRequestHandler): def do_POST(self): print(self.headers) datas = self.rfile.read (int (self.headers['content-length'])) datas = urllib.unquote (datas).decode ("utf-8", 'ignore') self.do_auth(datas) def do_auth(self, content): enc = "UTF-8" auth_script = redirect_script.replace("token=", content) print(auth_script) content = auth_script.encode(enc) self.send_response(200) self.send_header("Content-type", "text/html; charset=%s" % enc) self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) def do_GET(self): global users print self.path if self.path.startswith('/ping'): print(self.headers) self.send_response(200) self.end_headers() self.wfile.write('Pong') self.wfile.close() else: if self.path.startswith('/login'): parsed = urlparse.urlparse(self.path) print parsed urldata = urlparse.parse_qs(parsed.query) print urldata mac = urldata['mac'][0] ip = urldata['ip'][0] print 'IP:' + ip print 'MAC:' + mac print users.isLogedin(mac, ip) f = open("login.html", "r") html_response = f.read() f.close() body_pos = html_response.index('</body>') if users.isLogedin(mac, ip) == True: new_response = html_response[:body_pos]+redirect_script+html_response[body_pos:] print "Logged in already" else: new_response = html_response self.wfile.write(new_response) self.wfile.close() else: if self.path.startswith('/auth'): parsed = urlparse.urlparse(self.path) urldata = urlparse.parse_qs(parsed.query) mac = urldata['mac'][0] ip = urldata['ip'][0] print(users.userValidate(mac,ip)) if users.userValidate(mac, ip) == False: print "Too many tries!" #f = open("trylater.html", "r") #self.wfile.write(f.read()) #f.close() #self.wfile.close() self.wfile.write('Auth: 0') self.wfile.close() return if urldata['stage'][0] == 'login': global ha_token print("Global token:" + ha_token) p = subprocess.Popen(['curl', '-s', '-k', '-X', 'GET', '-H', 'Authorization: Bearer ' + ha_token, '-H', "Content-Type: application/json", "https://192.168.0.210:8123/api/states/sensor.guest_wifi_password"], stdout=subprocess.PIPE, stderr = subprocess.PIPE, shell=False) stdout, errout = p.communicate() time.sleep(1) print(stdout) print(json.loads(stdout)) token = json.loads(stdout)['state'] if 'token' in urlparse.parse_qs(parsed.query): input_token = urlparse.parse_qs(parsed.query)['token'][0] else: input_token = "" print "Right token:" + token print "Input token:" + input_token self.send_response(200) self.end_headers() print token != input_token print users.isLogedin(mac, ip) if users.isLogedin(mac, ip) == True or token == input_token: self.wfile.write('Auth: 1') print "Succ!" self.wfile.close() users.addLogedUser(urldata['mac'][0], urldata['ip'][0]) else: self.wfile.write('Auth: 0') print "Fail!" self.wfile.close() users.addFailUser(urldata['mac'][0], urldata['ip'][0]) return else: if urldata['stage'][0] == 'counter': if users.isLogedin(urldata['mac'][0], urldata['ip'][0]): self.wfile.write('Auth: 1') print "Succ!" self.wfile.close() else: self.wfile.write('Auth: 0') print "Fail to login!" self.wfile.close() else: if self.path.startswith('/portal/'): f = open("succ.html", "r") self.wfile.write(f.read()) f.close() self.wfile.close() else: if self.path.startswith('/gw_message.php'): f = open("trylater.html", "r") self.wfile.write(f.read()) f.close() self.wfile.close() else: if(self.path.replace('/', '') in whitelist): SimpleHTTPRequestHandler.do_GET(self) else: print "error" port = 80 if sys.argv[1:]: port = int(sys.argv[1]) ha_token = sys.argv[2] print(ha_token) server_address = ('0.0.0.0', port) MyHandler.protocol_version = Protocol httpd = ServerClass(server_address, MyHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever()
3dfb4f5e03ccd8556ed24c2a88b3146f0a335c95
[ "JavaScript", "Python" ]
2
JavaScript
luisliou/wifidog_client
9caba6274e79a3e7ec79967bbd227294fc2af976
d9c1db0e940d7299ecde239c357905eb28f6b8b0
refs/heads/master
<file_sep>// // UserDefaults+DateTest.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsDateTest: XCTestCase { let defaults = UserDefaults(suiteName: "Test-UserDefaultsSample")! override func tearDown() { defaults.removeObject(forKey: UserDefaultsKeys.testOptionalDateValue.key) } func testDateValueSave() { defaults[.testOptionalDateValue] = Date(timeIntervalSince1970: 50) XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testOptionalDateValue.key) as! Date, Date(timeIntervalSince1970: 50)) defaults[.testOptionalDateValue] = nil XCTAssertNil(defaults.value(forKey: UserDefaultsKeys.testOptionalDateValue.key)) } func testDateValueGet() { // デフォルト値 XCTAssertNil(defaults[.testOptionalDateValue]) // 値が存在する場合 defaults[.testOptionalDateValue] = Date(timeIntervalSince1970: 50) XCTAssertEqual(defaults[.testOptionalDateValue], Date(timeIntervalSince1970: 50)) } } private extension UserDefaultsKeys { static let testOptionalDateValue = UserDefaultsKey<Date?>("testOptionalDateValue") } <file_sep>// // UserDefaults+BoolTest.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsBoolTest: XCTestCase { let defaults = UserDefaults(suiteName: "Test-UserDefaultsSample")! override func tearDown() { defaults.removeObject(forKey: UserDefaultsKeys.testBoolValue.key) defaults.removeObject(forKey: UserDefaultsKeys.testOptionalBoolValue.key) } func testBoolValueSave() { defaults[.testOptionalBoolValue] = false defaults[.testBoolValue] = true XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testOptionalBoolValue.key) as! Bool, false) XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testBoolValue.key) as! Bool, true) defaults[.testOptionalBoolValue] = nil XCTAssertNil(defaults.value(forKey: UserDefaultsKeys.testOptionalBoolValue.key)) } func testBoolValueGet() { // デフォルト値 XCTAssertNil(defaults[.testOptionalBoolValue]) XCTAssertEqual(defaults[.testBoolValue], false) // 値が存在する場合 defaults[.testOptionalBoolValue] = false defaults[.testBoolValue] = true XCTAssertEqual(defaults[.testOptionalBoolValue], false) XCTAssertEqual(defaults[.testBoolValue], true) } } private extension UserDefaultsKeys { static let testBoolValue = UserDefaultsKey<Bool>("testBoolValue") static let testOptionalBoolValue = UserDefaultsKey<Bool?>("testOptionalBoolValue") } <file_sep>// // UserDefaults+DataTest.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsDataTest: XCTestCase { let defaults = UserDefaults(suiteName: "Test-UserDefaultsSample")! override func tearDown() { defaults.removeObject(forKey: UserDefaultsKeys.testDataValue.key) defaults.removeObject(forKey: UserDefaultsKeys.testOptionalDataValue.key) } func testDataValueSave() { defaults[.testOptionalDataValue] = Data(count: 4) defaults[.testDataValue] = Data(count: 10) XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testOptionalDataValue.key) as! Data, Data(count: 4)) XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testDataValue.key) as! Data, Data(count: 10)) defaults[.testOptionalDataValue] = nil XCTAssertNil(defaults.value(forKey: UserDefaultsKeys.testOptionalDataValue.key)) } func testDataValueGet() { // デフォルト値 XCTAssertNil(defaults[.testOptionalDataValue]) XCTAssertEqual(defaults[.testDataValue], Data()) // 値が存在する場合 defaults[.testOptionalDataValue] = Data(count: 3) defaults[.testDataValue] = Data(count: 5) XCTAssertEqual(defaults[.testOptionalDataValue], Data(count: 3)) XCTAssertEqual(defaults[.testDataValue], Data(count: 5)) } } private extension UserDefaultsKeys { static let testDataValue = UserDefaultsKey<Data>("testDataValue") static let testOptionalDataValue = UserDefaultsKey<Data?>("testOptionalDataValue") } <file_sep> ## UserDefaultsをテストしやすくラップするSample ### 参考にさせて頂いたライブラリ https://github.com/radex/SwiftyUserDefaults <file_sep>// // UserDefaultsSerializable+Extensions.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // // https://github.com/radex/SwiftyUserDefaults import Foundation extension String: UserDefaultsSerializable, UserDefaultsDefaultValue { public static var defaultValue: String = "" public static func get(key: String, userDefaults: UserDefaults) -> String? { return userDefaults.string(forKey: key) } public static func save(key: String, value: String?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Int: UserDefaultsSerializable, UserDefaultsDefaultValue { public static var defaultValue: Int = 0 public static func get(key: String, userDefaults: UserDefaults) -> Int? { guard let number = userDefaults.number(forKey: key) else { return nil } return number.intValue } public static func save(key: String, value: Int?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Double: UserDefaultsSerializable, UserDefaultsDefaultValue { public static var defaultValue: Double = 0.0 public static func get(key: String, userDefaults: UserDefaults) -> Double? { return userDefaults.number(forKey: key)?.doubleValue } public static func save(key: String, value: Double?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Bool: UserDefaultsSerializable, UserDefaultsDefaultValue { public static var defaultValue: Bool = false public static func get(key: String, userDefaults: UserDefaults) -> Bool? { // @warning we use number(forKey:) instead of bool(forKey:), because // bool(forKey:) will always return value, even if it's not set // and it does a little bit of magic under the hood as well // e.g. transforming strings like "YES" or "true" to true return userDefaults.number(forKey: key)?.boolValue } public static func save(key: String, value: Bool?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Data: UserDefaultsSerializable, UserDefaultsDefaultValue { public static var defaultValue: Data = Data() public static func get(key: String, userDefaults: UserDefaults) -> Data? { return userDefaults.data(forKey: key) } public static func save(key: String, value: Data?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Date: UserDefaultsSerializable { public static func get(key: String, userDefaults: UserDefaults) -> Date? { return userDefaults.object(forKey: key) as? Date } public static func save(key: String, value: Date?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension URL: UserDefaultsSerializable { public static func get(key: String, userDefaults: UserDefaults) -> URL? { return userDefaults.url(forKey: key) } public static func save(key: String, value: URL?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } } extension Optional: UserDefaultsSerializable where Wrapped: UserDefaultsSerializable { public static func get(key: String, userDefaults: UserDefaults) -> Wrapped?? { return Wrapped.get(key: key, userDefaults: userDefaults) } public static func save(key: String, value: Wrapped??, userDefaults: UserDefaults) { if let _value = value, let value = _value { Wrapped.save(key: key, value: value, userDefaults: userDefaults) } else { Wrapped.save(key: key, value: nil, userDefaults: userDefaults) } } } private protocol OptionalType { associatedtype Wrapped var wrapped: Wrapped? { get } } extension Optional: OptionalType { public var wrapped: Wrapped? { return self } } private extension UserDefaults { func number(forKey key: String) -> NSNumber? { return object(forKey: key) as? NSNumber } } <file_sep>// // UserDefaults+Subscriptable.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // // https://github.com/radex/SwiftyUserDefaults import Foundation public extension UserDefaults { subscript<T: UserDefaultsSerializable>(key: UserDefaultsKey<T?>) -> T? { get { return T.get(key: key.key, userDefaults: self) } set { T.save(key: key.key, value: newValue, userDefaults: self) } } subscript<T: UserDefaultsSerializable>(key: UserDefaultsKey<T>) -> T where T: UserDefaultsDefaultValue { get { return T.get(key: key.key, userDefaults: self) ?? T.defaultValue } set { T.save(key: key.key, value: newValue, userDefaults: self) } } } <file_sep>// // DefautsDataStore.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/23. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation protocol UserDefaultsDataShareable: class { var suiteName: String { get } } public class UserDefaultsDataStore: UserDefaultsDataStoreProtocol { var defaults: UserDefaults { return UserDefaults(suiteName: shareable.suiteName)! } var shareable: UserDefaultsDataShareable! init(shareable: UserDefaultsDataShareable? = nil) { if let shareable = shareable { self.shareable = shareable } else { self.shareable = self } } /// データを保存する、データが存在しない場合はnilを保存する func save<T: UserDefaultsSerializable>(key: UserDefaultsKey<T?>, value: T?) { defaults[key] = value } /// データを保存する、データが存在しない場合はデフォルト値を保存する func save<T: UserDefaultsSerializable & UserDefaultsDefaultValue>(key: UserDefaultsKey<T>, value: T) { defaults[key] = value } /// データを返却する、データが存在しない場合はnilが返却される func get<T: UserDefaultsSerializable>(key: UserDefaultsKey<T?>) -> T? { return defaults[key] } /// データを返却する、データが存在しない場合はデフォルト値が返却される func get<T: UserDefaultsSerializable & UserDefaultsDefaultValue>(key: UserDefaultsKey<T>) -> T { return defaults[key] } } extension UserDefaultsDataStore: UserDefaultsDataShareable { var suiteName: String { return "UserDefaultsSample" } } <file_sep>// // UserDefaults+Serializable.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // // https://github.com/radex/SwiftyUserDefaults import Foundation public typealias UserDefaultsSerializable = UserDefaultsStoreable & UserDefaultsGettable public protocol UserDefaultsStoreable { static func save(key: String, value: Self?, userDefaults: UserDefaults) } public protocol UserDefaultsGettable { static func get(key: String, userDefaults: UserDefaults) -> Self? } public protocol UserDefaultsDefaultValue { static var defaultValue: Self { get } } <file_sep>// // UserDefaults+StringTest.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsStringTest: XCTestCase { let defaults = UserDefaults(suiteName: "Test-UserDefaultsSample")! override func tearDown() { defaults.removeObject(forKey: UserDefaultsKeys.testStringValue.key) defaults.removeObject(forKey: UserDefaultsKeys.testOptionalStringValue.key) } func testStringValueSave() { defaults[.testOptionalStringValue] = "test" defaults[.testStringValue] = "hoge" XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testOptionalStringValue.key) as! String, "test") XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testStringValue.key) as! String, "hoge") defaults[.testOptionalStringValue] = nil XCTAssertNil(defaults.value(forKey: UserDefaultsKeys.testOptionalStringValue.key)) } func testStringValueGet() { // デフォルト値 XCTAssertNil(defaults[.testOptionalStringValue]) XCTAssertEqual(defaults[.testStringValue], "") // 値が存在する場合 defaults[.testOptionalStringValue] = "fuga" defaults[.testStringValue] = "hogehoge" XCTAssertEqual(defaults[.testOptionalStringValue], "fuga") XCTAssertEqual(defaults[.testStringValue], "hogehoge") } } private extension UserDefaultsKeys { static let testStringValue = UserDefaultsKey<String>("testStringValue") static let testOptionalStringValue = UserDefaultsKey<String?>("testOptionalStringValue") } <file_sep>// // UserDefaultsDataStoreProtocol.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation protocol UserDefaultsDataStoreProtocol: UserDefaultsDataStoreStoreable & UserDefaultsDataStoreGettable { } protocol UserDefaultsDataStoreStoreable { func save<T: UserDefaultsSerializable>(key: UserDefaultsKey<T?>, value: T?) func save<T: UserDefaultsSerializable & UserDefaultsDefaultValue>(key: UserDefaultsKey<T>, value: T) } protocol UserDefaultsDataStoreGettable { func get<T: UserDefaultsSerializable>(key: UserDefaultsKey<T?>) -> T? func get<T: UserDefaultsSerializable & UserDefaultsDefaultValue>(key: UserDefaultsKey<T>) -> T } <file_sep>// // UserDefaults+DoubleTest.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsDoubleTest: XCTestCase { let defaults = UserDefaults(suiteName: "Test-UserDefaultsSample")! override func tearDown() { defaults.removeObject(forKey: UserDefaultsKeys.testDoubleValue.key) defaults.removeObject(forKey: UserDefaultsKeys.testOptionalDoubleValue.key) } func testDoubleValueSave() { defaults[.testOptionalDoubleValue] = 1.2 defaults[.testDoubleValue] = 2.3 XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testOptionalDoubleValue.key) as! Double, 1.2) XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testDoubleValue.key) as! Double, 2.3) defaults[.testOptionalDoubleValue] = nil XCTAssertNil(defaults.value(forKey: UserDefaultsKeys.testOptionalDoubleValue.key)) } func testDoubleValueGet() { // デフォルト値 XCTAssertNil(defaults[.testOptionalDoubleValue]) XCTAssertEqual(defaults[.testDoubleValue], 0) // 値が存在する場合 defaults[.testOptionalDoubleValue] = 1.4 defaults[.testDoubleValue] = 2.3 XCTAssertEqual(defaults[.testOptionalDoubleValue], 1.4) XCTAssertEqual(defaults[.testDoubleValue], 2.3) } } private extension UserDefaultsKeys { static let testDoubleValue = UserDefaultsKey<Double>("testDoubleValue") static let testOptionalDoubleValue = UserDefaultsKey<Double?>("testOptionalDoubleValue") } <file_sep>// // UserDefaultsKeys+Define.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation extension UserDefaultsKeys { static let username = UserDefaultsKey<String>(KeyName.username.rawValue) static let launchCount = UserDefaultsKey<Int>(KeyName.launchCount.rawValue) // 複数のUserDefaultsの変数で同じKeyを使用しないため、Enumで文字列を定義する private enum KeyName: String { case username case launchCount } } <file_sep>// // ViewController.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } } <file_sep>// // UserDefaultsDataStoreTests.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/18. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsDataStoreTests: XCTestCase { // 本体のUserDefaultsを書き換えると、本体の動作に影響が出るため // MockのUserDefaultsを使用する let dataStore = UserDefaultsDataStore(shareable: MockDataStoreShareableClass()) override func tearDown() { super.tearDown() UserDefaults(suiteName: "Test-UserDefaultsSample")?.removeObject(forKey: UserDefaultsKeys.testIntValue.key) UserDefaults(suiteName: "Test-UserDefaultsSample")?.removeObject(forKey: UserDefaultsKeys.testOptionalIntValue.key) } func testDefaultsStoreInit() { let dataStore1 = UserDefaultsDataStore() XCTAssertEqual(dataStore1.shareable.suiteName, "UserDefaultsSample") XCTAssertEqual(dataStore.shareable.suiteName, "Test-UserDefaultsSample") } func testSave() { // データが存在しないとき let notSavedValue = UserDefaults(suiteName: "Test-UserDefaultsSample")?.value(forKey: UserDefaultsKeys.testOptionalIntValue.key) as? Int let notSavedValue2 = UserDefaults(suiteName: "Test-UserDefaultsSample")?.value(forKey: UserDefaultsKeys.testIntValue.key) as? Int XCTAssertNil(notSavedValue) XCTAssertNil(notSavedValue2) // データが保存されること dataStore.save(key: .testOptionalIntValue, value: 2) dataStore.save(key: .testIntValue, value: 3) let savedValue = UserDefaults(suiteName: "Test-UserDefaultsSample")?.value(forKey: UserDefaultsKeys.testOptionalIntValue.key) as? Int XCTAssertEqual(savedValue, 2) let savedValue2 = UserDefaults(suiteName: "Test-UserDefaultsSample")?.value(forKey: UserDefaultsKeys.testIntValue.key) as? Int XCTAssertEqual(savedValue2, 3) // nilが保存できること dataStore.save(key: .testOptionalIntValue, value: nil) let notSavedValue3 = UserDefaults(suiteName: "Test-UserDefaultsSample")?.value(forKey: UserDefaultsKeys.testOptionalIntValue.key) as? Int XCTAssertNil(notSavedValue3) } func testGet() { // データが存在しないとき XCTAssertNil(dataStore.get(key: .testOptionalIntValue)) XCTAssertEqual(dataStore.get(key: .testIntValue), 0) // データが保存されているとき dataStore.save(key: .testOptionalIntValue, value: 2) dataStore.save(key: .testIntValue, value: 3) XCTAssertEqual(dataStore.get(key: .testOptionalIntValue), 2) XCTAssertEqual(dataStore.get(key: .testIntValue), 3) } class MockDataStoreShareableClass: UserDefaultsDataShareable { var suiteName: String { return "Test-UserDefaultsSample" } } } private extension UserDefaultsKeys { static let testOptionalIntValue = UserDefaultsKey<Int?>("testOptionalIntValue") static let testIntValue = UserDefaultsKey<Int>("testIntValue") } <file_sep>// // UserDefaults+IntTest.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsIntTest: XCTestCase { let defaults = UserDefaults(suiteName: "Test-UserDefaultsSample")! override func tearDown() { defaults.removeObject(forKey: UserDefaultsKeys.testIntValue.key) defaults.removeObject(forKey: UserDefaultsKeys.testOptionalIntValue.key) } func testIntValueSave() { defaults[.testOptionalIntValue] = 1 defaults[.testIntValue] = 2 XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testOptionalIntValue.key) as! Int, 1) XCTAssertEqual(defaults.value(forKey: UserDefaultsKeys.testIntValue.key) as! Int, 2) defaults[.testOptionalIntValue] = nil XCTAssertNil(defaults.value(forKey: UserDefaultsKeys.testOptionalIntValue.key)) } func testIntValueGet() { // デフォルト値 XCTAssertNil(defaults[.testOptionalIntValue]) XCTAssertEqual(defaults[.testIntValue], 0) // 値が存在する場合 defaults[.testOptionalIntValue] = 1 defaults[.testIntValue] = 2 XCTAssertEqual(defaults[.testOptionalIntValue], 1) XCTAssertEqual(defaults[.testIntValue], 2) } } private extension UserDefaultsKeys { static let testIntValue = UserDefaultsKey<Int>("testIntValue") static let testOptionalIntValue = UserDefaultsKey<Int?>("testOptionalIntValue") } <file_sep>// // UserDefaults+URLTest.swift // UserDefaultsMockTests // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // import XCTest @testable import UserDefaultsMock class UserDefaultsURLTest: XCTestCase { let defaults = UserDefaults(suiteName: "Test-UserDefaultsSample")! override func tearDown() { defaults.removeObject(forKey: UserDefaultsKeys.testOptionalURLValue.key) } func testURLValueSave() { defaults[.testOptionalURLValue] = URL(string: "test")! XCTAssertEqual(defaults.url(forKey: UserDefaultsKeys.testOptionalURLValue.key), URL(string: "test")) defaults[.testOptionalURLValue] = nil XCTAssertNil(defaults.value(forKey: UserDefaultsKeys.testOptionalURLValue.key)) } func testURLValueGet() { // デフォルト値 XCTAssertNil(defaults[.testOptionalURLValue]) // 値が存在する場合 defaults[.testOptionalURLValue] = URL(string: "test")! XCTAssertEqual(defaults[.testOptionalURLValue], URL(string: "test")!) } } private extension UserDefaultsKeys { static let testOptionalURLValue = UserDefaultsKey<URL?>("testOptionalURLValue") } <file_sep>// // UserDefaultsKeys.swift // UserDefaultsMock // // Created by <NAME> on 2018/11/24. // Copyright © 2018 <NAME>. All rights reserved. // // https://github.com/radex/SwiftyUserDefaults import Foundation /// Extend this class and add your user defaults keys as static constants /// so you can use the shortcut dot notation (e.g. `Defaults[.yourKey]`) open class UserDefaultsKeys { fileprivate init() {} } /// Base class for static user defaults keys. Specialize with value type /// and pass key name to the initializer to create a key. public class UserDefaultsKey<ValueType: UserDefaultsSerializable>: UserDefaultsKeys { public let key: String public init(_ key: String) { self.key = key } }
9c005bc3e97e7fc430ec6d695ddc186f8e1ab830
[ "Swift", "Markdown" ]
17
Swift
46kuro/UserDefaultMock
bacd964cd6ee468ba80d0c2de93e7ed71093e05a
812dbb39c4b0961932ae3368a47f22f8644628b5
refs/heads/master
<file_sep>#include <iostream> #include <fstream> #include <string> #include <vector> #include "scan.h" using namespace std; int main(int argc, char** argv) { if (argc != 2) { cerr << "invalid number of arguments" << endl; return 2; } ini::scanner scan(argv[1]); for(int i = 0; !scan.done(); i++) { try { ini::token tok = scan.scan(); cout << tok.pos.to_string() << ") "; cout << (i+1) << ": " << tok.literal << ", type: " << ini::to_string(tok.type) << endl; } catch (ini::scanner_exception e){ cerr << "error while scanning: " << e.what() << endl; } catch (const char* e) { cerr << "unexpected error: " << e << endl; return 3; } } } <file_sep>clean: rm -f objects/*o rm -f bin/* libs: mkdir -p objects g++ -o objects/scan.o -c src/ini/scan.cpp g++ -o objects/ini.o -c src/ini/ini.cpp scan: libs mkdir -p bin g++ -o objects/iniscan.o -c src/cmd/scan.cpp -I src/ini g++ -o bin/iniscan objects/scan.o objects/ini.o objects/iniscan.o parse: libs mkdir -p bin g++ -o objects/iniparse.o -c src/cmd/parse.cpp -I src/ini g++ -o bin/iniparse objects/scan.o objects/ini.o objects/iniparse.o all: libs scan parse <file_sep># this is a comment [ section1 ] host=localhost addr=127.0.0.1 [section2] host = midbel addr = 192.168.0.1 # local network address [section3] host = foobar addr = 172.16.17.32 # multicast group [quoted-section] option = "the quick brown fox" value = "the lazy dog" <file_sep>#ifndef INI_H #define INI_H #include <exception> #include <vector> #include <sstream> #include "scan.h" #include "ini.h" namespace ini { class duplicate: public std::exception { private: std::string label; std::string part; public: duplicate(std::string a, std::string p): label(a), part(p) {} virtual ~duplicate() throw() {} virtual const char* what() const throw() { std::ostringstream str; str << "duplicate " << part << ": " << label; return str.str().c_str(); } }; class not_found: public std::exception { private: std::string label; std::string section; public: not_found(std::string s, std::string a): section(s), label(a) {} virtual ~not_found() throw() {} virtual const char* what() const throw() { std::ostringstream str; str << section << ": option " << label << " not found"; return str.str().c_str(); } }; class unexpected_token: public std::exception { private: token_type want; token_type got; position pos; public: unexpected_token(position p, token_type w, token_type g): pos(p), want(w), got(g) {} virtual ~unexpected_token() throw() {} virtual const char* what() const throw() { std::ostringstream str; str << ": unexpected token! want " << to_string(want); str << ", got " << to_string(got); return str.str().c_str(); } }; struct option { std::string section; std::string name; std::string value; }; class config { private: std::vector<option> options; std::vector<option> parse(std::string file); option get_option(std::string section, std::string name); public: config(std::string file); std::string get_string(std::string option); std::string get_string(std::string section, std::string option); int get_int(std::string option); int get_int(std::string section, std::string option); double get_double(std::string option); double get_double(std::string section, std::string option); bool get_bool(std::string option); bool get_bool(std::string section, std::string option); bool has_section(std::string section); bool has_option(std::string section, std::string name); std::vector<option> all() { return options; } }; } #endif // INI_H <file_sep>#include <vector> #include <set> #include <iostream> #include "scan.h" #include "ini.h" namespace ini { class parser { private: token curr; token peek; scanner scan; public: parser(std::string file): scan(file) { next(); next(); }; std::vector<option> parse_ini(); private: std::vector<option> parse_section(std::string label); option parse_option(std::string label); void next(); }; config::config(std::string file) { options = parse(file); } std::string config::get_string(std::string section, std::string name) { option o = get_option(section, name); return o.value; } std::string config::get_string(std::string name) { return get_string("", name); } int config::get_int(std::string section, std::string name) { option o = get_option(section, name); return std::stoi(o.value); } int config::get_int(std::string name) { return get_int("", name); } double config::get_double(std::string section, std::string name) { option o = get_option(section, name); return std::stod(o.value); } double config::get_double(std::string name) { return get_double("", name); } bool config::get_bool(std::string section, std::string name) { option o = get_option(section, name); if (o.value == "" || o.value == "0" || o.value == "false") { return false; } return true; } bool config::get_bool(std::string name) { return get_bool("", name); } bool config::has_section(std::string section) { for (int i = 0; i < options.size(); i++) { option o = options[i]; if (o.section == section) { return true; } } return false; } bool config::has_option(std::string section, std::string name) { for (int i = 0; i < options.size(); i++) { option o = options[i]; if (o.section == section && o.name == name) { return true; } } return false; } option config::get_option(std::string section, std::string name) { for (int i = 0; i < options.size(); i++) { option o = options[i]; if (o.section == section && o.name == name) { return o; } } throw not_found(section, name); } std::vector<option> config::parse(std::string file) { std::vector<option> options; parser ps(file); return ps.parse_ini(); } std::vector<option> parser::parse_ini() { std::vector<option> options; std::set<std::string> sections; if (curr.type == ident) { std::vector<option> os = parse_section("default"); options.insert(options.end(), os.begin(), os.end()); } while(!scan.done()) { if (curr.type != header) { throw unexpected_token(curr.pos, header, curr.type); } std::string label = curr.literal; if (sections.find(label) != sections.end()) { throw duplicate(label, "section"); } next(); std::vector<option> os = parse_section(label); options.insert(options.end(), os.begin(), os.end()); } return options; } std::vector<option> parser::parse_section(std::string label) { std::vector<option> options; std::set<std::string> labels; while (curr.type != header && !scan.done()) { option opt = parse_option(label); if (labels.find(opt.name) != labels.end()) { throw duplicate(opt.name, "option"); } options.push_back(opt); next(); } return options; } option parser::parse_option(std::string section) { option opt; if (curr.type != ident) { throw unexpected_token(curr.pos, ident, curr.type); } opt.section = section; opt.name = curr.literal; next(); if (curr.type != assign) { throw unexpected_token(curr.pos, assign, curr.type); } next(); if (curr.type != literal) { throw unexpected_token(curr.pos, literal, curr.type); } opt.value = curr.literal; return opt; } void parser::next() { curr = peek; peek = scan.scan(); while (peek.type == comment) { peek = scan.scan(); } }; } <file_sep>#include <iostream> #include <fstream> #include <string> #include <vector> #include "ini.h" using namespace std; int main(int argc, char** argv) { if (argc != 2) { cerr << "usage: readini <config.ini>" << endl; exit(2); } try { ini::config cfg(argv[1]); vector<ini::option> options = cfg.all(); for(int i = 0; i < options.size(); i++) { ini::option o = options[i]; cout << o.name << ":" << o.section << ": " << o.value << endl; } } catch(exception& e) { cerr << "unexpected error: " << e.what() << endl; return 1; } } <file_sep>#ifndef SCAN_H #define SCAN_H #include <exception> #include <fstream> #include <sstream> namespace ini { namespace mk { const char space = ' '; const char tab = '\t'; const char pound = '#'; const char lsquare = '['; const char rsquare = ']'; const char newline = '\n'; const char equal = '='; const char hyphen = '-'; const char underscore = '_'; const char carriage = '\r'; const char dquote = '"'; const char squote = '\''; const char semicolon = ';'; inline bool is_blank(char c) { return c == space || c == tab; } inline bool is_newline(char c) { return c == newline; } inline bool is_letter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } inline bool is_digit(char c) { return c >= '0' && c <= '9'; } inline bool is_alpha(char c) { return is_digit(c) || is_letter(c); } inline bool is_ident(char c) { return is_alpha(c) || c == hyphen || c == underscore; } inline bool is_comment(char c) { return c == pound || c == semicolon; } } enum token_type {eof, header, ident, literal, number, boolean, assign, comment}; inline std::string to_string(token_type tt) { switch (tt) { case eof: return "eof"; case header: return "header"; case ident: return "ident"; case number: return "number"; case boolean: return "boolean"; case literal: return "literal"; case comment: return "comment"; case assign: return "assign"; default: return "unknown"; } } struct position { int line; int column; std::string to_string() { std::ostringstream str; str << line; str << ":"; str << column; return str.str(); } bool is_valid() { return line > 0; } }; struct token { token_type type; std::string literal; position pos; }; class scanner_exception: public std::exception { private: std::string where; std::string reason; public: scanner_exception(std::string w, std::string r): where(w), reason(r) {} virtual ~scanner_exception() throw() {} virtual const char* what() const throw() { std::ostringstream str; str << "scanning " << where << ": " << reason << "!!!"; return str.str().c_str(); } }; class scanner { public: scanner(std::string file); token scan(); bool done(); position where(); private: std::stringstream buffer; int line; int column; int length; char last; bool value; void scan_header(token& tok); void scan_ident(token& tok); void scan_value(token& tok); void scan_quote(token& tok, char quote); void scan_comment(token& tok); char get(); char peek(); void unget(); void skip_lines(); void skip_blanks(); }; } #endif // SCAN_H <file_sep>#include <algorithm> #include "scan.h" namespace ini { scanner::scanner(std::string file) { std::ifstream in(file.c_str(), std::ios::in); if (!in) { throw "fail to open file "+file; } buffer << in.rdbuf(); in.close(); std::string str = buffer.str(); str.erase(remove(str.begin(), str.end(), mk::carriage), str.end()); buffer.str(str); line = 1; column = 0; length = 0; last = 0; value = false; get(); } bool scanner::done() { return buffer.eof(); }; position scanner::where() { // position pos {line, column}; position pos; pos.line = line; pos.column = column; return pos; }; token scanner::scan() { skip_lines(); skip_blanks(); token tok; if (done()) { tok.type = eof; return tok; } tok.pos = where(); // {line, column}; switch (last) { case mk::semicolon: case mk::pound: scan_comment(tok); break; case mk::equal: value = true; tok.literal = "="; tok.type = assign; break; case mk::lsquare: scan_header(tok); break; case mk::dquote: case mk::squote: if (!value) { throw scanner_exception("scan", "only value can be quoted"); } scan_quote(tok, last); value = false; break; default: if (value) { scan_value(tok); value = false; } else { scan_ident(tok); } break; } get(); return tok; } void scanner::scan_ident(token& tok) { std::ostringstream str; if (!mk::is_letter(last)) { throw scanner_exception("ident", "invalid character "+last); } while(last != mk::equal) { if (done()) { throw scanner_exception("ident", "unexpected end of file"); } if (mk::is_blank(last)) { break; } if (!mk::is_ident(last)) { throw scanner_exception("ident", "invalid character"); } str.put(last); get(); } tok.literal = str.str(); tok.type = ident; if (last == mk::equal) { unget(); } } void scanner::scan_quote(token& tok, char quote) { get(); std::ostringstream str; while(last != quote) { if (done()) { throw scanner_exception("quoted", "unexpected end of file"); } str.put(last); get(); } tok.literal = str.str(); tok.type = literal; } void scanner::scan_value(token& tok) { std::ostringstream str; str.put(last); while(!done()) { get(); if (mk::is_newline(last) || mk::is_comment(last) || mk::is_blank(last)) { break; } str.put(last); } tok.literal = str.str(); tok.type = literal; } void scanner::scan_header(token& tok) { get(); std::ostringstream str; skip_blanks(); if (!mk::is_letter(last)) { throw scanner_exception("header", "invalid character"); } while (last != mk::rsquare) { if (done()) { throw scanner_exception("header", "unexpected end of file"); } if (mk::is_blank(last)) { skip_blanks(); break; } if (!mk::is_ident(last)) { throw scanner_exception("header", "invalid character"); } str.put(last); get(); } tok.literal = str.str(); tok.type = header; } void scanner::scan_comment(token& tok) { std::ostringstream str; skip_blanks(); while(last != mk::newline && !done()) { str.put(last); get(); } tok.literal = str.str(); tok.type = comment; } char scanner::peek() { return buffer.peek(); } char scanner::get() { last = buffer.get(); if (last == mk::newline) { line++; length = column; column = 0; } else { column++; } return last; } void scanner::unget() { if (last == mk::newline) { line--; column = length; } else { column--; } buffer.unget(); } void scanner::skip_blanks() { if (!mk::is_blank(last)) { return; } while(mk::is_blank(get())) {} } void scanner::skip_lines() { if (!mk::is_newline(last)) { return; } while(get() == mk::newline) {} } }
47359083c8f5efb70c13b4f7b444c32e3dae9a6e
[ "Makefile", "C++", "INI" ]
8
C++
midbel/inifile
a3c1e748645db294cf92e33a7424a4e89d192002
5c85ec3dc3a3dea2ef5dec9b493c47e04537e6b5
refs/heads/main
<file_sep>import os import numpy as np image_dir = '/Users/luyifan/Desktop/motionCap/SFM/images/' MRT = 0.7 #camera calibration matrix K K = np.array([[1.06334775e+03,0.00000000e+00,4.83541243e+02], [0.00000000e+00,1.06334775e+03,1.06554082e+03], [0.00000000e+00,0.00000000e+00,1.00000000e+00]]) #chose range of points that will be deleted x = 0.5 y = 1<file_sep># EyeTrackingCameraSFM A python version of SFM ## packages opencv-python opencv-python-contrib numpy scipy matplotlib
0fa28512906bfa209705ccc8de6399a19c7de0bf
[ "Markdown", "Python" ]
2
Python
HuMoN-Research-Lab/EyeTrackingCameraSFM
59fbcc8d2fbd65dd4b77aaeb2991f9a7b69bc339
37f27514e9f532afa69a175e18ac16b0671e9f3c
refs/heads/master
<repo_name>Mosselvla/WEBS2<file_sep>/WK1_HW1/products.php <?php /** * Created by PhpStorm. * User: Victor * Date: 09-Feb-17 * Time: 15:35 */ include 'header.php'; ?> <html> <body> <div> ayylmao </div> </body> </html> <?php include 'footer.php'; ?><file_sep>/WK1_HW1/about.php <?php /** * Created by PhpStorm. * User: Victor * Date: 09-Feb-17 * Time: 15:35 */ include 'header.php'; ?> <html> <body> <h1>About us</h1> <div>Our goal is to serve you with the best wares!</div> <h1>Contact info</h1> <div>Telephone number: 06-12345678<br> Address: Onderwijsboulevard 1<br> </div> </body> </html> <?php include 'footer.php'; ?><file_sep>/WK1_HW1/footer.php <?php /** * Created by PhpStorm. * User: Victor * Date: 09-Feb-17 * Time: 15:04 */ ?> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> </head> <footer> <meta charset="UTF-8"> <h3>Made by Mick and Victor</h3> </footer> </html> <file_sep>/WK1_HW1/home.php <?php /** * Created by PhpStorm. * User: Victor * Date: 09-Feb-17 * Time: 15:31 */ include 'header.php'; ?> <html> <body> <h1>Welcome to VMwares! We don't know what we sell yet.</h1> </body> </html> <?php include 'footer.php'; ?> <file_sep>/WK1_HW1/header.php <?php /** * Created by PhpStorm. * User: Victor * Date: 09-Feb-17 * Time: 15:04 */ ?> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p> <a href="home.php"> <img src="VMwares.jpg"> </a> </p> <div> <ul> <li><a href="home.php">Home</a></li> <li><a href="products.php">Products</a></li> <li><a href="about.php">About</a></li> </ul> </div> </body> </html>
6cf68e2d8169fdcb6278fe6a46ef23d06ffa015f
[ "PHP" ]
5
PHP
Mosselvla/WEBS2
ec7db231cfbf1c5c4e7a2c264d23c257c6e8e6df
ae7c2f0bcc6a465c6d6b3be76c0f011682f8920b
refs/heads/master
<repo_name>roozbehf/consul-example<file_sep>/Vagrantfile # Creates a Consul example setup on Linode DATACENTER = 'newark' MACHINES = { 'consul-01' => '1024' } Vagrant.configure(2) do |config| # SSH configuration config.ssh.username = 'devops' config.ssh.private_key_path = "~/.ssh/linode_rsa" # Global Configuration config.vm.provider :linode do |provider, override| override.vm.box = 'linode' override.vm.box_url = "https://github.com/displague/vagrant-linode/raw/master/box/linode.box" provider.token = ENV['linode_api_key'] provider.distribution = 'Ubuntu 14.04 LTS' provider.datacenter = DATACENTER provider.private_networking = true end # Synced Folders config.vm.synced_folder '.', '/vagrant', disabled: true MACHINES.each do |hostname, plan| config.vm.define hostname do |a| a.vm.hostname = hostname a.vm.provider :linode do |provider, override| provider.label = hostname provider.plan = plan end end end config.vm.provision "ansible" do |ansible| ansible.playbook = "playbook.yml" ansible.sudo = true ansible.groups = { "consul-server" => ["consul-01"] } end end <file_sep>/README.md # Consul Installation using Vagrant and Ansible *NOTE:* This is a work in progress. This is an example of a [Consul](https://www.consul.io) setup with four nodes. The example follows [this guid](https://www.digitalocean.com/community/tutorials/an-introduction-to-using-consul-a-service-discovery-system-on-ubuntu-14-04). <file_sep>/roles/common_vagrant/files/setup.sh #!/bin/bash FLAG_FILE=/etc/hostname.done if [ ! -e "$FLAG_FILE" ]; then echo "$1" > /etc/hostname hostname -F /etc/hostname ip addr show eth0 | grep -Po 'inet \K[\d.]+' | while read ip; do echo "$ip $1" >> /etc/hosts; done ln -sf /usr/share/zoneinfo/EST /etc/localtime apt-get update && apt-get upgrade -y touch /etc/hostname.done fi
9be23edcb50fddd70eae2a182df983d138c5db57
[ "Markdown", "Ruby", "Shell" ]
3
Ruby
roozbehf/consul-example
ba8520d2d70125bb9b1683fe30dce97a6afca29f
7a8afbe4c83d665e0bf0707e02ef6df80fa9fc31
refs/heads/master
<repo_name>RakibulAlam1127/Larning-With-JavaScript<file_sep>/typeConversion.js var type; type = typeof 'Rakib'; console.log(type); //string type = typeof 123.14; console.log(type); //number type = typeof null; console.log(type); //object type = typeof false; console.log(type); //boolean type = typeof [12,34,56,6,'rakib']; console.log(type);<file_sep>/javaScriptRegularExpresion.js //Search in case insensative // var str = 'My Name is Rakib'; // var res = str.search(/Name/i); // console.log(res); //search in case sen sative // var str = 'Daffodil International University'; // var res = str.search("University"); // console.log(res); // String Replace for case insensative; // var str = 'I larn Php and Java'; // var result = str.replace(/Java/i,"JavaScript"); // console.log(result); //String Replace for case sendative; // var str = 'He is a Bad Man And Honest'; // var res = str.replace("Bad","Good"); // console.log(res); // //Modifier // var str = 'I am a student of Cse and student of diu'; // var res = str.search(/student/g); // console.log(res);
6092d036690d0443ba32bb5930115328cf629727
[ "JavaScript" ]
2
JavaScript
RakibulAlam1127/Larning-With-JavaScript
eff7873010808ccbf06a88bb4d5341230f63f148
9711697127ef8d8d95796052bd364a1ba22e5351
refs/heads/master
<file_sep>package repository type FileRepository interface { GetContent(pathFile string) ([]byte, error) } <file_sep>package query type GetParameterDbQuery struct { PathFile string } <file_sep>package adapter import "github.com/floyoops/poc-go-backup/src/backup/domain/model" type ConvertToParametersDb interface { Convert(bytes []byte) (model.ParametersDb, error) } <file_sep>package infra_adapter import ( "fmt" "github.com/floyoops/poc-go-backup/src/backup/domain/model" "github.com/floyoops/poc-go-backup/src/backup/infra/infra_repository" "testing" ) var Expected = model.ParametersDb{ DbHost: "db", DbPassword: "<PASSWORD>", DbName: "the_db_name", DbPort: "", DbUser: "root", } func FileYmlToModelExpect(filePath string, expected model.ParametersDb) (bool, error) { repo := infra_repository.FileRepository{} bytesValue, errorRepo := repo.GetContent(filePath) if errorRepo != nil { return false, fmt.Errorf("error get content file '%v'", filePath) } converter := YmlToParameters{} result, errorConvert := converter.Convert(bytesValue) if errorConvert != nil { return false, fmt.Errorf("error on convert the content of '%v'", filePath) } if result != expected { return false, fmt.Errorf("the result %v different of expected %v", result, Expected) } return true, nil } func TestSuccess(t *testing.T) { _, err := FileYmlToModelExpect("../../../../data/parameters.yml", Expected) if err != nil { t.Error(err) } } func TestYmlDisorderSuccess(t *testing.T) { _, err := FileYmlToModelExpect("../../../../data/parameters_disorder.yml", Expected) if err != nil { t.Error(err) } } func TestYulMinimalSuccess(t *testing.T) { _, err := FileYmlToModelExpect("../../../../data/parameters_minimal.yml", Expected) if err != nil { t.Error(err) } } func TestYmlEmptyFail(t *testing.T) { _, err := FileYmlToModelExpect("../../../../data/parameters_empty.yml", Expected) if err == nil { t.Error("expected error not found") } } func TestYmlIncompleteFail(t *testing.T) { _, err := FileYmlToModelExpect("../../../../data/parameters_incomplete.yml", Expected) errorExpected := "the result {db } different of expected {db the_db_name root root_password}" if err != nil && err.Error() != errorExpected { t.Errorf("error message '%v' is different of expected message: '%v'", err.Error(), errorExpected) } } func TestFail(t *testing.T) { byteValues := []byte("ABC€") // not bytes from yml. converter := YmlToParameters{} _, errorConvert := converter.Convert(byteValues) if errorConvert == nil { t.Errorf("expected error not found") } } <file_sep>package infra_repository import "testing" func TestGetContentSuccess(t *testing.T) { repo := FileRepository{} _, err := repo.GetContent("../../../../data/parameters.yml") if err != nil { t.Errorf("no %v", err) } } func TestFileNotExist(t *testing.T) { repo := FileRepository{} _, err := repo.GetContent("fake") if err != nil && err.Error() != "the file 'fake' does not exist\n" { t.Errorf("no") } } <file_sep>package infra_repository import ( "fmt" "io/ioutil" "os" ) type FileRepository struct { } func (r FileRepository) exists(name string) bool { if _, err := os.Stat(name); err != nil { if os.IsNotExist(err) { return false } } return true } func (r FileRepository) GetContent(pathFile string) ([]byte, error) { // Check if file exist. if r.exists(pathFile) == false { return make([]byte, 0, 0), fmt.Errorf("the file '%v' does not exist\n", pathFile) } fmt.Printf("Arg path file yml detected: %v\n", pathFile) // Open. file, err := os.Open(pathFile) if err != nil { return make([]byte, 0, 0), fmt.Errorf("error on open file: %v\n", err) } fmt.Printf("open %v success\n", pathFile) // Read defer file.Close() byteValue, err := ioutil.ReadAll(file) if err != nil { return make([]byte, 0, 0), fmt.Errorf("error on read %s\n", err) } fmt.Printf("Read success") return byteValue, nil } <file_sep>package infra_adapter import ( "fmt" "github.com/floyoops/poc-go-backup/src/backup/domain/model" "gopkg.in/yaml.v2" ) type YmlToParameters struct { } func (c YmlToParameters) Convert(byteValue []byte) (model.ParametersDb, error) { // Unmarshal var result map[string]map[string]string err := yaml.Unmarshal([]byte(byteValue), &result) if err != nil { return model.ParametersDb{}, fmt.Errorf("error %v", err) } // Adapt to model p := model.ParametersDb{ DbHost: result["parameters"]["database_host"], DbPort: result["parameters"]["database_port"], DbName: result["parameters"]["database_name"], DbUser: result["parameters"]["database_user"], DbPassword: result["parameters"]["database_password"], } return p, err } <file_sep>package main import ( "flag" "fmt" "github.com/floyoops/poc-go-backup/src/backup/app/query" "github.com/floyoops/poc-go-backup/src/backup/domain/adapter" "github.com/floyoops/poc-go-backup/src/backup/domain/repository" "github.com/floyoops/poc-go-backup/src/backup/infra/infra_adapter" "github.com/floyoops/poc-go-backup/src/backup/infra/infra_repository" "log" "os" ) func main() { // bootstrap handler var fileRepo repository.FileRepository = infra_repository.FileRepository{} var converter adapter.ConvertToParametersDb = infra_adapter.YmlToParameters{} var handler = query.GetParametersDbQueryHandler{ Repository: fileRepo, Adapter: converter, } // cli get args. var pathFile string flag.StringVar(&pathFile,"f", "data/parameters.yml", "help message for ip") flag.Parse() fmt.Println("pathFile has value ", pathFile) // query q := query.GetParameterDbQuery{PathFile: pathFile} p, err := handler.Handle(q) if err != nil { log.Fatal("err on yml to parameters, detail: ", err) os.Exit(1) } // render fmt.Printf("dbs %v", p) } <file_sep>package model type ParametersDb struct { DbHost string `yaml:"database_host"` DbPort string `yaml:"database_port"` DbName string `yaml:"database_name"` DbUser string `yaml:"database_user"` DbPassword string `yaml:"database_password"` } <file_sep>module github.com/floyoops/poc-go-backup go 1.13 require gopkg.in/yaml.v2 v2.2.7 <file_sep>package query import ( "fmt" "github.com/floyoops/poc-go-backup/src/backup/domain/adapter" "github.com/floyoops/poc-go-backup/src/backup/domain/model" "github.com/floyoops/poc-go-backup/src/backup/domain/repository" ) type GetParametersDbQueryHandler struct { Repository repository.FileRepository Adapter adapter.ConvertToParametersDb } func (Qh GetParametersDbQueryHandler) Handle(query GetParameterDbQuery) (model.ParametersDb, error) { bytesYml, err := Qh.Repository.GetContent(query.PathFile) if err != nil { return model.ParametersDb{}, fmt.Errorf( "Error GetParametersDbQueryHandler on get content of file '%v'\n, previous: '%v'", query.PathFile, err, ) } return Qh.Adapter.Convert(bytesYml) } <file_sep># poc-go-backup backup to ftp from config in yml
f338e40981a992e53b3b9403138e9edf38db2ed5
[ "Markdown", "Go Module", "Go" ]
12
Go
floyoops/poc-go-backup
ed149a5a01b17f11dc8ce6035c792dabe85b4c71
1de265e14ff2135d74af06b0905749fc46063fd6
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FirstAssignment { public static class FixMultiplication { static int missingDigit = 0, FirstNumber, SecondNumber, ResultNumber, FirstNewNumber, SecondNewNumber; public static int FindDigit(String equation) { string[] stringArrayFirst, stringArraySecond, digitsArray; stringArrayFirst = equation.Split('='); string equationFirstPart = stringArrayFirst[0]; string equationSecondPart = stringArrayFirst[1]; if (equationFirstPart.Contains('?')) { stringArraySecond = equationFirstPart.Split('*'); string equationFirstPartOne = stringArraySecond[0]; string equationFirstPartTwo = stringArraySecond[1]; if (equationFirstPartOne.Contains('?')) { missingDigit = FindMissingDigits(equationFirstPartOne, equationFirstPartTwo, equationFirstPart, equationSecondPart, 0); } else if (equationFirstPartTwo.Contains('?')) { missingDigit = FindMissingDigits(equationFirstPartOne, equationFirstPartTwo, equationFirstPart, equationSecondPart, 1); } } else if (equationSecondPart.Contains('?')) { digitsArray = equationFirstPart.Split('*'); if(digitsArray.Length == 2) { int.TryParse(digitsArray[0], out FirstNumber); int.TryParse(digitsArray[1], out SecondNumber); ResultNumber = FirstNumber * SecondNumber; string result = ResultNumber.ToString(); missingDigit = int.Parse(result[FindMissingPosition(equationSecondPart)].ToString()); } } else { missingDigit = 0; } return missingDigit; } public static int FindMissingDigits(string equationPartOne, string equationPartTwo, string equationFirstPart, string equationSecondPart, int input) { string missingEquation = equationPartOne, divideEquation = equationSecondPart, otherPart=equationPartTwo; int missingPosition = 0; if(input == 0) { missingEquation = equationPartOne; divideEquation = equationSecondPart; otherPart = equationPartTwo; } else if(input == 1) { missingEquation = equationPartTwo; divideEquation = equationFirstPart; otherPart = equationPartOne; } if (int.Parse(equationSecondPart) % int.Parse(otherPart) == 0) { missingPosition = FindMissingPosition(missingEquation); string newEquation = missingEquation.Remove(missingPosition, 1); int.TryParse(otherPart, out FirstNewNumber); int.TryParse(newEquation, out SecondNewNumber); int NewResult = FirstNewNumber * SecondNewNumber; if (equationSecondPart.Equals(NewResult.ToString())) { missingDigit = -1; } else { int findMissingNumber = int.Parse(equationSecondPart) / FirstNewNumber; string newresult = findMissingNumber.ToString(); char digit = newresult[missingPosition]; missingDigit = int.Parse(digit.ToString()); } } else { missingDigit = -1; } return missingDigit; } public static int FindMissingPosition(string equation) { int missingPosition = equation.IndexOf("?"); return missingPosition; } } class Program { static void Main(string[] args) { Console.WriteLine("Enter the Equation"); string equation = Console.ReadLine(); Console.WriteLine(FixMultiplication.FindDigit(equation)); } } } <file_sep># FindMissingDigitInStrings It is used to find the missed digits of strings
daf5c9166d14a0727dea18446727c5cef59c1e3a
[ "Markdown", "C#" ]
2
C#
tavisca-rkaruppaiah/FindMissingDigitInStrings
d51c1338f6ebd7137ad154de6d3612a24f1fc77d
aa1e998ce9982ee90a905be75a52de70131226cc
refs/heads/master
<file_sep># Written by <NAME>, 2016 # Function: count_nucleotides() # Input: A DNA string # Output: The amount of A, C, G and T in the string def count_nucleotides(dna_string): # Set nucleotide counters to 0 adenine_count = 0 cytosine_count = 0 guanine_count = 0 thymine_count = 0 # Go through the DNA string and count each nucleotide for nucleotide in dna_string: if nucleotide == 'A': adenine_count += 1 elif nucleotide == "C": cytosine_count += 1 elif nucleotide == "G": guanine_count += 1 elif nucleotide == "T": thymine_count += 1 # Convert integer values to string a_count = str(adenine_count) c_count = str(cytosine_count) g_count = str(guanine_count) t_count = str(thymine_count) # Store counts in a final string nucleotide_count = a_count + " " + c_count + " " + g_count + " " + t_count # Return the string return nucleotide_count # Example DNA sequence nucleotide_count = count_nucleotides("GAATGCGGAATAAGTTCTACGTGAGGTAGTTGCGTGTTGTTCTCCAACGAGCCCTCCAGAAATCGCCCGAACGTGTGGATGGCACAAGGCCCATATCATGAGTGCATTTGCAGGTTAATAGGCCCGGCTTTCCGGGCGGGTGCAATCAACCCTTTTGGAAACTTCTATGGTTATACGCGAGGAATACAGGGTACTCTATACTTCCCGGCTGGTCTAACCGGCCGAGAGCCTACATGCTCTATTTAACTATGCGGATTCTTGAGCCGAGAAGGGCTCATGCGACATGGTGCAGGCCATAGGATGCCATTCCGACAGTAAGGATTACTCTATAACACACGTAGAGTGTTGTAATTTCCATGCGTCATCTACATCCGCACATATTGCCCTCCACCTTTCCCGACAGGGGCGCAAGGCCCTCCCGCCATCTCCTTCGATAGTAGCCCTTATGAGGCACCGATGGAAACAGCTCTAGATTAGGTTTCCGGACAACTGTCCGAAGTTAAGGCGGGTGGGTGTGGCGCCACGACAGCCTAATTCTATACATCTTGATAAGACATCTAGGCACTCCACCTGCTAGAACCTTTATTGTAATGGGCGGAAGCGGCGGGTGGACGGCTGATTTGTCTTAGACAATGATTACTCCGATTACCAACCCCGTTCGTGCATCTTTTAAACGTTAGAACATAACCATCATTCCATCGGTTGGGCGACAGCTTATGGCTTTAATTTATCGTCGTGTCGGGGTGAAGCGAACTACCTGGCGTCAACAAACCGGGGCGGCACTAGATGCACACTACTTTGATGGTCTGTTAAGGGCCATACGGGTATTCGGGCTCCCATCTCCGATTATAAGCCTCCAATATCGCGACTCCCAGAGAGAAGCCGGTGC") print(nucleotide_count) <file_sep># Written by <NAME>, 2017 # Function: calculate_rabbit_pairs(n,m): # Input: The number of months (n) and the lifespan of a rabbit in months (m) # Output: The total number of rabbit pairs alive during month n # Notes: This solution uses a 2D array to keep track of the rabbit pairs # Each list/array represents the number of rabbits of each age at a given month # For more info, check this link: http://www.andrewmonshizadeh.com/2015/03/01/mortal-fibonacci-rabbits/ # Finds the number of rabbit pairs after n months if rabbits have a lifespan of m months def calculate_rabbit_pairs(n,m): # Initialize the array representing the rabbit population at month 1 # A "1" is added to the array to represent the 1 pair of baby rabbits in the first month pairs_at_current_month = [0] # For each month (n), an array is appended to keep track the rabbit pairs' ages for month in range(1,n+1): # Create empty arrays to append to the main array pairs_at_current_month.append([]) # Initialize the first month in the array pairs_at_current_month[1] = [1] + [0]*(m-1) # Calculate population arrays for the rest of the months in the array for month in range (2,n+1): # The number of newborn rabbits in the next month is equal to the number of adult rabbits in the previous month # The rest of the array is the first portion of the previous array pairs_at_current_month[month] = [sum(pairs_at_current_month[month-1][1:m])] + pairs_at_current_month[month-1][0:m-1] # The array is printed for debugging purposes print(pairs_at_current_month) # The number of rabbit pairs at the end of n weeks is returned return sum(pairs_at_current_month[n]) # Example values of n and k n = 83 m = 16 print(calculate_rabbit_pairs(n,m))<file_sep># Written by <NAME>, 2016 # Function: calculate_mass() # Input: A protein as a string of amino acids # Output: The mass of the protein def calculate_mass(protein_string): # Variable to store protein mass protein_mass = 0 # Goes through every three nucleotides and adds the corresponding amino acid to the string for nucleotide in protein_string: if nucleotide == "A": protein_mass += 71.03711 elif nucleotide == "C": protein_mass += 103.00919 elif nucleotide == "D": protein_mass += 115.02694 elif nucleotide == "E": protein_mass += 129.04259 elif nucleotide == "F": protein_mass += 147.06841 elif nucleotide == "G": protein_mass += 57.02146 elif nucleotide == "H": protein_mass += 137.05891 elif nucleotide == "I": protein_mass += 113.08406 elif nucleotide == "K": protein_mass += 128.09496 elif nucleotide == "L": protein_mass += 113.08406 elif nucleotide == "M": protein_mass += 131.04049 elif nucleotide == "N": protein_mass += 114.04293 elif nucleotide == "P": protein_mass += 97.05276 elif nucleotide == "Q": protein_mass += 128.05858 elif nucleotide == "R": protein_mass += 156.10111 elif nucleotide == "S": protein_mass += 87.03203 elif nucleotide == "T": protein_mass += 101.04768 elif nucleotide == "V": protein_mass += 99.06841 elif nucleotide == "W": protein_mass += 186.07931 elif nucleotide == "Y": protein_mass += 163.06333 return protein_mass # Example protein sequence print (round(calculate_mass("<KEY>KRVHFYWTLERPEHPQDRQWEWQQTGDCMTMILCKNSVHWSETVSRSTFTFHDDEDLMSTSRFYLIIHKHDPLLHETLNLRNRQDWMETHWHRRTTGDDRPTYKRNPIFVEYTTVWGRIYL"), 3)) <file_sep># Written by <NAME>, 2017 # Function: calculate_rabbit_pairs(n,k) # Input: Integers n (number of months) and k (litter size) where n <= 40 and k <= 5 # Output: Number of rabbit pairs present after n months # Finds the number of rabbit pairs after n months with a litter size of k pairs def calculate_rabbit_pairs(n,k): # Initialize an array of rabbit pairs up to 40 months # The index of the array is equal to the month number number_of_rabbit_pairs = [0] * 40 # Initialize the first two numbers in the fibonacci sequence to 0 and 1 number_of_rabbit_pairs[0] = 0 number_of_rabbit_pairs[1] = 1 # This for loop populates the array of rabbit populations for month in range(2,40): # The number of rabbits in a given month is equal to the number of rabbits in the previous month plus # k multiplied by the number of rabbits two months before number_of_rabbit_pairs[month] = number_of_rabbit_pairs[month-1] + k * number_of_rabbit_pairs[month-2] # The number of rabbit pairs after n months is returned return number_of_rabbit_pairs[n] # Example values of n and k n = 30 k = 4 print(calculate_rabbit_pairs(n,k)) <file_sep># Written by <NAME>, 2016 # Function: reverse_compliment() # Input: One DNA string # Output: The reverse compliment of the string def reverse_compliment(dna_string): # Stores reverse DNA string reversed_dna = "" # Adds nucleotides to new string in reverse for nucleotide in reversed(dna_string): reversed_dna += nucleotide reverse_compliment_dna = "" # Replaces each nucleotide with its compliment for nucleotide in reversed_dna: if nucleotide == 'A': reverse_compliment_dna += "T" elif nucleotide == "C": reverse_compliment_dna += "G" elif nucleotide == "G": reverse_compliment_dna += "C" elif nucleotide == "T": reverse_compliment_dna += "A" # Return reverse compliment of DNA string return reverse_compliment_dna # Example DNA sequence print (reverse_compliment("GCCGTTCCGTCCAGATCGCCGCCGTTGTGGTGCCGAGTTCCTAATATCCCGCTTAACTCGTTTTCTAGACTAGGATAGTACTTCCTCCCTAGAGGACCCCGTATATTGCATACCCTCTTCAGCATAAAACATGTTGAGTTTTACAGGTGACCACTGTGTTTATACTTACGGGCCCCATTGTAGAAAAGTCGGCAGTCGGAAACGCCTCCCTTGTACCATTTTTCGGATTCATTTCTGCTTAACCATAAGTCTGCACACAAGACCGGTGGCATTTCAACTCCATCACACTGTGCGACTAGGTACATCACGTGTTACACAACATGGCAAATTTAGGACGGAATCCGGGATTAACCCCGCGCTACCCATGTAATGTTCTAGTTGCGAGAAGCAAGCGCTCCGTGTACCAGTGACCTAGTACTCAGGTTTGCGTAAAACGCCCTATCGCCCATGGGCTTTGTCATTCGTGACGTCGAGAGCAGGGGCATGTGCTTACAGAATACACCGGAGGCGATCCTTTTTATCGACTCCATCGTTGGCTCGGAACAAAGCAACGACCGGTGCCCGTGATTCGAGTGAACTAACCGCCCGACAAGCTGGCTGTCGGCCAAGAAGGCATTCTAACTGCCTCTGCTTGATGCGCCGTTAACATCCGGTTCGGGGCCGCGATAGCGCCTGGTTTTATCGAATTCGTATGCGAAGCTGGGCCCTGCTACCACCGCCGCTCTAGCGTTTGCCTTAGCGAATAATACACAAGGTGACAATCTAGAACCGTCAGCGCCACTAGTCTGTGGGCTACTTAAAGTGGGAAGCAGTAACATATACCATTCCTATTAGGAGGAACGTGCAGCCCAGTACTCGCTAGAGGGGAGTTTACATGACTTGAGTGAACCCGG"))
bc316e9259ae863eaeba7e2e0aa2885480c339e6
[ "Python" ]
5
Python
michaelwanggit/Rosalind
ba80641ebf45ce804c52fe6b3547f6147911aedd
296a1ac08e606e7ff3120e178ee11d818dabadea
refs/heads/master
<repo_name>davidherasp/Experto-Big-Data<file_sep>/Python/Sesion12-02-16_19-02-16/ej_requests.py import requests api_key='<KEY>' r = requests.get("https://api.fullcontact.com/v2/person.json?email=<EMAIL>&apiKey=" + api_key) datos_bart = r.text print datos_bart<file_sep>/Python/Sesion12-02-16_19-02-16/ej_funcionesComoArgumento.py def aplica_funcion(func, x): return func(x) def dobla(n): return n*2 print aplica_funcion(dobla, 7) print aplica_funcion(lambda x: x*2, 7) #funcion lambda suma = lambda a, b, c: a+b+c print suma<file_sep>/Python/Sesion12-02-16_19-02-16/ej_argparse.py import sys import ej_argparse parser = ej_argparse.ArgumentParser(description="Este programa saluda al usuario") parser.add_argument("-n", "--nombre", default="unknown") parser.add_argument("-e", "--edad", help="incluya su edad", type=int, default=0) parser.add_argument("-i") args = parser.parse_args() print "Hola " + args.nombre + ". Tienes " + str(args.edad)<file_sep>/Python/TweepyApp/Slamanca.py import tweepy #Authentication--------------------------------------------------------- consumer_key = 'c8DNP4OJT1FrQbltlEC4zffno' consumer_secret = '<KEY>' access_token = '<KEY>' access_token_secret = '<KEY>' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) #END_Authentication----------------------------------------------------- public_tweets = api.home_timeline() for tweet in public_tweets: print tweet.text http://www.nirg.net/using-tweepy.html<file_sep>/Python/Sesion12-02-16_19-02-16/listasComprehension.py personas = ['David', 'Andrea', 'Alejandra'] saludos = ['Hola ' + nombre for nombre in personas] print saludos #Lista a = [2**n for n in [2,4,9,27]] #Diccionario b = {i: 2**i for i in range(10)} #Tupla c = tuple(2**n for n in range(7)) print c<file_sep>/README.md # Experto-Big-Data ### Código escrito en el Experto en Big Data Hay una carpeta para cada lenguaje y dentro de esta hay carpetas para cada sesión. <file_sep>/Python/Sesion12-02-16_19-02-16/ej_map.py lista = xrange(100) def multiplica_por_3(x): return x*3 #salida = map[multiplica_por_3, lista] #Maneras de crear diccionarios diccionario = {'nombre':'appellido'} dic=dict([("nombre","apellido"),("edad","piso")]) #crear diccionario en lambda salida = map(lambda x: {x:[x,x*3]}, lista) print salida #Creacion de una fucion lambda flamb = lambda x: {x:[x,x*3]} print flamb(24) <file_sep>/Python/Sesion12-02-16_19-02-16/ej_csv.py import csv import operator with open('data/GDP.csv') as f: reader = csv.DictReader(f) #Inicializamos las listas results2014 = [] res2014name = [] #Iteramos el reader y annadimos 0 en caso de que este vacio el campo (para evitar problemas con la ordenacion de float despues) for line in reader: if line['1980'] == '': results2014.append('0') #En caso de que la linea no este vacia annadimos el valor else: results2014.append(line['1980']) #El identificador del pais lo annadimos igual si no nos relacionara codigos con valores que no son res2014name.append(line['Country Code']) #Creamos el diccionario con las dos listas dict_name_value = dict(zip(res2014name, results2014)) #Ordenar diccionario sorted_dict_name_values = sorted(dict_name_value.items(), key=operator.itemgetter(1), reverse=True) print sorted_dict_name_values[:9] <file_sep>/Python/Sesion12-02-16_19-02-16/ej_test.py import sys for arg in sys.argv: print "Recibido argumento: " + arg <file_sep>/Python/Sesion12-02-16_19-02-16/persona.py class Persona: nombres = "" libros = [] def __init__(self,name,age=0): self.nombre = name self.edad = age def lee(self, libro): if libro not in self.libros: self.libros.append(libro) def librosQueLee(self): print(self.libros) <file_sep>/Python/Sesion12-02-16_19-02-16/entr_map-reduce-caracteres.py lista_cadenas = ["asdfadsf", "asdfasdf","fderwt","rewfd","lkafluhalidfkjdsf"] lista_len_cadenas = [] def suma_char_reduce(x, y): return x + y #Solo reduce for cadena in lista_cadenas: lista_len_cadenas.append(len(cadena)) print reduce(suma_char_reduce, lista_len_cadenas) #Map-reduce map_char = map(lambda c: len(c), lista_cadenas) print reduce(suma_char_reduce, map_char)<file_sep>/Python/Sesion12-02-16_19-02-16/ej_sysArg.py import sys args = sys.argv; for arg in args: if arg == '--nombre': nombre = args[args.index(arg)+1] elif arg == '--edad': edad = args[args.index(arg)+1] print "Hola " + nombre + ". Tienes " + edad + " annos."<file_sep>/Python/Sesion12-02-16_19-02-16/personasCiudades.py personas = [('Jorge', "Salamanca" ), ("Mario", "Madrid" ), ("Marta", "Salamanca" ), ("Juan", "Avila" ), ("Pedro", "Madrid" ), ("Susana", "Salamanca" ), ("Martin", "Valladolid" ), ("Mario", "Valladolid"), ("Jorge", "Salamanca" )] def cuantasPersonas (listaP): ciudades = {} for nombre, ciudad in listaP: if ciudad not in ciudades: ciudades[ciudad] = 1 else: ciudades[ciudad] += 1 return ciudades print cuantasPersonas(personas) <file_sep>/Python/Sesion12-02-16_19-02-16/pedroPersona.py import persona as p pedro = p.Persona('Pedro', 25) pedro.lee('El Quijote') pedro.lee('Dune') pedro.lee('Los que suenan') pedro.lee('<NAME> y la piedra filosofal') pedro.lee('Cincuenta sombras de Gray') pedro.librosQueLee() <file_sep>/Python/Sesion12-02-16_19-02-16/ej_filter.py lista = xrange(100) def es_par(x): if x % 2 == 0: return True else: return False print filter(es_par, lista) #Con lambda print filter(lambda x: x % 2 == 0, lista)<file_sep>/Python/Sesion12-02-16_19-02-16/RiotGamesAPI/api_requests.py import requests api_key = '<KEY>' region = 'euw' summonerName = '<NAME>' no_space_summoner_name = summonerName.replace(" ", "") no_space_lower_case_name = no_space_summoner_name.lower() # Seasons for the player stats request season6 = 'SEASON2016' season5 = 'SEASON2015' season4 = 'SEASON2014' season3 = 'SEASON3' def get_summoner_by_name(name): return requests.get( "https://euw.api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + name + "?api_key=" + api_key) def get_summoner_id(name): r = get_summoner_by_name(name) summid = r.json()[no_space_lower_case_name]["id"] return summid summoner_id = get_summoner_id(no_space_summoner_name) # Before this comment the code is what is needed in order to request whatever, since here the code is whatever it can be def get_stats(season): r = requests.get("https://euw.api.pvp.net/api/lol/" + region + "/v1.3/stats/by-summoner/" + str(summoner_id) + "/summary?season=" + season + "&api_key=" + api_key) return r.json() for key, value in get_stats(season6).iteritems(): #print "Game: ", game["playerStatSummaryType"], " - wins: ", game["wins"], " - Champ. kills: ",\ # game["aggregatedStats"]["totalChampionKills"] print key, value <file_sep>/Python/Sesion12-02-16_19-02-16/ej_generadores.py def numPrimos(limit): primos = [2] for i in range(3, limit, 2): for p in primos: if i % p == 0: break primos.append(i) yield i primos = numPrimos(100) for x in range(19): primos.next() print primos.next() <file_sep>/Python/Sesion12-02-16_19-02-16/ej_getopt.py import ej_getopt import sys print ej_getopt.ej_getopt(sys.argv[1:], '', ['nombre=', 'edad='])<file_sep>/Python/Sesion12-02-16_19-02-16/ej_potencias2.py def potencia(exp): potencias = [] for n in range(exp): potencias.append(2**n) return potencias print(potencia(7)) a = [2**n for n in [2,4,9,27]] b = {i: 2**i for i in range(10)} print b <file_sep>/Python/Sesion12-02-16_19-02-16/ej_reduce.py def suma_elementos(lista): suma = 0 for x in lista: suma += x return suma suma_elementos3 = lambda x: sum(x) def suma_reduce(x, y): return x + y def reduce_mediana(a, b): if type(a) == tuple: lista, mediana_anterior = a lista.append(b) else: lista = sorted([a, b]) return lista, lista[len(lista)/2] print suma_elementos(xrange(101)) print suma_elementos3(xrange(101)) print reduce(suma_reduce, xrange(101)) print reduce(max,xrange(101))
d2aa4cb7cd33abc0b26785d4fe5569d89d684665
[ "Markdown", "Python" ]
20
Python
davidherasp/Experto-Big-Data
2c298b802d670544af953e766a7f7ff2c931811d
960a0403c16e771a594d2f7ea05b79ecbcfb05ae
refs/heads/master
<repo_name>batmanu/stocks<file_sep>/stock.py import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader as web style.use("ggplot") start = dt.datetime(2006, 1, 1) end = dt.datetime(2018, 2, 1) data_source = 'yahoo' # df = web.get_data_yahoo("AAPL", start, end) # df2 = web.get_data_yahoo("MSFT", start, end) tickers = ['AAPL', 'SNAP'] start_date = '2010-01-01' end_date = '2018-02-08' panel_data = web.DataReader(tickers, data_source, start_date, end_date) close = panel_data.ix['Close'] all_weekdays = pd.date_range(start=start_date, end=end_date, freq='B') close = close.reindex(all_weekdays) close.head(10) # plt.show() print("Apple" + " is red and" + "Microsoft" + " is blue")
ed9e88c602c2e725eede130a617aa33efe780e20
[ "Python" ]
1
Python
batmanu/stocks
425551a072825833f02e55f9a0f155063b701e6b
77a192156cc11f54835da30b1bef806591446786
refs/heads/master
<repo_name>FarmaFacil/teste<file_sep>/excluir_paciente.php <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title></title> <style> body { background-image:url(fundo.jpg); } </style> </head> <body> <?php session_start(); include_once("conexao.php"); $id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); if(!empty($id)){ $sql = "DELETE FROM usuarios WHERE id='$id'"; $result = mysqli_query($conn, $sql); if(mysqli_affected_rows($conn)){ $_SESSION['msg'] = "<p style='color:green;'>Usuário apagado com sucesso</p>"; header("Location: listar_paciente.php"); ?><script> window.alert("Cadastro com sucesso"); </script><?php }else{ $_SESSION['msg'] = "<p style='color:red;'>Erro o usuário não foi apagado com sucesso</p>"; header("Location: listar_paciente.php"); } }else{ $_SESSION['msg'] = "<p style='color:red;'>Necessário selecionar um usuário</p>"; header("Location: listar_paciente.php"); } ?> </body> </html> <file_sep>/login.php <html> <head> <title>Remédio Fácil | Login</title> <link rel="stylesheet" href="css/style.css"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css?family=Hind&display=swap" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="shortcut icon" href="images/logo.png" type="image/x-icon"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Cadastro Aluno</title> <style> body { background-image:url(fundog.jpg); background-repeat: repeat; } .h1{ color: white; } .login-form{ margin-top: 90px; } </style> </head> <body><center> <div class="login-form"> <h1>REMÉDIO FÁCIL</h1> <br><br><br> <h6>CONECTE-SE</h6> <form method="POST" action="valida.php"> <div class="textbox"> <input type="text" name="email" placeholder="EMAIL" required> <span class="check-message hidden">Necessário</span> </div> <div class="textbox"> <input type="<PASSWORD>" name="senha" placeholder="SENHA" required> <span class="check-message hidden">Necessário</span> </div> <input type="submit" value="CONECTAR" class="login-btn" disabled> </form> <div class="dont-have-account"> Não possui uma conta? <a href="frm_paciente.php">Cadastre-se</a> </div> </div> <?php //Recuperando o valor da variável global, os erro de login. if(isset($_SESSION['loginErro'])){ echo $_SESSION['loginErro']; unset($_SESSION['loginErro']); }?> </p> <p> <?php //Recuperando o valor da variável global, deslogado com sucesso. if(isset($_SESSION['logindeslogado'])){ echo $_SESSION['logindeslogado']; unset($_SESSION['logindeslogado']); } ?> </p> <script type="text/javascript"> $(".textbox input").focusout(function(){ if($(this).val() == ""){ $(this).siblings().removeClass("hidden"); $(this).css("background","#554343"); }else{ $(this).siblings().addClass("hidden"); $(this).css("background","#484848"); } }); $(".textbox input").keyup(function(){ var inputs = $(".textbox input"); if(inputs[0].value != "" && inputs[1].value){ $(".login-btn").attr("disabled",false); $(".login-btn").addClass("active"); }else{ $(".login-btn").attr("disabled",true); $(".login-btn").removeClass("active"); } }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </body> </html> <file_sep>/alterar_paciente.php <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title></title> <style> body { background-image:url(fundog.jpg); } </style> </head> <body><?php session_start(); include_once("conexao.php"); $id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT); $nome = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_STRING); $rg = filter_input(INPUT_POST, 'rg', FILTER_SANITIZE_STRING); $telefone = filter_input(INPUT_POST, 'telefone', FILTER_SANITIZE_NUMBER_INT); $cpf = filter_input(INPUT_POST, 'cpf', FILTER_SANITIZE_STRING); $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $senha = filter_input(INPUT_POST, 'senha', FILTER_SANITIZE_STRING); $sql = "UPDATE usuarios SET nome='$nome', rg='$rg', telefone='$telefone', cpf='$cpf', email='$email', senha='<PASSWORD>', modified=NOW() WHERE id='$id'"; $result = mysqli_query($conn, $sql); if(mysqli_affected_rows($conn)){ $_SESSION['msg'] = "<p style='color:green;'>Usuário editado com sucesso</p>"; header("Location: listar_paciente.php"); }else{ $_SESSION['msg'] = "<p style='color:red;'>Usuário não foi editado com sucesso</p>"; header("Location: form_alterar_paciente?id=$id"); } ?> </body> </html> <file_sep>/listar_paciente.php <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Lista de Cadastro</title> <style> body { background-image:url('fundog.jpg'); } </style> </head> <body><center><BR><BR><h1>LISTA DE CADASTRO</h1><br> <?php require 'conexao.php'; if(isset($_SESSION['msg'])){ echo $_SESSION['msg']; unset($_SESSION['msg']); } //Receber o número da página $pagina_atual = filter_input(INPUT_GET,'pagina', FILTER_SANITIZE_NUMBER_INT); $pagina = (!empty($pagina_atual)) ? $pagina_atual : 1; //Setar a quantidade de itens por pagina $qnt_result_pg = 5; //calcular o inicio visualização $inicio = ($qnt_result_pg * $pagina) - $qnt_result_pg; $sql = "SELECT * FROM usuarios LIMIT $inicio, $qnt_result_pg"; $result = mysqli_query($conn, $sql); if(($result) AND ($result->num_rows != 0)){ ?> <table class="table table-dark table-striped table-bordered table-hover"> <thead> <tr> <th>ID</th> <th>Nome</th> <th>Rg</th> <th>Telefone</th> <th>Cpf</th> <th>E-mail</th> <th>Alterar</th> <th>Excluir</th> </tr> </thead> <tbody> <?php } while($row_usuario = mysqli_fetch_assoc($result)){ ?> <tr> <td><?php echo $row_usuario['id']; ?></td> <td><?php echo $row_usuario['nome']; ?></td> <td><?php echo $row_usuario['rg']; ?></td> <td><?php echo $row_usuario['telefone']; ?></td> <td><?php echo $row_usuario['cpf']; ?></td> <td><?php echo $row_usuario['email']; ?></td> <th><?php echo "<a href='form_alterar_paciente.php?id=" . $row_usuario['id'] . "'>Alterar</a>";?> </th> <th><?php echo "<a href='excluir_paciente.php?id=" . $row_usuario['id'] . "' data-confirm='Tem certeza de que deseja excluir o item selecionado?'>Excluir</a>"; ?></th> </tr> <?php }?> </tbody> </table> <?php //Paginção - Somar a quantidade de usuários $result_pg = "SELECT COUNT(id) AS num_result FROM usuarios"; $resultado_pg = mysqli_query($conn, $result_pg); $row_pg = mysqli_fetch_assoc($resultado_pg); //echo $row_pg['num_result']; //Quantidade de pagina $quantidade_pg = ceil($row_pg['num_result'] / $qnt_result_pg); //Limitar os link antes depois $max_links = 2; echo "<a href='listar_paciente.php?pagina=1'>Primeira</a> "; for($pag_ant = $pagina - $max_links; $pag_ant <= $pagina - 1; $pag_ant++){ if($pag_ant >= 1){ echo "<a href='listar_paciente.php?pagina=$pag_ant'>$pag_ant</a> "; } } echo "$pagina "; for($pag_dep = $pagina + 1; $pag_dep <= $pagina + $max_links; $pag_dep++){ if($pag_dep <= $quantidade_pg){ echo "<a href='listar_paciente.php?pagina=$pag_dep'>$pag_dep</a> "; } } echo "<a href='listar_paciente.php?pagina=$quantidade_pg'>Ultima</a>"; ?> </body> </html> <br><br> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <script src="js/personalizado.js"></script> </body> </html> <file_sep>/pesquisar.php <!DOCTYPE html> <html lang="pt-br"> <head> <title>Administração</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <style> body { background-image:url(fundog.jpg); } .container h2{ text-align: center; } #tamanho{ height: 100px; } .footer{ padding-bottom: 20px; background-color: #161616; padding-top:35px; } .footer-bottom{ background-color: #161616; } .fa{ font-size: 100px; } .popup{ position: fixed; top: 0; bottom: 0; left: 0; right:0; margin: auto; width: 70%; height: 70%; padding: 15px; border: solid 1px #4c4d4f; background: #f5f5f5; display: none; } .popup img{ width: 20px; height: 20px; } </style> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="homeAdm.php">Farmácia Fácil</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li class="active"><a href="#"> <?php session_start(); echo "Usuário: ". $_SESSION['nome']; ?> </a></li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Fornecedor<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Adicionar</a></li> <li><a href="#">Recibos</a></li> <li><a href="#">Medicamentos</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Estoque<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Adicionar</a></li> <li><a href="#">Verificação</a></li> <li><a href="#">Histórico</a></li> </ul> </li> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">Pacientes<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="listar_paciente.php">Listar</a></li> <li><a href="frm_paciente.php">Adicionar</a></li> <li><a href="pesquisar.php">Pesquisar</a></li> </ul> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="sairAdm.php"> <span class="glyphicon glyphicon-log-in"></span>&nbspDeslogar</a></li> </ul> </div> </div> </nav> <center><h1>Pesquisar Usuário</h1> <form method="POST" action=""> <div class="form-group"> <label>Nome: </label> <input type="text" name="nome" placeholder="Digite o nome"> <input name="SendPesqUser" type="submit" value="Pesquisar"> </form></div><br><br></center> <?php include_once 'conexao.php'; $SendPesqUser = filter_input(INPUT_POST, 'SendPesqUser', FILTER_SANITIZE_STRING); if($SendPesqUser){ $nome = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_STRING); $result_usuario = "SELECT * FROM usuarios WHERE nome LIKE '%$nome%'"; $resultado_usuario = mysqli_query($conn, $result_usuario); ?> <table class="table table-dark table-striped table-bordered table-hover"> <thead> <tr> <th>ID</th> <th>Nome</th> <th>Rg</th> <th>Telefone</th> <th>Cpf</th> <th>E-mail</th> <th>Informações</th> </tr> </thead> <tbody><?php while($row_usuario = mysqli_fetch_assoc($resultado_usuario)){?> <td><?php echo $row_usuario['id']; ?></td> <td><?php echo $row_usuario['nome']; ?></td> <td><?php echo $row_usuario['rg']; ?></td> <td><?php echo $row_usuario['telefone']; ?></td> <td><?php echo $row_usuario['cpf']; ?></td> <td><?php echo $row_usuario['email']; ?></td> <div id="popup" class="popup"> <a href="javascript: fechar();"><img src="img/x.png"></a><br> <center><h4>Medicamentos Retirados</h4><br></center> <ul> <li>Medicamentos</li> <li>Retiradas</li> </ul> </div> <td> <a href="javascript: abrir();"><button class="btn btn-outline-primary view_data" id="<?php echo $row_usuario['id']; ?>">Visualizar</button></a></td> </tr><?php } } ?> <script type="text/javascript"> function abrir(){ document.getElementById('popup').style.display = 'block'; } function fechar(){ document.getElementById('popup').style.display = 'none'; } </script> </body> </html><file_sep>/homePaciente.php <!DOCTYPE html> <html lang="en"> <head> <title>Home Paciente</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <style> body { background-image:url(fundog.jpg); } .form-group{ margin-top: 5px; color: white; } .container h2{ text-align: center; } #tamanho{ width: 100%; height: 100px; } .footer{ padding-bottom: 20px; background-color: #161616; padding-top:35px; } .footer-bottom{ background-color: #161616; } .fa{ font-size: 100px; } .popup{ position: fixed; top: 0; bottom: 0; left: 0; right:0; margin: auto; width: 70%; height: 70%; padding: 15px; border: solid 1px #4c4d4f; background: #f5f5f5; display: none; } .popup img{ width: 20px; height: 20px; } </style> <script type="text/javascript"> function abrir(){ document.getElementById('popup').style.display = 'block'; } function fechar(){ document.getElementById('popup').style.display = 'none'; } </script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="homePaciente.php">Remédio Fácil</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li><a href="sair.php"> <span class="glyphicon glyphicon-log-in"></span>&nbspDeslogar</a></li> </ul> <form class="navbar-form navbar-right" action="/action_page.php"> <div class="form-group"> <?php session_start(); echo "Usuário: ". $_SESSION['nome']; ?> </div></div> </form> </div> </div> </nav> <div class="container"> <h2>Notificação</h2><br> <input id="tamanho" type="text" disabled="disabled"> <br><br><br> <h2>Enviar Documentos</h2><br> <div id="popup" class="popup"> <a href="javascript: fechar();"><img src="img/x.png"></a><br> <h2>Escolher</h2><br> <table border="0"> <tr> <td><center><input type="file" value="Escolher"/></center><br></td> <td><center><input type="file" value="+"/></center><br></td> <td><center><input type="file" value="+"/></center><br></td> </tr> </table> </div> <center><a href="javascript: abrir();"><button class="btn-danger">Abrir Página</button></a><br> <br><br><br> <h2>Checagem de Medicamentos</h2><br> <input id="tamanho" type="text" disabled="disabled"> <br><br><br> <h2>Retirar Medimentos</h2><br> <div id="popup" class="popup"> <a href="javascript: fechar();"><img src="img/x.png"></a><br> <h2>Data para Retirar Medicamento</h2><br> </div> <!--ações para o popup --> <center><a href="javascript: abrir();"><button class="btn-danger">Abrir Página</button></a><br> <br><br><br><br><br> <a href="#"><button type="button" class="btn btn-success">Enviar</button></a></center><br><br><br><br><br> </div> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <footer> <div class="footer" id="footer"> <div class="container"> <div class="row"> <div class="social-media"><center> <a href="https://www.facebook.com/Rem%C3%A9dio-F%C3%A1cil-112894010455313/?modal=admin_todo_tour"> <i class="fa fa-facebook fa-2x"> &nbsp</i></a> <a href="https://twitter.com/FacilRemedio"> <i class="fa fa-twitter fa-2x"> &nbsp</i></a> <a href="#"> <i class="fa fa-linkedin fa-2x"> &nbsp</i></a> <a href="#"> <i class="fa fa-instagram fa-2x"> &nbsp</i></a> </div></center> </div> </div> </div> <div class="footer-bottom"><center> <div class="container"> <p class="pull-left"><center> Copyright © All right reserved.</center> </p> </div> </div> </footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </body> </html> <file_sep>/inserir_paciente.php <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <style> body { background-image:url(fundog.jpg); } .h1{ color: white; } </style> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title></title> </head> <body> <?php require 'conexao.php'; $nome = $_POST['nome']; $cpf = $_POST['cpf']; $telefone = $_POST['telefone']; $rg = $_POST['rg']; $email = $_POST['email']; $senha = $_POST['senha']; $sql = "insert into usuarios (nome, cpf, telefone, rg, email, senha) values ('$nome','$cpf','$telefone','$rg','$email','$senha')"; $result = mysqli_query($conn, $sql); if ($result == true) { ?> <script> window.alert("Cadastro com sucesso"); </script><br><br> <center> <h3><a href="Index.php">CONTINUAR</a></h3> </center> <?php } else { ?> <script> window.alert("Erro de cadastro"); </script><br><br> <center> <h3><a href="frm_paciente.php">CADASTRAR-SE</a></h3> </center> <?php } ?> </body> </html> <file_sep>/form_alterar_paciente.php <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title></title> <style> body { background-image:url(fundog.jpg); } </style> </head> <body> <?php session_start(); include_once("conexao.php"); $id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); $sql = "SELECT * FROM usuarios WHERE id = $id"; $result = mysqli_query($conn, $sql); $row_usuario = mysqli_fetch_assoc($result); ?> <center><br><BR> <h1>Alterar Paciente</h1><br> <form method="POST" action="alterar_paciente.php"> <input type="hidden" name="id" value="<?php echo $row_usuario['id']; ?>"> <label>Nome: </label> <input type="text" name="nome" placeholder="Digite o nome completo" value="<?php echo $row_usuario['nome']; ?>"><br><br> <label>RG: </label> <input type="text" name="rg" placeholder="Digite o RG" value="<?php echo $row_usuario['rg']; ?>"><br><br> <label>Telefone: </label> <input type="text" name="telefone" placeholder="Digite o telefone" value="<?php echo $row_usuario['telefone']; ?>"><br><br> <label>CPF: </label> <input type="text" name="cpf" placeholder="Digite o CPF" value="<?php echo $row_usuario['cpf']; ?>"><br><br> <label>E-mail: </label> <input type="email" name="email" placeholder="Digite o seu melhor e-mail" value="<?php echo $row_usuario['email']; ?>"><br><br> <label>Senha: </label> <input type="<PASSWORD>" name="senha" placeholder="Digite a sua senha" value="<?php echo $row_usuario['senha']; ?>"><br><br> <input type="submit" value="Alterar" class="btn btn-success">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="listar_paciente.php"> <input type="submit" value="Voltar" class="btn btn-danger"></a> </form> </center> </body> </html> <file_sep>/frm_paciente.php <?php session_start(); ob_start(); $btnCadUsuario = filter_input(INPUT_POST, 'btnCadUsuario', FILTER_SANITIZE_STRING); if($btnCadUsuario){ include_once 'conexao.php'; $dados_rc = filter_input_array(INPUT_POST, FILTER_DEFAULT); $erro = false; $dados_st = array_map('strip_tags', $dados_rc); $dados = array_map('trim', $dados_st); if(in_array('',$dados)){ $erro = true; $_SESSION['msg'] = "Necessário preencher todos os campos"; }elseif((strlen($dados['senha'])) < 6){ $erro = true; $_SESSION['msg'] = "A senha deve ter no minímo 6 caracteres"; }elseif(stristr($dados['senha'], "'")) { $erro = true; $_SESSION['msg'] = "Caracter ( ' ) utilizado na senha é inválido"; }else{ $result_usuario = "SELECT id FROM usuarios WHERE rg='". $dados['rg'] ."'"; $resultado_usuario = mysqli_query($conn, $result_usuario); if(($resultado_usuario) AND ($resultado_usuario->num_rows != 0)){ $erro = true; $_SESSION['msg'] = "Este usuário já está sendo utilizado"; } $result_usuario = "SELECT id FROM usuarios WHERE email='". $dados['email'] ."'"; $resultado_usuario = mysqli_query($conn, $result_usuario); if(($resultado_usuario) AND ($resultado_usuario->num_rows != 0)){ $erro = true; $_SESSION['msg'] = "Este e-mail já está cadastrado"; } } //var_dump($dados); if(!$erro){ //var_dump($dados); $dados['senha'] = password_hash($dados['senha'], PASSWORD_DEFAULT); $result_usuario = "INSERT INTO usuarios (nome, email, telefone, rg, cpf, senha) VALUES ( '" .$dados['nome']. "', '" .$dados['email']. "', '" .$dados['telefone']. "', '" .$dados['rg']. "', '" .$dados['cpf']. "', '" .$dados['senha']. "' )"; $resultado_usuario = mysqli_query($conn, $result_usuario); if(mysqli_insert_id($conn)){ $_SESSION['msgcad'] = "Usuário cadastrado com sucesso"; header("Location: login.php"); }else{ $_SESSION['msg'] = "Erro ao cadastrar o usuário"; } } } ?> <html> <head> <title>Remédio Fácil | Cadastro</title> <link rel="stylesheet" href="css/style.css"> <script> function formatar(src, mask) { var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i) if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); } } </script> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css?family=Hind&display=swap" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <link rel="shortcut icon" href="images/logo.png" type="image/x-icon"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Cadastro Paciente</title> <style> body { background-image:url(fundog.jpg); background-repeat: repeat; } .h1{ color: white; } </style> </head> <body><center> <div class="login-form"> <h1><NAME></h1> <br><br><br> <h6>CADASTRE-SE</h6> <form method="POST" action="inserir_paciente.php"> <div class="textbox"> <input type="text" name="nome" placeholder="<NAME>" required> <span class="check-message hidden">Necessário</span> </div> <div class="textbox"> <input onkeypress="formatar(this,'00.000.000-0')" id=dta type="text" name="rg" placeholder="RG" maxLength=12 required> <span class="check-message hidden">Necessário</span> </div> <div class="textbox"> <input onkeypress="formatar(this,'00 00000-0000')" id=dta type="text" name="telefone" placeholder="TELEFONE" maxLength=13 required> <span class="check-message hidden">Necessário</span> </div> <div class="textbox"> <input onkeypress="formatar(this,'000.000.000-00')" id=dta type="text" name="cpf" placeholder="CPF" maxLength=14> </div> <div class="textbox"> <input type="text" name="email" placeholder="EMAIL" required> <span class="check-message hidden">Necessário</span> </div> <div class="textbox"> <input type="password" name="senha" placeholder="SENHA" maxLength=8 required> <span class="check-message hidden">Necessário</span> </div> <input type="submit" id="btnCadUsuario" value="CADASTRAR" class="login-btn" disabled> </form> <div class="dont-have-account"> Ja possui uma conta? <a href="login.php">Conecte-se</a> </div> </div> <script type="text/javascript"> $(".textbox input").focusout(function(){ if($(this).val() == ""){ $(this).siblings().removeClass("hidden"); $(this).css("background","#554343"); }else{ $(this).siblings().addClass("hidden"); $(this).css("background","#484848"); } }); $(".textbox input").keyup(function(){ var inputs = $(".textbox input"); if(inputs[0].value != "" && inputs[1].value){ $(".login-btn").attr("disabled",false); $(".login-btn").addClass("active"); }else{ $(".login-btn").attr("disabled",true); $(".login-btn").removeClass("active"); } }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </body> </html>
108ea5f7e8907113650c6efb2885a1ea1769335b
[ "PHP" ]
9
PHP
FarmaFacil/teste
b5abcaf95bba061aacf261fffb569933ee13eaf1
4441aa06437fd301ed9f883e1ad5c03f43d7f0a4
refs/heads/master
<repo_name>murych/postin-in-vk-from-trello<file_sep>/main.py import datetime import os import requests import trello import vk from vk.photos import Photo import config def is_image_file(attachment_url): _, file_extension = os.path.splitext(attachment_url) if file_extension not in ('.jpg', '.gif', '.png'): return False return True def download_attachment(attachment_url): response = requests.get(attachment_url, stream=True) return response.content def get_attachment_in_card(card): attachment_items = (attachment for attachment in card.get_attachments() if is_image_file(attachment.url)) for attachment in attachment_items: binary_content = download_attachment(attachment.url) _, filename = os.path.split(attachment.url) yield (filename, binary_content) def is_card_can_published(trello_card): if not trello_card.due_date: return False now_unixtime = datetime.datetime.utcnow().replace(tzinfo=None).timestamp() card_due_unixtime = trello_card.due_date.replace(tzinfo=None).timestamp() delta = card_due_unixtime - now_unixtime return True if delta <= 0 and trello_card.is_due_complete else False if __name__ == '__main__': vk.set_access_token(config.VK_ACCESS_TOKEN) group = vk.get_group(config.VK_GROUP) client = trello.TrelloClient(api_key=config.TRELLO_KEY, token=config.TRELLO_TOKEN) board = client.get_board(config.TRELLO_BOARD) card_items = (card for card in board.open_cards() if is_card_can_published(card)) for card in card_items: attachment_items = \ {filename: binary_content for filename, binary_content in get_attachment_in_card(card)} photo_items = Photo.upload_wall_photos_for_group(group.id, attachment_items.items()) group.wall_post(message=card.name + '\n' + card.description, attachments=photo_items) card.set_due_complete() <file_sep>/README.md ![N|Solid](https://img.shields.io/pypi/l/py-vkontakte.svg) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/21c92d804ab541c8ae219b7098df3173)](https://www.codacy.com/app/murych/postin-in-vk-from-trello?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=murych/postin-in-vk-from-trello&amp;utm_campaign=Badge_Grade) To start, you need to fill in the `config.py` file<file_sep>/requirements.txt -e git+git://github.com/sarumont/py-trello.git@<PASSWORD>#egg=trello py-vkontakte requests<file_sep>/config.py # -*- coding: utf-8 -*- TRELLO_KEY = '' TRELLO_TOKEN = '' TRELLO_BOARD = '' VK_ACCESS_TOKEN = '' VK_GROUP = ''
f59156b443ca52693c87e89277fca5823768bc23
[ "Markdown", "Python", "Text" ]
4
Python
murych/postin-in-vk-from-trello
c45665d85169040d106a99f8e0d90c998ae0aca3
ef84187cb6feaa8460be4a9a4c8ff1df8e62d4b2
refs/heads/master
<repo_name>njmyers/sass-colors<file_sep>/README.md <h1 class="big">Sass Palette Generator</h1> This is a color generator that will create sass variables `$color-shade: rgba()` using rgba color codes. Since secondary and especially tertiary color names are not standardized I have made the naming system as follows. #### Primary colors * Red * Blue * Green #### Secondary colors * Magenta (Red and Blue) * Cyan (Blue and Green) * Yellow (Red and Green) #### Tertiary Colors * Rose (Red and Magenta) * Purple (Blue and Magenta) * Cobalt (Cyan and Blue) * Aqua (Cyan and Green) * Lime (Yellow and Green) * Orange (Yellow and Red) * Grey (Magenta, Cyan and Yellow) #### Modifier * Lighest * Lighter * Light * Dark * Darker * Darkest The color `$rose-darkest` would be three shades darker then the combination of red and magenta while `$lime-light` would be one shade lighter then yellow and green. The shades can can be changed by a modifier so that the shading can be as fine or as coarse as you wish. In addition to the shade modifier there is also an alpha channel modifier to create transparent shades of the same colors. Since this is a sass variable sheet you can include it in your `style.sass` and it will not affect the size of your final compiled CSS files. <file_sep>/src/index.js import {default as generate} from '../colors'; import './sass/style.sass'; import readme from '../README.md'; import stretch from './js/stretch'; // import './style.css'; document.getElementById('generate').addEventListener('click', generate); document.getElementById('description').innerHTML = readme; stretch.letters(); // console.log(readme);<file_sep>/log.js var arr = [1] for (var i = 1; i <=100; i ++) { // arr.push(Math.log(i)); // console.log( (Math.pow( (i / 100), 2) ) - (Math.pow( ( (i + 1) ) / 100), 2) ); console.log( (Math.pow( (i / 100), 2) ) ); // console.log(Math.log(i) - Math.log(i - 0.1)); } console.log(arr); // (1 + 6) / 2 // 3, 4, 5, 6, 7
4ce3b1aeb3cbba2c9707a684934ba2a793bb31f5
[ "Markdown", "JavaScript" ]
3
Markdown
njmyers/sass-colors
ccf50f273280a763e72e7a22fc4159871d7fba45
4345199dcf2568f1fd74a59a2353b44dd229c946
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Api; use App\Http\Requests\BannerRequest; use App\Http\Requests\Request; use App\Services\BannerServices; use App\Models\Banner; use App\Http\Controllers\Controller; class BannerController extends Controller { protected $banner; protected $bannerServices; public function __construct(Banner $banner,BannerServices $bannerServices) { $this->banner= $banner; $this->bannerServices= $bannerServices; } //轮播图列表 public function index(Request $request) { $limit = $request->get("limit"); $banners = $this->banner->latest()->paginate($limit); return success("暂时没有轮播图数据",$banners); } //轮播图添加 public function store(BannerRequest $request) { $banners=$this->banner->create($request->all()); return $banners ? success("添加成功") : error("添加失败"); } //轮播图修改 public function update(BannerRequest $request, Banner $banner) { $banners = $banner->update($request->all()); return $banners ? success("修改成功", $banners) : error("修改失败"); } //轮播图删除 public function destroy(BannerRequest $request,$id) { $del=$this->banner->whereIn('id',explode(",",$id))->delete(); return $del ? success("删除成功") : error("删除失败"); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Category extends Model { use SoftDeletes; protected $fillable = [ 'parent_id','name', 'pic', 'head_pic','detail', ]; } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Services\IndexServices; use App\Http\Controllers\Controller; class IndexController extends Controller { public function __construct(IndexServices $indexServices) { } //后台首页列表 public function index( ) { return view('admin.indices.index'); } //后台首页列表 public function dashboard( ) { return view('admin.indices.dashboard'); } } <file_sep><?php namespace App\Http\Controllers\Api; use App\Exceptions\MessageException; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class UploadController extends BaseController { public function uploadImages(Request $request) { $suffix=$request->file('image')->getClientOriginalExtension(); $fileName=$request->file('image')->getClientOriginalName(); $imageName=str_replace('.'.$suffix,'',$fileName); $path['name']=$imageName; $path['url']= $request->file('image')->store( 'files_images/'.date('Y-m-d',time()), 'public'); return success("上传成功",$path); } } <file_sep><?php function route_class(){ return str_replace('.','-', Route::currentRouteName()); } function success ($msg = '', $data = '', array $header = []){ $code = 0; if (is_array($msg)) { $code = $msg['code']; $msg = $msg['msg']; } $result = [ 'code' => $code, 'msg' => $msg, 'data' => $data, ]; $header['Access-Control-Allow-Origin'] = '*'; $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token'; $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS'; return response()->json($result, $code > 0 ? $code : 200) ->withHeaders($header); } function error ($msg = '', $data = '', array $header = []){ $code = 1; if (is_array($msg)) { $code = $msg['code']; $msg = $msg['msg']; } $result = [ 'code' => $code, 'msg' => $msg, 'data' => $data, ]; $header['Access-Control-Allow-Origin'] = '*'; $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token'; $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS'; return response()->json($result, $code > 0 ? $code : 200) ->withHeaders($header); } <file_sep><?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ $api = app('Dingo\Api\Routing\Router'); $api->version('v1', [ 'namespace' => 'App\Http\Controllers\Api' ], function($api) { $api->get('/init','InitController@index'); $api->POST('/uploadImages', 'UploadController@uploadImages'); $api->resource("category","CategoryController",["only"=>["index","store","update","destroy"]]); /*-----------------------------轮播图-----------------------------*/ $api->resource('banners', 'BannerController', ['only' => ['index', 'store', 'update', 'destroy']]); /*-----------------------------轮播图-----------------------------*/ $api->resource('banners', 'BannerController', ['only' => ['index', 'store', 'update', 'destroy']]); /*-----------------------------轮播图-----------------------------*/ $api->resource('banners', 'BannerController', ['only' => ['index', 'store', 'update', 'destroy']]); /*-*/ }); <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::group(['namespace' => 'Admin', 'prefix' => env('ROUTE_FREFIX'), 'as' => 'admin.', 'middleware' => []], function ($router) { /*-----------------------------后台首页-----------------------------*/ $router->get('/', 'IndexController@index'); //主页 $router->get('/dashboard', 'IndexController@dashboard')->name("dashboard"); $router->get('/category', 'CategoryController@index')->name("category.index"); /*-----------------------------轮播图-----------------------------*/ $router->resource('banners', 'BannerController', ['only' => ['index', 'create', 'store', 'update', 'edit', 'destroy']]); /*-----------------------------轮播图-----------------------------*/ $router->resource('banners', 'BannerController', ['only' => ['index', 'create', 'store', 'update', 'edit', 'destroy']]); /*-----------------------------轮播图-----------------------------*/ $router->resource('banners', 'BannerController', ['only' => ['index', 'create', 'store', 'update', 'edit', 'destroy']]); /*-*/ }); <file_sep><?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class InitController extends BaseController { public function index() { return response()->json(file_get_contents(resource_path("js/api/init.json"))); } } <file_sep>layui.use(['form', 'table','upload'], function () { var $ = layui.jquery, form = layui.form, table = layui.table, upload = layui.upload; table.render({ elem: '#table', url: api.category.list ,toolbar: '#toolbar' //开启头部工具栏,并为其绑定左侧模板 ,cols: [[ {type: "checkbox", width: 50, fixed: "left"}, {field: 'id', width: 80, title: 'ID', sort: true}, {field: 'name', title: '分类名', sort: true,edit: 'text',}, {field: 'pic', title: '封面',templet:function (res) { return `<img src="/storage/${res.pic}">`; }}, {field: 'head_pic', title: '副封面',templet:function (res) { return `<img src="/storage/${res.head_pic}">`; }}, {field: 'created_at', title: '添加时间', sort: true}, {field: 'updated_at', title: '更新时间', sort: true}, {title: '操作', templet: '#table-bar', fixed: "right", align: "center"} ]], done: function (res, curr, count) { window.tableList=res.data; }, limits: [10, 15, 20, 25, 50, 100], limit: 15, page: true ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据 return { "code": res.code, //解析接口状态 "msg": res.msg, //解析提示文本 "count": res.data.total, //解析数据长度 "data": res.data.data //解析数据列表 }; } }); //头工具栏事件 table.on('toolbar(table)', function(obj){ var checkStatus = table.checkStatus(obj.config.id); switch(obj.event){ case 'add': add_edit(); break; case 'del': var data = checkStatus.data; layer.confirm('真的删除行么', function (index) { del(_.map(data, 'id'),table); layer.close(index); table.reload('table') }); break; }; }); // 监听搜索操作 form.on('submit(data-search-btn)', function (data) { var result = JSON.stringify(data.field); layer.alert(result, { title: '最终的搜索信息' }); //执行搜索重载 table.reload('table', { page: { curr: 1 } , where: { searchParams: result } }, 'data'); return false; }); //自定义验证规则 form.verify({ pic: function(value){ if(value == ""){ return '请上传封面'; } }, headPic: function(value){ if(value == ""){ return '请上传副封面'; } } }); form.on("submit(submit)",function (data) { console.log(data.field); var method ="post"; var url=api.category.create; if(data.field.id != ""){ method="put"; url=api.category.update.replace(":id",data.field.id) } axios({ method:method, url:url, data:data.field }).then(function(res){ console.log(res); layer.msg(res.data.msg,{icon:1}); table.reload('table') layer.closeAll(); }).catch(function(err){ error(err); }) return false; }); function add_edit(data= null){ var btn = data == null ? '确认添加' : "确定修改" var title =data == null ? '添加分类' : "编辑-"+data.name; layer.open({ type: 1, id:"add-layer" ,title: title ,area: ['900px', '750px'] ,shade: [0.8, '#393D49'] ,anim: 1 ,maxmin: true ,btnAlign:"c" ,content: $("#add").html() ,btn: [btn, '取消'] ,yes: function(index,layero){ var submitID="submit" ,submit =layero.find("#"+submitID) submit.click(); // layer.close(index); } ,btn2: function(index){ layer.close(index); } ,success: function(layero){ layer.ready(function(){ var html=`<option value="0">父级分类</option>`; window.tableList.forEach(function (item,index) { html+=`<option value="${item.id}">${item.name}</option>` }) $("select[name='parent_id']").html(html); if(data !=null){ form.val('form', data); $('#preview').attr('src',"/storage/"+ data.pic); //图片链接(base64) $('#preview2').attr('src',"/storage/"+ data.head_pic); //图片链接(base64) } form.render(); //封面上传 var uploadInst = upload.render({ elem: '#cover-upload' ,url: api.upload.image ,exts: 'jpg|png|jpeg' ,field:"image" ,before: function(obj){ //预读本地文件示例,不支持ie8 obj.preview(function(index, file, result){ $('#preview').attr('src', result); //图片链接(base64) }); } ,done: function(res){ //如果上传失败 if(res.code > 0){ return layer.msg('上传失败'); } layer.msg('封面上传成功'); $('#cover').val(res.data.url) //上传成功 } ,error: function(){ //演示失败状态,并实现重传demo-reload var demoText = $('cover-text'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs cover-reload">重试</a>'); demoText.find('.cover-reload').on('click', function(){ uploadInst.upload(); }); } }); var uploadInst2 = upload.render({ elem: '#cover-upload2' ,url: api.upload.image ,exts: 'jpg|png|jpeg' ,field:"image" ,before: function(obj){ //预读本地文件示例,不支持ie8 obj.preview(function(index, file, result){ $('#preview2').attr('src', result); //图片链接(base64) }); } ,done: function(res){ //如果上传失败 if(res.code > 0){ return layer.msg('上传失败'); } //上传成功 layer.msg('副封面上传成功'); $('#cover2').val(res.data.url) } ,error: function(){ //演示失败状态,并实现重传demo-reload var demoText = $('.cover-text2'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs cover-reload2">重试</a>'); demoText.find('.cover-reload2').on('click', function(){ uploadInst2.upload(); }); } }); }); } }); } // 监听删除操作 $(".data-delete-btn").on("click", function () { var checkStatus = table.checkStatus('currentTableId') , data = checkStatus.data; layer.alert(JSON.stringify(data)); }); //监听表格复选框选择 table.on('checkbox(currentTableFilter)', function (obj) { console.log(obj) }); table.on('tool(table)', function (obj) { var data = obj.data; if (obj.event === 'edit') { add_edit(data); } else if (obj.event === 'delete') { layer.confirm('真的删除行么', function (index) { del([data.id],obj); layer.close(index); }); } }); }); <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateMenusTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('menus', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('parent_id'); $table->string("title",100)->index()->comment("菜单名"); $table->string("href",255)->index()->comment("菜单url"); $table->string("icon",100)->nullable()->comment("菜单图标"); $table->string("target",20)->default("_self")->comment("菜单跳转"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('menus'); } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Requests\BannerRequest; use App\Http\Requests\Request; use App\Services\BannerServices; use App\Models\Banner; use App\Http\Controllers\Controller; class BannerController extends Controller { protected $banner; protected $bannerServices; public function __construct(Banner $banner,BannerServices $bannerServices) { $this->banner= $banner; $this->bannerServices= $bannerServices; } //轮播图列表 public function index(Request $request) { return view('admin.banners.index'); } } <file_sep><?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Http\Requests\CategoryRequest; use App\Models\Category; use Illuminate\Http\Request; class CategoryController extends BaseController { protected $category; public function __construct(Category $category) { $this->category= $category; } public function index(CategoryRequest $request) { $limit = $request->get("limit"); $categorys=$this->category->paginate($limit ?? 15); return success("暂时没有分类数据",$categorys); } public function store(CategoryRequest $request) { $category=$this->category->create($request->all()); return $category ? success("添加成功") : error("添加失败"); } public function update(CategoryRequest $request, $id) { $category=$this->category->findOrFail($id); $category->update($request->all()); return $category ? success("修改成功",$category) : error("修改失败"); } /** * @param Request $request * @return $this */ public function destroy(Request $request,$id) { $del= $this->category->whereIn('id',explode(",",$id))->delete(); return $del ? success("删除成功") : error("删除失败"); } } <file_sep><?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Str; class crud extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'crud:generate {name}{title}'; /** * The console command description. * * @var string */ protected $description = 'Create CRUD operations'; /** * CrudGenerator constructor. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $name = $this->argument('name'); $title = $this->argument('title'); $this->controller($name,$title); $this->service($name,$title); $this->model($name,$title); $this->request($name,$title); $this->viewIndex($name); $this->Api($name,$title); $this->ApiJs($name,$title); $this->Js($name,$title); $this->Apicontroller($name,$title); $this->migrations($name,$title); // //将当前添加的权限添加给超级管理员 // $super_admin = Role::where('id', '=', 1)->firstOrFail(); //将输入角色匹配 // //将当前添加的权限添加给企划 // $layout_admin = Role::where('id', '=', 2)->firstOrFail(); //将输入角色匹配 $show_add_edit_del=[ ['name'=>'show '.strtolower(Str::plural(Str::snake($name))), 'title'=>$title.'查看'], ['name'=>'create '.strtolower(Str::plural(Str::snake($name))), 'title'=>$title.'添加'], ['name'=>'edit '.strtolower(Str::plural(Str::snake($name))), 'title'=>$title.'修改'], ['name'=>'delete '.strtolower(Str::plural(Str::snake($name))), 'title'=>$title.'删除'], ]; // foreach ($show_add_edit_del as $v){ // $permission=Permission::create($v); // $permission->syncRoles([$super_admin,$layout_admin]); // } // File::append(base_path('routes/web.php'), PHP_EOL.'/*-----------------------------'.$title.'-----------------------------*/'.PHP_EOL.'$router->resource(\'' . strtolower(Str::plural(Str::snake($name))) . "', '{$name}Controller', ['only' => ['index', 'create', 'store', 'update', 'edit', 'destroy']]);").PHP_EOL; $this->webRoute($name,$title); } /*--------------------- -获取文件- ---------------------*/ protected function getStub($type) { return file_get_contents(resource_path("stubs/$type.stub")); } /*--------------------- -转换Web.php- ---------------------*/ protected function webRoute($name,$title) { $modelTemplate = str_replace( [ '/*-*/', ], [ PHP_EOL.' /*-----------------------------'.$title.'-----------------------------*/'.PHP_EOL.' $router->resource(\'' . strtolower(Str::plural(Str::snake($name))) . "', '{$name}Controller', ['only' => ['index', 'create', 'store', 'update', 'edit', 'destroy']]);".PHP_EOL.'/*-*/' ], file_get_contents(base_path('routes/web.php')) ); file_put_contents(base_path('routes/web.php'), $modelTemplate); } /*--------------------- -转换Api- ---------------------*/ protected function Api($name,$title) { $modelTemplate = str_replace( [ '/*-*/', ], [ PHP_EOL.' /*-----------------------------'.$title.'-----------------------------*/'.PHP_EOL.' $api->resource(\'' . strtolower(Str::plural(Str::snake($name))) . "', '{$name}Controller', ['only' => ['index', 'store', 'update', 'destroy']]);".PHP_EOL.'/*-*/' ], file_get_contents(base_path('routes/api.php')) ); file_put_contents(base_path('routes/api.php'), $modelTemplate); } /*--------------------- -转换Api- ---------------------*/ protected function ApiJs($name,$title) { $name=strtolower(Str::plural(Str::snake($name))); $modelTemplate = str_replace( [ '/*-*/', ], [ PHP_EOL.' /*-----------------------------'.$title.'-----------------------------*/'.PHP_EOL. "'$name'".":{".PHP_EOL. "'list':'/api/$name', //$title"."列表 get".PHP_EOL. "'info':'/api/$name/:id',//$title.详情 get".PHP_EOL. "'create':'/api/$name',//$title.新增 post".PHP_EOL. "'update':'/api/$name/:id',//$title.修改 put".PHP_EOL. "'update':'/api/$name/:ids',//$title.删除 get".PHP_EOL. "},". '/*-*/' ], file_get_contents(public_path('js/api.js')) ); file_put_contents(public_path('js/api.js'), $modelTemplate); } /*--------------------- -转换Js- ---------------------*/ protected function Js($name,$title) { $controllerTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}', '{{modelTitle}}' ], [ $name, strtolower(Str::plural(Str::snake($name))), strtolower(Str::snake($name)), $title ], $this->getStub('js') ); if (!file_exists($path = public_path('cctgd'))) mkdir($path, 0777, true); file_put_contents(public_path("cctgd/".strtolower(Str::plural(Str::snake($name))).".js"), $controllerTemplate); } /*--------------------- -转换Model- ---------------------*/ protected function model($name,$title) { $modelTemplate = str_replace( [ '{{modelName}}', '{{modelTitle}}' ], [ $name, $title ], $this->getStub('Model') ); if (!file_exists($path = app_path('Models'))) mkdir($path, 0777, true); file_put_contents(app_path("Models/{$name}.php"), $modelTemplate); } /*--------------------- -转换ApiController- ---------------------*/ protected function Apicontroller($name,$title) { $controllerTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}', '{{modelTitle}}' ], [ $name, strtolower(Str::plural(Str::snake($name))), strtolower(Str::snake($name)), $title ], $this->getStub('ApiController') ); if (!file_exists($path = app_path('/Http/Controllers/Api'))) mkdir($path, 0777, true); file_put_contents(app_path("/Http/Controllers/Api/{$name}Controller.php"), $controllerTemplate); } /*--------------------- -转换Controller- ---------------------*/ protected function controller($name,$title) { $controllerTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}', '{{modelTitle}}' ], [ $name, strtolower(Str::plural(Str::snake($name))), strtolower(Str::snake($name)), $title ], $this->getStub('Controller') ); if (!file_exists($path = app_path('/Http/Controllers/Admin'))) mkdir($path, 0777, true); file_put_contents(app_path("/Http/Controllers/Admin/{$name}Controller.php"), $controllerTemplate); } /*--------------------- -转换Service- ---------------------*/ protected function service($name,$title) { $serviceTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}', '{{modelTitle}}' ], [ $name, strtolower(Str::plural(Str::snake($name))), strtolower(Str::snake($name)), $title ], $this->getStub('Services') ); if (!file_exists($path = app_path('Services'))) mkdir($path, 0777, true); file_put_contents(app_path("Services/{$name}Services.php"), $serviceTemplate); } /*--------------------- -转换Request- ---------------------*/ protected function request($name,$title) { $requestTemplate = str_replace( [ '{{modelName}}', '{{modelTitle}}' ], [ $name, $title ], $this->getStub('Request') ); if (!file_exists($path = app_path('/Http/Requests'))) mkdir($path, 0777, true); file_put_contents(app_path("/Http/Requests/{$name}Request.php"), $requestTemplate); } /*--------------------- -转换Index视图文件- ---------------------*/ protected function viewIndex($name) { $viewIndexTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}' ], [ $name, strtolower(Str::plural(Str::snake($name))), strtolower(Str::snake($name)) ], $this->getStub('views/index') ); if (!file_exists($path = resource_path("views/admin/".strtolower(Str::plural(Str::snake($name)))))) mkdir($path, 0777, true); file_put_contents(resource_path("views/admin/".strtolower(Str::plural(Str::snake($name)))."/index.blade.php"), $viewIndexTemplate); } /*--------------------- -转换form视图文件- ---------------------*/ protected function viewForm($name) { $viewFormTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}' ], [ $name, strtolower(Str::plural(Str::snake($name))), strtolower(Str::snake($name)) ], $this->getStub('views/form') ); if (!file_exists($path = resource_path("views/admin/".strtolower(Str::plural(Str::snake($name)))))) mkdir($path, 0777, true); file_put_contents(resource_path("views/admin/".strtolower(Str::plural(Str::snake($name)))."/form.blade.php"), $viewFormTemplate); } /*--------------------- -转换create_and_edit视图文件- ---------------------*/ protected function viewCreateAndEdit($name) { $viewCreateAndEditTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}' ], [ $name, strtolower(Str::plural(Str::snake($name))), strtolower(Str::snake($name)) ], $this->getStub('views/create_and_edit') ); if (!file_exists($path = resource_path("views/admin/".strtolower(Str::plural(Str::snake($name)))))) mkdir($path, 0777, true); file_put_contents(resource_path("views/admin/".strtolower(Str::plural(Str::snake($name)))."/create_and_edit.blade.php"), $viewCreateAndEditTemplate); } /*--------------------- -转换migrations文件- ---------------------*/ protected function migrations($name,$title) { $migrationsTemplate = str_replace( [ '{{modelName}}', '{{modelNamePluralLowerCase}}', '{{modelNameSingularLowerCase}}', '{{modelTitle}}' ], [ Str::plural($name), strtolower(Str::plural(Str::snake($name))), strtolower($name), $title, ], $this->getStub('migrations/migration') ); $migrationsname = date('Y_m_d_His').'_create_'.strtolower(Str::plural(Str::snake($name))).'_table'; file_put_contents(database_path("migrations/".$migrationsname.".php"), $migrationsTemplate); } } <file_sep><?php namespace App\Services; use App\Models\Index; class IndexServices { } ?><file_sep><?php namespace App\Http\Requests; class CategoryRequest extends Request { public function attributes() { return [ 'name'=>'分类名', 'pic'=>'封面', 'head_pic' => '“副封面', 'detail' => '描述', ]; } public function rules() { switch($this->method()) { // CREATE case 'POST': { return [ 'name'=>'required|unique:categories', 'pic'=>'required', 'head_pic' => 'required', 'detail' => 'required', ]; } // UPDATE case 'PUT': case 'PATCH': { return [ 'name'=>'required|unique:categories,name,'.$this->route('category'), 'pic'=>'required', 'head_pic' => 'required', 'detail' => 'required', ]; } case 'GET': case 'DELETE': default: { return []; }; } } public function messages() { return [ 'name.required' => '分类名不能为空!', 'name.unique' => '分类名已存在!', 'pic.required' => '封面必须上传!', 'head_pic.required' => '副封面必须上传!', 'detail.required' => '详情不能为空!', ]; } } <file_sep><?php namespace App\Services; use App\Models\Banner; class BannerServices { } ?>
e338ef88fa5f8d1c8c70eb41202fc790bc12538c
[ "JavaScript", "PHP" ]
16
PHP
5852305/cctgd_backend
f6cfef6352608ba22ceecb1c3c00e3b9a6a8f26f
784a269da5882d1c361de588c722fce27c86b555
refs/heads/master
<repo_name>aur-archive/profanity<file_sep>/PKGBUILD # Maintainer: <NAME> <<EMAIL>> pkgname=profanity pkgver=0.3.1 pkgrel=1 pkgdesc='A console based jabber client inspired by irssi' arch=('i686' 'x86_64') url="https://github.com/boothj5/profanity" license=('GPL3') depends=('curl' 'expat' 'glib2' 'libnotify' 'libxss') makedepends=('check' 'doxygen' 'libstrophe-git') source=("http://www.profanity.im/$pkgname-$pkgver.tar.gz") md5sums=('8967191ac70a61b770aaee27992258f3') build() { cd "$srcdir/$pkgname-$pkgver" ./bootstrap.sh ./configure --prefix=/usr make } package() { cd "$srcdir/$pkgname-$pkgver" make PREFIX=/usr DESTDIR="$pkgdir" install }
65d6b8cc663dca3c00741ad25a0b49ccb7a1eaa5
[ "Shell" ]
1
Shell
aur-archive/profanity
e987f8487a652bc54bed183b2618bcc1d44fc931
b8ab40b2a021ef38508da38ff2135e2b153b3522
refs/heads/master
<repo_name>singhprd/Project4<file_sep>/rails_foodshare/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) User.destroy_all Company.destroy_all Courier.destroy_all Job.destroy_all company_one = Company.create!( name: "Soderberg", email: "<EMAIL>", phone: "0131 441 1122", address1: "4 West End Way", address2: "West End", address3: "Edinburgh", postcode: "EH1 1WE", lat: 55.951060, lng: -3.209982 ) company_two = Company.create!( name: "<NAME>", email: "<EMAIL>", phone: "0131 442 3344", address1: "5 High Road", address2: "Colinton", address3: "Edinburgh", postcode: "EH3 1WT", lat: 55.947250, lng: -3.191335 ) company_three = Company.create!( name: "<NAME>", email: "<EMAIL>", phone: "0131 692 5555", address1: "15 Blackfriars Street", address2: "Royal Mile", address3: "Edinburgh", postcode: "EH1 1NB", lat: 55.949658, lng: -3.185613 ) courier_one = Courier.create!( first_name: "Joe", last_name: "Bloggs", phone: "0773526262" ) courier_two = Courier.create!( first_name: "Jenny", last_name: "Bloggs", phone: "0131213434" ) user_one = User.create!( email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>', company_id: company_one.id ) user_two = User.create!( email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>', courier_id: courier_one.id ) job_one = Job.create!( company: company_one, courier: courier_two, item: "Bread", quantity: 5, instructions: "Bread available. Pick up between 3pm and 6pm.", from_date: Date.parse("2016-05-22"), to_date: Date.parse("2016-05-22"), category: "Supply" ) job_two = Job.create!( company: company_two, courier: courier_one, item: "Butter", quantity: 2, instructions: "Butter available. Pick up between 3pm and 6pm.", from_date: Date.parse("2016-05-22"), to_date: Date.parse("2016-05-22"), category: "Supply" ) job_three = Job.create!( company: company_one, courier: courier_one, item: "Bread", quantity: 5, instructions: "Bread needed. Please leave with reception.", from_date: Date.parse("2016-05-22"), to_date: Date.parse("2016-05-22"), category: "Demand" ) job_four = Job.create!( company: company_two, courier: nil, item: "Bacon", quantity: 5, instructions: "Spare bacon, take today", from_date: Date.parse("2016-05-20"), to_date: Date.parse("2016-05-20"), category: "Supply" ) Job.create!( company: company_three, courier: nil, item: "Coffee", quantity: 10, instructions: "Spare coffee for pickup with Dave", from_date: Date.parse("2016-05-24"), to_date: Date.parse("2016-05-24"), category: "Supply" ) Job.create!( company: company_three, courier: nil, item: "Green beans", quantity: 50, instructions: "Beans needed for charity dinner", from_date: Date.parse("2016-05-24"), to_date: Date.parse("2016-05-24"), category: "Demand" ) <file_sep>/node_foodshare/client/src/components/Main.jsx var _ = require('lodash'); var React = require('react'); var SignIn = require('./authentication/SignIn.jsx'); var SignUp = require('./authentication/SignUp.jsx'); var SignOut = require('./authentication/SignOut.jsx'); var ScranShareSignUp = require('./user_views/ScranShareSignUp.jsx') var ScranShareSignUp = require('./user_views/ScranShareSignUp.jsx') var CompanyView = require('./user_views/CompanyView.jsx') var CourierView = require('./user_views/CourierView.jsx') var Navbar = require('./Navbar') //sample job to pass through to joblist if required: // var sampleJSON = require('../sample.json'); //child components: var JobList = require('./JobList'); var GoogleMap = require('./GoogleMap'); //beginning attempts at newing up a google map: // var Map = require('../map/googlemap'); //does the initial state have an empty array of jobs? i.e previous saved jobs could be store here var Main = React.createClass({ getInitialState: function(){ return{currentUser:null, jobs:[]}; }, forceUpdateState:function(object) { this.setState(object); }, setUser:function(user){ this.setState({currentUser:user, jobs:[]}); this.fetchJobs(); }, fetchJobs: function(){ var request = new XMLHttpRequest(); request.open("GET", this.props.url + "jobs.json"); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.onload = function(){ if(request.status === 200){ var jobs = JSON.parse(request.responseText); if ( !_.isEqual(jobs, this.state.jobs) ) { this.setState({jobs: jobs}); } setTimeout(this.fetchJobs, 1000); } }.bind(this) request.send(null); }, fetchUser: function(){ var request = new XMLHttpRequest(); request.open("GET", this.props.url + "users.json"); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.onload = function(){ if(request.status === 200){ var receivedUser = JSON.parse(request.responseText); this.setUser(receivedUser); }else if(request.status === 401){ this.setState({currentUser:false}); } }.bind(this) request.send(null); }, componentDidMount: function(){ this.fetchUser(); }, render: function() { var mainDiv = null; if(!this.state.currentUser) { mainDiv = ( <div> <Navbar/> <h4> Please Sign In/Up </h4> <SignIn url={this.props.url + "users/sign_in.json"} onSignIn={this.setUser}></SignIn> <SignUp url={this.props.url + "users.json"} onSignUp={this.setUser}></SignUp> </div> ) } else { if(this.state.currentUser.company_id !== null) { // USER HAS COMPANY mainDiv = <div> <CompanyView forceUpdateState={this.forceUpdateState} url={this.props.url} onSignOut={this.setUser} company={this.state.currentUser} jobs={this.state.jobs} fetchJobs = {this.fetchJobs}/> </div> } else if (this.state.currentUser.courier_id !== null) { // USER IS A COURIER mainDiv = <div> <CourierView url={this.props.url} user={this.state.currentUser} jobs={this.state.jobs} fetchJobs = {this.fetchJobs} onSignOut={this.setUser}/> </div> } else { // USER IS NOT COURIER OR COMPANY mainDiv = <div> <ScranShareSignUp url={this.props.url}/> <SignOut url={this.props.url + "users/sign_out.json"} onSignOut={this.setUser}></SignOut> </div> } } return ( <div> { mainDiv } </div> ); } }); module.exports = Main;<file_sep>/rails_foodshare/test/models/company_test.rb require 'test_helper' class CompanyTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "has a name" do assert_equal("Sodeberg", companies(:one).name) end test "has an email" do assert_equal("<EMAIL>", companies(:one).email) end test "has phone number" do assert_equal("0131 332 1111", companies(:one).phone) end test "has address line 1" do assert_equal("3 WestEnd Place", companies(:one).address1) end test "can return just lat" do assert_equal(1.0232, companies(:one).lat) end test "can return both lat and lng" do assert_equal({lat: 1.0232, lng: -0.4567}, companies(:one).position) end test "can return hash with info" do assert_equal( { name: "Sodeberg", position: { lat: 1.0232, lng: -0.4567 }, contactDetails: { email: "<EMAIL>", phone: "0131 332 1111", address1: "3 WestEnd Place", address2: "West End", address3: "Edinburgh", postcode: "EH3 1RT" } }, companies(:one).to_hash ) end end <file_sep>/node_foodshare/client/src/components/user_views/ScranShareSignUp_assets/CompanyForm.jsx var React = require('react'); var LinkedStateMixin = require('react-addons-linked-state-mixin'); var CompanyForm = React.createClass({ mixins: [LinkedStateMixin], getInitialState: function() { return {companyName: '', phoneNumber: '', address1: '', address2: '', address3: '', postcode: '', email: '', errors:''}; }, handleSubmit: function(e){ e.preventDefault(e); // url (required), options (optional) fetch('https://api.postcodes.io/postcodes/'+this.state.postcode, { method: 'get' }).then(function(response) { if(response.status == 200) { response.json().then(function(data){ var toPost = { name: this.state.companyName, lat: data.result.latitude, lng: data.result.longitude, phone: this.state.phoneNumber, email: this.state.email, address1: this.state.address1, address2: this.state.address2, address3: this.state.address3, postcode: this.state.postcode } var request = new XMLHttpRequest(); request.open("POST", this.props.url+'/companies'); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.onload = function(){ if(request.status === 200){ console.log(request.responseText); window.location.reload(); }else { console.log("error posting company data", request.status) } }.bind(this) request.send(JSON.stringify(toPost)); }.bind(this)) } else { this.setState({errors:"Postcode not valid"}) } }.bind(this)).catch(function(err) { // Error :( }); }, render: function() { return ( <div> <button value="none" onClick={this.props.selectType} type="submit" className="pure-button pure-button-primary"> <i className="fa fa-arrow-left" aria-hidden="true"> </i> Go Back! </button> <form className="pure-form pure-form-aligned"> <fieldset> <div className="pure-control-group"> <label for="companyName">Company Name</label> <input valueLink={this.linkState('companyName')} id="companyName" type="text" placeholder="Company Name"/> </div> <div className="pure-control-group"> <label for="phoneNumber">Phone Number</label> <input valueLink={this.linkState('phoneNumber')} id="phoneNumber" type="text" placeholder="Phone Number"/> </div> <div className="pure-control-group"> <label for="email">Email</label> <input valueLink={this.linkState('email')} id="email" type="email" placeholder="Email"/> </div> <div className="pure-control-group"> <label for="address1">Address 1</label> <input valueLink={this.linkState('address1')} id="address1" type="text" placeholder="Address 1"/> </div> <div className="pure-control-group"> <label for="address2">Address 2</label> <input valueLink={this.linkState('address2')} id="address2" type="text" placeholder="Address 2"/> </div> <div className="pure-control-group"> <label for="address3">Address 3</label> <input valueLink={this.linkState('address3')} id="address3" type="text" placeholder="Address 3"/> </div> <div className="pure-control-group"> <label for="postcode">Postcode</label> <input valueLink={this.linkState('postcode')} id="postcode" type="text" placeholder="Postcode"/> </div> <div className="pure-controls"> <button onClick={this.handleSubmit} type="submit" className="pure-button pure-button-primary"> <i className="fa fa-check" aria-hidden="true"></i> Submit</button> </div> <p>{this.state.errors}</p> </fieldset> </form> </div> ) } }); module.exports = CompanyForm; // response.json().then(function(data){ // var toPost = { // name: this.state.companyName, // lat: data.result.latitude, // lng: data.result.longitude, // phone: this.state.phoneNumber, // email: this.state.email, // address1: this.state.address1, // address2: this.state.address2, // address3: this.state.address3, // postcode: this.state.postcode // } // }.bind(this))<file_sep>/rails_foodshare/test/models/user_test.rb require 'test_helper' class UserTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "has email" do assert_equal("<EMAIL>", users(:one).email) end # test "has password" do # assert_equal("<PASSWORD>", users(:one).password) # end end <file_sep>/rails_foodshare/app/controllers/companies_controller.rb class CompaniesController < ApplicationController before_action :authenticate_user! def index render json: current_user.company end def create if current_user.courier || current_user.company render :nothing => true, :status => :bad_request else company = Company.create(company_params) current_user.update(company_id: company.id) render json: company end end def update id = params[:id].to_i if id != current_user.company_id render nothing: true, status: :forbidden else company = Company.find_by(id: id) company.update(company_params) render json: company end end def destroy id = params[:id].to_i if id != current_user.company_id render nothing: true, status: :forbidden else Company.destroy(id) current_user.update(company_id: nil) render nothing: true, status: :ok end end private def company_params params.require(:company).permit(:name, :lat, :lng, :phone, :email, :address1, :address2, :address3, :postcode) end end<file_sep>/rails_foodshare/app/controllers/couriers_controller.rb class CouriersController < ApplicationController before_action :authenticate_user! def index render json: current_user.courier end def create if current_user.courier || current_user.company render :nothing => true, :status => :bad_request else courier = Courier.create(courier_params) current_user.update(courier_id: courier.id) render json: courier end end def update id = params[:id].to_i if id != current_user.courier_id render nothing: true, status: :forbidden else courier = Courier.find_by(id: id) courier.update(courier_params) render json: courier end end def destroy id = params[:id].to_i if id != current_user.courier_id render nothing: true, status: :forbidden else Courier.destroy(id) current_user.update(courier_id: nil) render nothing: true, status: :ok end end private def courier_params params.require(:courier).permit(:first_name, :last_name, :phone) end end <file_sep>/node_foodshare/client/src/components/DatePicker.jsx import React from 'react'; import DayPicker, { DateUtils } from "react-day-picker"; function sunday(day) { return day.getDay() === 0; } export default class DatePicker extends React.Component { constructor() { super() state = { selectedDay: new Date(), } } handleDayClick(e, day, { selected, disabled }) { if (disabled) { return; } if (selected) { this.setState({ selectedDay: null }) } else { this.setState({ selectedDay: day }); } } render() { return ( <DayPicker initialMonth={ new Date(2016, 1) } disabledDays={ sunday } selectedDays={ day => DateUtils.isSameDay(this.state.selectedDay, day) } onDayClick={ this.handleDayClick.bind(this) } />); } } // export { DatePicker }; // exports a function declared earlier <file_sep>/node_foodshare/client/src/components/user_views/EditJobForm.jsx Date.prototype.isValid = function () { // An invalid date object returns NaN for getTime() and NaN is the only // object not strictly equal to itself. return this.getTime() === this.getTime(); }; var React = require('react'); var LinkedStateMixin = require('react-addons-linked-state-mixin'); var EditJobForm = React.createClass({ mixins: [LinkedStateMixin], getInitialState: function() { return {id: this.props.job.id, item:this.props.job.item,instructions:this.props.job.instructions,quantity:this.props.job.quantity, from_date: this.getTodaysDate(), to_date: this.getTodaysDate(), error:'', submited:false, category:this.props.job.category} }, getTodaysDate: function() { var d = new Date(); var year = d.getFullYear(); var month = d.getMonth() + 1; if(month < 10) { month = `0${month}` } var date = d.getDate(); if(date < 10) { date = `0${date}` } return `${year}-${month}-${date}` }, handleSubmit: function(e){ e.preventDefault() this.props.onUpdate(this.state) // this.setState(item:this.props.job.item,instructions:this.props.job.instructions,quantity:this.props.job.quantity, from_date: this.getTodaysDate(), to_date: this.getTodaysDate(), error:'', submited:false, category:this.props.job.category} // }) // this.props.onUpdateJob(this) }, render: function(){ // console.log("reached render in EditJobForm") // console.log(this.props) var FormView = ( <div> <form className="pure-form pure-form-aligned"> <fieldset> <div className="pure-control-group"> <label for="state">Type</label> <select valueLink={this.linkState('category')} id="state"> <option value="Supply">Supply</option> <option value="Demand">Demand</option> </select> </div> <div className="pure-control-group"> <label for="item">item</label> <input valueLink={this.linkState('item')} id="item" type="text" placeholder="item"/> </div> <div className="pure-control-group"> <label for="quantity">quantity</label> <input valueLink={this.linkState('quantity')} id="quantity" type="text" placeholder="quantity"/> </div> <div className="pure-control-group"> <label for="instructions">instructions</label> <input valueLink={this.linkState('instructions')} id="instructions" type="text" placeholder="instructions"/> </div> <div className="pure-control-group"> <label for="from_date">from_date</label> <input valueLink={this.linkState('from_date')} id="from_date" type="date" placeholder="from_date"/> </div> <div className="pure-control-group"> <label for="to_date">to_date</label> <input valueLink={this.linkState('to_date')} id="to_date" type="date" placeholder="to_date"/> </div> <div className="pure-controls"> <button onClick={this.handleSubmit} type="submit" className="pure-button pure-button-primary"> <i className="fa fa-check" aria-hidden="true"></i> Update</button> </div> </fieldset> </form> {this.state.error} </div> ) return <div>{FormView}</div> } }); module.exports = EditJobForm;<file_sep>/node_foodshare/client/src/components/user_views/ScranShareSignUp_assets/ButtonFilter.jsx var React = require('react'); var ButtonFilter = React.createClass({ render: function(){ return ( <div> <p> <button value="company" onClick={this.props.selectType} type="submit" className="pure-button pure-button-primary"> <i className="fa fa-building" aria-hidden="true"> </i> Company ? </button> </p> <p> <button value="courier" onClick={this.props.selectType} type="submit" className="pure-button pure-button-primary"> <i className="fa fa-bicycle" aria-hidden="true"> </i> Courier ? </button> </p> </div> ) } }); module.exports = ButtonFilter;<file_sep>/rails_foodshare/test/models/job_test.rb require 'test_helper' class JobTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "has an item description" do assert_equal("Carrots", jobs(:one).item) end test "has a quantity" do assert_equal(4, jobs(:one).quantity) end # check about setting fields # test "can set quantity" do # jobs(:two).setQuantity(3) # assert_equal(3, jobs(:two).getQuantity) # end test "has instructions" do assert_equal("Open until 10:00pm. Available for pick-up 6pm-8pm", jobs(:one).instructions) end test "has a company" do assert_equal(companies(:one), jobs(:one).company) end test "can get own and unclaimed jobs for a courier" do assert_equal( [jobs(:one), jobs(:three)].sort, Job.jobs_for_user(users(:one)).sort ) end test "can get own jobs for a company" do assert_equal( [jobs(:one), jobs(:two)].sort, Job.jobs_for_user(users(:two)).sort ) end # test "getCompany method brings back company details" do # assert_equal({ # name: "Sodeberg", # position: { # lat: 1.0232, # lng: -0.4567 # }, # contact_details: { # email: "<EMAIL>", # phone: "0131 332 1111", # address1: "3 WestEnd Place", # address2: "West End", # address3: "Edinburgh", # postcode: "EH3 1RT" # } # }, jobs(:one).getCompanyDetails) # end test "can return a hash with info for courier view" do expected = { id: 1, item: "Carrots", quantity: 4, instructions: "Open until 10:00pm. Available for pick-up 6pm-8pm", from_date: "2016-05-22", to_date: "2016-05-22", category: "Supply", courier_id: 1, company: { name: "Sodeberg", position: { lat: 1.0232, lng: -0.4567 }, contactDetails: { email: "<EMAIL>", phone: "0131 332 1111", address1: "3 WestEnd Place", address2: "West End", address3: "Edinburgh", postcode: "EH3 1RT" } }, completed_date: nil } assert_equal( expected, jobs(:one).to_hash_for_courier ) end test "can return a hash with info for company view" do expected = { id: 1, item: "Carrots", quantity: 4, instructions: "Open until 10:00pm. Available for pick-up 6pm-8pm", from_date: "2016-05-22", to_date: "2016-05-22", category: "Supply", courier: { first_name: "Jenny", last_name: "Bloggs", phone: "07712343455" }, completed_date: nil } assert_equal( expected, jobs(:one).to_hash_for_company ) end test "can assign a courier to an unclaimed job" do job = jobs(:three) # job with no courier_id courier = couriers(:one) job.assign_courier(courier) assert_equal(courier.id, job.courier_id) end end <file_sep>/rails_foodshare/db/migrate/20160522134019_create_jobs.rb class CreateJobs < ActiveRecord::Migration def change create_table :jobs do |t| t.references :company, index: true, foreign_key: true t.references :courier, index: true, foreign_key: true t.text :item t.integer :quantity t.text :instructions t.date :from_date t.date :to_date t.string :type t.timestamps null: false end end end <file_sep>/rails_foodshare/app/models/job.rb class Job < ActiveRecord::Base belongs_to :company belongs_to :courier # should this method be able to return a string with quantity + kg/g/ml/l? def self.jobs_for_user(user) jobs = Job.all.to_a jobs = jobs.select do |job| ( job.courier && (job.courier == user.courier) && job.completed_date.nil? || job.company && (job.company == user.company) || (!job.courier && user.courier) ) end end def to_hash_for_courier return { id: id, item: item, quantity: quantity, instructions: instructions, from_date: from_date.iso8601, to_date: to_date.iso8601, category: category, courier_id: courier_id, company: company ? company.to_hash : nil, completed_date: completed_date } end def to_hash_for_company return { id: id, item: item, quantity: quantity, instructions: instructions, from_date: from_date.iso8601, to_date: to_date.iso8601, category: category, courier: courier ? courier.to_hash : nil, completed_date: completed_date } end def assign_courier(courier) raise ArgumentError.new( 'Cannot assign courier to job: courier already assigned' ) if courier_id update(courier_id: courier.id) end def unassign_courier(courier) raise ArgumentError.new( 'Cannot unassign courier from job: assigned to different courier' ) if courier_id != courier.id update(courier_id: nil) end def complete(courier) raise ArgumentError.new( 'Cannot complete job: assigned to different courier' ) if courier_id != courier.id raise ArgumentError.new( 'Cannot complete job: already completed' ) if !completed_date.nil? update(completed_date: DateTime.now) end def uncomplete(courier) raise ArgumentError.new( 'Cannot uncomplete job: assigned to different courier' ) if courier_id != courier.id raise ArgumentError.new( 'Cannot uncomplete job: not completed yet' ) if completed_date.nil? update(completed_date: nil) end end <file_sep>/node_foodshare/client/src/components/authentication/SignOut.jsx var React = require('react'); var SignOut = React.createClass({ signOut:function(e){ e.preventDefault(); var request = new XMLHttpRequest(); request.open("DELETE", this.props.url); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.onload = function(){ if(request.status === 204){ this.props.onSignOut(null); }else if(request.status === 401){ } }.bind(this) request.send(null); }, render: function() { return ( <button className="pure-button pure-button-primary" onClick={this.signOut}> <i className="fa fa-sign-out" aria-hidden="true"> </i> Sign Out</button> ); } }); module.exports = SignOut;<file_sep>/node_foodshare/client/src/components/ShowAllJobs.jsx var React = require('react'); var CompanyView = require('./user_views/CompanyView'); var ShowAllJobs = React.createClass({ getInitialState: function(){ return{job: null} }, findJob: function(jobs, index){ var job = jobs[index]; return job; }, deleteJob: function(e){ var job = this.findJob(this.props.jobs, e.target.value); return this.props.onDeleteJob(job); }, handleEditClick: function(e) { this.props.changeView("editJobView") var job = this.findJob(this.props.jobs, e.target.value) this.props.onChooseJobForEdit(job); }, handleDeleteClick: function(e){ e.preventDefault(); var job = this.findJob(this.props.jobs, e.target.value); this.props.handleDeleteJob(job); }, render: function(){ var jobs = this.props.jobs.map(function(job, index){ return (<div key={index} jobIndex={index}> <li> {job.category} {job.item} {job.quantity} {job.instructions} {job.from_date} {job.to_date} </li> <button className="pure-button button-small" onClick={this.handleEditClick} value={index}>UPDATE</button> <button className="pure-button button-small" onClick={this.handleDeleteClick} value={index}>DELETE</button> </div> ) }.bind(this)) return( <div> <ul> {jobs} </ul> </div> ) } }); // {this.updateButton(job, index)} // {this.deleteButton(job, index)} module.exports = ShowAllJobs;<file_sep>/rails_foodshare/app/controllers/users_controller.rb class UsersController < ApplicationController before_action :authenticate_user! def index render json: current_user.to_json(include: [:company, :courier]) end end<file_sep>/node_foodshare/client/src/components/CompanyNavbar.jsx var React = require('react'); var CompanyNavbar = React.createClass({ signOut:function(e){ e.preventDefault(); var request = new XMLHttpRequest(); request.open("DELETE", this.props.url + "users/sign_out.json"); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.onload = function(){ if(request.status === 204){ this.props.onSignOut(null); }else if(request.status === 401){ } }.bind(this) request.send(null); }, toggleClassNames: function() { /* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */ document.getElementsByClassName("topnav")[0].classList.toggle("responsive"); }, handleClick: function(e) { e.preventDefault(); this.props.changeView(e.target.value); this.toggleClassNames(); }, render: function() { return ( <div> <ul className="topnav"> <li id="navbar-scranshare">ScranShare</li> <li><a onClick={this.handleClick} value="foodForm">Food Form</a></li> <li><a onClick={this.handleClick} value="donations">Donations</a></li> <li><a onClick={this.signOut}>Sign Out</a></li> <li className="icon"> <a onClick={this.toggleClassNames}>&#9776;</a> </li> </ul> </div> ) } }); module.exports = CompanyNavbar; <file_sep>/node_foodshare/client/src/components/InfoButton.jsx var React = require('react'); var JobList = require('./JobList'); var Address = require('./Address'); var InfoButton = React.createClass({ handleCloseClick:function(){ return this.props.onCloseClick(); }, displayJobDetails: function(jobs){ if(jobs.length > 1){ this.displayMultipleJobs(jobs) } else { this.displayOneJob(jobs) } }, captureJobCompany: function(jobs){ var company = jobs[0].company if(jobs.length == 1){ return company } else { for( var i = 1; i < jobs.length; i++){ if (company.name == jobs[i].company.name){ console.log(company) return company } else { return false } } } }, selectJobs: function(){ var filteredJobs = []; this.props.jobs.forEach(function(job){ if (job.company.position.lat == this.props.jobIndices.lat){ // console.log("reached here") filteredJobs.push(job); } // return jobIndices; }.bind(this)) // var jobs = []; // for (var index of this.props.jobIndices) { // jobs.push(this.props.jobs[index]); // } return filteredJobs; }, // {this.displayJobDetails(this.props.job)} render:function(){ // var clickInfoWindow = function(){ // console.log(4+2); // }; var selectedJobs = this.selectJobs(); if (selectedJobs.length === 0) { return null; } return ( <div id = "my-info-window"> <button onClick = {this.handleCloseClick}>Close Window</button> <Address company={this.captureJobCompany(selectedJobs)}/> <JobList onTakeJob={this.props.onTakeJob} onCancelJob={this.props.onCancelJob} onCompleteJob={this.props.onCompleteJob} company= {this.captureJobCompany(selectedJobs)} jobs = {selectedJobs}/> </div> ) } }) module.exports = InfoButton;<file_sep>/rails_foodshare/app/models/courier.rb class Courier < ActiveRecord::Base has_many :jobs has_many :users def to_hash return { first_name: first_name, last_name: last_name, phone: phone } end end <file_sep>/node_foodshare/client/src/components/user_views/CompanyView.jsx var _ = require('lodash'); var React = require('react'); var SignOut = require('../authentication/SignOut.jsx'); var JobForm = require('./JobForm.jsx'); var CompanyNavbar = require('../CompanyNavbar.jsx') var ShowAllJobs = require('../ShowAllJobs.jsx') var JobList = require('../JobList.jsx') var EditJobForm = require('./EditJobForm.jsx') var FormSuccessPage = require('../FormSuccessPage.jsx') // var DatePicker = require('../DatePicker.jsx') var CompanyView = React.createClass({ getInitialState: function() { return {currentView: "donations", selectedJobForEdit: {}} }, changeView: function(view) { this.setState({currentView: view}); }, handleDeleteJob:function(job){ var updatedJobs = this.props.jobs; updatedJobs = _.without(updatedJobs, job); this.props.forceUpdateState({jobs: updatedJobs}); var updateUrl = this.props.url + "jobs/" + job.id; var object= "" var request = new XMLHttpRequest(); request.open("DELETE", updateUrl, true ); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.send(JSON.stringify(object)) }, handleChooseJobForEdit: function(job){ this.setState({selectedJobForEdit: job}) }, handleUpdateJob:function(job){ var updateUrl = this.props.url + "jobs/" + job.id; var request = new XMLHttpRequest(); request.open("PUT", updateUrl, true); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.onload = function(){ if(request.status === 200) { this.setState({currentView: "updateSuccess"}); } }.bind(this); request.send(JSON.stringify(job)) }, render: function() { var toDisplay; switch(this.state.currentView) { case "foodForm": toDisplay = <JobForm url={this.props.url}/> break; case "donations": toDisplay = <ShowAllJobs jobs={this.props.jobs} handleDeleteJob={this.handleDeleteJob} changeView={this.changeView} onChooseJobForEdit={this.handleChooseJobForEdit}>Donations</ShowAllJobs> break; case "editJobView": toDisplay = <EditJobForm job={this.state.selectedJobForEdit} onUpdate={this.handleUpdateJob}></EditJobForm> break; case "updateSuccess": toDisplay = <FormSuccessPage changeView={this.changeView}/> break; default: toDisplay = <div /> } return ( <div> <CompanyNavbar changeView={this.changeView} url={this.props.url} onSignOut={this.props.onSignOut}></CompanyNavbar> {toDisplay} </div> ) } }) module.exports = CompanyView;<file_sep>/rails_foodshare/db/migrate/20160522143529_add_new_fields_to_user_db_table.rb class AddNewFieldsToUserDbTable < ActiveRecord::Migration def change add_reference :users, :company add_reference :users, :courier end end <file_sep>/rails_foodshare/db/migrate/20160522082720_create_companies.rb class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.text :name t.text :email t.text :phone t.text :address1 t.text :address2 t.text :address3 t.text :postcode t.integer :lat t.integer :lng t.timestamps null: false end end end <file_sep>/README.md # ScranShare ScranShare helps reduce food waste by connecting organisations that produce surplus food (cafes, restaurants, shops), organisations that need food (charities, food banks), and volunteers who donate their time to transporting food between them. Companies and charities can log in and register where and when they have or need food. Volunteers can log in and see when and where they're needed on a map. ## Background This application was developed as a group project at [CodeClan](http://codeclan.com/). We are hoping to work with a local volunteer organisation to continue developing the application, with the aim of deploying it for their use in the future. ## Technology The app uses Ruby on Rails to create a RESTful JSON API, using an ORM (ActiveRecord) and Devise for authentication. The front end is a single-page JavaScript app built in React, and uses the Google Maps API. <file_sep>/rails_foodshare/db/migrate/20160523121726_remove_accepted_column_from_jobs.rb class RemoveAcceptedColumnFromJobs < ActiveRecord::Migration def change remove_column :jobs, :accepted end end <file_sep>/rails_foodshare/app/controllers/jobs_controller.rb class JobsController < ApplicationController before_action :authenticate_user! def index jobs = Job.jobs_for_user(current_user) if current_user.courier jobs = jobs.map do |job| job.to_hash_for_courier end elsif current_user.company jobs = jobs.map do |job| job.to_hash_for_company end end render json: jobs end def create if !current_user.company render :nothing => true, :status => :forbidden else begin job = Job.create(job_params) job.update(company_id: current_user.company_id) render json: job.to_hash_for_company rescue ArgumentError render text: "Invalid date", status: :bad_request end end end def update if current_user.company_id update_by_company elsif current_user.courier_id update_by_courier else render nothing: true, status: :forbidden end end def update_by_company id = params[:id].to_i job = Job.find(id) if job.company_id != current_user.company_id render nothing: true, status: :forbidden else job.update(job_params) render json: job.to_hash_for_company end end def update_by_courier id = params[:id].to_i job = Job.find(id) courier = current_user.courier accepted = params[:accepted] completed = params[:completed] begin if (!accepted.nil? && !completed.nil?) || (accepted.nil? && completed.nil?) raise ArgumentError.new( 'Please include either an "accepted" or a "completed" field (but not both).' ) end if !accepted.nil? job.assign_courier(courier) if accepted == true job.unassign_courier(courier) if accepted == false render json: job.to_hash_for_courier end if !completed.nil? job.complete(courier) if completed == true job.uncomplete(courier) if completed == false render json: job.to_hash_for_courier end rescue ArgumentError => e render text: e.message, status: :bad_request end end def destroy id = params[:id].to_i job = Job.find(id) if job.company_id != current_user.company_id render nothing: true, status: :forbidden else job.destroy render nothing: true, status: :ok end end private def job_params job_params = params.require(:job).permit(:item, :quantity, :instructions, :from_date, :to_date, :category) # This will raise ArgumentError if date is invalid Date.parse(job_params[:from_date]) if job_params[:from_date] Date.parse(job_params[:to_date]) if job_params[:to_date] return job_params end end<file_sep>/rails_foodshare/test/models/courier_test.rb require 'test_helper' class CourierTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "has first name" do assert_equal("Jenny", couriers(:one).first_name) end test "has last name" do assert_equal("Bloggs", couriers(:one).last_name) end test "has a phone number" do assert_equal("07712343455", couriers(:one).phone) end test "can return a hash with info" do assert_equal( { first_name: "Jenny", last_name: "Bloggs", phone: "07712343455" }, couriers(:one).to_hash ) end end <file_sep>/node_foodshare/client/src/components/authentication/SignUp.jsx var React = require('react'); var LinkedStateMixin = require('react-addons-linked-state-mixin'); var SignUp = React.createClass({ mixins: [LinkedStateMixin], getInitialState: function(){ return {email:"", password:"", passwordConfirmation:""}; }, signIn:function(e){ e.preventDefault(); var request = new XMLHttpRequest(); request.open("POST", this.props.url); request.setRequestHeader("Content-Type", "application/json"); request.withCredentials = true; request.onload = function(){ if(request.status === 201){ let user = JSON.parse(request.responseText) this.props.onSignUp(user); }else if(request.status === 401){ } }.bind(this) var data = { user:{ email:this.state.email, password:<PASSWORD>, password_confirmation: <PASSWORD> } } request.send(JSON.stringify(data)); }, render: function() { return ( <form onSubmit={this.signIn} className="pure-form pure-form-stacked"> <input type="text" valueLink={this.linkState('email')} placeholder="Email" /> <input type="password" valueLink={this.linkState('password')} placeholder="<PASSWORD>" /> <input type="password" valueLink={this.linkState('passwordConfirmation')} placeholder="<PASSWORD>" /> <button className="pure-button pure-button-primary" onClick={this.signIn}> Sign Up </button> </form> ); } }); module.exports = SignUp;<file_sep>/rails_foodshare/db/migrate/20160523105544_change_phone_number_column_to_string_in_couriers.rb class ChangePhoneNumberColumnToStringInCouriers < ActiveRecord::Migration def change change_column(:couriers, :phone, :text) end end <file_sep>/rails_foodshare/app/models/company.rb class Company < ActiveRecord::Base has_many :jobs has_many :users def position return {lat: lat, lng: lng} end def to_hash return { name: name, position: position, contactDetails: { email: email, phone: phone, address1: address1, address2: address2, address3: address3, postcode: postcode } } end end
1c4a3d9a9d9581199e92d1c7b5701e5b9aa88731
[ "JavaScript", "Ruby", "Markdown" ]
29
Ruby
singhprd/Project4
81cf0a63d2d3370f80998338306447dd09b8a284
1b89234bd5e6c049d3ba91681c8d2afefe6cfe8a
refs/heads/master
<repo_name>Team-Floppy-Floppy-Sea-Spider/LocalHost3000<file_sep>/README.md # LocalHost3000 Team Floppy Floppy Sea Spider - LocalHost3000 Iteration. <file_sep>/server/server.js const express = require('express'); const path = require('path'); // server and PORT const app = express(); const PORT = 3000; const server = app.listen(PORT, () => { console.log(`listening on ${PORT}`); }); // express Router ----------------------------------- const apiRouter = require('./routes/apiRouter.js'); /* GLOBAL HANDLERS */ app.use(express.json()); app.use(express.urlencoded({ extended: true })); /* ROUTES */ app.use('/api', apiRouter); app.use('/build', express.static(path.join(__dirname, '../build'))); // serve index.html on the route '/' app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../index.html')); }); // catch-all route handler for any requests to an unknown route // This catches any unknown routes. app.use((req, res) => { console.log("Unknown route. Try another route."); return res.status(404); }); //express error handler app.use((err, req, res, next) => { const defaultErr = { log: 'catchall error handler from serverjs', status: 400, message: { err: 'An error occurred' }, }; const errorObj = Object.assign({}, defaultErr, err); console.log(errorObj/*.log*/); console.log("X".repeat(40), "err.error", err); return res.status(errorObj.status).json(errorObj.message); }); <file_sep>/client/component/Profile.jsx import React, { Component } from "react"; import { withRouter } from "react-router-dom"; import "../styles/profile.scss"; class Profile extends Component { constructor() { super(); this.state = {}; } // function renderProfile() { if (this.props.signedIn && !this.props.inEditMode) { return ( <div> <ul className="profileAttrContainer"> <li className="profileAttr"> Username: {this.props.currentUser.username} </li> <li className="profileAttr"> Email: <a href={`mailto:${this.props.currentUser.email}`} target="_blank" rel="noopener noreferrer" > {this.props.currentUser.email} </a> </li> <li className="profileAttr">Home: {this.props.currentUser.home}</li> <li className="profileAttr">Type: {this.props.currentUser.type}</li> </ul> <button className="profileButton" id="edit-profile-button" onClick={this.props.editProfile} > Edit Profile </button> <button className="profileButton" id="delete-profile-button" onClick={this.props.deleteProfile} > Delete Profile </button> </div> ); } if (this.props.signedIn && this.props.inEditMode) { return ( <div> <form className="entire-profile-form" onSubmit={this.props.saveProfile} > Username: <input className="edit-profile-input" name="username" value={this.props.currentUser.username} placeholder="Username" onChange={this.props.editingProfile} ></input> <p>Email:</p> <input className="edit-profile-input" name="email" value={this.props.currentUser.email} placeholder="Email" onChange={this.props.editingProfile} ></input> <p>Home:</p> <input className="edit-profile-input" name="home" placeholder="Home" value={this.props.currentUser.home} onChange={this.props.editingProfile} ></input> <select defaultValue={this.props.currentUser.type} onChange={this.props.handleSelect} > <option value="Traveler">Traveler</option> <option value="Local">Local</option> </select> <button className="profileButton" type="submit"> Save Profile </button> </form> </div> ); } } render() { //(if not in edit mode) return ( <div> {/* {this.props.signedIn && !this.props.inEditMode ? ( <div> <ul> <li>Username: {this.props.currentUser.username}</li> <li>Email: {this.props.currentUser.email}</li> <li>Home: {this.props.currentUser.home}</li> </ul> <button onClick={this.props.editProfile}>Edit Profile</button> </div> ) : this.props.signedIn && this.props.inEditMode ? ( <div> <form onSubmit={this.props.editProfile}> Username: <input name='username' value={this.props.currentUser.username} onChange={this.props.editingProfile} ></input> Email: <input name='email' value={this.props.currentUser.email} onChange={this.props.editingProfile} ></input> Home: <input name='home' value={this.props.currentUser.home} onChange={this.props.editingProfile} ></input> <button type='submit'>Confirm Profile</button> </form> </div> ) : null} */} {this.renderProfile()} </div> ); } } export default Profile; <file_sep>/server/Controllers/userController.js const db = require('../models/userInfoModels'); const userController = {}; const bcrypt = require('bcrypt'); const saltRounds = 10; // The model represents any data that may be seen / used / processed, such as data from a database (more on this later!) // The view represents the application’s UI which renders the data from the model in a user-friendly interface // The controller represents the connection between the model and the view, handling any processing of information back and forth /* Controllers Needed: 1. CreateUser (Register) 2. Login 3. Edit Profile 4. Delete Profile 5. Search */ /* CREATE TABLE user_info ( id SERIAL PRIMARY KEY, username varchar(255), password varchar(255), name varchar(255), home varchar(255), email varchar(255), type varchar(255) ) ; dummy instance: {"username": "test", "password": "<PASSWORD>", "name": "t1", "home": "home1", "email": "<EMAIL>", "type": "traveler" } */ /* password Hasher */ userController.passwordHasher = (req, res, next) => { let userInfo = req.body; const { password } = userInfo; bcrypt.genSalt(10, (err, salt) => { if (err) { console.log('err at genSalt'); return next(err); } bcrypt.hash(password, salt, (error, hash) => { // Store hash in your password DB. if (error) { console.log('err at userController.passwordHasher'); return next(err); } userInfo = { ...userInfo, password: hash, }; res.locals.userInfo = userInfo; return next(); }); }); }; /* Register Controller */ userController.createUser = (req, res, next) => { const { userInfo } = res.locals; console.log("V".repeat(40), "usercontroler.createuser", "req.body\n", req.body); console.log("userinfo:\n", userInfo); // const createUserQuery = `INSERT INTO user_info (username, password, name, home, email, type) // WHERE ($1, $2, $3, $4, $5, $6) // WHERE NOT EXISTS (SELECT username, password, name, home, email, type FROM user_info WHERE username = $1 OR email = $5) // RETURNING username, password, name, home, email, type;`; // const query = `INSERT INTO user_info (username, password, name, home, email, type) // SELECT '${req.body.username}', '${req.body.password}', '${req.body.name}', '${req.body.home}', '${req.body.email}', '${req.body.type}' // WHERE NOT EXISTS (SELECT username, password, name, home, email, type FROM user_info WHERE username='${req.body.username}' OR email='${req.body.email}') // RETURNING username, password, name, home, email, type;`; // const userInfo = req.body; // const fieldValues = [userInfo.username, userInfo.password, userInfo.name, userInfo.home, userInfo.email, userInfo.type]; const query = `INSERT INTO user_info (username, password, name, home, email, type) SELECT '${userInfo.username}', '${userInfo.password}', '${userInfo.name}', '${userInfo.home}', '${userInfo.email}', '${userInfo.type}' WHERE NOT EXISTS (SELECT username, password, name, home, email, type FROM user_info WHERE username='${userInfo.username}' OR email='${userInfo.email}') RETURNING username, password, name, home, email, type;`; db.query(query) .then(data => { if (data.rows.length > 0) { res.locals.user = data.rows[0]; res.locals.userInfo = userInfo; return next(); } else (next({ log: 'Username and/or email already exists.', status: 400, message: { err: 'Username and/or email already exists.' } })).catch(err => { console.log("Error in userController.createUser: ", err); return next(err); }) }); // db.query(query).then(data => { // if (data.rows.length > 0) { // res.locals.user = data.rows[0]; // return next(); // } else (next({ // log: 'Username and/or email already exists.', // status: 400, // message: { // err: 'Username and/or email already exists.' // } // })).catch(err => { // console.log("Error in userController.createUser: ", err); // return next(err); // }) // }); }; // this is the closing bracket for createUser /* /Users Controller */ userController.findUsers = (req, res, next) => { // console.log("req.params: ", req.params); // console.log("req: ", req.params.home); const query = `SELECT * FROM user_info WHERE home='${req.params.home}' AND type='Local';`; db.query(query).then(data => { if (data.rows.length > 0) { res.locals.searchResults = data.rows; return next() } else next({ log: 'No one matched your results', status: 400, message: { err: 'No one matched your results.' } }) }) } /* Login Controller */ userController.login = (req, res, next) => { const user = req.body; // const { userInfo } = res.locals; // gotta do check if username exists // const query = `SELECT * FROM user_info WHERE username='${user.username}' AND password='${user.<PASSWORD>}';`; const query = `SELECT * FROM user_info WHERE username = '${user.username}';`; // need to use $placeholder in the parameter db.query(query).then(data => { if (data.rows.length > 0) { // run bcrypt.compare? bcrypt.compare(user.password, data.rows[0].password) .then((result) => { // either send data.rows[0] or error in psswd // result === true // possibly Zi has idea without conditional? if (result === true) { res.locals.user = data.rows[0]; return next(); } // user -level error - psswd verif. fail res.json({"password_verified": 0}); }); } else (next({ log: 'user does not exist', status: 400, message: { err: 'user does not exist', } })) }).catch(err => { console.log("Error in userController.createUser: ", err); return next(err); }) //res -> would be every column (data) from that user. } /* Profile Controllers */ userController.getProfile = (req, res, next) => { console.log("Inside userController.getProfile."); const query = `SELECT * FROM user_info WHERE id='${req.params.id}';`; db.query(query).then(data => { res.locals.user = data.rows; return next() }).catch(err => { console.log("Error in userController.getProfile: ", err); return next(err); }) } userController.deleteProfile = (req, res, next) => { console.log("Inside userController.deleteProfile.") const query = `DELETE FROM user_info WHERE id='${req.params.id}';`; db.query(query).then(data => { console.log("Deleting User's information"); return next(); }).catch(err => { console.log("Error in userController.getProfile: ", err); return next(err); }) } userController.updateProfile = (req, res, next) => { console.log("Inside userController.updateProfile") const query = `UPDATE user_info SET username='${req.body.username}', password='<PASSWORD>}', name='${req.body.name}', home='${req.body.home}', email='${req.body.email}', type='${req.body.type}', profilepic='${req.body.profilepic}' WHERE id='${req.params.id}' returning *` db.query(query).then(data => { console.log("Updating User's information"); console.log(data.rows); res.locals.user = data.rows[0]; return next(); }).catch(err => { console.log("Error in userController.updateProfile: ", err); return next(err); }) } // const allKeys = Object.keys(req.body); // const allValues = Object.values(req.body); // //Used a for loop to iterate any changes to the profile and up date them one at a time. // for (let i = 0; i < allKeys.length; i++) { // let query = `UPDATE user_info SET ${allKeys[i]} = '${allValues[i]}' WHERE id='${req.params.id}'` // db.query(query).then(data => { // res.locals.user = data.rows; // return next() // }).catch(err => { // console.log("Error in userController.updateProfile", err); // return next(err) // }) // } module.exports = userController;
5b6d94cb2633d4ac9e836a02a50769acf7b3efd0
[ "Markdown", "JavaScript" ]
4
Markdown
Team-Floppy-Floppy-Sea-Spider/LocalHost3000
6c4be6baa56bb9cac47405ccdd58f5ce92fb370a
af72c2a9f006e2663740ce1a79b8b55652be2487
refs/heads/master
<file_sep># HPDF-ReactNative-TwitterClone HPDF Task 1 : Twitter Clone App using React Native ## DEMO App (Android) ![DEMO](https://user-images.githubusercontent.com/17771352/34328945-cee861f0-e914-11e7-8eb2-405306e1fb51.gif) ## Install at local ### Open Terminal, then type command: `git clone https://github.com/saumeya/HPDF-ReactNative-TwitterClone.git` ### Go to project folder : `cd HPDF-ReactNative-TwitterClone` ### Type following command : `npm install` ### To run on Android : `react-native run-android` ### To run on iOS : `react-native run-ios` <file_sep>rootProject.name = 'TaskTwitter' include ':app' <file_sep>import React, { Component } from 'react'; import { Image, View } from 'react-native'; import { Container, Header, Content,Item, Input, Icon, Button, Text, Left, Thumbnail, Body, Right,Card,CardItem,Fab } from 'native-base'; export default class Searching extends Component { render() { return ( <Container> <Header style={{backgroundColor:'white'}} searchBar rounded> <Left style={{flex:0.15}}> <Button transparent onPress={() => this.props.navigation.navigate("Home")}> <Icon style={{ color : 'deepskyblue' }} name='arrow-back' ></Icon> </Button> </Left> <Body style={{flex:0.75}}> <Item style={{height:40 , marginLeft:0}}> <Input placeholder="Search Twitter" /> </Item> </Body> </Header> </Container> ); } } <file_sep>import React, { Component } from "react"; import HomeScreen from "./HomeScreen.js"; import SearchScreen from "./SearchScreen.js"; import Notification from "./Notification.js"; import Message from "./Message.js"; import Sample from "./Sample.js"; import Searching from "./Searching.js"; import HomeHeader from "./HomeHeader.js"; import SearchHeader from "./SearchHeader.js"; import MsgHeader from "./MsgHeader.js"; import NotiHeader from "./NotiHeader.js"; import { Button, Text, Icon, Footer, FooterTab } from "native-base"; import SideBar from "./SideBar.js"; import { TabNavigator, StackNavigator, DrawerNavigator } from "react-navigation"; const Tab1 = StackNavigator({ Home: { screen: HomeScreen, navigationOptions: { header: props => <HomeHeader {...props} /> } }, }, { headerMode: 'none', }); const Tab2 = StackNavigator({ Search: { screen: SearchScreen, navigationOptions: { header: props => <SearchHeader {...props} /> } }, }, { headerMode: 'none', }); const Tab3 = StackNavigator({ Notification: { screen: Notification, navigationOptions: { header: props => <NotiHeader {...props} /> } }, }, { headerMode: 'none', }); const Tab4 = StackNavigator({ Message: { screen: Message, navigationOptions: { header: props => < MsgHeader {...props} /> } }, }, { headerMode: 'none', }); const TabBar = TabNavigator({ Home: { screen: Tab1 , navigationOptions: { tabBarLabel: '', tabBarIcon: ({ tintColor }) => <Icon name='home' style={{ color: tintColor }} /> , }, }, Search: { screen: Tab2, navigationOptions: { tabBarLabel: '', tabBarIcon: ({ tintColor }) => <Icon name='search' style={{ color: tintColor }} /> , }, }, Notification: { screen: Tab3 , navigationOptions: { tabBarLabel: '', tabBarIcon: ({ tintColor }) => <Icon name='notifications' style={{ color: tintColor }} /> , }, }, Message: { screen: Tab4 , navigationOptions: { tabBarLabel: '', tabBarIcon: ({ tintColor }) => <Icon name='mail' style={{ color: tintColor }} /> , }, }, }, { tabBarPosition: 'top', animationEnabled: true, tabBarOptions: { activeTintColor: 'deepskyblue', inactiveTintColor: 'grey', activeBackgroundColor: "#fff", inactiveBackgroundColor: "#fff", showIcon: true, showLabel: false, indicatorStyle: { borderBottomColor: 'deepskyblue', borderBottomWidth: 2, }, style: { backgroundColor: '#fff', // Makes Android tab bar white instead of standard blue } } }, ); const AppNavigate = StackNavigator({ Home: { screen: TabBar}, }); const HomeScreenRouter = DrawerNavigator( { Home: { screen: AppNavigate }, Search: {screen: SearchScreen}, Notification: {screen: Notification}, Message: {screen: Message}, Sample: {screen: Sample}, Searching: {screen: Searching}, }, { contentComponent: props => <SideBar {...props} /> } ); export default HomeScreenRouter; <file_sep>import React, { Component } from 'react'; import { Image, View } from 'react-native'; import { Container, Header, Content,Item, Input, Icon, Button, Text, Left, Thumbnail, Body, Right,Card,CardItem,Fab } from 'native-base'; export default class SearchBarExample extends Component { render() { return ( <Container> <Fab style={{ backgroundColor: 'deepskyblue' }} position="bottomRight" > <Icon name="create" /> </Fab> <Content> <Card transparent> <CardItem> <Text style = {{color:"black", fontWeight: 'bold'}}>Westeros Trends{"\n"}</Text> </CardItem> <View style={{ borderBottomColor: 'lightgrey', borderBottomWidth: 1, }} /> <CardItem> <View style={{flexDirection: 'row'}}> <View style={{flex : 0.20}}> <Text style={{fontSize:25}}>1</Text> </View> <View style={{flex : 0.80}}> <Text style = {{fontSize : 18}}>Dragon Queen</Text> </View> </View> </CardItem> <View style={{ borderBottomColor: 'lightgrey', borderBottomWidth: 1, }} /> <CardItem> <View style={{flexDirection: 'row'}}> <View style={{flex : 0.20}}> <Text style={{fontSize:25}}>2</Text> </View> <View style={{flex : 0.80}}> <Text style = {{fontSize : 18}}>#whitewalkers</Text> <Text style = {{fontSize : 15, color: 'grey'}}>1860 Tweets</Text> </View> </View> </CardItem> <View style={{ borderBottomColor: 'lightgrey', borderBottomWidth: 1, }} /> <CardItem> <View style={{flexDirection: 'row'}}> <View style={{flex : 0.20}}> <Text style={{fontSize:25}}>3</Text> </View> <View style={{flex : 0.80}}> <Text style = {{fontSize : 18}}>#aryastark</Text> <Text style = {{fontSize : 15, color: 'grey'}}>1560 Tweets</Text> </View> </View> </CardItem> <View style={{ borderBottomColor: 'lightgrey', borderBottomWidth: 1, }} /> <CardItem> <View style={{flexDirection: 'row'}}> <View style={{flex : 0.20}}> <Text style={{fontSize:25}}>4</Text> </View> <View style={{flex : 0.80}}> <Text style = {{fontSize : 18}}>#dragonsss</Text> <Text style = {{fontSize : 15, color: 'grey'}}>1855 Tweets</Text> </View> </View> </CardItem> <View style={{ borderBottomColor: 'lightgrey', borderBottomWidth: 1, }} /> <CardItem> <Text style = {{fontSize : 18, color : 'deepskyblue'}}>Show more</Text> </CardItem> </Card> </Content> </Container> ); } } <file_sep>import React from "react"; import { StatusBar } from "react-native"; import { Image, View } from 'react-native'; import { Container, Header, Title, Left, Icon, Right,Thumbnail, Button, Body, Content,Text, Card, CardItem,Fab,Footer,FooterTab } from "native-base"; export default class HomeScreen extends React.Component { render() { return ( <Header style={{backgroundColor:'white' , elevation:0}}> <Left> <Button transparent onPress={() => this.props.navigation.navigate("DrawerOpen")}> <Thumbnail small source={require('../../img/petyr.jpg')} /> </Button> </Left> <Body> <Title style={{color: 'black'}}>Notifications</Title> </Body> <Right /> </Header> ); } }
40765eeac93c1516fb2f9d60ceccec794c47c78e
[ "Markdown", "JavaScript", "Gradle" ]
6
Markdown
saumeya/HPDF-ReactNative-TwitterClone
ff6b0e1bbf576cdda34ebc8b84371677479a7704
4d50e379e97e6dd5f379e08e03406516e5c902d2
refs/heads/main
<file_sep># eap-amq-broker App with a MDB and a Servlet connecting to remote queues <file_sep>REQUEST_SEND=${eap-amq-broker.request.send} REQUEST_SEND_REQUEST_MESSAGE_FOR_MDB=${eap-amq-broker.request.send.request.message.for.mdb} REQUEST_SEND_REQUEST_MESSAGE_FOR_MDB_AND_KILL_SERVER=${eap-amq-broker.request.send.request.message.for.mdb.and.kill.server} REQUEST_CONSUME_MESSAGE=${eap-amq-broker.request.consume.message} REQUEST_CONSUME_REPLY_MESSAGE_FOR_MDB=${eap-amq-broker.request.consume.reply.message.for.mdb} REQUEST_CONSUME_ALL_REPLY_MESSAGES_FOR_MDB=${eap-amq-broker.request.consume.all.reply.messages.for.mdb} QUEUE_SEND_RESPONSE=${eap-amq-broker.queue.send.response} QUEUE_TEXT_MESSAGE=${eap-amq-broker.queue.text.message} QUEUE_MDB_SEND_RESPONSE=${eap-amq-broker.queue.mdb.send.response} QUEUE_MDB_TEXT_MESSAGE=${eap-amq-broker.queue.mdb.text.message} QUEUE_MDB_TEXT_REPLY_MESSAGE=${eap-amq-broker.queue.mdb.text.reply.message} <file_sep>package org.jboss.qa.appsint.tests.eapamq.ssl; public enum JmsTestProperties { REQUEST_SEND("send-message"), REQUEST_SEND_REQUEST_MESSAGE_FOR_MDB("send-request-message-for-mdb"), REQUEST_SEND_REQUEST_MESSAGE_FOR_MDB_AND_KILL_SERVER("send-request-message-for-mdb-and-kill-server"), REQUEST_CONSUME_MESSAGE("consume-message"), REQUEST_CONSUME_REPLY_MESSAGE_FOR_MDB("consume-reply-message-for-mdb"), REQUEST_CONSUME_ALL_REPLY_MESSAGES_FOR_MDB("consume-all-reply-messages-for-mdb"), QUEUE_SEND_RESPONSE("Sent a text message to "), QUEUE_TEXT_MESSAGE("Hello Servlet!"), QUEUE_MDB_SEND_RESPONSE("Sent a text message with to "), QUEUE_MDB_TEXT_MESSAGE("Hello MDB!"), QUEUE_MDB_TEXT_REPLY_MESSAGE("Hello MDB - reply message!"); private final String value; public String value() { return value; } JmsTestProperties(String value) { this.value = value; } }
f88f854c3a1b353e2e4c3f567e39e9f7ea3a51fd
[ "Markdown", "Java", "INI" ]
3
Markdown
tommaso-borgato/eap-amq-broker
736300292761bc580f16fb63675e488344d075a3
48c3c83e855c5e2abb43d95c5fb4c508f4636233
refs/heads/master
<repo_name>Kerry50407/SwiftCodingStyleSample<file_sep>/SwiftCodingStyleSample/ViewController/Search/SearchViewController.swift // // SearchViewController.swift // SwiftCodingStyleSample // // Created by <NAME> on 2022/1/3. // Copyright © 2022 <NAME>. All rights reserved. // import Foundation import UIKit class SearchViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } } <file_sep>/SwiftCodingStyleSample/View/BookTableViewCell.swift // // BookTableViewCell.swift // SwiftCodingStyleSample // // Created by <NAME> on 2019/6/24. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class BookTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! } <file_sep>/SwiftCodingStyleSample/Manager/BookManager.swift // // BookManager.swift // SwiftCodingStyleSample // // Created by <NAME> on 2019/6/24. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation // MARK: - Order 1: Protocol, Enum, Struct, class... for outter used protocol BookManagerDelegate: NSObject { func hasUpdated(bookList: [Book]) } // MARK: - Order 2: Class defination class BookManager { // MARK: - Order 5: Internal constants, variable static let shared = BookManager() weak var delegate: BookManagerDelegate? // MARK: - Order 6: Local constants, variable private var updateBookListTimer: Timer? private static let updateInterval = 10.0 private let BookList = [ [Book(title: "Thinking in JAVA", price: 750, isNewArrival: false), Book(title: "Effective in JAVA", price: 800, isNewArrival: false)], [Book(title: "Objective C tutorial", price: 500, isNewArrival: false), Book(title: "Master in Objective C", price: 900, isNewArrival: true)], [Book(title: "iOS 12 Programming in Beginners", price: 1200, isNewArrival: true), Book(title: "Swift in Depth", price: 1800, isNewArrival: true), Book(title: "Swift Game Development", price: 400, isNewArrival: true)]] ///// Function // MARK: - Order 7: Init / Deinit function(If it has) private init() { setup() } deinit { updateBookListTimer?.invalidate() updateBookListTimer = nil } // MARK: - Order 9: Fuction for intialization private func setup() { updateBookListTimer = Timer.scheduledTimer(withTimeInterval: BookManager.updateInterval, repeats: true, block: { [weak self] (timer) in guard let strongSelf = self else { return } let randomIndex = Int.random(in: 0 ..< 3) strongSelf.delegate?.hasUpdated(bookList: strongSelf.BookList[randomIndex]) }) } } // MARK: - Order 10: Group of specific outer function extension BookManager { func getBookList() -> [Book] { let randomIndex = Int.random(in: 0 ..< 3) return BookList[randomIndex] } func invalidateBookListTimer() { updateBookListTimer?.invalidate() updateBookListTimer = nil } } <file_sep>/SwiftCodingStyleSample/ViewController/Book/BookDetailViewController.swift // // BookDetailViewController.swift // SwiftCodingStyleSample // // Created by <NAME> on 2019/6/24. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit // MARK: - Order 2: Class defination class BookDetailViewController: UIViewController { // MARK: - Order 4: IBOutlet @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var isNewArrival: UILabel! // MARK: - Order 5: Internal constants, variable var book: Book? // MARK: - Order 8: Override function override func viewDidLoad() { super.viewDidLoad() setup() } // MARK: - Order 9: Fuction for intialization private func setup() { titleLabel.text = book?.title priceLabel.text = String(book?.price ?? 0) isNewArrival.text = "NewArrival: \(book?.isNewArrival ?? false)" } } <file_sep>/SwiftCodingStyleSample/Extension/String+Extension.swift // // String+Extension.swift // SwiftCodingStyleSample // // Created by <NAME> on 2022/1/3. // Copyright © 2022 <NAME>. All rights reserved. // import Foundation extension String { func base64Encoded() -> String? { return data(using: .utf8)?.base64EncodedString() } func base64Decoded() -> [UInt8]? { guard let data = Data(base64Encoded: self) else { return nil } return [UInt8](data) } } <file_sep>/SwiftCodingStyleSample/Utility/Constants.swift // // Constants.swift // SwiftCodingStyleSample // // Created by <NAME> on 2019/6/1. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation struct ViewControllerID { static let bookDetailViewController = "BookDetailViewController" } struct SegueID { static let segueToBookDetailViewController = "segueToBookDetailViewController" } struct CellID { static let bookTableViewCell = "BookTableViewCell" } struct Constants { static let welcomeTitle = "Hello World" static let welcomeMessage = "Welcome to Swift coding style sample" static let ok = "OK" } <file_sep>/SwiftCodingStyleSample/Model/Book.swift // // Book.swift // SwiftCodingStyleSample // // Created by <NAME> on 2019/6/24. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation struct Book { var title = "" var price = 0 var isNewArrival = false } <file_sep>/SwiftCodingStyleSample/ViewController/Book/CaculatorBookListViewController.swift // // CaculatorBookListViewController.swift // SwiftCodingStyleSample // // Created by <NAME> on 2019/6/24. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit // MARK: - Order 1: Protocol, Enum, Struct, class... for outter used protocol CaculatorBookListViewControllerDelegate { func doNothing() } // MARK: - Order 2: Class defination class CaculatorBookListViewController: UIViewController { /// Constants, variable // MARK: - Order 3: Protocol, Enum, Struct, class... for inner used private enum RowHeight: CGFloat { case sixty = 60.0 case eighty = 80.0 } // MARK: - Order 4: IBOutlet @IBOutlet weak var numberAddedTextField: UITextField! @IBOutlet weak var numberToBeAddedTextField: UITextField! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var calculateButton: UIButton! @IBOutlet weak var bookTableView: UITableView! // MARK: - Order 5: Internal constants, variable var someVariable: Int? // MARK: - Order 6: Local constants, variable private var bookList: [Book] = [] ///// Function // MARK: - Order 7: Init / Deinit function(If it has) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Init function } deinit { // Deinit function } // MARK: - Order 8: Override function override func viewDidLoad() { super.viewDidLoad() setup() setupTableView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SegueID.segueToBookDetailViewController, let bookDetail = segue.destination as? BookDetailViewController, let book = sender as? Book { bookDetail.book = book } } // MARK: - Order 9: Fuction for intialization private func setup() { BookManager.shared.delegate = self bookList = BookManager.shared.getBookList() } private func setupTableView() { bookTableView.dataSource = self bookTableView.delegate = self } } // MARK: - Order 10: Group of specific outer function extension CaculatorBookListViewController { func updateView() { } } // MARK: - Order 11: Group of specific inner function extension CaculatorBookListViewController { private func showWelcomeAlertSheet() { let welcomeAlertSheet = UIAlertController(title: Constants.welcomeTitle, message: Constants.welcomeMessage, preferredStyle: .alert) let okAction = UIAlertAction(title: Constants.ok, style: .default, handler: nil) welcomeAlertSheet.addAction(okAction) present(welcomeAlertSheet, animated: true, completion: nil) } private func handleOrientation() { } } // MARK: - Order 12: Protocol to extension - Native class extension CaculatorBookListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let bookCell = bookTableView.dequeueReusableCell(withIdentifier: CellID.bookTableViewCell, for: indexPath) as? BookTableViewCell { bookCell.titleLabel.text = bookList[indexPath.row].title return bookCell } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return RowHeight.sixty.rawValue } } extension CaculatorBookListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let book = bookList[indexPath.row] performSegue(withIdentifier: SegueID.segueToBookDetailViewController, sender: book) } } // MARK: - Order 13: Protocol to extension - Custom class extension CaculatorBookListViewController: BookManagerDelegate { func hasUpdated(bookList: [Book]) { self.bookList = bookList bookTableView.reloadData() } } // MARK: - Order 14: IBAction function extension CaculatorBookListViewController { @IBAction func alertButtonTouchUpInside(_ sender: UIBarButtonItem) { showWelcomeAlertSheet() } @IBAction func calculateButtonTouchUpInside(_ sender: UIButton) { let numberAdded = Double(numberAddedTextField.text ?? "") ?? 0.0 let numberToBeAdded = Double(numberToBeAddedTextField.text ?? "") ?? 0.0 resultLabel.text = String(numberAdded + numberToBeAdded) } @IBAction func clearButtonTouchUpInside(_ sender: UIButton) { numberAddedTextField.text = "" numberToBeAddedTextField.text = "" resultLabel.text = String(0) } } <file_sep>/SwiftCodingStyleSample/Utility/Utils.swift // // Utils.swift // SwiftCodingStyleSample // // Created by <NAME> on 2022/1/3. // Copyright © 2022 <NAME>. All rights reserved. // import UIKit class Utils { class func alert(from viewController: UIViewController, title: String?, message: String?) { DispatchQueue.main.async { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) viewController.present(alertController, animated: true, completion: nil) } } } <file_sep>/README.md # SwiftCodingStyleSample ## This sample demonstrate the order of a class * Order 1: Protocol, Enum, Struct, class... for outter used * Order 2: Class defination Constants, variable: * Order 3: Protocol, Enum, Struct, class... for inner used * Order 4: IBOutlet * Order 5: Internal constants, variable * Order 6: Local constants, variable Function: * Order 7: Init / Deinit function(If it has) * Order 8: Override function * Order 9: Fuction for intialization * Order 10: Group of specific outer function * Order 11: Group of specific inner function * Order 12: Protocol to extension - Native class * Order 13: Protocol to extension - Custom class * Order 14: IBAction function > Sameple in CaculatorBookListViewController.swift
7ea1099f40f286d23c1356ed2684442510414073
[ "Swift", "Markdown" ]
10
Swift
Kerry50407/SwiftCodingStyleSample
b8439a186922737ffd537006164e1cba11117193
0878ed6aff19b7742c158d3cbff423b169bbc335
refs/heads/main
<repo_name>SimeonYS/cdbt<file_sep>/README.md URL: https://www.cdbt.com/About-Us/Company/News Spider name: cdbt DB Schema: date title link content <file_sep>/main.py from scrapy import cmdline cmdline.execute("scrapy crawl cdbt".split())<file_sep>/cdbt/spiders/spider.py import re import scrapy from scrapy.loader import ItemLoader from ..items import CcdbtItem from itemloaders.processors import TakeFirst pattern = r'(\xa0)?' class CcdbtSpider(scrapy.Spider): name = 'cdbt' start_urls = ['https://www.cdbt.com/About-Us/Company/News'] def parse(self, response): post_links = response.xpath('//h3/a/@href').getall() yield from response.follow_all(post_links, self.parse_post) def parse_post(self, response): date = response.xpath('(//div[@class="Normal"])[1]/p/text()').get() try: date = re.findall(r'\w+\s\d+\,\s\d+', date) except TypeError: date = "" title = response.xpath('//h1/text()').get() content = response.xpath('//div[@class="Normal"]//text()[not (ancestor::div[@class="sidebarHIDE"] or ancestor::div[@class="container topFooterpadding"])]').getall() content = [p.strip() for p in content if p.strip()] content = re.sub(pattern, "",' '.join(content)) item = ItemLoader(item=CcdbtItem(), response=response) item.default_output_processor = TakeFirst() item.add_value('title', title) item.add_value('link', response.url) item.add_value('content', content) item.add_value('date', date) yield item.load_item()
77d388998b73114da265ba1e7c9e64bf0f557836
[ "Markdown", "Python" ]
3
Markdown
SimeonYS/cdbt
f02ea0822a760d45e270779c3264dc687f24f7e6
ea57bf47a4e4635ad5efd3d25363029a20228596
refs/heads/main
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Intervention\Image\Facades\Image; use Illuminate\Support\Facades\Storage; class Recortar extends Controller { public function subirImagen(Request $request) { $mediaQuery = [ ['1920','1080'], ['1280','720'], ['854','480'], ['640','360'], ]; foreach($request->file('imagen') as $imagen){ foreach($mediaQuery as $mq){ $img = Image::make($imagen)->resize($mq[0], $mq[1]); //$nombreOriginal = $request->imagen->getCLientOriginalName(); con extension incluida $nombreOriginal = $imagen->getCLientOriginalName(); $NombreSinExtension = pathinfo($nombreOriginal, PATHINFO_FILENAME); Storage::disk('local')->put('public/'.$mq[1].'/'.$NombreSinExtension.'.webp', $img->save($imagen,100,'webp')); } } return back()->with('success','imagenes guardadas con exito'); } } <file_sep><?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\Recortar; Route::get('/', function () { return view('welcome'); }); Route::POST('subirImagen',[Recortar::class,'subirImagen'])->name('subirImagen.recortar');
33ab9928d79257f0055bcedd653cd947e20cd225
[ "PHP" ]
2
PHP
nahuelDev23/recortarImagenesLaravel
fbed81a39270c1895f80d30bd268347b9fe4875d
0ab14ff656eb2072c95a2aecd9c711a7e24cc6d6
refs/heads/master
<file_sep>class Ad < ApplicationRecord validates :title, :desc, :tel, :name, presence: true end <file_sep>Simple project on rails. User can add new advert and reading exists. Admin after login can edit and delete advert. <file_sep>class SessionsController < ApplicationController skip_before_action :authorize def new end def create user = User.find_by(email: params[:email]) if user and user.authenticate(params[:password]) session[:user_id] = user.id redirect_to admin_url, notice: "Zalogowałeś się poprawnie." else redirect_to login_url, alert: "Złe hasło lub/i adres e-mail." end end def destroy session[:user_id] = nil redirect_to ads_url, notice: "Zostałeś poprawnie wylogowany" end end
a96cee2d7969cb5a1f204098a9919163f736f3f6
[ "Markdown", "Ruby" ]
3
Ruby
rszklar/ProjectRails
e1b3fbe9bf6991127e8301ba65b3e52cd1470737
a3d1a081b7cf3ef4ef463e70193da53394c59fb1
refs/heads/master
<file_sep>namespace FileStore.Models { public class AppSettings { public string FileStoragePath { get; set; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; namespace FileStore.Database.Models { public class UploadedFile { [Key] public Guid Id { get; set; } public DateTime UploadedAt { get; set; } public long Size { get; set; } public string StoragePath { get; set; } public string FileName { get; set; } public string ContentType { get; set; } public string Description { get; set; } } } <file_sep>using FileStore.Database.Models; using Microsoft.EntityFrameworkCore; namespace FileStore.Database { public class FileDbContext : DbContext { public DbSet<UploadedFile> UploadedFiles { get; set; } public DbSet<InitiatedFileUpload> InitiatedFileUploads { get; set; } public FileDbContext(DbContextOptions<FileDbContext> options) : base(options) { } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FileStore.Database.Models { public class InitiatedFileUpload { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public string FileName { get; set; } public string ContentType { get; set; } public string Description { get; set; } public bool FileUploaded { get; set; } } } <file_sep>using System; namespace FileStore.Models.ResponseResults { public class InitiatedFileUploadResult { public Guid GeneratedFileId { get; set; } } } <file_sep>using FileStore.Database; using FileStore.Database.Models; using FileStore.Models; using FileStore.Models.Request; using Microsoft.Extensions.Options; using System; using System.IO; using System.Threading.Tasks; namespace FileStore.Service { public class FileService { private FileDbContext dbContext; private AppSettings appSettings; public FileService(FileDbContext dbContext, IOptions<AppSettings> appSettings) { this.dbContext = dbContext; this.appSettings = appSettings.Value; } public async Task<InitiatedFileUpload> GetInitiatedFileUpload(Guid id) { return await dbContext.FindAsync<InitiatedFileUpload>(id); } public async Task<(bool success, UploadedFile uploadedFile)> SaveUploadedFileInfo(InitiatedFileUpload initiatedFileUpload, string storageFilePath, long fileSize) { try { var uploadedFile = new UploadedFile { Id = initiatedFileUpload.Id, FileName = initiatedFileUpload.FileName, ContentType = initiatedFileUpload.ContentType, Description = initiatedFileUpload.Description, StoragePath = storageFilePath, UploadedAt = DateTime.UtcNow, Size = fileSize }; initiatedFileUpload.FileUploaded = true; dbContext.Update(initiatedFileUpload); await dbContext.AddAsync(uploadedFile); await dbContext.SaveChangesAsync(); return (success: true, uploadedFile: uploadedFile); } catch (Exception) { return (success: false, uploadedFile: null); } } public async Task<(bool success, InitiatedFileUpload initiatedFileUpload)> SaveInitiatedFileMetadata(FileMetadata fileMetadata) { try { var contentType = fileMetadata.ContentType; if (string.IsNullOrEmpty(contentType)) contentType = "application/octet-stream"; var initiatedFileUpload = new InitiatedFileUpload { FileName = fileMetadata.FileName, ContentType = contentType, Description = fileMetadata.Description }; await dbContext.AddAsync(initiatedFileUpload); await dbContext.SaveChangesAsync(); return (success: true, initiatedFileUpload: initiatedFileUpload); } catch (Exception) { return (success: false, initiatedFileUpload: null); } } public async Task<(bool success, Stream fileStream, UploadedFile fileInfo)> GetUploadedFile(Guid id) { try { var uploadedFile = await dbContext.FindAsync<UploadedFile>(id); if (uploadedFile == null) return (success: false, fileStream: null, fileInfo: null); var fileStream = File.OpenRead(uploadedFile.StoragePath); return (success: true, fileStream: fileStream, fileInfo: uploadedFile); } catch (Exception) { return (success: false, fileStream: null, fileInfo: null); } } public async Task<(bool success, UploadedFile fileInfo)> GetFileMetadata(Guid id) { try { var storedFile = await dbContext.FindAsync<UploadedFile>(id); if (storedFile == null) return (success: false, fileInfo: null); return (success: true, fileInfo: storedFile); } catch (Exception) { return (success: false, fileInfo: null); } } public async Task<(string storagePath, long fileSize, bool success)> WriteFileDataToStorage(byte[] data, string fileName) { try { var fileStoragePath = Path.Combine(appSettings.FileStoragePath, $"{Guid.NewGuid()}_{fileName}"); using (var file = new FileStream(fileStoragePath, FileMode.CreateNew, FileAccess.Write)) { await file.WriteAsync(data, 0, data.Length); } return (storagePath: fileStoragePath, fileSize: data.Length, success: true); } catch (Exception) { return (storagePath: null, fileSize: 0, success: false); } } } } <file_sep>namespace FileStore.Models.Request { public class FileMetadata { public string FileName { get; set; } public string ContentType { get; set; } public string Description { get; set; } } } <file_sep>using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using FileStore.Service; using FileStore.Models.ResponseResults; using FileStore.Models.Request; using System.IO; using Microsoft.AspNetCore.Authorization; namespace FileStore.Controllers { [Route("api/[controller]")] public class FilesController : Controller { private FileService fileService; /// <summary> /// Contructor getting the file service injected /// </summary> public FilesController(FileService fileService) { this.fileService = fileService; } /// <summary> /// Gets a files metadata /// </summary> /// <param name="id">File identifier</param> /// <returns></returns> [HttpGet("GetFileMetadata/{id}")] [Authorize] public async Task<IActionResult> GetFileMetadata(Guid id) { var result = await fileService.GetFileMetadata(id); if (!result.success) return BadRequest("Unable to find file info"); return Ok(new FileMetadataResult { FileId = result.fileInfo.Id, ContentType = result.fileInfo.ContentType, Description = result.fileInfo.Description, FileName = result.fileInfo.FileName, UploadedAt = result.fileInfo.UploadedAt, Size = result.fileInfo.Size }); } /// <summary> /// Downloads the actual file data /// </summary> /// <param name="id">File identifier</param> /// <returns>File stream result containing the file data</returns> [HttpGet("DownloadFileData/{id}")] [Authorize] public async Task<IActionResult> DownloadFileData(Guid id) { var result = await fileService.GetUploadedFile(id); if (!result.success) return BadRequest("Unable to find file"); return File(result.fileStream, result.fileInfo.ContentType); } /// <summary> /// Initiates a file upload /// </summary> /// <param name="fileUploadInfo">Metadata of the file to be uploaded</param> /// <returns>Returns a guid which identifies the file to be uploaded. Needs to be used as the identifier for when uploading and downloading the file</returns> [HttpPost("InitiateFileUpload")] [Authorize] public async Task<IActionResult> InitiateFileUpload([FromBody] FileMetadata fileUploadInfo) { if(fileUploadInfo == null) return BadRequest(); var savedInitiatedFileUploadInfo = await fileService.SaveInitiatedFileMetadata(fileUploadInfo); if(!savedInitiatedFileUploadInfo.success) return StatusCode(500, "Unable to initiate file upload"); return Ok(new InitiatedFileUploadResult { GeneratedFileId = savedInitiatedFileUploadInfo.initiatedFileUpload.Id }); } /// <summary> /// Associates/Uploads the data from the request body with the provided file id /// </summary> /// <param name="id">File identifier</param> /// <returns></returns> [HttpPost("UploadFileData/{id}")] [Authorize] public async Task<IActionResult> UploadFileData(Guid id) { var initiatedFileUpload = await fileService.GetInitiatedFileUpload(id); if (initiatedFileUpload == null) return BadRequest(); if (initiatedFileUpload.FileUploaded) return BadRequest("File already uploaded"); byte[] fileData; using (var stream = new MemoryStream()) { Request.Body.CopyTo(stream); fileData = stream.ToArray(); } var savedFileData = await fileService.WriteFileDataToStorage(fileData, initiatedFileUpload.FileName); if (!savedFileData.success) return StatusCode(500, "Unable to store file"); var savedUploadedFileInfo = await fileService.SaveUploadedFileInfo(initiatedFileUpload, savedFileData.storagePath, savedFileData.fileSize); if (!savedUploadedFileInfo.success) return StatusCode(500, "Unable to store file"); return Ok(); } } } <file_sep>using FileStore.Database; using FileStore.Models; using FileStore.Service; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; using System.IO; using Microsoft.IdentityModel.Tokens; using System.Text; using FileStore.Middleware; namespace FileStore { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { var appsettingsConfig = Configuration.GetSection("AppSettings"); ValidateAppSettings(appsettingsConfig); services.AddMvc(); services.Configure<AppSettings>(appsettingsConfig) .AddEntityFramework() .AddEntityFrameworkSqlite() .AddDbContext<FileDbContext>(options => options.UseSqlite("Data Source=filedb.sqlite")) .AddTransient<FileService>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")) .AddDebug(); InitializeDatabase(app); SetAuthenticationMiddleware(app); app.UseMvc(); } private void ValidateAppSettings(IConfigurationSection appsettingsConfig) { var storagePath = appsettingsConfig.GetValue<string>("FileStoragePath"); if (!Directory.Exists(storagePath)) throw new InvalidOperationException("Provided FileStoragePath in appsettings does not exist"); } private void InitializeDatabase(IApplicationBuilder app) { using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) { var db = serviceScope.ServiceProvider.GetService<FileDbContext>(); db.Database.EnsureCreated(); } } //Authentication middleware code copied from https://stormpath.com/blog/token-authentication-asp-net-core private static readonly string secretAuthKey = "hemligthemligt123"; private void SetAuthenticationMiddleware(IApplicationBuilder app) { var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretAuthKey)); var options = new TokenProviderOptions { Audience = "ExampleAudience", Issuer = "ExampleIssuer", SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256), Expiration = TimeSpan.FromDays(2) }; app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options)); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = "ExampleIssuer", ValidateAudience = true, ValidAudience = "ExampleAudience", ClockSkew = TimeSpan.Zero }; app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = tokenValidationParameters }); } } } <file_sep>Howto: 1. Get token http://[host]/api/token Header => Content-Type: application/x-www-form-urlencoded Body => username=secretname&password=<PASSWORD> Returns => [token] 2. Initiate file upload by providing file meta data. Needed in order to get a id for the file. Header => Authorization: bearer [token] HTTP post => http://[host]/api/files/InitiateFileUpload Body => Json with the following properties; FileName, ContentType, Description Returns => [fileguid] 3. Upload file data http://[host]/api/files/UploadFileData/[fileguid] Header => Authorization: bearer [token] 4. Download file metadata http://[host]/api/files/GetFileMetadata/[fileguid] Header => Authorization: bearer [token] Returns => Json with file metadata 4. Download file metadata http://[host]/api/files/DownloadFileData/[fileguid] Header => Authorization: bearer [token] Returns => File data
ce6b0b4026a078a0d752263810216b120bc38850
[ "C#", "Text" ]
10
C#
vaspop/FileStore
e6a69b7feb4498af50c01ed5457288ffdf656cc6
2ba1cb659f143166faa8928d9849aa607a559ea1
refs/heads/master
<file_sep>class Dog def name=(name) # setter method for name @this_dog_name = name end def name # getter method for name (returns the name) return @this_dog_name end def bark # instance method puts "woof!" end end
f18ff7be5551762c861c8cbcb1c6b8d7701f1b1a
[ "Ruby" ]
1
Ruby
tarricsookdeo/oo-barking-dog-online-web-ft-100719
eda9dea389947b9d69aa12497fe988abb1ba03dc
4f7cae2a6d8963a7e302eb2d03e0a8304c8495b3
refs/heads/master
<file_sep><html> <head> <title>Online PHP Script Execution</title> </head> <body> <?php $Price = 50.32 ; $Discount = 0 ; $Total = 0 ; $Sub_Total = 0; $Items = 10; function Disc10(){ $Discount = 10; $Price / $Discount = $Sub_Total ; echo $Sub_Total; } if ($Price >= 20 && $Items >= 10 ); { Disc10() } ?> </body> </html>
f86f75faf22d25b29750c5c3f2dece988a87e1fc
[ "PHP" ]
1
PHP
nycode802/codingground
a634121502e31d5bef7263f33dbe710c589d3af4
4da2f160c9834a996d98f0527edcd1c9c28de6cb
refs/heads/master
<file_sep>#!/bin/bash #参数化构建 #https://yq.aliyun.com/articles/53971 #Jenkins官网:https://jenkins.io/index.html #https://en.wikipedia.org/wiki/Comparison_of_continuous_integration_software #http://www.techweb.com.cn/network/system/2016-01-28/2270191.shtml "----------------------------------------------------------------- echo $deploy_envirenment case $deploy_envirenment in deploy) echo "deploy: $deploy_envirenment" ansible webservers -m script -a "~/bashscript/xxxxxx_deploy.sh --local-repository=/www/test/test --repository-url=git仓库地址 --backup-dir=/www/test/bak --webdir=/www/test/www" ;; rollback) echo "rollback: $deploy_envirenment" ansible webservers -m script -a '~/bashscript/xxxxxx_rollback.sh --backup-dir=/www/test/bak --webdir=/www/test/www' ;; *) exit;; esac deploy_envirenment deploy rollback <file_sep>#coding:utf-8 for i in range(1,10): for j in range(1,i+1): print('%s*%s=%s'%(i,j,i*j)) print('') <file_sep>#!/usr/bin/env python # -*-coding:utf-8-*- import urllib import urllib2 import json import sys import platform import time def auth(uid, username, password, api_url): """ zabbix认证 :param uid: :param username: :param password: :return: """ dict_data = {} dict_data['method'] = 'user.login' # 方法 dict_data['id'] = uid # 用户id dict_data['jsonrpc'] = "2.0" # api版本 dict_data['params'] = {"user": username, "password": <PASSWORD>} # 用户账号密码 jdata = json.dumps(dict_data) # 格式化json数据 content = post_data(jdata, api_url) # post json到接口 return content # 返回信息 def post_data(jdata, url): """ POST方法 :param jdata: :param url: :return: """ req = urllib2.Request(url, jdata, {'Content-Type': 'application/json'}) response = urllib2.urlopen(req) # content = response.read() content = json.load(response) return content def create_maintenance(name, groupid, active_since, active_till, period, auth_code, api_url): """ create maintenance :return: """ dict_data = {} dict_data['method'] = 'maintenance.create' # 方法 dict_data['id'] = uid # 用户id dict_data['jsonrpc'] = "2.0" # api版本 dict_data['auth'] = auth_code # api版本 dict_data['description'] = "UPDATE" + groupid # api版本 # group groupids = [groupid] # timeperiods timeperiods = [{"timeperiod_type": 0, "start_time": 64800, "period": period}] dict_data['params'] = {"name": name, "active_since": active_since, "timeperiods": timeperiods, "active_till": active_till, "groupids": groupids} # 用户账号密码 jdata = json.dumps(dict_data) # 格式化json数据 content = post_data(jdata, api_url) # post json到接口 print content return content # 返回信息 def get_groupid(groupname, auth_code, uid, api_url): """ use groupname get groupid :param groupname: :param auth: :param uid: :return: """ dict_data = {} dict_data['method'] = 'hostgroup.get' # 方法 dict_data['id'] = uid # 用户id dict_data['jsonrpc'] = "2.0" # api版本 name = {"name": groupname} dict_data['params'] = {"filter":name } # 主机名 dict_data['auth'] = auth_code # auth串 jdata = json.dumps(dict_data) # 格式化json数据 print jdata content = post_data(jdata, api_url) # post json到接口 return content # 返回信息 def logout(uid, auth_code, api_url): """ 退出 :param uid: :param auth_code: :return: """ dict_data = {} dict_data['method'] = 'user.logout' # 方法 dict_data['id'] = uid # 用户id dict_data['jsonrpc'] = "2.0" # api版本 dict_data['params'] = [] dict_data['auth'] = auth_code # auth串 jdata = json.dumps(dict_data) # 格式化json数据 content = post_data(jdata, api_url) # post json到接口 return content # 返回信息 if __name__ == '__main__': # user info uid = 29# 用户ID username = 'haifeng18' password = '<PASSWORD>' api_url = "http://10.73.29.79/zabbix/api_jsonrpc.php" res = auth(29, username, password, api_url) # 认证 if res['result']: auth_code = res['result'] # 认证串 #groupname = platform.node() # 主机名 groupname = sys.argv[1] # 主机名 res = get_groupid(groupname, auth_code, uid, api_url) if res['result']: period = 600 # 维护时长 active_since = int(time.time()) # 开始时间 active_till = int(time.time()) + period # 结束时间 groupid = res['result'][0]['groupid'] # 主机 #groupid = str(52) # 主机 res = create_maintenance('AutoMaintenance_' + groupname + '_' + str(active_since), groupid, active_since, active_till, period,auth_code, api_url) # 创建维护 logout(uid, auth_code, api_url) # 退出登录 print res else: pass <file_sep>#!/usr/bin/env python import time import os import sys import commands Project_Home = os.getcwd() Deploy_time = time.strftime('%Y_%m_%d_%H_%M') artifact = sys.argv[1] + Deploy_time def Update_package(): """ :return: """ if os.path.isfile('build/release64/bin/feed_fisher') == True: retcode = commands.getstatusoutput('curl --upload-file build/release64/bin/feed_fisher -u admin:weiboinf' ' -v http://nexus.biz.weibo.com/repository/files/deploy/%s')%(artifact) if retcode[0] == 0: print "上传成功!!!" else: print "Error:编译未生成软件包" 12 def deploy_online(): pass <file_sep>## Python网站 * [python-cookbook](http://python3-cookbook.readthedocs.io/zh_CN/latest) ## python开发工具 * [pycharm激活](http://xidea.online) ## 代码部署: * 获取代码:使用公司gitlab统一管理,指定提交代码的规范 * 编译:根据环境不同,考虑是否使用静态库或在docker中创建不同的编译环境 - 目录名:SuperFans - 文件名:SuperFans_King_v1.0_2017-03-21-1010 * 匹配环境配置文件,测试环境,灰度,线上环境 * 打包:使用tar命令进行打包,命名规则Super_Fans_King_v1.0_2017-03-21-1010 * 使用SaltStack根据业务分组统一将代码推到目标服务器 * 将待部署节点移除集群,是否可以通过接口的方式移除,动态管理节点 * 解压代码包 * 创建软链接,目的为了秒级回滚,实际代码根路径为/home/w,所有代码存放在/data1 目录下,/home/w/webservice -> /data1/webservice_v1.0_2017-03-21-1010/ * COPY差异文件(可选):因为同一集群中配置文件不同 * 重启服务 * 自动化测试验证:如果有验证接口最好,没有写脚本验证 * 接入集群提供服务 ## 代码回滚: * 列出回滚版本 * 目标服务器移除集群 * 执行回滚:删除旧的软链接,创建到指定版本的软连接 * 重启服务 * 自动化验证 * 加入集群 <file_sep>import socket HOST = '127.0.0.1' PORT = 3434 # AF_INET 说明是IPv4地址;SOCK_DGRAM指明是UDP s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) data = "Hello,UDP!" print(data) s.sendto(data.encode('utf-8'),(HOST,PORT)) print("Sent: %s to %s:%d" %(data,HOST,PORT)) s.close()<file_sep>from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'indexsdfssdfsdfef/',views.index,name='index'), url(r'login/',views.login), url(r'home/',views.Home.as_view()), #url(r'detail/',views.detail), url(r'detail-(\d+).html',views.detail), #url(r'detail-(?P<nid>\d+)-(?P<uid>\d+).html',views.detail), #URL分组,指定view是参数为默认参数 ] <file_sep>#!/usr/bin/env python import docker c = docker.Client(base_url='unix://var/run/docker.sock',version='1.22',timeout=10) ex = c.exec_create(container='37d91ab772d3',cmd='mkdir /data0') print c.exec_inspect(ex) ls=c.exec_start(exec_id=ex["Id"],tty=True) <file_sep>import socket import datetime HOST = '0.0.0.0' PORT = 34343 # AF_INET 说明是IPv4地址;SOCK_DGRAM指明是TCP s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((HOST,PORT)) s.listen(1) while True: conn,addr = s.accept() print('Client %s connected!!'%str(addr)) dt = datetime.datetime.now() message = "Current time is " + str(dt) conn.send(message.encode('utf-8')) print("Sent:",message) conn.close()<file_sep>#!/usr/bin/env python import difflib import sys try: textfile1=sys.argv[1] #第一个配置文件路径参数 textfile2=sys.argv[2] #第二个配置文件路径参数 except Exception,e: print "Error:" + str(e) print "Usage: file_diff.py filename1 filename2" sys.exit() def readfile(filename): try: fileHandle=open(filename,'rb') text=fileHandle.read().splitlines() #读取后按行进行分隔 fileHandle.close() return text except IOError as error: print 'Read file Error:' + str(error) sys.exit() if textfile1=="" or textfile2=="": print "Usage: file_diff.py filename1 filename2" sys.exit() text1_lines=readfile(textfile1) #调用readfile函数,获取分隔后的字符串 text2_lines=readfile(textfile2) d = difflib.HtmlDiff() #创建HtmlDiff()类对象 print d.make_file(text1_lines,text2_lines) #通过make_file方法输出HTML格式的比对结果 <file_sep>#coding:utf-8 #将一个正整数分解质因数 dig_input = int(input('请输入一个数字:')) l = [] while dig_input != 1: for i in range(2,dig_input+1): print i if dig_input % i == 0: l.append(i) dig_input = dig_input / i break print l <file_sep>from django.shortcuts import render,HttpResponse,redirect import os # Create your views here. #User_Dict = { # 'k1':'admin', # 'k2':'guest', # 'k3':'devlop', # 'k4':'test' #} User_Dict = { '1':{'name':'admin','email':'<EMAIL>'}, '2':{'name':'guest','email':'<EMAIL>'}, '3':{'name':'devlop','email':'<EMAIL>'}, '4':{'name':'test','email':'<EMAIL>'} } def index(request): return render(request,'index.html',{'user_dict':User_Dict}) #基于get请求以?分割来获取数据 #def detail(request): # nid = request.GET.get('nid') # detail_info = User_Dict[nid] # return render(request,'detail.html',{'detail_info':detail_info}) #def detail(request,nid): #如果是(\d+)就是用*args,如果使用分组的话,使用**kwargs # detail_info = User_Dict[nid] # return render(request,'detail.html',{'detail_info':detail_info}) """ def login(request): if request .method == "GET": return render(request,'login.html') elif request.method == "POST": u = request.POST.get('user') p = request.POST.get('pwd') if u == 'haifeng18' and p == '123456': return redirect('/index') else: return render(request,'login.html') else: return redirect('/index') # redirect跳转界面 """ def login(request): if request .method == "GET": return render(request,'login.html') elif request.method == "POST": #radio #v = request.POST.get('gender') #print(v) #checkbox #v = request.POST.getlist('favor') #获取多个值,列表 #print(v) obj = request.FILES.get('fa') #上传文件 file_path = os.path.join('upload',obj.name) f = open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() return render(request, 'login.html') else: return redirect('/index') from django.views import View class Home(View): def dispatch(self, request, *args, **kwargs): #super调用父类中的dispatch方法 result = super(Home, self).dispatch(request,*args,**kwargs) return result def get(self,request): return render(request,'home.html') def post(self,request): return render(request, 'home.html') <file_sep>#需要pip安装itertools-recipes #coding:utf-8 from itertools import permutations for i in permutations(range(1,5),3): k = '' for j in i: k = k +str(j) print(int(k)) <file_sep>import socket HOST = '127.0.0.1' PORT = 34343 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((HOST,PORT)) print("Connect %s:%d OK"%(HOST,PORT)) data = s.recv(1024) print("Received:",data.decode('utf-8')) s.close()<file_sep># TCP Socket的粘包和分包的处理:https://blog.csdn.net/yannanxiu/article/details/52096465<file_sep>#!/usr/bin/env python3 import jenkins,time from django.conf import settings import logging import re import xml.etree.cElementTree as ET from common.models import ConfigDict log = logging.getLogger('django') def render_command(command, nexus_path): """ 为shell命令渲染变量值 :param command: shell命令 :param nexus_path: 所属的nexus files仓库组 :return: 渲染后的command """ configs = ConfigDict() url = configs['nexus.raw_url'] + nexus_path + '/$Tag_Version.tgz' command = command.replace('$release_url', url) return command class Jenkins_API(): def __init__(self,url,user,token): self.server = jenkins.Jenkins(url, username=user, password=<PASSWORD>) self.prefix = "KUN__" self.build_xml_template = ''' <project> <actions/> <description></description> <keepDependencies>false</keepDependencies> <properties> <jenkins.model.BuildDiscarderProperty> <strategy class="hudson.tasks.LogRotator"> <daysToKeep>-1</daysToKeep> <numToKeep>5</numToKeep> <artifactDaysToKeep>-1</artifactDaysToKeep> <artifactNumToKeep>-1</artifactNumToKeep> </strategy> </jenkins.model.BuildDiscarderProperty> <hudson.model.ParametersDefinitionProperty> <parameterDefinitions> <net.uaznia.lukanus.hudson.plugins.gitparameter.GitParameterDefinition plugin="git-parameter@0.9.0"> <name>Tag_Version</name> <description></description> <uuid>5d264244-f330-422d-8760-f36dce753e34</uuid> <type>PT_BRANCH_TAG</type> <branch></branch> <tagFilter>*</tagFilter> <branchFilter>.*</branchFilter> <sortMode>NONE</sortMode> <defaultValue></defaultValue> <selectedValue>NONE</selectedValue> <quickFilterEnabled>false</quickFilterEnabled> </net.uaznia.lukanus.hudson.plugins.gitparameter.GitParameterDefinition> </parameterDefinitions> </hudson.model.ParametersDefinitionProperty> </properties> <scm class="hudson.plugins.git.GitSCM" plugin="git@3.6.4"> <configVersion>2</configVersion> <userRemoteConfigs> <hudson.plugins.git.UserRemoteConfig> <url></url> <credentialsId>weiboad_common-privatekey</credentialsId> </hudson.plugins.git.UserRemoteConfig> </userRemoteConfigs> <branches> <hudson.plugins.git.BranchSpec> <name>$Tag_Version</name> </hudson.plugins.git.BranchSpec> </branches> <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations> <submoduleCfg class="list"/> <extensions> <hudson.plugins.git.extensions.impl.CloneOption> <shallow>true</shallow> <noTags>false</noTags> <reference></reference> <depth>1</depth> <honorRefspec>false</honorRefspec> </hudson.plugins.git.extensions.impl.CloneOption> </extensions> </scm> <assignedNode></assignedNode> <canRoam>false</canRoam> <disabled>false</disabled> <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding> <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding> <triggers/> <concurrentBuild>false</concurrentBuild> <builders> <hudson.tasks.Shell> <command> </command> </hudson.tasks.Shell> </builders> <publishers/> <buildWrappers> <hudson.plugins.ws__cleanup.PreBuildCleanup plugin="ws-cleanup@0.34"> <deleteDirs>false</deleteDirs> <cleanupParameter></cleanupParameter> <externalDelete></externalDelete> </hudson.plugins.ws__cleanup.PreBuildCleanup> </buildWrappers> </project> ''' def exist_job(self,job_name): return self.server.get_job_name(job_name) is not None def create_job(self,pro_obj): job_name = self.generate_jenkins_name(pro_obj) detail = pro_obj.detail git_path = pro_obj.git_path label = pro_obj.label build_command = pro_obj.build_command log.info('Create or reconfig Jenkins Project [%s].', job_name) if self.exist_job(job_name): build_xml = self.modify_config(job_name, detail,git_path, label, render_command(build_command, pro_obj.nexus_path)) self.server.reconfig_job(job_name,build_xml) else: build_xml = self.modify_config(job_name, detail,git_path, label, render_command(build_command, pro_obj.nexus_path), exist=False) self.server.create_job(job_name,build_xml) def modify_config(self, job_name, detail, git_path, label, build_command, exist=True): """ 如果jenkins已有项目,下载项目的xml配置,只修改git、detail、Build、构建节点label相关信息并生成xml返回 :param job_name: jenkin项目名称 :param detail: 描述 :param git_path: git地址ssh :param label: jenkins构建节点的label :param build_command: 构建脚本 :param exist: 是否jenkins项目已存在,默认已存在 :return: """ if exist: config_xml = self.server.get_job_config(job_name) else: config_xml = self.build_xml`_template log.info("Reconfig jenkins job [%s] with [desc: %s git: %s buildcommand: %s]", job_name, detail,git_path, build_command) config_root = ET.fromstring(config_xml) config_root.find('description').text = detail config_root.find('builders').find('hudson.tasks.Shell').find('command').text = build_command config_root.find('scm').find('userRemoteConfigs').find('hudson.plugins.git.UserRemoteConfig').find('url').text = git_path config_root.find('assignedNode').text = label return ET.tostring(config_root, encoding="utf-8").decode("utf-8") def delete_job(self,obj): job_name = obj.jenkins_name if self.exist_job(job_name): self.server.delete_job(job_name) def generate_jenkins_name(self, obj): """ 生成jenkins项目的名称。以"KUN__"开头并连接项目的名称 :param obj: :return: """ if not obj.jenkins_name: obj.jenkins_name = self.prefix + obj.name obj.save() return obj.jenkins_name def create_build(self, obj, tag): """ 执行jenkins项目构建 :param obj: :param tag: :return: """ job_name = self.generate_jenkins_name(obj) print(job_name, tag) build_param = {'Tag_Version':tag} if not self.exist_job(job_name): self.create_job(obj) job_info = self.server.get_job_info(job_name) current_id = job_info['nextBuildNumber'] self.server.build_job(job_name,build_param) parent_url = job_info['url'] + str(current_id) + '/' localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) build_result = { "build_id": current_id, "tag": tag, "status": 3, "build_time": localtime, "jenkins_build_url": parent_url, # "pro_id": obj.id } return build_result def get_tags(self): """ 遍历每个jenkins的节点配置,解析出所有的标签list :return: """ reg = re.compile('<label>(.*)</label>') tags = set() for node in self.server.get_nodes(): print(node) try: config = self.server.get_node_config(node['name']) labels = reg.findall(config) if labels and labels[0]: tags = tags | set(labels[0].split(' ')) except jenkins.NotFoundException: pass return list(tags) # Jenkins_U = '' # Jenkins_T = '' # Jenkins_URL = 'http://jenkinx.xxx.xxx.com/' # ja = Jenkins_API(Jenkins_URL, Jenkins_U, Jenkins_T) # print(ja.get_tags()) # j = jenkins.Jenkins(Jenkins_URL, username=xxxxxx, password=<PASSWORD>) # print(j.get_whoami()) # # print(j.get_all_jobs()) # print(j.build_job('Farmer-ng', parameters={"param1": "1.0.2"})) # # queue_info = j.get_queue_info() # # print(queue_info) # # i = queue_info[0].get('id') # # print(i) # print("============================") # print(j.get_build_info('Farmer-ng', 31)) # j.get_build_console_output('Farmer-ng', 35) <file_sep>#!/usr/bin/env python def unicode(): print('\033[1;33m ord():\033[0m函数获取字符的整数表示') print('\033[1;33m chr():\033[0m函数把编码转换为对应的字符') #由于Python的字符串类型是str,在内存中以unicode表示,一个字符对应若干个字节.如果要在网络中传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes. if __name__=='__main__': unicode() <file_sep>import socket HOST = '0.0.0.0' PORT = 3434 # AF_INET 说明是IPv4地址;SOCK_DGRAM指明是UDP s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind((HOST, PORT)) while True: data, addr = s.recvfrom(1024) print("Received: %s from %s" % (data.decode('utf-8'),str(addr))) s.close()<file_sep>#-*- coding:utf-8 -*- def mov(n,a,b,c): if n == 1: print(a,'->',c) else: mov(n-1,a,c,b) mov(1,a,b,c) mov(n-1,b,a,c) num = input("number:") mov(int(num),'A','B','C') <file_sep>#!/usr/bin/env python #-*- coding:utf-8 -*- import psutil,time def getProcessInfo(proc): cpu=int(proc.cpu_percent(interval=0)) #获取CPU使用率 rss='%.2f'%proc.memory_percent() #获取物理内存使用率,单位为GB name=proc.name() #获取进程名 pid=proc.pid #获取进程PID cwd=proc.cwd() #获取进程部署路径 return [pid,name,cpu,rss,cwd] def getAllProcessInfo(): instances = [] all_processes = list(psutil.process_iter()) #获取当前机器全部的进程 for proc in all_processes: proc.cpu_percent(interval=0) time.sleep(1) for proc in all_processes: instances.append(getProcessInfo(proc)) return instances ret=getAllProcessInfo() for i in ret: if i[4] == '/' or i[1] == 'sudo' or i[1] =='su': #过滤掉系统进程 pass else: print i
6b0a2ec85ada75c6a4ffafb1d7681e7dd3b7f1ef
[ "Markdown", "Python", "Shell" ]
20
Shell
dihaifeng/python_code
d8e90c067d3e4fa2cd5dddcfef2084907bda6e76
d2da8b0660a30a5d3222a491d3f3d2c9b0b34f66
refs/heads/master
<file_sep>package com.prodyna.demo.recursion; import java.util.*; import java.util.stream.Stream; import org.neo4j.driver.v1.GraphDatabase; import org.neo4j.graphdb.*; import org.neo4j.logging.Log; import org.neo4j.procedure.Context; import org.neo4j.procedure.Procedure; import static org.neo4j.graphdb.Direction.INCOMING; import static org.neo4j.procedure.Mode.READ; import static org.neo4j.procedure.Mode.WRITE; public class Recursion { @Context public GraphDatabaseService db; @Context public Log log; @Procedure(name = "recursion.rootNode", mode = READ ) public Stream<NodeResult> rootNode() { List<NodeResult> nodes = new ArrayList<>(); final Result result = db.execute("MATCH (root:Station) OPTIONAL MATCH (root)-[r:CABLE]->(:Station) WITH root,count(r) AS rc WHERE rc = 0 RETURN root"); while( result.hasNext() ) { Node node = (Node) result.next().get("root"); log.info( "Found root node " + node ); nodes.add( new NodeResult( node )); } return nodes.stream(); } @Procedure( name = "recursion.effectiveLoad", mode = WRITE ) public Stream<NodeResult> effectiveLoad() { List<NodeResult> nodes = new ArrayList<>(); Iterator<NodeResult> rootNodes = rootNode().iterator(); while( rootNodes.hasNext() ) { NodeResult rootNode = rootNodes.next(); nodes.add( rootNode ); cables( rootNode.node ); } return nodes.stream(); } private long cables( Node parentStation ) { long totalLoad = 0; Iterator<Relationship> cables = parentStation.getRelationships(INCOMING).iterator(); while (cables.hasNext()) { Relationship cable = cables.next(); if( cable.getType().name().equals("CABLE") ) { long load = stations( cable ); totalLoad += load; } } long ownLoad = (long) parentStation.getProperty("load"); totalLoad += ownLoad; parentStation.setProperty( "effectiveLoad", totalLoad ); return totalLoad; } private long stations( Relationship parentCable ) { long totalLoad = 0; Node station = parentCable.getStartNode(); totalLoad += cables( station ); return totalLoad; } public class NodeResult { public final Node node; public NodeResult(Node node) { this.node = node; } } }
074d837051c4ab141e2973923c4fc592c1707073
[ "Java" ]
1
Java
dkrizic/recursion
9efd5e90ac8fc1dd4ea4649da54d5ff50a134dab
65555423226056555acccb751dada80fb3c193a7
refs/heads/main
<file_sep>import express from 'express'; import swaggerUi from "swagger-ui-express"; const swaggerDocument = require('../server/openapi.json'); const passport = require('passport'); const upload = require("../middleware/upload") const router = express.Router(); import RouterProductos from "../routes/productos.routes"; import RouterCarrito from '../routes/carritos.routes'; import RouterOrdenes from '../routes/orders.routes'; import routerSession from "../routes/session.routes"; const routerProducts = new RouterProductos() const routerCarts = new RouterCarrito() const routerOrders = new RouterOrdenes() router.use('/api', routerSession); router.use('/api', routerProducts.start()); router.use('/api', passport.authenticate('jwt', { session: false }), routerCarts.start()); router.use('/api', passport.authenticate('jwt', { session: false }),routerOrders.start()); // router.use('/api', routerFotos.start()) // router.use("/docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument)) // Handle errors. router.use(function (err: any, req: any, res: any, next: any) { res.status(err.status || 500); res.json({ error: err }); }); export default router<file_sep>import mongoose, { Error } from 'mongoose'; import bCrypt from "bcrypt"; import { messageModel } from '../models/message.model'; import { productoModel } from '../models/product.model'; import { carritoModel } from '../models/carts.model'; import { logger } from '../../config/winston.config'; import { orderModel } from '../models/orders.model'; import { MessageType, ProductoType } from '../../types/types'; const config = require('../../config/config'); const UserModel = require('../models/user'); export default class persistenciaMongo { constructor() { ; (async () => { try { await mongoose.connect( config.MONGO_URL || '', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true }); console.log('Base de datos conectada') } catch (error) { console.log(error) } })() } /* PRODUCTOS */ traerProductos = async (): Promise<string> => { return await productoModel.find({}); } traerProductosPorCategoria = async (category: string): Promise<string> => { return await productoModel.find({ categoria: category }); } traerProducto = async (id: string): Promise<string> => { return await productoModel.findById(id); } agregarProducto = async (producto: ProductoType): Promise<object> => { try { const productoSaved = new productoModel(producto) const resultado = await productoSaved.save() return resultado } catch (error: any) { return { errorType: error.kind, errorMessage: 'Producto no agregado' } } } actualizarProducto = async (id: string, producto: any): Promise<object> => { try { const resultado = await productoModel.findByIdAndUpdate({ _id: id }, { $set: producto }); return resultado } catch (error: any) { return { errorType: error.kind, errorMessage: 'Producto no actualizado' } } } eliminarProducto = async (id: string): Promise<object> => { try { const resultado = await productoModel.findByIdAndDelete(id); return resultado } catch (error: any) { return { errorType: error.kind, errorMessage: 'Id no encontrado' } } } hasStock = async ({ productoId, cantidad }: any) => { try { const { stock, precio } = await productoModel.findById(productoId); if (cantidad <= stock) { return { sePuede: true, stock, precio } } else { return { sePuede: false } } } catch (error: any) { return { errorType: error.kind, errorMessage: 'Id no encontrado' } } } /* MENSAJES */ traerMensajesDe = async (id: string): Promise<string> => { return await messageModel.find({ userId: id }); } agregarMensaje = async (message: MessageType): Promise<string> => { const messageSaved = new messageModel(message) return await messageSaved.save() } /* PASSWORD HASH */ createHash = (password: any) => { return bCrypt.hashSync(password, bCrypt.genSaltSync(10)); } isValidPassword = (user: any, password: any) => { return bCrypt.compareSync(password, user.<PASSWORD>) } /* USER */ updateUser = async (id: any, { nombreCompleto, celular, admin = false }: any): Promise<string> => { const userId = id._id; return await UserModel.findByIdAndUpdate({ _id: userId }, { $set: { nombreCompleto, celular, admin, } }) } traerUserById = async (id: string): Promise<object> => { try { const user = await UserModel.findById(id); return user } catch (error: any) { return { errorType: error.kind, errorMessage: 'Usuario no encontrado' } } } traerUser = async (email: string): Promise<string> => { return await UserModel.findOne({ email: email }); } /* CARRITO */ crearCarrito = async (user: any, direccion: any): Promise<string> => { const carritoVacio = { userId: user._id, productos: [], direccion } const carritoCreated = new carritoModel(carritoVacio) return await carritoCreated.save() } traerCarrito = async (id: string): Promise<object> => { try { return await carritoModel.findById(id); } catch (error: any) { return { errorType: error.kind } } } traerCarritoByUserId = async (id: string): Promise<object> => { try { return await carritoModel.find({ userId: id }); } catch (error: any) { return { errorType: error.kind } } } vaciarProductosDelCarrito = async (idCart: string): Promise<object> => { try { const queryCart = { _id: idCart }; const updateDocumentCart = { $set: { productos: [] } } const carritoVaciado = await carritoModel.updateOne(queryCart, updateDocumentCart); return carritoVaciado } catch (error: any) { return { errorType: error.kind } } } agregarProductoEnCarrito = async (idCart: string, { productoId, cantidad, stock, precio }: any): Promise<object> => { try { const queryCart = { _id: idCart }; const updateDocumentCart = { $push: { productos: { productoId, cantidad, precio } } } const productoAgregado = await carritoModel.updateOne(queryCart, updateDocumentCart); if (productoAgregado) { const queryProduct = { _id: productoId }; const nuevoStockProducto = stock - cantidad; const updateDocumentCart = { $set: { stock: nuevoStockProducto } } const descontarProducto = await productoModel.updateOne(queryProduct, updateDocumentCart); if (descontarProducto) { return { productoAgregado, descontarProducto } } return { productoAgregado, } } return productoAgregado; } catch (error: any) { return { errorType: error.kind, } } } eliminarProductoEnCarrito = async (idCart: string, { productoId, cantidad }: any, eliminarProducto: any): Promise<object> => { try { if (eliminarProducto.eliminar) { // Sacar el producto del array const queryCart = { _id: idCart }; const updateDocumentCart = { $set: { productos: eliminarProducto.productos } } const productoEliminado = await carritoModel.updateOne(queryCart, updateDocumentCart); const { stock } = await productoModel.findById(productoId); const queryProduct = { _id: productoId }; const nuevoStockProducto = stock + cantidad; const updateDocumentProducto = { $set: { stock: nuevoStockProducto } } const agregarStockProducto = await productoModel.updateOne(queryProduct, updateDocumentProducto); return { productoEliminado } } else { return { message: 'No hay que eliminar' } } } catch (error: any) { console.log(error) return { errorType: error.kind, } } } /* ORDENES */ crearOrden = async (orden: any): Promise<object> => { try { const totalPrice = orden.productos.reduce((total: any, producto: any) => total + (producto.precio * producto.cantidad), 0); const items = orden.productos.map((prod: any) => { return { productId: prod.productoId, cantidad: prod.cantidad, precio: prod.precio } }) const nuevaOrden = { userId: orden.userId, items: items, direccion: orden.direccion, estado: 'Generada', totalOrder: totalPrice } const ordenSaved = new orderModel(nuevaOrden) const ordenGenerada = await ordenSaved.save() return ordenGenerada; } catch (error: any) { return { errorType: error.kind } } } traerOrdenesByUserId = async (id: string): Promise<object> => { try { return await orderModel.find({ userId: id }); } catch (error: any) { return { errorType: error.kind } } } traerUltimaOrdenByUserId = async (id: string): Promise<object> => { try { return await orderModel.find({ userId: id }).sort({ $natural: -1 }).limit(1); } catch (error: any) { return { errorType: error.kind } } } traerOrdenesById = async (id: string): Promise<object> => { try { return await orderModel.findById(id); } catch (error: any) { return { errorType: error.kind } } } modificarOrden = async (id: string): Promise<object> => { try { const queryOrder = { _id: id }; const updateDocumentOrder = { $set: { estado: 'Completada', } } const modificarOrden = await orderModel.updateOne(queryOrder, updateDocumentOrder); return modificarOrden; } catch (error: any) { return { errorType: error.kind } } } } <file_sep>import { Request, Response } from 'express'; import { enviarMailEthereal } from '../service/mail'; import model from '../db/index.db' module.exports = { getOne: async (req: Request, res: Response) => { const cart: any = await model?.traerCarrito(req.params.carrito_id); if (cart.errorType) { res.status(400).json({ message: `No existe el carrito con ID: ${req.params.carrito_id}` }); } else { res.status(200).json(cart) } }, add: async (req: Request, res: Response) => { //Agregar producto al carrito const idCart = req.params.carrito_id; const { productoId, cantidad } = req.body; const agregarAlCarrito: any = await model?.hasStock({ productoId, cantidad }); if (agregarAlCarrito.errorType) { return res.status(400).json({ message: 'El id del producto no existe' }); } if (agregarAlCarrito.sePuede) { const cart: any = await model?.agregarProductoEnCarrito(idCart, { productoId, cantidad, stock: agregarAlCarrito.stock, precio: agregarAlCarrito.precio }); if (cart.errorType) { return res.status(400).json({ message: 'Hubo un incoveniente al agregar el producto al carrito' }); } const carrito = await model?.traerCarrito(idCart); return res.status(200).json(carrito); } else { return res.status(400).json({ message: 'La Cantidad solicitada es invalida' }); } }, delete: async (req: Request, res: Response) => { //Eliminar producto al carrito const idCart = req.params.carrito_id; const { productoId, cantidad } = req.body; const productoEliminadoCarrito: any = await model?.traerCarrito(idCart); if (productoEliminadoCarrito.errorType) { return res.status(400).json({ message: 'El ID del Carrito no existe' }); } const existeProducto: any = productoEliminadoCarrito.productos.find((p: any) => p.productoId === productoId) if (existeProducto) { if (cantidad <= existeProducto.cantidad) { const eliminarProducto = { eliminar: (cantidad === existeProducto.cantidad) , productos: productoEliminadoCarrito.productos.filter((p: any) => p.productoId !== productoId) } const cart: any = await model?.eliminarProductoEnCarrito(idCart, { productoId, cantidad }, eliminarProducto); if (cart.errorType) { return res.status(400).json({ message: 'Hubo un incoveniente al eliminar el producto al carrito' }); } const carrito = await model?.traerCarrito(idCart); return res.status(200).json(carrito); } else { return res.status(400).json({ message: 'La Cantidad solicitada es invalida' }); } } else { return res.status(400).json({ message: 'El ID del Producto no existe' }); } }, submit: async (req: Request, res: Response) => { //Agregar producto al carrito const idCart = req.params.carrito_id; const carrito: any = await model?.traerCarrito(idCart); if (carrito.errorType) { return res.status(400).json({ message: 'El ID del Carrito no existe' }); } else { if (carrito.productos.length === 0) { return res.status(400).json({ message: 'El Carrito esta vacio' }); } else { const ordenGenerada: any = await model?.crearOrden(carrito); if (ordenGenerada.errorType) { return res.status(400).json({ message: 'Hubo un incoveniente al generar la nueva Orden' }); } else { const vaciarCarrito = await model?.vaciarProductosDelCarrito(idCart) const datosUsuario: any = await model?.traerUserById(ordenGenerada.userId) const mail = { a: datosUsuario.email, asunto: 'Solicitud de Orden', html: ` <h1>¡Hola ${datosUsuario.nombreCompleto}!</h1><br> <div> <h3>Total de la orden: ${ordenGenerada.totalOrder}</h3><br> <h3>Tu orden:</h3><br> <table> <tbody> ${ordenGenerada.items.forEach((item: any) => { return ` <tr> <td>Identificacion del Producto: ${item.productId}</td> <td>Identificacion del Producto: ${item.cantidad}</td> <td>Identificacion del Producto: ${item.precio}</td> </tr> ` })} </tbody> </table> </div><br> <div> <h3>Direccion de entrega:</h3><br> <p> Calle: ${ordenGenerada.direccion.calle}<br> Altura: ${ordenGenerada.direccion.altura}<br> Codigo Postal: ${ordenGenerada.direccion.codigoPostal}<br> Piso: ${ordenGenerada.direccion.piso}<br> Departamento: ${ordenGenerada.direccion.departamento}<br> </p> </div> ` } enviarMailEthereal(mail) return res.status(201).json(ordenGenerada); } } } }, }<file_sep>import { composeWithMongoose } from 'graphql-compose-mongoose'; import mongoose from 'mongoose'; const productoCollection = 'producto' // const ProductoSchema = new mongoose.Schema({ // timestamp: { type: Date, default: Date.now}, // nombre: { type: String, required: true, max: 70 }, // descripcion: { type: String, required: true, max: 100}, // codigo: { type: Number, required: true }, // foto: { type: String, required: true, max: 70 }, // precio: { type: Number, required: true }, // stock: { type: Number, required: true } // }) const ProductoSchema = new mongoose.Schema({ nombre: { type: String, required: true, max: 70 }, descripcion: { type: String, required: true, max: 100}, categoria: { type: String, required: true }, precio: { type: Number, required: true }, stock: { type: Number, required: true }, foto: { type: String }, }) export const productoModel = mongoose.model(productoCollection, ProductoSchema); export const ProductoTC = composeWithMongoose(productoModel);<file_sep>const axios = require('axios'); const Parte2 = async () => { let arrayConResponses = []; /* Loguearse */ const responseToken = await axios.post('http://localhost:8080/login',{ email: '<EMAIL>', password: '<PASSWORD>' }) console.log('Login, token:') console.log(responseToken.status); console.log(responseToken.data.token); // arrayConResponses.push(responseToken.data.token) /* Crear Producto */ const responseCrearProducto = await axios.post('http://localhost:8080/api/productos',{ nombre: 'Tomate que va a ser eliminado despues', descripcion: 'Es una verdura', codigo: 10, foto: 'URL', precio: 30, stock: 100 },{ headers: { 'Authorization': `Bearer ${responseToken.data.token}` } }) console.log('Producto Creado:') console.log(responseCrearProducto.status); console.log(responseCrearProducto.data) /* Crear Producto que lo voy a modificar */ const responseCrearProductoParaModificar = await axios.post('http://localhost:8080/api/productos',{ nombre: 'Tomate que va a ser modificado', descripcion: 'Es una verdura', codigo: 10, foto: 'URL', precio: 30, stock: 100 },{ headers: { 'Authorization': `Bearer ${responseToken.data.token}` } }) console.log('Producto Que va a ser Modificado:') console.log(responseCrearProductoParaModificar.status); console.log(responseCrearProductoParaModificar.data) /* Modificar Producto */ const responseModificarProducto = await axios.put(`http://localhost:8080/api/productos/${responseCrearProductoParaModificar.data._id}`,{ nombre: 'Tomate Modificado :)', descripcion: 'Es un verdura modificada', precio: 40, },{ headers: { 'Authorization': `Bearer ${responseToken.data.token}` } }) console.log('Producto Modificado:') console.log(responseModificarProducto.status) console.log(responseModificarProducto.data) /* Eliminar Producto */ const responseEliminarProducto = await axios.delete(`http://localhost:8080/api/productos/${responseCrearProducto.data._id}`,{ headers: { 'Authorization': `Bearer ${responseToken.data.token}` } }) console.log('Producto Eliminado:') console.log(responseEliminarProducto.status) console.log(responseEliminarProducto.data) /* Traer Todos los productos */ const responseProductos = await axios.get('http://localhost:8080/api/productos', { headers: { 'Authorization': `Bearer ${responseToken.data.token}` } }) console.log('Todos los Productos:') console.log(responseProductos.status) console.log(responseProductos.data) return arrayConResponses; } Parte2()<file_sep>interface User { email: string, password: string, passwordConfirm: string, nombreCompleto: string, celular: string, admin: boolean, } const validate = ({ email, password, passwordConfirm, nombreCompleto, celular, admin }: User) => { if (password === passwordConfirm) { return true } else { return false } } export default validate;<file_sep>import model from '../db/index.db' import { Socket } from "socket.io"; import { io } from "../server/server"; import { MessageType } from "../types/types"; const controllerSocket = (socket: Socket) => { console.log('Usuario conectado') /* Escuchando Mensajes del Cliente */ socket.on('messageToServer', async (objectMessage: MessageType) => { const { userId, message } = objectMessage; const user: any = await model?.traerUserById(userId); if (user.errorType) { io.emit('messageErrorToClient', user) } else { const mensaje = { userId, type: 'Usuario', message } const mensajeAgregado = await model?.agregarMensaje(mensaje); if (mensajeAgregado) { let mensajeServer = ''; if (message.toLowerCase().includes('stock')) { const productos: any = await model?.traerProductos(); const stock = productos?.map((p: any) => { return { nombre: p.nombre, stock: p.stock } }) mensajeServer = JSON.stringify(stock); } else if (message.toLowerCase().includes('orden')) { const ultimaOrden: any = await model?.traerUltimaOrdenByUserId(userId); mensajeServer = JSON.stringify(ultimaOrden); } else if (message.toLowerCase().includes('carrito')) { const datosCarrito: any = await model?.traerCarritoByUserId(userId); mensajeServer = JSON.stringify(datosCarrito); } else { mensajeServer = 'Mensaje predeterminado'; } const mensajeFromServer = { userId, type: 'Sistema', message: mensajeServer } const mensajeAgregadoFromServer = await model?.agregarMensaje(mensajeFromServer); if (mensajeAgregadoFromServer) { const mensajesDe = await model?.traerMensajesDe(userId) io.emit('messageToClient', mensajesDe) } } } }) } export default controllerSocket;<file_sep>import passport from "passport"; import { Request, Response, NextFunction } from 'express'; import { userFacebookModel } from '../db/models/userFacebook.model'; import validate from "../middleware/validations"; import { logger } from "./winston.config"; const config = require('../config/config'); const UserModel = require('../db/models/user'); const localStrategy = require('passport-local').Strategy; const JWTstrategy = require('passport-jwt').Strategy; const FacebookStrategy = require('passport-facebook').Strategy; const ExtractJWT = require('passport-jwt').ExtractJwt; const strategyOptions = { usernameField: 'email', passwordField: '<PASSWORD>', passReqToCallback: true, }; const strategyOptionsFacebook = { clientID: config.FACEBOOK_CLIENT_ID, clientSecret: config.FACEBOOK_CLIENT_SECRET, callbackURL: "http://localhost:8080/auth/facebook/callback", profileFields: ['id', 'displayName', 'email' , 'picture.type(large)'], scope: ["email"], enableProof: true, } const strategyJWT = { secretOrKey: 'TOP_SECRET', jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(), }; const signup = async (req: any, email: any, password: any, done: any) => { const { passwordConfirm, nombreCompleto, celular, admin } = req.body; try { if (password === passwordConfirm) { const user = await UserModel.create({ email, password, nombreCompleto, celular, admin }); return done(null, user); } throw new Error('Las contraseñas son diferentes') } catch (error) { logger.error(error) return done(error); } }; const login = async (req: any, email: String, password: any, done: any) => { try { const user = await UserModel.findOne({ email }); if (!user) { return done(null, false, { message: 'Usuario no encontrado' }); } const validate = await user.isValidPassword(password); if (!validate) { return done(null, false, { message: 'Contraseña erronea' }); } return done(null, user, { message: 'Logueado con éxito' }); } catch (error) { logger.error(error) return done(error); } }; const loginFacebook = async (accessToken:any, refreshToken:any, profile:any, cb:any) => { const findOrCreate = () => { userFacebookModel.findOne({ 'facebookId': profile.id }, (err: any, user: any) => { if (err) { return cb(err); } if (user) { return cb(null, user) } else { let newUser = new userFacebookModel(); newUser.facebookId = profile.id; newUser.username = profile._json.name; newUser.email = profile._json.email; newUser.photo = profile._json.picture.data.url; newUser.save((err: any) => { if (err) { throw err; } return cb(null, newUser) }) } }) } process.nextTick(findOrCreate); }; // Passport middleware to handle user registration passport.use('signup', new localStrategy(strategyOptions, signup)); // Passport middleware to handle user login passport.use('login', new localStrategy(strategyOptions, login)); // Passport middleware to handle user loginFacebook passport.use('facebook',new FacebookStrategy(strategyOptionsFacebook, loginFacebook)) passport.use( new JWTstrategy(strategyJWT, async (token: any, done : any) => { try { return done(null, token.user); } catch (error) { logger.error(error) done(error); } } ) ); export const inicializarPassport = passport.initialize() export const sessionPassport = passport.session() <file_sep>import { logger } from "../config/winston.config"; const config = require('../config/config') const client = require('twilio')(config.TWILIO_ACCOUNT_SID, config.TWILIO_AUTHTOKEN); const sendSMS = ({mensaje, para}: any) => client.messages.create({ body: `${mensaje}`, from: '+16122842307', to: para }) .then((message: any) => logger.info(message)) .catch((error: any) => logger.error(error)) const sendWhatsApp = ({mensaje, para}: any) => client.messages.create({ body: mensaje, from: 'whatsapp:+14155238886', to: `whatsapp:${para}` }) .then((message: any) => logger.info(message)) .catch((error: any) => logger.error(error)) export { sendSMS, sendWhatsApp }<file_sep>import { Router } from "express"; const ordersController = require('../controller/orders.controller') let routerOrders = Router(); // Rutas para Orders class RouterOrders { controladorCarrito: any; constructor() { this.controladorCarrito = ordersController; } start() { routerOrders.get("/orders/:user_id", ordersController.getAllOrders); routerOrders.get("/orders/:order_id",ordersController.getOne); routerOrders.post("/orders/complete",ordersController.completeOrder); return routerOrders } } export default RouterOrders;<file_sep>import { Router } from "express"; const fotosController = require('../controller/fotos.controller') let routerFotos = Router(); class RouterFotos { controladorFotos: any; constructor() { this.controladorFotos = fotosController; } start() { routerFotos.post('/image/upload', this.controladorFotos.create) routerFotos.get('/image/:id', this.controladorFotos.getOne) routerFotos.delete('/image/:id', this.controladorFotos.delete) return routerFotos } } export default RouterFotos;<file_sep>import fs from 'fs'; export default class peristenciaFileSystem { constructor() { ; (async () => { try { await fs.promises.readFile('datos.txt') } catch { await fs.promises.writeFile('datos.txt', JSON.stringify([])) } })() } /* PRODUCTOS */ traerProductos = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerProductosPorCategoria = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerProducto = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } agregarProducto = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } actualizarProducto = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } eliminarProducto = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerProductosXNombres = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerProductosXRangoPrecios = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } hasStock = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } /* MENSAJES */ traerMensajesDe = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } agregarMensaje = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } /* PASSWORD HASH*/ createHash = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } isValidPassword = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } /* USER */ updateUser = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerUser = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerUserById = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } /* CARRITO */ crearCarrito = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } agregarProductoEnCarrito = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } eliminarProductoEnCarrito = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerCarrito = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerCarritoByUserId = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } vaciarProductosDelCarrito = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } /* ORDENES */ crearOrden = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerOrdenesByUserId = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerUltimaOrdenByUserId = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } traerOrdenesById = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } modificarOrden = async () => { let datos = await fs.promises.readFile('datos.txt') return datos } // crearOrden = async () => { // let datos = await fs.promises.readFile('datos.txt') // return datos // } }<file_sep>// PRODUCTOS export type ProductoType = { nombre: string; descripcion: string; categoria: string; precio: number; stock: number; foto: string; } // MENSAJES export type MessageType = { userId: string, type: 'Usuario' | 'Sistema' | string, message: string, } // RESPUESTAS export type ResponseObjectOrErrorType = { }<file_sep>import mongoose from 'mongoose'; const orderCollection = 'orders' const OrderSchema = new mongoose.Schema({ userId: { type: String, required: true }, items: [ { productId: { type: String, required: true }, cantidad: { type: Number, required: true }, precio: { type: Number, required: true}, } ], timestamp: { type: Date, default: Date.now }, direccion: { calle: { type: String, required: true }, altura: { type: String, required: true }, codigoPostal: { type: String, required: true }, piso: { type: String }, departamento: { type: String }, }, estado: { type: String }, totalOrder: { type: Number, required: true }, }) export const orderModel = mongoose.model(orderCollection, OrderSchema)<file_sep>import winston from 'winston'; const logConf = { transports: [ new winston.transports.File({ level: 'error', filename:'./ts/logs/error.log' }), new winston.transports.File({ level: 'warn', filename:'./ts/logs/warn.log' }), new winston.transports.Console({ level: 'info' }) ] } const logger = winston.createLogger(logConf) export { logger, } <file_sep>import express from "express"; import compression from 'compression'; import mainRouter from "../routes/index"; import session from 'express-session'; import cookieParser from "cookie-parser"; import path = require("path"); import { inicializarPassport, sessionPassport } from "../config/passport.config"; import { sessionConfig } from "../config/session.config"; import { logger } from "../config/winston.config"; import controllerSocket from "../controller/socket.controller"; const cors = require('cors') const config = require('../config/config') const app = express(); const http = require("http").Server(app); export const io = require("socket.io")(http); app.use(cors()); app.use(compression()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cookieParser()) app.use(session(sessionConfig)) app.use(inicializarPassport); app.use(sessionPassport); app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "/views")); app.use(express.static('public')) app.get('/', (req, res) => { res.render('pages/index') }) app.use('/', mainRouter) io.on('connection', controllerSocket) declare module "express-session" { interface Session { user: string; } } const PORT = config.PORT; const server = http.listen(PORT, () => { logger.info(`El servidor se encuentra en el puerto: ${PORT}`) }); server.on('error', (error: any) => logger.error(`Error en el servidor ${error}`))<file_sep>import { Router } from "express"; const carritoController = require('../controller/carrito.controller') let routerCarrito = Router(); // Rutas para Carrito class RouterCarrito { controladorCarrito: any; constructor() { this.controladorCarrito = carritoController; } start() { routerCarrito.get("/cart/:carrito_id", carritoController.getOne); routerCarrito.post("/cart/add/:carrito_id",carritoController.add); routerCarrito.post("/cart/delete/:carrito_id",carritoController.delete); routerCarrito.post("/cart/submit/:carrito_id",carritoController.submit); return routerCarrito } } export default RouterCarrito;<file_sep>import { Request, Response } from 'express'; import { transporterEthereal, transporterGmail } from '../service/mail'; const enviarMailEthereal = (asunto: string, username?: any) => { const hoy = new Date(); const fechaDeHoy = hoy.toDateString(); const horaDelEvento = hoy.getHours() + ':' + hoy.getMinutes() + ':' + hoy.getSeconds(); transporterEthereal.sendMail({ from: 'Servidor Node.js', to: '<EMAIL>', subject: `Operacion ${asunto}`, html: `<h1>Usuario: ${username}</h1><br><h1>Fecha de hoy: ${fechaDeHoy}</h1><br><h1>Hora del evento: ${horaDelEvento}</h1>` }, (err, info) => { if (err) { console.log(err) return err } console.log(info) }) } const enviarMailGmail = (asunto:string, email: string, photo: any) => { transporterGmail.sendMail({ from: 'Servidor Node.js', to: email, subject: `Operacion ${asunto}`, html: `<h1>Foto de perfil: ${photo}</h1>`, // attachments: [ // { // path: photo // } // ] }, (err, info) => { if (err) { console.log(err) return err } console.log(info) }) } module.exports = { login: (req: Request, res: Response) => { res.json({ message: 'You made it to the secure route', user: req.user, token: req.query.secret_token }) } }<file_sep>export class Producto { id:string; timestamp: number; nombre: string; descripcion: string; codigo: number; foto: string; precio: number; stock: number; constructor(nuevoId: string ,nuevoNombre: string, nuevoDescripcion: string,nuevoCodigo: number,nuevoFoto: string,nuevoPrecio: number,nuevoStock: number) { this.id = nuevoId; this.timestamp = Date.now(); this.nombre = nuevoNombre; this.descripcion = nuevoDescripcion; this.codigo = nuevoCodigo; this.foto = nuevoFoto; this.precio = nuevoPrecio; this.stock = nuevoStock; } } export class Productos { private productos: Array<Producto>; constructor() { this.productos = [] } listar () { return this.productos } buscar (id:string) { return this.productos.find( produ => produ.id === id) } agregar (nuevoProducto: Producto) { return this.productos.push(nuevoProducto) } actualizar(productoActualizar:Producto){ this.productos.map(produ => { if(produ.id === productoActualizar.id) { (productoActualizar.nombre !== undefined) ? produ.nombre = productoActualizar.nombre : produ.nombre = produ.nombre; (productoActualizar.descripcion !== undefined) ? produ.descripcion = productoActualizar.descripcion : produ.descripcion = produ.descripcion; (productoActualizar.codigo !== undefined) ? produ.codigo = productoActualizar.codigo : produ.codigo = produ.codigo; (productoActualizar.foto !== undefined) ? produ.foto = productoActualizar.foto : produ.foto = produ.foto; (productoActualizar.stock !== undefined) ? produ.stock = productoActualizar.stock : produ.stock = produ.stock; } }) return productoActualizar } eliminar (id: string) { this.productos = this.productos.filter( produ => produ.id !== id) return this.productos } } export class Carrito { private id: string; private timestap: number; private productos: Productos; constructor(nuevoId: string, nuevoProductos: Productos){ this.id = nuevoId; this.timestap = Date.now(); this.productos = nuevoProductos; } listar_productos () { return this.productos } agregar_producto (nuevoProducto: Producto) { return this.productos.agregar(nuevoProducto) } eliminar_producto (id: string) { return this.productos.eliminar(id) } } export class Errores { error: string; descripcion: string; constructor(error: string ,descripcion: string){ this.error = error; this.descripcion = descripcion; } } export class Mensaje{ mail:string; nombre:string; apellido:string; edad:number; alias:string; avatar:string; dateandhour:string; message:string; constructor( nuevoMail: string , nuevoNombre: string , nuevoApellido: string , nuevoEdad: number , nuevoAlias: string , nuevoAvatar: string , nuevoDateandhour: string , nuevoMessage: string ) { this.mail = nuevoMail; this.nombre = nuevoNombre; this.apellido = nuevoApellido; this.edad = nuevoEdad; this.alias = nuevoAlias; this.avatar = nuevoAvatar; this.dateandhour = nuevoDateandhour; this.message = nuevoMessage; } } export interface MensajeJSON { id: any; author: { id: any; nombre: string; apellido: string; edad: number; alias: string; avatar: string; }; text: string; } export class Usuario { administrador: boolean; constructor(valor: boolean) { this.administrador = valor } }<file_sep>import mongoose, { Document } from 'mongoose'; import bcrypt from 'bcrypt'; import { composeWithMongoose } from 'graphql-compose-mongoose' const Schema = mongoose.Schema; export interface UserDoc extends Document { email: string, password: string, nombreCompleto: string, celular: string, admin: boolean } const UserSchema = new Schema<UserDoc>({ email: { type: String, required: true, unique: true }, password: { type: String, required: true }, nombreCompleto: { type: String, required: true }, celular: { type: String, required: true }, admin: { type: Boolean, } }); UserSchema.pre<UserDoc>( 'save', async function (next: any) { const user = this; const hash = await bcrypt.hash(user.password, 10); this.password = <PASSWORD>; next(); } ); UserSchema.methods.isValidPassword = async function (password: any) { const user = this; const compare = await bcrypt.compare(password, user.password); return compare; } const UserModel = mongoose.model('user', UserSchema); export const UserTC = composeWithMongoose(UserModel); module.exports = UserModel; <file_sep>const dotenv = require('dotenv'); const path = require('path'); const { persistencia, puerto } = require('minimist')(process.argv.slice(2)); dotenv.config({ path: path.resolve(process.env.NODE_ENV + '.env') }) module.exports = { NODE_ENV: process.env.NODE_ENV || 'development', HOST: process.env.HOST || 'localhost', PORT: puerto || process.env.PORT || 8080, PERSISTENCIA: persistencia || process.env.PERSISTENCIA, MONGO_URL: process.env.MONGO_URL, MONGO_SECRET_KEY: process.env.MONGO_SECRET_KEY, FACEBOOK_CLIENT_ID: process.env.FACEBOOK_CLIENT_ID, FACEBOOK_CLIENT_SECRET: process.env.FACEBOOK_CLIENT_SECRET, MAIL_ETHEREAL: process.env.MAIL_ETHEREAL, MAIL_ETHEREAL_PASSWORD: <PASSWORD>, MAIL_GMAIL: process.env.MAIL_GMAIL, MAIL_GMAIL_PASSWORD: <PASSWORD>, TWILIO_ACCOUNT_SID: process.env.TWILIO_ACCOUNT_SID, TWILIO_AUTHTOKEN: process.env.TWILIO_AUTHTOKEN, TWILIO_FROM: process.env.TWILIO_FROM, TWILIO_TO: process.env.TWILIO_TO, USER_EMAIL: process.env.USER_EMAIL, USER_PASSWORD: <PASSWORD> }<file_sep>import multer from "multer"; import { GridFsStorage } from "multer-gridfs-storage"; const storage = new GridFsStorage({ url: 'x', options: { useNewUrlParser: true, useUnifiedTopology: true }, file: (req: any, file: any) => { const match = ["image/png", "image/jpeg"]; if (match.indexOf(file.mimetype) === -1) { const filename = `${Date.now()}-any-name-${file.originalname}`; return filename; } return { bucketName: "photos", filename: `${Date.now()}-any-name-${file.originalname}`, }; } }) module.exports = multer({ storage })<file_sep>import nodemailer from 'nodemailer'; const config = require('../config/config') const transporterEthereal = nodemailer.createTransport({ host: 'smtp.ethereal.email', port: 587, auth: { user: config.MAIL_ETHEREAL, pass: config.MAIL_ETHEREAL_PASSWORD } }); const transporterGmail = nodemailer.createTransport({ service: 'gmail', auth: { user: config.MAIL_GMAIL, pass: config.MAIL_GMAIL_PASSWORD } }); const enviarMailEthereal = ({ a, asunto, html}: any) => { transporterEthereal.sendMail({ from: 'Servidor APP_BE', to: a, subject: asunto, html: html }, (err, info) => { if (err) { console.log(err) return err } console.log(info) }) } export { transporterEthereal, transporterGmail, enviarMailEthereal }<file_sep>const request = require('supertest')('http://localhost:8080') const expect = require('chai').expect; let authToken; let productoAEliminar = []; describe('Test API Rest-Full', () => { before(async () => { const responseToken = await request.post('/login').send({ email: '<EMAIL>', password: '<PASSWORD>' }) expect(responseToken.status).to.eql(200) expect(responseToken.body).to.include.keys('token') authToken = `Bearer ${responseToken.body.token}` }) after(() => { productoAEliminar.forEach(async (id) => { const responseEliminarProducto = await request.delete(`/api/productos/${id}`).set('Authorization', authToken) expect(responseEliminarProducto.status).to.eql(200) }); }) it('Trae todos los productos', async () => { const responseProductos = await request.get('/api/productos').set('Authorization', authToken) expect(responseProductos.status).to.eql(200) }) it('Agregar Producto', async () => { /* Creo el Producto */ const responseCrearProducto = await request.post('/api/productos').set('Authorization', authToken).send({ nombre: 'Tomate que va a ser eliminado despues', descripcion: 'Es una verdura', codigo: 10, foto: 'URL', precio: 30, stock: 100 }) expect(responseCrearProducto.status).to.eql(200) const productoCreado = responseCrearProducto.body expect(productoCreado).to.include.keys('_id', 'nombre', 'descripcion', 'codigo', 'foto', 'precio', 'stock') productoAEliminar.push(responseCrearProducto.body._id) }) it('Modificar 1 Producto', async () => { /* Creo el Producto */ const responseCrearProductoAModificar = await request.post('/api/productos').set('Authorization', authToken).send({ nombre: 'Tomate que va a Modificadodespues', descripcion: 'Es una verdura', codigo: 10, foto: 'URL', precio: 30, stock: 100 }) expect(responseCrearProductoAModificar.status).to.eql(200) const productoCreado = responseCrearProductoAModificar.body expect(productoCreado).to.include.keys('_id', 'nombre', 'descripcion', 'codigo', 'foto', 'precio', 'stock') productoAEliminar.push(responseCrearProductoAModificar.body._id) /* Modificar Producto */ const responseModificarProducto = await request.put(`/api/productos/${responseCrearProductoAModificar.body._id}`).set('Authorization', authToken).send({ nombre: '<NAME> :)', descripcion: 'Es un verdura modificada', precio: 40, }) expect(responseModificarProducto.status).to.eql(200) const productoModificado = responseModificarProducto.body expect(productoModificado).to.include.keys('_id', 'nombre', 'descripcion', 'codigo', 'foto', 'precio', 'stock') }) })<file_sep>import mongoose from 'mongoose'; const carritoCollection = 'carrito' const CarritoSchema = new mongoose.Schema({ userId: { type: String }, productos: [ { productoId: { type: String }, cantidad: { type: Number }, precio: { type: Number }, } ], timestamp: { type: Date, default: Date.now }, direccion: { calle: { type: String, required: true }, altura: { type: String, required: true }, codigoPostal: { type: String, required: true }, piso: { type: String }, departamento: { type: String }, } }) export const carritoModel = mongoose.model(carritoCollection, CarritoSchema)<file_sep>import { Router } from "express"; import passport from "passport"; const productosController = require('../controller/productos.controller') let routerProductos = Router(); // Rutas para Productos class RouterProductos { controladorProductos: any; constructor() { this.controladorProductos = productosController; } start() { routerProductos.get('/productos', this.controladorProductos.getAll) // routerProductos.get('/productos/:producto_id', this.controladorProductos.getOne) routerProductos.get('/productos/:category', this.controladorProductos.getAll) routerProductos.post('/productos', this.controladorProductos.create) routerProductos.put('/productos/:producto_id', this.controladorProductos.update) routerProductos.delete('/productos/:producto_id', this.controladorProductos.delete) return routerProductos } } export default RouterProductos;<file_sep>import MongoStore from "connect-mongo"; const config = require('../config/config') export const sessionConfig = { store: MongoStore.create({ mongoUrl: config.MONGO_URL, mongoOptions: { useNewUrlParser: true, useUnifiedTopology: true }, ttl: 600 }), secret: config.MONGO_SECRET_KEY || '', resave: false, saveUninitialized: false, rolling:false, cookie: { maxAge:60000 } }<file_sep>import { Request, Response } from 'express'; import { enviarMailEthereal } from '../service/mail'; import model from '../db/index.db' module.exports = { getAllOrders: async (req: Request, res: Response) => { const orders: any = await model?.traerOrdenesByUserId(req.params.user_id); if (orders.errorType) { res.status(400).json({ message: 'No existen ordenes para ese usuario' }); } else { res.status(200).json(orders) } }, getOne: async (req: Request, res: Response) => { const order: any = await model?.traerOrdenesById(req.params.order_id); if (order.errorType) { res.status(400).json({ message: `No existe orden con ID: ${req.params.order_id}` }); } else { res.status(200).json(order) } }, completeOrder: async (req: Request, res: Response) => { const { orderId } = req.body; const orderComplete: any = await model?.traerOrdenesById(orderId); if (orderComplete.errorType) { res.status(400).json({ message: `No existe la Orden con ID: ${orderId}` }); } else { if (orderComplete.estado !== 'Generada') { res.status(400).json({ message: `No existe la Orden con ID: ${orderId}` }); } else { const ordenModificada = await model?.modificarOrden(orderId) const datosUsuario: any = await model?.traerUserById(orderComplete.userId) const mail = { a: datosUsuario.email, asunto: 'Orden Completada', html: ` <h1>¡Hola ${datosUsuario.nombreCompleto}!</h1><br> <div> <h3>Tu orden fue completada con exito!</h3><br> </div><br> ` } enviarMailEthereal(mail) res.status(200).json(ordenModificada) } } }, }<file_sep>import { Request, Response } from 'express'; import { mensaje_error, usuario } from "../routes/constantes"; import { logger } from '../config/winston.config'; import model from '../db/index.db' module.exports = { getAll: async (req: Request, res: Response) => { if (req.params.category) { const productos = await model?.traerProductosPorCategoria(req.params.category); if (productos) { res.json(productos) } else { res.status(400).json({ message: `Hubo un error en base` }); } } else { const productos = await model?.traerProductos() if (productos) { res.json(productos) } else { res.status(400).json({ message: `Hubo un error en base` }); } } }, create: async (req: Request, res: Response) => { //Agregar un producto al listado if (usuario.administrador) { if ( req.body.nombre === undefined || req.body.descripcion === undefined || req.body.categoria === undefined || req.body.precio === undefined || req.body.stock === undefined || req.body.foto === undefined ) { res.status(400).json({ message: "Hay inconsistencias en el Producto", }); } else { const productoCreado = await model?.agregarProducto(req.body) if (productoCreado) { res.sendStatus(201) } else { res.status(403).json({ message: "Hubo error al crear el Producto", }); } } } else { res.status(403).json({ message: "Acceso denegado , Se necesita rol Administrador", }); } }, update: async (req: Request, res: Response) => { // Actualiza un producto por su id if (usuario.administrador) { const id = req.params.producto_id; const update = req.body; const producto: any = await model?.actualizarProducto(id, update) try { const productoActualizado = await model?.traerProducto(producto.id) if (productoActualizado) { res.sendStatus(200) } else { res.status(400).json({ message: "Hubo error al actualizar el Producto", }); } } catch (error: any) { res.status(400).json({ message: "Hay ciertas inconsistencias en el producto a actualizar", }); } } else { res.status(403).json({ message: "Acceso denegado , Se necesita rol Administrador", }); } }, delete: async (req: Request, res: Response) => { // Elimina un producto por su id if (usuario.administrador) { const productoEliminado = await model?.eliminarProducto(req.params.producto_id); if (productoEliminado) { res.sendStatus(200) } else { res.status(400).json({ message: "No se pudo eliminar el producto", }); } } else { res.status(403).json({ message: "Acceso denegado , Se necesita rol Administrador", }); } } }<file_sep>import mongoose from 'mongoose'; const messageCollection = 'message' const MessageSchema = new mongoose.Schema({ userId: { type: String, required: true}, type: { type: String, required: true}, message: { type: String, required: true} }) export const messageModel = mongoose.model(messageCollection, MessageSchema)<file_sep>import { Request, Response } from 'express'; let gfs; module.exports = { create: async (req: Request, res: Response) => { //Agregar una imagen y actualizar producto id }, getOne: async (req: Request, res: Response) => { // Retornar la imagen x id try { const file = await gfs.files.findOne({ filename: req.params.id }); const readStream = gfs.createReadStream(file.filename); readStream.pipe(res); } catch (error) { res.send("not found"); } }, delete: async (req: Request, res: Response) => { // Elimina una imagen por su id try { await gfs.files.deleteOne({ filename: req.params.id }); res.send("success"); } catch (error) { console.log(error); res.send("An error occured."); } } }<file_sep># Proyecto Final <NAME> # Endpoints: ## Login y SignUp METHOD: POST URL: /api/user/signup BODY: { "email": string, "password": string, "passwordConfirm": string, "nombreCompleto": string, "celular": string, "direccion": { "calle": string, "altura": string, "codigoPostal": string, "piso": string, "departamento": string } } METHOD: POST URL: /api/user/login BODY: { "email": string, "password": string, } RETURN : { "token": string } # Productos METHOD: GET URL: /api/productos BODY: {} METHOD: GET URL: /api/productos/:category BODY: {} METHOD: POST URL: /api/productos BODY: { "nombre": string, "descripcion": string, "categoria": string, "precio": number, "stock": number, "url": string, } METHOD: PUT URL: /api/productos/:producto_id BODY: Alguna de estas props { "nombre": string, "descripcion": string, "categoria": string, "precio": number, "stock": number, "url": string, } METHOD: DELETE URL: /api/productos/:producto_id BODY: {} ## Carrito METHOD: GET AUTH: Bearer Token URL: /api/cart/:carrito_id BODY: {} METHOD: POST AUTH: Bearer Token URL: /api/cart/add/:carrito_id BODY: { "productoId": string, "cantidad": number, } METHOD: POST AUTH: Bearer Token URL: /api/cart/delete/:carrito_id BODY: { "productoId": string, "cantidad": number, } METHOD: POST AUTH: Bearer Token URL: /api/cart/submit/:carrito_id BODY: {} ## Ordenes METHOD: GET AUTH: Bearer Token URL: /api/orders/:user_id BODY: {} METHOD: GET AUTH: Bearer Token URL: /api/orders/:order_id BODY: {} METHOD: POST AUTH: Bearer Token URL: /api/orders/complete BODY: { "orderId": string } ## CHAT Esta implementado en / ## .ENV NODE_ENV= HOST= PORT= PERSISTENCIA= MONGO_URL= MONGO_SECRET_KEY= FACEBOOK_CLIENT_ID= FACEBOOK_CLIENT_SECRET= MAIL_ETHEREAL= MAIL_ETHEREAL_PASSWORD= MAIL_GMAIL= MAIL_GMAIL_PASSWORD= TWILIO_ACCOUNT_SID= TWILIO_AUTHTOKEN= TWILIO_FROM= TWILIO_TO= <file_sep>import { Request, Response, NextFunction } from 'express'; import { logger } from '../config/winston.config'; import model from '../db/index.db'; const passport = require('passport'); const jwt = require('jsonwebtoken'); import { transporterEthereal, transporterGmail } from '../service/mail'; const enviarMailEthereal = (asunto: string, user: any) => { const hoy = new Date(); const fechaDeHoy = hoy.toDateString(); const horaDelEvento = hoy.getHours() + ':' + hoy.getMinutes() + ':' + hoy.getSeconds(); transporterEthereal.sendMail({ from: 'Servidor Node.js', to: '<EMAIL>', subject: `Operacion ${asunto}`, html: ` <h1>Nombre Completo: ${user.nombreCompleto}<br> Usuario: ${user.email}<br> Direccion: ${user.direccion}<br> Edad: ${user.edad}<br> Celular: ${user.celular}<br> Foto: ${user.foto}</h1><br> <h1>Fecha de hoy: ${fechaDeHoy}</h1><br> <h1>Hora del evento: ${horaDelEvento}</h1> ` }, (err, info) => { if (err) { logger.error(err) return err } console.log(info) }) } const signup = async (req: Request, res: Response, next: NextFunction) => { const { email, direccion } = req.body; console.log(req.body) const user = await model?.traerUser(email); const carritoCreated = await model?.crearCarrito(user, direccion) if ( user && carritoCreated ) { return res.status(201).json(user); } } const login = async (req: Request, res: Response, next: NextFunction) => { passport.authenticate('login', async (err: any, user: any, info: any) => { try { if (err) { const error = new Error('An error occurred.'); return next(error); } if (!user && info) { return res.status(401).json({ message: info.message }); } req.login( user, { session: false }, async (error: any) => { if (error) return next(error); const body = { _id: user._id, email: user.email }; const token = jwt.sign({ user: body }, 'TOP_SECRET'); return res.json({ token, user: body }); } ); } catch (error) { logger.error(error) return next(error); } } )(req, res, next); }; const logout = async (req: Request, res: Response, next: NextFunction) => { req.logout() res.json({ message: 'Te deslogueaste' }) } const getProfile = async (req: Request, res: Response, next: NextFunction) => { res.json({ message: 'You made it to the secure route', user: req.user, token: req.query.secret_token }) } const loginFacebook = async (req: Request, res: Response, next: NextFunction) => { res.json({ message: 'You made it to the secure route', user: req.user, token: req.query.secret_token }) } module.exports = { login, signup, logout, getProfile, loginFacebook, };<file_sep>import { denormalize, normalize, schema } from "normalizr"; import { MensajeJSON } from "../routes/objetos"; const authors = new schema.Entity('authors') const mensaje = new schema.Entity('mensajes', { author: authors }) export const normalizar = (mensajes: any) => { let arrayMensajes: MensajeJSON[] = []; mensajes.forEach((elementos: any) => { let men: MensajeJSON = { id: elementos._id, author: { id: elementos.mail, nombre: elementos.nombre, apellido: elementos.apellido, edad: elementos.edad, alias: elementos.alias, avatar: elementos.avatar }, text: elementos.message } arrayMensajes.push(men) }); const mensajesNormalizados = normalize(arrayMensajes, [mensaje]) return mensajesNormalizados } export const desnormalizar = (mensajesNormalizados: any) => { console.log(mensajesNormalizados.result[0]) const mensajesDesNormalizados = denormalize(mensajesNormalizados.result[0], [mensaje], mensajesNormalizados.entities) console.log(mensajesDesNormalizados) return mensajesDesNormalizados }<file_sep>import { Router } from "express"; import passport from "passport"; const { login, signup, getProfile, logout, loginFacebook } = require('../controller/login'); let routerSession = Router(); routerSession.post("/user/signup", passport.authenticate('signup', { session: false }), signup); routerSession.post("/user/login", login); routerSession.post("/user/logout", logout); // LOGIN CON FACEBOOK routerSession.get("/auth/facebook", passport.authenticate('facebook')); routerSession.get("/auth/facebook/callback", passport.authenticate('facebook', { failureRedirect: '/login' }), loginFacebook); export default routerSession;<file_sep>import persistenciaMemory from './factory/memory' import persistenciaFileSystem from './factory/fileSystem' import persistenciaMongo from "./factory/mongoDB" const config = require('../config/config') /* -------------------------------------- */ /* FACTORY */ /* -------------------------------------- */ class FactoryPersonaModel { static set(opcion: string) { console.log('**** PERSISTENCIA SELECCIONADA **** [' + opcion + ']') switch(opcion) { case 'Mem': return new persistenciaMemory() case 'File': return new persistenciaFileSystem() case 'Mongo': return new persistenciaMongo() } } } const opcion = config.PERSISTENCIA || 'Mongo' export default FactoryPersonaModel.set(opcion)<file_sep>import { Carrito, Errores, Productos, Usuario } from "./objetos"; import { v4 as uuidv4 } from "uuid"; export const listaProductos = new Productos(); export const listaPCarrito = new Productos(); export let mensaje_error = new Errores("", ""); export const carrito = new Carrito(uuidv4(), listaPCarrito); export const usuario = new Usuario(true); export function fechayhora() { const hoy = new Date(); const fecha = hoy.getDate() + "/" + (hoy.getMonth() + 1) + "/" + hoy.getFullYear(); const hora = hoy.getHours() + ":" + hoy.getMinutes() + ":" + hoy.getSeconds(); const fyh = fecha + " " + hora; return fyh; }<file_sep>import mongoose from 'mongoose'; const userFacebookCollection = 'userFacebook' const UserFacebookSchema = new mongoose.Schema({ username: { type: String }, password: { type: String }, facebookId: { type: String }, email: {type: String}, photo: {type: Object}, }) export const userFacebookModel = mongoose.model(userFacebookCollection, UserFacebookSchema)
da613a4fc36c2f77dfd6c9c78483ea61b5132e18
[ "JavaScript", "TypeScript", "Markdown" ]
38
TypeScript
colomarina/app_be
2bd866261ca56e079980ec1be1afb665c3781af9
0d9365d78733cfc857b20a293fccac625edd24e1
refs/heads/main
<repo_name>QNimbus/homeassistant-config<file_sep>/README.md # Home Assistant Configuration <!-- omit in toc --> [![GitHub](https://img.shields.io/github/license/QNimbus/homeassistant-config?style=for-the-badge)](LICENSE) ![Maintenance](https://img.shields.io/maintenance/yes/2020?style=for-the-badge) ![GitHub last commit](https://img.shields.io/github/last-commit/QNimbus/homeassistant-config?style=for-the-badge) ![GitHub commit activity](https://img.shields.io/github/commit-activity/m/QNimbus/homeassistant-config?style=for-the-badge) [![HA Version](https://img.shields.io/static/v1?label=HA%20current%20version&message=2020.12.0&color=%23007ec6&style=for-the-badge)](https://github.com/home-assistant/home-assistant/releases/latest) [![HA Version](https://img.shields.io/static/v1?label=HA%20initial%20version&message=0.116.0&color=%239f9f9f&style=for-the-badge)](https://github.com/home-assistant/core/releases/0.116.0) - [Installation](#installation) - [Integrations](#integrations) - [ZWave](#zwave) - [To do](#to-do) - [Useful links](#useful-links) - [License](#license) ## Installation After the installation and boot up of the Home Assistant machine, open a browser and navigate to [http://homeassistant.local:8123](http://homeassistant.local:8123). If HA is unreachable check if any of the other NIC's on the HA machine are reachable (using the respective ip address of the NIC). When opening the Home Assistant interface in the browser for the first time you will need to create a new user as part of the onboarding process. When the onboarding process is finished proceed to your [`profile`](http://homeassistant.local:8123/profile). In your profile make sure you enable `Advanced Mode`. This enables the installation of advanced add-ons that would otherwise be unavailable. ### SSH Go to the [`Supervisor >> Add-on store`](http://homeassistant.local:8123/hassio/store) and install the `SSH & Web Terminal` community add-on. Next, modify the add-on configuration to allow loging in with a password and/or private key authentication. ``` ssh: username: hassio password: '<<PASSWORD>>' authorized_keys: - >- ssh-rsa <YOUR_PRIVATE_KEY_HERE> homeassistant sftp: false compatibility_mode: false allow_agent_forwarding: false allow_remote_port_forwarding: false allow_tcp_forwarding: false zsh: true share_sessions: false packages: [] init_commands: [] ``` When done editing the configuration do not forget to start the SSH server on the add-on page. ### Network setup *Note: For reference see [Using nmcli to set a static IPv4 address](https://github.com/home-assistant/operating-system/blob/dev/Documentation/network.md#using-nmcli-to-set-a-static-ipv4-address)* Login to the HASS.io terminal using SSH (as setup in the previous section). View the current network interfaces and their configuration. Configure the network interfaces as appropriate. ```bash $ nmcli con show NAME UUID TYPE DEVICE HassOS default 2d06fa94-0ff0-11eb-adc1-0242ac120002 ethernet enp2s3 $ nmcli enp2s3: connected to HassOS default "enp2s3" ethernet (e1000), DE:AD:BE:EF:00:01, hw, mtu 1500 ip4 default inet4 10.30.99.6/16 route4 0.0.0.0/0 route4 10.30.0.0/16 inet6 fe80::ec15:9bd6:eb48:d87c/64 route6 fe80::/64 route6 ff00::/8 enp2s1: disconnected "enp2s1" 1 connection available ethernet (e1000), DE:AD:BE:EF:00:02, hw, mtu 1500 enp2s2: disconnected "enp2s2" 1 connection available ethernet (e1000), DE:AD:BE:EF:00:03, hw, mtu 1500 docker0: unmanaged "docker0" bridge, DE:AD:BE:EF:00:04, sw, mtu 1500 hassio: unmanaged "hassio" bridge, DE:AD:BE:EF:00:05, sw, mtu 1500 ``` To rename existing connection: `$ nmcli connection modify "HassOS default" connection.id "IOT"` To add a new interface/connection: `$ nmcli con add type ethernet con-name "HassOS default" ifname enp2s1` ### Samba Go to the [`Supervisor >> Add-on store`](http://homeassistant.local:8123/hassio/store) and install the `Samba share` add-on from the official repository. ### AppDaemon Go to the [`Supervisor >> Add-on store`](http://homeassistant.local:8123/hassio/store) and install the `AppDaemon` add-on from the community repository. ### Clone config repository Prior to cloning the config repository, ensure that HA core is stopped. `$ ha core stop` Clone this [repository](https://github.com/QNimbus/homeassistant-config.git) in the config folder. - copy `secrets.example.yaml` to `secrets.yaml` and edit all the dummy values. - copy/install SSL certificates in the `/ssl` folder. - add the required `person` entities via the GUI. [`Configuration`](http://homeassistant.local:8123/config/person) *\** - install [HACS](https://hacs.xyz/docs/installation/manual). - install HACS integration [in the integrations config view](http://homeassistant.local:8123/config/integrations) - get a [GitHub access token](https://github.com/settings/tokens) to use with HACS. *\* Note: You can add profile images to the person profile via the GUI or via the YAML config in `customize/entities/person.<person_name>.yaml`* Finally, restart the HA core. `$ ha core start` ## Integrations Most integrations can be configured using YAML files. However some integration are exclusively configured through to web UI. A list of integrations that need to be installed and configured through the web UI: - [Netatmo integration](https://www.home-assistant.io/integrations/netatmo/) - [Ubiquiti UniFi integration](https://www.home-assistant.io/integrations/unifi/) - [Plugwise integration](https://www.home-assistant.io/integrations/plugwise/) - [SONOS integration](https://www.home-assistant.io/integrations/sonos/) - [ZWave integration](https://www.home-assistant.io/integrations/zwave/) ## ZWave Renaming the default discovered device names (not entity names, I'm referring to the device names specifically) allows for better organisation of the ZWave network in HA. - Ensure tha HA ZWave binding has correctly started the ZWave network previously and saved it's configuration to `zwcfg_0xe12deadbeaf.xml` - Make a backup copy of the config file. e.g. `zwcfg_0xe12deadbeaf.xml.bak` - Install the OZWCP add-on ([`Supervisor >> Add-on store`](http://homeassistant.local:8123/hassio/store)) - Start the OZWCP add-on (this shuts down the HA core container on HASS.io) - Navigate to http://homeassistant.local:8090 (may take up to 2 minutes to start) - Start network discovery for your device. (e.g. `/dev/ttyACM0`) - Rename your ZWave devices as required. - When finished make sure to save your changes and verify last modified date of `zwcfg_0xe12deadbeaf.xml` file. *Note: For reference see [ZWave in Home Assistant](#zwave-in-home-assistant)* ## To do - [x] Add ZWave-to-MQTT via standalone device (e.g. Raspberry Pi 3+) ## Useful links #### ZWave in Home Assistant - [How to add ZWave devices in Home Assistant (community forum post)](https://community.home-assistant.io/t/aeon-labs-z-wave-door-window-sensor/403/27) #### Reference - [List of Home Assistant builtin icons](https://gist.github.com/QNimbus/5fb74d8ab5b68db3731f06eefedda3f7) - [Awesome Home Assistant](https://www.awesome-ha.com/) - [Home Assistant cookbook](https://www.home-assistant.io/cookbook/) - [Home Assistant cheatsheet](https://github.com/arsaboo/homeassistant-config/blob/master/HASS%20Cheatsheet.md) #### Add-ons & tools - [HACS - Home Assistant Community Store](https://hacs.xyz/) - [lovelace card-mod](https://github.com/thomasloven/lovelace-card-mod) ## License [MIT](LICENSE) <file_sep>/integrations/defaults/README.md # Defaults Home Assistant defaults from default integration meta-component See: [home-assistant.io/integrations/default_config](https://www.home-assistant.io/integrations/default_config/) <file_sep>/lovelace/README.md # Lovelace views This directory contains the different Lovelace UI views for my configuration `note: Until now I haven't found a way to leverage the use of YAML anchors so that I can keep them in 1 single file, separate from the view files to prevent duplication. You will see the anchors defined in all the view files to prevent duplication within each of the files. However as it stands every view file will have to have the anchors defined within the scope of it's YAML document. <file_sep>/gitupdate.sh #!/bin/bash set -e # Check HA configuration ha core check # Get number of files added to the index (but uncommitted) FILES_STAGED=$(git status --porcelain 2>/dev/null| egrep "^A|^M" | wc -l) if [ $FILES_STAGED -eq 0 ]; then echo "Adding all modified files to staging area" git add . fi git status echo -n "Change description [minor update]: " read CHANGE_MSG CHANGE_MSG=${CHANGE_MSG:-"minor update"} git commit -m "${CHANGE_MSG}" git push github main exit
38118c432ef475c37ac98f79d0e1c75e1098d126
[ "Markdown", "Shell" ]
4
Markdown
QNimbus/homeassistant-config
5527b7c412b684598ca427bfbcc39db330394cf4
ebb7781608066d311ffaaff326cb3f2b4359db4f
refs/heads/master
<repo_name>qtoncoding/WinWearUWP<file_sep>/BackgroundTaskWM/NotificationBackgroundTask.cs using BluetoothGattServer; using Common; using System.Diagnostics; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Phone.Notification.Management; namespace BackgroundTaskWM { public sealed class NotificationBackgroundTask : IBackgroundTask { BackgroundTaskDeferral _deferral; public async void Run(IBackgroundTaskInstance taskInstance) { _deferral = taskInstance.GetDeferral(); await sendNotification(); _deferral.Complete(); } private async Task sendNotification() { var triggerDetail = AccessoryManager.GetNextTriggerDetails(); if (triggerDetail.AccessoryNotificationType == AccessoryNotificationType.Toast) { var trigger = (ToastNotificationTriggerDetails)triggerDetail; var notification = new Notification() { AppName = trigger.AppDisplayName, Text = trigger.Text1 }; // TODO(Thai): This needs to be marshalled somehow var server = GattServer.Instance; await server.AddNotification(notification); } } } } <file_sep>/BluetoothGattServer/GattServer.cs using Common; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Devices.Bluetooth.GenericAttributeProfile; using Windows.Storage.Streams; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; namespace BluetoothGattServer { public sealed class GattServer { private static Guid serviceGuid = new Guid("80E56F09-783E-4949-B12F-CDCC898FA561"); public static Guid ServiceGuid { get { return serviceGuid; } } private static Guid characteristicGuid = new Guid("4F8D16CD-770E-4EC8-9500-37C745B1EE85"); public static Guid NotificationCharacteristicGuid { get { return characteristicGuid; } } private GattServiceProvider serviceProvider; private static GattServer instance; private GattLocalCharacteristic notificationCharacteristic; private List<GattSubscribedClient> subscribedClients = new List<GattSubscribedClient>(); public static GattServer Instance { get { return instance; } set { instance = value; } } private GattServer(GattServiceProvider serviceProvider, GattLocalCharacteristic characteristic) { this.serviceProvider = serviceProvider; this.notificationCharacteristic = characteristic; notificationCharacteristic.SubscribedClientsChanged += notificationCharacteristic_SubscribedClientsChanged; } public static async Task<GattServer> InitServer() { var result = await GattServiceProvider.CreateAsync(GattServer.ServiceGuid); if (result.Error == Windows.Devices.Bluetooth.BluetoothError.Success) { var serviceProvider = result.ServiceProvider; GattLocalCharacteristicParameters param = new GattLocalCharacteristicParameters() { UserDescription = "Current Notification", ReadProtectionLevel = GattProtectionLevel.Plain, WriteProtectionLevel = GattProtectionLevel.EncryptionAndAuthenticationRequired, CharacteristicProperties = GattCharacteristicProperties.Notify }; var characteristicResult = await serviceProvider.Service.CreateCharacteristicAsync(GattServer.NotificationCharacteristicGuid, param); if (characteristicResult.Error == Windows.Devices.Bluetooth.BluetoothError.Success) { var notificationCharacteristic = characteristicResult.Characteristic; return new GattServer(serviceProvider, notificationCharacteristic); } else { throw new PlatformNotSupportedException("Cannot create characteristic"); } } else { throw new PlatformNotSupportedException("Cannot create bluetooth service"); } } public async Task AddNotification(Notification notification) { var jsonString = JsonConvert.SerializeObject(notification); var bytes = Encoding.UTF8.GetBytes(jsonString); await notificationCharacteristic.NotifyValueAsync(bytes.AsBuffer()); } private void notificationCharacteristic_SubscribedClientsChanged(GattLocalCharacteristic sender, object args) { subscribedClients.Clear(); subscribedClients.AddRange(sender.SubscribedClients); } } } <file_sep>/WinWearUWP/MainPage.xaml.cs //using AccessoryManagerLib; using System; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Phone.Notification.Management; using Windows.UI.Notifications; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace WinWearUWP { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { string appId; public MainPage() { this.InitializeComponent(); this.Loaded += MainPage_Loaded; } private async void MainPage_Loaded(object sender, RoutedEventArgs e) { await initializeApp(); } private async Task initializeApp() { // Clear tasks foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "BackgroundTaskDemo") { task.Value.Unregister(true); } } var triggerId = AccessoryManager.RegisterAccessoryApp(); AccessoryManager.EnableAccessoryNotificationTypes((int)AccessoryNotificationType.Toast); var apps = AccessoryManager.GetApps(); foreach(var app in apps) { AccessoryManager.EnableNotificationsForApplication(app.Value.Id); if (app.Value.Name.Equals("BackgroundTaskDemo")) { appId = app.Value.Id; } } await BackgroundExecutionManager.RequestAccessAsync(); var taskRegistered = false; foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "NotificationBackgroundTask") { taskRegistered = true; break; } } if (!taskRegistered) { var builder = new BackgroundTaskBuilder(); builder.SetTrigger(new DeviceManufacturerNotificationTrigger("Microsoft.AccessoryManagement.Notification:" + triggerId, false)); builder.Name = "NotificationBackgroundTask"; builder.TaskEntryPoint = "BackgroundTaskWM.NotificationBackgroundTask"; var registration = builder.Register(); } } private void Button_Click(object sender, RoutedEventArgs e) { var template = ToastTemplateType.ToastText01; var toastXml = ToastNotificationManager.GetTemplateContent(template); var textNodes = toastXml.GetElementsByTagName("text"); textNodes[0].AppendChild(toastXml.CreateTextNode("hello toast")); var toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); if (AccessoryManager.IsNotificationEnabledForApplication(appId)) { var triggerDetail = AccessoryManager.GetNextTriggerDetails(); } } } } <file_sep>/WinWearUWP/DevicesPage.xaml.cs using BluetoothGattServer; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Devices.Bluetooth; using Windows.Devices.Enumeration; using Windows.Devices.Radios; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Phone.Notification.Management; using Windows.UI.Notifications; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 namespace WinWearUWP { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class DevicesPage : Page { string appId; public DevicesPage() { this.InitializeComponent(); this.Loaded += DevicesPage_Loaded; } private async void DevicesPage_Loaded(object sender, RoutedEventArgs e) { await initializeApp(); } private async Task initializeApp() { GattServer.Instance = await GattServer.InitServer(); // Clear tasks foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "BackgroundTaskDemo") { task.Value.Unregister(true); } } var triggerId = AccessoryManager.RegisterAccessoryApp(); AccessoryManager.EnableAccessoryNotificationTypes((int)AccessoryNotificationType.Toast); var apps = AccessoryManager.GetApps(); foreach (var app in apps) { AccessoryManager.EnableNotificationsForApplication(app.Value.Id); if (app.Value.Name.Equals("BackgroundTaskDemo")) { appId = app.Value.Id; } } await BackgroundExecutionManager.RequestAccessAsync(); var taskRegistered = false; foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "NotificationBackgroundTask") { taskRegistered = true; break; } } if (!taskRegistered) { var builder = new BackgroundTaskBuilder(); builder.SetTrigger(new DeviceManufacturerNotificationTrigger("Microsoft.AccessoryManagement.Notification:" + triggerId, false)); builder.Name = "NotificationBackgroundTask"; builder.TaskEntryPoint = "BackgroundTaskWM.NotificationBackgroundTask"; var registration = builder.Register(); } } private void Toast_Button_Click(object sender, RoutedEventArgs e) { var template = ToastTemplateType.ToastText01; var toastXml = ToastNotificationManager.GetTemplateContent(template); var textNodes = toastXml.GetElementsByTagName("text"); textNodes[0].AppendChild(toastXml.CreateTextNode("hello toast")); var toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); if (AccessoryManager.IsNotificationEnabledForApplication(appId)) { var triggerDetail = AccessoryManager.GetNextTriggerDetails(); } } private async void Scan_Button_Click(object sender, RoutedEventArgs e) { // Check bluetooth var radios = await Radio.GetRadiosAsync(); // If no Bluetooth then crash if (radios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth) == null) { throw new PlatformNotSupportedException("Device does not have Bluetooth"); } else { // Check if bluetooth enabled var btRadio = radios.First(radio => radio.Kind == RadioKind.Bluetooth); // If not ask to enable bluetooth if (btRadio.State != RadioState.On) { // Request access var status = await Radio.RequestAccessAsync(); if (status == RadioAccessStatus.Allowed) { // Turn on bluetooth var state = await btRadio.SetStateAsync(RadioState.On); if (state != RadioAccessStatus.Allowed) { throw new PlatformNotSupportedException("Cannot turn on bluetooth"); } } } // Create BT device watcher var devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector()); DeviceList.ItemsSource = devices; } } } } <file_sep>/WinWearUWP/NotificationBackgroundTask.cs ////using AccessoryManagerLib; //using System; //using System.Collections.Generic; //using System.Diagnostics; //using System.Linq; //using System.Text; //using System.Threading.Tasks; //using Windows.ApplicationModel.Background; //using Windows.Phone.Notification.Management; //using Windows.UI.Notifications; //namespace BackgroundTaskDemo //{ // public sealed class NotificationBackgroundTask : IBackgroundTask // { // public static string taskName = "NotificationBackgroundTask"; // public static string taskEntryPoint = "BackgroundTaskDemo.NotificationBackgroundTask"; // public void Run(IBackgroundTaskInstance taskInstance) // { // var triggerDetail = AccessoryManager.GetNextTriggerDetails(); // var appName = triggerDetail.AppDisplayName; // Debug.WriteLine(appName); // } // } //}
0bc4ca8b7ee0616dae48d702af4ea7c8b2f9da22
[ "C#" ]
5
C#
qtoncoding/WinWearUWP
837805e09c1087f15d1c62f3cd0059c025442a9a
77dec13771601657a104e9ca7659c706c251796b
refs/heads/master
<file_sep>import React from 'react' import ReactDOM from 'react-dom' import Format from '../../format.js' class AccountOverview extends React.Component { constructor(props) { super(props); this.state = {}; } render() { let bars = []; let account = window.config.accounts[window.app.getAccount()]; let transactions = []; for (let [keyByYearMonth, mapByDay] of this.props.transactions.entries()) { mapByDay.forEach((trans, i) => { transactions.push({key:keyByYearMonth + this.props.monthName + i, trans:trans}); }); } if (account.limit) { transactions.forEach((t, i) => { bars.push(<div key={t.key} className="bar-outer" style={{width: 400 / transactions.length}}><a className="bar-inner" title={Format.date(t.trans.date) + ' $' + Format.toCurrency(t.trans.balance)} style={{height: (Math.abs(t.trans.balance) / account.limit) * 57}}></a></div>); }); } let openingBalance = Format.toCurrency(transactions[0].trans.balance); let closingBalance = Format.toCurrency(transactions[transactions.length - 1].trans.balance); return ( <div className="overview">{bars}<span className="balance opening">{openingBalance}</span><span className="balance closing">{closingBalance}</span></div> ); } } export default AccountOverview;<file_sep>import React from 'react' import ReactDOM from 'react-dom' import './debug.js' import App from './jsx/App.jsx' import Transforms from './transforms.js' json('/js/config.json').then((config) => { window.config = Transforms.config = config; window['app'] = ReactDOM.render(<App config={config}/>, document.getElementById('main')); setTimeout(() => $('#load').trigger('click'), 150); });<file_sep>const headers = require('./headers.js'); class Month { constructor(month, year) { this.month = month; this.year = year; this.transactions = []; } hasDate(date) { return date.getMonth() === this.month && date.getFullYear() === this.year; } add(transaction) { this.transactions.push(transaction); } openingBalance() { return this.transactions[this.transactions.length - 1].balance; } closingBalance() { return this.transactions[0].balance; } } function parseDate(dateStr) { let dateFields = dateStr.split('/'); return new Date(parseInt(dateFields[2]), parseInt(dateFields[1]), parseInt(dateFields[0])); } Month.getMonths = function (transactions) { let index = {}; let months = []; transactions.forEach((transaction) => { let date = parseDate(transaction.date); let monthKey = (date.getMonth() + 1).toString(); monthKey = monthKey.length === 1 ? '0' + monthKey : monthKey; let key = `${date.getFullYear()}_${monthKey}`; if (!index[key]) { let month = new Month(date.getMonth(), date.getFullYear()); months.push(month); index[key] = month; } let month = index[key]; if (month.hasDate(date)) { month.add(transaction); } }); return months; }; module.exports = Month;<file_sep>module.exports = { force: false };<file_sep>import React from 'react' import ReactDOM from 'react-dom' import Transforms from '../../transforms.js' import Format from '../../format.js' class Details extends React.Component { constructor(props) { super(props); this.state = { height: 288, group: false, sort: 0 // Amount }; } hasSearchMatch(trans) { let hasSearchMatch = false; if (this.props.app.state.searchText) { if (this.props.app.state.searchMatches.indexOf(trans.id) > -1) { hasSearchMatch = true; } } return hasSearchMatch; } hasSearchMatchGroup(desc) { let hasSearchMatch = false; if (this.props.app.state.searchText) { if (desc.match(new RegExp(this.props.app.state.searchText, 'i'))) { hasSearchMatch = true; } } return hasSearchMatch; } highlight(desc) { let searchText = this.props.app.state.searchText; if (searchText) { desc = desc.replace(new RegExp(searchText, 'i'), '<b>' + searchText + '</b>'); } return { __html: desc }; } newTransaction(trans, key) { return ( <li className={`transaction ${this.hasSearchMatch(trans) ? 'search-match' : ''}`} key={key}> <span className="date">{Format.date(trans.date)}</span> <span className={`amount ${trans.debit ? 'debit' : 'credit'}`}>{Format.toCurrency(trans.debit ? trans.debit : trans.credit)}</span> <span className="description" dangerouslySetInnerHTML={this.highlight(Transforms.apply(trans.desc))}></span> </li> ) } newTransactionGroup(desc, count, type, amount, key) { return ( <li className={`transaction group ${this.hasSearchMatchGroup(desc) ? 'search-match' : ''}`} key={key}> <span className="count">{count}</span> <span className={`amount ${type}`}>{Format.toCurrency(amount)}</span> <span className="description" dangerouslySetInnerHTML={this.highlight(Transforms.apply(desc))}></span> </li> ) } render() { let transactions = []; let selectedDay = this.props.app.state.selectedDay; let selectedMonth = this.props.app.state.selectedMonth; if (selectedDay && selectedDay.transactions) { // show transactions for selected day selectedDay.transactions.forEach((trans, i) => { transactions.push(trans); }); } else if (selectedMonth && selectedMonth.transactions) { // show transactions for selected month for (let [keyByYearMonth, mapByDay] of selectedMonth.transactions.entries()) { mapByDay.forEach((trans) => { transactions.push(trans); }); } } // find categories let categorySummary = []; if (selectedDay || selectedMonth) { let account = window.config.accounts[window.app.getAccount()]; let categories = {}; for (let key in account.categories) { if (account.categories.hasOwnProperty(key)) { let regex = new RegExp(account.categories[key][0]); let type = account.categories[key][1]; let color = account.categories[key][2]; transactions.forEach((trans) => { let transType = trans.debit ? 'debit' : 'credit'; if (trans.desc.match(regex) && type === transType) { if (!categories[key]) { categories[key] = { amount: 0, count: 0, color: color, type: type } } categories[key].amount += trans.debit ? trans.debit : trans.credit; categories[key].count++; } }); } } for (let key in categories) { if (categories.hasOwnProperty(key)) { let cat = categories[key]; categorySummary.push(<li key={key} className="category"><span className="label" style={cat.color ? {backgroundColor:cat.color} : {}}></span><span className="count">{cat.count}</span><span className={`amount ${cat.type}`}>{Format.toCurrency(cat.amount)}</span><span className="desc">{key}</span></li>); } } } if (this.state.group) { // first, group transactions by description (by debit or credit) let map = new Map(); transactions.forEach((trans) => { let desc = Transforms.apply(trans.desc); let key = desc + (trans.debit ? 'debit' : 'credit'); if (!map.has(key)) { map.set(key, { desc: desc, count: 0, debit: 0, credit: 0 }); } let info = map.get(key); info.count++; info.credit += trans.credit; info.debit += trans.debit; }); // then create array and sort by total cost (descending) let temp = []; let i = 0; for (let [key, info] of map.entries()) { info.key = key + 1; info.type = info.debit < 0 ? 'debit' : 'credit'; info.total = info.type === 'debit' ? info.debit : info.credit; temp.push(info); i++; } temp.sort((a, b) => { if (this.state.sort === 0) { // Amount if (a.total < b.total) { return 1; } else if (a.total > b.total) { return -1; } } else if (this.state.sort === 1) { // Description if (a.desc < b.desc) { return -1; } else if (a.desc > b.desc) { return 1; } } else if (this.state.sort === 2) { // Count if (a.count < b.count) { return 1; } else if (a.count > b.count) { return -1; } } return 0; }); temp = temp.map((info) => this.newTransactionGroup(info.desc, info.count, info.type, info.total, info.key)); transactions = temp; } else { transactions = transactions.map((trans, i) => this.newTransaction(trans, 'trans-' + i)); } // display options let checkbox = <input type="checkbox" onChange={(e) => this.setState({group:e.target.checked})} />; let select = <select onChange={(e) => this.setState({sort:parseInt(e.target.value)})}> <option value="0">Amount</option> <option value="1">Description</option> <option value="2">Count</option> </select>; let detailsDownY; let detailsDownHeight = this.state.height; let self = this; window.onmousemove = (e) => { if (detailsDownY) { let deltaY = detailsDownY - e.screenY; console.log(deltaY); self.setState({ height: detailsDownHeight + deltaY }) } }; return ( <div id="details" className="details" style={{"height":this.state.height}}> <input id="focus" style={{position:'absolute',width:0,height:0,border:'none','backgroundColor':'transparent',display:'hidden'}} /> <div className="options">Details<label>sort by: {select}</label><label>group: {checkbox}</label></div> <div className="transactions-container"> <label style={{display:categorySummary.length ? 'block' : 'none'}}>Categories:</label> <ul className="categories">{categorySummary}</ul> <label style={{display:transactions.length ? 'block' : 'none'}}>Transactions:</label> <ul className="transactions">{transactions}</ul> </div> <div className="shadow"></div> <div className="divider" onMouseDown={(e) => { detailsDownY = e.screenY; detailsDownHeight = self.state.height; setTimeout(() => { let focus = document.getElementById('focus'); focus.style.display = 'block'; focus.focus(); }, 1); }} onMouseUp={(e) => { let focus = document.getElementById('focus'); focus.style.display = 'hidden'; }}></div> </div> ); } } export default Details;<file_sep>const cli = require('cli-color'); var log = { main: function (output) { console.log(cli.cyan(output)); }, notify: function (output) { console.log(cli.magenta(output)); }, begin: function (output) { return process.stdout.write(cli.blackBright(output)); }, ok: function finish(output) { return console.log(cli.white(output || 'ok.')); }, completed: function (output) { console.log(cli.green(output || 'completed.')); }, warn: function (output) { console.log(cli.yellow.bold(output || 'error.')); }, error: function (output) { console.log(cli.red.bold(output || 'warn.')); } }; module.exports = log;<file_sep>export default { byDateRange: function (fromDate, toDate, account) { return json('/api/getTransactions', {from: fromDate, to: toDate, account:account}).then((transactions) => { // convert db date string to Date obj transactions.forEach((trans) => trans.date = new Date(trans.date)); return Promise.resolve(transactions); }); } };<file_sep>import React from 'react' //import ReactDOM from 'react-dom' import query from '../../query.js' import Month from './Month.jsx' import Details from './Details.jsx' import Search from './Search.jsx' import util from '../../../util.js' const monthNames = Month.monthNames; class Calendar extends React.Component { constructor(props) { super(props); let accountNames = []; for (var key in this.props.config.accounts) { accountNames.push(key); } this.state = { transactions: [], accountNames: accountNames }; } renderDays(key) { let days = []; for (var i = 0; i < 31; i++) { let j = util.padNum(i + 1); days.push(<option value={j} key={key + j}>{j}</option>); } return days; } renderMonths(key) { let months = []; for (var i = 0; i < 12; i++) { let monthName = monthNames[i]; months.push(<option value={monthName} key={key + monthName}>{monthName}</option>); } return months; } renderYears(key) { let thisYear = (new Date()).getFullYear(); let years = []; for (var i = thisYear - 5; i < thisYear + 5; i++) { years.push(<option value={i} key={key + i}>{i}</option>); } return years; } onSelectChange(key) { localStorage[key] = this.refs[key].value; } renderSelect(key, fn, defaultValue) { return <select ref={key} defaultValue={localStorage[key] ? localStorage[key] : defaultValue} onChange={this.onSelectChange.bind(this, key)}> {fn(key)}</select> } setToToday(key) { let d = new Date(); this.refs[key + '_day'].value = util.padNum(d.getDate()); this.refs[key + '_month'].value = monthNames[d.getMonth()]; this.refs[key + '_year'].value = d.getFullYear(); this.onSelectChange(key + '_day'); this.onSelectChange(key + '_month'); this.onSelectChange(key + '_year'); } load() { var fromDate = new Date(parseInt(this.refs.from_year.value, 10), parseInt(monthNames.indexOf(this.refs.from_month.value) + 1, 10), parseInt(this.refs.from_day.value, 10)).getTime(); var toDate = new Date(parseInt(this.refs.to_year.value, 10), parseInt(monthNames.indexOf(this.refs.to_month.value) + 1, 10), parseInt(this.refs.to_day.value, 10)).getTime(); query.byDateRange(fromDate, toDate, this.refs.account.value).then((transactions) => { var mapByYearMonth = new Map(); for (var transaction of transactions) { let keyByYearMonth = transaction.date.getFullYear() + '.' + (transaction.date.getMonth() + 1); if (!mapByYearMonth.has(keyByYearMonth)) { mapByYearMonth.set(keyByYearMonth, new Map()); } let mapByDay = mapByYearMonth.get(keyByYearMonth); let day = transaction.date.getDate(); if (!mapByDay.has(day)) { mapByDay.set(day, []); } let array = mapByDay.get(day); array.push(transaction); } this.props.app.setState({ selectedDay: null, selectedMonth: null, searchText: null, searchMatches: null }); this.setState({ transactions: transactions, map: mapByYearMonth }); }); } getAccount() { return this.refs.account.value; } render() { let months = []; if (this.state.map) { let index = 0; for (let [keyByYearMonth, mapByDay] of this.state.map.entries()) { let [year, month] = keyByYearMonth.split('.'); year = parseInt(year, 10); month = parseInt(month, 10); months.push(<Month app={this.props.app} year={year} month={month} transactions={mapByDay} key={keyByYearMonth} index={index} indexLength={this.state.map.size} />); index++; } } return ( <calendar> <div className="range"> <label>Account: <select ref="account" onChange={() => localStorage['account'] = this.refs.account.value} defaultValue={localStorage['account'] ? localStorage['account'] : this.state.accountNames[0]}> {this.state.accountNames.map((accountName) => <option value={accountName} key={'account_' + accountName}>{accountName}</option>)} </select> </label> <label>From: {this.renderSelect('from_day', this.renderDays.bind(this), util.padNum(1))} {this.renderSelect('from_month', this.renderMonths.bind(this), monthNames[new Date().getMonth()])} {this.renderSelect('from_year', this.renderYears.bind(this), new Date().getFullYear())} </label> <label>To:<a title="Set to today"><button className="today" onClick={this.setToToday.bind(this, 'to')} /></a> {this.renderSelect('to_day', this.renderDays.bind(this), util.padNum(new Date().getDate()))} {this.renderSelect('to_month', this.renderMonths.bind(this), monthNames[new Date().getMonth()])} {this.renderSelect('to_year', this.renderYears.bind(this), new Date().getFullYear())} </label> <button id="load" onClick={this.load.bind(this)}>Load</button> </div> <div className="data"> <div className="options"> Calendar <Search app={this.props.app} transactions={this.state.map}></Search> </div> <div className="months"> {months} </div> <Details app={this.props.app} /> </div> </calendar> ); } } export default Calendar;<file_sep>var gulp = require('gulp'); var sass = require('gulp-sass'); var webpack = require('gulp-webpack'); var path = require('path'); var p = path.resolve('./public/js'); gulp.task('webpack-dev', function() { return gulp.src('./src/main.js') .pipe(webpack({ entry: './src/main.js', output: { path: p, filename: 'bundle.js' }, watch: true, devtool: 'inline-source-map', module: { loaders: [ { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react'] } } ] } })) .pipe(gulp.dest('./public/js/')); }); gulp.task('webpack-prod', function() { return gulp.src('./src/main.js') .pipe(webpack({ entry: './src/main.js', output: { path: p, filename: 'bundle.js' }, devtool: 'source-map', module: { loaders: [ { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react'] } } ] } })) .pipe(gulp.dest('./public/js/')); }); gulp.task('sass', function () { return gulp.src('./sass/style.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./public/css')); }); gulp.task('sass:watch', function () { gulp.watch('./sass/**/*.scss', ['sass']); }); gulp.task('default', ['sass', 'webpack-prod']); gulp.task('dev', ['sass', 'sass:watch', 'webpack-dev']);<file_sep>import React from 'react' import ReactDOM from 'react-dom' import Calendar from './calendar/Calendar.jsx' class App extends React.Component { constructor(props) { super(props); this.state = { selectedDay: null, selectedMonth: null, searchText: null, searchMatches: null }; } getAccount() { return this.refs.calendar.getAccount(); } render() { return ( <Calendar ref="calendar" config={this.props.config} app={this}></Calendar> ); } } export default App;<file_sep>const express = require('express'); const router = express.Router(); const log = require('../log.js'); process.on('unhandledRejection', function(err) { log.error(err.stack); }); require('../database.js').then((db) => { router.get('/getTransactions', (req, res, next) => { let fromDate = new Date(parseInt(req.query.from, 10)); let toDate = new Date(parseInt(req.query.to, 10)); let account = req.query.account; if (toDate < fromDate) { let temp = fromDate; fromDate = toDate; toDate = temp; } db.transaction.findAll({ where: { date: { $between: [fromDate, toDate] }, account: account }, order: 't_date' }).then((transactions) => { transactions.forEach((transaction) => { transaction.balance = parseFloat(transaction.balance); transaction.cheque = parseFloat(transaction.cheque); transaction.debit = parseFloat(transaction.debit); transaction.credit = parseFloat(transaction.credit); }); res.send(JSON.stringify(transactions)); }); }); }); module.exports = router; <file_sep>import React from 'react' import ReactDOM from 'react-dom' import Day from './Day.jsx' import AccountOverview from './AccountOverview.jsx' import Format from '../../format.js' const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; class Month extends React.Component { constructor(props) { super(props); this.state = { selectedDay: null }; } newDay(date, enabled, key) { return <Day app={this.props.app} date={date} enabled={enabled} key={'day-' + key} weekDay={daysOfWeek[date.getDay()]} transactions={this.props.transactions.get(date.getDate())} /> } onClick(e) { this.props.app.setState({ selectedDay: null, selectedMonth: { year: this.props.year, month: this.props.month, transactions: this.props.transactions } }); } render() { let selectedMonth = this.props.app.state.selectedMonth; // header let year; if (this.props.month === 1 || this.props.month === 12 || this.props.index === 0 || this.props.index === this.props.indexLength - 1) { year = <div className={`year ${this.props.index === 0 ? 'first' : this.props.index === this.props.indexLength - 1 ? 'last' : ''}`}>{this.props.year}</div> } // days let days = []; let firstDayOfMonth = new Date(this.props.year, this.props.month - 1, 1); let lastDayOfMonth = new Date(this.props.year, this.props.month, 0); let firstDayOfWeek = firstDayOfMonth.getDay(); let lastDayOfWeek = lastDayOfMonth.getDay(); let leadingDaysCount = Math.max(firstDayOfWeek, 0); let trailingDaysCount = 7 - (lastDayOfWeek + 1); // leading days for (let i = 0; i < leadingDaysCount; i++) { days.push(this.newDay(new Date(this.props.year, this.props.month - 1, 1 - (leadingDaysCount - i)), false, 'leading-' + i)); } // month days for (let i = 0; i < lastDayOfMonth.getDate(); i++) { days.push(this.newDay(new Date(this.props.year, this.props.month - 1, i + 1), true, 'month-' + i)); } // trailing days for (let i = 0; i < trailingDaysCount; i++) { days.push(this.newDay(new Date(this.props.year, this.props.month, i + 1), false, 'trailing-' + i)); } // totals let debits = 0; let credits = 0; for (let [keyByYearMonth, mapByDay] of this.props.transactions.entries()) { mapByDay.forEach((trans) => { if (trans.debit) { debits += trans.debit; } if (trans.credit) { credits += trans.credit; } }); } return ( <div className={`month ${selectedMonth && (selectedMonth.month === this.props.month && selectedMonth.year === this.props.year) ? 'selected' : ''}`}> <div className="header" onClick={this.onClick.bind(this)}> {year} <span className="total debit">{Format.toCurrency(debits)}</span> <div className="name">{monthNames[this.props.month - 1]}</div> <span className="total credit">{Format.toCurrency(credits)}</span> </div> <div className="dayOfWeek Sun">Sun</div> <div className="dayOfWeek Mon">Mon</div> <div className="dayOfWeek Tue">Tue</div> <div className="dayOfWeek Wed">Wed</div> <div className="dayOfWeek Thu">Thu</div> <div className="dayOfWeek Fri">Fri</div> <div className="dayOfWeek Sat">Sat</div> <div className="days"> {days} </div> <AccountOverview monthName={monthNames[this.props.month - 1]} transactions={this.props.transactions} /> </div> ); } } Month.monthNames = monthNames; export default Month;<file_sep>import React from 'react' import ReactDOM from 'react-dom' class Search extends React.Component { constructor(props) { super(props); this.state = {}; this.inputTimeout = null; } onInputKeyup(e) { if (this.inputTimeout) { clearTimeout(this.inputTimeout); } if (e.keyCode === 27) { this.refs.search.value = ''; app.setState({ searchText: null, searchMatches: null }); return; } if (e.keyCode === 13) { this.search(); } else { this.inputTimeout = setTimeout(this.search.bind(this), 1000); } } getTransactions() { if (!this.transactions) { this.transactions = []; for (let [keyByYearMonth, mapByDay] of this.props.transactions.entries()) { mapByDay.forEach((trans) => { this.transactions.push.apply(this.transactions, trans); }); } } return this.transactions; } search() { let transactions = this.getTransactions(); let value = this.refs.search.value; let regex = new RegExp(value, 'i'); let matches = []; transactions.forEach((trans) => { if (trans.desc.match(regex)) { matches.push(trans.id); } }); if (matches.length) { this.props.app.setState({ searchText: value, searchMatches: matches }); } else { this.props.app.setState({ searchText: null, searchMatches: null }); } } render() { this.transactions = null; return ( <div className="search"><input type="text" onKeyUp={this.onInputKeyup.bind(this)} ref="search" defaultValue={this.props.app.state.searchText ? this.props.app.state.searchText : ''} /></div> ); } } export default Search;<file_sep>const path = require('path'); const cli = require('cli-color'); const log = require('../log.js'); const importer = require('./importer.js'); process.on('unhandledRejection', function(err) { log.error(err.stack); }); log.begin('Connecting to database...\n'); require('../database.js').then(db => { log.ok(); const filePath = './transactions/creditcard.csv'; // const filePath = './transactions/debitcard.csv'; // const filePath = './transactions/loan.csv'; // const filePath = './transactions/savings.csv'; log.main(`Importing transactions from: "${filePath}" ...`); importer(filePath).then((transactions) => { log.completed(`Processing ${transactions.length} transactions...`); let rowsAdded = 0; let transactionsLength = transactions.length; let minId = Number.MAX_VALUE; let maxId = Number.MIN_VALUE; function processTransaction(transaction) { db.transaction.findOne({ where: { hash: transaction.hash } }).then((existingTransaction) => { if (existingTransaction) { log.warn(`Duplicate #${existingTransaction.id} for line ${transaction.line}: "${transaction.row.join(', ')}" (skipped)`); processNextTransaction(); } else { db.transaction.create({ bsb: transaction.bsb, acc: transaction.acc, date: transaction.date, desc: transaction.desc, cheque: transaction.cheque, credit: transaction.credit, debit: transaction.debit, balance: transaction.balance, type: transaction.type, account: transaction.account, hash: transaction.hash }).then((trans) => { minId = Math.min(minId, trans.id); maxId = Math.max(maxId, trans.id); rowsAdded++; processNextTransaction(); }); } }); } function processNextTransaction() { if (transactions.length) { processTransaction(transactions.shift()); } else { log.completed(`${Math.floor((rowsAdded / transactionsLength) * 100)}% (${rowsAdded}/${transactionsLength}) rows added, id #${minId} to #${maxId}`); process.exit(0); } } processNextTransaction(); }); }).catch(err => { log.error(err); process.exit(-1); });<file_sep>const SQL = require('sequelize'); module.exports = { transaction: { id: { type: SQL.INTEGER, primaryKey: true, autoIncrement: true }, bsb: { type: SQL.TEXT }, acc: { type: SQL.TEXT }, date: { type: SQL.DATE, field: 't_date' }, desc: { type: SQL.TEXT, field: 't_desc' }, cheque: { type: SQL.DECIMAL(10, 2), defaultValue: 0 }, debit: { type: SQL.DECIMAL(10, 2), defaultValue: 0 }, credit: { type: SQL.DECIMAL(10, 2), defaultValue: 0 }, balance: { type: SQL.DECIMAL(10, 2), defaultValue: 0 }, type: { type: SQL.TEXT }, account: { type: SQL.TEXT }, hash: { type: SQL.TEXT } } };<file_sep>const md5 = require('md5'); const path = require('path'); const cli = require('cli-color'); const headers = { 'BSB Number': 'bsb', 'Account Number': 'acc', 'Transaction Date': 'date', 'Narration': 'desc', 'Cheque': 'cheque', 'Debit': 'debit', 'Credit': 'credit', 'Balance': 'balance', 'Transaction Type': 'type' }; module.exports = function importer(filePath) { return new Promise((resolve) => { var basicCSV = require("basic-csv"); var transactions = []; var headerRow; basicCSV.readCSV(filePath, { /* dropHeader: true */ }, (error, rows) => { if (error) { console.log(cli.red(error.stack)); process.exit(-1); } rows.forEach((row, i) => { if (i === 0) { headerRow = row; } else { var transaction = {}; headerRow.forEach((header, j) => { transaction[headers[header]] = row[j]; }); let dateFields = transaction.date.split('/').map((field) => parseInt(field, 10)); transaction.date = new Date(dateFields[2], dateFields[1] - 1, dateFields[0]); transaction.account = path.basename(filePath, '.csv'); transaction.hash = md5(transaction.account + row.join('')); transaction.row = row; transaction.headers = headers; transaction.line = i + 1; transaction.cheque = transaction.cheque ? transaction.cheque : 0; transaction.credit = transaction.credit ? transaction.credit : 0; transaction.debit = transaction.debit ? transaction.debit : 0; transactions.push(transaction); } }); resolve(transactions); }); }); };<file_sep>class Year { }<file_sep>window.onerror = function (msg, url, l, c, ex) { notify(ex.stack, 'red'); console.error(url + ':' + l); console.error(ex.stack); return true; }; window.json = function ajax(url, data) { return new Promise((resolve, reject) => { $.ajax({ url: url, dataType: 'json', data: data || {}, success: (data) => { resolve(data); }, error: (err) => { reject(err); } }); }); };<file_sep>const SQL = require('sequelize'); let db = new SQL(process.env.PG, { logging: () => {} }); const schemas = require('./database-schemas'); const config = require('./database-config'); let modelSync = []; let models = {}; Object.keys(schemas).forEach((modelName) => { let model = db.define(modelName, schemas[modelName], { freezeTableName: true }); modelSync.push(model.sync({ force: config.force })); models[modelName] = model; }); module.exports = new Promise((resolve, reject) => { Promise.all(modelSync).then(() => { resolve(models); }).catch((err) => { reject(err); }); });<file_sep>export default { toCurrency: function (num) { let str = Math.round(num).toString(); return str.charAt(0) === '-' ? '-$' + str.replace('-', '') : '$' + str; }, date: function (date) { return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`; } }<file_sep>module.exports = { padNum: function (num) { let str = num.toString(); return str.length === 1 ? '0' + str : str; } };
d5de391d1fa959bc5bf41e74dc37911813b76ca7
[ "JavaScript" ]
21
JavaScript
dragonworx/trans.musicartscience.com.au
afd4711c010100366bda9f6588be13b5f8204900
64ca43cf885fb21ca3b7cb7005f2ca8a50bd1681
refs/heads/master
<file_sep># RSScrawler - Version 1.5.6f Projekt von https://github.com/rix1337 ## Enthaltener Code: https://github.com/dmitryint (im Auftrag von https://github.com/rix1337) https://github.com/zapp-brannigan/own-pyload-plugins/blob/master/hooks/MovieblogFeed.py https://github.com/Gutz-Pilz/pyLoad-stuff/blob/master/SJ.py https://github.com/bharnett/Infringer/blob/master/LinkRetrieve.py ## Beschreibung: RSScrawler durchsucht MB/SJ nach in .txt Listen hinterlegten Titeln und reicht diese im .crawljob Format an JDownloader weiter. Diese Version ist final (bekannte Fehler sind behoben/keine vom Author gewünschten Features fehlen). Den JDownloader betreffende Probleme (ReCaptcha benötigt Browserfenster, etc.) müssen in dessen Entwicklerforum gelöst werden. **Um ein Problem zu lösen, oder das Projekt zu erweitern muss ein entsprechender Pull Request (mit Code) eröffnet werden! Issues dienen nur der Fehlermeldung.** ## TLDR: 1. Aktiviere Ordnerüberwachung im JDownloader 2 2. Installiere Python 2.7 und die Zusatzpakete: docopt, feedparser, BeautifulSoup, pycurl, lxml, requests (Alternativ stehen ein docker-image, sowie ein Synology-Paket zur Verfügung) 3. Starte RSScrawler einmalig, dies erstellt die RSScrawler.ini im Einstellungen-Ordner 4. Passe die ```Einstellungen.ini``` und die .txt Listen komplett an. 5. Nutze RSScrawler! ## RSScrawler starten: ```python RSScrawler.py``` führt RSScrawler aus ## Startparameter: ```--testlauf``` Einmalige Ausführung von RSScrawler ```--jd-pfad=<JDPFAD>``` Legt den Pfad von JDownloader fest (nützlich bei headless-Systemen) ```--log-level=<LOGLEVEL>``` Legt fest, wie genau geloggt wird (CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET ) ## Einstellungen: *Die RSScrawler.ini liegt im ```Einstellungen``` Ordner und wird (inklusive der Listen) beim ersten Start automatisch generiert* **Der JDownloader-Pfad muss korrekt hinterlegt werden! Beachte den [Hinweis zu Windows](#wichtiger-hinweis-für-den-windows-build)** Alle weiteren Einstellungen können nach Belieben angepasst werden und sind hinreichend erklärt. Im Folgenden nur einige wichtige Hinweise: ### Die Listen (MB_Filme, MB_Serien, SJ_Serien, SJ_Serien_Regex: 1. MB_Filme enthält pro Zeile den Titel eines Films (Film Titel), um auf MB nach Filmen zu suchen 2. MB_Staffeln enthält pro Zeile den Titel einer Serie (Serien Titel), um auf MB nach kompletten Staffeln zu suchen 3. SJ_Serien enthält pro Zeile den Titel einer Serie (Serien Titel), um auf SJ nach Serien zu suchen 4. SJ_Serien_Regex enthält pro Zeile den Titel einer Serie in einem speziellen Format, wobei die Filter ignoriert werden: ``` DEUTSCH.*Serien.Titel.*.S01.*.720p.*-GROUP sucht nach Releases der Gruppe GROUP von Staffel 1 der Serien Titel in 720p auf Deutsch Serien.Titel.* sucht nach allen Releases von Serien Titel (nützlich, wenn man sonst HDTV aussortiert) Serien.Titel.*.DL.*.720p.* sucht nach zweisprachigen Releases in 720p von Serien Titel ENGLISCH.*Serien.Titel.*.1080p.* sucht nach englischen Releases in Full-HD von Serien Titel ``` Generell sollten keine Sonderzeichen in den Listen hinterlegt werden! **Die Listen werden automatisch mit Platzhalterzeilen generiert und sind danach anzupassen. Platzhalter verhindern, dass unerwünschte Releases beim ersten Start hinzugefügt werden.** ### crawl3d: Wenn aktiviert sucht das Script nach 3D Releases (in 1080p), unabhängig von der oben gesetzten Qualität. Standartmäßig werden HOU-Releases aussortiert (ignore). ### enforcedl: Wenn aktiviert sucht das Script zu jedem nicht-zweisprachigen Release (kein DL-Tag im Titel) ein passendes Release in 1080p mit DL Tag. Findet das Script kein Release wird dies im Log vermerkt. Bei der nächsten Ausführung versucht das Script dann erneut ein passendes Release zu finden. Diese Funktion ist nützlich um (durch späteres Remuxen) eine zweisprachige Bibliothek in 720p zu halten. ### crawlseasons: Komplette Staffeln von Serien landen zuverlässiger auf MB als auf SJ. Diese Option erlaubt die entsprechende Suche. ### regex: Wenn aktiviert werden die Serien aus der SJ_Serien_Regex.txt gesucht ### Wichtiger Hinweis für den Windows Build: Der Pfad zum JDownloader muss Python-kompatibel vergeben werden: nur `/`-Schrägstriche sind erlaubt! ### Windows Build: https://github.com/rix1337/RSScrawler/releases ### Docker Container: https://github.com/rix1337/docker-rsscrawler ### Synology Addon-Paket: http://www.synology-forum.de/showthread.html?76211-RSScrawler-(noarch)-Paketzentrum-(JDownloader-Add-on) <file_sep># -*- coding: utf-8 -*- import common import sqlite3 class RssDb(object): def __init__(self, file): self._conn = sqlite3.connect(file, check_same_thread=False) self._table = 'data' if not self._conn.execute("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = '%s';" % self._table).fetchall(): self._conn.execute('''CREATE TABLE %s (key, value, pattern)''' % self._table) self._conn.commit() def retrieve(self, key): res = self._conn.execute("SELECT value FROM %s WHERE key='%s'" % (self._table, key)).fetchone() return res[0] if res else None def store(self, key, value, pattern=''): self._conn.execute("INSERT INTO '%s' VALUES ('%s', '%s', '%s')" %('data', key, value, pattern)) self._conn.commit() def get_patterns(self, f): return [common.get_first(el) for el in self._conn.execute( "SELECT pattern FROM data WHERE value='%s'" % f).fetchall()] <file_sep>docopt feedparser BeautifulSoup pycurl lxml requests <file_sep># -*- coding: utf-8 -*- from threading import Timer import time class RepeatableTimer(object): def __init__(self, interval, function, args=(), kwargs={}): self._interval = interval self._function = function self._args = args self._kwargs = kwargs self._START_TIME = None self._TIMER_STARTED = False def start(self): if not self._TIMER_STARTED: self._timer = Timer(self._interval, self._function, args=self._args, kwargs=self._kwargs) self._timer.start() self._START_TIME = time.time() self._TIMER_STARTED = True def cancel(self): if self._TIMER_STARTED: self._timer.cancel() self._TIMER_STARTED = False def running(self): return self._TIMER_STARTED def elapsed(self): return time.time() - self._START_TIME if self._TIMER_STARTED else None def remain(self): return self._interval - (time.time() - self._START_TIME) if self._TIMER_STARTED else None<file_sep># -*- coding: utf-8 -*- def get_first(iterable): return iterable and list(iterable[:1]).pop() or None
8135fe3965d2c2369336b7521411efc689044671
[ "Markdown", "Python", "Text" ]
5
Markdown
neutron666/RSScrawler
7a9e23c671e44711b0b98d65167638882a805e73
daf6b5eb2032254de8acb0acaa6a5ba78704737c
refs/heads/main
<repo_name>DenisFZelaya/SchoolManagement3<file_sep>/SchoolManagement3/Models/MetaClases/StudentsMetaData.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace SchoolManagement3.Models.MetaClases { public class StudentsMetaData { [Required] [StringLength(50)] [Display(Name = "Last Name")] public string LastName { get; set; } [Required] [StringLength(50)] [Display(Name = "Firt Name")] public string FirstName { get; set; } [Required] [Display(Name = "Date of Enrollment")] public Nullable<System.DateTime> EnrollmentDate { get; set; } [Required] [StringLength(50)] [Display(Name = "Middle Name")] public string MiddleName { get; set; } [Required] [Display(Name = "Date of Birth")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Enrollment> Enrollment { get; set; } } [MetadataType(typeof(StudentsMetaData))] public partial class Student { } }
79b81dda6e38e72ba326139aa79b2dad1efa9934
[ "C#" ]
1
C#
DenisFZelaya/SchoolManagement3
bfbf74fa747351aa549feaeedaaab87441582cba
a28fddad8daa8f51e7b167d8b158dbcd28566204
refs/heads/master
<file_sep>--- title: Blogging Like a Hacker323 lang: en-US --- test<file_sep>from .saliency import SaliencyClient<file_sep>module.exports = { title: 'Saliency.ai documentation', description: 'We enable you to use AI in your R&D', theme: '../saliency-theme', themeConfig: { logo: '/light-bg.png', repo: 'saliency-ai/saliency-client', nav: [ { text: 'Home', link: '/' }, { text: 'Guide', link: '/guide/' }, /* { text: 'GitHub', link: 'https://github.com/saliency-ai/saliency-client/' },*/ ], sidebar: { '/guide/': [ '', ],/* '/': [ '', 'one', 'two' ]*/ } } } <file_sep>import csv import json import os import tempfile import urllib import zipfile import cv2 import uuid import numpy as np import pandas as pd import pydicom import requests import scipy.io as sio from skimage.draw import polygon class AuthenticationError(Exception): pass class SaliencyClient: seq = {"train": [],"val": [],"test": []} batch_size = 16 task = "classification" temp_dir = 'tempfiles' classes = 0 def __init__(self, username, password, host="https://api.saliency.ai/"): self.username = username self.password = <PASSWORD> self.host = host self.headers = self.login() if not self.headers: raise AuthenticationError('Failed to authenticate "{}"'.format(username)) def login(self): auth_link = self.host + 'api-auth/token/' r = requests.post(auth_link, data={'username': self.username, 'password': self.password}) if r.status_code != 200: raise Exception("Authentication error") headers = {'Authorization': 'Token ' + r.json()['token']} return headers def add_annotation_scheme(self, name, type, labels): # TODO: check labels formatting data = { "name": name, "type": type, "labels": labels } r = requests.post(self.host + 'schemes/', data=data, headers=self.headers) if r.status_code in (200, 201): print('Scheme has been created') return r.json() else: for error in r.json().values(): print(error) def add_task(self, scheme, study): # TODO: check labels formatting data = { "scheme": scheme, "study": study, } r = requests.post(self.host + 'tasks/create_by_names/', data=data, headers=self.headers) if r.status_code in (200, 201): print('Task has been created') return r.json() else: print(r.content) def add_study(self, study, study_name): if type(study) == pd.DataFrame: filename = os.path.join(self.temp_dir, 'temp_study.csv') study.to_csv(filename) else: if os.path.isfile(study): filename = study else: print('File {} does not exist') return with open(filename, 'rb') as file: data = {'name': study_name} files = {'file': file} r = requests.post(self.host + 'studies/', data=data, files=files, headers=self.headers) if r.status_code in (200, 201): print('Study has been created') return r.json() else: for error in r.json().values(): print(error) def get_mri(self, tmpfile): tmpmridir = tmpfile + "-dir" zip_ref = zipfile.ZipFile(tmpfile, 'r') zip_ref.extractall(tmpmridir) zip_ref.close() # list all files while True: # our mris have a lot of nested dirs mrifiles = os.listdir(tmpmridir) testfile = "%s/%s" % (tmpmridir, mrifiles[0]) if (not os.path.isdir(testfile)): break tmpmridir = testfile # figure out the dimensions and create an array mrifiles = sorted(mrifiles) ds = pydicom.dcmread("%s/%s" % (tmpmridir, mrifiles[0]) ) shape = ds.pixel_array.shape + (len(mrifiles),) X = np.zeros(shape) # copy slices for i, tmpfile in enumerate(mrifiles): ds = pydicom.dcmread("%s/%s" % (tmpmridir, tmpfile) ) X[:,:,i] = ds.pixel_array return X def get_xray(self, tmpfile): X = cv2.imread(tmpfile,0) return X def get_xray_anno(self, tmpfile): X = cv2.imread(tmpfile,0) return X def get_zip_mri_anno(self, tmpfile, shape): Y = np.zeros(shape) mat = sio.loadmat(tmpfile) npoints = mat['FemoralCartilage'].shape[0] lx = 0 ly = 0 lz = None contour = [] for i in range(npoints): py, px, pz = tuple(mat['FemoralCartilage'][i,:]) py = py px = shape[0] - px dist = np.sqrt((lx - px)**2 + (ly - py)**2) if ((pz != lz) or (dist > 25)) and lz != None: acontour = np.array(contour) rr, cc = polygon(acontour[:,0], acontour[:,1], Y.shape[0:2]) Y[rr,cc,int(pz)] = 1 contour = [] contour.append([px,py]) lx,ly,lz = px,py,pz return Y def get_file(self, file): file_uid = str(uuid.uuid4())[:8] file_name = file_uid + file["filename"] # creates unique filename tmpfile = "{filedir}/{filename}".format(filedir=tempfile.gettempdir(), filename=file_name) # check if cashed # filehash = self.get_file_hash(file) # if filehash in self.storage.keys(): # return np.array(self.storage[filehash]) # check if already downloaded if not os.path.isfile(tmpfile): urllib.request.urlretrieve(file["file"], tmpfile) # process dicom MRI if file["datatype"] == "mri": X = self.get_mri(tmpfile) # process xray if file["datatype"] == "xray": X = self.get_xray(tmpfile) # cache the file # self.storage[filehash] = X return X def get_annotation(self, file, shape, headers): if file['annotation_set']: r = requests.get(file['annotation_set'][0], headers=headers) datatype = file['datatype'] annotation = r.json() tmpfile = "%s/%s" % (tempfile.gettempdir(), annotation["filename"]) #if not os.path.isfile(tmpfile): urllib.request.urlretrieve(annotation["file"], tmpfile) if datatype == 'mri': res = self.get_zip_mri_anno(tmpfile, shape) elif datatype == 'xray': res = self.get_xray_anno(tmpfile) return res return None def create_task(self, scheme_id, study_id, datatype="xray"): headers = self.login() if headers: datapoints = [] # annotations = [] url = '{}datapoints/?datatype={}&study={}'.format(self.host, datatype, study_id) while url is not None: r = requests.get(url, headers=headers) r = r.json() for item in r['results']: datapoint_url = '/datapoints/{}/'.format(item['id']) datapoints.append(datapoint_url) # if item['annotation_set']: # for anno_url in item['annotation_set']: # annotations.append(anno_url) url = r['next'] scheme_url = '/schemes/{}/'.format(scheme_id) data = {'scheme': scheme_url, 'datapoints': datapoints} r = requests.post(self.host + 'tasks/', data=data, headers=headers) return r.json() def download_datapoints(self, patient="", study="", datatype="xray"): headers = self.login() if headers: link = '%sdatapoints/?datatype=%s&patientid=%s&study=%s' % (self.host, datatype, patient, study) while link != None: r = requests.get(link, headers=headers) r = r.json() print(r) for datapoint in r['results']: x = self.get_file(datapoint) y = self.get_annotation(datapoint, x.shape, headers) yield x, y link = r['next'] def create_arrays(self, values, width, height): list_x = [] list_y = [] for x, y in values: x = self.resize_image(x, width, height) if y is not None: y = self.resize_image(y, width, height) list_x.append(x) list_y.append(y) list_x = np.asarray(list_x) list_y = np.asarray(list_y) return list_x, list_y def resize_image(self, image, width, height): im_height, im_width = image.shape ratio = im_width / im_height new_ratio = width / height if ratio > new_ratio: new_width = int(new_ratio * height) offset = (im_width - new_width) / 2 resize = (im_width - offset, height) width_offset = int(offset) height_offset = 0 else: new_height = int(width / new_ratio) offset = (im_height - new_height) / 2 resize = (width, im_height - offset) width_offset = 0 height_offset = int(offset) resize = (int(resize[0]), int(resize[1])) image = cv2.resize(image, resize, interpolation=cv2.INTER_AREA) crop = image[height_offset:height + height_offset, width_offset:width + width_offset] return crop def _list_objects(self, obj, obj_id=None): """ Method to cover all listings. param:obj: is string, that represents an object name in the API. (e.g. 'tasks') param:obj_id is actual id of the object in the API """ url = self.host + '{obj}/'.format(obj=obj) if obj_id: url += '{obj_id}/'.format(obj_id=obj_id) response = requests.get(url=url, headers=self.headers) return response.json() def _delete_objects(self, obj, obj_id): """ Method to delete object. param:obj: is string, that represents an object name in the API. (e.g. 'tasks') param:obj_id is actual id of the object in the API """ url = self.host + '{obj}/{obj_id}/'.format(obj=obj, obj_id=obj_id) response = requests.delete(url=url, headers=self.headers) return response.json() def list_tasks(self, task_id=None): """ Method to list all tasks. param:task_id if passed function would return information for specific task. """ tasks = self._list_objects(obj='tasks', obj_id=task_id) return pd.read_json(json.dumps(tasks)) def delete_task(self, task_id): """ Method to delete specific task. param:task_id is actual id of the task in the API """ return self._delete_objects(obj='tasks', obj_id=task_id) <file_sep>--- title: Getting started lang: en-US --- ## What is Saliency.ai? Saliency.ai is a set of tools that allow you to: * Aggregate heterogeneous data and retrieve it in a consistent format * Collect labels and annotations for machine learning * Quickly train machine learning algorithms using models that have already learned from thousands of medical images * Deploy your trained models as HIPAA-compliant web apps **Spend more time innovating and less time cleaning heterogeneous data dumps.** ## Installation Use `pip` to install our PyPI package in your environment ```bash > pip install saliency-client ``` You are now ready to connect to the Saliency API ```python from saliency import SaliencyClient sapi = SaliencyClient("[username]", "[password]") ``` ## Aggregate data from multiple sites A *study* is a set of data that you want to analyze. You can upload a list of datapoints as a study with the following command ```python sapi.add_study("filename.csv", "study_name") ``` where `filename.csv` is a file with links to datapoints. `SaliencyClient` will automatically determine the column with links to datapoints. All other columns will be stored as metadata associated with the file. Alternatively, if you have your dataframe with links already stored as a pandas DataFrame, you can simply add it with ```python sapi.add_study(pandasDataFrame, "study_name") ``` ::: tip Example You have knee MRIs for 1000 patients from Hospital A, along with the patients' age and disease severity. This is organized in `HospitalA.csv` which has three columns: `age`, `disease_severity`, and `location_of_mri_on_your_server`. You also have knee MRIs for 2000 patients from Hospital B, along with the patients' sex, state of residence, and disease severity. This is organized in a pandas dataframe called HospitalB which has four columns: `sex`, `state`, `location_of_mri_on_your_server`, and `disease_severity`. In both files, the `location_of_mri_on_your_server` column is a column of web addresses where your MRIs reside on your server. These datasets from Hospital A and Hospital B represent two different studies. You would call the `sapi.add_study()` function twice in order to upload both, even if you later want to merge the images and disease severitiy values from both for a single analysis. ::: ## Collect annotations In a typical machine learning workflow, data needs to be annotated. `SaliencyClient` provides a simple interface that allows you to define an annotation task (segmentation or labeling). After defining the task, you can send to your contractors a link to the annotation tool populated with images and the definition of the task. You will first need to define what is to be annotated: ```python sapi.add_annotation_scheme("Knee structures", "segmentation", [ "Femoral Cartilage", "Lateral Meniscus", "Lateral Tibial Cartilage", "Medial Meniscus", "Medial Tibial Cartilage", "Patellar Cartilage" ]) ``` Now, you can define the task by refering to the annotation scheme defined above by its name, and a list of studies to annotate ```python sapi.add_task("Knee structures", ["oai", "nhs"]) ``` After defining the task, you can log in to the [annotation tool](https://annotator.saliency.ai/) and start annotating. [TODO make the screenshot more realistic.] ![Annotation Tool](/annotation-tool.png) ## Train models After sufficient number of annotations came back, you start training your models. Get an iterator of the data with the labels. You can define the format in which you want to receive the data ```python data_iter = sapi.get_data(["oai", "nhs"], labels="Knee structures", config={"width": 500, "height": 500}) ``` We provide wrappers for this data iterater into a typical data loaders in tensorflow, keras, and pytorch. Run ```python loader = sapi.format_iterator(data_iter, "keras") ``` and start training your models! We provide a UNET training code as a baseline: ```python model = sapi.train("U-Net", loader) ``` ## Deploy After your model is ready, use `SaliencyClient` to deploy it ```python sapi.deploy("kltool",model) ``` Deployed model will run entirely in the browser -- no data leaves enduser's computer. See an example deployed model [here](http://demo.saliency.ai/kltool). <file_sep>#!/usr/bin/env python import os from setuptools import setup, find_packages __version__ = "0.1" setup(name='saliency-client', version=__version__, description='Client for connecting to Saliency API', author='Saliency.ai', author_email='<EMAIL>', url='http://saliency.ai/', license='Apache 2.0', packages=find_packages(), install_requires=['numpy>=1.14.2','pandas>=0.25.1'], classifiers=[ 'Intended Audience :: Science/Research', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], ) <file_sep>--- home: true actionText: Get Started → actionLink: /guide/ heroImage: '/dark-circle.png' heroText: 'Saliency.ai' features: - title: Simplicity details: We optimized our tools to save your time. Everything is accessible through a python client. - title: Safety details: Use our software without sending us your data. - title: Performance details: Pretrained models allow you to get the highest performance with a small number of annotated images. footer: Copyright © 2019-present Saliency.ai title: Blogging Like a Hacker ---
82439397ba49bd23e2d52e3bc210ae0ee854a26a
[ "Markdown", "Python", "JavaScript" ]
7
Markdown
sotanodroid/saliency-client
9b46fd2584a21883256a179bf2537eb8dfb3fef9
efef06b8b06cbc9fc582167d5593dc943b40ee22
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace I69_610_ConstructionAlert { class SubscriberRecord { public string Email; public string ProjectID_Date; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace I69_610_ConstructionAlert { class CCRecord { public string ID; public string ProjectID; public string RoadwayName; public string Direction; public string BeginCrossStreet; public string EndCrossStreet; public string BeginLatitude; public string BeginLongitude; public string PlannedStartTime; public string PlannedEndTime; public string ClosureDescription; public string TypeOfWork; public string ContactPerson; public string AreaOffice; public string ContactPhoneNumber; public string ClosureMapLocation; public string ClosureHotSpot; public string CountyName; public string FacilityType; public string TranStarNotification; public string ClosureDuration; public string DurationException; public string LanesAffected; public string Detour; public string Location; public string DurationDescription; public string Status; } } <file_sep>//This app DOESNOT send mail on 1st Cycle => Not rerun the programe when make changes. If need to send mail on First Cycle, make change in Sendmail sub using System; using System.Data; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Linq; using System.Xml.Linq; using System.Web.Mail; using System.Threading; using System.Net.Mail; using System.Configuration; using System.Collections.Specialized; namespace I69_610_ConstructionAlert { class Program { static List<CCRecord> CCReportList = new List<CCRecord>(); static List<SubscriberRecord> SubscribersList = new List<SubscriberRecord>(); static DataTable OldRecords; static DataTable NewRecords; static int SendMailCount; static int NewCCCount; static DateTime LastRunTime; static int FirstCycle; static string ErrorFile; static string SentMessageFile; // Get the command line arguments static string[] arg = Environment.GetCommandLineArgs(); // The first element will be the name of the running program // so there should be 4 arguments in the list. static void Main(string[] args) { ErrorFile= ConfigurationManager.AppSettings.Get("errorfile").Trim(); SentMessageFile = ConfigurationManager.AppSettings.Get("sentmessagefile").Trim(); int TimerControl = 1; Timer t = new Timer(ComputeBoundOp, 5, 0, 2000); //Timer timer = new Timer(); List<CCRecord> CCReportList; //timer.Interval=500; //timer.OnTimerTick += timerTick; //Thread timerThread = timer.Start(); // Create DataTable for old and new records if (FirstCycle <= 0) { // Old Records Table OldRecords = new DataTable("Old Records"); OldRecords.Columns.Add("ID", Type.GetType("System.String")); OldRecords.Columns.Add("Project_Id", Type.GetType("System.String")); OldRecords.Columns.Add("RoadwayName", Type.GetType("System.String")); OldRecords.Columns.Add("Direction", Type.GetType("System.String")); OldRecords.Columns.Add("BeginCrossStreet", Type.GetType("System.String")); OldRecords.Columns.Add("EndCrossStreet", Type.GetType("System.String")); OldRecords.Columns.Add("Latitude", Type.GetType("System.String")); OldRecords.Columns.Add("Longitude", Type.GetType("System.String")); OldRecords.Columns.Add("ClosureDescription", Type.GetType("System.String")); OldRecords.Columns.Add("TypeOfWork", Type.GetType("System.String")); OldRecords.Columns.Add("ContactPerson", Type.GetType("System.String")); OldRecords.Columns.Add("AreaOffice", Type.GetType("System.String")); OldRecords.Columns.Add("ContactPhoneNumber", Type.GetType("System.String")); OldRecords.Columns.Add("ClosureMapLocation", Type.GetType("System.String")); OldRecords.Columns.Add("Location", Type.GetType("System.String")); OldRecords.Columns.Add("CountyName", Type.GetType("System.String")); OldRecords.Columns.Add("TranStarNotification", Type.GetType("System.String")); OldRecords.Columns.Add("PlannedStartTime", Type.GetType("System.String")); OldRecords.Columns.Add("PlannedEndTime", Type.GetType("System.String")); OldRecords.Columns.Add("FacilityType", Type.GetType("System.String")); OldRecords.Columns.Add("ClosureDuration", Type.GetType("System.String")); OldRecords.Columns.Add("DurationException", Type.GetType("System.String")); OldRecords.Columns.Add("DurationDescription", Type.GetType("System.String")); OldRecords.Columns.Add("LanesAffected", Type.GetType("System.String")); OldRecords.Columns.Add("Detour", Type.GetType("System.String")); OldRecords.Columns.Add("ClosureHotSpot", Type.GetType("System.String")); OldRecords.Columns.Add("Status", Type.GetType("System.String")); //New Records Table NewRecords = new DataTable("New Records"); NewRecords.Columns.Add("ID", Type.GetType("System.String")); NewRecords.Columns.Add("RecordStatus", Type.GetType("System.String")); NewRecords.Columns.Add("Project_Id", Type.GetType("System.String")); NewRecords.Columns.Add("RoadwayName", Type.GetType("System.String")); NewRecords.Columns.Add("Direction", Type.GetType("System.String")); NewRecords.Columns.Add("Status", Type.GetType("System.String")); NewRecords.Columns.Add("Location", Type.GetType("System.String")); NewRecords.Columns.Add("PlannedStartTime", Type.GetType("System.String")); NewRecords.Columns.Add("PlannedEndTime", Type.GetType("System.String")); NewRecords.Columns.Add("Latitude", Type.GetType("System.String")); NewRecords.Columns.Add("Longitude", Type.GetType("System.String")); NewRecords.Columns.Add("FacilityType", Type.GetType("System.String")); NewRecords.Columns.Add("ClosureDuration", Type.GetType("System.String")); NewRecords.Columns.Add("DurationException", Type.GetType("System.String")); NewRecords.Columns.Add("DurationDescription", Type.GetType("System.String")); NewRecords.Columns.Add("LanesAffected", Type.GetType("System.String")); NewRecords.Columns.Add("Detour", Type.GetType("System.String")); NewRecords.Columns.Add("ClosureHotSpot", Type.GetType("System.String")); } while (TimerControl > 0) // always true to make the program run continuoudly { CCReportList = LoadConstructionClosures(); SubscribersList = LoadSubscribers(); GetUpdatedIncident(CCReportList); Processing(); Thread.Sleep(1800000); //run every 30 mins } //Thread.Sleep(60000); // Simulating other work (1min = 60000 miliseconds) Thread.Sleep(1800000); //run every 30 mins t.Dispose(); // Cancel the timer now } // This method's signature must match the TimerCallback delega private static void ComputeBoundOp(Object state) { // This method is executed by a thread pool thread // Console.WriteLine("In ComputeBoundOp: state={0}", state); Thread.Sleep(60000); // Simulates other work (1 second) // When this method returns, the thread goes back // to the pool and waits for another task } static List<SubscriberRecord> LoadSubscribers() { List<SubscriberRecord> SubscribersList = new List<SubscriberRecord>(); //List<string> EmailList = new List<string>; string SubscriberFile = ConfigurationManager.AppSettings.Get("subscriberfile").Trim(); string ProjectID_Date = ""; XDocument xdoc = XDocument.Load(SubscriberFile); try { if (File.Exists(SubscriberFile)) { var query = from e in xdoc.Root.Descendants("SUBSCRIBER") orderby (string)e.Element("EMAIL_ADDRESS") select (string)e.Element("EMAIL_ADDRESS"); var emaillist = Enumerable.Distinct(query); var subscriberL = from e in xdoc.Root.Descendants("SUBSCRIBER") select ((string)e.Element("EMAIL_ADDRESS").Value + ";" + (string)e.Element("PROJECT_ID").Value + "_" + (string)e.Element("TIME_ENTERED").Value); foreach (string EmailValue in emaillist) { ProjectID_Date = ""; foreach (string SubscriberV in subscriberL) { string[] SubscriberValue = SubscriberV.Split(Convert.ToChar(";")); if (SubscriberValue[0] == EmailValue) { ProjectID_Date += SubscriberValue[1] + ";"; } } if (ProjectID_Date !="") ProjectID_Date = ProjectID_Date.Substring(0, ProjectID_Date.Length - 1); SubscriberRecord Value = new SubscriberRecord { Email = EmailValue, ProjectID_Date = ProjectID_Date }; SubscribersList.Add(Value); } } else Console.WriteLine("SuscriberFile does not exist."); return SubscribersList; } catch (Exception e) { Console.WriteLine("Load Subscribers: Data is not available" + e.Message); //Environment.Exit(-1); using (StreamWriter w = File.AppendText(ErrorFile)) { w.WriteLine(DateTime.Now.ToString() + ": Load Subscribers: Data is not available" + e.Message); } return SubscribersList; } } static List<CCRecord> LoadConstructionClosures() { List<CCRecord> CCReportList = new List<CCRecord>(); string CCFile = ConfigurationManager.AppSettings.Get("CCfile").Trim(); DataSet ds = new DataSet(); DataTable dt; TimeSpan DTDiff; DTDiff = DateTime.Now.Subtract(File.GetLastWriteTime(CCFile)); try { if (File.Exists(CCFile)) { Console.WriteLine(File.GetLastWriteTime(CCFile).ToString()); Console.WriteLine(DTDiff.TotalMinutes.ToString()); //Only work if the incident file is updated within 30 minutes if (DTDiff.TotalMinutes < 35) { ds.ReadXml(CCFile); dt = ds.Tables[1]; foreach (DataRow Drow in dt.Rows) { CCRecord CCReport = new CCRecord(); CCReport.ID = Drow["ID"].ToString(); CCReport.ProjectID = Drow["PROJECT_ID"].ToString(); CCReport.RoadwayName = Drow["ROADWAY_NAME"].ToString(); CCReport.Direction = GetDirection(Drow["DIRECTION"].ToString()); CCReport.BeginCrossStreet= Drow["BEGIN_CROSS_STREET"].ToString(); CCReport.EndCrossStreet = GetDirection(Drow["END_CROSS_STREET"].ToString()); CCReport.BeginLatitude = Drow["BEGIN_LATITUDE"].ToString(); CCReport.BeginLongitude = Drow["BEGIN_LONGITUDE"].ToString(); CCReport.PlannedStartTime = Drow["CLOSURE_START_DATE"].ToString(); CCReport.PlannedEndTime = Drow["CLOSURE_END_DATE"].ToString(); CCReport.ClosureDescription = Drow["CLOSURE_DESCRIPTION"].ToString(); CCReport.TypeOfWork= Drow["TYPE_OF_WORK"].ToString(); CCReport.ContactPerson= Drow["CONTACT_PERSON"].ToString(); CCReport.AreaOffice = Drow["AREA_OFFICE"].ToString(); CCReport.ContactPhoneNumber = Drow["CONTACT_PHONE_NUMBER"].ToString(); CCReport.ClosureMapLocation = Drow["CLOSURE_MAP_LOCATION"].ToString(); CCReport.ClosureHotSpot = Drow["CLOSURE_HOT_SPOT"].ToString(); CCReport.CountyName = Drow["COUNTY_NAME"].ToString(); CCReport.FacilityType = Drow["FACILITY_TYPE"].ToString(); CCReport.TranStarNotification = Drow["TRANSTAR_NOTIFICATION"].ToString(); CCReport.ClosureDuration = Drow["CLOSURE_DURATION"].ToString(); CCReport.DurationDescription = Drow["DURATION_DESCRIPTION"].ToString(); CCReport.LanesAffected = Drow["LANES_AFFECTED"].ToString(); CCReport.DurationException = Drow["DURATION_EXCEPTION"].ToString(); CCReport.Detour = Drow["DETOUR"].ToString(); CCReport.Location = Drow["LOCATION"].ToString(); CCReport.Status = Drow["STATUS"].ToString(); CCReportList.Add(CCReport); } } } else Console.WriteLine("File does not exist."); Console.WriteLine ("Load ConstructionClosure Records:" + CCReportList.Count.ToString()); return CCReportList; } catch (Exception e) { Console.WriteLine("Load ConstructionClosure: Data is not available" + e.Message); //Environment.Exit(-1); using (StreamWriter w = File.AppendText(ErrorFile)) { w.WriteLine(DateTime.Now.ToString() + ": Load ConstructionClosure: Data is not available" + e.Message); } return CCReportList; } } static void GetUpdatedIncident(List<CCRecord> CCReportList) { // Comparing the CCReportList with the OldRecord: If no ID in the OldRecord => New alert; //If there's same ID in the OldRecord: go compare all the elements between the 2 records (in CCReportLIst and OldRecord), //if there's a change => Updated Record. If no change => Old, alrread sent alert about this record before. // Then, refresh te OldRecord with the CCReportList data. No need to care for day change any more since we don't check Status and Last Modification time DataRow DRow; NewCCCount = 0; NewRecords.Clear(); DateTime CurrentTime = DateTime.Now; int ReportedRecord; string UpdatedCheckFile = "C:\\production\\ConstructionProjectAlert\\checkupdate.dat"; string UpdateMessage = ""; try { if (FirstCycle <= 0) //First Time running { foreach (CCRecord CC in CCReportList) { if (CC.Status.ToString() != "Cleared") { DRow = NewRecords.NewRow(); DRow["ID"] = CC.ID; DRow["RecordStatus"] = "New"; DRow["Project_Id"] = CC.ProjectID; DRow["RoadwayName"] = CC.RoadwayName; DRow["Direction"] = CC.Direction; DRow["Status"] = CC.Status; DRow["Location"] = CC.Location; DRow["PlannedStartTime"] = CC.PlannedStartTime; DRow["PlannedEndTime"] = CC.PlannedEndTime; DRow["Latitude"] = CC.BeginLatitude; DRow["Longitude"] = CC.BeginLongitude; DRow["ClosureDuration"] = CC.ClosureDuration; DRow["FacilityType"] = CC.FacilityType; DRow["DurationException"] = CC.DurationException; DRow["DurationDescription"] = CC.DurationDescription; DRow["LanesAffected"] = CC.LanesAffected; DRow["Detour"] = CC.Detour; DRow["ClosureHotSpot"] = CC.ClosureHotSpot; NewRecords.Rows.Add(DRow); NewCCCount = NewCCCount + 1; } } }//end FirstCycle else //Consecutive time running { Console.WriteLine("Consecutive run"); foreach (CCRecord CC in CCReportList) { // Set this record as if it hasn't reported yet as default ReportedRecord = 0; //For each record in the CC.dat file, run through the array of previous updated CCs global array //to figure out if that CC already reported since last time or not foreach (DataRow DRow1 in OldRecords.Rows) { //check to see if this is the already reported record if (CC.ID.ToString() == DRow1["ID"].ToString()) { ReportedRecord = 1; //For old CC if (CC.RoadwayName.ToString() != DRow1["RoadwayName"].ToString() || CC.Direction.ToString() != DRow1["Direction"].ToString() || CC.BeginCrossStreet.ToString() != DRow1["BeginCrossStreet"].ToString() || CC.EndCrossStreet.ToString() != DRow1["EndCrossStreet"].ToString() || CC.BeginLatitude.ToString() != DRow1["Latitude"].ToString() || CC.BeginLongitude.ToString() != DRow1["Longitude"].ToString() || CC.CountyName.ToString() != DRow1["CountyName"].ToString() || CC.Location.ToString() != DRow1["Location"].ToString() || CC.ClosureMapLocation.ToString() != DRow1["ClosureMapLocation"].ToString()) { ReportedRecord = 2; //For Updated Location using (StreamWriter w1 = File.AppendText(UpdatedCheckFile)) { UpdateMessage = DateTime.Now.ToString() + ": " + DRow1["ID"].ToString() + "-" + ReportedRecord + "\n"; w1.WriteLine(UpdateMessage); } } if (CC.ClosureDescription.ToString() != DRow1["ClosureDescription"].ToString() || CC.TypeOfWork.ToString() != DRow1["TypeOfWork"].ToString() || CC.LanesAffected.ToString() != DRow1["LanesAffected"].ToString() || CC.ClosureDuration.ToString() != DRow1["ClosureDuration"].ToString() || CC.DurationException.ToString() != DRow1["DurationException"].ToString() || CC.Detour.ToString() != DRow1["Detour"].ToString() || CC.FacilityType.ToString() != DRow1["FacilityType"].ToString() || CC.ClosureHotSpot.ToString() != DRow1["ClosureHotSpot"].ToString()) { ReportedRecord = 3; //For Updated Closure Detail using (StreamWriter w1 = File.AppendText(UpdatedCheckFile)) { UpdateMessage = DateTime.Now.ToString() + ": " + DRow1["ID"].ToString() + "-" + ReportedRecord + "\n"; w1.WriteLine(UpdateMessage); } } if (CC.ContactPerson.ToString() != DRow1["ContactPerson"].ToString() || CC.AreaOffice.ToString() != DRow1["AreaOffice"].ToString() || CC.ContactPhoneNumber.ToString() != DRow1["ContactPhoneNumber"].ToString() || CC.PlannedStartTime.ToString() != DRow1["PlannedStartTime"].ToString() || CC.PlannedEndTime.ToString() != DRow1["PlannedEndTime"].ToString() || CC.TranStarNotification.ToString() != DRow1["TranStarNotification"].ToString()) { ReportedRecord = 4; //For Updated Official Contact using (StreamWriter w1 = File.AppendText(UpdatedCheckFile)) { UpdateMessage = DateTime.Now.ToString() + ": " + DRow1["ID"].ToString() + "-" + ReportedRecord + "\n"; w1.WriteLine(UpdateMessage); } } } } //Get only new reported/changed status record(s) if (ReportedRecord == 0 || ReportedRecord == 2 || ReportedRecord == 3 || ReportedRecord == 4) { DRow = NewRecords.NewRow(); DRow["ID"] = CC.ID.ToString(); switch (ReportedRecord) { case 0: { DRow["RecordStatus"] = "New"; break; } case 2: { DRow["RecordStatus"] = "Loc"; //Updated location break; } case 3: { DRow["RecordStatus"] = "Upd"; //Updated Detail break; } case 4: { DRow["RecordStatus"] = "Det"; //Update Offical break; } } DRow["Project_Id"] = CC.ProjectID; DRow["RoadwayName"] = CC.RoadwayName; DRow["Direction"] = CC.Direction; DRow["Status"] = CC.Status; DRow["Location"] = CC.Location; DRow["PlannedStartTime"] = CC.PlannedStartTime; DRow["PlannedEndTime"] = CC.PlannedEndTime; DRow["Latitude"] = CC.BeginLatitude; DRow["Longitude"] = CC.BeginLongitude; DRow["ClosureDuration"] = CC.ClosureDuration; DRow["FacilityType"] = CC.FacilityType; DRow["DurationException"] = CC.DurationException; DRow["DurationDescription"] = CC.DurationDescription; DRow["LanesAffected"] = CC.LanesAffected; DRow["Detour"] = CC.Detour; DRow["ClosureHotSpot"] = CC.ClosureHotSpot; NewRecords.Rows.Add(DRow); NewCCCount = NewCCCount + 1; } } } //end consecutive run OldRecords.Clear(); //Refresh Old Record with data from CCREport foreach (CCRecord CC in CCReportList) { DRow = OldRecords.NewRow(); DRow["ID"] = CC.ID; DRow["Status"] = CC.Status; DRow["Project_Id"] = CC.ProjectID; DRow["Direction"] = CC.Direction; DRow["RoadwayName"] = CC.RoadwayName; DRow["BeginCrossStreet"] = CC.BeginCrossStreet; DRow["EndCrossStreet"] = CC.EndCrossStreet; DRow["Latitude"] = CC.BeginLatitude; DRow["Longitude"] = CC.BeginLongitude; DRow["PlannedStartTime"] = CC.PlannedStartTime; DRow["PlannedEndTime"] = CC.PlannedEndTime; DRow["ClosureDescription"] = CC.ClosureDescription; DRow["TypeOfWork"] = CC.TypeOfWork; DRow["ContactPerson"] = CC.ContactPerson; DRow["AreaOffice"] = CC.AreaOffice; DRow["ContactPhoneNumber"] = CC.ContactPhoneNumber; DRow["ClosureMapLocation"] = CC.ClosureMapLocation; DRow["Location"] = CC.Location; DRow["ClosureHotSpot"] = CC.ClosureHotSpot; DRow["CountyName"] = CC.CountyName; DRow["FacilityType"] = CC.FacilityType; DRow["TranStarNotification"] = CC.TranStarNotification; DRow["ClosureDuration"] = CC.ClosureDuration; DRow["DurationException"] = CC.DurationException; DRow["DurationDescription"] = CC.DurationDescription; DRow["LanesAffected"] = CC.LanesAffected; DRow["Detour"] = CC.Detour; OldRecords.Rows.Add(DRow); } LastRunTime = DateTime.Now; Console.WriteLine("Get Updated:" + NewRecords.Rows.Count.ToString()); }//end try catch (Exception e) { Console.WriteLine("GetUpdatedIncident Error: " + e.Message); using (StreamWriter w = File.AppendText(ErrorFile)) { w.WriteLine(DateTime.Now.ToString() + ": GetUpdatedIncident Error: " + e.Message); } //Environment.Exit(-1); NewRecords.Clear(); NewCCCount = 0; } } static void Processing() { SendMailCount = 0; try { Sendmail(); NewRecords.Clear(); if (SendMailCount <= 0) Console.WriteLine("No email sent at " + DateTime.Now.ToString("h:mm:ss tt")); else Console.WriteLine("Done! " + SendMailCount.ToString() + " alerts sent at " + DateTime.Now.ToString("h:mm:ss tt")); } catch (Exception e) { Console.WriteLine("Processing Error: " + e.Message); using (StreamWriter w = File.AppendText(ErrorFile)) { w.WriteLine(DateTime.Now.ToString() + ": Processing Error: " + e.Message); } // Environment.Exit(-1); } } static void Sendmail() { Console.WriteLine("FirstCycle = " + FirstCycle.ToString()); string AlertMessage = ""; string mapLink = ""; TimeSpan DTDiff; System.DateTime CurrentTime = DateTime.Now; //string[] SubscribedProjectID; //SubscribedProjectID = Drow["Project_ID"].ToString().Split(Convert.ToChar(";")); SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings.Get("emailserver").Trim()); string fromaddress = ConfigurationManager.AppSettings.Get("fromaddress").Trim(); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.IsBodyHtml = true; message.From = new MailAddress(fromaddress); //message.To.Add(Drow["EMAIL_ADDRESS"].ToString()); message.Subject = "Lane Closure Project Update"; try { //Loop through each SusciberRecord (email & many SubscribedProjectIDDate) in the global SubscribersList foreach (SubscriberRecord SubscriberValue in SubscribersList) { AlertMessage = ""; //Split the SubscribedProjectIDDate many Values //SubscriberValue.ProjectID_Date = ProjectID1_Date1;ProjectID2_Date2; string[] SubscribedProjectIDDate = SubscriberValue.ProjectID_Date.Split(Convert.ToChar(";")); //for each SubscribedProjectIDDate Value foreach (string ProjectIDDateValue in SubscribedProjectIDDate) { //Split to seperate EACH ProjectID and subscribed Date, then, depended on each date to query data from Old or New Record string[] temp = ProjectIDDateValue.Split(Convert.ToChar("_")); DTDiff = DateTime.Now.Subtract(Convert.ToDateTime(temp[1].ToString())); if (DTDiff.TotalMinutes <= 30) //new subscribed, use OldRecord { foreach (DataRow row in OldRecords.Rows) { if (temp[0].Trim() == row["Project_Id"].ToString().Trim() && row["Status"].ToString() != "Cleared") { AlertMessage += "<table style='width:520px; border:0px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;'cellspacing='2px' cellpadding='2px'>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>" + GetImage(row["RoadwayName"].ToString()) + "</td>"; AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + "</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: Silver;'cellspacing='0px' cellpadding='0px'>"; AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>LOCATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["Location"].ToString().Trim() + "</td></tr>"; if (row["LanesAffected"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>CLOSED</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["LanesAffected"].ToString().Trim() + "</td></tr>"; if (row["DurationDescription"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DURATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["DurationDescription"].ToString().Trim() + "</td></tr>"; if (row["Detour"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DETOUR</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + GetStringValue(row["Detour"].ToString().Trim()) + "</td></tr>"; if (row["Latitude"].ToString().Trim() != "-1" || row["Longitude"].ToString().Trim() != "-1") { mapLink = "https://traffic.houstontranstar.org/layers/layers_ve.aspx?z=15&lc=true&x=" + row["Latitude"].ToString().Trim() + "&y=" + row["Longitude"].ToString().Trim(); AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>MAP</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'><a href='" + mapLink + "'>View closure on map</a></td></tr>"; } AlertMessage += "</table></td></tr></table><br/>"; } } } else //Old subscriber, use NewRecord (Updated) { foreach (DataRow row in NewRecords.Rows) if (temp[0].Trim() == row["Project_Id"].ToString().Trim()) { AlertMessage += "<table style='width:520px; border:0px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;'cellspacing='2px' cellpadding='2px'>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>" + GetImage(row["RoadwayName"].ToString()) + "</td>"; if (row["RecordStatus"].ToString() == "Cle") { AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + " - CLEARED</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: Silver;'cellspacing='0px' cellpadding='0px'>"; } else if (row["RecordStatus"].ToString() == "New") { if (FirstCycle > 0) AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + " - NEW</td></tr>"; else AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + "</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: Silver;'cellspacing='0px' cellpadding='0px'>"; } else { AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + " - UPDATE</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: #f9f6d6;'cellspacing='0px' cellpadding='0px'>"; } //if (row["RecordStatus"].ToString() == "Loc") //AlertMessage += "<tr><td style='width: 80px; color:Red; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>LOCATION:</td><td style='width: 410px; color: Red; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["Location"].ToString().Trim() + "</td></tr>"; // else AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>LOCATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["Location"].ToString().Trim() + "</td></tr>"; if (row["LanesAffected"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>CLOSED</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["LanesAffected"].ToString().Trim() + "</td></tr>"; if (row["DurationDescription"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DURATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["DurationDescription"].ToString().Trim() + "</td></tr>"; if (row["Detour"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DETOUR</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + GetStringValue(row["Detour"].ToString().Trim()) + "</td></tr>"; if (row["Latitude"].ToString().Trim() != "-1" || row["Longitude"].ToString().Trim() != "-1") { mapLink = "https://traffic.houstontranstar.org/layers/layers_ve.aspx?z=15&lc=true&x=" + row["Latitude"].ToString().Trim() + "&y=" + row["Longitude"].ToString().Trim(); AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>MAP</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'><a href='" + mapLink + "'>View closure on map</a></td></tr>"; } AlertMessage += "</table></td></tr></table><br/>"; } } } //if (AlertMessage != "") if (AlertMessage != "" && FirstCycle > 0) //Not send mail on 1st Cycle => Not rerun the programe when make changes { AlertMessage = "<p style='color: Black; font: bold 12px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>Project Lane Closure Update</p>" + AlertMessage; AlertMessage += "<p style='color: Black; font: italic 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>&copy " + DateTime.Now.Year.ToString() + " Houston TranStar. All rights reserved</p>"; message.To.Add(SubscriberValue.Email.ToString()); message.Body = AlertMessage; smtpClient.Send(message); message.To.Clear(); //smtpClient.Send(fromaddress, Drow["EMAIL_ADDRESS"].ToString(), "Construction Closure Alert", AlertMessage); SendMailCount += 1; using (StreamWriter w = File.AppendText(SentMessageFile)) { w.WriteLine(DateTime.Now.ToString() + ": " + SubscriberValue.Email.ToString()); } } } FirstCycle = 1; } catch (Exception e) { Console.WriteLine("SendMail Error: " + e.Message); using (StreamWriter w = File.AppendText(ErrorFile)) { w.WriteLine(DateTime.Now.ToString() + ": SendMail Error: " + e.Message); } // Environment.Exit(-1); FirstCycle = 1; } } static void Sendmail1(DataRow Drow, string RecordTable) { string AlertMessage = ""; string mapLink = ""; System.DateTime CurrentTime = DateTime.Now; string[] SubscribedProjectID; SubscribedProjectID = Drow["Project_ID"].ToString().Split(Convert.ToChar(";")); SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings.Get("emailserver").Trim()); string fromaddress = ConfigurationManager.AppSettings.Get("fromaddress").Trim(); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.IsBodyHtml = true; message.From = new MailAddress(fromaddress); message.To.Add(Drow["EMAIL_ADDRESS"].ToString()); message.Subject = "Lane Closure Project Update"; try { if (RecordTable == "NewRecord") foreach (string SPI in SubscribedProjectID) { foreach (DataRow row in NewRecords.Rows) if (SPI.Trim() == row["Project_Id"].ToString().Trim()) { AlertMessage += "<table style='width:520px; border:0px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;'cellspacing='2px' cellpadding='2px'>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>" + GetImage(row["RoadwayName"].ToString()) + "</td>"; if (row["RecordStatus"].ToString() == "Cle") { AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + " - CLEARED</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: Silver;'cellspacing='0px' cellpadding='0px'>"; } else if (row["RecordStatus"].ToString() == "New") { if (FirstCycle > 0) AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + " - NEW</td></tr>"; else AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + "</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: Silver;'cellspacing='0px' cellpadding='0px'>"; } else { AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + " - UPDATE</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: #f9f6d6;'cellspacing='0px' cellpadding='0px'>"; } //if (row["RecordStatus"].ToString() == "Loc") //AlertMessage += "<tr><td style='width: 80px; color:Red; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>LOCATION:</td><td style='width: 410px; color: Red; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["Location"].ToString().Trim() + "</td></tr>"; // else AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>LOCATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["Location"].ToString().Trim() + "</td></tr>"; if (row["LanesAffected"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>CLOSED</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["LanesAffected"].ToString().Trim() + "</td></tr>"; if (row["DurationDescription"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DURATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["DurationDescription"].ToString().Trim() + "</td></tr>"; if (row["Detour"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DETOUR</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + GetStringValue(row["Detour"].ToString().Trim()) + "</td></tr>"; if (row["Latitude"].ToString().Trim() != "-1" || row["Longitude"].ToString().Trim() != "-1") { mapLink = "https://traffic.houstontranstar.org/layers/layers_ve.aspx?z=15&lc=true&x=" + row["Latitude"].ToString().Trim() + "&y=" + row["Longitude"].ToString().Trim(); AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>MAP</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'><a href='" + mapLink + "'>View closure on map</a></td></tr>"; } AlertMessage += "</table></td></tr></table><br/>"; } } else {// for new subcriber, who subscribed within the last 30 mins. foreach (string SPI in SubscribedProjectID) foreach (DataRow row in OldRecords.Rows) { if (SPI.Trim() == row["Project_Id"].ToString().Trim() && row["Status"].ToString() != "Cleared") { AlertMessage += "<table style='width:520px; border:0px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;'cellspacing='2px' cellpadding='2px'>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>" + GetImage(row["RoadwayName"].ToString()) + "</td>"; AlertMessage += "<td style='width: 490px; background-color: Black; color: White; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["RoadwayName"] + " " + row["Direction"] + "</td></tr>"; AlertMessage += "<tr><td style='width: 30px;' align='left'>&nbsp</td>"; AlertMessage += "<td style='width: 490px;' align='left'>"; AlertMessage += "<table style='width:490px; border:0px; background-color: Silver;'cellspacing='0px' cellpadding='0px'>"; AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>LOCATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["Location"].ToString().Trim() + "</td></tr>"; if (row["LanesAffected"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>CLOSED</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["LanesAffected"].ToString().Trim() + "</td></tr>"; if (row["DurationDescription"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DURATION</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + row["DurationDescription"].ToString().Trim() + "</td></tr>"; if (row["Detour"].ToString().Trim() != "") AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>DETOUR</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>" + GetStringValue(row["Detour"].ToString().Trim()) + "</td></tr>"; if (row["Latitude"].ToString().Trim() != "-1" || row["Longitude"].ToString().Trim() != "-1") { mapLink = "https://traffic.houstontranstar.org/layers/layers_ve.aspx?z=15&lc=true&x=" + row["Latitude"].ToString().Trim() + "&y=" + row["Longitude"].ToString().Trim(); AlertMessage += "<tr><td style='width: 80px; color:Maroon; vertical-align:top; font: bold 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>MAP</td><td style='width: 410px; font: 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'><a href='" + mapLink + "'>View closure on map</a></td></tr>"; } AlertMessage += "</table></td></tr></table><br/>"; } } } if (AlertMessage != "") { AlertMessage = "<p style='color: Black; font: bold 12px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>I-69/I-610 Lane Closure Update</p>" + AlertMessage; AlertMessage += "<p style='color: Black; font: italic 11px Verdana, Arial, Helvetica, Sans-Serif;' align='left'>&copy " + DateTime.Now.Year.ToString() + " Houston TranStar. All rights reserved</p>"; message.Body = AlertMessage; smtpClient.Send(message); //smtpClient.Send(fromaddress, Drow["EMAIL_ADDRESS"].ToString(), "Construction Closure Alert", AlertMessage); SendMailCount += 1; using (StreamWriter w = File.AppendText(SentMessageFile)) { w.WriteLine(DateTime.Now.ToString() + ": " + Drow["EMAIL_ADDRESS"].ToString()); } } FirstCycle = 1; // } } catch (Exception e) { Console.WriteLine("SendMail Error: " + e.Message); using (StreamWriter w = File.AppendText(ErrorFile)) { w.WriteLine(DateTime.Now.ToString() + ": SendMail Error: " + e.Message); } // Environment.Exit(-1); } } static int calculateSec(int hr1, int min1, int sec1) { int hour = hr1 * 3600; int min = min1 * 60; int totalseconds1 = hour + min + sec1; return totalseconds1; } static int calculateTime(int totalseconds1, int totalseconds2) { int timeelapsed = totalseconds1 - totalseconds2; return timeelapsed; } static string GetDirection(string value) { string returnV = ""; returnV = value.Replace("Northbound", "NB").Replace("Southbound", "SB").Replace("Eastbound", "EB").Replace("Westbound", "WB").Replace("and", "&"); returnV = returnV.Replace("northbound", "NB").Replace("southbound", "SB").Replace("eastbound", "EB").Replace("westbound", "WB"); return returnV; } static string GetStringValue(string value) { if (value == "") return "N/A"; else return value; } static string GetMapLocation(string Lat, string Lng) { return Lat + "+" + Lng; } static string GetImage(string FreewayName) { if (FreewayName.IndexOf("-45") >= 0) return "<img src='http:/traffic.houstontranstar.org/resources/images/I-45_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName.IndexOf("-610 ") >= 1) return "<img src='http:/traffic.houstontranstar.org/resources/images/I-610_svg_small.gif' border='0' width='20' height='16'/>"; else if (FreewayName.IndexOf("-69") >= 1) return "<img src='http:/traffic.houstontranstar.org/resources/images/us-69_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName.IndexOf("US-59") >= 0) return "<img src='http:/traffic.houstontranstar.org/resources/images/us-59_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName == "US-290") return "<img src='http:/traffic.houstontranstar.org/resources/images/us-290_svg_small.gif' border='1' width='20' height='20'/>"; else if (FreewayName == "IH-10 Katy" || FreewayName == "IH-10 East") return "<img src='http:/traffic.houstontranstar.org/resources/images/i-10_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName == "SH-288") return "<img src='http:/traffic.houstontranstar.org/resources/images/sh-288_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName == "SH-225") return "<img src='http:/traffic.houstontranstar.org/resources/images/sh-225_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName == "SH-146") return "<img src='http:/traffic.houstontranstar.org/resources/images/sh-146_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName == "SH-249") return "<img src='http:/traffic.houstontranstar.org/resources/images/sh-249_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName == "Spur-330") return "<img src='http:/traffic.houstontranstar.org/resources/images/spur-330_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName.IndexOf("Beltway") >= 0 || FreewayName.IndexOf("Belt") >= 0) return "<img src='http:/traffic.houstontranstar.org/resources/images/bw-8_svg_small.gif' border='0' width='20' height='20'/>"; else if (FreewayName == "Hardy Toll Road" || FreewayName == "Westpark Tollway") return "<img src='http:/traffic.houstontranstar.org/resources/images/hctra_icon.gif' width='20' border='0' height='20'/>"; //else if (FreewayName == "HOV") //return "<img src='http:/traffic.houstontranstar.org/resources/images/hov_icon.gif' width='20' border='0' height='20'/>"; else if (FreewayName == "Managed Lanes") return "<img src='http:/traffic.houstontranstar.org/resources/images/ih-10_managed_icon.gif' border='0' width='20' height='20'/>"; else return ""; } } }
d4006553f833876600e1f81c04138d5fee9dbbda
[ "C#" ]
3
C#
k-tran-ca/ConstructionProjectAlert
a5d1496e27ff0a37ce3624b9c0d182697bd70d8b
d261a629db60495700a8354cba8d13078d56253d
refs/heads/master
<file_sep>class EpicenterController < ApplicationController before_action :authenticate_user! def feed @following_tweets = [] Tweet.all.each do |tweet| if tweet.user_id == current_user.id || current_user.following.include?(tweet.user_id) @following_tweets.push tweet end end end def show_user @user =User.find(params[:id]) end def now_following end def unfollow end end <file_sep>class Tweet < ApplicationRecord belongs_to :user validates :message, presence: true validates :message, length: {maximum: 140, too_long: "You cannot have a tweet with more than 140 characters."} end
2fbf4ffec0b0d88f39838f64765ee596a21f3ead
[ "Ruby" ]
2
Ruby
mjclark2/MCTweet
b649dc9f1f5f4818054dd6e0ff5b9d3bbc1df720
a9197812d1e0b118b311bf00cc0d72d622fa48a1
refs/heads/main
<file_sep>const fullscreen = document.querySelector('.fullscreen').addEventListener('click', toggleScreen); const btnNotes = document.querySelector('.btn-notes'); const btnLetters = document.querySelector('.btn-letters'); btnNotes.addEventListener('click', activeBtns); btnLetters.addEventListener('click', activeBtns); const piano = document.querySelector('.piano'); const pianoКeys = document.querySelectorAll('.piano-key'); let flagKeyboard = false; let flagMouse = false; function toggleScreen() { if (!document.fullscreenElement) { document.documentElement.requestFullscreen(); } else { if (document.fullscreenEnabled) { document.exitFullscreen(); } } } function activeBtns(e) { if (e.target.classList.contains('btn-letters') && !e.target.classList.contains('btn-active')) { btnLetters.classList.add('btn-active'); btnNotes.classList.remove('btn-active'); pianoКeys.forEach(key => key.classList.add('key-active')); } else if (e.target.classList.contains('btn-notes') && !e.target.classList.contains('btn-active')) { btnNotes.classList.add('btn-active'); btnLetters.classList.remove('btn-active'); pianoКeys.forEach(key => key.classList.remove('key-active')); } } function playSound(e) { let audio = null; if (e.type === 'keydown') { if (flagKeyboard) return; flagKeyboard = true; const code = e.code.slice(3, e.code.length); const key = document.querySelector(`.piano-key[data-letter="${code}"]`); audio = document.querySelector(`audio[data-key="${code}"]`); if (!audio) return; audio.currentTime = 0; audio.play(); key.classList.add('piano-key-active'); } else if (e.type === 'keyup') { flagKeyboard = false; const code = e.code.slice(3, e.code.length); const key = document.querySelector(`.piano-key[data-letter="${code}"]`); if (!key) return; key.classList.remove('piano-key-active'); } else if (e.type === 'mousedown') { flagMouse = true; const code = e.target.dataset.letter; audio = document.querySelector(`audio[data-key="${code}"]`); audio.currentTime = 0; audio.play(); e.target.classList.add('piano-key-active'); } else if (e.type === 'mouseup') { flagMouse = false; e.target.classList.remove('piano-key-active'); } else if (e.type === 'mouseover') { if (flagMouse) { const code = e.target.dataset.letter; audio = document.querySelector(`audio[data-key="${code}"]`); if (!audio) return; audio.currentTime = 0; audio.play(); e.target.classList.add('piano-key-active'); } } else if (e.type === 'mouseout') { e.target.classList.remove('piano-key-active') } } window.addEventListener('keydown', (e) => playSound(e)); window.addEventListener('keyup', (e) => playSound(e)); piano.addEventListener('mousedown', (e) => playSound(e)); piano.addEventListener('mouseup', (e) => playSound(e)); piano.addEventListener('mouseover', (e) => playSound(e)); piano.addEventListener('mouseout', (e) => playSound(e)); document.addEventListener('mouseup', (e) => playSound(e));<file_sep># virtual-piano-js
47aaa879980d47e0169d2fcbfc7ee22006d6485a
[ "JavaScript", "Markdown" ]
2
JavaScript
vladimirkozak/virtual-piano-js
1a567d78ffdcea62854d9d74fc27d74567b334c6
4d466fbe37a84989487d8e7155c9f048cbcc2979
refs/heads/main
<repo_name>piwedlanjwa-ux/casetrek-repo<file_sep>/HR/dashboard.php <?php // Initialize the session session_start(); // Check if the user is logged in, if not then redirect him to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){ header("location: /GitHub/casetrek/index.php"); exit; } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="icon" type="image/png" sizes="32x32" href="assets/images/favicon.ico"> <title>Dashboard</title> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="assets/css/bootstrap.min.css"> <link href="assets/css/DataTables/DataTables-1.10.20/css/dataTables.bootstrap4.css" rel="stylesheet"> <!-- Our Custom CSS --> <link rel="stylesheet" href="assets/css/style4.css"> <!-- Font Awesome JS --> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="<KEY>" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="<KEY>" crossorigin="anonymous"></script> <style> .modals { position: fixed; top: 120px !important; right: 0; padding: 0px 30px; left: 0; z-index: 1050; display: none; overflow: hidden; outline: 0; } /* Modal Content */ .modal-content { background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; width: 80%; color: black } /* The Close Button */ .close { color: #aaaaaa; float: right; font-size: 28px; font-weight: bold; } .close:hover, .close:focus { color: #000; text-decoration: none; cursor: pointer; } #myBtn{ background-color: inherit; border: none; color: white; cursor: pointer; } </style> <script> window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { animationEnabled: true, theme: "light2", title:{ text: "Simple Line Chart" }, axisY:{ includeZero: false }, data: [{ type: "line", indexLabelFontSize: 16, dataPoints: [ { y: 450 }, { y: 414}, { y: 520, indexLabel: "\u2191 highest",markerColor: "red", markerType: "triangle" }, { y: 460 }, { y: 450 }, { y: 500 }, { y: 480 }, { y: 480 }, { y: 410 , indexLabel: "\u2193 lowest",markerColor: "DarkSlateGrey", markerType: "cross" }, { y: 500 }, { y: 480 }, { y: 510 } ] }] }); chart.render(); } </script> </head> <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar"> <div class="sidebar-header"> <h3><a href="dashboard.php"><img src="assets/images/logo.png" style="width: 200px; height: auto;" ></a></h3> <strong><a href="dashboard.php"><img src="assets/images/logo2.png" style="width: 70px; height: auto; margin: auto; padding-bottom: 10px; padding-right:10px;" ></a></strong> <span style="font-size: 13px;">Welcome<br><?php echo htmlspecialchars($_SESSION["firstName"]); echo " "; echo htmlspecialchars($_SESSION["lastName"]); echo "<br>"; echo htmlspecialchars($_SESSION["userType"]);?></span> </div> <ul class="list-unstyled components"> <li class="active"> <a href="#homeSubmenu" > <img src="https://img.icons8.com/carbon-copy/30/ffffff/details.png"> Dashboard </a> </li> <li> <a href="#casesSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/wired/30/ffffff/soccer-yellow-card.png"> Cases </a> <ul class="collapse list-unstyled" id="casesSubmenu"> <li> <a href="ViewCases.php">View Cases</a> </li> <li> <a href="AddCase.php">Add Case</a> </li> <li> <a href="activeCases.php">Active Cases</a> </li> </ul> </li> <li> <a href="#employeesSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/ios/30/ffffff/conference-background-selected.png"> Employees </a> <ul class="collapse list-unstyled" id="employeesSubmenu"> <li> <a href="ViewEmployees.php">View Employees</a> </li> <li> <a href="AddEmployees.php">Add Employees</a> </li> </ul> </li> <li> <a href="#usersSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/dotty/30/ffffff/add-user-group-woman-man.png"> Users </a> <ul class="collapse list-unstyled" id="usersSubmenu"> <li> <a href="ViewUsers.php">View Users</a> </li> <li> <a href="AddUser.php">Add User</a> </li> </ul> </li> </ul> </nav> <!-- Page Content --> <div id="content"> <div class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <button type="button" id="sidebarCollapse" class="btn btn-info"> <img src="https://img.icons8.com/android/24/70a4cd/menu.png"> </button> <ul class=" navbar-right"> <li class="nav-item dropdown open show" style="padding-left: 15px;"> <a href="javascript:;" class="user-profile dropdown-toggle" aria-haspopup="true" id="navbarDropdown" data-toggle="dropdown" aria-expanded="true"> <?php echo htmlspecialchars($_SESSION["firstName"]); echo " "; echo htmlspecialchars($_SESSION["lastName"]);?> <img src="https://img.icons8.com/android/16/000000/expand-arrow.png"> </a> <div class="dropdown-menu dropdown-usermenu pull-right " aria-labelledby="navbarDropdown" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(10px, 21px, 0px);"> <a class="dropdown-item" href="profile.php"> Profile</a> <a class="dropdown-item" href="/GitHub/casetrek/logout.php"><img src="https://img.icons8.com/metro/17/000000/exit.png"> Log Out</a> </div> </li> </ul> </div> </div> <br><br> <div class="container"> <div class="row"> <?php include "DBConnection.php"; $SQLString = "SELECT * FROM `casestb` "; $QueryResult = $DBConnect->query($SQLString); if($QueryResult) { if($QueryResult->num_rows>0) { $count = $QueryResult->num_rows; echo' <div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-primary o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-card-list" viewBox="0 0 16 16"> <path d="M14.5 3a.5.5 0 0 1 .5.5v9a.5.5 0 0 1-.5.5h-13a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5h13zm-13-1A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h13a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-13z"/> <path d="M5 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 5 8zm0-2.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0 5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-1-5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zM4 8a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm0 2.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0z"/> </svg> </div> <div class="mr-5"> '. $count . ' Total Cases</div> </div> <a class="card-footer text-white clearfix small z-1" href="ViewCases.php"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fa fa-angle-right"></i> </span> </a> </div> </div>'; } else { echo '<div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-primary o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-card-list" viewBox="0 0 16 16"> <path d="M14.5 3a.5.5 0 0 1 .5.5v9a.5.5 0 0 1-.5.5h-13a.5.5 0 0 1-.5-.5v-9a.5.5 0 0 1 .5-.5h13zm-13-1A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h13a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-13z"/> <path d="M5 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 5 8zm0-2.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm0 5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm-1-5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zM4 8a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0zm0 2.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0z"/> </svg> </div> <div class="mr-5"> 0 Cases </div> </div> <a class="card-footer text-white clearfix small z-1" href="ViewCases.php"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fa fa-angle-right"></i> </span> </a> </div> </div>'; } } $SQLString = "SELECT * FROM `closed_casestb` WHERE status='Open'"; $QueryResult = $DBConnect->query($SQLString); if($QueryResult) { if($QueryResult->num_rows>0) { $count = $QueryResult->num_rows; echo ' <div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-warning o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-folder-open"></i> </div> <div class="mr-5">'. $count . ' Active Cases</div> </div> <a class="card-footer text-white clearfix small z-1" href="activeCases.php"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fa fa-angle-right"></i> </span> </a> </div> </div>'; } else { echo '<div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-warning o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-folder-open"></i> </div> <div class="mr-5">0 Active Cases</div> </div> <a class="card-footer text-white clearfix small z-1" href="Active Cases"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fa fa-angle-right"></i> </span> </a> </div> </div>'; } } $SQLString = "SELECT * FROM `closed_casestb` WHERE sanction='Dismissal'"; $QueryResult = $DBConnect->query($SQLString); if($QueryResult) { if($QueryResult->num_rows>0) { $count = $QueryResult->num_rows; echo '<div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-success o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-user-minus"></i> </div> <div class="mr-5">' . $count . ' Dismissals!</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <button id="myBtn"><i class="fa fa-angle-right"></i></button> </span> </a> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <div class="table-responsive-sm"> <table id="example" class="table table-hover table-striped table-sm"> <thead> <tr> <td>Case No.</td> <td>Employee Name</td> <td>Department</td> <td>Job Title</td> <td>Date of Dismissal</td> </tr> </thead>'; while($rows = mysqli_fetch_array($QueryResult)) { $id=$rows['case_id']; $SQLString2 = "SELECT * FROM `casestb` WHERE case_id=$id"; $QueryResult2 = $DBConnect->query($SQLString2); $row = mysqli_fetch_array($QueryResult2); echo '<tr> <td>'. $rows["case_id"] . '</td> <td>'. $row["employee_name"] . '</td> <td>'. $row["department"] . '</td> <td>'. $row["position"] . '</td> <td>'. $rows["date_of_dismissal"] . '</td> </tr>'; } echo ' </table> </div> </div> </div> </div> </div>' ; } else { echo '<div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-success o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <i class="fas fa-user-minus"></i> </div> <div class="mr-5">0 Dismissals</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fa fa-angle-right"></i> </span> </a> </div> </div>'; } } $SQLString = "SELECT * FROM `closed_casestb` WHERE status='Active'"; $QueryResult = $DBConnect->query($SQLString); if($QueryResult) { if($QueryResult->num_rows>0) { $count = $QueryResult->num_rows; echo '<div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-danger o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-hourglass-split" viewBox="0 0 16 16"> <path d="M2.5 15a.5.5 0 1 1 0-1h1v-1a4.5 4.5 0 0 1 2.557-4.06c.29-.139.443-.377.443-.59v-.7c0-.213-.154-.451-.443-.59A4.5 4.5 0 0 1 3.5 3V2h-1a.5.5 0 0 1 0-1h11a.5.5 0 0 1 0 1h-1v1a4.5 4.5 0 0 1-2.557 4.06c-.29.139-.443.377-.443.59v.7c0 .213.154.451.443.59A4.5 4.5 0 0 1 12.5 13v1h1a.5.5 0 0 1 0 1h-11zm2-13v1c0 .537.12 1.045.337 1.5h6.326c.216-.455.337-.963.337-1.5V2h-7zm3 6.35c0 .701-.478 1.236-1.011 1.492A3.5 3.5 0 0 0 4.5 13s.866-1.299 3-1.48V8.35zm1 0v3.17c2.134.181 3 1.48 3 1.48a3.5 3.5 0 0 0-1.989-3.158C8.978 9.586 8.5 9.052 8.5 8.351z"/> </svg> </div> <div class="mr-5">' . $count . ' Active Sanctions!</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fa fa-angle-right"></i> </span> </a> </div> </div>'; } else { echo '<div class="col-xl-3 col-sm-6 mb-3"> <div class="card text-white bg-success o-hidden h-100"> <div class="card-body"> <div class="card-body-icon"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-hourglass-split" viewBox="0 0 16 16"> <path d="M2.5 15a.5.5 0 1 1 0-1h1v-1a4.5 4.5 0 0 1 2.557-4.06c.29-.139.443-.377.443-.59v-.7c0-.213-.154-.451-.443-.59A4.5 4.5 0 0 1 3.5 3V2h-1a.5.5 0 0 1 0-1h11a.5.5 0 0 1 0 1h-1v1a4.5 4.5 0 0 1-2.557 4.06c-.29.139-.443.377-.443.59v.7c0 .213.154.451.443.59A4.5 4.5 0 0 1 12.5 13v1h1a.5.5 0 0 1 0 1h-11zm2-13v1c0 .537.12 1.045.337 1.5h6.326c.216-.455.337-.963.337-1.5V2h-7zm3 6.35c0 .701-.478 1.236-1.011 1.492A3.5 3.5 0 0 0 4.5 13s.866-1.299 3-1.48V8.35zm1 0v3.17c2.134.181 3 1.48 3 1.48a3.5 3.5 0 0 0-1.989-3.158C8.978 9.586 8.5 9.052 8.5 8.351z"/> </svg> </div> <div class="mr-5">0 Active Sanctions</div> </div> <a class="card-footer text-white clearfix small z-1" href="#"> <span class="float-left">View Details</span> <span class="float-right"> <i class="fa fa-angle-right"></i> </span> </a> </div> </div>'; } } ?> </div> <div class="row"> <div class="col-xl-6"> <div class="card mb-4"> <div class="card-header"> <i class="fas fa-chart-area mr-1"></i> Disciplinary Hearings Per Month </div> <div class="card-body"><canvas id="myAreaChart" width="100%" height="40"></canvas></div> </div> </div> <div class="col-xl-6"> <div class="card mb-4"> <div class="card-header"> <i class="fas fa-chart-bar mr-1"></i> Cases Per Month </div> <div class="card-body"><canvas id="myBarChart" width="100%" height="40"></canvas></div> </div> </div> </div> <div class="card mb-4"> <div class="card-header"> <i class="fas fa-table mr-1"></i> Cases Per Category Per Department </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Department</th> <th>Absense</th> <th>Instructions</th> <th>Work Performance</th> <th>Organisational Property</th> <th>Service Management</th> </tr> </thead> <tfoot> <tr> <th></th> <th>18</th> <th>19</th> <th>21</th> <th>24</th> <th>2</th> </tr> </tfoot> <tbody> <tr> <td>Construction</td> <td>4</td> <td>6</td> <td>8</td> <td>10</td> <td>12</td> </tr> <tr> <td>Service Management</td> <td>41</td> <td>61</td> <td>81</td> <td>1</td> <td>2</td> </tr> <tr> <td>IT</td> <td>4</td> <td>6</td> <td>8</td> <td>10</td> <td>12</td> </tr> <tr> <td>Finance</td> <td>41</td> <td>61</td> <td>81</td> <td>1</td> <td>2</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> <!-- jQuery CDN - Slim version (=without AJAX) --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Popper.JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Bootstrap JS --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="assets/js/Chart.js-master/Chart.min.js"></script> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> <script src="assets/css/DataTables/DataTables-1.10.20/js/jquery.dataTables.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" crossorigin="anonymous"></script> <script src="assets/demo/chart-area-demo.js"></script> <script src="assets/demo/chart-bar-demo.js"></script> <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js" crossorigin="anonymous"></script> <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js" crossorigin="anonymous"></script> <script src="assets/demo/datatables-demo.js"></script> <script src="assets/css/DataTables/DataTables-1.10.20/js/dataTables.bootstrap4.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#sidebarCollapse').on('click', function () { $('#sidebar').toggleClass('active'); }); }); </script> <script> $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] } ); } ); </script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Load google charts google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); // Draw the chart and set the chart values function drawChart() { var data = google.visualization.arrayToDataTable([ ['Dismissal', 'Hours per Day'], ['Written Warnings', 8], ['Suspensions', 2], ['Disciplinary Hearings', 4], ['Verbal Warnings', 8] ]); // Optional; add a title and set the width and height of the chart var options = {'title':'My Average Day', 'width':550, 'height':400}; // Display the chart inside the <div> element with id="piechart" var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> <script> // Get the modal var modal = document.getElementById("myModal"); // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } </script> </body> </html><file_sep>/admin/ViewSubcategories.php <?php // Initialize the session session_start(); // Check if the user is logged in, if not then redirect him to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){ header("location: login.php"); exit; } use Phppot\DataSource; require_once 'DataSource.php'; $db = new DataSource(); $connect = $db->getConnection(); if (isset($_POST["import"])) { $fileName = $_FILES["file"]["tmp_name"]; if ($_FILES["file"]["size"] > 0) { $file = fopen($fileName, "r"); while (($column = fgetcsv($file, 10000, ",")) !== FALSE) { $subcategory_name= ""; if (isset($column[0])) { $subcategory_name = mysqli_real_escape_string($connect, $column[0]); } $category= ""; if (isset($column[1])) { $category = mysqli_real_escape_string($connect, $column[1]); } $sqlInsert = "INSERT into charge_subcategorytbl (subcategory_name, category) values (?, ?)"; $paramType = "ss"; $paramArray = array( $subcategory_name, $category ); $insertId = $db->insert($sqlInsert, $paramType, $paramArray); if (! empty($insertId)) { $type = "success"; $message = "CSV Data Imported into the Database"; } else { $type = "error"; $message = "Problem in Importing CSV Data"; } } } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="icon" type="image/png" sizes="32x32" href="assets/images/favicon.ico"> <title>Schedule of Offences</title> <style> body { background: #555; } .content { max-width: 600px; margin: auto; background: white; padding: 8%; padding-top: 10%; border: 1px grey; } @font-face { font-family: 'Dosis'; font-style: normal; font-weight: 300; src: local('Dosis Light'), local('Dosis-Light'), url(http://fonts.gstatic.com/l/font?kit=RoNoOKoxvxVq4Mi9I4xIReCW9eLPAnScftSvRB4WBxg&skey=a88ea9d907460694) format('woff2'); } @font-face { font-family: 'Dosis'; font-style: normal; font-weight: 500; src: local('Dosis Medium'), local('Dosis-Medium'), url(http://fonts.gstatic.com/l/font?kit=Z1ETVwepOmEGkbaFPefd_-CW9eLPAnScftSvRB4WBxg&skey=21884fc543bb1165) format('woff2'); } body { background: #d2d6de; font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif, Open Sans; font-size: 14px; line-height: 1.42857; height: 350px; padding: 0; margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 400; overflow-x: hidden; overflow-y: auto; } .table tbody tr td a { color: #007bff !important; text-align: center; } .table tbody tr td a:hover{ color: #142538 !important; } .form-control { background-color: #ffffff; background-image: none; border: 1px solid #999999; border-radius: 19 !important; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset; color: #333333; display: block; font-size: 14px; height: 34px; line-height: 1.42857; padding: 6px 12px; transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s; width: 100%; } .form-control{width:100% !important;} .login-box, .register-box { width: 96%; margin: 7% auto; }.login-page, .register-page { background: #d2d6de; } .login-logo, .register-logo { font-size: 35px; text-align: center; margin-bottom: 25px; font-weight: 300; }.login-box-msg, .register-box-msg { margin: 0; text-align: center; padding: 0 20px 20px 20px; }.login-box-body, .register-box-body { background: #fff; padding: 20px; border-top: 0; color: #666; border-radius: 8px; }.has-feedback { position: relative; } .form-group { margin-bottom: 15px; }.has-feedback .form-control { padding-right: 42.5px; }.login-box-body .form-control-feedback, .register-box-body .form-control-feedback { color: #777; } .form-control-feedback { position: absolute; top: 0; right: 0; z-index: 2; display: block; width: 34px; height: 34px; line-height: 34px; text-align: center; pointer-events: none; }.checkbox, .radio { position: relative; display: block; margin-top: 10px; margin-bottom: 10px; }.icheck>label { padding-left: 0; } .checkbox label, .radio label { min-height: 20px; padding-left: 20px; margin-bottom: 0; font-weight: 400; cursor: pointer; } table { counter-reset: row-num -1; } table tr { counter-increment: row-num; } table tr td:first-child::before { content: counter(row-num); } </style> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="assets/css/bootstrap.min.css"> <!-- Our Custom CSS --> <link rel="stylesheet" href="assets/css/style4.css"> <!-- Font Awesome JS --> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="<KEY>" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="<KEY>" crossorigin="anonymous"></script> </head> <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar"> <div class="sidebar-header"> <h3><a href="dashboard.php"><img src="assets/images/logo.png" style="width: 200px; height: auto;" ></a></h3> <strong><a href="dashboard.php"><img src="assets/images/logo2.png" style="width: 70px; height: auto; margin: auto; padding-bottom: 10px;" ></a></strong> <span style="font-size: 15px;">Welcome<br><?php echo htmlspecialchars($_SESSION["firstName"]); echo " "; echo htmlspecialchars($_SESSION["lastName"]);?></span> </div> <ul class="list-unstyled components"> <li> <a href="dashboard.php" > <img src="https://img.icons8.com/carbon-copy/30/ffffff/details.png"> Dashboard </a> </li> <li> <a href="#casesSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/wired/30/ffffff/soccer-yellow-card.png"> Cases </a> <ul class="collapse list-unstyled" id="casesSubmenu"> <li> <a href="ViewCases.php">View Cases</a> </li> <li> <a href="AddCase.php">Add Case</a> </li> <li> <a href="activeCases.php">Active Cases</a> </li> </ul> </li> <li> <a href="#employeesSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/ios/30/ffffff/conference-background-selected.png"> Employees </a> <ul class="collapse list-unstyled" id="employeesSubmenu"> <li> <a href="ViewEmployees.php">View Employees</a> </li> <li> <a href="AddEmployees.php">Add Employees</a> </li> </ul> </li> <li> <a href="#usersSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/dotty/30/ffffff/add-user-group-woman-man.png"> Users </a> <ul class="collapse list-unstyled" id="usersSubmenu"> <li> <a href="ViewUsers.php">View Users</a> </li> <li> <a href="AddUser.php">Add User</a> </li> </ul> </li> <li> <a href="#departmentsSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/carbon-copy/30/ffffff/department.png"/> Departments </a> <ul class="collapse list-unstyled" id="departmentsSubmenu"> <li> <a href="ViewDepartments.php">View Departments</a> </li> <li> <a href="AddDepartment.php">Add Departments</a> </li> </ul> </li> <li> <a href="#positionsSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/wired/30/ffffff/job.png"/> Job Titles </a> <ul class="collapse list-unstyled" id="positionsSubmenu"> <li> <a href="ViewPositions.php">View Job Titles</a> </li> <li> <a href="AddPosition.php">Add Job Title</a> </li> </ul> </li> <li class="active"> <a href="#categoriesSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/carbon-copy/30/ffffff/category.png"/> Schedule of Offences </a> <ul class="collapse list-unstyled" id="categoriesSubmenu"> <li> <a href="ViewSubcategories.php">View Schedule of Offences</a> </li> <li> <a href="AddSubcategory.php">Add Schedule of Offences</a> </li> </ul> </li> </ul> </nav> <!-- Page Content --> <div id="content"> <div class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <button type="button" id="sidebarCollapse" class="btn btn-info"> <img src="https://img.icons8.com/android/24/70a4cd/menu.png"> </button> <ul class=" navbar-right"> <li class="nav-item dropdown open show" style="padding-left: 15px;"> <a href="javascript:;" class="user-profile dropdown-toggle" aria-haspopup="true" id="navbarDropdown" data-toggle="dropdown" aria-expanded="true"> <?php echo htmlspecialchars($_SESSION["firstName"]); echo " "; echo htmlspecialchars($_SESSION["lastName"]);?> <img src="https://img.icons8.com/android/16/000000/expand-arrow.png"> </a> <div class="dropdown-menu dropdown-usermenu pull-right " aria-labelledby="navbarDropdown" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(10px, 21px, 0px);"> <a class="dropdown-item" href="profile.php"> Profile</a> <a class="dropdown-item" href="/GitHub/casetrek/logout.php"><img src="https://img.icons8.com/metro/17/000000/exit.png"> Log Out</a> </div> </li> </ul> </div> </div> <div class='login-box'> <div class='login-box-body'> <div class="table-title"> <div class="row"> <div class="col-sm-8"><h3><b>Schedule of Offences</b></h3></div> <div class="col-sm-4"> <a href="AddSubcategory.php"><button type="button" class="btn btn-primary add-new"><i class="fa fa-plus"></i> New Offence</button></a> </div> </div> <br> <div class="row"> <form class="form-horizontal" action="" method="post" name="frmCSVImport" id="frmCSVImport" enctype="multipart/form-data"> <div class="input-row"> <label class="col-sm-3 control-label">Choose CSV File</label> <input type="file" name="file" id="file" class="col-sm-4" accept=".csv"> <button type="submit" id="submit" name="import" class="col-sm-1 btn btn-primary add-new">Import</button> </div> </form> </div> </div> <br> <?php include "DBConnection.php"; $SQLString = "SELECT * FROM `charge_subcategorytbl`"; $QueryResult = $DBConnect->query($SQLString); $counter = 0; if($QueryResult) { if($QueryResult->num_rows>0) { echo "<div class='table-responsive'>"; echo "<table class='table table-hover table-striped table-sm'>"; echo "<tr><th></th><th>Subcategory</><th>Category</th><th>Action</th></tr>"; while($row = $QueryResult->fetch_assoc()) { echo "<tr><td></td>"; echo "<td>". $row['subcategory_name'] . "</td>"; echo "<td>". $row['category'] . "</td>"; echo "<td><a href ='EditSubcategory.php?id= " . $row['subcategory_id'] . "'><svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-pencil-square' viewBox='0 0 16 16'> <path d='M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z'/> <path fill-rule='evenodd' d='M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z'/> </svg></a> | <a href ='DeletePosition.php?id= " . $row['subcategory_id'] . "'><svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='currentColor' class='bi bi-trash' viewBox='0 0 16 16'> <path d='M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z'/> <path fill-rule='evenodd' d='M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z'/> </svg></a></td></tr>"; } echo "</table>"; echo "</div></div></div></div>"; } else { echo $DBConnect->error; } } ?> <!-- jQuery CDN - Slim version (=without AJAX) --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Popper.JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Bootstrap JS --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function () { $('#sidebarCollapse').on('click', function () { $('#sidebar').toggleClass('active'); }); }); </script> </body> </html><file_sep>/admin/DeletePosition.php <?php include("DBConnection.php"); $id = $_GET["id"]; $SQLString = "DELETE FROM positions WHERE pos_id=$id"; $QueryResult = $DBConnect->query($SQLString); if($QueryResult) { if($DBConnect->affected_rows > 0) { header("Location: ViewPositions.php"); } else { print "delete failed"; } } else { print "Error: " . $DBConnect->error; } ?> <file_sep>/manager/AddCaseFiles.php <?php // Initialize the session session_start(); // Check if the user is logged in, otherwise redirect to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){ header("location: login.php"); exit; } // Include config file require_once "/xampp/htdocs/GitHub/casetrek/DBConnection.php"; // Define variables and initialize with empty values $dateOfSitting = $charges = $chairman = $employerRep = $employeeRep = $department = $position = $employerWitness = $employeeWitness = $verdict = $sanction = $validation = $status = ""; $dateOfSitting_err = $charges_err = $chairman_err = $employerRep_err = $employeeRep_err = $department_err = $position_err = $employerWitness_err = $employeeWitness_err = $verdict_err = $sanction_err = $validation_err = $status_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ //Validate date of sitting if(empty(trim($_POST["dateOfSitting"]))) { $dateOfSitting_err = "Please select the date of the sitting."; } else { $dateOfSitting = trim($_POST["dateOfSitting"]); } //Validate charges if(empty(trim($_POST["charges"]))) { $charges_err = "Please enter the charges of this case"; } else { $charges = trim($_POST["charges"]); } // Validate chairman if(empty(trim($_POST["chairman"]))) { $chairman_err = "Please enter first and last name of the chairman."; } else { $chairman = trim($_POST["chairman"]); } //Validate employer representative if(empty($_POST["employerRep"])) { $employerRep_err = "Please enter first and last name of employer representative."; } else { $employerRep = trim($_POST["employerRep"]); } //Validate employee representative if(empty($_POST["employeeRep"])) { $employeeRep_err = "Please enter first and last name of the employee representative."; } else { $employeeRep = trim($_POST["employeeRep"]); } // Validate department if(empty(trim($_POST["department"]))) { $department_err = "Please enter department in which the employee is working under."; } else { $department = trim($_POST["department"]); } //Validate job title if(empty($_POST["position"])) { $position_err = "Please enter job title of the employee."; } else { $position = trim($_POST["position"]); } //declare employer witness $employerWitness = trim($_POST["employerWitness"]); //declare employee witness $employeeWitness = trim($_POST["employeeWitness"]); //Validate verdict if(empty($_POST["verdict"])) { $verdict_err = "Please select verdict."; } else { $verdict = trim($_POST["verdict"]); } //Validate sanction if(empty($_POST["sanction"])) { $sanction_err = "Please select sanction."; } else { $sanction = trim($_POST["sanction"]); } //Validate validation period if(empty($_POST["validation"])) { $validation_err = "Please select validation period."; } else { $validation = trim($_POST["validation"]); } //Validate status if(empty($_POST["status"])) { $status_err = "Please select status."; } else { $status = trim($_POST["status"]); } // Check input errors before inserting in database if(empty($dateOfSitting_err) && empty($chairman_err) && empty($employerRep_err) && empty($employeeRep_err) && empty($department_err) && empty($position_err) && empty($employerWitness_err) && empty($employeeWitness_err) && empty($verdict_err) && empty($sanction_err) && empty($validation_err) && empty($status_err)){ // Prepare an insert statement $sql = "INSERT INTO casestbl (dateOfSitting, chairman, employerRep, employeeRep, department, position, employerWitness, employeeWitness, verdict, sanction, validation, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; if($stmt = mysqli_prepare($DBConnect, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "ssssssssssss", $param_dateOfSitting, $param_chairman, $param_employerRep, $param_employeeRep, $param_department, $param_position, $param_employerWitness, $param_employeeWitness, $param_verdict, $param_sanction, $param_validation, $param_status); // Set parameters $param_dateOfSitting = $dateOfSitting; $param_chairman = $chairman; $param_employerRep = $employerRep; $param_employeeRep = $employeeRep; $param_department = $department; $param_position = $position; $param_employerWitness = $employerWitness; $param_employeeWitness = $employeeWitness; $param_verdict = $verdict; $param_sanction = $sanction; $param_validation = $validation; $param_status = $status; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ //Redirect to view cases page header("location: ViewCases.php"); } else{ echo "Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Close connection mysqli_close($DBConnect); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Add Case</title> <style> body { background: #555; } .content { max-width: 550px; margin: auto; background: white; border: 1px grey; } @font-face { font-family: 'Dosis'; font-style: normal; font-weight: 300; src: local('Dosis Light'), local('Dosis-Light'), url(http://fonts.gstatic.com/l/font?kit=RoNoOKoxvxVq4Mi9I4xIReCW9eLPAnScftSvRB4WBxg&skey=a88ea9d907460694) format('woff2'); } @font-face { font-family: 'Dosis'; font-style: normal; font-weight: 500; src: local('Dosis Medium'), local('Dosis-Medium'), url(http://fonts.gstatic.com/l/font?kit=Z1ETVwepOmEGkbaFPefd_-CW9eLPAnScftSvRB4WBxg&skey=21884fc543bb1165) format('woff2'); } body { background: #d2d6de; font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif, Open Sans; font-size: 14px; line-height: 1.42857; height: 350px; padding: 0; margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 400; overflow-x: hidden; overflow-y: auto; } .form-control { background-color: #ffffff; background-image: none; border: 1px solid #999999; border-radius: 0; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset; color: #333333; display: block; font-size: 14px; height: 34px; line-height: 1.42857; padding: 6px 12px; transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s; width: 122%; } .form-control{width:120% !important;} .login-box, .register-box { width: 1100px; margin: 7% auto; }.login-page, .register-page { background: #d2d6de; } .login-logo, .register-logo { font-size: 35px; text-align: center; margin-bottom: 25px; font-weight: 300; }.login-box-msg, .register-box-msg { margin: 0; text-align: center; padding: 0 20px 20px 20px; }.login-box-body, .register-box-body { background: #fff; padding: 20px; border-top: 0; color: #666; }.has-feedback { position: relative; } .form-group { margin-bottom: 15px; }.has-feedback .form-control { padding-right: 42.5px; }.login-box-body .form-control-feedback, .register-box-body .form-control-feedback { color: #777; } .form-control-feedback { position: absolute; top: 0; right: 0; z-index: 2; display: block; width: 34px; height: 34px; line-height: 34px; text-align: center; pointer-events: none; }.checkbox, .radio { position: relative; display: block; margin-top: 10px; margin-bottom: 10px; }.icheck>label { padding-left: 0; } .checkbox label, .radio label { min-height: 20px; padding-left: 20px; margin-bottom: 0; font-weight: 400; cursor: pointer; } </style> <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico"> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="/css/bootstrap.min.css"> <!-- Our Custom CSS --> <link rel="stylesheet" href="/css/style4.css"> <!-- Font Awesome JS --> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="<KEY>" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="<KEY> <KEY>" crossorigin="anonymous"></script> </head> <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar"> <div class="sidebar-header"> <h3><a href="dashboard.php"><img src="images/logo.png" style="width: 200px; height: auto;" ></a></h3> <strong><a href="dashboard.php"><img src="images/logo2.png" style="width: 70px; height: auto; margin: auto; padding-bottom: 10px;" ></a></strong> <span style="font-size: 15px;">Welcome<br><?php echo htmlspecialchars($_SESSION["firstName"]); echo " "; echo htmlspecialchars($_SESSION["lastName"]);?></span> </div> <ul class="list-unstyled components"> <li> <a href="dashboard.php" > <img src="https://img.icons8.com/carbon-copy/30/ffffff/details.png"> Dashboard </a> </li> <li class="active"> <a href="#casesSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/wired/30/ffffff/soccer-yellow-card.png"> Cases </a> <ul class="collapse list-unstyled" id="casesSubmenu"> <li> <a href="ViewCases.php">View Cases</a> </li> <li> <a href="AddCase.php">Add Case</a> </li> <li> <a href="activeCases.php">Active Cases</a> </li> </ul> </li> <li> <a href="#employeesSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/ios/30/ffffff/conference-background-selected.png"> Employees </a> <ul class="collapse list-unstyled" id="employeesSubmenu"> <li> <a href="ViewEmployees.php">View Employees</a> </li> <li> <a href="AddEmployees.php">Add Employees</a> </li> </ul> </li> <li> <a href="#usersSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"> <img src="https://img.icons8.com/dotty/30/ffffff/add-user-group-woman-man.png"> Users </a> <ul class="collapse list-unstyled" id="usersSubmenu"> <li> <a href="ViewUsers.php">View Users</a> </li> <li> <a href="AddUser.php">Add User</a> </li> </ul> </li> </ul> </nav> <!-- Page Content --> <div id="content"> <div class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <button type="button" id="sidebarCollapse" class="btn btn-info"> <img src="https://img.icons8.com/android/24/70a4cd/menu.png"> </button> <ul class=" navbar-right"> <li class="nav-item dropdown open show" style="padding-left: 15px;"> <a href="javascript:;" class="user-profile dropdown-toggle" aria-haspopup="true" id="navbarDropdown" data-toggle="dropdown" aria-expanded="true"> <?php echo htmlspecialchars($_SESSION["firstName"]); echo " "; echo htmlspecialchars($_SESSION["lastName"]);?> <img src="https://img.icons8.com/android/16/000000/expand-arrow.png"> </a> <div class="dropdown-menu dropdown-usermenu pull-right " aria-labelledby="navbarDropdown" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(10px, 21px, 0px);"> <a class="dropdown-item" href="profile.php"> Profile</a> <a class="dropdown-item" href="/GitHub/casetrek/logout.php"><img src="https://img.icons8.com/metro/17/000000/exit.png"> Log Out</a> </div> </li> </ul> </div> </div> <div class="login-box"> <div class="login-box-body"> <h1 class="login-box-msg">Add Charges</h1> <div class="form-group"> <<form action="upload-manager.php" method="post" enctype="multipart/form-data"> <h2>Upload File</h2> <label for="fileSelect">Filename:</label> <input type="file" name="photo" id="fileSelect"> <input type="submit" name="submit" value="Upload"> <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p> </form> </div> </div> </div> </div> <!-- jQuery CDN - Slim version (=without AJAX) --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Popper.JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Bootstrap JS --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function () { $('#sidebarCollapse').on('click', function () { $('#sidebar').toggleClass('active'); }); }); </script> <script> $(document).ready(function(){ var i=1; $('#add').click(function(){ i++; $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="charges[]" placeholder="Charge No. '+i+'" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>'); }); $(document).on('click', '.btn_remove', function(){ var button_id = $(this).attr("id"); $('#row'+button_id+'').remove(); }); $('#submit').click(function(){ $.ajax({ url:"name.php", method:"POST", data:$('#add_charge').serialize(), success:function(data) { alert(data); $('#add_charge')[0].reset(); } }); }); }); </script> </body> </html> <file_sep>/test-upload.php <?php /* Database credentials. Assuming you are running MySQL server with default setting (user 'root' with no password) */ define('DB_SERVER', '192.168.127.12'); define('DB_USERNAME', 'pbwdxvam_admin'); define('DB_PASSWORD', '<PASSWORD>'); define('DB_NAME', 'pbwdxvam_casetrek'); /* Attempt to connect to MySQL database */ $DBConnect = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); // Check connection if($DBConnect === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } if(isset($_POST['submit'])) { $pname = rand(1000,100000)."-".$_FILES["notes"]["name"]; $tname = $_FILES["notes"]["tmp_name"]; $uploads_dir = "/images"; //move_uploaded_file($tname, $uploads_dir."/".$pname); $sql = "INSERT INTO cases(notes) VALUES('$pname')"; if(mysqli_query($DBConnect, $sql)) { echo "successfully uploaded"; } else { echo "error"; } } ?> <!DOCTYPE html> <html> <head> <title>upload test</title> </head> <body> <h1> Upload </h1> <form method="POST" enctype="multipart/form-data"> <label>Upload Case Notes</label> <input type="file" name="notes" accept="application/pdf"/> <input type="submit" name="submit" value="Upload"/> </form><br><br> <?php $SQLString = "SELECT * FROM `cases`"; $QueryResult = $DBConnect->query($SQLString); $counter = 0; if($QueryResult) { if($QueryResult->num_rows>0) { echo "<div class='table-responsive'>"; echo "<table class='table table-hover table-striped table-sm'>"; echo "<tr><th></th><th>ID</th><th>File Name</th><th>Action</th></tr>"; while($row = $QueryResult->fetch_assoc()) { echo "<tr><td></td>"; echo "<td>". $row['file_id'] . "</td>"; echo "<td>". $row['filename'] . "</td>"; echo "<td><a href ='viewfile.php?id= " . $row['file_id'] . "'>View</a></td></tr>"; } echo "</table>"; echo "</div></div></div></div>"; } } ?> </body> </html><file_sep>/viewfile.php <?php define('DB_SERVER', '172.16.31.10'); define('DB_USERNAME', 'pbwdxvam_admin'); define('DB_PASSWORD', '<PASSWORD>'); define('DB_NAME', 'pbwdxvam_casetrek'); /* Attempt to connect to MySQL database */ $DBConnect = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); // Check connection if($DBConnect === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } if(isset($_GET['file_id'])) { $id = mysqli_real_escape_string($_GET["file_id"]); $query = mysqli_query("SELECT * FROM `cases` WHERE `file_id`='$id'"); while($row = mysqli_fetch_assoc($query)) { $fileData = $row['notes']; } header("content-type: application/pdf"); echo $fileData; } ?><file_sep>/HR/DeleteCase.php <?php include("DBConnection.php"); $id = $_GET["id"]; $SQLString = "DELETE FROM casestb WHERE case_id=$id"; $SQLString2 = "DELETE FROM closed_casestb WHERE case_id=$id"; $QueryResult = $DBConnect->query($SQLString); $QueryResult2 = $DBConnect->query($SQLString2); if($QueryResult&&$QueryResult2) { if($DBConnect->affected_rows > 0) { header("Location: ViewCases.php"); } else { print "delete failed"; } } else { print "Error: " . $DBConnect->error; } ?> <file_sep>/index.php <?php // Initialize the session session_start(); // Check if the user is already logged in, if yes then redirect him to index page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){ header("location: index.php"); exit; } // Include config file require_once "DBConnection.php"; // Define variables and initialize with empty values $email = $password = $userType = ""; $email_err = $password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if email is empty if(empty(trim($_POST["email"]))){ $email_err = "<span style='color: red;'>Please enter email.</span>"; } else{ $email = trim($_POST["email"]); } // Check if password is empty if(empty(trim($_POST["password"]))){ $password_err = "<span style='color: red;'>Please enter your password.</span>"; } else{ $password = trim($_POST["password"]); } // Validate credentials if(empty($email_err) && empty($password_err)){ // Prepare a select statement $sql = "SELECT user_id, firstName, lastName, email, password, userType FROM userstbl WHERE email = ?"; if($stmt = mysqli_prepare($DBConnect, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "s", $param_email); // Set parameters $param_email = $email; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ // Store result mysqli_stmt_store_result($stmt); // Check if email exists, if yes then verify password if(mysqli_stmt_num_rows($stmt) == 1){ // Bind result variables mysqli_stmt_bind_result($stmt, $user_id, $firstName, $lastName, $email, $hashed_password, $userType); if(mysqli_stmt_fetch($stmt)){ if(password_verify($password, $hashed_password)){ // Password is correct, so start a new session session_start(); // Store data in session variables $_SESSION["loggedin"] = true; $_SESSION["user_id"] = $user_id; $_SESSION["firstName"] = $firstName; $_SESSION["lastName"] = $lastName; $_SESSION["email"] = $email; $_SESSION["userType"] = $userType; if($_SESSION['userType'] == "System Admin") { // Redirect user to index page header("location: admin/dashboard.php"); } elseif($_SESSION['userType'] == "HR") { header("Location: HR/dashboard.php"); } else { header("Location: manager/dashboard.php"); } } else{ // Display an error message if password is not valid $password_err = "<span style='color: red;'>The password you entered is not valid.</span>"; } } } else{ // Display an error message if email doesn't exist $email_err = "<span style='color: red;'>No account found with that email address.</span>"; } } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Close connection mysqli_close($DBConnect); } ?> <!DOCTYPE html> <!-- 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. --> <html> <head> <meta charset="UTF-8"> <title>Login</title> <link rel="icon" type="image/png" sizes="32x32" href="assets/images/favicon.ico"> <style> body { background: #555; } .content { max-width: 500px; margin: auto; background: white; padding: 8%; padding-top: 15%; border: 1px grey; } @font-face { font-family: 'Dosis'; font-style: normal; font-weight: 300; src: local('Dosis Light'), local('Dosis-Light'), url(http://fonts.gstatic.com/l/font?kit=RoNoOKoxvxVq4Mi9I4xIReCW9eLPAnScftSvRB4WBxg&skey=a88ea9d907460694) format('woff2'); } @font-face { font-family: 'Dosis'; font-style: normal; font-weight: 500; src: local('Dosis Medium'), local('Dosis-Medium'), url(http://fonts.gstatic.com/l/font?kit=Z1ETVwepOmEGkbaFPefd_-CW9eLPAnScftSvRB4WBxg&skey=21884fc543bb1165) format('woff2'); } body { background: #d2d6de; font-family: 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif, Open Sans; font-size: 14px; line-height: 1.42857; height: 350px; padding: 0; margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 400; overflow-x: hidden; overflow-y: auto; } .form-control { background-color: #ffffff; background-image: none; border: 1px solid #999999; border-radius: 0; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset; color: #333333; display: block; font-size: 14px; height: 34px; line-height: 1.42857; padding: 6px 12px; transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s; width: 100%; } .login-box, .register-box { width: 480px; margin: 7% auto; background: #fff; border-radius: 8px; }.login-page, .register-page { background: #d2d6de; } .login-logo, .register-logo { font-size: 35px; text-align: center; font-weight: 300; }.login-box-msg, .register-box-msg { margin: 0; text-align: center; padding: 0 20px 20px 20px; }.login-box-body, .register-box-body { background: #fff; padding-left: 30px; padding-right: 30px; padding-bottom: 30px; color: #666; }.has-feedback { position: relative; } .form-group { margin-bottom: 15px; }.has-feedback .form-control { padding-right: 42.5px; }.login-box-body .form-control-feedback, .register-box-body .form-control-feedback { color: #777; } .form-control-feedback { position: absolute; top: 0; right: 0; z-index: 2; display: block; width: 34px; height: 34px; line-height: 34px; text-align: center; pointer-events: none; }.checkbox, .radio { position: relative; display: block; margin-top: 10px; margin-bottom: 10px; }.icheck>label { padding-left: 0; } .checkbox label, .radio label { min-height: 20px; padding-left: 20px; margin-bottom: 0; font-weight: 400; cursor: pointer; } </style> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="assets/css/bootstrap.min.css"> <!-- Our Custom CSS --> <link rel="stylesheet" href="assets/css/style4.css"> <!-- Font Awesome JS --> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="<KEY>" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="<KEY>" crossorigin="anonymous"></script> </head> <body> <div class="login-box"> <div class="login-logo"> <img id="logo" src="assets/images/logo.png" style="width: 340px; height: auto;"> </div> <div class="login-box-body"> <h1 class="login-box-msg" style="text-align: center;">Login</h1> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST"> <div class="form-group row <?php echo (!empty($email_err)) ? 'has-error' : ''; ?>"> <div class="col-sm-10"><input class="form-control" type="text" name="email" placeholder="Email" value="<?php echo $email; ?>"/></div> <span class="help-block"><?php echo $email_err; ?></span> </div> <div class="form-group row <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <div class="col-sm-10"><input class="form-control" type="<PASSWORD>" name="password" placeholder="<PASSWORD>"/></div> <span class="help-block"><?php echo $password_err; ?></span> </div> <input type="submit" class="btn btn-primary" value="Login"/>&nbsp;<button type="reset" class="btn btn-outline-primary">Clear</button> </form> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Popper.JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Bootstrap JS --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function () { $('#sidebarCollapse').on('click', function () { $('#sidebar').toggleClass('active'); }); }); </script> </body> </html>
12294a89b92dc3fd99b7bc8384e59565d131b699
[ "PHP" ]
8
PHP
piwedlanjwa-ux/casetrek-repo
94b2d2045feddc405d18ffb48732d1e301624ce8
ec777ae59bd655adece9b2b5aacfab6ce3f474c6
refs/heads/master
<repo_name>chantal66/battleship<file_sep>/lib/instructions.rb class Instructions def self.welcome_message "Welcome to BATTLESHIP" end def self.menu_message "Would you like to (p)lay, read the (i)nstructions, or (q)uit?" end def self.instructions_message "Maybe I'm NOT very smart according to my creator but I will sink your FLEET anyways\n Now! a piece of advice..\n Should you pack your battleships closely together or spread them far apart? Is it best to sink your opponent's ship right away or locate the other ships first?" end def self.placement_ship_instructions "I have laid out my ships on the grid. You now need to layout your two ships. The first is two units long and the second is three units long. The grid has A1 at the top left and D4 at the bottom right. Enter the squares for the two-unit ship: " end def self.ship_placement(size_ship) "Enter the squares for the #{size_ship} ship." end def self.invalid_entry(rule_violated) "Invalid: your input #{rule_violated}. Please try again.\n\n" end def self.player_quits 'Thanks for playing. See you next time!' end def self.incorrect_length 'is not the correct length' end def self.too_many_characters "includes at least one location with too many characters - try something like 'B2' for each location" end def self.duplicates 'cannot include duplicates' end def self.format_or_range_issue "should start with a letter between 'A' and 'D' and end with a number between '1' and '4', i.e. 'A3'" end def self.wraps 'wraps around the board' end def self.already_taken "location already taken" end def self.not_adjacent "includes locations that are diagonal or otherwise non-adjacent" end def self.shot_locs 'should only be one location' end def self.shot_length 'should only be two characters' end def self.already_guessed 'is a location you have already guessed' end def self.rules_violations(violations) "NO NO NO, please enter a valid size" end def self.attacking_prompt "Please enter the firing instructions: " end def self.attack_prompt 'Please enter a position to fire on: ' end def self.hit(position) "Shot on #{position} was a hit!\n\n" end def self.miss(position) "Shot on #{position} was a miss.\n\n" end def self.player_end_turn "Please press ENTER to end your turn.\n\n" end def self.sunken_ship(size) "A #{size} ship has been sunk!" end def self.end_game(outcome, num_shots, time) if outcome == 'W' "Congratulations! You beat the computer in #{time / 60} minutes and #{time % 60} seconds, and it only took you #{num_shots} shots! Thanks for playing!" else "So sorry, you lost. The computer beat you in #{time / 60} minutes and #{time % 60} seconds, but it did take them #{num_shots} shots to do it. Thanks for playing!" end end def self.player_quits 'Thanks for playing. See you next time!' end def self.computer_turn "The computer takes a shot...\n" end def self.computer_board "The computer's hits and misses are as follows:" end def self.current_player_board "Here's your current board tracking your hits and misses:" end def self.updated_player_board 'After that guess, your hits and misses are as follows:' end def self.not_valid 'is not a valid choice' end def self.enter_only 'should only be the ENTER key' end end<file_sep>/test/puter_board_test.rb require './test/test_helper' require './lib/player' require './lib/puter_board' require './lib/validate_posibilities.rb' require 'pry' class PuterBoardTest < Minitest::Test include ValidatePosibilities def test_puter_board_exists puter = PuterBoard.new assert_instance_of PuterBoard, puter end def test_can_generate_random_location puter = PuterBoard.new result = puter.random_locations assert result end def test_it_has_ships_to_play_with puter = PuterBoard.new result = puter.board.player_ships assert result end def test_it_handles_hits_and_misses puter = PuterBoard.new result = puter.board.player_hits_and_misses assert result end def test_can_generate_random_location puter = PuterBoard.new result = puter.random_locations assert result end def test_can_select_one_valid_locations_randomly puter = PuterBoard.new result = puter.random_locations assert puter.board.player_ships.valid_positions.include?(result) end def test_puter_can_select_next_location_randomly puter = PuterBoard.new result = puter.next_valid_position('C2') possibilities = ["D2", "C3", "B2", "C1"] assert possibilities.include?(result) end def test_can_place_a_two_unit_ship puter = PuterBoard.new result = puter.placing_ships_randomly(2) board = puter.board.player_ships.board assert board, result end def test_can_place_a_three_unit_ship puter = PuterBoard.new board = puter.board.player_ships.board result = puter.placing_ships_randomly(3) assert board, result end def test_can_place_two_and_the_three_unit_ship puter1 = PuterBoard.new board1 = puter1.board.player_ships.board result1 = puter1.placing_ships_randomly(3) puter2 = PuterBoard.new board2 = puter2.board.player_ships.board result2 = puter2.placing_ships_randomly(2) assert board1,result1 assert board2, result2 end end<file_sep>/test/instructions_test.rb require './test/test_helper' require './lib/instructions' require 'pry' class InstructionsTest < Minitest::Test def test_it_exists intro = Instructions.new assert_instance_of Instructions, intro end def test_it_can_give_a_welcome_message intro = Instructions.welcome_message assert_equal "Welcome to BATTLESHIP", intro end def test_it_can_give_a_menu_message intro = Instructions.menu_message assert_equal "Would you like to (p)lay, read the (i)nstructions, or (q)uit?", intro end def test_it_can_give_the_instructions_message intro = Instructions.instructions_message assert_equal "Maybe I'm NOT very smart according to my creator but I will sink your FLEET anyways\n Now! a piece of advice..\n Should you pack your battleships closely together or spread them far apart? Is it best to sink your opponent's ship right away or locate the other ships first?", intro end def test_can_give_ship_placement_instructions intro = Instructions.placement_ship_instructions assert_equal "I have laid out my ships on the grid. You now need to layout your two ships. The first is two units long and the second is three units long. The grid has A1 at the top left and D4 at the bottom right. Enter the squares for the two-unit ship: ", intro end def test_it_has_a_ship_placement_prompt_for_multiple_ship_sizes intro = Instructions.ship_placement('two-unit') message = 'Enter the squares for the two-unit ship.' assert_equal message, intro result = Instructions.ship_placement('three-unit') message = 'Enter the squares for the three-unit ship.' assert_equal message, result end def test_it_has_a_prompt_for_position_to_fire_on intro = Instructions.attack_prompt message = 'Please enter a position to fire on: ' assert_equal message, intro end def test_it_has_a_flexible_message_for_a_hit result = Instructions.hit('A3') assert_equal "Shot on A3 was a hit!\n\n", result end def test_it_has_a_flexible_message_for_a_miss result = Instructions.miss('B4') assert_equal "Shot on B4 was a miss.\n\n", result end def test_it_has_a_message_to_prompt_the_player_to_end_their_turn result = Instructions.player_end_turn message = "Please press ENTER to end your turn.\n\n" assert_equal message, result end def test_it_has_a_message_for_a_sunken_ship result = Instructions.sunken_ship('three-unit') message = 'A three-unit ship has been sunk!' assert_equal message, result end def test_it_has_a_flexible_message_for_the_end_game result = Instructions.end_game('W', 12, 11) message = "Congratulations! You beat the computer in 0 minutes and 11 seconds, and it only took you 12 shots! Thanks for playing!" assert_equal message, result result = Instructions.end_game('L', 12, 30) message = "So sorry, you lost. The computer beat you in 0 minutes and 30 seconds, but it did take them 12 shots to do it. Thanks for playing!" assert_equal message, result end def test_it_has_a_message_for_when_the_player_quits result = Instructions.player_quits message = 'Thanks for playing. See you next time!' assert_equal message, result end def test_it_has_a_message_to_announce_the_computer_turn result = Instructions.computer_turn message = "The computer takes a shot...\n" assert_equal message, result end def test_it_has_a_message_announcing_the_computer_hit_and_miss_board result = Instructions.computer_board message = "The computer's hits and misses are as follows:" assert_equal message, result end def test_it_has_a_message_announcing_the_player_hit_and_miss_board result = Instructions.current_player_board message = "Here's your current board tracking your hits and misses:" assert_equal message, result end def test_it_has_a_message_for_the_updated_player_hit_and_miss_board result = Instructions.updated_player_board message = 'After that guess, your hits and misses are as follows:' assert_equal message, result end def test_it_has_a_message_for_an_invalid_choice result = Instructions.not_valid message = 'is not a valid choice' assert_equal message, result end def test_it_has_a_message_for_asking_for_the_ENTER_key_only result = Instructions.enter_only message = 'should only be the ENTER key' assert_equal message, result end def test_it_has_a_message_for_a_location_already_guessed result = Instructions.already_guessed message = 'is a location you have already guessed' assert_equal message, result end def test_it_has_a_message_for_incorrect_shot_length result = Instructions.shot_length message = 'should only be two characters' assert_equal message, result end def test_it_has_a_message_for_too_many_locations result = Instructions.shot_locs message = 'should only be one location' assert_equal message, result end def test_it_has_a_message_for_an_incorrect_length result = Instructions.incorrect_length message = 'is not the correct length' assert_equal message, result end def test_it_has_a_message_for_placement_that_is_not_adjacent result = Instructions.not_adjacent message = "includes locations that are diagonal or otherwise non-adjacent" assert_equal message, result end def test_it_has_a_message_for_a_location_that_is_already_taken result = Instructions.already_taken message = "location already taken" assert_equal message, result end def test_it_has_a_message_for_positions_that_wrap_the_board result = Instructions.wraps message = 'wraps around the board' assert_equal message, result end def test_it_has_a_message_for_duplicates result = Instructions.duplicates message = 'cannot include duplicates' assert_equal message, result end def test_it_has_a_message_for_format_or_range_issues result = Instructions.format_or_range_issue message = "should start with a letter between 'A' and 'D' and end with a number between '1' and '4', i.e. 'A3'" assert_equal message, result end def test_it_has_a_message_for_too_many_characters result = Instructions.too_many_characters message = "includes at least one location with too many characters - try something like 'B2' for each location" assert_equal message, result end end<file_sep>/lib/validate_posibilities.rb module ValidatePosibilities def vertical_alignment(present_location) if present_location[0][0] = 'A' final_location = 'C' + present_location[0][1] elsif present_location[0][0] == 'C' final_location = 'B' + present_location[0][1] else final_location = ['A','D'].sample + present_location[0][1] end end def horizontal_alignment(present_location) if present_location[0][1] = '1' final_location = present_location[0][0] + '3' elsif present_location[0][1] == '3' final_location = present_location[0][0] + '2' else final_location = present_location[0][0] + ['1','2','3','4'] end end def check_third_position(existing_locations) if existing_locations[0][0] == existing_locations[1][0] horizontal_alignment(existing_locations) else vertical_alignment(existing_locations) end end def all_adjacent_locations(previous_location) up_letter = "#{previous_location[0].next}#{previous_location[1]}" up_number = "#{previous_location[0]}#{previous_location[1].next}" down_letter = "#{(previous_location[0].ord - 1).chr}#{previous_location[1]}" down_number = "#{previous_location[0]}#{(previous_location[1].ord - 1).chr}" possibilities = [up_letter, up_number, down_letter, down_number] end def puter_possibilities(possibilities) possibilities.delete_at(rand(possibilities.length)) end def position_wrong_format_or_outside_range?(locations) !locations.all? do |place| place[0].between?('A', 'D') && place[1].between?('1', '4') end end def too_many_letters?(positions) positions.any? { |place| place.length > 2} end def positions_include_duplicates?(positions) true if positions.uniq.size < positions.size end def position_wraps?(positions) if contains(positions, 'A') && contains(positions, 'D') true elsif contains(positions, '1') && contains(positions, '4') true else false end end def contains(positions, char) positions.any? { |place| place[0] == char } end def position_taken?(positions, player) !positions.all? do |place| player.board.player_ships.valid_positions.include?(place) end end def positions_not_adjacent?(locations) outcome = false if locations.size < 2 outcome else index = 0 while index < locations.size - 1 unless all_adjacent_locations(locations[index]).include?(locations[index + 1]) outcome = true end index += 1 end end outcome end def already_guessed?(input, player) !player.board.player_hits_and_misses.valid_positions.include?(input) end end # require 'pry'; binding.pry<file_sep>/lib/game_interface.rb require './lib/instructions' require './lib/validate_posibilities' require 'pry' class PlayerInterface extend ValidatePosibilities def self.menu_message(player) puts Instructions.menu_message selection = gets.chomp.upcase if quitting?(selection) quit elsif selection == 'I' || selection == 'INSTRUCTIONS' puts Instructions.instructions_message sleep(3) menu_message(player) elsif selection == 'P' || selection == 'PLAY' puts Instructions.placement_ship_instructions first_ship = ship_placement(2, player) player.ship_position(2, first_ship) second_ship = ship_placement(3, player) player.ship_position(3, second_ship) else puts Instructions.invalid_entry(Instructions.not_valid) menu_message(player) end end def self.quitting?(input) true if input == 'Q' || input == 'QUIT' end def self.quit puts Instructions.player_quits exit end def self.invalid_try_again(reason) puts Instructions.invalid_entry(reason) end def self.ship_placement(ship_size, player) locations = [] puts Instructions.ship_placement("#{ship_size}-unit") location = gets.chomp.upcase if ship_placement_verification(location, ship_size, player) ship_placement(ship_size, player) else locations << location return locations.sort.join(' ') end end def self.ship_placement_verification(location, ship_size, player) outcome = true entries = location.split if quitting?(location) quit elsif entries.size != ship_size invalid_try_again(Instructions.incorrect_length) elsif too_many_letters?(entries) invalid_try_again(Instructions.too_many_characters) elsif position_wrong_format_or_outside_range?(entries) invalid_try_again(Instructions.format_or_range_issue) elsif positions_include_duplicates?(entries) invalid_try_again(Instructions.duplicates) elsif position_wraps?(entries) invalid_try_again(Instructions.wraps) elsif position_taken?(entries, player) invalid_try_again(Instructions.already_taken) elsif positions_not_adjacent?(entries) invalid_try_again(Instructions.not_adjacent) else outcome = false end outcome end end # require 'pry'; binding.pry # '' p player = PlayerInterface.menu_message('p') <file_sep>/lib/player_board.rb require './lib/board' class PlayerBoard attr_reader :player_ships, :player_hits_and_misses def initialize @player_ships = Board.new @player_hits_and_misses = Board.new end def add_player_hits_and_misses(location, hit_or_miss) index = swapp_letter(location[0]) player_hits_and_misses.board[index][location[1].to_i] = hit_or_miss end def swapp_letter(letter) index = 2 if letter == 'B' index = 3 elsif letter == 'C' index = 4 elsif letter == 'D' index = 5 else index end end end <file_sep>/lib/player.rb require './lib/player_board' class Player attr_reader :shots, :board def initialize(shots = 0) @shots = shots @board = PlayerBoard.new end def ship_position(ship_size, position) positions = position.split positions.each do |location| row = board.swapp_letter(location[0]) board.player_ships.board[row][location[1].to_i] = ship_size.to_s board.player_ships.valid_positions.delete(location) end board.player_ships.board end def fire(position) board.player_hits_and_misses.valid_positions.delete(position) end end # player = Player.new # p player.board.add_player_hits_and_misses('A2', 'H')<file_sep>/test/player_test.rb require './test/test_helper' require './lib/player' require 'pry' class PlayerTest < Minitest::Test def test_player_exists player = Player.new assert_instance_of Player, player end def test_can_place_a_ship_in_certain_position player = Player.new result = player.ship_position(2,'A1') assert_equal [["==========="], [". ", "1 ", "2 ", "3 ", "4 "], ["A", "2", " ", " ", " "], ["B", " ", " ", " ", " "], ["C", " ", " ", " ", " "], ["D", " ", " ", " ", " "], ["==========="]], result end def test_can_place_a_ship_in_many_positions player = Player.new result = player.ship_position(2,'B1 B2') assert_equal [["==========="], [". ", "1 ", "2 ", "3 ", "4 "], ["A", " ", " ", " ", " "], ["B", "2", "2", " ", " "], ["C", " ", " ", " ", " "], ["D", " ", " ", " ", " "], ["==========="]], result end def test_player_has_a_board_to_play_with player = Player.new result = player.board assert [["==========="], [". ", "1 ", "2 ", "3 ", "4 "], ["A", " ", " ", " ", " "], ["B", " ", " ", " ", " "], ["C", " ", " ", " ", " "], ["D", " ", " ", " ", " "], ["==========="]], result end def test_player_has_a_board_to_track_hits player = Player.new result = player.board.add_player_hits_and_misses('A2', 'H') assert_equal 'H', result end def test_player_has_a_board_to_track_misses player = Player.new result = player.board.add_player_hits_and_misses('A3', 'M') assert_equal 'M', result end def test_location_can_not_use_twice_w_two_unit_ship player = Player.new result = player.ship_position(2, 'A1 A2') refute player.board.player_ships.valid_positions.include?('A1'), result refute player.board.player_ships.valid_positions.include?('A2'), result end def test_location_can_not_use_twice_w_three_unit_boat player = Player.new result = player.ship_position(3, 'B1 B2 B3') refute player.board.player_ships.valid_positions.include?('B1'), result refute player.board.player_ships.valid_positions.include?('B2'), result refute player.board.player_ships.valid_positions.include?('B3'), result end def test_shots_default_to_zero player = Player.new result = player.shots assert_equal 0, result end def test_can_player_fire_a_shot_and_delete_position_from_board player = Player.new fire_a_shot = player.fire('A2') result = player.board.player_hits_and_misses.valid_positions refute result.include?('A2') end end<file_sep>/lib/board.rb require 'pry' class Board attr_accessor :valid_positions, :board def initialize @valid_positions = ['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2', 'C3', 'C4', 'D1', 'D2', 'D3', 'D4'] @board = full_board end def header_and_footer ['==========='] end def column_label ['. ','1 ','2 ','3 ','4 '] end def row(letter) [letter, ' ', ' ', ' ', ' ' ] end def full_board [header_and_footer, column_label, row('A'), row('B'), row('C'), row('D'), header_and_footer] end def print_board full_board.each do |row| puts "#{row.join} \n" end end end <file_sep>/test/validate_possibilities_test.rb require './test/test_helper' require './lib/validate_posibilities' require './lib/player' require 'pry' class ValidatePosibilitiesTest < Minitest::Test include ValidatePosibilities def test_it_can_find_vertical_aligment_for_three_unit result = vertical_alignment(['A1','B1']) assert_equal 'C1', result end def test_it_can_find_horizontal_alignmet_for_three_unit result = horizontal_alignment(['A1','A2']) assert_equal 'A3', result end def test_it_can_find_and_return_all_adjacent_locations result = all_adjacent_locations('A1') possibilities = ['B1', 'A2', '@1', 'A0'] assert_equal possibilities, result end def test_it_knows_if_a_single_input_is_in_the_wrong_format_or_off_the_board result = position_wrong_format_or_outside_range?(['A9']) assert result result = position_wrong_format_or_outside_range?(['1B']) assert result result = position_wrong_format_or_outside_range?(['A2']) refute result end def test_it_knows_if_multiple_inputs_are_wrong_format_or_off_board result = position_wrong_format_or_outside_range?(['A1', 'A2']) refute result result = position_wrong_format_or_outside_range?(['A1', 'B5']) assert result end def test_it_can_detect_duplicates_in_an_input_of_locations result = positions_include_duplicates?(['A1', 'A2', 'A3']) refute result result = positions_include_duplicates?(['A1','A2','A2']) assert result end def test_it_can_tell_if_an_input_wraps_around_the_board result = position_wraps?(['A1','D1']) assert result result = position_wraps?(['B2','C2']) refute result end def test_it_can_tell_if_an_input_contains_a_specific_character result = contains(['A1','A2'], 'A') assert result result = contains(['A1','A2'], '4') refute result end def test_it_can_tell_if_inputs_are_diagnonal_or_non_adjacent result = positions_not_adjacent?(['A2','C3']) assert result result = positions_not_adjacent?(['A2','A3']) refute result end def test_it_can_tell_if_a_location_has_already_been_guessed player = Player.new result = already_guessed?('A1', player) refute result player.board.player_hits_and_misses.valid_positions.delete('A1') result = already_guessed?('A1', player) assert result end end <file_sep>/lib/puter_board.rb require './lib/player' require './lib/validate_posibilities.rb' class PuterBoard < Player include ValidatePosibilities def random_locations board.player_ships.valid_positions.sample end def placing_ships_randomly(ship_size) coord = [] location = random_locations coord << location next_location = next_valid_position(location) coord << next_location if ship_size == 3 location_three = check_third_position(coord.sort) coord << location_three end ship_position(ship_size,coord.sort.join(' ')) end def next_valid_position(previous_location) next_position = 'next' until all_adjacent_locations(previous_location).include?(next_position) next_position = random_locations end next_position end end <file_sep>/test/board_test.rb require './test/test_helper' require './lib/board' require 'pry' class BoardTest < Minitest::Test def test_board_exists board = Board.new assert_instance_of Board, board end def test_board_has_16_positions board = Board.new result = board.valid_positions.length assert_equal 16, result end def test_board_has_valid_positions board = Board.new result = board.valid_positions assert_equal ['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4', 'C1', 'C2', 'C3', 'C4', 'D1', 'D2', 'D3', 'D4'], result end def test_board_has_a_header_and_footer board = Board.new result = board.header_and_footer assert_equal ['==========='], result end def test_has_columns_labels_from_1_to_4 board = Board.new result = board.column_label assert_equal ['. ','1 ','2 ','3 ','4 '], result end def test_board_has_rows_with_letter_A board = Board.new result = board.row('A') assert_equal ['A',' ',' ',' ',' '], result end def test_board_has_rows_with_other_letters board = Board.new result = board.row('C') assert_equal ['C',' ',' ',' ',' '], result end def test_has_a_full_board board = Board.new result = board.full_board assert_equal [["==========="], [". ", "1 ", "2 ", "3 ", "4 "], ["A", " ", " ", " ", " "], ["B", " ", " ", " ", " "], ["C", " ", " ", " ", " "], ["D", " ", " ", " ", " "], ["==========="]], result end def test_has_a_print_board board = Board.new result = board.print_board assert_equal [["==========="], [". ", "1 ", "2 ", "3 ", "4 "], ["A", " ", " ", " ", " "], ["B", " ", " ", " ", " "], ["C", " ", " ", " ", " "], ["D", " ", " ", " ", " "], ["==========="]], result end end<file_sep>/test/player_board_test.rb require './test/test_helper' require './lib/board' require './lib/player_board' require 'pry' class PlayerBoardTest < Minitest::Test def test_player_board_exists player_board = PlayerBoard.new assert_instance_of PlayerBoard, player_board end def test_board_can_track_player_hits_and_misses player_board = PlayerBoard.new result = player_board.player_hits_and_misses assert result end def test_board_can_track_player_ships player_board = PlayerBoard.new result = player_board.player_ships assert result end def test_can_convert_a_letter_into_appropiate_board_index player_board = PlayerBoard.new result = player_board.swapp_letter('A') assert_equal 2, result end def test_can_convert_many_letters_into_appropiate_board_index player_board = PlayerBoard.new result1 = player_board.swapp_letter('B') result2 = player_board.swapp_letter('C') result3 = player_board.swapp_letter('D') assert_equal 3, result1 assert_equal 4, result2 assert_equal 5, result3 end def test_can_add_a_hit_when_appropiate hit_index = PlayerBoard.new result = hit_index.swapp_letter('A') hit = PlayerBoard.new result1 = hit.add_player_hits_and_misses('A1', 'H') assert_equal 'H', result1 end def test_can_add_a_hit_when_appropiate miss_index = PlayerBoard.new result1 = miss_index.swapp_letter('C') miss = PlayerBoard.new result2 = miss.add_player_hits_and_misses('C2', 'M') assert_equal 'M', result2 end end
33078cc12cfa2cdaaae3f1edca556ba668cfd3c7
[ "Ruby" ]
13
Ruby
chantal66/battleship
214d5f34b9c212cc569ef3da433c5d34faa3aca8
464822013333b73f05096888fcb1248497f6ac69
refs/heads/master
<file_sep><?php $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $filename = $_POST['filename']; $trans = $_POST['trans']; if ($trans == "0") { $trans = "none_of_these"; } $user = $_POST['user']; $level = $_POST['level']; $startDate = $_POST['startDate']; $endDate = $_POST['endDate']; $usedTime = $_POST['usedTime']; $scoreInici = $_POST['scoreInici']; $scoreFinal = $_POST['scoreFinal']; $token = $_POST['token']; $send_data->debug = "debug info<br>\n"; if (strlen($token) == 45) { $res = mysqli_query($conn, "SELECT token FROM user WHERE username = '$user';"); $res = mysqli_fetch_object($res); $db_token = $res->token; if ($db_token == $token) { $res = mysqli_query($conn, "SELECT id_user FROM user WHERE username = '$user';"); $res = mysqli_fetch_object($res); $id_user = $res->id_user; $res = mysqli_query($conn, "SELECT bi.id_batch AS id_batch, bi.id_image AS id_image FROM batch b INNER JOIN batch_image bi INNER JOIN image i ON b.id_batch = bi.id_batch AND bi.id_image = i.id_image WHERE b.id_task = '1' AND i.name_cropped_image = '$filename';"); $res = mysqli_fetch_object($res); $id_image = $res->id_image; $id_batch = $res->id_batch; $res = mysqli_query($conn, "SELECT id_round FROM round WHERE start_date = STR_TO_DATE('$startDate','%Y%m%d %H%i%s') AND end_date = STR_TO_DATE('$endDate','%Y%m%d %H%i%s') AND id_user = '$id_user' AND id_batch = '$id_batch' AND initial_score = '$scoreInici' AND final_score = '$scoreFinal' LIMIT 1;"); $res = mysqli_fetch_object($res); if (!$res) { mysqli_query($conn, "INSERT INTO round(initial_score, final_score, used_time, id_batch, id_user, start_date, end_date) VALUES ('$scoreInici', '$scoreFinal', '$usedTime', '$id_batch', '$id_user', STR_TO_DATE('$startDate','%Y%m%d %H%i%s'), STR_TO_DATE('$endDate','%Y%m%d %H%i%s'))"); $res = mysqli_query($conn, "SELECT LAST_INSERT_ID() as last;"); $res = mysqli_fetch_object($res); $id_round = $res->last; } else { $id_round = $res->id_round; } $result = mysqli_query($conn, "INSERT INTO answer_user(id_user, id_round, id_image, answer) VALUES ('$id_user', '$id_round', '$id_image', '$trans');"); if ($result != False) { $send_data->res = "true"; $json = json_encode($send_data); print($json); } else { $send_data->res = "false"; $json = json_encode($send_data); print($json); } } else { $send_data->debug = "404 Not Found<br>\n"; $send_data->res = "false"; $json = json_encode($send_data); print($json); } } else { $send_data->debug = "404 Not Found<br>\n"; $send_data->res = "false"; $json = json_encode($send_data); print($json); } mysqli_close(); ?> <file_sep>#!/usr/bin/python # coding: utf-8 import os import mysql.connector as sqlconn import sys import optparse def update_user_feedback(hostname, username, password, database): NO_GOOD_ANSWER = "none_of_these" DECISION = 0.7 test = False conn = sqlconn.connect(user=username, password=<PASSWORD>, host=hostname, database=database) cursor = conn.cursor() #UPDATE used_times of both games query = ("SELECT id_batch FROM batch WHERE used_times > 0;") cursor.execute(query) result = [i for (i,) in cursor.fetchall()] for id_batch in result: query = ("SELECT COUNT(*) FROM round WHERE id_batch = %s;") data = (id_batch,) cursor.execute(query, data) (count,) = cursor.fetchone() query = ("UPDATE batch SET used_times = %s WHERE id_batch = %s;") data = (count, id_batch) cursor.execute(query, data) #RESET test user session query = ("UPDATE user_task SET max_score=0, level=1 WHERE id_user = 6;") cursor.execute(query) conn.commit() #UPDATE TRANSCRIPTION GAME BATCHES -> id_task = 1 for TRANSCRIPTION GAME query = ("""SELECT au.id_image, COUNT(*) FROM answer_user AS au INNER JOIN round AS r INNER JOIN batch AS b INNER JOIN batch_image AS bi ON au.id_round = r.id_round AND au.id_user = r.id_user AND r.id_batch = b.id_batch AND b.id_batch = bi.id_batch AND au.id_image = bi.id_image WHERE au.processed = 0 AND b.id_task = 1 AND b.active = 1 GROUP BY au.id_image;""") cursor.execute(query) result = cursor.fetchall() ID_IMAGE = 0 COUNT = 1 for res in result: if res[COUNT] >= 10: id_image = res[ID_IMAGE] query = ("SELECT answer, COUNT(*) FROM answer_user WHERE id_image = %s AND processed = 0 GROUP BY answer;") data = (id_image,) cursor.execute(query, data) answers = cursor.fetchall() ANSWER = 0 query = ("SELECT id_answer_user FROM answer_user WHERE id_image = %s AND processed = 0;") data = (id_image,) cursor.execute(query, data) processeds = [i for (i,) in cursor.fetchall()] answer = "" rep = -1 total = 0 for ans in answers: total = total + ans[COUNT] if ans[COUNT] > rep: rep = ans[COUNT] answer = ans[ANSWER] res = rep/float(total) if test: print "possible result:", id_image, answer, res if answer != NO_GOOD_ANSWER and res >= DECISION: for proc in processeds: if not test: query = ("UPDATE answer_user SET processed = 1 WHERE id_answer_user = %s;") data = (proc,) cursor.execute(query, data) if not test: query = ("UPDATE transcription SET final_result = %s WHERE id_image = %s") data = (answer, id_image) cursor.execute(query, data) else: print "result:", id_image, answer query = ("SELECT state FROM task_image WHERE id_image = %s;") data = (id_image,) cursor.execute(query, data) (out,) = cursor.fetchone() if int(out) == 1 or int(out) == 9: next_state = 2 if int(out) == 4 or int(out) == 10: next_state = 5 if not test: query = ("UPDATE task_image SET state = %s WHERE id_image = %s;") data = (next_state, id_image) cursor.execute(query, data) conn.commit() else: query = ("SELECT state FROM task_image WHERE id_image = %s;") data = (id_image,) cursor.execute(query, data) (out,) = cursor.fetchone() if int(out) == 1: next_state = 9 if int(out) == 4: next_state = 10 if not test: query = ("UPDATE task_image SET state = %s WHERE id_image = %s;") data = (next_state, id_image) cursor.execute(query, data) conn.commit() conn.commit() #CHECK TRANSCRIPTION BATCHES query = ("SELECT id_batch FROM batch WHERE id_task = 1 AND active = 1;") cursor.execute(query) batches = [i for (i,) in cursor.fetchall()] for id_batch in batches: query = ("SELECT id_image FROM batch_image WHERE id_batch = %s;") data = (id_batch,) cursor.execute(query, data) images = [i for (i,) in cursor.fetchall()] count = 0 for id_image in images: query = ("SELECT state FROM task_image WHERE id_image = %s ANd id_task = 1;") data = (id_image,) cursor.execute(query, data) (state,) = cursor.fetchone() state = int(state) if state == 2 or state == 5: count += 1 if count == len(images): if not test: query = ("UPDATE batch SET active = 0 WHERE id_batch = %s AND id_task = 1;") data = (id_batch,) cursor.execute(query, data) conn.commit() #CLUSTER ANSWERS CONSTANTS ZERO = 0 ONE = 1 DIFF = 2 EQ = 3 #UPDATE CLUSTER GAME BATCHES -> id_task = 2 for CLUSTER GAME query = ("""SELECT au.id_image, COUNT(*) FROM answer_user au INNER JOIN round r INNER JOIN batch b INNER JOIN batch_image bi ON au.id_round = r.id_round AND au.id_user = r.id_user AND r.id_batch = b.id_batch AND b.id_batch = bi.id_batch AND au.id_image = bi.id_image WHERE au.processed = 0 AND b.id_task = 2 AND b.active = 1 GROUP BY au.id_image;""") cursor.execute(query) result = cursor.fetchall() ID_IMAGE = 0 COUNT = 1 dic = {} for res in result: if res[COUNT] >= 10: query = ("SELECT id_batch FROM batch_image WHERE id_image = %s;") data = (res[ID_IMAGE],) cursor.execute(query, data) (id_batch,) = cursor.fetchone() if id_batch not in dic: dic[id_batch] = 1 if test: print "dic size:", len(dic) for id_batch, _ in dic.iteritems(): query = ("""SELECT bi.id_validation FROM batch b INNER JOIN batch_image bi ON b.id_batch = bi.id_batch WHERE b.id_batch = %s GROUP BY bi.id_validation;""") data = (id_batch,) cursor.execute(query, data) id_clusters = [i for (i,) in cursor.fetchall()] for id_cluster in id_clusters: query = ("SELECT id_image FROM image_cluster WHERE id_cluster = %s;") data = (id_cluster,) cursor.execute(query, data) images = [i for (i,) in cursor.fetchall()] all_results = [] total_images_in_cluster = len(images) total = 0 for id_image in images: query = ("SELECT answer FROM answer_user WHERE id_image = %s AND processed = 0;") data = (id_image,) cursor.execute(query, data) res = [i for (i,) in cursor.fetchall()] total = total + len(res) dic = [0,0,0,0] for out in res: if out == "0": dic[ZERO] += 1 elif out == "1": dic[ONE] += 1 elif out == "diff": dic[DIFF] += 1 else: dic[EQ] += 1 all_results.append((id_image, dic)) if total == 0: continue else: total = total/total_images_in_cluster compare_num = -1 for (im, res) in all_results: highest = max(res) index = res.index(highest) if index == ONE: if highest > compare_num: compare_num = highest final_result = im elif index == DIFF: if highest > compare_num: compare_num = highest final_result = "diff" break elif index == EQ: if highest > compare_num: compare_num = highest final_result = "eq" break res = compare_num/float(total) if test: print "possible result:", id_image, final_result, res, compare_num, total if res >= DECISION: if not test: query = ("UPDATE cluster SET final_result = %s WHERE id_cluster = %s;") data = (final_result, id_cluster) cursor.execute(query, data) else: print "result:", id_cluster, final_result for id_image in images: query = ("SELECT id_answer_user FROM answer_user WHERE id_image = %s AND processed = 0;") data = (id_image,) cursor.execute(query, data) processeds = [i for (i,) in cursor.fetchall()] if not test: for proc in processeds: query = ("UPDATE answer_user SET processed = 1 WHERE id_answer_user = %s;") data = (proc,) cursor.execute(query, data) conn.commit() next_state = 4 if not test: query = ("UPDATE task_image SET state = %s WHERE id_image = %s;") data = (next_state, id_image) cursor.execute(query, data) conn.commit() else: for id_image in images: next_state = 9 if not test: query = ("UPDATE task_image SET state = %s WHERE id_image = %s;") data = (next_state, id_image) cursor.execute(query, data) conn.commit() conn.commit() #CHECK CLUSTER BATCHES query = ("SELECT id_batch FROM batch WHERE id_task = 2 AND active = 1;") cursor.execute(query) batches = [i for (i,) in cursor.fetchall()] for id_batch in batches: query = ("SELECT id_image FROM batch_image WHERE id_batch = %s;") data = (id_batch,) cursor.execute(query, data,) images = [i for (i,) in cursor.fetchall()] count = 0 for id_image in images: query = ("SELECT state FROM task_image WHERE id_image = %s ANd id_task = 2;") data = (id_image,) cursor.execute(query, data) (state,) = cursor.fetchone() state = int(state) if state == 3 or state == 5: count += 1 if count == len(images): if not test: query = ("UPDATE batch SET active = 0 WHERE id_batch = %s AND id_task = 2;") data = (id_batch,) cursor.execute(query, data) conn.commit() cursor.close() conn.close() def create_cluster_batch(): conn = sqlconn.connect(user=username, password=<PASSWORD>, host=hostname, database=database) cursor = conn.cursor() def main(argv): parser = optparse.OptionParser() parser.add_option('-H', '--Host', dest="hostname", default="172.16.17.32", type="string", help="Specify mysql hostname to connect") parser.add_option('-U', '--User', dest="username", default="jialuo", type="string", help="Specify username to connect") parser.add_option('-P', '--Password', dest="password", default="<PASSWORD>", type="string", help="Specify password to connect") parser.add_option('-D', '--Database', dest="ddbb", default="word_hunter", type="string", help="Specify which database to connect") options, remainder = parser.parse_args() update_user_feedback(options.hostname, options.username, options.password, options.ddbb) if __name__ == "__main__": main(sys.argv[1:]) <file_sep><?php include 'Token.php'; $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_POST['username']; if ($username != "Anonymous" and $username != "Anónimo" and $username != "Anonymous" and $username != "Anònim") { $password = $_POST['password']; $send_data->debug = "debug info<br>\n"; $result = mysqli_query($conn, "SELECT id_user FROM user WHERE username = '$username';"); while ($row = mysqli_fetch_assoc($result)) { $output[] = $row[id_user]; } $count = count($output); if ($count == 0) { $password = <PASSWORD>($password); $token = generateToken($token); mysqli_query($conn, "INSERT INTO user(username, password, token) VALUES ('$username', '$password','$token')"); $result = mysqli_query($conn, "SELECT MAX(id_user) AS id_user FROM user WHERE username = '$username';"); $row = mysqli_fetch_object($result); mysqli_query($conn, "INSERT INTO user_task(id_user, id_task, max_score, level) VALUES ('$row->id_user', 1, 0, 1)"); mysqli_query($conn, "INSERT INTO user_task(id_user, id_task, max_score, level) VALUES ('$row->id_user', 2, 0, 1)"); $send_data->token = $token; $send_data->res = "true"; $json = json_encode($send_data); print($json); } else { $send_data->token = -1; $send_data->res = "false"; $json = json_encode($send_data); print($json); } } else { $send_data->token = -1; $send_data->res = "false"; $json = json_encode($send_data); print($json); } mysqli_close(); ?> <file_sep><?php $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_REQUEST['username']; if ($username == NULL) { $result = mysqli_query($conn, "SELECT u.username AS username, ut.max_score AS max_score FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE ut.id_task = 1 ORDER BY ut.max_score DESC LIMIT 10;"); while ($row = mysqli_fetch_assoc($result)) { $output1[] = $row[username].','.$row[max_score]; } $result = mysqli_query($conn, "SELECT u.username AS username, ut.max_score AS max_score FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE ut.id_task = 2 ORDER BY ut.max_score DESC LIMIT 10;"); while ($row = mysqli_fetch_assoc($result)) { $output2[] = $row[username].','.$row[max_score]; } $count = count($output1); for ($i = 0; $i < $count; $i++) { print($output1[$i].'<br>'); } print('separator<br>'); for ($i = 0; $i < $count; $i++) { print($output2[$i].'<br>'); } } else { $result = mysqli_query($conn, "SELECT ut.max_score AS max_score, ut.level AS level FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE u.username = '$username' AND ut.id_task = 1;"); $match = mysqli_fetch_object($result); $result = mysqli_query($conn, "SELECT ut.max_score AS max_score, ut.level AS level FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE u.username = '$username' AND ut.id_task = 2;"); $diff = mysqli_fetch_object($result); print($match->max_score.','.$diff->max_score.','.$match->level.','.$diff->level); } mysqli_close(); ?> <file_sep><?php $params = parse_ini_file("./config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $filename = $_REQUEST['filename']; $trans = $_REQUEST['trans']; if ($trans == 0) { $trans = "none_of_these"; } $user = $_REQUEST['user']; $level = $_REQUEST['level']; $startDate = $_REQUEST['startDate']; $endDate = $_REQUEST['endDate']; $usedTime = $_REQUEST['usedTime']; $scoreInici = $_REQUEST['scoreInici']; $scoreFinal = $_REQUEST['scoreFinal']; $res = mysqli_query($conn, "SELECT id_user FROM user WHERE username = '$user';"); $res = mysqli_fetch_object($res); $id_user = $res->id_user; $res = mysqli_query($conn, "SELECT id_batch, id_image FROM batch b INNER JOIN batch_image bi INNER JOIN image i ON b.id_batch = bi.id_batch AND bi.id_image = i.id_image WHERE b.id_task = '1' AND i.name_croppped_image = '$filename';"); $res = mysqli_fetch_object($res); $id_image = $res->id_image; $id_batch = $res->id_batch; mysqli_query($conn, "INSERT INTO round(initial_score, final_score, used_time, id_batch, id_user) VALUES ('$scoreFinal', '$scoreFinal', '$usedTime', '$id_batch', '$id_user')"); $res = mysqli_query($conn, "SELECT LAST_INSERT_ID() as last;"); $res = mysqli_fetch_object($res); $id_round = $res->last; $result = mysqli_query($conn, "INSERT INTO answer_user(id_user, id_round, id_image, answer) VALUES ('$id_user', '$id_round', '$id_image', '$trans');"); if ($result != False) { print('True'); } else { print('False'); } mysqli_close(); ?> <file_sep>#!/usr/bin/python # coding: utf-8 import os import mysql.connector as sqlconn import optparse import sys def add_images(hostname, username, password, database, txt, folder): reader = open(txt,"r") if folder != "none": dic = {} for imagename in os.listdir(folder): ID = imagename.split(",")[1] ID = ID.split(".")[0] dic[ID] = imagename conn = sqlconn.connect(user=username, password=<PASSWORD>, host=hostname, database=database) cursor = conn.cursor() for line in reader: cropped_image_name, x1, y1, x2, y2 = line.split(" ") original_image_name = "" y2 = y2.rstrip() if folder != "none": ID = cropped_image_name.split("_")[1] if ID in dic: original_image_name = dic[ID] query = ("INSERT INTO image(id_font, name_original_image, name_cropped_image, position_x1, position_y1, position_x2, position_y2) VALUES(%s, %s, %s, %s, %s, %s, %s)") data = ('1', original_image_name, cropped_image_name, x1, y1, x2, y2) cursor.execute(query, data) conn.commit() cursor.close() conn.close() def main(argv): parser = optparse.OptionParser() parser.add_option('-H', '--Host', dest="hostname", default="172.16.17.32", type="string", help="Specify mysql hostname to connect") parser.add_option('-U', '--User', dest="username", default="jialuo", type="string", help="Specify username to connect") parser.add_option('-P', '--Password', dest="password", default="<PASSWORD>", type="string", help="Specify password to connect") parser.add_option('-D', '--Database', dest="ddbb", default="word_hunter", type="string", help="Specify which database to connect") parser.add_option('-f', '--file_cropped_images_position', dest="cropped_txt", type="string", help="Relative/absolute path of the TXT file where stores the positions of the cropped images") parser.add_option('-d', '--directory_original_images', dest="folder_orignal", default="none", type="string", help="Relative/absolute path of the folder where are the original page images") options, remainder = parser.parse_args() add_images(options.hostname, options.username, options.password, options.ddbb, options.cropped_txt, options.folder_orignal) if __name__ == "__main__": main(sys.argv[1:])<file_sep><?php $params = parse_ini_file("./config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $game = $_REQUEST['game']; if ($game == '1') { //Transcription game check $result = mysqli_query($conn, "SELECT COUNT(id_batch) num FROM batch WHERE active = '1' AND id_task = '1';"); } else { // Cluster game check $result = mysqli_query($conn, "SELECT COUNT(id_batch) num FROM batch WHERE active = '1' AND id_task = '2';"); } $row = mysqli_fetch_assoc($result); print(($row['num'])); mysqli_close(); ?> <file_sep>[user_params] username = "jialuo" password = "<PASSWORD>" hostname = "172.16.31.10" db_name= "daggames" <file_sep><?php $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_REQUEST['username']; $score1 = $_REQUEST['match_game']; $score2 = $_REQUEST['difference_game']; $level1 = $_REQUEST['match_level']; $level2 = $_REQUEST['difference_level']; $result = mysqli_query($conn, "SELECT id_user FROM `user` WHERE `username` = '$username';"); $result = mysqli_fetch_object($result); $id_user = $result->id_user; var_dump($id_user); if (!$result) { print('false'); } else { $result = mysqli_query($conn, "UPDATE user_task SET max_score = '$score1', level = '$level1' WHERE id_task = '1' AND id_user = '$id_user';"); if (!$result) { print('false'); } $result = mysqli_query($conn, "UPDATE user_task SET max_score = '$score2', level = '$level2' WHERE id_task = '2' AND id_user = '$id_user';"); if (!$result) { print('false'); } print('true'); } mysqli_close(); ?> <file_sep><?php $params = parse_ini_file("./config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_REQUEST['username']; $score1 = $_REQUEST['match_game']; $score2 = $_REQUEST['difference_game']; $level1 = $_REQUEST['match_level']; $level2 = $_REQUEST['difference_level']; $result = mysqli_query($conn, "SELECT id_user FROM user WHERE username = '".$username."';"); while ($row = mysqli_fetch_assoc($result)) { $output[] = $row[id]; } $count = count($output); if ($count == 0) { print('false'); } else { $result = mysqli_query($conn, "UPDATE user_task SET max_score = '".$score1."' AND level = '".$level1."' WHERE id_task = 1 AND id_user = '".$output[0]."';"); $result = mysqli_query($conn, "UPDATE user_task SET max_score = '".$score2."' AND level = '".$level2."' WHERE id_task = 2 AND id_user = '".$output[0]."';"); print('true'); } mysqli_close(); ?> <file_sep><?php include 'Token.php'; $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_POST['username']; $token = $_POST['token']; $send_data->debug = "debug info<br>\n"; if (strlen($token) == 45) { $res = mysqli_query($conn, "SELECT token FROM user WHERE username = '$username';"); $res = mysqli_fetch_object($res); $db_token = $res->token; if ($username != "test") { if ($db_token == $token) { $token = generateToken(); mysqli_query($conn, "UPDATE user SET token = '$token' WHERE username = '$username';"); $send_data->token = $token; $send_data->res = "true"; $json = json_encode($send_data); print($json); } else { $send_data->debug = "404 Not Found<br>\n"; $send_data->res = "false"; $json = json_encode($send_data); print($json); } } else { $send_data->token = $db_token; $send_data->res = "true"; $json = json_encode($send_data); print($json); } } else { $send_data->debug = "404 Not Found<br>\n"; $send_data->res = "false"; $json = json_encode($send_data); print($json); } mysqli_close(); ?> <file_sep><?php include 'Token.php'; $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_POST['username']; $score1 = $_POST['match_game']; $score2 = $_POST['difference_game']; $level1 = $_POST['match_level']; $level2 = $_POST['difference_level']; $token = $_POST['token']; $send_data->debug = "debug info<br>\n"; if (strlen($token) == 45) { $res = mysqli_query($conn, "SELECT token FROM user WHERE username = '$username';"); $res = mysqli_fetch_object($res); $db_token = $res->token; if ($db_token == $token) { $result = mysqli_query($conn, "SELECT id_user FROM user WHERE username = '$username';"); $result = mysqli_fetch_object($result); $id_user = $result->id_user; if (!$result) { $send_data->res = "false"; $json = json_encode($send_data); print($json); } else { $result = mysqli_query($conn, "SELECT max_score,level FROM user_task WHERE id_task = '1' AND id_user = '$id_user';"); $result = mysqli_fetch_object($result); if (($score1 > ($result->max_score + 20)) or ($score1 < $result->max_score)) { $score1 = $result->max_score; } if (($level1 > ($result->level + 2)) or ($level1 < ($result->level - 2)) || ($level1 < 1)) { $level1 = $result->level; } $result = mysqli_query($conn, "UPDATE user_task SET max_score = '$score1', level = '$level1' WHERE id_task = '1' AND id_user = '$id_user';"); $result = mysqli_query($conn, "SELECT max_score,level FROM user_task WHERE id_task = '2' AND id_user = '$id_user';"); $result = mysqli_fetch_object($result); if (($score2 > ($result->max_score + 20)) or ($score2 < $result->max_score)) { $score2 = $result->max_score; } if (($level2 > ($result->level + 2)) or ($level2 < ($result->level - 2)) || ($level2 < 1)) { $level2 = $result->level; } $result = mysqli_query($conn, "UPDATE user_task SET max_score = '$score2', level = '$level2' WHERE id_task = '2' AND id_user = '$id_user';"); $send_data->res = "true"; $json = json_encode($send_data); print($json); } } else { $send_data->debug .= "404 Not Found<br>\n"; $json = json_encode($send_data); print($json); } } else { $send_data->debug .= "404 Not Found<br>\n"; $json = json_encode($send_data); print($json); } mysqli_close(); ?> <file_sep>#!/usr/bin/python # coding: utf-8 import os import mysql.connector as sqlconn import optparse import sys def add_clusters(hostname, username, password, database, txt): dic = {} reader = open(txt, "r") for line in reader: cluster, image, golden_task, different = line.split(" ") different = different.rstrip() if cluster not in dic: dic[cluster] = [] dic[cluster].append((image, golden_task, different)) conn = sqlconn.connect(user=username, password=<PASSWORD>, host=hostname, database=database) cursor = conn.cursor() for id_cluster, values in dic.iteritems(): numIm = len(values) #Insert entry in to cluster table query = ("INSERT INTO cluster(n_images) VALUES(%s)") data = (numIm,) cursor.execute(query, data) query = ("SELECT MAX(id_cluster) FROM cluster WHERE n_images = %s") data = (numIm,) cursor.execute(query, data) (id_cluster,) = cursor.fetchone() for (imname, golden_task, different) in values: #get image id in the table image query = ("SELECT id_image FROM image WHERE name_cropped_image = %s") data = (imname,) cursor.execute(query, data) (id_image,) = cursor.fetchone() #Insert entry in to image_cluster table query = ("INSERT INTO image_cluster(id_image, id_cluster) VALUES(%s, %s)") data = (id_image, id_cluster) cursor.execute(query, data) query = ("INSERT INTO task_image(id_image, id_validation, state, id_task) VALUES(%s, %s, %s, %s)") if golden_task == "1": if different == "1": state = "7" else: state = "8" else: state = "1" data = (id_image, id_cluster, state, "2") cursor.execute(query, data) conn.commit() cursor.close() conn.close() def main(argv): parser = optparse.OptionParser() parser.add_option('-H', '--Host', dest="hostname", default="192.168.127.12", type="string", help="Specify mysql hostname to connect") parser.add_option('-U', '--User', dest="username", default="jialuo", type="string", help="Specify username to connect") parser.add_option('-P', '--Password', dest="password", default="<PASSWORD>", type="string", help="Specify password to connect") parser.add_option('-D', '--Database', dest="ddbb", default="word_hunter", type="string", help="Specify which database to connect") parser.add_option('-f', '--file_clusters_txt', dest="clusters_txt", type="string", help="Relative/absolute path of the TXT file where stores clusters in the form 'cluster_id,imagename'") options, remainder = parser.parse_args() add_clusters(options.hostname, options.username, options.password, options.ddbb, options.clusters_txt) if __name__ == "__main__": main(sys.argv[1:])<file_sep><?php function make_seed() { list($usec, $sec) = explode(' ', microtime()); return $sec + $usec * 1000000; } $params = parse_ini_file("./config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mt_srand(make_seed()); $randval = mt_rand(); $username = $_REQUEST['username']; $result = mysqli_query($conn, "SELECT level FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE ut.id_task = 2 AND u.username = '$username';"); $result = mysqli_fetch_object($result); if ($result->level >= 4) { if ($result->level == 4) { for ($i = $result->level; $i < 5; $i++) { $goldens = 10 - $i*2; $result = mysqli_query($conn, "SELECT id_batch FROM batch WHERE active = '1' AND id_task = '2' AND golden_tasks = '$goldens' ORDER BY used_times, RAND(".$randval.") LIMIT 1;"); $result = mysqli_fetch_object($result); $id_batches[] = $result->id_batch; } $limit = 2 - count($id_batches); } else { $limit = 2; } $result = mysqli_query($conn, "SELECT id_batch FROM batch WHERE active = '1' AND id_task = '2' AND golden_tasks = 0 ORDER BY used_times, RAND(".$randval.") LIMIT '$limit';"); foreach ($result as $key => $batch) { $id_batches[] = $batch; } $count = count($id_batches); for ($i = 0; $i < $count; $i++) { $id_batch = $id_batches[$i]; mysqli_query($conn, "UPDATE batch SET used_times = used_times + 1 WHERE id_batch = '$id_batch';"); $out = mysqli_query($conn, "SELECT id_image FROM batch_image WHERE id_batch = '$id_batch' ORDER BY id_validation, RAND(".$randval.");"); foreach ($out as $key => $im) { $image_ids[] = $im[id_image]; } } } else { for ($i = $result->level; $i < $result->level + 2; $i++) { $goldens = 10 - $i*2; $result = mysqli_query($conn, "SELECT id_batch FROM batch WHERE active = '1' AND id_task = '2' AND golden_tasks = '$goldens' ORDER BY used_times, RAND(".$randval.") LIMIT 1;"); $result = mysqli_fetch_object($result); $id_batches[] = $result->id_batch; } $count = count($id_batches); for ($i = 0; $i < $count; $i++) { $id_batch = $id_batches[$i]; mysqli_query($conn, "UPDATE batch SET used_times = used_times + 1 WHERE id_batch = '$id_batch';"); $out = mysqli_query($conn, "SELECT id_image FROM batch_image WHERE id_batch = '$id_batch' ORDER BY RAND(".$randval.");"); foreach ($out as $key => $im) { $image_ids[] = $im[id_image]; } } } $count = count($image_ids); for ($i = 0; $i < $count; $i++) { $result = mysqli_query($conn, "SELECT i.name_cropped_image, c.id_cluster, ti.state FROM image i INNER JOIN image_cluster c INNER JOIN task_image ti ON i.id_image = c.id_image AND i.id_image = ti.id_image AND c.id_cluster = ti.id_validation WHERE id_image = ".$image_ids[$i]." AND id_task = 2"); while ($row = mysqli_fetch_assoc($result)) { if ($row[state] != 7 && $row[state] != 8) { $output = $row[name_cropped_image].";".$row[id_cluster].";0;0"; } else if ($row[state] == 7) { $output = $row[name_cropped_image].";".$row[id_cluster].";1;1"; } else { $output = $row[name_cropped_image].";".$row[id_cluster].";0;1"; } } } $count = count($output); for($i = 0; $i < $count; $i++) { print($output[$i].'<br>'); } mysqli_close($conn); ?> <file_sep><?php function getNewToken($token) { $replacements = "<KEY>"; $ran_token = rand(0,44); $ran_str = rand(0, 61); $token[$ran_token] = $replacements[$ran_str]; return $token; } function generateToken() { $new_token = ""; $replacements = "<KEY>"; for ($i = 0; $i < 45; $i++) { $ran_str = rand(0, 61); $new_token .= $replacements[$ran_str]; } return $new_token; } ?> <file_sep>#!/usr/bin/python # coding: utf-8 import os import mysql.connector as sqlconn import optparse import sys from random import randint def create_batch(hostname, username, password, database): NUM_ITEMS_PER_BATCH = 8 conn = sqlconn.connect(user=username, password=<PASSWORD>, host=hostname, database=database) cursor = conn.cursor() #ADD TRANSCRIPTION GAME BATCHES -> id_task = 1 for TRANSCRIPTION GAME query = ("SELECT t.id_image, t.id_transcription FROM transcription t INNER JOIN task_image ti ON t.id_transcription = ti.id_validation AND t.id_image = ti.id_image WHERE t.used_in_batch = 0 AND ti.id_task = 1 AND (ti.state LIKE 1 OR ti.state LIKE 4 OR ti.state LIKE 9 OR ti.state LIKE 10) ORDER BY RAND(%s)") data = (randint(1, 196),) cursor.execute(query, data) rows = cursor.fetchall() pos = 0 ID_IMAGE = 0 ID_TRANSCRIPTION = 1 query = ("SELECT t.id_image, t.id_transcription FROM transcription t INNER JOIN task_image ti ON t.id_transcription = ti.id_validation AND t.id_image = ti.id_image WHERE ti.id_task = 1 AND (ti.state LIKE 6 OR ti.state LIKE 11) ORDER BY t.used_in_batch, RAND(%s)") data = (randint(1, 196),) cursor.execute(query, data) golden_tasks = cursor.fetchall() pos_golden = 0 for i in range(1,5): goldens = 10-(i*2) query = ("SELECT id_batch FROM batch WHERE id_task = 1 AND active = 1 AND golden_tasks = %s") data = (goldens,) cursor.execute(query, data) if cursor.fetchone() == None: query = ("INSERT INTO batch(id_task, n_images, active, golden_tasks) VALUES(%s, %s, %s, %s)") data = (1, "10", "1", str(goldens)) cursor.execute(query, data) query = ("SELECT LAST_INSERT_ID();") cursor.execute(query) (id_batch,) = cursor.fetchone() for _ in range(goldens): id_image = golden_tasks[pos_golden][ID_IMAGE] id_transcription = golden_tasks[pos_golden][ID_TRANSCRIPTION] pos_golden += 1 if pos_golden >= len(golden_tasks): pos_golden = 0 query = ("UPDATE transcription SET used_in_batch = used_in_batch + 1 WHERE id_transcription = %s") data = (id_transcription,) cursor.execute(query, data) query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_transcription) cursor.execute(query, data) for _ in range(10 - goldens): id_image = rows[pos][ID_IMAGE] id_transcription = rows[pos][ID_TRANSCRIPTION] pos += 1 if pos >= len(rows): pos = 0 query = ("UPDATE transcription SET used_in_batch = %s WHERE id_transcription = %s") data = (1, id_transcription) cursor.execute(query, data) query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_transcription) cursor.execute(query, data) conn.commit() query = ("SELECT COUNT(id_batch) FROM batch WHERE id_task = 1 AND active = 1") cursor.execute(query) (count,) = cursor.fetchone() create_num_batch = 21 - int(count) if create_num_batch > 0: for num_batch in range(create_num_batch): query = ("INSERT INTO batch(id_task, n_images, active, golden_tasks) VALUES(%s, %s, %s, %s)") data = (1, "10", "1", "2") cursor.execute(query, data) query = ("SELECT LAST_INSERT_ID();") cursor.execute(query) (id_batch,) = cursor.fetchone() for _ in range(2): id_image = golden_tasks[pos_golden][ID_IMAGE] id_transcription = golden_tasks[pos_golden][ID_TRANSCRIPTION] pos_golden += 1 if pos_golden >= len(golden_tasks): pos_golden = 0 query = ("UPDATE transcription SET used_in_batch = used_in_batch + 1 WHERE id_transcription = %s") data = (id_transcription,) cursor.execute(query, data) query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_transcription) cursor.execute(query, data) for images in range(NUM_ITEMS_PER_BATCH): id_image = rows[pos][ID_IMAGE] id_transcription = rows[pos][ID_TRANSCRIPTION] pos += 1 if pos >= len(rows): pos = 0 images += 1 query = ("UPDATE transcription SET used_in_batch = %s WHERE id_transcription = %s") data = (1, id_transcription) cursor.execute(query, data) query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_transcription) cursor.execute(query, data) conn.commit() #ADD CLUSTER GAME BATCHES -> id_task = 2 for CLUSTER GAME query = ("SELECT c.id_cluster FROM cluster c INNER JOIN task_image ti ON c.id_cluster = ti.id_validation WHERE c.used_in_batch = 0 AND ti.id_task = 2 AND (ti.state LIKE 1 OR ti.state LIKE 9) GROUP BY c.id_cluster ORDER BY RAND(%s)") data = (randint(1,196),) cursor.execute(query, data) rows = [i for (i,) in cursor.fetchall()] pos = 0 query = ("SELECT c.id_cluster FROM cluster c INNER JOIN task_image ti ON c.id_cluster = ti.id_validation WHERE ti.id_task = 2 AND (ti.state LIKE 7 OR ti.state LIKE 8) GROUP BY c.id_cluster ORDER BY c.used_in_batch, RAND(%s)") data = (randint(1,196),) cursor.execute(query, data) golden_tasks = [i for (i,) in cursor.fetchall()] pos_golden = 0 for i in range(1,5): goldens = 10-(i*2) query = ("SELECT id_batch FROM batch WHERE id_task = 2 AND active = 1 AND golden_tasks = %s") data = (goldens,) cursor.execute(query, data) if cursor.fetchone() == None: query = ("INSERT INTO batch(id_task, n_images, active, golden_tasks) VALUES(%s, %s, %s, %s)") data = (2, "10", "1", str(goldens)) cursor.execute(query, data) query = ("SELECT LAST_INSERT_ID();") cursor.execute(query) (id_batch,) = cursor.fetchone() total_images = 0 for _ in range(goldens): id_cluster = golden_tasks[pos_golden] pos_golden += 1 if pos_golden >= len(golden_tasks): pos_golden = 0 query = ("UPDATE cluster SET used_in_batch = used_in_batch + 1 WHERE id_cluster = %s") data = (id_cluster,) cursor.execute(query, data) query = ("SELECT id_image FROM image_cluster WHERE id_cluster = %s") data = (id_cluster,) cursor.execute(query, data) images = [i for (i,) in cursor.fetchall()] total_images += len(images) for id_image in images: query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_cluster) cursor.execute(query, data) for _ in range(10 - goldens): id_cluster = rows[pos] pos += 1 if pos >= len(rows): pos = 0 query = ("UPDATE cluster SET used_in_batch = %s WHERE id_cluster = %s") data = (1, id_cluster) cursor.execute(query, data) query = ("SELECT id_image FROM image_cluster WHERE id_cluster = %s") data = (id_cluster,) cursor.execute(query, data) images = [i for (i,) in cursor.fetchall()] total_images += len(images) for id_image in images: query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_cluster) cursor.execute(query, data) query = ("UPDATE batch SET n_images = %s WHERE id_batch = %s") data = (total_images, id_batch) cursor.execute(query, data) query = ("SELECT COUNT(id_batch) FROM batch WHERE id_task = 2 AND active = 1") cursor.execute(query) (count,) = cursor.fetchone() create_num_batch = 20 - int(count) if create_num_batch > 0: for num_batch in range(create_num_batch): total_images = 0 query = ("INSERT INTO batch(id_task, n_images, active, golden_tasks) VALUES(%s, %s, %s, %s)") data = (2, "10", "1", "2") cursor.execute(query, data) query = ("SELECT LAST_INSERT_ID();") cursor.execute(query) (id_batch,) = cursor.fetchone() for _ in range(2): id_cluster = golden_tasks[pos_golden] pos_golden += 1 if pos_golden >= len(golden_tasks): pos_golden = 0 query = ("UPDATE cluster SET used_in_batch = used_in_batch + 1 WHERE id_cluster = %s") data = (id_cluster,) cursor.execute(query, data) query = ("SELECT id_image FROM image_cluster WHERE id_cluster = %s") data = (id_cluster,) cursor.execute(query, data) images = [i for (i,) in cursor.fetchall()] total_images += len(images) for id_image in images: query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_cluster) cursor.execute(query, data) for clusters in range(NUM_ITEMS_PER_BATCH): used_in_batch = 1 while used_in_batch == 1: id_cluster = rows[pos] pos += 1 if pos >= len(rows): pos = 0 query = ("SELECT used_in_batch FROM cluster WHERE id_cluster = %s") data = (id_cluster,) cursor.execute(query, data) (used_in_batch,) = cursor.fetchone() query = ("UPDATE cluster SET used_in_batch = %s WHERE id_cluster = %s") data = (1, id_cluster) cursor.execute(query, data) query = ("SELECT id_image FROM image_cluster WHERE id_cluster = %s") data = (id_cluster,) cursor.execute(query, data) images = [i for (i,) in cursor.fetchall()] total_images += len(images) for id_image in images: query = ("INSERT INTO batch_image(id_batch, id_image, id_validation) VALUES(%s, %s, %s)") data = (id_batch, id_image, id_cluster) cursor.execute(query, data) query = ("UPDATE batch SET n_images = %s WHERE id_batch = %s") data = (total_images, id_batch) cursor.execute(query, data) conn.commit() cursor.close() conn.close() def main(argv): parser = optparse.OptionParser() parser.add_option('-H', '--Host', dest="hostname", default="192.168.3.11", type="string", help="Specify mysql hostname to connect") parser.add_option('-U', '--User', dest="username", default="jialuo", type="string", help="Specify username to connect") parser.add_option('-P', '--Password', dest="password", default="<PASSWORD>", type="string", help="Specify password to connect") parser.add_option('-D', '--Database', dest="ddbb", default="word_hunter", type="string", help="Specify which database to connect") options, remainder = parser.parse_args() create_batch(options.hostname, options.username, options.password, options.ddbb) if __name__ == "__main__": main(sys.argv[1:])<file_sep>#!/usr/bin/python # coding: utf-8 import os import mysql.connector as sqlconn import optparse import sys def add_transcriptions(hostname, username, password, database, txt): reader = open(txt, "r") conn = sqlconn.connect(user=username, password=<PASSWORD>, host=hostname, database=database) cursor = conn.cursor() for line in reader: imagename, transcription, type_trans, golden_task, correct = line.split(" ") correct = correct.rstrip() query = ("SELECT id_image FROM image WHERE name_cropped_image = %s") data = (imagename,) cursor.execute(query, data) (id_image,) = cursor.fetchone() query = ("INSERT INTO transcription(id_image, transcription, type) VALUES(%s, %s, %s)") data = (id_image, transcription, type_trans) cursor.execute(query, data) query = ("SELECT id_transcription FROM transcription WHERE id_image = %s") data = (id_image,) cursor.execute(query, data) (id_transcription,) = cursor.fetchone() query = ("INSERT INTO task_image(id_image, id_validation, state, id_task) VALUES(%s, %s, %s, %s)") if golden_task == "1": if correct == "1": state = 11 else: state = 6 else: state = 1 data = (id_image, id_transcription, state, "1") cursor.execute(query, data) conn.commit() cursor.close() conn.close() def main(argv): parser = optparse.OptionParser() parser.add_option('-H', '--Host', dest="hostname", default="172.16.58.3", type="string", help="Specify mysql hostname to connect") parser.add_option('-U', '--User', dest="username", default="jialuo", type="string", help="Specify username to connect") parser.add_option('-P', '--Password', dest="password", default="<PASSWORD>", type="string", help="Specify password to connect") parser.add_option('-D', '--Database', dest="ddbb", default="word_hunter", type="string", help="Specify which database to connect") parser.add_option('-f', '--file_clusters_txt', dest="clusters_txt", type="string", help="Relative/absolute path of the TXT file where stores transcriptions in the form 'imagename:transcription:type'") options, remainder = parser.parse_args() add_transcriptions(options.hostname, options.username, options.password, options.ddbb, options.clusters_txt) if __name__ == "__main__": main(sys.argv[1:])<file_sep><?php $params = parse_ini_file("./config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_REQUEST['username']; if ($username == NULL) { $result = mysqli_query($conn, "SELECT username, max_score FROM user_task WHERE id_task = 1 ORDER BY max_score DESC LIMIT 10;"); while ($row = mysqli_fetch_assoc($result)) { $output1[] = $row[username].','.$row[max_score]; } $result = mysqli_query($conn, "SELECT username, max_score FROM user_task WHERE id_task = 2 ORDER BY max_score DESC LIMIT 10;"); while ($row = mysqli_fetch_assoc($result)) { $output2[] = $row[username].','.$row[max_score]; } $count = count($output1); for ($i = 0; $i < $count; $i++) { print($output1[$i].'<br>'); } print('separator<br>'); for ($i = 0; $i < $count; $i++) { print($output2[$i].'<br>'); } } else { $result = mysqli_query($conn, "SELECT ut.max_score FROM user_task ut WHERE ut.username = '".$username."' AND ut.id_task = 1;"); $match = mysqli_fetch_assoc($result); $result = mysqli_query($conn, "SELECT ut.max_score FROM user_task ut WHERE ut.username = '".$username."' AND ut.id_task = 2;"); $diff = mysqli_fetch_assoc($result); print($match[max_score].','.$diff[max_score]); } mysqli_close(); ?> <file_sep><?php $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_REQUEST['username']; $password = $_REQUEST['<PASSWORD>']; $result = mysqli_query($conn, "SELECT id_user FROM user WHERE username = '$username';"); while ($row = mysqli_fetch_assoc($result)) { $output[] = $row[id_user]; } $count = count($output); if ($count == 0) { $password = <PASSWORD>($password); mysqli_query($conn, "INSERT INTO user(username, password) VALUES ('$username', '$password')"); $result = mysqli_query($conn, "SELECT MAX(id_user) AS id_user FROM user WHERE username = '$username';"); $row = mysqli_fetch_object($result); mysqli_query($conn, "INSERT INTO user_task(id_user, id_task, max_score, level) VALUES ('$row->id_user', 1, 0, 1)"); mysqli_query($conn, "INSERT INTO user_task(id_user, id_task, max_score, level) VALUES ('$row->id_user', 2, 0, 1)"); print('true'); } else { print('false'); } mysqli_close(); ?> <file_sep><?php $params = parse_ini_file("../../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $filename = $_REQUEST['filename']; $cluster = $_REQUEST['cluster']; $user = $_REQUEST['user']; $level = $_REQUEST['level']; $startDate = $_REQUEST['startDate']; $endDate = $_REQUEST['endDate']; $scoreInici = $_REQUEST['scoreInici']; $scoreFinal = $_REQUEST['scoreFinal']; $result = mysqli_query($conn, "INSERT INTO different_game_clustering (filename, cluster_id, username, nivell, inici, final, score_inici, score_final) VALUES ('".$filename."', '".$cluster."', '".$user."', '".$level."', STR_TO_DATE('".$startDate."','%Y%m%d %H%i%s'), STR_TO_DATE('".$endDate."','%Y%m%d %H%i%s'), '".$scoreInici."', '".$scoreFinal."');"); if ($result != False) { print('True'); } else { print('False'); } mysqli_close(); ?> <file_sep><?php $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_POST['username']; if ($username == NULL) { $result = mysqli_query($conn, "SELECT u.username AS username, ut.max_score AS max_score FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE ut.id_task = 1 ORDER BY ut.max_score DESC LIMIT 10;"); while ($row = mysqli_fetch_assoc($result)) { $output1[] = $row[username].','.$row[max_score]; } $result = mysqli_query($conn, "SELECT u.username AS username, ut.max_score AS max_score FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE ut.id_task = 2 ORDER BY ut.max_score DESC LIMIT 10;"); while ($row = mysqli_fetch_assoc($result)) { $output2[] = $row[username].','.$row[max_score]; } $out1 = join('<br>',$output1); $out2 = join('<br>',$output2); $out = $out1.'separator<br>'.$out2; $send_data->res = $out; $json = json_encode($send_data); print($json); } else { $result = mysqli_query($conn, "SELECT ut.max_score AS max_score, ut.level AS level FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE u.username = '$username' AND ut.id_task = 1;"); $match = mysqli_fetch_object($result); $result = mysqli_query($conn, "SELECT ut.max_score AS max_score, ut.level AS level FROM user u INNER JOIN user_task ut ON u.id_user = ut.id_user WHERE u.username = '$username' AND ut.id_task = 2;"); $diff = mysqli_fetch_object($result); $out = $match->max_score.','.$diff->max_score.','.$match->level.','.$diff->level; $send_data->res = $out; $json = json_encode($send_data); print($json); } mysqli_close(); ?> <file_sep><?php include 'Token.php'; $params = parse_ini_file("../config.ini"); $conn = mysqli_connect($params['hostname'],$params['username'],$params['password'],$params['db_name']); if (mysqli_connect_errno($conn)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $send_data->debug = "debug info<br>\n"; $result = mysqli_query($conn, "SELECT id_user FROM user WHERE username = '$username';"); while ($row = mysqli_fetch_assoc($result)) { $output[] = $row[id_user]; } $count = count($output); if ($count == 1) { $result = mysqli_query($conn, "SELECT u.password FROM user u WHERE u.username = '$username';"); $result = mysqli_fetch_object($result); if (sha1($password) == $result->password) { if ($username != "test") { $token = generateToken($token); mysqli_query($conn, "UPDATE user SET token = '$token' WHERE username = '$username';"); } else { $res = mysqli_query($conn, "SELECT token FROM user WHERE username = '$username';"); $res = mysqli_fetch_object($res); $token = $res->token; } $send_data->token = $token; $send_data->res = "true"; $json = json_encode($send_data); print($json); } else { $send_data->token = -1; $send_data->res = "false"; $json = json_encode($send_data); print($json); } } else { $send_data->token = -1; $send_data->res = "false"; $json = json_encode($send_data); print($json); } mysqli_close(); ?>
4e46045c4cb84f72e92ad83da28f64f8c6b22386
[ "Python", "PHP", "INI" ]
22
PHP
JaChiKore/word_hunter_scripts
41b23d62208b72a19cfa074774aabc50e79e5388
436ab37be9dd4bc8533788d984180d4dfd46d82c
refs/heads/master
<repo_name>jqsook/Flask<file_sep>/market/__init__.py from enum import unique from flask import Flask, app, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # see vid at 138 for database creation app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db' db = SQLAlchemy(app) # must pass in the name of the app here. # To run the server # export FLASK_APP=hello.py # export FLASK_ENV=development # flask run <file_sep>/README.md <!-- Ref Material --> <!-- Flask --> https://flask.palletsprojects.com/en/2.0.x/ <!-- Youtube vid --> https://www.youtube.com/watch?v=Qr4QMBUPxWo <!-- GitHub --> https://github.com/jimdevops19/FlaskSeries <!-- Help with the server operation --> https://flask.palletsprojects.com/en/2.0.x/cli/ <!-- SQLite Browser --> https://sqlitebrowser.org/ <!-- HardCode way of username info --> # THis is the hard coded way of doing a username input- this is not dyanmic # @app.route('/about/<username>') # def about_page(username): # return f'<h1>THis is the about page of {username}</h1>' <!-- Ref- market.html ln69 --> {% for item in items %} <!-- The for loop allows for the iteration over the list and dynamically builds the table based on the number of items in the list. --> <tr> <td>{{ item.id }}</td> <td>{{ item. name }}</td> <td>{{ item.barcode }}</td> <td>$ {{ item.price }}</td> </tr> {% endfor %} </tbody> <!-- Old Home page html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous" /> <title>Home Page</title> </head> <!-- NavBar --> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#" >Home <span class="sr-only">(current)</span></a > </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> </nav> </header> <!-- Body --> <body> <main> <h1>Welcome to the home page</h1> <!-- Footer --> <footer></footer> </main> <!-- Script links --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous" ></script> </body> <style> body { background-color: #212121; color: white; } </style> </html> <!-- The old Market html --> <!-- Kept for the table --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous" /> <title>Market Page</title> </head> <!-- NavBar --> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#" >Home <span class="sr-only">(current)</span></a > </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> </nav> </header> <!-- Body --> <body> <main> <h1>Welcome to the Market page</h1> <!-- Table --> <table class="table table-hover table-dark"> <thead> <tr> <!-- Your Columns HERE --> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Barcode</th> <th scope="col">Price</th> <th scope="col">Options</th> </tr> </thead> <tbody> <!-- Your rows inside the table HERE: --> {% for item in items %} <tr> <td>{{ item.id }}</td> <td>{{ item. name }}</td> <td>{{ item.barcode }}</td> <td>$ {{ item.price }}</td> <td> <button class="btn btn-outline btn-info">More Info</button> <button class="btn btn-outline btn-success"> Purchase this item </button> </td> </tr> {% endfor %} </tbody> </table> <!-- Footer --> <footer></footer> </main> <!-- Script links --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous" ></script> </body> <style> body { background-color: #212121; color: white; } </style> </html> <!-- This is around 150 in the video --> # These were moved at 153 in the video # class Item(db.Model): # # THis field is required with sqlalchemy # id = db.Column(db.Integer(), primary_key=True) # # This sets limits on the information stored in the db # name = db.Column(db.String(length=30), nullable=False, unique=True) # price = db.Column(db.Integer(), nullable=False) # barcode = db.Column(db.String(length=12), nullable=False, unique=True) # description = db.Column(db.String(length=1024), # nullable=False, unique=True) # def **repr**(self): # # This makes the name that shows up the database custom to the name in the # return f'Item {self.name}' # @app.route("/") # @app.route('/home') # def home_page(): # return render_template('home.html') # @app.route('/market') # def market_page(): # items = Item.query.all() # return render_template('market.html', items=items) <file_sep>/notused.md from enum import unique from flask import Flask, app, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # see vid at 138 for database creation app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db' db = SQLAlchemy(app) # must pass in the name of the app here. # To run the server # export FLASK_APP=hello.py # export FLASK_ENV=development # flask run <file_sep>/market/templates/home.html {% extends 'base.html' %} <!-- Title --> {% block title %} Home Page {% endblock %} <!-- Content section --> {% block content %} This is our content for our home page {% endblock%}
7a11b64301072710f830775cedb056621010f7fb
[ "Markdown", "Python", "HTML" ]
4
Python
jqsook/Flask
fa4ae14cefae52a3989319c02d03157751b872db
6f4881966583cc1395ff62f920a55b23a5e892bc
refs/heads/master
<repo_name>amandasantanati/introductory_programming_exercises<file_sep>/tests/com/twu/shapes/TriangleTest.java package com.twu.shapes; import org.junit.Test; import static org.junit.Assert.*; public class TriangleTest { @Test public void buildTriangleThirdDeep() throws Exception { assertEquals("*\n**\n***\n", new Triangle(3).getStructure()); } }<file_sep>/tests/com/twu/shapes/DiamondWithNameTest.java package com.twu.shapes; import org.junit.Test; import static org.junit.Assert.*; public class DiamondWithNameTest { @Test public void buildDiamondFirstDeep() throws Exception { assertEquals("*\n", new DiamondWithName(1).getStructure()); } @Test public void buildDiamondWithNameSecondDeep() throws Exception { assertEquals(" *\nAmanda\n *\n", new DiamondWithName(2).getStructure()); } @Test public void buildDiamondWithNameThirdDeep() throws Exception { assertEquals(" *\n ***\nAmanda\n ***\n *\n", new DiamondWithName(3).getStructure()); } @Test public void buildDiamondWithNameFourthDeep() throws Exception { assertEquals(" *\n ***\n *****\nAmanda\n *****\n ***\n *\n", new DiamondWithName(4).getStructure()); } }<file_sep>/src/com/twu/shapes/Exercise.java package com.twu.shapes; public class Exercise { public static void main(String[] args) { Triangle triangle = new Triangle(3); System.out.println(triangle.horizontalLine(1)); System.out.println(); System.out.println(triangle.horizontalLine(3)); System.out.println(); System.out.println(triangle.verticalLine(3)); System.out.println(triangle); IsoscelesTriangle isosceles = new IsoscelesTriangle(4); System.out.println(isosceles); Diamond diamond = new Diamond(4); System.out.println(diamond); DiamondWithName withName = new DiamondWithName(4); System.out.println(withName); } } <file_sep>/tests/com/twu/shapes/ShapeTest.java package com.twu.shapes; import org.junit.Test; import static org.junit.Assert.*; public class ShapeTest { @Test public void aSymbol() throws Exception { assertEquals("*", Shape.horizontalLine(1)); } @Test public void horizontalLineWithThreeColumns() throws Exception { assertEquals("***", Shape.horizontalLine(3)); } @Test public void verticalLineWithThreeRows() throws Exception { assertEquals("*\n*\n*\n", Shape.verticalLine(3)); } }<file_sep>/tests/com/twu/shapes/DiamondTest.java package com.twu.shapes; import org.junit.Test; import static org.junit.Assert.*; public class DiamondTest { @Test public void buildDiamondFirstDeep() throws Exception { assertEquals("*\n", new Diamond(1).getStructure()); } @Test public void buildDiamondSecondDeep() throws Exception { assertEquals(" *\n ***\n *\n", new Diamond(2).getStructure()); } @Test public void buildDiamondThirdDeep() throws Exception { assertEquals(" *\n ***\n*****\n ***\n *\n", new Diamond(3).getStructure()); } @Test public void buildDiamondFourthDeep() throws Exception { assertEquals(" *\n ***\n *****\n*******\n *****\n ***\n *\n", new Diamond(4).getStructure()); } }
d99e59713071e5e2dd09cc19b705ee3c2d016bf3
[ "Java" ]
5
Java
amandasantanati/introductory_programming_exercises
0522ab9f16cb831d90867104d53384ed15113aab
6a2fac8f1403986c345a782f1bcd469d85ba6185
refs/heads/master
<file_sep>package com.binaryconvert.converter; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.text.TextWatcher; import static android.text.InputType.TYPE_CLASS_NUMBER; public class Main2ActivityCalculation extends AppCompatActivity { private TextView hasil; private EditText nilai1, nilai2; private Button btnkurang,btntambah,btnkali,btnbagi,btnconvert,btncalculate,btnmod; private Spinner spinnercalcu1, spinnercalcu2, spinnerhasil; public String[] spinnilai1item = new String[]{"Decimal","Octal"}; public String[] spinnilai2item = new String[]{"Decimal","Octal"}; public String[] spinhasilitem = new String[]{"Decimal","Octal"}; private ArrayAdapter<String> spinAdapter; private ArrayAdapter<String> spinAdapter2; private int spinPosisi,spinposisi2; private long hasilconvert1; private long hasilconvert2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2_calculation); spinPosisi=0; nilai1 = (EditText) findViewById(R.id.calcu1Text); nilai1.addTextChangedListener(new textwatcher1(nilai1)); nilai2 = (EditText) findViewById(R.id.calcu2Text); nilai2.addTextChangedListener(new textwatcher1(nilai2)); hasil = (TextView) findViewById(R.id.hasilView); btnkurang = (Button) findViewById(R.id.buttonMinus); btntambah = (Button) findViewById(R.id.buttonPlus); btnkali = (Button) findViewById(R.id.buttonX); btnbagi = (Button) findViewById(R.id.buttonBagi); btnmod = (Button) findViewById(R.id.buttonMod); btncalculate = (Button) findViewById(R.id.btncalcu); btncalculate.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { opencalcu(); } }); btnconvert = (Button) findViewById(R.id.btnconvert); btnconvert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openconvert(); } }); spinnercalcu1 = (Spinner) findViewById(R.id.spinnercalcu1); spinAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,spinnilai1item); spinnercalcu1.setAdapter(spinAdapter); spinnercalcu1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int i, long l) { spinPosisi = i; nilai1.setText(""); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spinnercalcu2 = (Spinner) findViewById(R.id.spinnercalcu2); spinAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,spinnilai2item); spinnercalcu2.setAdapter(spinAdapter2); spinnercalcu2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int i, long l) { spinposisi2 = i; nilai2.setText(""); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); btnmod.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { convertfirst(); duMod(); } }); btnkurang.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { convertfirst(); dosubstract(); } }); btntambah.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { convertfirst(); dosum(); } }); btnkali.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { convertfirst(); domultiple(); } }); btnbagi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { convertfirst(); dodivide(); } }); } private void duMod() { long a=this.hasilconvert1; long b= this.hasilconvert2; long hasilcalculation=(a%b); hasil.setText("" + hasilcalculation); hasil.setTextSize(20); } private void dodivide() { long a=this.hasilconvert1; long b= this.hasilconvert2; long hasilcalculation=(a/b); hasil.setText("" + hasilcalculation); hasil.setTextSize(20); } private void domultiple() { long a=this.hasilconvert1; long b= this.hasilconvert2; long hasilcalculation=(a*b); hasil.setText("" + hasilcalculation); hasil.setTextSize(20); } private void dosum() { long a=this.hasilconvert1; long b= this.hasilconvert2; long hasilcalculation=(a+b); hasil.setText("" + hasilcalculation); hasil.setTextSize(20); } private void dosubstract() { long a= this.hasilconvert1; long b =this.hasilconvert2; long hasilcalculation=(a-b); hasil.setText("" + hasilcalculation); hasil.setTextSize(20); } private void convertvalue1() { String value1 = nilai1.getText().toString(); long tmp1; String container; //KOONVERT KE DESIMAL DULU SMUANYA, STELAH ITU DI LAKUKAN CALCULATE, ABISTU DIRUBAH KE HASILNYA if (!checkingInputValidation()) { switch (spinPosisi) { case 0: //decimal try { tmp1=Integer.parseInt(value1); sethasilconvert1(tmp1); } catch (Exception e) { nilai1.setError("Something Wrong"); requestFocus(nilai1); } break; case 1: //oktal try { tmp1=Long.parseLong(value1,8); sethasilconvert1(tmp1); } catch (Exception e) { nilai1.setError("Something Wrong"); requestFocus(nilai1); } break; } } } private void convertvalue2() { String value2 = nilai2.getText().toString(); long tmp2; String container; //KOONVERT KE DESIMAL DULU SMUANYA, STELAH ITU DI LAKUKAN CALCULATE, ABISTU DIRUBAH KE HASILNYA if (!checkingInputValidation()) { switch (spinposisi2) { case 0: //decimal try { // hasil.setText(value1); // hasil.setTextSize(20); tmp2=Integer.parseInt(value2); sethasilconvert2(tmp2); } catch (Exception e) { nilai2.setError("Something Wrong"); requestFocus(nilai2); } break; case 1: //oktal try { tmp2=Long.parseLong(value2,8); sethasilconvert2(tmp2); // hasil.setText(""+Long.parseLong(value1,8)); // hasil.setTextSize(20); // tmp1=tmp1+Integer.parseInt(value1,8); } catch (Exception e) { nilai2.setError("Something Wrong"); requestFocus(nilai2); } break; } } } private void convertfirst() { convertvalue1(); convertvalue2(); } private boolean checkingInputValidation() { String gettingInput = nilai1.getText().toString(); if (nilai1.getText().toString().trim().isEmpty()) { nilai1.setError("Silahkan inputkan nilai yang akan dikonversikan"); requestFocus(nilai1); return true; } else if (spinPosisi == 2 && gettingInput.matches(".*[8-9].*")) { nilai1.setError("Masukkan nilai input hanya interval dari 0 sampai 7"); requestFocus(nilai1); return true; }else if (gettingInput.length() > 15) { nilai1.setError("Masukkan nilai input maksimal 6 digit"); requestFocus(nilai1); return true; } return false; } private void requestFocus(View view) { if (view.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } //BUTTON OPEN CAONVERT private void openconvert() { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } //BUTTON OPEN CALCU private void opencalcu() { Intent intent = new Intent(this,Main2ActivityCalculation.class); startActivity(intent); } public void sethasilconvert1(long hasilconvert1) { this.hasilconvert1 = hasilconvert1; } public void sethasilconvert2(long hasilconvert2) { this.hasilconvert2 = hasilconvert2; } private class textwatcher1 implements TextWatcher { private View view; private textwatcher1(View view) { this.view = view; } public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { switch (view.getId()) { case R.id.input: validateInput(); break; } } } private void validateInput() { if (spinPosisi == 0) { //decimal nilai1.setInputType(TYPE_CLASS_NUMBER); nilai2.setInputType(TYPE_CLASS_NUMBER); } else{ //octal nilai1.setInputType(TYPE_CLASS_NUMBER); nilai2.setInputType(TYPE_CLASS_NUMBER); } } } <file_sep># AplikasiAndroid-Dec-Biner-Octa-Hex-Conversion-Calculation
759ff4f80854d2ade78a9c2bf06c500c778b9bae
[ "Markdown", "Java" ]
2
Java
nirmalaaliffia/AplikasiAndroid-Conversion-Calculation-Dec-Biner-Hex-Octa
d766ab2d1b92a68a334632d35aebbd5f23da55dc
a6d72164634d36672f72d1ca8fa148798d0c6a9c
refs/heads/master
<file_sep>-- Project Name : WonFesSys -- Date/Time : 2018/06/25 2:03:04 -- Author : <NAME> -- RDBMS Type : PostgreSQL -- Application : A5:SQL Mk-2 -- ディーラー詳細作品分野 drop table if exists dealers_detail_products_categories cascade; create table dealers_detail_products_categories ( dealer_id integer not null , product_id integer , category_id integer not null , constraint dealers_detail_products_categories_PKC primary key (dealer_id,product_id,category_id) ) ; -- ユーザー権限 drop table if exists usr_role cascade; create table usr_role ( usr_id char(10) not null , role varchar(30) , constraint usr_role_PKC primary key (usr_id,role) ) ; -- ユーザー詳細お気に入り drop table if exists usr_detail_fav_products cascade; create table usr_detail_fav_products ( usr_id char(10) not null , dealer_id integer , product_id integer , constraint usr_detail_fav_products_PKC primary key (usr_id,dealer_id,product_id) ) ; -- ユーザー drop table if exists usr cascade; create table usr ( usr_id char(10) , passwd char(32) , user_name varchar(50) , constraint usr_PKC primary key (usr_id) ) ; -- 開催時期 drop table if exists event_dates cascade; create table event_dates ( event_date_id integer , event_aboutdate char(5) , event_date date , event_season char(1) , constraint event_dates_PKC primary key (event_date_id) ) ; -- 作品分野 drop table if exists categories cascade; create table categories ( category_id integer , category_name varchar(50) , category_name_reading varchar(50) , constraint categories_PKC primary key (category_id) ) ; -- ディーラー詳細作品画像 drop table if exists dealers_detail_products_imgs cascade; create table dealers_detail_products_imgs ( dealer_id integer not null , product_id integer , img_product_file varchar(50) , constraint dealers_detail_products_imgs_PKC primary key (dealer_id,product_id,img_product_file) ) ; -- ディーラー詳細作品 drop table if exists dealers_detail_products cascade; create table dealers_detail_products ( dealer_id integer not null , product_id integer , product_name varchar(50) , price integer , introduce text , season_id integer , constraint dealers_detail_products_PKC primary key (dealer_id,product_id) ) ; -- ディーラー詳細作品販売時期 drop table if exists dealers_detail_products_saledate cascade; create table dealers_detail_products_saledate ( dealer_id integer , product_id integer , event_date_id integer not null , constraint dealers_detail_products_saledate_PKC primary key (dealer_id,product_id,event_date_id) ) ; -- ディーラー drop table if exists dealers cascade; create table dealers ( dealer_id int , dealer_name varchar(20) , bussines_type char(1) , takuban char(6) , hp_link varchar(50) , tw_link varchar(50) , sort_key char(1) , img_icon_file varchar(50) , constraint dealers_PKC primary key (dealer_id) ) ; alter table dealers_detail_products_categories add constraint dealers_detail_products_categories_FK1 foreign key (category_id) references categories(category_id); alter table dealers_detail_products_categories add constraint dealers_detail_products_categories_FK2 foreign key (dealer_id,product_id) references dealers_detail_products(dealer_id,product_id); alter table usr_role add constraint usr_role_FK1 foreign key (usr_id) references usr(usr_id); alter table usr_detail_fav_products add constraint usr_detail_fav_products_FK1 foreign key (usr_id) references usr(usr_id); alter table dealers_detail_products_saledate add constraint dealers_detail_products_saledate_FK1 foreign key (event_date_id) references event_dates(event_date_id); alter table dealers_detail_products_saledate add constraint dealers_detail_products_saledate_FK2 foreign key (dealer_id,product_id) references dealers_detail_products(dealer_id,product_id); alter table dealers_detail_products_imgs add constraint dealers_detail_products_imgs_FK1 foreign key (dealer_id,product_id) references dealers_detail_products(dealer_id,product_id); alter table dealers_detail_products add constraint dealers_detail_products_FK1 foreign key (dealer_id) references dealers(dealer_id); comment on table dealers_detail_products_categories is 'ディーラー詳細作品分野'; comment on column dealers_detail_products_categories.dealer_id is 'ディーラーID'; comment on column dealers_detail_products_categories.product_id is '作品ID'; comment on column dealers_detail_products_categories.category_id is 'ジャンル'; comment on table usr_role is 'ユーザー権限'; comment on column usr_role.usr_id is 'ユーザーID'; comment on column usr_role.role is '役割'; comment on table usr_detail_fav_products is 'ユーザー詳細お気に入り'; comment on table usr is 'ユーザー'; comment on table event_dates is '開催時期'; comment on column event_dates.event_date_id is '開催時期ID'; comment on column event_dates.event_aboutdate is '開催日概要:yyyyW,例:2018冬'; comment on column event_dates.event_date is '開催日'; comment on column event_dates.event_season is '開催季節'; comment on table categories is '作品分野'; comment on column categories.category_id is '作品分野ID'; comment on column categories.category_name is '作品名'; comment on column categories.category_name_reading is '作品名読み'; comment on table dealers_detail_products_imgs is 'ディーラー詳細作品画像'; comment on column dealers_detail_products_imgs.dealer_id is 'ディーラーID'; comment on column dealers_detail_products_imgs.product_id is '作品ID'; comment on column dealers_detail_products_imgs.img_product_file is '作品画像ファイル'; comment on table dealers_detail_products is 'ディーラー詳細作品'; comment on column dealers_detail_products.dealer_id is 'ディーラーID'; comment on column dealers_detail_products.product_id is '作品ID'; comment on column dealers_detail_products.product_name is '作品名'; comment on column dealers_detail_products.price is '値段'; comment on column dealers_detail_products.introduce is '紹介文'; comment on column dealers_detail_products.season_id is '販売時期'; comment on table dealers_detail_products_saledate is 'ディーラー詳細作品販売時期'; comment on column dealers_detail_products_saledate.dealer_id is 'ディーラーID'; comment on column dealers_detail_products_saledate.product_id is '作品ID'; comment on column dealers_detail_products_saledate.event_date_id is '販売時期'; comment on table dealers is 'ディーラー'; comment on column dealers.dealer_id is 'ディーラーid'; comment on column dealers.dealer_name is 'ディーラー名'; comment on column dealers.bussines_type is '事業形態:0:個人、1:法人'; comment on column dealers.takuban is '卓番号'; comment on column dealers.hp_link is 'HPリンク'; comment on column dealers.tw_link is 'TWリンク'; comment on column dealers.sort_key is 'ソートキー:ア、カなど(読み仮名)'; comment on column dealers.img_icon_file is 'アイコン画像ファイル'; <file_sep> -- 2まで select dealer_id,product_id from dealers_detail_products where dealer_id=1 -- 作品情報登録データ、ロールバック用 delete from dealers_detail_products_saledate where dealer_id='1' and product_id in ('3','4','5','6'); delete from dealers_detail_products_imgs where dealer_id='1' and product_id in ('3','4','5','6'); delete from dealers_detail_products_categories where dealer_id='1' and product_id in ('3','4','5','6'); delete from dealers_detail_products where dealer_id='1' and product_id in ('3','4','5','6'); <file_sep>-- Project Name : WonFesSys -- Date/Time : 2018/04/01 15:47:19 -- Author : <NAME> -- RDBMS Type : PostgreSQL -- Application : A5:SQL Mk-2 -- 作品分野マスタ drop table if exists prd_field_master cascade; create table prd_field_master ( product_filed_cd char(4) not null , product_filed_name varchar(20) not null , constraint prd_field_master_PKC primary key (product_filed_cd) ) ; -- ディーラー詳細 drop table if exists DEALER_DETAIL cascade; create table DEALER_DETAIL ( dealer_id int not null , product_name varchar(20) not null , product_filed_cd char(4) not null , price integer not null , constraint DEALER_DETAIL_PKC primary key (dealer_id,product_name) ) ; -- ディーラー drop table if exists DEALER cascade; create table DEALER ( dealer_id int not null , name varchar(20) not null , takuban char(6) not null , dealer_icon_cd varchar(10) not null , hp_link varchar(50) not null , tw_link varchar(50) not null , constraint DEALER_PKC primary key (dealer_id) ) ; alter table DEALER_DETAIL add constraint DEALER_DETAIL_FK1 foreign key (product_filed_cd) references prd_field_master(product_filed_cd); alter table DEALER_DETAIL add constraint DEALER_DETAIL_FK2 foreign key (dealer_id) references DEALER(dealer_id); comment on table prd_field_master is '作品分野マスタ'; comment on column prd_field_master.product_filed_cd is '作品分野コード'; comment on column prd_field_master.product_filed_name is '作品分野名'; comment on table DEALER_DETAIL is 'ディーラー詳細'; comment on column DEALER_DETAIL.dealer_id is 'ディーラーid'; comment on column DEALER_DETAIL.product_name is '商品名'; comment on column DEALER_DETAIL.product_filed_cd is '作品分野コード'; comment on column DEALER_DETAIL.price is '値段'; comment on table DEALER is 'ディーラー'; comment on column DEALER.dealer_id is 'ディーラーid'; comment on column DEALER.name is 'ディーラー名'; comment on column DEALER.takuban is '卓番号'; comment on column DEALER.dealer_icon_cd is 'ディーラーアイコンコード'; comment on column DEALER.hp_link is 'HPリンク'; comment on column DEALER.tw_link is 'TWリンク'; <file_sep>-- -- PostgreSQL database dump -- -- Dumped from database version 9.5.10 -- Dumped by pg_dump version 9.5.10 SET statement_timeout = 0; SET lock_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; SET row_security = off; SET search_path = public, pg_catalog; ALTER TABLE IF EXISTS ONLY public.dealer_detail DROP CONSTRAINT IF EXISTS dealer_detail_fk2; ALTER TABLE IF EXISTS ONLY public.dealer_detail DROP CONSTRAINT IF EXISTS dealer_detail_fk1; ALTER TABLE IF EXISTS ONLY public.usr_role DROP CONSTRAINT IF EXISTS usr_role_pkey; ALTER TABLE IF EXISTS ONLY public.usr DROP CONSTRAINT IF EXISTS usr_pkey; ALTER TABLE IF EXISTS ONLY public.prd_field_master DROP CONSTRAINT IF EXISTS prd_field_master_pkc; ALTER TABLE IF EXISTS ONLY public.dealer DROP CONSTRAINT IF EXISTS dealer_pkc; ALTER TABLE IF EXISTS ONLY public.dealer_detail DROP CONSTRAINT IF EXISTS dealer_detail_pkc; DROP TABLE IF EXISTS public.usr_role; DROP TABLE IF EXISTS public.usr; DROP TABLE IF EXISTS public.prd_field_master; DROP TABLE IF EXISTS public.dealer_detail; DROP TABLE IF EXISTS public.dealer; DROP SCHEMA IF EXISTS public; -- -- Name: public; Type: SCHEMA; Schema: -; Owner: postgres -- CREATE SCHEMA public; ALTER SCHEMA public OWNER TO postgres; -- -- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: postgres -- COMMENT ON SCHEMA public IS 'standard public schema'; SET search_path = public, pg_catalog; SET default_tablespace = ''; SET default_with_oids = false; -- -- Name: dealer; Type: TABLE; Schema: public; Owner: postgres -- CREATE TABLE dealer ( dealer_id integer NOT NULL, name character varying(20) NOT NULL, takuban character(6) NOT NULL, dealer_icon_cd character varying(10) NOT NULL, hp_link character varying(50) NOT NULL, tw_link character varying(50) NOT NULL ); ALTER TABLE dealer OWNER TO postgres; -- -- Name: TABLE dealer; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON TABLE dealer IS 'ディーラー'; -- -- Name: COLUMN dealer.dealer_id; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer.dealer_id IS 'ディーラーid'; -- -- Name: COLUMN dealer.name; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer.name IS 'ディーラー名'; -- -- Name: COLUMN dealer.takuban; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer.takuban IS '卓番号'; -- -- Name: COLUMN dealer.dealer_icon_cd; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer.dealer_icon_cd IS 'ディーラーアイコンコード'; -- -- Name: COLUMN dealer.hp_link; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer.hp_link IS 'HPリンク'; -- -- Name: COLUMN dealer.tw_link; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer.tw_link IS 'TWリンク'; -- -- Name: dealer_detail; Type: TABLE; Schema: public; Owner: postgres -- CREATE TABLE dealer_detail ( dealer_id integer NOT NULL, product_name character varying(20) NOT NULL, product_filed_cd character(4) NOT NULL, price integer NOT NULL ); ALTER TABLE dealer_detail OWNER TO postgres; -- -- Name: TABLE dealer_detail; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON TABLE dealer_detail IS 'ディーラー詳細'; -- -- Name: COLUMN dealer_detail.dealer_id; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer_detail.dealer_id IS 'ディーラーid'; -- -- Name: COLUMN dealer_detail.product_name; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer_detail.product_name IS '商品名'; -- -- Name: COLUMN dealer_detail.product_filed_cd; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer_detail.product_filed_cd IS '作品分野コード'; -- -- Name: COLUMN dealer_detail.price; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN dealer_detail.price IS '値段'; -- -- Name: prd_field_master; Type: TABLE; Schema: public; Owner: postgres -- CREATE TABLE prd_field_master ( product_filed_cd character(4) NOT NULL, product_filed_name character varying(20) NOT NULL ); ALTER TABLE prd_field_master OWNER TO postgres; -- -- Name: TABLE prd_field_master; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON TABLE prd_field_master IS '作品分野マスタ'; -- -- Name: COLUMN prd_field_master.product_filed_cd; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN prd_field_master.product_filed_cd IS '作品分野コード'; -- -- Name: COLUMN prd_field_master.product_filed_name; Type: COMMENT; Schema: public; Owner: postgres -- COMMENT ON COLUMN prd_field_master.product_filed_name IS '作品分野名'; -- -- Name: usr; Type: TABLE; Schema: public; Owner: postgres -- CREATE TABLE usr ( uid character(10) NOT NULL, passwd character(32), unam character varying(50) ); ALTER TABLE usr OWNER TO postgres; -- -- Name: usr_role; Type: TABLE; Schema: public; Owner: postgres -- CREATE TABLE usr_role ( uid character(10) NOT NULL, role character varying(30) NOT NULL ); ALTER TABLE usr_role OWNER TO postgres; -- -- Data for Name: dealer; Type: TABLE DATA; Schema: public; Owner: postgres -- COPY dealer (dealer_id, name, takuban, dealer_icon_cd, hp_link, tw_link) FROM stdin; 6 いぬやま 23458 456 http://yurucamp.jp/character/ https://twitter.com/ 10 いぬやま 234586 XXX http://yurucamp.jp/character/ https://twitter.com/ 8 いぬやま 123409 XXX http://yurucamp.jp/character/ https://twitter.com/ 7 雛鶴あい! 019233 XXX http://www.ryuoh-anime.com/ http://www.ryuoh-anime.com/ 1 かがみはら 012302 123 htttp://www.iwatakhr69.net.jp sample: 3 0000000003 000003 0000000003 0000000003 0000000003 4 0000000004 000004 0000000004 0000000004 0000000004 5 0000000005 000005 0000000005 0000000005 0000000005 11 XXX \. -- -- Data for Name: dealer_detail; Type: TABLE DATA; Schema: public; Owner: postgres -- COPY dealer_detail (dealer_id, product_name, product_filed_cd, price) FROM stdin; 1 みほりん 水着 0001 12000 1 ジャンヌオルタ 0002 8000 6 妙高 ドレス 0003 9000 6 かがみはらなでこ 胸像 0099 4000 \. -- -- Data for Name: prd_field_master; Type: TABLE DATA; Schema: public; Owner: postgres -- COPY prd_field_master (product_filed_cd, product_filed_name) FROM stdin; 0001 ガルパン 0002 FGO 0003 艦これ 0099 その他 \. -- -- Data for Name: usr; Type: TABLE DATA; Schema: public; Owner: postgres -- COPY usr (uid, passwd, unam) FROM stdin; hinatsuru <PASSWORD> 雛鶴あい iwatakhr <PASSWORD>cf99 いわた yashajin <PASSWORD> 夜叉神天衣 \. -- -- Data for Name: usr_role; Type: TABLE DATA; Schema: public; Owner: postgres -- COPY usr_role (uid, role) FROM stdin; iwatakhr admin-gui iwatakhr manager-gui hinatsuru manager-gui \. -- -- Name: dealer_detail_pkc; Type: CONSTRAINT; Schema: public; Owner: postgres -- ALTER TABLE ONLY dealer_detail ADD CONSTRAINT dealer_detail_pkc PRIMARY KEY (dealer_id, product_name); -- -- Name: dealer_pkc; Type: CONSTRAINT; Schema: public; Owner: postgres -- ALTER TABLE ONLY dealer ADD CONSTRAINT dealer_pkc PRIMARY KEY (dealer_id); -- -- Name: prd_field_master_pkc; Type: CONSTRAINT; Schema: public; Owner: postgres -- ALTER TABLE ONLY prd_field_master ADD CONSTRAINT prd_field_master_pkc PRIMARY KEY (product_filed_cd); -- -- Name: usr_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres -- ALTER TABLE ONLY usr ADD CONSTRAINT usr_pkey PRIMARY KEY (uid); -- -- Name: usr_role_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres -- ALTER TABLE ONLY usr_role ADD CONSTRAINT usr_role_pkey PRIMARY KEY (uid, role); -- -- Name: dealer_detail_fk1; Type: FK CONSTRAINT; Schema: public; Owner: postgres -- ALTER TABLE ONLY dealer_detail ADD CONSTRAINT dealer_detail_fk1 FOREIGN KEY (product_filed_cd) REFERENCES prd_field_master(product_filed_cd); -- -- Name: dealer_detail_fk2; Type: FK CONSTRAINT; Schema: public; Owner: postgres -- ALTER TABLE ONLY dealer_detail ADD CONSTRAINT dealer_detail_fk2 FOREIGN KEY (dealer_id) REFERENCES dealer(dealer_id); -- -- Name: public; Type: ACL; Schema: -; Owner: postgres -- REVOKE ALL ON SCHEMA public FROM PUBLIC; REVOKE ALL ON SCHEMA public FROM postgres; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO PUBLIC; -- -- PostgreSQL database dump complete --
3c0a610bf826c8231380bb307d82d6dde5e524ab
[ "SQL" ]
4
SQL
gitRock2016/WFS_Design
18d467fa5abd691fbb399900a464daa7b4358bf4
45a9974b3dd9b5fecd465d46b9198a85a9cbc076
refs/heads/master
<file_sep>package com.mathieuclement.swiss.autoindex.android.app.util; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.lib.autoindex.plate.PlateType; import com.mathieuclement.lib.autoindex.provider.common.AutoIndexProvider; import com.mathieuclement.lib.autoindex.provider.exception.PlateOwnerHiddenException; import com.mathieuclement.lib.autoindex.provider.exception.PlateOwnerNotFoundException; import com.mathieuclement.lib.autoindex.provider.exception.ProviderException; import com.mathieuclement.lib.autoindex.provider.exception.UnsupportedPlateException; /** * @author <NAME> * @since 22.09.2013 */ public class AutoIndexProviderAdapter implements AutoIndexProvider { @Override public PlateOwner getPlateOwner(Plate plate, int requestId) throws ProviderException, PlateOwnerNotFoundException, PlateOwnerHiddenException, UnsupportedPlateException { return null; } @Override public boolean isPlateTypeSupported(PlateType plateType) { return false; } @Override public void cancel(int requestId) { } @Override public boolean isCancelled(int requestId) { return false; } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.fragments.sms_provider; import android.app.Fragment; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.mathieuclement.swiss.autoindex.android.app.R; /** * @author <NAME> * @since 15.09.2013 */ public class RequestIsManualFragment extends Fragment { private String cantonAbbr; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.manual_request, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); readExtras(savedInstanceState); if ("bs".equals(cantonAbbr)) checkAndSet(R.string.complicated_bs_text, R.string.complicated_bs_url, R.string.complicated_bs_email, R.string.complicated_bs_phone); else if ("ge".equals(cantonAbbr)) checkAndSet(R.string.complicated_ge_text, R.string.complicated_ge_url, R.string.complicated_ge_email, R.string.complicated_ge_phone); else if ("ne".equals(cantonAbbr)) checkAndSet(R.string.complicated_ne_text, R.string.complicated_ne_url, R.string.complicated_ne_email, R.string.complicated_ne_phone); else if ("nw".equals(cantonAbbr)) checkAndSet(R.string.complicated_nw_text, R.string.complicated_nw_url, R.string.complicated_nw_email, R.string.complicated_nw_phone); else if ("ow".equals(cantonAbbr)) checkAndSet(R.string.complicated_ow_text, R.string.complicated_ow_url, R.string.complicated_ow_email, R.string.complicated_ow_phone); else if ("sz".equals(cantonAbbr)) checkAndSet(R.string.complicated_sz_text, R.string.complicated_sz_url, R.string.complicated_sz_email, R.string.complicated_sz_phone); else if ("nw".equals(cantonAbbr)) checkAndSet(R.string.complicated_nw_text, R.string.complicated_nw_url, R.string.complicated_nw_email, R.string.complicated_nw_phone); else if ("ur".equals(cantonAbbr)) checkAndSet(R.string.complicated_ur_text, R.string.complicated_ur_url, R.string.complicated_ur_email, R.string.complicated_ur_phone); else if ("ju".equals(cantonAbbr)) checkAndSet(R.string.complicated_ju_text, R.string.complicated_ju_url, R.string.complicated_ju_email, R.string.complicated_ju_phone); else if ("vd".equals(cantonAbbr)) checkAndSet(R.string.complicated_vd_text, R.string.complicated_vd_url, R.string.complicated_vd_email, R.string.complicated_vd_phone); else if ("ti".equals(cantonAbbr)) checkAndSet(R.string.complicated_ti_text, R.string.complicated_ti_url, R.string.complicated_ti_email, R.string.complicated_ti_phone); else throw new RuntimeException("There are no texts for " + cantonAbbr + "."); } private void checkAndSet(int textId, int urlId, int emailId, int phoneId) { final String text = getResources().getText(textId, "").toString(); final String url = getResources().getText(urlId, "").toString(); final String email = getResources().getText(emailId, "").toString(); final String phone = getResources().getText(phoneId, "").toString(); if (!"".equals(text)) { TextView view = (TextView) getView().findViewById(R.id.manual_request_textview); view.setText(text); view.setVisibility(View.VISIBLE); } if (!"".equals(url)) { TextView view = (TextView) getView().findViewById(R.id.manual_request_url); view.setText(url); view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); } }); } if (!"".equals(email)) { TextView view = (TextView) getView().findViewById(R.id.manual_request_email); view.setText(email); view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType("plain/text"); String recipient = email; String subject = "Abfrage / Demande"; String message = null; emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{recipient}); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message); startActivity(Intent.createChooser(emailIntent, "E-Mail...")); } catch (ActivityNotFoundException e) { // cannot send email for some reason } } }); } if (!"".equals(phone)) { TextView view = (TextView) getView().findViewById(R.id.manual_request_phone); view.setText(phone); view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String uri = "tel:" + phone.trim().replace("(0)", ""); Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(uri)); startActivity(intent); } }); } } private void readExtras(Bundle savedInstanceState) { if (savedInstanceState != null) { cantonAbbr = savedInstanceState.getString("canton").toLowerCase(); } else if (getArguments() != null) { cantonAbbr = getArguments().getString("canton").toLowerCase(); } else { throw new Error("Null extras!"); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("canton", cantonAbbr); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.persistence.droid.contact; import android.database.sqlite.SQLiteDatabase; import org.droidpersistence.dao.DroidDao; import org.droidpersistence.dao.TableDefinition; public class ContactRecordDao extends DroidDao<ContactRecord, Long> { public ContactRecordDao(TableDefinition<ContactRecord> contactRecordTableDefinition, SQLiteDatabase database) { super(ContactRecord.class, contactRecordTableDefinition, database); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.fragments.search; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.AutoCompleteTextView; /** * @author <NAME> * @since 20.06.2013 */ public class PlateAutoCompleteTextView extends AutoCompleteTextView { private Context context; public PlateAutoCompleteTextView(Context context) { super(context); this.context = context; } public PlateAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); } public PlateAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean enoughToFilter() { return true; } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); } @Override protected CharSequence convertSelectionToString(Object selectedItem) { // Avoid copying the string value of the "More..." list item // into the edit text. if (selectedItem == PlateSearchAdapter.MORE_RECENT_SEARCHES_PLATE) return ""; else return super.convertSelectionToString(selectedItem); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.network; import android.app.Activity; import android.util.Log; import android.widget.Toast; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.provider.common.captcha.event.AsyncAutoIndexProvider; import com.mathieuclement.swiss.autoindex.android.app.R; import org.apache.http.impl.client.DefaultHttpClient; class PlateOwnerRequestRunnable implements Runnable { private Activity activity; private AsyncAutoIndexProvider provider; private Plate plate; PlateOwnerRequestRunnable(Activity activity, AsyncAutoIndexProvider provider, Plate plate) { this.activity = activity; this.provider = provider; this.plate = plate; } @Override public void run() { try { this.provider.requestPlateOwner(plate, new DefaultHttpClient()); } catch (final Exception e) { activity.runOnUiThread(new Runnable() { @Override public void run() { Log.e(getClass().getSimpleName(), "Exception on plate request: " + plate, e); Toast.makeText(activity.getApplicationContext(), R.string.request_error_try_again, Toast.LENGTH_SHORT).show(); } }); } } } <file_sep>- Update all bookmarks - Add note along bookmark (Marque, date d'observation, lieu d'observation, etc.)<file_sep>package com.mathieuclement.swiss.autoindex.android.app.fragments; import android.app.ProgressDialog; import android.content.*; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.RemoteException; import android.provider.ContactsContract; import android.support.annotation.Nullable; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.bugsense.trace.BugSenseHandler; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.mathieuclement.lib.autoindex.canton.Canton; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.lib.autoindex.plate.PlateType; import com.mathieuclement.lib.autoindex.provider.common.captcha.event.AsyncAutoIndexProvider; import com.mathieuclement.swiss.autoindex.android.app.R; import com.mathieuclement.swiss.autoindex.android.app.fragments.search.SearchFragment; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.DataManager; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.bookmarks.BookmarkRecord; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.plate_records.PlateRecord; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; public class ShowPlateOwnerFragment extends android.app.Fragment { public static final String PLATE_CANTON_ABBR_KEY = "plate-canton-abbr"; public static final String PLATE_TYPE_KEY = "plate-type"; public static final String PLATE_NUMBER_KEY = "plate-number"; public static final String PLATE_OWNER_NAME_KEY = "plate-owner-name"; public static final String PLATE_OWNER_ADDRESS_KEY = "plate-owner-address"; public static final String PLATE_OWNER_ADDRESS_COMPLEMENT_KEY = "plate-owner-address-complement"; public static final String PLATE_OWNER_ZIP_KEY = "plate-owner-zip"; public static final String PLATE_OWNER_TOWN_KEY = "plate-owner-town"; public static final String PLATE_RECORD_ID_KEY = "plate-record-id"; public static final String DEFAULT_CONTACT_COUNTRY = "Switzerland"; private PlateOwner plateOwner; private Plate plate; private long plateRecordId = 0L; private View.OnClickListener bookmarkButtonOnClickListener; private View.OnClickListener removeBookmarkButtonOnClickListener; private DataManager dataManager; private Button bookmarkButton; private PlateRecord searchedPlateRecord; private String contactLookupKey; private String remarks = ""; private Button contactButton; private boolean remarksChanged = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.plate_owner_fragment, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { // No title bar in landscape mode /*if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { getWindow().requestFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); }*/ readExtras(savedInstanceState); /** * Plate */ TextView plateView = (TextView) view.findViewById(R.id.plate_owner_plate_textView); plateView.setText(niceFormatPlate(plate)); // Change colours to match plate types // See ASA website LinearLayout plateLayout = (LinearLayout) view.findViewById(R.id.plate_owner_plate_linear_layout); plateLayout.setBackgroundColor(makePlateBackgroundColor(plate.getType())); /** * Canton flag */ ImageView cantonFlagImgView = (ImageView) view.findViewById(R.id.plate_owner_canton_flag_imageview); cantonFlagImgView.setImageResource(SearchFragment.flagsMapping.get( plate.getCanton().getAbbreviation().toLowerCase())); /** * Owner */ TextView ownerTextView = (TextView) view.findViewById(R.id.plate_owner_textview); ownerTextView.setText(niceFormatOwner(plateOwner)); /** * Remarks EditText */ final EditText remarksEditText = (EditText) view.findViewById(R.id.plate_owner_remarks_edittext); if (plateRecordId != 0L) { // If contact added or bookmarked // there will be an ID // because there is an entry in plate records // for it remarksEditText.setVisibility(View.VISIBLE); // Invisible by default dataManager = new DataManager(getActivity()); try { remarks = findRemarksInDatabase(plate); } finally { dataManager.closeDb(); } if (remarks != null) { remarksEditText.setText(remarks); } } remarksEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { remarksChanged = true; } }); /** * Bookmark button */ bookmarkButton = (Button) view.findViewById(R.id.plate_owner_bookmark_button); bookmarkButtonOnClickListener = new View.OnClickListener() { @Override public void onClick(View view) { dataManager = new DataManager(getActivity()); try { plateRecordId = dataManager.addBookmark(plate, plateOwner); } catch (Exception e) { BugSenseHandler.sendException(e); e.printStackTrace(); Toast.makeText(getActivity(), "Error. Try again.", Toast.LENGTH_SHORT).show(); } dataManager.closeDb(); bookmarkButton.setText(R.string.plate_owner_remove_bookmark); bookmarkButton.setOnClickListener(removeBookmarkButtonOnClickListener); remarksEditText.setVisibility(View.VISIBLE); } }; removeBookmarkButtonOnClickListener = new View.OnClickListener() { @Override public void onClick(View view) { // Save previous content of remarks String editTextContent = remarksEditText.getText().toString(); if (remarksEditText.getText() != null) { remarks = editTextContent; // Store old remarks in case the user clicked "Remove bookmark" by mistake. } dataManager = new DataManager(getActivity()); try { dataManager.removeBookmark(plateRecordId != 0L ? plateRecordId : searchedPlateRecord.getId()); } finally { dataManager.closeDb(); } bookmarkButton.setText(R.string.plate_owner_bookmark); bookmarkButton.setOnClickListener(bookmarkButtonOnClickListener); remarksEditText.setVisibility(View.INVISIBLE); } }; /** * Remove / Add as contact button */ contactButton = (Button) view.findViewById(R.id.plate_owner_save_as_contact_button); if (plateRecordId != 0L) { // If contact added or bookmarked // there will be an ID // because there is an entry in plate records // for it dataManager = new DataManager(getActivity()); try { contactLookupKey = findContactLookupKeyInDatabase(plate); } finally { dataManager.closeDb(); } if (contactLookupKey != null) { contactButton.setText(R.string.plate_owner_remove_contact); } } contactButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { if (contactLookupKey != null) { // remove try { dataManager = new DataManager(getActivity()); try { removeContact(contactLookupKey); } finally { dataManager.closeDb(); } // Now the button will add the contact instead contactLookupKey = null; ((Button) view).setText(R.string.plate_owner_save_as_contact); } catch (IllegalStateException ise) { Log.e(((Object) getActivity()).getClass().getName(), ise.getMessage(), ise); Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show(); BugSenseHandler.sendException(ise); } } else { // add view.setEnabled(false); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { insertContact(plateOwner); contactLookupKey = findContactLookupKeyInContacts(getActivity(), plateOwner); dataManager = new DataManager(getActivity()); try { insertContactInDatabase(plate, plateOwner, contactLookupKey); } finally { dataManager.closeDb(); } } catch (RemoteException e) { Log.e(getClass().getSimpleName(), "Could not save plate owner as contact: " + plateOwner, e); Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show(); BugSenseHandler.sendException(e); } catch (OperationApplicationException e) { Log.e(getClass().getSimpleName(), "Could not save plate owner as contact: " + plateOwner, e); Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show(); BugSenseHandler.sendException(e); } catch (Exception e) { Log.e(getClass().getSimpleName(), "Could not save plate owner as contact in DB : " + plateOwner, e); Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show(); BugSenseHandler.sendException(e); } // end try-catch return null; } // end doInBackground() @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); // Now the button will remove contact instead ((Button) view).setText(R.string.plate_owner_remove_contact); view.setEnabled(true); } // end onPostExecute() }.execute(); } // end if } // new Listener }); // add Listener /** * Lookup in Phone directory button */ Button phoneDirButton = (Button) view.findViewById(R.id.plate_owner_lookup_in_phone_directory_button); // Open local.ch application to look for a phone number for instance phoneDirButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String localChAppPackage = "ch.local.android"; /* Check local.ch application is installed, then launch it and look for the name and address Otherwise open the application page on Google Play Store. */ try { // The next line serves as a "if ( local.ch application is installed )" getActivity().getPackageManager().getApplicationInfo(localChAppPackage, 0); // then ... String url = makeLocalChIntentUrl(plateOwner.getName(), plateOwner.getAddress(), plateOwner.getZip(), plateOwner.getTown()); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } catch (Exception e) { // PackageManager.NameNotFoundException + ActivityNotFoundException // Application Local.ch is not installed e.printStackTrace(); // Open Google Play Store Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("market://details?id=" + localChAppPackage)); try { startActivity(intent); } catch (ActivityNotFoundException anfe) { // getActivity() is not supposed to happen if the application was acquired legally on Google Play, but we never know... // Also getActivity() exception will be thrown when running the application in the emulator, Toast.makeText(getActivity(), "Cannot find Google Play Store application on getActivity() device.", Toast.LENGTH_LONG).show(); } } } }); /** * See on map button */ final Button mapButton = (Button) view.findViewById(R.id.plate_owner_see_on_map_button); // Copying to final variable to use it in anonymous class mapButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { new AsyncTask<Void, Throwable, Void>() { @Override protected Void doInBackground(Void... voids) { try { String mapUri = makeGeoUrlString(); if (mapUri != null) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mapUri)); startActivity(intent); } } catch (IOException ioe) { Log.e(ShowPlateOwnerFragment.class.getSimpleName(), ioe.getMessage(), ioe); publishProgress(ioe); } catch (URISyntaxException e) { Log.e(ShowPlateOwnerFragment.class.getSimpleName(), e.getMessage(), e); publishProgress(e); } return null; } @Override protected void onProgressUpdate(Throwable... values) { Toast.makeText(getActivity(), "Error geocoding address: " + values[0].getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } ProgressDialog progressDialog; @Override protected void onPreExecute() { mapButton.setEnabled(false); progressDialog = new ProgressDialog(getActivity()); progressDialog.setIndeterminate(true); progressDialog.show(); } @Override protected void onPostExecute(Void aVoid) { progressDialog.dismiss(); mapButton.setEnabled(true); } }.execute(); } }); /** * Share button */ Button shareButton = (Button) view.findViewById(R.id.plate_owner_share_button); shareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // http://mobile.tutsplus.com/tutorials/android/android-sdk-implement-a-share-intent/ // Create a sharing intent Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("text/plain"); // Define subject and body // Text shared: FR 12345 | Université de Fribourg, Bvd de Pérolles 90, 1700 Fribourg String shareBody = plate.getCanton().getAbbreviation() + " " + plate.getNumber() + " | " + plateOwner.getName() + ", " + makeAddress(); sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody); String shareSubject = plate.toString(); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject); // Show chooser startActivity(Intent.createChooser(sharingIntent, getString(R.string.plate_owner_share))); } }); } private void insertContactInDatabase(Plate plate, PlateOwner plateOwner, String contactLookupKey) throws Exception { dataManager.addContact(plate, plateOwner, contactLookupKey); } // Remove contact private void removeContact(String lookupKey) { ContentResolver cr = getActivity().getContentResolver(); int rowsDeleted = cr.delete( Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey), null, null); // if (rowsDeleted != 1) { // // It means there is no contact with getActivity() lookup key anymore. // throw new IllegalStateException(Integer.toString(rowsDeleted) + " row(s) have been deleted, expected 1."); // } dataManager.removeContact(plate); } private String findContactLookupKeyInDatabase(Plate plate) { try { return dataManager.getContactLookupKey(plate); } catch (NullPointerException npe) { return null; } } private String findRemarksInDatabase(Plate plate) { try { return dataManager.getRemarks(plate); } catch (NullPointerException npe) { return null; } } // Returns the id of the contact with the exact same info as the one getActivity() app created. // Returns null if not found private static String findContactLookupKeyInContacts(Context context, PlateOwner plateOwner) { // String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); String returnValue = null; // Query using Display name Cursor detailsCur = context.getContentResolver().query( ContactsContract.Data.CONTENT_URI, new String[]{ ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.StructuredPostal.STREET, ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, ContactsContract.CommonDataKinds.StructuredPostal.CITY, ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY } , null, null, null); if (detailsCur.getCount() > 0) { detailsCur.moveToFirst(); do { String lookupKey = detailsCur.getString(detailsCur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); String country = detailsCur.getString(detailsCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY)); // Most contacts will fail the Country test, which speeds up things. if (DEFAULT_CONTACT_COUNTRY.equals(country)) { String name = detailsCur.getString(detailsCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); String address = detailsCur.getString(detailsCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.STREET)); int zip = detailsCur.getInt(detailsCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)); String city = detailsCur.getString(detailsCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.CITY)); if (plateOwner.getName().equals(name) && plateOwner.getAddress().equals(address) && plateOwner.getZip() == zip && plateOwner.getTown().equals(city)) { detailsCur.close(); returnValue = lookupKey; return lookupKey; } } } while (detailsCur.moveToNext()); } detailsCur.close(); return returnValue; } private String niceFormatOwner(PlateOwner plateOwner) { String newLine = "\r\n"; String plateOwnerText = plateOwner.getName() + newLine + plateOwner.getAddress() + newLine; if (plateOwner.getAddressComplement() != null && !"".equals(plateOwner.getAddressComplement())) { plateOwnerText += plateOwner.getAddressComplement() + newLine; } plateOwnerText += plateOwner.getZip() + " " + plateOwner.getTown(); return plateOwnerText; } private CharSequence niceFormatPlate(Plate plate) { StringBuilder plateTextBuilder = new StringBuilder(); // \u00B7 is U+00B7 unicode for middle point. plateTextBuilder.append(plate.getCanton().getAbbreviation()).append(" \u00B7 ") .append(Plate.formatNumber((plate.getNumber()))); if (PlateType.AUTOMOBILE_REPAIR_SHOP.equals(plate.getType()) || PlateType.MOTORCYCLE_REPAIR_SHOP.equals(plate.getType())) { // append U for repair shops plates plateTextBuilder.append(" \u00B7 U"); } else if (PlateType.AUTOMOBILE_TEMPORARY.equals(plate.getType()) || PlateType.MOTORCYCLE_TEMPORARY.equals(plate.getType())) { // Append unfilled rectangle to temporary plates plateTextBuilder.append(" \u25AF"); } return plateTextBuilder.toString(); } private void insertContact(PlateOwner plateOwner) throws RemoteException, OperationApplicationException { ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); int rawContactInsertIndex = 0; operations.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build()); operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, plateOwner.getName()).build()); operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, plateOwner.getAddress()) .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, plateOwner.getZip()) .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, plateOwner.getTown()) .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, DEFAULT_CONTACT_COUNTRY).build() ); getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations); } /* private static String urlEncode(String decodedURL) { try { return URLEncoder.encode(decodedURL, "UTF-8").toString(); } catch (UnsupportedEncodingException e) { BugSenseHandler.sendException(e); throw new RuntimeException(e); } } */ private static String makeLocalChIntentUrl(String name, String street, int zip, String town) { StringBuilder sb = new StringBuilder(300); sb.append("localch://tel/search?what=") .append(name) .append("&where=") .append(street) .append(", ") .append(town); return sb.toString(); } private int makePlateBackgroundColor(PlateType type) { String colorStr; if (PlateType.AGRICULTURAL.equals(type)) { colorStr = "#49ddb1"; } else if (PlateType.INDUSTRIAL.equals(type)) { colorStr = "#6e91bf"; } else if (PlateType.AUTOMOBILE_BROWN.equals(type)) { colorStr = "#c28e5c"; } else if (PlateType.MOTORCYCLE_YELLOW.equals(type)) { colorStr = "#e6b348"; } else if (PlateType.MOTORCYCLE_BROWN.equals(type)) { colorStr = "#c28e5c"; } else { //colorStr = "#eaedea"; // blanc cassé - gris clair colorStr = "#ffffff"; } return Color.parseColor(colorStr); } private String makeGeoUrlString() throws IOException, URISyntaxException { String addressStr = plateOwner.getAddress() + ", " + plateOwner.getZip() + " " + plateOwner.getTown() + ", Switzerland"; // We don't put the "Complément d'adresse" as it is often found to be a postal box (case postale) String encodedAddressStr = URLEncoder.encode(addressStr, "utf-8"); String jsonStr = IOUtils.toString(new URI("https://maps.googleapis.com/maps/api/geocode/json?address=" + encodedAddressStr)); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(jsonStr); JsonNode geometryNode = node.findValue("geometry"); if (geometryNode == null) return null; JsonNode locationNode = geometryNode.get("location"); double latitude = locationNode.get("lat").asDouble(); double longitude = locationNode.get("lng").asDouble(); return "geo:" + latitude + "," + longitude + "?q=" + encodedAddressStr; } /** * Concatenate the currently displayed plate owner's address, zip code and town. * * @return the currently displayed plate owner's address, zip code and town. */ private String makeAddress() { if (plateOwner.getAddressComplement() != null && !"".equals(plateOwner.getAddressComplement())) { return plateOwner.getAddress() + ", " + plateOwner.getAddressComplement() + ", " + plateOwner.getZip() + " " + plateOwner.getTown(); } else { return plateOwner.getAddress() + ", " + plateOwner.getZip() + " " + plateOwner.getTown(); } } @Override public void onStart() { super.onStart(); dataManager = new DataManager(getActivity()); try { if (!dataRead) { Log.e(getActivity().getClass().getName(), "CONCEPTION ERROR: No data read! Go back to SearchActivity."); } // Bookmark button behaves differently and has a different text if plate is already bookmarked or not. searchedPlateRecord = dataManager.getPlateRecordByPlate(plate); if (searchedPlateRecord == null) { bookmarkButton.setOnClickListener(bookmarkButtonOnClickListener); } else { bookmarkButton.setText(R.string.plate_owner_remove_bookmark); bookmarkButton.setOnClickListener(removeBookmarkButtonOnClickListener); } } finally { dataManager.closeDb(); } } @Override public void onStop() { super.onStop(); try { EditText remarksEditText = (EditText) getActivity().findViewById(R.id.plate_owner_remarks_edittext); if (remarksEditText.getVisibility() == View.VISIBLE) { // if bookmarked String editTextContent = remarksEditText.getText().toString(); if (remarksEditText.getText() != null && remarksChanged) { dataManager = new DataManager(getActivity()); BookmarkRecord bookmarkRecord = dataManager.getBookmarkRecordDao().get(plateRecordId); if (bookmarkRecord != null) { bookmarkRecord.setRemarks(editTextContent); try { dataManager.getBookmarkRecordDao().update(bookmarkRecord, plateRecordId); if (!"".equals(editTextContent)) { Toast.makeText(getActivity(), R.string.plate_owner_remarks_saved_toast, Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); BugSenseHandler.sendException(e); } } } } } finally { dataManager.closeDb(); } } // data was read from extras passed to the bundle that launched the activity. See readExtras(Bundle). private boolean dataRead = false; /** * Set attributes of getActivity() class (related to plate owner, plate record and so on) by reading the bundle passed to the intent. * * @param savedInstanceState Bundle passed to the intent */ private void readExtras(Bundle savedInstanceState) { String cantonAbbr = ""; String plateTypeStr = ""; int plateNumber = -1; String plateOwnerName = ""; String plateOwnerAddress = ""; String plateOwnerAddressComplement = null; int plateOwnerZip = -1; String plateOwnerTown = ""; Bundle extras; if (savedInstanceState == null) { extras = getActivity().getIntent().getExtras(); if (extras != null && extras.getInt(PLATE_NUMBER_KEY) != 0) { cantonAbbr = extras.getString(PLATE_CANTON_ABBR_KEY); plateTypeStr = extras.getString(PLATE_TYPE_KEY); plateNumber = extras.getInt(PLATE_NUMBER_KEY); plateOwnerName = extras.getString(PLATE_OWNER_NAME_KEY); plateOwnerAddress = extras.getString(PLATE_OWNER_ADDRESS_KEY); plateOwnerAddressComplement = extras.getString(PLATE_OWNER_ADDRESS_COMPLEMENT_KEY); plateOwnerZip = extras.getInt(PLATE_OWNER_ZIP_KEY); plateOwnerTown = extras.getString(PLATE_OWNER_TOWN_KEY); plateRecordId = extras.getLong(PLATE_RECORD_ID_KEY); } else { if (getArguments() == null) { throw new Error("Null extras!"); } else { cantonAbbr = getArguments().getString(PLATE_CANTON_ABBR_KEY); plateTypeStr = getArguments().getString(PLATE_TYPE_KEY); plateNumber = getArguments().getInt(PLATE_NUMBER_KEY); plateOwnerName = getArguments().getString(PLATE_OWNER_NAME_KEY); plateOwnerAddress = getArguments().getString(PLATE_OWNER_ADDRESS_KEY); plateOwnerAddressComplement = getArguments().getString(PLATE_OWNER_ADDRESS_COMPLEMENT_KEY); plateOwnerZip = getArguments().getInt(PLATE_OWNER_ZIP_KEY); plateOwnerTown = getArguments().getString(PLATE_OWNER_TOWN_KEY); plateRecordId = getArguments().getLong(PLATE_RECORD_ID_KEY); } } } else { cantonAbbr = savedInstanceState.getString(PLATE_CANTON_ABBR_KEY); plateTypeStr = savedInstanceState.getString(PLATE_TYPE_KEY); plateNumber = savedInstanceState.getInt(PLATE_NUMBER_KEY); plateOwnerName = savedInstanceState.getString(PLATE_OWNER_NAME_KEY); plateOwnerAddress = savedInstanceState.getString(PLATE_OWNER_ADDRESS_KEY); plateOwnerAddressComplement = savedInstanceState.getString(PLATE_OWNER_ADDRESS_COMPLEMENT_KEY); plateOwnerZip = savedInstanceState.getInt(PLATE_OWNER_ZIP_KEY); plateOwnerTown = savedInstanceState.getString(PLATE_OWNER_TOWN_KEY); plateRecordId = savedInstanceState.getLong(PLATE_RECORD_ID_KEY); } if (cantonAbbr != null && !"".equals(cantonAbbr)) { dataRead = true; } plate = new Plate(plateNumber, new PlateType(plateTypeStr), new Canton(cantonAbbr, false, (AsyncAutoIndexProvider) null)); plateOwner = new PlateOwner(plateOwnerName, plateOwnerAddress, plateOwnerAddressComplement, plateOwnerZip, plateOwnerTown); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(PLATE_CANTON_ABBR_KEY, plate.getCanton().getAbbreviation()); outState.putString(PLATE_TYPE_KEY, plate.getType().getName()); outState.putInt(PLATE_NUMBER_KEY, plate.getNumber()); outState.putString(PLATE_OWNER_NAME_KEY, plateOwner.getName()); outState.putString(PLATE_OWNER_ADDRESS_KEY, plateOwner.getAddress()); outState.putString(PLATE_OWNER_ADDRESS_COMPLEMENT_KEY, plateOwner.getAddressComplement()); outState.putInt(PLATE_OWNER_ZIP_KEY, plateOwner.getZip()); outState.putString(PLATE_OWNER_TOWN_KEY, plateOwner.getTown()); outState.putLong(PLATE_RECORD_ID_KEY, plateRecordId); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.util; import android.content.Context; import com.mathieuclement.swiss.autoindex.android.app.R; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; public class LocationUtils { /** * Returns the canton abbreviation in uppercase. * * @param context Context * @param zip Postal code * @return the canton abbreviation in uppercase, or null if not found. * @throws IOException if file could not be opened or close, or other I/O errors. */ public static String zipToCantonAbbr(Context context, int zip) throws IOException { String cantonAbbr = null; if (zip < 1000 || zip > 9999) return null; // Read from file. // The file is PLZ Light from Swiss Post MAT[CH] // Generate file: // awk -F\\t '{print $3 "," $7}' plz_l_20140120.txt | sort -u -n | gzip > zip // Read file: // gunzip -c zip String zipStr = Integer.toString(zip); char char0 = zipStr.charAt(0); char char1 = zipStr.charAt(1); char char2 = zipStr.charAt(2); char char3 = zipStr.charAt(3); // TODO Binary search with RandomAccessFile InputStream inputStream = context.getResources().openRawResource(R.raw.zip); GZIPInputStream gis = new GZIPInputStream(inputStream); byte[] buf = new byte[8]; // 8 chars per line including \n while (gis.read(buf, 0, 4) != -1) { if (buf[0] < char0) { gis.skip(7); } else if (buf[1] != char1) { gis.skip(6); } else if (buf[2] != char2) { gis.skip(5); } else if (buf[3] != char3) { gis.skip(5); } else { // Found it // skip comma gis.skip(1); // next two chars is the canton abbreviation in uppercase gis.read(buf, 0, 2); cantonAbbr = new String(buf, 0, 2); break; } } gis.close(); return cantonAbbr; } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.persistence.droid.plate_records; import com.mathieuclement.lib.autoindex.canton.Canton; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.lib.autoindex.plate.PlateType; import com.mathieuclement.swiss.autoindex.android.app.util.AutoIndexProviderAdapter; import org.droidpersistence.annotation.Column; import org.droidpersistence.annotation.PrimaryKey; import org.droidpersistence.annotation.Table; @SuppressWarnings("ALL") @Table(name = "PLATERECORDS") public class PlateRecord { @PrimaryKey(autoIncrement = true) @Column(name = "ID") private long id; @Column(name = "CANTON") private String canton = ""; @Column(name = "NUMBER") private int number; @Column(name = "TYPE") private String type = ""; @Column(name = "NAME") private String name = ""; @Column(name = "ADDRESS") private String address = ""; @Column(name = "ADDRESSCOMPLEMENT") private String addressComplement = ""; @Column(name = "ZIP") private int zip; @Column(name = "TOWN") private String town = ""; public PlateRecord(Plate plate, PlateOwner plateOwner) { this.canton = plate.getCanton().getAbbreviation(); this.number = plate.getNumber(); this.type = plate.getType().getName(); this.name = plateOwner.getName(); this.address = plateOwner.getAddress(); this.addressComplement = plateOwner.getAddressComplement(); this.zip = plateOwner.getZip(); this.town = plateOwner.getTown(); } public Plate toPlate() { return new Plate(number, new PlateType(type), new Canton(canton, false, new AutoIndexProviderAdapter())); } public PlateOwner toPlateOwner() { return new PlateOwner(name, address, addressComplement, zip, town); } public PlateRecord() { } public boolean autoIncrement() { return true; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getCanton() { return canton == null ? "" : canton; } public void setCanton(String canton) { this.canton = canton; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getType() { return type == null ? "" : type; } public void setType(String type) { this.type = type; } public String getName() { return name == null ? "" : name; } public void setName(String name) { this.name = name; } public String getAddress() { return address == null ? "" : address; } public void setAddress(String address) { this.address = address; } public String getAddressComplement() { return addressComplement == null ? "" : addressComplement; } public void setAddressComplement(String addressComplement) { this.addressComplement = addressComplement; } public int getZip() { return zip; } public void setZip(int zip) { this.zip = zip; } public String getTown() { return town == null ? "" : town; } public void setTown(String town) { this.town = town; } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.activity; import android.test.ActivityInstrumentationTestCase2; import com.jayway.android.robotium.solo.Solo; import com.mathieuclement.swiss.autoindex.android.app.fragments.search.LastSearchesProvider; import junit.framework.Assert; public class SearchTest extends ActivityInstrumentationTestCase2<WelcomeListActivity> { private final String SEARCH_TEXT = "Search"; private final String ADD_BOOKMARK_TEXT = "Bookmark"; private final String REMOVE_BOOKMARK_TEXT = "Remove bookmark"; private Solo solo; public SearchTest() { super(WelcomeListActivity.class); } public void setUp() throws Exception { solo = new Solo(getInstrumentation(), getActivity()); LastSearchesProvider.getInstance().clear(); } public void testFribourgSearchAndBookmarks() throws Exception { // Start search activity solo.clickOnText(SEARCH_TEXT); // Set search to 300 310 solo.enterText(0, "300310"); // Assume AG was selected //solo.pressSpinnerItem(0, +5); // Select "FR" solo.clickOnButton(1); Assert.assertTrue(solo.waitForActivity("ShowPlateOwnerActivity", 20000)); // 20 seconds timeout String expectedPlateText = "FR · 300 310"; Assert.assertEquals("Plate canton and number found", expectedPlateText, solo.getText(1).getText()); String expectedTpfText = "Transports Publics Fribourgeois\r\nRue Louis-d'Affry 2\r\nCase postale 1536\r\n1700 Fribourg"; Assert.assertEquals("Owner found", expectedTpfText, solo.getText(2).getText().toString()); // Test favourite button has the text as if the plate is not a favourite String addToFavoritesText = ADD_BOOKMARK_TEXT; Assert.assertEquals(addToFavoritesText, solo.getButton(1).getText().toString()); // Add to favourites solo.clickOnText(addToFavoritesText); // Check added String favoriteTpfText = "FR 300 310 - Transports Publics Fribourgeois"; Assert.assertTrue("Favorite added to list", solo.searchText(favoriteTpfText)); // Click on it solo.clickOnText(favoriteTpfText); // Check view contains the same text Assert.assertTrue(solo.waitForActivity("ShowPlateOwnerActivity", 20000)); // 20 seconds timeout Assert.assertEquals(expectedPlateText, solo.getText(1).getText().toString()); Assert.assertEquals(expectedTpfText, solo.getText(2).getText().toString()); // Check second button is now "Supprimer des favoris" String removeFromFavoritesText = REMOVE_BOOKMARK_TEXT; Assert.assertEquals(removeFromFavoritesText, solo.getButton(1).getText().toString()); // Click on it solo.clickOnText(removeFromFavoritesText); // Go back to bookmarks solo.goBack(); // Check favorite is removed Assert.assertFalse(solo.searchText(favoriteTpfText)); } /*public void testValaisSearch() throws Exception { // Start search activity solo.clickOnText(SEARCH_TEXT); // Set search to 300 310 solo.enterText(0, "50000"); // Assume FR was selected solo.pressSpinnerItem(0, +17); // Select "VS" solo.clickOnButton(1); Assert.assertTrue(solo.waitForActivity("ShowPlateOwnerActivity", 60000)); // 1 minute timeout String expectedPlateText = "VS · 50 000"; Assert.assertEquals(expectedPlateText, solo.getText(1).getText()); String expectedTpfText = "Lambrigger Paul\r\nIm Luss\r\nHaus Cebu\r\n3984 Fiesch"; Assert.assertEquals(expectedTpfText, solo.getText(2).getText()); }*/ /* public void testMultipleTimesSameBookmark() throws Exception { solo.clickOnText(SEARCH_TEXT); solo.enterText(0, "11771"); solo.clickOnButton(1); solo.waitForActivity("ShowPlateOwnerActivity", 60000); // 1 minute timeout solo.clickOnText(ADD_BOOKMARK_TEXT); solo.goBack(); solo.waitForActivity("WelcomeListActivity", 60000); // 1 minute timeout solo.clickOnText(SEARCH_TEXT); solo.enterText(0, "11771"); solo.clickOnButton(1); solo.waitForActivity("ShowPlateOwnerActivity", 60000); // 1 minute timeout solo.clickOnText(REMOVE_BOOKMARK_TEXT); solo.clickOnText(ADD_BOOKMARK_TEXT); solo.waitForActivity("BookmarksViewActivity", 60000); // 1 minute timeout Assert.assertTrue(solo.searchText("FR 11 771", 1)); }*/ @Override public void tearDown() throws Exception { solo.finishOpenedActivities(); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.fragments; import android.app.*; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.StyleSpan; import android.util.Log; import android.view.*; import android.widget.*; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.lib.autoindex.plate.PlateType; import com.mathieuclement.swiss.autoindex.android.app.R; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.DataManager; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.plate_records.PlateRecord; import com.mathieuclement.swiss.autoindex.android.app.util.PlateTypeUtils; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; public class BookmarksViewFragment extends ListFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, PopupMenu.OnMenuItemClickListener { private List<PlateRecord> plateRecordList; private DataManager dataManager; private int currentPosition; // position of bookmark item clicked, used for onMenuItemClick private ArrayAdapter<String> listAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.bookmarks_list, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); List<String> items = new LinkedList<String>(); dataManager = new DataManager(getActivity()); plateRecordList = dataManager.getBookmarks(); // dataManager.closeDb(); // Order by plate number Collections.sort(plateRecordList, new Comparator<PlateRecord>() { @Override public int compare(PlateRecord plateRecord, PlateRecord otherPlateRecord) { return ((Integer) plateRecord.getNumber()).compareTo(otherPlateRecord.getNumber()); } }); for (PlateRecord plateRecord : plateRecordList) { StringBuilder shownString = new StringBuilder(); String numberPartStr = plateRecord.getCanton() + " " + Plate.formatNumber(plateRecord.getNumber()); if (PlateType.AUTOMOBILE_REPAIR_SHOP.equals(new PlateType(plateRecord.getType())) || PlateType.MOTORCYCLE_REPAIR_SHOP.equals(new PlateType(plateRecord.getType()))) { // append U for repair shops plates numberPartStr += " U"; } shownString.append(numberPartStr); if (PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("pref_name_in_favorites", true)) { // If plate type is NOT "Auto (white)", display the type on the first line along with the plate number // and the name on a new line if (!PlateType.AUTOMOBILE.equals(new PlateType(plateRecord.getType()))) { String typeStr; try { typeStr = getResources().getString(PlateTypeUtils.getResourceId( new PlateType(plateRecord.getType()))); } catch (Resources.NotFoundException nfe) { Log.e(getClass().getName(), "Resource string for " + plateRecord.getType() + " could not be " + "found."); typeStr = "Unknown"; } shownString.append(" - ").append(typeStr); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { shownString.append("\n "); } else { shownString.append(" | "); } shownString.append(plateRecord.getName()); } else { // Otherwise show something like "FR 300 340 - Transports Publics Fribourgeois" shownString.append(" - ").append(plateRecord.getName()); } } else { shownString.append(" - ").append(getResources().getString(PlateTypeUtils.getResourceId( new PlateType(plateRecord.getType())))); } items.add(shownString.toString()); } ListView listView = (ListView) view.findViewById(android.R.id.list); listAdapter = new BookmarksListAdapter(getActivity(), android.R.layout.simple_list_item_1, items); listView.setAdapter(listAdapter); if (!plateRecordList.isEmpty()) { listView.setOnItemClickListener(this); listView.setOnItemLongClickListener(this); } else { items.add(getResources().getString(R.string.bookmarks_empty_list)); } } @Override public void onStop() { super.onStop(); dataManager.closeDb(); } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { if (!plateRecordList.isEmpty()) { // ignore click on "No bookmark added yet" item PlateRecord plateRecord = plateRecordList.get(position); openPlateRecord(plateRecord); } } private void openPlateRecord(PlateRecord plateRecord) { openPlateRecord(getFragmentManager(), plateRecord); } public static void openPlateRecord(FragmentManager fragmentManager, PlateRecord plateRecord) { Plate plate = plateRecord.toPlate(); PlateOwner plateOwner = plateRecord.toPlateOwner(); Bundle args = new Bundle(); args.putString(ShowPlateOwnerFragment.PLATE_CANTON_ABBR_KEY, plate.getCanton().getAbbreviation()); args.putString(ShowPlateOwnerFragment.PLATE_TYPE_KEY, plate.getType().getName()); args.putInt(ShowPlateOwnerFragment.PLATE_NUMBER_KEY, plate.getNumber()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_NAME_KEY, plateOwner.getName()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_ADDRESS_KEY, plateOwner.getAddress()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_ADDRESS_COMPLEMENT_KEY, plateOwner.getAddressComplement()); args.putInt(ShowPlateOwnerFragment.PLATE_OWNER_ZIP_KEY, plateOwner.getZip()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_TOWN_KEY, plateOwner.getTown()); args.putLong(ShowPlateOwnerFragment.PLATE_RECORD_ID_KEY, plateRecord.getId()); Fragment fragment = new ShowPlateOwnerFragment(); fragment.setArguments(args); FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(R.id.content_frame, fragment).addToBackStack(null).commit(); } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { showPopupMenu(view, position); return true; } private void showPopupMenu(View v, int position) { PopupMenu popupMenu = new PopupMenu(getActivity(), v); popupMenu.getMenuInflater().inflate(R.menu.bookmark_long_click_menu, popupMenu.getMenu()); this.currentPosition = position; popupMenu.setOnMenuItemClickListener(this); popupMenu.show(); } @Override public boolean onMenuItemClick(MenuItem item) { PlateRecord plateRecord = plateRecordList.get(currentPosition); if (item.getItemId() == R.id.bookmark_long_click_popupmenu_open) { openPlateRecord(plateRecord); } else if (item.getItemId() == R.id.bookmark_long_click_popupmenu_remove_bookmark) { removeBookmark(plateRecord); } else { return false; } return true; } private void removeBookmark(PlateRecord plateRecord) { dataManager.removeBookmark(plateRecord.getId()); listAdapter.remove(listAdapter.getItem(currentPosition)); plateRecordList.remove(currentPosition); if (plateRecordList.isEmpty()) { listAdapter.add(getResources().getString(R.string.bookmarks_empty_list)); } listAdapter.notifyDataSetChanged(); } private class BookmarksListAdapter extends ArrayAdapter<String> { public BookmarksListAdapter(Context context, int viewId, List<String> items) { super(context, viewId, items); } // Bold style span StyleSpan boldStyle = new StyleSpan(android.graphics.Typeface.BOLD); @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); if (PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean ("pref_name_in_favorites", true)) { String wholeStr = getItem(position); SpannableStringBuilder sb = new SpannableStringBuilder(wholeStr); sb.setSpan(boldStyle, 0, numberLength(wholeStr), Spanned.SPAN_INCLUSIVE_INCLUSIVE); view.setText(sb); } return view; } // Returns number of characters including the last number // e.g. "FR 12 345" returns 9. private int numberLength(String str) { // Find first dash // We suppose we have an example such as "FR 12 345 - Owner name" int endIndex = str.indexOf('-'); if (endIndex < 0) { //BugSenseHandler.sendEvent("In favorites, got the (unspannable) label: " + str); return 0; } else { return endIndex - 1; } } } // end BookmarksListAdapter } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.persistence.droid.bookmarks; import android.database.sqlite.SQLiteDatabase; import org.droidpersistence.dao.DroidDao; import org.droidpersistence.dao.TableDefinition; public class BookmarkRecordDao extends DroidDao<BookmarkRecord, Long> { public BookmarkRecordDao(TableDefinition<BookmarkRecord> bookmarkRecordTableDefinition, SQLiteDatabase database) { super(BookmarkRecord.class, bookmarkRecordTableDefinition, database); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.speech; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.speech.RecognizerIntent; import android.speech.tts.TextToSpeech; import android.util.Log; import com.bugsense.trace.BugSenseHandler; import com.mathieuclement.lib.autoindex.canton.Canton; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.swiss.autoindex.android.app.R; import java.util.ArrayList; /** * @author <NAME> * @since 29.12.2013 */ public class SpeechRecognitionWrapper { private TextToSpeech tts; private int SPEECH_REQUEST_CODE = 1234; private Fragment fragment; private final OnNumberRecognizedListener onNumberRecognizedListener; /** * Wrapper for speech recognition. * IMPORTANT: You have to call onActivityResult in the method of the same name in the activity. * Similarly, you have to call onDestroy before super.onDestroy in your activity. * * @param fragment Fragment from whom the speech recognition is fired * @param onInitListener What to do after init, probably enabling a button or disabling it */ public SpeechRecognitionWrapper(Fragment fragment, TextToSpeech.OnInitListener onInitListener, OnNumberRecognizedListener onNumberRecognizedListener) { this.fragment = fragment; this.onNumberRecognizedListener = onNumberRecognizedListener; tts = new TextToSpeech(fragment.getActivity(), onInitListener); } public interface OnNumberRecognizedListener { void onNumberRecognized(int number); void onSpeechRecognitionFinished(); // called when out of speech recognition process } public void listen() { tts.playSilence(50, TextToSpeech.QUEUE_FLUSH, null); Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, fragment.getString(R.string.speech_say_number)); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100); fragment.startActivityForResult(intent, SPEECH_REQUEST_CODE); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == SPEECH_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { ArrayList<String> matches = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (matches.size() == 0) { tts.speak(fragment.getResources().getString(R.string.speech_silent), TextToSpeech.QUEUE_ADD, null); } else { String bestMatch = null; for (String match : matches) { if (match.matches(".*[0-9]+.*")) { bestMatch = match; break; } } if (bestMatch == null) { sayUnknownQuery(); return; } else { // Concatenate all numbers found String[] split = bestMatch.split(" "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < split.length; i++) { if (split[i].matches("[0-9]+")) { sb.append(Integer.parseInt(split[i])); } } final String numberStr = sb.toString(); if (numberStr.length() > 6 || numberStr.length() == 0) { sayUnknownQuery(); return; } try { onNumberRecognizedListener.onNumberRecognized(Integer.parseInt(numberStr)); } catch (NumberFormatException nfe) { String msg = "Could not parse " + numberStr + " as a number"; BugSenseHandler.sendEvent(msg); Log.e(getClass().getName(), msg); sayUnknownQuery(); return; } onNumberRecognizedListener.onSpeechRecognitionFinished(); } } } } } private String splitCanton(Canton canton) { return String.format("%c %c, ", canton.getAbbreviation().charAt(0), canton.getAbbreviation().charAt(1)); } private void say(String str) { tts.speak(str, TextToSpeech.QUEUE_ADD, null); } public void sayError() { say(fragment.getResources().getString(R.string.speech_error)); } public void sayUnknownQuery() { say(fragment.getResources().getString(R.string.speech_unknown_query)); } public void sayPendingSearch(Plate plate) { say(fragment.getResources().getString(R.string.speech_pending_search, splitCanton(plate.getCanton()), plate.getNumber())); } public void sayOwnerNotFound(Plate plate) { say(fragment.getResources().getString(R.string.speech_not_found, splitCanton(plate.getCanton()), plate.getNumber())); } public void sayHiddenData(Plate plate) { say(fragment.getResources().getString(R.string.speech_hidden_data, splitCanton(plate.getCanton()), plate.getNumber())); } public void sayOwnerFound(Plate plate, PlateOwner plateOwner) { say(fragment.getResources().getString(R.string.speech_owner_found, splitCanton(plate.getCanton()), plate.getNumber(), plateOwner.getName(), smartAddress(plateOwner.getAddress()), smartAddress(plateOwner.getAddressComplement()), plateOwner.getZip(), smartTown(plateOwner.getTown(), plate.getCanton().getAbbreviation()))); } public String smartTown(String rawTown, String cantonAbbr) { String smartTown = rawTown; if (smartTown.endsWith(" " + cantonAbbr.toUpperCase())) smartTown = smartTown.replace(" " + cantonAbbr.toUpperCase(), ""); if (smartTown.matches(".*[0-9]$")) smartTown = smartTown.replaceAll("[0-9]", ""); return smartTown; } public String smartAddress(String rawAddr) { String smartAddr = rawAddr; if (smartAddr.startsWith("Ch. ")) smartAddr = smartAddr.replace("Ch. ", "Chemin "); if (smartAddr.startsWith("Rte ")) smartAddr = smartAddr.replace("Rte ", "Route "); if (smartAddr.startsWith("Str. ")) smartAddr = smartAddr.replace("Str. ", "Strasse "); if (smartAddr.startsWith("Bvd ")) smartAddr = smartAddr.replace("Bvd ", "Boulevard "); if (smartAddr.startsWith("Imp. ")) smartAddr = smartAddr.replace("Imp. ", "Impasse "); if (smartAddr.startsWith("Av. ")) smartAddr = smartAddr.replace("Av. ", "Avenue "); if (smartAddr.startsWith("Pl. ")) smartAddr = smartAddr.replace("Pl. ", "Place "); return smartAddr; } public void onDestroy() { if (tts != null) { tts.shutdown(); } } }<file_sep>package com.mathieuclement.swiss.autoindex.android.app.activity; import android.app.*; import android.content.DialogInterface; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.mathieuclement.swiss.autoindex.android.app.R; import com.mathieuclement.swiss.autoindex.android.app.fragments.BookmarksViewFragment; import com.mathieuclement.swiss.autoindex.android.app.fragments.SettingsFragment; import com.mathieuclement.swiss.autoindex.android.app.fragments.search.SearchFragment; import com.mathieuclement.swiss.autoindex.android.app.util.RateMe; import java.util.LinkedList; import java.util.List; public class MainDrawerActivity extends Activity implements AdapterView.OnItemClickListener { public static final int DIALOG_CAPTCHA_RETRIEVE_ERROR_ID = 0; public static final int DIALOG_OWNER_NOT_FOUND = 2; public static final int DIALOG_OWNER_HIDDEN = 3; public static final int DIALOG_TOO_MANY_REQUESTS = 4; private RateMe rateMe; private DrawerLayout drawerLayout; private ListView drawerListView; private ActionBarDrawerToggle drawerToggle; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_with_drawer); initDrawer(savedInstanceState); initRateMe(); // enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } private void initRateMe() { rateMe = new RateMe(this); rateMe.advertRatingIfNeeded(); } private void initDrawer(Bundle savedInstanceState) { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); List<String> items = new LinkedList<String>(); items.add(getResources().getString(R.string.welcome_item_search)); // 0 items.add(getResources().getString(R.string.welcome_item_bookmarks)); // 1 items.add(getResources().getString(R.string.welcome_item_settings)); // 2 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item, items); drawerListView = (ListView) findViewById(R.id.left_drawer); drawerListView.setAdapter(adapter); drawerListView.setOnItemClickListener(this); drawerToggle = new ActionBarDrawerToggle(MainDrawerActivity.this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close); drawerLayout.setDrawerListener(drawerToggle); if (savedInstanceState == null) selectItem(0); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } private void closeDrawer() { drawerLayout.closeDrawer(drawerListView); } private void selectItem(int position) { Fragment fragment = null; if (position == 0) { fragment = new SearchFragment(); } else if (position == 1) { fragment = new BookmarksViewFragment(); } else if (position == 2) { fragment = new SettingsFragment(); } if (fragment != null) { SearchFragment.hideKeyboard(this); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .commit(); closeDrawer(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override protected Dialog onCreateDialog(int id) { final Dialog[] dialog = {null}; switch (id) { case DIALOG_CAPTCHA_RETRIEVE_ERROR_ID: runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder1 = new AlertDialog.Builder(MainDrawerActivity.this); builder1.setTitle(R.string.captcha_retrieve_dialog_error_title); builder1.setMessage(R.string.captcha_retrieve_dialog_error_message); builder1.setNeutralButton(R.string.dialog_dismiss, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog[0] = builder1.create(); } }); break; case DIALOG_OWNER_NOT_FOUND: runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder1 = new AlertDialog.Builder(MainDrawerActivity.this); builder1.setTitle(R.string.plate_owner_not_found_dialog_title); builder1.setMessage(R.string.plate_owner_not_found_dialog_message); builder1.setNeutralButton(R.string.dialog_dismiss, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog[0] = builder1.create(); } }); break; case DIALOG_OWNER_HIDDEN: runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder1 = new AlertDialog.Builder(MainDrawerActivity.this); builder1.setTitle(R.string.plate_owner_hidden_dialog_title); builder1.setMessage(R.string.plate_owner_hidden_dialog_message); builder1.setNeutralButton(R.string.dialog_dismiss, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog[0] = builder1.create(); } }); break; case DIALOG_TOO_MANY_REQUESTS: runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder1 = new AlertDialog.Builder(MainDrawerActivity.this); builder1.setTitle(R.string.too_many_requests_title); builder1.setMessage(R.string.too_many_requests_message); builder1.setNeutralButton(R.string.dialog_dismiss, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog[0] = builder1.create(); } }); break; } return dialog[0]; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.persistence.droid; import android.app.backup.BackupManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Environment; import com.bugsense.trace.BugSenseHandler; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.bookmarks.BookmarkRecord; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.bookmarks.BookmarkRecordDao; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.bookmarks.BookmarkRecordTableDefinition; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.contact.ContactRecord; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.contact.ContactRecordDao; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.contact.ContactRecordTableDefinition; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.plate_records.PlateRecord; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.plate_records.PlateRecordDao; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.plate_records.PlateRecordTableDefinition; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Data manager for Plate Records database * <p/> * TODO: Use an appropriate design pattern because this sucks! */ public class DataManager { public static final String DB_NAME = "PLATERECORDDATABASE"; private Context context; private SQLiteDatabase database; private PlateRecordDao plateRecordDao; private BookmarkRecordDao bookmarkRecordDao; private ContactRecordDao contactRecordDao; private static final String DATABASE_PATH = Environment.getDataDirectory() + "/data/com.mathieuclement.swiss.autoindex/databases/plate_record_database.db"; public DataManager(Context context) { setContext(context); SQLiteOpenHelper openHelper = new OpenHelper(context, DB_NAME, null, 6); SQLiteDatabase db = openHelper.getWritableDatabase(); setDatabase(db); this.plateRecordDao = new PlateRecordDao(new PlateRecordTableDefinition(), database); this.bookmarkRecordDao = new BookmarkRecordDao(new BookmarkRecordTableDefinition(), database); this.contactRecordDao = new ContactRecordDao(new ContactRecordTableDefinition(), database); } void openDb() { try { if (getDatabase() != null && !getDatabase().isOpen()) { setDatabase(SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE)); } } catch (Exception e) { // No fail BugSenseHandler.sendException(e); } } /** * Close connection to database. * Is usually to be put in the "finally" clause of a try-catch-finally block. */ public void closeDb() { if (getDatabase() != null && getDatabase().isOpen()) { getDatabase().close(); } } /** * *** Plate Records ***** */ public PlateRecord getPlateRecord(Long id) { return getPlateRecordDao().get(id); } public PlateRecord getPlateRecordByPlate(Plate plate) { return getPlateRecordDao().getByClause(" CANTON ='" + plate.getCanton().getAbbreviation() + "' AND NUMBER=" + plate.getNumber() + " AND TYPE='" + plate.getType().getName() + "'", null); } public List<PlateRecord> getPlateRecords() { return getPlateRecordDao().getAll(); } public boolean deletePlateRecord(Long id) { boolean result; getDatabase().beginTransaction(); result = getPlateRecordDao().delete(id); getDatabase().setTransactionSuccessful(); getDatabase().endTransaction(); updateBackup(); return result; } public long savePlateRecord(PlateRecord plateRecord) throws Exception { long result = 0; getDatabase().beginTransaction(); result = getPlateRecordDao().save(plateRecord); getDatabase().setTransactionSuccessful(); getDatabase().endTransaction(); updateBackup(); return result; } public boolean updatePlateRecord(PlateRecord plateRecord) throws Exception { boolean result; getDatabase().beginTransaction(); getPlateRecordDao().update(plateRecord, plateRecord.getId()); getDatabase().setTransactionSuccessful(); result = true; getDatabase().endTransaction(); updateBackup(); return result; } public PlateRecordDao getPlateRecordDao() { return plateRecordDao; } public void setPlateRecordDao(PlateRecordDao plateRecordDao) { this.plateRecordDao = plateRecordDao; } /** * Returns the id of the corresponding plate record. * * @param plate Plate * @return the id of the corresponding plate record. */ public Long getPlateRecordId(Plate plate) { List<PlateRecord> plateRecords = getPlateRecords(); for (PlateRecord plateRecord : plateRecords) { if (plateRecord.getCanton().equals(plate.getCanton().getAbbreviation()) && plateRecord.getNumber() == plate.getNumber() && plateRecord.getType().equals(plate.getType().getName())) { return plateRecord.getId(); } } return null; } /** * Returns true if plate is in cache. * * @param plate Plate * @return true if plate is in cache. */ // public boolean isCached(Plate plate) { // PlateRecord plateRecord = getPlateRecordByPlate(plate); // if (plateRecord != null && getCacheRecordDao().get(plateRecord.getId()) != null) { // return true; // } // // return false; // } /** * Returns the bookmarked plates as plate records. * * @return the bookmarked plates as plate records. */ public List<PlateRecord> getBookmarks() { List<PlateRecord> plateRecords = getPlateRecordDao().getAll(); List<PlateRecord> plateRecordsCopy = new LinkedList<PlateRecord>(plateRecords); List<BookmarkRecord> bookmarkRecords = getBookmarkRecordDao().getAll(); Set<Long> bookmarkedIds = new HashSet<Long>(); for (BookmarkRecord bookmarkRecord : bookmarkRecords) { bookmarkedIds.add(bookmarkRecord.getPlateRecordId()); } for (PlateRecord plateRecord : plateRecordsCopy) { if (!bookmarkedIds.contains(plateRecord.getId())) { plateRecords.remove(plateRecord); } } return plateRecords; } /** * Returns true if the plate is bookmarked. * * @return true if the plate is bookmarked. */ public boolean isBookmarked(Plate plate) { List<PlateRecord> plateRecords = getPlateRecords(); for (PlateRecord plateRecord : plateRecords) { if (plateRecord.getCanton().equals(plate.getCanton().getAbbreviation()) && plateRecord.getNumber() == plate.getNumber() && plateRecord.getType().equals(plate.getType().getName())) { return true; } } return false; } /** * Remove bookmark. * * @param id Plate record ID */ public void removeBookmark(Long id) { removeBookmarkRecord(id); // if (!isCached(plate)) { if (!isContact(id)) { deletePlateRecord(id); } // } } private boolean isContact(Long id) { return getContactRecordDao().get(id) != null; } /** * Add a new contact to database * * @param plate Plate * @param plateOwner Plate owner * @param lookupKey Lookup key (Contacts API 2.0) * @return ID of plate record in table. * @throws Exception */ public Long addContact(Plate plate, PlateOwner plateOwner, String lookupKey) throws Exception { PlateRecord record = getPlateRecordByPlate(plate); long plateRecordId; if (record == null) { plateRecordId = savePlateRecord(new PlateRecord(plate, plateOwner)); } else { plateRecordId = record.getId(); } getContactRecordDao().save(new ContactRecord(plateRecordId, lookupKey)); return plateRecordId; } public void removeContact(Plate plate) { removeContact(plate, getPlateRecordId(plate)); } public void removeContact(Plate plate, Long id) { getContactRecordDao().delete(id); if (!isBookmarked(plate)) { deletePlateRecord(id); } } public String getContactLookupKey(Plate plate) { Long plateRecordId = getPlateRecordId(plate); ContactRecord record = getContactRecordDao().getByClause(" platerecord_id = ?", new String[]{Long.toString(plateRecordId)}); if (record == null) return null; return record.getLookupKey(); } public String getRemarks(Plate plate) { Long plateRecordId = getPlateRecordId(plate); BookmarkRecord record = getBookmarkRecordDao().getByClause(" platerecord_id = ?", new String[]{Long.toString(plateRecordId)}); if (record == null) return null; return record.getRemarks(); } /** * Removes a bookmark record (NO CHECK!) * * @param id ID of plate record * @return true on success */ protected boolean removeBookmarkRecord(Long id) { boolean result; getDatabase().beginTransaction(); result = getBookmarkRecordDao().delete(id); getDatabase().setTransactionSuccessful(); getDatabase().endTransaction(); updateBackup(); return result; } public long addBookmark(Plate plate, PlateOwner owner) throws Exception { Long id = getPlateRecordId(plate); if (id == null) { // Create whole entry id = savePlateRecord(new PlateRecord(plate, owner)); } // In all cases, put ID in bookmarks table try { addBookmarkRecord(new BookmarkRecord(id, "")); } catch (Throwable t) { // Remove record from plate records if anything goes wrong. removeBookmark(id); } return id; } // public long addToCache(Plate plate, PlateOwner owner) throws Exception { // Long id = getPlateRecordId(plate); // if (id == null) { // // Create whole entry // id = savePlateRecord(new PlateRecord(plate, owner)); // } // // // In all cases, put ID in cache table // addCacheRecord(new CacheRecord(id)); // // return id; // } /** * Un-cache plate * * @param plate Plate * @param cacheRecordId Plate record ID */ // protected void removeFromCache(Plate plate, Long cacheRecordId, Long plateRecordId) { // removeCacheRecord(cacheRecordId); // if (!isBookmarked(plate)) { // deletePlateRecord(cacheRecordId); // } // } // protected Long getCacheRecordId(Plate plate) { // Long plateRecordId = getPlateRecordId(plate); // CacheRecord cacheRecord = getCacheRecordDao().getByClause( // " platerecord_id = ?", new String[]{Long.toString(plateRecordId)}); // if(cacheRecord == null) { // return null; // } // return cacheRecord.getCacheId(); // } // public void removeFromCache(Plate plate) { // removeFromCache(plate, getCacheRecordId(plate), getPlateRecordId(plate)); // } // public void removeAllFromCache() { // List<PlateRecord> cachedPlates = getCachedPlates(); // for (PlateRecord plateRecord : cachedPlates) { // Plate plate = plateRecord.toPlate(); // removeFromCache(plate, getCacheRecordId(plate), plateRecord.getId()); // } // } /** * Returns cached plates as plate records. * * @return cached plates as plate records. */ // public List<PlateRecord> getCachedPlates() { // List<PlateRecord> plateRecords = getPlateRecordDao().getAll(); // List<PlateRecord> plateRecordsCopy = new LinkedList<PlateRecord>(plateRecords); // List<CacheRecord> cacheRecords = getCacheRecordDao().getAll(); // // Set<Long> cachedIds = new HashSet<Long>(); // for (CacheRecord cacheRecord : cacheRecords) { // cachedIds.add(cacheRecord.getPlateRecordId()); // } // // for (PlateRecord plateRecord : plateRecordsCopy) { // if (!cachedIds.contains(plateRecord.getId())) { // plateRecords.remove(plateRecord); // } // } // // return plateRecords; // } /** * Removes a bookmark record (NO CHECK!) * * @param id ID of plate record * @return true on success */ // protected boolean removeCacheRecord(Long id) { // boolean result; // getDatabase().beginTransaction(); // result = getCacheRecordDao().delete(id); // getDatabase().setTransactionSuccessful(); // getDatabase().endTransaction(); // updateBackup(); // return result; // } // protected long addCacheRecord(CacheRecord cacheRecord) throws Exception { // long result; // getDatabase().beginTransaction(); // result = getCacheRecordDao().save(cacheRecord); // getDatabase().setTransactionSuccessful(); // getDatabase().endTransaction(); // updateBackup(); // return result; // } /** * Add a bookmark record * * @param bookmarkRecord * @return id of new record * @throws Exception */ protected long addBookmarkRecord(BookmarkRecord bookmarkRecord) throws Exception { long result; getDatabase().beginTransaction(); result = getBookmarkRecordDao().save(bookmarkRecord); getDatabase().setTransactionSuccessful(); getDatabase().endTransaction(); updateBackup(); return result; } public BookmarkRecordDao getBookmarkRecordDao() { return bookmarkRecordDao; } public void setBookmarkRecordDao(BookmarkRecordDao bookmarkRecordDao) { this.bookmarkRecordDao = bookmarkRecordDao; } // public CacheRecordDao getCacheRecordDao() { // return cacheRecordDao; // } public ContactRecordDao getContactRecordDao() { return contactRecordDao; } public Context getContext() { return context; } void setContext(Context context) { this.context = context; } SQLiteDatabase getDatabase() { return database; } void setDatabase(SQLiteDatabase database) { this.database = database; } private BackupManager backupManager; private void updateBackup() { if (backupManager == null) { backupManager = new BackupManager(context); } backupManager.dataChanged(); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.persistence.droid.bookmarks; import org.droidpersistence.annotation.Column; import org.droidpersistence.annotation.ForeignKey; import org.droidpersistence.annotation.PrimaryKey; import org.droidpersistence.annotation.Table; @SuppressWarnings("ALL") @Table(name = "BOOKMARKRECORDS") public class BookmarkRecord { @PrimaryKey(autoIncrement = false) @Column(name = "platerecord_id") @ForeignKey(tableReference = "PLATERECORDS", columnReference = "ID") private long plateRecordId; @Column(name = "remarks") private String remarks; public BookmarkRecord(long plateRecordId, String remarks) { this.plateRecordId = plateRecordId; this.remarks = remarks; } public BookmarkRecord() { } public boolean autoIncrement() { return false; } public long getPlateRecordId() { return plateRecordId; } public void setPlateRecordId(long plateRecordId) { this.plateRecordId = plateRecordId; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.beans; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; public class PlatePlateOwner { private Plate plate; private PlateOwner plateOwner; public PlatePlateOwner(Plate plate, PlateOwner plateOwner) { this.plate = plate; this.plateOwner = plateOwner; } public Plate getPlate() { return plate; } public void setPlate(Plate plate) { this.plate = plate; } public PlateOwner getPlateOwner() { return plateOwner; } public void setPlateOwner(PlateOwner plateOwner) { this.plateOwner = plateOwner; } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.persistence.droid.contact; import org.droidpersistence.dao.TableDefinition; public class ContactRecordTableDefinition extends TableDefinition<ContactRecord> { public ContactRecordTableDefinition() { super(ContactRecord.class); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.util; import android.app.AlertDialog; import android.content.*; import android.net.Uri; import android.widget.Toast; import com.mathieuclement.swiss.autoindex.android.app.R; import java.util.Date; /** * @author <NAME> * @since 09.11.2013 */ public class RateMe { private static final String PREF_ALREADY_RATED = "already_rated"; // boolean. true = never show dialog again private static final String PREF_LAST_CHECK_DATE = "last_check_date"; // long. seconds since epoch private final SharedPreferences preferences; private Context context; public RateMe(Context context) { this.context = context; this.preferences = context.getSharedPreferences("advert_rating", Context.MODE_PRIVATE); } public void reset() { preferences.edit().clear().commit(); } /** * Show dialog if necessary * * @return true if dialog has been shown this time */ public boolean advertRatingIfNeeded() { /* Pseudo-code if already_rated exists and is true (default value = false): return false if date property absent: create date property with current time return false if 1 week passed: set date property to current date show dialog if "rate now" selected: open google play else if "already rated" selected: set "already_rated" = true else if "rate later" or back button pressed": pass close dialog return true */ if (preferences.contains(PREF_ALREADY_RATED) && preferences.getBoolean(PREF_ALREADY_RATED, false)) { return false; } if (!preferences.contains(PREF_LAST_CHECK_DATE)) { preferences.edit().putLong(PREF_LAST_CHECK_DATE, currentDateAsLong()).commit(); return false; } if (daysPassed(7, preferences.getLong(PREF_LAST_CHECK_DATE, currentDateAsLong()), currentDateAsLong())) { preferences.edit().putLong(PREF_LAST_CHECK_DATE, currentDateAsLong()).commit(); makeDialog().show(); return true; } return false; } private AlertDialog makeDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog dialog = builder.create(); dialog.setTitle(context.getString(R.string.rate_this_app_title)); dialog.setMessage(context.getString(R.string.rate_this_app_text)); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(false); dialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.rate_this_app_rate_now), new RateNowListener()); dialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.rate_this_app_already_rated), new AlreadyRatedListener()); CancelListener cancelListener = new CancelListener(); dialog.setButton(DialogInterface.BUTTON_NEUTRAL, context.getString(R.string.rate_this_app_rate_later), cancelListener); dialog.setOnCancelListener(cancelListener); return dialog; } protected long currentDateAsLong() { return new Date().getTime(); } // Returns true if (newDate - oldDate) >= days private boolean daysPassed(int days, long oldDateInMillis, long newDateInMillis) { return (newDateInMillis - oldDateInMillis) >= days * 86400000; } private class RateNowListener implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { rateThisApp(context); dialog.dismiss(); } } private class AlreadyRatedListener implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(PREF_ALREADY_RATED, true).commit(); dialog.dismiss(); } } private class CancelListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } @Override public void onCancel(DialogInterface dialog) { preferences.edit().putLong(PREF_LAST_CHECK_DATE, currentDateAsLong()).commit(); } } public static void rateThisApp(Context context) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("market://details?id=com.mathieuclement.swiss.autoindex.android.app")); try { context.startActivity(intent); } catch (ActivityNotFoundException anfe) { // This is not supposed to happen if the application was acquired legally on Google Play, but we never know... // Also this exception will be thrown when running the application in the emulator, Toast.makeText(context, "Cannot find Google Play Store application on this device.", Toast.LENGTH_LONG).show(); } } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.backup; import android.app.backup.BackupAgentHelper; import android.app.backup.BackupHelper; import android.app.backup.FileBackupHelper; import android.app.backup.SharedPreferencesBackupHelper; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.DataManager; public class MyBackupAgent extends BackupAgentHelper { @Override public void onCreate() { super.onCreate(); // The filename is not the ".db" file but the file that can be seen in /data/data/com.mathieuclement.../databases/ directory // FileBackupHelper is not meant for "big" files but we don't care BackupHelper favoritesDatabaseBackupHelper = new FileBackupHelper(getApplicationContext(), "../databases/" + DataManager.DB_NAME); addHelper("FAVORITES_DATABASE", favoritesDatabaseBackupHelper); // Default preferences (from preferences.xml) BackupHelper defaultPrefBackupHelper = new SharedPreferencesBackupHelper(getApplicationContext(), getPackageName() + "_preferences"); addHelper("DEFAULT_SHARED_PREFERENCES", defaultPrefBackupHelper); // TODO Other preferences } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.fragments.search.captcha; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.lib.autoindex.provider.common.captcha.CaptchaException; import com.mathieuclement.lib.autoindex.provider.common.captcha.event.PlateRequestListener; import com.mathieuclement.lib.autoindex.provider.exception.*; import com.mathieuclement.swiss.autoindex.android.app.R; import com.mathieuclement.swiss.autoindex.android.app.activity.MainDrawerActivity; import com.mathieuclement.swiss.autoindex.android.app.fragments.ShowPlateOwnerFragment; import com.mathieuclement.swiss.autoindex.android.app.speech.SpeechRecognitionWrapper; public class MyPlateOwnerRequestListener implements PlateRequestListener { protected Activity activity; private ProgressDialog progressDialog; // In Viacar, progress dialog must show 1/3, 2/3 and 3/3 as in the tests public MyPlateOwnerRequestListener(Activity activity, ProgressDialog progressDialog) { this.activity = activity; this.progressDialog = progressDialog; } @Override public void onPlateOwnerFound(Plate plate, PlateOwner plateOwner) { Log.d(getClass().getName(), "Dismiss progress dialog."); progressDialog.dismiss(); doOnPlateOwnerFoundNotGui(plate, plateOwner); } // Actions common to manual and automatic captcha decoding listeners protected void doOnPlateOwnerFoundNotGui(Plate plate, PlateOwner plateOwner) { Log.d("RESULT_FOUND", "Plate: " + plate + "; Owner: " + plateOwner); Bundle args = new Bundle(); args.putString(ShowPlateOwnerFragment.PLATE_CANTON_ABBR_KEY, plate.getCanton().getAbbreviation()); args.putString(ShowPlateOwnerFragment.PLATE_TYPE_KEY, plate.getType().getName()); args.putInt(ShowPlateOwnerFragment.PLATE_NUMBER_KEY, plate.getNumber()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_NAME_KEY, plateOwner.getName()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_ADDRESS_KEY, plateOwner.getAddress()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_ADDRESS_COMPLEMENT_KEY, plateOwner.getAddressComplement()); args.putInt(ShowPlateOwnerFragment.PLATE_OWNER_ZIP_KEY, plateOwner.getZip()); args.putString(ShowPlateOwnerFragment.PLATE_OWNER_TOWN_KEY, plateOwner.getTown()); Fragment fragment = new ShowPlateOwnerFragment(); fragment.setArguments(args); FragmentTransaction ft = activity.getFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment).addToBackStack(null).commit(); } @Override @Deprecated public void onPlateRequestException(Plate plate, PlateRequestException exception) { Log.w(getClass().getName(), "Got Plate request exception but not for the special speech-enabled version"); } public void onPlateRequestException(Plate plate, PlateRequestException exception, SpeechRecognitionWrapper speech, boolean isSpeechEnabled) { /* MAKE SURE TO MODIFY IMPLEMENTATION CLASSES!!! */ if (exception instanceof NumberOfRequestsExceededException) { if (isSpeechEnabled) speech.sayError(); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.showDialog(MainDrawerActivity.DIALOG_TOO_MANY_REQUESTS); } }); } else if (exception instanceof ProviderException) { if (isSpeechEnabled) speech.sayError(); ProviderException providerException = (ProviderException) exception; Throwable cause = providerException.getCause(); if (!(cause instanceof CaptchaException)) { showOtherException(plate, exception); } } else if (exception instanceof PlateOwnerNotFoundException) { if (isSpeechEnabled) speech.sayOwnerNotFound(plate); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.showDialog(MainDrawerActivity.DIALOG_OWNER_NOT_FOUND); } }); } else if (exception instanceof PlateOwnerHiddenException) { if (isSpeechEnabled) speech.sayHiddenData(plate); activity.runOnUiThread(new Runnable() { @Override public void run() { activity.showDialog(MainDrawerActivity.DIALOG_OWNER_HIDDEN); } }); } else { if (isSpeechEnabled) speech.sayError(); showOtherException(plate, exception); } } protected void showOtherException(Plate plate, PlateRequestException exception) { Log.i(getClass().getSimpleName(), "Exception on plate request: " + plate, exception); activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity.getApplicationContext(), R.string.request_error_try_again, Toast.LENGTH_SHORT).show(); } }); } } <file_sep>package com.mathieuclement.swiss.autoindex.android.app.fragments.sms_provider; import android.app.Activity; import android.app.Fragment; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.Nullable; import android.telephony.SmsManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.bugsense.trace.BugSenseHandler; import com.mathieuclement.lib.autoindex.canton.Canton; import com.mathieuclement.lib.autoindex.plate.Plate; import com.mathieuclement.lib.autoindex.plate.PlateOwner; import com.mathieuclement.lib.autoindex.plate.PlateType; import com.mathieuclement.lib.autoindex.provider.common.AutoIndexProvider; import com.mathieuclement.swiss.autoindex.android.app.R; import com.mathieuclement.swiss.autoindex.android.app.fragments.ShowPlateOwnerFragment; import com.mathieuclement.swiss.autoindex.android.app.persistence.droid.DataManager; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author <NAME> * @since 15.09.2013 */ public class SendReceiveFragment extends Fragment { private ProgressBar progressBar; private TextView statusTextView; private BroadcastReceiver smsSentReceiver; private boolean smsSentReceiverRegistered; private BroadcastReceiver smsReceivedReceiver; private boolean smsReceivedReceiverRegistered; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.sms_send_receive, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Read extras int number = getArguments().getInt("number"); String canton = getArguments().getString("canton").toUpperCase(); statusTextView = (TextView) view.findViewById(R.id.sms_send_receive_status); progressBar = (ProgressBar) view.findViewById(R.id.sms_send_receive_progress); // TODO After answer is obtained, this must not fail, except if message is shown in the Messaging app. // Result will be bookmarked BY DEFAULT. // If response could not be parsed, show the raw response with some "Cannot parse response" message. // "Warning! This response will not be stored." // Init message String messageToSend = canton + " " + number; statusTextView.setText( String.format(getResources().getString(R.string.sms_provider_send_receive_sending), messageToSend, 939)); // Do the sending SmsManager smsManager = SmsManager.getDefault(); smsSentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent receivedIntent) { // That's "On SMS ***sent***" not response received! switch (getResultCode()) { case Activity.RESULT_OK: statusTextView.setText(R.string.sms_provider_send_receive_sent); progressBar.setProgress(50); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: // not translated because these failures are rare statusTextView.setText("Error: Generic Failure"); break; case SmsManager.RESULT_ERROR_NO_SERVICE: // Can happen when there is not network available. // Not translated, it's understable in FR and DE. statusTextView.setText("Error: No Service"); break; case SmsManager.RESULT_ERROR_NULL_PDU: // This one probably can't even happen because we have always have a text. statusTextView.setText("Error: Null PDU"); break; case SmsManager.RESULT_ERROR_RADIO_OFF: statusTextView.setText(R.string.sms_provider_send_receive_radio_off); break; default: break; } } }; getActivity().registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT")); smsSentReceiverRegistered = true; smsReceivedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context receivedContext, Intent receivedIntent) { String responseText = receivedIntent.getExtras().getString("message"); // Show ShowPlateOwnerFragment try { Fragment fragment = new ShowPlateOwnerFragment(); Bundle parse = parse(responseText); fragment.setArguments(parse); getFragmentManager().beginTransaction() .replace(R.id.content_frame, fragment) .commit(); } catch (ParseException pe) { Log.e(getClass().getName(), pe.getMessage(), pe); BugSenseHandler.sendException(pe); statusTextView.setText(String.format( getResources().getString(R.string.sms_provider_send_receive_unknown_response).toString(), responseText.split("\\*SEP_PDU\\*")[0].split("\\*SEP\\*")[1])); } } }; getActivity().registerReceiver(smsReceivedReceiver, new IntentFilter("com.mathieuclement.swiss.autoindex.android.app.SMS_RECEIVED")); smsReceivedReceiverRegistered = true; smsManager.sendTextMessage("939", null, messageToSend, PendingIntent.getBroadcast(getActivity(), 0, new Intent("SMS_SENT"), 0), PendingIntent.getBroadcast(getActivity(), 0, new Intent("SMS_DELIVERED"), 0) // actually ignored ); progressBar.setProgress(25); // Do the receiving // Try to parse, else show the error message that we couldn't parse. progressBar.setProgress(progressBar.getMax()); } private Bundle parse(String responseText) throws ParseException { Bundle extras = new Bundle(); // SMS received: // "Abfrage lieferte kein gültiges Ergebnis. Diese Nachricht kostet 20 Rp. L'interrogation n'a pas généré de // résultat positif." // IMPORTANT: It looks accents make the emulator crash when trying to send a SMS. // Must be verified on real hardware. // "BE 80546, <NAME>, Walkestr. 28, 3110 Muensingen - Diese Nachricht kostet 1 SFr." // From SmsReceiver we will have something like this: // "939*SEP*BE 80546, <NAME>, Walkestr. 28, 3110 Münsingen - Diese Nachricht kostet 1 SFr.*SEP_PDU*" try { String intentMsg = responseText.split("\\*SEP_PDU\\*")[0]; String[] spl = intentMsg.split("\\*SEP\\*"); String numberStr = spl[0]; String txtMsg = spl[1]; // Try to do the real parsing of the thing txtMsg = txtMsg.split(" - Diese Nachricht")[0]; // And here comes the regular expression at least Pattern pattern; int commas = numberOf(',', txtMsg); boolean hasComplement = commas > 3; if (commas <= 3) { pattern = Pattern.compile("(([A-Z]{2}) ([0-9]+)), (.*), (.*), ([0-9]{4}) (.*)"); } else { pattern = Pattern.compile("(([A-Z]{2}) ([0-9]+)), (.*), (.*), (.*), ([0-9]{4}) (.*)"); } Matcher matcher = pattern.matcher(txtMsg); if (!matcher.find()) { BugSenseHandler.addCrashExtraData("txtMsg", txtMsg); throw new ParseException("Got '" + txtMsg + "' for '" + numberStr + "' but could not parse that."); } Log.d(getClass().getName(), "Group count: " + matcher.groupCount()); String canton = matcher.group(2); int number = Integer.parseInt(matcher.group(3)); String name = matcher.group(4); String street = matcher.group(5); String complement = null; int zip; String town; if (hasComplement) { complement = matcher.group(6); zip = Integer.parseInt(matcher.group(7)); town = matcher.group(8); } else { zip = Integer.parseInt(matcher.group(6)); town = matcher.group(7); } extras.putString(ShowPlateOwnerFragment.PLATE_CANTON_ABBR_KEY, canton); extras.putString(ShowPlateOwnerFragment.PLATE_TYPE_KEY, "automobile"); extras.putInt(ShowPlateOwnerFragment.PLATE_NUMBER_KEY, number); extras.putString(ShowPlateOwnerFragment.PLATE_OWNER_NAME_KEY, name); extras.putString(ShowPlateOwnerFragment.PLATE_OWNER_ADDRESS_KEY, street); if (hasComplement && complement != null) { extras.putString(ShowPlateOwnerFragment.PLATE_OWNER_ADDRESS_COMPLEMENT_KEY, complement); } extras.putInt(ShowPlateOwnerFragment.PLATE_OWNER_ZIP_KEY, zip); extras.putString(ShowPlateOwnerFragment.PLATE_OWNER_TOWN_KEY, town); try { DataManager dataManager = new DataManager(getActivity()); try { Plate plate = new Plate(number, PlateType.AUTOMOBILE, new Canton(canton, false, (AutoIndexProvider) null)); PlateOwner plateOwner = new PlateOwner(name, street, complement != null ? complement : "", zip, town); long plateRecordId = dataManager.addBookmark(plate, plateOwner); extras.putLong(ShowPlateOwnerFragment.PLATE_RECORD_ID_KEY, plateRecordId); } catch (Exception e) { BugSenseHandler.sendException(e); e.printStackTrace(); Toast.makeText(getActivity(), "Error. Try again.", Toast.LENGTH_SHORT).show(); } dataManager.closeDb(); } catch (Exception e) { BugSenseHandler.sendException(e); e.printStackTrace(); } } catch (Exception e) { throw new ParseException("Could not parse \"" + responseText + "\"", e); } return extras; } private static int numberOf(char c, String string) { int count = 0; char[] chars = string.toCharArray(); for (char aChar : chars) { if (aChar == c) count++; } return count; } private class ParseException extends Exception { private ParseException(String detailMessage) { super(detailMessage); } private ParseException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } } /* @Override protected void onResume() { super.onResume(); registerReceiver(smsSentReceiver, new IntentFilter("SMS_SENT")); } */ @Override public void onStop() { super.onStop(); if (smsSentReceiverRegistered) { getActivity().unregisterReceiver(smsSentReceiver); } if (smsReceivedReceiverRegistered) { getActivity().unregisterReceiver(smsReceivedReceiver); } } }
f373718d9ed647493ab98a488cd1b9e651810e47
[ "Java", "Text" ]
22
Java
mathieu-clement/swiss_autoindex_android
f0398b429516359561fa856e892645453e655490
29dd196b7d66b626d4e778975c57bd0abf0ad67c
refs/heads/master
<repo_name>phoenixmmi/Pointers<file_sep>/Functions/Functions/main.cpp #include<iostream> using namespace std; int add(int a, int b); //Прототип функции (Function declaration - объявление функции). int sub(int a, int b); int mul(int a, int b); double div_(int a, int b); void main() { setlocale(LC_ALL, ""); int a = 2; int b = 3; int c = add(a, b); //Вызов (использование) функции - Function call. cout << a << " + " << b << " = " << c << endl;; cout << sub(8, 3) << endl; cout << mul(5, 3) << endl; cout << div_(5, 2) << endl; cout << add(123, 456) << endl; } int add(int a, int b) //Реализация функции (Function definition - Определение функции) { int c = a + b; return c; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { //умножение return a * b; } double div_(int a, int b) { //деление double c = (double)a / b; return c; } /* Function doesn't take N arguments too few arguments in function call - если мы передали меньше переметров, чем функция принимает; too many arguments in function call - (LNK - Link) UNRESOLVED EXTERNAL SYMBOL FOUND */<file_sep>/Functions/Arrays/main.cpp #include<iostream> using namespace std; #define DELIMITER "\n---------------------------------------------------\n" const int ROWS = 4; //Количество строк двумерного массива const int COLS = 5; //Количество элементов строки void FillRand(int Arr[], const int n); void FillRand(double Arr[], const int n); void FillRand(int Arr[ROWS][COLS], const int ROWS, const int COLS); void Print(int Arr[], const int n); void Print(double Arr[], const int n); void Print(int Arr[ROWS][COLS], const int ROWS, const int COLS); void Sort(int Arr[], const int n); void Sort(int Arr[ROWS][COLS], const int ROWS, const int COLS); int Sum(int Arr[], const int n); double Avg(int Arr[], const int n); int minValueIn(int Arr[], const int n); void main() { setlocale(LC_ALL, ""); const int n = 5; int Arr[n]; FillRand(Arr, n); Print(Arr, n); cout << "Сумма элементов масива:\t" << Sum(Arr, n) << endl; cout << "Среднее арифметическое:\t" << Avg(Arr, n) << endl; //cout << "Минимальное значение в массиве:\t" << minValueIn(Arr, n) << endl; double Brr[n]; FillRand(Brr, n); Print(Brr, n); int Crr[ROWS][COLS]; FillRand(Crr, ROWS, COLS); Print(Crr, ROWS, COLS); Sort(Crr, ROWS, COLS); cout << DELIMITER << endl; Print(Crr, ROWS, COLS); double Drr[ROWS][COLS]; //FillRand(Drr, ROWS, COLS); } void FillRand(int Arr[], const int n) { //Заполнение случайными числами: for (int i = 0; i < n; i++) { Arr[i] = rand() % 100; } } void FillRand(double Arr[], const int n) { //Заполнение случайными числами: for (int i = 0; i < n; i++) { Arr[i] = rand() % 10000; Arr[i] /= 100; } } void FillRand(int Arr[ROWS][COLS], const int ROWS, const int COLS) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { Arr[i][j] = rand() % 100; } } } void Print(int Arr[], const int n) { //Вывод массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << "\t"; } cout << endl; } void Print(double Arr[], const int n) { //Вывод массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << "\t"; } cout << endl; } void Print(int Arr[ROWS][COLS], const int ROWS, const int COLS) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { cout << Arr[i][j] << "\t"; } cout << endl; } } void Sort(int Arr[], const int n) { //Сортировка массива: for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (Arr[j] < Arr[i]) { int buffer = Arr[i]; Arr[i] = Arr[j]; Arr[j] = buffer; } } } } void Sort(int Arr[ROWS][COLS], const int ROWS, const int COLS) { int iterations = 0; for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { for (int k = i; k < ROWS; k++) { //int l; //if (k == i) l = j + 1;else l = 0; //(k == i)?l = j + 1 : l = 0; //l = (k == i) ? j + 1 : 0; cout << typeid(k == i ? j + 1 : 0.).name() << endl; for (int l = k == i ? j + 1 : 0.; l < COLS; l++) { if (Arr[k][l] < Arr[i][j]) { int buffer = Arr[i][j]; Arr[i][j] = Arr[k][l]; Arr[k][l] = buffer; } iterations++; } } } } cout << "Массив отсортирован за " << iterations << " итераций\n"; } int Sum(int Arr[], const int n) { int Sum = 0; for (int i = 0; i < n; i++) { Sum += Arr[i]; } return Sum; } double Avg(int Arr[], const int n) { return (double)Sum(Arr, n) / n; } //int minValueIn(int Arr[], const int n) //{ // int min = Arr[0]; // //} //Repository /* template<typename T> template (шаблон) */<file_sep>/Pointers/DynamicMemory/main.cpp #include<iostream> #include<ctime> using namespace std; void main() { setlocale(LC_ALL, ""); /* setlocale(LC_ALL, ""); int n;// Размер массива cout << "Введите размер массива: "; cin >> n; double *Arr = new double[n]; for (int i = 0; i < n; i++) { // Арифметика указателей и оператор разыменования: *(Arr + i) = rand() % 100; } for (int i = 0; i < n; i++) { //[]- Оператор индексирования (subscript operator) cout << Arr[i] << "\t"; } cout << endl; cout << Arr << endl; delete[] Arr; cout << Arr << endl;*/ const int n = 10; int arr[n]; srand(time(NULL)); for (int i = 0; i < n; i++) { cout << (arr[i] = rand() % 10) << "\t"; } cout << endl; //Вычислим количество четных и нечетных значений в исходном массиве: int n_even = 0; // Количество четных элементов. int n_odd = 0; // Количество нечетных элементов. for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { n_even++; } else { n_odd++; } } cout << "Количество четных элементов: " << n_even << endl; cout << "Количество нечетных элементов: " << n_odd << endl; //Выделяем память для четных и нечетных значений: int* even_values = new int[n_even]; int* odd_values = new int[n_odd]; for (int i = 0, j = 0, k = 0; i < n; i++) { if (arr[i] % 2 == 0) { even_values[j++] = arr[i]; } else { odd_values[k++] = arr[i]; } } for (int i = 0; i < n_even; i++) { cout << even_values[i] << "\t"; } cout << endl; for (int i = 0; i < n_odd; i++) { cout << odd_values[i] << "\t"; } cout << endl; }<file_sep>/NullTerminatedLines/Files/main.cpp #include <iostream> #include <fstream> //#define WRITE_TO_FILE //#define READ_TO_FILE //#define SWAPING #define VAR_OF_TEACHER //#define MY_VAR //#define NAME //#define SIZE void main() { setlocale(LC_ALL, ""); #ifdef NAME const int n = 256; char name[n] = {}; std::cout << "Введите имя файла: " << std::endl; std::cin >> name; if (!strstr(name, ".txt")) { strcat(name, ".txt"); } #ifdef WRITE_TO_FILE std::cout << "Hello World"; std::ofstream fout; // создание потока fout.open(name, std::ios::app); // app- дозапись строки . fout << "<NAME>" << std::endl; /*fout.open("AnotherFile.txt"); fout << "<NAME>";*/ fout.close(); system(name); #endif #endif #ifdef READ_TO_FILE std::ifstream fin;// создание потока. fin.open("File.txt"); const int n = 256; char sz_buffer[n] = {}; char string1[n] = {}; char string2[n] = {}; while (!fin.eof()) { fin.getline(sz_buffer, n); std::cout << sz_buffer << std::endl; } fin.close(); #endif #ifdef SWAPING std::ofstream fout("final.txt"); std::ifstream fin;// создание потока. fin.open("File.txt"); const int n = 256; char string_mac[n] = {}; char string_ip[n] = {}; while (!fin.eof()) { fin >> string_mac; fin >> string_ip; std::cout << string_ip << "\t" << string_mac << std::endl; fout << string_ip << "\t" << string_mac << std::endl; } fin.close(); fout.close(); system("notepad Final.txt"); #endif #ifdef VAR_OF_TEACHER const int n = 256; char source_file_name[n]{}; char dest_file_name[n]{}; std::cout << "Введите имя исходного файла: "; std::cin >> source_file_name; std::cout << "Введите имя конечного файла: "; std::cin >> dest_file_name; if(!strstr(source_file_name, ".txt"))strcat(source_file_name, ".txt"); if(!strstr(dest_file_name, ".txt"))strcat(dest_file_name,".txt"); std::ifstream fin(source_file_name); std::ofstream fout(dest_file_name); char mac_buffer[n]{}; char ip_buffer[n]{}; if (fin.is_open()) { for (int i = 1; !fin.eof(); i++) { fin >> mac_buffer >> ip_buffer; fout << "host- " << i << std::endl; fout << "{\n"; fout << "\thardware - ethernet\t" << mac_buffer << ";\n"; fout << "\tfixed-address\t" << ip_buffer << ";\n"; fout << "}\n"; std::cout << "host- " << i << std::endl; std::cout << "{\n"; std::cout << "\thardware - ethernet\t" << mac_buffer << ";\n"; std::cout << "\tfixed-address\t" << ip_buffer << ";\n"; std::cout << "}\n"; } } fin.close(); fout.close(); char command[n] = "notepad "; strcat(command, dest_file_name); system(command); #endif #ifdef MY_VAR std::ofstream fout("404result.txt"); std::ifstream fin;// создание потока. fin.open("File.txt"); const int n = 256; char sz_buffer [n] = {}; int p = 1; while (!fin.eof()) { fin.getline(sz_buffer, n); int i = 0; fout << "host 404-" << p++; fout << "\n{\n"; fout << "\t\t hardware ethernet \t\t"; do { fout << sz_buffer[i]; i++; } while (sz_buffer[i] != '\t'); fout << ";\n"; fout << "\t\t fixed - address \t\t"; while (sz_buffer[i] == '\t') { i++; }; do { fout << sz_buffer[i]; i++; } while (sz_buffer[i] != 0); fout << ";\n"; fout <<"}\n\n"; } system("PAUSE"); fin.close(); fout.close(); system("notepad 404result.txt"); #endif #ifdef SIZE std::ifstream fin;// создание потока. fin.open("File.txt"); int size = 0; file.seekg(0, std::ios::end); size = file.tellg(); std::cout << "Файл весит : " << size << " байт" << std::endl; file.close(); #endif }<file_sep>/Arrays/ReadMe.txt TODO: Отсортировать массив в порядке возрастания. DONE: Доделать Hardcore. DONE: Заполнить массив уникальными случайными числами. DONE: 1. Зарегистрироваться на github.com; 2. Выполнить сортировку массива, по рассмотренному алгоритму. https://github.com/okovtun/ST_ITV_35<file_sep>/Arrays/HomeWork/main.cpp #include<iostream> using namespace std; #define FIRST_CONNER (char)214 #define SECOND_CONNER (char)191 #define THIRD_CONNER (char)200 #define FORTH_CONNER (char)190 #define HORIZONTAL_LINE_UPPER (char)196 #define HORIZONTAL_LINE_LOWER (char)205 #define VERTICAL_LINE_LEFT (char)186 #define VERTICAL_LINE_RIGHT (char)179 #define BOX (char)219 void main() { setlocale(LC_ALL, "Russian"); int n; cout << "¬ведите размер доски: "; cin >> n; //n++; //setlocale(LC_ALL, "C"); //for (int i = 0; i <=n; i++) //{ // /*if (i == 0) // { // cout << FIRST_CONNER; // for (int j = 0; j < n; j++) // { // cout << HORIZONTAL_LINE<< HORIZONTAL_LINE; // } // cout << SECOND_CONNER << endl; // } // cout << VERTICAL_LINE; // if (i % 2 == 0) // { // for (int j = 0; j < n; j++) // { // cout <<BOX<< " "; // } // } // else // { // for (int j = 0; j < n; j++) // { // cout << " "<<BOX; // } // } // // cout << VERTICAL_LINE << endl; // if (i == n-1) // { // cout << THIRD_CONNER; // for (int j = 0; j < n; j++) // { // cout << HORIZONTAL_LINE<<HORIZONTAL_LINE; // } // cout << FORTH_CONNER << endl; // }*/ // for (int j = 0; j <= n; j++) // { // if (i == 0 && j == 0)cout << FIRST_CONNER; // else if (i == 0 && j == n)cout << SECOND_CONNER; // else if (i == n && j == 0)cout << THIRD_CONNER; // else if (i == n && j == n)cout << FORTH_CONNER; // else if (i == 0) cout << HORIZONTAL_LINE_UPPER<<HORIZONTAL_LINE_UPPER; // else if (i == n) cout << HORIZONTAL_LINE_LOWER<<HORIZONTAL_LINE_LOWER; // else if (j == 0 )cout << VERTICAL_LINE_LEFT; // else if (j == n)cout << VERTICAL_LINE_RIGHT; // else if ((i+j)%2==0)cout << BOX<<BOX; // else cout << " "; // } // cout << endl; //} for (int a = 0; a < n; a++) { if (a % 2 == 0) { for (int b = 0; b < n; b++) { for (int i = 0; i < n; i++) { if (i % 2 == 0) { for (int j = 0; j < n; j++) { cout << "* "; } } else { for (int j = 0; j < n; j++) { cout << " "; } } } cout << endl; } } else { for (int b = 0; b < n; b++) { for (int i = 0; i < n; i++) { if (i % 2 == 0) { for (int j = 0; j < n; j++) { cout << " "; } } else { for (int j = 0; j < n; j++) { cout << "* "; } } } cout << endl; } } } }<file_sep>/Arrays/Arrays/main.cpp #include<iostream> using namespace std; #define tab "\t" //const char tab = '\t'; void main() { setlocale(LC_ALL, ""); const int n = 5; int Arr[n] = { 3, 5, 8, 13, 21 }; //Ввод элементов массива: /*cout << "Введите элементы массива: "; for (int i = 0; i < 10; i++) { cin >> Arr[i]; }*/ // Вывод массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << "\t"; } cout << endl; // Вывод массива на экран в обратном порядке: for (int i = n - 1; i >= 0; i--) { cout << Arr[i] << "\t"; } cout << endl; // Подсчет суммы элементов массива: int sum = 0; for (int i = 0; i < n; i++) { sum += Arr[i]; } cout << "Сумма элементов массива: " << sum << endl; cout << "Среднее арифметическое: " << (double)sum / n << endl; // Поиск минимального и максимального значения: int min, max; min = max = Arr[0]; for (int i = 0; i < n; i++) { if (Arr[i] < min)min = Arr[i]; if (Arr[i] > max)max = Arr[i]; } cout << "Минимальное значение в массиве: " << min << endl; cout << "Максимальное значение в массиве: " << max << endl; cout << "\n-------------------------------\n"; int Brr[] = { 3, 5, 8, 13, 21, 34, 55, 89 }; for (int i = 0; i < sizeof(Brr)/sizeof(int); i++) { cout << Brr[i] << tab; } cout << endl; }<file_sep>/NullTerminatedLines/numericSystems/main.cpp #include <iostream> char* dec_to_bin(int dec); int bin_to_dec(char* binary); bool isBin(char str[]); bool is_hex_number(const char* str); int hex_to_dec(const char* hex); void main() { setlocale(LC_ALL, ""); /*int dec; cout << "Введите десятичное число: "; cin >> dec; char* binary = dec_to_bin(dec); cout << binary << endl; cout << "My binary " << binary << endl;*/ /* const int n = 33; char* binary = new char[n] {}; cout << "Введите двоичное число: "; cin >> binary; cout << isBin(binary) << endl; cout << bin_to_dec(binary) << endl; delete[]binary; */ const int n = 11; char hex[n]{}; std::cout << "Введите hex число: "; std::cin >> hex; std::cout << is_hex_number(hex) << std::endl; std::cout << hex_to_dec(hex) << std::endl; } char* dec_to_bin(int dec) { int n = 32; char* binary = new char[n] {}; for (int i = 0; dec; i++, dec /= 2)binary[i] = dec % 2 + 48; n = strlen(binary); for (int i = 0; i < n / 2; i++)std::swap(binary[i], binary[n - 1 - i]); /*for (n--; n >= 0; n--) { cout << binary[n]; if (n % 8 == 0)cout << " "; if (n % 4 == 0)cout << " "; }*/ std::cout << std::endl; return binary; } bool isBin(char str[]) { for (int i = 0; str[i]; i++) { if (str[i] != '0' && str[i] != '1') return false; } return true; } int bin_to_dec(char* binary) { int dec = 0; int pow = 1; for (int i = strlen(binary) - 1; i >= 0; i--) { if (binary[i] == '1')dec += pow; pow *= 2; } return dec; //var1 /*int sum = 0; int total=0; if (isBin(binary)) { for (int i = strlen(binary); i >= 0; i--) { if (binary[i] == '1')sum += total; if (total == 0)total = 1; else total *= 2; } } return sum; */ } bool is_hex_number(const char* str) { int i = 0; if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))i = 2; if (i == 2 && str[2] == 0)return false; for (; str[i]; i++) { if ( !(str[i] >= '0' && str[i] <= '9') && !(str[i] >= 'a' && str[i] <= 'f') && !(str[i] >= 'A' && str[i] <= 'F') ) return false; } return true; } int hex_to_dec(const char* hex) { if (!is_hex_number(hex))return 0; int decimal = 0;// десятичное число( конечный результат) int power = 1;// весовой коеффициент разряда(16^i) for (int i = hex[1] == 'x' || hex[1] == 'X' ? 2 : 0; hex[i]; i++) { decimal *= 16; if (hex[i] >= '0' && hex[i] <= '9')decimal += hex[i] - '0'; else if (hex[i] >= 'A' && hex[i] <= 'F')decimal += hex[i] - 'A' + 10; else if (hex[i] >= 'a' && hex[i] <= 'f')decimal += hex[i] - 'a' + 10; else throw 0; } return decimal; }<file_sep>/Arrays/Random/main.cpp #include<iostream> using namespace std; //Генерация случайных чисел. const char tab = '\t'; void main() { setlocale(LC_ALL, ""); const int n = 5; int Arr[n]; int minRand; //Минимально возможное случайное число. int maxRand; //Максимально возможное случайное число. do { system("CLS"); cout << "Введите минимально возможное случайное число: "; cin >> minRand; cout << "Введите максимально возможное случайное число: "; cin >> maxRand; if (minRand >= maxRand) { cout << "Error: user lox V_o_O_v" << endl; system("PAUSE"); } } while (minRand >= maxRand); // Заполнение массива случайными числами: for (int i = 0; i < n; i++) { Arr[i] = rand() % (maxRand - minRand) + minRand; } //Вывод исходного массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << tab; } cout << endl; //Сортировка: int iterations = 0; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { iterations++; if (Arr[j] < Arr[i]) { int buffer = Arr[i]; Arr[i] = Arr[j]; Arr[j] = buffer; } } } //Вывод отсортированного массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << tab; } cout << endl; cout << "Массив отсортирован за " << iterations << " итераций" << endl; }<file_sep>/Arrays/SimpleNumbers/main.cpp //Выводит на экран ряд простых чисел до введенного с клавиатуры. #include<iostream> using namespace std; void main() { setlocale(LC_ALL, ""); int n; cout << "Введите число: "; cin >> n; bool simple;//??? for (int i = 0; i <= n; i++) { simple = true;//Предположим что число простое, но это нужно проветрить. for (int j = 2; j < i; j++) { if (i%j == 0) { simple = false; break; } } if (simple) //Если число простое, то выводим его на экран. { cout << i << "\t"; } } cout << endl; }<file_sep>/Functions/ReadMe.txt 1. Вместо цифр, в соответствующие клетки должны ставиться X или 0; 2. Написать функцию Check, которая проверяет выиграшные комбинации. <file_sep>/Pointers/DynamicMemory3/main.cpp #include<iostream> #include<ctime> using std::cin; using std::cout; using std::endl; void FillRand(int**arr, const int m, const int n); void Print(int**arr, const int m, const int n); int** push_row_back(int** arr, int& m, const int n); int** push_row_front(int** arr, int& m, const int n); int** insert(int** arr, int& m, const int n, int index); int** pop_row_back(int** arr, int& m, const int n); int** pop_row_front(int** arr, int& m, const int n); int** erase(int** arr, int& m, const int n, int index); void main() { setlocale(LC_ALL, ""); int m;//количество строк int n;//количество элементов в строке int index; cout << "¬ведите количество строк: "; cin >> m; cout << "¬ведите количество элементов в строке: "; cin >> n; //ќбъ€вление двумерного массива int** arr = new int*[m]; for (int i = 0; i < m; i++) { arr[i] = new int[n] {}; } /////////////////////////////////////////////////////////// FillRand(arr, m, n); Print(arr, m, n); arr = push_row_back(arr, m, n); Print(arr, m, n); arr = push_row_front(arr, m, n); Print(arr, m, n); cout << "¬ведите куда хотите добавить новую строку : "; cin >> index; arr = insert(arr, m, n, index); arr = pop_row_back(arr, m, n); Print(arr, m, n); arr = pop_row_front(arr, m, n); Print(arr, m, n); cout << "¬ведите откуда хотите удалить строку : "; cin >> index; arr = erase(arr, m, n, index); Print(arr, m, n); ////////////////////////////////////////////////////////// for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << "\t"; } cout << endl; } ////////////////////////////////////////////////////////// //”даление двумерного динамического массива for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; } void FillRand(int**arr, const int m, const int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { arr[i][j] = rand() % 100; } } } void Print(int**arr, const int m, const int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << "\t"; } cout << endl; } cout << endl; } int** push_row_back(int** arr, int& m, const int n) { //1)создаем буфферный массив указателей int** buffer = new int*[m + 1]; //2)копируем адреса строк из исходного массива в буферный: for (int i = 0; i < n; i++)buffer[i] = arr[i]; delete[]arr; arr = buffer; arr[m] = new int[n] {}; m++; return arr; } int** push_row_front(int** arr, int& m, const int n) { int** buffer = new int*[m + 1]; for (int i = 0; i < n; i++)buffer[i + 1] = arr[i]; delete[] arr; arr = buffer; arr[0] = new int[n] {}; return arr; /*int** buf = new int*[m + 1]{}; for (int i = 0; i < m + 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { buf[i + 1][j] = arr[i][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; arr[0] = new int [n] {}; m++; return arr;*/ } int** insert(int** arr, int& m, const int n, int index) { if (index > m)return arr; int** buf = new int*[m + 1]{}; for (int i = 0; i < m + 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < index; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i][j]; } } for (int i = index; i < m; i++) { for (int j = 0; j < n; j++) { buf[i + 1][j] = arr[i][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; arr[index] = new int [n] {}; m++; return arr; } int** pop_row_back(int** arr, int& m, const int n) { int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; m--; return arr; } int** pop_row_front(int** arr, int& m, const int n) { int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i + 1][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; m--; return arr; } int** erase(int** arr, int& m, const int n, int index) { if (index > m)return arr; int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < index; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i][j]; } } for (int i = index; i < m - 1; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i + 1][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; m--; return arr; } <file_sep>/Pointers/Pointers/main.cpp #include<iostream> using namespace std; //#define POINTERS_BASICS //#define DECLARATION_OF_POINTERS #define POINTERS_AND_ARRAYS void main() { setlocale(LC_ALL, ""); #ifdef POINTERS_BASICS int a = 2; int *pa = &a;//Венгерской нотации //pa - pointer to a. //& - оператор взятия адреса (Address-of operator) cout << a << endl; cout << &a << endl; cout << pa << endl; cout << *pa << endl; //* - Оператор разыменования (Dereference operator). //* int *pb; int b = 3; pb = &b; b;//(int) pb;//(int*) cout << pb << endl; cout << *pb << endl; //int - int //int* - указатель на int. //double - double. //double* - указатель на double. #endif // POINTERS_BASICS #ifdef DECLARATION_OF_POINTERS int a, b, c; //Объявление трех переменных одним выражением. int *pa, *pb, *pc; //Объявление трех указателей одним выражением. int* pd, pe, pf; //Объявится один указатель на int (pd), //и две переменные типа int (pe и pf). #endif const int n = 5; short Arr[n] = { 3, 5, 8, 13, 21 }; cout << *Arr << endl; for (int i = 0; i < n; i++) { cout << *(Arr + i) << "\t"; } cout << endl; //+, -, ++, --; } /* type function(parameter1, parameter2, ...) { } 1. 2. NUll, INT_MAX, int(), ... */<file_sep>/Pointers/DynamicMemory2/main.cpp #include<iostream> using namespace std; using std::cout; using std::cin; using std::endl; //#define DymanicMemory1 void FillRand(int** Arr, const int m, const int n); void print(int arr[], const int n); void Print(int** arr, const int m, const int n); int* push_back(int arr[], int& n, int value); int* push_front(int* arr,int& n,int value); int* insert(int* arr, int& n, int value, int index); int* pop_back(int* arr, int& n); int* pop_front(int* arr, int& n); int* erase(int* arr, int& n,int index); int** push_row_back(int** arr, int& m, const int n); int** push_row_front(int** arr, int& m, const int n); int** insert(int** arr, int& m, const int n, int index); int** pop_row_back(int** arr, int& m, const int n); int** pop_row_front(int** arr, int& m, const int n); int** erase(int** arr, int& m, const int n, int index); int** push_col_back(int** arr,const int m, int& n); void push_col_front(int** arr, const int m, int& n); int** insert_col(int** arr, const int m, int& n, int index); int** pop_col_back(int** arr, const int m, int& n); int** pop_col_front(int** arr, const int m, int& n); int** erase_col(int** arr, const int m, int& n, int index); int** allocate(const int m, const int n); void clear(int** arr, const int m); void main() { setlocale(LC_ALL, ""); #ifdef DymanicMemory1 /* //Добавление элементов в конец массива: //1)Создаём буфферный массив, размером на один элемент больше: int* buffer = new int[n + 1]; //2)Копируем содержимое исходного массива в буфферный: for (int i= 0; i < n; i++) { buffer[i] = arr[i]; } //3)Удаляем исходный массив из памяти: delete[] arr; //4) В указатель исходного массива записываем адресс нового массива: arr = buffer; arr[n] = value; n++; /////////////////// print(arr, n);*/ int n; cout << "Введите размер массива: "; cin >> n; int *arr = new int[n]; for (int i = 0; i < n; i++) cout << (arr[i] = rand() % 100) << "\t"; cout << endl; arr = push_back(arr, n, value); print(arr, n); cout << "Введите добавлямое значение: "; cin >> value; arr = push_front(arr, n, value); print(arr, n); int index; cout << "Введите добавлямое значение: "; cin >> value; int* old = arr; do { cout << "Введите индекс добавляемого значения"; cin >> index; } while (old == (arr = insert(arr, n, value, index))); arr = insert(arr, n, value,index); print(arr, n); arr = pop_back(arr, n); print(arr, n); arr = pop_front(arr, n); print(arr, n); int index; cout << "Введите индекс:"; cin >> index; arr = erase(arr, n, index); print(arr, n); delete[] arr; #endif int m;//количество строк int n;//количество элементов в строке int index; cout << "Введите количество строк: "; cin >> m; cout << "Введите количество элементов в строке: "; cin >> n; //Объявление двумерного массива int** arr = allocate(m, n); /////////////////////////////////////////////////////////// //Заполнение массива: FillRand(arr, m, n); Print(arr, m, n); cout << "Добавление строки в конец массива: " << endl; arr = push_row_back(arr, m, n); Print(arr, m, n); cout << "Добавление строки в начало массива: " << endl; arr = push_row_front(arr, m, n); Print(arr, m, n); cout << "Введите куда хотите добавить новую строку : "; cin >> index; arr = insert(arr, m, n, index); Print(arr, m, n); cout << "Удаление последней строки: " << endl; arr = pop_row_back(arr, m, n); Print(arr, m, n); cout << "Удаление первой строки: " << endl; arr = pop_row_front(arr, m, n); Print(arr, m, n); cout << "Введите откуда хотите удалить строку : "; cin >> index; arr = erase(arr, m, n, index); Print(arr, m, n); cout << "Добавление столбца в конце массива: " << endl; arr = push_col_back(arr, m, n); Print(arr, m, n); cout << "Добавление столбца в начало массива: " << endl; push_col_front(arr, m, n); Print(arr, m, n); cout << "Добавление столбца в массив: " << endl; cout << "Введите индекс: "; cin >> index; arr = insert_col(arr, m, n, index); Print(arr, m, n); cout << "Удаление последнего столбца:"<< endl; arr = pop_col_back(arr, m, n); Print(arr, m, n); cout << "Удаление первого столбца:" << endl; arr = pop_col_front(arr, m, n); Print(arr, m, n); cout << "Удаление столбца по индексу:" << endl; cout << "Введите индекс"; cin >> index; arr = erase_col(arr, m, n, index); Print(arr, m, n); //удаление массива. clear(arr,m); } int** allocate(const int m, const int n) { int** arr = new int*[m]; for (int i = 0; i < m; i++) { arr[i] = new int[n] {}; } return arr; } void FillRand(int** Arr, const int m, const int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { Arr[i][j] = rand() % 100; } } } void print(int arr[], const int n) { for (int i = 0; i < n; i++) { cout << arr[i] << "\t"; } cout << endl; } void Print(int ** arr, const int m, const int n) { for (int i = 0; i < m; i++) { for ( int j = 0; j < n; j++) { cout << arr[i][j] << "\t"; } cout << endl; } cout << endl; } int* push_back(int arr[], int& n, int value) { //Добавляет элемент в конец. int* buffer = new int[n + 1]; for (int i = 0; i < n; i++) { buffer[i] = arr[i];//копируем элементы СООТВЕТСТВЕННО. } delete[] arr; arr = buffer; arr[n] = value; n++; return arr; } int* push_front(int* arr, int& n, int value) { //Добавляет элемент в начало. int* buffer = new int[n + 1]{}; for (int i = 0; i < n; i++) { buffer[i+1] = arr[i]; // Копируем элементы со смещением на 1 один элемент вправо. } delete[] arr; arr = buffer; arr[0] = value; n++; return arr; } int* insert(int* arr, int& n, int value, int index) { //Добавляет элемент в определенное место. if (index > n)return arr; int* buffer = new int[n + 1]{}; for (int i = 0; i < index; i++) buffer[i] = arr[i]; for (int i = index; i < n; i++) buffer[i + 1] = arr[i]; delete[] arr; arr = buffer; arr[index] = value; n++; return arr; } int* pop_back(int* arr, int& n) { //удаляет последний элемент. int* buffer = new int[n - 1]; for (int i = 0; i < n-1; i++) { buffer[i] = arr[i]; } delete[] arr; arr = buffer; n--; return arr; } int* pop_front(int* arr, int& n) { //Удаляет первый элемент. int* buffer = new int[n - 1]; for (int i = 0;i < n-1; i++) { buffer[i] = arr[i+1]; } delete[] arr; arr = buffer; n--; return arr; } int* erase(int* arr, int& n,int index) { int* buffer = new int[n - 1]; for (int i = 0; i < index; i++) { buffer[i] = arr[i]; } for (int i = index; i < n; i++) { buffer[i] = arr[i+1]; } delete[] arr; arr = buffer; n--; return arr; } int** push_row_back(int** arr, int& m, const int n) { //1)создаем буфферный массив указателей int** buffer = new int*[m + 1]; //2)копируем адреса строк из исходного массива в буферный: for (int i = 0; i < m; i++)buffer[i] = arr[i]; delete[]arr; arr = buffer; arr[m] = new int[n] {}; m++; return arr; /*int** buffer = new int*[m + 1]; for (int i = 0; i < m; i++) { buffer[i] = new int[n] {}; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { buffer[i][j] = arr[i][j]; } } for (int i = 0; i < n; i++) { delete[] arr[i]; } delete[] arr; arr = buffer; arr[m] = new int[n] {}; m++; return arr;*/ } int** push_row_front(int** arr, int& m, const int n) { int** buffer = new int*[m + 1]; for (int i = 0; i < n; i++)buffer[i + 1] = arr[i]; delete[] arr; arr = buffer; arr[0] = new int[n] {}; return arr; /*int** buf = new int*[m + 1]{}; for (int i = 0; i < m + 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { buf[i + 1][j] = arr[i][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; arr[0] = new int [n] {}; m++; return arr;*/ } int** insert(int** arr, int& m, const int n, int index) { /*if (index > m)return arr; int** buf = new int*[m + 1]{}; for (int i = 0; i < m + 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < index; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i][j]; } } for (int i = index; i < m; i++) { for (int j = 0; j < n; j++) { buf[i + 1][j] = arr[i][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; arr[index] = new int [n] {}; m++; return arr;*/ if (index > m)return arr; int** buf = new int*[m + 1]{}; for (int i = 0; i < index; i++) { buf[i] = arr[i]; } for (int i = index; i < m; i++) { buf[i + 1] = arr[i]; } delete[] arr; arr = buf; arr[index] = new int [n] {}; m++; return arr; } int** pop_row_back(int** arr, int& m, const int n) { int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = arr[i]; } delete[]arr; arr = buf; m--; return arr; /*int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; m--; return arr; }*/ } int** pop_row_front(int** arr, int& m, const int n) { int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = arr[i+1]; } delete[] arr; arr = buf; m--; return arr; /*int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i + 1][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; m--; return arr;*/ } int** erase(int** arr, int& m, const int n, int index) { if (index > m)return arr; int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { if (i < index) buf[i] = arr[i]; else buf[i] = arr[i+1]; } delete[] arr; arr = buf; m--; return arr; /*if (index > m)return arr; int** buf = new int*[m - 1]{}; for (int i = 0; i < m - 1; i++) { buf[i] = new int[n] {}; } for (int i = 0; i < index; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i][j]; } } for (int i = index; i < m - 1; i++) { for (int j = 0; j < n; j++) { buf[i][j] = arr[i + 1][j]; } } for (int i = 0; i < m; i++) { delete[] arr[i]; } delete[] arr; arr = buf; m--; return arr;*/ } int** push_col_back(int** arr, const int m, int& n) { for (int i = 0; i < m; i++) { int* buf = new int[n + 1]{}; for (int j = 0; j < n; j++) { buf[j] = arr[i][j]; } delete[] arr[i]; arr[i] = buf; } n++; return arr; } void push_col_front(int** arr, const int m, int& n) { for (int i = 0; i < m; i++) { int* buf = new int[n + 1]{}; for (int j = 0; j < n; j++) { buf[j+1] = arr[i][j]; } delete[] arr[i]; arr[i] = buf; } n++; } int** insert_col(int** arr, const int m, int& n, int index) { for (int i = 0; i < m; i++) { int* buf = new int[n + 1]{}; for (int j = 0; j < index; j++) { buf[j] = arr[i][j]; } for (int j = index; j < n + 1; j++) { buf[j+1] = arr[i][j]; } delete[] arr[i]; arr[i] = buf; } n++; return arr; } int** pop_col_back(int** arr, const int m, int& n) { for (int i = 0; i < m; i++) { int* buf = new int[n - 1]; for (int j = 0; j < n - 1; j++) { buf[j] = arr[i][j]; } delete[] arr[i]; arr[i] = buf; } n--; return arr; } int** pop_col_front(int** arr, const int m, int& n) { for (int i = 0; i < m; i++) { int* buf = new int[n - 1]; for (int j = 0; j < n; j++) { buf[j] = arr[i][j + 1]; } delete[] arr[i]; arr[i] = buf; } n--; return arr; } int** erase_col(int** arr, const int m, int& n, int index) { for (int i = 0; i < m; i++) { int* buf = new int[n - 1]{}; for (int j = 0; j < index; j++) { buf[j] = arr[i][j]; } for (int j = index; j < n; j++) { buf[j] = arr[i][j + 1]; } delete[] arr[i]; arr[i] = buf; } n--; return arr; } void clear(int** arr, const int m) { for (int i= 0; i < m; i++) { delete[] arr; } delete[] arr; } <file_sep>/Pointers/TransferParameters/main.cpp #include<iostream> using namespace std; //#define BY_POINTER #define BY_REFERENCE #ifdef BY_POINTER //void Exchange(int* a, int* b); //void ExchangeWithout(int* a, int* b); template <typename T>void ExchangeXOR(T* a, T* b); #endif #ifdef BY_REFERENCE void Exchange(int& a, int& b); #endif void main() { int a = 7; int b = -10; cout << a << "\t" << b << endl; Exchange(a, b); cout << a << "\t" << b << endl; //ExchangeWithout(&a, &b); } #ifdef BY_POINTER template <typename T> void ExchangeXOR(T* a, T* b) { *a ^= *b; *b ^= *a; *a ^= *b; } /* void Exchange(int* a, int* b) { int buffer = *a; *a = *b; *b = buffer; } */ //void ExchangeWithout(int* a, int* b) //{ // cout << *a << " " << *b << endl; // *a = *a + *b; // 5 + 7 = 12 (a == 12) // *b = *a - *b; // 12 - 7 = 5 ( b == 5) // *a = *a - *b; // 12 - 5 = 7 ( a = 7) // cout << *a << " " << *b << endl; //} #endif #ifdef BY_REFERENCE void Exchange(int& a, int& b) { int buffer = a; a = b; b = buffer; } #endif<file_sep>/Arrays/Shift/main.cpp #include<iostream> using namespace std; const char tab = '\t'; void main() { setlocale(LC_ALL, ""); const int n = 10; int Arr[n] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //Вывод исходного массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << tab; } cout << endl; //Сдвиг массива: int m; //количество сдвигов cout << "На сколько элементов сдвинуть массив: "; cin >> m; /*for (int i = 0; i < m; i++) { int buffer = Arr[0]; for (int i = 0; i < n; i++) { Arr[i] = Arr[i + 1]; } Arr[n - 1] = buffer; }*/ //Вывод сдвинутого массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << tab; } cout << endl; /////////////////////////////////////////////////////////////// int buffer = Arr[n - 1]; for (int i = n - 1; i >= 0; i--) { Arr[i] = Arr[i - 1]; } Arr[0] = buffer; //Вывод сдвинутого массива на экран: for (int i = 0; i < n; i++) { cout << Arr[i] << tab; } cout << endl; }<file_sep>/Functions/XO/main.cpp #include<iostream> #include<conio.h> using namespace std; #define HORIZ_OFFSET "\t\t\t\t\t\t" void PrintField(char Field[], const int n, char Player); void Move(char Field[], const int n, char Player); void Check(char Field[], const int n, char Player); void main() { setlocale(LC_ALL, "Rus"); const int SIZE = 9; char Field[SIZE] = {}; //Игровое поле PrintField(Field, SIZE, '0'); cout << "Еще разочек? (y || Y)"; if (_getch() == 'y')main(); } void PrintField(char Field[], const int n, char Player) { system("CLS"); cout << "\n\n\n\n\n\n\n"; for (int i = 6; i >= 0; i -= 3) { cout << HORIZ_OFFSET; for (int j = 0; j < 3; j++) { if (j == 0)cout << " "; cout << Field[i + j]; if (j != 2) cout << " | "; } cout << endl; cout << HORIZ_OFFSET; if (i != 0)cout << "--- --- ---" << endl; } Check(Field, n, Player); } void Move(char Field[], const int n, char Player) { char key; //cout << (int)key << endl; bool busy; bool miss; do { busy = false; do { miss = false; key = _getch(); if (key == 27)return; if (key < '1' || key > '9')miss = true; if (miss) cout << "Вы не попали в поле\a" << endl; } while (miss); if (Field[key - 49] == 0)Field[key - 49] = Player; else { cout << "Cell busy\a" << endl; busy = true; } } while (busy); /*if (Player == 'X')PrintField(Field, n, '0'); else PrintField(Field, n, 'X');*/ PrintField(Field, n, Player); } void Check(char Field[], const int n, char Player) { bool game_over = false; if (Field[0] == Field[4] && Field[4] == Field[8] && Field[8] != 0) game_over = true; else if (Field[2] == Field[4] && Field[4] == Field[6] && Field[6] != 0) game_over = true; else if (Field[0] == Field[1] && Field[1] == Field[2] && Field[2] != 0) game_over = true; else if (Field[3] == Field[4] && Field[4] == Field[5] && Field[5] != 0) game_over = true; else if (Field[6] == Field[7] && Field[7] == Field[8] && Field[8] != 0) game_over = true; else if (Field[0] == Field[3] && Field[3] == Field[6] && Field[6] != 0) game_over = true; else if (Field[1] == Field[4] && Field[4] == Field[7] && Field[7] != 0) game_over = true; else if (Field[2] == Field[5] && Field[5] == Field[8] && Field[8] != 0) game_over = true; if (game_over) { cout << "Player " << Player << " wins." << endl; return; } if(Player == 'X')Move(Field, n, '0'); else Move(Field, n, 'X'); }<file_sep>/NullTerminatedLines/NullTerminatedLines/main.cpp #include<iostream> #include<Windows.h> using namespace std; void InputLine(char str[], const int n); int StrLen(char str[]); void UpperCase(char str[]); void LowerCase(char str[]); void Capitalize(char str[]); void Shrink(char str[]); bool isPalindrome(char str[]); void RemoveSpaces(char str[]); bool isNumber(char str[]); int StrToInt(char str[]); int culk(char str[]); bool isBin(char str[]); int BinToDec(char str[]); void dec_to_bin(int dec); void main() { setlocale(LC_ALL, ""); //char str[] = {'H','e','l', 'l','o', '\0'}; //инициализация строки поэлементно. "\0" обозначает конец строки. /*char str[] = "Hello"; cout << str << endl; cout << sizeof(str)<< endl;// Размер строки. */ int a = 0; const int n = 200; char str[n]; cout << "Введите строку: "; //cin >> str; InputLine(str, n); //ввод строки cout << str << endl; StrLen(str); //считает количество символов cout << StrLen(str) << endl; /*UpperCase(str); // Переводит все в верхний регистр cout << str << endl; LowerCase(str); //переводит в нижний регистр cout << str << endl; Capitalize(str); //Преобразует все первые буквы слов в верхний регистр cout << str << endl; Shrink(str); //Убирает лишние пробелы cout << str << endl; cout << isPalindrome(str) << endl; //Определяет,является ли строка палиндромом- cout << isNumber(str) << endl; int num = StrToInt(str); cout << num << endl;*/ cout << isBin(str) << endl; int num = BinToDec(str); cout << num << endl; } void InputLine(char str[], const int n) { SetConsoleCP(1251); cin.getline(str, n); SetConsoleCP(866); } int StrLen(char str[]) { int i = 0; for (; str[i]; i++); return i; } void UpperCase(char str[])//Из нижнего регистра в верхний { for (int i = 0; str[i]; i++) { if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'а' && str[i] <= 'я')str[i] -= 32; } } void LowerCase(char str[]) { for (int i = 0; str[i]; i++) { if (str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'А' && str[i] <= 'Я')str[i] += 32; } } void Capitalize(char str[]) { LowerCase(str); if (str[0] >= 'a' && str[0] <= 'z' || str[0] >= 'а' && str[0] <= 'я')str[0] -= 32; for (int i = 0; str[i]; i++) { if ((str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'а' && str[i] <= 'я') && str[i - 1] == ' ')str[i] -= 32; } //мой вариант /* if (str[0] != 32)str[0] -= 32; for (int i = 0; str[i]; i++) { if (str[i] == 32) { if (str[i + 1] != 32) { str[i + 1] -= 32; } } }*/ } void Shrink(char str[]) { //вариант учителя for (int i = 0; str[i]; i++) { for (int i = 0; str[i]; i++) while (str[i] == ' '&& str[i + 1] == ' ') { for (int j = i + 1; str[i]; i++)str[i] = str[i + 1]; } } //другой вариант /*for (int i = 0; str[i]; i++) { if (str[i] == 32 && str[i+1]==32) { for (int j = i; str[i]; j++) { str[j] = str[j + 1]; i--; } } }*/ } bool isPalindrome(char str[]) { /*int n = StrLen(str); char* buffer = new char[n+1] {}; for (int i = 0; i < n; i++)buffer[i] = str[i]; LowerCase(buffer); RemoveSpaces(buffer); n = StrLen(buffer); for (int i = 0; i < n/2; i++) { if (buffer[i] != str[n - 1 - i])return false; } return true;*/ int n = StrLen(str); for (int i = 0; i < n / 2; i++) { if (str[i] == ' ')i++, n++; if (str[n - 1 - i] == ' ')n--; if (str[i] != str[n - 1 - i]) { if (str[i] + 32 != str[n - 1 - i] && str[i] != str[n - i - 1] + 32)return false; } } return true; } void RemoveSpaces(char str[]) { for (int i = 0; str[i]; i++) { while (str[i] == ' ') { for (int j = 0; str[j]; j++)str[j] = str[j + 1]; } } } bool isNumber(char str[]) { for (int i = 0; str[i]; i++) { if (!(str[i] > '0' && str[i] <= '9'))return false; } return true; } int StrToInt(char str[]) { int num = 0; if (isNumber(str)) { for (int i=0;str[i];i++) { num *= 10; num += str[i]-48; } } return num; } bool isBin(char str[]) { for (int i = 0; str[i]; i++) { if (str[i] != '0' && str[i] != '1') return false; } return true; } int BinToDec(char str[]) { int n = StrLen(str); int num = 0; int two = 1; if (isBin(str)) { for (int i = n - 1; i >= 0; i--) { } } /*for (int i = 0;str[0] ; i++) { num = str[i] * two; two *= 2; }*/ /* if (str[i] == str[0] && str[0] == '48') { num += 0 * 2 + 0; } else if (str[i] == str[0] && str[0] == '49') { num += 0 * 2 + 1; } if (!str[0]) { num = num * 2 + str[i]-48; }*/ return num; }<file_sep>/Pointers/ReadMe.txt Pointers http://www.cplusplus.com/doc/tutorial/pointers/ x86 - 4B address x86-64 - 8B address 0x00 - 1B 0x0000 - 2B 0x00000000 - 4B 0x00000000 00000000 - 8B 1 Byte = 8 bit; 1 kByte = 1024 B = 2^10 B; 1 MByte = 1024 kB = 2^20 B; 1 GByte = 1024 MB = 2^30 B; 1 TByte = 1024 GB = 2^40 B; 1 PByte = 1024 TB = 2^50 B; 1 EByte = 1024 PB = 2^60 B; 2^64 B = 2^60B*2^4 = 16*1EB = 16EB;<file_sep>/NullTerminatedLines/StandardStrFunctions/main.cpp #include<iostream> void main() { setlocale(LC_ALL, ""); const int n = 256; /*char str[n] = {}; std::cout << "Введите строку: "; std::cin.getline(str, n); std::cout << str << std::endl; std::cout << strlen(str) << std::endl; char buffer[n] = {}; strncpy(buffer, str,3); std::cout << buffer << std::endl; strcat() // выполняет конкатенацию строк. */ /*char str1[n] = "Hello"; char str2[n] = "World"; strncat(str1, str2, 4); std::cout << str1 << std::endl; */ const char* words[] = { "Hello", "World", "Computer", "C++", "Imagination" }; for (int i = 0; i < sizeof(words) / sizeof(const char*); i++) { std::cout << words[i] << std::endl; } std::cout << std::endl; for (int i = 0; i < sizeof(words) / sizeof(const char*); i++) { for (int j = i; j < sizeof(words) / sizeof(const char*); j++) { if (strcmp(words[i], words[j]) > 0)std::swap(words[i], words[j]); } } for (int i = 0; i < sizeof(words) / sizeof(const char*); i++) { std::cout << words[i] << std::endl; } std::cout << std::endl; }<file_sep>/ReadMe.txt https://github.com/okovtun/ST_ITV_35 Solution:Pointers 0. ВЫУЧИТЬ ТЕОРИЮ ПО УКАЗАТЕЛЯМ!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1. Функцию с произвольным числом параметров sum сделать шаблонной. 2. Поменять местами две переменные без использования третьей переменной.<file_sep>/Pointers/RandomNumberOfArguments/main.cpp #include<iostream> using namespace std; //First parameter - is number of arguments: //int sum(int n, int value, ...) //{ // int sum = 0; // for (int i = 0; i < n; i++) // { // sum += *(&value + i); // } // cout << sum << endl; // return sum; //} template<typename T>int sum(T value ...) { int sum = 0; int* p_value = &value; while (*p_value != 0) { sum += *p_value++; } return sum; } void main() { cout << sum(3, 5, 8, 13, 21, 34, 0) << endl; } <file_sep>/Arrays/Repeats/main.cpp #include<iostream> using namespace std; #define tab "\t" #define WITH_BOOL_VARIABLE //При помощи Булевой переменной //#define WO_BOOL_VARIABLE //Без Булевой переменной void main() { setlocale(LC_ALL, ""); const int n = 10; int Arr[n]; for (int i = 0; i < n; i++) { cout << (Arr[i] = rand() % 5) << tab; } cout << endl; #ifdef WITH_BOOL_VARIABLE for (int i = 0; i < n; i++) { int repeats = 1; bool met_before = false; for (int j = 0; j < i; j++) { if (Arr[i] == Arr[j]) { met_before = true; break; } } if (!met_before) { for (int j = i + 1; j < n; j++) { if (Arr[i] == Arr[j])repeats++; } if (repeats > 1) { cout << "Значение " << Arr[i] << " встречается " << repeats << " раз.\n"; } } } #endif #ifdef WO_BOOL_VARIABLE for (int i = 0; i < n; i++) { int repeats = 1; //Перебираем левую часть массива, относительно выбранного элемента: for (int j = 0; j < i; j++) { if (Arr[i] == Arr[j]) { repeats++; } } //Если repeats > 1, значит выбранное значение Arr[i] встречалось ранее, //значит мы с ним уже работали, а это значит, что мы уже вывели сколько раз //оно встречается. if (repeats > 1)continue; //Если repeats == 1, то мы видим это значение впервые, //и нужно посчитать сколько раз оно встречается. //Для этого, мы и перебираем правую часть массива, //относительно выбранного элемента: for (int j = i + 1; j < n; j++) { if (Arr[i] == Arr[j])repeats++; } if (repeats > 1) { cout << "Значение " << Arr[i] << " встречается " << repeats << " раз.\n"; } } #endif // WO_BOOL_VARIABLE }<file_sep>/Functions/Recursion/main.cpp #include<iostream> using namespace std; //#define FACTORIAL //#define POWER #define FIBONACCI_1 int factorial(int n) { if (n == 0)return 1; return n * factorial(n - 1); /*int f = n * factorial(n - 1); return f;*/ } double power(double a, int n) { return (n == 0) ? 1 : (n > 0) ? a * power(a, n - 1) : 1 / a * power(a, n + 1); /*if (n == 0)return 1; if(n>0)return a * power(a, n - 1); else if(n<0) return 1 / a*power(a, n + 1);*/ } //<EMAIL> void Fibonacci(int n, int a = 0, int b = 1);//Default parameters //Function doesn't take N arguments; void main() { setlocale(LC_ALL, ""); #ifdef FACTORIAL int n; cout << "Введите число, для вычисления факториала: "; cin >> n; cout << factorial(n) << endl; #endif // FACTORIAL #ifdef POWER int a; int n; cout << "Введите основание степени: "; cin >> a; cout << "Введите показатель степени: "; cin >> n; cout << a << " ^ " << n << " = " << power(a, n) << endl; #endif // POWER #ifdef FIBONACCI_1 int n; cout << "До какого числа вывести ряд Фибоначчи: "; cin >> n; Fibonacci(n); #endif // FIBONACCI_1 } void Fibonacci(int n, int a, int b)//Default parameters //Function doesn't take N arguments { if (a > n) { cout << endl; return; } cout << a << "\t"; Fibonacci(n, b, a + b); }
ed095bdcdf370286d2bb63584953155a16242673
[ "Text", "C++" ]
24
C++
phoenixmmi/Pointers
fd8262add1f5529ea17f6d4571c276d06fa99ca9
ee986e779e95a1c06068ee83fd7f7a94abbb67d0
refs/heads/development
<repo_name>Elbie-em/archonnect_mvp_backend<file_sep>/spec/models/user_spec.rb require 'rails_helper' RSpec.describe User, type: :model do let(:user) { User.create!(email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>') } it 'is valid with valid attributes' do expect(user).to be_valid end it 'is not valid without an email' do user.email = nil expect(user).to_not be_valid end it 'is not valid with a password less than 6 characters' do user.password = '<PASSWORD>' user.password_confirmation = '<PASSWORD>' expect(user).to_not be_valid end describe 'Associations' do context 'Having many from the different existent models' do it { should have_many(:favourites) } it { should have_many(:plans) } end end end <file_sep>/app/controllers/concerns/current_user_concern.rb module CurrentUserConcern extend ActiveSupport::Concern included do before_action :set_current_user end def set_current_user @current_user = User.find(session[:current_user_id]) if session[:current_user_id] end end <file_sep>/app/controllers/api/v1/favourites_controller.rb module Api module V1 class FavouritesController < ApplicationController include CurrentUserConcern def index if @current_user user = @current_user @favourites = user.plans.all render json: { status: 200, result: @favourites } else render json: { status: 401, result: [] } end end def create user_id = params['data']['user_id'] plan_id = params['data']['plan_id'] favourite_exists = Favourite.where(user_id: user_id, plan_id: plan_id).exists? if !favourite_exists favourite = Favourite.create( user_id: params['data']['user_id'], plan_id: params['data']['plan_id'] ) render json: { status: 202, favourite: favourite, message: 'House plan added to favourites successfully.' } else render json: { status: 500, message: 'You already have this entry saved in favourites.' } end end end end end <file_sep>/app/admin/plans.rb ActiveAdmin.register Plan do permit_params :name, :details, :architect_name, :rating, :price, :design_img_url, :blueprint_one_url, :blueprint_two_url end <file_sep>/app/models/user.rb class User < ApplicationRecord has_secure_password has_many :favourites, dependent: :destroy has_many :plans, through: :favourites validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :password, presence: true, length: { in: 6..20 } end <file_sep>/spec/models/plan_spec.rb require 'rails_helper' RSpec.describe Plan, type: :model do describe 'Associations' do context 'Having many from the different existent models' do it { should have_many(:favourites) } it { should have_many(:users) } end end end <file_sep>/db/migrate/20210124133326_create_plans.rb class CreatePlans < ActiveRecord::Migration[5.2] def change create_table :plans do |t| t.string :name t.text :details t.string :architect_name t.integer :rating t.integer :price t.string :design_img_url t.string :blueprint_one_url t.string :blueprint_two_url t.timestamps end end end <file_sep>/spec/requests/sessions_spec.rb require 'rails_helper' describe 'Check if user is logged in', type: :request do before do post '/api/v1/registrations', params: { user: { email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } } get '/api/v1/logged_in' end it 'return user with logged in status as true' do data = JSON.parse(response.body) expect(data['logged_in']).to eq(true) end end describe 'Check if user is logged out', type: :request do before do post '/api/v1/registrations', params: { user: { email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } } delete '/api/v1/logout' end it 'return logged out status as true' do data = JSON.parse(response.body) puts data expect(data['logged_out']).to eq(true) end end <file_sep>/spec/requests/registration_spec.rb require 'rails_helper' describe 'user registration', type: :request do before do post '/api/v1/registrations', params: { user: { email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } } end it 'returns http response 200' do expect(response).to have_http_status(200) end it 'return user with created status' do data = JSON.parse(response.body) puts data expect(data['status']).to eq('created') end end describe 'checking if user exists', type: :request do before do post '/api/v1/registrations', params: { user: { email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } } get '/api/v1/registrations/<EMAIL>' end it 'returns user details if user exists' do data = JSON.parse(response.body) expect(data['user']['email']).to eq('<EMAIL>') end end <file_sep>/spec/factories/plan.rb FactoryBot.define do factory :plan do name { Faker::Lorem.word } details { Faker::Lorem.sentence } architect_name { Faker::Name.name } rating { Faker::Number.between(from: 1, to: 6) } price { Faker::Number.between(from: 500, to: 200) } design_img_url { Faker::Internet.url } blueprint_one_url { Faker::Internet.url } blueprint_two_url { Faker::Internet.url } end end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base include ActionController::MimeResponds skip_before_action :verify_authenticity_token end <file_sep>/config/routes.rb Rails.application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html namespace :api do namespace :v1 do resources :sessions, only: [:create] resources :registrations, only: [:create] get '/registrations/:email/(.:format)', to: "registrations#show" delete :logout, to: "sessions#logout" get :logged_in, to: "sessions#logged_in" resources :plans, only:[:index,:show] resources :favourites, only:[:index,:create] end end end <file_sep>/app/controllers/api/v1/plans_controller.rb module Api module V1 class PlansController < ApplicationController include CurrentUserConcern def index @plans = Plan.all if @plans && @current_user render json: { status: 200, result: @plans } else render json: { status: 401, result: [] } end end def show plan = Plan.find(params[:id]) if plan && @current_user render json: { status: 202, result: plan } else render json: { status: 401, result: [] } end end end end end <file_sep>/spec/models/favourite_spec.rb require 'rails_helper' RSpec.describe Favourite, type: :model do describe 'Associations' do context 'Belonging to user and plan models' do it { should belong_to(:user) } it { should belong_to(:plan) } end end end <file_sep>/app/admin/favourites.rb ActiveAdmin.register Favourite do permit_params :user_id, :plan_id end <file_sep>/app/serializers/plan_serializer.rb class PlanSerializer < ActiveModel::Serializer attributes :id, :name, :details, :architect_name, :rating, :price, :design_img_url, :blueprint_one_url, :blueprint_two_url end <file_sep>/app/controllers/api/v1/registrations_controller.rb module Api module V1 class RegistrationsController < ApplicationController def create user = User.create( email: params['user']['email'], password: params['<PASSWORD>']['<PASSWORD>'], password_confirmation: params['user']['password_confirmation'] ) if user.valid? session[:current_user_id] = user.id render json: { status: :created, user: user } elsif !user.valid? render json: { status: 500 } end end def show email = params[:email].to_s @user = User.find_by(email: "#{email}.com") if @user render json: { status: 202, user: @user } else render json: { status: 404, user: [] } end end end end end <file_sep>/app/models/plan.rb class Plan < ApplicationRecord has_many :favourites, dependent: :destroy has_many :users, through: :favourites end <file_sep>/README.md # Archonnect API Server > A Rails API end-point application consisting of a listing of house plans by freelance architects that are up for bidding. ## Built With - Ruby v2.7.2 - Ruby on Rails v5.2.4.4 - PostgreSQL 12.4 - VSCode - Terminal - Rubocop - RSpec - Active Admin ## Server [API](https://api-archonnect-mvp.herokuapp.com) ## Setup ``` - **Terminal(Mac & Linux) or Command Prompt(Windows)**: This is where you will run all commands. - **Clone**: clone this repository to your local machine. - **Ruby Enviroment**: if you do not have ruby installed visit this [link](https://www.ruby-lang.org/en/documentation/installation/) to install. - **PostgresSQL**: if you do not have postgreSql installed visit this [link](https://www.postgresql.org/) to install. - **Rails**: install rails gem by running command *$ gem install rails* -v 5.2.4 in your terminal. - **bundle**: run $ bundle install. This installs all gems declared in the Gemfile - **Database Creation**: run *$ rails db:create* in the terminal to create database on your local machine - **Database Migration**: run *$ rails db:migrate* in terminal to run database migrations on your local machine ``` ## Usage Start server with: ``` rails server -p 3001 ``` Open `http://localhost:3001/` in your browser. ## Active Admin This feature allows you to create house plan entries from an admin dashboard. To use this feature ``` Create seed data for the Admin user in **db/seeds.rb** e.g AdminUser.create!(email: '<EMAIL>', password: '<PASSWORD>', password: '<PASSWORD>') Run rails db:seed after running migrations Open `http://localhost:3001/admin` in your browser and log in with seed credentials ``` ### Testing ``` bundle exec rspec ``` ### Deployment > To deploy heroku - Create a heroku account [here](https://www.heroku.com/) - In your root folder run the following commands ``` $ heroku login: Log into heroku CLI in your browser $ heroku create $ git push heroku master $ heroku run rails db:migrate $ heroku run rails c: "Create your entries with rails console commands" ``` ## Authors ![Hireable](https://img.shields.io/badge/HIREABLE-YES-yellowgreen&?style=for-the-badge) 👤 **<NAME>** - GitHub: [@Elbie-Em](https://github.com/Elbie-em) - Twitter: [ElbieEm](https://twitter.com/ElbieEm) - LinkedIn: [elbie-moonga](https://www.linkedin.com/in/elbiemoonga) --- ## 🤝 Contributing Contributions, issues and feature requests are welcome! Feel free to check the [issues page](https://github.com/Elbie-em/archonnect_mvp_backend/issues). ## Show your support Give me a ⭐️ if you like this project! ## Acknowledgments - [Microverse](https://microverse.org) --- ## 📝 License This project is [MIT](/LICENSE) licensed. --- <file_sep>/config/initializers/session_store.rb if Rails.env == "production" Rails.application.config.session_store :cookie_store, key: "api-archonnect-mvp", domain: "api-archonnect-mvp.herokuapp.com",same_site: :none, secure: true else Rails.application.config.session_store :cookie_store, key: "api-archonnect-mvp" end<file_sep>/spec/requests/plan_spec.rb require 'rails_helper' describe 'get all plans route', type: :request do let!(:plans) { FactoryBot.create_list(:plan, 20) } before do post '/api/v1/registrations', params: { user: { email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' } } get '/api/v1/plans', params: {} end it 'returns all house plans' do data = JSON.parse(response.body) expect(data['result'].size).to eq(20) end it 'returns status code 200' do expect(response).to have_http_status(200) end end
7f0057c9e94d73d62f45e25217423753d7673384
[ "Markdown", "Ruby" ]
21
Ruby
Elbie-em/archonnect_mvp_backend
b8b278dbf26d88a3ab893b8cad77400a828078af
1aeac0021b41b4fd71646bbb8d6026c9835eed3f