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
Python
UTF-8
2,198
3.53125
4
[ "BSD-3-Clause" ]
permissive
# $begin two_levels.py$$ $newlinech #$$ # # $section Using Two Levels of AD: Example and Test$$ # # $index a2float$$ # $index two, AD levels$$ # $index levels, two AD$$ # $index AD, two levels$$ # # $head Purpose$$ # This example is intended to demonstrate how # $code a_float$$ and $code a2float$$ # can be used together to compute derivatives of functions that are # defined in terms of derivatives of other functions. # # $head F(u)$$ # For this example, the function $latex F : \B{R}^2 \rightarrow \B{R}$$ # is defined by # $latex \[ # F(u) = u_0^2 + u_1^2 # \] $$ # It follows that # $latex \[ # \begin{array}{rcl} # \partial_{u(0)} F(u) = 2 * u_0 \\ # \partial_{u(1)} F(u) = 2 * u_1 # \end{array} # \] $$ # # $head G(x)$$ # For this example, the function $latex G : \B{R}^2 \rightarrow \B{R}$$ is # defined by # $latex \[ # G(x) = x_1 * \partial_{u(0)} F(x_0 , 1) + x_0 * \partial_{u(1)} F(x_0, 1) # \] $$ # where $latex \partial{u(j)} F(a, b)$$ denotes the partial of $latex F$$ # with respect to $latex u_j$$ and evaluated at $latex u = (a, b)$$. # It follows that # $latex \[ # \begin{array}{rcl} # G (x) & = & 2 * x_1 * x_0 + 2 * x_0 \\ # \partial_{x(0)} G (x) & = & 2 * x_1 + 2 \\ # \partial_{x(1)} G (x) & = & 2 * x_0 # \end{array} # \] $$ # # $code # $verbatim%example/two_levels.py%0%# BEGIN CODE%# END CODE%1%$$ # $$ # $end # BEGIN CODE from pycppad import * def pycppad_test_two_levels(): # start recording a_float operations x = numpy.array( [ 2. , 3. ] ) a_x = independent(x) # start recording a2float operations a_u = numpy.array( [a_x[0] , ad(1) ] ) a2u = independent(a_u) # stop a2float recording and store operations if f a2v = numpy.array( [ a2u[0] * a2u[0] + a2u[1] * a2u[1] ] ) a_f = adfun(a2u, a2v) # F(u0, u1) = u0 * u0 + u1 * u1 # evaluate the gradient of F a_J = a_f.jacobian(a_u) # stop a_float recording and store operations in g a_y = numpy.array( [ a_x[1] * a_J[0,0] + a_x[0] * a_J[0,1] ] ) g = adfun(a_x, a_y) # G(x0, x1) = x1 * F_u0(x0, 1) + x0 * F_u1(x0, 1) # evaluate the gradient of G J = g.jacobian(x) assert J[0,0] == 2. * x[1] + 2 assert J[0,1] == 2. * x[0] # END CODE
PHP
UTF-8
206
3.625
4
[]
no_license
<html> <head> <title> Example 4-13.The equality and identity operators</title> </head> <body> <?php $a = "1000"; $b = "+1000"; if ($a == $b) echo "1"; if ($a === $b) echo "2"; ?> </body> </html>
Java
ISO-8859-1
1,353
2.4375
2
[]
no_license
package fr.sywoo.customsettings.listener.server; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import com.wasteofplastic.askyblock.ASkyBlockAPI; import fr.sywoo.customsettings.player.IslandsSettings; public class CommandsIntercepter implements Listener { @EventHandler public void onCommand(PlayerCommandPreprocessEvent event){ Player player = event.getPlayer(); String command = event.getMessage(); if(command.contains("/akyblock:settings")){ event.setCancelled(true); return; } if(command.contains("/island settings") || command.contains("/is settings")){ event.setCancelled(true); if(ASkyBlockAPI.getInstance().getIslandAt(player.getLocation()) == null){ player.sendMessage("cVeuillez faire ca sur votre Ile !"); return; } if(!ASkyBlockAPI.getInstance().hasIsland(player.getUniqueId())){ player.sendMessage("cVous n'tes propritaire d'aucune ile !"); return; } if(ASkyBlockAPI.getInstance().getIslandAt(player.getLocation()).getMembers().contains(player.getUniqueId())){ player.openInventory(IslandsSettings.getInfos(player).inventory()); }else{ player.sendMessage("cVous devez tre sur votre ile !"); return; } } } }
C#
UTF-8
1,906
3.375
3
[]
no_license
using System; namespace Lab12_Roshambo_Game { class RoshamboApp { static void Main(string[] args) { Player randomPlayer = new RandomRoshamboPlayer("Rando"); Player rockPlayer = new RockPlayer("Brick"); int userScore = 0; Console.WriteLine("Please enter your username!"); Player user = new UserPlayer(Console.ReadLine()); Console.WriteLine($"{user.Name} please pick your opponent - \"{randomPlayer.Name}\" or \"{rockPlayer.Name}\"!"); bool validinput = false; Player opponent = null; while (!validinput) { string opponentChoice = Console.ReadLine().ToLower(); if (opponentChoice == randomPlayer.Name.ToLower()) { opponent = randomPlayer; validinput = true; } else if (opponentChoice == rockPlayer.Name.ToLower()) { opponent = rockPlayer; validinput = true; } else { Console.WriteLine("Not a valid opponent... Try a real player!"); } } bool repeat = true; int games = 0; while (repeat) { games++; user.GenerateRoshambo(); opponent.GenerateRoshambo(); Console.WriteLine(user); Console.WriteLine(opponent); userScore = Player.Shoot(user.Choice, opponent.Choice, userScore, user.Name); Console.WriteLine($"{user.Name} you have won {userScore} games out of {games}!"); Console.Write("Would you like to play again? (Y/N?): "); repeat = Validator.GetYesorNo(); } } } }
C#
UTF-8
1,120
2.875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Models; using Data.Context; namespace Data.Repository { class SportRepository:IRepository<Sport> { private ToteContext db; public SportRepository(ToteContext context) { this.db = context; } public IEnumerable<Sport> GetAll() { return db.Sports; } public Sport Get(int id) { var selectedSport = from sport in db.Sports where sport.SportId == id select sport; return selectedSport.First(); } public void Create(Sport sport) { db.Sports.Add(sport); } public void Update(Sport sport) { } public IEnumerable<Sport> Find(Func<Sport, Boolean> predicate) { return db.Sports.Where(predicate).ToList(); } public void Delete(int id) { } } }
C++
UTF-8
843
2.78125
3
[]
no_license
#include <iostream> #include "../library/lib.hpp" class BPingvinPoloIMatrica { public: void solve(std::istream& in, std::ostream& out) { ll n = read_ll(); ll m = read_ll(); ll d = read_ll(); vll vec = read_vll(m * n); sort(all(vec)); ll first = vec[0]; forn(i, n * m) { vec[i] -= first; if(vec[i] % d) { print -1; return; } else { vec[i] /= d; } } ll ans = 0; if(vec.size() % 2 == 1) { ll median = vec[vec.size() / 2]; forn(i, n * m) ans += abs(vec[i] - median); } else { ll median1 = vec[vec.size() / 2 - 1]; ll median2 = vec[vec.size() / 2]; forn(i, n * m / 2) ans += abs(vec[i] - median1); for(int i = n * m / 2; i < n * m; i++) ans += abs(vec[i] - median2); ans += (median2 - median1) * n * m / 2; } print ans; } };
C++
UTF-8
584
2.84375
3
[]
no_license
#ifndef __COMPLEXOBJECT_H__ #define __COMPLEXOBJECT_H__ #include "simpleObject.h" /** * A complexObject is a simpleObject with mass & density... */ class complexObject : public simpleObject { public: complexObject(int x, int y, int z, int width, int height, int mass, float density); ~complexObject(); /* override simpleObjects display_info() function */ void display_info(FILE* ofp, const char* sMsg) const; int get_mass() const; float get_density() const; protected: int m_mass; // Objects mass in lbs float m_density; // Objects density }; #endif
Java
UTF-8
573
2.125
2
[ "Apache-2.0" ]
permissive
package io.quarkus.runtime.annotations; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicates that a config item should be converted using a default converter: built-in/implicit converters or a custom * converter. */ @Retention(RUNTIME) @Target({ FIELD, PARAMETER }) @Documented public @interface DefaultConverter { }
C++
UTF-8
15,315
3.046875
3
[]
no_license
#include <iostream> #include <vector> #include <queue> #include <string> #include <tuple> #include <unordered_map> #include <numeric> #include <algorithm> #include <cassert> template<class BiIter> bool next_combination_idx(int n, BiIter comb_first, BiIter comb_last) { int k = std::distance(comb_first, comb_last); assert(n >= k && k > 0); // Obviously if k==0 there is no next combination BiIter cur_pos = comb_last; --cur_pos; int chg_max = n - 1; while (true) { auto cur_idx = *cur_pos + 1; if (chg_max >= cur_idx) { while (cur_pos != comb_last) *cur_pos++ = cur_idx++; return true; } else { if (cur_pos != comb_first) { --cur_pos; --chg_max; } else return false; } } } std::vector<std::vector<int>> get_all_combs_idx(int n, int k) { std::vector<std::vector<int>> all_combs; std::vector<int> cur_comb(k); std::iota(cur_comb.begin(), cur_comb.end(), 0); do { all_combs.push_back(cur_comb); } while (next_combination_idx(n, cur_comb.begin(), cur_comb.end())); return all_combs; } std::vector<std::vector<int>> get_multi_comb_idx_bits(int *grp_cnts, int num_grps, int combo_cnt) { std::vector<std::vector<int>> results; if (num_grps == 1) { if (combo_cnt == 0) results.push_back(std::vector<int>(1, 0)); else if (grp_cnts[0] >= combo_cnt) { for (auto& vi : get_all_combs_idx(grp_cnts[0], combo_cnt)) { int this_grp_comb = 0; for (int i : vi) this_grp_comb |= (1 << i); results.push_back(std::vector<int>(1, this_grp_comb)); } } } else if (combo_cnt == 0) { std::vector<int> temp; for (int i = 0; i < num_grps; ++i) temp.push_back(0); results.push_back(std::move(temp)); return results; } else { for (int i = std::min(combo_cnt, grp_cnts[0]); i >= 0; --i) { std::vector<std::vector<int>> comb_0; if (i == 0) comb_0.push_back(std::vector<int>()); else comb_0 = std::move(get_all_combs_idx(grp_cnts[0], i)); for (auto& c : comb_0) { int grp_cnt_0 = 0; for (int i : c) grp_cnt_0 |= (1 << i); for (auto& vi : get_multi_comb_idx_bits(grp_cnts + 1, num_grps - 1, combo_cnt - i)) { vi.insert(vi.begin(), grp_cnt_0); results.push_back(std::move(vi)); } } } } return results; } // Both DFS and BFS give out correct answer 20, but, // DFS has only 30 solutions, while BFS has 8100! // Make sure to have the 2 tables sorted first! //const std::vector<int> missionaries{ 4, 5, 6 }; //const std::vector<int> cannibals{ 1, 2, 3 }; //const int boat_volume = 2; // Both DFS and BFS give out correct answer 20, but, // DFS has only 30 solutions, while BFS has 8100! // Make sure to have the 2 tables sorted first! const std::vector<int> missionaries{ 4, 5, 6 }; const std::vector<int> cannibals{ 1, 2, 3 }; const int boat_volume = 2; // Both DFS and BFS give out correct answer 28, but, DFS solutions // increased to 264, while BFS solutions jumped to 944784! So it will // take tons of time even to print all these solutions. //const std::vector<int> missionaries{ 4, 5, 6, 7 }; //const std::vector<int> cannibals{ 2, 3, 5 }; //const int boat_volume = 2; // There is no solution when M=C=4 and boat_volume=2 //const std::vector<int> missionaries{ 6, 8, 10, 12 }; //const std::vector<int> cannibals{ 3, 5, 7, 9 }; //const int boat_volume = 2; // Best time 11, 368 DFS solutions. //const std::vector<int> missionaries{ 2, 4, 5, 6 }; //const std::vector<int> cannibals{ 1, 2, 3, 4 }; //const int boat_volume = 3; // Total 1584 DFS solutions, best time 15 //const std::vector<int> missionaries{ 2, 4, 5, 6, 8 }; //const std::vector<int> cannibals{ 1, 2, 3, 4, 5 }; //const int boat_volume = 3; // Total 73086 DFS solutions, best time 9, one of the best solution is: // m2m4c1c2-> m2c1<- m2m5c1c3-> m2c1<- m2m5c1c4-> m5c1<- m6m8c1c5-> m6c1<- m5m6c1c6-> //const std::vector<int> missionaries{ 2, 4, 5, 5, 6, 8 }; //const std::vector<int> cannibals{ 1, 2, 3, 4, 5, 6 }; //const int boat_volume = 4; // Best time 11, Best solution: m2m4c1c2-> m2c1<- m2m5c1c3-> m2c1<- // m2m5c1c4-> m2c1<- m2m6c1c5-> m2c1<- m2m8m9c1-> c1<- c1c6c7-> // Try this with some patience. //const std::vector<int> missionaries{ 2, 4, 5, 5, 6, 8, 9 }; //const std::vector<int> cannibals{ 1, 2, 3, 4, 5, 6, 7 }; //const int boat_volume = 4; struct state { unsigned int mLeft; unsigned int cLeft; unsigned int mRight; unsigned int cRight; bool boat_side; // boat's side, false for left side, true for right side std::string movs; // the moves till this state int time; // the time till this state state(unsigned int mL, unsigned int cL, unsigned int mR, unsigned int cR, bool side, std::string mv, int tm) : mLeft(mL), cLeft(cL), mRight(mR), cRight(cR), boat_side(side), movs(mv), time(tm) {}; }; typedef std::unordered_map<unsigned long long, int> UsedStateTable; const int INTEGER_BITS = sizeof(int)* 8;// Total bits in an integer, maximum elements in an integer should be INTEGER_BITS-1 static int g_Missionary_N; // number of missionaries static int g_Cannibal_N; // number of cannibals, this may be less than the missionaries static int g_BestTime = std::numeric_limits<int>::max(); static std::string g_BestSolution; unsigned char BIT_CNT[256]; // number of ones in a char, used to check ones in integers quickly inline void init_bit_cnt_table(unsigned char table[]) // initialize bit-count table { unsigned char bit_cnt_4bits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; for (int i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) table[i * 16 + j] = bit_cnt_4bits[i] + bit_cnt_4bits[j]; } inline int count_ones(unsigned int x) // count the ones in an unsigned integer { int total_bits = 0; for (unsigned int i = 0; i < sizeof(int); ++i) { total_bits += BIT_CNT[x & 0xff]; x >>= 8; } return total_bits; } inline bool is_safe_mov(int nml, int ncl, int nmr, int ncr) // check if a move safe or not { return (!nml || nml >= ncl) && (!nmr || nmr >= ncr); } inline bool solution_found(const state& st, int boat_volume) // check if we have found a solution { return (count_ones(st.mLeft)+count_ones(st.cLeft) <= boat_volume) && (st.boat_side == false); } // By checking bit_order, convert the bit index into real order in missionary or cannibal table index std::vector<int> bit_index_to_real_index(unsigned int bit_order, int max_bits, int bit_index) { std::vector<int> result; std::vector<int> int_index; // change bit_index's bit index into integer index to lookup the bit_order unsigned int bit_mask = 1; unsigned int max_bit_mask = (1 << max_bits); int bit_pos = 0; while (bit_mask < max_bit_mask) { if (bit_mask & bit_index) int_index.push_back(bit_pos); bit_mask <<= 1; ++bit_pos; } bit_mask = 1; bit_pos = 0; unsigned int cnt = 0; int bit_idx_cnt = -1; while (cnt < int_index.size()) { int idx = int_index[cnt]; while (bit_mask < max_bit_mask) { if (bit_mask & bit_order) { ++bit_idx_cnt; if (bit_idx_cnt == idx) { result.push_back(bit_pos); bit_mask <<= 1; ++bit_pos; break; } } bit_mask <<= 1; ++bit_pos; } ++cnt; } return result; } // Filter unsafe next states and get all safe next states // If a state is previously visited and has shorter time, it will also be filtered out std::vector<state> get_safe_movs(const state& st, int boat_volume, const UsedStateTable& used_states) { std::vector<state> results; std::vector<std::vector<int>> possible_combos; int grps[2]; grps[0] = st.boat_side ? count_ones(st.mRight) : count_ones(st.mLeft); grps[1] = st.boat_side ? count_ones(st.cRight) : count_ones(st.cLeft); if (st.boat_side) // Search strategy, if the boat is at the other side, choose fewer people first { for (int i = 1; i <= boat_volume; ++i) for (auto& gc : get_multi_comb_idx_bits(grps, 2, i)) possible_combos.push_back(std::move(gc)); } else // Search strategy, try to take as many as possible people to the other side first { for (int i = boat_volume; i >= 1; --i) for (auto& gc : get_multi_comb_idx_bits(grps, 2, i)) possible_combos.push_back(std::move(gc)); } for (auto& pc : possible_combos) { unsigned int ml = st.mLeft; unsigned int cl = st.cLeft; unsigned int mr = st.mRight; unsigned int cr = st.cRight; unsigned int & m_from = st.boat_side ? mr : ml; unsigned int & m_to = st.boat_side ? ml : mr; unsigned int & c_from = st.boat_side ? cr : cl; unsigned int & c_to = st.boat_side ? cl : cr; int min_m_time = std::numeric_limits<int>::max(); int min_c_time = std::numeric_limits<int>::max(); std::vector<int> m_bit_index = std::move(bit_index_to_real_index(m_from, g_Missionary_N, pc[0])); std::vector<int> c_bit_index = std::move(bit_index_to_real_index(c_from, g_Cannibal_N, pc[1])); if (!m_bit_index.empty()) min_m_time = missionaries[m_bit_index[0]]; //because missionaries and m_bit_index are all sorted, so the first is the shortest in time if (!c_bit_index.empty()) min_c_time = cannibals[c_bit_index[0]]; for (int i : m_bit_index) // move the missionaries from this state to next state { m_from &= (~(1<<i)); m_to |= (1 << i); } for (int i : c_bit_index) // move the cannibals from this state to next state { c_from &= (~(1 << i)); c_to |= (1 << i); } // check if this next state is safe or not if (!is_safe_mov(count_ones(ml), count_ones(cl), count_ones(mr), count_ones(cr))) continue; bool found = false; unsigned long long key = ml; // construct HashKey key <<= INTEGER_BITS; key |= ((cl << 1) | (st.boat_side ? 0 : 0x1)); // Note that boat_side is inverted here! auto iter = used_states.find(key); if (iter != used_states.end()) { if (st.time + std::min(min_m_time, min_c_time) >= iter->second) found = true; } if (!found) { std::string mov(" "); for (int i : m_bit_index) mov = mov + 'm' + std::to_string(missionaries[i]); for (int i : c_bit_index) mov = mov + 'c' + std::to_string(cannibals[i]); results.emplace_back(ml, cl, mr, cr, !st.boat_side, st.movs + mov + (st.boat_side ? "<- " : "-> "), st.time + std::min(min_m_time, min_c_time)); } } return results; } void find_solution_dfs(const state& cur_st, int boat_volume, UsedStateTable& used_states) { if (solution_found(cur_st, boat_volume)) { int min_m_time = std::numeric_limits<int>::max(); int min_c_time = std::numeric_limits<int>::max(); std::string s = cur_st.movs + " "; for (int i = 0; i < g_Missionary_N; ++i) { if (cur_st.mLeft & (1 << i)) { int time = missionaries[i]; s = s + 'm' + std::to_string(time); if (time < min_m_time) min_m_time = time; } } for (int i = 0; i < g_Cannibal_N; ++i) { if (cur_st.cLeft & (1 << i)) { int time = cannibals[i]; s = s + 'c' + std::to_string(time); if (time < min_c_time) min_c_time = time; } } int cur_time = cur_st.time + std::min(min_m_time, min_c_time); if (cur_time < g_BestTime) { g_BestTime = cur_time; g_BestSolution = s + "->"; } } else { bool found = false; unsigned long long key = cur_st.mLeft; key <<= INTEGER_BITS; key |= ((cur_st.cLeft << 1) | (cur_st.boat_side ? 0x1 : 0)); auto iter = used_states.find(key); if(iter != used_states.end()) { if (cur_st.time < iter->second) iter->second = cur_st.time; found = true; } if (!found) used_states.emplace(key, cur_st.time); for (auto& gsm : get_safe_movs(cur_st, boat_volume, used_states)) find_solution_dfs(gsm, boat_volume, used_states); } } void find_solution_bfs(std::queue<state>& cur_states, int boat_volume, UsedStateTable& used_states) { while (!cur_states.empty()) { state st = cur_states.front(); cur_states.pop(); bool found = false; unsigned long long key = st.mLeft; key <<= INTEGER_BITS; key |= ((st.cLeft << 1) | (st.boat_side ? 0x1 : 0)); auto iter = used_states.find(key); if (iter != used_states.end()) { if (st.time < iter->second) iter->second = st.time; found = true; } if (!found) used_states.emplace(key, st.time); for (auto& gc : get_safe_movs(st, boat_volume, used_states)) { if (gc.time >= g_BestTime) continue; if (solution_found(gc, boat_volume)) { int min_m_time = std::numeric_limits<int>::max(); int min_c_time = std::numeric_limits<int>::max(); std::string s = gc.movs + " "; for (int i = 0; i < g_Missionary_N; ++i) { if (gc.mLeft & (1 << i)) { int time = missionaries[i]; s = s + 'm' + std::to_string(time); if (time < min_m_time) min_m_time = time; } } for (int i = 0; i < g_Cannibal_N; ++i) { if (gc.cLeft & (1 << i)) { int time = cannibals[i]; s = s + 'c' + std::to_string(time); if (time < min_c_time) min_c_time = time; } } int cur_time = gc.time + std::min(min_m_time, min_c_time); if (cur_time < g_BestTime) { g_BestTime = cur_time; g_BestSolution = s + "->"; } } else cur_states.push(std::move(gc)); } } } int main(void) { for (auto& vi : get_all_combs_idx(5, 3)) { for (auto i : vi) std::cout << i << ", "; std::cout << std::endl; } int grp_cnts[] = { 3, 2, 2 }; std::vector<std::vector<int>> multi_idxs_bits = get_multi_comb_idx_bits(grp_cnts, 3, 3); for (auto& vi : multi_idxs_bits) { for (auto i : vi) { std::cout << "[ "; for (unsigned int idx = 0; idx<8 * sizeof(int); ++idx) if (i & (1 << idx)) std::cout << idx << " "; std::cout << "]; "; } std::cout << std::endl; } std::cout << std::endl; // Some initialization init_bit_cnt_table(BIT_CNT); g_Missionary_N = missionaries.size(); g_Cannibal_N = cannibals.size(); std::cout << std::endl << "******************** DFS algorithm *********************" << std::endl << std::endl; UsedStateTable used_states; find_solution_dfs(state((1<<missionaries.size())-1, (1<<cannibals.size())-1, 0, 0, false, "", 0), boat_volume, used_states); if (g_BestTime != std::numeric_limits<int>::max()) std::cout << "The best DFS time is: " << g_BestTime << ", DFS solution is: " << g_BestSolution << std::endl; else std::cout << "No solution" << std::endl; /* std::cout << std::endl << "******************** BFS algorithm *********************" << std::endl << std::endl; g_BestTime = std::numeric_limits<int>::max(); g_BestSolution = ""; std::queue<state> q_states; used_states.clear(); q_states.push(state((1<<missionaries.size())-1, (1<<cannibals.size())-1, 0, 0, false, "", 0)); find_solution_bfs(q_states, boat_volume, used_states); if (g_BestTime != std::numeric_limits<int>::max()) std::cout << "The best BFS time is: " << g_BestTime << ", BFS solution is: " << g_BestSolution << std::endl; else std::cout << "No solution" << std::endl; */ return 0; }
Swift
UTF-8
1,223
2.828125
3
[]
no_license
// // VideoPlayerContainerView.swift // SwiftUIVideo // // Created by Gray Campbell on 5/3/20. // Copyright © 2020 Gray Campbell. All rights reserved. // import AVKit import SwiftUI struct VideoPlayerContainerView: View { @ObservedObject var viewModel: VideoViewModel var body: some View { ZStack { if self.viewModel.isExpanded { Color.black .edgesIgnoringSafeArea(.all) } else { Color.black } VideoPlayerView(player: self.viewModel.player) .aspectRatio(1242.0 / 529.0, contentMode: .fit) VideoPlayerControlsView(viewModel: self.viewModel) .opacity(self.viewModel.isShowingControls ? 1 : 0) .animation(.easeInOut) } .onTapGesture(perform: self.toggleControls) } private func toggleControls() { self.viewModel.isShowingControls.toggle() self.viewModel.startControlTimer() } } struct VideoPlayerContainerView_Previews: PreviewProvider { static var previews: some View { VideoPlayerContainerView(viewModel: VideoViewModel(video: Video.sintel)) } }
Java
UTF-8
1,047
2.421875
2
[]
no_license
package org.usfirst.frc.team5010.auto.modes; import org.usfirst.frc.team5010.auto.steps.AutonDriveForwardForTime; import org.usfirst.frc.team5010.auto.steps.MoveArm; import org.usfirst.frc.team5010.boulder.BoulderHandler; import org.usfirst.frc.team5010.drivetrain.DriveTrainManager; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.interfaces.Gyro; public class LowBarMode extends SuperAutonMode implements AutoModeInterface { private Gyro headingGyro = null; public LowBarMode() { headingGyro = new ADXRS450_Gyro(); } @Override public void initAuton(DriveTrainManager driveTrain, BoulderHandler boulderHandler) { numberOfSteps = 3; currentStepIndex = 0; super.initAuton(driveTrain, boulderHandler); steps[0] = new MoveArm(boulderHandler, true); steps[1] = new MoveArm(boulderHandler, false); steps[2] = new AutonDriveForwardForTime(driveTrain, headingGyro, 6000); steps[0].startStep(); } @Override public void run() { super.run(); } }
PHP
UTF-8
9,072
3.046875
3
[]
no_license
<?php /* Created by : Rhalf Wendel D Caacbay Created on : 20170430 Modified by : # Modified on : # functions : Defines the class area and supplies the requests such as select, insert, update & delete. */ class Area implements IQuery { public $id; public $name; public $desc; public $coordinates; public $speedMinL; public $speedMaxL; public $speedMinH; public $speedMaxH; public $isVisible; public $nation; public function __construct() { } public static function selectAll() { $connection = Flight::dbMain(); try { $sql = "SELECT * FROM area;"; $query = $connection->prepare($sql); $query->execute(); $rows = $query->fetchAll(PDO::FETCH_ASSOC); $result = array(); foreach ($rows as $row) { $area = new Area(); $area->id = (int) $row['id']; $area->name = $row['area_name']; $area->desc = $row['area_desc']; $area->coordinates = json_decode($row['area_coordinates']); $area->speedMinL = (int) $row['area_speed_min_l']; $area->speedMaxL = (int) $row['area_speed_max_l']; $area->speedMinH = (int) $row['area_speed_min_h']; $area->speedMaxH = (int) $row['area_speed_max_h']; $area->isVisible = (bool) $row['area_is_visible']; $area->nation = nation::select($row['e_nation_id']); array_push($result, $area); } return $result; } catch (PDOException $pdoException) { throw $pdoException; } catch (Exception $exception) { throw $exception; } finally { $connection = null; } } public static function select($id) { $connection = Flight::dbMain(); try { $sql = "SELECT * FROM area WHERE id = :id;"; $query = $connection->prepare($sql); $query->bindParam(':id',$id, PDO::PARAM_INT); $query->execute(); if ($query->rowCount() < 1){ return null; } $row = $query->fetch(PDO::FETCH_ASSOC); $area = new Area(); $area->id = (int) $row['id']; $area->name = $row['area_name']; $area->desc = $row['area_desc']; $area->coordinates = json_decode($row['area_coordinates']); $area->speedMinL = (int) $row['area_speed_min_l']; $area->speedMaxL = (int) $row['area_speed_max_l']; $area->speedMinH = (int) $row['area_speed_min_h']; $area->speedMaxH = (int) $row['area_speed_max_h']; $area->isVisible = (bool) $row['area_is_visible']; $area->nation = nation::select($row['e_nation_id']); return $area; } catch (PDOException $pdoException) { throw $pdoException; } catch (Exception $exception) { throw $exception; } finally { $connection = null; } } public static function selectBynation($id) { $connection = Flight::dbMain(); try { $sql = "SELECT * FROM area WHERE e_nation_id = :e_nation_id;"; $query = $connection->prepare($sql); $query->bindParam(':e_nation_id',$id, PDO::PARAM_INT); $query->execute(); $rows = $query->fetchAll(PDO::FETCH_ASSOC); $result = array(); foreach ($rows as $row) { $area = new Area(); $area->id = (int) $row['id']; $area->name = $row['area_name']; $area->desc = $row['area_desc']; $area->coordinates = json_decode($row['area_coordinates']); $area->speedMinL = (int) $row['area_speed_min_l']; $area->speedMaxL = (int) $row['area_speed_max_l']; $area->speedMinH = (int) $row['area_speed_min_h']; $area->speedMaxH = (int) $row['area_speed_max_h']; $area->isVisible = (bool) $row['area_is_visible']; $area->nation = nation::select($row['e_nation_id']); array_push($result, $area); } return $result; } catch (PDOException $pdoException) { throw $pdoException; } catch (Exception $exception) { throw $exception; } finally { $connection = null; } } public static function insert() { $connection = Flight::dbMain(); try { $area = json_decode(file_get_contents("php://input")); if ($area == null) { throw new Exception(json_get_error()); } $sql = " INSERT INTO area ( area_name, area_desc, area_coordinates, area_speed_min_l, area_speed_max_l, area_speed_min_h, area_speed_max_h, area_is_visible, e_nation_id) VALUES ( :area_name, :area_desc, :area_coordinates, :area_speed_min_l, :area_speed_max_l, :area_speed_min_h, :area_speed_max_h, :area_is_visible, :e_nation_id );"; $query = $connection->prepare($sql); $query->bindParam(':area_name', $area->name, PDO::PARAM_STR); $query->bindParam(':area_desc', $area->desc, PDO::PARAM_STR); $json = json_encode($area->coordinates); $query->bindParam(':area_coordinates', $json, PDO::PARAM_STR); $query->bindParam(':area_speed_min_l', $area->speedMinL, PDO::PARAM_INT); $query->bindParam(':area_speed_max_l', $area->speedMaxL, PDO::PARAM_INT); $query->bindParam(':area_speed_min_h', $area->speedMinH, PDO::PARAM_INT); $query->bindParam(':area_speed_max_h', $area->speedMaxH, PDO::PARAM_INT); $query->bindParam(':area_is_visible', $area->isVisible, PDO::PARAM_BOOL); $query->bindParam(':e_nation_id', $area->nation->id, PDO::PARAM_INT); $query->execute(); $result = new Result(); $result->status = Result::INSERTED; $result->id = $connection->lastInsertid(); $result->message = 'Done'; return $result; } catch (PDOException $pdoException) { throw $pdoException; } catch (Exception $exception) { throw $exception; } finally { $connection = null; } } public static function update($id) { $connection = Flight::dbMain(); try { $area = json_decode(file_get_contents("php://input")); if ($area == null) { throw new Exception(json_get_error()); } $sql = " UPDATE area SET area_name = :area_name, area_desc = :area_desc, area_coordinates = :area_coordinates, area_speed_min_l = :area_speed_min_l, area_speed_max_l = :area_speed_max_l, area_speed_min_h = :area_speed_min_h, area_speed_max_h = :area_speed_max_h, area_is_visible = :area_is_visible, e_nation_id = :e_nation_id WHERE id = :id;"; $query = $connection->prepare($sql); $query->bindParam(':area_name', $area->name, PDO::PARAM_STR); $query->bindParam(':area_desc', $area->desc, PDO::PARAM_STR); $json = json_encode($area->coordinates); $query->bindParam(':area_coordinates', $json, PDO::PARAM_STR); $query->bindParam(':area_speed_min_l', $area->speedMinL, PDO::PARAM_INT); $query->bindParam(':area_speed_max_l', $area->speedMaxL, PDO::PARAM_INT); $query->bindParam(':area_speed_min_h', $area->speedMinH, PDO::PARAM_INT); $query->bindParam(':area_speed_max_h', $area->speedMaxH, PDO::PARAM_INT); $query->bindParam(':area_is_visible', $area->isVisible, PDO::PARAM_BOOL); $query->bindParam(':e_nation_id', $area->nation->id, PDO::PARAM_INT); $query->bindParam(':id', $id, PDO::PARAM_INT); $query->execute(); $result = new Result(); $result->status = Result::UPDATED; $result->id = $id; $result->message = 'Done.'; return $result; } catch (PDOException $pdoException) { throw $pdoException; } catch (Exception $exception) { throw $exception; } finally { $connection = null; } } public static function delete($id) { $connection = Flight::dbMain(); try { $sql = " DELETE FROM area WHERE id = :id"; $query = $connection->prepare($sql); $query->bindParam(':id', $id, PDO::PARAM_INT); $query->execute(); $result = new Result(); $result->status = Result::DELETED; $result->message = 'Done'; $result->id = $id; return $result; } catch (PDOException $pdoException) { throw $pdoException; } catch (Exception $exception) { throw $exception; } finally { $connection = null; } } public static function selectByUnitData($areas, $unitData){ $coordinate = $unitData->gps->coordinate; $result = null; //$result = array(); foreach ($areas as $index => $area) { if(Area::checkPoint($area, $coordinate) == true) { //array_push($result, $area); $result = $area->id; } } return $result; } private static function checkPoint($area, $coordinate) { $coordinates = $area->coordinates; $count = sizeof($area->coordinates); $result = false; for ($index1 = 0, $index2 = $count - 1; $index1 < $count; $index2 = $index1++) { if (((($coordinates[$index1]->latitude <= $coordinate->latitude) && ($coordinate->latitude < $coordinates[$index2]->latitude)) || (($coordinates[$index2]->latitude <= $coordinate->latitude) && ($coordinate->latitude < $coordinates[$index1]->latitude))) && ($coordinate->longitude < ($coordinates[$index2]->longitude - $coordinates[$index1]->longitude) * ($coordinate->latitude - $coordinates[$index1]->latitude) / ($coordinates[$index2]->latitude - $coordinates[$index1]->latitude) + $coordinates[$index1]->longitude)) { $result = !$result; } } return $result; } } ?>
C++
UTF-8
2,216
2.546875
3
[]
no_license
// Copyright (C) 2010 Alessandro Bruni // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301, USA. #ifndef DWT_H #define DWT_H #include "Bitmap.cpp" #include <string> using namespace std; /** * Applies the Discrete Wavelet Transformation to compress bitmap images. * Uses arbitrary quantization to 8-16bits per coefficient and compresses * the output using Huffman + RLE (only on zeros). * File format: * | Header | Payload | * * Header: | AB | bpp | width | height | Huffman tree | * AB: magic number * bpp: bits per pixel * width: real width of the original image * height: real height of the original image * Huffman tree: the tree used to decode Huffman encoded coefficents * * Payload: 0 + Huffman encoded coefficent | 1 0 + RLE 3 bits | 1 1 + RLE 8 bits */ class DWT { private: static const char magic[2]; // Matrix of coefficients float *coeff; // Quantization coefficient unsigned int bpp; // Padded width and height unsigned int width; unsigned int height; // Real width and height of the image unsigned int realWidth; unsigned int realHeight; unsigned char nrm(int val); unsigned int range(float val); void transform1d(float *src, unsigned int length, unsigned int step, float *tmp); void untransform1d(float *src, unsigned int length, unsigned int step, float *tmp); public: DWT(unsigned int bpp); DWT(Bitmap *input, unsigned int bpp); ~DWT(); void transform(); void untrasform(); Bitmap *toBitmap(); void save(const string &fileName); void load(const string &fileName); }; #endif
Java
UTF-8
5,960
1.929688
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package TransferManagement; import DepositEntity.Session.TransferSessionBeanLocal; import Exception.TransferException; import Exception.UserHasNoSavingAccountException; import TellerManagedBean.ServiceCustomerManagedBean; import java.io.IOException; import java.io.Serializable; import java.math.BigDecimal; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.inject.Named; import javax.enterprise.context.Dependent; import javax.enterprise.context.SessionScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.inject.Inject; import org.primefaces.context.RequestContext; /** * * @author Bella */ @Named(value = "transferManagedBean") @SessionScoped public class TransferManagedBean implements Serializable { @EJB TransferSessionBeanLocal tfsb; @Inject private ServiceCustomerManagedBean serviceCustomerManagedBean; private List<Long> savingAccountList; private String recipientName; private String amountString; private BigDecimal amountBD; private Long recipientAccountNumLong; private String recipientAccountNumString; private Long giverAccountNumLong; private Long customerID; @PostConstruct public void init() { } public TransferManagedBean() { } public void dashboardToIntraTransfer(ActionEvent event) { try { customerID = serviceCustomerManagedBean.getCustomer().getId(); if (customerID != null) { setCustomerID(serviceCustomerManagedBean.getCustomer().getId()); this.getSavingAccountNumbers(); FacesContext.getCurrentInstance().getExternalContext() .redirect("/MerlionBankBackOffice/TransferManagement/intraTransfer.xhtml"); } else { FacesMessage sysMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "System Message", "Please select a customer first!"); RequestContext.getCurrentInstance().showMessageInDialog(sysMessage); } } catch (Exception e) { System.out.print("Dashboard go to intra transfer encounter error!"); } } public void getSavingAccountNumbers() throws IOException, UserHasNoSavingAccountException { try { savingAccountList = tfsb.getSavingAccountNumbers(customerID); } catch (UserHasNoSavingAccountException ex) { System.out.print("User Has No Saving Account"); } } public void oneTimeTransfer(ActionEvent event) throws TransferException, IOException { try { if (giverAccountNumLong != null) { amountBD = new BigDecimal(amountString); recipientAccountNumLong = Long.parseLong(recipientAccountNumString); System.out.print(amountBD); System.out.print(recipientAccountNumLong); tfsb.intraOneTimeTransferCheck(customerID, giverAccountNumLong, recipientAccountNumLong, amountBD); FacesContext.getCurrentInstance().getExternalContext() .redirect("/MerlionBankBackOffice/TransferManagement/intraTransferSuccess.xhtml"); } else { FacesMessage sysMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "System Message", "Please Select a Saving Account!"); RequestContext.getCurrentInstance().showMessageInDialog(sysMessage); } } catch (TransferException ex) { System.out.print("OneTimeTransfer Encounter Error"); FacesMessage sysMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "System Message", ex.getMessage()); RequestContext.getCurrentInstance().showMessageInDialog(sysMessage); } } public void goBackToHomePage(ActionEvent event) { try { FacesContext.getCurrentInstance().getExternalContext() .redirect("/MerlionBankBackOffice/StaffDashboard.xhtml"); } catch (Exception e) { System.out.print("Redirect to Home Page Encounter Error!"); } } public List getSavingAccountList() { return savingAccountList; } public void setSavingAccountList(List savingAccountList) { this.savingAccountList = savingAccountList; } public String getRecipientName() { return recipientName; } public void setRecipientName(String recipientName) { this.recipientName = recipientName; } public String getAmountString() { return amountString; } public void setAmountString(String amountString) { this.amountString = amountString; } public BigDecimal getAmountBD() { return amountBD; } public void setAmountBD(BigDecimal amountBD) { this.amountBD = amountBD; } public Long getRecipientAccountNumLong() { return recipientAccountNumLong; } public void setRecipientAccountNumLong(Long recipientAccountNumLong) { this.recipientAccountNumLong = recipientAccountNumLong; } public String getRecipientAccountNumString() { return recipientAccountNumString; } public void setRecipientAccountNumString(String recipientAccountNumString) { this.recipientAccountNumString = recipientAccountNumString; } public Long getGiverAccountNumLong() { return giverAccountNumLong; } public void setGiverAccountNumLong(Long giverAccountNumLong) { this.giverAccountNumLong = giverAccountNumLong; } public Long getCustomerID() { return customerID; } public void setCustomerID(Long customerID) { this.customerID = customerID; } }
Python
UTF-8
3,826
3.296875
3
[]
no_license
import copy class Board: BLACK = 0 WHITE = 1 TURN = 1 def __init__(self): self.board = [ [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None]] def set_standard(self): self.board = [ [Rook(0), Knight(0), Bishop(0), Queen(0), King(0), Bishop(0), Knight(0), Rook(0)], [Pawn(0), Pawn(0), Pawn(0), Pawn(0), Pawn(0), Pawn(0), Pawn(0), Pawn(0)], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [Pawn(1), Pawn(1), Pawn(1), Pawn(1), Pawn(1), Pawn(1), Pawn(1), Pawn(1)], [Rook(1), Knight(1), Bishop(1), Queen(1), King(1), Bishop(1), Knight(1), Rook(1)]] def __str__(self): s = ' +---+---+---+---+---+---+---+---+ \n' for y in range(len(self.board)): s += str(8 - y) + ' | ' for x in range(len(self.board[y])): if self.board[y][x] is None: s += ' | ' else: s += str(self.board[y][x]) + ' | ' s += '\n +---+---+---+---+---+---+---+---+ \n' s += ' a b c d e f g h' return s def col(self, cha): return ord(cha) - 97 def move(self, notation): if len(notation) == 2: # pawn move # Find appropriate pawn for y in range(len(self.board)): for x in range(len(self.board[y])): piece = copy.deepcopy(self.board[y][x]) if self.col(notation[0]) == x and piece is not None: if self.TURN == piece.color and piece.name == "Pawn": print(f"moving {piece} to {notation}") self.board[8 - int(notation[1])][x] = piece self.board[y][x] = None self.end_turn() return True elif notation[0] == 'K': # King move pass elif notation[0] == 'Q': # Queen move pass elif notation[0] == 'R': # Rook move pass elif notation[0] == 'B': # Bishop move pass elif notation[0] == 'N': # Knight move pass def end_turn(self): if self.TURN: self.TURN = 0 else: self.TURN = 1 class Piece: pass class King(Piece): name = "King" def __init__(self, color): self.color = color def __str__(self): return 'K' class Queen(Piece): name = "Queen" def __init__(self, color): self.color = color def __str__(self): return 'Q' class Rook(Piece): name = "Rook" def __init__(self, color): self.color = color def __str__(self): return 'R' class Bishop(Piece): name = "Bishop" def __init__(self, color): self.color = color def __str__(self): return 'B' class Knight(Piece): name = "Knight" def __init__(self, color): self.color = color def __str__(self): return 'N' class Pawn(Piece): name = "Pawn" def __init__(self, color): self.color = color def __str__(self): return 'p'
Java
UTF-8
1,613
2.578125
3
[]
no_license
package com.orendel.transfer.dialogs; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.SWT; import com.orendel.transfer.composites.AddBarcodeComposite; import com.orendel.transfer.controllers.CounterpointController; import com.orendel.transfer.util.DialogUtil; public class AddBarcodeDialog extends Dialog { protected Object result; protected Shell shell; private CounterpointController controller; private String itemNo; /** * Create the dialog. * @param parent * @param style */ public AddBarcodeDialog(Shell parent, int style, CounterpointController controller, String itemNo) { super(parent, style); setText("Agregar código de barra"); this.controller = controller; this.itemNo = itemNo; } /** * Open the dialog. * @return the result */ public Object open() { createContents(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } /** * Create contents of the dialog. */ private void createContents() { shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); shell.setSize(500, 360); shell.setText(getText()); shell.setLocation(DialogUtil.calculateDialogLocation(shell, false)); shell.setLayout(new FillLayout(SWT.HORIZONTAL)); AddBarcodeComposite composite = new AddBarcodeComposite(shell, SWT.None, controller, itemNo); composite.layout(); } }
Go
UTF-8
353
2.921875
3
[]
no_license
package main import ( "testing" ) func TestWorldPopulationSet(t *testing.T){ // create a world world,err := NewWorld(nil) if err != nil{ t.Fatal("Failed to create World") } // set the population world.SetPopulation(5) // get the population if world.Population() != 5{ t.Fatal("population getter didn't return the correct population") } }
Markdown
UTF-8
4,296
2.765625
3
[]
no_license
# 投资中,大部分人一辈子都无法走出的思维误区! - 知乎 # ![](https://pic2.zhimg.com/v2-94cd9dbb34b4483934c93b5c9dcd6c29_b.jpg)![](data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1080' height='720'></svg>) 霜降之时,桂花遍地,有人喊,春天不远了。 不过,今天要不是金融、地产的护盘,大盘又会很难看。因为每只股票的权重不一样,上证指数经常是失真的,并不能代表市场所有股票的涨跌水平。 比如2015年6月12日,当时市场上总共2745只股票,截至今天收盘,有2121只股票跌幅大于50%,有463只股票跌幅超过80%。如果仅仅看大盘,从最高点至今跌幅只是49.73%。 散户有个非常典型的误区:**看着一只股票一直上涨,始终不敢买。只要稍微跌一点,就急不可耐的进去“抄底”。** 比如有人看到老板电器从53元跌到37元,已经跌了30%,以为这是好公司给了便宜的价格,所以在37元抄底买入。没想到随后继续下跌,今天收盘差不多只有20元。 ![](https://pic1.zhimg.com/v2-d7c5739d45f5d0d6f04fe8d5e15f6490_b.jpg)![](data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1639' height='888'></svg>) 53元顶部买入的股民,现在亏损62%。而37元“抄底”买入的股民,现在亏损46%。这两种人的亏损差别并不大。 还有个现象:**当一家公司股票连续下跌半年或一年后,就很少会有人提及“抄底”这回事了。** 再举个例子,记得2016年刚写公众号的时候,我跟读者说华宝油气在0.6元以下可以分批买入,网格交易。两年过去了,几乎每次都是当快涨到顶部的时候才有一大堆人私信问我该不该买入。 特别是2017年上半年这波凌厉的大跌,几乎让跟着我一起做华宝油气网格的大部分人都出局了。现在想来还是历历在目,当时还有人一片好心来劝我放弃,理由无非是新能源革命、美国页岩油技术革新等。 ![](https://pic2.zhimg.com/v2-9fb90571bf7a7ae0246b635fec32420d_b.jpg)![](data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1639' height='890'></svg>) 我们似乎总是被价格波动牵着鼻子在走,比如去年被追捧了中概互联(513050),还有谁关心呢? ![](https://pic2.zhimg.com/v2-6b8b87cdba0aff18feacaf322d737f19_b.jpg)![](data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1080' height='586'></svg>) **可能大多数人既没有追涨(右侧买入)的勇气,也没有抄底(左侧买入)的耐心,所以才会不断高买低卖。** 经常有人要我推荐股票或基金,但就算告诉你这是家好公司,你真的拿的住吗? **投资必须独立思考,你自己悟出来的和别人告诉你的,完全不一样。**如果你自己没想明白,在大家恐惧的时候,你怎么发现机会?在大家都贪婪的时候,你怎么保持冷静? 再以我曾经提过的天弘沪深300A(000961)为例,以前分析过它的跟踪误差低,费率也在偏低档次。下图是天弘沪深300A的季度涨幅情况,很多人看到2017年每个季度都是正收益而定投,而2018年至今持续下跌就不敢定投了。 我觉得,下跌就不敢定投的人,一定没有真正理解定投。他们可能是人云亦云,从来没有深入思考过策略的本质是什么。 ![](https://pic2.zhimg.com/v2-25c5baeb8035745579bbfd848742e871_b.jpg)![](data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='991' height='349'></svg>) 我们每个人从小都学习用脑,而独立思考并不是人人都会的。别人都认为对的事情,你有没有尝试思考这会不会是错的呢?媒体每天的报道,也可能只是他们想让我们看到的东西。有些事情,换个角度去观察,会产生完全不一样的结论。 真正的独立思考,应该是怀疑,但不否定一切;开放,但不摇摆不定;分析,但不吹毛求疵;决断,但不顽固不化;评价,但不恶意臆断。 **一个理性的投资者,“春天”不需要别人来告诉你,你的“春天”只存在于独立思考之后。** **微信公众号:moneylife1818**
Python
UTF-8
1,034
4.03125
4
[]
no_license
# # Copyright (c) 2006-2019, RT-Thread Development Team # # SPDX-License-Identifier: MIT License # # Change Logs: # Date Author Notes # 2019-07-27 SummerGift first version # # 集合(set)是由一个或数个形态各异的大小整体组成的,构成集合的事物或对象称作元素或是成员 # 基本功能是进行成员关系测试和删除重复元素 # 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典 student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'} print(student) # 输出集合,重复的元素被自动去掉 # 成员测试 if 'Rose' in student: print('Rose is in set') else: print('Rose is not in set') # set可以进行集合运算 a = set('abracadabra') b = set('alacazam') print(a) print(a - b) # a 和 b 的差集 print(a | b) # a 和 b 的并集 print(a & b) # a 和 b 的交集 print(a ^ b) # a 和 b 中不同时存在的元素
Java
UTF-8
1,739
2.390625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package hibernate.builder; import core.entities.Article; import core.entities.Match; import core.entities.User; import core.ibuilder.IArticleBuilder; import java.util.Date; import java.util.List; /** * * @author Administrator */ public class ArticleBuilder implements core.ibuilder.IArticleBuilder { private hibernate.entities.Article article = new hibernate.entities.Article(); @Override public Article buildCoreArticle() { return (Article) article; } @Override public IArticleBuilder setName(String name) { article.setName(name); return this; } @Override public IArticleBuilder setContent(String content) { article.setContent(content); return this; } @Override public IArticleBuilder setDateCreated() { article.setDateCreated(new Date()); return this; } @Override public IArticleBuilder setUser(User user) { article.setUserId((hibernate.entities.User) user); return this; } @Override public IArticleBuilder setMatches(List<Match> matches) { article.setMatchList((List<hibernate.entities.Match>)(List<?>) matches); return this; } @Override public IArticleBuilder setId(Integer id) { article.setId(id); return this; } @Override public IArticleBuilder clearBuilder() { article = new hibernate.entities.Article(); return this; } }
C++
UTF-8
278
3.171875
3
[]
no_license
#include<iostream> using namespace std; int main() { int num, first = -1, sec = 1, count = 0, sum = 0; cout << "Enter number: "; cin >> num; while (count<=num) { sum = first + sec; first = sec; sec = sum; count++; } cout << sum << endl; return 0; }
C#
UTF-8
2,404
2.53125
3
[]
no_license
using BazaPodataka; using Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Servis { public class KvarServis : IKvarServis { IBaza _baza; public KvarServis(IBaza baza) { this._baza = baza; } public void DodajKvar(string kratakOpis, string uzrok, string detaljanOpis, DateTime vreme, string akcija, string elektricniElement) { Akcija akcija1 = new Akcija(akcija, vreme); string el = elektricniElement.Remove(1, 4); string[] parts = el.Split(' '); int idElement = Int32.Parse(parts[0]); string elElement = parts[1]; Kvar kvar = new Kvar(kratakOpis, uzrok, detaljanOpis, akcija1, elElement, idElement); kvar.Id = CreateID(kvar.Id); _baza.DodajKvar(kvar); } public void AzurirajKvar(string id, string kratakOpis, string uzrok, string detaljanOpis, Status status, DateTime vreme, string akcija, string elektricniElement) { Kvar kvar = new Kvar(); string el = elektricniElement.Remove(1, 4); string[] parts = el.Split(' '); int idElement = Int32.Parse(parts[0]); string elElement = parts[1]; kvar.Id = id; kvar.KratakOpis = kratakOpis; kvar.Uzrok = uzrok; kvar.DetaljanOpis = detaljanOpis; kvar.Status = status; kvar.Akcija.Vreme = vreme; kvar.Akcija.Opis = akcija; kvar.ElektricniElement = elektricniElement; kvar.IdElement = idElement; _baza.AzurirajKvar(kvar); } public List<ElektricniElement> GetElektricniElementi() { return _baza.GetElektricniElementi(); } public List<Kvar> GetKvarovi(DateTime date1, DateTime date2) { return _baza.GetKvarovi(date1, date2); } public List<string> GetStatus() { List<string> list = new List<string>(); foreach (Status s in Enum.GetValues(typeof(Status))) { list.Add(s.ToString()); } return list; } public string CreateID(string kvarID) { return _baza.CreateID(kvarID); } } }
Java
UTF-8
848
2.15625
2
[]
no_license
package cn.com.crowdsourcedtesting.modelhelper; import java.util.List; import cn.com.crowdsourcedtesting.bean.Tester; import cn.com.crowdsourcedtesting.struts.form.LoginForm; import cn.com.crowdsourcedtesting.subinterface.RoleIdentify; import cn.com.crowdtest.factory.*; public class CheckAuthority implements RoleIdentify{ @Override public boolean isLegalUser(LoginForm loginForm) { // TODO Auto-generated method stub List <Tester> testers = DAOFactory.getTesterDAO().findByProperty("testername",loginForm.getUsername()); if(testers!=null&&testers.get(0).getTesterPassword().equals(loginForm.getPassword())) { return true; } return false; } @Override public UserType roleOfUser(LoginForm loginForm) { // TODO Auto-generated method stub return null; } }
JavaScript
UTF-8
1,677
2.625
3
[]
no_license
import React, { Component } from 'react'; import axios from "axios"; import PizzaUpdate from './pizzeriaupdate'; class PizzaDetail extends Component{ constructor(props) { super(props); this.state = { showComponent: false, }; this.updatePizzeriaDetails = this.updatePizzeriaDetails.bind(this); this.deletePizzeria=this.deletePizzeria.bind(this); } updatePizzeriaDetails() { this.setState({ showComponent: true }); } deletePizzeria(obj){ console.log(obj); axios.delete("http://127.0.0.1:8000".concat(obj)) .then((response) => { console.log(response); }) .catch(function (error) { console.log(error); }); } render(){ const obj = this.props.pizzariaDetail; return( <div style={{ color: "yellow", border: "1px solid yellow" }}> <h4>{obj.pizzeria_name}</h4> <h1>hjjh</h1> <h4>{obj.street} {obj.city}{obj.state}{obj.zip_code}</h4> <h4>{obj.description}</h4> <button style={{ backgroundColor: "white" }} onClick={()=> this.updatePizzeriaDetails()}> Update </button> <button style={{ backgroundColor: "white" }} onClick={() => this.deletePizzeria(obj.delete)}> Delete </button> {this.state.showComponent ? <PizzaUpdate pizzariaUpdate={obj}/> : null } </div> ) } } export default PizzaDetail;
Markdown
UTF-8
1,092
2.796875
3
[]
no_license
File Downloader from Multiple Sources ============ This product has the function of downloading the files from multiple hosts, like HTTP, FTP or SFTP. Even this product can be enhanced in future to handle other type of protocols too. Development ------ ### Requirements * JDK 8 * [Lombok](https://projectlombok.org/) * Maven 3.3.3+ (or use the included Maven wrapper via `mvnw`) Release Notes ------ ### 0.0.1 Current version has below features. * Download files from HTTP, FTP and SFTP * Due to un-availability of valid SFTP host, SFTP downloader might need testing before releasing to host. ### Release procedure * Create input directory and edit the <b>src/main/resources/inputDirectory.properties</b> to point to the input directory name * Create output directory path and edit the <b>src/main/resources/outputDirectory.properties</b> to point to the output files location * Run below maven goals using below command. <i>mvn clean compile package install</i> * We can run the downloader application using below command: <i> java -jar downloader-0.0.1-SNAPSHOT.jar </i>
Java
UTF-8
167
1.976563
2
[]
no_license
package jeu; public interface BoostStat { public int renforceDefence(); public int renforceAttaque(); public void placerBaseEquipement(BoostStat be); }
Shell
UTF-8
344
3.96875
4
[]
no_license
#!/bin/bash if [ "$#" -lt 1 ]; then echo "USAGE: $0 TIME" >&2 echo "Exits at TIME." >&2 exit 255 fi target=$(date -d "$1" +%s) duration=$((target - $(date +%s))) if [ "$duration" -lt 0 ]; then echo "Time $(date -d "@$target") is in the past" >&2 exit 1 fi echo "Waiting until $(date -d "@$target") ($duration seconds)" sleep "$duration"
PHP
UTF-8
7,108
2.8125
3
[]
no_license
<?php namespace AppBundle\Entity\Calendar; use DateTime; use DateInterval; use DateTimeZone; use Doctrine\ORM\Mapping as ORM; /** * Class Event * @package AppBundle\Entity\Calendar * * @ORM\Table(name="events") * @ORM\Entity(repositoryClass="AppBundle\Repository\Calendar\EventRepository") */ class Event { // TODO : trim and replace special chars in strings // TODO : parse description, summary to extract location, teachers and info const TIMEZONE = 'Europe/Paris'; /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * @ORM\Column(type="string", unique=true) */ private $uid; /** * @var DateTime * @ORM\Column(type="datetime") */ private $updatedAt; /** * @var DateTime * @ORM\Column(type="datetime") */ private $createdAt; /** * @var DateTime * @ORM\Column(type="datetime") */ private $startAt; /** * @var DateTime * @ORM\Column(type="datetime") */ private $endAt; /** * @var string * @ORM\Column(type="string", length=2047) */ private $summary; /** * @var string * @ORM\Column(type="string", length=2047) */ private $description; /** * @var string * @ORM\Column(type="string") */ private $timestamp; /** * @var Calendar * * @ORM\ManyToOne(targetEntity="Calendar", inversedBy="events") * @ORM\JoinColumn(nullable=false) */ private $calendar; /** * Event constructor. * @param $uid * @param $description * @param $summary * @param $createdAt * @param $updatedAt * @param $startAt * @param $endAt * @param $timestamp */ public function __construct($uid, $description, $summary, $createdAt, $updatedAt, $startAt, $endAt, $timestamp) { $this->setUid($uid); $this->setDescription($description ?? ''); $this->setSummary($summary); $this->setCreatedAt($createdAt); $this->setUpdatedAt($updatedAt); $this->setStartAt($startAt); $this->setEndAt($endAt); $this->duration = $this->endAt->diff($this->startAt); $this->setTimestamp($timestamp); } /** * @return mixed */ public function getId() { return $this->id; } /** * @return string */ public function getUid(): string { return $this->uid; } /** * @param string $uid */ public function setUid(string $uid) { $this->uid = $this->_parseUid($uid); } /** * @return DateTime */ public function getUpdatedAt(): DateTime { return $this->updatedAt; } /** * @param DateTime $updatedAt */ public function setUpdatedAt(DateTime $updatedAt) { $updatedAt->setTimezone(new DateTimeZone(self::TIMEZONE)); $this->updatedAt = $updatedAt; } /** * @return DateTime */ public function getCreatedAt(): DateTime { return $this->createdAt; } /** * @param DateTime $createdAt */ public function setCreatedAt(DateTime $createdAt) { $createdAt->setTimezone(new DateTimeZone(self::TIMEZONE)); $this->createdAt = $createdAt; } /** * @return DateTime */ public function getStartAt(): DateTime { return $this->startAt; } /** * @param DateTime $startAt */ public function setStartAt(DateTime $startAt) { $startAt->setTimezone(new DateTimeZone(self::TIMEZONE)); $this->startAt = $startAt; } /** * @return DateTime */ public function getEndAt(): DateTime { return $this->endAt; } /** * @param DateTime $endAt */ public function setEndAt(DateTime $endAt) { $endAt->setTimezone(new DateTimeZone(self::TIMEZONE)); $this->endAt = $endAt; } /** * @return string */ public function getSummary(): string { return $this->summary; } /** * @param string $summary */ public function setSummary(string $summary) { $this->summary = $this->_formatString($summary); } /** * @return string */ public function getDescription(): string { return $this->description; } /** * @param string $description */ public function setDescription(string $description) { $this->description = $this->_parseDescription($this->_formatString($description)); } /** * @return DateTime */ public function getTimestamp() { return $this->timestamp; } /** * @param string $timestamp */ public function setTimestamp(string $timestamp) { $this->timestamp = $timestamp; } /** * Used to display human readable times in easy admin * * @return string */ public function getStringDuration(): string { if ((int)$this->endAt->diff($this->startAt)->format('%d') >= 1) { $format = '%dj'; } else { $format = '%hh%I'; } return $this->endAt->diff($this->startAt)->format($format); } /** * @return DateInterval */ public function getDuration(): DateInterval { return $this->endAt->diff($this->startAt); } /** * @return Calendar */ public function getCalendar(): Calendar { return $this->calendar; } /** * @param Calendar $calendar */ public function setCalendar(Calendar $calendar) { $this->calendar = $calendar; } /** * Trim and remove formatting in strings imported from calendar * @param $string * @return string */ private function _formatString($string) { $string = str_replace('&amp;', '&', $string); $string = str_replace(PHP_EOL, '', $string); return trim($string); } /** * Extract data from uid * Example raw uids "Férié-594-5A - IW 3-Index-Education", "Cours-508333-33-5A - IW 3-Index-Education" * @param string $string * @return string */ private function _parseUid(string $string): string { return $string; } /** * Exemple : Matière : Anglais Préparation au Toeic 2\n * Enseignants : M. BRENEUR, M. GARDINIER, M. HIDALGO-BARQUERO, M. NOEL, M. RAULIN, M. WEBER\n * Promotions : 5A - IW 3, 5A - MCSI 1, 5A - MCSI 2, 5A - SRC 3\n * Salles : NA SALLE A 14, NA SALLE A 23, NA SALLE A 24, NA SALLE C 02, NA SALLE C 03, NA SALLE C 05 - Salle de Dessin * @param string $string * @return string */ private function _parseDescription(string $string): string { return $string; } /** * @param string $string * @return string */ private function _parseSummary(string $string): string { return $string; } function __toString() { return $this->summary; } }
Java
UTF-8
4,015
1.726563
2
[]
no_license
package com.jagex; import com.jagex.Class149; import com.jagex.Class21; import com.jagex.Class243; import com.jagex.InterfaceDef; import com.jagex.Class357; import com.jagex.Class429; import com.jagex.Class51; import com.jagex.RSByteBuffer; import com.jagex.Class566; import com.jagex.Class615; import com.jagex.Class619; import com.jagex.Class679; import com.jagex.Class681; import com.jagex.client; import com.jagex.twitchtv.TwitchWebcamDevice; import java.io.EOFException; public class Class333 { public Class333(int var1) { } static void method4255(Class681 var0, int var1) { String var2 = (String)var0.anObjectArray8624[(var0.anInt8625 -= 2019513325) * 540934629]; TwitchWebcamDevice var3 = Class429.method5049(var2, 1669017392); if(var3 == null) { var0.anIntArray8622[(var0.anInt8623 += -1957887669) * -1730576285 - 1] = -1; var0.anObjectArray8624[(var0.anInt8625 += 2019513325) * 540934629 - 1] = ""; var0.anObjectArray8624[(var0.anInt8625 += 2019513325) * 540934629 - 1] = ""; } else { var0.anIntArray8622[(var0.anInt8623 += -1957887669) * -1730576285 - 1] = var3.anInt1137 * -355702023; var0.anObjectArray8624[(var0.anInt8625 += 2019513325) * 540934629 - 1] = var3.aString1135; var0.anObjectArray8624[(var0.anInt8625 += 2019513325) * 540934629 - 1] = var3.aString1136; } } static final void method4256(InterfaceDef var0, Class243 var1, Class681 var2, int var3) { String var4 = (String)var2.anObjectArray8624[(var2.anInt8625 -= 2019513325) * 540934629]; if(Class149.method1747(var4, var2, (byte)0) != null) { var4 = var4.substring(0, var4.length() - 1); } var0.anObjectArray2603 = Class615.method7280(var4, var2, -668887601); var0.aBool2560 = true; } public static Class51 method4257(int var0) { Class21 var1 = null; try { Class51 var19; try { var1 = Class619.method7340("3", client.aClass676_11127.aString8591, false, 818846928); byte[] var2 = new byte[(int)var1.method658((byte)-32)]; int var18 = 0; while(true) { if(var18 >= var2.length) { var19 = new Class51(new RSByteBuffer(var2)); break; } int var4 = var1.method653(var2, var18, var2.length - var18, (byte)73); if(-1 == var4) { throw new EOFException(); } var18 += var4; } } catch (Exception var16) { Class51 var3 = new Class51(); try { if(var1 != null) { var1.method651(1596676876); } } catch (Exception var14) { ; } return var3; } try { if(var1 != null) { var1.method651(336529609); } } catch (Exception var15) { ; } return var19; } finally { try { if(var1 != null) { var1.method651(323286687); } } catch (Exception var13) { ; } } } static final void method4258(Class681 var0, int var1) { var0.anInt8623 -= 379191958; int var2 = var0.anIntArray8622[var0.anInt8623 * -1730576285]; int var3 = var0.anIntArray8622[var0.anInt8623 * -1730576285 + 1]; Class679 var4; if(var0.aBool8628) { var4 = var0.aClass679_8631; } else { var4 = var0.aClass679_8621; } var0.anIntArray8622[(var0.anInt8623 += -1957887669) * -1730576285 - 1] = -1 != var3 && var4.method8020(var2, var3, (byte)-117)?1:0; } static void method4259(int var0) { Class357.method4575((byte)114); } static final void method4260(Class681 var0, int var1) { var0.anIntArray8622[(var0.anInt8623 += -1957887669) * -1730576285 - 1] = Class566.aClass223_7610.method3109(1986732427); } }
C
UTF-8
762
3.515625
4
[]
no_license
#include "queue.h" void queue_init(Queue *queue) { queue->enqueue = enqueue; queue->dequeue = dequeue; queue->head = NULL; queue->tail = NULL; } int enqueue(Queue *queue, void *item) { int status = UNDEFINED; if (queue) { Node *node = (Node *) malloc(sizeof(Node)); node->item = item; if (queue->head) { queue->head->next = node; } queue->head = node; if (!queue->tail) { queue->tail = node; } status = SUCCESS; } return status; } void *dequeue(Queue *queue) { if (!queue || !queue->tail) return NULL; Node *node = queue->tail; queue->tail = node->next; void *item = node->item; free(node); return item; }
C++
UTF-8
995
3.75
4
[]
no_license
#include <iostream> using namespace std; int binary_search(int [], int, int); int main() { int a[100], i, n, x; cout<<"How many numbers do you want to enter : "; cin>>n; cout<<"\nPlease enter the elements : "; for(i=0; i<n; ++i) { cout<<"\nElement "<<(i+1)<<" : "; cin>>a[i]; } cout<<"\nEnter the element to be searched for : "; cin>>x; cout<<"\n The given array is : "; for(i=0; i<n; ++i) cout<<a[i]<<"\t"; int p = binary_search(a, n, x); if(p!=-1) cout<<"\n\nThe given element is present in the position : "<<p+1; return 0; } int binary_search(int a[], int n, int x) { int u=n-1, l=0, mid; for(int i=0; i<n; ++i) { mid = (l+u)/2; if(a[mid]<x) u = mid - 1; else if(a[mid]>x) l = mid + 1; else { cout<<"\nThe given element is present in the given array."; return(mid); } } if(!(l<=u)) { cout<<"\nThe given element is not present in the given array."; return(-1); } }
C++
UTF-8
3,197
3.140625
3
[]
no_license
#include "util.h" #include "PacketBuffer.h" PacketBuffer::PacketBuffer() : readPos(0) , writePos(0) { buffer.assign(0); } PacketBuffer::~PacketBuffer() { } bool PacketBuffer::AppendBuffer(const char* pBuffer, uint16 size) { if (!pBuffer) return false; if (size == 0) return false; if (size > GetRemainSize()) { ReArrange(); } if (size > GetRemainSize()) { LOG_ERROR("Not enough remain buffer."); return false; } CopyMemory(buffer.data() + writePos, pBuffer, size); writePos += size; return true; } void PacketBuffer::Clear() { readPos = 0; writePos = 0; buffer.assign(0); } uint16 PacketBuffer::GetPacketNo() const { if (writePos < GetHeaderSize()) { LOG_ERROR("Not enough data."); return 0; } uint16 packetNo = 0; CopyMemory(&packetNo, buffer.data() + readPos + sizeof(uint16), sizeof(uint16)); return packetNo; } bool PacketBuffer::IsAbleToGetPacket() const { const uint16 packetSize = GetPacketSize(); if (packetSize == 0) return false; const uint16 packetBufferSize = GetBufferSize(); if (packetBufferSize == 0) return false; return (packetSize <= packetBufferSize); } void PacketBuffer::ConsumePacket() { const uint16 packetSize = GetPacketSize(); TruncateBuffer(packetSize); } const char* PacketBuffer::GetBuffer() const { return buffer.data() + readPos; } uint16 PacketBuffer::GetBufferSize() const { if (readPos > writePos) { LOG_ERROR("Not enough buffer size."); return 0; } return writePos - readPos; } const char* PacketBuffer::GetPacketBuffer() const { return GetBuffer(); } uint16 PacketBuffer::GetPacketSize() const { const uint16 bufferSize = GetBufferSize(); if (bufferSize < sizeof(uint16)) { return 0; } uint16 packetSize = 0; CopyMemory(&packetSize, buffer.data() + readPos, sizeof(packetSize)); return packetSize; } const char* PacketBuffer::GetPayloadBuffer() const { return GetBuffer() + GetHeaderSize(); } uint16 PacketBuffer::GetPayloadBufferSize() const { return GetPacketSize() - GetHeaderSize(); } void PacketBuffer::ReArrange() { const uint16 bufferSize = GetBufferSize(); MoveMemory(buffer.data(), GetBuffer(), bufferSize); readPos = 0; writePos = bufferSize; } void PacketBuffer::TruncateBuffer(uint16 size) { if (size > GetBufferSize()) { LOG_ERROR("Fail to truncate buffer. remain size: {}, truncate size: {}", writePos - readPos, size); return; } readPos += size; } bool PacketBuffer::SetPacketSize(uint16 packetSize) { if (packetSize > MAX_BUF_SIZE) { LOG_ERROR("packet size is bigger than MAX_BUF_SIZE. packetSize: {}", packetSize); return false; } CopyMemory(buffer.data() + writePos, &packetSize, sizeof(packetSize)); writePos += sizeof(packetSize); return true; } bool PacketBuffer::SetPacketNo(uint16 packetNo) { CopyMemory(buffer.data() + writePos, &packetNo, sizeof(packetNo)); writePos += sizeof(packetNo); return true; }
Python
UTF-8
672
3.828125
4
[]
no_license
def validate_string(input_string): tmp_stack = [] for s in input_string: if s == '{' or s == '[' or s == '(': tmp_stack.append(s) elif s == '}': if len(tmp_stack) == 0 or tmp_stack.pop() != '{': return False elif s == ']': if len(tmp_stack) == 0 or tmp_stack.pop() != '[': return False elif s == ')': if len(tmp_stack) == 0 or tmp_stack.pop() != '(': return False else: continue if len(tmp_stack) !=0: return False else: return True print(validate_string('{[]}')) validate_string('Hem')
JavaScript
UTF-8
2,578
3.5
4
[]
no_license
function average(sum, number) { var av = sum / number; av = av.toFixed(1); av = av.replace('.', ','); return av; } function numsort(a,b) { return a - b; } function median(values) { values.sort(numsort); if (values.length % 2 == 1) { return values[(values.length - 1)/2]; } else { var tmp = values[values.length / 2 - 1] + values[values.length / 2]; return average(tmp, 2); } document.write(values); } // lies den Text aus dem Artikel aus var text = document.querySelector('article').innerHTML; // sammle die einzelnen Wörter aus dem Text in einer Variablen 'words' var words = text.split(/[.,;«»!?"'\s-]+/); var longestWord = ''; var wordsLengthTotal = 0; var wordLengths = []; var wordUnique = {}; words.forEach(function(word, i) { // aktualisiere die gesamte Textlänge wordsLengthTotal += word.length; // sichere das aktuell längste Word if (word.length > longestWord.length) { longestWord = word; } // sichere die Länge des aktuellen Worts wordLengths.push(word.length); // var lcWord = word.toLowerCase(); if (wordUnique[lcWord] == undefined) { wordUnique[lcWord] = 0; } ++wordUnique[lcWord]; }) var wordCount = 0 usedOnce = [], mostPopular = {count:0}; for (var key in wordUnique) { ++wordCount; if (wordUnique[key] === 1) { usedOnce.push(key); } if (wordUnique[key] > mostPopular.count) { mostPopular.word = key; mostPopular.count = wordUnique[key]; } } Math. var randoms = []; while (randoms.length < 5) { if (randoms.length === usedOnce.length) { break; } var random = Math.floor(Math.random() * usedOnce.length); if (randoms.indexOf(random) === -1) { document.write('<li>' + usedOnce[random] + '</li>'); } randoms.push(random); } var pubdate = new Date('1915-10-01'); var datediff = Date.now() - pubdate.getTime(); datediff /= 1000 * 60 * 60 * 24; datediff = Math.floor(datediff); var years = Math.floor(datediff / 365.2425); var days = Math.round(datediff % 365.2425); var months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']; document.write('<p>Das mit ' + longestWord.length + ' Zeichen längste Wort lautet: <q>' + longestWord + '</q>'); document.write('<p>Durchschnittliche Wortlänge: ' + average(wordsLengthTotal, words.length) + ' Zeichen'); document.write('<p>' + median(wordLengths)); document.write('<p>' + pubdate.getDate() + '.' + months[pubdate.getMonth()] + '.' + pubdate.getFullYear()); document.write('<p>Dieser Text erschien vor ' + (years ? years + ' Jahren und ' : '') + days + ' Tagen.</p>');
C
UTF-8
3,368
4.03125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> struct Stack{ int size; int top; char* arr; }; int isEmpty(struct Stack *ptr){ if(ptr->top == -1){ return 1; } return 0; } int isFull(struct Stack *ptr){ if(ptr->top == (ptr->size -1)){ return 1; } return 0; } int push(struct Stack* ptr,char data){ if(isFull(ptr)){ printf("Stack overflow,can't push more\n"); return 0; } else{ ptr->top ++; ptr->arr[ptr->top] = data ; printf("Element %c successfullt pushed\n",data); } } char pop(struct Stack* ptr){ if(isEmpty(ptr)){ printf("Stack underflow,can't pop more\n"); return -1; } else{ char val = ptr->arr[ptr->top]; ptr->top--; //printf("Element successfullt popped\n"); return val; } } char peek(struct Stack* ptr,char i){ int result = ptr->top - i +1 ; if(result < 0){ printf("Invalid peek\n"); return -1; } else{ return ptr->arr[result]; } } char stackTop(struct Stack *ptr){ return ptr->arr[ptr->top]; } int stackBottom(struct Stack *ptr){ return ptr->arr[0]; } void StackTraversal(struct Stack* ptr){ for(int i = 0;i<=ptr->top;i++){ printf("The stack element is %c\n",ptr->arr[i]); } } int match(char a,char b){ if(a == '(' && b == ')'){ return 1; } if(a == '[' && b == ']'){ return 1; } if(a == '{' && b == '}'){ return 1; } return 0; } int isBalanceParanthesis(struct Stack* ptr){ struct Stack *temp; temp->size = 15; temp->top=-1; temp->arr = (char*)malloc(temp->size * sizeof(char)); for(int i = 0;i<=ptr->top;i++){ printf("The stack element is %c\n",ptr->arr[i]); char ele = ptr->arr[i]; if(ele == '(' || ele == '[' || ele == '{'){ push(temp,ele); } else if(ele == ')' || ele == ']' || ele == '}'){ char x = pop(temp); if(match(x,ele)){ printf("successfully Popped %c\n",x); } else{ printf("In Else Paranthesis DONOT match!! Hence NO Balance"); return -1; } } } if(isEmpty(temp)){ printf("Paranthesis match!! Hence Balance"); } else{ printf("Paranthesis DONOT match!! Hence NO Balance"); } } int main() { struct Stack *s = (struct Stack*)malloc(sizeof(struct Stack)); //to push and pop the paranthesis ( and ) s->size = 15; s->top=-1; s->arr = (char*)malloc(s->size * sizeof(char)); push(s,'{'); push(s,'3'); push(s,'*'); push(s,'2'); push(s,'['); push(s,'-'); push(s,'('); push(s,'8'); push(s,'+'); push(s,'1'); push(s,')'); push(s,']'); push(s,'}'); //printf("Element %d successfullt popped\n",pop(s)); //printf("Peek Element is %d \n",peek(s,5)); //printf("Peek Element is %d \n",peek(s,7)); //printf("Stack Top Element is %d \n",stackTop(s)); //printf("Stack Bottom Element is %d \n",stackBottom(s)); if(isEmpty(s)){ printf("Stack is empty\n"); } else{ printf("NOt empty\n"); } printf("This is top of stack %d\n",s->top); isBalanceParanthesis(s); //StackTraversal(s); return 0; }
C++
UTF-8
289
2.75
3
[]
no_license
#include "Random.h" #include <cstdlib> #include <ctime> void Random::SetRand() { SetRand((int)time(NULL)); } void Random::SetRand(int seed) { srand(seed); } float Random::GetNumber() { return rand() / (int)RAND_MAX; } int Random::GetNumber( int max ) { return 0 + rand() % max; }
Markdown
UTF-8
1,758
3.109375
3
[ "MIT" ]
permissive
name: inverse layout: true class: center, middle, inverse --- ### STAT 430: Lecture 15 ## Multiple Random Variables ### Functions of Jointly Distributed Random Variables 2 .footnote[Course page: [imouzon.github.io/stat430](https://imouzon.github.io/stat430)] --- layout: true class: center, middle, inverse --- # A Quick Correction --- layout:false .left-column[ ### $Z = g(X,Y)$ ] .right-column[ ### Functions of Multiple Random Variables **Special Cases** Suppose that $X$ and $Y$ are both random variables with joint distribution given by $f\_{XY}(x,y)$. Then if ### Discrete case 1. $Z = X + Y$ then \\[p\_Z(z) = \sum\_{-\infty}^{\infty} p\_{XY}(x, z - x)\\] 1. $Z = Y/X$ then \\[f\_Z(z) = \sum\_{-\infty}^{\infty} |x| p\_{XY}(x, xz) dx \\] ### Continuous case 1. $Z = X + Y$ then \\[p\_Z(z) = \int\_{-\infty}^{\infty} f\_{XY}(x, z - x)\\] 1. $Z = Y/X$ then \\[f\_Z(z) = \sum\_{-\infty}^{\infty} |x| f\_{XY}(x, xz) dx \\] ] --- layout: true class: center, middle, inverse --- # Functions of Jointly Distributed Random Variables ## The General Case: $Z = g(X,Y)$ --- layout:false .left-column[ ### $Z = g(X,Y)$ ] .right-column[ ### Revisiting the Last Example Suppose that $X$ and $Y$ are two random variables with joint distribution given by $f\_{XY}(x,y)$ and that $u = g\_1(x, y)$ and $v = g\_2(x,y)$. If we can invert both $U$ and $V$ to get $X = h\_1(u, v)$ and $Y = h\_2(u, v)$ and we can get the Jacobian: \\[ J(x,y) = \begin{bmatrix} \frac{ \partial u}{ \partial x} & \frac{ \partial v}{ \partial x} \\ \frac{ \partial u}{ \partial y} & \frac{ \partial v}{ \partial y} \\ \end{bmatrix} \\] and the determinate of the Jacobian is not always 0 then \\[ f\_{UV}(u,v) = f\_{XY}(h\_1(u,v), h\_2(u,v))| J^{-1}(h\_1(u,v), h\_2(u,v)) | \\] ] ---
Markdown
UTF-8
1,467
3.09375
3
[]
no_license
# LETTers Solution Report - Date: 12 April 2018 - Author: JackieZhai - Problem ID: [POJ3104](http://poj.org/problem?id=3468) ## Description modeling - 有一些衣服,每件衣服有一定水量,有一个烘干机,每次可以烘一件衣服,每分钟可以烘掉M滴水 - 每件衣服没分钟可以自动蒸发掉一滴水,用烘干机烘衣服时不蒸发 - 问最少需要多少时间能烘干所有的衣服 ## Points in solving - 用二分法求解 - 题意是烘干机烘干的时候不会自然掉水 - 转化为烘干机每分钟掉M-1水,这样所有都是自然烘干掉1水了 ## Warnings - 注意烘干机烘的过程中,不会自动掉一滴水! ```c++ #include <cstdio> #include <iostream> #include <algorithm> using namespace std; const int INF=0x3f3f3f3f, MAX_N=100007; int N, M; long long x[MAX_N]; bool C(int minu) { int coun=0; for(int i=0; i<N; i++) { if(x[i]-minu>0) { int xre=x[i]-minu; if(xre%(M-1)==0) coun+=xre/(M-1); else coun+=xre/(M-1)+1; if(coun>minu) return false; } } return true; } int main() { scanf("%d", &N); for(int i=0; i<N; i++) scanf("%lld", &x[i]); scanf("%d", &M); if(M==1) { int ans=0; for(int i=0; i<N; i++) if(ans<x[i]) ans=x[i]; printf("%d\n", ans); } else { int lb=0, ub=INF; while(ub-lb>1) { int mid=(ub+lb)/2; if(C(mid)) ub=mid; else lb=mid; } printf("%d\n", ub); } return 0; } ```
Swift
UTF-8
876
2.65625
3
[]
no_license
// // Navigator.swift // TestSwift // // Created by jianqiang on 17/4/18. // Copyright © 2017年 jianqiang. All rights reserved. // import Foundation import UIKit class Navigator { static var myNavigator: Navigator? = nil; private init() { } static func getInstance() -> Navigator { if myNavigator == nil { myNavigator = Navigator() } return myNavigator! } var nav: UINavigationController? = nil func navigateTo(_ viewController: String) { navigateTo(viewController, nil) } func navigateTo(_ viewController: String, _ params: Dictionary<String, NSObject>?) { let classObject = Reflect.getClassFromString(viewController)! classObject.params = params nav?.pushViewController(classObject, animated: true) } }
Java
UTF-8
2,198
2.640625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2016 Jonathan Beaudoin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xena.keylistener; import java.awt.event.KeyEvent; import java.util.function.Consumer; import static org.xena.keylistener.NativeKeyUtils.*; /** * Created by Jonathan on 9/20/2015. */ public final class NativeKeyCombination { private final int modifiers; private final int[] keys; private final Consumer<NativeKeyEvent> event; public NativeKeyCombination(Consumer<NativeKeyEvent> event, int modifiers, int... keys) { this.modifiers = modifiers; this.keys = keys; this.event = event; } void exec(NativeKeyEvent e) { event.accept(e); } boolean matches(NativeKeyEvent event) { if ((modifiers & CONTROL) != CONTROL && isCtrlDown() || (modifiers & CONTROL) == CONTROL && !isCtrlDown()) { return false; } if ((modifiers & SHIFT) != SHIFT && isShiftDown() || (modifiers & SHIFT) == SHIFT && !isShiftDown()) { return false; } if ((modifiers & ALT) != ALT && isAltDown() || (modifiers & ALT) == ALT && !isAltDown()) { return false; } for (int i : keys) { if (event.getKeyCode() == i) { return true; } } return false; } @Override public String toString() { if (keys[0] == -1) { return "None"; } StringBuilder builder = new StringBuilder(); for (int key : keys) { builder.append(KeyEvent.getKeyText(key)).append(", "); } String s = builder.toString(); if ((modifiers & ALT) == ALT) { s = "Alt + [" + s + "]"; } if ((modifiers & SHIFT) == SHIFT) { s = "Shift + [" + s + "]"; } if ((modifiers & CONTROL) == CONTROL) { s = "Ctrl + [" + s + "]"; } return s; } }
C#
UTF-8
216
2.8125
3
[]
no_license
using System; namespace AdvancedWorld { public abstract class FemaleHuman : Human { public FemaleHuman(String name, int age) : base(name, age, Sex.Female) { } } }
JavaScript
UTF-8
362
2.59375
3
[]
no_license
function init() { var canvas = document.getElementById("game_canvas"); var context = canvas.getContext('2d'); var spriteSheet = new Image(); spriteSheet.onload = function(){ context.drawImage(spriteSheet, 324, 0, 462, 140, 0, 0, 462, 140); context.drawImage(spriteSheet, 83, 23, 15, 15, 35, 33, 15, 15); }; spriteSheet.src = 'pacman10-hp-sprite.png'; }
PHP
UTF-8
1,512
2.984375
3
[]
no_license
<?php class errorController extends Controller { //Inicializa las variables de la aplicación public function __construct() { parent::__construct(); } //Crea la vista de error public function index() { $this->_view->assign('titulo', 'Error'); $this->_view->assign('mensaje', $this->_getError()); $this->_view->renderizar('index'); } //Crea la vista de error de acceso segun algun codigo que se halla mandado. public function access($codigo) { $this->_view->assign('titulo', 'Error'); $this->_view->assign('mensaje', $this->_getError($codigo)); $this->_view->renderizar('access'); } //Devuelve un error según el codigo especificado, sino exite se manda al predeterminado. private function _getError($codigo = false) { if($codigo){ $codigo = $this->filtrarInt($codigo); if(is_int($codigo)) $codigo = $codigo; } else{ $codigo = 'default'; } $error['default'] = 'Ha ocurrido un error y la página no puede mostrarse'; $error['5050'] = 'Acceso restringido!'; $error['8080'] = 'Tiempo de la sesion agotado'; //comprueba y devuelve el error segun el codigo, caso contrario el predeterminado. if(array_key_exists($codigo, $error)){ return $error[$codigo]; } else{ return $error['default']; } } } ?>
Java
UTF-8
1,412
2.734375
3
[ "Apache-2.0" ]
permissive
package com.jalat.logging; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.function.Supplier; /** * Logger over {@code SLF4J} * * @author Andrey Paslavsky * @since 0.1 */ final class Slf4jLogger implements Logger { private final org.slf4j.Logger logger; Slf4jLogger(Class<?> aCLass) { logger = org.slf4j.LoggerFactory.getLogger(aCLass); } @Override public void error(@Nonnull Supplier<String> message, @Nullable Throwable error) { if (logger.isErrorEnabled()) { logger.error(message.get(), error); } } @Override public void warning(@Nonnull Supplier<String> message, @Nullable Throwable error) { if (logger.isWarnEnabled()) { logger.warn(message.get(), error); } } @Override public void info(@Nonnull Supplier<String> message, @Nullable Throwable error) { if (logger.isInfoEnabled()) { logger.info(message.get(), error); } } @Override public void debug(@Nonnull Supplier<String> message, @Nullable Throwable error) { if (logger.isDebugEnabled()) { logger.debug(message.get(), error); } } @Override public void trace(@Nonnull Supplier<String> message, @Nullable Throwable error) { if (logger.isTraceEnabled()) { logger.trace(message.get(), error); } } }
Java
UTF-8
2,871
2.625
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 Business; import java.sql.Date; import java.util.ArrayList; /** * * @author Eric */ public class CourseOffering { private String courseOfferingID; private Course course; private Semester semester; private Teacher teacher; private ArrayList<Seat> seatList; private ClassRoom classRoom; private String teacherID; private String room; private String building; private String year; private String season; private String courseName; public CourseOffering() { seatList = new ArrayList<Seat>(); course = new Course(); semester = new Semester(); teacher = new Teacher(); classRoom = new ClassRoom(); } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public ClassRoom getClassRoom() { return classRoom; } public void setClassRoom(ClassRoom classRoom) { this.classRoom = classRoom; } public String getCourseOfferingID() { return courseOfferingID; } public void setCourseOfferingID(String courseOfferingID) { this.courseOfferingID = courseOfferingID; } public ArrayList<Seat> getSeatList() { return seatList; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public Semester getSemester() { return semester; } public void setSemester(Semester semester) { this.semester = semester; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public ArrayList<Seat> getSeat() { return seatList; } public Seat addSeat(){ Seat seat = new Seat(); seatList.add(seat); return seat; } public String getTeacherID() { return teacherID; } public void setTeacherID(String teacherID) { this.teacherID = teacherID; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } public String getBuilding() { return building; } public void setBuilding(String building) { this.building = building; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getSeason() { return season; } public void setSeason(String season) { this.season = season; } }
Java
UTF-8
602
3.53125
4
[]
no_license
// Dawid Paluszak // Pracownia PO, czwartek, s. 108 // L5, z1, Por�wnywalna hierarchia klas // Figury // Kolo.java // 2018-03-29 // klasa przechowuj�ca ko�a public class Kolo extends Figury { double promien; public Kolo(double r) { promien = r; } @Override public double pole() { return promien * promien * 3.14159265359; } @Override public double obwod() { return 2 * promien * 3.14159265359; } @Override public String toString() { String str = "Kolo: promien: " + promien ; str = str +" obwod: " + obwod() + " pole: " + pole(); return str; } }
C
UTF-8
612
3.4375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #define SSIZE_MAX 1048576 // 1MiB int main(int argc, char **argv) { int i; int fd; char buffer[SSIZE_MAX]; if (argc < 2) { printf("Missing argument, aborting\n"); return EXIT_FAILURE; } for (i = 1; i < argc; i++) { if((fd = open(argv[i], O_RDONLY)) == -1) { printf("Error while opening file, aborting\n"); return EXIT_FAILURE; } read(fd, buffer, SSIZE_MAX); printf("%s\n", buffer); } close(fd); return EXIT_SUCCESS; }
C#
UTF-8
1,103
3.734375
4
[ "MIT" ]
permissive
// Justification: Checking for null isn't discussed yet. #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_21; public class TicTacToe // Declares the TicTacToe class { public static void Main() // Declares the entry point of the program { #region INCLUDE string input; // Prompt the user to select a 1- or 2- player game Console.Write($""" 1 - Play against the computer 2 - Play against another player. Choose: """ ); input = Console.ReadLine(); #region HIGHLIGHT if (input == "1") // The user selected to play the computer Console.WriteLine( "Play against computer selected."); else // Default to 2 players (even if user didn't enter 2) Console.WriteLine( "Play against another player."); #endregion HIGHLIGHT #endregion INCLUDE } }
Shell
UTF-8
1,023
2.65625
3
[]
no_license
# vim: set noexpandtab ts=4 ft=sh: # Gentoo Zope Instance configure tool config file. # # Originally written by Jason Shoemaker <kutsuya@gentoo.org> # Portions by Jodok Batlogg <batlogg@gentoo.org> (Logging and some cleanups) # Portions by Robin Johnson <robbat2@gentoo.org> (Documentation and further cleanup) # # Copyright 1999-2004 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header: /var/cvsroot/gentoo-x86/app-admin/zope-config/files/0.5/zope-config.conf,v 1.1 2005/01/02 14:05:24 batlogg Exp $ # default name for new instances DEFAULT_ZINSTANCENAME="zope-" # Logging directory EVENTLOGDIR="/var/log/zope/" # you probably shouldn't change anything below this # ------------------------------------------------- # Name of zope user on your system ZUID=zope # This is where the real zope lives ZS_DIR="/usr/share/zope/" ZS_DIR2="/usr/lib/zope-" # This is where we will put our new instance of zope ZI_DIR="/var/lib/zope/" # place for init script # and it's associated configuration file INITD="/etc/init.d/" CONFD="/etc/conf.d/"
Java
UTF-8
1,016
3.296875
3
[]
no_license
import java.util.Scanner; public class imcCalcul { static Scanner read = new Scanner(System.in); public static void main(String[] args) { System.out.println("cc"); double taille = 1; double poids = 1; String restart; do { boolean error = true; while (error) { try { System.out.println("Entrer la taille en metre"); taille = read.nextDouble(); System.out.println("Entrer poids"); poids = read.nextDouble(); if (poids <= 0) System.out.println("Rentrer des valeurs positives"); else { double imc = poids / (taille * taille); System.out.println("Votre imc est de :" + imc); error = false; } } catch (Exception e) { // TODO: handle exception System.out.println("Erreur de saisie de la taille ou du poids : " + e.getMessage()); read.nextLine(); } } System.out.println("Voulez vous recommencer ? (oui/non)"); restart = read.next(); } while (restart.equals("oui")); System.out.println("Salut !"); } }
Java
UTF-8
3,264
3.03125
3
[]
no_license
// based on https://github.com/beryx/streamplify/blob/master/streamplify-examples/src/main/java/org/beryx/streamplify/example/Arrangements.java // answer to https://github.com/beryx/streamplify/issues/7 package permutations; import org.beryx.streamplify.combination.Combinations; import org.beryx.streamplify.permutation.Permutations; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class ArrangementsStreamplify { private final int n; private final int k; public ArrangementsStreamplify(int n, int k) { this.n = n; this.k = k; } public Stream<int[]> stream() { return new Combinations(n, k) .stream() .flatMap(comb -> new Permutations(k) .stream() .map(perm -> Arrays.stream(perm).map(p -> comb[p]).toArray())); } public Stream<int[]> parallelStream() { return new Combinations(n, k) .parallelStream() .flatMap(comb -> new Permutations(k) .parallelStream() .map(perm -> Arrays.stream(perm).map(p -> comb[p]).toArray())); } public static void main(String[] args) { /** * Demonstrates solution for the following problem:<pre> * Alice, Bob, Chloe, David, and Emma take part in a competition. * List all possible outcomes for the top 3 ranking.</pre> */ String[] names = {"Alice", "Bob", "Chloe", "David", "Emma"}; System.out.println(new ArrangementsStreamplify(5, 3) .stream() .map(arr -> Arrays.stream(arr).mapToObj(i -> names[i]).collect(Collectors.toList()).toString()) .collect(Collectors.joining("\n"))); System.out.println("\n-----------------------------------------------------------------------------------\n\n"); /** * k-permutations of n names from the input file */ try { String fileName = System.getProperty( "file", "23_names.txt" ); // get user name or use 'unknown' System.out.println("k-permutations of n names from the input file " + fileName ); System.out.println("press any key to continue or Ctrl^C to exit..."); System.in.read(); List<String> namesList = NamesFileUtil.readLines(new File(fileName)); String[] namesArray = namesList.toArray(new String[0]); // with improvement suggested at https://github.com/beryx/streamplify/issues/7#issuecomment-366178625 System.out.println("Permutations on array length " + namesArray.length + "\n"); Stream<String> permStream = new ArrangementsStreamplify(namesArray.length, 12) .stream() .map(arr -> Arrays.stream(arr).mapToObj(i -> namesArray[i]).collect(Collectors.toList()).toString()); permStream.forEach(System.out::println); System.out.println("-----------------------------------------------------------------------------------"); } catch (Exception ex) { System.out.println(ex.getStackTrace()); } } }
Java
UTF-8
1,326
3.328125
3
[]
no_license
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; /* 1,创建DatagramSocket 对象 ,绑定端口号 要和发送端一致 2,创建字符数组接收数据 3,创建DatagramPacket 对象接收数据 空参即可 4,调用DatagramSpcket 类的receive方法 5,拆包 发送的IP地址 DatagramPacket getAddress()获取发送端的地址 返回InetAddres对象 getHostAddress()可查询发送端地址 接收到的字节个数 数据包对象DatagramPacket类的对象getLength() 发送方的端口号 DatagramPacket getPort()获取发送端的端口号 int 6,关闭资源 */ public class UDPRDemo { public static void main(String[] args) throws IOException { DatagramSocket ds=new DatagramSocket(6000); byte[] data =new byte[1024*64]; while (true){ DatagramPacket dp=new DatagramPacket(data,data.length); ds.receive(dp); String ip=dp.getAddress().getHostAddress(); int port=dp.getPort(); //拆包 System.out.println(new String(data,0,dp.getLength())+"...."+ip+"...."+port); } } }
Markdown
UTF-8
5,265
2.5625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: 'Procedura: Creare una tabella a livello di codice' ms.date: 03/30/2017 dev_langs: - csharp - vb helpviewer_keywords: - tables [WPF], creating programmatically ms.assetid: e3ca88f3-6e94-4b61-82fc-42104c10b761 ms.openlocfilehash: 9c9061d3c4d6b3de5e1ab42a6b98c20813835ba8 ms.sourcegitcommit: 68653db98c5ea7744fd438710248935f70020dfb ms.translationtype: MT ms.contentlocale: it-IT ms.lasthandoff: 08/22/2019 ms.locfileid: "69964165" --- # <a name="how-to-build-a-table-programmatically"></a>Procedura: Creare una tabella a livello di codice Negli esempi seguenti viene illustrato come creare un oggetto a <xref:System.Windows.Documents.Table> livello di codice e compilarlo con il contenuto. Il contenuto della tabella è ripartito in cinque righe (rappresentate da <xref:System.Windows.Documents.TableRow> oggetti contenuti in un <xref:System.Windows.Documents.Table.RowGroups%2A> oggetto) e sei colonne ( <xref:System.Windows.Documents.TableColumn> rappresentate da oggetti). Le righe vengono usate per scopi di presentazione diversi, ad esempio una riga è destinata a contenere il titolo dell'intera tabella, una riga di intestazione a descrivere le colonne di dati nella tabella e una riga di piè di pagina a fornire informazioni di riepilogo. Si noti che i concetti di righe di "titolo", "intestazione" e "piè di pagina" non sono inerenti alla tabella, ma fanno semplicemente riferimento a righe con caratteristiche diverse. Le celle della tabella contengono il contenuto effettivo, che può essere costituito da testo, immagini o quasi tutti [!INCLUDE[TLA#tla_ui](../../../../includes/tlasharptla-ui-md.md)] gli altri elementi. ## <a name="example"></a>Esempio Viene innanzitutto creato <xref:System.Windows.Documents.FlowDocument> un oggetto per ospitare l' <xref:System.Windows.Documents.Table>oggetto e viene <xref:System.Windows.Documents.FlowDocument>creato <xref:System.Windows.Documents.Table> un nuovo oggetto che viene aggiunto al contenuto di. [!code-csharp[TableSnippets#_TableCreate](~/samples/snippets/csharp/VS_Snippets_Wpf/TableSnippets/CSharp/Table.cs#_tablecreate)] [!code-vb[TableSnippets#_TableCreate](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TableSnippets/VisualBasic/Table.vb#_tablecreate)] ## <a name="example"></a>Esempio Successivamente, vengono <xref:System.Windows.Documents.TableColumn> creati sei oggetti e aggiunti alla <xref:System.Windows.Documents.Table.Columns%2A> raccolta della tabella, con una formattazione applicata. > [!NOTE] > Si noti che la <xref:System.Windows.Documents.Table.Columns%2A> raccolta della tabella usa l'indicizzazione standard in base zero. [!code-csharp[TableSnippets#_TableCreateColumns](~/samples/snippets/csharp/VS_Snippets_Wpf/TableSnippets/CSharp/Table.cs#_tablecreatecolumns)] [!code-vb[TableSnippets#_TableCreateColumns](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TableSnippets/VisualBasic/Table.vb#_tablecreatecolumns)] ## <a name="example"></a>Esempio Viene quindi creata una riga del titolo che viene aggiunta alla tabella con l'applicazione di alcuni elementi di formattazione. La riga del titolo può contenere una sola cella che si estende su tutte e sei le colonne della tabella. [!code-csharp[TableSnippets#_TableAddTitleRow](~/samples/snippets/csharp/VS_Snippets_Wpf/TableSnippets/CSharp/Table.cs#_tableaddtitlerow)] [!code-vb[TableSnippets#_TableAddTitleRow](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TableSnippets/VisualBasic/Table.vb#_tableaddtitlerow)] ## <a name="example"></a>Esempio Successivamente, viene creata e aggiunta alla tabella una riga di intestazione, per la quale vengono create celle in cui viene inserito contenuto. [!code-csharp[TableSnippets#_TableAddHeaderRow](~/samples/snippets/csharp/VS_Snippets_Wpf/TableSnippets/CSharp/Table.cs#_tableaddheaderrow)] [!code-vb[TableSnippets#_TableAddHeaderRow](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TableSnippets/VisualBasic/Table.vb#_tableaddheaderrow)] ## <a name="example"></a>Esempio Successivamente, viene creata e aggiunta alla tabella una riga per i dati, per la quale vengono create celle in cui viene inserito contenuto. La compilazione di questa riga è simile alla compilazione della riga di intestazione, con l'applicazione di una formattazione leggermente diversa. [!code-csharp[TableSnippets#_TableAddDataRow](~/samples/snippets/csharp/VS_Snippets_Wpf/TableSnippets/CSharp/Table.cs#_tableadddatarow)] [!code-vb[TableSnippets#_TableAddDataRow](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TableSnippets/VisualBasic/Table.vb#_tableadddatarow)] ## <a name="example"></a>Esempio Infine, viene creata, aggiunta e formattata una riga di piè di pagina. Analogamente alla riga del titolo, il piè di pagina contiene una sola cella che si estende su tutte e sei le colonne della tabella. [!code-csharp[TableSnippets#_TableAddFooterRow](~/samples/snippets/csharp/VS_Snippets_Wpf/TableSnippets/CSharp/Table.cs#_tableaddfooterrow)] [!code-vb[TableSnippets#_TableAddFooterRow](~/samples/snippets/visualbasic/VS_Snippets_Wpf/TableSnippets/VisualBasic/Table.vb#_tableaddfooterrow)] ## <a name="see-also"></a>Vedere anche - [Cenni preliminari sull'elemento Table](table-overview.md)
Markdown
UTF-8
2,753
3
3
[]
no_license
# StetsonHomeAutomation Home automation (lights, audio, etc) for the Stetson household. :warning: Abandonware! :warning: * [Statement to Potential Employers](#statement-to-potential-employers) This repo contains the half-finished abandonware attempt at creating a touch-sensitive panel for interacting with various smart home devices in the house. This was largely abandoned due to issues with the hardware at the house with which this interfaces. ### Design and Issues This was designed to run on a raspberry pi with an attached touch screen. This design was successful, but the screen's housing that I purchased was too small by a centimeter, so the screen never fit, and I just never got a new housing. So the unit was sitting on a table with exposed electronics for kids and cats to mess with. In its current state, it is capable of turning my lights on/off and setting their colors. It is also capable of switching the inputs and outputs on my Onkyo audio receiver with the help of an attached Arduino that has an infrared LED attached to it. You'll see some COM port signals being exchanged between the pi and arduino in some code modules. One of the features was a plugin system for adding games to one of the panels, allowing people near one of the devices to have a little fun while sitting around. I added a Magic 8-ball app, but never finished the plugin architecture and left code in the `__init__.py`, so ... another thing abandoned. The kivy UI did work quite handsomely on the PC, but stuttered quite a bit on the RPi which was disappointing. Kivy did present a bit of a barrier since it had so many dependencies that needed to be installed in order to iterate on the code, and no two PCs in my house had the same modules installed. The smartest idea would have been to set up a docker container with python3 and all required modules, including kivy, ready to go on any machine, but I never graduated to that point. ### Future I hestitate to drop this repo from my github in case I ever come back to it in my free time, especially now that Kivy has matured. My guess is that, if I ever did pick this up, I'd likely use PyQt since I am so familiar with it and it is supported on so many platforms, but kivy does have its appeal particularly in the realm of mobile. I also hesitate to leave this in my github repo for fear that it will reflect poorly on my ability to write code, but decided that I'll reconcile that fear with this: ## STATEMENT TO POTENTIAL EMPLOYERS This code is in an infantile stage and does not represent my best work. While somewhat functional, it is by no means my best attempt to make something usable, readable, pretty, or representative of my skill. Ok, be well, all.
C
UTF-8
12,601
2.59375
3
[]
no_license
/* *------------------------------------------------------------------------------ * schedular.c * /* *------------------------------------------------------------------------------ * Include Files *------------------------------------------------------------------------------ */ #include "board.h" #include "config.h" #include "schedular.h" /* *------------------------------------------------------------------------------ * Private Defines *------------------------------------------------------------------------------ */ /* *------------------------------------------------------------------------------ * Private Macros *------------------------------------------------------------------------------ */ /* *------------------------------------------------------------------------------ * Private Data Types *------------------------------------------------------------------------------ */ /* *------------------------------------------------------------------------------ * Public Variables *------------------------------------------------------------------------------ */ #pragma udata sch_data // The array of tasks stTask SchedularTaks[SCH_MAX_TASKS]; // Used to display the error code UINT8 ErrorCode; #pragma udata /* *------------------------------------------------------------------------------ * Private Variables (static) *------------------------------------------------------------------------------ */ // Keeps track of time since last error was recorded static UINT16 ErrorTickCount; // The code of the last error (reset after ~1 minute) static UINT8 LastErrorCode; /* *------------------------------------------------------------------------------ * Public Constants *------------------------------------------------------------------------------ */ /* *------------------------------------------------------------------------------ * Private Constants (static) *------------------------------------------------------------------------------ */ /* *------------------------------------------------------------------------------ * Private Function Prototypes (static) *------------------------------------------------------------------------------ */ static void SCH_GoToSleep(void); static void SCH_ReportStatus(void); /* *------------------------------------------------------------------------------ * Public Functions *------------------------------------------------------------------------------ */ /* *------------------------------------------------------------------------------ * void SCH_init(void) * Summary : Scheduler initialisation function. Prepares scheduler * data structures and sets up timer interrupts at required rate. * Must call this function before using the scheduler. * * Input : None * * Output : None * *------------------------------------------------------------------------------ */ void SCH_init(void) { UINT8 taskIndex; for (taskIndex = 0; taskIndex < SCH_MAX_TASKS; taskIndex++) { SCH_DeleteTask(taskIndex); } ErrorCode = 0; //Reset the global error variable } /* *------------------------------------------------------------------------------ * void SCH_Update(void) * Summary : This is the scheduler routine. It is called at a rate * determined by the timer settings in InitSchedularTimer(). * This is triggered by Timer 0 interrupts. * * Input : None * * Output : None * *------------------------------------------------------------------------------ */ void SCH_Update(void) { UINT8 Index; // NOTE: calculations are in *TICKS* (not milliseconds) for (Index = 0; Index < SCH_MAX_TASKS; Index++) { // Check if there is a task at this location if (SchedularTaks[Index].mpTaskPointer) { if (SchedularTaks[Index].mStartupDelay == 0) { // The task is due to run SchedularTaks[Index].mRunMe += 1; // Inc. the 'Run Me' flag if (SchedularTaks[Index].mTaskFrequency) { // Schedule periodic tasks to run again SchedularTaks[Index].mStartupDelay = SchedularTaks[Index].mTaskFrequency; } } else { // Not yet ready to run: just decrement the mStartupDelay SchedularTaks[Index].mStartupDelay -= 1; } } } } /* *------------------------------------------------------------------------------ * void SCH_Start(void) * Summary : Starts the scheduler, by enabling interrupts. * to keep the tasks synchronised. * * Input : None * * Output : None * * Note : Usually called after all regular tasks are added. * ONLY THE SCHEDULER INTERRUPT SHOULD BE ENABLED! * *------------------------------------------------------------------------------ */ void SCH_Start(void) { // Enable interrupt priority RCONbits.IPEN = 1; // Enable all high priority interrupts INTCONbits.GIEH = 1; EXIT_CRITICAL_SECTION(); } /* *------------------------------------------------------------------------------ * void SCH_DispatchTasks(void) * Summary : This is the 'dispatcher' function. When a task (function) * is due to run, SCH_DispatchTasks() will run it. * This function must be called (repeatedly) from the main loop. * * Input : None * * Output : None * *------------------------------------------------------------------------------ */ void SCH_DispatchTasks(void) { UINT8 index; // Dispatches (runs) the next task (if one is ready) for (index = 0; index < SCH_MAX_TASKS; index++) { if (SchedularTaks[index].mRunMe > 0) { (*SchedularTaks[index].mpTaskPointer)(); // Run the task SchedularTaks[index].mRunMe -= 1; // Reset / reduce mRunMe flag // Periodic tasks will automatically run again // if this is a 'one shot' task, remove it from the array if (SchedularTaks[index].mTaskFrequency == 0) { SCH_DeleteTask(index); } } } // Report system status SCH_ReportStatus(); // The scheduler enters idle mode at this point SCH_GoToSleep(); } /* *------------------------------------------------------------------------------ * UINT8 SCH_AddTask(void (far rom void * pFunction)(), * const UINT16 Delay, * const UINT16 Period) * * Summary : Causes a task (function) to be executed at regular intervals * or after a user-defined delay. * * Input : pFunction - The name of the function which is to be scheduled. * NOTE: All scheduled functions must be 'void,that is, they must * take no parameters, and have a void return type. * * Delay - The interval (TICKS) before the task is first executed * * Period - If 'Period' is 0, the function is only called once, * at the time determined by 'Delay'. If Period is non-zero, * then the function is called repeatedly at an interval * determined by the value of mTaskFrequency (see below for examples * which should help clarify this). * * * Output : Returns the position in the task array at which the task has been * added. If the return value is SCH_MAX_TASKS then the task could * not be added to the array (there was insufficient space). If the * return value is < SCH_MAX_TASKS, then the task was added * successfully. * * Note : this return value may be required, if a task is * to be subsequently deleted - see SCH_DeleteTask(). * * Examples : Task_ID = SCH_AddTask(Do_X,1000,0); * Causes the function Do_X() to be executed once after 1000 sch ticks. * * Task_ID = SCH_AddTask(Do_X,0,1000); * Causes the function Do_X() to be executed regularly, every 1000 sch ticks. * * Task_ID = SCH_AddTask(Do_X,300,1000); * Causes the function Do_X() to be executed regularly, every 1000 ticks. * Task will be first executed at T = 300 ticks, then 1300, 2300, etc. * *------------------------------------------------------------------------------ */ UINT8 SCH_AddTask(rom void (*pFunction)(), const UINT16 Delay, const UINT16 Period) { UINT8 Index = 0; // First find a gap in the array (if there is one) while ((SchedularTaks[Index].mpTaskPointer != 0) && (Index < SCH_MAX_TASKS)) { Index++; } // Have we reached the end of the list? if (Index == SCH_MAX_TASKS) { // Task list is full // Set the global error variable ErrorCode = ERROR_SCH_TOO_MANY_TASKS; // Also return an error code return SCH_MAX_TASKS; } // If we're here, there is a space in the task array SchedularTaks[Index].mpTaskPointer = pFunction; SchedularTaks[Index].mStartupDelay = Delay; SchedularTaks[Index].mTaskFrequency = Period; SchedularTaks[Index].mRunMe = 0; // return position of task (to allow later deletion) return Index; } /* *------------------------------------------------------------------------------ * BOOL SCH_DeleteTask(const UINT8 taskIndex) * Summary : Removes a task from the scheduler. Note that this does * not delete the associated function from memory: * it simply means that it is no longer called by the scheduler * * Input : const UINT8 taskIndex- The task index. Provided by SCH_AddTask(). * * Output : BOOL - RETURN_ERROR or RETURN_NORMAL * *------------------------------------------------------------------------------ */ BOOL SCH_DeleteTask(const UINT8 taskIndex) { BOOL Return_code; if (SchedularTaks[taskIndex].mpTaskPointer == 0) { // No task at this location... // Set the global error variable ErrorCode = ERROR_SCH_CANNOT_DELETE_TASK; // also return an error code Return_code = RETURN_ERROR; } else { Return_code = RETURN_NORMAL; } SchedularTaks[taskIndex].mpTaskPointer = 0x0000; SchedularTaks[taskIndex].mStartupDelay = 0; SchedularTaks[taskIndex].mTaskFrequency = 0; SchedularTaks[taskIndex].mRunMe = 0; return Return_code; // return status } /* *------------------------------------------------------------------------------ * Private Functions *------------------------------------------------------------------------------ */ /* *------------------------------------------------------------------------------ * void SCH_ReportStatus(void) * Summary : Simple function to display error codes.This displays code on a * port with attached LEDs adapt, if required, to report errors * over serial link, etc.Errors are only displayed for a limited * Period (60000 ticks = 1 minute at 1ms tick interval). * After this the the error code is reset to 0.This code may be * easily adapted to display the last error 'for ever'. * * Input : None * * Output : None * *------------------------------------------------------------------------------ */ void SCH_ReportStatus(void) { #ifdef SCH_REPORT_ERRORS // Only applies if we are reporting errors. // Check for a new error code if (ErrorCode != LastErrorCode) { // Negative logic on LEDs assumed Error_port = 255 - ErrorCode; LastErrorCode = ErrorCode; if (ErrorCode != 0) { ErrorTickCount = 60000; } else { ErrorTickCount = 0; } } else { if (ErrorTickCount != 0) { if (--ErrorTickCount == 0) { ErrorCode = 0; // Reset error code } } } #endif } /* *------------------------------------------------------------------------------ * void SCH_GoToSleep(void) * Summary : This scheduler enters 'idle mode' between clock ticks to save power. * The next clock tick will return the processor to the normal * operating state. * * Input : None * * Output : None * * Note : A slight performance improvement is possible if this function is * implemented as a macro, or if the code here is simply pasted into * the 'dispatch' function. However, by making this a function call, * it becomes easier - during development - to assess the performance * of the scheduler, using the 'performance analyser'. May wish to * disable this if using a watchdog. * *------------------------------------------------------------------------------ */ void SCH_GoToSleep(void) { //PCON |= 0x01; // Enter idle mode (generic 8051 version) // Entering idle mode requires TWO consecutive instructions // on 80c515 / 80c505 - to avoid accidental triggering //PCON |= 0x01; // Enter idle mode (#1) //PCON |= 0x20; // Enter idle mode (#2) } /* * End of schedular.c */
C#
UTF-8
274
3.765625
4
[]
no_license
public static T CheckNull<T>(Func<T> canBeNull) where T : class { try { return canBeNull(); } catch (NullReferenceException) { return default(T); } }
Python
UTF-8
852
2.984375
3
[]
no_license
#feito no python 3.6.2 import struct import sys if len(sys.argv) != 2: print ('USO %s [CEP]' % sys.argv[0]) quit() registroCEP = struct.Struct("72s72s72s72s2s8s2s") cepColumn = 5 print ("Tamanho da Estrutura: %d" % registroCEP.size) f = open("cep_ordenado.dat","r") line = f.read(registroCEP.size) while line != "": record = registroCEP.unpack(line) if record[cepColumn] == sys.argv[1]: for i in range(0,len(record)-1): print (record[i]) # .decode('latin1') break line = f.read(registroCEP.size) counter += 1 print ("Total de Registros Lidos: %d" % counter) f.close() def buscabinaria(vet, cep): esquerda, direita, tentativa = 0, len(vet), 1 while 1: meio = (esquerda + direita) // 2 aux_cep = vet[meio] if cep == aux_cep: return tentativa elif cep > aux_cep: esquerda = meio else: direita = meio tentativa += 1
JavaScript
UTF-8
435
3.609375
4
[]
no_license
// Asked by Google // Given a string input 'ABIJYAB'm return first recurrent letter - A. // O(n) const find = (str) => { let cache = {}; for (let i = 0; i < str.length; i++) { if (cache[str[i]]) { return str[i]; } cache[str[i]] = true; } } let start = new Date().getTime(); let res = find('AKJHGUFJYGHVFUBIJYAB'); let end = new Date().getTime(); console.log('Result:', res, `execution time: ${end - start}`);
Java
UTF-8
18,728
1.625
2
[]
no_license
package binos.yarn; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.URI; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.SynchronousQueue; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Arrays; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.AMRMProtocol; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.ContainerManager; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest; import org.apache.hadoop.yarn.api.records.AMResponse; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.ContainerToken; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnRemoteException; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.util.Records; import com.google.common.collect.*; public class ApplicationMaster { private static final Log LOG = LogFactory.getLog(ApplicationMaster.class); private ApplicationAttemptId appAttemptId; private Configuration conf; private YarnRPC rpc; private AMRMProtocol resourceManager; private String binosHome; private int totalSlaves; private int slaveMem; private int slaveCpus; private int masterMem; private int masterPort; private int slavePort; private int failCount; private String logDirectory; //private String mainClass; private String programArgs; //private URI jarUri; private Process master; private String masterUrl; private Process application; private boolean appExited = false; private int appExitCode = -1; private int requestId = 0; // For giving unique IDs to YARN resource requests // Have a cache of UGIs on different nodes to avoid creating too many RPC // client connection objects to the same NodeManager private Map<String, UserGroupInformation> ugiMap = new HashMap<String, UserGroupInformation>(); public static void main(String[] args) throws Exception { new ApplicationMaster(args).run(); } public ApplicationMaster(String[] args) throws Exception { try { Options opts = new Options(); opts.addOption("yarn_timestamp", true, "YARN cluster timestamp"); opts.addOption("yarn_id", true, "YARN application ID"); opts.addOption("yarn_fail_count", true, "YARN application fail count"); opts.addOption("binos_home", true, "directory where Binos is installed"); opts.addOption("slaves", true, "number of slaves"); opts.addOption("slave_mem", true, "memory per slave, in MB"); opts.addOption("slave_cpus", true, "CPUs to use per slave"); opts.addOption("master_mem", true, "memory for master, in MB"); opts.addOption("master_port", true, "port for master service (default: 6060)"); opts.addOption("slave_port", true, "port for slave service (default: 6061)"); opts.addOption("class", true, "main class of application"); opts.addOption("args", true, "command line arguments for application"); //opts.addOption("jar_uri", true, "full URI of the application JAR to download"); opts.addOption("log_dir", true, "log directory for our container"); CommandLine line = new GnuParser().parse(opts, args); // Get our application attempt ID from the command line arguments ApplicationId appId = Records.newRecord(ApplicationId.class); appId.setClusterTimestamp(Long.parseLong(line.getOptionValue("yarn_timestamp"))); appId.setId(Integer.parseInt(line.getOptionValue("yarn_id"))); //int failCount = Integer.parseInt(line.getOptionValue("yarn_fail_count")); failCount = Integer.parseInt(line.getOptionValue("yarn_fail_count", "1")); appAttemptId = Records.newRecord(ApplicationAttemptId.class); appAttemptId.setApplicationId(appId); appAttemptId.setAttemptId(1); LOG.info("Application ID: " + appId + ", fail count: " + failCount); // Get other command line arguments binosHome = line.getOptionValue("binos_home", System.getenv("BINOS_HOME")); logDirectory = line.getOptionValue("log_dir"); totalSlaves = Integer.parseInt(line.getOptionValue("slaves")); slaveMem = Integer.parseInt(line.getOptionValue("slave_mem")); slaveCpus = Integer.parseInt(line.getOptionValue("slave_cpus")); masterMem = Integer.parseInt(line.getOptionValue("master_mem")); masterPort = Integer.parseInt(line.getOptionValue("master_port", "6060")); slavePort = Integer.parseInt(line.getOptionValue("slave_port", "6061")); programArgs = line.getOptionValue("args", ""); // Set up our configuration and RPC conf = new Configuration(); rpc = YarnRPC.create(conf); } catch (ParseException e) { System.err.println("Failed to parse command line options: " + e.getMessage()); System.exit(1); } } private void run() throws IOException { LOG.info("Starting application master"); LOG.info("Working directory is " + new File(".").getAbsolutePath()); resourceManager = connectToRM(); registerWithRM(); /*LOG.info("Downloading job JAR from " + jarUri); FileSystem fs = FileSystem.get(jarUri, conf); fs.copyToLocalFile(new Path(jarUri), new Path("job.jar"));*/ startBinosMaster(); // Start and manage the slaves int slavesLaunched = 0; int slavesFinished = 0; boolean sentRequest = false; List<ResourceRequest> noRequests = new ArrayList<ResourceRequest>(); List<ContainerId> noReleases = new ArrayList<ContainerId>(); while (slavesFinished != totalSlaves && !appExited) { AMResponse response; if (!sentRequest) { sentRequest = true; ResourceRequest request = createRequest(totalSlaves); LOG.info("Making resource request: " + request); response = allocate(Lists.newArrayList(request), noReleases); } else { response = allocate(noRequests, noReleases); } for (Container container: response.getAllocatedContainers()) { LOG.info("Launching container on " + container.getNodeId().getHost()); launchContainer(container); slavesLaunched++; if (slavesLaunched == totalSlaves) { LOG.info("All slaves launched; starting user application"); try { Thread.sleep(3000); } catch (InterruptedException e) {} //startApplication(); } } for (ContainerStatus container: response.getCompletedContainersStatuses()) { LOG.info("Container finished: " + container.getContainerId()); slavesFinished++; } try { Thread.sleep(1000); } catch (InterruptedException e) {} } boolean succeeded = false; if (appExited) { LOG.info("Shutting down because user application exited"); succeeded = (appExitCode == 0); } else { LOG.info("Shutting down because all containers died"); } /*master.destroy(); if (application != null) { application.destroy(); } unregister(succeeded);*/ } // Start binos-master and read its URL into binosUrl private void startBinosMaster() throws IOException { String[] command = new String[] {binosHome + "/bin/binos-master.sh", "--port=6060", "--log_dir=" + logDirectory}; System.out.println(Arrays.toString(command)); master = Runtime.getRuntime().exec(command); final SynchronousQueue<String> urlQueue = new SynchronousQueue<String>(); // Start a thread to redirect the process's stdout to a file new Thread("stdout redirector for app-master") { public void run() { BufferedReader in = new BufferedReader(new InputStreamReader(master.getInputStream())); PrintWriter out = null; try { out = new PrintWriter(new FileWriter(logDirectory + "/app-master.stdout")); String line = null; while ((line = in.readLine()) != null) { out.println(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) out.close(); } } }.start(); // Start a thread to get Binos-Master URL new Thread("Get Binos-Master URL") { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } BufferedReader in = null; try { in = new BufferedReader(new FileReader(logDirectory + "/binos-master.log")); boolean foundUrl = false; Pattern pattern = Pattern.compile(".*Master started at (.*)"); String line = null; while ((line = in.readLine()) != null) { if (!foundUrl) { Matcher m = pattern.matcher(line); if (m.matches()) { String url = m.group(1); urlQueue.put(url); foundUrl = true; } } } in.close(); } catch (Exception e) { e.printStackTrace(); } } }.start(); // Wait until we've read the URL while (masterUrl == null) { try { masterUrl = urlQueue.take(); } catch (InterruptedException e) {} } LOG.info("Binos master started with URL " + masterUrl); try { Thread.sleep(500); // Give binos-master a bit more time to start up } catch (InterruptedException e) {} } // Start the user's application /*private void startApplication() throws IOException { try { String sparkClasspath = getSparkClasspath(); String jobJar = new File("job.jar").getAbsolutePath(); String javaArgs = "-Xms" + (masterMem - 128) + "m -Xmx" + (masterMem - 128) + "m"; javaArgs += " -Djava.library.path=" + binosHome + "/lib/java"; String substitutedArgs = programArgs.replaceAll("\\[MASTER\\]", masterUrl); if (mainClass.equals("")) { javaArgs += " -cp " + sparkClasspath + " -jar " + jobJar + " " + substitutedArgs; } else { javaArgs += " -cp " + sparkClasspath + ":" + jobJar + " " + mainClass + " " + substitutedArgs; } String java = "java"; if (System.getenv("JAVA_HOME") != null) { java = System.getenv("JAVA_HOME") + "/bin/java"; } String bashCommand = java + " " + javaArgs + " 1>" + logDirectory + "/application.stdout" + " 2>" + logDirectory + "/application.stderr"; LOG.info("Command: " + bashCommand); String[] command = new String[] {"bash", "-c", bashCommand}; String[] env = new String[] {"BINOS_HOME=" + binosHome, "MASTER=" + masterUrl, }; application = Runtime.getRuntime().exec(command, env); new Thread("wait for user application") { public void run() { try { appExitCode = application.waitFor(); appExited = true; LOG.info("User application exited with code " + appExitCode); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); LOG.info("User application started"); } catch (BinosClasspathException e) { // Could not find the Spark classpath, either because SPARK_HOME is wrong or Spark wasn't compiled LOG.fatal(e.getMessage()); unregister(false); System.exit(1); return; } } private static class BinosClasspathException extends Exception { public BinosClasspathException(String message) { super(message); } } private String getSparkClasspath() throws YarnRemoteException, BinosClasspathException { String assemblyJar = null; // Find the target directory built by SBT File targetDir = new File(sparkHome + "/core/target"); if (!targetDir.exists()) { throw new SparkClasspathException("Path " + targetDir + " does not exist: " + "either you gave an invalid SPARK_HOME or you did not build Spark"); } // Look in target to find the assembly JAR for (File f: targetDir.listFiles()) { if (f.getName().startsWith("core-assembly") && f.getName().endsWith(".jar")) { assemblyJar = f.getAbsolutePath(); } } if (assemblyJar == null) { throw new SparkClasspathException("Could not find Spark assembly JAR in " + targetDir + ": " + "you probably didn't run sbt assembly"); } return assemblyJar; }*/ private AMRMProtocol connectToRM() { YarnConfiguration yarnConf = new YarnConfiguration(conf); InetSocketAddress rmAddress = NetUtils.createSocketAddr(yarnConf.get( YarnConfiguration.RM_SCHEDULER_ADDRESS, YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS)); LOG.info("Connecting to ResourceManager at " + rmAddress); return ((AMRMProtocol) rpc.getProxy(AMRMProtocol.class, rmAddress, conf)); } private void registerWithRM() throws YarnRemoteException { RegisterApplicationMasterRequest req = Records.newRecord(RegisterApplicationMasterRequest.class); req.setApplicationAttemptId(appAttemptId); req.setHost(""); req.setRpcPort(1); req.setTrackingUrl(""); resourceManager.registerApplicationMaster(req); LOG.info("Successfully registered with resource manager"); } private ResourceRequest createRequest(int totalTasks) { ResourceRequest request = Records.newRecord(ResourceRequest.class); request.setHostName("*"); request.setNumContainers(totalTasks); Priority pri = Records.newRecord(Priority.class); pri.setPriority(1); request.setPriority(pri); Resource capability = Records.newRecord(Resource.class); capability.setMemory(slaveMem); request.setCapability(capability); return request; } /** * launch binos-slave at allocated container. * @param container * @throws IOException */ private void launchContainer(Container container) throws IOException { ContainerManager mgr = connectToCM(container); ContainerLaunchContext ctx = Records.newRecord(ContainerLaunchContext.class); ctx.setContainerId(container.getId()); ctx.setResource(container.getResource()); ctx.setUser(UserGroupInformation.getCurrentUser().getShortUserName()); List<String> commands = new ArrayList<String> (); commands.add(binosHome + "/bin/binos-slave.sh " + "--port=" + (this.slavePort++) + " " + "--url=" + masterUrl + " " + "--log_dir=" + this.logDirectory ); ctx.setCommands(commands); StartContainerRequest req = Records.newRecord(StartContainerRequest.class); req.setContainerLaunchContext(ctx); mgr.startContainer(req); } private ContainerManager connectToCM(Container container) throws IOException { // Based on similar code in the ContainerLauncher in Hadoop MapReduce ContainerToken contToken = container.getContainerToken(); final String address = container.getNodeId().getHost() + ":" + container.getNodeId().getPort(); LOG.info("Connecting to ContainerManager at " + address); UserGroupInformation user = UserGroupInformation.getCurrentUser(); if (UserGroupInformation.isSecurityEnabled()) { if (!ugiMap.containsKey(address)) { Token<ContainerTokenIdentifier> hadoopToken = new Token<ContainerTokenIdentifier>( contToken.getIdentifier().array(), contToken.getPassword().array(), new Text(contToken.getKind()), new Text(contToken.getService())); user = UserGroupInformation.createRemoteUser(address); user.addToken(hadoopToken); ugiMap.put(address, user); } else { user = ugiMap.get(address); } } ContainerManager mgr = user.doAs(new PrivilegedAction<ContainerManager>() { public ContainerManager run() { YarnRPC rpc = YarnRPC.create(conf); return (ContainerManager) rpc.getProxy(ContainerManager.class, NetUtils.createSocketAddr(address), conf); } }); return mgr; } private AMResponse allocate(List<ResourceRequest> resourceRequest, List<ContainerId> releases) throws YarnRemoteException { AllocateRequest req = Records.newRecord(AllocateRequest.class); req.setResponseId(++requestId); req.setApplicationAttemptId(appAttemptId); req.addAllAsks(resourceRequest); req.addAllReleases(releases); AllocateResponse resp = resourceManager.allocate(req); return resp.getAMResponse(); } private void unregister(boolean succeeded) throws YarnRemoteException { LOG.info("Unregistering application"); FinishApplicationMasterRequest req = Records.newRecord(FinishApplicationMasterRequest.class); req.setAppAttemptId(appAttemptId); req.setFinishApplicationStatus(succeeded ? FinalApplicationStatus.SUCCEEDED: FinalApplicationStatus.FAILED); //req.setFinalState(succeeded ? "SUCCEEDED" : "FAILED"); resourceManager.finishApplicationMaster(req); } }
C
UTF-8
1,873
2.578125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "msg.h" #include "mem.h" int memid, sem_salida, sem_hilos; Msg *ptr_msg; main() { fprintf(stderr, "Obteniendo segmento de memoria compartida.\n"); if ( (memid=shmget(LLAVE_MEM,sizeof(Msg),0))<0){ fprintf(stderr, "No se pudo obtener la memoria compartida.\n"); fprintf(stderr, "¿Ejecutar Hilos Primero?.\n"); exit(1); } fprintf(stderr, "Conectando (attach) segmento de memoria compartida.\n"); if ( (ptr_msg=(Msg *)shmat(memid,(char *)0,0))==(Msg *) -1) err_sys("client: can't attach shared memory segment"); ptr_msg->terminar = false; fprintf(stderr, "Localizando semáforos creados.\n"); if ( (sem_salida=sem_open(LLAVE_SEM_SALIDA))<0) err_sys("client: can't open client semaphore"); if ( (sem_hilos=sem_open(LLAVE_SEM_HILOS))<0) err_sys("client: can't open server semaphore"); printf("============ESCUCHANDO===============\n"); salida(); printf("============TERMINANDO===============\n"); fprintf(stderr, "Desconectando el área de memoria compartida.\n"); if (shmdt(ptr_msg)<0) err_sys("client: can't detach shared memory"); exit(0); } salida(){ sem_wait(sem_salida); while( !(ptr_msg->terminar) ) { if (ptr_msg->mesg_type == 1) { printf(COLOR_ERR); printf("Error: "); } // si es un error, pone el color en rojo. printf(ptr_msg->mesg_data); //Imprime el mensaje/error printf("\x1B[0m"); //Cambia el color de la salida al normal. sem_signal(sem_hilos); //Prende el semaforo de los hilos sem_wait(sem_salida); //Espera el de salida. } printf("Recibido mensaje de cierre.\n"); sem_signal(sem_hilos); //Prende el semaforo de los hilos }
Java
UTF-8
938
2.21875
2
[]
no_license
package com.eco.challengeuserservice.converter; import com.eco.challengeuserservice.domain.ChallengePlayer; import com.eco.challengeuserservice.dto.ChallengePlayerDto; import javax.inject.Named; import org.springframework.core.convert.converter.Converter; import static com.eco.challengeuserservice.dto.builder.ChallengePlayerDtoBuilder.aChallengePlayerDto; @Named public class ChallengePlayerConverter implements Converter<ChallengePlayer, ChallengePlayerDto> { @Override public ChallengePlayerDto convert(ChallengePlayer challengePlayer) { return aChallengePlayerDto().withId(challengePlayer.getId()) .withChallengeId(challengePlayer.getChallengeId()) .withPlayerId(challengePlayer.getPlayerId()) .withValidation(challengePlayer.getNumberOfValidation()) .build(); } }
Markdown
UTF-8
507
2.53125
3
[]
no_license
# Article 696-6 Sous réserve des exceptions prévues à l'article 696-34, l'extradition n'est accordée qu'à la condition que la personne extradée ne sera ni poursuivie, ni condamnée pour une infraction autre que celle ayant motivé l'extradition et antérieure à la remise. **Liens relatifs à cet article** _Codifié par_: - Ordonnance 58-1296 1958-12-23 _Créé par_: - Loi n°2004-204 du 9 mars 2004 - art. 17 () JORF 10 mars 2004 _Cite_: - CODE DE PROCEDURE PENALE - art. 696-34 (V)
Python
UTF-8
6,087
2.859375
3
[]
no_license
import open3d as o3d import numpy as np import utils def edge_hash(p1, p2): mid = (p1+p2)/2 return "%f %f %f" % (mid[0], mid[1], mid[2]) def edge_hash2(p1, p2): if p1 < p2: return "%d %d" % (p1, p2) else: return "%d %d" % (p2, p1) def loop_subdivision(vertices, triangles, save_name=None, vis=False): """ upsampling mesh using loop subdivision :param vertices: :param triangles: :param save_name: :param vis: :return: """ edge2id = {} vert2neighbours = {} count = 0 for x, y, z in triangles: if x not in vert2neighbours: vert2neighbours[x] = [y, z] else: vert2neighbours[x].extend([y, z]) if y not in vert2neighbours: vert2neighbours[y] = [x, z] else: vert2neighbours[y].extend([x, z]) if z not in vert2neighbours: vert2neighbours[z] = [y, x] else: vert2neighbours[z].extend([y, x]) # hash edge edge_key = edge_hash2(x, y) if edge_key not in edge2id: edge2id[edge_key] = [count, 0, [z], [x, y]] count += 1 else: edge2id[edge_key][2].append(z) edge2id[edge_key][1] = 1 edge_key = edge_hash2(y, z) if edge_key not in edge2id: edge2id[edge_key] = [count, 0, [x], [y, z]] count += 1 else: edge2id[edge_key][2].append(x) edge2id[edge_key][1] = 1 edge_key = edge_hash2(z, x) if edge_key not in edge2id: edge2id[edge_key] = [count, 0, [y], [z, x]] count += 1 else: edge2id[edge_key][2].append(y) edge2id[edge_key][1] = 1 # compute odd vertices new_vert_ind = vertices.shape[0] new_vert2id = {} for edge_key in edge2id: edge_id, interior, left_vert, line_vert = edge2id[edge_key] if interior == 0: vert = vertices[line_vert[0]]*0.5 + vertices[line_vert[1]]*0.5 elif interior == 1: vert = vertices[line_vert[0]]*3/8 + vertices[line_vert[1]]*3/8 vert += vertices[left_vert[0]]/8 + vertices[left_vert[1]]/8 edge2id[edge_key].append(new_vert_ind) new_vert2id[new_vert_ind] = vert new_vert_ind += 1 # connect faces new_faces = [] for v0, v1, v2 in triangles: edge_key1 = edge_hash2(v0, v1) edge_key2 = edge_hash2(v1, v2) edge_key3 = edge_hash2(v2, v0) u8 = edge2id[edge_key1][-1] u5 = edge2id[edge_key2][-1] u7 = edge2id[edge_key3][-1] new_faces.extend([[u8, u5, u7], [u7, v0, u8], [u5, u8, v1], [v2, u7, u5]]) # compute even vertices new_even_vertices = np.zeros_like(vertices) for vert_id in vert2neighbours: neighbors = list(set(vert2neighbours[vert_id])) vert_deg = len(neighbors) if vert_deg == 2: vert = vertices[vert_id]*0.75 + vertices[neighbors[0]]/8 + vertices[neighbors[1]]/8 elif vert_deg == 3: beta = 3/16.0 arr = np.array(vertices[neighbors]).sum(axis=0) vert = vertices[vert_id] * (1 - vert_deg * beta) + arr * beta else: beta = 3/8.0/vert_deg arr = np.array(vertices[neighbors]).sum(axis=0) vert = vertices[vert_id] * (1 - vert_deg * beta) + arr * beta new_even_vertices[vert_id] = vert triangles2 = np.zeros((len(triangles)+len(new_faces), 3), np.int) vertices2 = np.zeros((new_vert_ind, 3), np.float) # load into new arrays for vid in range(new_vert_ind): if vid >= vertices.shape[0]: vertices2[vid] = [new_vert2id[vid][0], new_vert2id[vid][1], new_vert2id[vid][2]] if vid < vertices.shape[0]: vertices2[vid] = [vertices[vid][0], vertices[vid][1], vertices[vid][2]] tid = 0 for x, y, z in triangles: triangles2[tid] = [x, y, z] tid += 1 for x, y, z in new_faces: triangles2[tid] = [x, y, z] tid += 1 if save_name is not None: with open(save_name, 'w') as file: for vid in range(new_vert_ind): print("v %f %f %f" % (vertices2[vid][0], vertices2[vid][1], vertices2[vid][2]), file=file) for x, y, z in triangles2: print("f %d %d %d" % (x + 1, y + 1, z + 1), file=file) if vis: vis = o3d.visualization.Visualizer() vis.create_window() ctr = vis.get_view_control() remove_mesh = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(vertices2), o3d.utility.Vector3iVector(triangles2)) wf_mesh = o3d.geometry.LineSet.create_from_triangle_mesh(remove_mesh) vis.add_geometry(wf_mesh) ang = 0 while ang < 2000: ctr.rotate(10.0, 0.0) vis.poll_events() vis.update_renderer() ang += 10 return vertices2, triangles2 if __name__ == '__main__': vertices, triangles = utils.read_obj_file_texture_coords("test_models/spot_triangulated.obj") # vis = o3d.visualization.Visualizer() # vis.create_window() # ctr = vis.get_view_control() # ctr.rotate(180.0, 0.0) # for ind in range(100): # mesh = o3d.geometry.TriangleMesh(o3d.utility.Vector3dVector(vertices), o3d.utility.Vector3iVector(triangles)) # mesh.compute_vertex_normals() # vis.clear_geometries() # vis.add_geometry(mesh) # ctr.rotate(500.0, 0.0) # vis.capture_screen_image("saved/loop-%d.png" % ind) # vertices, triangles = loop_subdivision(vertices, triangles, "test_models/loop-%d.obj" % ind) # vis.poll_events() # vis.update_renderer() import cProfile, io, pstats pr = cProfile.Profile() pr.enable() for _ in range(2): vertices, triangles = loop_subdivision(vertices, triangles) s = io.StringIO() sortby = 'time' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats(20) print(s.getvalue())
C++
UTF-8
506
3.1875
3
[]
no_license
#include<iostream> #include<string> #include<cmath> using namespace std; double Factorial(int i){ double ans = 1; for (int i = i;i >=1;i--){ ans *= i; } return ans; } double func(double x,double n){ if (n == 1){ return x; } else{ double ans = pow(double(-1),n-1) * pow(x,2*n - 1) /Factorial(2 * n -1); return ans + func(x,n-1); } } int main(){ double x,n; cin >> x >> n; cout << func(x,n); return 0; }
Markdown
UTF-8
2,134
2.890625
3
[ "MIT" ]
permissive
# Available Beer Visualizer ABV is a very simple POS system for beverages with no capacity for handling payment methods. Free as in beer! Its also free as in speech under the MIT license, so feel free to use it as a baseline for your own projects! ## Configuration ABV expects a file named config.toml to exist in the ~/.abv directory. An example config file is kept updated in the root of the project repository. We use [viper](https://github.com/spf13/viper) to handle all configuration. Priority for configuration elements is given to environmental variables, followed by config file entries, followed by default values (which are described when applicable in the example config.toml file) ### Untappd Credentials An ID and Secret are needed to communicate with the Untappd API. These are not included in the config file for obvious security reasons. You can add these to your config file at the root of the toml file named `untappdID` and `untappdSecret` respectively. Alternatively, environmental variables named `ABV_UNTAPPDID` and `ABV_UNTAPPDSECRET` can be used instead. ## Deployment An SQLite database is the heart of the ABV application. The ABV gui can be used to create and update the database. The API application depends on this database but can be run separately as needed. The Frontend application is used to present the HTML5 Menu, and depends on the API to be running. ### Docker Docker containers are uploaded to Docker Hub with the names ``bhutch29/abv_api` and `bhutch29/abv_frontend`. They can be started with the following commands: `docker run -p 8081:8081 bhutch29/abv_api` `docker run -p 80:8080 bhutch29/abv_frontend` Don't forget the `-d` option to start the containers detached from the terminal. There is also a docker-compose.yml file in the repository root director. The only **prerequisite** for the docker-compose file is that the abv.sqlite database already exist in your ~/.abv directory. This can be accomplished by simply starting the abv application. Then you can launch the above containers using: `docker-compose up` Again, don't forget the `-d` option for starting detached!
Markdown
UTF-8
590
3.3125
3
[ "Apache-2.0" ]
permissive
# CouldBeSequence Long chains of collection operations will have a performance penalty due to a new list being created for each call. Consider using sequences instead. Read more about this in the [documentation](https://kotlinlang.org/docs/sequences.html) ## Noncompliant Code ```kotlin listOf(1, 2, 3, 4).map { it*2 }.filter { it < 4 }.map { it*it } ``` ## Compliant Code ```kotlin listOf(1, 2, 3, 4).asSequence().map { it*2 }.filter { it < 4 }.map { it*it }.toList() listOf(1, 2, 3, 4).map { it*2 } ``` [Source](https://arturbosch.github.io/detekt/performance.html#couldbesequence)
Java
WINDOWS-1252
4,137
2.78125
3
[]
no_license
package uebung11; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.text.DecimalFormat; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class Einkauf extends JFrame { private JPanel contentPane; private JTextField tfStueckzahl; private JTextField tfStueckpreis; private JTextField tfRabatt; private JLabel lblAusgabe; private String CerrMessage = "Die Eingaben sind unvollstndig"; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Einkauf frame = new Einkauf(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Einkauf() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 529, 227); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); tfStueckzahl = new JTextField(); tfStueckzahl.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { tfStueckpreis.requestFocus(); // tf erhlt Fokus } } }); tfStueckzahl.setColumns(10); tfStueckzahl.setBounds(10, 36, 101, 20); contentPane.add(tfStueckzahl); JLabel lblStueckzahl = new JLabel("Stueckzahl:"); lblStueckzahl.setBounds(10, 11, 101, 14); contentPane.add(lblStueckzahl); JButton btnBerechnen = new JButton("Berechnen"); btnBerechnen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (allesAusgefuellt()) { calc(); } else { lblAusgabe.setText(CerrMessage); } } }); btnBerechnen.setBounds(343, 35, 89, 23); contentPane.add(btnBerechnen); JLabel lblStueckpreis = new JLabel("St\u00FCckpreis:"); lblStueckpreis.setBounds(121, 11, 101, 14); contentPane.add(lblStueckpreis); tfStueckpreis = new JTextField(); tfStueckpreis.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { tfRabatt.requestFocus(); // tf erhlt Fokus } } }); tfStueckpreis.setColumns(10); tfStueckpreis.setBounds(121, 36, 101, 20); contentPane.add(tfStueckpreis); JLabel lblRabatt = new JLabel("Rabatt (%)"); lblRabatt.setBounds(232, 11, 101, 14); contentPane.add(lblRabatt); tfRabatt = new JTextField(); tfRabatt.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (allesAusgefuellt()) { calc(); } else { lblAusgabe.setText(CerrMessage); } } } }); tfRabatt.setColumns(10); tfRabatt.setBounds(232, 36, 101, 20); contentPane.add(tfRabatt); JButton btnEnde = new JButton("Ende"); btnEnde.setBounds(343, 69, 89, 23); contentPane.add(btnEnde); lblAusgabe = new JLabel(" . . . "); lblAusgabe.setBounds(10, 73, 323, 14); contentPane.add(lblAusgabe); } boolean allesAusgefuellt() { if (tfStueckzahl.getText().equals("") || tfStueckpreis.getText().equals("") || tfRabatt.getText().equals("")) { return false; } else return true; } void calc() { double stueckZahl, stueckPreis, Rabatt; stueckZahl = Double.parseDouble(tfStueckzahl.getText().replace(",", ".")); stueckPreis = Double.parseDouble(tfStueckpreis.getText().replace(",", ".")); Rabatt = Double.parseDouble(tfRabatt.getText().replace(",", ".")); double erg = (stueckZahl * stueckPreis) - (stueckZahl * stueckPreis) * Rabatt / 100; DecimalFormat f = new DecimalFormat("#0.00"); lblAusgabe.setText("Der EK betrgt: " + f.format(erg) + " "); tfStueckzahl.requestFocus(); // tf erhlt Fokus tfStueckzahl.selectAll(); // Markiert den Eintrag } }
Java
UTF-8
1,649
2.234375
2
[]
no_license
package com.hzyw.basic.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.Column; import java.io.Serializable; import java.util.List; /** * @author haoyuan * @date 2019.08.07 */ @Data @ApiModel(value = "能量报表") @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"}) public class ResSensorReportVO implements Serializable { /** * 按环境监测指标的9个指标展示趋势图 * 【温度、湿度、PM2.5、PM10、气压、风速、风向、雨量、噪音】, * 统计时间维度:周、月、年趋势图 */ private static final long serialVersionUID = 1L; @Column @ApiModelProperty(value = "唯一标示") private String signCode; @Column @ApiModelProperty(value = "温度") private List<Float> temperatures; @Column @ApiModelProperty(value = "湿度") private List<Float> humiditys; @Column @ApiModelProperty(value = "pm25") private List<Float> pm25s; @Column @ApiModelProperty(value = "pm10") private List<Float> pm10s; @Column @ApiModelProperty(value = "气压") private List<Float> pressures; @Column @ApiModelProperty(value = "风速") private List<Float> windSpeed; @Column @ApiModelProperty(value = "风向") private List<Float> windDirections; @Column @ApiModelProperty(value = "雨量") private List<Float> rainfall; @Column @ApiModelProperty(value = "噪音") private List<Float> noises; }
C#
UTF-8
1,482
3.71875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms.Sorting { class QuickSort : ISort { public int[] Sort(int[] arr) { QuickSortRecursive(ref arr, 0, arr.Length - 1); return arr; } private void QuickSortRecursive(ref int[] arr,int left,int right) { if (right - left <= 0) return; int pivot = arr[right]; int partition = Partition(ref arr, left, right, pivot); QuickSortRecursive(ref arr, left, partition - 1); QuickSortRecursive(ref arr,partition + 1,right); } public int Partition(ref int[] arr,int left,int right,int pivot) { int leftPtr = left; int rightPtr = right - 1; while (true) { while (arr[leftPtr] < pivot) leftPtr++; while (rightPtr > 0 && arr[rightPtr] > pivot) rightPtr--; if (leftPtr >= rightPtr) break; else Swap(ref arr,leftPtr,rightPtr); } Swap(ref arr, leftPtr, right); return leftPtr; } private void Swap(ref int[] arr, int a,int b) { var temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } } }
C#
UTF-8
953
2.625
3
[]
no_license
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using UITests.Models; namespace APITests { class ForecastContext { private string Url = "https://www.metaweather.com/api/"; public async Task<WeatherForecastModel> GetByWoeid(int woeid) { using (var client = new HttpClient()) { return JsonConvert.DeserializeObject<WeatherForecastModel>(await client.GetStringAsync($"{Url}/location/{woeid}/")); } } public async Task<List<DayForecastModel>> GetByDate(int woeid, DateTime date) { using (var client = new HttpClient()) { return JsonConvert.DeserializeObject<List<DayForecastModel>>(await client.GetStringAsync($"{Url}/location/{woeid}/{date.Year}/{date.Month}/{date.Day}/")); } } } }
C
UTF-8
2,092
3.875
4
[]
no_license
#include "CException.h" #include "OutStream.h" #include "ErrorCode.h" #include <stdio.h> #include <malloc.h> /*To open a file with write method for writing * *Input: *fileName -> the file name. * *openMethod -> open method ("w" for write, "r" for read) * *Output:outStream -> pointer to OutStream struct * *Throw: - * */ OutStream *openOutStream(char *fileName, char *openMethod){ OutStream *outStream = calloc(1, sizeof(OutStream)); outStream->file = fopen(fileName, openMethod); outStream->filename = fileName; outStream->currentByte = 0; outStream->bitIndex = 0; return outStream; } /*To write bytes into the file * *Input: *out -> pointer to OutStream struct * bitsToWrite -> the bits to be written to the file * bitSize -> number of bits to be written * *Output: - * *Throw: - * */ void streamWriteBits(OutStream *out, int bitsToWrite, int bitSize){ int i, bitsToOutput, mask = 0x80; uint8 tempBitsToWrite, bitToWrite; tempBitsToWrite = bitsToWrite; for(i = 0; i < bitSize; i++){ out->currentByte = out->currentByte << 1; bitToWrite = (tempBitsToWrite & mask) >> 7; streamWriteBit(out, bitToWrite); tempBitsToWrite = tempBitsToWrite << 1; } fputc(out->currentByte, out->file); } /*To write a bit to currentByte member of OutStream struct * *Input: *out -> pointer to OutStream struct * bitToWrite -> the bit to be written to currentByte * *Output: - * *Throw: - * */ void streamWriteBit(OutStream *out, uint8 bitToWrite){ out->currentByte = out->currentByte | bitToWrite; out->bitIndex++; if(out->bitIndex == 8) out->bitIndex = 0; } /*To flush out remaining bits in currentByte member of OutStream struct * *Input: *out -> pointer to OutStream struct * *Output: - * *Throw: - * */ void streamFlush(OutStream *out){ fputc(out->currentByte, out->file); } /*To close the file and free the OutStream struct * *Input: *out -> pointer to OutStream struct * *Output: - * *Throw: - * */ void closeOutStream(OutStream *out){ fclose(out->file); free(out); }
Java
UTF-8
9,346
1.976563
2
[]
no_license
package br.eletrosom.portalcolaborador.controller; import java.io.IOException; import java.security.Principal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import br.eletrosom.portalcolaborador.entity.CadastroProdutos; import br.eletrosom.portalcolaborador.entity.Empresa; import br.eletrosom.portalcolaborador.entity.SolicitacoesDiversas; import br.eletrosom.portalcolaborador.exporter.EnvioProdutosExporter; import br.eletrosom.portalcolaborador.model.EnvioProdutosModel; import br.eletrosom.portalcolaborador.service.CadastroProdutosService; import br.eletrosom.portalcolaborador.service.EmpresaService; import br.eletrosom.portalcolaborador.service.LogService; import br.eletrosom.portalcolaborador.service.SolicitacoesDiversasService; import br.eletrosom.portalcolaborador.service.UsuarioService; import br.eletrosom.portalcolaborador.utils.DateUtil; import br.eletrosom.portalcolaborador.view.UsuarioView; /* * CONTROLADOR DA SESSÃO DE ACESSO DO RH */ @Controller //@RequestMapping("logado_rh") public class LogadoRhController { // private static final Model = null; @Autowired private UsuarioService usuarioService; @Autowired private CadastroProdutosService produtosService; @Autowired private EmpresaService empresaService; @Autowired private LogService logService; @Autowired private SolicitacoesDiversasService solicitacoesService; // lista produtos cadastrados @ModelAttribute("allProdutos") public List<CadastroProdutos> populateProdutos() { return this.produtosService.listaTodosProduto(); } // lista empresas cadastradas @ModelAttribute("allEmpresas") public List<Empresa> populateEmpresas() { return this.empresaService.listarEmpresasAtivas(); } // lista todas as solcitacoes com status pendente @ModelAttribute("allSolicitacoesPendentes") public List<SolicitacoesDiversas> populateSolicitacoes() { return this.solicitacoesService.listaTodosPendentes(); } // TELA DAS OPÇÕES DISPONIVEIS AO RH @GetMapping("/logado_rh/opcoes_rh") public String opcoesRh(Principal principal, Model model) { UsuarioView usuarioView = new UsuarioView(); model.addAttribute("usuarioView", usuarioService.buscarUsuarioView(usuarioView, principal.getName())); return "logado_rh/opcoes_rh"; } // CADASTRA PRODUTOS @GetMapping("/logado_rh/produto") public String cadastroProdutos(Principal principal, Model model) { UsuarioView usuarioView = new UsuarioView(); model.addAttribute("usuarioView", usuarioService.buscarUsuarioView(usuarioView, principal.getName())); CadastroProdutos cadastroProduto = new CadastroProdutos(); Long id = produtosService.buscaId(); cadastroProduto.setId(id); cadastroProduto.setCodigo(id.toString()); model.addAttribute("cadastroProduto", cadastroProduto); return "logado_rh/produto"; } // VISUALIZA PRODUTOS CADASTRADOS @GetMapping("/logado_rh/visualizar_produtos") public String visualizarProdutos(Principal principal, Model model, String solicitacao) { UsuarioView usuarioView = null; model.addAttribute("usuarioView", usuarioView); if (solicitacao == null || solicitacao.equals("ALL")) { List<CadastroProdutos> listaProdutos = produtosService.listaTodosProduto(); model.addAttribute("listaProdutos", listaProdutos); return "logado_rh/visualizar_produtos"; } List<CadastroProdutos> listaProdutos = produtosService.listaProdutoTipo(solicitacao); if(listaProdutos != null || listaProdutos.isEmpty()) { model.addAttribute("listaProdutos", listaProdutos); }else { listaProdutos.add(new CadastroProdutos()); model.addAttribute("listaProdutos",listaProdutos ); } return "logado_rh/visualizar_produtos"; } // LISTA AS SOLICITAÇÕES PENDENTES PARA ENVIO @GetMapping("/logado_rh/envio_produtos") public String enviarProdutosView(Principal principal, Model model, String solicitacao, String unidade) { UsuarioView usuarioView = null; model.addAttribute("usuarioView", usuarioView); EnvioProdutosModel listaEnvio = solicitacoesService.listaEnvioProdutosModel(unidade, solicitacao); List<SolicitacoesDiversas> listaSolicitacoes = listaEnvio.getLista(); model.addAttribute("listaSolicitacoes", listaSolicitacoes); model.addAttribute("listaEnvio", listaEnvio); return "logado_rh/envio_produtos"; } // POST - CADSATRO DOS PRODUTOS @PostMapping("/logado_rh/produto") public String saveProduto(Principal principal, final CadastroProdutos cadastroProduto, final BindingResult bindingResult, final ModelMap model) { if (bindingResult.hasErrors()) { return "logado_rh/produto"; } this.produtosService.salvarProduto(cadastroProduto); logService.registrarLog("CADASTRO PRODUTO", principal.getName()); model.clear(); return "redirect:/logado_rh/produto"; } // REGISTRA OS ENVIOS DAS SOLICITAÇÕES SELECIONADS @PostMapping("/logado_rh/envio_produtos") public String salvarEnvio(HttpServletResponse response, Principal principal, final EnvioProdutosModel listaEnvio, String calendario, final BindingResult bindingResult, final Model model) { try { // String red = ""; if (bindingResult.hasErrors()) { // return new ModelAndView("logado_rh/envio_produtos"); return "erro"; // enviarProdutosView(principal, model, "", ""); } if (listaEnvio.getLista().isEmpty()) { // return new ModelAndView("logado_rh/envio_produtos"); return "erro"; //enviarProdutosView(principal, model, "", ""); } String tipo = ""; EnvioProdutosModel envio = new EnvioProdutosModel(); try { envio.setDataEnvio(new DateUtil().stringToDate(calendario)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (SolicitacoesDiversas item : listaEnvio.getLista()) { if (item.isSelected()) { // listaEnvio.getLista().remove(item); tipo = item.getSolicitacao(); switch (tipo) { case "CRA": tipo = "Cracha"; break; case "UNI": tipo = "Uniforme"; break; case "SAU": tipo = "Plano Saude"; break; case "ODO": tipo = "Plano Odontologico"; break; case "ALI": tipo = "Vale Alimentação"; break; case "TRA": tipo = "Vale Transporte"; break; case "DRO": tipo = "Drogalider"; break; default: tipo = item.getSolicitacao(); break; } // item.setSolicitacao(tipo); envio.getLista().add(item); } } model.addAttribute("listaEnvio", envio); this.solicitacoesService.salvarEnvioSolicitacao(envio); logService.registrarLog("ENVIO PRODUTO", principal.getName()); // this.exportToExcel(response, envio, tipo); response.setContentType("application/octet-stream"); DateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); String envioformat = dateFormatter.format(envio.getDataEnvio()); String headerKey = "Content-Disposition"; String headerValue = "attachment; filename=envio_" + tipo + "_" + envioformat + ".xlsx"; response.setHeader(headerKey, headerValue); EnvioProdutosModel e = solicitacoesService.listaEnvioExportacao(envio); if (e != null) { EnvioProdutosExporter excelExporter = new EnvioProdutosExporter(e); excelExporter.export(response, tipo); } // red = "logado_rh/envio_produtos"; // ModelAndView modelAndView = new ModelAndView("erro"); // return modelAndView; // enviarProdutosView(principal, model, "", ""); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return "erro"; } catch (ServletException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // red = "/logado_rh/envio_produtos"; // return modelAndView; // RequestDispatcher dd=response.getRequestDispatcher(red); // dd.forward(request, response); // model.clear(); // return new ModelAndView("erro"); return "logado_rh/envio_produtos"; } // EXPORTA OS PRODUTOS ENVIADOS PARA XLSX /* * public void exportToExcel(HttpServletResponse response, EnvioProdutosModel * envio, String tipo) { response.setContentType("application/octet-stream"); * DateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); * * String envioformat = dateFormatter.format(envio.getDataEnvio()); * * String headerKey = "Content-Disposition"; String headerValue = * "attachment; filename=envio_" + tipo + "_" + envioformat + ".xlsx"; * response.setHeader(headerKey, headerValue); * * EnvioProdutosModel e = solicitacoesService.listaEnvioExportacao(envio); * * EnvioProdutosExporter excelExporter = new EnvioProdutosExporter(e); * * try { excelExporter.export(response.getOutputStream(), tipo); } catch * (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } * } */ }
Python
UTF-8
821
2.984375
3
[]
no_license
from __future__ import print_function import argparse import cv2 # path = ./trex.png ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") # argument is path to image on disk args = vars(ap.parse_args()) # parse arguments and store in dictionary image = cv2.imread(args["image"]) # load image off disk with path to image and imread print("width: {} pixels".format(image.shape[1])) # examine dimensions of the image. use NumPy array format and shape attribute print("height: {} pixels".format(image.shape[0])) print("channels: {}".format(image.shape[2])) cv2.imshow("Image", image) # name of window, reference to image cv2.waitKey(0) # execution after key is pressed, 0 means any key cv2.imwrite("newimage.jpg", image) # write and ssave image in JPG format
JavaScript
UTF-8
3,289
2.65625
3
[ "MIT" ]
permissive
APPNAME = 'WeatherApp'; angular .module(APPNAME, ['ui.router', 'ngAnimate']) .run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) { // It's very handy to add references to $state and $stateParams to the $rootScope // so that you can access them from any scope within your applications.For example, // <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li> // to active whenever 'contacts.list' or one of its decendents is active. $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; }]) ; // // Keys mapping // function Keyboard(){} Keyboard.keys = []; Keyboard.keys[13] = "enter"; Keyboard.keys[8] = "backspace"; Keyboard.keys[9] = "tab"; Keyboard.keys[13] = "enter"; Keyboard.keys[16] = "shift"; Keyboard.keys[17] = "ctrl"; Keyboard.keys[18] = "alt"; Keyboard.keys[19] = "pause"; Keyboard.keys[20] = "capslock" Keyboard.keys[27] = "escape"; Keyboard.keys[32] = "space"; Keyboard.keys[33] = "pageup"; Keyboard.keys[34] = "pagedown"; Keyboard.keys[35] = "end"; Keyboard.keys[36] = "home"; Keyboard.keys[37] = "leftarrow"; Keyboard.keys[38] = "uparrow"; Keyboard.keys[39] = "rightarrow"; Keyboard.keys[40] = "downarrow"; Keyboard.keys[45] = "insert"; Keyboard.keys[46] = "delete"; Keyboard.keys[48] = "0"; Keyboard.keys[49] = "1"; Keyboard.keys[50] = "2"; Keyboard.keys[51] = "3"; Keyboard.keys[52] = "4"; Keyboard.keys[53] = "5"; Keyboard.keys[54] = "6"; Keyboard.keys[55] = "7"; Keyboard.keys[56] = "8"; Keyboard.keys[57] = "9"; Keyboard.keys[65] = "a"; Keyboard.keys[66] = "b"; Keyboard.keys[67] = "c"; Keyboard.keys[68] = "d"; Keyboard.keys[69] = "e"; Keyboard.keys[70] = "f"; Keyboard.keys[71] = "g"; Keyboard.keys[72] = "h"; Keyboard.keys[73] = "i"; Keyboard.keys[74] = "j"; Keyboard.keys[75] = "k"; Keyboard.keys[76] = "l"; Keyboard.keys[77] = "m"; Keyboard.keys[78] = "n"; Keyboard.keys[79] = "o"; Keyboard.keys[80] = "p"; Keyboard.keys[81] = "q"; Keyboard.keys[82] = "r"; Keyboard.keys[83] = "s"; Keyboard.keys[84] = "t"; Keyboard.keys[85] = "u"; Keyboard.keys[86] = "v"; Keyboard.keys[87] = "w"; Keyboard.keys[88] = "x"; Keyboard.keys[89] = "y"; Keyboard.keys[90] = "z"; Keyboard.keys[97] = "a"; Keyboard.keys[98] = "b"; Keyboard.keys[99] = "c"; Keyboard.keys[100] = "d"; Keyboard.keys[101] = "e"; Keyboard.keys[102] = "f"; Keyboard.keys[103] = "g"; Keyboard.keys[104] = "h"; Keyboard.keys[105] = "i"; Keyboard.keys[106] = "j"; Keyboard.keys[107] = "k"; Keyboard.keys[108] = "l"; Keyboard.keys[109] = "m"; Keyboard.keys[110] = "n"; Keyboard.keys[111] = "o"; Keyboard.keys[112] = "p"; Keyboard.keys[113] = "q"; Keyboard.keys[114] = "r"; Keyboard.keys[115] = "s"; Keyboard.keys[116] = "t"; Keyboard.keys[117] = "u"; Keyboard.keys[118] = "v"; Keyboard.keys[119] = "w"; Keyboard.keys[120] = "x"; Keyboard.keys[121] = "y"; Keyboard.keys[122] = "z"; /** * Find the caracter associated with a key code * * @param code int * @return String **/ Keyboard.find = function( code ) { return Keyboard.keys[code]; } /** * Is the given key code associated with a letter * * @param code int * @return Boolean **/ Keyboard.isLetter = function( code ) { return ( (code >= 65 && code <= 90) || (code >=97 && code <= 122) ) }
C++
UTF-8
1,085
3.234375
3
[]
no_license
const int tempPin = A0; int incomingByte;// incoming data void setup() { Serial.begin(9600); // initialization pinMode(LED_BUILTIN, OUTPUT); Serial.println("Press 1 to LED ON or 0 to LED OFF..."); digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW } void loop() { int val = analogRead(tempPin); float volt = (val/1024.0) * 5.0; float temperature = (volt - .5) * 100; Serial.print(temperature); Serial.print("C \n"); if (Serial.available() > 0) { // if the data came incomingByte = Serial.read(); // read byte //Serial.println(incomingByte); if(incomingByte == '0') { digitalWrite(LED_BUILTIN, LOW); // if 1, switch LED Off //Serial.println("LED OFF. Press 1 to LED ON!"); // print message } if(incomingByte == '1') { digitalWrite(LED_BUILTIN, HIGH); // if 0, switch LED on //Serial.println("LED ON. Press 0 to LED OFF!"); } } }
PHP
UTF-8
1,046
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php defined('SYSPATH') or die('No direct script access.'); class Controller_Register extends Controller { public function action_index() { $post = $this->request->post(); $ret = ''; if(isset($post['submit'])) { $firstname = $post['firstname']; $lastname = $post['lastname']; $comDetails = $post['companyDetails']; $comImg = $post['companyImg']; $email = $post['email']; $username = $post['username']; $password = $post['password']; $radioCheck = $post['logtype']; if($radioCheck == "student") { $ret = User::register($username,$password,$firstname, $lastname, $email); } elseif ($radioCheck == "company") { $ret = Company::register($username,$password,$comDetails,$email,$comImg); } } $this->response->body(View::factory('header').View::factory('register')->set('ret', $ret)); } }
Java
UTF-8
919
1.867188
2
[]
no_license
package com.hiekn.metacloud.feign; import cn.hiboot.mcn.core.model.result.RestResp; import com.hiekn.metacloud.feign.bean.UserBean; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; /** * describe about this class * * @author DingHao * @since 2020/1/8 15:37 */ //url的使用可以支持哪些不需要注册服务仅仅使用feign的项目 @Validated @FeignClient(value = "${reactive.web:reactive-web}",url = "${reactive.web.url:}",path = "/user") public interface UserApi { @GetMapping("list") RestResp<List<UserBean>> list(); @PostMapping("json") RestResp<UserBean> postJson(@Validated @RequestBody UserBean userBean); }
Java
UTF-8
320
1.71875
2
[]
no_license
package com.hxy.nzxy.stexam.center.region.service; import com.hxy.nzxy.stexam.center.region.domain.StudentRegionQueryDO; import com.hxy.nzxy.stexam.common.utils.Query; import java.util.List; public interface StudentRegionQueryService { List<StudentRegionQueryDO> list(Query query); int count(Query query); }
Markdown
UTF-8
3,154
2.890625
3
[ "MIT" ]
permissive
# flydrive-google-drive This is GoogleDrive access driver for [node-flydrive](https://github.com/Slynova-Org/node-flydrive) library ## Dependencies This package depends on google-auth-library, you can get it by running `npm i --save google-auth-library` The ``google-auth-library`` permits using OAuth for google drive authentication, its main role is to get a new token from refresh token if any ## Installation You can get this package by running just `npm i --save flydrive-google-drive` ## Usage ### With flydrive library You need to install @slynova/flydrive that is a fluent nodejs storage library `npm i --save @slynova/flydrive` And now you just import StorageManager from flydrive and register flydrive-google-drive ```js const StorageManager = require('@slynova/flydrive') const GoogleDriver = require('flydrive-google-drive') const storageManager = new StorageManager({ default: 'googledrive', 'disks': { 'local': { 'driver': 'local', 'root': process.cwd() }, 's3': { 'driver': 's3', 'key': 'AWS_S3_KEY', 'secret': 'AWS_S3_SECRET', 'region': 'AWS_S3_REGION', 'bucket': 'AWS_S3_BUCKET' }, 'googledrive': { 'driver': 'googledrive', 'clientId': 'GOOGLE_DRIVE_CLIENT_ID', 'clientSecret': 'GOOGLE_DRIVE_CLIENT_SECRET', 'redirectUrl': 'GOOGLE_DRIVE_REDIRECT_URL', 'access_token': 'GOOGLE_DRIVE_ACCESS_TOKEN', 'refresh_token': 'GOOGLE_DRIVE_REFRESH_TOKEN' } } }) storageManager.extend('googledrive', GoogleDriver) ``` You can now call file operation method from on a Storage object instance that you can get from storage manager ````js async function test() { const storage = storageManager.disk('googledrive') let file = await storage.put('storage-test.txt', 'From storage manager') file = await storage.move('storage-test.txt', 'storage-test-cp.txt') const content = await storage.get('storage-test-cp.txt') const r = await storage.delete('storage-test-cp.txt') } ```` > Please refer to [flydrive wiki](https://github.com/Slynova-Org/node-flydrive/wiki) for more information about this ### Use as standlone You can use this library standlone Import ``GoogleDrive`` ````js const GoogleDriver = require('flydrive-google-drive') ```` Create an instance of the `GoogleDrive` ```js const config = { 'clientId': 'GOOGLE_DRIVE_CLIENT_ID', 'clientSecret': 'GOOGLE_DRIVE_CLIENT_SECRET', 'redirectUrl': 'GOOGLE_DRIVE_REDIRECT_URL', 'access_token': 'GOOGLE_DRIVE_ACCESS_TOKEN', 'refresh_token': 'GOOGLE_DRIVE_REFRESH_TOKEN' } async function test() { const drive = new GoogleDrive(config); //if you provide a refresh token , this will be used to get a new token on each request, to ensure there is not authentication error let r =await drive.exists('some-file.txt'); if(!r){ await drive.put('some-file.txt','Some file') let file = await drive.getMeta('some-file.txt') const content = await drive .with({token:"new token",refresh_token:'new refresh token'}) .get(file.name,'utf-8'); console.log(content) } } ``` ##Licence MIT
C
UTF-8
514
4.03125
4
[]
no_license
/* Program: pattern.c Author: Van Nguyen Date Created: 9/25/2018 Description: This program prints letters from F to A in a pattern */ #include <stdio.h> #define ROWS 6 void pattern(void); int main(void) { pattern(); getchar(); getchar(); return 0; } void pattern(void) { char ch; int rows, columns, i; i = 6; for (rows = 0; rows < ROWS; rows++) { for (columns = i, ch = 'F'; columns <= ROWS; columns++, ch--) { printf("%c", ch); } printf("\n"); i--; } }
JavaScript
UTF-8
2,652
2.546875
3
[]
no_license
//All database request that are made from server side import { db } from "./firebase-admin"; import { compareDesc, parseISO } from "date-fns"; export async function getAllBakers() { const snapshot = await db.collection("users").get(); const sites = []; snapshot.forEach((doc) => { sites.push({ id: doc.id, ...doc.data() }); }); return { sites }; } export async function getBakeryName(bakerId) { try { const snapshot = await db .collection("users") .where("uid", "==", bakerId) .get(); const bakerList = []; snapshot.forEach((doc) => { bakerList.push({ id: doc.id, ...doc.data() }); }); return { bakerList }; } catch (err) { return err; } } export async function getAllOrders() { const snapshot = await db.collection("orders").get(); const orders = []; snapshot.forEach((doc) => { orders.push({ id: doc.id, ...doc.data() }); }); return { orders }; } export async function getPendingOrders(bakerId) { try { const snapshot = await db .collection("orders") .where("bakerId", "==", bakerId) .where("status", "==", "Pending") .get(); const orderList = []; snapshot.forEach((doc) => { orderList.push({ id: doc.id, ...doc.data() }); }); orderList.sort((a, b) => compareDesc(parseISO(a.createdAt), parseISO(b.createdAt)) ); return { orderList }; } catch (err) { return err; } } export async function getAllBakerOrders(bakerId) { try { const snapshot = await db .collection("orders") .where("bakerId", "==", bakerId) .get(); const orderList = []; snapshot.forEach((doc) => { orderList.push({ id: doc.id, ...doc.data() }); }); return { orderList }; } catch (err) { return err; } } export async function getOrder(orderId) { try { const snapshot = await db.collection("orders").doc(orderId).get(); const order = { id: snapshot.id, ...snapshot.data(), }; return { order }; } catch (err) { return err; } } export async function getUserInfo(userId) { try { const snapshot = await db.collection("users").doc(userId).get(); return { ...snapshot.data() }; } catch (err) { return err; } } export async function getCompletedOrders(bakerId) { try { const snapshot = await db .collection("orders") .where("bakerId", "==", bakerId) .where("status", "==", "Completed") .get(); const orderList = []; snapshot.forEach((doc) => { orderList.push({ id: doc.id, ...doc.data() }); }); return { orderList }; } catch (err) { return err; } }
JavaScript
UTF-8
2,031
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
(function(module) { "use strict"; var requestify = require('requestify'); var BugzillaAPIMethod = { BUG_GET: 'Bug.get', BUG_SEARCH: 'Bug.search', BUG_COMMENT: 'Bug.comments' }; var BugzillaClient = function (options) { options = options || {}; this.username = options.username; this.password = options.password; this.apiUrl = options.url || "https://bugzilla.mozilla.org/jsonrpc.cgi"; }; var handleResponse = function (response, field, callback) { var error = response.getBody().error; var json; if (response.getCode() >= 300 || response.getCode() < 200) { error = "HTTP status " + response.response.getCode(); } else { try { json = response.getBody(); } catch (e) { error = "Response wasn't valid json: '" + response.getBody() + "'"; } } if (json && json.error) { error = json.error.message; } var ret = null; if (!error) { ret = field ? json[field] : json; } callback(error, ret); }; var requestAPI = function(method, requestMethod, params, field, callback, _this) { var url = _this.apiUrl; if (_this.username && _this.password) { params.Bugzilla_login = _this.username; params.Bugzilla_password = _this.password; } if (params) { url += '?method=' + method + '&params=[' + JSON.stringify(params) + ']'; } requestify.request(url, { method: requestMethod, headers: {'Content-type': 'application/json' }, dataType: 'json' }) .then(function(response) { handleResponse(response, field, callback); }); }; BugzillaClient.prototype = { query: function (queryMethod, params, callback) { if (!callback) { callback = params; params = {}; } requestAPI(queryMethod, 'GET', params, 'result', callback, this); } }; exports.createClient = function (options) { return new BugzillaClient(options); }; exports.queryMethod = BugzillaAPIMethod; }(module));
Python
UTF-8
989
2.53125
3
[]
no_license
import RPi.GPIO as gp import pyrebase from credentials import firebaseConfig from time import sleep import sys gp.setmode(gp.BOARD) inp = 7 #out = 11 if __name__ == '__main__': gp.setup(11,gp.OUT) gp.setup(inp,gp.IN) #gp.setup(out,gp.OUT) firebase = pyrebase.initialize_app(firebaseConfig) db = firebase.database() known = False allow = False while True: known = db.child('known').get().val() allow = db.child('allow').child('value').get().val() print(f' Known : {known}') gp.output(11,gp.LOW) if known or allow: #gp.output(11,gp.HIGH) print('Dooor Open') if gp.input(inp) == 1: #print('Door Open') #while (gp.input(inp) == 0) #gp.output(11,gp.LOW) print('Door Closed') db.child('allow').child('value').set(False) db.child('known').set(False) sys.exit() else: if gp.input(inp) == 1: print('Forcefully Entered') gp.output(11,gp.HIGH) sleep(2) gp.output(11,gp.LOW)
Java
UTF-8
2,265
1.914063
2
[]
no_license
/** * */ package com.vn.ael.persistence.manager; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.vn.ael.constants.AELConst; import com.vn.ael.constants.TypeOfFee; import com.vn.ael.enums.ServicesType; import com.vn.ael.persistence.entity.Accountingcus; import com.vn.ael.persistence.entity.Accountingcusdetail; import com.vn.ael.persistence.entity.Attachment; import com.vn.ael.persistence.entity.Docsgeneral; import com.vn.ael.persistence.entity.Exfeetable; import com.vn.ael.persistence.entity.Extendfeeacc; import com.vn.ael.persistence.entity.OfferItem; import com.vn.ael.persistence.entity.OfferPrice; import com.vn.ael.persistence.repository.AccountingcusRepository; import com.vn.ael.persistence.repository.AccountingcusdetailRepository; import com.vn.ael.persistence.repository.AttachmentRepository; import com.vn.ael.persistence.repository.ContsealRepository; import com.vn.ael.persistence.repository.DocsgeneralRepository; import com.vn.ael.persistence.repository.ExfeetableRepository; import com.vn.ael.persistence.repository.ExtendfeeaccRepository; import com.vn.ael.persistence.repository.OfferPriceRepository; import com.vn.ael.persistence.repository.TruckingdetailRepository; import com.vn.ael.persistence.repository.TruckingserviceRepository; import com.vn.ael.webapp.util.EntityUtil; import com.vn.ael.webapp.util.CommonUtil; /** * @author liv1hc * */ @Transactional @Service public class AttachmentManagerImpl extends GenericManagerImpl<Attachment> implements AttachmentManager{ private AttachmentRepository attachmentRepository; @Autowired OfferPriceRepository offerPriceRepository; @Autowired public AttachmentManagerImpl(final AttachmentRepository attachmentRepository) { this.attachmentRepository = attachmentRepository; this.repository = attachmentRepository; } @Override public List<Attachment> findWithOfferPriceId(String offerPriceId) { OfferPrice offerPrice = offerPriceRepository.findOne(Long.valueOf(offerPriceId)); return attachmentRepository.findByOfferPrice(offerPrice); } }
Java
UTF-8
11,276
2.453125
2
[ "MIT" ]
permissive
package co.edu.udea.optimizacion; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.math3.geometry.euclidean.threed.Line; import org.apache.commons.math3.geometry.euclidean.threed.Plane; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.log4j.Logger; import org.jzy3d.analysis.AbstractAnalysis; import org.jzy3d.analysis.AnalysisLauncher; import org.jzy3d.chart.factories.AWTChartComponentFactory; import org.jzy3d.colors.Color; import org.jzy3d.colors.ColorMapper; import org.jzy3d.colors.colormaps.ColorMapRainbow; import org.jzy3d.maths.Coord3d; import org.jzy3d.maths.Range; import org.jzy3d.plot3d.builder.Builder; import org.jzy3d.plot3d.builder.Mapper; import org.jzy3d.plot3d.builder.concrete.OrthonormalGrid; import org.jzy3d.plot3d.primitives.CroppableLineStrip; import org.jzy3d.plot3d.primitives.Point; import org.jzy3d.plot3d.primitives.Scatter; import org.jzy3d.plot3d.primitives.Shape; import org.jzy3d.plot3d.primitives.axes.layout.IAxeLayout; import org.jzy3d.plot3d.primitives.axes.layout.providers.SmartTickProvider; import org.jzy3d.plot3d.primitives.axes.layout.renderers.IntegerTickRenderer; import org.jzy3d.plot3d.rendering.canvas.Quality; public class SimulatedAnnealing extends AbstractAnalysis { private static Logger log = Logger.getLogger(SimulatedAnnealing.class); public List<CroppableLineStrip> tourLines = new ArrayList<CroppableLineStrip>(); private static List<City> bestSolution = new ArrayList<>(); private static Line frontierLine; private static Plane frontierPlane; private static double frontierP1X; private static double frontierP1Y; private static double frontierP1Z; private static double frontierP2X; private static double frontierP2Y; private static double frontierP2Z; private static double frontierP3X; private static double frontierP3Y; private static double frontierP3Z; public static void main(String[] args) { long initTime = System.currentTimeMillis(); loadFileWithCities(args[0]); initializeFrontier(args); double temperature = 100; // Initial solution Tour currentSolution = new Tour(); currentSolution.generateRandomIndividual(); City initialCity = getInitialCity(args); setFirstCity(currentSolution, initialCity); simulate(temperature, currentSolution); long finalTime = System.currentTimeMillis(); System.out.println("###### TIME SPENT #####\n" + (finalTime - initTime) + " millisecs"); drawSolution(); } private static void simulate(double temperature, Tour currentSolution) { // Set as current best Tour best = new Tour(currentSolution.getTour()); System.out.println("Initial solution cost: " + currentSolution.getDistance()); // Loop until system has cooled for (int i = 0; i < 1000; i++) { temperature = 100; while (temperature > 1) { // Create new solution tour Tour newSolution = new Tour(currentSolution.getTour()); shuffleTour(newSolution); currentSolution = getNewSolution(temperature, currentSolution, newSolution); // Keep track of the best solution found if (currentSolution.getDistance() < best.getDistance()) { best = new Tour(currentSolution.getTour()); } temperature = temperature - 1; } } System.out.println("Best solution cost: " + best.getDistance()); System.out.println("Tour: " + best); bestSolution = best.getTour(); } private static void setFirstCity(Tour currentSolution, City initialCity) { // Get index from initial city int initialCityIndex = 0; for (int cityIndex = 0; cityIndex < currentSolution.getTour().size(); cityIndex++) { if (currentSolution.getCity(cityIndex).equals(initialCity)) { initialCityIndex = cityIndex; } } // Put initial city at the first position of the tour City citySwap1a = currentSolution.getCity(initialCityIndex); City citySwap2a = currentSolution.getCity(0); currentSolution.setCity(0, citySwap1a); currentSolution.setCity(initialCityIndex, citySwap2a); } private static City getInitialCity(String[] args) { double initialX = Double.parseDouble(args[10]); double initialY = Double.parseDouble(args[11]); double initialZ = Double.parseDouble(args[12]); City initialCity = new City(initialX, initialY, initialZ); return initialCity; } private static void drawSolution() { try { AnalysisLauncher.open(new SimulatedAnnealing()); } catch (Exception e) { log.error("Error al intentar graficar.", e); } } private static Tour getNewSolution(double temperature, Tour currentSolution, Tour newSolution) { double currentEnergy = currentSolution.getDistance(); double neighbourEnergy = newSolution.getDistance(); // Decide if we should accept the new solution if (acceptanceProbability(currentEnergy, neighbourEnergy, temperature) > Math.random()) { currentSolution = new Tour(newSolution.getTour()); } return currentSolution; } private static void shuffleTour(Tour newSolution) { // Get random positions in the tour from the second city to the last city. int tourPos1 = ThreadLocalRandom.current().nextInt(1, TourManager.getNumberOfCities()); int tourPos2 = ThreadLocalRandom.current().nextInt(1, TourManager.getNumberOfCities()); // Swap cities randomly City citySwap1 = newSolution.getCity(tourPos1); City citySwap2 = newSolution.getCity(tourPos2); newSolution.setCity(tourPos2, citySwap1); newSolution.setCity(tourPos1, citySwap2); } private static void initializeFrontier(String[] args) { frontierP1X = Double.parseDouble(args[1]); frontierP1Y = Double.parseDouble(args[2]); frontierP1Z = Double.parseDouble(args[3]); frontierP2X = Double.parseDouble(args[4]); frontierP2Y = Double.parseDouble(args[5]); frontierP2Z = Double.parseDouble(args[6]); frontierP3X = Double.parseDouble(args[7]); frontierP3Y = Double.parseDouble(args[8]); frontierP3Z = Double.parseDouble(args[9]); Vector3D frontierP1 = new Vector3D(frontierP1X, frontierP1Y, frontierP1Z); Vector3D frontierP2 = new Vector3D(frontierP2X, frontierP2Y, frontierP2Z); Vector3D frontierP3 = new Vector3D(frontierP3X, frontierP3Y, frontierP3Z); frontierLine = new Line(frontierP1, frontierP2); frontierPlane = new Plane(frontierP1, frontierP2, frontierP3); } public static double acceptanceProbability(double currentEnergy, double neighbourEnergy, double temperature) { // If the new solution is better, accept it // If the new solution is worse, calculate an acceptance probability return (neighbourEnergy < currentEnergy) ? 1.0 : Math.exp((currentEnergy - neighbourEnergy) / temperature); } public void init() throws Exception { Mapper planeFunction = new Mapper() { @Override public double f(double x, double y) { double coeffX = frontierPlane.getNormal().getX(); double coeffY = frontierPlane.getNormal().getY(); double coeffZ = frontierPlane.getNormal().getZ(); double bias = frontierPlane.getOffset(new Vector3D(0, 0, 0)); return (-coeffX * x - coeffY * y - bias) / coeffZ; } }; chart = AWTChartComponentFactory.chart(Quality.Advanced, "newt"); drawCities(); drawFrontierPlane(planeFunction); drawTour(); setView(); } private void setView() { IAxeLayout axeLayout = chart.getAxeLayout(); axeLayout.setXAxeLabel("Eje X"); axeLayout.setYAxeLabel("Eje Y"); axeLayout.setZAxeLabel("Eje Z"); axeLayout.setXTickRenderer(new IntegerTickRenderer()); axeLayout.setYTickRenderer(new IntegerTickRenderer()); axeLayout.setZTickRenderer(new IntegerTickRenderer()); axeLayout.setXTickProvider(new SmartTickProvider(10)); axeLayout.setYTickProvider(new SmartTickProvider(10)); axeLayout.setZTickProvider(new SmartTickProvider(10)); chart.getView().setViewPoint(new Coord3d(-2 * Math.PI / 3, Math.PI / 4, 0)); } private void drawTour() { this.parseFileWithCities("./Datos1.csv"); chart.getScene().getGraph().add(this.tourLines); } private void drawFrontierPlane(Mapper mapper) { Range range = new Range(-20, 20); int steps = 10; final Shape surface = Builder.buildOrthonormal(new OrthonormalGrid(range, steps, range, steps), mapper); surface.setColorMapper( new ColorMapper(new ColorMapRainbow(), surface.getBounds().getZmin(), surface.getBounds().getZmax(), new Color(1, 1, 1, .5f))); surface.setFaceDisplayed(true); surface.setWireframeDisplayed(false); chart.getScene().getGraph().add(surface); } private void drawCities() { double x; double y; double z; Coord3d[] points = new Coord3d[bestSolution.size()]; Color[] colors = new Color[bestSolution.size()]; for (int i = 0; i < bestSolution.size(); i++) { x = bestSolution.get(i).getX(); y = bestSolution.get(i).getY(); z = bestSolution.get(i).getZ(); points[i] = new Coord3d(x, y, z); colors[i] = Color.BLACK; } colors[0] = Color.RED; Scatter scatter = new Scatter(points, colors, 5); chart.getScene().add(scatter); } private static void loadFileWithCities(String filename) { String line = ""; String cvsSplitBy = ";"; City city; double x; double y; double z; BufferedReader br = null; try { br = new BufferedReader(new FileReader(filename)); while ((line = br.readLine()) != null) { line = line.replace(',', '.'); // Use semicolon as separator String[] cityCoordinates = line.split(cvsSplitBy); x = Double.parseDouble(cityCoordinates[0]); y = Double.parseDouble(cityCoordinates[1]); z = Double.parseDouble(cityCoordinates[2]); city = new City(x, y, z); TourManager.addCity(city); } } catch (IOException e) { log.error("No se pudo leer el archivo.", e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { log.error("No se pudo leer el archivo.", e); } } } } public List<CroppableLineStrip> parseFileWithCities(String filename) { CroppableLineStrip lineStrip = new CroppableLineStrip(); lineStrip.setWireframeColor(Color.BLUE); // Add cities to the line strip for (City city : bestSolution) { lineStrip.add(new Point(new Coord3d(city.getX(), city.getY(), city.getZ()))); } // Close trip to initial city lineStrip.add(new Point(new Coord3d(bestSolution.get(0).getX(), bestSolution.get(0).getY(), bestSolution.get(0).getZ()))); CroppableLineStrip frontier = new CroppableLineStrip(); frontier.setWireframeColor(Color.RED); frontier.setWidth(1); Point point1 = new Point(new Coord3d(frontierP1X, frontierP1Y, frontierP1Z)); Point point2 = new Point(new Coord3d(frontierP2X, frontierP2Y, frontierP2Z)); frontier.add(point1); frontier.add(point2); tourLines.add(lineStrip); // tourLines.add(frontier); return tourLines; } public static Line getFrontierLine() { return frontierLine; } public static Plane getFrontierPlane() { return frontierPlane; } }
Java
UTF-8
476
2.765625
3
[]
no_license
package znetwork; import java.io.Serializable; public class Packet implements Serializable { private static final long serialVersionUID = 1L; public enum Type { } private Type type; private Object data; public Packet(Type type, Object data) { this.type = type; this.data = data; } public Type getType() { return type; } public Object getData() { return data; } }
Markdown
UTF-8
4,239
2.546875
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: TLSGetServerCertificate function description: Returns the certificate of the Remote Desktop license server. ms.assetid: 7a31e7f9-f6d6-4030-b7db-43be118bb158 ms.tgt_platform: multiple keywords: - TLSGetServerCertificate function Remote Desktop Services topic_type: - apiref api_name: - TLSGetServerCertificate api_location: - Mstlsapi.dll api_type: - DllExport ms.topic: reference ms.date: 05/31/2018 --- # TLSGetServerCertificate function Returns the certificate of the Remote Desktop license server. > [!Note] > This function has no associated header file or import library. To call this function, you must create a user-defined header file and use the [**LoadLibrary**](/windows/desktop/api/libloaderapi/nf-libloaderapi-loadlibrarya) and [**GetProcAddress**](/windows/desktop/api/libloaderapi/nf-libloaderapi-getprocaddress) functions to dynamically link to Mstlsapi.dll. ## Syntax ```C++ DWORD WINAPI TLSGetServerCertificate( _In_ TLS_HANDLE hHandle, _In_ BOOL bSignCert, _Out_ LPBYTE *ppbCertBlob, _Out_ LPDWORD lpdwCertBlobLen, _Out_ PDWORD pdwErrCode ); ``` ## Parameters <dl> <dt> *hHandle* \[in\] </dt> <dd> Handle to a Remote Desktop license server that is opened by a call to the [**TLSConnectToLsServer**](tlsconnecttolsserver.md) function. </dd> <dt> *bSignCert* \[in\] </dt> <dd> **TRUE** if signature certificate, **FALSE** if exchange certificate. </dd> <dt> *ppbCertBlob* \[out\] </dt> <dd> Pointer to a variable that receives a pointer to a buffer that contains the certificate. </dd> <dt> *lpdwCertBlobLen* \[out\] </dt> <dd> Pointer to a variable that receives the size of the certificate that is returned. </dd> <dt> *pdwErrCode* \[out\] </dt> <dd> Pointer to a variable that receives the error code. <dt> <span id="LSERVER_S_SUCCESS"></span><span id="lserver_s_success"></span> <span id="LSERVER_S_SUCCESS"></span><span id="lserver_s_success"></span>**LSERVER\_S\_SUCCESS** (0) </dt> <dd> Call is successful. </dd> <dt> <span id="TLS_W_SELFSIGN_CERTIFICATE"></span><span id="tls_w_selfsign_certificate"></span> <span id="TLS_W_SELFSIGN_CERTIFICATE"></span><span id="tls_w_selfsign_certificate"></span>**TLS\_W\_SELFSIGN\_CERTIFICATE** (4007) </dt> <dd> Certificate returned is a self-signed certificate. </dd> <dt> <span id="TLS_W_TEMP_SELFSIGN_CERT"></span><span id="tls_w_temp_selfsign_cert"></span> <span id="TLS_W_TEMP_SELFSIGN_CERT"></span><span id="tls_w_temp_selfsign_cert"></span>**TLS\_W\_TEMP\_SELFSIGN\_CERT** (4009) </dt> <dd> Certificate returned is temporary. </dd> <dt> <span id="TLS_E_ACCESS_DENIED"></span><span id="tls_e_access_denied"></span> <span id="TLS_E_ACCESS_DENIED"></span><span id="tls_e_access_denied"></span>**TLS\_E\_ACCESS\_DENIED** (5003) </dt> <dd> Access denied. </dd> <dt> <span id="TLS_E_ALLOCATE_HANDLE"></span><span id="tls_e_allocate_handle"></span> <span id="TLS_E_ALLOCATE_HANDLE"></span><span id="tls_e_allocate_handle"></span>**TLS\_E\_ALLOCATE\_HANDLE** (5007) </dt> <dd> Server is too busy to process the request. </dd> <dt> <span id="TLS_E_NO_CERTIFICATE"></span><span id="tls_e_no_certificate"></span> <span id="TLS_E_NO_CERTIFICATE"></span><span id="tls_e_no_certificate"></span>**TLS\_E\_NO\_CERTIFICATE** (5022) </dt> <dd> Cannot retrieve a certificate. </dd> </dl> </dd> </dl> ## Return value This function returns the following possible return values. <dl> <dt> **RPC\_S\_OK** </dt> <dd> The call succeeded. Check the value of the *pdwErrCode* parameter to get the return code for the call. </dd> <dt> **RPC\_S\_INVALID\_ARG** </dt> <dd> The argument was invalid. </dd> </dl> ## Requirements | Requirement | Value | |-------------------------------------|-----------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows Vista<br/> | | Minimum supported server<br/> | Windows Server 2008<br/> | | DLL<br/> | <dl> <dt>Mstlsapi.dll</dt> </dl> | ## See also <dl> <dt> [**TLSConnectToLsServer**](tlsconnecttolsserver.md) </dt> </dl>
Python
UTF-8
2,062
2.53125
3
[]
no_license
#coding=utf-8 import sys import numpy as np reload(sys) sys.setdefaultencoding('utf-8') thre = int(sys.argv[1]) fr = open('../data/corpus_train.txt','r') class_types = {} class_types_num = 0 all_text = [] while True: line = fr.readline() if not line: break content = line.strip().split() all_text.append(content) if content[0] not in class_types: class_types[content[0]] = class_types_num class_types_num+=1 fr.close() word_text_map = {} text_num_of_each_class = [0]*class_types_num for text in all_text: duplicate = {} text_num_of_each_class[class_types[text[0]]] +=1 for word in text[1:]: if word in duplicate: continue duplicate[word] = 1 if word in word_text_map: text_map = word_text_map[word] else: text_map = [0]*class_types_num text_map[class_types[text[0]]] += 1 word_text_map[word] = text_map total_text_num = len(all_text) word_text_list = [] word_list = [] for k in word_text_map.keys(): word_list.append(k) word_text_list.append(word_text_map[k]) word_text_list = np.array(word_text_list,dtype=np.float32) text_num_of_each_class = np.array(text_num_of_each_class,dtype=np.float32) word_total_frequence = np.reshape(np.sum(word_text_list,1),(-1,1)) word_in_other_class = word_total_frequence - word_text_list other_word_in_class = text_num_of_each_class - word_text_list not_the_word_and_class = total_text_num - word_text_list - word_in_other_class - other_word_in_class word_num = len(word_list) print('word num:\t%d' % word_num) chi_square_value = np.divide(np.square(np.multiply(word_text_list,not_the_word_and_class) - np.multiply(word_in_other_class,other_word_in_class)) , np.multiply(word_text_list+word_in_other_class, other_word_in_class+not_the_word_and_class)) chosed_word = {} for cla in range(class_types_num): cur_chi = chi_square_value[:,cla] order = np.argsort(-cur_chi) for i in order[:thre]: if i in chosed_word: continue chosed_word[i] = 1 fw = open('../data/chi_square_word_%d.txt' % thre,'w') for k in chosed_word: fw.write(word_list[k]+'\n') fw.close()
PHP
UTF-8
825
2.859375
3
[ "MIT" ]
permissive
<?php namespace App\Http; use Illuminate\Http\Request as BaseRequest; class Request extends BaseRequest { protected $foo; public function __construct() { parent::__construct(); // Do your set up here, for example: $this->yourAttribute = 'foo'; } /** * Get a unique fingerprint for the request / route / IP address. * * @return string * * @throws \RuntimeException */ public function fingerprint() { if (! $this->route()) { throw new RuntimeException('Unable to generate fingerprint. Route unavailable.'); } return sha1( implode('|', $this->route()->methods()). '|'.$this->route()->domain(). '|'.$this->route()->uri(). '|'.$this->ip() ); } }
Python
UTF-8
3,752
3.046875
3
[]
no_license
from Tkinter import * import random import sys import sha import math class App: def __init__(self, master): frame = Frame(master) frame.pack(padx=10, pady=10) self.useNumbers = BooleanVar(master, True, None) self.useSymbols = BooleanVar(master, True, None) # Label Label(frame, state=ACTIVE, text="Unencrypted Password: ").grid(row=0, padx=5, pady=5, sticky=W) # Text field self.input = Entry(frame, width=32, show="*") self.input.grid(row=0, column=1, padx=5, pady=5, sticky=W) # self.input.bind("<Key>", self.encryptListener) self.input.bind("<Return>", self.encryptListener) # Button self.submit = Button(frame, text="Encrypt", command=self.encrypt) self.submit.grid(row=0, column=2, sticky=W, padx=5, pady=5) # Label Label(frame, state=ACTIVE, text="Options: ").grid(row=1, padx=5, pady=5, sticky=E) # Slider self.slider = Scale(frame, from_=8, to=40, orient=HORIZONTAL, length=200, command=self.encryptListener) self.slider.grid(row=1, column=1, columnspan=2, sticky=W, padx=1, pady=5) sliderDefault = IntVar() sliderDefault.set(40) self.slider.config(variable=sliderDefault) # Checkbox: numbers self.useNumbersCheckbox = Checkbutton(frame, text="Use numbers in encryption", variable=self.useNumbers, command=self.encrypt, onvalue=True, offvalue=False) self.useNumbersCheckbox.select() self.useNumbersCheckbox.grid(row=2, column=1, columnspan=2, sticky=W) # Checkbox: symbols self.useSymbolsCheckbox = Checkbutton(frame, text="Use symbols in encryption", variable=self.useSymbols, command=self.encrypt, onvalue=True, offvalue=False) self.useSymbolsCheckbox.select() self.useSymbolsCheckbox.grid(row=3, column=1, columnspan=2, sticky=W) # Label Label(frame, state=ACTIVE, text="Encrypted Password: ").grid(row=4, padx=5, pady=5, sticky=W) # Results self.output = Entry(frame, state="readonly", relief="flat", width=45) self.output.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W) def encryptListener(self, event): self.encrypt() def encrypt(self): result = "" if (len(self.input.get()) > 0): length = self.slider.get() crypt = sha.new(self.input.get()) random.seed(int(crypt.hexdigest(), 16) / length) # Define possible characters chars = [] for i in range(65, 91): chars.append(chr(i)) # A-Z for i in range(97, 123): chars.append(chr(i)) # a-z if self.useNumbers.get(): for i in range(48, 58): chars.append(chr(i)) # 0-9 if self.useSymbols.get(): for i in range(0,3): chars.append("!"); chars.append("$"); chars.append("?"); # Generate the string for i in range(0, length): result = result + chars[random.randint(0, len(chars)-1)] var = StringVar() var.set(result) self.output.config(textvariable=var) root = Tk() app = App(root) app.input.focus() root.resizable(0, 0) root.title("Patrick's Passwordifier") root.mainloop()
Python
UTF-8
875
3.234375
3
[]
no_license
# -*- coding: utf-8 -*- class Solution(object): def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ res = dict() for index, num in enumerate(nums): if num in res: res[num].append(index) else: res[num] = [index] d, du = 100000, -1 for k, v in res.items(): _len = len(v) if _len > du: du = _len if _len > 1: d = v[-1] - v[0] + 1 elif _len == du: if _len > 1: _d = v[-1] - v[0] + 1 if _d < d: d = _d return d if d != 100000 else 1 if __name__ == '__main__': s = Solution() res = s.findShortestSubArray([1, 2, 2, 3, 1, 4, 2]) print(res)
Markdown
UTF-8
2,424
2.84375
3
[]
no_license
# Data_Science_Manutencao # Departamento de Manutenção - **IA e ML estão transformando a indústria, principalmente os departamentos de produção e manutenção** - **De acordo com o relatório do World Economic Forum, essas tecncologias terão grande impacto na indústria 4.0.** - Departamento de manutenção - Departamento de produção - Cadeia de suprimentos - **Técnicas de Deep Learning tem provado serem eficientes para detecção e localização de defeitos em imagens.** - **LandingAI: https://landing.ai/defect-detection/.** Referência: "https://www.cio.com/article/3302797/how-ai-is-revolutionizing- manufacturing.html". **CLASSIFICAÇÃO E SEGMENTAÇÃO** ![Classificação e Segmentação](https://github.com/callacius/Data_Science_Manutencao/blob/main/images/01.png?raw=true) **MASK (MÁSCARA)** - **O objetivo da segmentação de imagens é “entender” a imagem pixel a pixel, sendo que cada pixel é associado a uma classe** - **A saída da segmentação produz uma nova imagem, que é chamada de “máscara da imagem”.** - **Máscaras podem ser representadas associando valores de pixels para coordenadas.** - **Para representar máscaras aplicamos o processo de “flattening” – 1-D array.** - **Exemplo: [255, 0, 0, 255], [1, 0, 0, 1].** ![Mask](https://github.com/callacius/Data_Science_Manutencao/blob/main/images/02.png?raw=true) **RUN LENGTH ENCODING (RLE)** - **Técnica para compressão de dados que armazena sequências que contém dados consecutivos (combinação em um só valor).** - **Considerando que temos uma imagem com texto preto em fundo branco.** ** WWWWWWWWWWWWBWWWWWWWWWW** ** WWBBBWWWWWWWWWWWWWWWWWWW** ** WWWWWBWWWWWWWWWWWWWW** - **Run-length encoding (RLE):** ** 12W1B12W3B24W1B14W** **RESUNET** - **Combina a arquitetura UNet com blocos residuais (skip connection) para reduzir o problema do gradiente desaparecendo (vanish gradient problem)** - **Consiste em três partes:** - (1) Encoder or contracting path - (2) Bottleneck - (3) Decoder or expansive path ![Resunet](https://github.com/callacius/Data_Science_Manutencao/blob/main/images/03.png?raw=true) **ARQUITETURA** ![Arquitetura](https://github.com/callacius/Data_Science_Manutencao/blob/main/images/04.png?raw=true) Fonte: **https://www.udemy.com/course/ciencia-de-dados-para-empresas-e-negocios**
C++
UTF-8
7,899
2.984375
3
[]
no_license
/* Client.h -- Card Game Client Desktop Application Lucas Weisensee January 2015 Stores info for current Client allows for: -connection info to be stored and monitored -packages to be sent -name -device ************************TO DO********************** --Implement connection closed error instead of repeated 'result' checks */ // DEBUGGING: #define DEBUG true #ifdef DEBUG #define DEBUG_IF(cond) if(cond) #else #define DEBUG_IF(cond) if(false) #endif #define WIN32_LEAN_AND_MEAN #pragma once #include <winsock2.h> #include <stdlib.h> #include <string> #include <list> #include <atomic> #include <time.h> //#include "..\Library\LogFile.h" //Log writing library #include "..\Library\Message.h" //Message type library #include "..\Library\ServerException.h" //exception library #include "..\Library\Card.h" static DWORD WINAPI launchListenThread(LPVOID* callingObj); // creates a thread that listens on the socket for incoming packets class Client: public Message { public: // ::Client CONSTRUCTORS AND SETUP:: Client() : Client((SOCKET)NULL){} Client(const Client &toCopy); Client(SOCKET pSocket) : Client("NONE", pSocket){} // Constructs Client with given socket and no name Client(std::string nName, SOCKET pSocket); //constructs Client with arguments passed in Client(std::string nName, SOCKET pSocket, int tInterval); //constructs Client with arguments passed in, and given timeout Interval ~Client(); // ::SEND Message FUNCTIONS:: int sendMFinal(unsigned char code, std::string* toSend); // Sends char array to Client, of Message type: code int sendM(unsigned char code, std::string toSend); // Sends char array to Client, of Message type: code int sendM(unsigned char code, char * toSend); // Sends char array to Client, of Message type: code int sendM(unsigned char code, char toSend); // Sends char Message to Client, of Message type: code int sendM(unsigned char code, int toSend); // Sends int Message to Client, of Message type: code int sendM(unsigned char code, const char * toSend); // Sends char array to Client, of Message type: code int sendM(unsigned char code, std::string* toSend); // Sends char array to Client, of Message type: code int sendM(int code, std::string* toSend); // Sends char array to Client, of Message type: code int sendM(unsigned char code); // Sends char array to Client, of Message type: code int sendM(int n); // Sends char array to Client, includes description in case error log must be written // ::GET ANSWER FUNCTIONS:: /* All "getAnswer" functions return an error/success status of the function. 0 if receive error or if answer code doesn't match 'aCode' -1 on connection closure 1 on success and if answer code matches 'aCode' ALL "getAnswer" functions return only the answer from the Client */ Card* getNextPlay(); // return the Clients next Card play on the current trick unsigned char getAnswerType(); // Returns the Message code from the most recent packet received from the Client, -1 if null int getConnectionType(); // Returns what type of connection the Client wants to initiate: database access or game play, 0 if answer not answered correctly int receiveMessage(); // emulate recv function, pulling from inbox(std::list) int getStrAnswer(std::string * ans, unsigned char aCode); // Sets ans to Client's string response and checks ans type, returns 0 if receive error or if answer code doesn't match 'aCode', and -1 on connection closure, 1 on success and if answer code matches 'aCode' int getStrQueryAnswer(std::string * ans, unsigned char qCode, unsigned char aCode); // Sets ans to Client's string response to Message "qcode" and checks ans type, returns 0 if receive error or if answer code doesn't match 'aCode', and -1 on connection closure, 1 on success and if answer code matches 'aCode' int getIntAnswer(int * ans, unsigned char aCode);// Gets integer answer from Client, returns receive success code if answer type matches aCode type bool closeConnection(); // ::REQUEST HANDLING:: void checkInbox(); // checks the inbox for any requests and processes any pings void requestHandled(unsigned char code, bool success); // notify Client of request handled and success void requestHandled(unsigned char code); // notify Client of request handled unsigned char getNextRequest(); // returns code of next request to process bool hasRequests(bool* hasReq); // returns true if there are requests to be handled, false otherwise void handleRequestFailure(unsigned char code); // handles the server's failure to fulfill a specified request bool isRequest(unsigned char code); // returns true if code is a request type that must be answered //:: GETTERS AND SETTERS:: int getStatus(); // returns true if the Client has been active within the set time interval bool setUpdateEvent(WSAEVENT newEvent); // sends in the update event to be signaled by the Client when updates are received from user bool setName(std::string nName); // sets passed in name to Client's name, returns true if successful bool setName(); // queries user for name then sets their new name, returns true if successful std::string getName(); // returns Client's name int getPlayerPref(); // returns player # preference, or 0 if none void setPlayerPref(int n); // updates player # preference void setSocket(SOCKET nSocket); // updates the Clients socket SOCKET getSocket(); // returns the Clients socket std::string* generateMessage(unsigned char code, std::string *toSend); int checkClientResponse(unsigned char aCode); // checks that correct response was received, considers receive success, then checks code of received Message. if receive was successful, returns 1 if Message type matched, 0 otherwise. if receive failed, returns failure code int setupClient(std::string nName, SOCKET pSocket); //constructs Client with arguments passed in // GLOBAL DATA VALUES static const int DEFAULT_BUFLEN = 1024; std::string buffer; // incoming Message buffer std::string name; // Client's name SOCKET ClientSocket; // Client's socket //LogFile * pLog; // log file unsigned char recent; // Most recent Message type int playerPref; // players preferred position # (1-max) // ::INBOX AND REQUEST HISTORY:: bool inboxHas(unsigned char aCode); // returns true if a Message of type 'aCode' is in the inbox void printRequests(); // print out the requests list for debugging void printinbox(); // print out the Messages in the inbox int getInboxMessage(std::string * ans, unsigned char aCode); // get's specified Message from inbox as if it were just received std::list<std::string> requests; // lists of active requests std::list<std::string> inbox; // lists of unreceived Messages // ::TIMEOUT AND ACTIVITY MONITORING:: int localStatus; // the status to return when queried for local status void handlePing(); // checks and handles a status request from server bool recentlyActive(); // returns true if the Client was active within a set time interval void updateStatus(); // checks in with and updates the current Client's status void updateStatus(int n); // checks in with and updates the current Client's status double timeoutInterval; // how long between contact with Client before server re-checks status time_t recentActivity; // most recent time of contact with Client // ::MULTI_THREADING:: bool hasUpdateEvent; // true if the Client has an update event they should be signaling WSAEVENT newMessage; // server's new Message event void signalNewMessage(); // updates the server of new Message arrival void listenForPacket(); // listens for packet on the Client's socket CRITICAL_SECTION inboxLock; // Message inbox access lock CRITICAL_SECTION EventLock; // Message inbox access lock std::atomic<int> ClientStatus; // status of Client's connection };
Java
UTF-8
1,266
2.359375
2
[]
no_license
package com.example.post; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "POST") public class Post implements Serializable { private static final long serialVersionUID = 7548395543L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "POST_ID") private Integer postId; @Column(name = "TEXT") private String text; @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true) private List<Comment> comments = new ArrayList<>(); public Integer getPostId() { return postId; } public void setPostId(Integer postId) { this.postId = postId; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public void addComment(Comment comment) { comments.add(comment); comment.setPost(this); } public void removeComment(Comment comment) { comments.remove(comment); comment.setPost(null); } }
PHP
UTF-8
197
2.6875
3
[]
no_license
<?php $myfile = fopen("files/newfile.txt","w"); $data = "New Data Inserted"; $filecreated=fwrite($myfile,$data); if($filecreated){ echo "Inserted Data Successfully"; } fclose($myfile); ?>
Java
UTF-8
2,698
2.375
2
[]
no_license
package com.egfds.vinshop.controllers; import com.egfds.vinshop.models.Attribute; import com.egfds.vinshop.models.AttributeList; import com.egfds.vinshop.models.ProductType; import com.egfds.vinshop.services.ProductService.*; import org.springframework.core.style.StylerUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/productTypes") public class ProductTypeController { IProductTypeService productTypeService; IAttributeService attributeService; IValueService valueService; public ProductTypeController(IProductTypeService productTypeService, IAttributeService attributeService, IValueService valueService) { this.productTypeService = productTypeService; this.attributeService = attributeService; this.valueService = valueService; } @GetMapping("/create") public String create(Model model){ model.addAttribute("productType", new ProductType()); return "productType/create"; } @PostMapping("/create") public String create(@ModelAttribute ProductType productType){ productTypeService.save(productType); return "redirect:/productTypes/create"; } @GetMapping("/list") public String list(Model model){ model.addAttribute("types", productTypeService.findAll()); return "productType/list"; } @PostMapping("/edit") public String edit(@RequestParam("id") long typeId, Model model){ model.addAttribute("type", productTypeService.findById(typeId).get()); model.addAttribute("attributeList", new AttributeList(attributeService.getAttributesByType(typeId))); return "productType/edit"; } @PostMapping("/update") public String update(@ModelAttribute ProductType type, @ModelAttribute AttributeList wrapper){ for(Attribute att : wrapper.getAttributes()){ attributeService.save(att); } productTypeService.save(type); return "redirect:/productTypes/list"; } @PostMapping("/deleteAttribute") public String deleteAttribute(@RequestParam long attributeId, @ModelAttribute ProductType type, Model model){ System.out.println("ATTRIBUTE ID: " + attributeId); // Removing all values linked to the attribute valueService.deleteByAttributeId(attributeId); // Removing attribute attributeService.deleteById(attributeId); model.addAttribute("type", type); model.addAttribute("attributeList", new AttributeList(attributeService.getAttributesByType(type.getId()))); return "productType/edit"; } }
PHP
UTF-8
2,456
3.40625
3
[]
no_license
<?php namespace App; use App\Exceptions\InvaliidParametersException; class RandomCodesGenerator { /** * default possible characters * * @var string */ private $possibleCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; /** * method to generate code * * @param integer $lenghtOfCode * * @return string */ public function generateCode(int $lenghtOfCode): string { if ($lenghtOfCode <= 0) { throw new InvaliidParametersException('Lenght of code must be greater than 0'); } $charactersLength = $this->getPossibleCharactersLength(); $randomcode = ''; for ($i = 0; $i < $lenghtOfCode; $i++) { $randomcode .= $this->possibleCharacters[mt_rand(0, $charactersLength - 1)]; } return $randomcode; } /** * generate codes * * @param integer $lenghtOfCode * @param integer $numberOfCodes * @param boolean $unique - control flag all codes in the table are to be unique - default false * * @return array */ public function generateCodes(int $lenghtOfCode, int $numberOfCodes, bool $unique = false): array { $codesArray = []; if ($numberOfCodes <= 0) { throw new InvaliidParametersException('Number of codes must be greater than 0'); } if ($unique) { $numberOfRandomCodes = 0; while ($numberOfRandomCodes < $numberOfCodes) { $code = $this->generateCode($lenghtOfCode); if (!in_array($code, $codesArray)) { $codesArray[] = $code; $numberOfRandomCodes++; } } } else { for ($i = 0; $i < $numberOfCodes; $i++) { $codesArray[] = $this->generateCode($lenghtOfCode); } } return $codesArray; } /** * method to set custom posible characters * * @param string $possibleCharacters * * @return void */ public function setPossibleCharacters(string $possibleCharacters): void { $this->possibleCharacters = $possibleCharacters; } /** * get possible characters length * * @return integer */ private function getPossibleCharactersLength(): int { return mb_strlen($this->possibleCharacters, 'UTF-8'); } }
Python
UTF-8
877
3.40625
3
[]
no_license
import sys def handle_case(line): cakes = line.strip() def check(cakes): return cakes == '+'*len(cakes) def swap(cakes): new=[] for cake in cakes: if cake == '+': new.append('-') else: new.append('+') return new if check(cakes): return 0 # filp from right to left whenever we see a '-' flip_count = 0 while True: idx = cakes.rfind('-') if idx != -1: cakes = ''.join(list(swap(cakes[:idx+1]))+list(cakes[idx+2:])) flip_count += 1 else: return flip_count if __name__ == '__main__': cases = int(sys.stdin.readline().strip()) for i in xrange(1, cases+1): line = sys.stdin.readline().strip() answer = handle_case(line) print "Case #{}: {}".format(i, answer)
Markdown
UTF-8
3,019
3.3125
3
[]
no_license
# Diversity, Inclusion and Belonging https://www.linkedin.com/learning/diversity-inclusion-and-belonging Summary: this is a really upbeat and short course explaining the benefits of nurturing diversity, inclusion and belonging in an organisation. People want to feel like they belong to a community, that they have psychological safety and that "someone really cares about me and my unique self". # Hold up a mirror using the data Movement happens when I have both your mind and your heart * Data grabs the intellect * Emotions grab the heart * If you couple them together it's way more powerful ## How to improve "employee experience" * We are genetically wired to belong to a community * Power of taking a moment of uncertainty is through story-telling * When you share stories you can shorten an uncertainty moment and shorten the distance to productivity * Paul Nack: power of story-telling: story-telling releases chemicals in our brains to make us more compassionate, empathetic * Story-telling is an underrated amazing tool that every human being should explore more ## It's about you If you're a manager you have an opportunity to change lives on your team by creating belonging moments and share your story with your team # Hiring diverse talent * You have to slow your brain. If you go fast your biases creep up. * Every individual makes the job bigger or better because of who they are. Job description describes only 25% of the candidate. * When you recruit someone tell them "why you" * We all make mistakes. We have to have a compassionate company. # How to listen to employees * All hands * Mini lunches * Be as approachable as possible (formal title can be a barrier) * Poll new hires * Poll those who said no to us # Integrate DIBs into the employee life cycle * DIBs should be in the DNA of everything that we do, not an initiative * Do you see people like you? * Do you feel like you're celebrated because of your unique background? # Measure with a DIBs index * How do we measure DIBs? * Drivers of DIBs engagement * Someone cares about me at work * When something bad happens, I feel OK, I feel safe * Have you given a belonging moment to someone else? * How you emote, how your body talks to me, is really what I look for and listen to # Operationalise DIBs * Small things you can do every day to make someone feel great * Start meetings with gratitude -- i.e. share things you are personally grateful for outside of work. This helps the team to get to know each other as individuals. * Share gratitude to another team. * Be aware of the voices that are not being heard. In a remote meeting assign an individual in the room to look after the interests of each remote participant. * Say "thank you" and appreciate people. * If someone has something to say and they're striving to be heard then the least you can do is listen. Don't fill in the gaps or fill it in for them.
Markdown
UTF-8
2,181
3.75
4
[ "MIT" ]
permissive
--- metaTitle: "PHP - Object Serialization" description: "Serialize / Unserialize, The Serializable interface" --- # Object Serialization ## Serialize / Unserialize `serialize()` returns a string containing a byte-stream representation of any value that can be stored in PHP. `unserialize()` can use this string to recreate the original variable values. **To serialize an object** ```php serialize($object); ``` **To Unserialize an object** ```php unserialize($object) ``` **Example** ```php $array = array(); $array["a"] = "Foo"; $array["b"] = "Bar"; $array["c"] = "Baz"; $array["d"] = "Wom"; $serializedArray = serialize($array); echo $serializedArray; //output: a:4:{s:1:"a";s:3:"Foo";s:1:"b";s:3:"Bar";s:1:"c";s:3:"Baz";s:1:"d";s:3:"Wom";} ``` ## The Serializable interface **Introduction** > Classes that implement this interface no longer support `__sleep()` and `__wakeup()`. The method serialize is called whenever an instance needs to be serialized. This does not invoke `__destruct()` or has any other side effect unless programmed inside the method. When the data is `unserialized` the class is known and the appropriate `unserialize()` method is called as a constructor instead of calling `__construct()`. If you need to execute the standard constructor you may do so in the method. **Basic usage** ```php class obj implements Serializable { private $data; public function __construct() { $this->data = "My private data"; } public function serialize() { return serialize($this->data); } public function unserialize($data) { $this->data = unserialize($data); } public function getData() { return $this->data; } } $obj = new obj; $ser = serialize($obj); var_dump($ser); // Output: string(38) "C:3:"obj":23:{s:15:"My private data";}" $newobj = unserialize($ser); var_dump($newobj->getData()); // Output: string(15) "My private data" ``` #### Syntax - serialize($object) - unserialize($object) #### Remarks All PHP types except for resources are serializable. Resources are a unique variable type that reference "external" sources, such as database connections.