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
Java
UTF-8
1,231
2.109375
2
[]
no_license
package com.wisea.cultivar.supply.po; import com.wisea.cloud.model.annotation.Check; import io.swagger.annotations.ApiModelProperty; /** * 修改价格 * @author chengq * @date 2020/8/15 18:45 */ public class SerUpdateStatePo { @ApiModelProperty("服务单id") @Check(test = {"required" }, requiredMsg = "服务单id不能为空") private Long id; @ApiModelProperty(value = "状态 1-待服务 2-服务中 3-已取消") @Check(test = { "required", "liveable" }, liveable = {"1", "2", "3"}, logicMsg = "商品发布状态只能为1、2、3") private String serListStateType; @ApiModelProperty(value = "取消原因") private String serListCancelReason; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSerListStateType() { return serListStateType; } public void setSerListStateType(String serListStateType) { this.serListStateType = serListStateType; } public String getSerListCancelReason() { return serListCancelReason; } public void setSerListCancelReason(String serListCancelReason) { this.serListCancelReason = serListCancelReason; } }
C#
UTF-8
15,500
2.640625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; using TheManager.Comparators; namespace TheManager { public class RandomDrawingLevel : IRandomDrawing { private readonly GroupsRound _round; private readonly ClubAttribute _attribute; public RandomDrawingLevel(GroupsRound tour, ClubAttribute attribute) { _round = tour; _attribute = attribute; } public void RandomDrawing() { List<Club> pot = new List<Club>(_round.clubs); try { pot.Sort(new ClubComparator(_attribute, false)); if (pot[0] as NationalTeam != null) { List<NationalTeam> nationalsTeams = new List<NationalTeam>(); foreach (Club c in pot) { nationalsTeams.Add(c as NationalTeam); } nationalsTeams.Sort(new NationsFifaRankingComparator(false)); pot.Clear(); foreach (NationalTeam nt in nationalsTeams) { pot.Add(nt); } } } catch { Utils.Debug("Le tri pour " + _round.name + "(" + _round.Tournament.name + " de type niveau a echoué"); } int minTeamsByGroup = _round.clubs.Count / _round.groupsCount; List<Club>[] baseHats = new List<Club>[minTeamsByGroup]; //Some groups will get one more team if (_round.clubs.Count % _round.groupsCount > 0) { baseHats = new List<Club>[minTeamsByGroup + 1]; } int ind = 0; for (int i = 0; i < minTeamsByGroup; i++) { baseHats[i] = new List<Club>(); for (int j = 0; j < _round.groupsCount; j++) { baseHats[i].Add(pot[ind]); ind++; } } //Create last hat if there is remaining teams if (_round.clubs.Count % _round.groupsCount > 0) { baseHats[baseHats.Length - 1] = new List<Club>(); for (int j = _round.groupsCount * minTeamsByGroup; j < _round.clubs.Count; j++) { baseHats[baseHats.Length - 1].Add(pot[j]); } } //Shuffle hats because of the case 2 for (int i = 0; i < baseHats.Count(); i++) { baseHats[i].Shuffle(); } bool succeed = false; while(!succeed) { succeed = true; for(int i = 0; i<_round.groupsCount; i++) { _round.groups[i].Clear(); } try { List<Club>[] hats = new List<Club>[baseHats.Length]; for(int i = 0; i < baseHats.Length; i++) { hats[i] = new List<Club>(baseHats[i]); } bool ruleConcernsContinent = _round.rules.Contains(Rule.OneTeamByContinentInGroup); //Foreach groups for (int i = 0; i < _round.groupsCount; i++) { //Create constraints dictionnary. Specify for each continent or country minimum and maximum numbers of teams on each group to respect rules. //Only used if round include OneTeamByContinentInGroup or OneClubByCountryInGroup rule Dictionary<ILocalisation, List<int>> constraintsContinents = new Dictionary<ILocalisation, List<int>>(); Dictionary<ILocalisation, List<int>> constraintsCountry = new Dictionary<ILocalisation, List<int>>(); foreach (Continent c in Session.Instance.Game.kernel.world.continents) { int teamsCount = TeamsOfContinent(hats, c); float teamsRatio = teamsCount / (_round.groupsCount - i + 0.0f); constraintsContinents.Add(c, new List<int> { (int)Math.Floor(teamsRatio), (int)Math.Ceiling(teamsRatio) }); } List<Country> roundCountries = new List<Country>(); foreach (Club c in _round.clubs) { Country cCountry = c.Country(); if (!roundCountries.Contains(cCountry)) { roundCountries.Add(cCountry); } } foreach (Country c in roundCountries) { int teamsCount = TeamsOfCountry(hats, c); float teamsRatio = teamsCount / (_round.groupsCount - i + 0.0f); constraintsCountry.Add(c, new List<int> { (int)Math.Floor(teamsRatio), (int)Math.Ceiling(teamsRatio) }); } //Foreach hats for (int j = 0; j < hats.Length; j++) { if (hats[j].Count > 0) { List<Club> possibleTeams = new List<Club>(); foreach (Club hatClub in hats[j]) { if (!_round.rules.Contains(Rule.OneTeamByContinentInGroup) && !_round.rules.Contains(Rule.OneClubByCountryInGroup)) { possibleTeams.Add(hatClub); } else { ILocalisation hcLocalisation = null; if(ruleConcernsContinent) { hcLocalisation = hatClub.Country().Continent; } else { hcLocalisation = hatClub.Country(); } Dictionary<ILocalisation, List<int>> constraintsLocalisable = ruleConcernsContinent ? constraintsContinents : constraintsCountry; //Case 1 //Si le nombre d'équipes par groupe + les équipes qui sont obligées d'arriver (car certains chapeaux contiennent uniquement des équipes de tel pays) est inférieur au nombre maximal d'équipes autorisées dans le groupe, alors on peut l'ajouter aux équipes sélectionnables. if (CountClubsOfLocalisation(_round.groups[i], hcLocalisation, ruleConcernsContinent) - HatsWithOnlyTeamsOfLocalizable(hats, j + 1, hcLocalisation, ruleConcernsContinent) < constraintsLocalisable[hcLocalisation][1]) { possibleTeams.Add(hatClub); } //Case 2 // Si le nombre de chapeaux restants avec des équipes de tel pays est égal au nombre minimum d'équipes nécessaire qui manque dans le groupe, alors on est obligé de prendre cette équipe if (RemainingHatsWithTeamsOfLocalizable(hats, j, hcLocalisation, ruleConcernsContinent) == constraintsLocalisable[hcLocalisation][0] - CountClubsOfLocalisation(_round.groups[i], hcLocalisation, ruleConcernsContinent)) { possibleTeams = new List<Club> { hatClub }; break; } /* if (_round.rules.Contains(Rule.OneTeamByContinentInGroup)) { Continent hcContinent = hatClub.Country().Continent; //Case 1 if (CountClubsOfContinent(_round.groups[i], hcContinent) - HatsWithOnlyTeamsOfContinent(hats, j + 1, hcContinent) < constraintsContinents[hcContinent][1]) { possibleTeams.Add(hatClub); } //Case 2 if (RemainingHatsWithTeamsOfContinent(hats, j, hcContinent) == constraintsContinents[hcContinent][0] - CountClubsOfContinent(_round.groups[i], hcContinent)) { possibleTeams = new List<Club> { hatClub }; break; } } else if (_round.rules.Contains(Rule.OneClubByCountryInGroup)) { Country hcCountry = hatClub.Country(); //Case 1 if (CountClubsOfCountry(_round.groups[i], hcCountry) - HatsWithOnlyTeamsOfCountry(hats, j + 1, hcCountry) < constraintsCountry[hcCountry][1]) { possibleTeams.Add(hatClub); } //Case 2 if (RemainingHatsWithTeamsOfCountry(hats, j, hcCountry) == constraintsCountry[hcCountry][0] - CountClubsOfCountry(_round.groups[i], hcCountry)) { possibleTeams = new List<Club> { hatClub }; break; } }*/ } } Club selectedTeam = possibleTeams[Session.Instance.Random(0, possibleTeams.Count)]; _round.groups[i].Add(selectedTeam); hats[j].Remove(selectedTeam); } } } } catch(Exception e) { Utils.Debug(_round.Tournament.name + " (" + _round.name + ") Echec du tirage au sort de ce tour. Nouvelle tentative"); succeed = false; } } } private int CountClubsOfLocalisation(List<Club> clubs, ILocalisation localizable, bool withContinents) { int res = 0; foreach (Club c in clubs) { ILocalisation comp = null; if (withContinents) { comp = c.Country().Continent; } else { comp = c.Country(); } if (comp == localizable) { res++; } } return res; } private int TeamsOfCountry(List<Club>[] hats, Country country) { int res = 0; foreach (List<Club> lc in hats) { foreach (Club c in lc) { if (c.Country() == country) { res++; } } } return res; } private int TeamsOfContinent(List<Club>[] hats, Continent continent) { int res = 0; foreach (List<Club> lc in hats) { foreach (Club c in lc) { if (c.Country().Continent == continent) { res++; } } } return res; } private int TeamsOfLocalizable(List<Club>[] hats, ILocalisation localizable, bool withContinents) { int res = 0; foreach (List<Club> lc in hats) { foreach (Club c in lc) { ILocalisation comp = null; if (withContinents) { comp = c.Country().Continent; } else { comp = c.Country(); } if (comp == localizable) { res++; } } } return res; } private int RemainingHatsWithTeamsOfLocalizable(List<Club>[] hats, int currentHat, ILocalisation localizable, bool withContinents) { int res = 0; for (int i = currentHat; i < hats.Count(); i++) { bool teamsOfContinent = false; foreach (Club c in hats[i]) { ILocalisation comp = null; if (withContinents) { comp = c.Country().Continent; } else { comp = c.Country(); } if (comp == localizable) { teamsOfContinent = true; } } if (teamsOfContinent) { res++; } } return res; } private int HatsWithOnlyTeamsOfLocalizable(List<Club>[] hats, int currentHat, ILocalisation localizable, bool continent) { int res = 0; for (int i = currentHat; i < hats.Count(); i++) { bool onlyTeam = true; foreach (Club c in hats[i]) { ILocalisation comp = null; if(continent) { comp = c.Country().Continent; } else { comp = c.Country(); } if (comp != localizable) { onlyTeam = false; } } if (onlyTeam) { res++; } } return res; } } }
C++
UTF-8
1,974
3.890625
4
[]
no_license
// 251 Flatten 2D Vector // Implement an iterator to flatten a 2d vector. // For example, // Given 2d vector = // [ // [1,2], // [3], // [4,5,6] // ] // By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6]. // Hint: // How many variables do you need to keep track? // Two variables is all you need. Try with x and y. // Beware of empty rows. It could be the first few rows. // To write correct code, think about the invariant to maintain. What is it? // The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it? // Not sure? Think about how you would implement hasNext(). Which is more complex? // Common logic in two different places should be refactored into a common method. /** * Your Vector2D object will be instantiated and called as such: * Vector2D i(vec2d); * while (i.hasNext()) cout << i.next(); */ class Vector2D { public: Vector2D(vector<vector<int>>& vec2d) { rowIt = vec2d.begin(); rowEndIt = vec2d.end(); if (rowIt != vec2d.end()) colIt = rowIt->begin(); } int next() { hasNext(); return *colIt++; } bool hasNext() { while (rowIt != rowEndIt && colIt == rowIt->end()) { ++rowIt; if (rowIt != rowEndIt) colIt = rowIt->begin(); } return rowIt != rowEndIt; } private: vector<vector<int>>::iterator rowIt; vector<vector<int>>::iterator rowEndIt; vector<int>::iterator colIt; }; class Vector2D { vector<vector<int>>::iterator i, iEnd; int j = 0; public: Vector2D(vector<vector<int>>& vec2d) { i = vec2d.begin(); iEnd = vec2d.end(); } int next() { hasNext(); return (*i)[j++]; } bool hasNext() { while (i != iEnd && j == (*i).size()) i++, j = 0; return i != iEnd; } };
C
UTF-8
544
2.78125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "../ubootenv.h" static void list_bootenvs(void) { env_attribute *attr = bootenv_get_attr(); while(attr != NULL) { printf("[%s]: [%s]\n", attr->key, attr->value); attr = attr->next; } } int main(int argc, char *argv[]) { bootenv_init(); if (argc == 1) { list_bootenvs(); } else { //printf("key:%s\n", argv[1]); const char* p_value = bootenv_get(argv[1]); if (p_value) { printf("%s\n", p_value); } } return 0; }
C++
UTF-8
3,124
3.015625
3
[]
no_license
#include "MyOthelloAI.hpp" #include <ics46/factory/DynamicFactory.hpp> #include<iostream> chenjunz::MyOthelloAI::MyOthelloAI() { } std::pair<int,int> chenjunz::MyOthelloAI::chooseMove(const OthelloGameState& state) { std::vector<std::pair<int,int>> validMoves = validMove(state); int index = 0; int depth = 5; std::vector<int> eval; std::string turn; for(int i = 0; i<validMoves.size(); i++) { std::unique_ptr<OthelloGameState> state_ptr = state.clone(); state_ptr->makeMove(validMoves[i].first,validMoves[i].second); if (state.isBlackTurn()) { turn = "black"; } else { turn = "white"; } eval.push_back(search(*state_ptr,depth,turn)); } for(int i = 0; i<eval.size(); i++) { if (eval[index]<eval[i]) { index = i; } } return validMoves[index]; } int chenjunz::MyOthelloAI::search(OthelloGameState& s, int depth, std::string turn) { if (depth == 0) { if (turn == "black"){return (s.blackScore()-s.whiteScore());} else {return (s.whiteScore()-s.blackScore());} } else { std::vector<std::pair<int,int>> validMoves = validMove(s); std::unique_ptr<OthelloGameState> s_ptr; int eval; if(checkTurn(s,turn)) { int bestEval = -999; for(unsigned int i = 0; i < validMoves.size(); i++) { s_ptr = s.clone(); s_ptr->makeMove(validMoves[i].first,validMoves[i].second); eval = search(*s_ptr,depth-1,turn); if (eval >= bestEval) {bestEval = eval;} } } else { int bestEval = 999; for(unsigned int i = 0; i < validMoves.size(); i++) { s_ptr = s.clone(); s_ptr->makeMove(validMoves[i].first,validMoves[i].second); eval = search(*s_ptr,depth-1,turn); if (eval <= bestEval) {bestEval = eval;} } } return eval; } } bool chenjunz::MyOthelloAI::checkTurn(OthelloGameState& s,std::string turn) { if (turn == "black") { if (s.isBlackTurn()) {return true;} else {return false;} } else { if (s.isWhiteTurn()) {return true;} else {return false;} } } std::vector<std::pair<int,int>> chenjunz::MyOthelloAI::validMove(const OthelloGameState& state) { std::vector<std::pair<int,int>> validMove; int width = state.board().width(); int height = state.board().height(); for(int x = 0; x<width; x++) { for(int y = 0; y<height; y++) { if (state.isValidMove(x,y)) { validMove.push_back(std::make_pair(x,y)); } } } return validMove; } ICS46_DYNAMIC_FACTORY_REGISTER(OthelloAI,chenjunz::MyOthelloAI,"My Othello AI(Required)");
C#
UTF-8
1,131
2.875
3
[]
no_license
using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Api.Services { public class GitService : IGitService { public async Task<string[]> GetGitRepos(string userName) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("product", "1")); var url = $"https://api.github.com/users/{userName}/repos"; var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsAsync<JObject[]>(); return data.Select(x => x["name"].ToString()).ToArray(); } else { Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented)); Console.WriteLine(url); } } return new string[] { }; } } }
Python
UTF-8
5,922
2.578125
3
[]
no_license
#!/usr/bin/python # -*- coding:utf-8 -*- from bs4 import BeautifulSoup import urllib import bs4 import requests import time import schedule import json #check mode #1: check latest by timer 3600s and if win a prize then send message to ifttt #2: check latest 30 times award number #3: just check latest award number and if win a prize then send message to ifttt CHECK_MODE = 3 #set you ifttt key IFTTT_KEY = '' #message type MESSAGE_AWARD_NUMBER = 0 MESSAGE_COUNT15 = 1 #Notify mode NOTIFY_BY_IFTTT = 0 NOTIFY_BY_PHONENUMBER = 1 #default number check_number_red = [] check_number_blue = [] prizeData = [] checked_red = [] checked_blue = [] f_award_number_start = 0 def get_prize_data(): print "get data form chart.lottery.gov.cn..." page = urllib.urlopen('http://chart.lottery.gov.cn//dltBasicKaiJiangHaoMa.do?typ=1&issueTop=30') pageCode = page.read() page.close() #pageFile = open('pageCode.txt','w') #pageFile.write(pageCode) #pageFile.close() return pageCode def create_list(obj): if type(obj) is bs4.element.Tag: #find Issue and get number if len(obj.select('.Issue')) > 0: tmpDate = {"NO":obj.select('.Issue')[0].string, "red":[], "blue":[]} #print(obj.select('.Issue')[0].string) for item in obj.select('.B_1'): tmpDate["red"].append(item.string) #print(item.string) for item in obj.select('.B_5'): tmpDate["blue"].append(item.string) #print(item.string) prizeData.append(tmpDate) if obj.next_sibling == None: return create_list(obj.next_sibling) def check_prize(list_d): del checked_blue[:] del checked_red[:] #check red for index in check_number_red: for x in list_d["red"]: if index == x: checked_red.append(index) break #check blue #for index in check_number_blue: # for x in list_d["blue"]: # if index == x: # checked_blue.append(index) # break map(f_check_blue, list_d["blue"]) def f_check_blue(number): for index in check_number_blue: if index == number: checked_blue.append(number) return number def check_30_times_award_number(): print "chack prize..." for i, item in enumerate(prizeData): if i%5 == 0: print "-----------------------------------" check_prize(item) print prizeData[i]["NO"], checked_red, checked_blue def check_latest_award_number(): global f_award_number_start global check_number_red global check_number_blue global IFTTT_KEY soup = BeautifulSoup(get_prize_data(), 'html.parser', from_encoding = 'gb2312') print "analysis data..." create_list(soup.tr) #get user data jsonData = get_user_data() for x in jsonData["data"]: check_number_red = x["red"] check_number_blue = x["blue"] print "check last prize result..." + x["name"] if check_latest_prize_result(): if x["NotifyMode"] == NOTIFY_BY_IFTTT: IFTTT_KEY = x["key"] send_message_to_ifttt(MESSAGE_AWARD_NUMBER) elif x["NotifyMode"] == NOTIFY_BY_PHONENUMBER: #send by phone number print "1" #check start number if check_start_number(x["startNO"]): x["startNO"] = int(prizeData[-1]["NO"]) if x["NotifyMode"] == NOTIFY_BY_IFTTT: IFTTT_KEY = x["key"] send_message_to_ifttt(MESSAGE_COUNT15) elif x["NotifyMode"] == NOTIFY_BY_PHONENUMBER: #send by phone number print "1" save_user_data(jsonData) del prizeData[:] soup.decompose() def main(): if CHECK_MODE == 1: #1:run with schedule schedule.every().tuesday.at("8:00").do(check_latest_award_number) schedule.every().thursday.at("8:00").do(check_latest_award_number) schedule.every().sunday.at("8:00").do(check_latest_award_number) while True: schedule.run_pending() time.sleep(60) elif CHECK_MODE == 2: #2:print last 30 times prize number soup = BeautifulSoup(get_prize_data(), 'html.parser', from_encoding = 'gb2312') print "analysis data..." create_list(soup.tr) check_30_times_award_number() elif CHECK_MODE == 3: #3:check last prize result check_latest_award_number() print "check end!" def check_latest_prize_result(): check_prize(prizeData[-1]) print prizeData[-1]["NO"], checked_red, checked_blue if (len(checked_red) + len(checked_blue) > 2) or (len(checked_blue) == 2): return True return False def send_message_to_ifttt(message_type): global IFTTT_KEY ifttt_webhook_url = 'https://maker.ifttt.com/trigger/lottery/with/key/' + IFTTT_KEY print "send message to ifttt..." if message_type == MESSAGE_AWARD_NUMBER: tmp = {'value1': prizeData[-1]["NO"], 'value2': checked_red, 'value3': checked_blue} requests.post(ifttt_webhook_url, json = tmp) return elif message_type == MESSAGE_COUNT15: tmp = {'value1': prizeData[-1]["NO"], 'value2': "it's time to buy a new lottery"} requests.post(ifttt_webhook_url, json = tmp) return print "same award_number, do not send..." return def get_user_data(): with open("data.json", "r") as f: return json.load(f) def save_user_data(data): with open("data.json","w") as dump_f: json.dump(data,dump_f) def check_start_number(start_number): count = 0 for x in prizeData: if int(x["NO"]) >= start_number: count += 1 if count == 15: return True return False if __name__ == '__main__': main()
JavaScript
UTF-8
1,419
3.265625
3
[]
no_license
/** * Creates a new data section - an element to display data about a professor from a certain source. * Just creating the object will not put it onto the page. To do that, you must add `dataSection.elements.main` * to the page. * * @constructor * @param {string} title The title to use to identify the section. * @param {string} id The unique id used for this section. Must be a valid CSS ID. * @param {{label, dataField}[]} fields An array of ojects with the format {label, dataField} where label * is the text to use on the `page` and `dataField` is the key that will hold the relevant data in `this.data` */ function DataSection(title, id, fields, noDataMsg, errorHandler) { //Object of most recently fetched data for this section this.data = null; //URL the user can click to see the most recently fetched data from the original source this.url = null; //Cache of all previously requested data with the key being "<subjectCode><courseCode> <fullname>" this.cache = {}; //The current course being parsed. To prevent race conditions hopefully this.currentCourse = ''; // The message to show when there is no data to display. this.noDataMsg = noDataMsg; this.errorHandler = errorHandler; //Object of elements relevant to this section this.elements = {}; this.title = title; this.id = id; this.fields = fields; this.createElements(); }
Python
UTF-8
860
2.75
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: lzzhang # @Date: 2018-05-14 08:29:08 # @Last Modified by: lzzhang # @Last Modified time: 2018-05-14 08:42:13 class Solution: def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ if len(grid) == 0: return 0 m = len(grid) n = len(grid[0]) dp = [0 for _ in range(n)] for i in range(0,m): for j in range(0,n): if i == 0: if j == 0: dp[j] = grid[i][j] else: dp[j] = dp[j-1] + grid[i][j] elif j == 0: dp[j] = dp[j] + grid[i][j] else: dp[j] = min(dp[j], dp[j-1]) + grid[i][j] return dp[-1]
C#
UTF-8
12,325
2.640625
3
[]
no_license
/*using System; using System.Collections.Generic; using System.Linq; using System.Text; using Mars_Rover_RCU.Kinematics; using Mars_Rover_Configuration; namespace Mars_Rover_RCU.Kinematics { public class Kinematics { private int FLOffset = 0; private int RLOffset = 20; private int FROffset = 0; private int RROffset = 20; private int gripperInterval = 50; private int MAX_VELOCITY; private int sensors; /// <summary> /// Creates an instance of Kinematics with the specified maximum velocity. /// </summary> /// <param name="max_vel"></param> public Kinematics(int max_vel) { if (max_vel <= 0) throw new ArgumentOutOfRangeException("Maximum velocity must be positive"); MAX_VELOCITY = max_vel; } /// <summary> /// Performs calculation for the wheel states based on the input. /// </summary> /// <param name="radius">Radius of the circle to travel (center of robot as reference). /// Negative values are a counter-clockwise travel; positive value are clockwise travel. /// A radius of Infinity (either positive or negative) forces robot to travel straight. /// A radius less than MINIMUM_RADIUS will cause the robot to spin in place.</param> /// <param name="velocity">Velocity to travel (center of robot as reference)</param> /// <returns></returns> public Dictionary<Devices, int> GetWheelStates(int radius, int velocity, int armVelocity, bool ScoopIn, bool ScoopOut, bool autoStopArmUp, bool autoStopArmDown, bool wallFollow) { Dictionary<Devices, int> states = new Dictionary<Devices, int>(); int adjustedArmVelocity = Convert.ToInt32(Math.Min(MAX_VELOCITY, Math.Abs(armVelocity))) * Math.Sign(armVelocity); //deal with scoop servo (NOTE: MAKE SETTING FOR SENSITIVITY) if (ScoopIn == true && ScoopOut == false) //scoop in states[Devices.FrontRightSteering] = gripperInterval; else if (ScoopIn == false && ScoopOut == true) //retract gripper states[Devices.FrontRightSteering] = gripperInterval * -1; else if (ScoopIn == false && ScoopOut == false) // gripper not in use - stay at last position states[Devices.FrontRightSteering] = 0; if (Program._Phidgets != null) //deal with arm motor { if (adjustedArmVelocity > 0 && Program._Phidgets.getUpperSwitch() == true) //arm is moving up (+ velocity value) and at max position states[Devices.FrontRightWheel] = 0; else if (adjustedArmVelocity < 0 && Program._Phidgets.getLowerSwitch() == true) //arm is moving down (- velocity value) and at minimum position states[Devices.FrontRightWheel] = 0; else //arm is operating between min and max position (no switch is pressed) states[Devices.FrontRightWheel] = adjustedArmVelocity; } else states[Devices.FrontRightWheel] = 0; //phidgets board not in use so do not use arm for the safety of the hardware (switches must be checked) if (Math.Abs(radius) >= 2047) { //simple enough, just drive straight at the given velocities. return GetStraightSystemState(states, velocity, autoStopArmUp, autoStopArmDown, wallFollow); } else { //general case return GetGeneralSystemState(states, radius, velocity, autoStopArmUp, autoStopArmDown); } } private Dictionary<Devices, int> GetStraightSystemState(Dictionary<Devices, int> states, double velocity, bool autoStopArmUp, bool autoStopArmDown, bool wallFollow) { int adjusted_velocity = Convert.ToInt32(Math.Min(MAX_VELOCITY, Math.Abs(velocity))) * Math.Sign(velocity); ; int frontSensor = Program._Phidgets.getFront(); int leftSensor = Program._Phidgets.getLeft(); int rightSensor = Program._Phidgets.getRight(); int radiusVariation = 0; double val = 0; if (autoStopArmDown == true) { if (velocity < 0 && frontSensor <= 208 && frontSensor >= 80) //negative (going forward) sensor in range 80-208 { double factor = (double)(208 - frontSensor) / 128; factor = Math.Pow(factor, 2); adjusted_velocity = Convert.ToInt32(factor * adjusted_velocity); } else if (velocity < 0 && frontSensor > 208) // trying to go forward when not allowed { adjusted_velocity = 0; } } else if (autoStopArmUp == true) { if (velocity < 0 && frontSensor <= 403 && frontSensor >= 80) //negative (going forward) sensor in range 80-423 { double factor = (double)(403 - frontSensor) / 323; factor = Math.Pow(factor, 2); adjusted_velocity = Convert.ToInt32(factor * adjusted_velocity); } else if (velocity < 0 && frontSensor > 403) // trying to go forward when not allowed { adjusted_velocity = 0; } } if (wallFollow == true && leftSensor >= 112 && leftSensor <= 397) { if (leftSensor > 187 && leftSensor <= 397)//the robot is moving towards the left side of the track, correct right by slowing down the right side { val = 1 - (double)(397 - leftSensor) / 209; //between 0 and 1 radiusVariation = Convert.ToInt32(Math.Round(val * 30)); GetGeneralSystemState(states, (-1 * (100 - radiusVariation)), adjusted_velocity, autoStopArmUp, autoStopArmDown); //+radius go right } else if (leftSensor <= 187 && leftSensor >= 112)//robot moving towards the right side, correct by slowing down left motor { val = (double)(187 - leftSensor) / 75; radiusVariation = Convert.ToInt32(Math.Round(val * 30)); GetGeneralSystemState(states, (100 - radiusVariation), adjusted_velocity, autoStopArmUp, autoStopArmDown); //-radius go left } } else if (wallFollow == true && rightSensor >= 116 && rightSensor <= 400) { if (rightSensor > 191 && rightSensor <= 400) { val = 1 - (double)(400 - rightSensor) / 208; //between 0 and 1 radiusVariation = Convert.ToInt32(Math.Round(val * 30)); GetGeneralSystemState(states, (100 - radiusVariation), adjusted_velocity, autoStopArmUp, autoStopArmDown); //+radius go right } else if (rightSensor <= 191 && leftSensor >= 116) { val = (double)(1 - leftSensor) / 75; radiusVariation = Convert.ToInt32(Math.Round(val * 30)); GetGeneralSystemState(states, (-1 * (100 - radiusVariation)), adjusted_velocity, autoStopArmUp, autoStopArmDown); //-radius go left } } else { states[Devices.FrontLeftWheel] = adjusted_velocity; states[Devices.FrontLeftSteering] = FLOffset; //states[Devices.FrontRightSteering] = FROffset; states[Devices.MidLeftWheel] = adjusted_velocity; //mercury left motors states[Devices.MidRightWheel] = adjusted_velocity; //mercury right motors states[Devices.RearLeftWheel] = adjusted_velocity; states[Devices.RearLeftSteering] = RLOffset; states[Devices.RearRightWheel] = adjusted_velocity; states[Devices.RearRightSteering] = RROffset; } return states; } private Dictionary<Devices, int> GetGeneralSystemState(Dictionary<Devices, int> states, double radius, double velocity, bool autoStopArmUp, bool autoStopArmDown) { //first, calculate wheel angles --Not important for mercury rover double rad_magnitude = Math.Abs(radius); int inner_angle = 20;//Convert.ToInt32(90 - Math.Acos((Constants.WHEEL_BASE / 2) / (inner_radius+1)) * 180 / Math.PI); int outer_angle = 20;//Convert.ToInt32(90 - Math.Acos((Constants.WHEEL_BASE / 2) / outer_radius) * 180 / Math.PI); //calculate wheel velocities --> formula: Vinner = ((2R-width)/(2R+width)) * Vouter (Vouter is the velocity passed in) int outer_vel = Convert.ToInt32(Math.Min(MAX_VELOCITY, Math.Abs(velocity))) * Math.Sign(velocity); int inner_vel = Convert.ToInt32(((2 * rad_magnitude) - Constants.TRACK_WIDTH) / ((2 * rad_magnitude) + Constants.TRACK_WIDTH) * outer_vel); int frontSensor = Program._Phidgets.getFront(); if (autoStopArmDown == true && radius != 0) { if (velocity < 0 && frontSensor <= 208 && frontSensor >= 80) //negative (going forward) sensor in range 80-208 { double factor = (double)(208 - frontSensor) / 128; factor = Math.Pow(factor, 2); outer_vel = Convert.ToInt32(factor * outer_vel); inner_vel = Convert.ToInt32(factor * inner_vel); } else if (velocity < 0 && frontSensor > 208) // trying to go forward when not allowed { outer_vel = 0; inner_vel = 0; } } else if (autoStopArmUp == true && radius != 0) { if (velocity < 0 && frontSensor <= 403 && frontSensor >= 80) //negative (going forward) sensor in range 80-423 { double factor = (double)(403 - frontSensor) / 323; factor = Math.Pow(factor, 2); outer_vel = Convert.ToInt32(factor * outer_vel); inner_vel = Convert.ToInt32(factor * inner_vel); } else if (velocity < 0 && frontSensor > 403) // trying to go forward when not allowed { outer_vel = 0; inner_vel = 0; } } if (radius < 0) { //turn left: left side inner, right side outer. Front wheels negative rotate, rear wheels positive. states[Devices.FrontLeftWheel] = inner_vel; states[Devices.FrontLeftSteering] = -inner_angle - FLOffset; //states[Devices.FrontRightSteering] = -outer_angle + FROffset; states[Devices.MidLeftWheel] = inner_vel; //left mercury motors states[Devices.MidRightWheel] = outer_vel; //right mercury motors states[Devices.RearLeftWheel] = inner_vel; states[Devices.RearLeftSteering] = -inner_angle - RLOffset; states[Devices.RearRightWheel] = outer_vel; states[Devices.RearRightSteering] = -outer_angle - RROffset; } else { //turn right: left side outer, right side inner. Front wheels positive rotate, rear wheels negative. states[Devices.FrontLeftWheel] = outer_vel; states[Devices.FrontLeftSteering] = outer_angle - FLOffset; //states[Devices.FrontRightSteering] = inner_angle + FROffset; states[Devices.MidLeftWheel] = outer_vel; //left mercury motors states[Devices.MidRightWheel] = inner_vel; //right mercury motors states[Devices.RearLeftWheel] = outer_vel; states[Devices.RearLeftSteering] = outer_angle + RLOffset; states[Devices.RearRightWheel] = inner_vel; states[Devices.RearRightSteering] = inner_angle + RROffset; } return states; } } }*/
Markdown
UTF-8
2,048
3.15625
3
[]
no_license
# Frontend Mentor - Testimonials grid section solution This is a solution to the [Testimonials grid section challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/testimonials-grid-section-Nnw6J7Un7). Frontend Mentor challenges help you improve your coding skills by building realistic projects. ## Table of contents - [Overview](#overview) - [The challenge](#the-challenge) - [Screenshot](#screenshot) - [Links](#links) - [My process](#my-process) - [Built with](#built-with) - [What I learned](#what-i-learned) - [Continued development](#continued-development) - [Useful resources](#useful-resources) - [Author](#author) - [Acknowledgments](#acknowledgments) ## Overview ### The challenge Users should be able to: - View the optimal layout for the site depending on their device's screen size ### Screenshot ![](images/screenshot.png) ### Links - Solution URL: [Add solution URL here](https://your-solution-url.com) - Live Site URL: https://m-kgobe.github.io/testimonials-grid-section-main/ ## My process ### Built with - Semantic HTML5 markup - CSS custom properties - Flexbox - CSS Grid - Mobile-first workflow ### What I learned *adding google fonts to HTML and CSS *using box-shadow To see how you can add code snippets, see below: ```css .name{ box-shadow: 2px 2px 20px rgba(0,0,0,0.2); } body{ justify-content: center; align-items: center; margin: auto; } ``` ### Continued development 1. I would like to focus more on aligning grids to a specific position on the wepage, I seem to take longer to figure out that, perhaps even try out new grid displays. 2. Distinguish where to use a grid vs flexbox. 3. Making a background image in grid. ### Useful resources ## Author - Website - [Add your name here](https://www.your-site.com) - Frontend Mentor - [@M-Kgobe](https://www.frontendmentor.io/profile/M-Kgobe) - Twitter - [@M_kgobe](https://www.twitter.com/M_kgoe) ## Acknowledgments Always gotta give thanks to the stackoverflow, freecodecamp, github communities.
Python
UTF-8
183
3.703125
4
[]
no_license
def rangefunction(startvalue,endvalue,stepvalue): for i in range(startvalue,endvalue,stepvalue): result = i ** 2 print(result, end = " ") rangefunction(2,9,2)
Java
UTF-8
235
1.898438
2
[]
no_license
import org.junit.jupiter.api.Test; /** * Created by trez_ on 9/28/2017. */ public class InitTestRobertBebber { @Test public void test() { System.out.println("This is a test for seeing if the basics works."); } }
Python
UTF-8
225
2.75
3
[]
no_license
from Utilities import utilities def prime(): try: n = int(input("Enter the nth value")) utilities.Prime(n) except ValueError: print("Enter Valid input") if __name__ == "__main__": prime()
C++
UTF-8
508
2.8125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ unordered_set<string> strset; strset.insert("code"); strset.insert("in"); strset.insert("c++"); strset.insert("is"); strset.insert("fast"); string key = "slow"; if(strset.find(key)==strset.end()) printf("%s is not in the set.\n",key.c_str()); else printf("Found!\n"); unordered_set<string>::iterator itr; for(itr = strset.begin(); itr!=strset.end(); itr++) printf("%s\n",(*itr).c_str()); return 0; }
Go
UTF-8
2,831
2.625
3
[]
no_license
package iris import ( "time" "github.com/kataras/iris/v12" "github.com/sirupsen/logrus" "github.com/tyr-tech-team/hawk/trace" "go.uber.org/zap" ) type detail struct { TraceID string `json:"traceid"` Method string `json:"method"` Path string `json:"path"` Raw string `json:"raw"` ClientIP string `json:"clientip"` Size int64 `json:"size"` Start time.Time `json:"start"` End time.Time `json:"end"` Latency string `json:"latency"` HTTPCode int `json:"httpcode"` ErrorMessage interface{} `json:"error"` } // LoggerWithLogrus - func LoggerWithLogrus(logger *logrus.Entry) iris.Handler { return func(ctx iris.Context) { l := detail{} t := time.Now() l.Start = t ctx.Next() tid := trace.GetTraceID(ctx.Request().Context()) l.TraceID = tid // after request l.Method = ctx.Method() l.Path = ctx.Path() l.ClientIP = ctx.RemoteAddr() l.End = time.Now() l.Latency = time.Since(t).String() l.HTTPCode = ctx.GetStatusCode() l.Raw = ctx.Request().URL.RawFragment l.Size = ctx.GetContentLength() l.ErrorMessage = ctx.Values().Get("error") log := logger.WithFields(logrus.Fields{ "traceid": l.TraceID, "start": l.Start.Format(time.RFC3339), "end": l.End.Format(time.RFC3339), "latency": l.End.Sub(l.Start).Microseconds(), "clientip": l.ClientIP, "httpcode": l.HTTPCode, "error": l.ErrorMessage, "method": l.Method, "path": l.Path, "size": l.Size, "raw": l.Raw, }) if l.ErrorMessage != nil { log.Errorln("failed request") } else { log.Infoln("success request") } } } // LoggerWithZap - func LoggerWithZap(logger *zap.Logger) iris.Handler { return func(ctx iris.Context) { l := detail{} t := time.Now() l.Start = t ctx.Next() tid := trace.GetTraceID(ctx.Request().Context()) l.TraceID = tid // after request l.Method = ctx.Method() l.Path = ctx.Path() l.ClientIP = ctx.RemoteAddr() l.End = time.Now() l.Latency = time.Since(t).String() l.HTTPCode = ctx.GetStatusCode() l.Raw = ctx.Request().URL.RawFragment l.Size = ctx.GetContentLength() l.ErrorMessage = ctx.Values().Get("error") log := logger.With( zap.String("traceID", l.TraceID), zap.String("start", l.Start.Format(time.RFC3339)), zap.String("end", l.End.Format(time.RFC3339)), zap.Int64("latency", l.End.Sub(l.Start).Microseconds()), zap.String("clientip", l.ClientIP), zap.Int("httpcode", l.HTTPCode), zap.Any("error", l.ErrorMessage), zap.String("method", l.Method), zap.String("path", l.Path), zap.Int64("size", l.Size), zap.String("raw", l.Raw), ) if l.ErrorMessage != nil { log.Error("failed request") } else { log.Info("success request") } } }
C++
UTF-8
2,660
2.703125
3
[]
no_license
#include<iostream> #include<cstdio> #include<vector> #include<cstring> #include<algorithm> #include<sstream> #include<map> using namespace std; class team { public: string name; string nameM; int goaldiff; int matches; int wins; int tie; int loses; int goalscored; int goalsagainst; int points; public: team() {} team(string name) { this -> name = name; goaldiff = matches = points = wins=tie=loses = goalscored=goalsagainst = 0; nameM = name; transform(nameM.begin(), nameM.end(), nameM.begin(), ::toupper); } void mod(int a,int b) { goalscored+=a; goalsagainst += b; goaldiff+=(a-b); matches++; if(a==b) tie++,points++; else if(a>b) wins++,points+=3; else loses++; } }; bool comp(const team &a, const team &b) { if(a.points!=b.points) return a.points>b.points; if(a.wins!=b.wins) return a.wins>b.wins; if(a.goaldiff!=b.goaldiff) return a.goaldiff>b.goaldiff; if(a.goalscored!=b.goalscored) return a.goalscored>b.goalscored; if(a.matches!=b.matches) return a.matches<b.matches; return a.nameM < b.nameM; } int main() { int n,t,m; scanf("%d\n",&n); team x[31]; while(n--) { map<string,int>mp; char namet[101]; gets(namet); scanf("%d\n",&t); for(int i=0; i<t; i++) { string s; getline(cin,s); x[i] = team(s); mp[s] =i; } scanf("%d",&m); getchar(); string name1; string name2; while(m--) { stringstream ss; int a,b; string in; getline(cin,in); int fa = in.find('#'); name1=string(in.begin(),in.begin()+fa); in.erase(in.begin(),in.begin()+fa+1); fa = in.find('#'); sscanf(string(in.begin(),in.begin()+fa).c_str(),"%d@%d#",&a,&b); in.erase(in.begin(),in.begin()+fa+1); name2 = in; int f1 = mp[name1]; x[f1].mod(a,b); f1 = mp[name2]; x[f1].mod(b,a); } sort(x,x+t,comp); printf("%s\n",namet); for(int i=0; i<t; i++) printf("%d) %s %dp, %dg (%d-%d-%d), %dgd (%d-%d)\n",i+1,x[i].name.c_str(),x[i].points,x[i].matches,x[i].wins,x[i].tie,x[i].loses,x[i].goaldiff,x[i].goalscored,x[i].goalsagainst); if(n)printf("\n"); } return 0; }
C#
UTF-8
1,080
3.0625
3
[ "MIT" ]
permissive
namespace Tests { using System; using System.Linq; using Core; using Shouldly; public class BirthdayOrderTests { private readonly Person[] _people = new[] { new Person { Name = "a", Birthday = new Birthday(4, 5) }, new Person { Name = "b", Birthday = new Birthday(4, 15) }, new Person { Name = "c", Birthday = new Birthday(4, 25) }, new Person { Name = "d", Birthday = new Birthday(5, 5) }, new Person { Name = "e", Birthday = new Birthday(5, 15) }, new Person { Name = "f", Birthday = new Birthday(5, 25) }, new Person { Name = "g", Birthday = new Birthday(6, 5) }, }; public void should_order_from_a_given_date() { var testDateTime = new DateTime(2000, 5, 1); var ordered = BirthdayOrder.FromDate(testDateTime, _people); ordered.First().Name.ShouldBe("d"); ordered.Last().Name.ShouldBe("c"); } } }
C++
UTF-8
927
2.6875
3
[]
no_license
class Solution{ public: vector<int> majorityElement(vector<int>& nums) { vector<int> res; int n=nums.size(); int ele1=-1,ele2=-1,c1=0,c2=0; for(int i=0;i<n;i++) { if(ele1==nums[i]) c1++; else if(ele2==nums[i]) c2++; else if(c1==0) { ele1=nums[i]; c1=1; } else if(c2==0) { ele2=nums[i]; c2=1; } else { c1--; c2--; } } c1=0,c2=0; for(int i=0;i<n;i++) { if(ele1==nums[i]) c1++; else if(ele2==nums[i]) c2++; } if(c1>n/3) res.push_back(ele1); if(c2>n/3) res.push_back(ele2); return res; }};
Markdown
UTF-8
1,888
2.953125
3
[]
no_license
# Homework2 - Math Library Second homework for Game Architecture. Due: Monday 2/4/19, 11:59pm In this homework you will implement parts of vector and matrix math library. See src/engine/math/ga_vec3f.h and src/engine/math/ga_mat4f.cpp. To determine if your implementation is functionally correct, the engine runs some simple unit tests. See src/engine/math/ga_vec3f.tests.cpp and src/engine/math/ga_mat4f.tests.cpp. For this homework you must correctly implement the stubbed out methods in ga_vec3f and ga_mat4f (search for "TODO: Homework 2") and all unit tests must pass. This repo is meant to be built stand-alone, with just the math code. If you wish to incorporate the rest of the engine, you'll need to update CMakeLists.txt Run build\setup_win64.bat, then in the newly-created folder, open gamearch2.sln in Visual Studio. Build the project, and set "ga" to be your startup project, as before. For 10% Extra Credit, implement in 2D one sprite with translational and rotational movement, and a player-controlled sprite with translational and rotational movement, such as up arrow=forward, left/right arrow=+/- rotation, both using your vector and math library. You do not need to draw the sprites rotated, but use your vec3f and mat4f classes to represent their positions, orientations, and movements. (Recall that movement in 2 dimensions is a special case of movement in 3 dimensions) To submit this assignment: 1. clone your working repository from Submitty: git clone https://submitty.cs.rpi.edu/git/s19/cogs4550/hw2/{username} 2. this will clone a bare empty directory from the submitty server to your local machine. 3. add the sample code from this repository into your working repo 4. commit and push to upload your work back to the submitty git server. You only need to add the source files you have changed (.cpp and .h), you do not need to add build files.
C
UTF-8
590
4.1875
4
[]
no_license
/* Name-Saurav Roll-1601CS41 The aim of this program is to recursively find the min and max digits of a number. */ #include<stdio.h> #include<stdlib.h> #include<string.h> long long calcAns(long long a){ if(a/10==0){ if(a%2==0){ return 0; }else{ return 1; } } if((a%10)%2==0){ return calcAns(a/10); }else{ return 1 + calcAns(a/10); } } int main(){ //taking the input long long a; printf("Enter the number : "); scanf("%lld",&a); //calculating and printing the answer long long ans = calcAns(a); printf("The number of odd digits is %lld",ans); return 0; }
Java
UTF-8
1,289
2.34375
2
[]
no_license
package de.mdelab.sdm.interpreter.core.notifications; import java.util.Map; import de.mdelab.sdm.interpreter.core.variables.Variable; import de.mdelab.sdm.interpreter.core.variables.VariablesScope; /** * Execution of an activity has finished. * * @author Stephan Hildebrandt * * @param <Activity> * @param <Classifier> */ public class ActivityExecutionFinishedNotification<Activity, Classifier> extends InterpreterNotification<Classifier> { private final Activity activity; private final Map<String, Variable<Classifier>> returnValues; public ActivityExecutionFinishedNotification(final VariablesScope<Activity, ?, ?, ?, ?, ?, Classifier, ?, ?> variablesScope, final Notifier<Activity, ?, ?, ?, ?, ?, Classifier, ?, ?> notifier, final Activity activity, final Map<String, Variable<Classifier>> returnValues) { super(NotificationTypeEnum.ACTIVITY_EXECUTION_FINISHED, variablesScope, notifier); assert activity != null; assert returnValues != null; this.activity = activity; this.returnValues = returnValues; } public Activity getActivity() { return this.activity; } @Override public Object getMainStoryDiagramElement() { return this.getActivity(); } public Map<String, Variable<Classifier>> getReturnValues() { return this.returnValues; } }
Java
UTF-8
1,695
2.6875
3
[]
no_license
package ru.eugene.java.learn.generator.builder; public class Computer { private String motherboard; private int ram; private int rom; private String chipSet; private String oc; private String videoAdapter; public Computer(String motherboard) { this.motherboard = motherboard; this.ram = 4; this.rom = 500; this.chipSet = "intel core i3"; this.oc = "linux"; this.videoAdapter = "Radeon"; } public String getMotherboard() { return motherboard; } public void setMotherboard(String motherboard) { this.motherboard = motherboard; } public int getRam() { return ram; } public void setRam(int ram) { this.ram = ram; } public int getRom() { return rom; } public void setRom(int rom) { this.rom = rom; } public String getChipSet() { return chipSet; } public void setChipSet(String chipSet) { this.chipSet = chipSet; } public String getOc() { return oc; } public void setOc(String oc) { this.oc = oc; } public String getVideoAdapter() { return videoAdapter; } public void setVideoAdapter(String videoAdapter) { this.videoAdapter = videoAdapter; } @Override public String toString() { return "Computer{" + "motherboard='" + motherboard + '\'' + ", ram=" + ram + ", rom=" + rom + ", chipSet='" + chipSet + '\'' + ", oc='" + oc + '\'' + ", videoAdapter='" + videoAdapter + '\'' + '}'; } }
Java
UTF-8
2,357
2.453125
2
[]
no_license
package com.tisj.tareax.adapters; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.tisj.tareax.R; import com.tisj.tareax.modelo.Teorico; import java.util.ArrayList; /** * Created by maske on 03/11/2016. */ public class TeoricoAdapter extends ArrayAdapter<Teorico> { private Activity activity; private ArrayList<Teorico> teoricos; private static LayoutInflater inflater = null; public TeoricoAdapter(Activity activity, int textViewResourceId, ArrayList<Teorico> _teoricos) { super(activity, textViewResourceId, _teoricos); try { this.activity = activity; this.teoricos = _teoricos; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } catch (Exception e) { } } public int getCount() { return teoricos.size(); } public Teorico getItem(Teorico position) { return position; } public long getItemId(int position) { return position; } public static class ViewHolder { public TextView teoricoId; public TextView teoricoNumero; public TextView teoricoPdf; } public View getView(int position, View convertView, ViewGroup parent) { View vi = convertView; final ViewHolder holder; try { if (convertView == null) { vi = inflater.inflate(R.layout.list_teorico, null); holder = new ViewHolder(); holder.teoricoId = (TextView) vi.findViewById(R.id.teoricoId); holder.teoricoNumero = (TextView) vi.findViewById(R.id.teoricoNumero); holder.teoricoPdf = (TextView) vi.findViewById(R.id.teoricoPdf); vi.setTag(holder); } else { holder = (ViewHolder) vi.getTag(); } holder.teoricoId.setText(teoricos.get(position).getId()); holder.teoricoNumero.setText("Numero: " + teoricos.get(position).getNumero()); holder.teoricoPdf.setText(teoricos.get(position).getPdf()); } catch (Exception e) { } return vi; } }
C++
UTF-8
913
2.890625
3
[]
no_license
#pragma once #include<iostream> #include<vector> #include<string> #include<algorithm> #include<unordered_map> #include<unordered_set> #include<queue> using namespace std; vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> result; if (!root) { return result; } queue<TreeNode*>q; stack<vector<int>> s; vector<int> rootv = { root->val }; s.push(rootv); q.push(root); q.push(nullptr); vector<int>tmp; while (!q.empty()) { TreeNode* node = q.front(); q.pop(); if (node == nullptr) { if (tmp.size() > 0) { s.push(tmp); } if (!q.empty()) { q.push(nullptr); tmp.clear(); } } else { if (node->left) { tmp.push_back(node->left->val); q.push(node->left); } if (node->right) { tmp.push_back(node->right->val); q.push(node->right); } } } while (!s.empty()) { result.push_back(s.top()); s.pop(); } return result; }
Shell
UTF-8
296
2.96875
3
[]
permissive
# SPDX-License-Identifier: BSD-3-Clause # skip if tcti-cmd not installed pkg-config --exists tss2-tcti-cmd if [ $? -ne 0 ]; then exit 077 fi source helpers.sh start_up random="$(tpm2 getrandom -T"cmd:tpm2 send" --hex 32)" count="$(echo -n "$random" | wc -c)" test "$count" -eq 64 exit 0
C#
UTF-8
3,722
2.578125
3
[]
no_license
using tabuleiro; namespace xadrez { class Dama : Peca { public Dama(Tabuleiro tabuleiro, Cor cor) : base(tabuleiro, cor) { } public override string ToString() { return "D"; } public override bool[,] movimentosPossiveis() { bool[,] mat = new bool[tabuleiro.linhas, tabuleiro.colunas]; Posicao aux = new Posicao(0, 0); for (int i = 1; i < tabuleiro.linhas; i++) { aux.linha = posicao.linha + i; aux.coluna = posicao.coluna + i; if (tabuleiro.posicaoValida(aux)) { if (podeMover(aux)) { mat[aux.linha, aux.coluna] = true; } if (tabuleiro.peca(aux) != null) break; } } for (int i = 1; i < tabuleiro.linhas; i++) { aux.linha = posicao.linha + i; aux.coluna = posicao.coluna - i; if (tabuleiro.posicaoValida(aux)) { if (podeMover(aux)) { mat[aux.linha, aux.coluna] = true; } if (tabuleiro.peca(aux) != null) break; } } for (int i = 1; i < tabuleiro.linhas; i++) { aux.linha = posicao.linha - i; aux.coluna = posicao.coluna + i; if (tabuleiro.posicaoValida(aux)) { if (podeMover(aux)) { mat[aux.linha, aux.coluna] = true; } if (tabuleiro.peca(aux) != null) break; } } for (int i = 1; i < tabuleiro.linhas; i++) { aux.linha = posicao.linha - i; aux.coluna = posicao.coluna - i; if (tabuleiro.posicaoValida(aux)) { if (podeMover(aux)) { mat[aux.linha, aux.coluna] = true; } if (tabuleiro.peca(aux) != null) break; } } //verifica o movimento para o norte aux.definirPosicao(posicao.linha - 1, posicao.coluna); while (tabuleiro.posicaoValida(aux) && podeMover(aux)) { mat[aux.linha, aux.coluna] = true; if (tabuleiro.peca(aux) != null) break; aux.linha--; } //verifica o movimento para o leste aux.definirPosicao(posicao.linha, posicao.coluna + 1); while (tabuleiro.posicaoValida(aux) && podeMover(aux)) { mat[aux.linha, aux.coluna] = true; if (tabuleiro.peca(aux) != null) break; aux.coluna++; } //verifica o movimento para o sul aux.definirPosicao(posicao.linha + 1, posicao.coluna); while (tabuleiro.posicaoValida(aux) && podeMover(aux)) { mat[aux.linha, aux.coluna] = true; if (tabuleiro.peca(aux) != null) break; aux.linha++; } //verifica o movimento para o oeste aux.definirPosicao(posicao.linha, posicao.coluna - 1); while (tabuleiro.posicaoValida(aux) && podeMover(aux)) { mat[aux.linha, aux.coluna] = true; if (tabuleiro.peca(aux) != null) break; aux.coluna--; } return mat; } } }
Java
UTF-8
1,391
2.03125
2
[]
no_license
package cn.cntv.app.ipanda.db.entity; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "livechina_chinnel". */ public class LiveChinaChannelEntity { private String title; private String url; private String type; private String order; // KEEP FIELDS - put your custom fields here // KEEP FIELDS END public LiveChinaChannelEntity() { } public LiveChinaChannelEntity(String title) { this.title = title; } public LiveChinaChannelEntity(String title, String url, String type, String order) { this.title = title; this.url = url; this.type = type; this.order = order; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } // KEEP METHODS - put your custom methods here // KEEP METHODS END }
C++
UTF-8
649
2.5625
3
[ "BSD-3-Clause" ]
permissive
#include "MultipleKernels.h" #include "hlslib/xilinx/Stream.h" void FirstKernel(uint64_t const *memory, hlslib::Stream<uint64_t> &stream, int n) { #pragma HLS INTERFACE m_axi port=memory offset=slave bundle=gmem0 #pragma HLS INTERFACE axis port=stream for (int i = 0; i < n; ++i) { #pragma HLS PIPELINE II=1 stream.Push(memory[i] + 1); } } void SecondKernel(hlslib::Stream<uint64_t> &stream, uint64_t *memory, int n) { #pragma HLS INTERFACE axis port=stream #pragma HLS INTERFACE m_axi port=memory offset=slave bundle=gmem1 for (int i = 0; i < n; ++i) { #pragma HLS PIPELINE II=1 memory[i] = 2 * stream.Pop(); } }
C
ISO-8859-1
528
3.25
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main (){ /*E nescessaro uma string para ler a string dentro do arquivo porem se ela no for do mesmo tamanho que a do arquivo ela nao ira exibir tudo*/ char str[20]; FILE *f; f = fopen("arquivo006.txt","r"); if (f == NULL){ printf("Ocorreu um problema com o arquivo, favor verificar.\n"); exit(1); } char *result = fgets(str,20 ,f); if(result == NULL){ printf("Ocorreu um erro na leitura\n"); } else{ printf("%s",str); } printf("\n"); fclose(f); return 0; }
C++
UTF-8
1,268
2.78125
3
[]
no_license
#pragma once #include "LinkNode.h" #include "Item.h" class linkList { private: linkNode* head; //Points to the head node in the list linkNode* tail; //Points to the tail node in the lsit linkNode* current; //points to the current node in the list linkNode* middle; int itemCount; public: //Constructor linkList(); //Parameterized Constructor linkList(int inItemCount); //Copy Constructor linkList(const linkList& linkListToCopy); //Destructor ~linkList(); //Reporters bool isEmpty() const; bool inList() const; bool operator<(const linkList& otherList) const; bool operator>(const linkList& otherList) const; item getCurrentData() const; //Mutators bool prefixNode(const item& newData); bool insert(const item& newData); bool advance(); void addNode(groceryInfo tempItem); void goToHead(); void goToTail(); bool deleteCurrentNode(); bool setCurrentData(const item& newData); void invLoad(ifstream& inFile); void printGroceryData(ofstream& outFile); void updateInventories(ifstream& inFile, string searchObj); void invAdd(ifstream& inFile, int& k, int& currentMax); void invDelete(ifstream& inFile); void bubbleSort(ifstream& inFile); bool binarySearch(string searchObj); };
Python
UTF-8
14,041
2.828125
3
[]
no_license
import torch import torch.nn as nn import torch.nn.functional as f from torchsummary import summary device = 'cuda' if torch.cuda.is_available() else 'cpu' class Generator(nn.Module): """ Class representing the Generator network to be used. """ VALID_OUT_FRAMES = (8, 16) def __init__(self, in_channels, out_frames, gen_name='Video Generator'): """ Initializes the Generator network. :param in_channels: (int) The number of channels in the input tensor. :param out_frames: (int) The number of frames desired in the generated output video. Legal values: 8, 16 :param gen_name: (str, optional) The name of the network (default 'Video Generator'). Raises: ValueError: if 'out_frames' is not a legal value. """ if out_frames not in self.VALID_OUT_FRAMES: raise ValueError('Invalid number of frames in desired output: %d' % out_frames) super(Generator, self).__init__() self.gen_name = gen_name self.out_frames = out_frames # definition of all layer channels layer_out_channels = {'conv_1a': 256, 'conv_1b': 256, 'conv_2a': 256, 'conv_2b': 256, 'rdn_block': sum(in_channels), 'inc_block': 256, 'conv_3a': 128, 'conv_3b': 128, 'conv_4a': 128, 'conv_4b': 3 } # key: layer name, value: layer_out_channels layer_in_channels = {'conv_1a': sum(in_channels), 'conv_1b': layer_out_channels['conv_1a'], 'conv_2a': layer_out_channels['conv_1b'] + in_channels[0] + in_channels[1], # + 256 'conv_2b': layer_out_channels['conv_2a'], 'rdn_block': sum(in_channels), 'inc_block': layer_out_channels['rdn_block'], 'conv_3a': layer_out_channels['conv_2b'] + in_channels[0] + in_channels[1], # + 128 'conv_3b': layer_out_channels['conv_3a'], 'conv_4a': layer_out_channels['conv_3b'], 'conv_4b': layer_out_channels['conv_4a'] } # key: layer name, value: layer_in_channels # definition of all network layers # block 1 self.avg_pool_1 = nn.AvgPool3d(kernel_size=(4, 4, 4), stride=(4, 4, 4)) # layer = 'conv_1a' # self.conv3d_1a = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], # kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) # self.relu_1a = nn.ReLU(inplace=True) # layer = 'conv_1b' # self.conv3d_1b = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], # kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) # self.relu_1b = nn.ReLU(inplace=True) layer = 'res_block' self.res_block = ResidualBlock(in_features=layer_in_channels[layer]) # block 2 self.avg_pool_2 = nn.AvgPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2)) # layer = 'conv_2a' # self.conv3d_2a = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], # kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) # self.relu_2a = nn.ReLU(inplace=True) # layer = 'conv_2b' # self.conv3d_2b = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], # kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) # self.relu_2b = nn.ReLU(inplace=True) layer = 'inc_block' self.inc_block = InceptionModule(in_channels=layer_in_channels[layer], out_channels=[32, 64, 64, 32, 32, 32]) # block 3 self.avg_pool_3 = nn.AvgPool3d(kernel_size=(2, 1, 1), stride=(2, 1, 1)) layer = 'conv_3a' self.conv3d_3a = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) self.relu_3a = nn.ReLU(inplace=True) layer = 'conv_3b' self.conv3d_3b = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) self.relu_3b = nn.ReLU(inplace=True) # block 4 layer = 'conv_4a' self.conv3d_4a = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1)) self.relu_4a = nn.ReLU(inplace=True) layer = 'conv_4b' self.conv3d_4b = nn.Conv3d(in_channels=layer_in_channels[layer], out_channels=layer_out_channels[layer], kernel_size=(1, 1, 1), stride=(1, 1, 1), padding=(0, 0, 0)) self.sigmoid = nn.Sigmoid() # print('%s Model Successfully Built \n' % self.gen_name) def forward(self, app, kp): """ Function to compute a single forward pass through the network, according to the architecture. :param app: (tensor) The input appearance encoding for the desired view of the generated video. Must be a tensor of shape: (bsz, in_channels[0], 4, 14, 14) for this application. :param rep: (tensor) The input motion representation for the generated video. Must be a tensor of shape: (bsz, in_channels[1], 4, 14, 14) for this application. :return: A tensor representing the video generated by the network. Shape of output is: (bsz, 3, out_frames, 112, 112) for this application. """ # block 1 block = 1 app_block_input = app[-block] kp_block_input = self.avg_pool_1(kp) x = torch.cat([app_block_input, kp_block_input], dim=1) # dim=channels # x = self.conv3d_1a(x) # x = self.relu_1a(x) # x = self.conv3d_1b(x) # x = self.relu_1b(x) x = self.res_block(x) x = f.interpolate(x, size=(8, 28, 28), mode='trilinear') # block 2 block = 2 app_block_input = app[-block] kp_block_input = self.avg_pool_2(kp) x = torch.cat([app_block_input, kp_block_input, x], dim=1) # x = self.conv3d_2a(x) # x = self.relu_2a(x) # x = self.conv3d_2b(x) # x = self.relu_2b(x) x = self.inc_block(x) x = f.interpolate(x, size=(8, 56, 56), mode='trilinear') # block 3 block = 3 app_block_input = app[-block] kp_block_input = self.avg_pool_3(kp) x = torch.cat([app_block_input, kp_block_input, x], dim=1) x = self.conv3d_3a(x) x = self.relu_3a(x) x = self.conv3d_3b(x) x = self.relu_3b(x) x = f.interpolate(x, size=(self.out_frames, 56, 56), mode='trilinear') # block 4 x = self.conv3d_4a(x) x = self.relu_4a(x) x = self.conv3d_4b(x) x = self.sigmoid(x) return x class ResidualBlock(nn.Module): def __init__(self, in_features): super(ResidualBlock, self).__init__() self.conv_block = nn.Sequential( nn.Conv2d(in_features, in_features, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(in_features, 0.8), nn.PReLU(), nn.Conv2d(in_features, in_features, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(in_features, 0.8), ) def forward(self, x): return x + self.conv_block(x) class InceptionModule(nn.Module): """ Class representing a single Inception Module that is part of the I3D Network design. """ def __init__(self, in_channels, out_channels, name): super(InceptionModule, self).__init__() self.b0 = Unit3D(in_channels=in_channels, output_channels=out_channels[0], kernel_shape=[1, 1, 1], padding=0, name=name + '/Branch_0/Conv3d_0a_1x1') self.b1a = Unit3D(in_channels=in_channels, output_channels=out_channels[1], kernel_shape=[1, 1, 1], padding=0, name=name + '/Branch_1/Conv3d_0a_1x1') self.b1b = Unit3D(in_channels=out_channels[1], output_channels=out_channels[2], kernel_shape=[3, 3, 3], name=name + '/Branch_1/Conv3d_0b_3x3') self.b2a = Unit3D(in_channels=in_channels, output_channels=out_channels[3], kernel_shape=[1, 1, 1], padding=0, name=name + '/Branch_2/Conv3d_0a_1x1') self.b2b = Unit3D(in_channels=out_channels[3], output_channels=out_channels[4], kernel_shape=[3, 3, 3], name=name + '/Branch_2/Conv3d_0b_3x3') self.b3a = MaxPool3dSamePadding(kernel_size=[3, 3, 3], stride=(1, 1, 1), padding=0) self.b3b = Unit3D(in_channels=in_channels, output_channels=out_channels[5], kernel_shape=[1, 1, 1], padding=0, name=name + '/Branch_3/Conv3d_0b_1x1') self.name = name def forward(self, x): b0 = self.b0(x) b1 = self.b1b(self.b1a(x)) b2 = self.b2b(self.b2a(x)) b3 = self.b3b(self.b3a(x)) return torch.cat([b0, b1, b2, b3], dim=1) class MaxPool3dSamePadding(nn.MaxPool3d): """ Class respresenting a 3D Max Pooling layer that computes padding necessary for legal computation with kernel. """ def compute_pad(self, dim, s): if s % self.stride[dim] == 0: return max(self.kernel_size[dim] - self.stride[dim], 0) else: return max(self.kernel_size[dim] - (s % self.stride[dim]), 0) def forward(self, x): # compute 'same' padding (batch, channel, t, h, w) = x.size() # print t,h,w out_t = np.ceil(float(t) / float(self.stride[0])) out_h = np.ceil(float(h) / float(self.stride[1])) out_w = np.ceil(float(w) / float(self.stride[2])) # print out_t, out_h, out_w pad_t = self.compute_pad(0, t) pad_h = self.compute_pad(1, h) pad_w = self.compute_pad(2, w) # print pad_t, pad_h, pad_w pad_t_f = pad_t // 2 pad_t_b = pad_t - pad_t_f pad_h_f = pad_h // 2 pad_h_b = pad_h - pad_h_f pad_w_f = pad_w // 2 pad_w_b = pad_w - pad_w_f pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b) # print x.size() # print pad x = F.pad(x, pad) return super(MaxPool3dSamePadding, self).forward(x) class Unit3D(nn.Module): """ Class Representing a 3D Convolutional Unit that computes padding necessary for legal convolution with kernel. """ def __init__(self, in_channels, output_channels, kernel_shape=(1, 1, 1), stride=(1, 1, 1), padding=0, activation_fn=F.relu, use_batch_norm=True, use_bias=False, name='unit_3d'): """Initializes Unit3D module.""" super(Unit3D, self).__init__() self._output_channels = output_channels self._kernel_shape = kernel_shape self._stride = stride self._use_batch_norm = use_batch_norm self._activation_fn = activation_fn self._use_bias = use_bias self.name = name self.padding = padding self.conv3d = nn.Conv3d(in_channels=in_channels, out_channels=self._output_channels, kernel_size=self._kernel_shape, stride=self._stride, padding=0, # we always want padding to be 0 here. # We will dynamically pad based on input size in forward function bias=self._use_bias) if self._use_batch_norm: self.bn = nn.BatchNorm3d(self._output_channels, eps=0.001, momentum=0.01) def compute_pad(self, dim, s): if s % self._stride[dim] == 0: return max(self._kernel_shape[dim] - self._stride[dim], 0) else: return max(self._kernel_shape[dim] - (s % self._stride[dim]), 0) def forward(self, x): # compute 'same' padding (batch, channel, t, h, w) = x.size() # print t,h,w out_t = np.ceil(float(t) / float(self._stride[0])) out_h = np.ceil(float(h) / float(self._stride[1])) out_w = np.ceil(float(w) / float(self._stride[2])) # print out_t, out_h, out_w pad_t = self.compute_pad(0, t) pad_h = self.compute_pad(1, h) pad_w = self.compute_pad(2, w) # print pad_t, pad_h, pad_w pad_t_f = pad_t // 2 pad_t_b = pad_t - pad_t_f pad_h_f = pad_h // 2 pad_h_b = pad_h - pad_h_f pad_w_f = pad_w // 2 pad_w_b = pad_w - pad_w_f pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b) # print x.size() # print pad x = F.pad(x, pad) # print x.size() x = self.conv3d(x) if self._use_batch_norm: x = self.bn(x) if self._activation_fn is not None: x = self._activation_fn(x) return x if __name__ == "__main__": print_summary = True gen = Generator(layer_in_channels=[1, 1], out_frames=16) if print_summary: summary(gen, input_size=[[(1, 56, 56), (1, 28, 28), (1, 14, 14)], (1, 4, 14, 14)])
Java
UTF-8
9,061
1.742188
2
[]
no_license
package view; import java.io.ByteArrayInputStream; import java.io.OutputStream; import javax.faces.context.FacesContext; import oracle.adf.model.BindingContext; import oracle.adf.model.binding.DCIteratorBinding; import oracle.adf.view.rich.component.rich.data.RichTable; import oracle.adf.view.rich.context.AdfFacesContext; import oracle.adf.view.rich.event.QueryOperationEvent; import oracle.binding.BindingContainer; import oracle.binding.OperationBinding; import org.apache.commons.io.IOUtils; import view.utils.ADFUtils; public class AuditReportsMBean { public AuditReportsMBean() { super(); } private auditReportsBBean getAuditReportsBBean() { auditReportsBBean auditRptsBBean = (auditReportsBBean) ADFUtils.evaluateEL("#{backingBeanScope.auditReportsBBean}"); return auditRptsBBean; } public void auditReportPDFDownload(FacesContext facesContext, OutputStream outputStream) { String methodName = (String)ADFUtils.evaluateEL("#{backingBeanScope.methodActionName}"); String reportName = (String)ADFUtils.evaluateEL("#{backingBeanScope.reportName}"); System.err.println("Method Name: "+methodName); System.err.println("Report Name: "+reportName); try { BindingContext bc = BindingContext.getCurrent(); BindingContainer bindings = bc.getCurrentBindingsEntry(); OperationBinding operationBinding = bindings.getOperationBinding(methodName); if (null != operationBinding) { String xml = (String) operationBinding.execute(); if (null != xml && xml.length() > 0) { IOUtils.copy(new ByteArrayInputStream(FileOperations.genPdfRep(xml.getBytes(), FileOperations.getRTFAsInputStream(reportName))), outputStream); // flush the outout stream outputStream.flush(); }else ADFUtils.showInfoMessage("No PDF available."); }else ADFUtils.showInfoMessage("No PDF available."); } catch (Exception e) { e.printStackTrace(); ADFUtils.showErrorMessage("Error while downloading PDF."); } } public void carriersQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccCfgCarriersAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding carrierIter = ADFUtils.findIterator("XpeDccCfgCarriersAdtView1Iterator"); carrierIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getCarriersTblBind()); } } public void countiesQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccCfgCountiesAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccCfgCountiesAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getCountiesTblBind()); } } public void destinationQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccCfgDestinationsAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccCfgDestinationsAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getDestinationTblBind()); } } public void originQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccCfgOriginsAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccCfgOriginsAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getOriginsTblBind()); } } public void vehiclesQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccCfgVehiclesAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccCfgVehiclesAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getVehiclesTblBind()); } } public void customerQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccCfgPcsshtnamesAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccCfgPcsshtnamesAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getCustomerTblBind()); } } public void contractsQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccContractsAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccContractsAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getContractsTblBind()); } } public void contractVerQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccContractVersionAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccContractVersionAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getContractVerTblBind()); } } public void contractLineQueryOperationListener(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccContractLineAdtViewCriteriaQuery.processQueryOperation}", Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding viewIter = ADFUtils.findIterator("XpeDccContractLineAdtView1Iterator"); viewIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getContractLineTblBind()); } } public void cntrctPrcngQueryOperationLstnr(QueryOperationEvent queryOperationEvent) { ADFUtils.invokeEL("#{bindings.XpeDccCntrctPrcngTermAdtViewCriteriaQuery.processQueryOperation}",Object.class, QueryOperationEvent.class, queryOperationEvent); if (queryOperationEvent.getOperation().name().toUpperCase().equals("RESET")) { DCIteratorBinding carrierIter = ADFUtils.findIterator("XpeDccCntrctPrcngTermAdtView1Iterator"); carrierIter.getViewObject().executeEmptyRowSet(); AdfFacesContext.getCurrentInstance().addPartialTarget(this.getAuditReportsBBean().getCntrctPrcngTblBind()); } } }
C++
UTF-8
756
2.78125
3
[]
no_license
#include "catch.hpp" #include "../FileIterator/FileIterator.hpp" const std::string fileName("/Users/mac/Desktop/Iterators/Iterators/Tests/task.in"); TEST_CASE("FileIterator check", "[FileIterator]") { FileIterator* it = new FileIterator(fileName); SECTION("Constructor test") { REQUIRE(it->get() == ' '); } SECTION("next()") { it->next(); REQUIRE(it->get() == 'a'); it->next(); REQUIRE(it->get() == 'b'); it->next(); REQUIRE(it->get() == 'c'); it->next(); REQUIRE(it->get() == 'd'); it->next(); REQUIRE(it->get() == '1'); it->next(); REQUIRE(it->get() == '2'); it->next(); REQUIRE(it->get() == '3'); } }
Java
UTF-8
8,338
1.710938
2
[]
no_license
package com.ss.android.ttve.monitor; import android.text.TextUtils; import com.meituan.robust.PatchProxy; import com.ss.android.medialib.log.d; import com.ss.android.vesdk.y; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; public final class e { /* renamed from: a reason: collision with root package name */ public static int f31254a = 0; /* renamed from: b reason: collision with root package name */ public static int f31255b = 1; /* renamed from: c reason: collision with root package name */ public static WeakReference<IMonitor> f31256c = null; /* renamed from: d reason: collision with root package name */ private static String f31257d = ""; public static void a() { TEMonitorInvoker.nativeReset(); } public static boolean a(String str, String str2, long j) { HashMap hashMap = new HashMap(); hashMap.put(str2, Long.valueOf(j)); return a(str, str2, (Map) hashMap); } public static boolean a(String str, String str2, float f2) { HashMap hashMap = new HashMap(); hashMap.put(str2, Float.valueOf(f2)); return a(str, str2, (Map) hashMap); } public static boolean a(String str, String str2, Map map) { return a(f31256c, str, str2, map); } private static boolean a(WeakReference<IMonitor> weakReference, String str, String str2, Map map) { JSONObject jSONObject = new JSONObject(); try { if (!TextUtils.isEmpty(str2)) { jSONObject.put("service", str2); } if (!str2.equals("iesve_veeditor_record_finish")) { if (!str2.equals("iesve_veeditor_composition_finish")) { a(map, jSONObject); a(weakReference, str, jSONObject); return true; } } a(str2, map, jSONObject); a(weakReference, str, jSONObject); return true; } catch (JSONException unused) { y.b("TEMonitor", "No monitor callback, skip"); return false; } } private static void a(Map map, JSONObject jSONObject) throws JSONException { int i; Map map2 = map; JSONObject jSONObject2 = jSONObject; for (String str : map.keySet()) { if (str.startsWith("iesve_")) { if (PatchProxy.isSupport(new Object[]{str}, null, d.f29692a, true, 17468, new Class[]{String.class}, Integer.TYPE)) { i = ((Integer) PatchProxy.accessDispatch(new Object[]{str}, null, d.f29692a, true, 17468, new Class[]{String.class}, Integer.TYPE)).intValue(); } else if (d.f29696e.contains(str)) { i = d.f29694c; } else if (d.f29697f.contains(str)) { i = d.f29695d; } else { i = d.f29693b; } } else { i = g.a(str); } if (i == g.f31265b) { try { jSONObject2.put(str, Integer.parseInt((String) map2.get(str))); } catch (Exception unused) { y.b("TEMonitor", "Parse int error:" + map2.get(str)); } } else if (i == g.f31266c) { try { jSONObject2.put(str, (double) Float.parseFloat((String) map2.get(str))); } catch (Exception unused2) { y.b("TEMonitor", "Parse float error"); } } else { jSONObject2.put(str, map2.get(str)); } } } private static String b() { return d.a("device_id"); } public static void b(int i) { TEMonitorInvoker.nativeMonitorPerfWithType(i); } public static void d(int i) { TEMonitorInvoker.nativeReset(i); } public static void a(int i) { TEMonitorInvoker.nativeMonitorPerf(i); } private static int a(JSONObject jSONObject) { try { if (jSONObject.has("completed")) { return jSONObject.getInt("completed"); } return 0; } catch (JSONException unused) { y.d("TEMonitor", "get complete filed error!"); return 0; } } public static void c(int i) { if (i == 0) { a(0, "te_record_err_code", 0); return; } if (i == 1) { a(1, "te_edit_err_code", 0); a(1, "te_composition_err_code", 0); } } public static void a(String str, double d2) { if (TextUtils.isEmpty(str)) { y.c("TEMonitor", "perfDouble: key is null"); } else { TEMonitorInvoker.nativePerfDouble(str, d2); } } public static void a(String str, long j) { if (TextUtils.isEmpty(str)) { y.c("TEMonitor", "perfLong: key is null"); } else { TEMonitorInvoker.nativePerfLong(str, j); } } public static void a(int i, String str, long j) { if (!TextUtils.isEmpty(str)) { TEMonitorInvoker.nativePerfLong(i, str, j); } } public static void a(int i, String str, double d2) { if (TextUtils.isEmpty(str)) { y.c("TEMonitor", "perfDouble: key is null"); } else { TEMonitorInvoker.nativePerfDouble(i, str, d2); } } public static void a(int i, String str, String str2) { if (TextUtils.isEmpty(str)) { y.c("TEMonitor", "perfString: key is null"); return; } if (str2 == null) { str2 = ""; } TEMonitorInvoker.nativePerfString(i, str, str2); } private static void a(String str, Map map, JSONObject jSONObject) throws JSONException { int i; for (String str2 : map.keySet()) { if (!str.equals("iesve_veeditor_record_finish") && !str.equals("iesve_veeditor_composition_finish")) { i = g.a(str2); } else if (h.f31274e.contains(str2)) { i = h.f31271b; } else if (h.f31275f.contains(str2)) { i = h.f31272c; } else if (h.g.contains(str2)) { i = h.f31273d; } else { i = h.f31270a; } if (i == g.f31265b) { try { jSONObject.put(str2, Integer.parseInt((String) map.get(str2))); } catch (Exception unused) { y.b("TEMonitor", "Parse int error:" + map.get(str2)); } } else if (i == g.f31266c) { try { jSONObject.put(str2, (double) Float.parseFloat((String) map.get(str2))); } catch (Exception unused2) { y.b("TEMonitor", "Parse float error"); } } else { jSONObject.put(str2, map.get(str2)); } } } static void a(WeakReference<IMonitor> weakReference, String str, JSONObject jSONObject) { int i; String str2 = "sdk_video_edit_compose"; if (jSONObject != null) { i = a(jSONObject); try { if (jSONObject.has("service")) { str2 = jSONObject.getString("service"); } if (str2.equals("iesve_veeditor_record_finish") || str2.equals("iesve_veeditor_composition_finish")) { if ("".equals(f31257d)) { f31257d = b() + "_" + System.currentTimeMillis(); } jSONObject.put("te_record_compose_vid", f31257d); } if (str2.equals("iesve_veeditor_composition_finish")) { f31257d = ""; } } catch (JSONException unused) { } } else { i = 0; } d.a(str2, i, jSONObject); if (!(weakReference == null || weakReference.get() == null)) { try { ((IMonitor) weakReference.get()).monitorLog(str, jSONObject); } catch (Exception unused2) { } } } }
Java
UTF-8
6,896
2.203125
2
[]
no_license
package com.contactlab.services.impl; import de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService; import de.hybris.platform.acceleratorservices.model.email.EmailAddressModel; import de.hybris.platform.acceleratorservices.model.email.EmailAttachmentModel; import de.hybris.platform.acceleratorservices.model.email.EmailMessageModel; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataSource; import javax.mail.util.ByteArrayDataSource; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.apache.log4j.Logger; import com.contactlab.enums.EmailMessageType; import com.contactlab.utils.ContactlabMailUtils; /** * @author Techedge Group * */ public class DefaultContactlabEmailService extends DefaultEmailService { protected static final Logger LOG = Logger.getLogger(DefaultContactlabEmailService.class); @Override public boolean send(final EmailMessageModel message) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } if (message.getEmailMessageType() != null) { if (EmailMessageType.DEFAULT.equals(message.getEmailMessageType())) { super.send(message); } else { final boolean sendEnabled = getConfigurationService().getConfiguration() .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true); if (sendEnabled) { try { final HtmlEmail email = (HtmlEmail) ContactlabMailUtils.getPreConfiguredEmail(); // final HtmlEmail email = getPerConfiguredEmail(); email.setCharset("UTF-8"); final List<EmailAddressModel> toAddresses = message.getToAddresses(); if (CollectionUtils.isNotEmpty(toAddresses)) { email.setTo(getAddresses(toAddresses)); } else { throw new IllegalArgumentException("message has no To addresses"); } final List<EmailAddressModel> ccAddresses = message.getCcAddresses(); if (ccAddresses != null && !ccAddresses.isEmpty()) { email.setCc(getAddresses(ccAddresses)); } final List<EmailAddressModel> bccAddresses = message.getBccAddresses(); if (bccAddresses != null && !bccAddresses.isEmpty()) { email.setBcc(getAddresses(bccAddresses)); } final EmailAddressModel fromAddress = message.getFromAddress(); email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName())); // Add the reply to if specified final String replyToAddress = message.getReplyToAddress(); if (replyToAddress != null && !replyToAddress.isEmpty()) { email.setReplyTo(Collections.singletonList(createInternetAddress(replyToAddress, null))); } email.setSubject(message.getSubject()); email.setHtmlMsg(getBody(message)); // AGGIUNTA HEADER final Map<String, String> headersMap = new HashMap<String, String>(); headersMap.put("X-Clab-SmartRelay-DeliveryId", String.valueOf(message.getCampaign().getCampaignId())); headersMap.put("X-Clab-SmartRelay-DeliveryLabel", message.getCampaign().getCampaignName()); email.setHeaders(headersMap); // To support plain text parts use email.setTextMsg() final List<EmailAttachmentModel> attachments = message.getAttachments(); if (attachments != null && !attachments.isEmpty()) { for (final EmailAttachmentModel attachment : attachments) { try { final DataSource dataSource = new ByteArrayDataSource( getMediaService().getDataFromMedia(attachment), attachment.getMime()); email.attach(dataSource, attachment.getRealFileName(), attachment.getAltText()); } catch (final EmailException ex) { LOG.error("Failed to load attachment data into data source [" + attachment + "]", ex); return false; } } } // Important to log all emails sent out LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From [" + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]"); // Send the email and capture the message ID final String messageID = email.send(); message.setSent(true); message.setSentMessageID(messageID); message.setSentDate(new Date()); getModelService().save(message); return true; } catch (final EmailException e) { LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "] cause: " + e.getMessage()); if (LOG.isDebugEnabled()) { LOG.debug(e); } } } else { LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]"); LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'"); return true; } } } return true; } }
C++
UTF-8
1,227
3.015625
3
[]
no_license
#include <vector> #include <iostream> using namespace std; struct sptEntry { int value; bool valid; }; int log2(int val) { int ret = -1; while (val != 0) { val >>= 1; ret++; } return ret; } int twoPow(int val) { return 1 << val; } int main() { // Read stuff int width, height; vector<vector<int> > map = vector<vector<int> >(width, vector<int>(height, 0)); /* ** Build lvl 1 sparse table */ //initialize int heightLog = log2(height); sptEntry prototype = {0, false}; vector<vector<vector<sptEntry> > > verticalTables = vector<vector<vector<sptEntry> > > (width, vector<vector<sptEntry> >(height, vector<sptEntry>(heightLog, prototype))); for (int column = 0; column < width; column++) { for (int row = 0; row < height; row++) { for (int sptIndex = 0; sptIndex < heightLog; sptIndex++) { int indexPow = twoPow(sptIndex); if (indexPow + row < height) { for (int i = row; i < indexPow; i++) { if (!verticalTables[column][row][sptIndex].valid || map[column][row] > verticalTables[column][row][sptIndex].value) { verticalTables[column][row][sptIndex].value = map[column][row]; verticalTables[column][row][sptIndex].valid = true; } } } } } } }
Markdown
UTF-8
391
2.78125
3
[]
no_license
--- title: "ABC #139 D" problem: https://atcoder.jp/contests/abc139/tasks/abc139_d --- $$ M_i $$ の取りうる最大値は $$ P_i-1 $$ である. $$ \{ P_1, P_2, \ldots, P_{N-1}, P_N \} = \{ 2, 3, \dots, N, 1 \} $$ とすればすべての $$ M_i $$ は取りうる最大値になるので, 合計も最大値となる. よって, $$ \sum_{k=1}^{N-1} k = N(N-1)/2 $$ が答えである.
C++
UTF-8
1,518
3.40625
3
[]
no_license
#ifndef Polygon_HPP #define Polygon_HPP #define pi 3.1415926535897 std::vector<std::string> nameByType = {"", "Point", "Line", "Triangle", "Square", "Pentagon", "Hexagon", "Heptagon", "Octagon", "Nonagon"}; template <class T> struct Polygon { int n; Point<T> center; T side; T radius; std::vector<Point<T>> points; T area; Polygon() = default; Polygon(int _n, Point<T> _center, T _side) : n(_n), center(_center), side(_side) { radius = side / (2 * sin((180 / n) * pi / 180)); points.resize(n); for (int i = 0; i < n; ++i) { points[i].x = radius * cos(2 * pi * i / n) + center.x; points[i].y = radius * sin(2 * pi * i / n) + center.y; } area = 0.5 * radius * radius * n * sin((360 / n) * pi / 180); } }; template <class U> std::istream &operator>>(std::istream &in, Polygon<U> &pg) { std::cout << "Enter <number_of_vertices>, <center.x, center.y>, <side>\n"; in >> pg.n >> pg.center >> pg.side; pg = Polygon<U>(pg.n, pg.center, pg.side); return in; } template <class U> std::ostream &operator<<(std::ostream &out, const Polygon<U> &pg) { for (int i = 0; i < 28; ++i) out << "-"; out << '\n'; out << "Type: " << nameByType[pg.n] << '\n'; out << "Side: " << pg.side << '\n'; out << "Area: " << pg.area << '\n'; out << "Points: "; for (int i = 0; i < pg.n; ++i) { out << pg.points[i] << " "; } out << '\n'; return out; } #endif
C#
UTF-8
2,516
3.015625
3
[]
no_license
using csharp_dotnet_core_web_api_hotel_listing.Data; using csharp_dotnet_core_web_api_hotel_listing.IRepository; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace csharp_dotnet_core_web_api_hotel_listing.Repository { public class GenericRepository<T> : IGenericRepository<T> where T : class { private readonly DatabaseContext _context; private DbSet<T> _db; public GenericRepository(DatabaseContext context) { _context = context; _db = _context.Set<T>(); } public async Task Delete(int id) { var entity = await _db.FindAsync(id); _db.Remove(entity); } public void DeleteRange(IEnumerable<T> entities) { _db.RemoveRange(entities); } public async Task Insert(T entity) { await _db.AddAsync(entity); } public async Task InsertRange(IEnumerable<T> entities) { await _db.AddRangeAsync(entities); } public void Update(T entity) { _db.Attach(entity); _context.Entry(entity).State = EntityState.Modified; } public async Task<T> Get(Expression<Func<T, bool>> expression, List<string> includes) { IQueryable<T> records = _db; if (includes != null) { foreach (var include in includes) { records = records.Include(include); } } return await records.AsNoTracking().FirstOrDefaultAsync(expression); } public async Task<IList<T>> GetAll(Expression<Func<T, bool>> expression = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, List<string> includes = null) { IQueryable<T> records = _db; if (expression != null) { records = records.Where(expression); } if (includes != null) { foreach (var include in includes) { records = records.Include(include); } } if (orderBy != null) { records = orderBy(records); } return await records.AsNoTracking().ToListAsync(); } } }
Java
UTF-8
1,169
2.640625
3
[]
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 CITstrangerthings.model; /** * * @author Raye Ang */ public class FleeResults { private String message; private int reason; private Character CharacterRemoved = null; public FleeResults() { } public FleeResults(String message, int reason, Character CharacterRemoved) { this.message = message; this.reason = reason; this.CharacterRemoved = CharacterRemoved; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getReason() { return reason; } public void setReason(int reason) { this.reason = reason; } public Character getCharacterRemoved() { return CharacterRemoved; } public void setCharacterRemoved(Character CharacterRemoved) { this.CharacterRemoved = CharacterRemoved; } }
Python
UTF-8
537
2.8125
3
[]
no_license
from bs4 import BeautifulSoup import requests from datetime import datetime url = "http://www.daum.net/" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') rank = 1 results = soup.findAll('a','link_favorsch') search_rank_file = open("rankresult.txt","a") print(datetime.today().strftime("%Y년 %m월 %d일의 실시간 검색어 순위입니다.\n")) for result in results: search_rank_file.write(str(rank)+"위:"+result.get_text()+"\n") print(rank,"위 : ",result.get_text(),"\n") rank += 1
Python
UTF-8
5,026
2.890625
3
[ "MIT" ]
permissive
""" Home Work 5 Ankit Khandelwal Exercise 12 15863 """ from math import sqrt import matplotlib.pyplot as plt import numpy as np G = 1 m1 = 150 m2 = 200 m3 = 250 delta = 10 ** -3 def f(solution): r1x = solution[0] r2x = solution[1] r3x = solution[2] rv1x = solution[3] rv2x = solution[4] rv3x = solution[5] r1y = solution[6] r2y = solution[7] r3y = solution[8] rv1y = solution[9] rv2y = solution[10] rv3y = solution[11] fr1x = rv1x fr2x = rv2x fr3x = rv3x fr1y = rv1y fr2y = rv2y fr3y = rv3y r1 = sqrt(r1x ** 2 + r1y ** 2) r2 = sqrt(r2x ** 2 + r2y ** 2) r3 = sqrt(r3x ** 2 + r3y ** 2) frv1x = G * m2 * (r2x - r1x) / abs(r2 - r1) ** 3 + G * m3 * (r3x - r1x) / abs(r3 - r1) ** 3 frv2x = G * m1 * (r1x - r2x) / abs(r1 - r2) ** 3 + G * m3 * (r3x - r2x) / abs(r3 - r2) ** 3 frv3x = G * m2 * (r2x - r3x) / abs(r2 - r3) ** 3 + G * m1 * (r1x - r3x) / abs(r1 - r3) ** 3 frv1y = G * m2 * (r2y - r1y) / abs(r2 - r1) ** 3 + G * m3 * (r3y - r1y) / abs(r3 - r1) ** 3 frv2y = G * m1 * (r1y - r2y) / abs(r1 - r2) ** 3 + G * m3 * (r3y - r2y) / abs(r3 - r2) ** 3 frv3y = G * m2 * (r2y - r3y) / abs(r2 - r3) ** 3 + G * m1 * (r1y - r3y) / abs(r1 - r3) ** 3 return np.array([fr1x, fr2x, fr3x, frv1x, frv2x, frv3x, fr1y, fr2y, fr3y, frv1y, frv2y, frv3y]) ti = 0 tf = 2 h = .1 hh = [] solution = np.array([3, -1, -1, 0, 0, 0, 1, -2, 1, 0, 0, 0], float) r1xpoints = [] r2xpoints = [] r3xpoints = [] r1ypoints = [] r2ypoints = [] r3ypoints = [] r1xpoints.append(solution[0]) r2xpoints.append(solution[1]) r3xpoints.append(solution[2]) r1ypoints.append(solution[6]) r2ypoints.append(solution[7]) r3ypoints.append(solution[8]) r1xpoints_ = [] r2xpoints_ = [] r3xpoints_ = [] r1ypoints_ = [] r2ypoints_ = [] r3ypoints_ = [] check = solution.copy() r1xpoints_.append(check[0]) r2xpoints_.append(check[1]) r3xpoints_.append(check[2]) r1ypoints_.append(check[6]) r2ypoints_.append(check[7]) r3ypoints_.append(check[8]) final = solution.copy() h_min = 10 ** -13 / 11 while ti < tf: check_h = 0 while check_h == 0: for t in [ti, ti + h]: k1 = h * f(solution) k2 = h * f(solution + 0.5 * k1) k3 = h * f(solution + 0.5 * k2) k4 = h * f(solution + k3) solution += (k1 + 2 * k2 + 2 * k3 + k4) / 6 r1xpoints.append(solution[0]) r2xpoints.append(solution[1]) r3xpoints.append(solution[2]) r1ypoints.append(solution[6]) r2ypoints.append(solution[7]) r3ypoints.append(solution[8]) h = 2 * h for t in [ti]: k1 = h * f(check) k2 = h * f(check + 0.5 * k1) k3 = h * f(check + 0.5 * k2) k4 = h * f(check + k3) check += (k1 + 2 * k2 + 2 * k3 + k4) / 6 r1xpoints_.append(check[0]) r2xpoints_.append(check[1]) r3xpoints_.append(check[2]) r1ypoints_.append(check[6]) r2ypoints_.append(check[7]) r3ypoints_.append(check[8]) h = h / 2 e1 = 1 / 30 * (r1xpoints[-1] - r1xpoints_[-1]) e2 = 1 / 30 * (r2xpoints[-1] - r2xpoints_[-1]) e3 = 1 / 30 * (r3xpoints[-1] - r3xpoints_[-1]) e4 = 1 / 30 * (r1ypoints[-1] - r1ypoints_[-1]) e5 = 1 / 30 * (r2ypoints[-1] - r2ypoints_[-1]) e6 = 1 / 30 * (r3ypoints[-1] - r3ypoints_[-1]) error = sqrt(e1 ** 2 + e2 ** 2 + e3 ** 2 + e4 ** 2 + e5 ** 2 + e6 ** 2) if error == 0: h_new = 1.5 * h else: h_new = h * (h * delta / error) ** (1 / 4) if h_new > 1.5 * h: h_new = 1.5 * h if h_new < h and h_new > h_min: h = h_new solution = final.copy() check = final.copy() r1xpoints.pop(-1) r2xpoints.pop(-1) r3xpoints.pop(-1) r1ypoints.pop(-1) r2ypoints.pop(-1) r3ypoints.pop(-1) r1xpoints.pop(-1) r2xpoints.pop(-1) r3xpoints.pop(-1) r1ypoints.pop(-1) r2ypoints.pop(-1) r3ypoints.pop(-1) elif h_new > h: ti = ti + 2 * h check_h = 1 final = solution.copy() check = solution.copy() h = h_new else: ti = ti + 2 * h check_h = 1 final = solution.copy() check = solution.copy() h = h_min hh.append(h) plt.plot(r1xpoints, r1ypoints, 'b.', markersize=1, label='Star 1') plt.plot(r2xpoints, r2ypoints, 'r.', markersize=1, label='Star 2') plt.plot(r3xpoints, r3ypoints, 'g.', markersize=1, label='Star 3') plt.xlabel('X') plt.ylabel('Y') plt.yscale('symlog') plt.xscale('symlog') plt.xticks((-10 ** 12, -10 ** 8, -10 ** 4, -10, 10, 10 ** 4, 10 ** 8, 10 ** 12)) plt.yticks((-10 ** 12, -10 ** 8, -10 ** 4, -10, 10, 10 ** 4, 10 ** 8, 10 ** 12)) plt.title('Log Trajectory') plt.legend(loc='lower left') plt.show()
Java
UTF-8
1,056
2.453125
2
[]
no_license
package com.grsu.committee.service.impl; import com.grsu.committee.dataaccess.impl.AdministratorDao; import com.grsu.committee.dataaccess.impl.SheetDao; import com.grsu.committee.entities.Administrator; import com.grsu.committee.entities.Enrollee; import com.grsu.committee.entities.Sheet; import com.grsu.committee.service.AdministratorService; import com.grsu.committee.table.AdministratorTable; public class AdministratorServiceImpl extends AbstractServiceImpl<AdministratorTable, Administrator> implements AdministratorService { private SheetDao sheetDao; public AdministratorServiceImpl() { dao = new AdministratorDao(); sheetDao = new SheetDao(); } @Override public void addEnrolleeToSheet(Sheet sheet, Enrollee enrollee) { if (sheet.getFaculty() == null) { sheet.setFaculty(enrollee.getFaculty()); } if (!sheet.getRegisteredEnrollee().contains(enrollee)) { sheet.getRegisteredEnrollee().add(enrollee); } sheetDao.saveOrUpdate(sheet); } }
Java
UTF-8
9,331
2.828125
3
[]
no_license
import cs3500.pyramidsolitaire.controller.PyramidSolitaireTextualController; import cs3500.pyramidsolitaire.model.hw02.PyramidSolitaireModel; import java.util.Collections; import java.util.List; import org.junit.Test; import cs3500.pyramidsolitaire.model.hw02.BasicPyramidSolitaire; import cs3500.pyramidsolitaire.model.hw02.Card; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.Reader; import java.io.StringReader; /** * Class for tests for controller. */ public class ControllerTest { private PyramidSolitaireModel<Card> model = new BasicPyramidSolitaire(); private List<Card> deck = model.getDeck(); @Test(expected = IllegalArgumentException.class) public void testNullModelGame() { StringBuilder s = new StringBuilder(); Reader inp = new StringReader(""); PyramidSolitaireTextualController c = new PyramidSolitaireTextualController(inp, s); c.playGame(null, model.getDeck(), true, 2, 3); } // tests an invalid draw index /** * Tests invalid discard draw. * @throws IOException exception */ private void testInvalidDD() throws IOException { StringBuilder s = new StringBuilder(); Reader inp = new StringReader("dd 4"); PyramidSolitaireTextualController c = new PyramidSolitaireTextualController(inp, s); c.playGame(model, model.getDeck(), true, 2, 3); } // null string input Readable @Test(expected = IllegalArgumentException.class) public void testInvalidController() { StringBuilder s = null; Reader inp = new StringReader("rm1 4 5"); PyramidSolitaireTextualController c = new PyramidSolitaireTextualController(inp, s); c.playGame(model, model.getDeck(), true, 5, 6); } // null Appendable @Test(expected = IllegalArgumentException.class) public void testInvalidController2() { StringBuilder s = new StringBuilder(); Reader inp = null; PyramidSolitaireTextualController c = new PyramidSolitaireTextualController(inp, s); c.playGame(model, model.getDeck(), true, 2, 2); } // invalid command inputted "howdy" /** * Tests invalid command input to controller. * @throws IOException exception */ private void testInvalidCommand() throws IOException { StringBuilder s = new StringBuilder(); Reader inp = new StringReader("howdy"); PyramidSolitaireTextualController c = new PyramidSolitaireTextualController(inp, s); c.playGame(model, deck, false, 6, 5); } @Test public void testPlayGameDD() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("dd 1"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); Collections.reverse(card); controller.playGame(game, card, false, 3, 2); assertEquals(out.toString(), " K♠\n" + " K♥ K♦\n" + "K♣ Q♠ Q♥\n" + "Draw: Q♦, Q♣\n" + "Score: 76\n" + " K♠\n" + " K♥ K♦\n" + "K♣ Q♠ Q♥\n" + "Draw: Q♣\n" + "Score: 152\n"); } @Test public void testPlayGameBadDD() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("dd 7"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); Collections.reverse(card); controller.playGame(game, card, false, 3, 5); assertEquals(out.toString(), " K♠\n" + " K♥ K♦\n" + "K♣ Q♠ Q♥\n" + "Draw: Q♦, Q♣, J♠, J♥, J♦\n" + "Score: 76\n" + "Invalid move\n"); } @Test(expected = IllegalStateException.class) public void testPlayGameRm1Bad() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("rm1 2 2"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); Collections.reverse(card); controller.playGame(game, card, false, 3, 5); } // this should be a valid move but it's not allowing it @Test public void testPlayGameRm1() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("rm1 2 0"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); Collections.reverse(card); controller.playGame(game, card, false, 3, 5); assertEquals(out.toString(), " K♠\n" + " K♥ K♦\n" + "K♣ Q♠ Q♥\n" + "Draw: Q♦, Q♣, J♠, J♥, J♦\n" + "Score: 76\n" + "Invalid move\n"); } // this is throwing an error i don't know why @Test public void testPlayGameRm2() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("rm2 6 2 6 3"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); controller.playGame(game, card, false, 7, 5); assertEquals(out.toString(), " A♣\n" + " A♦ A♥\n" + " A♠ 2♣ 2♦\n" + " 2♥ 2♠ 3♣ 3♦\n" + "3♥ 3♠ 4♣ 4♦ 4♥\n" + "4♠ 5♣ 5♦ 5♥ 5♠ 6♣\n" + "6♦ 6♥ 6♠ 7♣ 7♦ 7♥ 7♠\n" + "Draw: 8♣, 8♦, 8♥, 8♠, 9♣\n" + "Score: 112\n" + "Invalid move.\n"); } @Test public void testPlayGameRmwd() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("rmwd 3 5 5"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); controller.playGame(game, card, false, 6, 5); assertEquals(out.toString(), " A♣\n" + " A♦ A♥\n" + " A♠ 2♣ 2♦\n" + " 2♥ 2♠ 3♣ 3♦\n" + "3♥ 3♠ 4♣ 4♦ 4♥\n" + "4♠ 5♣ 5♦ 5♥ 5♠ 6♣\n" + "Draw: 6♦, 6♥, 6♠, 7♣, 7♦\n" + "Score: 66\n" + "Invalid move.\n"); } @Test public void testPlayGameRmwdBad() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("rmwd 9 5 5"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); controller.playGame(game, card, false, 6, 5); assertEquals(out.toString(), " A♣\n" + " A♦ A♥\n" + " A♠ 2♣ 2♦\n" + " 2♥ 2♠ 3♣ 3♦\n" + "3♥ 3♠ 4♣ 4♦ 4♥\n" + "4♠ 5♣ 5♦ 5♥ 5♠ 6♣\n" + "Draw: 6♦, 6♥, 6♠, 7♣, 7♦\n" + "Score: 66\n" + "Invalid move.\n"); } @Test public void testGameQuitCaps() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("Q"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); controller.playGame(game, card, false, 6, 5); assertEquals(out.toString(), " A♣\n" + " A♦ A♥\n" + " A♠ 2♣ 2♦\n" + " 2♥ 2♠ 3♣ 3♦\n" + "3♥ 3♠ 4♣ 4♦ 4♥\n" + "4♠ 5♣ 5♦ 5♥ 5♠ 6♣\n" + "Draw: 6♦, 6♥, 6♠, 7♣, 7♦\n" + "Score: 66\n" + "Game quit!\n" + " A♣\n" + " A♦ A♥\n" + " A♠ 2♣ 2♦\n" + " 2♥ 2♠ 3♣ 3♦\n" + "3♥ 3♠ 4♣ 4♦ 4♥\n" + "4♠ 5♣ 5♦ 5♥ 5♠ 6♣\n" + "Draw: 6♦, 6♥, 6♠, 7♣, 7♦\n" + "Score: 132\n"); } @Test public void testGameQuitLower() { StringBuilder out = new StringBuilder(); Reader in = new StringReader("q"); PyramidSolitaireTextualController controller = new PyramidSolitaireTextualController(in, out); PyramidSolitaireModel<Card> game = new BasicPyramidSolitaire(); List<Card> card = game.getDeck(); controller.playGame(game, card, false, 6, 5); assertEquals(out.toString(), " A♣\n" + " A♦ A♥\n" + " A♠ 2♣ 2♦\n" + " 2♥ 2♠ 3♣ 3♦\n" + "3♥ 3♠ 4♣ 4♦ 4♥\n" + "4♠ 5♣ 5♦ 5♥ 5♠ 6♣\n" + "Draw: 6♦, 6♥, 6♠, 7♣, 7♦\n" + "Score: 66\n" + "Game quit!\n" + " A♣\n" + " A♦ A♥\n" + " A♠ 2♣ 2♦\n" + " 2♥ 2♠ 3♣ 3♦\n" + "3♥ 3♠ 4♣ 4♦ 4♥\n" + "4♠ 5♣ 5♦ 5♥ 5♠ 6♣\n" + "Draw: 6♦, 6♥, 6♠, 7♣, 7♦\n" + "Score: 132\n"); } }
Python
UTF-8
4,580
3.109375
3
[]
no_license
import textmagic.client client = textmagic.client.TextMagicClient('****', '****') import time import random #result = client.send("Hello, World!", "17162923620") #message_id = result['message_id'].keys()[0] import Adafruit_BBIO.ADC as ADC ADC.setup() pin1="P9_33" #2132633578 # content of last message def finding_last_message(): #all messages received_messages = client.receive(0) #constructing a tree dictionary messages_info = received_messages['messages'] num_messages = len(messages_info) # the following line will make the list dictionary of the last message last=messages_info[num_messages-1] # now i have to read the content of the last message so i have to call content(text) # from the dictionary last_text=last[('text')] last_text=last_text.lower() return last_text # sender of last message def finding_last_number(): #all messages received_messages = client.receive(0) #constructing a tree dictionary messages_info = received_messages['messages'] num_messages = len(messages_info) # the following line will make the list dictionary of the last message last=messages_info[num_messages-1] #now i have to read the content of the last message so i have to call #the numer (from) from the dictionary last_number=last[('from')] last_number_string=str(last_number) return last_number_string # ID of last message def finding_last_id(): #all messages received_messages = client.receive(0) #constructing a tree dictionary messages_info = received_messages['messages'] num_messages = len(messages_info) # the following line will make the list dictionary of the last message last=messages_info[num_messages-1] # now i have to read the content of the last message so i have to # call the numer (from) from the dictionary last_id=last[('message_id')] return last_id # sending a text to a number def sending_txt(txt, number): #sending result = client.send(txt, number) #uniqque id for a txt message message_id = result['message_id'].keys()[0] return message_id # reading the devleivery status of a sent message # this doesn't work for now def status(message_id): response = client.message_status(message_id) message_info = response[message_id] delivery_status = message_info['status'] time_string = time.strftime("%a, %d %b %Y %H:%M:%S", message_info['created_time']) return delivery_status return time_string # i need to develope it but it's one of the last steps dec 03 def insist(): return "come on, it is easy! move me please!" # i need to develope it but it's one of the last steps dec 03 def thanking(): return "Thanks. This was an experiment research to examine people's biases or prejudices about daily activities of different ethnicities." def thanking2(): return "Hope You're happy with what you've done. You'll see the end result somewhere! Have a good life" # generating the random select along the 4 different ethinical names dec 04 def figure_name(): name_list= ["Mohammad","George","Jing","Gabriela"] figure_name= random.choice(name_list) return figure_name #generating a random day time def random_daytime(): time_list=["9 am", "3 pm", "7 pm", "11 pm"] daytime= random.choice(time_list) return daytime # this is the request function def request_txt(): txt_req="Hello, this is "+ figure_name()+". It's "+random_daytime()+"."+"\n"+"Where do you think I should be now? Please move me over there!" return txt_req # condition to start the game def hello_check(): last=finding_last_message() st=last.replace(',','') str=st.replace('.','') string=str.split() list=[] for t in string: list.append(t) if list[0]=="hello": bol=True else: bol=False return bol #understanding the name which is followed by hello def last_name(): last=finding_last_message() st=last.replace(',','') str=st.replace('.','') string=str.split() list=[] for t in string: list.append(t) list.append(" ") del list[0] last_name=''.join(list) return last_name # this function will get the location of figure from the sensors # i need to develope it but i still don't have the circut def get_location(): # only testing one location loc1=ADC.read(pin1) loc1=loc1*1.8 if loc1>1: location="house" elif loc1<1: location="office" return location
TypeScript
UTF-8
2,056
2.59375
3
[]
no_license
import { Component, OnInit, Testability } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; import Cocktail, { ingredientMeasure } from '../../models/Cocktail'; import { CocktailService } from '../services/cocktail.service'; @Component({ selector: 'app-cocktail-detail', templateUrl: './cocktail-detail.component.html', styleUrls: ['./cocktail-detail.component.scss'], }) export class CocktailDetailComponent implements OnInit { cocktail = new Cocktail(); private sub?: Subscription; amountCocktails = 1; previousAmount = this.amountCocktails; sumMeasures = 0; constructor( private route: ActivatedRoute, private cocktailService: CocktailService ) {} ngOnInit(): void { this.route.params.subscribe((params) => { this.sub?.unsubscribe(); this.sub = this.cocktailService .getCocktailDetails(params.id) .subscribe((cocktail) => { this.cocktail = cocktail; }); }); } /** * Changes the amount of ingredient based on the input value */ amount(): void { // Reject Values that make no sense if (this.amountCocktails <= 0 || this.amountCocktails > 100) { alert( `This is a serious app and does not support the making of ${this.amountCocktails} cocktails. \nPlease enter a more reasonable number. Thank you.` ); return; } // TODO: Use the array operator map on the array "this.cocktail.ingredients" to change the amount of ingredients, based on "this.amountCocktails". // Optional: Consider how to change the ingredient.measure value const ingredients = this.cocktail.ingredients.map((ingredient: ingredientMeasure) => { return { prefix: ingredient.prefix, ingredient: ingredient.ingredient, measure: (ingredient.measure / this.previousAmount) * this.amountCocktails, unit: ingredient.unit, }; }); this.cocktail.ingredients = ingredients; this.previousAmount = this.amountCocktails; } }
C#
UTF-8
1,655
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using WPF.ViewModels; namespace WPF.Commands { public class SearchFoodCommand : ICommand { public event EventHandler CanExecuteChanged; public EnterMealsVM EnterMealsVM { get; set; } public SearchFoodCommand(EnterMealsVM EnterMealsVM) { this.EnterMealsVM = EnterMealsVM; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { switch (int.Parse(parameter.ToString())) { case 1: EnterMealsVM.SearchFood(1); break; case 2: EnterMealsVM.SearchFood(2); break; case 3: EnterMealsVM.SearchFood(3); break; case 4: EnterMealsVM.SearchFood(4); break; case 5: EnterMealsVM.SearchFood(5); break; case 6: EnterMealsVM.SearchFood(6); break; case 7: EnterMealsVM.SearchFood(7); break; case 8: EnterMealsVM.SearchFood(8); break; case 9: EnterMealsVM.SearchFood(9); break; } } } }
PHP
UTF-8
396
2.640625
3
[]
no_license
<?php class Logger { public static function send($message) { $config = Config::me()->get('logs'); if (!$config['enabled']) { return; } } protected static function extendMessage($jsonMessage) { $jsonMessage['microdatetime'] = Time::getMicroDateTime(); $jsonMessage['pid'] = getmypid(); return $jsonMessage; } }
Java
UTF-8
1,243
3.0625
3
[]
permissive
package com.xiong.nowcoder; public class NC55 { public class Solution { /** * @param strs string字符串一维数组 * @return string字符串 */ public String longestCommonPrefix(String[] strs) { // write code here int i = 0; if (strs == null) { return null; } if (strs.length == 0) { return ""; } if (strs.length == 1) { return strs[0]; } while (i < strs[0].length()) { char t = strs[0].charAt(i); boolean eq = true; for (int j = 1; j < strs.length; j++) { String str = strs[j]; if (str.length() <= i) { eq = false; break; } if (strs[j].charAt(i) != t) { eq = false; break; } } if (eq) { i++; } else { break; } } return strs[0].substring(0, i); } } }
PHP
UTF-8
2,964
2.84375
3
[ "MIT" ]
permissive
<?php namespace Code_Alchemy\Models\Factories; use Code_Alchemy\Core\Alchemist; use Code_Alchemy\Models\Dynamic_Model; use Code_Alchemy\Models\Model; /** * Class Model_Cloner * @package Code_Alchemy\Models\Factories * * Clones a Model */ class Model_Cloner extends Alchemist{ /** * @var \Code_Alchemy\Models\Model */ private $clone; /** * Model_Cloner constructor. * @param Dynamic_Model $original * @param array $overrides */ public function __construct( Dynamic_Model $original, array $overrides = array() ){ $original_model_name1 = $original->model_name(); \FB::info($original->id(),get_called_class()); $model = new Model($original_model_name1); // Get cloning rules $cloning_rules = $original->cloning_rules(); if ( $cloning_rules ){ // Collate all values $values = $overrides; // If custom renamed fields if ( isset( $cloning_rules['custom_renamed_fields'])) foreach( $cloning_rules['custom_renamed_fields'] as $field => $custom_method ) $values[$field] = $original->custom_method($custom_method,array(),false); // Copy over fields $seed_values = array_merge($original->members_as_array($cloning_rules['copy_fields']),$overrides); if ( ! $model->create_from($seed_values)->exists ) { \FB::error("Unable to clone Model: ".$model->error()); $this->error = $model->error(); } else { $this->is_cloned = true; // Now check if we should clone referencing if ( isset( $cloning_rules['clone_referencing'])) // Foreach one foreach ( $cloning_rules['clone_referencing'] as $model_name ){ $searchQuery = $original_model_name1 . "_id='" . $original->get($original->key_column()) . "'"; $referencing = (new Model_Factory($model_name)) ->find_all_undeleted($searchQuery); // For each Model that references the Original... foreach ( $referencing as $refmodel ){ // Clone it.. $member_name = $model->key_column(); $newref = $refmodel->_clone(array( // Point it to the new model $original_model_name1."_id" => $model->get($member_name) )); } } } } else { \FB::warn(get_called_class().": No cloning rules for Model ". $original_model_name1); } $this->clone = $model; } /** * @return Model */ public function get_clone(){ return $this->clone; } }
Java
UTF-8
329
2.296875
2
[]
no_license
package com.stu1; import com.stu.Student; public class Student1 { public static void main(String[] args) { // TODO Auto-generated method stub Student s = new Student(); s.setName("Sai"); s.setAddress("7-145/8"); s.toString(); s.addCourseGrade(); s.printGrades(); s.getAverageGrade(); } }
Python
UTF-8
3,034
2.53125
3
[ "MIT" ]
permissive
__author__ = 'Simon' import json import re import time import urllib.request def fetch(url): print("Try to get: " + url) try: return urllib.request.urlopen(url) except: print("Failed to get: " + url) time.sleep(5) return fetch(url) params = {'format': 'json', 'action': 'query', 'list': 'categorymembers', 'cmtitle': 'Category:Scripting_Commands', 'cmtype':'page', 'cmlimit':500, 'cmcontinue':0} f = fetch("https://community.bistudio.com/wikidata/api.php?%s" % urllib.parse.urlencode(params)) content = json.loads(f.read().decode('utf-8')) data = [] while 'continue' in content: data = data + content['query']['categorymembers'] params['cmcontinue'] = content['continue']['cmcontinue'] f = fetch("https://community.bistudio.com/wikidata/api.php?%s" % urllib.parse.urlencode(params)) content = json.loads(f.read().decode('utf-8')) data = data + content['query']['categorymembers'] params = {'format': 'json', 'action': 'parse', 'pageid': '', 'prop': 'text'} blacklist = [ "a = b", "for", "switch", "switch do"] output = [] index = 0 for item in data: index = index + 1 if item['title'] not in blacklist: params['pageid'] = item['pageid'] f = fetch("https://community.bistudio.com/wikidata/api.php?%s" % urllib.parse.urlencode(params)) content = json.loads(str(f.read().decode()))['parse'] text = str(content['text']['*']) rawText = text description = '' description = re.search(r"Description:</dt>[\s]+<dd>(.+?)</dd>",text,re.DOTALL|re.MULTILINE).group(1) text = re.sub(r"(Description:</dt>\s+<dd>.+?</dd>)",'',text) syntaxRegex = re.search(r'Syntax:</dt>\s+<dd>(.+?)</dd>',text,re.DOTALL|re.MULTILINE) while syntaxRegex: command = {} text = text[syntaxRegex.end():] syntax='' syntax = re.sub(r'(<.*?>)','',syntaxRegex.group(1)) returnValue = '' returnValueRegex = re.search(r"Return Value:</dt>\s*(?:<p>)?\s*<dd>(.+?)</dd>",text,re.DOTALL|re.MULTILINE) if returnValueRegex: returnValue = returnValueRegex.group(1) text = re.sub(r"(Return Value:</dt>\s+<dd>.+?</dd>)",'',text,1) parameter = '' parameterRegex = re.search(r'Parameters:</dt>\s*(.+?)</dl>',text,re.DOTALL|re.MULTILINE) if parameterRegex: parameter = parameterRegex.group(1) text = re.sub(r"(Parameters:</dt>\s*(.+?)</dl>)",'',text,1) command['title'] = str(item['title']) command['rawText'] = str(rawText) command['description'] = str(description) command['syntax'] = str(syntax) command['parameter'] = str(parameter) command['returnValue'] = str(returnValue) output.append(command) syntaxRegex = re.search(r"Syntax:</dt>\s+<dd>(.+?)</dd>",text,re.DOTALL|re.MULTILINE) with open('bi-wiki-operator.json', 'w') as f: json.dump(output,f) print("\nExecute 'parseOperators.py' to parse the retrieved information.")
JavaScript
UTF-8
1,004
2.9375
3
[]
no_license
function agregar(){ var pro = document.getElementById("producto").value; var cant = document.getElementById('cantidad').value; var http = new XMLHttpRequest(); http.onreadystatechange = function(){ if(this.readyState == 4 && this.status== 200){ mostrar(); console.log('datos enviados correctamente'); } }; http.open('POST','../controlador/ctrlSalida.php',true); http.setRequestHeader('Content-type','application/x-www-form-urlencoded'); http.send('producto='+pro+'&cantidad='+cant+'&accion=agregar'); } function mostrar(){ var env = new XMLHttpRequest(); env.onreadystatechange = function(){ if(this.readyState == 4 && this.status ==200){ document.getElementById('tabla-reg').innerHTML=this.responseText; } }; env.open('POST','../controlador/ctrlSalida.php',true); env.setRequestHeader('Content-type','application/x-www-form-urlencoded'); env.send('accion=mostrar'); } mostrar();
PHP
UTF-8
923
2.765625
3
[]
no_license
<!doctype html> <html> <head> <meta charset="utf-8"/> <title>traitement</title> </head> <body> <?php echo "merci d'avoir remplis le formulaire ! je vous contacterais dès que possible !<br/>"; echo '<a href="index.html">cliquez ici pour revenir sur le portfolio </a><br/>'; // On récupere les infos du formulaire $name=$_POST['nom']; $Fname=$_POST['firstname']; $mail=$_POST['mail']; $message= $_POST['message']; //connexion bdd $link = mysqli_connect("localhost", "root", "MySQL","portfolio"); // on crée la requête $query="INSERT INTO `contact` (`id`, `nom`, `prenom`, `mail`, `message`) VALUES (NULL,'" .$name ."','" . $Fname ."','" . $mail."','".$message."');"; $result=mysqli_query($link,$query); mysql_close($link); ?> </body> </html>
C++
UTF-8
1,628
3.015625
3
[]
no_license
#include <algorithm> #include <cctype> #include <fstream> #include <iostream> #include <sstream> uint64_t pow(int base, int exp) { uint64_t p = 1; for (int i = 0; i < exp; ++i) { p *= base; } return p; } int main(int argc, char** argv) { if (argc < 3) { std::cout << "filename input output\n"; return EXIT_FAILURE; } std::ifstream input(argv[1]); std::ofstream output(argv[2]); int T = 0; input >> T; for (int t = 1; t <= T; ++t) { int K, C, S; input >> K >> C >> S; uint64_t index = 0; int count = 0; uint64_t max_index = pow(K, C); output << "Case #" << t << ": "; std::ostringstream out; while (true) { uint64_t final_index = index; for (int i = 1; i < C; ++i) { if (index < K-1) { final_index = final_index * K + (index+1); ++index; } else { // index == K-1 final_index = final_index * K + (index); } } ++count; if (count > S) { output << "IMPOSSIBLE\n"; break; } if (index < K-1) { out << final_index+1 << " "; ++index; continue; } else { // index == K-1 out << std::min(final_index+1, max_index) << "\n"; output << out.str(); break; } } } }
C#
UTF-8
1,794
2.546875
3
[]
no_license
using UnityEngine; using UnityEngine.UI; namespace Menu.Selectors { public class CharacterSelector : MonoBehaviour { public CharacterSetuper characterSetuper; private Image _button1; private Image _button2; private Image _button3; private void Start() { var button1T = gameObject.transform.Find("DickClarkButton"); var button2T = gameObject.transform.Find("HuLieButton"); var button3T = gameObject.transform.Find("VitaliTsalButton"); _button1 = button1T.gameObject.GetComponent<Image>(); _button2 = button2T.gameObject.GetComponent<Image>(); _button3 = button3T.gameObject.GetComponent<Image>(); characterSetuper.SetupCharacter("Dick Clark"); } public void DickClarkPressed() { characterSetuper.SetupCharacter("Dick Clark"); SwitchButtonColor(1); } public void HuLeePressed() { characterSetuper.SetupCharacter("Hu Lee"); SwitchButtonColor(2); } public void VitaliTsalPressed() { characterSetuper.SetupCharacter("Vitali Tsal"); SwitchButtonColor(3); } private void SwitchButtonColor(int button) { switch (button) { case 1: _button1.color = new Vector4(0.6f, 0.6f, 0.6f, 1f); _button2.color = new Vector4(1f, 1f, 1f, 1f); _button3.color = new Vector4(1f, 1f, 1f, 1f); break; case 2: _button1.color = new Vector4(1f, 1f, 1f, 1f); _button2.color = new Vector4(0.6f, 0.6f, 0.6f, 1f); _button3.color = new Vector4(1f, 1f, 1f, 1f); break; case 3: _button1.color = new Vector4(1f, 1f, 1f, 1f); _button2.color = new Vector4(1f, 1f, 1f, 1f); _button3.color = new Vector4(0.6f, 0.6f, 0.6f, 1f); break; } } } }
Markdown
UTF-8
448
3.125
3
[]
no_license
# combination_sum_IV ## 题目截图 ![](combination_sum_IV.jpg) ## 思路一 动态规划 class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: # 采用 动态规划,有顺序的背包问题 dp = [0] * (target + 1) dp[0] = 1 for i in range(target + 1): for num in nums: if i >= num: dp[i] += dp[i - num] return dp[-1]
Java
UTF-8
1,448
2.046875
2
[]
no_license
package com.locensate.letnetwork.entity; import com.locensate.letnetwork.main.ui.fragments.machine.GridItem; import java.util.List; /** * ------------------------------------- * <p> * 项目名称: MotorTesting * <p> * 版权:locensate.com 版权所有 2016 * <p> * 公司主页:http://www.locensate.com/ * <p> * 描述: * <p> * 作者: xiaobinghe * <p> * 时间: 2017/1/3 14:43 * <p> * 修改历史: * <p> * 修改时间: * <p> * 修改描述: * <p> * ------------------------------------- */ public class MultiSectionEntity { public List<GridItem> items; public String title; public String id; public boolean isFolder; public boolean isFolder() { return isFolder; } public void setFolder(boolean folder) { isFolder = folder; } public List<GridItem> getItems() { return items; } public void setItems(List<GridItem> items) { this.items = items; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getId() { return id; } public void setId(String id) { this.id = id; } public MultiSectionEntity(String id, List<GridItem> items, String title, boolean isFolder) { this.id = id; this.items = items; this.title = title; this.isFolder = isFolder; } }
Markdown
UTF-8
1,010
2.546875
3
[]
no_license
<p class="type">EXPLORATION</p> # Welco Logo Guideline <p class="meta">Design / Monday, February 2, 2015 7:41:06am</p> This is the guideline brand of the welco logo. Welco is a company engaged in the processing, packaging and selling of chocolate products. This brand guideline was made because my team was trusted to redesign the Welco logo. Brandguideline itself is very important to ensure that the logo used in its application is suitable and does not violate the rules that have been prepared when making the logo. So, with the brand guideline logo can be applied in a variety of implementations without violating the rules that have been made. So ordinary people can easily distinguish the logo from other logos that may be similar. ![Welco Logo Guideline](https://farooq-agent.web.app/assets/images/works/details/2-welco-logo-guideline/welco-logo-guideline.jpg) Tools: - Adobe Illustrator Copyright 2014 - [Trio Digital Agency](https://triodigitalagency.com/) - [Welco](http://welco.co.id/)
Markdown
UTF-8
2,582
3.09375
3
[]
no_license
# Coindesk-API Pods are included, you can simply download the project, open the `*.xcworkspace` file and run it. ### Design pattern I chose the MVVM design pattern as I find it clear, good separation of concers without being too complicated and easy to maintain. ### External libraries #### Alamofire I use Alamofire for the network request in my `Service` class. It is a small part of the code but I like to have it clear and Alamofire is a nice library for this kind of code. #### SwiftyJSON This library is not essential but it helps make the code a bit cleaner when parsing the data received from the Coindesk API. ### Accessibility All texts in the app are dynamic. It allows automatic update of the font size when device's content size category changes. ## The app ### User interface The 1st screen displays the currente rate in € as well as the history. If you click on the current rate or on any cell, you have the rate in USD, GBP and EUR. The red and green color in the table view indicates if the rate went up or went down compared to the previous day (I need to pull one extra day of data that I won't display in order to display the correct color for the last cell). ### Network requests I know from the API documentation that today's BPI is updated every minute and that the history has only one value per day. As I store the data on the device, if the user presses the refresh button it will only make a network request if the current stored data is expired (and if there is an available internet connection). ### Offline mode I chose to download the three currencies (USD, GBP and EUR) together when I'm fetching the EUR Bitcoin Price Index history for two reasons: One is that it prevents making 3 requests for a specific date and currency each time I select a cell. Network requests are power consuming, especially if you need to bring the hardware up everytime to do so. We can see in the Energy report that the overhead is bringing the avera energy impact to High when there is a network request. The second is that it allows the user to utilise the app offline and keeping the code simple. The `Last update` message is displayed in red if it is actually not up-to-date, but the user can still open each day of the history to see the details in 3 currencies. ### Utils & extensions There is quite a few utils and extensions in the project. It helps make the code more readable, maintainable and safer. ### Tests XCode 10 does not run classic XCTest UI tests on simulator with the new build system, which is why I'm using the legacy build system.
Java
UTF-8
1,520
2.46875
2
[]
no_license
package com.appnomic.appsone.config; import com.appnomic.appsone.config.entity.ClusterGridEntity; import com.appnomic.appsone.config.entity.ConfigEntity; import com.google.gson.Gson; public class ClusterGridConfigManager implements ConfigManager { private static final ClusterGridConfigManager agcm = new ClusterGridConfigManager(); private static final Gson gson = new Gson(); private static final String classKey = ClusterGridEntity.class.getName(); private ClusterGridConfigManager() { } public static final ClusterGridConfigManager getInstance() { return agcm; } public ConfigEntity getConfig() { ClusterGridEntity age = null; LevelDBManager instance = null; try { instance = LevelDBManager.getInstance(); System.out.println("retrieving: key = " + classKey); String json = instance.read(classKey); if(json==null) { DefaultTableCreator.createClusterGridDefaultConfig(); json = instance.read(classKey); } age = gson.fromJson(json, ClusterGridEntity.class); } catch (Exception e) { e.printStackTrace(); } return age; } public boolean saveConfig(ConfigEntity configEntity) { LevelDBManager instance = null; try { instance = LevelDBManager.getInstance(); ClusterGridEntity age = (ClusterGridEntity)configEntity; String json = gson.toJson(age); System.out.println("saving: key = " + classKey + " value = " + json); instance.write(classKey, json); } catch(Exception e) { e.printStackTrace(); return false; } return true; } }
Java
UTF-8
1,486
2.625
3
[ "MIT" ]
permissive
package net.avicus.magma.database.table.impl; import java.util.List; import java.util.Optional; import net.avicus.magma.database.model.impl.TeamMember; import net.avicus.quest.database.Database; import net.avicus.quest.model.Table; import net.avicus.quest.query.Filter; public class TeamMemberTable extends Table<TeamMember> { public TeamMemberTable(Database database, String name, Class<TeamMember> model) { super(database, name, model); } /** * Find the accepted team member of a user. */ public Optional<TeamMember> findAcceptedByUser(int userId) { return select().where("user_id", userId).where("accepted", true).execute().stream().findFirst(); } /** * Find all member associations of a user. More than one is possible * due to old validation errors. For example, a player have been invited to * Team A, accepted to Team A, then invited to Team B. * * @param userId The user's id. * @return The team members. */ public List<TeamMember> findByUser(int userId) { return select().where("user_id", userId).execute(); } /** * Find all members of a team. * * @param teamId The team's id. * @param onlyAccepted If true, only accepted team members will be returned. */ public List<TeamMember> findByTeam(int teamId, boolean onlyAccepted) { Filter filter = new Filter("team_id", teamId); if (onlyAccepted) { filter.and("accepted", true); } return select().where(filter).execute(); } }
Java
UTF-8
333
1.546875
2
[]
no_license
package cn.luoxx.shiro.dao.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import javax.annotation.Resource; public class BaseDao { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource protected JdbcTemplate jdbcTemplate; }
C
UTF-8
1,027
2.90625
3
[]
no_license
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <malloc.h> #include "node.h" int main() { long int N; scanf("%ld", N); node Root; input_node(&Root); for (long int i = 1; i < N; i++) { node temp; //Allocate memory temp.children = malloc(); ///////////////////////// Vivek -> Idk how to do this input_node(&temp); findParentAndInsert(&Root, &temp); } int a; int Depth = 0; for (int i = 0; i < N; i++) { if (root[i].parent != (-1)) { a = (Root[(Root[i].parent - 1)].children); (Root[(Root[i].parent - 1)].children)++; Root[(Root[i].parent - 1)].children[a] = &Root[i]; nodePtr ROOT = &Root[i]; while (ROOT->parent != (-1)) { Depth = Depth + 1; int D = ((ROOT->parent) - 1); ROOT = &(Root[D]); } root[i].Depth = Depth; } } return 0; }
Python
UTF-8
2,281
3.203125
3
[]
no_license
# encoding=utf-8 import re, urllib2 class neihanba(): def inter(self, startPage, endPage): url = "http://www.neihanpa.com/article/list_5_" for page in range(startPage, endPage + 1): urlFull = url + str(page) + ".html" html = self.loadPage(urlFull, page) self.dealPage(html, page) def loadPage(self, url, page): print "正在爬取第" + str(page) + "页数据。。。。" header = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36" } request = urllib2.Request(url, headers=header) response = urllib2.urlopen(request) html = response.read() return html def writePage(self, context, page): print "正在将第" + str(page) + "页数据写入文件。。。" with open("../out/neihanba.txt", "a") as file: file.writelines(context + "\n") def dealPage(self, html, page): # 先把li标签里的内容爬出来 partten = re.compile('<li class="piclist\d+">(.*?)</li>', re.S) titleList = partten.findall(html) for li in titleList: # 标题的正则 li_title = re.compile('<a href="/article/\d+.html">(.*?)</a>', re.S) title = li_title.findall(li) for t in title: fin_title = t.replace("<b>", "").replace("</b>", "") fin = "Title:" + fin_title self.writePage(fin, page) # 内容的正则 li_context = re.compile('<div class="f18 mb20">(.*?)</div>', re.S) context = li_context.findall(li) for c in context: fin_context = c.replace("<p>", "").replace("</p>", "").replace("<br>", "") \ .replace("<br />", "").replace("&ldquo", "").replace("&rdquo", "") \ .replace("&hellip", "").replace(' ', '') fin = "Context:" + fin_context.strip() + "\n\n" self.writePage(fin, page) if __name__ == '__main__': startPage = raw_input("请输入爬虫的起始页:") endPage = raw_input("请输入爬虫的终止页:") n = neihanba() n.inter(int(startPage), int(endPage))
Java
UTF-8
3,990
2.421875
2
[]
no_license
package org.controlador; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.modelo.CrudEntrenador; import org.modelo.Entrenador; /** *Nombre de la clase:OperacionesEntrenador * Fecha:17/10/2017 * Version:1.0 * Copyright:ITCA-FEPADE * @author Ale Gomez */ public class OperacionesEntrenador extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Entrenador en= new Entrenador(); CrudEntrenador ce= new CrudEntrenador(); //RequestDispatcher rd= null; String val=null; try { en.setIdEntre(Integer.parseInt(request.getParameter("id"))); en.setNombre(request.getParameter("nombre")); en.setApellido(request.getParameter("apellido")); en.setGenero(request.getParameter("genero")); en.setEdad(Integer.parseInt(request.getParameter("edad"))); en.setTelefono(request.getParameter("telefono")); en.setCorreo(request.getParameter("correo")); en.setIdEqu(Integer.parseInt(request.getParameter("equipo"))); if (request.getParameter("insertar")!=null) { ce.add(en); val="Datos Insertados Correctamente"; }else if (request.getParameter("modificar")!=null) { ce.update(en); val="Datos Modificados Correctamente"; }else if (request.getParameter("eliminar")!=null) { ce.delete(en); val="Datos Eliminados Correctamente"; } request.setAttribute("valor", val); //rd=request.getRequestDispatcher("Admin/Entrenador.jsp"); request.getRequestDispatcher("Entrenador.jsp").forward(request, response); } catch (Exception e) { out.print(val); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
JavaScript
UTF-8
1,880
2.671875
3
[]
no_license
const { expect } = require('chai'); const utils = require('./src/utils'); describe('JSON API 用例', function() { describe('根据键名筛选内容', function() { it('filterKeys', function() { expect( utils.filterKeys( { foo: 1, bar: 2 }, ['foo'] ) ).to.deep.equal({ foo: 1 }); }); }); describe('根据键值筛选内容', function() { it('filterValues', function() { expect( utils.filterValues( { foo: 1, bar: 2, baz: '1' }, // 注意 undefined 则会丢弃该键 (key, val) => (typeof val !== 'string' ? val : undefined) ) ).to.deep.equal({ foo: 1, bar: 2 }); }); }); describe('格式化输出', function() { it('采用空格格式化输出', function() { expect( JSON.stringify( { foo: 1, bar: 2 }, null, 2 ) ).to.deep.equal(`{\n "foo": 1,\n "bar": 2\n}`); }); it('采用其他占位符格式化输出', function() { expect( JSON.stringify( { foo: 1, bar: { baz:1 } }, null, '*' ) ).to.deep.equal(`{\n*"foo": 1,\n*"bar": {\n**"baz": 1\n*}\n}`); }); }); });
Python
UTF-8
599
4.25
4
[]
no_license
""" Created on Tue Feb 9 00:55:48 2021 @author: marin """ """problema 2 Escribir un programa en el cual se ingresen cuatro números, calcular e informar la suma de los dos primeros y el producto del tercero y el cuarto.""" num1=int(input("ingrese el primer numero: ")) num2=int(input("ingrese el segundo numero: ")) num3=int(input("ingrese el del tercer numero: ")) num4=int(input("ingrese el del cuarto numero: ")) suma=num1+num2 print("la suma del primer y segundo numero es ") print(suma) producto=num3*num4 print("el producto del tercer y cuarto numero es") print(producto)
Java
UTF-8
1,060
2.34375
2
[]
no_license
package com.wladek.pension.web; import com.wladek.pension.domain.User; import com.wladek.pension.domain.enumeration.UserRole; import com.wladek.pension.service.UserDetailsImpl; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by wladek on 7/6/15. */ @Controller public class PageDirectorController { @RequestMapping(value = "/url-processor" , method = RequestMethod.GET) public String redirect(){ UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = userDetails.getUser(); if (user.getUserRole().equals(UserRole.ADMIN)){ return "redirect:/admin/home" ; } if (user.getUserRole().equals(UserRole.EMPLOYEE)){ return "redirect:/employee/home" ; } return "redirect:/"; } }
Java
UTF-8
6,682
2.28125
2
[]
no_license
package alexhao.codeheu.Util; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import alexhao.codeheu.Application.iApplication; /** * Created by ALexHao on 15/7/16. * 封装http操作和流操作 */ public class HttpStreamTools { iApplication iapp; String responseCookie = "cookie is null"; String sessionId = "sessionid is null"; public HttpStreamTools() { this.iapp = iApplication.getInstance(); } /** * get请求 * @param geturl * @param type 0 :请求验证图片 1:请求数据 * @return * @throws IOException */ public byte[] httpGet(String geturl,int type) throws IOException { URL url = new URL(geturl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(false); conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch"); conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); conn.setRequestProperty("Cache-Control", "max-age=0"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Host", "jw.hrbeu.edu.cn"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36"); if(type==1){ conn.setRequestProperty("Cookie", iapp.getSessionId()); conn.setRequestProperty("Referer", "http://jw.hrbeu.edu.cn/ACTIONLOGON.APPPROCESS?mode=1&applicant=ACTIONQUERYSTUDENTSCORE"); if (conn.getResponseCode() == 200) { InputStream instream = conn.getInputStream(); return streamToByte(instream,type); } else { byte[] falsestream = new byte[0]; return falsestream; } }else{ responseCookie = iapp.getResponseCookie(); responseCookie = conn.getHeaderField("Set-Cookie"); if(responseCookie==null) { byte[] falsestream = new byte[0]; return falsestream; } iapp.setResponseCookie(responseCookie); sessionId = iapp.getSessionId(); sessionId = responseCookie.substring(0, responseCookie.indexOf(";")); iapp.setSessionId(sessionId); if (conn.getResponseCode() == 200) { InputStream instream = conn.getInputStream(); return streamToByte(instream,type); } else { byte[] falsestream = new byte[0]; return falsestream; } } } /** * post请求 * @param posturl * @param sb * @param type 0:登录 1: 学期请求 * @return * @throws IOException */ public byte[] httpPost(String posturl, StringBuilder sb,int type ) throws IOException { URL url=new URL(posturl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch"); conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); conn.setRequestProperty("Cache-Control","max-age=0"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Length", String.valueOf(sb.toString().getBytes().length)); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Host", "jw.hrbeu.edu.cn"); conn.setRequestProperty("Origin", "http://jw.hrbeu.edu.cn"); conn.setRequestProperty("Referer", "http://jw.hrbeu.edu.cn/ACTIONLOGON.APPPROCESS?mode=1&applicant=ACTIONQUERYSTUDENTSCORE"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36"); conn.setRequestProperty("Cookie", iapp.getSessionId()); conn.getOutputStream().write(sb.toString().getBytes("GBK")); conn.getOutputStream().flush(); conn.getOutputStream().close(); if (conn.getResponseCode() == 200) { InputStream instream = conn.getInputStream(); return streamToByte(instream,type); } else { byte[] falsestream = new byte[0]; return falsestream; } } /** * byte 转 String * * @param b * @return * @throws UnsupportedEncodingException */ public String byteToString(byte[] b) throws UnsupportedEncodingException { String result = new String(b, "GBK"); return result; } /** * stream 转 byte * * @param is * @return * @throws IOException */ public byte[] streamToByte(InputStream is, int type) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[2048]; if (type == 0) //下载验证图片 { int count = 0; while (count == 0) { count = is.available(); } if (count < 1000) return null; while (true) { int length = is.read(b); if (length == -1) { break; } baos.write(b, 0, length); } return baos.toByteArray(); } else if (type == 1) { //其他数据 while (true) { int length = is.read(b); if (length == -1) { break; } baos.write(b, 0, length); } return baos.toByteArray(); } return null; } }
Markdown
UTF-8
2,524
2.859375
3
[]
no_license
# 上海融觉 标签(空格分隔): 面试总结 --- 总的感受:还是多数问的关于项目的问题,看来还是着重在项目上吧。还有就是项目好久没去看了,很多都忘了,我觉得接下来懂得工作还是js基础和项目吧 一、.vue通信 1.基本思想:prop向下传递,事件向上 2.父子组件通信: 1.子调用父:触发$emit 2.父调用子:通过子组件的引用ref 3.兄弟组件:通信:使用一个空的vue实例作为中央控制总线,通过$emit触发a组件,在b组件通过$on监听事件 二、.vuex模块 vuex 允许将 store(仓库)分成若干个模块,每个模块拥有自己的state,mutation,action,getter,在大兴项目中,模块化的思想是非常重要的 三.小程序 四.ES6promise,语法,this,箭头函数 1.let局部声明变量 不存在变量提提升,必须先声明后使用 新增块级作用域,所以外部无法访问if内部变量 存在暂时性死区,只要在声明之前使用,就会报错 2.const声明常量 拥有let的所有特性 新增:一旦声明必须立即赋值,后续不得继续赋值操作 3.箭头函数: 简介性 箭头函数的this是在定义时确定的,解决了this指向不明确的难题 箭头函数的嵌套,可以用来部署管道机制的例子,就是一个函数的输出是后一个函数的输入 4.promise promise是一个代表异步操作的对象 三个状态:Pending(进行中),resolved(成功),rejected(失败) Promise对象是一个构造函数,可以构造 Promise实例 Promise接收一个函数作为参数,而这个函数又接收两个函数: resolved(将成功的信息传递出去),rejected(将失败的信息床底出去)(两者有js引擎 提供,不需要自己部署) then方法用来指定resolved,rejected的回掉函数,也接受两个参数,第一个是状态变为resolved时调用,第二个是变为reject时调用,then返回的是新的Promise,所以可以链式调用 catch是指定发生错误时调用的函数,取代then的第二个参数函数 all方法是将多个promise封装在一起,等待所有promise都变为resolved时,才会变为resolved,否则为rejected race和all相反,只要一个promise改变就会随着改变 五.css居中,布局,兼容
Python
UTF-8
786
3.09375
3
[]
no_license
import tensorflow as tf, numpy as np; np.set_printoptions(linewidth=400); print(np.get_printoptions()); mnist = tf.keras.datasets.mnist; (x_train, y_train), (x_test, y_test) = mnist.load_data(); #normalization of dataset x_train=x_train/255; x_test=x_test/255; print("Dataset dimensions:"); print(len(x_train), len(y_train)); print(type(x_train), type(y_train)); print(x_train.shape, y_train.shape); print(x_train[0]); #visualize normalized example print("Input should be (as we're not using CNNs):", x_train[0].shape); #Assumptions: #not going to use CNN => input is 28*28=784 #output = an integer between 0 and 9 #try relu as activation #two hidden layers should be enough #cost function is good as before #architecture definition: model = tf.keras.Sequential(); model.add();
Java
UTF-8
852
3.15625
3
[]
no_license
package ch.epfl.cs108; import java.util.ArrayList; import java.util.List; public class Transposed implements ASCIImage { private ASCIImage baseImage; public Transposed(ASCIImage img) { baseImage = img; } @Override public int width() { return baseImage.height(); } @Override public int height() { return baseImage.width(); } @Override public List<String> drawing() { List<String> finalList = new ArrayList<>(); for (int i = 0; i < height(); ++i) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < width(); ++j) { builder.append(baseImage.drawing().get(j).charAt(i)); } finalList.add(builder.toString()); } return finalList; } }
Markdown
UTF-8
2,971
2.75
3
[]
no_license
# 課程作業 * 線上評測系統:http://neoj.sprout.tw/ ## 每週勾選作業 | 週次 | 小專案 | 上課練習 | 勾選作業 | | :----: | :------- | :--------- | :--------- | | 0226 | | [100-修羅道的開始](http://neoj.sprout.tw/problem/100/)、[101-修羅道的傳統-morris的煩惱](http://neoj.sprout.tw/problem/101/)| 無 | | 0305 | | [304-野豬騎士來囉](http://neoj.sprout.tw/problem/304/)、[305-三元排序](http://neoj.sprout.tw/problem/305/)、[299-3n+1問題](http://neoj.sprout.tw/problem/299/)| [2001-修羅道的岔路](http://neoj.sprout.tw/problem/2001/) 、[2002-修羅道的中場休息](http://neoj.sprout.tw/problem/2002/)| | 0312 | | [2003](http://neoj.sprout.tw/problem/2003/)、[2004](http://neoj.sprout.tw/problem/2004/)、[299](http://neoj.sprout.tw/problem/299/)、[309](http://neoj.sprout.tw/problem/309/)| [2007](http://neoj.sprout.tw/problem/2007/) 、[2005](http://neoj.sprout.tw/problem/2005/) 、[2006](http://neoj.sprout.tw/problem/2006/)、[307](http://neoj.sprout.tw/problem/307/)、[308](http://neoj.sprout.tw/problem/308/)、[310](http://neoj.sprout.tw/problem/310/)、[330](http://neoj.sprout.tw/problem/310/)| | 0402 | [大作業1](https://drive.google.com/open?id=0B5P2VH3szaKEdEJvall5WEZsWnM) | [2010-西瓜排序](https://neoj.sprout.tw/problem/2010)、[2011-凌晨4點的修羅道](https://neoj.sprout.tw/problem/2011) | [336-Function--GCD練習](https://neoj.sprout.tw/problem/336)、[339-海芭樂愛的大冒險III](https://neoj.sprout.tw/problem/339) | | 0409 | [大作業2](https://drive.google.com/file/d/0B6wbwXKOYgvhYUZxN1lIY2xUNG8/view) | | | 0416 | | [5566-rilak與他的快樂小夥伴們](http://neoj.sprout.tw/problem/5566/) | [354-野豬騎士史記 I](http://neoj.sprout.tw/problem/354/)、[382-西瓜的奇妙冒險 -- 大數據篇](http://neoj.sprout.tw/problem/382/)、[383-海捌樂愛的大冒險 -- 異世界篇](http://neoj.sprout.tw/problem/383/)、[384-海捌樂愛的幸運數字](http://neoj.sprout.tw/problem/384/)| |0508||[2014-再探修羅道-停修的滋味QQ](http://neoj.sprout.tw/problem/2014/)|| |0514|| [8770-Queue 練習](http://neoj.sprout.tw/problem/8770/)、[8771-Stack 練習](http://neoj.sprout.tw/problem/8771/) | [8772-括弧匹配](http://neoj.sprout.tw/problem/8772/) | |0521||[2015-修羅道的暴力](https://neoj.sprout.tw/problem/2015/)、[2016-修羅道的輕鬆練習-fibonacci](https://neoj.sprout.tw/problem/2016/)|[2017-修羅道的有點不輕鬆練習-枚舉](https://neoj.sprout.tw/problem/2017/)| |0528||[2019-修羅道的資料挖掘師 -- 天氣篇](https://neoj.sprout.tw/problem/2019/)|| |0604||[2020-八七皇后問題](https://neoj.sprout.tw/problem/2020/)|[2021-修羅道的載物者 - 工具人](https://neoj.sprout.tw/problem/2021/)| |0611||||
C++
UTF-8
5,145
4.375
4
[]
no_license
#ifndef LINKEDLIST_H_INCLUDED #define LINKEDLIST_H_INCLUDED #include <string> #include "Node.h" class LinkedList{ private: Node * head; //This points to the first element of the linked list. It is used to point to the first element of the list. This should never be manipulated out of add. Node * traversalNode; //Points to the getNext of Head. This shows all of the elements that are connected to the node. Node * iteratorNode; //Allows you to move an iterator through every element of the linked list; including the head. int lengthOfList; public: LinkedList(){ head = NULL; traversalNode = NULL; lengthOfList = 0; } //This is the constructor if you want to use the linked list with a traversal node. LinkedList(std::string initialString){ Node * initialNode = new Node(initialString, traversalNode); head = initialNode; traversalNode = NULL; lengthOfList = 1; } //Adds the element to the linked list by adding it AFTER the head, but before any other existing elements. void addToTraversal(std::string stringToBeAdded){ Node *nodeToBeAdded = new Node(stringToBeAdded, traversalNode); head->setNext(nodeToBeAdded); traversalNode = nodeToBeAdded; lengthOfList++; } //Returns the string of the head of the linked list. std::string getDataOfHead(){ return head->getData(); } //Returns the head of the linked list. Node * getNodeHead(){ return head; } //Gets the string data from the node of the traversal pointer. std::string getDataOfTraversal(){ return traversalNode->getData(); } Node * getTraversalNode(){ return traversalNode; } //Moves the traversal node up by one element (node). void moveTraversalNode(){ traversalNode = traversalNode->getNext(); } //Creates or restores the traversalNode back to head->getNext() void setTraversal(){ traversalNode = head->getNext(); } //Creates or restores the iterator to the first node of the linked list. void setIterator(){ iteratorNode = head; } //Moves the iterator up by one element. void moveIterator(){ iteratorNode = iteratorNode->getNext(); } //Gets the string data of the current iterator position (the node of) std::string getDataOfIterator(){ return iteratorNode->getData(); } //Gets the node of the iterator position. Node * getIterator(){ return iteratorNode; } //Adds a NODE object to the linked list given a string object. void add(std::string stringToBeAdded){ //If the below conditional is taken, it means that the list was empty and that this is the first element to be inserted. if(head == NULL){ Node *nodeToBeAdded = new Node(stringToBeAdded, NULL); head = nodeToBeAdded; lengthOfList++; //Increasing the list length by one since an element was added. } //If this element to be added is NOT the first element to be added. else if(head != NULL){ Node *nodeToBeAdded = new Node(stringToBeAdded, head); head = nodeToBeAdded; lengthOfList++; //Increasing the list length by one since an element was added. } //If the above two conditionals are not taken, an error branch print statement is given. else{ std::cout << "The string was not added to the linked list. Program stability is unknown." << std:: endl; } } //Adds a NODE to think linked list given a NODE object. void add(Node *nodeToBeAdded){ if(head == NULL){ head = nodeToBeAdded; nodeToBeAdded->setNext(NULL); lengthOfList++; //Increasing the list length by one since an element was added. } else if(head != NULL){ nodeToBeAdded->setNext(head); head = nodeToBeAdded; lengthOfList++; //Increasing the list length by one since an element was added. } //If the above two conditionals are not taken, an error branch print statement is given. else{ std::cout << "The node was not added to the linked list. Program stability is unknown." << std::endl; } } //Returns the length of the list. int getLength(){ return lengthOfList; } //Print all elements within the linked list. void print(){ Node * printerNode = head; //Putting the head variable into the temp node (printerNode) so we don't mess with the head's position. int i = 0; while(printerNode != NULL){ //Iterating through the entire linked list. if(i == 0){ std::cout << "The first element of the linked list is: " << printerNode->getData(); printerNode = printerNode->getNext(); i++; } else{ std::cout << " " << printerNode->getData() << " "; printerNode = printerNode->getNext(); } } } }; #endif // LINKEDLIST_H_INCLUDED
C++
UTF-8
685
2.859375
3
[ "MIT" ]
permissive
///by r@ul! #include <string> #include <iostream> using namespace std; const int CJ = 10; int VJ[CJ]; void cambiarv(int & a, int & b){ int c = a; a = b; b = c; } int main() { int cn, a = 1; cin >> cn; while(cn > 0){ for(int i = 1 ; i <= CJ ; i++) cin >> VJ[i]; for(int i = 1 ; i <= CJ ; i++) for(int j = i + 1 ; j <= CJ ; j++) if(VJ[i] < VJ[j]) cambiarv(VJ[i], VJ[j]); int sum = 0; for(int i = 2 ; i < CJ ; i++) sum += VJ[i]; cout << a << " " << sum << '\n'; a++; cn--; } return 0; }
Java
UTF-8
534
2.3125
2
[]
no_license
package com.vinod.test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import reactor.bus.Event; import reactor.bus.EventBus; @Service public class CustomerPublisher { @Autowired EventBus eventBus; public void publishCustomerDetails() throws InterruptedException { Customer customer = new Customer(); customer.setName("vinod"); customer.setAddress("Sasi area"); eventBus.notify("customer", Event.wrap(customer)); System.out.println("Message sent"); } }
Java
UTF-8
1,115
2.125
2
[]
no_license
package gson; import com.google.gson.*; import request.receive.*; import java.time.LocalDate; public abstract class RequestDeserializer { public static Gson getDeserializer() { RuntimeTypeAdapterFactory<GenericResponse> typeAdapterFactory = RuntimeTypeAdapterFactory .of(GenericResponse.class, "type") .registerSubtype(AuthentificationResponse.class, ResponseType.AUTHENTIFICATION.toString()) .registerSubtype(ErrorResponse.class, ResponseType.ERROR.toString()) .registerSubtype(SuccessResponse.class, ResponseType.SUCCESS.toString()) .registerSubtype(SearchResponse.class, ResponseType.SEARCH.toString()) .registerSubtype(PreviewImageResponse.class, ResponseType.PREVIEWIMAGE.toString()) .registerSubtype(LikeResponse.class, ResponseType.LIKE.toString()) .registerSubtype(SearchPerDayResponse.class, ResponseType.SEARCHPERDAY.toString()) .registerSubtype(FullImageResponse.class, ResponseType.FULLIMAGE.toString()); return new GsonBuilder().registerTypeAdapterFactory(typeAdapterFactory) .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()).create(); } }
PHP
UTF-8
747
2.953125
3
[ "BSD-3-Clause" ]
permissive
<?php /** * State calculator for multiple objects that returns the average state */ class AverageStateCalculator extends WorstStateCalculator { public function add_event($row = false) { foreach ($this->sub_reports as $idx => $rpt) { $rpt->add_event($row); } } public function calculate_object_state() { /* No thanks */ } public function finalize() { foreach ($this->sub_reports as $rpt) { $rpt->finalize(); } foreach ($this->sub_reports as $rpt) { foreach ($rpt->st_raw as $type => $value) { $this->st_raw[$type] = (isset($this->st_raw[$type])?$this->st_raw[$type]:0) + $value; } } $c = count($this->sub_reports); foreach ($this->st_raw as $type => $val) { $this->st_raw[$type] = $val / $c; } } }
Python
UTF-8
5,708
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Mon Mar 1 20:22:59 2021 @author: gabriel """ import numpy as np import pandas as pd import tensorflow as tf import keras as kr from keras.models import Sequential from keras.layers import Dense from keras.utils import np_utils from sklearn.preprocessing import LabelEncoder from keras.optimizers import Adam import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix def normalizeGender(genderColumn): return genderColumn.str.replace('M', '1').str.replace('m', '1').str.replace('F', '0').str.replace('f', '0').astype('category') def normalizeAge(ageColumn): return ageColumn.str.replace('?', 'Unknown').astype('category') #Função irá substituir os valores na coluna ethnicity a fim de normaliza-los talvez tirar essa coluna def nomalizeEthnicity(ethnicityColumn): return ethnicityColumn.str.replace('?',"Unknown").str.replace(' ','_').str.replace('\'Middle_Eastern_\'',"ME" ).str.replace('\'South_Asian\'','SA').str.replace('others','Others').astype('category') #Troca valores de Yes por 1 e No por 0 def normalizeJundice(jundiceColumn): return jundiceColumn.str.replace('yes', '1').str.replace('no', '0').astype('category') #Normaliza a coluna que tem informação se alguém da família tem Autismo de yes para 1 e de no para 0 def normalizeRelativesWithAutism(autismColumn): return autismColumn.str.replace('yes', '1').str.replace('Yes', '1').str.replace('no', '0').str.replace('No', '0').astype('category') #Normaliza a coluna de range de idade trocando de 4 a 11 por 1 de 12 a 15 por 2 e de 18+ para 3 def normalizeAgeRange(age_descColumn): return age_descColumn.str.replace('\'4-11 years\'', '1').str.replace('\'12-16 years\'', '2').str.replace('\'12-15 years\'', '2').str.replace('\'18 and more\'', '3').astype('category') #Normaliza coluna da pessoa que está realizando o teste talvez excluir essa coluna seja melhor def normalizeRelation(relationColumn): return relationColumn.str.replace('Self', 'self').str.replace('\'Health care professional\'', 'HealthProfessional').str.replace('?', 'Unknown').astype('category') #Normaliza a classificação de YES para 1 e de NO para 0 def normalizeClassification(classColumn): return classColumn.str.replace('YES', '1').str.replace('Yes', '1').str.replace('yes', '1').str.replace('NO', '0').str.replace('No', '0').str.replace('no', '0').astype('category') def normalizeData(dataFrame): dataFrame.gender = normalizeGender(dataFrame.gender) dataFrame.age = normalizeAge(dataFrame.age) dataFrame.ethnicity = nomalizeEthnicity(dataFrame.ethnicity) dataFrame.jundice = normalizeJundice(dataFrame.jundice) dataFrame.austim = normalizeRelativesWithAutism(dataFrame.austim) dataFrame.age_desc = normalizeAgeRange(dataFrame.age_desc) dataFrame.relation = normalizeRelation(dataFrame.relation) dataFrame.Class = normalizeClassification(dataFrame.Class) dataFrame = dataFrame.drop('contry_of_res',axis=1) dataFrame = dataFrame.drop('used_app_before',axis=1) return dataFrame def fixPredictions(predictions): newArray = [] for index, case in enumerate(predictions): if(case[0] > case[1]): newArray.append([1.0, 0.0]) else: newArray.append([0.0, 1.0]) return newArray header=['A1_Score','A2_Score','A3_Score','A4_Score','A5_Score','A6_Score','A7_Score','A8_Score','A9_Score','A10_Score','age','gender','ethnicity','jundice','austim','contry_of_res','used_app_before','result','age_desc','relation','Class'] data = pd.read_csv('allData.data', header=None) dataFrame = pd.DataFrame(data.values,columns=header) dataFrame = normalizeData(dataFrame) #chamar as 4 primeiras funções de normalizar genero, etinia, jundice e parentes com autismo #dataSet = pd.get_dummies(dataFrame,drop_first=True,columns=['gender','ethnicity','age_desc','relation'],prefix={'gender':'gen','ethnicity':'eth','age_desc':'ageD','relation':'rel'}) #dataSet = dataFrame.select_dtypes(include=['category','int64','float64','uint8']).apply(pd.to_numeric).astype(astype) #dataSet = dataFrame.values #entries = (dataSet[:, 0:10]).astype('float32') #classification = dataFrame[:, 18] #dataFrame.drop('Class') classification = dataFrame.Class dataFrame = dataFrame.drop('Class', axis=1) dataSet = pd.get_dummies(dataFrame) dataSet = dataSet.select_dtypes(include=['category','int64','float64','uint8']).apply(pd.to_numeric).astype('float64') encoder = LabelEncoder() encodedClass = encoder.fit_transform(classification) classificationEncoded = np_utils.to_categorical(encodedClass) X_train, X_test, y_train, y_test = train_test_split(dataSet, classificationEncoded, test_size = 0.4) model = Sequential() model.add(Dense(15, input_dim=117, activation='relu')) model.add(Dense(7, input_dim=15, kernel_initializer='normal', activation='relu')) model.add(Dense(2, activation='sigmoid')) adam=Adam(lr=0.001) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) historico = model.fit(X_train, y_train, epochs=40) predictions = model.predict(X_test) predictions = fixPredictions(predictions) predictions = np.array(predictions) print(confusion_matrix(y_test.argmax(axis=1), predictions.argmax(axis=1))) print(classification_report(y_test, predictions)) plt.style.use("ggplot") plt.figure() plt.plot(historico.history['loss'], label = 'Loss') plt.plot(historico.history['accuracy'], label = 'Accuracy') plt.title('Épocas x Perda/Precisão') plt.xlabel('Quantidade de Épocas') plt.ylabel('Accuracy, Loss') plt.legend() plt.axis([0, 50, -0.1, 1.1]) plt.show()
Ruby
UTF-8
377
3.6875
4
[]
no_license
#exercise 1 #check for the sequence of characters "lab" def has_lab?(string) if /lab/.match(string) puts ":) #{string} contains the sequence of characters 'lab'!" else puts ":( #{string} does not contain sequence of characters 'lab'." end end has_lab?("laboratory") has_lab?("experiment") has_lab?("Pans Labyrinth") has_lab?("elaborate") has_lab?("polar bear")
JavaScript
UTF-8
4,485
2.609375
3
[]
no_license
import React, { Component } from 'react'; import axios from 'axios'; class NewProduct extends Component { constructor(props) { super(props); this.state = { name: "", brand: "", form: "", category: "", price: 0, description: "", descriptionBullets: "", direction: "", quantity: "", ingredients: "", warnings: "", image: "", popular: false, } } _createProduct = () => { var categoryArray = this.state.category.split('~'); var descriptionArray = this.state.description.split('~'); var descriptionBulletsArray = this.state.descriptionBullets.split('~'); var ingredientsArray = this.state.ingredients.split('~'); axios.post('http://localhost:5000/api/product/add', { name: this.state.name, brand: this.state.brand, form: this.state.form, category: categoryArray, price: this.state.price, description: descriptionArray, descriptionBullets: descriptionBulletsArray, direction: this.state.direction, quantity: this.state.quantity, ingredients: ingredientsArray, warnings: this.state.warnings, image: this.state.image, popular: this.state.popular, }); } render() { return( <div className = "Page-length"> <h3>Create New User</h3> <form onSubmit={()=> this._createProduct()}> <label htmlFor="name">name: </label> <input id="name" type="text" required onChange={(e) => this.setState({name:e.target.value})}/> <br/> <label htmlFor="brand">brand: </label> <input id="brand" type="text" onChange={(e) => this.setState({brand:e.target.value})}/> <br/> <label htmlFor="form">form: </label> <input id="form" type="text" onChange={(e) => this.setState({form:e.target.value})}/> <br/> <label htmlFor="category">category: </label> <input id="category" type="text" onChange={(e) => this.setState({category:e.target.value})}/> <br/> <label htmlFor="price">price: </label> <input id="price" type="text" onChange={(e) => this.setState({price:e.target.value})}/> <br/> <label htmlFor="description">description: </label> <input id="description" type="text" onChange={(e) => this.setState({description:e.target.value})}/> <br/> <label htmlFor="descriptionBullets">description bullets: </label> <input id="descriptionBullets" type="text" onChange={(e) => this.setState({descriptionBullets:e.target.value})}/> <br/> <label htmlFor="direction">direction: </label> <input id="direction" type="text" onChange={(e) => this.setState({direction:e.target.value})}/> <br/> <label htmlFor="quantity">quantity: </label> <input id="quantity" type="text" onChange={(e) => this.setState({quantity:e.target.value})}/> <br/> <label htmlFor="ingredients">ingredients: </label> <input id="ingredients" type="text" onChange={(e) => this.setState({ingredients:e.target.value})}/> <br/> <label htmlFor="warnings">warnings: </label> <input id="warnings" type="text" onChange={(e) => this.setState({warnings:e.target.value})}/> <br/> <label htmlFor="image">image: </label> <input id="image" required type="text" onChange={(e) => this.setState({image:e.target.value})}/> <br/> <label htmlFor="popular">popular: </label> <select name="popular" onChange={(e) => this.setState({popular: e.target.value})}> <option value="" selected>Is the product popular</option> <option value={true}>Yes</option> <option value={false}>No</option> </select> <br/> <input type="submit" value="submit"/> </form> </div> ); }; }; export default NewProduct;
Python
UTF-8
2,868
2.75
3
[ "Apache-2.0" ]
permissive
""" Created on Sun Aug 12 15:43:10 2018 @author: TANVEER MUSTAFA """ import cv2 import numpy as np import os from test_frames1 import analyse_frame from termcolor import colored from PIL import Image import matplotlib.pyplot as plt from os.path import isfile, join image_array=[] def convert_frames_to_video(pathIn): frame_array = [] files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))] files.sort(key = lambda x: int(x[5:-4])) j=0 img1=[] img3=[] img1.append(files) for i in range(len(files)): img2=pathIn + files[i] img3.append(img2) img1 = cv2.imread(img2) i=0 j=0 print(len(img3)) def plot_graph(): plt.xlabel('x - axis') plt.ylabel('y - axis') plt.title('Activity detection of a person') xs = [x[0] for x in image_array] ys = [x[1] for x in image_array] j=1 y_dif=[] x_dif=[] for i in range(len(xs)): if(j<len(xs)): #print(j) y=ys[j]-ys[i] y_dif.append(abs(y)) x=xs[j]-xs[i] x_dif.append(abs(x)) j=j+1 print("person action y-axis",y_dif) print("person action x-axis",x_dif) if(abs(ys[1]-ys[0])<7): print("person in horizontal motion") for i in range(len(x_dif)): if(x_dif[i]>7): print (colored("person running","red")) elif(x_dif[i]>2 and x_dif[i]<5 ): print(colored("person walking",'blue')) elif(x_dif[i]>4 and x_dif[i]<8 ): print(colored("person jogging",'green')) elif(abs(xs[1]-xs[0])<2): print("person in vertical motion") for i in range(len(y_dif)): if(y_dif[i]>6): print("climbing") elif(y_dif[i]>2 and y_dif[i]<6 ): print("slow climb") else: print("very slow climb") plt.plot(xs, ys) count=1 for i in range(len(img3)): if(i==30*count): plot_graph() count=count+1 if(i==j ): k=img3[i] image1=analyse_frame.frame_new1(cv2.imread(k)) if (image1=='NULL'): j=j+1 else: print("the center is",image1) image_array.append(image1) j=j+1 plot_graph() def main(): pathIn= 'z1video_frames4/' convert_frames_to_video(pathIn) if __name__=="__main__": main()
C++
UTF-8
270
3.28125
3
[]
no_license
#include <iostream> using namespace std; void printNumber(int x) { cout << "an integer " << x << endl; } void printNumber(float y) { cout << "a float " << y << endl; } int main() { int a = 54; float b = 32.4896; printNumber(a); printNumber(b); }
Markdown
UTF-8
8,810
3.25
3
[]
no_license
--- layout: post id: 1138 alias: the-jsonbuilder-of-groovy-is-not-groovy-enough tags: 其它语言 date: 2012-12-21 16:36:31 title: Groovy的JsonBuilder还是不够groovy --- 之前特别想把groovy的支持集成到play中,最主要的原因是看中了它的JsonBuilder。看下面这段代码: <pre class="csharpcode"> <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> json() { def builder = <span class="kwrd">new</span> groovy.json.JsonBuilder() def root = builder.people { person { firstName <span class="str">'Guillame'</span> lastName <span class="str">'Laforge'</span> <span class="kwrd">if</span> (1 == 0) { address { city <span class="str">'Paris'</span> country <span class="str">'France'</span> zip 12345 } } married <span class="kwrd">true</span> <span class="rem">// a list of values</span> conferences <span class="str">'JavaOne'</span>, <span class="str">'Gr8conf'</span> } } renderJSON(builder.toString()) }<style type="text/css">.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } </style>``` 这个JsonBuilder的结构我非常喜欢,简洁明了,最重要的是还可以在中间随意穿插自己的控制逻辑。 为什么我这么看重JsonBuilder,因为我使用了angularjs这样的前端框架,前后台经常需要用json通信。为了得到最好的性能,为每个页面定制json是非常必要的手段。但使用gson/jackson把bean转换为json,控制的粒度不够细;而在java代码中拼json,不用想就知道有多痛苦;而在play模板中拼json,除了要对每个值进行raw()的处理外,还需要处理分隔符,少不了这样的语句: > <font style="background-color: #ffffff">${if var_isLast ? "" : ","}</font> 有够麻烦。 当我看到groovy的JsonBuilder的时候,我眼前一亮,这东西太好了。 (后来发现不需要专门集成groovy,因为play的模板就是基于groovy的,我们可以把这个builder直接写在模板里,用 %{}%括起来就行了。这是另一个问题,不在本文中说了) 然而现在却发现这个JsonBuilder还不够groovy,还不够好,因为如果想生成一个array形式的json,它的这种语法不支持。 比如我想生成一个这样的json: <pre class="csharpcode">[ {<span class="str">"code"</span>: <span class="str">"111"</span>, <span class="str">"value"</span>:<span class="str">"222"</span>}, {<span class="str">"code"</span>: <span class="str">"333"</span>, <span class="str">"value"</span>:<span class="str">"444"</span>} ]``` <style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style> <p>JsonBuilder没办法按前面的语法来写,因为它只能生成object形式的,比如例中的那样,或者下面这样的: > { > > "code" : "111", > > "value" : "222" > > } > > 那么JsonBuilder是否能生成array形式的json呢?可以是可以,但语法形式就不一样了。如下例: <pre class="csharpcode">def list = [ [code: <span class="str">"111"</span>, <span class="kwrd">value</span>: <span class="str">"222"</span>], [code: <span class="str">"333"</span>, <span class="kwrd">value</span>: <span class="str">"444"</span>] ] builder = <span class="kwrd">new</span> groovy.json.JsonBuilder(list) println builder.toString()``` <style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style> <p>可以看到,这已经是纯粹的groovy代码了。这时候要使用[]而不是{},而且list和map都是用[]。 看一下这两种写法之间的不同: 1. JsonBuilder的语法,使用{},每行结果没有逗号,key与value之间没有冒号2. 使用groovy内置的集合语法时,使用[],而且list和map都是[],并且各元素之间都要有逗号 这里存在着一大坑:如果你写错了,比如多写了冒号或少写了逗号,它有可能不报错,但结果不同;也有可能报一个完全让人摸不着头脑的错误! 比如, 1. 如果用JsonBuilder的语法,在key与value之间多写了一个冒号,不会报错,只是那一项被忽略了2. 如果用集合的写法,但在list的元素之间,少写了行尾的逗号,会报一个NullPointerException! 这种混乱会让人在使用过程中极易犯错,而花费大量的调试时间。 就算我强制只使用object形式的json,对于array,就给它加上一个无意义的key,也不能完全避免以上混乱。假设我现在有如下的一个list: > def list = [ > > [code: 111, value: 222], > > [code: 333, value: 444], > > ] > > 在生成json的时候,我要用它这个list,并且把它的每个值都加倍,应该怎么做呢? <pre class="csharpcode">def builder = <span class="kwrd">new</span> groovy.json.JsonBuilder() builder.system { name <span class="str">"mysystem"</span> settings list.collect { [ code: it.code * 2, <span class="kwrd">value</span>: it.<span class="kwrd">value</span> * 2 ] } } println builder.toPrettyString()``` <style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style> <p>看到了吗?要使用collect方法对原list进行变换,它要把每个元素转换为一个map,即[]包裹起来的代码。在复杂的情况下,这实在让人难以接受。 综上所述,在play中引入groovy的JsonBuilder,带来的混乱要大于其方便性,所以决定抛弃它。如果抛弃了JsonBuilder,则集成groovy的意义也不大了,所以我打算不再考虑groovy。 现在想到的办法,还是对play进行扩展,增加以下功能: 1. 给list标签增加separator属性,方便增加json间的逗号2. 添加一个新的render方法,以字符串形式返回生成的模板内容,而不是抛出异常。以方便在模板中调用拿结果。3. 增加一个将object转换为json的扩展方法,返回Raw类型,方便在模板中调用 后两者可以在自己的代码中实现,而对于1,必须要修改play的源代码,因为list标签是写死在代码中(GroovyInlineTag),没有办法对它进行扩展。
Python
UTF-8
1,003
3.28125
3
[ "MIT" ]
permissive
from math import sqrt, ceil from array import * T = int(input()) for _ in range(T): # readin plain_text = input() text_len = len(plain_text) k = ceil(sqrt(text_len)) # k x k matrix m = k * k asteriks = m - text_len text_matrix = [[None for _ in range(k)] for _ in range(k)] traversal = 0 # make plain text for i in range(k): for j in range(k): if traversal >= text_len: text_matrix[i][j] = '*' else: text_matrix[i][j] = plain_text[traversal] traversal += 1 cipher_matrix = [[None for _ in range(k)] for _ in range(k)] # decipher for i in range(k): for j in range(k): cipher_matrix[i][j] = text_matrix[k - 1 - j][i] # print the matrix without '*' for i in range(k): for j in range(k): if cipher_matrix[i][j] != '*': print(cipher_matrix[i][j], end = '') # next line print()
Python
UTF-8
1,924
2.625
3
[]
no_license
import config, csv, json from binance.client import Client from tafunc import ta_analyze from collections import OrderedDict #@todo: add overload for user selection of data intervals #this function gets the kline data provided in the binance api def get_klines(selected_interval): client = Client(config.API_KEY,config.API_SECRET) #get the possible exchanges for the quoting asset, that are spot tradeable exinfo = client.get_exchange_info() exlist = [] for symbol in exinfo["symbols"]: if((symbol["quoteAsset"] == "USDT") & (symbol["permissions"].count("SPOT") == 1)): exlist.append(symbol["symbol"]) #getting the kline data to analyse for the exchangeable assets klines = {} unsorted = {} if selected_interval == "1HOUR": s_interval = Client.KLINE_INTERVAL_1HOUR elif selected_interval =="15MIN": s_interval = Client.KLINE_INTERVAL_15MINUTE elif selected_interval =="4HOUR": s_interval = Client.KLINE_INTERVAL_4HOUR elif selected_interval =="1DAY": s_interval = Client.KLINE_INTERVAL_1DAY elif selected_interval =="1MIN": s_interval = Client.KLINE_INTERVAL_1MINUTE else: s_interval = Client.KLINE_INTERVAL_4HOUR for exchange in exlist: candledata = [] try: print(exchange) candledata.append(client.get_klines(symbol = exchange, interval = s_interval, limit = 100)) klines[exchange] = candledata unsorted[exchange] = ta_analyze(candledata) print("done") except Exception as e: print("can't because") print(e) #sorting with lambda black magic fuckery sortedsigs = dict(OrderedDict(sorted(unsorted.items(), key= lambda t:t[1]['signal']))) print("sorted") return (sortedsigs)
Markdown
UTF-8
3,964
2.984375
3
[]
no_license
# TDR_Alert_Runspaces ## .SYNOPSIS Small utility to detect specific event ID in all active virtual machines in Citrix XenDesktop environment. Utility leverages multithreaded runspaces to minimize execution time. ## .DESCRIPTION Citrix XenDesktop is able to leverage NVIDIA GRID technology to boost graphics and improve overall end-user experience. NVIDIA GRID technology on VMWare ESXI hypervisor has been known to experience system faults which can lead to hypervisors experiencing purple-screen-of-death. Virtual machines being hosted on hypervisors running NVIDIA Grid require a graphics driver in order to fully utilize this NVIDIA hardware. The graphics driver in the guest VM generates a system event ID = 4101 warning of hardware failure. Unfortunately, if a hypervisor host crashes, all of the virtual machines on the host fail as well. The main pain point here is that the Citrix Farm will not register these sessions as 'terminated' meaning users will not be able to start a fresh session since the Broker still thinks there is an 'active' session on the backend. From a business continuity standpoint, we can leverage the event ID 4101 to predict an impeding failure of a host. The utility scans all virtual machines in the Citrix environment for any 4101 errors generated in the past 20 minutes. If an event is detected, the following will occur: 1. All time stamps will be captured in a log file. 2. List of impacted virtual machines along with the current user (if any) and hypervisor host name are neatly formatted using CSS 3. Email containing the information from steps 1 + 2 above is sent out to the Helpdesk and any other necessary recipients. 4. Helpdesk will reach out to listed users in the email to notify them and advise them to save their work and terminate their sessions. Users will be able to log back in immediately so they are given a new virtual machine on a different hypervisor host. Please note, while the helpdesk is coordinating logoffs with users, the administration team is powering down VMs on the impacted hypervisor host and prepping the host for maintenance work. Below is an exmaple of the correspondance data: Machine_Name | Current_User | ESXi_Host ------------ | ------------- | ------------- VirtualMachine_132 | Domain\Username_01 | Hypervisor_234 VirtualMachine_043 | Domain\Username_04 | Hypervisor_234 VirtualMachine_031 | Domain\Username_06 | Hypervisor_234 ## .ACCOMPLISHMENTS/WHAT I LEARNED Although this script was intended to benefit the environment from a business continuty point, the technical benefit of this was learning to optimize powershell scripts using runspaces. Native powershell runspaces for threading tasks can be cumbersome and not provide streamline methods of customization. PoshRSJOB is a wrapper to the native runspaces framework and provides an intutive method of tweaking attributes such as the timeout limit for each thread, throttle number of parallel threads, and easily pass in functions/modules/snapins to each runspace that gets created. Without runspaces, scanning of 1600 virtual machines by iterating through the list in a linear fashion resulted in 15 minutes of execution time. Implementing the utlility using runspaces brought the total run time to less than 10 seconds. Server resources are not heavily impacted as well. Hosting server had 4 CPU cores + 8 GB of RAM. Resource utilization barely increased at runtime. ## .AREAS OF IMPROVEMENT Areas of improvement would be dynamically passing an event ID in to each runspace. This would help anyone running the script dynamically input their targetted iD. Additionally, packaging this script and adding parameter input would allow for anyone to pass parameters via terminal. ## .NOTES Script was created using Powershell 5.1. PoshRSJob and Citrix Broker SDK are required. Script can be leveraged for non-citrix managed virtual machines by simple providing computer names via another source.
Markdown
UTF-8
906
2.671875
3
[]
no_license
--- title: '2018-03-29' date: 2018-03-29 15:33:23 tags: --- 昨夜花儿们可能悄悄拉了勾,「都开了吧,不等了」; 于是粉白的、鹅黄的、玫红的,一树树,一丛丛,怯怯地互相观望着,开在了雾霾下。 雾霾没能兜住这三月底的阳光,大地在睡眼惺忪中接受着恩惠,眼前像隔着刚盛过牛奶的玻璃杯。 柳芽儿在不知不觉中织成了一张张网,青烟似的荡在空中。 还有一些树,大约不愿从冬日长长的梦里醒过来,依旧伸展着光秃秃的枝干,高高地,在灰色的天空下。 这天地,热闹又安静。 -- 下午三点左右,想到了早晨来时路上的花,便下楼去看。 院子中央的树林里,七八个年轻人,跟着前排一个盘盘扣的中年人,有模有样地打太极。 我走到他们后边,舒展胳膊腿,发现什么也不会了...
Rust
UTF-8
2,205
3.125
3
[]
no_license
use intcode::Interpreter; type Phases = (i64, i64, i64, i64, i64); fn amplify(interpreter: &Interpreter, (a, b, c, d, e): Phases) -> i64 { let mut interpreters = [ interpreter.clone(), interpreter.clone(), interpreter.clone(), interpreter.clone(), interpreter.clone(), ]; interpreters[0].input.push_back(a); interpreters[1].input.push_back(b); interpreters[2].input.push_back(c); interpreters[3].input.push_back(d); interpreters[4].input.push_back(e); interpreters[0].input.push_back(0); while !interpreters.last().unwrap().done { for i in 0..interpreters.len() { interpreters[i].run(); if let Some(output) = interpreters[i].output.pop_front() { interpreters[(i + 1) % interpreters.len()] .input .push_back(output); } } } interpreters[0].input[0] } fn for_all_phases(left: i64, right: i64, mut f: impl FnMut(Phases) -> ()) { for a in left..=right { for b in left..=right { if !(b != a) { continue; } for c in left..=right { if !(c != a && c != b) { continue; } for d in left..=right { if !(d != a && d != b && d != c) { continue; } for e in left..=right { if !(e != a && e != b && e != c && e != d) { continue; } f((a, b, c, d, e)) } } } } } } fn largest_output(interpreter: &Interpreter, low: i64, high: i64) -> i64 { let mut result = 0; for_all_phases(low, high, |phases| { let output = amplify(&interpreter, phases); if output > result { result = output; } }); result } fn main() { let interpreter = Interpreter::from_input(include_str!("input.txt")); println!("{}", largest_output(&interpreter, 0, 4)); println!("{}", largest_output(&interpreter, 5, 9)); }
Java
UTF-8
968
1.914063
2
[ "Apache-2.0" ]
permissive
package ru.alexproject.blogserver.services; import ru.alexproject.blogserver.model.domain.Comment; import ru.alexproject.blogserver.model.domain.Like; import ru.alexproject.blogserver.model.domain.Post; import ru.alexproject.blogserver.model.domain.User; import ru.alexproject.blogserver.model.dto.CommentDto; import ru.alexproject.blogserver.model.dto.LikeDto; import ru.alexproject.blogserver.model.dto.PostDto; import ru.alexproject.blogserver.model.dto.UserDto; import java.util.List; import java.util.Set; public interface LikeService { List<Like> getAll(); Set<Like> getLikesOnComment(); Set<Like> getLikesByCommentId(Long id); Set<Like> getLikesOnPosts(); Set<Like> getLikesByPostId(Long id); void increasePostLikeCount(User user, Post post); void decreasePostLikeCount(User user, Post post); void increaseCommentLikeCount(User user, Comment comment); void decreaseCommentLikeCount(User user, Comment comment); }
PHP
UTF-8
2,205
2.78125
3
[]
no_license
<?php define('DB_USER', "a8532754_root"); // db user define('DB_PASSWORD', "mess123"); // db password (mention your db password here) define('DB_SERVER', "mysql9.000webhost.com"); // db serve $conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } #MESS information $name = 'omkar7'; $addr= 'omkar7'; $area = 'omkar7'; #owner information $owner = 'omkar7'; $cont = '12345'; $contact=((int)$cont); #Menu information $menu = 'No menu yet'; #password $pass = 'omkar8'; #PASSWD TABLE REGISTRATION $sql = "INSERT INTO a8532754_mess.PASSWD". "(PASSWD) ". "VALUES('$pass')"; $status1=$conn -> query($sql) or die(mysql_error()); #GETTING MESS_ID $sql2= "select MESS_ID from a8532754_mess.PASSWD where PASSWD='$pass'"; $res1= $conn -> query($sql2) or die(mysql_error()); $row=$res1 ->fetch_array(MYSQLI_NUM); $mid = ((int)$row[0]); #Inserting into owner table with taken mess_id $sql3 = "INSERT INTO a8532754_mess.OWNER". "(MESS_ID,OWNER_NAME,CONTACT) ". "VALUES($mid,'$owner',$contact)"; $status2=$conn -> query($sql3); #Inserting into MESS table with already taken mess_id $sql4 = "INSERT INTO a8532754_mess.MESS". "(MESS_ID,MESS_NAME,ADDRESS,AREA) ". "VALUES($mid,'$name','$addr','$area')"; $status3=$conn -> query($sql4); #Inserting into MENU table with already taken mess_id $sql5="insert into a8532754_mess.MENU(MESS_ID,MENU) values($mid,'no menu yet')"; $status4=$conn -> query($sql5); #check if all conditions satisfied and send appropriate message if(($status1 and $status2) and ($status3 and $status4)) { $string1 = "You have been successfully registered . . ."; $string2 ="MESS ID :".$mid; $string3 ="You will be requiring the MESS ID for logging in,So we recommend you to Note it down or remember carefully"; $string4 ="Thanks for registering and Now you can login!!!"; } else { $string1 ="You Registration didn't complete"; $string2= "We recommend you to reregister"; $string3= "Check your internet connection firstly"; $string4= "Thanks though!!!"; } $arr["status"]=$string1; $arr["messid"]=$string2; $arr["reco"]=$string3; $arr["thank"]=$string4; echo json_encode($arr); ?>
JavaScript
UTF-8
2,389
2.546875
3
[]
no_license
// grab the root view of the player. function getCurrentTrack() { let view = document.getElementsByClassName('NowPlayingView')[0]; let key = Object.keys(view).filter(e => e.includes('__reactInternalInstance')); // get the state props, for the track data. return view[key].return.stateNode.props.track; } function getPlayer() { return document.getElementsByClassName('Root__now-playing-bar')[0]; } function movePlayerBarToTop() { // move the player from the bottom to the top. getPlayer().style.setProperty("height", "100%"); } function getAlbumArt() { return document.getElementById('chromecast-album-art'); } // add the big albumart in the center of the screen. function openAlbumArt() { var art = document.createElement('img'); art.id = 'chromecast-album-art'; art.src = getCurrentTrack().album.images[0].url; art.onclick = uninstall; art.style.cssText = `width: 640px; z-index: 999; cursor: pointer; height: 640px; left: 0px; right: 0px; top: 0px; position: absolute; margin: auto; bottom: 0px;`; document.body.appendChild(art); } function uninstall() { // show the scroll again. document.body.style.removeProperty("overflow-y"); // move the player to the bottom again. getPlayer().style.removeProperty("height"); // remove the album art image. document.body.removeChild(getAlbumArt()); } function install() { // for some reason the page becomes super long, hack it away. document.body.style.setProperty("overflow-y", "hidden"); movePlayerBarToTop(); openAlbumArt(); let lastTrack = getCurrentTrack(); // make sure to update the track image every 1s if changed. let timer = setInterval(() => { let currentTrack = getCurrentTrack(); if (lastTrack.id !== currentTrack.id) { let image = getAlbumArt(); if (image) { console.log(`updating image src to ${currentTrack.album.images[0].url}`); image.src = currentTrack.album.images[0].url; } else { // the album art image has been removed, stop this timer. window.clearInterval(timer); } lastTrack = currentTrack; } }, 1000); } document.getElementsByClassName('navBar-header')[0].onclick = install;
Markdown
UTF-8
1,732
3.21875
3
[]
no_license
# Astro-Analytics This machine learning hackathon wqas conducted as part of Techsoc 2020, Shaastra. The competition link is given here [Astro-Analytics Hackathon](https://www.kaggle.com/c/astro-analytics-techsoc-iitm/overview).The competition details are given below. ><h3>Astro Analytics Challenge</h3> >Objective - Build a model that would predict the position of space objects using simulation data.<br> ><h3>Background information.</h3> > >Predicting the position of satellites is one of the most important tasks in astronomy. For example, information on the exact position of satellites in orbit is necessary to avoid >extremely dangerous satellite collisions. Each collision leads not only to satellite destruction but also results in thousands of space debris pieces. For instance, the IridIridium- >Coscos collision in 2009 increased the number of space debris by approximately 13%. >Further collisions may result in Kessler syndrome and the inaccessibility of outer space. Also, a more accurate prediction of satellite position will help calculate more efficient >maneuvers to save propellant and extend satellite life in orbit. ><h3>What do you exactly predict?</h3> > >Participants are asked to clarify the prediction of a Simplified General Perturbations-4 (SGP4) model. SGP4 is able to predict a lot of effects but is applied to near-Earth objects with >an orbital period of fewer than 225 minutes, while high orbit space objects have orbital periods up to 200 hours. For the true position of the satellites, the position obtained using a >more accurate simulator will be taken. Subsequently, the obtained models will be applied to real classified data and will help to predict the positions of these space objects.
Python
UTF-8
609
3.515625
4
[]
no_license
from datetime import datetime, date, timedelta tday = datetime.now() print ("Сегодня: ", datetime.now()) delta_for_day = timedelta(1) delta_for_month = timedelta(30) yday = tday - delta_for_day month_ago = tday - delta_for_month print("Сейчас: ",tday) print("Вчера: ",yday) print("Отмотаем на месяц: ",month_ago) date_string = '01/01/2017 12:10:03.234567' date = datetime.strptime(date_string, "%m/%d/%Y %H:%M:%S.%f") print(date) # можно ли в timedelta указывать месяца, года? #dt_now = datetime.now() #print(dt_now.strftime('%Y %A %D'))
Python
UTF-8
8,481
2.640625
3
[]
no_license
"""Incremental demo for wx support of tasks. Multiple tasks Note that naively subclassing SecondTask from ExampleTask, it initially used the same menu_bar and tool_bars traits from ExampleTask. This caused the incorrect tying of the controls to SecondTask because the class attributes were shared between both classes. """ import logging logging.basicConfig(level=logging.DEBUG) import wx # Enthought library imports. from pyface.api import GUI, ConfirmationDialog, FileDialog, \ ImageResource, YES, OK, CANCEL from pyface.tasks.api import Task, TaskWindow, TaskLayout, PaneItem, IEditor, \ IEditorAreaPane, EditorAreaPane, Editor, DockPane, HSplitter, VSplitter from pyface.tasks.action.api import DockPaneToggleGroup, SMenuBar, \ SMenu, SToolBar, TaskAction, TaskToggleGroup from traits.api import on_trait_change, Property, Instance, Str, List class Pane1(DockPane): #### TaskPane interface ################################################### id = 'steps.pane1' name = 'Pane 1' class Pane2(DockPane): #### TaskPane interface ################################################### id = 'steps.pane2' name = 'Pane 2' #### FileBrowserPane interface ############################################ # The list of wildcard filters for filenames. filters = List(Str) def create_contents(self, parent): control = wx.GenericDirCtrl(parent, -1, size=(200,-1), style=wx.NO_BORDER) control.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.on_selected) return control def on_selected(self, evt): selected_file = self.control.GetFilePath() wx.CallAfter(self.task.window.application.load_file, selected_file, self.task, in_current_window=True) class HtmlWindow(wx.html.HtmlWindow): def __init__(self, parent): print("calling HtmlWindow constructor") wx.html.HtmlWindow.__init__(self, parent, -1, style=wx.NO_FULL_REPAINT_ON_RESIZE) print("setting HtmlWindow fonts") self.SetStandardFonts() class HtmlEditor(Editor): def create(self, parent): self.control = HtmlWindow(parent) class ExampleTask(Task): """ A simple task for opening a blank editor. """ #### Task interface ####################################################### id = 'example.example_task' name = 'Multi-Tab Editor' active_editor = Property(Instance(IEditor), depends_on='editor_area.active_editor') editor_area = Instance(IEditorAreaPane) menu_bar = SMenuBar(SMenu(TaskAction(name='New', method='new', accelerator='Ctrl+N'), TaskAction(name='Add Task', method='add_task', accelerator='Ctrl+A'), TaskAction(name='Remove Task', method='remove_task', accelerator='Ctrl+R'), id='File', name='&File'), SMenu(DockPaneToggleGroup(), TaskToggleGroup(), id='View', name='&View')) tool_bars = [ SToolBar(TaskAction(method='new', tooltip='New file', image=ImageResource('document_new')), image_size = (32, 32)), ] ########################################################################### # 'Task' interface. ########################################################################### def _default_layout_default(self): return TaskLayout( top=VSplitter( HSplitter( PaneItem('steps.pane1'), PaneItem('steps.pane2')), )) def create_central_pane(self): """ Create the central pane: the script editor. """ self.editor_area = EditorAreaPane() return self.editor_area def create_dock_panes(self): """ Create the file browser and connect to its double click event. """ return [ Pane1(), Pane2() ] ########################################################################### # 'ExampleTask' interface. ########################################################################### def new(self): """ Opens a new empty window """ editor = HtmlEditor() self.editor_area.add_editor(editor) self.editor_area.activate_editor(editor) self.activated() def add_task(self): """ Opens a new empty window """ task3 = ThirdTask() self.window.add_task(task3) self.window.activate_task(task3) def remove_task(self): """ Opens a new empty window """ task = self.window.tasks[0] window = self.window window.remove_task(self) window.activate_task(task) #### Trait property getter/setters ######################################## def _get_active_editor(self): if self.editor_area is not None: return self.editor_area.active_editor return None class SecondTask(ExampleTask): """ A simple task for opening a blank editor. """ #### Task interface ####################################################### id = 'example.second_task' name = 'Second Multi-Tab Editor' tool_bars = [ SToolBar(TaskAction(method='new', tooltip='New file', image=ImageResource('document_new')), TaskAction(method='new', tooltip='New file', image=ImageResource('document_new')), image_size = (32, 32)), ] ########################################################################### # 'Task' interface. ########################################################################### def _default_layout_default(self): return TaskLayout( left=VSplitter( HSplitter( PaneItem('steps.pane1'), PaneItem('steps.pane2')), )) class ThirdTask(ExampleTask): """ A simple task for opening a blank editor. """ #### Task interface ####################################################### id = 'example.third_task' name = 'Third Multi-Tab Editor' tool_bars = [ SToolBar(TaskAction(method='new', tooltip='New file', image=ImageResource('document_new')), TaskAction(method='new', tooltip='New file', image=ImageResource('document_new')), TaskAction(method='new', tooltip='New file', image=ImageResource('document_new')), TaskAction(method='new', tooltip='New file', image=ImageResource('document_new')), image_size = (32, 32)), ] ########################################################################### # 'Task' interface. ########################################################################### def _default_layout_default(self): return TaskLayout( right=VSplitter( HSplitter( PaneItem('steps.pane1'), PaneItem('steps.pane2')), )) def main(argv): """ A simple example of using Tasks. """ # Create the GUI (this does NOT start the GUI event loop). gui = GUI() # # Create a Task and add it to a TaskWindow. # task1 = ExampleTask() # task2 = SecondTask() # window = TaskWindow(size=(800, 600)) # window.add_task(task1) # window.add_task(task2) # task1.new() # task2.new() # # Show the window. # window.open() # info = wx.adv.AboutDialogInfo() # Start the GUI event loop. frame = wx.Frame(None, -1, "Test", size=(400,400)) html = wx.html.HtmlWindow(frame, -1) frame.Show(True) gui.start_event_loop() if __name__ == '__main__': import wx.html app = wx.App() import wx.adv import sys main(sys.argv)
Shell
UTF-8
7,179
3.328125
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # Common Vars SCRIPT_NAME=$(basename $0) SCRIPT_DIR=$(cd `dirname $0` && pwd) # Lab password LAB_PW='Welcome2lab!' # Sanity Checks if [ $(id -un) != "root" ]; then echo "ERROR: Must be run as root. Run sudo su - before running this script" exit 1 fi # # # check_rc () { if [ $1 -ne 0 ]; then echo "ERROR" exit 1 else echo "SUCCESS" fi } # # Main # # Set the Ambari server password echo -e "\n### Prompting the user for the Ambari server admin password" /usr/sbin/ambari-admin-password-reset check_rc $? # Add zeppelin to sudoers echo -e "\n### Adding the zeppelin user to sudoers: " echo "zeppelin ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers check_rc $? # Allow zeppelin to access postgres echo -e "\n### Setup postgres access for zeppelin" echo "host all all 127.0.0.1/32 md5" >> /var/lib/pgsql/data/pg_hba.conf check_rc $? # Add zeppelin to the HDFS group echo -e "\n### Adding the zeppelin user to the hdfs group" usermod -G hdfs zeppelin check_rc $? # Setup the zeppelin password file for SQOOP echo -e "\n### Creating the zeppelin password file for SQOOP" echo -n "zeppelin" > /home/zeppelin/.password hdfs dfs -put /home/zeppelin/.password /user/zeppelin/ check_rc $? rm /home/zeppelin/.password # Download the latest zeppelin notebooks echo -e "\n### Downloading and installing zeppelin notebooks" curl -sSL https://raw.githubusercontent.com/hortonworks-gallery/zeppelin-notebooks/master/update_all_notebooks.sh | sudo -u zeppelin -E sh check_rc $? # Download the latest code from the git repo echo -e "\n### Downloading the latest single view demo code" cd /home/zeppelin && sudo -u zeppelin -E git clone https://github.com/abajwa-hw/single-view-demo.git check_rc $? # Restart Ambari-agent echo -e "\n### Restarting ambari-agent" service ambari-agent stop service ambari-agent start check_rc $? # Restart postgres echo -e "\n### Restarting postgres" service postgresql stop service postgresql start check_rc $? # Configure SQOOP for Postgres echo -e "\n### Configuring SQOOP for Postgres" sudo wget https://jdbc.postgresql.org/download/postgresql-9.4.1207.jar -P /usr/hdp/current/sqoop-client/lib check_rc $? # Download the contoso dataset echo -e "\n### Downloading the contoso data set" cd /tmp && wget https://www.dropbox.com/s/r70i8j1ujx4h7j8/data.zip && unzip data.zip check_rc $? # Create the contoso database echo -e "\n### Creating Postgres database contoso" sudo -u postgres psql -c "create database contoso;" sudo -u postgres psql -c "CREATE USER zeppelin WITH PASSWORD 'zeppelin';" sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE contoso to zeppelin;" sudo -u postgres psql -c "\du" check_rc $? # Load the contoso data into Postgres echo -e "\n### Loading the contoso data into Postgres... this will take a while" export PGPASSWORD=zeppelin psql -U zeppelin -d contoso -h localhost -f /home/zeppelin/single-view-demo/contoso-psql.sql check_rc $? # Increase the amount of memory available to YARN echo -e "\n### Increasing the amount of memory allocated to YARN" /var/lib/ambari-server/resources/scripts/configs.sh -u admin -p $LAB_PW set localhost Sandbox yarn-site "yarn.nodemanager.resource.memory-mb" "8192" check_rc $? # Set hive.tez.container.size to avoid OOM echo -e "\n### Setting hive.tez.container.size to 1GB to avoid OOM" /var/lib/ambari-server/resources/scripts/configs.sh -u admin -p $LAB_PW set localhost Sandbox hive-site "hive.tez.container.size" "2048" check_rc $? # Start Hive mysql echo -e "\n### Starting up Hive's mysql instance" export SERVICE=HIVE export AMBARI_HOST=localhost export CLUSTER=Sandbox curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Start Hive via REST"}, "Body": {"ServiceInfo": {"state": "STARTED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 60 check_rc $? # Restart hive echo -e "\n### Restarting Hive for hive.tez.container.size change" export SERVICE=HIVE export AMBARI_HOST=localhost export CLUSTER=Sandbox curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Stop Hive via REST"}, "Body": {"ServiceInfo": {"state": "INSTALLED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 60 curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Start Hive via REST"}, "Body": {"ServiceInfo": {"state": "STARTED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 300 check_rc $? # Restart oozie echo -e "\n### Restarting Oozie for hive.tez.container.size change" export SERVICE=OOZIE export AMBARI_HOST=localhost export CLUSTER=Sandbox curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Stop Oozie via REST"}, "Body": {"ServiceInfo": {"state": "INSTALLED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 120 curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Start Oozie via REST"}, "Body": {"ServiceInfo": {"state": "STARTED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 60 check_rc $? # Restart yarn echo -e "\n### Restarting YARN for nodemanager memory change" export SERVICE=YARN export AMBARI_HOST=localhost export CLUSTER=Sandbox curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Stop YARN via REST"}, "Body": {"ServiceInfo": {"state": "INSTALLED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 120 curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Start YARN via REST"}, "Body": {"ServiceInfo": {"state": "STARTED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 60 check_rc $? # Restart MapReduce2 echo -e "\n### Restarting YARN for nodemanager memory change" export SERVICE=MAPREDUCE2 export AMBARI_HOST=localhost export CLUSTER=Sandbox curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Stop MapReduce2 via REST"}, "Body": {"ServiceInfo": {"state": "INSTALLED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 120 curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Start MapReduce2 via REST"}, "Body": {"ServiceInfo": {"state": "STARTED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 60 check_rc $? # Restart Tez echo -e "\n### Restarting Tez for nodemanager memory change" export SERVICE=TEZ export AMBARI_HOST=localhost export CLUSTER=Sandbox curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Stop Tez via REST"}, "Body": {"ServiceInfo": {"state": "INSTALLED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 120 curl -u admin:$LAB_PW -i -H 'X-Requested-By: ambari' -X PUT -d '{"RequestInfo": {"context" :"Start Tez via REST"}, "Body": {"ServiceInfo": {"state": "STARTED"}}}' http://$AMBARI_HOST:8080/api/v1/clusters/$CLUSTER/services/$SERVICE && sleep 60 check_rc $? exit 0
C#
UTF-8
1,046
2.75
3
[]
no_license
using System.Numerics; using Rosalind.Core.Math; using Xunit; namespace Rosalind.Solutions.Math { public class FactorialTests { [Fact] public void Simple() { Assert.Equal(1, Factorial.For(1)); Assert.Equal(2, Factorial.For(2)); Assert.Equal(120, Factorial.For(5)); Assert.Equal(2432902008176640000, Factorial.For(20)); } [Fact] public void Large() { Assert.Equal(BigInteger.Parse("15511210043330985984000000"), Factorial.For(25)); Assert.Equal(BigInteger.Parse("30414093201713378043612608166064768844377641568960512000000000000"), Factorial.For(50)); Assert.Equal(BigInteger.Parse("93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000"), Factorial.For(100)); } [Fact] public void ExceedsLongMaxValue() { Assert.True(Factorial.For(21) > long.MaxValue); } } }
Shell
UTF-8
1,276
3.1875
3
[]
no_license
### .bashrc is run when interactive bash starts. # prompt setting [[ -f $HOME/.bob-the-bash.sh ]] && source $HOME/.bob-the-bash.sh # right prompt setting function __command_rprompt() { local rprompt=$(LANG=C date +"%a %b %d %H:%M:%S %Y") # 右プロンプトに表示させる内容。今回はタイムスタンプ。 local num=$(($COLUMNS - ${#rprompt})) # 右プロンプトを表示するために必要となる幅 printf "%${num}s$rprompt\r" '' # 右プロンプトの表示(\rがないとうまく動作しないので注意) } PROMPT_COMMAND=__command_rprompt # git completion [[ -f $HOME/.git-completion.bash ]] && source $HOME/.git-completion.bash # git prompt # [[ -f $HOME/.git-prompt.sh ]] && source $HOME/.git-prompt.sh && PS1=' \w\[\033[32m\]$(__git_ps1)\[\033[00m\] \[\033[35m\]$\[\033[0m\]' # GIT_PS1_SHOWDIRTYSTATE=true # GIT_PS1_SHOWUNTRACKEDFILES=true # GIT_PS1_SHOWSTASHSTATE=true # GIT_PS1_SHOWUPSTREAM=auto # alias settings [[ -f $HOME/.aliasrc ]] && source $HOME/.aliasrc [[ -f $HOME/.kokorc ]] && [[ $(whoami) == "Kokorin" ]] && source $HOME/.kokorc [[ -f $HOME/.taiharc ]] && [[ $(whoami) == "taihara" || $(whoami) = "Aihara" ]] && source $HOME/.taiharc alias -- -='cd -' # enable autocd [[ $BASH_VERSINFO -ge 4 ]] && shopt -s autocd