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
PHP
UTF-8
800
2.953125
3
[ "MIT" ]
permissive
<?php namespace App\Library; /** * Class ResponseMessages * @author Adeyemi Olaoye <yemi@cottacush.com> * @package App\Library */ class ResponseMessages { private static $messages = [ ResponseCodes::METHOD_NOT_IMPLEMENTED => 'method not implemented', ResponseCodes::INTERNAL_SERVER_ERROR => 'an internal server error occurred', ResponseCodes::UNEXPECTED_ERROR => 'an unexpected error occurred', ]; /** * @author Adeyemi Olaoye <yemi@cottacush.com> * @param $code * @return mixed */ public static function getMessageFromCode($code) { if (array_key_exists($code, self::$messages)) { return self::$messages[$code]; } else { return self::$messages[ResponseCodes::UNEXPECTED_ERROR]; } } }
Python
UTF-8
12,254
2.5625
3
[]
no_license
#! /usr/bin/python import cgi import cgitb import json cgitb.enable() us_state_abbrev = { 'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'District of Columbia': 'DC', 'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS', 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY', } states = { 'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas', 'AS': 'American Samoa', 'AZ': 'Arizona', 'CA': 'California', 'CO': 'Colorado', 'CT': 'Connecticut', 'DC': 'District of Columbia', 'DE': 'Delaware', 'FL': 'Florida', 'GA': 'Georgia', 'GU': 'Guam', 'HI': 'Hawaii', 'IA': 'Iowa', 'ID': 'Idaho', 'IL': 'Illinois', 'IN': 'Indiana', 'KS': 'Kansas', 'KY': 'Kentucky', 'LA': 'Louisiana', 'MA': 'Massachusetts', 'MD': 'Maryland', 'ME': 'Maine', 'MI': 'Michigan', 'MN': 'Minnesota', 'MO': 'Missouri', 'MP': 'Northern Mariana Islands', 'MS': 'Mississippi', 'MT': 'Montana', 'NA': 'National', 'NC': 'North Carolina', 'ND': 'North Dakota', 'NE': 'Nebraska', 'NH': 'New Hampshire', 'NJ': 'New Jersey', 'NM': 'New Mexico', 'NV': 'Nevada', 'NY': 'New York', 'OH': 'Ohio', 'OK': 'Oklahoma', 'OR': 'Oregon', 'PA': 'Pennsylvania', 'PR': 'Puerto Rico', 'RI': 'Rhode Island', 'SC': 'South Carolina', 'SD': 'South Dakota', 'TN': 'Tennessee', 'TX': 'Texas', 'UT': 'Utah', 'VA': 'Virginia', 'VI': 'Virgin Islands', 'VT': 'Vermont', 'WA': 'Washington', 'WI': 'Wisconsin', 'WV': 'West Virginia', 'WY': 'Wyoming' } HTML_HEADER = 'Content-type: text/html\n\n' Top_HTML = ''' <html> <head> <title>Sample Python Forms-responder</title> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <link href='https://fonts.googleapis.com/css?family=Playfair+Display' rel='stylesheet' type='text/css'> </head> <body> <style> .nav{ border:1px solid #ccc; border-width:1px 0; list-style:none; margin:0; padding:0; text-align:center; } .nav li{ display:inline; } .nav a{ display:inline-block; padding:10px; color: #008FD5; text-decoration: none; font-size: 17px; line-height: 26px; font-family: AtlasGrotesk, 'Helvetica Neue', Helvetica, Arial, sans-serif; } .nav a:hover { font-size: 30px; } </style> <ul class = "nav"> <li><a href="http://marge.stuy.edu/~anish.shenoy/Final_Project/main.py">Home</a></li> <li><a href="https://www.washingtonpost.com/graphics/politics/2016-election/primaries/schedule/">Primary Dates</a></li> <li><a href="https://votesmart.org/education/presidential-primary#.V1NTW7grKUk">Information on Primaries</a></li> </ul> ''' Bottom_HTML = "</body></html>" def convertListToJs(list): finalString = "[" for i in list: finalString += "'" + str(i) + "', " finalString += "]" return finalString def openFile(filename): f = open(filename, "rU") s = f.read() f.close() return s def organize(): s = openFile("demdata.csv") stateByState = s.split("\n") lst = [i.split(",") for i in stateByState] keys = lst[0] mD = {} for i in lst[1:-1]: d = {} for n in range(len(keys)): if n < len(i): d[keys[n]] = i[n] else: d[keys[n]] = "" if d["Bernie Delegates"] != "" and d["Clinton Delegates"] != "": if max(int(d["Bernie Delegates"]), int(d["Clinton Delegates"])) == int(d["Bernie Delegates"]): d["Winner"] = "Bernie" else: d["Winner"] = "Clinton" else: d["Winner"] = "None" if i[0] in us_state_abbrev: mD[us_state_abbrev.get(i[0], "")] = d else: mD[i[0]] = d return mD def locationsAndValues(masterDict): winnerDict = {"Bernie":0, "Clinton":1, "None":0.5} locations =[] values = [] for i in masterDict: if len(i) == 2: if "Winner" in masterDict[i]: locations.append(i) values.append(winnerDict[masterDict[i]["Winner"]]) return [locations, values] def displayMap(masterDict): locationsValues = locationsAndValues(masterDict) js = ''' var chartDiv = document.getElementById('chart-div'); var data = [{ type: "choropleth", locations: ''' + convertListToJs(locationsValues[0]) + "," + ''' locationmode: "USA-states", colorscale: [[0,"rgb(102, 187, 106)"], [1,"rgb(21, 101, 192)"]], showscale: false, hoverinfo: "location", z: ''' + convertListToJs(locationsValues[1]) + ''', marker: { line: { width: 2, color: "white" } } }]; var layout = { autosize: false, width: window.innerWidth, height: window.innerHeight - 100, geo: { scope: "usa", showlakes: true, lakecolor: 'cyan' }, font: { family: 'Playfair Display, serif', size: 24, color: "Black", bold: true } }; Plotly.plot(chartDiv, data, layout); chartDiv.on("plotly_click", function(data){ window.open("main.py?state=" + data.points[0].location); }); ''' print('<div id="page">') print('<center><div id="header"><h1> <font size=10>2016 Democratic Primaries</font></h1><p>With the upcoming elections predicted to be one of the most influential elections in history, it is imperative that we have some of the most informed voters in history. This map is updated daily with results from the democratic primaries; click on a state for more information about the results from that state.</p></div></center>') style = ''' <style> #header { position: relative; } </style> ''' print('<center><div id="chart-div"></div></center>') print('</div>') print(style) print("<script>") print(js) print("</script>") def plotDelgateGraph(bernieDel, clintonDel, state, divName): js = ''' var trace1 = { x: ''' + convertListToJs([bernieDel]) + "," + ''' y: ["Sanders"], name: "Bernie Sanders", orientation: 'h', type: 'bar', marker: { color: 'rgba(102, 187, 106, .5)', width: 1 } }; var trace2 = { x: ''' + convertListToJs([clintonDel]) +',' + ''' y: ["Clinton"], name: 'Hillary Cinton', orientation: 'h', type: 'bar', marker: { color: "rgba(21, 101, 192, 0.5)", width: 1 } }; var data = [trace1, trace2]; var layout = { title: 'The ''' + states[state] + ''' Delegate Count', width: 1024, height: 350, font: { family: 'Playfair Display, serif', size: 20, color: 666 } }; Plotly.newPlot("''' + divName + '''", data, layout); ''' return js def plotDelgatePie(bernieDel, clintonDel, state, divName): values = [bernieDel, clintonDel] js = ''' var data = [{ values: ''' + convertListToJs(values) + ',' + ''' labels: ['Bernie Sanders', 'Hillary Clinton'], type: 'pie', marker :{ colors: ['rgba(102, 187, 106, .5)', 'rgba(21, 101, 192, 0.5)'] } }]; var layout = { title: 'The ''' + states[state] + ''' Delegate Count by %', height: 400, width: 1000, font: { family: 'Playfair Display, serif', size: 20, color: "Black" }, autoexpand: false }; Plotly.newPlot(''' + "'" + divName + "'" + ''', data, layout); ''' return js def plotVoteGraph(bernieVotes, clintonVotes, state, divName): js = ''' var trace1 = { x: ''' + convertListToJs([bernieVotes]) + "," + ''' y: ["Sanders"], name: "Bernie Sanders", orientation: 'h', type: 'bar', marker: { color: 'rgba(102, 187, 106, .5)', width: 1 } }; var trace2 = { x: ''' + convertListToJs([clintonVotes]) +',' + ''' y: ["Clinton"], name: 'Hillary Cinton', orientation: 'h', type: 'bar', marker: { color: "rgba(21, 101, 192, 0.5)", width: 1 } }; var data = [trace1, trace2]; var layout = { title: 'The ''' + states[state] + ''' Popular Vote', width: 1024, height: 350, font: { family: 'Playfair Display, serif', size: 20, color: 666 } }; Plotly.newPlot("''' + divName + '''", data, layout); ''' return js def plotVotePieChart(bernieVotes, clintonVotes, state, divName): values = [bernieVotes, clintonVotes] js = ''' var data = [{ values: ''' + convertListToJs(values) + ',' + ''' labels: ['Bernie Sanders', 'Hillary Clinton'], type: 'pie', marker :{ colors: ['rgba(102, 187, 106, .5)', 'rgba(21, 101, 192, 0.5)'] } }]; var layout = { title: 'The ''' + states[state] + ''' Popular Vote by %', height: 400, width: 1000, font: { family: 'Playfair Display, serif', size: 20, color: "Black" }, autoexpand: false }; Plotly.newPlot(''' + "'" + divName + "'" + ''', data, layout); ''' return js def stateNotVoted(state): print(states[state] + " Has Not Voted Yet") def displayStatePage(state, masterDict): print('<center><div id="delegate-div">') print('<div id="delegate-horiz"></div>') print('<div id="delegate-pie"></div>') print('</div></center>') print('<center><div id="pop-div">') print('<div id="pop-horiz"></div>') print('<div id="pop-pie"></div>') print('</div></center>') style = ''' <style> #delegate-pie, #delegate-horiz, #pop-pie, #pop-horiz { display: inline-block; } </style> ''' print(style) if state in masterDict: stateInfo = masterDict[state] if stateInfo["Bernie Delegates"] != "" and stateInfo["Clinton Delegates"] != "": bernieDel = int(stateInfo["Bernie Delegates"]) clintonDel = int(stateInfo["Clinton Delegates"]) print("<script>") print(plotDelgateGraph(bernieDel, clintonDel, state, "delegate-horiz")) print(plotDelgatePie(bernieDel, clintonDel, state, "delegate-pie")) print("</script>") else: stateNotVoted(state) if stateInfo["Bernie Votes"] != "" and stateInfo["Clinton Votes"] != "": bernieVotes = int(stateInfo["Bernie Votes"]) clintonVotes = int(stateInfo["Clinton Votes"]) print("<script>") print(plotVoteGraph(bernieVotes, clintonVotes, state, "pop-horiz")) print(plotVotePieChart(bernieVotes, clintonVotes, state, "pop-pie")) print("</script>") def main(): masterDict = organize() print(HTML_HEADER) print(Top_HTML) elements = cgi.FieldStorage() keys = elements.keys() if "state" in keys: displayStatePage(str(elements.getvalue("state")), masterDict) else: displayMap(masterDict) print(Bottom_HTML) main()
Shell
UTF-8
1,306
4
4
[]
no_license
#!/bin/sh unmountusb() { [ -z "$drives" ] && exit chosen=$(echo "$drives" | dmenu -i -p "Unmount which drive?" | awk '{print $1}' | sed 's/\\/\\\\/g') [ -z "$chosen" ] && exit device="$(lsblk -nrpo "name,type,size,mountpoint" | grep "$chosen" | awk -F\ '{ print $1 }')" [ -L "$HOME"/Media ] && rm "$HOME"/Media udisksctl unmount -b "$device" && notify-send "💻 USB unmounting" "$chosen unmounted." } unmountandroid() { \ case "$(printf "Yes\\nNo" | dmenu -i -p "Unmount Android device?")" in Yes) fusermount -u "$HOME/MountAndroid" && rmdir "$HOME/MountAndroid" && notify-send "🤖 Android unmounting" "Device unmounted." ;; No) exit ;; esac } asktype() { \ case "$(printf "USB\\nAndroid" | dmenu -i -p "Unmount a USB drive or Android device?")" in USB) unmountusb ;; Android) unmountandroid ;; esac } drives=$(lsblk -nrpo "name,type,size,mountpoint" | awk '$2=="part"&&$4!~/\/boot|\/home$|SWAP/&&length($4)>1{printf "%s (%s)\n",$4,$3}') if [ -z "$HOME/MountAndroid" ]; then [ -z "$drives" ] && echo "No drives to unmount." && exit echo "Unmountable USB drive detected." unmountusb else if [ -z "$drives" ] then echo "Unmountable Android device detected." unmountandroid else echo "Unmountable USB drive(s) and Android device(s) detected." asktype fi fi
Java
UTF-8
314
2.265625
2
[ "Apache-2.0" ]
permissive
package de.diedavids.refactoring.codingdojo.step2_moving_features_between_objects.example1_move_method; public class AccountType { private boolean premium; public boolean isPremium() { return premium; } public void setPremium(boolean premium) { this.premium = premium; } }
Java
UTF-8
474
2.6875
3
[]
no_license
package dreamschool.csourse.chapter10; public class AccoutTest { public static void main(String[] args) { FundAccount fun1 = new FundAccount("111-2222", "홍길동", 5000000, 4.7); FundAccount fun2 = new FundAccount("666-7777", "홍길순", 1000000, 2.9); fun1.openAccount(); System.out.println("수익이 발생했습니다."); System.out.println(); fun2.openAccount(); System.out.println("수익이 발생했습니다."); } }
Java
UTF-8
944
2.359375
2
[ "MIT" ]
permissive
package com.amatkivskiy.gitter.sdk.async.faye.listeners; import com.google.gson.Gson; import com.amatkivskiy.gitter.sdk.async.faye.model.UserPresenceEvent; import com.amatkivskiy.gitter.sdk.async.faye.model.UserPresenceEvent.PresenceStatus; import static com.amatkivskiy.gitter.sdk.async.faye.FayeConstants.FayeChannels.ROOM_USERS_PRESENCE_CHANNEL_TEMPLATE; /** * Use this channel to catch user {@link PresenceStatus#In} and {@link PresenceStatus#Out} events in the room. */ public abstract class RoomUserPresenceChannel extends AbstractChannelListener<UserPresenceEvent> { private String roomId; public RoomUserPresenceChannel(String roomId) { super(new Gson()); this.roomId = roomId; } @Override public String getChannel() { return String.format(ROOM_USERS_PRESENCE_CHANNEL_TEMPLATE, roomId); } @Override protected Class<UserPresenceEvent> getParameterClass() { return UserPresenceEvent.class; } }
Java
UTF-8
6,590
1.90625
2
[]
no_license
package com.example.admin.restro.Signing; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.admin.restro.MainActivity; import com.example.admin.restro.R; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.ProgressDialog; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class Signup extends AppCompatActivity { private static final String REGISTER_URL = "http://restro.ey.es/signinreg.php"; Button done; EditText username, email, pass, verpassword, phoneno, addressloc; String name1, username1, password1, address1, phone1; private Boolean check; Context context = getBaseContext(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); username = (EditText) findViewById(R.id.s1); email = (EditText) findViewById(R.id.s2); pass = (EditText) findViewById(R.id.s3); verpassword = (EditText) findViewById(R.id.s4); phoneno = (EditText) findViewById(R.id.s5); addressloc = (EditText) findViewById(R.id.s6); done = (Button) findViewById(R.id.done); done.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* String subject = "Confirmation Email"; String message = "Thanking you for Signing up for Restro"; Intent mail = new Intent(Intent.ACTION_SEND); mail.putExtra(Intent.EXTRA_EMAIL, emaildid); mail.putExtra(Intent.EXTRA_SUBJECT, subject); mail.putExtra(Intent.EXTRA_TEXT,message); mail.setType("message/rfc822"); startActivity(Intent.createChooser(mail,"Choose an Email Client: "));*/ final String emailtext = email.getText().toString(); final String password = pass.getText().toString(); final String verify = verpassword.getText().toString(); final String user = username.getText().toString(); final String number = phoneno.getText().toString(); final String home = addressloc.getText().toString(); if (user.length() == 0) { username.setError("Enter a username"); } if (emailtext.length() == 0) { email.setError("Enter an Email"); } if (password.length() == 0) { pass.setError("Enter a Password"); } if (verify.length() == 0) { verpassword.setError("Enter a Password Above"); } if (number.length() == 0) { phoneno.setError("Enter your Phone Number"); } if (home.length() == 0) { addressloc.setError("Enter your Address"); } if (!isValidEmail(emailtext) && emailtext.length() != 0) { email.setError("Invalid Email"); } if (password.length() > 12) { pass.setError("Password should be lesser than 12 characters"); } boolean a = password.equalsIgnoreCase(verify); if (!a && password.length() != 0) { verpassword.setError("Password do not match Bro"); } if (!isValidNumber(number)) { phoneno.setError("Invalid Phone Number"); } if (isValidEmail(emailtext)&& (password.length() != 0 && password.length() < 13) /*&& (password == verify)*/) { registerUser(); Intent intent = new Intent(Signup.this, MainActivity.class); startActivity(intent); check(); } } }); } private void registerUser() { name1 = username.getText().toString(); username1 = email.getText().toString(); password1 = pass.getText().toString(); phone1 = phoneno.getText().toString(); address1 = addressloc.getText().toString(); String method = "register"; RegisterUserClass ru = new RegisterUserClass(this); // String abc="method" + method +"username" + username +"pass"+password; ru.execute(method, name1, username1, password1, phone1, address1); sendEmail(); } private boolean isValidEmail(String emailtext) { String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Pattern pattern = Pattern.compile(EMAIL_PATTERN); Matcher matcher = pattern.matcher(emailtext); return matcher.matches(); } private boolean isValidNumber(String number) { String NUMBER_PATTERN = "^[789]\\d{9}$"; Pattern pattern = Pattern.compile(NUMBER_PATTERN); Matcher matcher = pattern.matcher(number); return matcher.matches(); } public void check() { SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); check = true; editor.putBoolean("check", check); editor.commit(); } private void sendEmail() { //Getting content for email String email = username1; String subject = "RESTRO Registeration Notification"; String message = "Thanks for getting on board with Restro " +name1 +"!"; //Creating SendMail object SendMail sm = new SendMail(this, email, subject, message); //Executing sendmail to send email sm.execute(); } }
Java
UTF-8
3,568
2.171875
2
[]
no_license
package lt.codeacademy.project.api.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lt.codeacademy.project.api.EndPoint; import lt.codeacademy.project.api.dto.PostDto; import lt.codeacademy.project.api.entity.Post; import lt.codeacademy.project.api.entity.User; import lt.codeacademy.project.api.service.GroupService; import lt.codeacademy.project.api.service.PostService; import lt.codeacademy.project.api.service.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; import java.util.UUID; @RestController @RequestMapping(EndPoint.API_ROOT) @Api public class PostController { private final PostService postService; private final GroupService groupService; private final PostDto postDto; private final UserService userService; public PostController(PostService postService, GroupService groupService, UserService userService) { this.postService = postService; this.groupService = groupService; this.userService = userService; this.postDto = new PostDto(); } @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = EndPoint.PUBLIC + EndPoint.POST) @ApiOperation(value = "Get all Posts", httpMethod = "GET") public List<PostDto> getPosts() { return postDto.parseList(postService.getAllPosts()); } @GetMapping(value = EndPoint.PUBLIC + EndPoint.POST + EndPoint.BY_UUID, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get Post by UUID", httpMethod = "GET") private PostDto getPost(@PathVariable(EndPoint.UUID) UUID uuid) { return postDto.parseObject(postService.getPost(uuid)); } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = EndPoint.POST + EndPoint.BY_UUID) @ApiOperation(value = "Create Post", httpMethod = "POST") @ResponseStatus(HttpStatus.CREATED) public void createPost(@Valid @RequestBody Post post, @PathVariable(EndPoint.UUID) UUID id, @AuthenticationPrincipal String username) { post.setGroup(groupService.getGroup(id)); post.setUser((User) userService.loadUserByUsername(username)); postService.addPost(post); } @DeleteMapping(value = EndPoint.POST + EndPoint.BY_UUID) @ApiOperation(value = "Remove Post", httpMethod = "DELETE") @ResponseStatus(HttpStatus.NO_CONTENT) public void deletePost(@PathVariable(EndPoint.UUID) UUID uuid) { postService.removePost(uuid); } @PutMapping(EndPoint.POST) @ApiOperation(value = "Update Post", httpMethod = "PUT") public PostDto updatePost(@Valid @RequestBody Post post) { post.setComments(postService.getPost(post.getId()).getComments()); post.setUser(postService.getPost(post.getId()).getUser()); post.setGroup(postService.getPost(post.getId()).getGroup()); return postDto.parseObject(postService.updatePost(post)); } @GetMapping(value = EndPoint.PUBLIC + EndPoint.POST + EndPoint.BY_UUID + EndPoint.GROUP , produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get Post by group UUID", httpMethod = "GET") public List<PostDto> getPostsByGroupID(@PathVariable(EndPoint.UUID) UUID uuid) { return postDto.parseList(postService.getPostByGroupID(uuid)); } }
C++
UTF-8
2,583
2.6875
3
[]
no_license
#include "Debug.hpp" #include <cstdio> #include <cstdarg> #include <iostream> #if defined(_WIN32) || defined(_WIN64) #define RENDERFISH_LOG_IS_WINDOWS 1 #include <windows.h> static HANDLE hstdout; #define vsprintf vsprintf_s #elif defined(__APPLE__) #define RENDERFISH_LOG_IS_APPLE 1 #else //defined(__linux__) #define RENDERFISH_LOG_IS_LINUX 1 #endif #define SPRINT_BUF_SIZE 1024 static char sprint_buf[SPRINT_BUF_SIZE]; using std::cout; void Debug::Init() { #ifdef RENDERFISH_LOG_IS_WINDOWS AllocConsole(); AttachConsole(GetCurrentProcessId()); FILE* dont_care; freopen_s(&dont_care, "CON", "w", stdout); //freopen("CON", "w", stdout); //HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE); hstdout = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(hstdout, &csbi); #endif } void Debug::Log(const char *fmt, ...) { #if RENDERFISH_LOG_IS_WINDOWS SetConsoleTextAttribute(hstdout, 0x0F); #elif RENDERFISH_LOG_IS_APPLE || RENDERFISH_LOG_IS_LINUX // http://stackoverflow.com/questions/9005769/any-way-to-print-in-color-with-nslog# // https://wiki.archlinux.org/index.php/Color_Bash_Prompt#List_of_colors_for_prompt_and_Bash printf("\e[0;37m"); // white #endif std::cout << "[info] "; va_list args; va_start(args, fmt); int n = vsprintf(sprint_buf, fmt, args); va_end(args); std::cout.write(sprint_buf, n); std::cout << std::endl; #if RENDERFISH_LOG_IS_APPLE || RENDERFISH_LOG_IS_LINUX printf("\e[m"); #endif } void Debug::LogWarning(const char *fmt, ...) { #if RENDERFISH_LOG_IS_WINDOWS SetConsoleTextAttribute(hstdout, 0x0E); #elif RENDERFISH_LOG_IS_APPLE || RENDERFISH_LOG_IS_LINUX printf("\e[0;33m"); // yellow #endif std::cout << "[warning] "; va_list args; va_start(args, fmt); int n = vsprintf(sprint_buf, fmt, args); va_end(args); std::cout.write(sprint_buf, n); std::cout << std::endl; #if RENDERFISH_LOG_IS_APPLE || RENDERFISH_LOG_IS_LINUX printf("\e[m"); #endif } void Debug::LogError(const char *fmt, ...) { #if RENDERFISH_LOG_IS_WINDOWS SetConsoleTextAttribute(hstdout, 0x0C); #elif RENDERFISH_LOG_IS_APPLE || RENDERFISH_LOG_IS_LINUX printf("\e[0;31m"); // red #endif std::cout << "[error] "; va_list args; va_start(args, fmt); int n = vsprintf(sprint_buf, fmt, args); va_end(args); std::cout.write(sprint_buf, n); std::cout << std::endl; #if RENDERFISH_LOG_IS_APPLE || RENDERFISH_LOG_IS_LINUX printf("\e[m"); #endif } #undef vsprintf_s
Java
UTF-8
1,361
2.03125
2
[]
no_license
package com.example.administrator.wankuoportal.fragment.pingjia; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.example.administrator.wankuoportal.R; import com.example.administrator.wankuoportal.adapter.PaoTuiPingJia_Adapter; import com.example.administrator.wankuoportal.global.BaseFragment; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/8/16 0016. */ public class EvaluationToWan_fragment extends BaseFragment { private android.widget.ListView baselist; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.base_list, container, false);//关联布局文件 this.baselist = (ListView) rootView.findViewById(R.id.base_list); List<String> title = new ArrayList<>(); title.add("开店赚钱"); title.add("广告投放"); title.add("万哥跑腿"); title.add("城市合作"); title.add("开店赚钱"); PaoTuiPingJia_Adapter j = new PaoTuiPingJia_Adapter(getActivity(),title); baselist.setAdapter(j); return rootView; } }
Markdown
UTF-8
2,491
3.296875
3
[]
no_license
# DataMadnessKickstarter An analysis on the success of Kickstarter Projects (UM Project) This was a short project which is summarized in the following video. The dataset can be obtained from https://www.kaggle.com/kemical/kickstarter-projects?select=ks-projects-201801.csv https://vimeo.com/401928960 Brian Huynen, I6097103 - Tim Smeets, I6071641 Given the dataset is majorly clean, not much preprocessing was required. It was of greatest interest to keep the main_category, deadline, launched, state, usd_pledged_real and usd_goal_real columns to answer our questions. We picked main_category over category to make it easier to visualize our findings – it is a hassle to plot a clear graph over the 159 sub-categories as opposed to the 15 main categories. Furthermore, usd_pledged_real and usd_goal_real are defined as the actual amount of money set as goal and yielded from the campaign in USD, which keeps the analysis consistent (since not all projects use the same valuta for its campaign). To define the duration of the project, we used the datetime library to determine the length in days by converting deadline and launched to a date object and subtracting the launchtime from the deadline. For our analysis, we subdivided the allocated goal budget in four categories: • 0 to 1000 USD • 1000 – 10000 USD • 10000 – 50000 USD • 50000 USD and above Furthermore, we subdivided the duration of projects in three categories: • Below 30 days (~1 month) • Between 30 and 60 days (~1 to 2 months) • Over 60 days (over 2 months) Doing this allowed us to get a more detailed overview of success rates within projects of different caliber. Lastly, we plotted a couple of correlation graphs in regards to project duration, goal allocation and the success of a campaign. The idea behind this is to determine in what way the duration and goal are related to a project being successful. From this can be concluded that the size of the goal budget seems to be more detrimental to a project being successful than its length. This correlation remains the same when checking the correlation between duration and success within each goal category and the correlation between goal and success within each duration category. Conclusion: From our observations it can be concluded that popular categories do not necessarily guarantee a greater chance of success. It is far more important to not set your goals too high and not make your campaign too long.
C++
UTF-8
1,515
2.625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Zlib", "MIT" ]
permissive
#include <cassert> #include "pack.hpp" #include "netstring.hpp" #include "compress.hpp" int main( int argc, char **argv ) { bistring name = bistring( "name", "description" ); bistring data = bistring( "data", "im a descriptor" ); bistrings bi; bi.push_back( name ); bi.push_back( data ); std::cout << bi[0] << std::endl; std::cout << bi[1] << std::endl; std::cout << pack::json( bi ) << std::endl; std::cout << pack::xml( bi ) << std::endl; std::cout << pack::netstring( bi ) << std::endl; std::cout << pack::zip( bi ) << std::endl; #define with(p) \ std::cout << #p "=" << p( bi ).size() << " vs z(" #p ")=" << moon9::z( p( bi ) ).size() << "bytes" << std::endl; with( pack::json ); with( pack::xml ); with( pack::zip ); with( pack::netstring ); #undef with { std::string saved = pack::xml( bi ); bi[0] = bistring(); bi[1] = bistring(); bi = unpack::xml( saved ); assert( bi[0] == name ); assert( bi[1] == data ); } { std::string saved = pack::netstring( bi ); bi[0] = bistring(); bi[1] = bistring(); bi = unpack::netstring( saved ); assert( bi[0] == name ); assert( bi[1] == data ); } { std::string saved = pack::zip( bi ); bi[0] = bistring(); bi[1] = bistring(); bi = unpack::zip( saved ); assert( bi[0] == name ); assert( bi[1] == data ); } return 0; }
Ruby
UTF-8
465
2.734375
3
[]
no_license
class Link < ApplicationRecord validates :url, presence: true, uniqueness: true validates :read_count, presence: true def add_read update(read_count: read_count + 1) end def self.top_ten Link.all.sort_by do |link| link.read_count end.reverse[0..9] end def status top_ten = self.class.top_ten if self == top_ten.first 'top read' elsif self.in?(top_ten) 'hot read' else 'not hot' end end end
Python
UTF-8
731
3.296875
3
[]
no_license
def solution(n): n = str(n) if len(n) == 0: return [0, n] count = 0 while len(n) > 1: q = len(n) // 2 left_num, right_num = n[:q], n[q:] pos_right = 0 while pos_right < len(right_num) and right_num[pos_right] == '0': pos_right += 1 if pos_right == len(right_num): left_num, right_num = left_num + right_num[:pos_right-1], right_num[pos_right-1:] else: left_num, right_num = n[:len(left_num) + pos_right], n[len(left_num) + pos_right:] n = str(int(left_num) + int(right_num)) count += 1 return [count, int(n)] print(solution(74325)) print(solution(1000)) print(solution(10007)) print(solution(9))
JavaScript
UTF-8
1,230
2.6875
3
[]
no_license
const LocalStrategy= require('passport-local').Strategy const User=require('../models/user') const bcrypt= require ('bcrypt') function init(passport){ passport.use(new LocalStrategy({usernameField:'email'},async (email,password,done) => { //to use await its parent function should be asynchronus //Login //check if email exists const user= await User.findOne({email:email}) if(!user){ return done(null,false,{message:'No user with this email'}) } bcrypt.compare(password,user.password).then( match =>{ if(match){ return done(null,user,{message:'Logged in successfully'}) } return done(null,false,{message:'Wrong Username or Password'}) }).catch( err =>{ //in case error during bcrypt return done(null,false,{message:'OOps! something went wrong'}) }) })) passport.serializeUser((user,done)=>{ done(null,user._id) //passport allows us to store any parameter of logged in user..here we r using id of customer }) passport.deserializeUser((id,done)=>{ // User.findOne{_} User.findById(id,(err,user)=>{ done(err, user) }) //due to this deserialise function we can use req.user to get logged in user } ) } module.exports=init
JavaScript
UTF-8
322
3.328125
3
[]
no_license
// 给定一个数组。如何实现按顺序请求每一个地址 // ['baidu.com','aliyun.com','aaaaa.com'] function fetchSyn(arr) { async function fn(arr) { const res = []; for (let i = 0; i < arr.length; i++) { await window.fetch(arr[i]); } } fn(arr); } fetchSyn(["baidu.com", "aliyun.com"]);
C
UTF-8
1,045
2.8125
3
[]
no_license
#include <stdio.h> #include "lib.h" char *alfb = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ; char *p ; long int outnum = 0; long int exp = 1; long int index; int istr = 0; long int i_alfb(char c) { if((p=strchr(alfb, c))) { return (long int)(p - alfb); } else { return (long int)NULL ; } } long int bN10(char *strnum, int basen) { index = strlen(strnum) - 1; if(index <= 0) return -1 ; while(index >= 0) { outnum += i_alfb(strnum[index])*exp; index-- ; exp = exp * basen ; } return outnum ; } void b10toM(char *str, long int inpnum, int basem) { int istr = 0; if(inpnum == 0) { str[0]='0'; istr=1; } while(inpnum) { str[istr++]=alfb[inpnum%basem]; inpnum /= basem; } str[istr]=0 ; if(istr>0) { char t ; long int i=0 ; istr-- ; while(i <= istr/2) { t = str[istr-i] ; str[istr-i] = str[i]; str[i++] = t; } } }
C#
UTF-8
803
2.515625
3
[]
no_license
using System; using System.Globalization; using System.Windows.Data; namespace FMA.View.Helpers { //public class SubstractionConverter : IValueConverter //{ // public object Convert(object value, Type targetType, object parameter, CultureInfo culture) // { // try // { // var intValue = int.Parse(value.ToString()); // var minus = int.Parse(parameter.ToString()); // return intValue - minus; // } // catch (Exception e) // { // return value; // } // } // public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) // { // throw new NotImplementedException(); // } //} }
C++
ISO-8859-7
6,120
2.59375
3
[]
no_license
/* * cereal2.h * * Created on: 31 2017 * Author: IsM */ #ifndef SERIALIZATION_CEREAL2_H_ #define SERIALIZATION_CEREAL2_H_ #include <DALFramework/serialization/helpers2.h> #include <DALFramework/serialization/traits2.h> #include <utility> #include <cstdint> #include <WString.h> namespace cereal2 { //! The base input archive class /*! This is the base input archive for all input archives. If you create a custom archive class, it should derive from this, passing itself as a template parameter for the ArchiveType. The base class provides all of the functionality necessary to properly forward data to the correct serialization functions. Individual archives should use a combination of prologue and epilogue functions together with specializations of serialize, save, and load to alter the functionality of their serialization. @tparam ArchiveType The archive type that derives from InputArchive @tparam Flags Flags to control advanced functionality. See the Flags enum for more information. @ingroup Internal */ template<class ArchiveType, std::uint32_t Flags = 0> class InputArchive: public detail2::InputArchiveBase { private: ArchiveType * const self; public: //! Construct the output archive /*! @param derived A pointer to the derived ArchiveType (pass this from the derived archive) */ InputArchive(ArchiveType * const derived) : self(derived) // itsBaseClassSet(), // itsSharedPointerMap(), // itsPolymorphicTypeMap(), // itsVersionedTypes() { } //! Serializes all passed in data /*! This is the primary interface for serializing data with an archive */ template<class ... Types> inline ArchiveType & operator()(Types && ... args) { process(std::forward<Types>( args )...); return *self; } private: //! Serializes data after calling prologue, then calls epilogue template<class T> inline void process(T && head) { prologue(*self, head); self->processImpl(head); epilogue(*self, head); } //! Unwinds to process all data template <class T, class ... Other> inline void process( T && head, Other && ... tail ) { process( std::forward<T>( head ) ); process( std::forward<Other>( tail )... ); } template<class Archive, class T> inline static auto member_load(Archive & ar, T & t) -> decltype(t.load(ar)) { return t.load(ar); } //! process if has load method template<class T, typename std::enable_if< detail2::has_load_method<T, void(const detail2::InputArchiveBase&)>::value , detail2::sfinae>::type = {}> inline ArchiveType & processImpl(T & t) { member_load(*self, t); return *self; } //! process for things which don't have member load template<typename T, typename std::enable_if< !detail2::has_load_method<T, void(const detail2::InputArchiveBase&)>::value , detail2::sfinae>::type = {}> inline ArchiveType & processImpl(T & t) { load(*self, t); return *self; } }; template<class ArchiveType, std::uint32_t Flags = 0> class OutputArchive: public detail2::OutputArchiveBase { public: //! Construct the output archive /*! @param derived A pointer to the derived ArchiveType (pass this from the derived archive) */ OutputArchive(ArchiveType * const derived) :self(derived), itsCurrentPointerId(1), itsCurrentPolymorphicTypeId(1) { } //! Serializes all passed in data /*! This is the primary interface for serializing data with an archive */ template<class ... Types> inline ArchiveType & operator()(Types && ... args) { self->process(std::forward<Types>( args )...); return *self; } private: ArchiveType * const self; //! The id to be given to the next pointer std::uint32_t itsCurrentPointerId; //! The id to be given to the next polymorphic type name std::uint32_t itsCurrentPolymorphicTypeId; //! Serializes data after calling prologue, then calls epilogue template<class T> inline void process(T && head) { prologue(*self, head); self->processImpl(head); epilogue(*self, head); } //! Unwinds to process all data template <class T, class ... Other> inline void process( T && head, Other && ... tail ) { self->process( std::forward<T>( head ) ); self->process( std::forward<Other>( tail )... ); } enum class enabler{}; template<class Cond, class T = enabler> using EnableIf = typename std::enable_if<Cond::value, T>::type; //! NameValuePair handle /* template <typename T, typename std::enable_if< std::is_base_of<detail2::NameValuePairCore, T>::value , detail2::sfinae>::type = detail2::sfinae2> inline ArchiveType & processImpl(T const & t) { // save(*self, t); cout << "processImpl2 for NameValuePair<T> " << endl; return *self; }*/ template<class Archive, class T> inline static auto member_save(Archive & ar, T const & t) -> decltype(t.save(ar)) { //cout << "Inside member_save " << endl; return t.save(ar); } //! process if has save method template<class T, typename std::enable_if< detail2::has_save_method<T, void(const detail2::OutputArchiveBase&)>::value , detail2::sfinae>::type = {}> inline ArchiveType & processImpl(T const & t) { //cout << "processImpl for classes with save method " << endl; member_save(*self, t); return *self; } //! process for things which don't have member save template<typename T, typename std::enable_if< !detail2::has_save_method<T, void(const detail2::OutputArchiveBase&)>::value , detail2::sfinae>::type = {}> inline ArchiveType & processImpl(T const & t) { //cout << "process for things which don't have member save " << endl; save(*self, t); return *self; } }; template<class T> inline NameValuePair<T> make_nvp(String name, T&& value){ return {name, std::forward<T>(value)}; } #define CEREAL2_NVP(T) ::cereal2::make_nvp(#T, T) } /* namespace cereal2 */ #endif /* SERIALIZATION_CEREAL2_H_ */
Markdown
UTF-8
1,349
2.796875
3
[ "Apache-2.0" ]
permissive
# xml_parse Parsing XML, and retrieving specific text or attribute. * **Baseline**: Simple XML with just one tag, no attributes. * **Attributes**: 1 tag with 1000 attributes. * **Serial**: 1000 tags, opening and closing, opening and closing. No nesting. * **Nested**: 1000 nested entries, each inside of the other. | | baseline | serial | attribute | nested | | --- | --- | --- | --- | --- | | **[quick_xml](https://crates.io/crates/quick_xml)** | 0.331 | *95.667* | *36.364* | *54.551* | | **[dummy_xml](https://crates.io/crates/dummy_xml)** | *0.257* | 144.144 | 200.536 | 145.042 | | **[roxmltree](https://crates.io/crates/roxmltree)** | 0.761 | 281.645 | 2667.008 | 3906.095 | | **[xmltree](https://crates.io/crates/xmltree)** | 3.895 | 2567.188 | 4547.001 | - | | **[treexml](https://crates.io/crates/treexml)** | 4.215 | 2541.496 | 4419.271 | 18896.049 | Speed units are in microseconds per iteration. Less is better. ## Crate versions quick-xml = "0.13.1" # High performance xml reader and writer dummy_xml = "0.1.6" # Fast Non-validating XML DOM parser. roxmltree = "0.4.1" # Represent an XML as a read-only tree. xmltree = "0.8.0" # Parse an XML file into a simple tree-like structure treexml = "0.7.0" # An XML tree library for Rust Compiled on: `rustc 1.31.1 (b6c32da9b 2018-12-18)`
Python
UTF-8
1,329
2.625
3
[]
no_license
from udacity import atoms from udacity.utils.object_dict import ObjectDict from udacity.utils.renderer import ClassRenderer class Course(ClassRenderer): def __init__(self, seq=None, **kwargs) -> None: super().__init__(seq, **kwargs) self['lessons'] = [self.Lesson(self, lesson) for lesson in self['lessons']] def iter_lessons(self): for lesson in self.lessons: yield lesson def iter_concepts(self): for lesson in self.iter_lessons(): for concept in lesson.concepts: yield concept def iter_atoms(self): for concept in self.iter_concepts(): for atom in concept.atoms: yield atom class Lesson(ClassRenderer): def __init__(self, course, seq=None, **kwargs): super().__init__(seq, **kwargs) self.course = course self['concepts'] = [self.Concept(self, concept) for concept in self['concepts']] class Concept(ClassRenderer): def __init__(self, lesson, seq=None, **kwargs): super().__init__(seq, **kwargs) self.lesson = lesson create_atom = lambda atom: getattr(atoms, atom['semantic_type'])(atom, concept=self) self['atoms'] = [create_atom(atom) for atom in self['atoms']]
Python
ISO-8859-1
713
2.90625
3
[]
no_license
''' Created on 4 févr. 2017 @author: mathi ''' class PacketUpdate(): ''' classdocs ''' #Initialisation de la class avec les variables par dfault def __init__(self): self.id = -1 self.main = None #Fonction utiliser pour ENVOYER : Permet d'initier les variables def init(self, main): self.main = main return self #Fonction utiliser pour ENVOYER : Permet de transformer les informations de la class en une chaine de caractre : #Exemple : #Id du joueur = 23 #Protocol de la class = 0 # -> 0#23 def write(self): return (self.main.protocolmap.getProtocol(self)+"#"+str(self.main.id))
PHP
UTF-8
7,496
2.5625
3
[]
no_license
<?php class QuestionnaireController extends Controller { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout='//layouts/column2'; /** * @return array action filters */ public function filters() { return array( 'accessControl', // perform access control for CRUD operations 'postOnly + delete', // we only allow deletion via POST request ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $this->render('view',array( 'model'=>$this->loadModel($id), )); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new Event1311QuestionnaireConstruction; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Event1311QuestionnaireConstruction'])) { $model->attributes=$_POST['Event1311QuestionnaireConstruction']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('create',array( 'model'=>$model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Event1311QuestionnaireConstruction'])) { $model->attributes=$_POST['Event1311QuestionnaireConstruction']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('update',array( 'model'=>$model, )); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); } /** * Lists all models. */ public function actionIndex() { $this->redirect(array('admin')); $dataProvider=new CActiveDataProvider('Event1311QuestionnaireConstruction'); $this->render('index',array( 'dataProvider'=>$dataProvider, )); } /** * Manages all models. */ public function actionAdmin() { $model=new Event1311QuestionnaireConstruction('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Event1311QuestionnaireConstruction'])) $model->attributes=$_GET['Event1311QuestionnaireConstruction']; $this->render('admin',array( 'model'=>$model, )); } public function actionResult($id) { $model = $this->loadModel($id); $qname = $model->name; $qid = $model->id; $dataProvider=new CActiveDataProvider('Event1311Questionnaire', array( 'criteria'=>array( 'condition' => 'qid=:QID', 'params' => array( ':QID' => $id, ), ), 'pagination'=>array( 'pageSize'=>10, ), )); $fields = $this->getFields($id); $this->render('result',array( 'dataProvider'=>$dataProvider, 'model'=>$model, 'fields' => $fields, 'name'=>$qname, 'id'=>$qid, )); } public function actionExport($id) { $model = $this->loadModel($id); $res = Event1311Questionnaire::model()->findAll(array( 'condition' => 'qid=:QID', 'params' => array( ':QID' => $id, ), )); $exportField = array(); $content = array(); $fields = $this->getFields($id); foreach($res as $data) { $line = array(); foreach($fields as $n => $entry) { $field = 'field'.($n+1); if( !in_array($entry['label'], $exportField) ) $exportField[] = $entry['label']; switch($entry['type']) { case '单项选择题': case 'radio': foreach($entry['options'] as $option) { if( $data->$field == $option['value'] ) { $line[] = $this->fmtCvsValue($option['label']); break; } } break; case '多项选择题': case 'checkbox': $v = explode('|', $data->$field); $label = array(); foreach($entry['options'] as $option) { if( in_array($option['value'],$v) ) { $label[] = str_replace('|','',$option['label']); } } $line[] = $this->fmtCvsValue(implode('|',$label)); break; case '单行输入': case 'text': case '多行输入': case 'textarea': $line[] = $this->fmtCvsValue($data->$field); break; } } $content[] = implode(',', $line); } header("Content-type:text/csv; charset=UTF-8"); header("Content-Disposition:attachment;filename=".trim($model->name).".csv"); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); //header("Content-type:application/vnd.ms-excel; charset=UTF-8"); //header("Content-Disposition:filename=".trim($model->name).".csv"); echo "\xEF\xBB\xBF".implode(',', $exportField)."\n"; echo implode("\n", $content); } public function actionSample() { $tpl = str_replace("\\","/",dirname(Yii::app()->basePath)).'/tpl/questionnaire/demo.tpl'; echo '<html><body><pre>'; echo file_get_contents($tpl); echo '</pre></body></html>'; } public function fmtCvsValue($val) { $from = array("\r","\n","\""); $to = array('','',"\"\""); if( strstr($val, ',') || strstr($val, '"') ) return "\"".str_replace($from,$to,$val)."\""; return str_replace($from,$to,$val); } /* public function actionResult($id) { $model = $this->loadModel($id); $qname = $model->name; $qid = $model->id; $model=new Event1311Questionnaire('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Event1311Questionnaire'])) $model->attributes=$_GET['Event1311Questionnaire']; $fields = $this->getFields($id); $column = array(); for($i=1;$i<=count($fields);$i++) $column[] = 'field'.$i; $column[] = array( 'class'=>'CButtonColumn', ); $this->render('result',array( 'model'=>$model, 'column'=>$column, 'name'=>$qname, 'id'=>$qid, )); } */ public function getFields($id) { $model = $this->loadModel($id); $fields= json_decode($model->construction, true); return $fields['question']; } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer $id the ID of the model to be loaded * @return Event1311QuestionnaireConstruction the loaded model * @throws CHttpException */ public function loadModel($id) { $model=Event1311QuestionnaireConstruction::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param Event1311QuestionnaireConstruction $model the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='event1311-questionnaire-construction-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } }
C++
UTF-8
722
3.671875
4
[ "MIT" ]
permissive
// This program calculates hourly wages, including overtime. #include <iostream> using namespace std; int main() { double regularWages, basePayRate = 18.25, regularHours = 40.0, overtimeWages, overtimePayRate = 27.78, overtimeHours = 10, totalWages; // Calculate the regular wages. regularWages = basePayRate * regularHours; // Calculate the overtime wages. overtimeWages = overtimePayRate * overtimeHours; // Calculate the total wages. totalWages = regularWages + overtimeWages; // Display the total wages. cout << "Wages for this week are $" << totalWages << endl; return 0; }
JavaScript
UTF-8
42,280
2.578125
3
[]
no_license
'use strict'; /* basic strategy for using SVG: In SVG you can draw on an arbitrarily large plane and have a 'viewbox' that shows a sub-area of that. Because of this, for a piano roll, you can 'draw' a piano-roll at an arbitrary size and move around the viewbox rather than 'redrawing' the piano roll when you want to zoom/move. What's TBD is to see how annoying it might be to program selecting/dragging/highlighting/resizing with this approach. In general, aiming for Ableton piano-roll feature parity wrt mouse interaction (assuming keyboard shortcuts are trivial to implement if you can get the mouse stuff right) order of library features to test (for each, make sure they're sensible under viewbox zoom too): NOTE - this is only a test of INTERACTIONS - the look is ugly and the code is organized for quick hacking. How note-state <-> note-svg-elements is handled is still TBD. - X - dragging behavior - X - dragging and snap to grid - NOTE - clicking on a note is interpeted as a 'drag' and will automatically quantize it (see bugs below) - X - multiselection + dragging via mouse - X - multiselection + dragging + snap to grid - X - multiselection and ableton style note length resizing - X - multiselected resizing + snap to grid - done, but design choices necessary - X figure out good UI for viewbox resizing/position control and scroll (panzoom plugin if necessary?) - done, but more polished design choices necessary - could implement 2 finger scroll - https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Multi-touch_interaction - X implement double-click to add note interaction (should be straightforwards, svg-wise) - X implement delete - X implement undo/redo - get to ableton parity with regards to - X selected notes and then moving/resizing a non-sected note - POSTPONED - handle drag quantization to be ableton like - handle drag quantizing so that clicked note snaps to grid when moved large distances - need to handle out-of-bounds dragging - handling overlaps on resizing, drag and doubleclick-to-add-note - resizing quantization should be triggered once the end nears a note-section border. currently it quantizes once the deviation distance is near the quanization length - in general - if selected/new notes intersect with start start of 'other' note, the 'other' note is deleted, and if they intersect with the end of 'other' notes, the 'other' notes are truncated. - The exception is if a selected note is resized into another selected note, in which case the resizing is truncated at the start of the next selected note - X implement showing note names on notes - implement cursor and cut/copy/paste - implement moving highlighted notes by arrow click - figure out floating note names on side and time-values on top - figure out cursor animation and viewbox movement for a playing piano roll - decide how to do ableton 'draw mode' style interaction (shouldn't require any new funky SVG behavior, but will likely be tricky wrt UI-state management) comment tags cleanup - stuff that works but needs cleaning inProgress - stuff that's not totally built yet future - guide notes for longer term extensible implementation ideas postponed - features that are wanted but can be done later */ /* General organization - Look at attachHandlersOnBackground to see how notes are drawn/created. Look at attachHandlersOnElement to see how notes can be moved and modified. Basic strategy for implementing multi-note modifications - - Define the 'target' element (the one the mouse gestures are happening on) and the other 'selected' elements. - Calulate the mouse motion/deviation from the mousedown point on the target element - Use this mouse deviation info to control movement/resizing of all selected elements */ class PianoRoll { constructor(containerElementId, playHandler, noteOnOffHandler){ this.svgRoot; //the svg root element /* a dictionary that, upon the start of a group drag/resize event, stores the * initial positions and lengths of all notes so that the mouse modifications to * one note can be bounced to the rest of the selected notes*/ this.noteModStartReference; //structure tracking both note info and note svg element state this.notes = {}; //used to track note show/hide on resize/drag - map of pitch -> noteInfo of that pitch sorted by start time this.spatialNoteTracker = {} //elements selected by a mouse-region highlight this.selectedElements = new Set(); this.selectedNoteIds = []; //IDs of selected notes saved separtely to speed up multi drag/resize performance this.selectRect; //the variable holding the mouse-region highlight svg rectabgle this.cursorElement; //cursor that corresponds to interaction and editing this.cursorPosition = 0.25; //cursor position is in beats this.cursorWidth = 2.1; this.playCursorElement; //cursor that moves when piano roll is being played //svg elements in the pianoRoll background this.backgroundElements; this.quarterNoteWidth = 120; //in pixels this.noteHeight = 20; //in pixels this.whiteNotes = [0, 2, 4, 5, 7, 9, 11]; this.noteSubDivision = 16; //where to draw lines and snap to grid this.timeSignature = 4/4; //b this.numMeasures = 100; // Every quarter note region of the background will be alternately colored. // In ableton this changes on zoom level - TODO - is this even used? Could ignore this behavior this.sectionColoringDivision = 4; this.NUM_MIDI_NOTES = 128; //snap to grid quantization sizes this.xSnap = 1; //x-variable will change depending on user quantization choice, or be vertLineSpace as calculated below this.ySnap = this.noteHeight; this.backgroundColor1 = '#ddd'; this.backgroundColor2 = '#bbb'; this.noteColor = '#f23'; this.selectedNoteColor = '#2ee' this.thickLineWidth = 1.8; this.thinLineWidth = 1; this.viewportHeight = 720; this.viewportWidth = 1280; this.maxZoom; this.noteCount = 0; // Create an SVGPoint for future math this.refPt; this.shiftKeyDown = false; this.historyList = [[]]; //list of states. upon an edit, the end of historyList is always the current state // How far away from end of array (e.g, how many redos available). // historyListIndex is always the index of the current state in historyList this.historyListIndex = 0; this.pianoRollHeight; this.pianoRollWidth; //variables relating to note-name labels this.pitchStrings = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']; this.textDev = 4; //variables relating to mouse movement state (scroll, zoom, resize, drag, etc) this.mouseScrollActive = false; this.mouseZoomActive = false; this.mouseMoveRootNeedsReset = true; this.mouseMoveRoot = {x: -1, y: -1}; //notes that are modified during drag or resize because they overlap with selected notes this.nonSelectedModifiedNotes = new Set(); this.count = 0; //some debugging variable this.draggingActive = false; this.quantDragActivated = false; this.dragTarget = null; this.resizingActive = false; this.quantResizingActivated = false; this.resizeTarget = null; //used to get around scope/'this' issues - for drag/resize handlers we have access to raw //svg element but need the SVG.js wrapper this.rawSVGElementToWrapper = {}; this.copiedNoteBuffer = []; this.containerElement = document.getElementById(containerElementId); this.containerElement.tabIndex = 0; this.containerElementId = containerElementId; this.temporaryMouseMoveHandler = null; //variable used to manage logic for various mouse-drag gestures this.mousePosition = {x: 0, y: 0}; //current position of mouse in SVG coordinates //callback to play notes when selected/moved/etc. Takes a single pitch argument this.playHandler = playHandler; //handler for separate on/off actions. takes a pitch val and on/off string this.noteOnOffHandler = noteOnOffHandler; this.drawBackgroundAndCursor(); // attach the interaction handlers not related to individual notes this.attachHandlersOnBackground(this.backgroundElements, this.svgRoot); this.addNote(55, 0, 1, false); this.addNote(60, 0, 1, false); //set the view-area so we aren't looking at the whole 127 note 100 measure piano roll this.svgRoot.viewbox(0, 55*this.noteHeight, this.viewportWidth, this.viewportHeight); this.containerElement.addEventListener('keydown', event => this.keydownHandler(event)); this.containerElement.addEventListener('keyup', event => this.keyupHandler(event)); this.containerElement.addEventListener('mousemove', event => { this.mousePosition = this.svgMouseCoord(event); }); } drawBackgroundAndCursor() { this.pianoRollHeight = this.noteHeight * this.NUM_MIDI_NOTES; let pulsesPerMeasure = this.timeSignature * 4; this.pianoRollWidth = this.quarterNoteWidth * pulsesPerMeasure * this.numMeasures; let numVertLines = this.numMeasures * pulsesPerMeasure * (this.noteSubDivision / 4); let vertLineSpace = this.pianoRollWidth / numVertLines; this.xSnap = vertLineSpace; let measureWidth = this.quarterNoteWidth*pulsesPerMeasure; this.svgRoot = SVG(this.containerElementId).attr('id', 'pianoRollSVG').size(this.viewportWidth, this.viewportHeight); this.refPt = this.svgRoot.node.createSVGPoint(); this.maxZoom = this.viewportHeight / this.pianoRollHeight; this.backgroundElements = new Set(); for(let i = 0; i < this.numMeasures; i++){ let color = i % 2 == 0 ? this.backgroundColor1 : this.backgroundColor2; let panel = this.svgRoot.rect(measureWidth, this.pianoRollHeight).move(i*measureWidth, 0).fill(color); this.backgroundElements.add(panel); } for(let i = 1; i < numVertLines; i++){ let xPos = i*vertLineSpace; let strokeWidth = xPos % this.quarterNoteWidth == 0 ? this.thickLineWidth : this.thinLineWidth; let line = this.svgRoot.line(xPos, 0, xPos, this.pianoRollHeight).stroke({width: strokeWidth}); this.backgroundElements.add(line); } for(let i = 1; i < this.NUM_MIDI_NOTES; i++){ let line = this.svgRoot.line(0, i*this.noteHeight, this.pianoRollWidth, i*this.noteHeight).stroke({width: this.thinLineWidth}); this.backgroundElements.add(line); } this.cursorElement = this.svgRoot.rect(this.cursorWidth, this.pianoRollHeight).move(this.cursorPosition * this.quarterNoteWidth, 0).fill(this.noteColor); this.playCursorElement = this.svgRoot.rect(this.cursorWidth, this.pianoRollHeight).move(this.cursorPosition * this.quarterNoteWidth, 0).fill('#2d2').opacity(0); this.cursorElement.animate(1500, '<>').attr({fill: '#fff'}).loop(Infinity, true); } //duration is number of quarter notes, pitch is 0-indexed MIDI addNote(pitch, position, duration, avoidHistoryManipulation){ let rect = this.svgRoot.rect(duration*this.quarterNoteWidth, this.noteHeight).move(position*this.quarterNoteWidth, (127-pitch)*this.noteHeight).fill(this.noteColor); this.rawSVGElementToWrapper[rect.node.id] = rect; rect.noteId = this.noteCount; rect.selectize({rotationPoint: false, points:['r', 'l']}).resize(); let text = this.svgRoot.text(this.svgYToPitchString(rect.y())) .font({size: 14}) .move(position*this.quarterNoteWidth + this.textDev, (127-pitch)*this.noteHeight) .style('pointer-events', 'none'); this.attachHandlersOnElement(rect, this.svgRoot); this.notes[this.noteCount] = { elem: rect, info: {pitch, position, duration}, label: text } this.noteCount++; if(!avoidHistoryManipulation){ this.snapshotNoteState(); } this.playHandler(pitch); return rect.noteId; } deleteElement(elem){ elem.selectize(false); elem.remove(); this.notes[elem.noteId].label.remove(); } deleteNotes(elements){ //for selected notes - delete svg elements, remove entries from 'notes' objects elements.forEach((elem)=>{ this.deleteElement(elem); delete this.notes[elem.noteId]; }); this.snapshotNoteState(); } //update underlying note info from SVG element change updateNoteInfo(note, calledFromBatchUpdate){ if(note.elem.visible()) { let pitch = this.svgYtoPitch(note.elem.y()); let position = this.svgXtoPosition(note.elem.x()); let duration = note.elem.width()/this.quarterNoteWidth; note.info = {pitch, position, duration}; } else { this.deleteElement(note.elem); delete this.notes[note.elem.noteId]; } if(!calledFromBatchUpdate) this.snapshotNoteState(); } //a separate function so that batch note changes are saved in the undo history as a single event updateNoteInfoMultiple(notes){ notes.forEach(note => this.updateNoteInfo(note, true)); this.snapshotNoteState(); } //update note SVG element from underlying info change updateNoteElement(note){ note.elem.show(); note.elem.x(note.info.position * this.quarterNoteWidth); note.elem.y((127-note.info.pitch)*this.noteHeight); note.elem.width(note.info.duration*this.quarterNoteWidth); note.label.show(); note.label.x(note.info.position * this.quarterNoteWidth + this.textDev); note.label.y((127-note.info.pitch)*this.noteHeight); note.label.text(this.svgYToPitchString(note.label.y())); } // Get point in global SVG space from mousemove event svgMouseCoord(evt){ this.refPt.x = evt.clientX; this.refPt.y = evt.clientY; return this.refPt.matrixTransform(this.svgRoot.node.getScreenCTM().inverse()); } svgYtoPitch(yVal) {return 127 - yVal/this.noteHeight;} svgXtoPosition(xVal) {return xVal/this.quarterNoteWidth} svgXYtoPitchPos(xVal, yVal){ return {pitch: 127 - yVal/this.noteHeight, position: xVal/this.quarterNoteWidth}; } svgXYtoPitchPosQuant(xVal, yVal) { let notesPerQuarterNote = this.noteSubDivision/4; let rawPosition = xVal / this.quarterNoteWidth; return {pitch: 127 - Math.floor(yVal/this.noteHeight), position: Math.floor(rawPosition * notesPerQuarterNote)/notesPerQuarterNote}; } // need to calculate mouse delta from screen coordinates rather than SVG coordinates because // the SVG view moves after every frame, thus changing the read mouse coordintates and creating // wild feedback. root is the mouse position 'snapshot' against which the delta is measured getMouseDelta(event, root){ return {x: event.clientX - root.mouseX, y: event.clientY - root.mouseY}; } //take a snapshot of the mouse position and viewbox size/position resetMouseMoveRoot(event){ let vb = this.svgRoot.viewbox(); let svgXY = this.svgMouseCoord(event); this.mouseMoveRoot = { mouseX: event.clientX, mouseY: event.clientY, svgX: svgXY.x, svgY: svgXY.y, vbX: vb.x, vbY: vb.y, vbWidth: vb.width, vbHeight: vb.height, zoom: vb.zoom }; this.mouseMoveRootNeedsReset = false; } mouseScrollHandler(event){ if(this.mouseMoveRootNeedsReset) this.resetMouseMoveRoot(event); if(this.mouseScrollActive){ let mouseDetla = this.getMouseDelta(event, this.mouseMoveRoot); let boundVal = (n, l, h) => Math.min(h, Math.max(l, n)); //inverted scrolling let scrollFactor = 1/this.mouseMoveRoot.zoom; let newVBPos = { x: boundVal(this.mouseMoveRoot.vbX - mouseDetla.x * scrollFactor, 0, this.pianoRollWidth - this.mouseMoveRoot.vbWidth), y: boundVal(this.mouseMoveRoot.vbY - mouseDetla.y * scrollFactor, 0, this.pianoRollHeight - this.mouseMoveRoot.vbHeight) }; this.svgRoot.viewbox(newVBPos.x, newVBPos.y, this.mouseMoveRoot.vbWidth, this.mouseMoveRoot.vbHeight); } } mouseZoomHandler(event){ if(this.mouseMoveRootNeedsReset) this.resetMouseMoveRoot(event); if(this.mouseZoomActive){ let mouseDetla = this.getMouseDelta(event, this.mouseMoveRoot); let boundVal = (n, l, h) => Math.min(h, Math.max(l, n)); let zoomChange = (4**(mouseDetla.y/this.mouseMoveRoot.zoom / this.mouseMoveRoot.vbHeight)); let zoomFactor = this.mouseMoveRoot.zoom * zoomChange; if(zoomFactor < this.maxZoom) return; let svgMouseVBOffsetX = this.mouseMoveRoot.svgX - this.mouseMoveRoot.vbX; let svgMouseVBOffsetY = this.mouseMoveRoot.svgY - this.mouseMoveRoot.vbY; let newWidth = this.mouseMoveRoot.vbWidth/zoomChange; let newHeight = this.mouseMoveRoot.vbHeight/zoomChange; let newVBPos = { x: boundVal(this.mouseMoveRoot.svgX - svgMouseVBOffsetX/zoomChange, 0, this.pianoRollWidth - newWidth), y: boundVal(this.mouseMoveRoot.svgY - svgMouseVBOffsetY/zoomChange, 0, this.pianoRollHeight - newHeight) }; this.svgRoot.viewbox(newVBPos.x, newVBPos.y, newWidth, newHeight); } } keydownHandler(event){ if(event.key == 'Shift') this.shiftKeyDown = true; if(event.ctrlKey && !event.altKey){ this.mouseMoveRootNeedsReset = true; this.mouseScrollActive = true; this.temporaryMouseMoveHandler = ev => this.mouseScrollHandler(ev); this.containerElement.addEventListener('mousemove', this.temporaryMouseMoveHandler); } if(event.altKey && !event.ctrlKey){ this.mouseMoveRootNeedsReset = true; this.mouseZoomActive = true; this.temporaryMouseMoveHandler = ev => this.mouseZoomHandler(ev); this.containerElement.addEventListener('mousemove', this.temporaryMouseMoveHandler); } if(event.key == 'Backspace'){ this.deleteNotes(this.selectedElements); } if(event.key === 'z' && event.metaKey){ if(this.shiftKeyDown) this.executeRedo(); else this.executeUndo(); } if(event.key === 'c' && event.metaKey){ if(this.selectedElements.size > 0) this.copyNotes(); } if(event.key === 'v' && event.metaKey){ if(this.copiedNoteBuffer.length > 0) this.pasteNotes(); } if(event.key === 'ArrowUp'){ if(this.selectedElements.size > 0) this.shiftNotesPitch(1); event.preventDefault(); } if(event.key === 'ArrowDown'){ if(this.selectedElements.size > 0) this.shiftNotesPitch(-1); event.preventDefault(); } if(event.key === 'ArrowLeft'){ if(this.selectedElements.size > 0) this.shiftNotesTime(-0.25); event.preventDefault(); } if(event.key === 'ArrowRight'){ if(this.selectedElements.size > 0) this.shiftNotesTime(0.25); event.preventDefault(); } if(event.key === ' '){ if(pianoRollIsPlaying) { stopPianoRoll(this); } else { playPianoRoll(this); } event.preventDefault(); } if(['Digit1', 'Digit2', 'Digit3', 'Digit4'].includes(event.code)){//have 1, 2, 3, 4 be different lengths let noteInfo = this.svgXYtoPitchPosQuant(this.mousePosition.x, this.mousePosition.y); let keyNum = parseFloat(event.code[5]); let dur = 2**(keyNum-1) * (this.shiftKeyDown ? 2 : 1) * 0.25; this.addNote(noteInfo.pitch, noteInfo.position, dur); } if(event.key == 'q'){ this.getNotesAtPosition(this.cursorPosition+0.01).map(n => this.playHandler(n.info.pitch)); } if(event.key == 'w'){ if(!this.wIsDown){ this.wIsDown = true; this.getNotesAtPosition(this.cursorPosition+0.01).map(n => this.noteOnOffHandler(n.info.pitch, 'on')); } } event.stopPropagation(); } keyupHandler(event){ if(event.key == 'Shift') this.shiftKeyDown = false; if(!event.ctrlKey && this.mouseScrollActive) { this.mouseScrollActive = false; this.containerElement.removeEventListener('mousemove', this.temporaryMouseMoveHandler); this.temporaryMouseMoveHandler = null; } if(!event.altKey && this.mouseZoomActive) { this.mouseZoomActive = false; this.containerElement.removeEventListener('mousemove', this.temporaryMouseMoveHandler); this.temporaryMouseMoveHandler = null; } if(event.key == 'w'){ this.wIsDown = false; //replace with generic interactionPlay() handler this.getNotesAtPosition(this.cursorPosition+0.01).map(n => this.noteOnOffHandler(n.info.pitch, 'off')); } } copyNotes(){ this.selectedNoteIds = Array.from(this.selectedElements).map(elem => elem.noteId); let selectedNoteInfos = this.selectedNoteIds.map(id => this.notes[id].info); let minNoteStart = Math.min(...selectedNoteInfos.map(info => info.position)); this.copiedNoteBuffer = selectedNoteInfos.map(info => { let newInfo = Object.assign({}, info); newInfo.position -= minNoteStart return newInfo; }); } pasteNotes(){ this.initializeNoteModificationAction(); //marking the newly pasted notes as 'selected' eases overlap handling this.selectedNoteIds = this.copiedNoteBuffer.map(info => this.addNote(info.pitch, this.cursorPosition+info.position, info.duration, true)); this.selectedElements = new Set(this.selectedNoteIds.map(id => this.notes[id].elem)); this.executeOverlapVisibleChanges(); this.updateNoteStateOnModificationCompletion(); //deselect all notes to clean up Object.keys(this.notes).forEach((id)=>this.deselectNote(this.notes[id].elem)); } shiftNotesPitch(shiftAmount){ this.initializeNoteModificationAction(); this.selectedNoteIds.forEach(id => { let note = this.notes[id]; note.info.pitch += shiftAmount; this.playHandler(note.info.pitch); this.updateNoteElement(note); }); this.executeOverlapVisibleChanges(); this.updateNoteStateOnModificationCompletion(); // this.refreshNoteModStartReference(this.selectedNoteIds); // this.snapshotNoteState(); } shiftNotesTime(shiftAmount){ this.initializeNoteModificationAction(); this.selectedNoteIds.forEach(id => { let note = this.notes[id]; note.info.position += shiftAmount; this.updateNoteElement(note); }); this.executeOverlapVisibleChanges(); this.updateNoteStateOnModificationCompletion(); // this.refreshNoteModStartReference(this.selectedNoteIds);// // this.snapshotNoteState(); } snapshotNoteState(){ console.log('snapshot', this.historyList.length, this.historyListIndex); let noteState = Object.values(this.notes).map(note => Object.assign({}, note.info)); if(this.historyListIndex == this.historyList.length-1){ this.historyList.push(noteState); } else { this.historyList = this.historyList.splice(0, this.historyListIndex+1); this.historyList.push(noteState); } this.historyListIndex++; } executeUndo() { if(this.historyListIndex == 0) return; //always start with an 'no-notes' state this.historyListIndex--; this.restoreNoteState(this.historyListIndex); } executeRedo() { if(this.historyListIndex == this.historyList.length-1) return; this.historyListIndex++; this.restoreNoteState(this.historyListIndex); } restoreNoteState(histIndex){ Object.values(this.notes).forEach(note => this.deleteElement(note.elem)); this.notes = {}; let noteState = this.historyList[histIndex]; noteState.forEach((noteInfo)=>{ this.addNote(noteInfo.pitch, noteInfo.position, noteInfo.duration, true); }); } midiPitchToPitchString(pitch){ return this.pitchStrings[pitch%12] + (Math.floor(pitch/12)-2) } svgYToPitchString(yVal){ let pitch = this.svgYtoPitch(yVal); return this.midiPitchToPitchString(pitch); } //function that snapes note svg elements into place snapPositionToGrid(elem, xSize, ySize){ elem.x(Math.round(elem.x()/xSize) * xSize); elem.y(Math.round(elem.y()/ySize) * ySize); //because we're using lines instead of rectangles let label = this.notes[elem.noteId].label; label.x(Math.round(elem.x()/xSize) * xSize + this.textDev); label.y(Math.round(elem.y()/ySize) * ySize); //because we're using lines instead of rectangles label.text(this.svgYToPitchString(label.y())); } // Resets the 'start' positions/sizes of notes for multi-select transformations to current position/sizes refreshNoteModStartReference(noteIds){ this.noteModStartReference = {}; noteIds.forEach((id)=>{ this.noteModStartReference[id] = { x: this.notes[id].elem.x(), y: this.notes[id].elem.y(), width: this.notes[id].elem.width(), height: this.notes[id].elem.height() }; }); } getNotesAtPosition(pos){ let notesAtPos = Object.values(pianoRoll.notes).filter(n => n.info.position <= pos && pos <= n.info.position+n.info.duration); return notesAtPos; } //used to differentiate between 'clicks' and 'drags' from a user perspective //to stop miniscule changes from being added to undo history checkIfNoteMovedSignificantly(noteElement, thresh){ return Math.abs(noteElement.x() - this.noteModStartReference[noteElement.noteId].x) > thresh || Math.abs(noteElement.y() - this.noteModStartReference[noteElement.noteId].y) > thresh; } //used to differentiate between 'clicks' and 'resize' from a user perspective //to stop miniscule changes from being added to undo history checkIfNoteResizedSignificantly(noteElement, thresh){ return Math.abs(noteElement.width() - this.noteModStartReference[noteElement.noteId].width) > thresh; } initializeNoteModificationAction(element){ this.selectedNoteIds = Array.from(this.selectedElements).map(elem => elem.noteId); this.nonSelectedModifiedNotes.clear(); if(element && !this.selectedNoteIds.includes(element.noteId)) { if(!this.shiftKeyDown) this.clearNoteSelection(); this.selectNote(element); this.selectedNoteIds = [element.noteId]; } this.populateSpatialNoteTracker(); this.refreshNoteModStartReference(this.selectedNoteIds); } updateNoteStateOnModificationCompletion(){ this.refreshNoteModStartReference(this.selectedNoteIds); let changedNotes = this.selectedNoteIds.map(id => this.notes[id]).concat(Array.from(this.nonSelectedModifiedNotes).map(id => this.notes[id])); this.updateNoteInfoMultiple(changedNotes); } endSelect(){ this.selectRect.draw('stop', event); this.selectRect.remove(); this.svgRoot.off('mousemove'); this.selectRect = null; } endDrag(){ this.draggingActive = false; this.quantDragActivated = false; this.svgRoot.off('mousemove'); //used to prevent click events from triggering after drag this.dragTarget.motionOnDrag = this.checkIfNoteMovedSignificantly(this.dragTarget, 3); if(!this.dragTarget.motionOnDrag) return; //refresh the startReference so the next multi-select-transform works right this.updateNoteStateOnModificationCompletion(); this.dragTarget = null; } endResize(){ this.resizingActive= false; this.quantResizingActivated = false; this.svgRoot.off('mousemove'); if(!this.checkIfNoteResizedSignificantly(this.resizeTarget, 3)) return; console.log('resize done'); this.resizeTarget.resize(); this.updateNoteStateOnModificationCompletion(); this.resizeTarget = null; } startDragSelection(){ //clear previous mouse multi-select gesture state this.clearNoteSelection(); //restart new mouse multi-select gesture this.selectRect = this.svgRoot.rect().fill('#008').attr('opacity', 0.25); this.selectRect.draw(event); this.svgRoot.on('mousemove', (event)=>{ //select this.notes which intersect with the selectRect (mouse selection area) Object.keys(this.notes).forEach((noteId)=>{ let noteElem = this.notes[noteId].elem; let intersecting = this.selectRectIntersection(noteElem); if(intersecting) { this.selectNote(noteElem); } else { this.deselectNote(noteElem) } }); }); } // attaches the appropriate handlers to the mouse event allowing to to // start a multi-select gesture (and later draw mode) attachHandlersOnBackground(backgroundElements_, svgParentObj){ // need to listen on window so select gesture ends even if released outside the // bounds of the root svg element or browser window.addEventListener('mouseup', (event)=>{ //end a multi-select drag gesture if(this.selectRect) { this.endSelect(); } if(this.draggingActive){ this.endDrag(); } if(this.resizingActive){ this.endResize(); } }); backgroundElements_.forEach((elem)=>{ elem.on('mousedown', (event)=>{ let quantRound = (val, qVal) => Math.round(val/qVal) * qVal; let mouseXY = this.svgMouseCoord(event); let posSVG = quantRound(mouseXY.x, this.quarterNoteWidth/4); this.cursorElement.x(posSVG-this.cursorWidth/2); this.cursorPosition = posSVG/this.quarterNoteWidth; // console.log('mousedown background', posSym, posSVG, event); this.startDragSelection(); }); elem.on('dblclick', (event)=>{ let svgXY = this.svgMouseCoord(event); let pitchPos = this.svgXYtoPitchPosQuant(svgXY.x, svgXY.y); this.addNote(pitchPos.pitch, pitchPos.position, 4/this.noteSubDivision, false); }); }); } populateSpatialNoteTracker(){ this.spatialNoteTracker = {}; Object.values(this.notes).forEach((note)=>{ if(this.spatialNoteTracker[note.info.pitch]){ this.spatialNoteTracker[note.info.pitch].push(note); } else { this.spatialNoteTracker[note.info.pitch] = []; this.spatialNoteTracker[note.info.pitch].push(note); } }); Object.values(this.spatialNoteTracker).forEach(noteList => noteList.sort((a1, a2) => a1.info.position - a2.info.position)); } executeOverlapVisibleChanges(){ let currentlyModifiedNotes = new Set(); let notesToRestore = new Set(); this.selectedElements.forEach((selectedElem)=>{ let selectedNote = this.notes[selectedElem.noteId]; let samePitch = this.spatialNoteTracker[selectedNote.info.pitch]; if(samePitch) { samePitch.forEach((note)=>{ if(selectedElem.noteId != note.elem.noteId) { if(this.selectedElements.has(note.elem)){ let earlierElem = note.elem.x() < selectedNote.elem.x() ? note : selectedNote; let laterElem = note.elem.x() > selectedNote.elem.x() ? note : selectedNote; //todo - handle case when two selected notes are the same pitch and you do a group resize and one overlaps another } else { //truncating the end of the non-selected note if(note.info.position < selectedNote.info.position && selectedNote.info.position < note.info.position+note.info.duration) { if(this.count++ < 10) console.log(this.nonSelectedModifiedNotes, currentlyModifiedNotes, notesToRestore); currentlyModifiedNotes.add(note.elem.noteId); note.elem.show(); note.label.show(); note.elem.width((selectedNote.info.position - note.info.position)*this.quarterNoteWidth); //deleting the non-selected note } else if(selectedNote.info.position <= note.info.position && note.info.position < selectedNote.info.position+selectedNote.info.duration) { currentlyModifiedNotes.add(note.elem.noteId); note.elem.hide(); note.label.hide(); } } } }); } }); notesToRestore = this.setDifference(this.nonSelectedModifiedNotes, currentlyModifiedNotes); notesToRestore.forEach(id => this.updateNoteElement(this.notes[id])); this.nonSelectedModifiedNotes = currentlyModifiedNotes; } setDifference(setA, setB){ var difference = new Set(setA); for (var elem of setB) { difference.delete(elem); } return difference; } isDragOutOfBounds(){ } isResizeOutOfBounds(){ } // sets event handlers on each note element for position/resize multi-select changes attachHandlersOnElement(noteElement, svgParentObj){ /* Performs the same drag deviation done on the clicked element to * the other selected elements */ noteElement.on('point', (event)=>{ console.log('select', event)}); noteElement.on('mousedown', (event)=>{ if(!this.mouseScrollActive && !this.mouseZoomActive) { this.resetMouseMoveRoot(event); this.dragTarget = this.rawSVGElementToWrapper[event.target.id]; this.initializeNoteModificationAction(this.dragTarget); this.draggingActive = true; svgParentObj.on('mousemove', (event)=>{ let svgXY = this.svgMouseCoord(event); let xMove; let xDevRaw = svgXY.x - this.mouseMoveRoot.svgX; let quantWidth = this.quarterNoteWidth * (4/this.noteSubDivision); let quant = (val, qVal) => Math.floor(val/qVal) * qVal; let quantRound = (val, qVal) => Math.round(val/qVal) * qVal; if(Math.abs(svgXY.x - this.mouseMoveRoot.svgX) < quantWidth * 0.9 && !this.quantDragActivated) { xMove = xDevRaw; } else { xMove = quantRound(xDevRaw, quantWidth); this.quantDragActivated = true; } let yMove = quant(svgXY.y, this.noteHeight) - quant(this.mouseMoveRoot.svgY, this.noteHeight); this.selectedNoteIds.forEach((id)=>{ let noteModStart = this.noteModStartReference[id]; //Todo - make note quantization more like ableton's on drag this.notes[id].elem.x(noteModStart.x + xMove); this.notes[id].elem.y(noteModStart.y + yMove); this.notes[id].label.x(noteModStart.x + xMove + this.textDev); this.notes[id].label.y(noteModStart.y + yMove); this.notes[id].label.text(this.svgYToPitchString(this.notes[id].label.y())); this.updateNoteInfo(this.notes[id], true); }); this.executeOverlapVisibleChanges(); }); } }); noteElement.on('resizestart', (event)=>{ this.resizeTarget = this.rawSVGElementToWrapper[event.target.id]; this.initializeNoteModificationAction(this.resizeTarget); //extracting the base dom-event from the SVG.js event so we can snapshot the current mouse coordinates this.resetMouseMoveRoot(event.detail.event.detail.event); //inProgress - to get reizing to work with inter-select overlap and to stop resizing of //clicked element at the start of another selected element, might need to remove the resize //handlers of all of the selected elements here, calculate the resize using 'mousemove' info //by moving 'resizing' handler logic to 'mousemove', and then on 'mouseup' reattaching 'resize' //handler (at least, for 'resizestart' to piggyback on the gesture detection). this.resizeTarget.resize('stop'); this.resizingActive = true; svgParentObj.on('mousemove', (event)=>{ let svgXY = this.svgMouseCoord(event); let xMove; let xDevRaw = svgXY.x - this.mouseMoveRoot.svgX; let oldX = this.noteModStartReference[this.resizeTarget.noteId].x; let isEndChange = this.resizeTarget.x() === oldX; //i.e, whehter you're moving the 'start' or 'end' of the note this.selectedNoteIds.forEach((id)=>{ let oldNoteVals = this.noteModStartReference[id]; //inProgress - control the resizing/overlap of the selected elements here and you don't //have to worry about them in executeOverlapVisibleChanges() //inProgress - quantize long drags if(isEndChange) { this.notes[id].elem.width(oldNoteVals.width + xDevRaw); } else { this.notes[id].elem.width(oldNoteVals.width - xDevRaw); this.notes[id].elem.x(oldNoteVals.x + xDevRaw); this.notes[id].label.x(oldNoteVals.x + xDevRaw); } this.updateNoteInfo(this.notes[id], true); }); this.executeOverlapVisibleChanges(); }) }); // noteElement.on('click', function(event){ // if(!this.motionOnDrag) { // if(!this.shiftKeyDown) clearNoteSelection(); // console.log('this.shiftKeyDown on click', this.shiftKeyDown); // selectNote(this); // } // }); noteElement.on('dblclick', (event)=>{ this.deleteNotes([this.rawSVGElementToWrapper[event.target.id]]); }) } selectNote(noteElem){ if(!this.selectedElements.has(noteElem)) { this.selectedElements.add(noteElem); noteElem.fill(this.selectedNoteColor); this.playHandler(this.notes[noteElem.noteId].info.pitch) } } deselectNote(noteElem){ if(this.selectedElements.has(noteElem)) { this.selectedElements.delete(noteElem); noteElem.fill(this.noteColor); } } // calculates if a note intersects with the mouse-multiselect rectangle selectRectIntersection(noteElem){ //top-left and bottom right of bounding rect. done this way b/c getBBox doesnt account for line thickness let noteBox = { tl: {x: noteElem.x(), y: noteElem.y() - this.noteHeight/2}, br: {x: noteElem.x() + noteElem.width(), y: noteElem.y() + this.noteHeight/2}, }; let selectRectBox = this.selectRect.node.getBBox(); let selectBox = { tl: {x: selectRectBox.x, y: selectRectBox.y}, br: {x: selectRectBox.x + selectRectBox.width , y: selectRectBox.y + selectRectBox.height} }; return this.boxIntersect(noteBox, selectBox); } //the actual rectangle intersection calculation, separated out for debugging ease boxIntersect(noteBox, selectBox){ let returnVal = true; //if noteBox is full to the left or right of select box if(noteBox.br.x < selectBox.tl.x || noteBox.tl.x > selectBox.br.x) returnVal = false; //if noteBox is fully below or above rect box //comparison operators are wierd because image coordinates used e.g (0,0) at 'upper left' of positive quadrant if(noteBox.tl.y > selectBox.br.y || noteBox.br.y < selectBox.tl.y) returnVal = false; return returnVal; } clearNoteSelection(){ this.selectedElements.forEach(noteElem => this.deselectNote(noteElem)); } }
C
UTF-8
1,098
3.28125
3
[]
no_license
//3. Napisati program koji prikazuje zaglavlje koverte koristeci formatere. //Prva 3 reda treba da sadrze na koga je naslovljena koverta i da budu s u gornjem lijevom uglu koverte. //Datum treba da bude u gornjem desnom uglu koverte a zadnjih nekoliko redova treba da sadrze ko salje kovertu i da budu u donjem desnom uglu koverte. //Svi redovi treba da imaju lijevo poravnanje. (Prikazati obris koverte sa znakovima - i |). Sve informacije unijeti preko tastature. //Restrikcija: Prazna mjesta ne dodavati u printf funkciji, dodati ih kroz formatere #include <stdio.h> int main(){ printf("-----------------------------------------------------\n"); printf("%.s| IPI Akademija %30.sDatum |\n"); printf("%.s|Kulina bana 2 %37.s|\n"); printf("%.s| Tuzla %44.s|\n"); printf("%.s| %50.s|\n"); printf("%.s| %50.s|\n"); printf("%.s| %50.s|\n"); printf("%.s| %50.s|\n"); printf("%.s| %50.s|\n"); printf("%.s| %50.s|\n"); printf("%.s| %50.s|\n"); printf("%.s| %31.s Zvonimir Madarac |\n"); printf("-----------------------------------------------------\n"); return 0; }
Python
UTF-8
578
3.96875
4
[]
no_license
''' Write a program to check whether a given number is an ugly number. https://leetcode.com/problems/ugly-number/ Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. ''' class Solution: def maxDivide(self,a,b): while a%b == 0: a = a // b return a def isUgly(self, num: int) -> bool: if num<=0: return False num = self.maxDivide(num,2) num = self.maxDivide(num,3) num = self.maxDivide(num,5) if num == 1: return True else: return False
JavaScript
UTF-8
8,666
3.8125
4
[]
no_license
function game() { this.player1 = ''; this.player2 = ''; this.players = ''; this.currPlayer = ''; this.board = {'00':'', '01':'', '02':'', '10':'', '11':'', '12':'', '20':'', '21':'', '22':''}; this.turns = 0; this.winningCombos = [ ['00', '01', '02'], ['10', '11', '12'], ['20', '21', '22'], ['00', '10', '20'], ['01', '11', '21'], ['02', '12', '22'], ['00', '11', '22'], ['02', '11', '20'] ]; } /*------GAME LOGIC--------*/ //draw X or O on game board game.prototype.drawXorO = function(value) { if(document.getElementById(value).innerHTML) { document.getElementById(value).innerHTML = this.currPlayer; } else { this.updateBoard(value); document.getElementById(value).innerHTML = this.currPlayer; } this.setColor(value); } //Change player game.prototype.updatePlayer = function() { this.turns++; if(this.currPlayer === this.player1) { this.currPlayer = this.player2; } else { this.currPlayer = this.player1; } } //Update board object after each turn game.prototype.updateBoard = function(value) { this.updatePlayer(); if(!this.board[value]) { //fill space with X or O this.board[value] = this.currPlayer; } } //Check to see if there is a winner game.prototype.checkWinner = function() { var combinations = this.winningCombos; var board = this.board; var player = this.currPlayer; return combinations.some(function(arr){ return arr.every(function(el){ return board[el] === player; }); }); } //Create new elements to display the winner and button to reset the game game.prototype.getResultElements = function(text) { var message = document.getElementById("message"); message.style.visibility = "visible"; var result = document.getElementById("result"); result.style.visibility = "visible"; result.innerHTML = text; var reset = document.getElementById("reset"); reset.style.visibility = "visible"; } //Winner message game.prototype.displayWinner = function() { return this.currPlayer + " wins!"; } //Draw message game.prototype.displayDraw = function() { return "Draw!"; } //Methods called when a space is clicked game.prototype.getTurn = function(value) { this.drawXorO(value); if(this.players === 'one' && this.turns < 9) { this.computerTurn(); } if(this.checkWinner() === true) { this.getResultElements(this.displayWinner()); } if(this.checkDraw() === true) { this.getResultElements(this.displayDraw()); } } //Set symbol color game.prototype.setColor = function(value) { if(document.getElementById(value).innerHTML === 'X') { document.getElementById(value).style.color = "#B10DC9"; } else { document.getElementById(value).style.color = "#39CCCC"; } } //Checks for a possible draw if there is no winner game.prototype.checkDraw = function() { if(this.turns > 8 && this.checkWinner() === false) { return true; } } //Choose number of players for game game.prototype.chooseGame = function(id) { this.players = id; document.getElementById("chooseGame").style.visibility = "hidden"; document.getElementById("choosePlayer").style.visibility = "visible"; } //Choose X or O game.prototype.playerChoice = function(text) { this.player1 = text; if(this.player1 === 'X') { this.player2 = 'O'; } else { this.player1 = 'O'; this.player2 = 'X'; } document.getElementById("choosePlayer").style.visibility = "hidden"; document.getElementById("displayGame").style.visibility = "visible"; } /*------COMPUTER MOVES--------*/ //Computer move game.prototype.computerTurn = function() { if(this.checkBlockOrWin()[0]) { this.setBlock(); } else { this.computerMove(); } } //Filter out filled in rows game.prototype.getOpenMoves = function() { var combinations = this.winningCombos; var board = this.board; return combinations.filter(function(arr){ var fill = arr.every(function(el){ return board[el]; }); if(fill === true) { return false; } return true; }); } //Get opponent symbol game.prototype.getLastPlayer = function() { if(this.currPlayer === this.player1) { return this.player2; } else { return this.player1; } } //check if other player is about to score //if true, block player game.prototype.checkBlockOrWin = function() { var open = this.getOpenMoves(); var board = this.board; var opponent = this.currPlayer; var player = this.getLastPlayer(); var empty; //Find spot needed for block or win return open.filter(function(combo) { var opp = combo.filter(function(el){ if(board[el] === opponent && board[el] !== player) { return el } else if(!board[el]){ empty = el; } }); var play = combo.filter(function(el){ if(board[el] === player && board[el] !== opponent) { return el; } else if(!board[el]) { empty = el; } }); if(opp.length === 2 || play.length === 2) { return empty; } }); } //check if opponent could win. If true, set block; game.prototype.setBlock = function() { var blockArray = this.checkBlockOrWin()[0]; var space; this.updatePlayer(); var board = this.board; var player = this.currPlayer; for(var i = 0; i < blockArray.length; i++) { if(!board[blockArray[i]]) { space = blockArray[i]; } } document.getElementById(space).innerHTML = player; board[space] = player; this.setColor(space); } //Return all unoccupied spaces on the board game.prototype.getEmptySpots = function() { var board = this.board; var empty = []; for(var i in board) { if(!board[i]) { empty.push[i]; } } return empty; } //set move if not blocking game.prototype.computerMove = function() { this.updatePlayer(); var center = '11'; var board = this.board; var openSpots = this.getEmptySpots(); var cornerMoves = this.checkCorner(); if(!board[center]) { board[center] = this.currPlayer; document.getElementById(center).innerHTML = this.currPlayer; this.setColor(center); } else if(cornerMoves[0]) { board[cornerMoves[0]] = this.currPlayer; document.getElementById(cornerMoves[0]).innerHTML = this.currPlayer; this.setColor(cornerMoves[0]); } else if(openSpots[0]){ board[openSpots[0]] = this.currPlayer; document.getElementById(openSpots[0]).innerHTML = this.currPlayer; this.setColor(openSpots[0]); } } //Return open corner spaces game.prototype.checkCorner = function() { var corners = ["00","02","20","22"]; var board = this.board; return corners.filter(function(corner){ if(!board[corner]) { return corner; } }); } /*------RESET GAME PROPERTIES--------*/ //Reset board object game.prototype.resetBoard = function() { return this.board = {'00':'', '01':'', '02':'', '10':'', '11':'', '12':'', '20':'', '21':'', '22':''}; } //Reset turns for the game game.prototype.resetGame = function() { this.turns = 0; this.player1 = ''; this.player2 = ''; this.players = ''; this.currPlayer = ''; } //Reset visible game board game.prototype.clearBoard = function() { var cells = document.getElementsByTagName("td"); for(var i = 0; i < cells.length; i++) { cells[i].innerHTML = ''; } } //Compiles reset functions game.prototype.getReset = function() { this.resetBoard(); this.resetGame(); this.clearBoard(); document.getElementById("chooseGame").style.visibility = "visible"; document.getElementById("displayGame").style.visibility = "hidden"; document.getElementById("reset").style.visibility = "hidden"; document.getElementById("result").style.visibility = "hidden"; document.getElementById("message").style.visibility = "hidden"; } var myGame = new game(); var players = document.getElementsByClassName('game'); for(var i = 0; i < players.length; i++) { players[i].addEventListener("click", function(){ myGame.chooseGame(this.id); }); } var choices = document.getElementsByClassName('choice'); for(var k = 0; k < players.length; k++) { choices[k].addEventListener("click", function() { myGame.playerChoice(this.innerHTML); }); } var cells = document.getElementsByTagName('td'); for(var t = 0; t < cells.length; t++) { cells[t].addEventListener("click", function() { myGame.getTurn(this.id); }); } document.querySelector("body").addEventListener("click", function() { if(event.target.id === "reset") { myGame.getReset(); } });
Ruby
UTF-8
122
2.765625
3
[]
no_license
#!/usr/bin/env ruby File.open('data') do |f| num = 0 f.each_line do |l| num = num + l.to_i end puts num end
Java
UTF-8
3,723
2.515625
3
[]
no_license
package dinhphu.com.Controller; import dinhphu.com.Model.Product; import dinhphu.com.Service.ProductService; import dinhphu.com.Service.ProductServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.List; //@WebServlet(name = "ProductServlet",urlPatterns={"/index.jsp"}) public class ProductServlet extends HttpServlet { private ProductService products=new ProductServiceImpl(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); String url="/views/view.jsp"; String message=""; if (action==null){ action="view"; } switch(action){ case "add": createProduct(request,response); url="/views/thanks.jsp"; message="Them thanh cong"; break; case "edit": editProduct(request,response); url="/views/thanks.jsp"; message="Edit Thanh cong"; break; default: url="/views/view.jsp"; break; } request.setAttribute("message",message); getServletContext().getRequestDispatcher(url).forward(request,response); } private void editProduct(HttpServletRequest request, HttpServletResponse response) { String productName=request.getParameter("productName"); double productPrice=Double.parseDouble(request.getParameter("productPrice")); int productCode=Integer.parseInt(request.getParameter("productCode")); Product newProduct = new Product(productName,productPrice); products.update(productCode,newProduct); } private void createProduct(HttpServletRequest request, HttpServletResponse response) { String productName=request.getParameter("productName"); double productPrice=Double.parseDouble(request.getParameter("productPrice")); Product newProduct = new Product(productName,productPrice); products.insert(newProduct); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Product> productList = products.findAll(); request.setAttribute("products",productList); String action=request.getParameter("action"); String url="/views/view.jsp"; if (action==null){ action="view"; url="/views/view.jsp"; } switch(action){ case "edit": url="/views/edit.jsp"; int productCode=Integer.parseInt(request.getParameter("productCode")); System.out.println(productCode); Product editProduct=products.findProduct(productCode); request.setAttribute("editProduct",editProduct); break; case "delete": int deleteCode=Integer.parseInt(request.getParameter("productCode")); products.delete(deleteCode); url="/views/thanks.jsp"; request.setAttribute("message","Delete completed!"); break; case "create": url= "/views/create.jsp"; break; default: url="/views/view.jsp"; break; } getServletContext().getRequestDispatcher(url).forward(request,response); } }
Java
UTF-8
950
2.34375
2
[ "Apache-2.0" ]
permissive
package com.dream.android.sample.base; import android.os.Bundle; import com.dream.android.sample.di.component.ActivityComponent; import com.dream.android.sample.lib.base.BaseFragment; import com.dream.android.sample.lib.base.HasComponent; /** * Description:base dependency injection manager class * * Copyright: Copyright (c) 2016, All rights reserved. * * @author Dream * @date 16/5/27 */ public abstract class DIFragment extends BaseFragment { protected abstract void injectComponent(ActivityComponent activityComponent); @Override protected void onCreateView(Bundle savedInstanceState) { injectComponent(getComponent(ActivityComponent.class)); } /** * Gets a component for dependency injection by its type. */ @SuppressWarnings("unchecked") protected <C> C getComponent(Class<C> componentType) { return componentType.cast(((HasComponent<C>) getActivity()).getComponent()); } }
Java
UTF-8
916
3.03125
3
[]
no_license
public class Solution { public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { Stack<ArrayList<Integer>> resultStack = new Stack<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); List<TreeNode> pre = new LinkedList<TreeNode>(); List<TreeNode> cur = new LinkedList<TreeNode>(); if (root != null) cur.add(root); while (cur.size() != 0) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for (TreeNode node : cur) { tmp.add(node.val); if (node.left != null) pre.add(node.left); if (node.right != null) pre.add(node.right); } resultStack.push(tmp); cur = pre; pre = new LinkedList<TreeNode>(); } while (resultStack.size() != 0) { result.add(resultStack.pop()); } return result; } }
Markdown
UTF-8
466
3.0625
3
[]
no_license
# TriviaGame My code for a simple My Little Pony Trivia Game. This project was part of a coding bootcamp assignment to further understand the functions in JavaScript. Included in the app.js file is the function setInterval(), which can be used to increment (or in this case decrement) a variable every time a set period of time passes. For example, in this file setInterval(decrement, 1000) decreases a variable every 1000 milliseconds, or every second. Have fun!
Ruby
UTF-8
701
2.578125
3
[]
no_license
# Review objects contain a text review of a company. # # They have to be approved by an user of that company to # appear on their company's profile. # class Review < ActiveRecord::Base belongs_to :author_user, :class_name => 'User' belongs_to :author_company, :class_name => 'Company' belongs_to :company searchable after_create :create_notification # Returns <tt>true</tt>, if the review has been approved by a user. def approved? approved_by_id.full? end # Returns the name of the company of this review. def name company.full?(&:name) end private def create_notification Notification.create_for(company, self) end validates_presence_of :text end
Java
UTF-8
161
1.648438
2
[]
no_license
package ph.txtdis.app; import ph.txtdis.exception.InvalidException; public interface Edited { void save() throws InvalidException; void refresh(); }
C++
UTF-8
1,334
3.359375
3
[]
no_license
/* 백준 1062 가르침 input의 크기가 작기 때문에 완전탐색 사용 후 이중반복문까지 사용. 익힌 알파벳을 알기 위한 visit배열 k개만큼 배웠다면 모든 단어를 검사하여 알 수 있는 단어의 개수를 파악. 최대 개수와 비교 후 최신화. */ #include <iostream> #include <string> #include <vector> #include <algorithm> #include <queue> #include <stack> #include <map> using namespace std; int n,k; vector<string> v; int answer; void dfs(int idx, int num, bool* visit){ if(k==num){ int sanswer=0; for(int i=0; i<n; i++){ bool check=false; for(int j=0; j<v[i].length(); j++){ if(!visit[v[i][j]-'a']){ check=true; break; } } if(!check) sanswer++; } if(answer<sanswer) answer=sanswer; return; } for(int i=idx; i<26; i++){ if(visit[i]) continue; visit[i]=true; dfs(i+1,num+1,visit); visit[i]=false; } return; } int main() { cin >> n >> k; answer=0; if(k<5) { cout << answer; return 0; } for(int i=0; i<n; i++){ string s; cin >> s; if(s.compare("antatica")==0) v.push_back("a"); else v.push_back(s.substr(4,s.length()-8)); } bool visit[26]={false,}; visit[0]=true; visit['t'-'a']=true; visit['n'-'a']=true; visit['i'-'a']=true; visit['c'-'a']=true; dfs(1,5,visit); cout << answer; return 0; }
Java
UTF-8
534
2.9375
3
[]
no_license
package tree.nodes.functionals.logicals.logical_operators; import tree.nodes.Context; /** * Created by itzhak on 24-Mar-18. */ public class OrNode extends LogicalOperatorNode { public OrNode() { super(2); } @Override public Double parse(Context context) { if(this.parseChild(0,context ) == 1.0 || this.parseChild(1,context ) == 1.0){ return 1.0; } else{ return 0.0; } } @Override public String nodeStr() { return "OR"; } }
Java
UTF-8
683
3.703125
4
[]
no_license
package com.cognitran.classes.topic2; public class Method2Example { static int calculate(int a, int b) { int c = a + b; System.out.println("\nargument a: " + a); System.out.println("argument b: " + b); System.out.println("obliczono: " + c); return c; } public static void main(String[] args) { int x = 3; int y = 4; int z = calculate(x, y); System.out.println("Wynik metody: " + z); System.out.println("Wynik metody: " + calculate(12, 35)); calculate(1, 2); calculate(1, calculate(2, 3)); calculate(calculate(1, 2) + calculate(3, 4), calculate(2, 3)); } }
Python
UTF-8
2,387
2.671875
3
[]
no_license
from process import Ca import os, random, re import fnmatch from PIL import Image def naturallysorted(L, reverse=False): # helper from http://peternixon.net/news/2009/07/28/natural-text-sorting-in-python/ """Similar functionality to sorted() except it does a natural text sort which is what humans expect when they see a filename list.""" convert = lambda text: ("", int(text)) if text.isdigit() else (text, 0) alphanum = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(L, key=alphanum, reverse=reverse) def html_out(outdir): strings = [] # find all the image files dirs = [] for root, dirnames, filenames in os.walk(outdir): for name in dirnames: dirs.append(name) dirs = naturallysorted(dirs) for d in dirs: #print "d:",d files = [] for root, dirnames, filenames in os.walk(os.path.join(outdir, d)): for filename in fnmatch.filter(filenames, 'random_*.png'): files.append(filename) files = naturallysorted(files) #print files s = "<h2>Rule %s</h2>\n" % (d) for f in files: s += "<img class='bla' src='rules/%s/%s'>\n" % (d,f) strings.append(s) outstr = """ <html> <head> <style> body{ background-color: #eee; } </style> </head> <body> <h1>Cellular Automata Study</h1> %s </body> </html> """ % "\n".join(strings) outfile = os.path.join(outdir,"..","rules.html") #print outfile fp = open(outfile,'w') fp.write(outstr) fp.close() def foo(rule_nr,outdir,a,rule_study_number,pixel_factor=2): # output dir must exist path = os.path.join(outdir,"%s"%rule_nr) if not os.path.exists(path): os.makedirs(path) ca = Ca() for i in xrange(rule_study_number): # generate random input sequence line = [] while len(line) < a: line.append(random.randint(0, 1)) im = ca.getImage(line,rule_nr) strline = "" for j in line: strline += str(j) #im.save(os.path.join(path,"thumb_%s.png" % (strline)), "PNG") # enlarge im = im.resize((a*pixel_factor,a*pixel_factor), Image.NEAREST) im.save(os.path.join(path,"random_%s.png" % strline), "PNG")
Java
UTF-8
864
2.171875
2
[ "MIT" ]
permissive
package xcode.springcloud.dispatchservice; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; public interface OrderService { @RequestMapping(value = "/orders", method = RequestMethod.POST, produces = "application/json") Order create( @RequestBody(required = true) Order inputOrder); @RequestMapping(value="/orders", method=RequestMethod.GET) List<Order> getAll( @RequestParam(value="tripId", defaultValue="") String tripId); @RequestMapping(value="/orders/{id}", method=RequestMethod.GET) Order get(@PathVariable("id") String id); @RequestMapping(value="/orders/{id}", method=RequestMethod.PUT) Order update(@PathVariable("id") String id, @RequestBody(required = true) Order inputOrder); }
JavaScript
UTF-8
1,806
3.125
3
[]
no_license
import React, { useEffect, useState } from "react"; import './App.css'; //importing Components import Form from './components/form'; import ToDoList from './components/ToDoList'; function App() { //setState variables const [inputText, setInputText] = useState(''); const [toDos, setToDos] = useState([]); const [status, setStatus] = useState('all'); const [filteredToDos, setFilterToDos] = useState([]); //handlers for filtering const filterHandler = () =>{ if (status === "all"){ return toDos } else if(status === "completed"){ return toDos.filter(el => el.completed === true) } else if (status === "incomplete"){ return toDos.filter(el => el.completed === false) } else{ alert("this is not a valid filter") } } //get Todos from database const getAllTodos = async ()=>{ const response = await fetch("/todos",{ method : "GET" }) const data = await response.json(); setToDos(data); }; //rerender everytime status and toDos changes React.useEffect(()=>{ setFilterToDos(filterHandler); },[toDos, status]) //render once when application starts React.useEffect(()=> { getAllTodos(); },[]) return ( <div className="App"> <header>Henry's ToDo List</header> <h2>If you are on mobile please rotate for the best viewing experience</h2> {/* <button onClick = {getAllTodos}>HERE</button> */} <Form inputText = {inputText} setInputText = {setInputText} setToDos = {setToDos} toDos = {toDos} setStatus = {setStatus} /> <ToDoList toDos={toDos} setToDos={setToDos} filteredToDos ={filteredToDos} setFilterToDos={setFilterToDos}/> </div> ); } export default App;
Shell
UTF-8
4,301
3.59375
4
[]
no_license
#!/bin/bash #***************************************************************************************** # *用例名称:RAID_3108_Firmware_HBA_008 # *用例功能:1、测试LSI SAS3108是否可以通过storcli对物理硬盘进行各级别的数据擦除 # 2、是否可以停止数据擦除动作 # *作者:fwx654472 # *完成时间:2019-1-21 # *前置条件: # 1、服务器1台,配置LSI SAS3108卡 # 2、正常硬盘2块,将slot0槽位硬盘创建RAID0(Write Policy设置成WB模式),安装Linux OS,安装过程将硬盘分为系统和非系统分区,第2块硬盘选择尽量小容量型号 # 3、设置串口重定向监控RAID卡 # 4、LSI SAS3108卡管理软件StorCLI # *测试步骤: # 1、给服务器上电 # 2、对没有OS数据的硬盘执行初始化命令,预期结果A # (1)硬盘初始化命令(encloser 11, slot 1) # ./storcli64 /c0/e9/s1 start initialization # (2)查询硬盘初始化进度命令(encloser 11, slot 1) # ./storcli64 /c0/e9/s1 show initialization # *测试结果: # A: 可以进行硬盘初始化 #***************************************************************************************** #加载公共函数 . ../../../../utils/error_code.inc . ../../../../utils/test_case_common.inc . ../../../../utils/sys_info.sh . ../../../../utils/sh-test-lib #. ./error_code.inc #. ./test_case_common.inc #获取脚本名称作为测试用例名称 test_name=$(basename $0 | sed -e 's/\.sh//') #创建log目录 TMPDIR=./logs/temp mkdir -p ${TMPDIR} #存放脚本处理中间状态/值等 TMPFILE=${TMPDIR}/${test_name}.tmp #存放每个测试步骤的执行结果 RESULT_FILE=${TMPDIR}/${test_name}.result TMPCFG=${TMPDIR}/${test_name}.tmp_cfg test_result="pass" #预置条件 function init_env() { #检查结果文件是否存在,创建结果文件: PRINT_LOG "INFO" "*************************start to run test case<${test_name}>**********************************" fn_checkResultFile ${RESULT_FILE} #fio -h || fn_install_pkg fio 3 cp ../../../utils/tools/storcli64 ./. || PRINT_LOG "INFO" "cp fio is fail" chmod 777 storcli64 } #测试执行 function test_case() { #测试步骤实现部分 ./storcli64 /c0/e9/s1 start initialization if [ $? -eq 0 ] then PRINT_LOG "INFO" " /storcli64 /c0/e9/s1 start initialization is success." else PRINT_LOG "INFO" " /storcli64 /c0/e9/s1 start initialization is fail." fi ./storcli64 /c0/e9/s1 show initialization | grep "Initialization Status Succeeded" if [ $? -eq 0 ] then PRINT_LOG "INFO" " storcli64 /c0/e9/s1 show initialization is success." fn_writeResultFile "${RESULT_FILE}" "initializetion" "pass" else PRINT_LOG "INFO" "storcli64 /c0/e9/s1 show initialization is fail." fn_writeResultFile "${RESULT_FILE}" "initialization" "fail" fi #检查结果文件,根据测试选项结果,有一项为fail则修改test_result值为fail, check_result ${RESULT_FILE} } #恢复环境 function clean_env() { #清除临时文件 FUNC_CLEAN_TMP_FILE #自定义环境恢复实现部分,工具安装不建议恢复 #需要日志打印,使用公共函数PRINT_LOG,用法:PRINT_LOG "INFO|WARN|FATAL" "xxx" PRINT_LOG "INFO" "*************************end of running test case<${test_name}>**********************************" } function main() { init_env || test_result="fail" if [ ${test_result} = "pass" ] then test_case || test_result="fail" fi clean_env || test_result="fail" [ "${test_result}" = "pass" ] || return 1 } main $@ ret=$? #LAVA平台上报结果接口,勿修改 lava-test-case "$test_name" --result ${test_result} exit ${ret}
C#
UTF-8
3,895
2.765625
3
[]
no_license
using ITM.Courses.DAOBase; using ITM.Courses.Utilities; using MySql.Data.MySqlClient; using System; using System.Data.Common; namespace ITM.Courses.DAO { public class ApplicationLogoHeaderDAO { public string Q_AddLogoHeaderDetails = "Insert into applicationlogoheader(collegeName, logoimage,logoimagepath,logotext,DateCreated) values('{0}','{1}','{2}','{3}','{4}')"; public string Q_GetLogoHeaderbyCollege = "select * from applicationlogoheader where collegeName='{0}'"; public string Q_UpdateLogoHeader = "Update applicationlogoheader set logoimage='{0}',logoimagepath='{1}',logotext ='{2}' where id={3}"; public void AddLogoHeaderDetails(string college, string logoImage, string logoImagePath, string logoText, string cnxnString, string logPath) { try { string cmdText = string.Format(Q_AddLogoHeaderDetails, college, logoImage, logoImagePath, ParameterFormater.FormatParameter(logoText), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ff")); Database db = new Database(); using (MySqlConnection con = new MySqlConnection(cnxnString)) { con.Open(); db.Insert(cmdText, logPath, con); con.Close(); } } catch (Exception ex) { throw ex; } } public void UpdateLogoHeader(int id, string logoImage, string logoImagePath, string logoText, string cnxnString, string logPath) { try { string cmdText = string.Format(Q_UpdateLogoHeader, logoImage, logoImagePath, ParameterFormater.FormatParameter(logoText), id); Database db = new Database(); using (MySqlConnection con = new MySqlConnection(cnxnString)) { con.Open(); db.Update(cmdText, logPath, con); con.Close(); } } catch (Exception ex) { throw ex; } } public ApplicationLogoHeader GetLogoHeaderbyCollege(string collegeName, string cnxnString, string logPath) { try { string cmdText = string.Format(Q_GetLogoHeaderbyCollege, collegeName); Database db = new Database(); using (MySqlConnection con = new MySqlConnection(cnxnString)) { con.Open(); using (DbDataReader reader = db.Select(cmdText, logPath, con)) { if (reader.HasRows) { ApplicationLogoHeader appLogoHeader = new ApplicationLogoHeader(); while (reader.Read()) { appLogoHeader.Id = Convert.ToInt32(reader["id"]); appLogoHeader.CollegeName = reader["collegeName"].ToString(); appLogoHeader.LogoImageName = reader["logoimage"].ToString(); appLogoHeader.LogoImagePath = reader["logoimagepath"].ToString(); appLogoHeader.LogoText = ParameterFormater.UnescapeXML(reader["logotext"].ToString()); } if (!reader.IsClosed) { reader.Close(); } return appLogoHeader; } } con.Close(); } } catch (Exception ex) { throw ex; } return null; } } }
Ruby
UTF-8
1,665
3.515625
4
[]
no_license
class EditorTexto def initialize() end def mostrarMenu() puts "Bienvenido al editor de texto" puts "" puts "Menú" puts "1- Nuevo" puts "2- Abrir" puts "3- Escribir archivo existente" puts "4- Salir" puts "Por favor seleccione una acción" STDOUT.flush opcion = gets.chomp() return opcion end def seleccionarAccion(opcion) puts opcion case opcion when "1" STDOUT.flush puts "Ingrese el texto" data = gets.chomp() nombre = nombrarArchivo() escribirArchivo(data, nombre) when "2" STDOUT.flush archivo = elegirArchivos() leerArchivo(archivo) else end end private def escribirArchivo(data, nombre) puts "opcion 1" File.open(nombre + ".txt", "w") do |f| puts data f.write(data) end f.close gets.chomp() end private def leerArchivo(archivo) puts "opcion 2" File.foreach(archivo) { |line| puts line } f.close end def nombrarArchivo() puts "" puts "Escriba el nombre del archivo" STDOUT.flush nombreArchivo = gets.chomp() return nombreArchivo end def elegirArchivos() puts "" puts "Elija el archivo que desea leer" lista = Dir.glob("*") puts lista nombreArchivo = gets.chomp() return nombreArchivo end end #File.read("contenido.txt")
Java
UTF-8
1,381
2.171875
2
[]
no_license
package kr.green.springwebproject.service; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kr.green.springwebproject.dao.Board; import kr.green.springwebproject.dao.BoardComment; import kr.green.springwebproject.dao.BoardCommentMapper; import kr.green.springwebproject.dao.User; @Service public class BoardCommentService { @Autowired private BoardCommentMapper boardCommentMapper; public ArrayList<BoardComment> GetBoardComment(Board board,BoardComment boardComment){ return boardCommentMapper.getBoardComment(board, boardComment); } public boolean InsertBoardComment(User user, Board board, BoardComment boardComment) { boardComment.setWriter(user.getId()); boardCommentMapper.insertBoardComment(board, boardComment); return true; } public boolean DeleteBoardComment(Integer cno, BoardComment boardComment, Board board) { boardCommentMapper.deleteBoardComment(board, boardComment); return true; } public boolean modifyBoardComment(Integer cno, BoardComment boardComment, User user) { boardCommentMapper.modifyBoardComment(user, boardComment); return true; } public int CountComment(BoardComment boardComment, Board board) { int totalCount = 0; totalCount = boardCommentMapper.commentCount(board, boardComment); return totalCount; } }
C#
UTF-8
1,402
3.34375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ListeZad5 { class Program { static void Main(string[] args) { //Dictionary<TKey, TValue> Dictionary<string, int> gradovi = new Dictionary<string, int>() { {"Beograd", 2000000 }, {"Nis", 1400000 }, {"Kraljevo", 400000 }, }; Console.WriteLine("Grad - Stanovnici"); foreach (KeyValuePair<string, int> grad in gradovi) Console.WriteLine(grad.Key + " - " + grad.Value); Console.WriteLine("====================================="); Console.WriteLine("Preko var-a"); foreach (var grad in gradovi) Console.WriteLine(grad); Console.WriteLine("====================================="); Console.WriteLine("Samo vrednosti"); foreach (var grad in gradovi.Values) Console.WriteLine(grad); Console.WriteLine("====================================="); Console.WriteLine("Samo kljucevi"); foreach (var grad in gradovi.Keys) Console.WriteLine(grad); Console.WriteLine("====================================="); Console.ReadLine(); } } }
PHP
UTF-8
3,020
2.734375
3
[]
no_license
<?php namespace App\Http\Api\Authentication\Services; use App\Http\Api\Authentication\Requests\LoginUserRequest; use App\Http\Api\Authentication\Requests\RegisterUserRequest; use App\Http\Api\Role\Constants\Roles; use App\Http\Api\User\Resources\UserResource; use App\Http\Api\User\Models\User; use App\Http\Api\User\Interfaces\UserRepositoryInterface; use Illuminate\Http\JsonResponse; use Illuminate\Support\Carbon; use Illuminate\Support\Str; /** |-------------------------------------------------------------------------- | Authentication Service |-------------------------------------------------------------------------- | | This class is a type of service, in which we are doing | the whole logic about authentication stuff. | | @author David Ivanov <david4obgg1@gmail.com> */ class AuthenticationService { /** * Initializing the instance of User Repository interface. * * @var UserRepositoryInterface */ private UserRepositoryInterface $userRepository; /** * AuthenticationService constructor. * * @param UserRepositoryInterface $userRepository */ public function __construct(UserRepositoryInterface $userRepository) { $this->userRepository = $userRepository; } /** * Login the user with his credentials. * * @param LoginUserRequest $request * @return JsonResponse */ public function login(LoginUserRequest $request) : JsonResponse { $validated = $request->validated(); if (!auth()->attempt($validated)) { return response()->json(['message' => 'Email address or/and password are incorrect.'], 401); } $user = $this->userRepository->findById(auth()->user()->id); $user->update([ 'last_login_ip' => $request->getClientIp(), 'last_login_at' => Carbon::now()->toDateTimeString() ]); return response()->json(new UserResource($user)); } /** * Register the user with his credentials. * * @param RegisterUserRequest $request * @return JsonResponse */ public function register(RegisterUserRequest $request): JsonResponse { $validated = $request->validated(); $userClass = User::class; $user = User::create([ 'first_name' => $validated['first_name'], 'middle_name' => $validated['middle_name'], 'last_name' => $validated['last_name'], 'email' => $validated['email'], 'password' => $validated['password'], 'avatar' => $validated['avatar'] ?? User::DEFAULT_PICTURE, 'token' => Str::random(255) ]); $user->checkForPicture($request, 'avatar', 'avatars', $user); $user->assignRole()->create([ 'role_id' => Roles::EMPLOYEE_SELF_SERVICE_ROLE, 'model_type' => $userClass, 'model_id' => $user->id, 'model_from' => $userClass ]); return response()->json(new UserResource($user)); } }
Markdown
UTF-8
561
2.796875
3
[]
no_license
# bash_yt_mp3_downloader A simple bash script that uses youtube-dl to download mp3 from youtube. # How to use: Install youtube-dl from: https://github.com/rg3/youtube-dl/blob/master/README.md#readme Write in your terminal chmod +x dw.sh in order to give it the right privilages Execute as ./dw.sh '<youtube_link>' (notice that you should put the link between ') # Troubleshooting: Make sure you pasted the URL between ' or " Some terminals convert the /watch?v to /watch\?v\ when pasting. Make sure that you remove the \ if it is the case
Java
UTF-8
2,471
2.03125
2
[]
no_license
package com.icw.pronounciationpractice.endpoints; import com.icw.pronounciationpractice.dto.UsuarioQuestaoDTO; import com.icw.pronounciationpractice.entity.UsuarioQuestao; import com.icw.pronounciationpractice.entity.UsuarioQuestaoId; import com.icw.pronounciationpractice.mapper.UsuarioQuestaoMapper; import com.icw.pronounciationpractice.service.interfaces.QuestaoService; import com.icw.pronounciationpractice.service.interfaces.UsuarioQuestaoService; import com.icw.pronounciationpractice.service.interfaces.UsuarioService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; @RestController @RequestMapping("/v1/usuario-questao") public class UsuarioQuestaoController { @Autowired private UsuarioQuestaoService usuarioQuestaoService; @Autowired private UsuarioService usuarioService; @Autowired private QuestaoService questaoService; @Autowired private UsuarioQuestaoMapper usuarioQuestaoMapper; @GetMapping("/questao/{id}") public UsuarioQuestaoDTO findByQuestaoId(@PathVariable("id") Long questaoId, @RequestParam(required = true) Long usuarioId){ return usuarioQuestaoService.findByQuestaoId(usuarioId, questaoId).map(usuarioQuestaoMapper::map).orElse(null); } @PostMapping public UsuarioQuestaoDTO save(@RequestBody UsuarioQuestaoDTO usuarioQuestaoDTO){ return usuarioQuestaoMapper.map(usuarioQuestaoService.save(formataUsuarioQuestao(usuarioQuestaoDTO))); } @PutMapping public UsuarioQuestaoDTO update(@RequestBody UsuarioQuestaoDTO usuarioQuestaoDTO){ return usuarioQuestaoMapper.map(usuarioQuestaoService.save(formataUsuarioQuestao(usuarioQuestaoDTO))); } private UsuarioQuestao formataUsuarioQuestao(UsuarioQuestaoDTO usuarioQuestaoDTO){ UsuarioQuestao usuarioQuestao = new UsuarioQuestao(); UsuarioQuestaoId usuarioQuestaoId = new UsuarioQuestaoId(); usuarioQuestaoId.setQuestao(questaoService.findById(usuarioQuestaoDTO.getQuestaoId()).orElse(null)); usuarioQuestaoId.setUsuario(usuarioService.findById(usuarioQuestaoDTO.getUsuarioId()).orElse(null)); usuarioQuestao.setDataAtualizacao(LocalDateTime.now()); usuarioQuestao.setId(usuarioQuestaoId); usuarioQuestao.setPontuacao(usuarioQuestaoDTO.getPontuacao()); return usuarioQuestao; } }
C++
UTF-8
1,801
2.921875
3
[ "LGPL-2.0-or-later", "LGPL-3.0-or-later", "LGPL-2.1-or-later", "MIT" ]
permissive
/** * This is a minimal example, see extra-examples.cpp for a version * with more explantory documentation, example routines, how to * hook up your pixels and all of the pixel types that are supported. * * On Photon, Electron, P1, Core and Duo, any pin can be used for Neopixel. * * On the Argon, Boron and Xenon, only these pins can be used for Neopixel: * - D2, D3, A4, A5 * - D4, D6, D7, D8 * - A0, A1, A2, A3 * * In addition on the Argon/Boron/Xenon, only one pin per group can be used at a time. * So it's OK to have one Adafruit_NeoPixel instance on pin D2 and another one on pin * A2, but it's not possible to have one on pin A0 and another one on pin A1. */ #include "Particle.h" #include "neopixel.h" SYSTEM_MODE(AUTOMATIC); // IMPORTANT: Set pixel COUNT, PIN and TYPE #define PIXEL_PIN D2 #define PIXEL_COUNT 10 #define PIXEL_TYPE WS2812B Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE); // Prototypes for local build, ok to leave in for Build IDE void rainbow(uint8_t wait); uint32_t Wheel(byte WheelPos); void setup() { strip.begin(); strip.show(); // Initialize all pixels to 'off' } void loop() { rainbow(20); } void rainbow(uint8_t wait) { uint16_t i, j; for(j=0; j<256; j++) { for(i=0; i<strip.numPixels(); i++) { strip.setPixelColor(i, Wheel((i+j) & 255)); } strip.show(); delay(wait); } } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { if(WheelPos < 85) { return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } else if(WheelPos < 170) { WheelPos -= 85; return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 170; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } }
Java
UTF-8
1,354
3.046875
3
[]
no_license
/** * Copyright 2016 Jasper Infotech (P) Limited . All Rights Reserved. * JASPER INFOTECH PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package src.mytest; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * @version 1.0, 01-Mar-2016 * @author ankit */ public class ThreadTimeOut { public static void main(String[] args) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(4000); // Just to demo a long running task of 4 seconds. return "Ready!"; } }); try { System.out.println("Started.."); System.out.println(future.get(2, TimeUnit.SECONDS)); System.out.println("Finished!"); } catch (TimeoutException e) { future.cancel(true); System.out.println("Terminated!"); } catch (Exception e) { future.cancel(true); System.out.println("Strange!"); } executor.shutdownNow(); } }
Markdown
UTF-8
3,277
3.40625
3
[]
no_license
## 数据库相关概念的学习 1. 不可重复读 不能重复读是指在事务开始之后, 第一次读取的结果集和第二次读取的结果集不一致。 | TRANSACTION1 | TRANSACTIONS2 | | ---------------------------- | ------------------------ | | select * from p where id < 5 | | | | insert into p values (2) | | | commit | | select * from p where id < 5 | | 以上是作为一个正确的事务执行顺序, 如果`TRANSACTION1`两次执行了相同的SQL语句, 但是却获取了`TRANSACTION2`插入的结果。 这种主要是事务级别为`READ COMMITTED`时出现。 2. 脏读 脏读是指的事务之间读取了其他事务没有提交的数据 | TRANSACTION1 | TRANSACTIONS2 | | ----------------------------- | ------------------------- | | BEGIN | | | SELECT * FROM p WHERE id < 5; | | | | BEGIN | | | INSERT INTO p VALUES (2); | | SELECT * FROM p WHERE id < 5 | | `TRANSACTION1`两次读取之间,事务`TRANSACTION2`插入了一条数据,但是没有提交,如果`TRANSACTION1`读取到了`TRANSACTION2`插入的数据, 这就产生了数据脏读. 这种情况主要出现在`READ UNCOMMITTED`的隔离级别之下。 3. 幻读 幻读指的是两个事务之间, 操作相同的数据差生了冲突,导致另外一个事务无法正常执行业务的后续操作。 | TRANSACTION1 | TRANSACTIONS2 | | ----------------------------------------------------------- | ------------------------ | | BEGIN | | | SELECT * FROM WHERE id = 1 | | | | BEGIN | | | INSERT INTO p VALUES (1) | | INSERT INTO p VALUES (1) | | | ERROR 1062 (23000): `Duplicate entry '1' for key 'PRIMARY'` | | 以上主要操作了两个事务, 在`TRANSACTION1`中判断`id=1`的记录不存在, 准备插入一个`id = 1`的记录, 但是在这期间, `TRANSACTION2`插入了一条`id = 1`的记录, 这是导致了`TRANSACTION1`插入失败,但是当通过`select * from where id = 1`查询这条记录时, 却查询不到这条记录, 这是因为`mysql`采用了`REPEATABLE READ`的策略,导致了其他事务提交的数据不能被读取到。 解决幻读最好的办法就是通过`锁`的方式对需要操作的数据加锁, 防止事务执行失败。 > NOTE: 在`Serializable`隔离级别之下, 查询语句默认的都会加锁(共享锁(S)), 因此这种的话, `TRANSACTION1`的第三部可以正常执行,`TRANSACTION2`等待锁的释放. ![Serializable查询锁](../img/mysql/SERIZIABLE_SELECT_LOCK.png)
Python
UTF-8
288
2.625
3
[]
no_license
#!/usr/bin/env python3 """Convert a parquet file to CSV.""" import pandas import io import sys IN_FILE, OUT_FILE = sys.argv[1], sys.argv[2] if not OUT_FILE: print("Output file argument required.") exit(1) data = pandas.read_parquet(IN_FILE) data.to_csv(OUT_FILE, index=False)
C#
UTF-8
1,329
2.765625
3
[]
no_license
using MQHelper; using Newtonsoft.Json; using SMS.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SMSService { /// <summary> /// 短信提交到MQ /// </summary> public class SMSSubmit { private RabbitMQHelper mq; private SMSSubmit() { mq = new RabbitMQHelper(AppConfig.MQHost, AppConfig.MQVHost, AppConfig.MQUserName, AppConfig.MQPassword); //设置最多10个优先级 mq.BindQueue("SendQueue", AppConfig.MaxPriority, "SendQueue"); } private static SMSSubmit _instance = null; private static object locker = new object(); public static SMSSubmit Instance { get { if (_instance == null) { lock (locker) { if (_instance == null) { _instance = new SMSSubmit(); } } } return _instance; } } public void SendSMS(SMSDTO sms) { string message = JsonConvert.SerializeObject(sms); mq.PublishMessage(message, sms.Message.SMSLevel); } } }
Java
UTF-8
1,334
2.421875
2
[]
no_license
package org.noranj.core.server.servlet; import java.io.IOException; import java.util.Properties; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeMessage; import javax.servlet.http.*; /** * This is a general MailHandler all the emails sent to the application are processed here. * * Right now we do not process any general email and they all are dumped. * * This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY. * See http://www.noranj.org for further information. * * @author * @since 0.2 * @version 0.2.20120820 * @change * */ @SuppressWarnings("serial") public class MailHandlerServlet extends HttpServlet { protected static Logger logger = Logger.getLogger(MailHandlerServlet.class.getName()); public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session, req.getInputStream()); //TODO parse the message } catch (MessagingException msgex){ //do something } } }
Markdown
UTF-8
1,078
3.65625
4
[ "MIT" ]
permissive
```cpp /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ int height(TreeNode *root) { if (!root) return 0; else return 1 + max(height(root->left), height(root->right)); } void traverse(vector<vector<int>> &res, int level, int maxLevel, TreeNode *node) { if (!node) return; if (level == maxLevel) { res[maxLevel].emplace_back(node->val); return; } if (maxLevel % 2 == 1) { traverse(res, level + 1, maxLevel, node->right); traverse(res, level + 1, maxLevel, node->left); } else { traverse(res, level + 1, maxLevel, node->left); traverse(res, level + 1, maxLevel, node->right); } } vector<vector<int>> Solution::zigzagLevelOrder(TreeNode *A) { int levels = height(A); vector<vector<int>> res(levels); for (int i = 0; i < levels; i++) { traverse(res, 0, i, A); } return res; } ```
C++
UTF-8
16,717
3.984375
4
[ "BSD-2-Clause" ]
permissive
#include <iostream> #include "bstree.hpp" /* * ********* BSTREE CLASS * ********* Public Methods * */ /* * Function: Destructor * * Description: Destroys the tree by freeing all nodes it possesses * */ template <typename TKey, typename TVal> BSTree<TKey, TVal>::~BSTree() { _deleteTree(root); } /* * Function: insert * @param1: TKey key : Lookup key. * @param2: TVal data : The data which the key leads to. * @returns: void * * Description: This function inserts the specified data (@param2) to the binary search tree * and uses the key (@param1) to determine the node's location. * */ template <typename TKey, typename TVal> void BSTree<TKey, TVal>::insert(TKey key, TVal data) { // If the BSTree is empty, create the node at the root. if(!root) { root = _newNode(key, data); } else { BSTree<TKey, TVal>::node** current = &root, *parent = NULL; // Loop until an empty slot is found in the tree while(*current) { parent = *current; if(key < (*current)->key) { current = &parent->left; } else { current = &parent->right; } } // Empty slot is found, fill it with the given parameters. *current = _newNode(key,data); (*current)->parent = parent; } } /* * Function: del * @param1: TKey key : Lookup key. * @returns: true if successful, false otherwise. * * Description: This function finds and deletes the desired node from the * binary search tree using the given lookup key (@param1). * */ template <typename TKey, typename TVal> bool BSTree<TKey, TVal>::del(TKey key) { // Check if the binary search tree is not empty. if(!root) { return false; } BSTree<TKey, TVal>::node** current = &root; // Loop until the node with given key is found, // or until there are no nodes left to look for. while(*current && (*current)->key != key) { if(key < (*current)->key) { current = &(*current)->left; } else { current = &(*current)->right; } } // Check if the end of the tree is reached. if(!*current) { return false; } // If not then the desired node is found. // If the left node is empty, move the right node // to the current node. if(!(*current)->left) { if((*current)->right) { (*current)->right->parent = (*current)->parent; } BSTree<TKey, TVal>::node* ptrToFree = *current; *current = (*current)->left; delete ptrToFree; } // If the right node is empty, move the left node // to the current node. else if(!(*current)->right) { if((*current)->left) { (*current)->left->parent = (*current)->parent; } BSTree<TKey, TVal>::node* ptrToFree = *current; *current = (*current)->left; delete ptrToFree; } // If the left and the right nodes are both present, // find the leftmost (smallest) node in the right subtree // and copy the contents to the node that will be deleted. else { BSTree<TKey, TVal>::node** temp = &(*current)->right; while((*temp)->left) temp = &(*temp)->left; (*current)->data = (*temp)->data; (*current)->key = (*temp)->key; // Delete the copied node. BSTree<TKey, TVal>::node* ptrToFree = *temp; *temp = (*temp)->right; delete ptrToFree; } return true; } // Same as del template <typename TKey, typename TVal> bool BSTree<TKey, TVal>::remove(TKey key) { return del(key); } /* * Function: print * @param1: TRAVERSAL_METHOD t : Method to be used to print the tree (inorder, preorder, postorder) * @returns: void * * Description: This function prints the values inside the binary search tree * to the stdout with desired order (@param1). * */ template <typename TKey, typename TVal> void BSTree<TKey, TVal>::print(TRAVERSAL_METHOD t) { switch(t) { case INORDER : { _printInOrder(root); break; } case PREORDER : { _printPreOrder(root); break; } case POSTORDER : { _printPostOrder(root); break; } } std::cout << std::endl; } /* * Function: has * @param1: TKey key : Lookup key. * @returns: true if found, false otherwise. * * Description: This function checks if the binary search tree * has a node with the given key (@param1). * */ template <typename TKey, typename TVal> bool BSTree<TKey, TVal>::has(TKey key) { BSTree<TKey, TVal>::node* current = root; // Loop until there are no nodes left to check. while(current) { // If the current key equals to the search key (@param1), the node is found; return if(key == current->key) { return true; } if(key < current->key) { current = current->left; } else { current = current->right; } } return false; } /* * Function: findNode * @param1: TKey key : Lookup key. * @returns: The read-only reference of the node with given key. * * Description: This function finds the node with given key (@param1) and * returns its read-only reference. * */ template <typename TKey, typename TVal> const typename BSTree<TKey, TVal>::node* BSTree<TKey, TVal>::findNode(TKey key) { // Same procedure with function "has" BSTree<TKey, TVal>::node* current = root; while(current) { if(key == current->key) { return current; } if(key < current->key) { current = current->left; } else { current = current->right; } } return NULL; } /* * Function: getVal * @param1: TKey key : Lookup key. * @returns: The read-only reference of the data that the key leads to. * * Description: This function finds the node with given key (@param1) and * returns its data field's read-only reference. * */ template <typename TKey, typename TVal> const TVal* BSTree<TKey, TVal>::getVal(TKey key) { // Same procedure with function "has" BSTree<TKey, TVal>::node* current = root; while(current) { if(key == current->key) { return &(current->data); } if(key < current->key) { current = current->left; } else { current = current->right; } } return NULL; } /* * Function: change * @param1: TKey key : Lookup key. * @param2: TVal data : New data to change to. * @returns: true if successful, false otherwise. * * Description: This function finds the node with given key (@param1) and * changes its data field with the given data (@param2). * */ template <typename TKey, typename TVal> bool BSTree<TKey, TVal>::change(TKey key, TVal data) { BSTree<TKey, TVal>::node** current = &root; // Loop until there are no nodes left to check. while(*current) { // If the current key equals to the search key (@param1), // change the node's data to the given data (@param2). if(key == (*current)->key) { (*current)->data = data; return true; } if(key < (*current)->key) { current = &(*current)->left; } else { current = &(*current)->right; } } return false; } /* * Function: begin * @returns: An inorder BSTree iterator object at the * beginning of the tree (node with smallest key) */ template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator BSTree<TKey, TVal>::begin() { BSTree<TKey, TVal>::node* current = root; // Check if the tree is empty if(current != NULL) { // If it's not, make the iterator object point to the leftmost node of the tree. while(current->left != NULL) current = current->left; } // Create the object with the private constructor and return it. // If the tree is empty, the iterator will point to the end of the tree (which is NULL). return iterator(current,this); } /* * Function: begin (overload) * @param1: int start : Offset * @returns: An inorder BSTree iterator object that points to the node * at the given position (@param1) in the tree. */ template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator BSTree<TKey, TVal>::begin(int start) { // Create an iterator that points to the first element. BSTree<TKey, TVal>::iterator temp = this->begin(); // Iterate by desired amount (@param1). int i=0; while(i<start && temp != this->end()) { temp++; i++; } // Return it at the current position. return temp; } /* * Function: rbegin * @returns: An inorder BSTree iterator object that points to the * last node in the tree (node with greatest key). * * Description: rbegin = reverse begin. */ template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator BSTree<TKey, TVal>::rbegin() { BSTree<TKey, TVal>::node* current = root; if(current != NULL) { // Find the rightmost element while(current->right != NULL) current = current->right; } return iterator(current,this); } /* * Function: end * @returns: An inorder BSTree iterator object at the end of * the tree (an iterator that points to a NULL node). * * Description: Used to compare with other iterators, to represent the end condition. */ template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator BSTree<TKey, TVal>::end() { return iterator(NULL,this); } /* ********* Private Methods */ /* * Creates and initializes a node struct */ template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::node* BSTree<TKey, TVal>::_newNode(TKey key, TVal data) { node* newNode = new node; newNode->data = data; newNode->key = key; newNode->left = NULL; newNode->right = NULL; newNode->parent = NULL; return newNode; } /* * Destroys the tree with given root by freeing all nodes it possesses recursively */ template <typename TKey, typename TVal> void BSTree<TKey, TVal>::_deleteTree(node* root) { if(root != NULL) { _deleteTree(root->left); _deleteTree(root->right); delete root; } } /* * RECURSIVE PRINTERS */ template <typename TKey, typename TVal> void BSTree<TKey, TVal>::_printInOrder(node* root) { if(root != NULL) { _printInOrder(root->left); std::cout << root->data << " "; _printInOrder(root->right); } } template <typename TKey, typename TVal> void BSTree<TKey, TVal>::_printPreOrder(node* root) { if(root != NULL) { std::cout << root->data << " "; _printPreOrder(root->left); _printPreOrder(root->right); } } template <typename TKey, typename TVal> void BSTree<TKey, TVal>::_printPostOrder(node* root) { if(root != NULL) { _printPostOrder(root->right); _printPostOrder(root->left); std::cout << root->data << " "; } } /* * ********* BSTREE ITERATOR SUBCLASS * */ template <typename TKey, typename TVal> const TVal BSTree<TKey, TVal>::iterator::get() { return currentNode->data; } template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator& BSTree<TKey, TVal>::iterator::operator= (const iterator& rhs) { this->currentNode = rhs.currentNode; this->tree = rhs.tree; return *this; } // PRE-INCREMENT template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator& BSTree<TKey, TVal>::iterator::operator++ () { if(currentNode == NULL) { currentNode = tree->root; // If it is still NULL, then the tree is empty. while( currentNode->left != NULL) currentNode = currentNode->left; } else { if(currentNode->right != NULL) { currentNode = currentNode->right; while(currentNode->left != NULL) { currentNode = currentNode->left; } } else { BSTree<TKey, TVal>::node* parent = currentNode->parent; while(parent != NULL && currentNode != parent->left) { currentNode = parent; parent = parent->parent; } currentNode = parent; } } return *this; } // POST-INCREMENT template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator BSTree<TKey, TVal>::iterator::operator++ (int) { BSTree<TKey, TVal>::iterator temp = *this; if(currentNode == NULL) { currentNode = tree->root; // If it is still NULL, then the tree is empty. while( currentNode->left != NULL) currentNode = currentNode->left; } else { if(currentNode->right != NULL) { currentNode = currentNode->right; while(currentNode->left != NULL) { currentNode = currentNode->left; } } else { BSTree<TKey, TVal>::node* parent = currentNode->parent; while(parent != NULL && currentNode != parent->left) { currentNode = parent; parent = parent->parent; } currentNode = parent; } } return temp; } // PRE-DECREMENT template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator& BSTree<TKey, TVal>::iterator::operator-- () { if(currentNode == NULL) { currentNode = tree->root; // If it is still NULL, then the tree is empty. // Go to the rightmost leaf. while( currentNode->right != NULL) currentNode = currentNode->right; } else { if(currentNode->left != NULL) { currentNode = currentNode->left; while(currentNode->right != NULL) { currentNode = currentNode->right; } } else { BSTree<TKey, TVal>::node* parent = currentNode->parent; while(parent != NULL && currentNode != parent->right) { currentNode = parent; parent = parent->parent; } currentNode = parent; } } return *this; } // POST-DECREMENT template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator BSTree<TKey, TVal>::iterator::operator-- (int) { BSTree<TKey, TVal>::iterator temp = *this; if(currentNode == NULL) { currentNode = tree->root; // If it is still NULL, then the tree is empty. // Go to the rightmost leaf. while( currentNode->right != NULL) currentNode = currentNode->right; } else { if(currentNode->left != NULL) { currentNode = currentNode->left; while(currentNode->right != NULL) { currentNode = currentNode->right; } } else { BSTree<TKey, TVal>::node* parent = currentNode->parent; while(parent != NULL && currentNode != parent->right) { currentNode = parent; parent = parent->parent; } currentNode = parent; } } return temp; } template <typename TKey, typename TVal> bool BSTree<TKey, TVal>::iterator::operator== (const BSTree<TKey, TVal>::iterator& rhs) const { return this->currentNode == rhs.currentNode; } template <typename TKey, typename TVal> bool BSTree<TKey, TVal>::iterator::operator!= (const BSTree<TKey, TVal>::iterator& rhs) const { return this->currentNode != rhs.currentNode; } template <typename TKey, typename TVal> const typename BSTree<TKey, TVal>::node& BSTree<TKey, TVal>::iterator::operator* () const { return *(this->currentNode); } /* * NOT NEEDED AND DANGEROUS * // ADDITION template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator& BSTree<TKey, TVal>::iterator::operator+ (const int rhs) { for(int i=0; i<rhs; i++) (*this)++; return *this; } // SUBTRACTION template <typename TKey, typename TVal> typename BSTree<TKey, TVal>::iterator& BSTree<TKey, TVal>::iterator::operator- (const int rhs) { for(int i=0; i<rhs; i++) (*this)--; return *this; }*/ template class BSTree<int, int>; template class BSTree<int, const char*>; template class BSTree<char, int>; template class BSTree<char, const char*>; template class BSTree<const char*, int>; template class BSTree<const char*, const char*>; template class BSTree<float, const char*>; //...
Java
UTF-8
15,514
2.015625
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 rs.ac.bg.fon.silab.gui.form; import rs.ac.bg.fion.silab.gui.general.GeneralGUINew; import rs.ac.bg.fion.silab.gui.general.GeneralGUI; import java.awt.Frame; import java.time.LocalDate; import java.time.ZoneId; import java.util.Calendar; import java.util.Date; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JTextField; /** * * @author MARINA */ public class FStudentNew extends javax.swing.JDialog implements GeneralGUI, GeneralGUINew { /** * Creates new form FStudentNew * * @param parent * @param modal */ public FStudentNew(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setButtons(); setDatumRodjenjaField(); pack(); } private void setButtons() { jPanelButtons = new PButtonsNew(); jPanelButtons.setVisible(true); this.add(jPanelButtons, BoxLayout.Y_AXIS); } public void setPrijava(PPrijavaDiplomskogRada panelPrijava) { jPanelPrijava = panelPrijava; jPanelPrijava.setVisible(true); this.add(jPanelPrijava, BoxLayout.Y_AXIS); pack(); } public void setOdobravanje(POdobravanjeDiplomskogRada panelOdobravanje) { jPanelOdobravanje = panelOdobravanje; jPanelOdobravanje.setVisible(true); this.add(jPanelOdobravanje, BoxLayout.Y_AXIS); pack(); } public void setOdbrana(POdbraniDiplomskiRad panelOdbrani) { jPanelOdbrani = panelOdbrani; jPanelOdbrani.setVisible(true); this.add(jPanelOdbrani, BoxLayout.Y_AXIS); pack(); } public void setKomisija(PKomisija panelKomisija) { jPanelKomisija = panelKomisija; jPanelKomisija.setVisible(true); this.add(jPanelKomisija, BoxLayout.Y_AXIS); pack(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTxtBrojIndeksa3 = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jTxtBrojIndeksa = new javax.swing.JTextField(); jTxtJMBG = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTxtIme = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jTxtPrezime = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jSpinnerGodinaStudija = new javax.swing.JSpinner(); jCheckBoxBudzet = new javax.swing.JCheckBox(); jCheckBoxPrviPutUpisao = new javax.swing.JCheckBox(); jBtnGenerisiBrojIndeksa = new javax.swing.JButton(); jDateRodjenja = new org.jdesktop.swingx.JXDatePicker(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); jLabel1.setText("Broj indeksa:"); jTxtBrojIndeksa.setEditable(false); jLabel2.setText("JMBG:"); jLabel3.setText("Ime:"); jLabel4.setText("Prezime:"); jLabel5.setText("Datum rodjenja:"); jLabel6.setText("Godina studija:"); jCheckBoxBudzet.setText("Budzet"); jCheckBoxPrviPutUpisao.setText("Prvi put upisao"); jBtnGenerisiBrojIndeksa.setText("Generisi broj indeksa"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jTxtIme)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTxtJMBG)) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTxtPrezime) .addComponent(jSpinnerGodinaStudija) .addComponent(jDateRodjenja, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTxtBrojIndeksa, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBtnGenerisiBrojIndeksa, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE))) .addGap(25, 25, 25)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jCheckBoxBudzet, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxPrviPutUpisao) .addContainerGap()))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTxtBrojIndeksa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBtnGenerisiBrojIndeksa)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTxtJMBG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTxtIme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTxtPrezime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jDateRodjenja, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jSpinnerGodinaStudija, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCheckBoxBudzet) .addComponent(jCheckBoxPrviPutUpisao)) .addContainerGap(31, Short.MAX_VALUE)) ); getContentPane().add(jPanel2); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jBtnGenerisiBrojIndeksa; private javax.swing.JCheckBox jCheckBoxBudzet; private javax.swing.JCheckBox jCheckBoxPrviPutUpisao; private org.jdesktop.swingx.JXDatePicker jDateRodjenja; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel2; private javax.swing.JSpinner jSpinnerGodinaStudija; private javax.swing.JTextField jTxtBrojIndeksa; private javax.swing.JTextField jTxtBrojIndeksa3; private javax.swing.JTextField jTxtIme; private javax.swing.JTextField jTxtJMBG; private javax.swing.JTextField jTxtPrezime; // End of variables declaration//GEN-END:variables private PButtonsNew jPanelButtons; private PPrijavaDiplomskogRada jPanelPrijava; private POdobravanjeDiplomskogRada jPanelOdobravanje; private POdbraniDiplomskiRad jPanelOdbrani; private PKomisija jPanelKomisija; public String getBrojIndeksa() { return jTxtBrojIndeksa.getText().trim(); } public String getJMBG() { return jTxtJMBG.getText().trim(); } public String getIme() { return jTxtIme.getText().trim(); } public String getPrezime() { return jTxtPrezime.getText().trim(); } public boolean getBudzet() { return jCheckBoxBudzet.isSelected(); } public int getGodinaStudija() { return (Integer) jSpinnerGodinaStudija.getValue(); } public LocalDate getDatumRodjenja() { return jDateRodjenja.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); } public boolean getPrviPutUpisao() { return jCheckBoxPrviPutUpisao.isSelected(); } public void setBrojIndeksa(String brojIndeksa) { jTxtBrojIndeksa.setText(brojIndeksa); } public void setJMBG(String jmbg) { jTxtJMBG.setText(jmbg); } public void setIme(String ime) { jTxtIme.setText(ime); } public void setPrezime(String prezime) { jTxtPrezime.setText(prezime); } public void setBudzet(boolean budzet) { jCheckBoxBudzet.setSelected(budzet); } public void setGodinaStudija(int godinaStudija) { jSpinnerGodinaStudija.setValue(godinaStudija); } public void setDatumRodjenja(LocalDate datumRodjenja) { jDateRodjenja.setDate( Date.from(datumRodjenja.atStartOfDay(ZoneId.systemDefault()).toInstant())); } public void setPrviPutUpisao(boolean prviPutUpisao) { jCheckBoxPrviPutUpisao.setSelected(prviPutUpisao); } @Override public JButton getSave() { return jPanelButtons.getjBtnSave(); } @Override public JButton getUpdate() { return jPanelButtons.getjBtnUpdate(); } @Override public JButton getEdit() { return jPanelButtons.getJbtnEdit(); } @Override public JButton getCancel() { return jPanelButtons.getjBtnCancel(); } public JButton getGenerisiBrojIndeksa() { return jBtnGenerisiBrojIndeksa; } @Override public void setMessage(String signal) { JOptionPane.showMessageDialog(rootPane, signal); } @Override public void close() { dispose(); } public javax.swing.JCheckBox getjCheckBoxBudzet() { return jCheckBoxBudzet; } public javax.swing.JCheckBox getjCheckBoxPrviPutUpisao() { return jCheckBoxPrviPutUpisao; } public org.jdesktop.swingx.JXDatePicker getjDateRodjenja() { return jDateRodjenja; } public javax.swing.JTextField getjTxtBrojIndeksa() { return jTxtBrojIndeksa; } public javax.swing.JTextField getjTxtIme() { return jTxtIme; } public javax.swing.JTextField getjTxtJMBG() { return jTxtJMBG; } public JTextField getjTxtPrezime() { return jTxtPrezime; } public PButtonsNew getjPanelButtons() { return jPanelButtons; } public javax.swing.JSpinner getjSpinnerGodinaStudija() { return jSpinnerGodinaStudija; } private void setDatumRodjenjaField() { int year = Calendar.getInstance().get(Calendar.YEAR) - 1919; jDateRodjenja.setDate(new Date(year, 0, 1)); } }
C
UTF-8
488
3.640625
4
[ "MIT" ]
permissive
#include<stdio.h> #include<stdlib.h> // void print_vector(int *m, int n); // void print_vector(int m[], int n); // void print_vector(int m[5], int n); void print_vector(int *n, int tam){ /*Prints an array as follows: vet[index] = value*/ for (int i = 0; i < tam; i++) { printf("vet[%d] = %d\n", i, n[i]); } } int main(int argc, char const *argv[]) { int v[5] = {1, 2, 3, 4, 5}; print_vector(v, 5); return 0; }
Markdown
UTF-8
3,706
2.546875
3
[]
no_license
--- copyright: years: 2019, 2020 lastupdated: "2020-02-25" keywords: catalog, private catalogs, visibility, filter catalog, hide offering, catalog filtering subcollection: account --- {:shortdesc: .shortdesc} {:codeblock: .codeblock} {:screen: .screen} {:tip: .tip} {:note: .note} {:important: .important} {:external: target="_blank" .external} # Filtering the {{site.data.keyword.cloud_notm}} catalog for all account users {: #filter-account} This tutorial walks you through the steps to set a filter to include all {{site.data.keyword.cloud}} offerings, except for {{site.data.keyword.appid_full}}, in the {{site.data.keyword.cloud_notm}} catalog. {: shortdesc} This feature is available only in a closed beta. If you’re interested in participating, contact kala.nenkova@ibm.com. {: note} ## Before you begin {: #prereqs-acctfilter} To complete this tutorial, you need to be assigned the administrator role on the private catalog service. With this type of access, you can set filters in the {{site.data.keyword.cloud_notm}} catalog for all users in the account. For more information, see [Assigning users access](/docs/account?topic=account-catalog-access). If you don't see what you're expecting in the console based on your permissions, try refreshing your session by going to https://cloud.ibm.com/login. {: tip} ## Set a catalog filter in the console {: #create-acctfilter} Complete the following steps to set a filter that includes all {{site.data.keyword.cloud_notm}} offerings in the catalog except for {{site.data.keyword.appid_short_notm}}. 1. Log in to your {{site.data.keyword.cloud_notm}} account, and go to [Manage > Catalogs](https://cloud.ibm.com/content-mgmt/catalogs). 1. Select **Settings**. 2. Make sure the visibility of the {{site.data.keyword.cloud_notm}} catalog is turned on. 1. In the Rules section, click the **Edit** icon ![Edit icon](../icons/edit-tagging.svg). 1. Select **Exclude all offerings in the {{site.data.keyword.cloud_notm}} catalog** to start with an empty catalog. 1. Click **Add rule**, select **Provider**, and click **IBM**. 1. Click **Add exception**, and select **Exclude** > **{{site.data.keyword.appid_short_notm}}**. 1. In the Preview section, verify that the value for {{site.data.keyword.appid_short_notm}} in the Included column is No. 1. Click **Update** to apply your changes. ## Set a catalog filter by using the CLI {: #cli-acctfilter} Before you start this task, make sure you [install the {{site.data.keyword.cloud_notm}} CLI and the catalogs management CLI plug-in](/docs/account?topic=account-manage-catalog#landing-prereqs). <br> Complete the following steps to set a filter that includes all {{site.data.keyword.cloud_notm}} offerings in the catalog except for {{site.data.keyword.appid_short_notm}}. 1. Remove the existing filter that you created in the previous steps. ``` ibmcloud catalog filter delete ``` {: codeblock} 1. Create a filter that includes only {{site.data.keyword.cloud_notm}} offerings in the catalog and excludes {{site.data.keyword.appid_short_notm}} from the catalog. ``` ibmcloud catalog filter create --include-all false --provider ibm_created --exclude-list appid ``` {: codeblock} ## Next steps {: #next-acctfilter} A user in the account validates that they can view all catalog offerings except {{site.data.keyword.appid_short_notm}}. See [Validating the account-level catalog filters](/docs/account?topic=account-validate-acctfilter) for more information. ### Providing feedback {: #survey-acctfilters} We put together a [survey](https://airtable.com/shrOeKPjUz5bzw02c){: external} specifically about this tutorial. We'd love to know what you think!
Python
UTF-8
1,339
2.6875
3
[]
no_license
# -*- coding:UTF-8 -*- import socket,os,hashlib import time from crypt import PrpCrypt server = socket.socket() server.bind(('0.0.0.0',9999)) server.listen() while True: conn,addr = server.accept() print("new conn:",addr) while True: print("server on....") data = conn.recv(1024) if not data: print("客户端已断开") break cmd,file = data.decode().split() print(file) if os.path.isfile(file): #是否是文件 temporary = PrpCrypt(file, '1234567891011121')#传递文件名和密钥 filename = temporary.encrypt_output(file)#加密文件 f = open(filename,"rb") m = hashlib.md5() #创建md5校验 file_size = os.stat(filename).st_size #获取文件大小 conn.send(str(file_size).encode()) #发送文件大小 conn.recv(1024) #等待ACK交互防止粘包 for line in f: m.update(line) #递增加密文件 conn.send(line) print("file md5",m.hexdigest()) #打印16进制md5 f.close() conn.send(m.hexdigest().encode()) print("send done") server.close()
Markdown
UTF-8
3,963
2.96875
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
# _Super Battle Game_ #### _This is a RPG that will allow a person to battle their inner child. | Feb 5th. 2020_ #### By _**Alex Skreen & Dusty McCord**_ [link to demo site coming](#) ## Description This was a Epicodus class project. It is an RPG that allows a user to create a character and battle another character. It uses webpack and Jest testing. ## Setup/Installation Requirements _Make sure you have [git version control](https://git-scm.com/downloads) installed on your computer._ 1. find the green 'Clone or Download' button and copy the link 2. open terminal and type... **Windows** ```sh cd desktop ``` Mac & linux ```sh cd ~/Desktop ``` 3. in terminal type '_git clone {link to repository}_ ' ```sh git clone Link-Here ``` 4. navigate to the new folder that was created on your desk ```sh cd folder name ``` 5. run npm install ```sh npm install ``` 6. run development server ```sh npm run start ``` 7. edit files in '/src' to make changes to the project. 8. enjoy this project ## Specs ### Behavior Driven Development Spec List Behavoir | Input | Output :---------|:------:|:------: |1 - The program allows a user to choose a Golden girl and will return a golden girl character | Pick Rose | Rose with standard properties. | |2 - The program will allow a user to allocate points to armor and health based on a total of 100 points. | 70 to HP, 30 to Armor | 70 to HP, 30 to Armor | |3 - The program will allow user 2 to select a character and allocate points. | Rose + points | Rose + points | |4 - The program will allow user 1 to start their turn by drawing from inventory or holding current inventory | Draw | randomly selected new item | |5 - The program will allow user 1 to nap or attack | attack | attack user 2 | |6 - The program will allow a user to win or lose an attack based off of an advanced algorithm | Roll Dice | Win | |7 - If the user wins the HP score of the attacker will go down by 5 and the loser will go down by the attack total | attack 80 | User 1 (HP - 5), User 2 (HP - 80) | |8 - The program will allow user 2 to draw or hold | hold | hold | |9 - The program will allow user 2 to nap or attack. If nap the user heals | nap | heal 5 HP | ## Support _The software is provided as is. It might work as expected - or not. Use at your own risk._ ## Built With * [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) - Simple Scaffolding * [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) - Used for interactivity in the page * [jQuery](https://jquery.com/) - Used to interact with the DOM * [Bootstrap 4.4](https://getbootstrap.com/) - Used for styling * [webpack](https://webpack.js.org/) * [Sass](https://sass-lang.com/) * [ESLint](https://eslint.org/) * [Node.js](https://nodejs.org/en/) * [Uglifyjs](https://www.uglifyjs.net/) * [Jest](https://jestjs.io/) ## Useful tools * [free icons @ icons8](https://icons8.com/) * [free icons @ fontawesome](https://fontawesome.com/) --- * [Old School Gifs Search](https://gifcities.org/) * [free images @ unsplash](https://unsplash.com/) * **_source.unsplash.com_ will return a random image at a desired size by simply calling the size after the url followed by a '?' and a keyword. Example below** * _https://source.unsplash.com/400x400/?cat_ * http://unsplash.it/500/500 - This will just return a random image the size of 500x500 --- * [Flex-box Cheat Sheet](http://yoksel.github.io/flex-cheatsheet/) * [CSS Grid Cheat Sheet](http://grid.malven.co/) --- * [CSS Gradient BG Generator](https://mycolor.space/gradient) * [CSS Basic Gradient Generator](https://cssgradient.io/) --- * [CSS Dropshadow Generator](https://cssgenerator.org/box-shadow-css-generator.html) ### License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details Copyright (c) 2020 **_Dusty McCord_**
C++
UTF-8
341
2.953125
3
[ "MIT" ]
permissive
#include <iostream> int main(){ // outer block int n(5); // n created and initialized here { // begin nested block double d(4.0); // d created and initialized here } // d goes out of scope and is destroyed here // d can not be used here because it was already destroyed! return 0; } // n goes out f scope and is destroyed here
C#
UTF-8
289
2.546875
3
[ "MIT" ]
permissive
// CustomItemProperty using System; [Serializable] public struct CustomItemProperty { public string customName; public string customType; public object customValue; public override string ToString() { return $"Name: {customName}, Type: {customType}, Value: {customValue}"; } }
Java
UTF-8
428
2.28125
2
[]
no_license
package com.ds.swagger.service.beans; public class AbstractService { private String serviceName; public AbstractService(String serviceName) { this.serviceName = serviceName; System.out.println("----> " +this.serviceName); } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } }
Java
UTF-8
2,608
1.835938
2
[]
no_license
/******************************************************************************* * Copyright (c) 2017 * All rights reserved. * * Contributors: * <mrostren> Initial code *******************************************************************************/ /** */ package fr.rostren.tracker.provider.dev; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.ecore.EObject; import fr.rostren.tracker.Operation; import fr.rostren.tracker.TrackerFactory; import fr.rostren.tracker.TrackerPackage; import fr.rostren.tracker.provider.CheckingAccountItemProvider; /** * This is the item provider adapter for a * {@link fr.rostren.tracker.CheckingAccount} object. <!-- begin-user-doc --> * <!-- end-user-doc --> */ public class CheckingAccountItemProviderDev extends CheckingAccountItemProvider { /** * This constructs an instance from a factory and a notifier. <!-- * begin-user-doc --> <!-- end-user-doc --> * @param adapterFactory the {@link AdapterFactory} */ public CheckingAccountItemProviderDev(AdapterFactory adapterFactory) { super(adapterFactory); } @Override public Collection<?> getChildren(Object object) { Collection<?> children=super.getChildren(object); List<Operation> operations=children.stream().filter(child -> child instanceof Operation).map(child -> (Operation)child).collect(Collectors.toList()); Collections.sort(operations, (op1, op2) -> op1.getDate().compareTo(op2.getDate())); return operations; } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s * describing the children that can be created under this object. <!-- * begin-user-doc --> <!-- end-user-doc --> */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { newChildDescriptors.add(createChildParameter(TrackerPackage.Literals.CHECKING_ACCOUNT__OPERATIONS, TrackerFactory.eINSTANCE.createCredit((EObject)object))); newChildDescriptors.add(createChildParameter(TrackerPackage.Literals.CHECKING_ACCOUNT__OPERATIONS, TrackerFactory.eINSTANCE.createDebit((EObject)object))); newChildDescriptors.add(createChildParameter(TrackerPackage.Literals.CHECKING_ACCOUNT__OPERATIONS, TrackerFactory.eINSTANCE.createIncoming((EObject)object))); newChildDescriptors.add(createChildParameter(TrackerPackage.Literals.CHECKING_ACCOUNT__OPERATIONS, TrackerFactory.eINSTANCE.createOutgoing((EObject)object))); } }
C#
UTF-8
879
2.71875
3
[]
no_license
using System; using System.Globalization; using Gtk; //using System.Text.RegularExpressions; namespace calendar { public partial class AddWindowView { public long GetTime(){ return this.time; } public long GetDistance(){ Console.Write ("dist "+distance); return this.distance; } public long GetStart(){ return this.start; } private int start; public void getSessionData () { string initEntry = this.en4.Text; var distanceEntry = this.en2.Text; var timeEntry = this.en3.Text; string[] hoursAndMinutes = initEntry.Split (':'); var minutes = Convert.ToInt32(hoursAndMinutes[1]); var hours = Convert.ToInt32(hoursAndMinutes[0]); var seconds = hours * 3600 + minutes * 60; this.start = seconds; this.distance = int.Parse(distanceEntry); this.time = 60 * Convert.ToInt64 (timeEntry); } } }
Python
UTF-8
4,169
3.078125
3
[]
no_license
# -*- coding: utf-8 -*- # @Time : 17-12-7 下午5:27 # @Author : J.Y.Zhang # @File : PreFeatureEngineering.py # @Description: import pandas as pd import numpy as np from collections import Counter def dealNan(df): # 票价Nan setting silly values to nan df.Fare = df.Fare.map(lambda x: np.nan if x == 0 else x) # 未知的船舱号 df.Cabin = df.Cabin.fillna('Unknown') # 年龄平均填充 meanAge = np.mean(df.Age) df.Age = df.Age.fillna(meanAge) # 登船口 众数填充 word_counts = Counter(df.Embarked) mode = word_counts.most_common() modeEmbarked = mode[0][0] df.Embarked = df.Embarked.fillna(modeEmbarked) #modeEmbarked = mode(int(df.Embarked)) #df.Embarked = df.Embarked.fillna(modeEmbarked) # Fare per person return df def extractDeck(df): # Turning cabin number into Deck cabin_list = ['A', 'B', 'C', 'D', 'E', 'F', 'T', 'G', 'Unknown'] df['Deck'] = df['Cabin'].map(lambda x: substrings_in_string(x, cabin_list)) return df def extractFamilysize(df): # Creating new family_size column df['Family_Size'] = df['SibSp'] + df['Parch'] return df def substrings_in_string(big_string, substrings): for substring in substrings: if big_string.find(substring) != -1: return substring print(big_string) return np.nan def extractTitle(df): # creating a title column from name title_list = ['Mrs', 'Mr', 'Master', 'Miss', 'Major', 'Rev', 'Dr', 'Ms', 'Mlle', 'Col', 'Capt', 'Mme', 'Countess', 'Don', 'Jonkheer'] df['Title'] = df['Name'].map(lambda x: substrings_in_string(x, title_list)) # replacing all titles with mr, mrs, miss, master def replace_titles(x): title = x['Title'] if title in ['Don', 'Major', 'Capt', 'Jonkheer', 'Rev', 'Col']: return 'Mr' elif title in ['Countess', 'Mme']: return 'Mrs' elif title in ['Mlle', 'Ms']: return 'Miss' elif title == 'Dr': if x['Sex'] == 'Male': return 'Mr' else: return 'Mrs' else: return title df['Title'] = df.apply(replace_titles, axis=1) #参数一是函数 参数二是函数应用的轴 0 是每一列 1 是每一行 return df def preFeatureEngineering(train,test): # nan train = dealNan(train) test = dealNan(test) # 名字里身份的特征 train = extractTitle(train) test = extractTitle(test) # 家庭规模 train = extractDeck(train) test = extractDeck(test) # 客舱位置 train = extractFamilysize(train) test = extractFamilysize(test) data_type_dict = {'Pclass': 'ordinal', 'Sex': 'nominal', 'Age': 'numeric', 'Fare': 'numeric', 'Embarked': 'nominal', 'Title': 'nominal', 'Deck': 'nominal', 'Family_Size': 'ordinal'} return [train, test, data_type_dict] def discretise_numeric(train, test, data_type_dict, no_bins= 10): N=len(train) M=len(test) test=test.rename(lambda x: x+N) joint_df=train.append(test) for column in data_type_dict: if data_type_dict[column]=='numeric': joint_df[column]=pd.qcut(joint_df[column], 10) data_type_dict[column]='ordinal' train=joint_df.ix[range(N)] test=joint_df.ix[range(N,N+M)] return train, test, data_type_dict if __name__ == "__main__": trainpath = 'train.csv' testpath = 'test.csv' traindf = pd.read_csv(trainpath) testdf = pd.read_csv(testpath) #print(traindf.head(10)) # traindf, testdf, data_type_dict = preFeatureEngineering(traindf,testdf) traindf, testdf, data_type_dict = discretise_numeric(traindf, testdf, data_type_dict) print(traindf.head(10)) traindf.to_csv('traindf.csv', index=False) testdf.to_csv('testdf.csv', index= False) # create a submission file for kaggle predictiondf = pd.DataFrame(testdf['PassengerId']) predictiondf['Survived']=[0 for x in range(len(testdf))] predictiondf.to_csv('prediction.csv',header=None, index=False)
Python
UTF-8
2,661
3.796875
4
[]
no_license
import re class Step(object): def __init__(self, name): self.name = name self.relies_on = set() self.finished = True def __repr__(self): """Helps me debug a bit""" return self.name class OrderOfOps(object): def __init__(self): self.steps = dict() self.finished_steps = list() def add_step(self, step, relies_on=''): """Just build the steps and specify if they rely on another step before being started""" if step not in self.steps: self.steps[step] = Step(step) if relies_on: self.steps[step].relies_on.add(relies_on) self.steps[step].finished = False def determine_order(self): # so you can track when youre done original_step_len = len(self.steps) while len(self.finished_steps) != original_step_len: # Alphabetically sort (important) for key in sorted(self.steps): if self.steps[key].finished: # marks everything appropriately so the next iteration picks up on the changes self.finished_steps.append(key) del self.steps[key] # Since we just finished a step, it's important to go through the other steps specify that # they no longer rely on the finished step for step in self.steps.values(): if key in step.relies_on: step.relies_on.remove(key) if not step.relies_on: step.finished = True break # all there is return ''.join(self.finished_steps) if __name__ == '__main__': """It was a bit tricky to figure this one out. It took a bit of brainpower to map out the "business rules" for this problem. """ with open('./input.txt') as f: data = f.read().splitlines() order_of_ops = OrderOfOps() # build out all of the steps and which ones require what. Then you can determine what order they need to # happen to be finished. pattern = re.compile(r'Step (?P<relies_on>[A-Z]) must be finished before step (?P<step>[A-Z])') for line in data: m = re.match(pattern, line) # two steps are either created or referenced in every line of the input.. so you have to create or update both step = m.group('step') relies_on = m.group('relies_on') order_of_ops.add_step(relies_on) order_of_ops.add_step(step, relies_on) print(step, relies_on) print(order_of_ops.determine_order())
Java
UTF-8
21,309
1.640625
2
[ "Apache-2.0" ]
permissive
package org.apache.batik.ext.awt.image.renderable; public interface TurbulenceRable extends org.apache.batik.ext.awt.image.renderable.FilterColorInterpolation { void setTurbulenceRegion(java.awt.geom.Rectangle2D turbulenceRegion); java.awt.geom.Rectangle2D getTurbulenceRegion(); int getSeed(); double getBaseFrequencyX(); double getBaseFrequencyY(); int getNumOctaves(); boolean isStitched(); boolean isFractalNoise(); void setSeed(int seed); void setBaseFrequencyX(double xfreq); void setBaseFrequencyY(double yfreq); void setNumOctaves(int numOctaves); void setStitched(boolean stitched); void setFractalNoise(boolean fractalNoise); java.lang.String jlc$CompilerVersion$jl7 = "2.7.0"; long jlc$SourceLastModified$jl7 = 1471188907000L; java.lang.String jlc$ClassType$jl7 = ("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" + "r/i27T+0deVlHCEAAA=="); java.lang.String jlc$CompilerVersion$jl5 = "2.7.0"; long jlc$SourceLastModified$jl5 = 1471188907000L; java.lang.String jlc$ClassType$jl5 = ("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"); }
Java
UTF-8
5,833
2.359375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.marksmana.beans; import com.marksmana.controllers.ApiHelper; import com.marksmana.info.SingleInformation; import com.marksmana.models.Score; import com.marksmana.models.ScoreLog; import com.marksmana.models.scoresbo.ScoresGroup; import com.marksmana.models.scoresbo.ScoresRecord; import com.marksmana.models.scoresbo.SingleScore; import com.marksmana.utils.Json; import java.io.Serializable; import java.util.ArrayList; import java.util.Hashtable; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author Giang */ @ManagedBean @RequestScoped public class ScoresBean implements Serializable { private int id; private ArrayList<String[]> list; private ScoresRecord record; /** * Creates a new instance of ScoresBean */ public ScoresBean() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public ArrayList<String[]> getList() { return list; } public void setList(ArrayList<String[]> list) { this.list = list; } public ScoresRecord getRecord() { return record; } public void setRecord(ScoresRecord record) { this.record = record; } public String doLoadScore(int studentId, String logId) { try { id = Integer.parseInt(logId); } catch (NumberFormatException ex) { return "student"; } loadArchive(id, studentId); return "logview"; } public String doLoadCurrent(int studentId) { loadCurrentScores(studentId); return "logview"; } private ArrayList<String[]> loadCurrentScores(int studentId) { list = new ArrayList<>(); int minCoeff = getMinCoeff(); int maxCoeff = getMaxCoeff(); try { String[] ctx = null; int coeff; Score[] scores = ApiHelper.readFromApi("student/" + studentId + "/scores", Score[].class); for (Score s : scores) { System.out.println(s.getScore()); } System.out.println(scores); Hashtable<Integer, String> subjects = new Hashtable<>(); // Init subjects for (Score s : scores) { subjects.put(s.getSubjectId().getId(), s.getSubjectId().getName()); } // Table header ctx = new String[maxCoeff - minCoeff + 1 + 1]; ctx[0] = "Môn học"; for (int i = minCoeff; i <= maxCoeff; i++) { ctx[i] = "Hệ số " + i; } list.add(ctx); // Table body for (Integer key : subjects.keySet()) { ctx = new String[maxCoeff - minCoeff + 1 + 1]; // Cols needed for scores = max - min + 1 plus 1 col for subject name ctx[0] = subjects.get(key); for (Score s : scores) { if (s.getSubjectId().getId().equals(key)) { coeff = Integer.parseInt(s.getCoefficient() + ""); if (ctx[coeff] == null) { ctx[coeff] = ""; } ctx[coeff] += s.getScore() + " ; "; } } list.add(ctx); } } catch (Exception ex) { } return list; } private ArrayList<String[]> loadArchive(int id, int studentId) { list = new ArrayList<>(); int minCoeff = getMinCoeff(); int maxCoeff = getMaxCoeff(); try { ScoreLog[] logs = ApiHelper.readFromApi("student/" + studentId + "/logs", ScoreLog[].class); for (ScoreLog log : logs) { if (log.getId() == id) { String[] ctx; // Load scores record = Json.DeserializeObject(log.getScores(), ScoresRecord.class); // Table header ctx = new String[maxCoeff - minCoeff + 1 + 2]; ctx[0] = "Môn học"; for (int i = minCoeff; i <= maxCoeff; i++) { ctx[i] = "Hệ số " + i; } ctx[ctx.length-1] = "Trung bình"; list.add(ctx); // Table body for (ScoresGroup sg : record.scores) { ctx = new String[maxCoeff - minCoeff + 1 + 2]; ctx[0] = sg.subject; ctx[ctx.length-1] = sg.avg+""; for (SingleScore ss : sg.scores) { if (ctx[ss.coeff]==null) { ctx[ss.coeff] = ""; } ctx[ss.coeff] += ss.score+" ; "; } list.add(ctx); } break; } } } catch (Exception ex) { ex.printStackTrace(); } return list; } private int getMinCoeff() { SingleInformation si; try { si = ApiHelper.readFromApi("prop/min_coeff", SingleInformation.class); return Integer.parseInt(si.getValue()); } catch (Exception ex) { return 0; } } private int getMaxCoeff() { SingleInformation si; try { si = ApiHelper.readFromApi("prop/max_coeff", SingleInformation.class); return Integer.parseInt(si.getValue()); } catch (Exception ex) { return 0; } } }
Shell
UTF-8
1,087
3.375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/bash # fasttext.bash: run experiment with fasttext # usage: fasttext.bash [ -w ] # 20180118 erikt(at)xs4all.nl FASTTEXTDIR=$HOME/software/fastText FASTTEXT=$FASTTEXTDIR/fasttext WIKIVEC=$FASTTEXTDIR/wiki.nl.vec EVAL=$HOME/projects/online-behaviour/machine-learning/eval.py TRAIN=TRAIN-TEST.fasttext TEST=TEST.fasttext TMPFILE=fasttext.bash.$$.$RANDOM MODEL=$TMPFILE.model DIM=300 MINCOUNT=5 USEWIKIVEC="" while getopts ":T:t:w" opt; do case $opt in T) TRAIN=$OPTARG ;; t) TEST=$OPTARG ;; w) USEWIKIVEC=1 ;; \?) echo $COMMAND ": invalid option " $opt ;; esac done if [ "$USEWIKIVEC" != "" ] then $FASTTEXT supervised -input $TRAIN -output $MODEL -dim $DIM \ -minCount $MINCOUNT -pretrainedVectors $WIKIVEC > /dev/null 2> /dev/null else $FASTTEXT supervised -input $TRAIN -output $MODEL -dim $DIM \ -minCount $MINCOUNT > /dev/null 2> /dev/null fi $FASTTEXT predict $MODEL.bin $TEST | tee $TEST.labels |\ paste -d' ' - $TEST | cut -d' ' -f1,2 |\ sed 's/^\(.*\) \(.*\)$/\2 \1/' | $EVAL rm -f $MODEL.bin exit 0
Markdown
UTF-8
6,651
2.890625
3
[]
no_license
#Blog 2: Five Weeks Over, Two Weeks Left.# Five weeks are over already, yet I feel like the internship has barely started. Since the submission for Blog 1, the interns and I have gone on two field trips to New Brighton State Beach and Pinnacles National Park. ##New Brighton State Beach## I finally got to visit New Brighton State Beach! Last year, I did not attend due to an out-of-state competition. Early morning, we drove through the fog and mountains down to Santa Cruz, where the beach is located. Noel noted that we would be searching for fossils from the border of the Miocene and the Pliocene, about 5 million years ago. Originally expecting to see a few whale fossils scattered on the sand, I was overwhelmed (in a positive sense) by the abundance of fossils on the cliff beds, rocks, and in the sand. My favorite part was being able to apply my knowledge of bivalves and gastropods, which I had learned through Noel’s lab the week before, to identify fossils. I was also surprised by how well-preserved some shells were, as indicated by their pearly-white or iridescent exterior. I enjoyed seeing the various wildlife, like purple-green crabs, sea anemones, kelp forests, and (terrifyingly huge) isopods. After about one hour of strolling aside the cliff wall and exploring the fossils, we were forced to head back by the rising tide which was wetting our feet. ![Fossils Collected from Beach] (Images/Blog_Beach.jpg) At the beach, I got to interact more with the individual interns, with whom I ate lunch. After lunch, we headed to the UCSC Marine Discovery Center, which had a beautiful view of the ocean and two large whale skeletons. I had never known about vestigial structures in the whale which indicate that whales used to live on land! While I love exploring the beach, I was hoping we would see tide pools. I LOVE TIDEPOOLS. I was recently in Washington State, where I participated in a tour with a naturalist. She took me to a quiet tide pool in Port Angeles, where I saw sea anemone, mussels, chiten, crabs, kelp, and sea worms everywhere. Thanks to Jenny and Noel, I now know where tidepools are in the Bay Area and how to track tides with an app, activities I will surely do once SEYI is over. ![View from Marine Discovery Center] (Images/Blog_MSI.jpg) ##Pinnacles field trip## Only one week later was camping, and I was so excited! Unfortunately, I forgot, from the year before, about the scorching 100-degree heat. We started our trip by searching the side of the highway for fossils of tiny crabs and bivalves; who knew you could find evidence of ancient Geologic Time from the road-side? Upon arriving at the Pinnacles campsite, the interns and I immediately left to hike on a trail that leads to caves. Sadly, the caves were closed (*womp womp*), so we headed on a different path that leads to a reservoir. The area reminded me of Zion Canyon, with its tall, red rock formation. The rocks we saw were formed from a volcanic eruption; I kept wondering how the rocks stuck together despite the presence of numerous cracks cutting into the rock wall. After a trek through tunnels and up steep stairs, we finally arrived at the reservoir. While this picturesque reservoir seemed out of place compared to the surrounding cliffs, I was mesmerized by its beauty and abundance of wildlife. Dragonflies colored a vibrant blue and red, in addition to thin damsel flies, zoomed across the grass next to the reservoir. We also saw a frog, garter snake, and an assortment of birds like the turkey vulture and quails, whose flying sounded like a storm! ![Rock Face from Pinnacles] (Images/Blog_Volcanic.jpg) ![Reservoir from Pinnacles] (Images/Blog_Reservoir.jpg) That same evening, we enjoyed delicious chicken fajitas. Similar to last year, a swarm of wasps buzzed around the meat; however, I am glad for I may have slightly conquered my fear of wasps. After having them buzz around me so much, I realized that wasps are less of a danger and more of a nuisance. At 11 PM, the Biodiversity group gathered outside in the darkness and watched for shooting stars on a beautiful, cloudless night. The next morning, after only one uncomfortable hour of sleep, Ameya and I awoke at 5 AM and cleaned up our tent and belongings in preparation for the hike. Despite the sores from the hike the day before, I surprisingly was energized and was ready to tackle the hike. The year before, the hike was extremely tough. Despite the excruciating heat and lack of water, I tried to keep pace with the front of the group, which made me very nauseous by the time I reached the top. This year, the experience was very different. I realized that I should go at my own pace and take breaks whenever I found bits of shade. I also brought three bottles of water and tangerines to quench my thirst. I was happy that a few other Biodiversity interns kept pace with me, as we encouraged each other to reach the top. As always, the view at the summit was breathtaking. I always find it so amazing that the exact same valley and summit exists in Southern California, due to the San Andreas Fault which separated the volcano. On the way down, the hike felt unexpectedly much longer than I had imagined. After rolling my ankle five times and many complaints about why we weren’t there yet (*Thank you Ameya and Noel for bearing through my comments*), I was relieved to reach the bottom safely. ##Project Progress## Within a couple weeks, Noah and I have made significant progress on our portion of the research paper. We are analyzing how the motility level of marine genera relates to body size evolution and extinction selectivity across time. We have made seven figures, including two boxplots showing body size vs motility level, a plot showing the proportion of motile and nonmotile genera overtime, numerous color-coded plots showing the stratigraphic ranges of genera, and plots of extinction rate and selectivity. We are very proud of our plots, and will be presenting them to Noel and Biodiversity interns for feedback. From our analysis so far, we find that the proportion of motile genera tend to decrease over-time, with mass extinctions causing transformative drops. We also learned that motile genera tend to have a larger body size, though the difference is only by an order of magnitude. With the team’s feedback, we hope to improve the design of our graphs and conduct more analyses. ##Well-Deserved Thank You’s## Thank you Jenny, Noel, and Nic (and anyone else involved) for arranging these awesome and immersive field trips. Thank you Noel for all your help in debugging code and understanding the results.
PHP
UTF-8
751
2.59375
3
[]
no_license
<?php namespace Popo1h\PhaadminProvider\ActionLoader; use Popo1h\PhaadminCore\Action; use Popo1h\PhaadminProvider\ActionLoader; class SimpleActionLoader extends ActionLoader { /** * @var Action[] */ private $actionMap; public function __construct() { $this->actionMap = []; } /** * @param Action $action */ public function registerAction(Action $action) { $this->actionMap[$action::getName()] = $action; } public function load($actionName) { if (!isset($this->actionMap[$actionName])) { return null; } return $this->actionMap[$actionName]; } public function getActionMap() { return $this->actionMap; } }
Java
UTF-8
3,193
1.59375
2
[]
no_license
package org.pdtextensions.core.ui.preferences; /** * Constant definitions for plug-in preferences */ public class PreferenceConstants { public static final String ENABLED = "enabled"; //$NON-NLS-1$ public static final String LINE_ALPHA = "line_alpha"; //$NON-NLS-1$ public static final String LINE_STYLE = "line_style"; //$NON-NLS-1$ public static final String LINE_WIDTH = "line_width"; //$NON-NLS-1$ public static final String LINE_SHIFT = "line_shift"; //$NON-NLS-1$ public static final String LINE_COLOR = "line_color"; //$NON-NLS-1$ public static final String DRAW_LEFT_END = "draw_left_end"; //$NON-NLS-1$ public static final String DRAW_BLANK_LINE = "draw_blank_line"; //$NON-NLS-1$ public static final String SKIP_COMMENT_BLOCK = "skip_comment_block"; //$NON-NLS-1$ public static final String CODE_TEMPLATES_KEY = "org.pdtextensions.core.ui.formatter.text.custom_code_templates"; /** * php cs fixer */ public static final String PREF_PHPCS_OPT_INDENTATION = "phpcs_indentation"; public static final String PREF_PHPCS_USE_DEFAULT_FIXERS = "phpcs_use_default_fixers"; public static final String PREF_PHPCS_PHAR_LOCATION = "phpcs_phar_location"; public static final String PREF_PHPCS_PHAR_NAME = "phpcs_phar_name"; public static final String PREF_PHPCS_CUSTOM_PHAR_LOCATIONS = "phpcs_custom_phar_locations"; public static final String PREF_PHPCS_CUSTOM_PHAR_NAMES = "phpcs_custom_custom_phar_names"; public static final String PREF_PHPCS_CONFIG = "phpcs_config"; public static final String PREF_PHPCS_OPTION_INDENTATION = "phpcs_option_indentation"; public static final String PREF_PHPCS_OPTION_LINEFEED = "phpcs_option_linefeed"; public static final String PREF_PHPCS_OPTION_TRAILING_SPACES= "phpcs_option_trailing_spaces"; public static final String PREF_PHPCS_OPTION_UNUSED_USE = "phpcs_option_unused_use"; public static final String PREF_PHPCS_OPTION_PHP_CLOSING_TAG = "phpcs_option_php_closing_tag"; public static final String PREF_PHPCS_OPTION_SHORT_TAG = "phpcs_option_short_tag"; public static final String PREF_PHPCS_OPTION_RETURN = "phpcs_option_return"; public static final String PREF_PHPCS_OPTION_VISIBILITY = "phpcs_option_visibility"; public static final String PREF_PHPCS_OPTION_BRACES = "phpcs_option_braces"; public static final String PREF_PHPCS_OPTION_PHPDOC_PARAMS = "phpcs_option_phpdoc_params"; public static final String PREF_PHPCS_OPTION_EOF_ENDING = "phpcs_option_eof_ending"; public static final String PREF_PHPCS_OPTION_EXTRA_EMPTY_LINES = "phpcs_option_extra_empty_lines"; public static final String PREF_PHPCS_OPTION_INCLUDE = "phpcs_option_include"; public static final String PREF_PHPCS_OPTION_PSR0 = "phpcs_option_psr0"; public static final String PREF_PHPCS_OPTION_CONTROLS_SPACE = "phpcs_option_controls_space"; public static final String PREF_PHPCS_OPTION_ELSEIF = "phpcs_option_elseif"; public static final String PREF_PHPCS_CONFIG_DEFAULT = "phpcs_config_default"; public static final String PREF_PHPCS_CONFIG_MAGENTO = "phpcs_config_magento"; public static final String PREF_PHPCS_CONFIG_SF20 = "phpcs_config_sf20"; public static final String PREF_PHPCS_CONFIG_SF21 = "phpcs_config_sf21"; }
C#
UTF-8
1,624
3.09375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Xml; using Bookmarks.Data; namespace SimpleBookmarksSearch { public class SimpleBookmarksSearchMain { static void Main(string[] args) { BookmarksEntities context = new BookmarksEntities(); using (context) { string simpleSearchXmlPath = @"..\..\simple-query.xml"; XmlDocument doc = new XmlDocument(); doc.Load(simpleSearchXmlPath); string xpathQuery = "query"; XmlNode bookmarkNode = doc.SelectSingleNode(xpathQuery); string username = null; XmlNode usernameNode = bookmarkNode.SelectSingleNode("username"); if (usernameNode != null) { username = usernameNode.InnerText; } string tag = null; XmlNode tagNode = bookmarkNode.SelectSingleNode("tag"); if (tagNode != null) { tag = tagNode.InnerText; } IEnumerable<Bookmark> bookmarks = BookmarksDAO.FindBookmarksByUsernameAndTag(context, username, tag); if (bookmarks.Count() > 0) { foreach (var bookmark in bookmarks) { Console.WriteLine(bookmark.URL); } } else { Console.WriteLine("Nothing found"); } } } } }
C++
UTF-8
219
3.21875
3
[]
no_license
#include <iostream> using namespace std; int main(){ //printing the multiple lines cout << "first statement"; cout << "second statement"; //here both the lines are print in a straight line return 0; }
Python
UTF-8
1,677
3.15625
3
[ "MIT" ]
permissive
import numpy as np from grabscreen import grab_screen import cv2 import time from getkeys import key_check import os def keys_to_output(keys): ''' Convert keys to a ...multi-hot... array [A,W,D] boolean values. ''' output = [0,0,0] if 'A' in keys: output[0] = 1 elif 'D' in keys: output[2] = 1 else: output[1] = 1 return output i=0 training_data=[] def new(): global i file_name = 'dataset/'+str(i)+'_training_data.npy' i=i+1 return file_name def main(): x=0 for i in list(range(10))[::-1]: print("Dataset is creating in",i+1, "Second") time.sleep(1) last_time = time.time() while True: global trainin_data # Grab Screen of your top left corner of 800 X 600 resolution screen = grab_screen(region=(0,0,800,600)) # Convert frame into Gray Scale screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY) # Resize Frame into 200 X 150 screen = cv2.resize(screen,(200,150)) # Check Which key is pressed at that frame keys = key_check() output = keys_to_output(keys) # Append Frame and key into list training_data.append([screen, output]) print(len(training_data),'Frame took {} seconds'.format(time.time() - last_time)) last_time = time.time() if len(training_data)%1000 ==0: # Create New file and save 1000 frame into .npy file np.save(new(), training_data) print(x,"SAVED") x = x + 1 training_data.clear() if __name__ == "__main__": main()
C#
UTF-8
1,039
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace CustomProgressBar { public partial class ProgressBarImage : UserControl { public ProgressBarImage() { InitializeComponent(); } protected double percent = 0.0f; [Category("GNR092")] [DefaultValue(true)] public double Valor { get { return percent; } set { if (value < 0) value = 0; else if (value > 100) value = 100; percent = value; PB_bar.Size = new Size((int)((value / 100) * Width), Height); Invalidate(); } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; } } }
Python
UTF-8
1,105
3.484375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 4 09:19:42 2021 @author: sidtrip """ # inititallizse C to zero # need to consider twom matrices A and B # need to find the dot product of two lsits # need to pick ith tow and jth column in matrix def initialize_mat(dim): #code verified, works on test case C = [] for i in range(dim): C.append([]) for j in range(dim): C[i].append(0) return C def dot_product(u, v): dim = len(u) ans = 0 for i in range(dim): ans += (u[i]*v[i]) return ans def row(M, i): l = M[i] return l def column(M,j): dim = len(M) l = [] for i in range(dim): l.append(M[i][j]) return l def mat_mul(A,B): dim = (len(A)) C = initialize_mat(dim) for i in range(dim): for j in range(dim): C[i][j] = dot_product(row(A,i),column(B,j)) return C def main(): A = [[1,2,3],[4,5,6],[7,8,9]] B = [[1,2,1],[3,1,7],[6,2,3]] C = mat_mul(A,B) for i in range(len(A)): print(C[i])
JavaScript
UTF-8
706
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
var musicians = []; var instruments = []; var facts = []; var aNumber; function theBeatlesPlay(musicians, instruments) { var emptyArray = []; for( let i = 0 ; i < musicians.length ; i++ ) { emptyArray[i] = `${musicians[i]} plays ${instruments[i]}`; } return emptyArray; } function johnLennonFacts(facts) { var shoutFacts = []; var count = 0; while ( count < facts.length ) { shoutFacts.push(`${facts[count]}!!!`); count++; } return shoutFacts; } function iLoveTheBeatles(aNumber) { var loveBeatlesArray = []; do{ loveBeatlesArray.push(`I love the Beatles!`); aNumber++; } while( aNumber < 15 ); return loveBeatlesArray; }
Markdown
UTF-8
3,260
2.671875
3
[]
no_license
--- lastUpdated: "03/26/2020" title: "Module-related Functions" description: "For an overview of the Momentum module API see Section 1 3 1 Module API and for an overview of hooks see Section 1 3 2 Hooking API..." --- | Name | Description | |---------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------| | [EC_DECLARE_HOOK](/momentum/3/3-api/apis-ec-declare-hook) | Runtime hooking | | [ec_module_manifest_iter_clone](/momentum/3/3-api/apis-ec-module-manifest-iter-clone) | clone a module manifest iterator | | [ec_module_manifest_iter_destroy](/momentum/3/3-api/apis-ec-module-manifest-iter-destroy) | destroy a module manifest iterator | | [ec_module_manifest_iter_init](/momentum/3/3-api/apis-ec-module-manifest-iter-init) | initialize a module manifest iterator | | [ec_module_manifest_iter_next](/momentum/3/3-api/apis-ec-module-manifest-iter-next) | advances a module manifest iterator | | [ec_module_manifest_refresh](/momentum/3/3-api/apis-ec-module-manifest-refresh) | refreshes the manifest list | | [ec_module_manifest_value_as_dict](/momentum/3/3-api/apis-ec-module-manifest-value-as-dict) | retrieves a dictionary of manifest values for a named module | | [ec_module_manifest_value_as_list](/momentum/3/3-api/apis-ec-module-manifest-value-as-list) | retrieves a list of manifest values for a named module | | [ec_module_manifest_value_as_string](/momentum/3/3-api/apis-ec-module-manifest-value-as-string) | retrieves a manifest value for a named module | | [ec_module_resolve_capability](/momentum/3/3-api/apis-ec-module-resolve-capability) | resolve a capability by loading modules | | [module_add_hook_first](/momentum/3/3-api/apis-module-add-hook-first) | Add a hook as the first hook | | [module_add_hook_last](/momentum/3/3-api/apis-module-add-hook-last) | Add a hook as the last hook | | [module_get_hook_array_from_transaction](/momentum/3/3-api/apis-module-get-hook-array-from-transaction) | Get the hooks associated with the current transaction | | [module_get_hook_head](/momentum/3/3-api/apis-module-get-hook-head) | Fetch the arguments for a hook | For an overview of the Momentum module API see [“Module API”](/momentum/3/3-api/arch-primary-apis#arch.module) and for an overview of hooks see [“Hooking API”](/momentum/3/3-api/arch-primary-apis#arch.hooking).
Java
UTF-8
4,300
2.03125
2
[]
no_license
package com.example.android.firebase; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.SimpleCursorTreeAdapter; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; public class MainActivity extends AppCompatActivity { EditText email_text,passowrd_text; Button login,resetPassword,signup; ProgressBar progressBar; FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = (ProgressBar)findViewById(R.id.progressBar); email_text = (EditText)findViewById(R.id.email); passowrd_text = (EditText)findViewById(R.id.password); resetPassword = (Button) findViewById(R.id.btn_reset_password); login = (Button)findViewById(R.id.sign_in_button); signup = (Button)findViewById(R.id.create_account_button); auth = FirebaseAuth.getInstance(); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = email_text.getText().toString().trim(); final String password = passowrd_text.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(MainActivity.this, "enter email", Toast.LENGTH_LONG).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(MainActivity.this, "enter paswword", Toast.LENGTH_LONG).show(); return; } progressBar.setVisibility(View.VISIBLE); auth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressBar.setVisibility(View.GONE); if (!task.isSuccessful()) { if (password.length()<6) passowrd_text.setError("Minimun 6 character required"); else Toast.makeText(MainActivity.this,"login failed",Toast.LENGTH_LONG).show(); } else { startActivity(new Intent(MainActivity.this, Home.class)); finish(); } } }); } }); resetPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,ResetPasswordActivity.class)); } }); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this,SignUpActivity.class)); } }); } @Override protected void onResume() { super.onResume(); progressBar.setVisibility(View.GONE); } }
Python
UTF-8
380
3.234375
3
[]
no_license
#Solved import prime sieve = prime.sieve(100) sieve2 = sieve[0:-1] def product(L): i = 0 prod = 1 while(i < len(L)): prod *= L[i] i += 1 return prod def totRatio(L): totList = [x-1 for x in L] return product(L)/product(totList) l = [sieve2.pop(0) for x in range(5)] print(sieve2[0]) while(product(l) < 100000): l.append(sieve2.pop(0)) print(totRatio(l),product(l))
JavaScript
UTF-8
7,328
3
3
[ "Apache-2.0" ]
permissive
var boardNumbers =[]; var getNumber = []; var checker = []; var getChecker = []; var clickColor; var fillColor; var restartCount = 0; var numberOfClicks = 0; for (var p = 1; p <= 75; p++){ boardNumbers.push(p); checker.push(p); } function in_array(array, el) { for(var i = 0 ; i < array.length; i++) if(array[i] == el) return true; return false; } function get_rand(array) { var rand = array[Math.floor(Math.random()*array.length)]; if(!in_array(getNumber, rand)) { getNumber.push(rand); return rand; } return get_rand(array); } function get_num(array) { var rand = array[Math.floor(Math.random()*array.length)]; if(!in_array(getChecker, rand)) { getChecker.push(rand); return rand; } return get_num(array); } function checkNumber (clicked_id){ return clicked_id; } function boardColors(xocolor){ for (var i = 1; i <= 25; i++){ document.getElementById("button"+i).innerHTML = get_rand(boardNumbers); document.getElementById("button"+i).style.backgroundColor = xocolor.fill; } clickColor = xocolor.stroke; fillColor = xocolor.fill; } function sugarOrNot(){ if (fillColor === undefined) { fillColor = '#ff0000'; clickColor = '#00ff00'; for (var i = 1; i <= 25; i++){ document.getElementById("button"+i).innerHTML = get_rand(boardNumbers); document.getElementById("button"+i).style.backgroundColor = fillColor; } } } var countdowntimer = 5; function offOverlay() { document.getElementById("overlay").style.display = "none"; } var countdownInterval; var showBingoNumber; function startTimer(){ countdownInterval = setInterval(function(){ countdowntimer--; document.getElementById("countdown").innerHTML = countdowntimer; if (countdowntimer == 1){ countdowntimer = 6; } }, 1000); } function bingoNumber(){ showBingoNumber = setInterval(function(){ document.getElementById("bingoNumber").innerHTML = get_num(checker); }, 5000); } startTimer(); bingoNumber(); function restart() { var newTimer = 5; restartCount++; boardNumbers =[]; getNumber = []; checker = []; getChecker = []; for (var p = 1; p <= 75; p++){ boardNumbers.push(p); checker.push(p); } for (var i = 1; i <= 25; i++){ document.getElementById("button"+i).innerHTML = get_rand(boardNumbers); document.getElementById("button"+i).style.backgroundColor = fillColor; } if (restartCount==1){ clearInterval(countdownInterval); clearInterval(showBingoNumber); document.getElementById("countdown").innerHTML = 5; document.getElementById("bingoNumber").innerHTML = null; newcountdownInterval = setInterval(function(){ newTimer--; document.getElementById("countdown").innerHTML = newTimer; if (newTimer == 1){ newTimer = 6; } }, 1000); newshowBingoNumber = setInterval(function(){ document.getElementById("bingoNumber").innerHTML = get_num(checker); }, 5000); } else if (restartCount>1){ clearInterval(newcountdownInterval); clearInterval(newshowBingoNumber); document.getElementById("countdown").innerHTML = 5; document.getElementById("bingoNumber").innerHTML = null; newcountdownInterval = setInterval(function(){ newTimer--; document.getElementById("countdown").innerHTML = newTimer; if (newTimer == 1){ newTimer = 6; } }, 1000); newshowBingoNumber = setInterval(function(){ document.getElementById("bingoNumber").innerHTML = get_num(checker); }, 5000); } } function checkNumber(clicked_id){ if (document.getElementById(clicked_id).innerHTML == document.getElementById("bingoNumber").innerHTML){ document.getElementById(clicked_id).style.backgroundColor = clickColor; document.getElementById(clicked_id).value = 1; numberOfClicks++; var winHOne = document.getElementById("button1").value + document.getElementById("button2").value + document.getElementById("button3").value + document.getElementById("button4").value + document.getElementById("button5").value ; var winHTwo = document.getElementById("button6").value + document.getElementById("button7").value + document.getElementById("button8").value + document.getElementById("button9").value + document.getElementById("button10").value ; var winHThree = document.getElementById("button11").value + document.getElementById("button12").value + document.getElementById("button13").value + document.getElementById("button14").value + document.getElementById("button15").value ; var winHFour = document.getElementById("button16").value + document.getElementById("button17").value + document.getElementById("button18").value + document.getElementById("button19").value + document.getElementById("button20").value ; var winHFive = document.getElementById("button21").value + document.getElementById("button22").value + document.getElementById("button23").value + document.getElementById("button24").value + document.getElementById("button25").value ; var winVOne = document.getElementById("button1").value + document.getElementById("button6").value + document.getElementById("button11").value + document.getElementById("button16").value + document.getElementById("button21").value ; var winVTwo = document.getElementById("button2").value + document.getElementById("button7").value + document.getElementById("button12").value + document.getElementById("button17").value + document.getElementById("button22").value ; var winVThree = document.getElementById("button3").value + document.getElementById("button8").value + document.getElementById("button13").value + document.getElementById("button18").value + document.getElementById("button23").value ; var winVFour = document.getElementById("button4").value + document.getElementById("button9").value + document.getElementById("button14").value + document.getElementById("button19").value + document.getElementById("button24").value ; var winVFive = document.getElementById("button5").value + document.getElementById("button10").value + document.getElementById("button15").value + document.getElementById("button20").value + document.getElementById("button25").value ; var winDOne = document.getElementById("button1").value + document.getElementById("button7").value + document.getElementById("button13").value + document.getElementById("button19").value + document.getElementById("button25").value ; var winDTwo = document.getElementById("button5").value + document.getElementById("button9").value + document.getElementById("button13").value + document.getElementById("button17").value + document.getElementById("button21").value ; var winList = [ winHOne, winHTwo, winHThree, winHFour, winHFive, winVOne, winVTwo, winVThree, winVFour, winVFive, winDOne, winDTwo ]; for (var n = 0; n < winList.length; n++){ if (winList[n] == 11111){ document.getElementById("text").innerHTML = "BINGO! You used " + numberOfClicks + " moves"; document.getElementById("overlay").style.display = "block"; for (var g = 1; g <= 25; g++){ document.getElementById("button"+g).value = 0; } numberOfClicks = 0; } } } }
Java
UTF-8
1,436
2.453125
2
[]
no_license
package com.smartrestaurants.demo.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name = "menu") public class Menu { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int menu_id; private String menu_name; private double price; private String image; private int menu_status; public Menu(){ super(); } public Menu(String menu_name, double price, String image, int menu_status) { this.menu_name = menu_name; this.price = price; this.image = image; this.menu_status = menu_status; } public int getMenu_id() { return menu_id; } public void setMenu_id(int menu_id) { this.menu_id = menu_id; } public String getMenu_name() { return menu_name; } public void setMenu_name(String menu_name) { this.menu_name = menu_name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public int getMenu_status() { return menu_status; } public void setMenu_status(int menu_status) { this.menu_status = menu_status; } }
JavaScript
UTF-8
1,539
3.03125
3
[]
no_license
var cadastrarUsuario = document.getElementById('cadastrarUsuario'); var loginUsuario = document.getElementById('loginUsuario') cadastrarUsuario.addEventListener('submit', function(e){ e.preventDefault(); var dados = new FormData(cadastrarUsuario) console.log(dados); console.log(dados.get('CadNome')); console.log(dados.get('CadEmail')); console.log(dados.get('CadSenha')); console.log(dados.get('CadCSenha')); fetch('cadastrar.php', { method: 'POST', body: dados }) .then( res => res.json()) .then( data => { console.log(data) if(data === 'erro1'){ alertify.error('Preencha todos os campos.'); }else if(data === 'erro2'){ alertify.error('As senha não combinam.'); } else if(data === 'erro3'){ alertify.error('E-mail já cadastrado.'); } else if(data === 'erro4'){ alertify.error('Preencha a senha com ao menos 8 caracteres.'); } else{ alertify.success('Cadastro realizado com sucesso. Por favor, faça login.') } }) }); loginUsuario.addEventListener('submit', function(e){ e.preventDefault(); var dados = new FormData(loginUsuario) console.log(dados); console.log(dados.get('LogEmail')); console.log(dados.get('LogSenha')); fetch('logar.php', { method: 'POST', body: dados }) .then( res => res.json()) .then( data => { console.log(data) if(data === 'erro1'){ alertify.error('Preencha todos os campos.'); }else{ alertify.success('Logado com sucesso.'); setTimeout(function() { window.location.href = "index.php"; }, 1500); } }) });
C++
UTF-8
1,244
2.6875
3
[]
no_license
#include <iostream> #include "MidiInput.h" #ifdef __platform_mac__ #define MIDI_DEVICE_ID 0 #else #define MIDI_DEVICE_ID 3 #endif MidiInput::MidiInput() { PmError err; err = Pm_Initialize(); if (err != pmNoError) { std::cout << "Error initializing: " << Pm_GetErrorText(err) << std::endl; } int numDevices = Pm_CountDevices(); std::cout << numDevices << " devices" << std::endl; err = Pm_OpenInput(&(this->stream), MIDI_DEVICE_ID, 0, 128, 0, 0); if (err != pmNoError) { std::cout << "Error opening input: " << Pm_GetErrorText(err) << std::endl; } // We only want note on/off signals Pm_SetFilter(this->stream, !PM_FILT_NOTE); } MidiInput::~MidiInput() { PmError err = Pm_Terminate(); if (err != pmNoError) { std::cout << "Error terminating: " << Pm_GetErrorText(err) << std::endl; } } void MidiInput::RunLoop() { int readResult = 0; PmEvent event; while(1) { readResult = Pm_Read(this->stream, &event, 1); if (readResult > 0) { MidiMessage msg(Pm_MessageData1(event.message), Pm_MessageData2(event.message)); this->queue->Add(msg); if (readResult > 1) { std::cout << "More than one!" << std::endl; } } } } void MidiInput::SetQueue(WorkQueue<MidiMessage>* queue) { this->queue = queue; }
JavaScript
UTF-8
1,659
2.765625
3
[]
no_license
User.save = function (aUser, callback) { var myKey = aUser.emailAddress; var shasum = crypto.createHash('sha1'); shasum.update(aUser.password); aUser.password = shasum.digest('hex'); User.findOne(myKey, function(error, existingUser){ if(error) { //an error occurred callback("ERR_DB", null); } else if( existingUser ) { //user with that email already exists callback("ERR_USER_EXISTS", null); }else{ //create user cb.set(myKey, JSON.stringify(aUser), function (err, meta) { if(err){ console.error(err); callback("error", null); }else{ console.info(meta); callback(null, meta); } }); } }); } User.findOne = function(username, callback) { cb.get(username, function (error, doc, meta) { if(error){ console.info(error); callback(null, false); }else if(doc){ console.info(doc); console.info(meta); callback(null, doc); } }); }; User.authenticate = function (username, password, callback) { console.info("User.authenticate"); console.info(username); console.info(password); User.findOne(username, function(error, aUser){ if(error){ return callback(null, false); }else{ if(!aUser){ callback(null, false); }else{ var shasum = crypto.createHash('sha1'); shasum.update(password); input_pass = shasum.digest('hex'); if(aUser.password == input_pass){ aUser.verifiedPass = true; return callback(null, aUser); }else{ aUser.verifiedPass = false; return callback(null, aUser); } } } }); };
C
UTF-8
1,351
4.1875
4
[]
no_license
/* Programa: cardinales.c Sinopsis: Nos ofrece el cardinal de un número natural de cero a nueve tecleado por consola Ejemplo de sentencia alternativa múltiple Version: Marzo 2018 Autor: Paco González Moya */ #include<stdio.h> //Función de validación int validaNumero (unsigned int num); //Función para obtener el cardinal void cardinalNumero (unsigned int num); int main() { unsigned int numero; //Pedimos el número por teclado printf("\nTeclea un número natural [0..9]:"); scanf("%u", &numero); if (validaNumero(numero)) { cardinalNumero(numero); } else { printf("\nEl número %u no está en el rango [0..9]\n", numero); } return 0; } //Valida si el número leído se encuentra en el rango [0..9] int validaNumero (unsigned int num) { return (num>=0 && num<=9); } //Función para obtener el ordinal void cardinalNumero (unsigned int num) { switch (num) { case 0: printf("\ncero\n"); break; case 1: printf("\nuno\n"); break; case 2: printf("\ndos\n"); break; case 3: printf("\ntres\n"); break; case 4: printf("\ncuatro\n"); break; case 5: printf("\ncinco\n"); break; case 6: printf("\nseis\n"); break; case 7: printf("\nsiete\n"); break; case 8: printf("\nocho\n"); break; case 9: printf("\nnueve\n"); break; default: printf("\n¿?\n"); } return; }
Markdown
UTF-8
1,097
2.515625
3
[]
no_license
# LeagueRelog 0.1 A way to startup the League of Legends client with a Server selected before starting the client. This safes time and since it only changes the server not the language used it stops the client from patching 1GB of data every time you relog e.g. from NA to EUW. ## How to use Simply start the LeagueRelog.exe from anywhere on your system. If you dont have League of Legends installed in the default directory a Dialog will open which lets you navigate to your League of Legends installation. Select the LeagueClient.exe in this dialog. Type 'path' if to change the path of the LeagueClient.exe To start League of Legends with one of the three options (EUW, NA or EUNE) simply type: * '1' or 'EUW' * '2' or 'NA' * '3' or 'EUNE' Type 'q' to exit the program ### Prerequisites Having League of Legends installed on any drive. ## Built With * Costura.Fody.3.2.1 * Fody.3.3.4 * Newtonsoft.Json.12.0.1 * YamlDotNet.5.3.0 ## Authors * [SupremeVoid](https://github.com/SupremeVoid) ## Acknowledgments * Riot Games for [League of Legends](https://euw.leagueoflegends.com/en/)
Java
UTF-8
13,074
2.125
2
[]
no_license
package com.narendra.sams.core.service.impl; import com.narendra.sams.core.dao.AcademicYearDAO; import com.narendra.sams.core.domain.AcademicYear; import com.narendra.sams.core.domain.AcademicYearClass; import com.narendra.sams.core.domain.AcademicYearCourse; import com.narendra.sams.core.domain.AcademicYearFee; import com.narendra.sams.core.domain.AcademicYearFeeDetail; import com.narendra.sams.core.domain.AcademicYearFeeInstallment; import com.narendra.sams.core.domain.AcademicYearFeeInstallmentDetail; import com.narendra.sams.core.domain.Course; import com.narendra.sams.core.domain.CourseYearSetting; import com.narendra.sams.core.domain.InstituteSetting; import com.narendra.sams.core.exception.DuplicateNameFoundException; import com.narendra.sams.core.service.AcademicYearAdmissionSchemeService; import com.narendra.sams.core.service.AcademicYearBusFeeService; import com.narendra.sams.core.service.AcademicYearFeeService; import com.narendra.sams.core.service.AcademicYearService; import com.narendra.sams.core.service.AcademicYearSettingService; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class AcademicYearServiceImpl implements AcademicYearService { private AcademicYearAdmissionSchemeService academicYearAdmissionSchemeService; private AcademicYearBusFeeService academicYearBusFeeService; private AcademicYearDAO academicYearDAO; private AcademicYearFeeService academicYearFeeService; private AcademicYearSettingService academicYearSettingService; public AcademicYearDAO getAcademicYearDAO() { return this.academicYearDAO; } public void setAcademicYearDAO(AcademicYearDAO academicYearDAO) { this.academicYearDAO = academicYearDAO; } public AcademicYear getActiveAcademicYearForAdmission(Long instituteId) { return this.academicYearDAO.getActiveAcademicYearForAdmission(instituteId); } public AcademicYear getActiveAcademicYearForEnquiry(Long instituteId) { return this.academicYearDAO.getActiveAcademicYearForEnquiry(instituteId); } public List<AcademicYear> getFeeAcademicYears(Long instituteId) { return this.academicYearDAO.getFeeAcademicYears(instituteId); } public AcademicYearSettingService getAcademicYearSettingService() { return this.academicYearSettingService; } public void setAcademicYearSettingService(AcademicYearSettingService academicYearSettingService) { this.academicYearSettingService = academicYearSettingService; } public AcademicYearBusFeeService getAcademicYearBusFeeService() { return this.academicYearBusFeeService; } public void setAcademicYearBusFeeService(AcademicYearBusFeeService academicYearBusFeeService) { this.academicYearBusFeeService = academicYearBusFeeService; } public AcademicYearFeeService getAcademicYearFeeService() { return this.academicYearFeeService; } public void setAcademicYearFeeService(AcademicYearFeeService academicYearFeeService) { this.academicYearFeeService = academicYearFeeService; } public Long saveAcademicYear(AcademicYear academicYear, Long userId) throws DuplicateNameFoundException { if (academicYear == null) { return null; } Long academicYearId = academicYear.getId(); if (academicYear.getId() != null) { AcademicYear persistAcademicYear = this.academicYearDAO.getAcademicYearByName(academicYear.getInstitute().getId(), academicYear.getName()); if (persistAcademicYear == null || persistAcademicYear.getId().equals(academicYear.getId())) { this.academicYearDAO.updateAcademicYear(academicYear, userId); return academicYearId; } throw new DuplicateNameFoundException("Academic Session ['" + academicYear.getName() + "'] already exists"); } else if (this.academicYearDAO.isAcademicYearNameExists(academicYear.getInstitute().getId(), academicYear.getName()).booleanValue()) { throw new DuplicateNameFoundException("Academic Session ['" + academicYear.getName() + "'] already exist"); } else { academicYear.setStatus("draft"); academicYearId = this.academicYearDAO.addAcademicYear(academicYear, userId); this.academicYearDAO.saveAcademicYearConfiguration(academicYearId); return academicYearId; } } public AcademicYear getAcademicYearById(long id) { return this.academicYearDAO.getAcademicYearById(id); } public List<AcademicYear> getAllAcademicYears(Long instituteId) { return this.academicYearDAO.getAllAcademicYears(instituteId); } public List<AcademicYear> getActiveAcademicYears(Long instituteId) { if (instituteId == null) { return null; } return this.academicYearDAO.getActiveAcademicYears(instituteId); } public Boolean isAcademicYearNameExists(Long instituteId, String name) { return this.academicYearDAO.isAcademicYearNameExists(instituteId, name); } public AcademicYear getAcademicYearByName(Long instituteId, String name) { return this.academicYearDAO.getAcademicYearByName(instituteId, name); } public List<AcademicYearClass> getActiveClassess(Long courseId, Long academicYearId) { return this.academicYearDAO.getActiveClassess(courseId, academicYearId); } public List<AcademicYearClass> getActiveAcademicYearClassess(Long affiliationAuthorityId, Long academicYearId) { return this.academicYearDAO.getActiveAcademicYearClassess(affiliationAuthorityId, academicYearId); } public List<Course> getActiveCourses(Long academicYearId, Long affiliationAuthorityId) { return this.academicYearDAO.getActiveCourses(academicYearId, affiliationAuthorityId); } public List<InstituteSetting> getInstituteSettings() { return this.academicYearDAO.getInstituteSettings(); } public List<AcademicYearClass> getPromotionClasses(Long courseId, Long academicYearId) { return this.academicYearDAO.getPromotionClasses(courseId, academicYearId); } public AcademicYear getAcademicYearByOrder(Short orderNo, Long instituteId) { return this.academicYearDAO.getAcademicYearByOrder(orderNo, instituteId); } public void copyAcademicYear(Long fromAcademicYear, Long toAcademicYear, Long userId) { List<AcademicYearCourse> fromAcademicYearCourses = this.academicYearSettingService.getAcademicYearCourses(fromAcademicYear); AcademicYear academicYear = new AcademicYear(); academicYear.setId(toAcademicYear); List<AcademicYearCourse> toAcademicYearCourses = new ArrayList(); for (AcademicYearCourse fromAcademicYearCourse : fromAcademicYearCourses) { AcademicYearCourse toAcademicYearCourse = new AcademicYearCourse(); toAcademicYearCourse.setAcademicYear(academicYear); toAcademicYearCourse.setActive(fromAcademicYearCourse.getActive()); toAcademicYearCourse.setCourse(fromAcademicYearCourse.getCourse()); toAcademicYearCourse.setCourseYearSettings(new HashSet()); for (CourseYearSetting fromCourseYearSetting : fromAcademicYearCourse.getCourseYearSettings()) { CourseYearSetting toCourseYearSetting = new CourseYearSetting(); toCourseYearSetting.setAcademicYear(academicYear); toCourseYearSetting.setActive(fromCourseYearSetting.getActive()); toCourseYearSetting.setCourseYear(fromCourseYearSetting.getCourseYear()); toCourseYearSetting.setCourseYearType(fromCourseYearSetting.getCourseYearType()); toCourseYearSetting.setIntake(fromCourseYearSetting.getIntake()); toCourseYearSetting.setAcademicYearClasses(new HashSet()); for (AcademicYearClass fromAcademicYearClass : fromCourseYearSetting.getAcademicYearClasses()) { AcademicYearClass toAcademicYearClass = new AcademicYearClass(); toAcademicYearClass.setName(fromAcademicYearClass.getName()); toAcademicYearClass.setActive(fromAcademicYearClass.getActive()); toAcademicYearClass.setAcademicYear(academicYear); toAcademicYearClass.setCourseYear(fromAcademicYearClass.getCourseYear()); toAcademicYearClass.setCourseYearSetting(toCourseYearSetting); toAcademicYearClass.setDisplayName(fromAcademicYearClass.getDisplayName()); toCourseYearSetting.getAcademicYearClasses().add(toAcademicYearClass); } toCourseYearSetting.setAcademicYearFees(new HashSet()); for (AcademicYearFee fromAcademicYearFee : fromCourseYearSetting.getAcademicYearFees()) { AcademicYearFee toAcademicYearFee = new AcademicYearFee(); toAcademicYearFee.setAcademicYear(academicYear); toAcademicYearFee.setCourseYear(fromAcademicYearFee.getCourseYear()); toAcademicYearFee.setCourseYearSetting(toCourseYearSetting); toAcademicYearFee.setAdmissionType(fromAcademicYearFee.getAdmissionType()); toAcademicYearFee.setAcademicYearFeeDetails(new HashSet()); for (AcademicYearFeeDetail fromAcademicYearFeeDetail : fromAcademicYearFee.getAcademicYearFeeDetails()) { AcademicYearFeeDetail toAcademicYearFeeDetail = new AcademicYearFeeDetail(); toAcademicYearFeeDetail.setAcademicYearFee(toAcademicYearFee); toAcademicYearFeeDetail.setFeeHead(fromAcademicYearFeeDetail.getFeeHead()); toAcademicYearFeeDetail.setAmount(fromAcademicYearFeeDetail.getAmount()); toAcademicYearFee.getAcademicYearFeeDetails().add(toAcademicYearFeeDetail); } toAcademicYearFee.setAcademicYearFeeInstallments(new HashSet()); for (AcademicYearFeeInstallment fromAcademicYearFeeInstallment : fromAcademicYearFee.getAcademicYearFeeInstallments()) { AcademicYearFeeInstallment toAcademicYearFeeInstallment = new AcademicYearFeeInstallment(); toAcademicYearFeeInstallment.setInstallment(fromAcademicYearFeeInstallment.getInstallment()); toAcademicYearFeeInstallment.setAcademicYearFee(toAcademicYearFee); toAcademicYearFeeInstallment.setDueDate(fromAcademicYearFeeInstallment.getDueDate()); toAcademicYearFeeInstallment.setLateFeeRule(fromAcademicYearFeeInstallment.getLateFeeRule()); toAcademicYearFeeInstallment.setAcademicYearFeeInstallmentDetails(new HashSet()); for (AcademicYearFeeInstallmentDetail fromAcademicYearFeeInstallmentDetail : fromAcademicYearFeeInstallment.getAcademicYearFeeInstallmentDetails()) { AcademicYearFeeInstallmentDetail toAcademicYearFeeInstallmentDetail = new AcademicYearFeeInstallmentDetail(); toAcademicYearFeeInstallmentDetail.setAcademicYearFeeInstallment(toAcademicYearFeeInstallment); toAcademicYearFeeInstallmentDetail.setFeeHead(fromAcademicYearFeeInstallmentDetail.getFeeHead()); toAcademicYearFeeInstallmentDetail.setAmount(fromAcademicYearFeeInstallmentDetail.getAmount()); toAcademicYearFeeInstallment.getAcademicYearFeeInstallmentDetails().add(toAcademicYearFeeInstallmentDetail); } toAcademicYearFee.getAcademicYearFeeInstallments().add(toAcademicYearFeeInstallment); } toCourseYearSetting.getAcademicYearFees().add(toAcademicYearFee); } toAcademicYearCourse.getCourseYearSettings().add(toCourseYearSetting); } toAcademicYearCourses.add(toAcademicYearCourse); } this.academicYearFeeService.saveAcademicYearCourses(toAcademicYearCourses); this.academicYearBusFeeService.copyBusStopAndFee(fromAcademicYear, toAcademicYear); this.academicYearBusFeeService.copyBusFeeInstallments(fromAcademicYear, toAcademicYear, userId); this.academicYearAdmissionSchemeService.copyAdmissionSchemes(fromAcademicYear, toAcademicYear, userId); } public void publishAcademicYear(Long academicSessionId) { this.academicYearDAO.publishAcademicYear(academicSessionId); } public AcademicYearAdmissionSchemeService getAcademicYearAdmissionSchemeService() { return this.academicYearAdmissionSchemeService; } public void setAcademicYearAdmissionSchemeService(AcademicYearAdmissionSchemeService academicYearAdmissionSchemeService) { this.academicYearAdmissionSchemeService = academicYearAdmissionSchemeService; } }
Java
UTF-8
5,442
1.8125
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.kafkaconnector.maven.catalog.descriptor; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.FileUtils; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; /** * Updates connector.properties file */ @Mojo(name = "list-descriptor-files", threadSafe = true) public class CollectConnectorDescriptorMojo extends AbstractMojo { /** * The maven project. */ @Parameter(property = "project", required = true, readonly = true) protected MavenProject project; /** * The directory for connectors */ @Parameter(defaultValue = "${project.directory}/../../connectors/") protected File connectorsDir; /** * The directory for catalog descriptors */ @Parameter(defaultValue = "${project.directory}/../../camel-kafka-connector-catalog/src/generated/resources/descriptors") protected File catalogDescriptorDir; /** * The connectors project name parameter. */ @Parameter(property = "connectors-project-name", defaultValue = "connectors", readonly = true) protected String connectorsProjectName; /** * Execute goal. * * @throws MojoExecutionException execution of the main class or one of the * threads it generated failed. * @throws MojoFailureException something bad happened... */ @Override public void execute() throws MojoExecutionException, MojoFailureException { if (!project.getArtifactId().equals(connectorsProjectName)) { getLog() .debug("Skipping project " + project.getArtifactId() + " since it is not " + connectorsProjectName + " can be configured with <connectors-project-name> option."); return; } try { executeComponentsReadme(); } catch (IOException e) { e.printStackTrace(); } } protected void executeComponentsReadme() throws MojoExecutionException, MojoFailureException, IOException { if (connectorsDir != null && connectorsDir.isDirectory()) { File[] files = connectorsDir.listFiles(); if (files != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { File fileSource = FileUtils.getFile(file, "src/generated/descriptors/connector-source.properties"); File fileSink = FileUtils.getFile(file, "src/generated/descriptors/connector-sink.properties"); if (fileSource.exists()) { try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileSource), "UTF-8"))) { String line = null; while ((line = br.readLine()) != null) { sb.append(line); sb.append(System.lineSeparator()); } } catch (IOException e) { e.printStackTrace(); } } if (fileSink.exists()) { try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileSink), "UTF-8"))) { String line = null; while ((line = br.readLine()) != null) { sb.append(line); sb.append(System.lineSeparator()); } } catch (IOException e) { e.printStackTrace(); } } } } File file = FileUtils.getFile(catalogDescriptorDir, "connectors.properties"); file.createNewFile(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { writer.write(sb.toString()); } } } } }
Python
UTF-8
1,026
3.46875
3
[]
no_license
""" @author Lucas @date 2019/4/2 9:51 """ # 堆排序 # 建大顶堆 def heap(a): while True: flag = True for i in range(len(a)): if (2*i + 1) < len(a) and (2*i + 2) < len(a): if a[2*i + 1] > a[2*i + 2]: max = 2*i + 1 else: max = 2*i + 2 if a[max] > a[i]: a[i], a[max] = a[max], a[i] flag = False elif (2*i + 1) < len(a): if a[2*i + 1] > a[i]: a[i], a[2*i + 1] = a[2*i + 1], a[i] flag = False if flag: break return a def heapSort(a): count = len(a) result = [] for i in range(count): a = heap(a) result.append(a[0]) a[0], a[-1] = a[-1], a[0] a = a[:-1] result.reverse() return result if __name__ == '__main__': a = [4, 6, 8, 5, 9, 1, 3, 2] b = heap(a) print(b) result = heapSort(a) print(result)
Python
UTF-8
425
3.140625
3
[]
no_license
import streamlit as st st.title('Penguin Classifier') st.write("This app uses 6 inputs to predict the species of penguin using " "a model built on the Palmer's Penguin's dataset. Use the form below" " to get started!") password_guess = st.text_input('What is the Password?') if password_guess != 'streamlit_is_great': st.stop() penguin_file = st.file_uploader('Upload your own penguin data')
Shell
UTF-8
559
3.8125
4
[ "BSD-2-Clause" ]
permissive
#!/bin/bash BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" . $BASEDIR/conf/settings FILE="$1" if [ -z "$FILE" ]; then echo "Error: Missing file. " echo "Usage: vms_download_file <file>" exit 1 fi if [ ! -d $BASEDIR/downloaded ]; then mkdir $BASEDIR/downloaded fi for VM in $(cat $BASEDIR/dhcp/leases.txt|awk '{print $3}'); do scp -o LogLevel=QUIET -o StrictHostKeyChecking=false -o UserKnownHostsFile=/dev/null $TEMPLATE_USER@$VM:$FILE $BASEDIR/downloaded/$FILE-$VM done echo "Files downloaded to $BASEDIR/downloaded"
Markdown
UTF-8
3,133
3.015625
3
[ "MIT" ]
permissive
--- layout: post title: 推荐算法之Embeding技术 subtitle: date: 2018-10-01 author: horizon-z40 header-img: img/post-bg-cook.jpg catalog: true tags: - 推荐系统 --- 每个user/item可以表示为一个向量,向量之间的相似度可以用来改善推荐。 ##### 1. denoising autoencode ​ Yahoo Japan的新闻推荐团队利用denoising autoencode的技术来学习新闻的vector表示。Autoencode大家可能比较熟悉,它通过最小化变换前后信号的误差来求解,而denoising则是对输入随机加入一些噪声,再对其进行变换输出,最终是通过最小化加噪声后的输出和原始(不加噪声)输入之间的差异来求解。应用中不少结果表明,这种方法比传统的autoencode学习到的vector效果更好。具体示意图如下。 ##### 2. ​ 微软研究院也提出过一种很有趣的得到item表示的方法。作者利用用户的搜索日志,同一个query下,搜索引擎往往返回n篇doc,用户一般会点击相关的doc,不太相关的一般不会点,利用这个反馈信息也可以训练神经网络。具体示意图如下,这里的优化目标就是要求点击的一个doc_i的预测得分p(D_i|Q)要高于不点击的,论文基于这个信息构造除了损失函数,也就得到了最终机器学习可以优化的一个目标。 ​ 目前只介绍了如何得到item的vector,实际推荐中要用到的一般是user对一个item的兴趣程度,只有在得到user vector后才能通过算user和item的相似度来度量这个兴趣程度。那么如何得到user的vector呢?了解的同学可能能想到,既然我们已经得到了新闻的item的表示,想办法把他们传到user侧不就行了么? ​ 确实如此,一种简单的做法是把用户近期点过的所有新闻的vector取个平均或者加权平均就可以得到user的vector了。 ​ 但这种模式还有优化的空间:1)用户点击是一个序列,每次点击不是独立的,如果把序列考虑进去就有可能得到更好的表示;2)点击行为和曝光是有联系的,点击率更能体现用户对某个或某类新闻的感兴趣程度。 ​ 鉴于这两点,我们很容易想到通过深度学习里经典的解决序列学习的RNN方法,Yahoo japan的人使用的就是一个经典的RNN特例:LSTM。训练时将用户的曝光和点击行为作为一个序列,每次有点或不点这样的反馈,就很容易套用LSTM训练得到user的vector,具体做法如下图所示。 ​ 微软还发表了《A Multi-View Deep Learning Approach for Cross Domain User Modeling in Recommendation Systems》,文章提出了一种有趣的得到user vector的方法,这是一个典型的multi-view learning的方法。现在很多公司都不仅仅只有一个产品,而是有多个产品线。比如微软可能就有搜索、新闻、appstore、xbox等产品,如果将用户在这些产品上的行为(反馈)统一在一起训练一个深度学习网络,就能很好的解决单个产品上(用户)冷启动、稀疏等问题。
Java
UTF-8
798
2.953125
3
[]
no_license
package com.khan.academy.infection; import java.util.HashSet; import java.util.Set; public class UserGraph { Set<User> infected; Set<User> uninfected; public UserGraph() { infected = new HashSet<User>(); uninfected = new HashSet<User>(); } public void addInfected(User user) { user.moveUserFromOldToNewVersion(); infected.add(user); uninfected.remove(user); } public void addUnifected(User user) { user.moveUserFromNewToOldVersion(); uninfected.add(user); infected.remove(user); } public Set<User> getInfected() { return infected; } public void setInfected(Set<User> infected) { this.infected = infected; } public Set<User> getUninfected() { return uninfected; } public void setUninfected(Set<User> uninfected) { this.uninfected = uninfected; } }
Java
UTF-8
696
2.9375
3
[]
no_license
package com.nextyu.book.study.source.chapter8_testing_concurrent_applications._2_monitoring_a_Lock_interface; import java.util.Collection; import java.util.concurrent.locks.ReentrantLock; /** * created on 2016-07-14 9:28 * * @author nextyu */ public class MyLock extends ReentrantLock { /** * returns the name of the thread that has the control of a lock (if any) * * @return */ public String getOwnerName() { return getOwner() == null ? "None" : getOwner().getName(); } /** * returns a list of threads queued in a lock * * @return */ public Collection<Thread> getThreads() { return getQueuedThreads(); } }
C
UTF-8
310
2.921875
3
[]
no_license
#include "../fe.h" char *fe_xdirname(char const *path) { /* Strdup the path, dirname chops it up. The caller is responsible for * freeing the return value. */ char *copy = fe_xstrdup(path); char *dirn = dirname(copy); char *ret = fe_xstrdup(dirn); free(copy); return ret; }