language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
1,991
2.625
3
[]
no_license
using GigHub.Core.Models; using GigHub.Core.Repositories; using GigHub.Persistence; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace GigHub.Persistence.Repositories { public class GigRepository : IGigRepository { private readonly IApplicationDbContext _context; public GigRepository(IApplicationDbContext context) { this._context = context; } public Gig GetGig(int gigId) { return _context.Gigs.Single(g => g.Id == gigId); } public Gig GetGigWithAttendees(int gigId) { return _context.Gigs .Include(g => g.Attendances.Select(a => a.Attendee)) .SingleOrDefault(g => g.Id == gigId); } public Gig GetGigWithArtistAndGenre(int gigId) { return _context.Gigs .Include(g => g.Artist) .Include(g => g.Genre) .SingleOrDefault(g => g.Id == gigId); } public IEnumerable<Gig> GetMyUpcomingGigs(string userId) { return _context.Gigs .Where(a => a.ArtistId == userId && a.DateTime > DateTime.Now && !a.IsCanceled) .Include(a => a.Genre); } public IEnumerable<Gig> GetUpcomingGigs() { return _context.Gigs .Include(m => m.Artist) .Include(m => m.Genre) .Where(m => m.DateTime > DateTime.Now && !m.IsCanceled); } public IEnumerable<Gig> GetGigsUserAttending(string userId) { return _context.Attendances .Where(a => a.AttendeeId == userId) .Select(a => a.Gig) .Include(g => g.Artist) .Include(g => g.Genre) .ToList(); } public void Add(Gig gig) { _context.Gigs.Add(gig); } } }
Java
UTF-8
900
3.453125
3
[]
no_license
package com.htc.ioss; // how to create directories import java.io.IOException; import java.io.File; public class CreateDirFiles { public static void main(String[] args) throws IOException { char fChar = File.separatorChar; System.out.println("Windows separator "+fChar); File f1 = new File("d:" + fChar + "aaa"); f1.mkdir(); System.out.println(f1.exists()); String path = f1.getAbsolutePath(); System.out.println(path); String s1 = path + fChar + "samp.txt"; f1 = new File(s1); System.out.println("File created is:" + f1.createNewFile()); f1 = new File(path + fChar + "bbb" + fChar + "ccc"); boolean boo = f1.mkdirs(); System.out.println("Statement that directories" + " are created is:" + boo); } }
Java
UTF-8
866
2.109375
2
[]
no_license
package com.clean_architecture.tronnv.presentationlayer.presenter; import com.clean_architecture.tronnv.presentationlayer.presenters.impl.MainPresenterImpl; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; public class MainPresenterImplTest { private MainPresenterImpl presenter; @Before public void setUp() { presenter = mock(MainPresenterImpl.class); } @After public void tearDown() { presenter = null; } @Test public void requestBalladMusic() { doNothing().when(presenter).requestBalladMusic(); presenter.requestBalladMusic(); } @Test public void requestPopMusic() { doNothing().when(presenter).requestPopMusic(); presenter.requestPopMusic(); } }
Java
UTF-8
2,818
2.328125
2
[]
no_license
package br.edu.ftlf.ads.revenda.model; import java.util.List; import org.hibernate.validator.constraints.NotEmpty; public class Veiculo extends Model { private static final long serialVersionUID = 1L; public static final String PROPERTY_MARCA = "marca"; public static final String PROPERTY_MODELO = "modelo"; public static final String PROPERTY_ANO = "ano"; @NotEmpty private String ano; @NotEmpty private String chassi; @NotEmpty private String especie; @NotEmpty private String marca; @NotEmpty private String modelo; @NotEmpty private String placa; @NotEmpty private String renavan; private List<Aquisicao> aquisicoes; public Veiculo() { } public Veiculo(Integer id) { setId(id); } public String getAno() { return this.ano; } public void setAno(String ano) { this.ano = ano; } public String getChassi() { return this.chassi; } public void setChassi(String chassi) { this.chassi = chassi; } public String getEspecie() { return this.especie; } public void setEspecie(String especie) { this.especie = especie; } public String getMarca() { return this.marca; } public void setMarca(String marca) { this.marca = marca; } public String getModelo() { return this.modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public String getPlaca() { return this.placa; } public void setPlaca(String placa) { this.placa = placa; } public String getRenavan() { return this.renavan; } public void setRenavan(String renavan) { this.renavan = renavan; } public List<Aquisicao> getAquisicoes() { return this.aquisicoes; } public void setAquisicoes(List<Aquisicao> aquisicoes) { this.aquisicoes = aquisicoes; } public Aquisicao addAquisicao(Aquisicao aquisicao) { getAquisicoes().add(aquisicao); aquisicao.setVeiculo(this); return aquisicao; } public Aquisicao removeAquisicoe(Aquisicao aquisicao) { getAquisicoes().remove(aquisicao); aquisicao.setVeiculo(null); return aquisicao; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((ano == null) ? 0 : ano.hashCode()); result = prime * result + ((aquisicoes == null) ? 0 : aquisicoes.hashCode()); result = prime * result + ((chassi == null) ? 0 : chassi.hashCode()); result = prime * result + ((especie == null) ? 0 : especie.hashCode()); result = prime * result + ((marca == null) ? 0 : marca.hashCode()); result = prime * result + ((modelo == null) ? 0 : modelo.hashCode()); result = prime * result + ((placa == null) ? 0 : placa.hashCode()); result = prime * result + ((renavan == null) ? 0 : renavan.hashCode()); return result; } @Override public String toString() { return String.format("%s %s %s %s", marca, modelo, ano, placa); } }
C++
UTF-8
3,004
2.765625
3
[ "MIT" ]
permissive
/*=========================================================================================================== * * HUC - Hurna Core * * Copyright (c) Michael Jeulin-Lagarrigue * * Licensed under the MIT License, you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/Hurna/Hurna-Core/blob/master/LICENSE * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * *=========================================================================================================*/ #ifndef MODULE_COMBINATORY_COMBINATIONS_HXX #define MODULE_COMBINATORY_COMBINATIONS_HXX // STD includes #include <list> namespace huc { namespace combinatory { /// Combinations - Return all possible combinations of elements containing within the sequence. /// /// @remark a vector is not recommended as type for the Output_Container to avoid stack overflow as well /// as extra complexity due to frequent resizing (use instead structure such as list or a another with /// your own allocator). /// /// @tparam Container type of IT type. /// @tparam IT type using to go through the collection. /// /// @param begin,end - iterators to the initial and final positions of /// the sequence. The range used is [first,last), which contains all the elements between /// first and last, including the element pointed by first but not the element pointed by last. /// /// @return a collection containing all possible combined subsets. template <typename Container, typename IT> std::list<Container> Combinations(const IT& begin, const IT& end) { std::list<Container> combinations; // Recusion termination const auto kSeqSize = static_cast<const int>(std::distance(begin, end)); if (kSeqSize <= 0) return combinations; // Keep first element Container elementContainer; elementContainer.push_back(*begin); combinations.push_back(elementContainer); // Recursion termination if (kSeqSize == 1) return combinations; // Build all permutations of the suffix - Recursion auto subCombinations = Combinations<Container, IT>(begin + 1, end); // Put the letter into every possible position of the existing permutations. for (auto it = subCombinations.begin(); it != subCombinations.end(); ++it) { combinations.push_back(*it); it->push_back(*begin); combinations.push_back(*it); } return combinations; } } } #endif // MODULE_COMBINATORY_COMBINATIONS_HXX
Java
UTF-8
899
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package game.Fishes; import city.cs.engine.BodyImage; import city.cs.engine.PolygonShape; import city.cs.engine.SolidFixture; import city.cs.engine.World; /** * * @author cs */ public class Whale extends Fish{ public Whale (World w) { super(w); PolygonShape shape = new PolygonShape( -1.43f,1.46f, 1.42f,1.48f, 1.41f,-1.47f, -1.43f,-1.48f, -1.44f,1.44f); this.addImage(new BodyImage("data/whale.png",5.0f));//Image taken from http://www.stickpng.com/img/at-the-movies/cartoons/finding-nemo/nemo-side-view SolidFixture fixture = new SolidFixture(this, shape); fixture.setRestitution(1); // private int liveCount; } }
Markdown
UTF-8
843
2.640625
3
[]
no_license
# Race report: Peterson Ridge Rumble 40 Mile Date: April 12, 2015 Website: [petersonridgerumble.com](http://www.petersonridgerumble.com/) Official time: 7:39:38 Strava link: [strava.com](https://www.strava.com/activities/284443137) Rumble #8 in the books. Returned to the 40 after a couple years doing the 20. Goal was to finish the race with enough gas in the tank for 10 more miles. So, ran conservatively. Time goal was a modest sub-8 hours. Felt great most of the time. Had a bit of stomach issues and slight cramping, but walking it off helped. Spent too much time lollygagging at the aid stations. Did a better job of taking in calories, but could have been better with hydration. Never felt dehydrated, though. Official time: 7:39:38 (http://runwildadventures.com/web_documents/2015_peterson_ridge_rumble_40_mile_results.htm)
Swift
UTF-8
2,326
2.828125
3
[]
no_license
// // SecondViewController.swift // Appecules // // Created by admin on 27/08/19. // Copyright © 2019 admin. All rights reserved. // import UIKit class UserDataVC: UIViewController { @IBOutlet weak var dataTableView: UITableView! var names: [String] = [] //names is a mutable array holding string values override func viewDidLoad() { super.viewDidLoad() self.customNavigationView(barType:appeculesScreen.OrderHistory) title = "The List" dataTableView.register(UITableViewCell.self, forCellReuseIdentifier: "UserDataCell") } @IBAction func buttonAction(_ sender: Any) { addName() } } extension UserDataVC : UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserDataCell", for: indexPath) cell.textLabel?.text = names[indexPath.row] return cell } func addName() { let alert = UIAlertController(title: "Name of User", message: "Add a new name", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return } self.names.append(nameToSave) self.dataTableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alert.addTextField() alert.addAction(saveAction) alert.addAction(cancelAction) UIApplication.visibleViewController.present(alert, animated: true) } }
JavaScript
UTF-8
850
2.53125
3
[]
no_license
import * as types from '../constants/types'; import update from 'immutability-helper'; export const initialState = { events : [] } export const reducer = (state = initialState, action) => { switch(action.type) { case types.ACTION_ADD_AVENT:{ return ({...state, events : [...state.events,{...action.payload,id : ++state.events.length}]}) } case types.ACTION_DELETE_AVENT:{ return ({...state, events : update(state.events, arr => arr.filter(item => item.id !== action.payload.id) )}) } case types.ACTION_UPDATE_AVENT:{ return ({...state, events : update(state.events, arr => arr.map(item => item.id === action.payload.id ? {...action.payload,id : item.id} : item) )}) } default: return state; } }
TypeScript
UTF-8
5,472
2.515625
3
[]
no_license
import { Request, Response } from 'express' import Image from '../models/image' import { APP_URL } from "../config/config" import path from 'path' import fs from 'fs' const getAllImage = (req: Request, res: Response) => { const perPage = 12 let page = parseInt(req.query.page as string) || 0 as any Image.find() .limit(perPage) .skip(perPage * page) .sort('-createdAt') .exec(function (err, images) { Image.count() .exec(function (err, count) { if (err) { res.status(500).json({ error: true, msg: "Server Error" }); return; }; res.status(200).json({ image_list: images, page: page, pages: Math.ceil(count / perPage) }); }) }) } const getImage = async (req: Request, res: Response) => { try { const imageId = req.params.id const findImage = await Image.findOne({ _id: imageId }) if (!findImage) { return res.status(404).json({ error: true, msg: "Image not found" }) } const image = await Image.findById({ _id: imageId } ).select({ _id: 0, __v: 0 }) return res.status(200).json({ error: false, data: image }) } catch (error) { console.log(error); return res.status(200).json({ error: true, msg: "Server Error" }) } } const addImage = async (req: Request, res: Response) => { try { if (req.file) { console.log(req.file) } if (!req.file) { return res.status(404).json({ error: true, msg: "File not found." }); } const file = req.file.filename const ext = path.extname(file).split("."); const file_type = ext[1] const file_name = file.replace(file_type, "").split('.') const image_title = file_name[0] console.log("image_title", image_title) const image = new Image({ title: image_title, imageURL: req.file.path, imageFullURL: APP_URL + req.file.filename }) await image.save() return res.status(201).json({ error: false, msg: "Add Succesfully", data: image }) } catch (error) { console.log(error); return res.status(200).json({ error: true, msg: "Server Error" }) } } const addImageByLink = async (req: Request, res: Response) => { try { let { imageFullURL } = req.body if (imageFullURL == undefined || imageFullURL == null || imageFullURL == '') { return res.status(401).json({ error: true, msg: "Image URL requried" }) } const image = new Image({ imageFullURL, }) await image.save() return res.status(201).json({ error: false, msg: "Add Succesfully", data: image }) } catch (error) { console.log(error); return res.status(200).json({ error: true, msg: "Server Error" }) } } const removeImage = async (req: Request, res: Response) => { try { const imageId = req.params.id const findImage = await Image.findOne({ _id: imageId }) if (!findImage) { return res.status(404).json({ error: true, msg: "Image not found" }) } const image = await Image.findByIdAndRemove({ _id: imageId }) if (image?.imageURL) { fs.unlinkSync(`${image?.imageURL}`); } return res.status(200).json({ error: false, msg: "Delete Successfuly" }) } catch (error) { console.log(error); return res.status(500).json({ error: true, msg: "Server Error" }) } } const filterData = async (req: Request, res: Response) => { var d = new Date(); d.setDate(d.getDate() - 7); // try { Image.aggregate([ { $match: { 'createdAt': { $gt: d } } }, { $addFields: { createdAtDate: { $toDate: "$createdAt" }, } }, { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAtDate" } }, count: { $sum: 1 } } }, { $project: { count: 1, date: "$_id", _id: 0 } } ]) .exec(function (err, image) { const result = Object.fromEntries(Object .entries(image.reduce((r, { date, count }) => { r[date] ??= 0; r[date] += count || -1; return r; }, {})) .map(([k, v]) => [k, v]) ); if (err) { res.status(500).json({ error: true, msg: "Server Error" }); return; }; res.status(200).json({ error: false, result: result }); }) // console.log(userData) // return res.status(200).json({ error: false, data: data }) // } catch (error) { // console.log(error); // return res.status(200).json({ error: true, msg: "Server Error" }) // } } export default { getAllImage, getImage, removeImage, addImage, addImageByLink, filterData }
Java
UTF-8
3,819
3.65625
4
[]
no_license
package leetcode; import java.util.Arrays; /** * @author: nj * @date: 2020-04-18 10:51 * @version: 0.0.1 */ public class Code_628 { /** * *Given an integer array, find three numbers whose product is maximum and output the maximum product. * * Example 1: * * Input: [1,2,3] * Output: 6 * * * Example 2: * * Input: [1,2,3,4] * Output: 24 * * * Note: * * The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. * Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. * * * 看似简单,实则😸😸😸😸😸😸😸😸😸😸 气死人 * * * 考虑到负数的存在(lenght > 3) * * * A > B > C > D * * A > B > C >= 0 A * B * C ??? xx * * A > B > 0 > C > D C * D * A * * A > 0 > B > C > D C * D * A * * 0 > A > B > C > * * * * Math.max(nums[0]*nums[1]*nums[n],nums[n]*nums[n-1]*nums[n-2]); * * * 第一大 第二大 第三大 .... 第三小 第二小 第一小 * */ public static int maximumProduct(int[] nums) { if(nums == null || nums.length < 3){ return 0; } int len = nums.length; if(len == 3){ return nums[0] * nums[1] * nums[2]; } Arrays.sort(nums); int a = nums[len - 1], b = nums[len - 2], c = nums[len - 3], d = nums[len - 4]; if(b > 0 && c < 0){ return a * nums[0] * nums[1]; }else if(b < 0 && a > 0){ return a * nums[0] * nums[1]; }else{ return Math.max(a * b * c, a * nums[0] * nums[1]); } } public int maximumProduct1(int[] nums) { if(nums==null || nums.length<3) return 0; Arrays.sort(nums); int n=nums.length-1; return Math.max(nums[0]*nums[1]*nums[n],nums[n]*nums[n-1]*nums[n-2]); } public int maximumProduct2(int[] nums) { int max1 = Integer.MIN_VALUE; // 第1大 int max2 = Integer.MIN_VALUE; // 第2大 int max3 = Integer.MIN_VALUE; // 第3大 int min2 = Integer.MAX_VALUE; // 第2小 int min1 = Integer.MAX_VALUE; // 第1小 for(int num : nums){ // max if(num > max1){ max3 = max2; max2 = max1; max1 = num; }else if(num > max2){ max3 = max2; max2 = num; }else if(num > max3){ max3 = num; } // min if(num < min1){ min2 = min1; min1 = num; }else if(num < min2){ min2 = num; } } return Math.max(max3 * max2 * max1, min1 * min2 * max1); } public static void main(String[] args) { int[] a = {-4,-3,-2,-1,60}; int[] b = {-4,-3,-2,-1,69,80}; int[] c = {-4,-3,-2,-1}; System.out.println(maximumProduct(a)); System.out.println(maximumProduct(b)); System.out.println(maximumProduct(c)); int[] d = {722,634,-504,-379,163,-613,-842,-578,750,951,-158,30,-238,-392,-487,-797,-157,-374,999,-5,-521,-879,-858,382,626,803,-347,903,-205,57,-342,186,-736,17,83,726,-960,343,-984,937,-758,-122,577,-595,-544,-559,903,-183,192,825,368,-674,57,-959,884,29,-681,-339,582,969,-95,-455,-275,205,-548,79,258,35,233,203,20,-936,878,-868,-458,-882,867,-664,-892,-687,322,844,-745,447,-909,-586,69,-88,88,445,-553,-666,130,-640,-918,-7,-420,-368,250,-786}; Arrays.sort(d); System.out.println(maximumProduct(d)); // System.out.println(Arrays.toString(d)); } }
Python
UTF-8
3,952
2.703125
3
[]
no_license
from __future__ import print_function from inputs import get_gamepad import time keys_dict = {} def main(): cnt = 0 prev_x = None prev_y = None prev_z = None while cnt < 10000: #print("Hi") events = get_gamepad() for event in events: #if (event.ev_type == 'Key'): if (event.ev_type != 'Sync' and event.ev_type == 'Absolute'): print(event.code) if (event.code == 'ABS_X' or event.code == 'ABS_Y' or event.code != 'ABS_Y'): #print("type:", event.ev_type, "code:", event.code, "state:", event.state) new = False new_z = False if (event.code == 'ABS_X'): if (prev_x == None or (abs(prev_x - event.state) > 1000)): prev_x = event.state new = True if (event.code == 'ABS_Y'): if (prev_y == None or (abs(prev_y - event.state) > 1000)): prev_y = event.state new = True if (new == True and prev_x != None and prev_y != None): print("(x,y) = (%d, %d)"%(prev_x, prev_y)) if (event.code == 'ABS_Z'): if (prev_z == None or (abs(prev_z - event.state) > 5)): prev_z = event.state new_z = True if (new_z == True and prev_z != None): print("(z) = (%d)"%(prev_z)) #if ('ABS_HAT' in event.code): #if (event.ev_type != 'Sync'): # if (event.code == 'ABS_RY'): # print(event.ev_type, event.code, event.state) pad_event = "" if (event.ev_type == 'Key'): if (event.code == 'BTN_NORTH'): pad_event += "Triangle: " elif (event.code == 'BTN_WEST'): pad_event += "Square: " elif (event.code == 'BTN_SOUTH'): pad_event += "Cross: " elif (event.code == 'BTN_EAST'): pad_event += "Circle: " elif (event.code == 'BTN_TL'): pad_event += "Left Bumper: " elif (event.code == 'BTN_TR'): pad_event += "Right Bumper: " elif (event.code == 'BTN_START'): pad_event += "Share: " elif (event.code == 'BTN_SELECT'): pad_event += "Options: " elif (event.code == 'BTN_THUMBL'): pad_event += "Left Stick: " elif (event.code == 'BTN_THUMBR'): pad_event += "Right Stick: " if (event.state == 1): pad_event += "Pressed" elif (event.state == 0): pad_event += "Released" if (event.ev_type == 'Absolute' and "ABS_HAT0" in event.code): if (event.code == 'ABS_HAT0X' and event.state == 0): pad_event = "Dpad-X: Released" elif (event.code == 'ABS_HAT0X' and event.state < 0): pad_event = "Dpad Left: Pressed" elif (event.code == 'ABS_HAT0X' and event.state > 0): pad_event = "Dpad Right: Pressed" elif (event.code == 'ABS_HAT0Y' and event.state == 0): pad_event = "Dpad-Y: Released" elif (event.code == 'ABS_HAT0Y' and event.state < 0): pad_event = "Dpad Up: Pressed" elif (event.code == 'ABS_HAT0Y' and event.state > 0): pad_event = "Dpad Down: Pressed" if (pad_event != ""): print(pad_event) #print(cnt) cnt += 1 if __name__ == "__main__": main()
C#
UTF-8
3,867
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StatusUpdatesModel; namespace Data { public static class PhaseKeywords { public static Dictionary<Phases, List<string>> ExactKeywords { get { return new Dictionary<Phases, List<string>> { {Phases.Build_Test, new List<string>() }, {Phases.Deploy, new List<string>() { "udeploy" } }, {Phases.Macro_Design, new List<string>() }, {Phases.Micro_Design, new List<string>() }, {Phases.Solution_Outline, new List<string>() }, {Phases.Start_Up, new List<string>() }, {Phases.Transition_Close, new List<string>() } }; } } public static Dictionary<Phases, List<string>> FuzzyKeywords { get { return new Dictionary<Phases, List<string>> { {Phases.Build_Test, new List<string>() { "build", "test", "testing" } }, {Phases.Deploy, new List<string>() { "deployment" } }, {Phases.Macro_Design, new List<string>() {"macro", "high level", "design" } }, {Phases.Micro_Design, new List<string>() {"micro", "detail", "design" } }, {Phases.Solution_Outline, new List<string>() { "outline", "sketch"} }, {Phases.Start_Up, new List<string>() {"start up" } }, {Phases.Transition_Close, new List<string>() {"close", "transition" } } }; } } public static Phases GuessPhase(string inputString) { inputString = inputString.ToLower(); //__if there is a match for an exact key, then simply use that value foreach (var entry in ExactKeywords) { foreach (string searchTerm in entry.Value) { if (inputString.Contains(searchTerm)) return entry.Key; } } Dictionary<Phases, int> phaseVotes = new Dictionary<Phases, int>(); foreach (var fuzzyKeyword in FuzzyKeywords) { Phases currentPhase = fuzzyKeyword.Key; foreach (string searchTerm in fuzzyKeyword.Value) { if (inputString.Contains(searchTerm)) { if (phaseVotes.ContainsKey(currentPhase)) phaseVotes[currentPhase] = phaseVotes[currentPhase]+1; else phaseVotes.Add(currentPhase, 1); } } } if (phaseVotes.Count > 0) { var voteList = phaseVotes.ToList(); voteList.Sort((p1, p2) => p1.Value.CompareTo(p2)); } Phases resultingPhase = Phases.Not_Assigned; if (phaseVotes.Count > 0) resultingPhase = phaseVotes.First().Key; return resultingPhase; } public static void GuessPhase(ref ProjectUpdate projectUpdate) { string stringToSearch = ""; stringToSearch += projectUpdate.Subject + " "; stringToSearch += projectUpdate.Body; projectUpdate.Phase = GuessPhase(stringToSearch).ToString(); } public static Phases GuessPhase(List<StatusUpdate> updates) { string stringToSearch = ""; foreach (StatusUpdate update in updates) { stringToSearch += update.UpdateKey + " "; stringToSearch += update.UpdateValue; } return GuessPhase(stringToSearch); } } }
JavaScript
UTF-8
651
3.4375
3
[]
no_license
/* 2845 */ const getClearData = data => { return data.map(ele => ele.split(' ').map(item => parseInt(item))); } const solution = (data) => { const [[people, square], newsCount] = getClearData(data) const answer = newsCount.map((ele) => { return ele - (people * square) }) console.log(answer.join(' ')) } const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let input = []; rl.on('line', function (line) { input.push(line) }) .on('close', function () { solution(input); process.exit(); }); // 여러줄 입력
PHP
UTF-8
7,114
2.609375
3
[]
no_license
<?php /** * BP_Groups_Hierarchy_Activity_Aggregation * * @package CC Group Activity Aggregation * @author David Cavins * @license GPL-2.0+ * @copyright 2014 Community Commons */ /* -------------------------------------------------------------------------------- BP_Groups_Hierarchy_Activity_Aggregation Class -------------------------------------------------------------------------------- */ class BP_Groups_Hierarchy_Activity_Aggregation { /** * properties */ // array of subgroups is built during recursion public $subgroup_ids = array(); /** * Instance of this class. * * @since 0.1.0 * * @var object */ protected static $instance = null; /** * @description: initialises this object * @return object */ function __construct() { // use translation // add_action( 'plugins_loaded', array( $this, 'translation' ) ); // Add a meta box to the group's "admin>settings" tab. // We're also using BP_Group_Extension's admin_screen method to add this meta box to the WP-admin group edit // add_filter( 'groups_custom_group_fields_editable', array( $this, 'meta_form_markup' ) ); // This is a hook I've added in the general "CC Group Meta" plugin add_action( 'cc_group_meta_details_form_before_channels', array( $this, 'meta_form_markup' ) ); // Catch the saving of the meta form, fired when create>settings pane is saved or admin>settings is saved // add_action( 'groups_group_details_edited', array( $this, 'meta_form_save') ); // add_action( 'groups_created_group', array( $this, 'meta_form_save' ) ); // This is a hook I've added in the general "CC Group Meta" plugin add_action( 'cc_group_meta_details_form_save', array( $this, 'meta_form_save' ) ); add_filter( 'bp_ajax_querystring', array( $this, 'activity_aggregation' ), 90, 2 ); // --< return $this; } /** * @description: loads translation, if present * @todo: * */ function translation() { // only use, if we have it... if( function_exists('load_plugin_textdomain') ) { // enable translations load_plugin_textdomain( // unique name 'bp-group-hierarchy-propagate', // deprecated argument false, // relative path to directory containing translation files dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); } } /** * Return an instance of this class. * * @since 0.1.0 * * @return object A single instance of this class. */ public static function get_instance() { // If the single instance hasn't been set, set it now. if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Renders extra fields on form when creating a group and when editing group details * Used by BP_Groups_Hierarchy_Activity_Aggregation_Group_Extension::admin_screen() * @param int $group_id * @return string html markup * @since 0.1.0 */ public function meta_form_markup( $group_id = 0 ) { if ( ! current_user_can( 'delete_others_pages' ) ) return; $group_id = $group_id ? $group_id : bp_get_current_group_id(); ?> <p><label for="group_use_aggregated_activity"><input type="checkbox" id="group_use_aggregated_activity" name="group_use_aggregated_activity" <?php checked( groups_get_groupmeta( $group_id, 'group_use_aggregated_activity' ), 1 ); ?> /> Include child group activity in this group&rsquo;s activity stream.</label></p> <?php } /** * Saves the input from our extra meta fields * Used by BP_Groups_Hierarchy_Activity_Aggregation_Group_Extension::admin_screen_save() * @param int $group_id * @return void * @since 0.1.0 */ public function meta_form_save( $group_id = 0 ) { $group_id = $group_id ? $group_id : bp_get_current_group_id(); $meta = array( // Checkboxes 'group_use_aggregated_activity' => isset( $_POST['group_use_aggregated_activity'] ), ); foreach ( $meta as $meta_key => $new_meta_value ) { /* Get the meta value of the custom field key. */ $meta_value = groups_get_groupmeta( $group_id, $meta_key, true ); /* If there is no new meta value but an old value exists, delete it. */ if ( '' == $new_meta_value && $meta_value ) groups_delete_groupmeta( $group_id, $meta_key, $meta_value ); /* If a new meta value was added and there was no previous value, add it. */ elseif ( $new_meta_value && '' == $meta_value ) groups_add_groupmeta( $group_id, $meta_key, $new_meta_value, true ); /* If the new meta value does not match the old value, update it. */ elseif ( $new_meta_value && $new_meta_value != $meta_value ) groups_update_groupmeta( $group_id, $meta_key, $new_meta_value ); } } /** * Filter bp_ajax_querystring to add subgroups of current group that user has access to. * * @since 0.1.0 * * @return string of group ids to include. */ function activity_aggregation( $query_string, $object ) { //Check to see that we're in the BuddyPress groups component, not the member stream or other. Also check that this is an activity request, not the group directory. Else, stop the process. if ( ! bp_is_group() || ( $object != 'activity' ) ) return $query_string; //Get the group id and the user id $group_id = bp_get_current_group_id(); //Check if this group is set to aggregate child group activity. Else, stop the process. if ( 1 != groups_get_groupmeta( $group_id, 'group_use_aggregated_activity' ) ) return $query_string; $children = $this->_get_children( $group_id, bp_loggedin_user_id() ); //Finally, append the result to the query string. This works because bp_has_activities() allows a comma-separated list of ids as the primary_id argument. if ( !empty( $children ) ) { $query_string .= '&primary_id=' . implode( ',', $children ); } return $query_string; } /** * @description: build a list of child group IDs (includes current group ID) * I've adopted Christian Wach's code for this piece, it was much more clever than mine. * https://github.com/christianwach/bp-group-hierarchy-propagate * @param integer $group_id * @return array $subgroup_ids */ function _get_children( $group_id, $user_id ) { // Add this group's id to the array $this->subgroup_ids[] = $group_id; // get children from BP Group Hierarchy $children = bp_group_hierarchy_get_by_hierarchy( array( 'parent_id' => $group_id ) ); // did we get any? if ( isset( $children['groups'] ) && count( $children['groups'] ) > 0 ) { // check them foreach( $children['groups'] as $child ) { // is the user allowed to see content from this group? if ( 'public' == $child->status || // Anyone can see this group's activity groups_is_user_member( $user_id, $group_id ) || // The user has access to the group's activity current_user_can( 'delete_others_pages' ) // Site admin can see everything ) { // recurse down the group hierarchy $this->_get_children( $child->id, $user_id ); } } } // --< return $this->subgroup_ids; } } // end class BP_Groups_Hierarchy_Activity_Aggregation
Java
UTF-8
1,070
2.59375
3
[]
no_license
package cms.sre.httpclient_connection_helper.embedded; import fi.iki.elonen.NanoHTTPD; public class InsecureServer extends NanoHTTPD implements EmbeddedServer{ private String response; public InsecureServer(String response){ super(EmbeddedServer.randomPort()); this.response = response; } public String getResponse(){return this.response;} @Override public Response serve(IHTTPSession session){ return this.response != null && this.response.length() > 0 ? this.newFixedLengthResponse(this.response) : this.newFixedLengthResponse("EMPTY RESPONSE"); } @Override public boolean isSecure() { return false; } @Override public String getUrl() { return "http://localhost:"+this.getListeningPort(); } @Override public void finalize(){ if(this.isRunning()){ super.closeAllConnections(); super.stop(); } } @Override public boolean isRunning(){ boolean isAlive = super.isAlive(); return isAlive; } }
C++
UTF-8
9,704
3.359375
3
[]
no_license
// insert delete // Avl Tree.h // AVL Tree // // Created by dali on 2/25/18. // Copyright © 2018 dali. All rights reserved. #include <iostream> #include <algorithm> #include <cassert> #include <fstream> #ifndef Avl_Tree_h #define Avl_Tree_h template <class T> class AVLTree{ public: //---------------------------------------------------------------------------------------------------------------------------------------------------- struct Node{ Node(){ element = 0; height = 0; count = 0; left = nullptr; right = nullptr;} Node(T E, int H , int C, Node* L, Node* R){ element = E; height = H; count = C; left = L; right = R; } T element; int height; int count; Node* left; Node* right; }; //---------------------------------------------------------------------------------------------------------------------------------------------------- AVLTree(){ root = NULL;} ~AVLTree(){ destroy(root); } void destroy(Node* root){ if(root){ if(root->left) destroy(root->left); if(root->right) destroy(root->right); delete root; } } //---------------------------------------------------------------------------------------------------------------------------------------------------- //Left Rotation and Right rotation //左旋和右旋不会改变root高度 Node* ClockWiseRotate(Node* root){ Node* Aright = root->left->right; Node* NewRoot = root->left; root->left = Aright; NewRoot -> right = root; root->height = max(getHeight(root->left),getHeight(root->right))+1; NewRoot->height = max(getHeight(NewRoot->left),getHeight(NewRoot->right))+1; return NewRoot; } Node* CounterClockWiseRotate(Node* root){ Node* Bleft = root->right->left; //B1 Node* NewRoot = root->right; root->right = Bleft; NewRoot -> left = root; root->height = max(getHeight(root->left),getHeight(root->right))+1; NewRoot->height = max(getHeight(NewRoot->left),getHeight(NewRoot->right))+1; return NewRoot; } Node* DoubleRotateLR(Node* root){ //assert(root->left->right); root->left = CounterClockWiseRotate(root->left); return ClockWiseRotate(root); } Node* DoubleRotateRL(Node* root){ assert(root->right->left); root->right = ClockWiseRotate(root->right); return CounterClockWiseRotate(root); } //---------------------------------------------------------------------------------------------------------------------------------------------------- void rangesearch(T LB, T UB){ rangesearch_(LB,UB,root); } void rangesearch_(T LB, T UB, Node* root){ if(root){ if(root->left) rangesearch_(LB,UB,root->left); if(root->element >= LB && root->element <= UB) cout<<root->element<<endl; if(root->right) rangesearch_(LB,UB,root->right); } } void Traversal(Node* root){ if(root){ if(root->left) Traversal(root->left); cout<<root->element<<" "<<root->count<<endl; if(root->right) Traversal(root->right); } } void outputall(ofstream& OUT){ outputall_(OUT, root); } void outputall_(ofstream& OUT, Node* root){ if(root){ if(root->left) outputall_(OUT,root->left); OUT << root->element << "\n"; if(root->right) outputall_(OUT,root->right); } } //---------------------------------------------------------------------------------------------------------------------------------------------------- bool search(T e){ return search_(e, root); } bool search_(T e, Node* root){ if(root == NULL) return false; else{ if( e == root->element ) return true; else if( e < root->element ) return search_(e, root->left); else return search_(e, root->right); } } //---------------------------------------------------------------------------------------------------------------------------------------------------- void insert(T e){ root = insert_(e,root); } Node* insert_(T e, Node* root){ if(root == nullptr){ T E = e; int one = 1; Node* Nullptr = NULL; return new Node(E, one, one, Nullptr, Nullptr); } else{ if(e == root->element){ root->count++; } else if(e < root->element){ root->left = insert_(e, root->left); } else if(e > root->element){ root->right = insert_(e, root->right); } if(abs( getHeight(root->left)-getHeight(root->right) ) == 2){ //删了一个叶节点, 每次进行return之前 都要检查一遍是否平衡 int CASE = whichCase(root); if(CASE == 1) return ClockWiseRotate(root); else if(CASE == 2) return DoubleRotateLR(root); else if(CASE == 3) return CounterClockWiseRotate(root); else return DoubleRotateRL(root); } root->height = max(getHeight(root->left),getHeight(root->right))+1; return root; } } //---------------------------------------------------------------------------------------------------------------------------------------------------- void remove(T e){ root = remove_(e,root); } Node* remove_(T e, Node* root){ if(root == NULL) return NULL; if( e < root->element) root->left = remove_(e, root->left); else if( e > root->element) root->right = remove_(e, root->right); else{ // e == root->element root->count--; if(root->count >= 1) return root; if( !root->left && !root->right){ delete root; return NULL; } else if( (root->left != NULL) ^ (root->right != NULL) ){ if(root->left){ Node* temp = root->left; delete root; root = temp; } else if(root->right){ Node* temp = root->right; delete root; root = temp; } } else{ //it is a internal node Node* pre = findSuccessor(root); root->element = pre->element; root->right = remove_(root->element, root->right); } } if(abs( getHeight(root->left)-getHeight(root->right) ) == 2){ //删了一个叶节点, 每次进行return之前 都要检查一遍是否平衡 int CASE = whichCase(root); if(CASE == 1) return ClockWiseRotate(root); else if(CASE == 2) return DoubleRotateLR(root); else if(CASE == 3) return CounterClockWiseRotate(root); else return DoubleRotateRL(root); } root->height = max(getHeight(root->left),getHeight(root->right))+1; return root; } //---------------------------------------------------------------------------------------------------------------------------------------------------- //Some helper function int getHeight(Node* root){ if(root == NULL) return 0; else return root->height; } Node* findSuccessor(Node* root){ //return NULL if it has no predecessor Node* temp = NULL; if(root->right){ temp = root->right; while(1){ if(temp->left == NULL) break; else temp = temp->left; } } return temp; } void updateheight(Node* root){ root->height = max(getHeight(root->left),getHeight(root->right))+1; } int whichCase(Node* root){ //used in AVL deletion. Determine the which action to be performed wiwh root 1: LL 2: LR 3:RR 4: RL if( getHeight(root->left) > getHeight(root->right) ){ //L //不存在等于的情况, 因为调用这个函数了, 肯定左右不平衡 if( getHeight(root->left->left) >= getHeight(root->left->right) ) return 1; else return 2; } else{ //R if( getHeight(root->right->right) >= getHeight(root->right->left) ) return 3; //RR else return 4; //RL } } //---------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------- Node* root; }; #endif /* Avl_Tree_h */
Java
UTF-8
1,096
3
3
[]
no_license
package externalworld; import network.Brain; import neuron.Neuron; public class AllNeuronsFireRandomlyExternalWorld extends ExternalWorld { private double chanceToFirePerNeuronPerTimestep; private double firingAmplitude; public AllNeuronsFireRandomlyExternalWorld(Brain brain, double chanceToFirePerNeuronPerTimestep, double firingAmplitude) { super(brain); this.setChanceToFirePerNeuronPerTimestep(chanceToFirePerNeuronPerTimestep); this.firingAmplitude = firingAmplitude; } @Override public void coordinateSensoryNeuronFiringThisTimeStep() { for (Neuron neuron : this.getBrain().getInputNeurons()) { fireNeuronIfRequired(neuron); } } private void fireNeuronIfRequired(Neuron neuron) { if (Math.random() < chanceToFirePerNeuronPerTimestep) { neuron.getAxon().fire(firingAmplitude); } } public void setChanceToFirePerNeuronPerTimestep(double chanceToFirePerNeuronPerTimestep) { this.chanceToFirePerNeuronPerTimestep = chanceToFirePerNeuronPerTimestep; } }
Swift
UTF-8
1,615
3.25
3
[]
no_license
// // DogApi.swift // dog Api udacity task // // Created by Mostafa Diaa on 1/28/19. // Copyright © 2019 Mostafa Diaa. All rights reserved. // import Foundation import UIKit class dogApi { enum Endpoint: String { case random = "https://dog.ceo/api/breeds/image/random" var url: URL { return URL(string: rawValue)! } } class func convertUrlToImage(url: URL, completionHandeler: @escaping (UIImage?, Error?) -> Void) { let task = URLSession.shared.dataTask(with: url) { data, _, error in guard let imageData = data else { completionHandeler(nil, error) print("can't get the data") return } let downloadedImage = UIImage(data: imageData)! completionHandeler(downloadedImage, nil) } task.resume() } class func requestRandomImage(randomImageUrl: URL, completionHandeler: @escaping (dogImage?, Error?) -> Void) { let task = URLSession.shared.dataTask(with: randomImageUrl) { data, _, error in guard let dogData = data else { print("somthing wrong") completionHandeler(nil, error) return } do { // using codeable let decoder = JSONDecoder() let imageData = try decoder.decode(dogImage.self, from: dogData) completionHandeler(imageData, nil) } catch { print(error) completionHandeler(nil, error) } } task.resume() } }
Java
UTF-8
1,938
2.984375
3
[]
no_license
package training.supportbank; //everything we need to import// import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.util.HashMap; public class Main { //needed for the logger system toAccount work// private static final Logger LOGGER = LogManager.getLogger(); //the main class// public static void main(String args[]) throws IOException, ParserConfigurationException, SAXException, ParseException { //gets the file the person wants to extract// Select select = new Select(); String fileLocation = select.getChoice(); //gets and converts file into string// LOGGER.info("About toAccount read the file"); Path path = Paths.get("C:\\Work\\Training\\SupportBank-Java-Template\\" + fileLocation); byte[] bytes = Files.readAllBytes(path); String IOU = new String(bytes); //creates hashMap where people will be stored// HashMap<String, Person> hm; if (fileLocation.equals("Transactions2013.json")) { //send the array to create people// hm = PersonCreator.createPerson(JsonReader.readJson(IOU)); }else if(fileLocation.equals("Transactions2012.xml")){ //calls XmlReader if they have called the Xml file hm = PersonCreator.createPerson(XmlReader.readXml(IOU)); }else { //creates an array of transactions and then puts it in person// hm = PersonCreator.createPerson(CvsReader.readCvs(IOU)); } //outputs all the results// Output output = new Output(); output.printOutputs(hm); } }
C
UTF-8
179
2.703125
3
[]
no_license
#include<stdio.h> int main(){ int j=0; int k=0; for(j=0;j<=5;j=j+1){ for(k=0;k<=4;k=k+1){ printf("+"); } printf("+\n"); } printf("Fin del programa"); }
C++
UTF-8
570
2.8125
3
[]
no_license
#pragma once #include<SFML/Graphics.hpp> #include<iostream> class Obstacle { private: sf::RenderWindow& m_window; float carposx = 450, carposy=0, truckposx=750, truckposy=0; int speed = 1; int score =0; sf::Texture carTexture,truckTexture; float xpos[4] = { 475,725,1025,1325 }; sf::Sprite car; sf::Sprite truck; public: Obstacle(sf::RenderWindow& window) : m_window(window) {}; void loadTexture(); void drawObstacle(int choice, float xpos, float ypos, float xsize, float ysize); void callObstacle(); sf::Sprite getcar(); sf::Sprite gettruck(); };
Java
UTF-8
2,353
3.859375
4
[]
no_license
package euler12_highlydivisibletriangularnumber; /** * * @author Ben Walker */ public class Euler12_highlyDivisibleTriangularNumber { public static void main(String[] args) { int numberOfFactors = 0; long currentNumber = 1L; long triangularNumber = 0L; while (numberOfFactors < 500) { triangularNumber = getTriangularNumber(currentNumber); numberOfFactors = findNumberOfFactors(triangularNumber, currentNumber); currentNumber ++; } System.out.println("FIRST TRIANGULAR NUMBER TO HAVE OVER 500 DIVISORS: " + triangularNumber); } private static long getTriangularNumber (long number) { return number * (number + 1) / 2; } private static int findNumberOfFactors (long triangularNumber, long currentNumber) { if(currentNumber % 2 == 0) return findDivisorsForEven(currentNumber); else return findDivisorsForOdd(currentNumber); } private static int findDivisorsForEven (long currentNumber) { long nDividedBy2 = currentNumber / 2; long nPlus1 = currentNumber + 1; int numberOfDivisorsA = 0, numberOfDivisorsB = 0; for (long i = 1L; i <= Math.sqrt(nDividedBy2); i++) { if(nDividedBy2 % i == 0) numberOfDivisorsA ++; } numberOfDivisorsA *= 2; for (long i = 1L; i <= Math.sqrt(nPlus1); i++) { if(nPlus1 % i == 0) numberOfDivisorsB ++; } numberOfDivisorsB *= 2; return numberOfDivisorsA * numberOfDivisorsB; } private static int findDivisorsForOdd (long currentNumber) { long n = currentNumber; long nPlus1DividedBy2 = (currentNumber + 1) / 2; int numberOfDivisorsA = 0, numberOfDivisorsB = 0; for (long i = 1L; i <= Math.sqrt(n); i++) { if(n % i == 0) numberOfDivisorsA ++; } numberOfDivisorsA *= 2; for (long i = 1L; i <= Math.sqrt(nPlus1DividedBy2); i++) { if(nPlus1DividedBy2 % i == 0) numberOfDivisorsB ++; } numberOfDivisorsB *= 2; return numberOfDivisorsA * numberOfDivisorsB; } }
Markdown
UTF-8
1,145
3.3125
3
[ "Apache-2.0" ]
permissive
## Dungeon Game [ [sourcecode](../src/dungeon-game.cpp) | [problem](https://leetcode.com/problems/dungeon-game/) ] ##解法分析 knight从左上角开始,每次向左或者向下走一次,走到右下角需要多少生命力。生命力为0时死亡。 解法1:假设knignt以0生命力一直走,health[i][j]表示knight走到map[i][j]之后可能保留的生命值的最大值,如果是负数-a就表示kngiht至少要a+1的生命值才能活着走到map[i][j]。 health[i][j]=max(health[i-1][j], health[i][j-1])+map[i][j]. 然后只需要遍历一遍health[i][j]找出最小值,时间空间,空间复杂度都是O(mn)。 优化空间复杂度:health[i][j]只与health[i-1][j], health[i][j-1]相关。从左上角开始一行一行扫描更新health,扫描到map[i][j]时,更新health[i][j+1],health[i+1][j], 更新之后health[i][j+1]的值就是最大生命值。简化成一维数组记录。 health[j] = max(health[j-1],health[j]) 解法2:从右下角倒推。 ##步骤或伪代码 ``` health[0] = map[0][0]; for (i,j) in map: health[j] = max(health[j-1], health[j]) + map[i][j] return health[m] ```
Python
UTF-8
432
3.15625
3
[]
no_license
import sys from io import StringIO import contextlib @contextlib.contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = stdout yield stdout sys.stdout = old code = """ i = [0,1,2] for j in i : print(j) """ with stdoutIO() as s: try: exec(code) except: print("Something wrong with the code") print("out:", s.getvalue())
Java
UTF-8
5,766
1.984375
2
[]
no_license
package activity.buy; import java.util.ArrayList; import java.util.HashMap; import util.BuyUtil; import util.PicUtil; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.DisplayMetrics; import android.view.Menu; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.ebay.ebayfriend.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; public class BuyActivity extends Activity { private ImageLoadingListener animateFirstListener = new PicUtil.AnimateFirstDisplayListener(); private GridView gv; private TextView description = null; private HashMap<String, Object> dataList = new HashMap<String, Object>(); private ArrayList<String> urlList = new ArrayList<String>(); private BuyHandler buyHandler; private String goodsId; private GridViewAdapter adapter; private TextView title; private ImageView buyBt; private PurchaseHandler purchaseHandler; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); Intent intent = getIntent(); Bundle b = intent.getExtras(); goodsId = b.getString("goodsId"); // // goodsId = "5195ab587985f706f8f8abc9"; super.onCreate(savedInstanceState); setContentView(R.layout.activity_buy); adapter = new GridViewAdapter(); buyHandler = new BuyHandler(); purchaseHandler = new PurchaseHandler(); gv = (GridView) findViewById(R.id.buy_grid_view); gv.setAdapter(adapter); buyBt = (ImageView) findViewById(R.id.buy_buy); buyBt.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Thread buyThread = new BuyThread(goodsId); buyThread.start(); } }); Thread thread = new LoadDataThread(); thread.start(); // try { // thread.join(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // ll.setBackgroundColor(Color.BLACK); } class LoadDataThread extends Thread{ @Override public void run(){ dataList = BuyUtil.getGoodsInfo(goodsId); urlList = (ArrayList<String>) dataList.get("pictures"); buyHandler.sendMessage(new Message()); } } class BuyHandler extends Handler{ public BuyHandler(){ } public BuyHandler(Looper l){ } @Override public void handleMessage(Message msg){ int size = urlList.size(); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); float density = dm.density; int allWidth = (int) (310 * size * density); int itemWidth = (int) (300 * density); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( allWidth, LinearLayout.LayoutParams.WRAP_CONTENT); gv.setLayoutParams(layoutParams); gv.setColumnWidth(itemWidth); gv.setHorizontalSpacing(10); gv.setStretchMode(GridView.NO_STRETCH); gv.setNumColumns(size); title = (TextView)BuyActivity.this.findViewById(R.id.buy_title); title.setText((String)dataList.get("name")); description = (TextView)BuyActivity.this.findViewById(R.id.description); description.setText((String)dataList.get("description")); gv.invalidate(); title.invalidate(); description.invalidate(); adapter.notifyDataSetChanged(); } } @SuppressLint("HandlerLeak") class PurchaseHandler extends Handler{ public PurchaseHandler (){ } public PurchaseHandler(Looper l){ } @Override public void handleMessage(Message msg){ Toast.makeText(getApplicationContext(), "Purchase Success", Toast.LENGTH_LONG).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.buy, menu); return true; } class GridViewAdapter extends BaseAdapter { @Override public int getCount() { return urlList.size(); } @Override public String getItem(int position) { return urlList.get(position - 1); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = getLayoutInflater().inflate(R.layout.buy_grid_view, null); ImageView iv = (ImageView) convertView.findViewById(R.id.buy_imageView); iv.setScaleType(ScaleType.CENTER_CROP); DisplayImageOptions options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.ic_stub) .showImageForEmptyUri(R.drawable.ic_empty) .showImageOnFail(R.drawable.ic_error).cacheInMemory() .cacheOnDisc().displayer(new RoundedBitmapDisplayer(0)) .build(); String picUrl = urlList.get(position); ImageLoader.getInstance().displayImage(picUrl, iv, options, animateFirstListener); return convertView; } } class BuyThread extends Thread{ private String goodsId; public BuyThread(String id){ this.goodsId=id; } @Override public void run(){ BuyUtil.buy(goodsId); Message msg = new Message(); purchaseHandler.sendMessage(msg); } } }
PHP
UTF-8
1,556
2.53125
3
[]
no_license
<?php /* Plugin Name: Include Me Plugin URI: http://www.satollo.net/plugins/include-me Description: Include external HTML or PHP in any post or page. Version: 1.1.1 Author: Stefano Lissa Author URI: http://www.satollo.net */ if (is_admin()) { include dirname(__FILE__) . '/admin.php'; } else { function includeme_call($attrs, $content = null) { if (isset($attrs['file'])) { $file = strip_tags($attrs['file']); if ($file[0] != '/') $file = ABSPATH . $file; ob_start(); include($file); $buffer = ob_get_clean(); $options = get_option('includeme', array()); if (isset($options['shortcode'])) { $buffer = do_shortcode($buffer); } } else { $tmp = ''; foreach ($attrs as $key => $value) { if ($key == 'src') { $value = strip_tags($value); } $value = str_replace('&amp;', '&', $value); if ($key == 'src') { $value = strip_tags($value); } $tmp .= ' ' . $key . '="' . $value . '"'; } $buffer = '<iframe' . $tmp . '></iframe>'; } return $buffer; } // Here because the funciton MUST be define before the "add_shortcode" since // "add_shortcode" check the function name with "is_callable". add_shortcode('includeme', 'includeme_call'); }
Java
UTF-8
1,401
2.90625
3
[]
no_license
package edu.mum.cs.projects.attendance.service; import java.util.List; import edu.mum.cs.projects.attendance.domain.entity.CourseOffering; public class AttendanceServiceImpl implements AttendanceService { CourseService courseService = ServiceFactory.getCourseService(); @Override public void createStudentAttendanceSpreadsheetsForBlock(String blockId) { // 1) Using blockId, get the list of course offerings for that particular block List<CourseOffering> offerings = courseService.getCourseOfferingListbyBlockId(blockId); offerings.forEach(System.out::println); // 2) Loop over all the course offerings // 3) For each course offering, get the list of registrations for that course from // course service // 4) For each registration object, get the student // 5) Get the list of barcode-records for each student (filter based on start and end date of the block) // 6) Get the list of sessions for the block from course service // 7) Create an attendance list or array based on the number of sessions in that block // 8) For each student, loop over all sessions and determine (from the barcode records // list) if the student has been present for that session // 9) Save the attendance info for each course offering in a separate spreadsheet // Note: Each course offering will have a list of students } }
PHP
UTF-8
1,502
2.796875
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; class TempUser extends Model { public $timestamps = false; protected $table = 'temp_users'; protected $fillable = [ 'name','email','password','lang','referral','code','try','time' ]; public function __construct(array $attributes = []) { if (! isset($attributes['code'])) { $attributes['code'] = $this->generateCode(); } $attributes['try'] = 0; parent::__construct($attributes); } /** * Generate a six digits code * * @param int $codeLength * @return string */ public function generateCode() { $code = mt_rand(100000,999999); return ''.$code; } /** * True if the token is not used nor expired * * @return bool */ public function isValid() { return ! $this->isVerified() && ! $this->isExpired(); } /** * Is the current token used * * @return bool */ public function isVerified() { return $this->verified; } public function manyTrid() { $tryTime = env('TOKEN_TRY_TIME'); return $this->try > $tryTime; } /** * Is the current token expired * * @return bool */ public function isExpired() { $expireTime = env('OTA_TOKEN_EXPIRE'); return $this->created_at < Carbon::now()->subMinutes($expireTime) ; } }
C++
UTF-8
1,289
2.8125
3
[ "MIT" ]
permissive
#ifndef __TARGET_FIELD_CPP__ #define __TARGET_FIELD_CPP__ 1 #include "target_field.hpp" #include <list> #include <exception> #include <Eigen/Dense> TargetField::TargetField( const double p_x_size, const double p_y_size, const int p_num_cells ) : x_size_(p_x_size), y_size_(p_y_size), num_cells_(p_num_cells) {} TargetField::~TargetField() {} TargetField& TargetField::add_target(const TargetField::Target& p_target) { targets_.push_back(p_target); return *this; // for call chaining } std::vector<TargetField::Target> TargetField::get_targets() const { return targets_; } Eigen::MatrixXd TargetField::as_cells() const { Eigen::MatrixXd cells(num_cells_, num_cells_); cells.setZero(); return cells; }; std::pair<double, double> TargetField::coordinates_of_cell( const int p_cell_x, const int p_cell_y ) const { return {0, 0}; } /** * Inner Class things */ TargetField::Target::Target( const double p_value, const std::pair<double, double> p_coordinates ) : value_(p_value), coordinates_(p_coordinates) {} TargetField::Target::~Target() {}; double TargetField::Target::value() const { return value_; } std::pair<double, double> TargetField::Target::coordinates() const { return coordinates_; } #endif //__TARGET_FIELD_CPP__
Markdown
UTF-8
867
2.609375
3
[ "MIT" ]
permissive
--- title: Brady Moon subtitle: Ph.D. Student job_title: Ph.D. Student category: phd_student layout: team_member_personal_page image: /img/team/brady.jpg hide_footer: true --- Brady Moon is a PhD student in the [Robotics Institute](https://www.ri.cmu.edu "Robotics Institute Homepage") at Carnegie Mellon University. He graduated *summa cum laude* from Brigham Young University with a B.S. in electrical engineering. Brady's passion is to improve the quality of people's lives through robot autonomy. He's obsessed with great design, innovation, and continual learning. His research is primarily focused on path planning, motion planning, machine learning, and autonomy. <br> **Website**: [bradymoon.com](https://bradymoon.com) **Email**: [bradygmoon@cmu.edu](mailto:bradygmoon@cmu.edu) **Github**: [bradygm](https://github.com/bradygm) <!-- <big><i class="fab fa-github"></i></big> -->
Java
UTF-8
1,465
2.625
3
[]
no_license
package sg.edu.np.twq2.e53listview; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class CustomLayoutActivity extends AppCompatActivity { List<Song> data = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_layout); for (int i = 0; i < 20; i++) { data.add(new Song("T" + i, "a" + i, "0:" + i)); } SongsAdapter itemsAdapter = new SongsAdapter(this, R.layout.item_song_layout, data); ListView listView = findViewById(R.id.lvCustom); listView.setAdapter(itemsAdapter); // Set an item click listener for ListView listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Song selectedItem = (Song) parent.getItemAtPosition(position); new AlertDialog.Builder(CustomLayoutActivity.this) .setMessage("You have selected " + selectedItem.getTitle()) .show(); } }); } }
Java
UTF-8
4,439
2.546875
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package render; import jinngine.math.*; import javax.media.opengl.GL2; import javax.media.opengl.GL; import javax.media.opengl.glu.GLU; /** * * @author shua */ public class Camera { private GLU glu = new GLU(); private int width = 800; private int height = 600; private int drawHeight = (int)(800.0/1.333333); private double zoom = 1; private double[] proj = null; private double[] mat = new double[16]; private Matrix4 inv; private boolean dirty = true; private boolean dirtyrot = true; private boolean dirtyinv = true; private Vector3 pos = new Vector3(0,0,0); private double pitch = 0; private double yaw = 0; private double roll = 0; private Quaternion rot = new Quaternion(); public Camera() { this.getGLMat(); } public Camera(Vector3 ps, double p, double y, double r) { pos = ps; this.setPitch(p); this.setYaw(y); this.setRoll(r); this.getGLMat(); } public void glSetProjection(GL c, int w, int h) { if(proj == null) proj = new double[16]; //GL2 gl = GLU.getCurrentGL().getGL2(); GL2 gl = c.getGL2(); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); //gl.glFrustum(-1.33333333*zoom, 1.3333333*zoom, -1.0*zoom, 1.0*zoom, 0.1, 50.0); glu.gluPerspective(60.0*zoom,((double)w)/h,1.0,100.0); height = h; width = w; drawHeight = (int)((double)w/1.3333333); gl.glViewport (0, (int)((h-drawHeight)/2.0), (int)w, (int)drawHeight); gl.glGetDoublev(GL2.GL_PROJECTION_MATRIX, proj, 0); dirtyinv = true; } public void glSetCamera(GL c) { //GL2 gl = GLU.getCurrentGL().getGL2(); GL2 gl = c.getGL2(); gl.glLoadIdentity(); gl.glMultMatrixd(this.getGLMat(), 0); } public Matrix4 getInverseTransform() { if(dirty|dirtyrot|dirtyinv) { if(proj==null) { proj = new Matrix4().toArray(); } inv = (new Matrix4(proj).multiply(new Matrix4(getGLMat())).inverse()); dirtyinv = false; } return inv; } public int[] getDim() { int[] ret = {width, height}; return ret; } public double getZoom() { return zoom; } public double getDrawHeight() { return drawHeight; } public Vector3 getPos() { return new Vector3(pos); } public Vector3 getEul() { return new Vector3(pitch, yaw, roll); } public Quaternion getInvQuat() { if(dirtyrot) { Quaternion r = Quaternion.rotation(-roll, new Vector3(0,0,1)); Quaternion p = Quaternion.rotation(-pitch, new Vector3(1,0,0)); Quaternion y = Quaternion.rotation(-yaw, new Vector3(0,1,0)); rot = r.multiply(p.multiply(y)); } dirtyrot = false; return rot; } public double[] getGLMat() { if(dirty | dirtyrot) { mat = Transforms.rotateAndTranslate4(getInvQuat(), pos.negate()).toArray(); } dirty = false; dirtyrot = false; return mat; } public Camera setGLU(GLU v) { glu = v; return this; } public Camera setZoom(double z) { zoom = Math.max(0.01,z); glSetProjection(GLU.getCurrentGL(), width, height); return this; } public Camera setPos(Vector3 p) { dirty |= (pos != (pos = p)); return this; } public Camera setPitch(double p) { dirtyrot |= (pitch != (pitch = Math.min(Math.PI/2, Math.max(p, Math.PI/-2)))); return this; } public Camera setYaw(double y) { dirtyrot |= (yaw != (yaw = y%(2*Math.PI))); return this; } public Camera setRoll(double r) { dirtyrot |= (roll != (roll = r%(2*Math.PI))); return this; } public Camera lookAt(Vector3 what) { Vector3 local = what.add(new Vector3(pos).negate()); this.setYaw(Math.asin(local.x/Math.sqrt(local.x*local.x+local.z*local.z))); this.setPitch(Math.asin(local.y/Math.sqrt(local.z*local.z+local.y*local.y))); return this; } }
Java
UTF-8
3,345
1.953125
2
[]
no_license
package com.jule.robot.config; import com.jule.core.configuration.ConfigurableProcessor; import com.jule.core.configuration.Property; import com.jule.core.database.DatabaseConfig; import com.jule.core.jedis.JedisConfig; import com.jule.core.utils.PropertiesUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; /** * @author SmartGuo */ public class Config { protected static final Logger log = LoggerFactory.getLogger(Config.class); @Property(key = "robot.bind.port", defaultValue = "9009") public static int ROBOT_BIND_PORT; @Property(key = "gate.svr.uri", defaultValue = "") public static String GATE_SVR_URI; @Property(key = "robot.desk.robot.max.num", defaultValue = "0") public static int ROBOT_DESK_ROBOT_NUM; @Property(key = "robot.desk.player.min.num", defaultValue = "0") public static int ROBOT_DESK_PLAYER_NUM; @Property(key = "robot.total.robot.num", defaultValue = "3000") public static int ROBOT_TOTAL_ROBOT_NUM; @Property(key = "check.thread.interval.sec", defaultValue = "3") public static int CHECK_THREAD_INTERVAL_SEC; @Property(key = "test.type.is.local", defaultValue = "0") public static int TEST_TYPE_IS_LOCAL; @Property(key = "test.type.is.stress", defaultValue = "0") public static int TEST_TYPE_IS_STRESS; @Property(key = "robot.join.null.table", defaultValue = "0") public static int ROBOT_JOIN_NULL_TABLE; @Property(key = "robot.join.null.max.ante", defaultValue = "20") public static int ROBOT_JOIN_NULL_MAX_ANTE; /**日志服*/ @Property(key = "app.log.url", defaultValue = "http://10.0.0.92:59001") public static String LOG_URL; @Property(key = "tomail.list", defaultValue = "guoxu@joloplay.com") public static String TO_MAIL_LIST; @Property(key = "robot.reward.croupier", defaultValue = "10") public static int ROBOT_REWARD_CROUPIER; @Property(key = "robot.give.gift", defaultValue = "5") public static int ROBOT_GIVE_GIFT; @Property(key = "robot.give.gift.win.bootamount", defaultValue = "20") public static int ROBOT_GIVE_GIFT_WIN_BOOTAMOUNT; //机器人连接最长的存活时间,超过此时间,断开机器人连接 @Property(key = "robot.timout.minute", defaultValue = "60") public static int ROBOT_TIMEOUT_MINUTE; @Property(key = "game.encryption.key", defaultValue = "") public static String GAME_ENCRYPE_KEY; @Property(key = "game.encryption.isOpen", defaultValue = "false") public static boolean GAME_ENCRYPE_ISOPEN; /** * Load configs from files. */ public static void load() { try { Properties myProps = null; try { log.info("Loading: mycs.properties"); myProps = PropertiesUtils.load("./config/mycs.properties"); } catch (Exception e) { log.info("No override properties found"); } Properties[] props = PropertiesUtils.loadAllFromDirectory("./config/network"); PropertiesUtils.overrideProperties(props, myProps); log.info("Loading: robot.properties"); ConfigurableProcessor.process(Config.class, props); log.info("Loading: redis.properties"); ConfigurableProcessor.process(JedisConfig.class, props); log.info("Loading: database.properties"); ConfigurableProcessor.process(DatabaseConfig.class, props); } catch (Exception e) { log.error("Can't load room configuration", e); throw new Error("Can't load room configuration", e); } } }
Python
UTF-8
660
3.234375
3
[]
no_license
from typing import List class Solution: def trap(self, height: List[int]) -> int: stack = [] ans = 0 for i in range(len(height)): while stack and height[stack[-1]] <= height[i]: last = stack.pop() # 取出当前栈顶高度 if not stack: break else: ans += (min(height[i], height[stack[-1]]) - height[last]) * (i - stack[-1] - 1) stack.append(i) return ans if __name__ == "__main__": print(Solution().trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) # 6 print(Solution().trap([5, 2, 1, 2, 1, 5])) # 14
PHP
UTF-8
617
2.90625
3
[ "MIT" ]
permissive
<?php namespace Ionut\Sylar\Receivers; use Ionut\Sylar\Alert; use Ionut\Sylar\Guardian; abstract class Receiver { /** * @var Guardian */ public $listener; abstract public function __construct(Guardian $listener); abstract public function call(Alert $alert); public function allowed() { return (bool)$this->getConfig(); } public function getConfig() { return $this->listener->config['receivers'][$this->getShortName()]; } public function getShortName() { $long = get_class($this); $short = explode('\\', $long); $short = $short[count($short) - 1]; return strtolower($short); } }
JavaScript
UTF-8
2,552
2.625
3
[]
no_license
const jwt = require('jsonwebtoken'); const crypto = require('crypto'); const User = require('../models/user'); const config = require('../config/main'); const generateToken = user => { return jwt.sign(user, config.secret, { expiresIn: 10080 // in seconds }); }; const setUserInfo = request => { return { _id: request._id, firstName: request.profile.firstName, lastName: request.profile.lastName, email: request.email, role: request.role }; }; // Login Route exports.login = (req, res, next) => { console.log(req.user); const userInfo = setUserInfo(req.user); res.status(200).json({ token: `JWT ${generateToken(userInfo)}`, user: userInfo }); }; //Registeration Route exports.register = (req, res, next) => { //check registeration errors const email = req.body.email; const firstName = req.body.firstName; const lastName = req.body.lastName; const password = req.body.password; // Return error if no email provided if (!email) { return res.status(422).json({ error: 'You must enter an email address' }); } // Return error if full name not provided if (!firstName || !lastName) { return res.status(422).send({ error: 'You must enter your full name.' }); } // Return error if no password provided if (!password) { return res.status(422).send({ error: 'You must enter a password.' }); } User.findOne({ email: email }) .then(existingUser => { if (existingUser) { return res .status(422) .send({ error: 'That email address is already in use.' }); } let user = new User({ email: email, password, profile: { firstName: firstName, lastName: lastName } }); //Saving user user .save() .then(user => { let userInfo = setUserInfo(user); res.status(201).json({ token: `JWT ${generateToken(userInfo)}`, user: userInfo }); }) .catch(err => next(err)); }) .catch(err => next(err)); }; //======================================== // Authorization Middleware //======================================== // Role authorization check exports.roleAuthorization = role => { return (req, res, next) => { const user = req.user; User.findById(user._id).then(user => { if (user.role === role) { return next(); } res .status(401) .json({ error: 'You are not authorized to view this content.' }); return next('Unauthorized'); }); }; };
JavaScript
UTF-8
691
2.90625
3
[]
no_license
window.onload = function () { // var active = $('li.active'); // var activePill = active.find('a').attr('id'); // var content = $('.details .' + activePill); // console.log(content); // //content.css('display', 'block'); $('li').on("click", function(){ // remove all active classes $('.about-list li').removeClass('active'); $('.about-list div.details').removeClass('active'); // find out which li was clicked, grap the 'id' for that var newlyActive = $(this); newlyActive.addClass('active'); var contentType = newlyActive.find('a').attr('id'); // make the corresponding content 'active' $('.about-list div.details.' + contentType).addClass('active'); }); };
Python
UTF-8
545
3.875
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Mar 2 14:33:48 2017 @author: Nick Lai """ ''' for the_char in 'hi mom': print(the_char) print() s = 'chapman' print( for x in s: print(x) for letter in s: print(letter) for watermelon in s: print(watermelon) ) ''' s = 'hello world' v = 'aeiou' for c in s: if c in v: print("There is a vowel...dumbass") for c in s: if c in 'o': #if c =='o': print("There is an o...didn't you type this shit in?")
Java
UTF-8
1,203
2.4375
2
[]
no_license
package com.example.administrator.text1.ui.testCanvas.testChart; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.util.AttributeSet; import android.view.View; /** * 功能描述:自定义虚线 * Created by hzhm on 2016/6/7. */ public class TextHiddenLine extends View { private Paint mPaint; public TextHiddenLine(Context context) { super(context); } public TextHiddenLine(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setColor(Color.DKGRAY); mPaint.setStyle(Paint.Style.STROKE); Path path = new Path(); //设置路径的起始点坐标 path.moveTo(0, 100); path.lineTo(480, 100); //设置虚线 PathEffect effects = new DashPathEffect(new float[]{5, 5, 5, 5}, 0); mPaint.setPathEffect(effects); canvas.drawPath(path, mPaint); } }
Markdown
UTF-8
1,979
3.1875
3
[ "MIT" ]
permissive
# vue-doctitle > Simple plugin for switching document title on transitions between routes (for VueRouter) ## Installation You can install this plugin globally or included in `dependencies` (in package.json) ```bash $ npm install vue-doctitle ``` ## Functionality and features - Switching page(document) title on transitions between routes ## Integration To use `VueDocTitle` in your app: ### 1. Simple Way: #### Importing and wrap VueRouter by VueDocTitle plugin > In your entry point (usually it's index.js or main.js) ```js import Vue from 'vue' import VueRouter from 'vue-router' import VueDocTitle from 'vue-doctitle' ...(ignore lines of codes) var router = new VueRouter({ // your set of options }) // defTitle in param 2, means default title if not set in any routes // filter in param 2, means to filter titles as you want VueDocTitle.wrap(router, { defTitle: 'my app', filter: function (title) { return 'my app - ' + title } }) router.map({ '': { component: Index }, '/a': { component: A, doctitle: 'my app - component a' // special document title of component A } ...(other routes) }) router.start(...) // start ...(ignore lines of codes) ``` **NOTE:** > `VueDocTitle.wrap` must be invoked before `router.start` ### 2. Directive Way: #### Importing and registering VueRouter plugin > In your entry point (usually it's index.js or main.js) ```js import Vue from 'vue' import VueDocTitle from 'vue-doctitle' ...(ignore lines of codes) Vue.use(VueDocTitle) ``` #### use directive in page components 1.dynamic (bind prop or data) ```html <template> <template v-doctitle="boundPropsOrData"></template> <...> <!-- other elements of component --> </template> ``` 2.literal ```html <template> <template v-doctitle.literal="my app - component xx"></template> <...> <!-- other elements of component --> <template> ``` **NOTE:** > Ways above can be used together > if both ways used, the directive way is prior
Go
UTF-8
2,354
4.34375
4
[]
no_license
package main import ( "fmt" "math" ) /* * Let us assume the following formula for displacement s as a function of * time t, acceleration a, initial velocity vo, and initial displacement so. * * s = 1/2 * a * t^2 + v_0 * t + s_0 * * Write a program which first prompts the user to enter values for * acceleration, initial velocity, and initial displacement. * Then the program should prompt the user to enter a value for time and the * program should compute the displacement after the entered time. * * You will need to define and use a function called GenDisplaceFn() which * takes three float64 arguments, acceleration a, initial velocity v_0, and * initial displacement s_0. * GenDisplaceFn() should return a function which computes displacement as * a function of time, assuming the given values acceleration, initial * velocity, and initial displacement. The function returned by * GenDisplaceFn() should take one float64 argument t, representing time, * and return one float64 argument which is the displacement travelled * after time t. * * For example, let’s say that I want to assume the following values for * acceleration, initial velocity, and initial displacement: * a = 10, vo = 2, so = 1. I can use the * following statement to call GenDisplaceFn() to generate a function fn * which will compute displacement as a function of time. * * fn := GenDisplaceFn(10, 2, 1) * * Then I can use the following statement to print the displacement after 3 * seconds. * * fmt.Println(fn(3)) * * And I can use the following statement to print the displacement after 5 * seconds. * * fmt.Println(fn(5)) */ func RequestValues() (float64, float64, float64, float64) { var acc, v0, s0, time float64 fmt.Print("Acceleration: ") fmt.Scanln(&acc) fmt.Print("Initial velocity: ") fmt.Scanln(&v0) fmt.Print("Initial displacement: ") fmt.Scanln(&s0) fmt.Print("Time: ") fmt.Scanln(&time) return acc, v0, s0, time } func GenDisplaceFn(acc, v0, s0 float64) func(time float64) float64 { return func(time float64) float64 { // s = 1/2 * a * t^2 + v_0 * t + s_0 partOne := 0.5 * acc * math.Pow(time, 2) partTwo := v0 * time return partOne + partTwo + s0 } } func main() { acc, v0, s0, time := RequestValues() displacementFn := GenDisplaceFn(acc, v0, s0) fmt.Printf("%f", displacementFn(time)) }
Python
UTF-8
733
2.84375
3
[]
no_license
# TIME - O(e + q * |V|!) v is number of variables # SPACE - O(e) def evaluateDivision(equations, values, queries): def dfs(n,d,visited): if n in lookup and d in lookup[n]: return (True, lookup[n][d]) for i,v in lookup[n].iteritems(): if i not in visited: visited.add(i) tmp = dfs(i,d,visited) if tmp[0]: return (True,v * tmp[1]) return (False,0) lookup = collections.defaultdict(dict) for i,e in enumerate(equations): lookup[e[0]][e[1]] = values[i] if values[i]: lookup[e[1]][e[0]] = 1.0/values[i] res = [] for q in queries: visited = set() tmp = dfs(q[0],q[1],visited) res.append(tmp[1] if tmp[0] else -1.0) return res
C#
WINDOWS-1250
6,246
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Miner.Enums; using Miner.GameInterface.MenuEntries; namespace Miner.GameInterface.GameScreens { /// <summary> /// Klasa bazowa dla wszystkich ekranw w menu /// </summary> public abstract class MenuScreen : GameScreen { int _selectedEntry = 0; /// <summary> /// Lista klawiszy odpowiedzialnych za zmian opcji na wysz /// </summary> protected InputAction MenuUp; /// <summary> /// Lista klawiszy odpowiedzialnych za zmian opcji na nisz /// </summary> protected InputAction MenuDown; /// <summary> /// Lista klawiszy odpowiedzialnych za wybranie opcji /// </summary> protected InputAction MenuSelect; /// <summary> /// Lista klawiszy odpowiedzialnych za wyjcie z ekranu /// </summary> protected InputAction MenuCancel; /// <summary> /// Wysoko na ktrej jest narysowany tytu ekranu /// </summary> protected float TitlePositionY { get; set; } /// <summary> /// Wysoko, na ktrej zaczyna si rysowanie opcji menu /// </summary> protected float MenuEntriesPositionY { get; set; } /// <summary> /// Tytu ekranu /// </summary> public string MenuTitle { get; set; } /// <summary> /// Opcje w menu /// </summary> protected List<MenuEntry> MenuEntries { get; private set; } public MenuScreen(string menuTitle) { MenuEntries = new List<MenuEntry>(); MenuTitle = menuTitle; TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); MenuUp = new InputAction( new Keys[] { Keys.Up }, true); MenuDown = new InputAction( new Keys[] { Keys.Down }, true); MenuSelect = new InputAction( new Keys[] { Keys.Enter, Keys.Space }, true); MenuCancel = new InputAction( new Keys[] { Keys.Escape }, true); TitlePositionY = 325; MenuEntriesPositionY = 400; } public override void HandleInput(GameTime gameTime, InputState input) { if (MenuUp.IsCalled(input)) { _selectedEntry--; if (_selectedEntry < 0) _selectedEntry = MenuEntries.Count - 1; } if (MenuDown.IsCalled(input)) { _selectedEntry++; if (_selectedEntry >= MenuEntries.Count) _selectedEntry = 0; } if (MenuSelect.IsCalled(input)) { OnSelectEntry(_selectedEntry); } else if (MenuCancel.IsCalled(input)) { OnCancel(); } } /// <summary> /// Co ma si sta po wybraniu opcji? /// </summary> /// <param name="entryIndex">numer opcji</param> protected virtual void OnSelectEntry(int entryIndex) { MenuEntries[entryIndex].OnEnter(); } /// <summary> /// Akcje wykonywane podczas anulowania ekranu /// </summary> protected virtual void OnCancel() { ExitScreen(); } protected void OnCancel(object sender, EventArgs e) { OnCancel(); } /// <summary> /// Aktualizuje pozycje opcji podczas pojawiania si/znikania ekranu /// </summary> protected virtual void UpdateMenuEntryLocations() { var transitionOffset = (float)Math.Pow(TransitionPosition, 2); var position = new Vector2(0,MenuEntriesPositionY); foreach (var menuEntry in MenuEntries) { // each entry is to be centered horizontally position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2; if (ScreenState == EScreenState.TransitionOn) position.X -= transitionOffset * 256; else position.X += transitionOffset * 512; menuEntry.Position = position; position.Y += menuEntry.GetHeight(this); } } public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (_selectedEntry < 0) _selectedEntry = 0; else if (_selectedEntry > MenuEntries.Count - 1) _selectedEntry = MenuEntries.Count - 1; for (int i = 0; i < MenuEntries.Count; i++) { bool isSelected = IsActive && (i == _selectedEntry); MenuEntries[i].Update(this, isSelected, gameTime); } } public override void Draw(GameTime gameTime) { // make sure our entries are in the right place before we draw them UpdateMenuEntryLocations(); GraphicsDevice graphics = ScreenManager.GraphicsDevice; SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; spriteBatch.Begin(); // Draw each menu entry in turn. for (int i = 0; i < MenuEntries.Count; i++) { MenuEntry menuEntry = MenuEntries[i]; menuEntry.Draw(this, gameTime); } float transitionOffset = (float)Math.Pow(TransitionPosition, 2); // Draw the menu title centered on the screen Vector2 titleOrigin = font.MeasureString(MenuTitle) / 2; Color titleColor = new Color(255, 255, 255) * TransitionAlpha; float titleScale = 1.25f; var titlePosition = new Vector2(ScreenManager.GraphicsDevice.Viewport.Width/2,TitlePositionY - transitionOffset*100); spriteBatch.DrawString(font, MenuTitle, titlePosition, titleColor, 0, titleOrigin, titleScale, SpriteEffects.None, 0); spriteBatch.End(); } } }
Java
UTF-8
301
2.734375
3
[]
no_license
/** * Created by abran on 17.11.2016. */ public class IdGenerator { private static long id = 111111111; public static long getId() { id++; if (id==999999999) { System.out.println("WARNING: ID LIMIT REACHED!!!!"); } return id; } }
Markdown
UTF-8
1,547
3.65625
4
[ "MIT" ]
permissive
# Insertion Sort This project contains a skeleton for you to implement Insertion Sort. In the file **lib/insertion_sort.js**, you should implement the Insertion Sort. The algorithm can be summarized as the following: 1. If it is the first element, it is already sorted. return 1; 2. Pick next element 3. Compare with all elements in the sorted sub-list 4. Shift all the elements in the sorted sub-list that is greater than the value to be sorted 5. Insert the value 6. Repeat until list is sorted This is a description of how the Insertion Sort works (and is also in the code file). ``` procedure insertionSort( A : array of items ) int holePosition int valueToInsert for i = 1 to length(A) inclusive do: /* select value to be inserted */ valueToInsert = A[i] holePosition = i /*locate hole position for the element to be inserted */ while holePosition > 0 and A[holePosition-1] > valueToInsert do: A[holePosition] = A[holePosition-1] holePosition = holePosition -1 end while /* insert the number at hole position */ A[holePosition] = valueToInsert end for end procedure ``` * Clone the project from https://github.com/appacademy-starters/algorithms-insertion-sort-starter. * `cd` into the project folder * `npm install` to install dependencies in the project root directory * `npm test` to run the specs * You can view the test cases in `/test/test.js`. Your job is to write code in the `/lib/insertion_sort.js` that implements the Insertion Sort.
C#
UTF-8
4,934
2.5625
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.GaussDB.V3.Model { /// <summary> /// /// </summary> public class RestoreRequest { /// <summary> /// 目标实例ID。 /// </summary> [JsonProperty("target_instance_id", NullValueHandling = NullValueHandling.Ignore)] public string TargetInstanceId { get; set; } /// <summary> /// 源实例ID。 /// </summary> [JsonProperty("source_instance_id", NullValueHandling = NullValueHandling.Ignore)] public string SourceInstanceId { get; set; } /// <summary> /// 用于恢复的备份ID。当使用备份文件恢复时需要指定该参数。 /// </summary> [JsonProperty("backup_id", NullValueHandling = NullValueHandling.Ignore)] public string BackupId { get; set; } /// <summary> /// 恢复数据的时间点,格式为UNIX时间戳,单位是毫秒,时区为UTC。 /// </summary> [JsonProperty("restore_time", NullValueHandling = NullValueHandling.Ignore)] public long? RestoreTime { get; set; } /// <summary> /// 表示恢复方式,枚举值: - backup:表示使用备份文件恢复,按照此方式恢复时,当\&quot;type\&quot;字段为非必选时,\&quot;backup_id\&quot;必选。 - timestamp:表示按时间点恢复,按照此方式恢复时,当\&quot;type\&quot;字段必选时,\&quot;restore_time\&quot;必选。 /// </summary> [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] public string Type { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RestoreRequest {\n"); sb.Append(" targetInstanceId: ").Append(TargetInstanceId).Append("\n"); sb.Append(" sourceInstanceId: ").Append(SourceInstanceId).Append("\n"); sb.Append(" backupId: ").Append(BackupId).Append("\n"); sb.Append(" restoreTime: ").Append(RestoreTime).Append("\n"); sb.Append(" type: ").Append(Type).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as RestoreRequest); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(RestoreRequest input) { if (input == null) return false; return ( this.TargetInstanceId == input.TargetInstanceId || (this.TargetInstanceId != null && this.TargetInstanceId.Equals(input.TargetInstanceId)) ) && ( this.SourceInstanceId == input.SourceInstanceId || (this.SourceInstanceId != null && this.SourceInstanceId.Equals(input.SourceInstanceId)) ) && ( this.BackupId == input.BackupId || (this.BackupId != null && this.BackupId.Equals(input.BackupId)) ) && ( this.RestoreTime == input.RestoreTime || (this.RestoreTime != null && this.RestoreTime.Equals(input.RestoreTime)) ) && ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.TargetInstanceId != null) hashCode = hashCode * 59 + this.TargetInstanceId.GetHashCode(); if (this.SourceInstanceId != null) hashCode = hashCode * 59 + this.SourceInstanceId.GetHashCode(); if (this.BackupId != null) hashCode = hashCode * 59 + this.BackupId.GetHashCode(); if (this.RestoreTime != null) hashCode = hashCode * 59 + this.RestoreTime.GetHashCode(); if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); return hashCode; } } } }
Rust
UTF-8
1,883
2.84375
3
[]
no_license
use uuid::Uuid; use comm::mpmc::bounded::Channel; use queue::{Queue, Queues}; use std::sync::{Arc, RwLock}; use std::collections::HashMap; #[derive(Clone)] pub struct ConcurrentQueues(usize, Arc<RwLock<HashMap<String, ConcurrentQueue>>>); impl ConcurrentQueues { /// Create a new collection of queueus. /// /// `capacity` will be used to set the capacity of the innner queues, /// which are bounded. pub fn new(capacity: usize) -> ConcurrentQueues { ConcurrentQueues(capacity, Arc::new(RwLock::new(HashMap::new()))) } /// Insert an existing queue into this collection of queues. pub fn insert_queue(&self, name: String, queue: ConcurrentQueue) { self.1.write().unwrap().insert(name, queue); } } impl Queues for ConcurrentQueues { type Queue = ConcurrentQueue; fn insert(&self, name: String) { self.1.write().unwrap().entry(name) .or_insert_with(|| ConcurrentQueue::new(self.0)); } fn remove(&self, name: &str) -> Option<ConcurrentQueue> { self.1.write().unwrap().remove(name) } fn queue(&self, name: &str) -> Option<ConcurrentQueue> { self.1.read().unwrap().get(name).cloned() } } #[derive(Clone)] pub struct ConcurrentQueue(Arc<Channel<'static, (Uuid, Vec<u8>)>>); impl ConcurrentQueue { /// Creat a new queue with the passed capacity. pub fn new(capacity: usize) -> ConcurrentQueue { ConcurrentQueue(Arc::new(Channel::new(capacity))) } } impl Queue for ConcurrentQueue { fn enqueue(&self, id: Uuid, data: Vec<u8>) -> Result<(), (Uuid, Vec<u8>)> { self.0.send_async((id, data)).map_err(|(data, _)| data) } fn requeue(&self, id: Uuid, data: Vec<u8>) -> Result<(), (Uuid, Vec<u8>)> { self.enqueue(id, data) } fn dequeue(&self) -> Option<(Uuid, Vec<u8>)> { self.0.recv_async().ok() } }
JavaScript
UTF-8
1,451
2.890625
3
[]
no_license
var Post = require('../models/post.js') // Displays all posts in the api function index (req, res) { Post.find({}, function (err, posts) { if (err) console.log(err); res.json(posts); }); } // Adds a new post to the api function newPost (req, res) { var post = new Post(); post.title = req.body.title; post.description = req.body.description; post.location = req.body.location; post.avatar_url = req.body.avatar_url post.save(function(err, post) { if(err) console.log(err) res.json(post) }) } // Deletes a post based on its id in the api function removePost (req, res) { var id = req.params.id Post.remove({_id: id}, function(error) { if(error) res.json({message: 'Could not delete post b/c' + error}); res.json({message: 'Post succesfully deleted'}) }) } // Updates a post based on its id in the api function updatePost (req, res) { var id = req.params.id Post.findById(id, function(error, post) { if(error) { res.send('Could not find post b/c' + error); } console.log('put request received ') console.log(post) post.title = req.body.title; post.description = req.body.description; post.location = req.body.location; post.avatar_url = req.body.avatar_url post.save(function(error) { if(error) { res.send("could not update post bc" + error) } res.json(post) }) }) } module.exports = { index: index, newPost: newPost, removePost: removePost, updatePost: updatePost }
Java
UTF-8
5,101
3.09375
3
[]
no_license
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.io.File; import java.io.BufferedReader;; // Class that reads & populates two different Collections. // ArrayList<Product> is populated by Stock.txt // HashMap<String,User> is populated by UserAccounts.txt public class Reader { private ArrayList<Product> productList; private ArrayList<User> userList; private int filler; private ArrayList<Log> logList; private String file; // CONSTRUCTORS public Reader(ArrayList<Product> productList) { this.productList = productList; } public Reader(ArrayList<User> userList, int filler) { this.userList = userList; this.filler = filler; } public Reader(ArrayList<Log> logList, String file) { this.logList = logList; this.file = file; } // READING & POPULATING FROM Stock.txt public void readStock() { Scanner scanner = null; try { File input = new File("Stock.txt"); scanner = new Scanner(input); Mouse mouse = null; Keyboard keyboard = null; while (scanner.hasNextLine()) { String[] info = scanner.nextLine().split(","); if (info[1].trim().equals("mouse")) { mouse = new Mouse(Integer.parseInt(info[0].trim()), info[3].trim(), info[4].trim(), Connectivity.valueOf(info[5].trim().toUpperCase()), Double.parseDouble(info[7].trim()), Double.parseDouble(info[8].trim()), Integer.parseInt(info[6].trim()), Integer.parseInt(info[9].trim()), MouseType.valueOf(info[2].trim().toUpperCase())); productList.add(mouse); } else { keyboard = new Keyboard(Integer.parseInt(info[0].trim()), info[3].trim(), info[4].trim(), Connectivity.valueOf(info[5].trim().toUpperCase()), Double.parseDouble(info[7].trim()), Double.parseDouble(info[8].trim()), Integer.parseInt(info[6].trim()), KeyboardType.valueOf(info[2].trim().toUpperCase()), KeyboardLayout.valueOf(info[9].trim().toUpperCase())); productList.add(keyboard); } } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } finally { scanner.close(); } } // READING & POPULATING FROM UserAccounts.txt public void readUsers() { Scanner scanner = null; try { File input = new File("UserAccounts.txt"); scanner = new Scanner(input); Admin admin = null; Customer customer = null; while (scanner.hasNextLine()) { String[] info = scanner.nextLine().split(","); if (info[6].trim().equals("admin")) { admin = new Admin(Integer.parseInt(info[0].trim()), info[1].trim(), info[2].trim(), Integer.parseInt(info[3].trim()), info[4].trim(), info[5].trim(), UserType.valueOf(info[6].trim().toUpperCase())); userList.add(admin); }else { ArrayList<Product> shoppingBasket = new ArrayList<Product>(); double amountToPay = 0.0; customer = new Customer(Integer.parseInt(info[0].trim()), info[1].trim(), info[2].trim(), Integer.parseInt(info[3].trim()), info[4].trim(), info[5].trim(), UserType.valueOf(info[6].trim().toUpperCase()), shoppingBasket, amountToPay); userList.add(customer); } } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } finally { scanner.close(); } } public void readLogs() { Scanner scanner = null; try { File input = new File(file); scanner = new Scanner(input); Log log = null; while (scanner.hasNextLine()) { String[] info = scanner.nextLine().split(","); if (info[5].trim().equalsIgnoreCase("purchased")){ if (info[6].trim().matches("Credit Card|CREDIT_CARD")){ log = new Log(Integer.parseInt(info[0].trim()), info[1].trim(), Integer.parseInt(info[2].trim()), Double.parseDouble(info[3].trim()), Integer.parseInt(info[4].trim()), OrderStatus.valueOf(info[5].toUpperCase().trim()), PaymentType.CREDIT_CARD, info[7].trim()); logList.add(log); }if (info[6].trim().matches("PayPal|PAYPAL")) { log = new Log(Integer.parseInt(info[0].trim()), info[1].trim(), Integer.parseInt(info[2].trim()), Double.parseDouble(info[3].trim()), Integer.parseInt(info[4].trim()), OrderStatus.valueOf(info[5].toUpperCase().trim()), PaymentType.PAYPAL, info[7].trim()); logList.add(log); } }else { log = new Log(Integer.parseInt(info[0].trim()), info[1].trim(), Integer.parseInt(info[2].trim()), Double.parseDouble(info[3].trim()), Integer.parseInt(info[4].trim()), OrderStatus.valueOf(info[5].toUpperCase().trim()), info[6].trim(), info[7].trim()); logList.add(log); } } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } finally { scanner.close(); } } }
Ruby
UTF-8
793
2.5625
3
[ "MIT" ]
permissive
require "mongoid/spec_helper" describe Mongoid::Fields do let(:address) do Address.new end describe "Special geo Array setter" do it "should split a String into parts and convert to floats" do address.locations = "23.5, -47" address.locations.should == [23.5, -47] end it "should convert Strings into floats" do address.locations = "23.5", "-48" address.locations.should == [23.5, -48] end it "should default to normal behavior" do address.locations = 23.5, -49 address.locations.should == [23.5, -49] address.locations = [23.5, -50] address.locations.should == [23.5, -50] end it "should handle nil values" do address.locations = nil address.locations.should be_nil end end end
Java
UTF-8
2,581
3.359375
3
[]
no_license
package com.john.funix.utils; import com.sun.istack.internal.NotNull; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Trung Nguyen * This class helps validate inputs from console */ public class InputHelper { public static String inputForName(String message, @NotNull Scanner scanner) { boolean isValid = false; String name; do { System.out.print(message); name = scanner.nextLine(); name = name.trim(); name = name.replaceAll("\\s+", " "); if (!name.isEmpty() && validateLetters(name)) isValid = true; else System.out.println("It's not a valid name. Please enter again!"); } while (!isValid); return name; } public static boolean validateLetters(String txt) { String regx = "^[\\p{L} .'-]+$"; Pattern pattern = Pattern.compile(regx, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(txt); return matcher.find(); } public static int inputForPositiveIntegerNumber(String message, Scanner scanner) { boolean isValid; String s; int number = 0; do { System.out.print(message); s = scanner.nextLine(); try { number = Integer.parseInt(s); if (number >= 0) { isValid = true; } else { System.out.println("Please enter a positive number!"); isValid = false; } } catch (NumberFormatException e) { System.out.println("It's not a valid number"); isValid = false; } } while (!isValid); return number; } public static double inputForPositiveDoubleNumber(String message, Scanner scanner) { boolean isValid; String s; double number = 0; do { System.out.print(message); s = scanner.nextLine(); try { number = Double.parseDouble(s); if (number > 0) { isValid = true; } else { System.out.println("Please enter a positive number!"); isValid = false; } } catch (NumberFormatException e) { System.out.println("It's not a valid number"); isValid = false; } } while (!isValid); return number; } }
JavaScript
UTF-8
5,993
2.703125
3
[]
no_license
/** * Created by akucherenko on 22.10.13. */ define([ 'lib/BaseScript', 'three', 'underscore', 'keyboard' ], function (BaseScript, THREE, _, Keyboard) { /** * Helpers class * * @class WireHelpers */ return BaseScript.extend({ /** * Here we save current displayed helpers, for future remove */ helpersCollection: [], /** * Current status */ isEnabled: false, /** * Here we save current displayed helpers, for future remove */ normalsHelperCollection: [], /** * Status normal helper */ isDrawNormalsEnable: false, /** * Call when script attached to object */ awake: function () { this.config.names = this.config.names || []; var scope = this; Keyboard.bind('z z', function(){ if(scope.isEnabled){ scope.disable(); }else{ scope.enable(); } }); Keyboard.bind('n n', function(){ if(scope.isDrawNormalsEnable){ scope.disableNormals(); }else{ scope.enableNormals(); } }); }, /** * Enable */ enable: function(){ var scope = this; this.addAxisHelper(); scope.scene.traverse(function(object){ if(object instanceof THREE.Camera){ scope.addCameraHelper(object); return } if(object instanceof THREE.DirectionalLight){ scope.addDirectionalLightHelper(object); return; } if(object instanceof THREE.PointLight){ scope.addPointLightHelper(object); return; } if (object instanceof THREE.Mesh) { if(!_.isEmpty(scope.config.names) && !_.contains(scope.config.names, object.name)){ return; } scope.drawWireFrame(object); scope.addBoxHelper(object); } }); scope.isEnabled = true; }, /** * Disable all helpers */ disable: function(){ var scope = this; _.each(scope.helpersCollection, function(helper){ scope.scene.remove(helper); }); scope.helpersCollection = []; scope.isEnabled = false; }, /** * Enable normals draw */ enableNormals: function(){ var scope = this; scope.scene.traverse(function(object){ if (object instanceof THREE.Mesh) { if(!_.isEmpty(scope.config.names) && !_.contains(scope.config.names, object.name)){ return; } scope.drawVertexNormals(object); scope.drawFacesNormals(object); } }); scope.isDrawNormalsEnable = true; }, /** * DisableNormals normals draw * */ disableNormals: function(){ var scope = this; _.each(scope.normalsHelperCollection, function(helper){ scope.scene.remove(helper); }); scope.helpersCollection = []; scope.isDrawNormalsEnable = false; }, /** * Enable normals draw * * @param mesh */ drawWireFrame: function(mesh){ var helper = new THREE.WireframeHelper(mesh); helper.material.depthTest = false; helper.material.opacity = 0.25; helper.material.transparent = true; this.helpersCollection.push(helper); this.scene.add(helper); }, /** * * @param mesh */ drawVertexNormals: function(mesh){ var helper = new THREE.VertexNormalsHelper(mesh, 1, false, 0.1); this.normalsHelperCollection.push(helper); this.scene.add(helper); }, /** * * @param mesh */ drawFacesNormals: function(mesh){ var helper = new THREE.FaceNormalsHelper(mesh, 1, false, 0.1); this.normalsHelperCollection.push(helper); this.scene.add(helper); }, /** * * @param mesh */ addBoxHelper: function(mesh){ var helper = new THREE.BoxHelper(mesh); this.helpersCollection.push(helper); this.scene.add(helper); }, /** * * */ addAxisHelper: function(){ var helper = new THREE.AxisHelper(100); this.helpersCollection.push(helper); this.scene.add(helper); }, /** * * @param camera */ addCameraHelper: function(camera){ var helper = new THREE.CameraHelper(camera); this.helpersCollection.push(helper); this.scene.add(helper); }, /** * * @param light */ addDirectionalLightHelper: function(light){ var helper = new THREE.DirectionalLightHelper(light, 10); this.helpersCollection.push(helper); this.scene.add(helper); }, /** * * @param light */ addPointLightHelper: function(light){ var helper = new THREE.PointLightHelper(light, 10); this.helpersCollection.push(helper); this.scene.add(helper); } }); });
Python
UTF-8
218
3.8125
4
[]
no_license
#### LECTURE 2 PROBLEM 11 if type(varA)==type('str') or type(varB)==type('str'): print 'string involved' elif varA > varB: print 'bigger' elif varA == varB: print 'equal' else: print 'smaller'
Java
UTF-8
1,143
2.3125
2
[]
no_license
package cn.edu.ujn.EqnoSms; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { void switchActivity() { startActivity(new Intent(MainActivity.this, SmsActivity.class)); finish(); } final int idTime = 5; CountDownTimer timer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timer = new CountDownTimer(idTime*1000, 1000) { int counter = 5; Button skip = findViewById(R.id.skip); @Override public void onTick(long l) { skip.setText(("跳过 "+counter)); counter --; } @Override public void onFinish() { switchActivity(); } }.start(); } public void skip(View view) { switchActivity(); timer.cancel(); } }
Markdown
UTF-8
1,504
2.78125
3
[]
no_license
<h1 align="center">Hi 👋, I'm Kevin Alejandro Mera Castillo</h1> <h3 align="center">A passionate frontend developer and student from Colombia</h3> - 🔭 I’m currently working on a laser game, consists on a matrix generated by the user (size) with hidden mirrors (/ or \) You can fire the laser by sides of matrix and try to knos where the mirrors and directions are. When you guess the mirror, your score will increase, otherwise, will decrease. [Laser Game](https://github.com/CH1GU1/LaserGame) - 👨‍💻 All of my projects are available at [https://github.com/CH1GU1](https://github.com/CH1GU1) - 📫 How to reach me **kamcak@hotmail.es** - 📄 Know about my experiences [Electronical development with arduino and flight simulation cockpits](Electronical development with arduino and flight simulation cockpits) <h3 align="left">Connect with me:</h3> <p align="left"> <a href="https://codesandbox.com/kevin alejandro mera castillo" target="blank"><img align="center" src="https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/codesandbox.svg" alt="kevin alejandro mera castillo" height="30" width="40" /></a> <a href="https://fb.com/kevin.mera" target="blank"><img align="center" src="https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/facebook.svg" alt="kevin.mera" height="30" width="40" /></a> </p> <h3 align="left">Languages and Tools:</h3> <p align="left"> <a href="https://www.java.com" target="_blank"> <img src="https://devicons.github.io/devicon/devicon.git/icons/java/java-original-wordmark.svg" alt="java" width="40" height="40"/> </a> </p>
Markdown
UTF-8
4,458
2.671875
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
<div align="center"> <!-- <img src="Resources/Logo.png atl="SeasonShift" height=75 align="bottom> --> <font size="15">Season Shift</font> <br> <font size="5">A japanese bullethell game made by a bunch of students</font> <hr /> </div> [![Travis (.com) branch](https://img.shields.io/travis/com/barrage-studios/SeasonShift/master?label=Stable%20Build)](https://travis-ci.com/barrage-studios/SeasonShift/branches) [![Travis (.com) branch](https://img.shields.io/travis/com/barrage-studios/SeasonShift/developement?label=Un-Stable%20Build)](https://travis-ci.com/barrage-studios/SeasonShift/branches) [![GitHub release (latest by date)](https://img.shields.io/github/v/release/barrage-studios/SeasonShift?label=Release)](https://github.com/barrage-studios/SeasonShift/releases/latest) [![GitHub](https://img.shields.io/badge/license-Barrage-informational)](https://github.com/barrage-studios/SeasonShift/.github/LICENSE) ![GitHub repo size](https://img.shields.io/github/repo-size/barrage-studios/SeasonShift) ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/barrage-studios/SeasonShift) [![GitHub issues](https://img.shields.io/github/issues-raw/barrage-studios/SeasonShift)](https://github.com/barrage-studios/SeasonShift/issues?q=is%3Aopen+is%3Aissue) [![GitHub issues](https://img.shields.io/github/issues-closed-raw/barrage-studios/SeasonShift)](https://github.com/barrage-studios/SeasonShift/issues?q=is%3Aissue+is%3Aclosed) ## Gameplay Overview &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This game is a 2D barrage shooter centered around survival mechanics with a strong emphasis on pattern recognition, evasive play, and quick reactions. ## Story Synopsis &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *"A young girl named Makoto has been invaded by sinister seasonal beings. These beings have destroyed her home and she is the last person to stand against them. In order to defeat these beings, she must take to the skies fighting them the best way she knows how to - with bullets. She knows it will take her a full year to overcome these seasonal creatures due to their nature, and has prepared to fight her nightmares in the sky until her planet is saved."* ## Structure &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;There are 3 main functional sections of this game. The splash screen, the menu screen, and the gameplay area. The splash screen just shows a couple splashes for things like Unity and our team. The menu screen allows you to enter the game through a level selector, change global settings, or fast quit the application. The game screen is where all the magic happens. Here you will actually get to experience the gameplay and story elements crafted by our team, first hand. Below is a crude diagram of the programs structure. - Splash - Menu - New Game - Load Game - Spring - Summer (Unlocked after Spring) - Fall (Unlocked after Summer) - Winter (Unlocked after Fall) - Settings - Profile Selector - Display Settings - Control Settings - Game Stats - Exit ## Default Controls - Movement - Up (W or ↑) - Down (S or ↓) - Left (A or ←) - Right (D or →) - Slow Time (LShift) - Special - Shoot (Space or Enter) - Switch Power-up (Q) - Use Power-up (E) - Pause Game (Escape) ## About the Team ### Keys [Faunsce](https://www.github.com/Faunsce) (Project Lead) [Erollsia](https://www.github.com/Erollsia) (Team Bridge) [AinzOolGown](https://github.com/AinzOolGown) (Original Concept) ### Technical Team [Faunsce](https://www.github.com/Faunsce) (Team Lead) [AinzOolGown](https://github.com/AinzOolGown) [Abedromerostudent](https://github.com/abedromerostudent) ### Art Team [Erollsia](https://www.github.com/Erollsia) (Team Lead) [UkameDesu](https://github.com/UkameDesu) [CayaKnight](https://github.com/CayaKnight) [KenJi832](https://github.com/KenJi832) ### Sound Team [ExplorerOfTime](https://www.github.com/ExplorerOfTime) (Team Lead) [Gakhur](https://github.com/Gakhur) [FireLance3](https://github.com/firelance3) ### Design Team [JordanBooz](https://github.com/JordanBooz) (Team Lead) [Jabog25](https://github.com/Jabog25) [Jwanna1223](https://github.com/Jwanna1223) [Darknight199876](https://github.com/darknight199876) [Diamonds-Angel96](https://github.com/Diamonds-Angel96) [Optimiticalman](https://github.com/Optimisticalman)
Python
UTF-8
1,163
2.609375
3
[]
no_license
from __future__ import print_function import argparse, json, sys from os.path import realpath, join from util import printplus def printLayer(l): print("layer - ",l['type']) print(" param: ") printplus(l['param'], " ") print(" config: ") printplus(l['config']," ") print(" weight_shape: ", l["weight"]["shape"]) print(" bias_shape: ", l["bias"]["shape"]) def lsNet(net=None, layer=-1): for i in range(net['num_layers']): if layer == -1: printLayer(net['layers'][i]) print("-----------------------------------------") elif layer == i: printLayer(net['layers'][i]) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-n", "--net", help="network json file", default="") parser.add_argument("-l", "--layer", help="layer id", default=-1) args = parser.parse_args() if args.net == "" : print("Please specify required network json file by -n, and config yaml file by -c.") with open(realpath(args.net)) as json_file: lsNet(net=json.load(json_file), layer=int(args.layer))
TypeScript
UTF-8
1,233
2.640625
3
[ "Unlicense" ]
permissive
// This is bascially https://github.com/helmetjs/helmet // for `web`. import { compose, Middleware } from "../mod.ts"; import { frameguard, FrameguardOptions } from "./frameguard.ts"; import { DnsPrefetchControlOptions, dnsPreftechControl, } from "./dns_prefetch_control.ts"; import { noSniff } from "./no_sniff.ts"; export type HelmetOptions = { frameguard: boolean | FrameguardOptions; dnsPrefetchControl: boolean | Partial<DnsPrefetchControlOptions>; noSniff: boolean; }; const defaultOptions: HelmetOptions = { frameguard: true, dnsPrefetchControl: true, noSniff: true, }; export function helmet(opts: Partial<HelmetOptions> = {}) { const options = { ...defaultOptions, ...opts }; // pick middlewares const stack: Middleware[] = []; // helper to add to our stack function configure<O>(x: boolean | O, m: (o?: O) => Middleware) { // disabled if (x === false) return; // default options if (x === true) return stack.push(m()); // custom options stack.push(m(x)); } configure(options.frameguard, frameguard); configure(options.dnsPrefetchControl, dnsPreftechControl); configure(options.noSniff, noSniff); // compose them all together return compose(...stack); }
JavaScript
UTF-8
652
2.625
3
[]
no_license
/** * Created by tujiaw on 2017/1/15. */ function hasParameter(name){ var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURI(r[2]); return null; } $('.pagination.menu a').click(function() { var newPage = parseInt($(this).text()); var firstLast = parseInt($(this).attr('value')); if (isNaN(newPage) && !isNaN(firstLast)) { newPage = firstLast; } var author = hasParameter('author'); if (author) { window.location.href = `/posts?author=${author}&page=${newPage}`; } else { window.location.href = `/posts?page=${newPage}`; } });
Ruby
UTF-8
375
2.609375
3
[]
no_license
require 'query/grammar' module Query class CompactParens def self.apply(args) open = Regexp.quote(Query::Grammar::OPEN_PAREN) close = Regexp.quote(Query::Grammar::CLOSE_PAREN) argstr = args.join(' ') while argstr =~ /#{open}\s*#{close}/ argstr = argstr.gsub(/#{open}\s*#{close}/, '') end argstr.split(' ') end end end
Python
UTF-8
1,334
2.8125
3
[]
no_license
#!/usr/bin/python3 ################################################ # Can be used to create a HTML5 galery of photos # Step 1 : # ./hovercraft_gallery.py > gallery.rst # Step 2 : # hovercraft gallery.rst gallery ################################################ import jinja2 import os import glob def get_list_of_interesting_images(filt="./images/*.jpg"): ll = glob.glob("./images/*.jpg") return ll def make_list(fname): with open(fname) as f: content = f.readlines() content = [x.strip() for x in content] return content def render_output(template_name, pic_list): heredoc=""" :title: HoverCraft Gallery generated from https://github.com/trohit/ppts/hovercraft_gallery.py """ #loader = jinja2.FileSystemLoader(os.getcwd()) loader = jinja2.FileSystemLoader("templates") jenv = jinja2.Environment(loader = loader, trim_blocks= True, lstrip_blocks = True) template = jenv.get_template(template_name) print(heredoc) for i in (range(len(pic_list))): #print(pic_list[i]) print(template.render(index=i, pic=pic_list[i])) if __name__ == "__main__": # ls -1 images > ls.txt # ll = make_list("ls.txt") ll = get_list_of_interesting_images() #print(ll) #output = template.render() render_output('hovercraft_gallery.tmpl', ll)
PHP
UTF-8
712
3.859375
4
[]
no_license
<?php class Endereco { private $Logradouro; private $Numero; private $Cidade; public function __construct($Logradouro, $Numero, $Cidade) { $this -> Logradouro = $Logradouro; $this -> Numero = $Numero; $this -> Cidade = $Cidade; } public function __destruct() { var_dump("DESTRUIR"); } public function __toString() { return $this -> Logradouro . ", " . $this -> Numero . ", " . $this -> Cidade . ". "; } } $meuEndereco = new Endereco("Rua Professor Eduardo Correa Lima", 236, "Curitiba"); // var_dump($meuEndereco); // unset($meuEndereco); echo $meuEndereco; ?>
Java
UTF-8
3,008
2.203125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.migration; /** * * @author Bolaji */ /* * 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. */ import com.util.AbstractFacade; import com.util.GenericLibrary; import com.source2.entity.EazyappPolicyDetails; import com.model.EazyappPolicyDetailsModel; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; /** * * @author Bolaji */ public class EazyappPolicyDetailsLogic extends AbstractFacade<EazyappPolicyDetails> { EntityManager em; private Query query; public EazyappPolicyDetailsLogic() { super(EazyappPolicyDetails.class); em = new GenericLibrary().getEM("eazyapp").createEntityManager(); } @Override protected EntityManager getEM() { return em; } public List<EazyappPolicyDetailsModel> getEazyappPolicyDetails() { List<EazyappPolicyDetailsModel> dlist = new ArrayList<>(); try { query = getEM().createNamedQuery("EazyappPolicyDetails.findAll"); //query.setParameter("fieldname", fieldname); List<EazyappPolicyDetails> agents = query.getResultList(); agents.forEach((dd) -> { EazyappPolicyDetailsModel dmodel = new EazyappPolicyDetailsModel(dd); dlist.add(dmodel); }); } catch (Exception ex) { System.out.println(ex.getMessage()); } return dlist; } public EazyappPolicyDetailsModel getEazyappPolicyDetailsByRefNo(String id) { EazyappPolicyDetailsModel dmodel = new EazyappPolicyDetailsModel(); try { query = getEM().createNamedQuery("EazyappPolicyDetails.findByProductrRefNo"); query.setParameter("productrRefNo", id); EazyappPolicyDetails dropdown = (EazyappPolicyDetails) query.setMaxResults(1).getSingleResult(); dmodel = new EazyappPolicyDetailsModel(dropdown); } catch (Exception ex) { System.out.println(ex.getMessage()); } return dmodel; } public EazyappPolicyDetailsModel getEazyappPolicyDetailsByPolhNum(String id) { EazyappPolicyDetailsModel dmodel = new EazyappPolicyDetailsModel(); try { query = getEM().createNamedQuery("EazyappPolicyDetails.findByProductMainPolicyNo"); query.setParameter("productMainPolicyNo", id); EazyappPolicyDetails dropdown = (EazyappPolicyDetails) query.setMaxResults(1).getSingleResult(); dmodel = new EazyappPolicyDetailsModel(dropdown); } catch (Exception ex) { System.out.println(ex.getMessage()); } return dmodel; } }
Python
UTF-8
3,672
2.546875
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- # Author: yongyuan.name from vgg16_1 import VGGNet from vgg16_2 import VGGNet2 import numpy as np import h5py import matplotlib.pyplot as plt import matplotlib.image as mpimg import argparse import os import glob os.environ["CUDA_VISIBLE_DEVICES"] = "0" class Query: def __init__(self): ap = argparse.ArgumentParser() #ap.add_argument("-query", default="/home/omnisky/flask-keras-cnn-image-retrieval-master/query/", # help = "Path to query which contains image to be queried") #ap.add_argument("-index", default='featureCNN.h5', # help = "Path to index") ap.add_argument("-result",default="/home/omnisky/flask-keras-cnn-image-retrieval-master/result/", help = "Path for output retrieved images") args = vars(ap.parse_args()) #args = ap.parse_args() def rank1(self,N,Nrel,Nrel_all,label,imlist): count = 0 j = 0 M = N * Nrel Ap_sum = 0 for i, name in enumerate(imlist): name = str(name, 'utf-8') #print(name) if name == 'deneme.jpg': continue elif name.split('-')[1] == str(label)+'.jpg': name_label = name.split('-')[1].split('.jpg')[0] if name_label == str(label): print(name) print(i) print(j/(i+1)) j += 1 count += i Ap_sum += j/(i+1) print('j =',j) print('count =', count) Ap_sum /= j print('AP =', Ap_sum) rank = (1 / M) * (count - Nrel_all) return rank,Ap_sum def query(self,feats1,feats2,imgNames,queryDir,label,N,Nrel,Nrel_all,query_path): print("--------------------------------------------------") print(" searching starts") print("--------------------------------------------------") # init VGGNet16 model model1 = VGGNet() model2 = VGGNet2() # extract query image's feature, compute simlarity score and sort queryVec1 = model1.extract_feat(queryDir) queryVec2 = model2.extract_feat(queryDir) scores1 = np.dot(queryVec1, feats1.T) scores2 = np.dot(queryVec2, feats2.T) length = len(scores1) rank1 = np.zeros(length,int) rank_ID1 = np.argsort(scores1)[::-1] for i,rank in enumerate(rank_ID1): rank1[rank] = i rank2 = np.zeros(length, int) rank_ID2 = np.argsort(scores2)[::-1] for i, rank in enumerate(rank_ID2): rank2[rank] = i rank_merge = 1/((1.0/(rank1+0.0001))+(1.0/(rank2+0.0001))) rank_merge = rank_merge.astype(np.int) rank_ID = np.argsort(rank_merge)[::1] #rank_score = scores1[rank_ID] # print (scores) # print (rank_ID) # print (rank_score) maxres = N-1 imlist = [imgNames[index] for i,index in enumerate(rank_ID[0:maxres])] #print("top %d images in order are: " %maxres, imlist) rank, AP = self.rank1(N,Nrel,Nrel_all,label,imlist) print('rank =',rank) # show top #maxres retrieved result one by one # for i,im in enumerate(imlist): # if i > 9: # break # image = mpimg.imread(query_path + "/"+str(im, 'utf-8')) # plt.subplot(1,10 , i + 1) # plt.imshow(image) # # plt.xticks([]) # plt.yticks([]) # #plt.title("search output %d" %(i+1)) # plt.imshow(image) # plt.show() return rank, AP
Java
UTF-8
1,786
2.265625
2
[]
no_license
package services; import exceptions.UsernameTakenException; import models.User; import play.libs.concurrent.HttpExecutionContext; import repository.IUserRepository; import repository.UserRepository; import javax.inject.Inject; import java.util.Optional; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; /** * Created by RP on 1/7/16. */ public class UserService extends WithPictureService<User, IUserRepository> implements IUserService { private final HttpExecutionContext httpExecutionContext; @Inject public UserService(UserRepository repository, AssetService assetService, HttpExecutionContext httpExecutionContext) { super(repository, assetService); this.httpExecutionContext = httpExecutionContext; } @Override public CompletionStage<Optional<User>> findByUsername(String username) { return repository.findByUsername(username); } @Override public CompletionStage<User> createUser(User user, String password) { return this.findByUsername(user.getUsername()).thenApplyAsync( optionalUser -> { if (optionalUser.isPresent()) { throw new CompletionException(new UsernameTakenException()); } else { user.setPassword(password); try { return super.insert(user).toCompletableFuture().get(); } catch (InterruptedException | ExecutionException e) { throw new CompletionException(e); } } } , this.httpExecutionContext.current()); } }
Python
UTF-8
2,789
3.0625
3
[]
no_license
from configparser import ConfigParser from wrapt import ObjectProxy import re def nested_set(dic, keys, value): for key in keys[:-1]: dic = dic.setdefault(key, {}) dic[keys[-1]] = value class CustomParser(ConfigParser): """Custom ConfigParser to hold our own rules Extends: ConfigParser """ _FLAGS = re.MULTILINE | re.VERBOSE # Regular expressions for parsing section headers and options _SECTION_HEADER = r""" ^\[ # [ in col 0 \s* # leading whitespace (?P<header>[^\]\n]+?) # get chars until close, # match as few as possible \s* # trailing whitespace \] # ] """ _OPTION = r""" ^(?P<option>\w.*?) # key starts in col 0 \s*(?P<vi>\:)\s* # colon surrounded by whitespace (?P<value> # match value as... (?: # for each line... (?:.|\n) # get all chars/newlines, (?!^[^\s]+) # until the next non-continued line # (match lines until it starts with space) )* # non-capture to hold negative lookahead )$ # everything up to eol """ # Compiled regular expression for matching sections SECTCRE = re.compile(_SECTION_HEADER, _FLAGS) # Compiled regular expression for matching options OPTCRE = re.compile(_OPTION, _FLAGS) def __init__(self, *args, **kwargs): kwargs['delimiters'] = (':',) super().__init__(*args, **kwargs) class Config(ObjectProxy): """Helper class to make working with the config file easier Acts as a proxy to our CustomParser class, adding a few helper functions on top of it. Extends: wrapt.ObjectProxy Variables: __slots__ {tuple} -- So the ObjectProxy knows not to forward these """ __slots__ = ('parsed', 'file_path') def __init__(self, file_path): self.file_path = file_path self.parsed = CustomParser() self.parsed.read(self.file_path) super().__init__(self.parsed) def get(self, key): value = self.parsed for k in key.split('.'): value = value[k] return value def set(self, key, value): nested_set(self.parsed, key.split('.'), value) def write(self): with open(self.file_path, 'w') as config_file: self.parsed.write(config_file)
TypeScript
UTF-8
573
2.53125
3
[ "MIT" ]
permissive
import { Facilities } from './facilities.entity'; import { OneToOne, CreateDateColumn, UpdateDateColumn, PrimaryGeneratedColumn, Column, Entity, JoinColumn } from 'typeorm'; @Entity() export class Addresses { @PrimaryGeneratedColumn() id: number; @Column() physical_address: string; @Column() postal_address: string; @OneToOne(type => Facilities, facility => facility.address) facility: Facilities; @CreateDateColumn({type: 'timestamp'}) created_at: Date; @UpdateDateColumn({type: 'timestamp'}) updated_at: Date; }
Python
UTF-8
2,719
2.5625
3
[]
no_license
import PyClient import Agent class Env: map_name = '' __map_width = 11 __map_height = 8 __map = ['TTWWWTTPDDT', '00000000000', '00000000000', '00001230000', '00000000000', '00000000000', '00000000000', 'TTTTBTCCCTT'] ''' T: Table W: Work Station P: Plate Station D: Deliver Station 0: Empty i: Ingredient i B: Food waste bin C: Cook Station ''' __step = 1.2 __room = 0.4 __x_base = 6.0 __z_base = 1.2 __x_border = __x_base-__step/2 __z_border = __z_base-__step/2 __chef_pos = [[0, 0, 0, 0], [0, 0, 0, 0]] pyclient = PyClient.PyClient() agent = Agent.Agent() # Static data def __init__(self, n): self.map_name = n def getmap(self): return self.__map def getmapwidth(self): return self.__map_width def getmapheight(self): return self.__map_height # Dynamic data def getchefpos(self): self.__chef_pos = self.pyclient.getchefpos() x0 = int((self.__chef_pos[0][0]-self.__x_border)/self.__step) z0 = int((self.__chef_pos[0][2]-self.__z_border)/self.__step) x1 = int((self.__chef_pos[1][0]-self.__x_border)/self.__step) z1 = int((self.__chef_pos[1][2]-self.__z_border)/self.__step) ''' Angle encoding: -45 to 45: 0 45 to 135: 1 135 to 225: 2 225 to 315: 3 ''' a0 = int((self.__chef_pos[0][3]+45)/90) a0 = 0 if a0 == 4 else a0 a1 = int((self.__chef_pos[1][3]+45)/90) a1 = 0 if a1 == 4 else a1 return [[x0, z0, a0], [x1, z1, a1]] def getorderlist(self): return self.pyclient.getorderlist() def getchefholding(self): return self.pyclient.getchefholding() def getobjposlist(self): templist = self.pyclient.getobjposlist() outputlist = {} for itemtype in templist: outputlist[itemtype] = [] for item in templist[itemtype]: x = int((item[0]-self.__x_border)/self.__step) z = int((item[2]-self.__z_border)/self.__step) outputlist[itemtype].append([x, z]) return outputlist def getpotprogress(self): return self.pyclient.getpotprogress() def isfire(self): return self.pyclient.isfire() def getscore(self): return self.pyclient.getscore() def getmapcell(self, x, z): return self.__map[self.__map_height - 1 - z][x] def getmapcellcenter(self, x, z): return [(x + 0.5) * self.__step + self.__x_border, (z + 0.5) * self.__step + self.__z_border]
JavaScript
UTF-8
135
2.703125
3
[]
no_license
const flatten = a => a.reduce((r, e) => r.concat(Array.isArray(e) ? flatten(e) : e), []); console.log(flatten([1, [[2], 3, 4], 5]));
C#
UTF-8
3,381
3.015625
3
[]
no_license
using System; using System.Text; using System.Collections.Concurrent; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading.Tasks; using System.Runtime.Serialization.Json; namespace AnyLogicDataServerLib { public class Server { ConcurrentQueue<String> persons; public Server() { this.persons = new ConcurrentQueue<String>(); } private static DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(AnyLogicPerson)); //Deserialize person from String private AnyLogicPerson Deserialize(string path) { var deserializerALP = new AnyLogicPerson(); var per = new MemoryStream(Encoding.UTF8.GetBytes(path)); deserializerALP = deserializer.ReadObject(per) as AnyLogicPerson; per.Close(); per.Dispose(); return deserializerALP; } public AnyLogicPerson GetPerson() { //Get last string from queue //Deserialize String personString; if (this.persons.TryDequeue(out personString)) { return this.Deserialize(personString); } else { return null; } } private Task receiveTask; public void StartServerInstance() { this.receiveTask = new Task(this.Run); this.receiveTask.Start(); } // //================================================================================================= public string personString; public string dataStringMy; public string data = null; public byte[] buffer = new byte[2048]; public bool telegramReceived = false; public int bytesRec; Socket serverListner; public int port = 9090; public string IpAddress = "127.0.0.1"; Socket socketForClients; private void Run() { serverListner = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), port); string dataString = null; try { serverListner.Bind(ep); serverListner.Listen(100); while (true) { Console.WriteLine("Waiting for a Data..."); socketForClients = serverListner.Accept(); socketForClients.ReceiveTimeout = 1000; while (!telegramReceived) { bytesRec = socketForClients.Receive(buffer); dataString += Encoding.ASCII.GetString(buffer, 0, bytesRec); telegramReceived = dataString.IndexOf("\r\n") > -1; } if (telegramReceived) { this.persons.Enqueue(dataString); dataString = null; telegramReceived = false; } } } catch (Exception e) { Console.WriteLine(e.ToString()); } } } }
Java
UTF-8
427
1.78125
2
[]
no_license
package com.travel.repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.travel.model.PricePlan; @Repository public interface PricePlanRepository extends JpaRepository<PricePlan, Long> { PricePlan findByIdEquals(Long id); PricePlan findByRoomtypeEqualsAndAccommodation_idEquals(int roomtype, Long id); }
Markdown
UTF-8
9,651
2.96875
3
[]
no_license
# squeal ![squeal-icon](http://www.emoticonswallpapers.com/emotion/cute-big-pig/cute-pig-smiley-046.gif) [![CircleCI](https://circleci.com/gh/echatav/squeal.svg?style=svg&circle-token=a699a654ef50db2c3744fb039cf2087c484d1226)](https://circleci.com/gh/morphismtech/squeal) [Github](https://github.com/morphismtech/squeal) [Hackage](https://hackage.haskell.org/package/squeal-postgresql) [Stackage](https://www.stackage.org/package/squeal-postgresql) [YouTube](https://www.youtube.com/watch?v=rWfEQfAaNc4) ## introduction Squeal is a deep embedding of SQL into Haskell. By "deep embedding", I am abusing the term somewhat. What I mean is that Squeal embeds both SQL terms and SQL types into Haskell at the term and type levels respectively. This leads to a very high level of type-safety in Squeal. Squeal embeds not just the structured query language of SQL but also the data manipulation language and the data definition language; that's `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `WITH`, `CREATE`, `DROP`, and `ALTER` commands. Squeal expressions closely match their corresponding SQL expressions so that the SQL they actually generate is completely predictable. They are also highly composable and cover a large portion of SQL. ## features * generic encoding of Haskell tuples and records into query parameters and generic decoding of query results into Haskell records using [`generics-sop`](https://hackage.haskell.org/package/generics-sop) * access to SQL alias system using the `OverloadedLabels` extension * type-safe `NULL` and `DEFAULT` * type-safe SQL constraints `CHECK`, `UNIQUE`, `PRIMARY KEY` and `FOREIGN KEY` * type-safe aggregation * escape hatches for writing raw SQL * [`mtl`](https://hackage.haskell.org/package/mtl) compatible monad transformer for executing as well as preparing queries and manipulations and [Atkey](https://bentnib.org/paramnotions-jfp.pdf) indexed monad transformer for executing definitions. * linear, invertible migrations * connection pools * transactions ## installation `stack install squeal-postgresql` ## testing start postgres on localhost port `5432` and create a database named `exampledb`. `stack test` ## usage Let's see an example! First, we need some language extensions because Squeal uses modern GHC features. ```haskell >>> :set -XDataKinds -XDeriveGeneric -XOverloadedLabels >>> :set -XOverloadedStrings -XTypeApplications -XTypeOperators ``` We'll need some imports. ```haskell >>> import Control.Monad (void) >>> import Control.Monad.Base (liftBase) >>> import Data.Int (Int32) >>> import Data.Text (Text) >>> import Squeal.PostgreSQL ``` We'll use generics to easily convert between Haskell and PostgreSQL values. ```haskell >>> import qualified Generics.SOP as SOP >>> import qualified GHC.Generics as GHC ``` The first step is to define the schema of our database. This is where we use `DataKinds` and `TypeOperators`. ```haskell >>> :{ type Schema = '[ "users" ::: '[ "pk_users" ::: 'PrimaryKey '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "name" ::: 'NoDef :=> 'NotNull 'PGtext ] , "emails" ::: '[ "pk_emails" ::: 'PrimaryKey '["id"] , "fk_user_id" ::: 'ForeignKey '["user_id"] "users" '["id"] ] :=> '[ "id" ::: 'Def :=> 'NotNull 'PGint4 , "user_id" ::: 'NoDef :=> 'NotNull 'PGint4 , "email" ::: 'NoDef :=> 'Null 'PGtext ] ] :} ``` Notice the use of type operators. `:::` is used to pair an alias `Symbol` with either a `TableType` or a `ColumnType`. `:=>` is used to pair a `TableConstraint`s with a `ColumnsType`, yielding a `TableType`, or to pair a `ColumnConstraint` with a `NullityType`, yielding a `ColumnType`. Next, we'll write `Definition`s to set up and tear down the schema. In Squeal, a `Definition` is a `createTable`, `alterTable` or `dropTable` command and has two type parameters, corresponding to the schema before being run and the schema after. We can compose definitions using `>>>`. Here and in the rest of our commands we make use of overloaded labels to refer to named tables and columns in our schema. ```haskell >>> :{ let setup :: Definition '[] Schema setup = createTable #users ( serial `As` #id :* (text & notNull) `As` #name :* Nil ) ( primaryKey (Column #id :* Nil) `As` #pk_users :* Nil ) >>> createTable #emails ( serial `As` #id :* (int & notNull) `As` #user_id :* text `As` #email :* Nil ) ( primaryKey (Column #id :* Nil) `As` #pk_emails :* foreignKey (Column #user_id :* Nil) #users (Column #id :* Nil) OnDeleteCascade OnUpdateCascade `As` #fk_user_id :* Nil ) :} ``` We can easily see the generated SQL is unsuprising looking. ```haskell >>> renderDefinition setup "CREATE TABLE users (id serial, name text NOT NULL, CONSTRAINT pk_users PRIMARY KEY (id)); CREATE TABLE emails (id serial, user_id int NOT NULL, email text, CONSTRAINT pk_emails PRIMARY KEY (id), CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE);" ``` Notice that `setup` starts with an empty schema `'[]` and produces `Schema`. In our `createTable` commands we included `TableConstraint`s to define primary and foreign keys, making them somewhat complex. Our tear down `Definition` is simpler. ```haskell >>> :{ let teardown :: Definition Schema '[] teardown = dropTable #emails >>> dropTable #users :} >>> renderDefinition teardown "DROP TABLE emails; DROP TABLE users;" ``` Next, we'll write `Manipulation`s to insert data into our two tables. A `Manipulation` is an `insertRow` (or other inserts), `update` or `deleteFrom` command and has three type parameters, the schema it refers to, a list of parameters it can take as input, and a list of columns it produces as output. When we insert into the users table, we will need a parameter for the `name` field but not for the `id` field. Since it's optional, we can use a default value. However, since the emails table refers to the users table, we will need to retrieve the user id that the insert generates and insert it into the emails table. Take a careful look at the type and definition of both of our inserts. ```haskell >>> :{ let insertUser :: Manipulation Schema '[ 'NotNull 'PGtext ] '[ "fromOnly" ::: 'NotNull 'PGint4 ] insertUser = insertRow #users (Default `As` #id :* Set (param @1) `As` #name :* Nil) OnConflictDoNothing (Returning (#id `As` #fromOnly :* Nil)) :} >>> :{ let insertEmail :: Manipulation Schema '[ 'NotNull 'PGint4, 'Null 'PGtext] '[] insertEmail = insertRow #emails ( Default `As` #id :* Set (param @1) `As` #user_id :* Set (param @2) `As` #email :* Nil ) OnConflictDoNothing (Returning Nil) :} >>> renderManipulation insertUser "INSERT INTO users (id, name) VALUES (DEFAULT, ($1 :: text)) ON CONFLICT DO NOTHING RETURNING id AS fromOnly;" >>> renderManipulation insertEmail "INSERT INTO emails (id, user_id, email) VALUES (DEFAULT, ($1 :: int4), ($2 :: text)) ON CONFLICT DO NOTHING;" ``` Next we write a `Query` to retrieve users from the database. We're not interested in the ids here, just the usernames and email addresses. We need to use an inner join to get the right result. A `Query` is like a `Manipulation` with the same kind of type parameters. ```haskell >>> :{ let getUsers :: Query Schema '[] '[ "userName" ::: 'NotNull 'PGtext , "userEmail" ::: 'Null 'PGtext ] getUsers = select (#u ! #name `As` #userName :* #e ! #email `As` #userEmail :* Nil) ( from (table (#users `As` #u) & innerJoin (table (#emails `As` #e)) (#u ! #id .== #e ! #user_id)) ) :} >>> renderQuery getUsers "SELECT u.name AS userName, e.email AS userEmail FROM users AS u INNER JOIN emails AS e ON (u.id = e.user_id)" ``` Now that we've defined the SQL side of things, we'll need a Haskell type for users. We give the type `Generics.SOP.Generic` and `Generics.SOP.HasDatatypeInfo` instances so that we can decode the rows we receive when we run `getUsers`. Notice that the record fields of the `User` type match the column names of `getUsers`. ```haskell >>> data User = User { userName :: Text, userEmail :: Maybe Text } deriving (Show, GHC.Generic) >>> instance SOP.Generic User >>> instance SOP.HasDatatypeInfo User ``` Let's also create some users to add to the database. ```haskell >>> :{ let users :: [User] users = [ User "Alice" (Just "alice@gmail.com") , User "Bob" Nothing , User "Carole" (Just "carole@hotmail.com") ] :} ``` Now we can put together all the pieces into a program. The program connects to the database, sets up the schema, inserts the user data (using prepared statements as an optimization), queries the user data and prints it out and finally closes the connection. We can thread the changing schema information through by using the indexed `PQ` monad transformer and when the schema doesn't change we can use `Monad` and `MonadPQ` functionality. ```haskell >>> :{ let session :: PQ Schema Schema IO () session = do idResults <- traversePrepared insertUser (Only . userName <$> users) ids <- traverse (fmap fromOnly . getRow 0) idResults traversePrepared_ insertEmail (zip (ids :: [Int32]) (userEmail <$> users)) usersResult <- runQuery getUsers usersRows <- getRows usersResult liftBase $ print (usersRows :: [User]) :} >>> :{ void . withConnection "host=localhost port=5432 dbname=exampledb" $ define setup & pqThen session & pqThen (define teardown) :} [User {userName = "Alice", userEmail = Just "alice@gmail.com"},User {userName = "Bob", userEmail = Nothing},User {userName = "Carole", userEmail = Just "carole@hotmail.com"}] ```
JavaScript
UTF-8
2,818
2.515625
3
[]
no_license
var React = require("react"); var PropTypes = require("prop-types"); import ClueButton from "./clue-button"; import {Group, Rect, Text} from "react-konva"; import gf from "./general_functions"; export default class CategoryGroup extends React.Component { render = () => { const fontFamily = "Oswald Bold"; const fontStyle = ""; const totalCluesHeight = (5/6) * this.props.height; const headerHeight = this.props.height - totalCluesHeight; const headerBorderV = 0.1 * headerHeight; const headerBorderH = 0.01 * headerHeight; const headerTextBoxHeight = headerHeight - 2*headerBorderV; const headerTextBoxWidth = this.props.width - 2*headerBorderH; const headerTextHeightMargin = 0.1 * headerTextBoxHeight; const headerTextHeight = (headerTextBoxHeight - 2 * headerTextHeightMargin) / 2; const headerTextWidthMargin = 0.1 * headerTextBoxWidth; const headerTextWidth = headerTextBoxWidth - 2*headerTextWidthMargin; const clueHeight = totalCluesHeight / this.props.category.clues.length; const splitCategory = gf.splitLongString(this.props.category.name.toUpperCase(), fontFamily, headerTextHeight, headerTextWidth); const clueButtons = this.props.category.clues.map((c, i) => ( <ClueButton clue={c} key={i} height={clueHeight} width={this.props.width} top={i * clueHeight + headerHeight} value={this.props.values[i]} prefix={this.props.prefix} suffix={this.props.suffix}/> )); // only show the category name if there are any clues left in it const showCategoryName = this.props.category.clues.some((clue) => clue.active); return ( <Group x={this.props.left} y={0}> <Rect width={this.props.width} height={this.props.height} x={0} y={0} fill="black" stroke="black" strokeWidth={2}/> <Rect width={this.props.width} height={headerHeight} x={0} y={0} fill="black"/> <Rect width={headerTextBoxWidth} height={headerTextBoxHeight} x={headerBorderH} y={headerBorderV} fill="#0B1885"/> <Text x={headerBorderH + headerTextWidthMargin + gf.textHorizontalSpacing(splitCategory, fontFamily, headerTextHeight, headerTextWidth, fontStyle)} y={headerBorderV + headerTextHeightMargin + gf.textVerticalSpacing(splitCategory, headerTextHeight)} height={headerTextHeight * 2} wrap="none" textAlign="center" fontSize={headerTextHeight} fontFamily={fontFamily} fontStyle={fontStyle} fill="white" align="center" scaleX={gf.textScale(splitCategory, fontFamily, headerTextHeight, headerTextWidth, fontStyle)} text={splitCategory} visible={showCategoryName}/> {clueButtons} </Group> ); } } CategoryGroup.propTypes = { category: PropTypes.object, values: PropTypes.array, prefix: PropTypes.string, suffix: PropTypes.string, height: PropTypes.number, width: PropTypes.number, left: PropTypes.number, };
Markdown
UTF-8
1,591
2.796875
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- description: Why use People Near Me? ms.assetid: 94e37cb0-1832-46ae-81ec-b92a5b4dcd51 title: Why use People Near Me? ms.topic: article ms.date: 05/31/2018 --- # Why use People Near Me? Some examples of scenarios that [People Near Me](about-people-near-me.md) (PNM) enables are the following: - Initiate chat with a person in a conference room during a meeting. Use a chat application to dynamically discover other users in the room, select a specific user, and begin a chat session to collaborate or exchange information. - The PNM API allows document sharing with everyone in your conference room. Although Universal Serial Bus (USB) flash drives (UFDs) make it very easy to transfer documents between computers in a closed setting, such as a meeting, it still takes time and effort to plug the UFD into each computer and copy the document to a local folder. With applications capable of PNM, you can select the users in the room with which you want to share or send a document. - Stream the information on the desktop of a machine to a coworker's computer for resource sharing. - Start a game with someone during a layover at an airport terminal that supports wireless connectivity. The PNM API allows an application to advertise your interest in playing a game, discover others at the airport who are also interested in playing the game, and start a gaming session. - Advertise interests at an industry conference and discover those of others using wireless connectivity. After discovery, users are able to chat or set up impromptu meetings to exchange ideas.    
C++
UTF-8
816
2.578125
3
[]
no_license
//incorrect solution... #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <bits/stdc++.h> using namespace std; long long int arr[100005]; long long int dp[100005]; long long int foo(long long int n){ if(dp[n] != 0) return dp[n]; if(n == 1) return (dp[n]=1); if(arr[n-1] > arr[n-2]) return (dp[n]=(1 + foo(n-1))); else if(arr[n-1] <= arr[n-2]) return (dp[n]=foo(n-1)-1); } int main() { long long int i, n, sum = 0; cin >> n; memset(dp, 0, sizeof(dp)); for(i = 0; i < n; i++) cin >> arr[i]; long long int x = foo(n); for(i = 1; i <= n; i++){ cout<<dp[i]<<" "; sum+=dp[i]; } cout<<sum<<endl; return 0; }
Java
UTF-8
1,544
3.15625
3
[]
no_license
package GameObject; import com.googlecode.lanterna.terminal.Terminal; public class GameObject { private int x; private int y; private int xOld; private int yOld; private Graphic graphic; private boolean needsDraw = true; private boolean traversable; public GameObject(int x, int y, char look, boolean traversable) { this(x, y, look, Terminal.Color.WHITE, traversable); } public GameObject(int x, int y, char look, Terminal.Color color, boolean traversable) { this.x = xOld = x; this.y = yOld = y; this.graphic = new Graphic(look, color); this.traversable = traversable; } public GameObject() { } public int getX() { return x; } public int getY() { return y; } public void onLoop() { } public void onDraw(Terminal terminal) { if (needsDraw) { graphic.draw(terminal, this.x, this.y, this.xOld, this.yOld); needsDraw = false; } } public void onCollide(GameObject object) { if (!object.isTraversable()) { this.x = this.xOld; this.y = this.yOld; this.needsDraw = true; } } private boolean isTraversable() { return traversable; } protected void move(int changeX, int changeY) { xOld = this.x; yOld = this.y; this.x += changeX; this.y += changeY; needsDraw = true; } public void needsToDraw() { needsDraw = true; } }
Java
UTF-8
5,436
2.40625
2
[ "Apache-2.0" ]
permissive
/* Copyright 2019 https://github.com/OughtToPrevail Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package oughttoprevail.asyncnetwork.util.selector; import java.io.Closeable; import java.io.IOException; import oughttoprevail.asyncnetwork.exceptions.LoadException; import oughttoprevail.asyncnetwork.server.IndexedList; import oughttoprevail.asyncnetwork.util.IndexesBuffer; import oughttoprevail.asyncnetwork.util.OS; public class LinuxMacSelector implements Closeable { private static boolean implemented; static { if(OS.LINUX) { implemented = NativeLoader.load("LinuxSelector", ".so"); } else if(OS.MAC) { implemented = NativeLoader.load("MacSelector", ".dylib"); } } public static boolean isImplemented() { return implemented; } private int fd; private long arrayAddress; public LinuxMacSelector() throws LoadException { if(!implemented) { NativeLoader.exception("LinuxMacSelector"); } } /** * Creates a file descriptor for the selector and registers the server for accept connections * using the specified serverFd and also creates an array for the select invocations. * * @param serverFd the file descriptor that will be used when registering the server for accept * connections * @param arraySize the arraySize that will be used for creating an array for select invocations */ public void createSelector(int serverFd, int arraySize) throws IOException { fd = createSelector0(serverFd); if(fd == -1) { return; } this.arrayAddress = createArray0(arraySize); } /** * Registers the specified socket file descriptor to the selector. * * @param socketFd the socket that will be used when registering the file descriptor * @param index the index of the specified socket file descriptor in the {@link IndexedList} */ public void registerClient(int socketFd, int index) throws IOException { registerClient0(this.fd, socketFd, index); } /** * Selects with the {@link LinuxMacSelector} array, the specified {@link IndexesBuffer} address * and the specified timeout to call operating system dependent select. * * @param indexesAddress the {@link IndexesBuffer#getAddress()} * @param arraySize the array size that the {@link LinuxMacSelector} will use when reading the * {@link LinuxMacSelector} array * @param timeout the timeout that will be used for the select call * @return the amount of indexes set to the {@link IndexesBuffer} or -1 if an error occurred */ public int select(long indexesAddress, int arraySize, int timeout) throws IOException { return select0(fd, indexesAddress, arrayAddress, arraySize, timeout); } /** * Closes the selector. * * @throws IOException if an error has occurred while closing the selector */ public void close() throws IOException { close0(fd); } /** * Creates the selector file descriptor and registers the specified serverFd. * * @param serverFd the serverSocket file descriptor that will be registered to the new selector file descriptor * @return the new selector file descriptor * @throws IOException if an exception has occurred while performing this operation */ private native int createSelector0(int serverFd) throws IOException; /** * Creates an array of events that can be put in {@link #select(long, int, int)} as the eventAddress. * * @param size the size of the events array * @return the array of events address */ private native long createArray0(int size); /** * Registers the specified socket file descriptor to the specified selectorFd * and saves the specified index with it. * * @param selectorFd the selector file descriptor which the socket will be registered to * @param socketFd the socket file descriptor which will be registered * @param index the index where the socket is saved * @throws IOException if an exception has occurred while performing this operation */ private native void registerClient0(int selectorFd, int socketFd, int index) throws IOException; /** * Blocks until it can find ready sockets or timeouts then puts the each socket index in the indexesAddress. * * @param selectorFd the selector file descriptor * @param indexesAddress the {@link IndexesBuffer} address * @param eventsAddress the events array address * @param eventsSize the events array size * @param timeout the timeout for this select call * @return how many indexes were put in the {@link IndexesBuffer} * @throws IOException if an exception has occurred while performing this operation */ private native int select0(int selectorFd, long indexesAddress, long eventsAddress, int eventsSize, int timeout) throws IOException; /** * Closes the selector file descriptor. * * @param selectorFd the selector file descriptor that will be closed. * @throws IOException if an error has occurred while closing the selector */ private native void close0(int selectorFd) throws IOException; }
Go
UTF-8
826
2.84375
3
[]
no_license
package notify import ( "log" "net/http" "net/url" "os" "strings" ) type Notify struct { accessToken string notifyApi string } // Initialize notify func NewNotify() *Notify { n := new(Notify) n.accessToken = os.Getenv("TOKEN") n.notifyApi = "https://notify-api.line.me/api/notify" return n } func (n *Notify) SendNotify(msg string) { u, err := url.ParseRequestURI(n.notifyApi) if err != nil { log.Fatal(err) } c := &http.Client{} form := url.Values{} form.Add("message", msg) body := strings.NewReader(form.Encode()) req, err := http.NewRequest("POST", u.String(), body) if err != nil { log.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "Bearer "+n.accessToken) _, err = c.Do(req) if err != nil { log.Fatal(err) } }
JavaScript
UTF-8
654
3.03125
3
[]
no_license
function prueba(){ let info = document.getElementById('art').value; let li = document.createElement("li"); let contenido = document.createTextNode(info); let ordenada = document.getElementById('order'); li.appendChild(contenido); document.body.appendChild(li); ordenada.appendChild(li); }; let input = document.getElementById('add'); input.addEventListener('click', prueba); function borrar() { let ol = document.getElementById('order'); let li = document.getElementsByTagName('li')[0]; ol.removeChild(li); } let borrado = document.getElementById('borrar'); borrado.addEventListener('click', borrar);
C++
UTF-8
781
2.78125
3
[]
no_license
// -*- mode: c++; flycheck-clang-language-standard: "c++11"; -*- #include <cmath> #include <iostream> #include "approx_sum.h" int main() { size_t n = 1000; double delta = 0.001; std::cout << "epsilon = %" << 100*delta << std::endl; approx_sum_t p(delta); long double sum = 0; for (exponent_t i = 0; i < n; ++i) { p.set_exponent(i, i); sum += std::exp((long double) i); } std::cout << std::log(sum) << std::endl; std::cout << p.log_lb() << std::endl; std::cout << "additive err = " << std::log(sum) - p.log_lb() << std::endl; for (exponent_t i = 3; i < n-1; ++i) { p.zero_term(i); } p.zero_term(n-1); auto e = std::exp(1); auto ans = std::log(1 + e + e*e); std::cout << "additive err = " << ans - p.log_lb() << std::endl; }
Python
UTF-8
1,533
2.65625
3
[]
no_license
# coding:utf-8 import cv2 # Sobel边缘检测算子 # img = cv2.imread('/home/z840/dataset/UCF_Crimes/crop_out_30/residuals/Arson016_x264/1069.jpg', 0) # x = cv2.Sobel(img, cv2.CV_16S, 1, 0) # y = cv2.Sobel(img, cv2.CV_16S, 0, 1) # # cv2.convertScaleAbs(src[, dst[, alpha[, beta]]]) # # 可选参数alpha是伸缩系数,beta是加到结果上的一个值,结果返回uint类型的图像 # Scale_absX = cv2.convertScaleAbs(x) # convert 转换 scale 缩放 # Scale_absY = cv2.convertScaleAbs(y) # result = cv2.addWeighted(Scale_absX, 0.5, Scale_absY, 0.5, 0) # cv2.imshow('img', img) # cv2.imshow('Scale_absX', Scale_absX) # cv2.imshow('Scale_absY', Scale_absY) # cv2.imshow('result', result) # cv2.waitKey(0) # cv2.destroyAllWindows() # canny # lowThreshold = 0 # max_lowThreshold = 100 # ratio = 3 # kernel_size = 3 # # img = cv2.imread('/home/z840/dataset/UCF_Crimes/crop_out_30/residuals/Arson016_x264/1069.jpg') # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # # cv2.namedWindow('canny demo') # # cv2.createTrackbar('Min threshold', 'canny demo', lowThreshold, max_lowThreshold, CannyThreshold) # # CannyThreshold(0) # initialization # if cv2.waitKey(0) == 27: # cv2.destroyAllWindows() # canny算子 img = cv2.imread('/home/z840/dataset/UCF_Crimes/crop_out_30/test_diff/Arson016_x264/1069.jpg', 0) blur = cv2.GaussianBlur(img, (3, 3), 0) # 用高斯滤波处理原图像降噪 canny = cv2.Canny(blur, 50, 150) # 50是最小阈值,150是最大阈值 cv2.imshow('canny', canny) cv2.waitKey(0) cv2.destroyAllWindows()
Java
UTF-8
5,280
3.796875
4
[]
no_license
/* Platinum 5 백준 6549 : 히스토그램에서 가장 큰 직사각형 기준 : 1s, 256MB Time : 648ms - 스택 문제 - 입력 순서대로 연산 후 스택에 넣으면서 최대 높이를 계산한다 - 스택에 존재하는 값보다 큰 값이 들어온 경우 : top에 새로 추가하며 count를 1로 초기화한다. - 작은 값이 들어오는 경우 : 스택의 값이 작거나 같은 수가 나올때 까지 pop한다 --> 이 때 스택에는 무조건 오름차순으로 저장되기 때문에 역순으로 count를 세고 현재 위치한 높이에서 (count + 그 위치에서의 count) 를 곱하여 넓이를 계산한다 --> 그 위치의 count를 더해서 곱하는 이유는 이전에 특정 높이보다 큰값이 있던 경우 해당 높이 count에 포함되어 있기 때문 - 반복 후 작거나 같은 값이 나온경우 작은 값 : 작은 값은 그대로 push하고 입력받은 높이의 count+1 하여 저장한다. ( 입력받은 값 포함, 작은 값 포함 안함 ) 같은 값 : 같은 값은 입력받은 높이의 count + 1을 같은값에 이어서 더한다. --> 처음에는 pop해서 사라진 부분에 대한 갯수를 고려하지 못해서 막혔다. - count를 스택에 같이 저장함으로써 중간중간 pop된 직사각형들의 개수를 기억하면서 구현하였다. 평균 Time : 500 ~ 630ms - 세그먼트 트리, 분할 정복 등의 다른 여러가지 방법들이 존재하는 것 같다. */ import java.io.*; import java.util.*; public class Main { public static long max; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; StringBuilder result = new StringBuilder(); Stack<Value> stack; int n, cnt; long val, calc; Value temp; while(true){ stack = new Stack<>(); st = new StringTokenizer(in.readLine()); max = 0; n = Integer.parseInt(st.nextToken()); if(n == 0) break; for(int i=0; i<n; i++) { cnt = 0; val = Integer.parseInt(st.nextToken()); // 제일 처음 사각형 입력 if(i == 0){ stack.push(new Value(val, val, 1)); continue; } // 두번째 부터 스택확인 연산 필요 while(!stack.isEmpty()){ // 값 확인을 위해 스택에서 하나를 pop temp = stack.pop(); // 크거나 같은 값이 들어온 경우 ( 작은값에서 반복한 뒤 나오는 경우도 포함 ) if(val >= temp.height){ // 큰 값의 경우 temp는 그대로 push하고 if(val != temp.height) { stack.push(temp); // cnt는 처음 큰값을 받으면 0이고 작은값에서 탐색하다 온 경우는 0이 아님 stack.push(new Value(val, val * (cnt + 1), cnt + 1)); } else{ // 같은 값의 경우는 그 값에 더해서 push stack.push(new Value(val, temp.total + val * (cnt+1), temp.count + cnt + 1)); } break; } // 작은 값이 들어온 경우 else { // 스택 값이 더 큰것이므로 높이를 계산한 뒤 pop한다. calc = temp.total + temp.height * cnt; if(max < calc) max = calc; // 확인하기 위한 값이 스택의 마지막이였으면 맨 처음 if문으로 갈 수 없기 때문에 // 여기서 추가한다 if(stack.empty()){ stack.push(new Value(val, val * (temp.count + cnt+1), temp.count + cnt+1)); break; } cnt += temp.count; } } } // 맨 마지막까지 한 뒤 스택에 값이 남은 경우 // 높이들을 계산 cnt = 0; while(!stack.isEmpty()){ temp = stack.pop(); if(max < temp.total + temp.height * cnt) max = temp.total + temp.height * cnt; cnt += temp.count; } result.append(max); result.append("\n"); } System.out.println(result.toString()); } } class Value{ long height; long total; long count; public Value(long height, long total, long count) { this.height = height; this.total = total; this.count = count; } @Override public String toString() { return "Value{" + "height=" + height + ", total=" + total + ", count=" + count + '}'; } }
Java
ISO-8859-1
1,058
2.90625
3
[]
no_license
package heranca_classes_abstratas; public class Teste { public static void main(String[] args) { // TODO Auto-generated method stub Papagaio papagaio = new Papagaio(); papagaio.alimentar(); papagaio.andar(); papagaio.emitirSom(); papagaio.voar(); papagaio.setNome("Veludo"); System.out.println("nome do papagaio "+papagaio.getNome()); System.out.println("==============================================="); Cachorro cachorro = new Cachorro(); cachorro.amamentar(); cachorro.alimentar(); cachorro.andar(); cachorro.emitirSom(); cachorro.setNome("Dike"); cachorro.setRaca("Pastor alemo"); cachorro.setTamanho(1.23); System.out.println(cachorro.getNome()); System.out.println(cachorro.getRaca()); System.out.println(cachorro.getTamanho()); System.out.println("==============================================="); Gato gato = new Gato(); gato.alimentar(); gato.amamentar(); gato.andar(); gato.emitirSom(); gato.setNome("gatinho"); gato.setRaa("olandesa"); } }
Java
UTF-8
7,231
2.546875
3
[]
no_license
package com.androidso.app.utils; import android.content.Context; import android.media.MediaPlayer; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; public class MediaPlayers extends MediaPlayer implements MediaPlayer.OnCompletionListener { private static MediaPlayers mediaPlayer = null; private static class SingletonHolder { static final MediaPlayers INSTANCE = new MediaPlayers(); } public static MediaPlayers getInstance() { mediaPlayer = SingletonHolder.INSTANCE; return mediaPlayer; } private MediaPlayers() { } //播放停止标识 true 播放 false停止播放,进度条为100 // public boolean isPlay=true; private Context context; private String path; private CallBackProgressBar callBackProgressBar; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 2002://播放中 if (mediaPlayer != null && mediaPlayer.isPlaying()) { Log.d("MediaPlayers", " 播放 getCurrentPositions()" + getCurrentPositions() + "----" + getDurations()); if (getCurrentPositions() != 0) { Log.d("MediaPlayers", "getCurrentPositions()" + getCurrentPositions() + "----" + getDurations()); if (callBackProgressBar != null) { if (getCurrentPositions() != 0) { callBackProgressBar.callBackProgressBar(getCurrentPositions(), getDurations()); } } } else { Log.d("MediaPlayers", "还没有开始播放"); } //TODO 音频文件特别短的时候需要调整 mHandler.sendEmptyMessageDelayed(2002, 10); } break; case 2003://停止播放 // callBackProgressBar.callBackProgressBar(getCurrentPositions(),getDurations()); if (callBackProgressBar != null) { callBackProgressBar.callBackProgressBar(0, 1); } break; case 2004://播放结束 Log.d("MediaPlayers", "播放结束了"); if (callBackProgressBar != null) { callBackProgressBar.callBackProgressBar(0, 1); } break; default: break; } } }; @Override public void onCompletion(MediaPlayer mediaPlayer) { Log.d("MediaPlayers", "播放完成了"); // isPlay=false; mHandler.sendEmptyMessage(2004); mediaPlayer.stop(); } /** * 进度条展示 */ public interface CallBackProgressBar { /** * @param positions 当前进度 * @param durations 总时长 */ void callBackProgressBar(int positions, int durations); } public void setCallBackProgressBar(CallBackProgressBar callBackProgressBar) { this.callBackProgressBar = callBackProgressBar; } /** * 本地文件播放 * * @throws IOException */ public void play() throws IOException { if (mediaPlayer != null) { // if (mediaPlayer.isPlaying()) { // mediaPlayer.stop(); // } mediaPlayer.reset(); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setDataSource(path); mediaPlayer.prepare(); mediaPlayer.start(); mHandler.sendEmptyMessage(2002); } } /** * 网络异步prepare * * @throws IOException */ public void playAsync() throws IOException { if (mediaPlayer != null) { // if (mediaPlayer.isPlaying()) { // mediaPlayer.stop(); // } mediaPlayer.reset(); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setDataSource(path); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); mHandler.sendEmptyMessage(2002); } }); } } /** * 停止播放 */ @Override public void stop() { if (mediaPlayer != null) { super.stop(); mHandler.sendEmptyMessage(2003); } } /** * 暂停 */ public void pause() { if (mediaPlayer != null) { super.pause(); mHandler.removeMessages(2002); } } /** * 总长度 * * @return */ public int getDurations() { if (mediaPlayer != null) { //如果不在播放状态,则停止更新 //播放器进度条,防止界面报错 if (!mediaPlayer.isPlaying()) { // PaiPaiLog.i("MediaPlayers", "播放器停止播放,跳过获取位置"); return 0; } return mediaPlayer.getDuration(); } return 0; } /** * 当前位置 在结束的时候当前位置为0 * * @return */ public int getCurrentPositions() { if (mediaPlayer != null) { //如果不在播放状态,则停止更新 //播放器进度条,防止界面报错 if (!mediaPlayer.isPlaying()) { // PaiPaiLog.i("MediaPlayers", "播放器停止播放,跳过获取位置"); return 0; } return mediaPlayer.getCurrentPosition(); } return 0; } public Context getContext() { return context; } public void setContext(Context context) { this.context = context; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public void play(String filePath) throws IOException { setPath(filePath); play(); } public void getMediaDuration(String filePath) { try { if (mediaPlayer != null) { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { long duration = mediaPlayer.getDuration(); // GetMediaDuration // EventBus.getDefault().post(new GoodsDescribeActivity.GetMediaDuration(duration)); } }); mediaPlayer.prepare(); } } catch (Exception e) { e.printStackTrace(); } } }
Shell
UTF-8
670
3.71875
4
[]
no_license
#!/bin/bash ############################################################## ## This script lets you copy/paste things on multiple OSes. ## ############################################################## OS=$(uname) if [ "$1" = "paste" ]; then if [ "$OS" = "Darwin" ]; then pbpaste else xsel -ob fi elif [ "$1" = "type" ]; then if [ "$OS" = "Darwin" ]; then echo "Unavailable on Darwin." else xdotool type -- $(mclip get) fi elif [ "$1" = "get" ]; then if [ "$OS" = "Darwin" ]; then pbpaste else xsel -ob fi else content=$(cat -) if [ "$OS" = "Darwin" ]; then printf "%s" "$content" | pbcopy else printf "%s" "$content" | xsel -ib fi fi
Shell
UTF-8
149
2.859375
3
[]
no_license
# menambahkan angka ((sum=25+35)) # print echo $sum :'The following script calculates the square value of the number, 5. ' ((area=5*5)) echo $area
JavaScript
UTF-8
5,554
2.6875
3
[ "MIT" ]
permissive
/* eslint-disable */ import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Barcode from 'react-barcode'; class App extends Component { constructor(props) { super(props); this.state = { payDate: '', payType: '', bizUnitCode: '', phoneNumber: '', billYearMonth: '', rev: '', price: '', firstBarcode: '', secondBarcode: '', thirdBarcode: '', }; } handleChange = (e) => { const field = e.target.id; const value = e.target.value; this.setState({ [field]: value.toUpperCase(), }, () => { this.renderBarcode(); }); } renderBarcode() { const { payDate, payType, bizUnitCode, phoneNumber, billYearMonth, rev, price, } = this.state; if (payDate && payDate.length === 6) { this.setState({ firstBarcode: `${payDate}001`, }); } if (payType && payType.length === 2 && bizUnitCode !== undefined && bizUnitCode.length > 0 && phoneNumber && phoneNumber.length === 10) { const dashes = '-'.repeat(16 - 2 - bizUnitCode.length - 10); this.setState({ secondBarcode: `${payType}${bizUnitCode}${dashes}${phoneNumber}`, }); } if (billYearMonth && billYearMonth.length === 4 && rev !== undefined && rev.length === 2 && price && price.length > 0) { const fillZero = '0'.repeat(15 - 4 - 2 - price.length); this.setState({ thirdBarcode: `${billYearMonth}${rev}${fillZero}${price}`, }); } } render() { const { payDate, payType, bizUnitCode, phoneNumber, billYearMonth, rev, price, firstBarcode, secondBarcode, thirdBarcode, } = this.state; return ( <div style={ { maxWidth: '600px' } }> <fieldset> <legend>電子帳單資訊</legend> <p>請依照您的中華電信電子帳單輸入以下資訊:</p> <div className="form-group"> <label htmlFor="payDate">繳費期限(6碼 <code>YYMMDD</code>)</label> <input type="text" id="payDate" className="form-control" maxLength="6" value={ payDate } onChange={ this.handleChange } /> </div> <div className="form-inline row"> <div className="form-group col-xs-12 col-md-5"> <label htmlFor="payType">帳單別(2碼)</label> <input type="text" id="payType" className="form-control" maxLength="2" value={ payType } onChange={ this.handleChange } /> </div> <div className="form-group col-xs-12 col-md-offset-1 col-md-5"> <label htmlFor="bizUnitCode">營運處代號(長度不定)</label> <input type="text" id="bizUnitCode" className="form-control" maxLength="4" value={ bizUnitCode } onChange={ this.handleChange } /> </div> </div> <div className="form-group"> <label htmlFor="phoneNumber">手機號碼(10碼)</label> <input type="text" id="phoneNumber" className="form-control" maxLength="10" value={ phoneNumber } onChange={ this.handleChange } /> </div> <div className="form-inline row"> <div className="form-group col-xs-12 col-md-4"> <label htmlFor="billYearMonth">帳單年月(4碼 <code>YYMM</code>)</label> <input type="text" id="billYearMonth" className="form-control" maxLength="4" value={ billYearMonth } onChange={ this.handleChange } /> </div> <div className="form-group col-xs-12 col-md-4"> <label htmlFor="rev">校對碼(2碼)</label> <input type="text" id="rev" className="form-control" maxLength="2" value={ rev } onChange={ this.handleChange } /> </div> <div className="form-group col-xs-12 col-md-4"> <label htmlFor="price">繳費金額</label> <input type="text" id="price" className="form-control" maxLength="9" value={ price } onChange={ this.handleChange } /> </div> </div> </fieldset> <hr /> <fieldset> <legend>條碼產生結果</legend> { !firstBarcode && !secondBarcode && !thirdBarcode && <p>尚未產生</p> } { firstBarcode && <Barcode format="CODE39" value={ firstBarcode } /> } { secondBarcode && <Barcode format="CODE39" value={ secondBarcode } /> } { thirdBarcode && <Barcode format="CODE39" value={ thirdBarcode } /> } </fieldset> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') );
PHP
UTF-8
2,443
2.625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php final class PhabricatorAuthFactorProviderStatus extends Phobject { private $key; private $spec = array(); const STATUS_ACTIVE = 'active'; const STATUS_DEPRECATED = 'deprecated'; const STATUS_DISABLED = 'disabled'; public static function newForStatus($status) { $result = new self(); $result->key = $status; $result->spec = self::newSpecification($status); return $result; } public function getName() { return idx($this->spec, 'name', $this->key); } public function getStatusHeaderIcon() { return idx($this->spec, 'header.icon'); } public function getStatusHeaderColor() { return idx($this->spec, 'header.color'); } public function isActive() { return ($this->key === self::STATUS_ACTIVE); } public function getListIcon() { return idx($this->spec, 'list.icon'); } public function getListColor() { return idx($this->spec, 'list.color'); } public function getFactorIcon() { return idx($this->spec, 'factor.icon'); } public function getFactorColor() { return idx($this->spec, 'factor.color'); } public function getOrder() { return idx($this->spec, 'order', 0); } public static function getMap() { $specs = self::newSpecifications(); return ipull($specs, 'name'); } private static function newSpecification($key) { $specs = self::newSpecifications(); return idx($specs, $key, array()); } private static function newSpecifications() { return array( self::STATUS_ACTIVE => array( 'name' => pht('Active'), 'header.icon' => 'fa-check', 'header.color' => null, 'list.icon' => null, 'list.color' => null, 'factor.icon' => 'fa-check', 'factor.color' => 'green', 'order' => 1, ), self::STATUS_DEPRECATED => array( 'name' => pht('Deprecated'), 'header.icon' => 'fa-ban', 'header.color' => 'indigo', 'list.icon' => 'fa-ban', 'list.color' => 'indigo', 'factor.icon' => 'fa-ban', 'factor.color' => 'indigo', 'order' => 2, ), self::STATUS_DISABLED => array( 'name' => pht('Disabled'), 'header.icon' => 'fa-times', 'header.color' => 'red', 'list.icon' => 'fa-times', 'list.color' => 'red', 'factor.icon' => 'fa-times', 'factor.color' => 'grey', 'order' => 3, ), ); } }
PHP
UTF-8
2,978
2.921875
3
[ "MIT" ]
permissive
<?php /* * This file is part of php-object-mapper. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace KrzysztofMazur\ObjectMapper\Mapping\Field; use KrzysztofMazur\ObjectMapper\Util\PropertyNameConverterInterface; use KrzysztofMazur\ObjectMapper\Util\Reflection; /** * @author Krzysztof Mazur <krz@ychu.pl> */ class FieldsMatchmaker implements FieldsMatchmakerInterface { const GETTER_PATTERN = '/^(is|get)(.*)$/'; /** * @var PropertyNameConverterInterface */ private $converter; /** * @param PropertyNameConverterInterface $converter */ public function __construct(PropertyNameConverterInterface $converter) { $this->converter = $converter; } /** * {@inheritdoc} */ public function match($sourceClass, $targetClass) { $fields = []; $targetClassProperties = Reflection::getPropertyNames($targetClass); $sourceClassProperties = Reflection::getPropertyNames($sourceClass); $this->matchProperties($fields, $targetClassProperties, $sourceClassProperties); $this->matchAccessors($fields, $targetClassProperties, $sourceClass); return $fields; } /** * @param array $fields * @param array $targetClassProperties * @param array $sourceClassProperties */ private function matchProperties(&$fields, $targetClassProperties, $sourceClassProperties) { foreach ($targetClassProperties as $targetClassProperty) { if (in_array($targetClassProperty, $sourceClassProperties)) { $fields[$targetClassProperty] = $targetClassProperty; } } } /** * @param array $fields * @param array $targetClassProperties * @param string $sourceClass */ private function matchAccessors(&$fields, $targetClassProperties, $sourceClass) { $parsedGetters = $this->parseGetters($this->getClassGetters($sourceClass)); foreach ($parsedGetters as $property => $getter) { if (isset($fields[$property])) { continue; } if (in_array($property, $targetClassProperties)) { $fields[$property] = sprintf("%s()", $getter); } } } /** * @param string $className * @return array */ private function getClassGetters($className) { return array_filter( Reflection::getMethodNames($className), function ($methodName) { return preg_match(self::GETTER_PATTERN, $methodName); } ); } /** * @param array $getters * @return array */ private function parseGetters(array $getters) { $result = []; foreach ($getters as $getter) { $result[$this->converter->getPropertyName($getter)] = $getter; } return $result; } }
Python
UTF-8
208
2.921875
3
[]
no_license
#!/usr/bin/python3 """ Module doc """ class Square: """ Class square defines a square """ def __init__(self, size=0): """ initialization of an instance Square """ self.__size = size
C++
UTF-8
967
3.578125
4
[]
no_license
#include <iostream> #include <vector> class A { public: A() { std::cout << "A constructor" << std::endl; } A(const A &a) { std::cout << "A copy constructor" << std::endl; } }; int main(void) { std::vector<A> va; A a; for (int i = 0; i < 8; i++) { std::cout << i << " : "; std::cout << "size = " << va.size() << ", "; std::cout << "capacity = " << va.capacity() << std::endl; va.push_back(a); } std::cout << "size = " << va.size() << ", "; std::cout << "capacity = " << va.capacity() << std::endl; va.insert(va.begin(), a); //调用九次拷贝构造函数 std::cout << "size = " << va.size() << ", "; std::cout << "capacity = " << va.capacity() << std::endl; va.insert(va.begin(), a); //此时会调用两次拷贝构造函数,这个和实现有关 std::cout << "size = " << va.size() << ", "; std::cout << "capacity = " << va.capacity() << std::endl; return 0; }
Java
UTF-8
3,693
2.1875
2
[]
no_license
package com.luckyhua.springboot.global.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.web.cors.CorsConfiguration; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Properties specific to JHipster. * <p> * <p> * Properties are configured in the application.yml file. * </p> */ @Component @ConfigurationProperties(prefix = "jhipster", ignoreUnknownFields = false) public class JHipsterProperties { private final Security security = new Security(); private final Swagger swagger = new Swagger(); public static class Security { private final Jwt jwt = new Jwt(); public Jwt getJwt() { return jwt; } public static class Jwt { private String secret; private long tokenValidityInSeconds = 1800; public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public long getTokenValidityInSeconds() { return tokenValidityInSeconds; } public void setTokenValidityInSeconds(long tokenValidityInSeconds) { this.tokenValidityInSeconds = tokenValidityInSeconds; } } } public static class Swagger { private String title = "springboot API"; private String description = "springboot API documentation"; private String version = "0.0.1"; private String termsOfServiceUrl; private String contactName; private String contactUrl; private String contactEmail; private String license; private String licenseUrl; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getTermsOfServiceUrl() { return termsOfServiceUrl; } public void setTermsOfServiceUrl(String termsOfServiceUrl) { this.termsOfServiceUrl = termsOfServiceUrl; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getContactUrl() { return contactUrl; } public void setContactUrl(String contactUrl) { this.contactUrl = contactUrl; } public String getContactEmail() { return contactEmail; } public void setContactEmail(String contactEmail) { this.contactEmail = contactEmail; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getLicenseUrl() { return licenseUrl; } public void setLicenseUrl(String licenseUrl) { this.licenseUrl = licenseUrl; } } public Security getSecurity() { return security; } public Swagger getSwagger() { return swagger; } }
TypeScript
UTF-8
583
2.59375
3
[]
no_license
import mongoose from 'mongoose'; const logger = require('./logger'); export interface TInput { db: string; } export default ({db}: TInput) => { const connectDb = () => { mongoose .connect( db, { useNewUrlParser: true } ) .then(() => { return logger.info(`Successfully connected to ${db}`); }) .catch(error => { logger.error('Error connecting to database: ', error); return process.exit(1); }); }; connectDb(); mongoose.connection.on('disconnected', connectDb); };
TypeScript
UTF-8
12,915
2.515625
3
[ "MIT" ]
permissive
import * as path from "path"; import { SinonStub } from "sinon"; import { MaquetteComponent, Projector, createProjector, h } from "../src/index"; import { expect, sinon } from "./test-utilities"; describe("Projector", () => { let requestAnimationFrame: SinonStub; let cancelAnimationFrame: SinonStub; beforeEach(() => { requestAnimationFrame = global.requestAnimationFrame = sinon.stub().returns(5); cancelAnimationFrame = global.cancelAnimationFrame = sinon.stub(); }); afterEach(() => { delete global.requestAnimationFrame; delete global.cancelAnimationFrame; }); it("renders the virtual DOM immediately when adding renderFunctions", () => { let parentElement = { appendChild: sinon.stub(), insertBefore: sinon.stub(), ownerDocument: { createElement: sinon.spy((tag: string) => { return document.createElement(tag); }), }, removeChild: sinon.stub(), }; let renderFunction = sinon.stub().returns(h("div", [h("span")])); let projector = createProjector({}); // Append projector.append(parentElement as any, renderFunction); expect(renderFunction).to.have.been.calledOnce; expect(parentElement.ownerDocument.createElement).to.have.been.calledOnce; expect(parentElement.appendChild).to.have.been.calledOnce; expect(parentElement.appendChild.lastCall.args[0].tagName).to.equal("DIV"); // InsertBefore let siblingElement = { parentNode: parentElement, }; projector.insertBefore(siblingElement as any, renderFunction); expect(renderFunction).to.have.been.calledTwice; expect(parentElement.insertBefore).to.have.been.calledOnce; expect(parentElement.insertBefore.lastCall.args[0].tagName).to.equal("DIV"); expect(parentElement.insertBefore.lastCall.args[1]).to.equal(siblingElement); // Merge let cleanRenderFunction = sinon.stub().returns(h("div", [h("span")])); let existingElement = { appendChild: sinon.stub(), ownerDocument: { createElement: sinon.spy((tag: string) => { return document.createElement(tag); }), }, }; projector.merge(existingElement as any, cleanRenderFunction); expect(cleanRenderFunction).to.have.been.calledOnce; expect(existingElement.ownerDocument.createElement).to.have.been.calledOnce; expect(existingElement.appendChild).to.have.been.calledOnce; expect(existingElement.appendChild.lastCall.args[0].tagName).to.equal("SPAN"); // Replace let oldElement = { parentNode: parentElement, }; projector.replace(oldElement as any, renderFunction); expect(renderFunction).to.have.been.calledThrice; expect(parentElement.removeChild).to.have.been.calledOnce; expect(parentElement.removeChild.lastCall.args[0]).to.equal(oldElement); expect(parentElement.insertBefore).to.have.been.calledTwice; expect(parentElement.insertBefore.lastCall.args[0].tagName).to.equal("DIV"); expect(parentElement.insertBefore.lastCall.args[1]).to.equal(oldElement); // ScheduleRender projector.scheduleRender(); expect(renderFunction).to.have.been.calledThrice; expect(requestAnimationFrame).to.have.been.calledOnce; requestAnimationFrame.callArg(0); expect(renderFunction).to.have.callCount(6); }); it("Can stop and resume", () => { let projector = createProjector({}); projector.scheduleRender(); expect(requestAnimationFrame).to.have.been.calledOnce; requestAnimationFrame.callArg(0); // Stop projector.stop(); projector.scheduleRender(); expect(requestAnimationFrame).to.have.been.calledOnce; // Resume projector.resume(); expect(requestAnimationFrame).to.have.been.calledTwice; requestAnimationFrame.callArg(0); // Stopping before rendering projector.scheduleRender(); expect(requestAnimationFrame).to.have.been.calledThrice; projector.stop(); expect(cancelAnimationFrame).to.have.been.calledOnce; }); it("Stops when an error during rendering is encountered", () => { let projector = createProjector({}); let parentElement = { appendChild: sinon.stub(), ownerDocument: document }; let renderFunction = sinon.stub().returns(h("div")); projector.append(parentElement as any, renderFunction); renderFunction.throws("Rendering error"); projector.scheduleRender(); expect(() => { requestAnimationFrame.callArg(0); }).to.throw(Error); requestAnimationFrame.callArg(0); renderFunction.resetHistory(); projector.scheduleRender(); requestAnimationFrame.callArg(0); expect(renderFunction).not.to.be.called; requestAnimationFrame.resetHistory(); renderFunction.returns(h("div")); projector.resume(); requestAnimationFrame.callArg(0); expect(renderFunction).to.be.calledOnce; }); it("schedules a render when event handlers are called", () => { let projector = createProjector({}); let parentElement = { appendChild: sinon.stub(), ownerDocument: document }; let handleClick = sinon.stub(); let renderFunction = () => h("button", { onclick: handleClick }); projector.append(parentElement as any, renderFunction); let button = parentElement.appendChild.lastCall.args[0] as HTMLElement; let evt = { currentTarget: button, type: "click" } as unknown as MouseEvent; expect(requestAnimationFrame).not.to.be.called; button.onclick.apply(button, [evt]); expect(requestAnimationFrame).to.be.calledOnce; expect(handleClick).to.be.calledOn(button).calledWith(evt); }); it('invokes the eventHandler with "this" set to the DOM node when no bind is present', () => { let parentElement = { appendChild: sinon.stub(), ownerDocument: document }; let projector = createProjector({}); let handleClick = sinon.stub(); let renderFunction = () => h("button", { onclick: handleClick }); projector.append(parentElement as any, renderFunction); let button = parentElement.appendChild.lastCall.args[0] as HTMLElement; let clickEvent = { currentTarget: button, type: "click" }; button.onclick(clickEvent as any); // Invoking onclick like this sets 'this' to the ButtonElement expect(handleClick).to.be.calledOn(button).calledWithExactly(clickEvent); }); describe("Event handlers", () => { /** * A class/prototype based implementation of a Component * * NOTE: This is not our recommended way, but this is completely supported (using VNodeProperties.bind). */ class ButtonComponent implements MaquetteComponent { private text: string; private clicked: (sender: ButtonComponent) => void; constructor(buttonText: string, buttonClicked: (sender: ButtonComponent) => void) { this.text = buttonText; this.clicked = buttonClicked; } public render() { return h("button", { onclick: this.handleClick, bind: this }, [this.text]); } private handleClick(evt: MouseEvent) { this.clicked(this); } } it('invokes the eventHandler with "this" set to the value of the bind property', () => { let clicked = sinon.stub(); let button = new ButtonComponent("Click me", clicked); let parentElement = { appendChild: sinon.stub(), ownerDocument: document, }; let projector = createProjector({}); projector.append(parentElement as any, () => button.render()); let buttonElement = parentElement.appendChild.lastCall.args[0] as HTMLElement; let clickEvent = { currentTarget: buttonElement, type: "click" }; buttonElement.onclick(clickEvent as any); // Invoking onclick like this sets 'this' to the ButtonElement expect(clicked).to.be.calledWithExactly(button); }); let allowsForEventHandlersToBeChanged = (createProjectorImpl: (arg: any) => Projector) => { let projector = createProjectorImpl({}); let parentElement = { appendChild: sinon.stub(), ownerDocument: document, }; let eventHandler = sinon.stub(); let renderFunction = () => h("div", [ h("span", [ h("button", { onclick: eventHandler, }), ]), ]); projector.append(parentElement as any, renderFunction); let div = parentElement.appendChild.lastCall.args[0] as HTMLElement; let button = div.firstChild.firstChild as HTMLElement; let evt = { currentTarget: button, type: "click", } as unknown as MouseEvent; expect(eventHandler).to.have.not.been.called; button.onclick.apply(button, [evt]); expect(eventHandler).to.have.been.calledOnce; // Simulate changing the event handler eventHandler = sinon.stub(); projector.renderNow(); button.onclick.apply(button, [evt]); expect(eventHandler).to.have.been.calledOnce; }; it("allows for eventHandlers to be changed", () => allowsForEventHandlersToBeChanged(createProjector)); it("allows for eventHandlers to be changed on IE11", () => { /* eslint @typescript-eslint/no-var-requires: "off" */ let apFind = Array.prototype.find; try { delete Array.prototype.find; // re-require projector.ts delete require.cache[path.normalize(path.join(__dirname, "../src/projector.ts"))]; let createProjectorImpl = require("../src/projector").createProjector; Array.prototype.find = apFind; allowsForEventHandlersToBeChanged(createProjectorImpl); } finally { Array.prototype.find = apFind; } }); it("will not call event handlers on domNodes which are no longer part of the rendered VNode", () => { let buttonVisible = true; let buttonBlur = sinon.spy(); let eventHandler = () => { buttonVisible = false; }; let renderFunction = () => h("div", [ buttonVisible ? [ h("button", { onblur: buttonBlur, onclick: eventHandler, }), ] : [], ]); let projector = createProjector({}); let parentElement = document.createElement("section"); projector.append(parentElement, renderFunction); let div = parentElement.firstChild as HTMLElement; let button = div.firstChild as HTMLButtonElement; button.onclick({ currentTarget: button, type: "click" } as any); expect(buttonVisible).to.be.false; projector.renderNow(); // In reality, during renderNow(), the blur event fires just before its parentNode is cleared. // To simulate this we recreate that state in a new button object. let buttonBeforeBeingDetached = { onblur: button.onblur as (evt: Partial<Event>) => boolean, parentNode: div, }; buttonBeforeBeingDetached.onblur({ currentTarget: buttonBeforeBeingDetached, type: "blur", } as any); expect(buttonBlur).to.not.have.been.called; }); it("will not call event handlers on domNodes which are detached, like in exotic cases in Safari", () => { let buttonVisible = true; let buttonBlur = sinon.spy(); let eventHandler = () => { buttonVisible = false; }; let renderFunction = () => h("div", [ buttonVisible ? [ h("button", { onblur: buttonBlur, onclick: eventHandler, }), ] : [], ]); let projector = createProjector({}); let parentElement = document.createElement("section"); projector.append(parentElement, renderFunction); let div = parentElement.firstChild as HTMLElement; let button = div.firstChild as HTMLButtonElement; button.onclick({ currentTarget: button, type: "click" } as any); expect(buttonVisible).to.be.false; projector.renderNow(); button.remove(); let detachedButton = { onblur: button.onblur as (evt: Partial<Event>) => boolean, parentNode: null as any, }; detachedButton.onblur({ currentTarget: detachedButton, type: "blur", } as any); expect(buttonBlur).to.not.have.been.called; }); }); it("can detach a projection", () => { let parentElement = { appendChild: sinon.stub(), ownerDocument: document }; let projector = createProjector({}); let renderFunction = () => h("textarea#t1"); let renderFunction2 = () => h("textarea#t2"); projector.append(parentElement as any, renderFunction); projector.append(parentElement as any, renderFunction2); let projection = projector.detach(renderFunction); expect(projection.domNode.id).to.equal("t1"); expect(() => { projector.detach(renderFunction); }).to.throw(); }); });
Python
UTF-8
944
2.6875
3
[ "Unlicense" ]
permissive
import os import string import shutil def exRoot(root): names = os.listdir(root) for name in names: process(root, name) def process(root, name): path = os.path.join(root, name) if(not os.path.isdir(path)): return singers = string.split(name, ',', 1) if(len(singers)<=1): return targetDir = os.path.join(root, singers[0]) if(not os.path.exists(targetDir)): os.makedirs(targetDir) names = os.listdir(path) for fileName in names: merge(root, singers[0], name, fileName) print 'rmdir ' + path os.rmdir(path) def merge(root, singer, dirName, fileName): sourceFile = os.path.join(root, dirName, fileName) targetFile = os.path.join(root, singer, fileName) if(not os.path.exists(targetFile)): print 'move ' + targetFile shutil.move(sourceFile, targetFile) else: print 'delete ' + sourceFile os.remove(sourceFile)
Markdown
UTF-8
613
2.6875
3
[]
no_license
# First Chapter GitBook allows you to organize your book into chapters, each chapter is stored in a separate file like this one.![](/assets/KOC_scree_plot %282%29.png) {% youtube %} src="https://www.youtube.com/watch?v=9bZkp7q19f0" {% endyoutube %} ok how about it? {% youtube %} src="https://www.youtube.com/watch?v=eYA3f1qo_5E" {% endyoutube %} or this one? ## H2 header ### H3 header ![](/assets/superformula.png) * item 1 * item 2 * item 2a * item 2b > ive alsobea sosf > but you know what happens *however* it always **depends** on *what it is that **you** want to say* # nexg
Java
UTF-8
931
2.4375
2
[]
no_license
package com.example.telemedical.tabs; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; public class WelcomePagerAdapter extends FragmentStatePagerAdapter { int noOfTabs; public WelcomePagerAdapter(@NonNull FragmentManager fm, int noOfTabs) { super(fm); this.noOfTabs=noOfTabs; } @NonNull @Override public Fragment getItem(int position) { switch (position){ case 0: Welcome1 welcome1=new Welcome1(); return welcome1; case 1: Welcome2 welcome2=new Welcome2(); return welcome2; default: Welcome1 def=new Welcome1(); return def; } } @Override public int getCount() { return noOfTabs; } }
Markdown
UTF-8
1,182
3.625
4
[]
no_license
# 349. Intersection of Two Arrays Given two arrays, write a function to compute their intersection. **Example:** Given nums1 = `[1, 2, 2, 1]`, nums2 = `[2, 2]`, return `[2]`. **Note:** - Each element in the result must be unique. - The result can be in any order. # Solution ## 我的思路: 双层循环,时间复杂度O(m*n)。(5%) ##优化方法 使用Set集合,使得他的时间复杂度降为O(m+n)。(21%) ##更好的方法 ###可以联想到双指针法 1. 对数组排序,双索引分别遍历两个数组。 2. 比较两个索引处值得大小,并依此来移动索引。 3. 如果相等则存到Set集合。 3. 直到其中一个索引指到结尾结束。(78%) ###问题: 发现 if(boolean){ exception; } 的效率高于 if(boolean) exception; ###实验: int j = 0; long t1=System.currentTimeMillis(); for(int i=0;i<100000000;i++) if(true) j++; long t2=System.currentTimeMillis(); System.out.println(t2-t1); j = 0; long t3=System.currentTimeMillis(); for(int i=0;i<100000000;i++){ if(true){ j++; } } long t4=System.currentTimeMillis(); System.out.println(t4-t3); 多次测试:
C++
UTF-8
892
3.40625
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <vector> #include <fstream> #include "RetailItem.h" using namespace std; void loadItems(vector<RetailItem> &); int main() { vector<RetailItem> item(20); loadItems(item); cout << "description" << setw(10) << "price" << setw(10) << "available" << setw(10) << "stock value" << endl << endl; for (int i = 0; i < item.size(); i++) { cout << setw(10) << item[i].getDescription() << setw(10) << item[i].getPrice << setw(10) << item[i].getUnits() << setw(10) << item[i].getStockValue << endl; } return 0; } void loadItems(vector<RetailItem> & other) { fstream file; string name, units, price; file.open("retail.csv"); while (getline(file, name, ',')) { getline(file, units, ','); getline(file, price, '\n'); RetailItem display(name, stoi(units), stod(price)); other.push_back(display); } file.close; }