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
SQL
UTF-8
746
2.546875
3
[]
no_license
-- REL FK: defaultUsers [DefaultGroup2User] alter table `user` add index fk_user_group (`group_oid`), add constraint fk_user_group foreign key (`group_oid`) references `group` (`oid`); -- REL FK: groups [User2Group] alter table `user_group` add index fk_user_group_user (`user_oid`), add constraint fk_user_group_user foreign key (`user_oid`) references `user` (`oid`); -- REL FK: users [Group2User] alter table `user_group` add index fk_user_group_group (`group_oid`), add constraint fk_user_group_group foreign key (`group_oid`) references `group` (`oid`); -- REL FK: CartToUser [rel4#role5] alter table `user` add index fk_user_cart (`cart_oid`), add constraint fk_user_cart foreign key (`cart_oid`) references `cart` (`oid`);
Java
UTF-8
1,231
2.109375
2
[]
no_license
package com.lx.mms.service; import com.lx.mms.entity.SysDept; import com.lx.mms.entity.param.DeptParam; import java.util.List; /** * (SysDept)่กจๆœๅŠกๆŽฅๅฃ * * @author Werdioไธถ * @since 2020-03-14 09:56:17 */ public interface SysDeptService { /** * ้€š่ฟ‡IDๆŸฅ่ฏขๅ•ๆกๆ•ฐๆฎ * * @param id ไธป้”ฎ * @return ๅฎžไพ‹ๅฏน่ฑก */ SysDept queryById(Long id); /** * ๆŸฅ่ฏขๅคšๆกๆ•ฐๆฎ * * @param offset ๆŸฅ่ฏข่ตทๅง‹ไฝ็ฝฎ * @param limit ๆŸฅ่ฏขๆกๆ•ฐ * @return ๅฏน่ฑกๅˆ—่กจ */ List<SysDept> queryAllByLimit(int offset, int limit); /** * ๆŸฅ่ฏขๆ‰€ๆœ‰ๆ•ฐๆฎ * * @return ๅฏน่ฑกๅˆ—่กจ */ List<SysDept> queryAll(); /** * ๆ–ฐๅขžๆ•ฐๆฎ * * @param sysDept ๅฎžไพ‹ๅฏน่ฑก * @return ๅฎžไพ‹ๅฏน่ฑก */ SysDept insert(SysDept sysDept); /** * ไฟฎๆ”นๆ•ฐๆฎ * * @param deptParam ๆ›ดๆ–ฐๅŽ็š„ๅ‚ๆ•ฐ * @return ๅ—ๅฝฑๅ“่กŒๆ•ฐ */ int update(DeptParam deptParam); /** * ้€š่ฟ‡ไธป้”ฎๅˆ ้™คๆ•ฐๆฎ * * @param id ไธป้”ฎ * @return ๆ˜ฏๅฆๆˆๅŠŸ */ boolean deleteById(Long id); /** * ไฟๅญ˜้ƒจ้—จ */ int save(DeptParam deptParam); }
Python
UTF-8
2,044
2.9375
3
[ "MIT" ]
permissive
import math import os import random import re import sys import functools as ft from operator import itemgetter, attrgetter from collections import Counter from itertools import combinations def pascal(n: int): a = [[1]] for _ in range(n - 1): tmp = zip([0] + a[-1], a[-1] + [0]) a.append([sum(i) for i in tmp]) return a def digital_root(n): while int(n) // 10 > 0: n = sum(list(map(int, str(n)))) return n def circularly_sorted(a: list) -> bool: i = 1 while i < len(a) and a[i] >= a[i - 1]: i += 1 b = zip(a[i:] + a[:i], sorted(a)) return len([i for i in b if i[0] == i[1]]) == len(a) def find_odd_times(a: list) -> int: # use list.count(number) instead cnt = 1 a.sort() for i in range(1, len(a)): if a[i] != a[i - 1]: if cnt % 2: return a[i - 1] cnt = 1 else: cnt += 1 return a[-1] def array_diff(a: list, b: list) -> list: c = set(a) & set(b) return [i for i in a if not (i in c)] def valid_parentheses(s: str) -> bool: a = list() for i in s: if i == '(': a.append(i) elif i == ')': if not len(a): return False a.pop() return not len(a) def duplicate_encode(s: str) -> str: res = list() s = s.lower() for i in s: res.append(')' if s.count(i) > 1 else '(') return "".join(res) def iq_test(a) -> int: a = [int(i) % 2 for i in a.split()] return a.index(1) + 1 if a.count(0) > 1 else a.index(0) + 1 def generate_hashtag(s: str): a = "".join(['#'] + [i[0].upper() + i[1:] for i in s.split()]) return False if not (len(a) - 1) or len(a) > 140 else a def move_zeros(a: list): cnt = a.count(0) a = list(filter(lambda i: i != 0, a)) a.extend([0] * cnt) return a def sort_list(a: list): # sort even after odd numbers return sorted(a, key=lambda i: (not (i % 2))) if __name__ == '__main__': n = int(input()) a = list() print(pascal(n))
Markdown
UTF-8
6,450
2.953125
3
[]
no_license
--- id: deployment-to-heroku title: Deployment to Heroku --- As React is one of the most popular frontend framework/libraries these days, I will be showing how to deploy a react project on Heroku. ### Heroku Dynos "The Heroku Platform uses the container model to run and scale all Heroku apps. The containers used at Heroku are called โ€œdynos.โ€ Dynos are isolated, virtualized Linux containers that are designed to execute code based on a user-specified command. Your app can scale to any specified number of dynos based on its resource demands. Herokuโ€™s container management capabilities provide you with an easy way to scale and manage the number, size, and type of dynos your app may need at any given time." > For free tier, the dyno only wakes up upon activity, and sleeps after 30 minutes of inactivity > For paid tier, the dyno will always be awake. ``` npx create-react-app my-app ``` ## Deploying to Heroku ### 1. Create Heroku App The heroku create CLI command creates a new empty application on Heroku, along with an associated empty Git repository If you run this command from your appโ€™s root directory, the empty Heroku Git repository is automatically set as a remote for your local repository. ``` heroku create ``` **Check that remote is set** ``` git remote -v ``` Sample results: ``` heroku https://git.heroku.com/react-test-app-1234.git (fetch) heroku https://git.heroku.com/react-test-app-1234.git (push) origin https://github.com/realtime-apps-iap/my-app.git (fetch) origin https://github.com/realtime-apps-iap/my-app.git (push) ``` > It looks like this for me, because this git repo is also linked to a github remote **Linking to an existing Heroku App** ``` heroku git:remote -a thawing-inlet-61413 ``` > If you created an application through Heroku website first, instead of directly through Heroku CLI ### 2. Deploying code ``` git push heroku master ``` > Heroku only deploys code that you push to master or main. Pushing code to another branch of the heroku remote has no effect. BUT if you want to deploy from another branch, you can do this: ``` git push heroku anotherBranch:master ``` ## What does Heroku run? Heroku will automatically detect what kind of app is this (e.g. Node.js, Python, etc), and if possible, try to automatically run the app. For instance if this is a create-react-app, Heroku will know (through package.json at the root) that is can run the most typical script which is `yarn start` or `npm start` and create a buildpack for it. Buildpacks are scripts that are run when your app is deployed. They are used to install dependencies for your app and configure your environment. > If your project is purely a React project at the root, you can just do this very simply. > Once you `git push heroku main`, the code will be uploaded to Heroku remote and automatically start running (if possible) and you can visit your link afterwards https://react-test-app-1234.herokuapp.com/ Otherwise, if Heroku does not know how and what to run this application, we have to specify it - through the use of the Heroku `Procfile` shown below. ## Heroku Procfile If Heroku does not know how to _automatically_ run the application, we need a Procfile saved at the root of the repository. A Profile is a text file in the root directory of your application, to **explicitly declare what command should be executed** to start your app. Before we go through what to write for a Procfile, let's check for our app that succeeded without having a Procfile. What did Heroku pick up for this react app and decide what to run? Go into the Heroku website and check it out with me... Observe under 'Overview' tab for the app project for 'Dyno formation' This is what's there for this react application of ours: ``` web npm start ``` In fact, this is essentially the Profile command! ### Specifying a Dyno process ``` <processType> <command & arguments if there is> ``` > This is essentially it! An example Procfile for a Django app: ``` web: python manage.py runserver 0.0.0.0:5000 ``` > In particular for website projects, specifying process type keyword `web` for the process that serves the website is important. > For Heroku, it declares that this process type will be attached to the HTTP routing stack of Heroku, and receive web traffic when deployed. ### Multiple Dyno processes What if you want to run more than a single command in a dyno? ``` web: puma -C config/puma.rb & sidekiq & wait -n ``` > Indicate the different commands separated by `&` > Note that `wait -n` exits when at least one of the commands exits and triggers the dyno to restart - might be a safe catch here because you don't want your dyno to run if one of the commands exits unexpectedly while the rest continues to run. > This method may not be a good practice for production applications as there will be limitations to 'process isolation, scaling and monitoring'. See the section below for a better way to do so - separating worker process types ### Multiple Dyno processes (Separate process types) You can have multiple worker process types running, instead of combining them together in one - though possible, it is not recommended. We just need to have separate process types. Sample: ``` web: python manage.py runserver 0.0.0.0:5000 worker1: python project/worker/worker.py processor1: python project/worker/processor.py ``` > The name of process types can be anything. Only the name `web` is special and reserved, as heroku needs to know to deal with web traffic. ## Running Heroku locally One thing that would be helpful in iteration and testing if your application would run correctly on heroku (especially with multiple processes indicated), is to try to run it locally first. To run it locally, ``` heroku local web ``` This serve the website on local host with the heroku development environment > Check that it runs well locally before you deploy it to heroku - saves time and effort --- ## Useful Heroku CLI commands ### Check existing heroku apps ``` heroku apps ``` ### Delete an existing heroku app ``` heroku apps:destroy <appname> --confirm <appname> ``` > For Heroku accounts that are not verified (with input credit card details), you can only create a maximum of 5 apps ### Rename an existing heroku app ``` heroku apps:rename <newname> --app <oldname> ``` > When you first create a heroku app through Heroku CLI, a random name will be given.
Java
UTF-8
1,085
2.984375
3
[]
no_license
public class Points { private double pAx, pAy; private double pBx, pBy; private double pCx, pCy; private double pDx, pDy; private double[] pointABCD; public Points() { } public Points(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy) { pointABCD = new double[]{ax, ay, bx, by, cx, cy, dx, dy}; this.pAx = ax; this.pAy = ay; this.pBx = bx; this.pBy = by; this.pCx = cx; this.pCy = cy; this.pDx = dx; this.pDy = dy; } public double[] getPoints() { return this.pointABCD; } public void setPointA(double x, double y) { this.pAx = x; this.pAy = y; } public void setPointB(double x, double y) { this.pBx = x; this.pBy = y; } public void setPointC(double x, double y) { this.pCx = x; this.pCy = y; } public void setPointD(double x, double y) { this.pDx = x; this.pDy = y; } }
Java
UTF-8
2,469
2.296875
2
[]
no_license
package com.authserver.app; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.authserver.model.OAuthUser; import com.authserver.service.UserService; @RestController @RequestMapping("/oauth/acct") public class OAuthUserController { @Autowired private UserService<OAuthUser> oauthUserService; @Autowired private PasswordEncoder passwordEncoder; @PostMapping("/user") public ResponseEntity<Void> createUser(@RequestBody OAuthUser user) { user.setPassword(passwordEncoder.encode(user.getPassword())); boolean created = oauthUserService.create(user); if (!created) { return new ResponseEntity<Void>(HttpStatus.PRECONDITION_FAILED); } return new ResponseEntity<Void>(HttpStatus.CREATED); } @PutMapping("/user") public ResponseEntity<OAuthUser> updateUser(@RequestBody OAuthUser user) { if (!oauthUserService.exists(user.getId())) { return new ResponseEntity<OAuthUser>(HttpStatus.NOT_FOUND); } boolean updated = oauthUserService.update(user); if (!updated) { return new ResponseEntity<OAuthUser>(HttpStatus.PRECONDITION_FAILED); } return new ResponseEntity<OAuthUser>(user, HttpStatus.OK); } @GetMapping("/user/{id}") public ResponseEntity<OAuthUser> findUserById(@PathVariable("id") long id) { OAuthUser user = oauthUserService.findOneById(id); if (user == null) { return new ResponseEntity<OAuthUser>(HttpStatus.NOT_FOUND); } return new ResponseEntity<OAuthUser>(user, HttpStatus.FOUND); } @GetMapping("/users") public ResponseEntity<List<OAuthUser>> findAllUsers() { List<OAuthUser> users = oauthUserService.findAll(); if (users.size() <= 0) { return new ResponseEntity<List<OAuthUser>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<OAuthUser>>(users, HttpStatus.OK); } }
Markdown
UTF-8
639
2.890625
3
[ "MIT" ]
permissive
[Character](https://developer.apple.com/documentation/swift/character) [Unicode.Scalar](https://developer.apple.com/documentation/swift/unicode/scalar) ### [CamelCase](https://www.hackerrank.com/challenges/camelcase) ```swift func camelcase(s: String) -> Int { let captials = s.filter { $0.isUppercase } return captials.count + 1 } ``` ### [Pangrams](https://www.hackerrank.com/challenges/pangrams/problem) ```swift func isPangrams(s: String) -> Bool { let c_ = Array(s.lowercased()) var count = [Character : Int]() c_.forEach { count[$0] = count[$0, default: 0] + 1 } return count.count == 27 } ```
Java
UTF-8
3,726
2.234375
2
[]
no_license
package com.attendence.abhis.attendence; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Show extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); final Spinner spap = (Spinner) findViewById(R.id.selsubject2); List<String> c_sub = new ArrayList<String>(); c_sub.add("AML100"); c_sub.add("CYP100"); c_sub.add("EEP100"); c_sub.add("EVP102"); c_sub.add("HUP103"); c_sub.add("MAL101"); c_sub.add("MEP100"); c_sub.add("MEP101"); c_sub.add("PHL100"); ArrayAdapter<String> datasub = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, c_sub); datasub.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spap.setAdapter(datasub); } String tsub; int p=0,a=0,t=0; public void onclick(View v){ Spinner msub = (Spinner) findViewById(R.id.selsubject2); tsub = msub.getSelectedItem().toString(); String FILENAME=tsub+"P.txt"; String linep="",linea=""; try{ FileInputStream fin = openFileInput(FILENAME); if (fin != null) { InputStreamReader inputreader = new InputStreamReader(fin); BufferedReader buffreader = new BufferedReader(inputreader); String line; try { while ((line = buffreader.readLine()) != null) linep+=line+"\n"; }catch (Exception e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } if(linep.equals("")==false){ String [] ptemp=linep.split("\n"); p=ptemp.length; } FILENAME=tsub+"A.txt"; try{ FileInputStream fin = openFileInput(FILENAME); if (fin != null) { InputStreamReader inputreader = new InputStreamReader(fin); BufferedReader buffreader = new BufferedReader(inputreader); String line; try { while ((line = buffreader.readLine()) != null) linea+=line+"\n"; a=a+1; }catch (Exception e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } if(linea.equals("")==false){ String [] atemp=linea.split("\n"); a=atemp.length; } t=a+p; TextView tt=findViewById(R.id.atten); String sss="Attended "+p+" out of "+t+" classes"; tt.setText(sss); tt=findViewById(R.id.percen); int pen; if(t==0){ pen=0; } else{ pen=(p*100)/t; } sss=pen+" %"; tt.setText(sss); tt=findViewById(R.id.textpre); sss="Present on \n"+linep; tt.setText(sss); tt=findViewById(R.id.textab); sss="Absent on \n"+linea; tt.setText(sss); p=0; t=0; a=0; } }
C
UTF-8
291
3.203125
3
[]
no_license
#include <stdio.h> #include <conio.h> #include <math.h> float main() { float x1, x2, distance; printf("Enter two points end press Enter \n"); scanf("%f%f", &x1, &x2); distance = fabs(x2 - x1); printf("Distance between two points X1 and X2 = %.2f \n", distance); getch(); return 0; }
Python
UTF-8
319
3.046875
3
[ "CC-BY-4.0", "MIT" ]
permissive
import numpy as np def draw_bs_reps(data, func, size=1): """Function to draw bootsrap replicates""" n = len(data) #Initialize array of replicates reps = np.empty(n) for i in range(n): bs_sample = np.random.choice(data, replace=True, size=n) reps[i]= func(bs_sample) return reps
Java
UTF-8
16,265
1.851563
2
[]
no_license
package com.dmedia.dlimited.activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.dmedia.dlimited.model.CommonData; import com.dmedia.dlimited.network.NetData; import com.dmedia.dlimited.network.NetManager; import com.dmedia.dlimited.R; import com.dmedia.dlimited.util.Utils; import org.chenglei.widget.datepicker.DatePicker; import org.json.JSONException; import org.json.JSONObject; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; /** * Created by xema0 on 2016-10-20. */ // TODO: 2016-10-31 ์ธ์Šคํƒ€๊ทธ๋žจ ์—ฐ๋™ ๋ฒ„ํŠผ ๊ตฌํ˜„ // TODO: 2016-10-31 ํฐ๋ฒˆํ˜ธ์ž…๋ ฅํ•˜๋Š” edittext๋Š” ์™œ์žˆ๋Š”๊ฑฐ์ง€ -> ์ด๊ฒƒ๋„ ๋ฐ”๊พธ๋Š”๊ฑด๊ฐ€ ์•„๋‹ˆ๋ฉด ๊ทธ๋ƒฅ ์ธ์ฆ์šฉ์ธ๊ฐ€ // TODO: 2016-10-31 internal server error public class AccountEditProfileActivity extends AppCompatActivity implements View.OnClickListener { Context mContext; private EditText mNicknameEditText; private EditText mPhoneEditText; //private Button mInstagramButton; private EditText mCommentEditText; private Button mBirthButton; private Button mGenderButton; private Button mModifyButton; private int year, month, day; private String nickname = ""; private String phone = ""; private String comment = ""; private String gender = ""; private String birth = ""; private String instaId = ""; private String profileUrl = ""; private String instaName = ""; private boolean genderCheck = false; private boolean birthCheck = false; //private InstagramApp mApp; private boolean instaAuthCheck = false; private DatePicker mBirthDatePicker; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account_edit_profile); mContext = this; //mApp = new InstagramApp(this, getString(R.string.insta_client_id), getString(R.string.insta_client_secret), getString(R.string.insta_redirect_url)); //mApp.setListener(instagramListener); GregorianCalendar calendar = new GregorianCalendar(); year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH); day = calendar.get(Calendar.DAY_OF_MONTH); ActionBar a = getSupportActionBar(); a.setDisplayHomeAsUpEnabled(true); a.setHomeAsUpIndicator(R.drawable.p08_bt_back); a.setTitle("ํ”„๋กœํ•„ ์ˆ˜์ •"); mNicknameEditText = (EditText) findViewById(R.id.edt_nickname); mPhoneEditText = (EditText) findViewById(R.id.edt_phone); //mInstagramButton = (Button) findViewById(R.id.btn_insta); mCommentEditText = (EditText) findViewById(R.id.edt_comment); mGenderButton = (Button) findViewById(R.id.btn_gender); mBirthButton = (Button) findViewById(R.id.btn_birth); mModifyButton = (Button) findViewById(R.id.btn_modify); mPhoneEditText.setEnabled(false); String birth = CommonData.LoginUserData.birthday; String gender = CommonData.LoginUserData.gender; if (birth != null) { mBirthButton.setText(birth); birthCheck = true; } if (gender != null) { if (gender.equals("male")) { this.gender = gender; mGenderButton.setText("๋‚จ์„ฑ"); genderCheck = true; } else if (gender.equals("female")) { this.gender = gender; mGenderButton.setText("์—ฌ์„ฑ"); genderCheck = true; } } mNicknameEditText.setText(CommonData.LoginUserData.userName); mPhoneEditText.setText(CommonData.LoginUserData.userId); if (CommonData.LoginUserData.comment != null && !CommonData.LoginUserData.comment.equals("null")) mCommentEditText.setText(CommonData.LoginUserData.comment); //mInstagramButton.setOnClickListener(this); mBirthButton.setOnClickListener(this); mGenderButton.setOnClickListener(this); mModifyButton.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { //case R.id.btn_insta: // mApp.authorize(); // break; case R.id.btn_birth: makeBirthDialog(); break; case R.id.btn_gender: makeGenderDialog(); break; case R.id.btn_modify: nickname = mNicknameEditText.getText().toString(); phone = mPhoneEditText.getText().toString(); comment = mCommentEditText.getText().toString(); if (Utils.isNicknameValid(nickname)) { if (genderCheck) { if (birthCheck) { if (Utils.isPhoneValid(phone)) { //if (instaAuthCheck) { //๋ชจ๋“  ํ˜•์‹ ์ผ์น˜ HashMap<String, Object> params = new HashMap<>(); params.put("userid", phone); params.put("session_token", CommonData.LoginUserData.loginToken); params.put("username", nickname); params.put("gender", gender); params.put("birthday", birth); // TODO: 2016-10-31 ์ง€์—ญ ๊ด€๋ จํ•œ๊ฒƒ์ด ๊ธฐํš์—์„œ ๋น ์ ธ์žˆ์Œ! params.put("address", CommonData.LoginUserData.address); // TODO: 2017-01-16 ์ธ์Šคํƒ€๊ทธ๋žจ ๊ด€๋ จ ์ˆ˜์ • - ์„œ๋ฒ„์—์„œ optional ํ•˜๊ฒŒ ๋ฐ”๋€Œ๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌ instaId = CommonData.LoginUserData.instagramId; instaName = CommonData.LoginUserData.instagramName; profileUrl = CommonData.LoginUserData.profileImgUrl; params.put("instagram", instaId); params.put("instagram_name", instaName); params.put("profile_img_url", profileUrl); params.put("comment", comment); NetData netData = new NetData(NetData.ProtocolType.USER_UPDATE, NetData.MethodType.POST, NetData.ProgressType.SPLASH, params); NetManager netManager = new NetManager(netData, mContext); netManager.setCallback(mNetManagerUserUpdateCallback); netManager.execute((Void) null); //} else { // Toast.makeText(mContext, "์ธ์Šคํƒ€๊ทธ๋žจ ์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค", Toast.LENGTH_SHORT).show(); //} } else { //ํฐ ํ˜•์‹ ๋ถˆ์ผ์น˜ Toast.makeText(this, "์œ ํšจํ•˜์ง€ ์•Š์€ ํœด๋Œ€ํฐ ๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show(); } } else { //์ƒ์ผ ์„ ํƒ ์•ˆํ•จ Toast.makeText(this, "์ƒ์ผ์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”", Toast.LENGTH_SHORT).show(); } } else { //์„ฑ๋ณ„ ์„ ํƒ ์•ˆํ•จ Toast.makeText(this, "์„ฑ๋ณ„์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”", Toast.LENGTH_SHORT).show(); } } else { //๋‹‰๋„ค์ž„ ๋ถ€์ ํ•ฉ mNicknameEditText.requestFocus(); Toast.makeText(this, "๋‹‰๋„ค์ž„์€ 2์ž๋ฆฌ ์ด์ƒ,14์ž๋ฆฌ ์ดํ•˜๋กœ ์„ค์ •ํ•ด์ฃผ์„ธ์š”", Toast.LENGTH_SHORT).show(); } break; } } //Spinner Dialog ์ƒ์„ฑ private void makeGenderDialog() { final String[] items = {"๋‚จ์„ฑ", "์—ฌ์„ฑ"}; AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle("์„ฑ๋ณ„ ์„ ํƒ"); b.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mGenderButton.setText(items[which]); if (which == 0) { gender = "male"; } else if (which == 1) { gender = "female"; } genderCheck = true; } }); b.show(); } private void makeBirthDialog() { LayoutInflater inflater = getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.dialog_datepicker, null); AlertDialog.Builder buider = new AlertDialog.Builder(this); buider.setTitle("์ƒ๋…„์›”์ผ"); buider.setView(dialogView); mBirthDatePicker = (DatePicker) dialogView.findViewById(R.id.dp_date); mBirthDatePicker.setTextColor(Color.BLACK) .setFlagTextColor(Color.BLACK) .setBackground(Color.WHITE) .setTextSize(50) .setFlagTextSize(15) .setRowNumber(5); buider.setPositiveButton("ํ™•์ธ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int year = mBirthDatePicker.getYear(); int monthOfYear = mBirthDatePicker.getMonth() - 1; int dayOfMonth = mBirthDatePicker.getDayOfMonth(); String monthStr = ""; String dayStr = ""; if (monthOfYear + 1 < 10) { monthStr = "0" + (monthOfYear + 1) + ""; } else { monthStr = (monthOfYear + 1) + ""; } if (dayOfMonth < 10) { dayStr = "0" + dayOfMonth + ""; } else { dayStr = dayOfMonth + ""; } String date = year + "-" + monthStr + "-" + dayStr; mBirthButton.setText(date); birth = date; birthCheck = true; } }); buider.setNegativeButton("์ทจ์†Œ", null); AlertDialog dialog = buider.create(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCanceledOnTouchOutside(false); dialog.show(); } /* private void makeBirthDialog() { DatePickerDialog d = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) { String monthStr = ""; String dayStr = ""; if (monthOfYear + 1 < 10) { monthStr = "0" + (monthOfYear + 1) + ""; } else { monthStr = (monthOfYear + 1) + ""; } if (dayOfMonth < 10) { dayStr = "0" + dayOfMonth + ""; } else { dayStr = dayOfMonth + ""; } String date = year + "-" + monthStr + "-" + dayStr; mBirthButton.setText(date); birth = date; birthCheck = true; } }, year, month, day); d.show(); } */ /* InstagramApp.OAuthAuthenticationListener instagramListener = new InstagramApp.OAuthAuthenticationListener() { @Override public void onSuccess() { mInstagramButton.setText(mApp.getUserName() + "์œผ๋กœ ์—ฐ๊ฒฐ๋˜์—ˆ์Šต๋‹ˆ๋‹ค"); instaName = mApp.getUserName(); instaId = mApp.getId(); profileUrl = mApp.getProfileUrl(); mInstagramButton.setOnClickListener(null);//๋น„ํ™œ์„ฑํ™” //mApp.resetAccessToken();//์ธ์Šคํƒ€๊ทธ๋žจ ์„ธ์…˜ ์ดˆ๊ธฐํ™” instaAuthCheck = true; } @Override public void onFail(String error) { Toast.makeText(AccountEditProfileActivity.this, error, Toast.LENGTH_SHORT).show(); } }; */ private NetManager.Callbacks mNetManagerUserUpdateCallback = new NetManager.Callbacks() { @Override public void result(JSONObject jsonObject) { if (jsonObject == null) { return; } try { int resultCode = jsonObject.getInt("result"); Log.d("callback : ", jsonObject.toString()); if (resultCode == 1) { //์„œ๋ฒ„ ์ˆ˜์ •๋จ : user ๋ฆฌํ„ดํ•˜์ง€ ์•Š์Œ /* JSONObject user = jsonObject.getJSONObject("user"); CommonData.LoginUserData.id = user.getInt("id");//ํšŒ์› ์ธ๋ฑ์Šค CommonData.LoginUserData.userId = user.getString("userid");//์•„์ด๋””(์ „ํ™”๋ฒˆํ˜ธ) CommonData.LoginUserData.userName = user.getString("username");//๋‹‰๋„ค์ž„ CommonData.LoginUserData.gender = user.getString("gender");//์„ฑ๋ณ„ CommonData.LoginUserData.birthday = user.getString("birthday");//์ƒ์ผ CommonData.LoginUserData.address = user.getString("address");//์ง€์—ญ CommonData.LoginUserData.comment = user.getString("comment");//์ž๊ธฐ์†Œ๊ฐœ CommonData.LoginUserData.instagramId = user.getString("instagram");//์ธ์Šคํƒ€ CommonData.LoginUserData.profileImgUrl = user.getString("profile_img_url");//์ธ์Šค if (user.has("dcode_id")) { CommonData.LoginUserData.dcodeId = user.getInt("dcode_id");//D-Code ์ธ๋ฑ์Šค } CommonData.LoginUserData.dMoney = user.getInt("dmoney");//D-Money์ž”์•ก CommonData.LoginUserData.level = user.getString("level");//๋ ˆ๋ฒจ(guest,h CommonData.LoginUserData.barcode = user.getString("barcode");//D-Money CommonData.LoginUserData.cDate = user.getString("cdate");//๊ฐ€์ž… ์‹œ๊ฐ */ CommonData.LoginUserData.userName = nickname; CommonData.LoginUserData.comment = comment; CommonData.LoginUserData.birthday = birth; CommonData.LoginUserData.gender = gender; CommonData.LoginUserData.instagramId = instaId; CommonData.LoginUserData.instagramName = instaName; CommonData.LoginUserData.profileImgUrl = profileUrl; Toast.makeText(mContext, "ํšŒ์›์ •๋ณด๋ฅผ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(AccountEditProfileActivity.this, MyPageTabActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); finish(); } else if (resultCode == 0) { Toast.makeText(mContext, "ํšŒ์›์ •๋ณด ์ˆ˜์ •์„ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.\n์ž ์‹œํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.", Toast.LENGTH_SHORT).show(); } else if (resultCode == 2) { Toast.makeText(mContext, "์กด์žฌํ•˜์ง€ ์•Š๋Š” ํšŒ์›์ž…๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "ํšŒ์›์ •๋ณด ์ˆ˜์ •์„ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.\n์ž ์‹œํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }; }
C#
UTF-8
5,424
2.546875
3
[ "MIT" ]
permissive
๏ปฟusing System; using System.Linq.Expressions; using CatFactory.ObjectRelationalMapping; namespace CatFactory.SqlServer.ObjectRelationalMapping { public static partial class EntityHelper { #pragma warning disable CS1591 public static EntityResult<TModel> SetColumnFor<TModel>(this EntityResult<TModel> result, Expression<Func<TModel, decimal>> selector, short prec = 0, short scale = 0, bool nullable = false, string type = null) where TModel : class { var column = new Column { Name = GetPropertyName(selector) }; if (result.Table.Columns.Contains(column)) { result.Table[column.Name].Prec = prec; result.Table[column.Name].Scale = scale; result.Table[column.Name].Nullable = nullable; if (!string.IsNullOrEmpty(type)) result.Table[column.Name].Type = type; } else { result.Table.Columns.Add(column); } return result; } public static EntityResult<TModel> SetColumnFor<TModel>(this EntityResult<TModel> result, Expression<Func<TModel, decimal?>> selector, short prec = 0, short scale = 0, bool nullable = false, string type = null) where TModel : class { var column = new Column { Name = GetPropertyName(selector) }; if (result.Table.Columns.Contains(column)) { result.Table[column.Name].Prec = prec; result.Table[column.Name].Scale = scale; result.Table[column.Name].Nullable = nullable; if (!string.IsNullOrEmpty(type)) result.Table[column.Name].Type = type; } else { result.Table.Columns.Add(column); } return result; } public static EntityResult<TModel> SetColumnFor<TModel>(this EntityResult<TModel> result, Expression<Func<TModel, double>> selector, short prec = 0, short scale = 0, bool nullable = false, string type = null) where TModel : class { var column = new Column { Name = GetPropertyName(selector) }; if (result.Table.Columns.Contains(column)) { result.Table[column.Name].Prec = prec; result.Table[column.Name].Scale = scale; result.Table[column.Name].Nullable = nullable; if (!string.IsNullOrEmpty(type)) result.Table[column.Name].Type = type; } else { result.Table.Columns.Add(column); } return result; } public static EntityResult<TModel> SetColumnFor<TModel>(this EntityResult<TModel> result, Expression<Func<TModel, double?>> selector, short prec = 0, short scale = 0, bool nullable = false, string type = null) where TModel : class { var column = new Column { Name = GetPropertyName(selector) }; if (result.Table.Columns.Contains(column)) { result.Table[column.Name].Prec = prec; result.Table[column.Name].Scale = scale; result.Table[column.Name].Nullable = nullable; if (!string.IsNullOrEmpty(type)) result.Table[column.Name].Type = type; } else { result.Table.Columns.Add(column); } return result; } public static EntityResult<TModel> SetColumnFor<TModel>(this EntityResult<TModel> result, Expression<Func<TModel, float>> selector, short prec = 0, short scale = 0, bool nullable = false, string type = null) where TModel : class { var column = new Column { Name = GetPropertyName(selector) }; if (result.Table.Columns.Contains(column)) { result.Table[column.Name].Prec = prec; result.Table[column.Name].Scale = scale; result.Table[column.Name].Nullable = nullable; if (!string.IsNullOrEmpty(type)) result.Table[column.Name].Type = type; } else { result.Table.Columns.Add(column); } return result; } public static EntityResult<TModel> SetColumnFor<TModel>(this EntityResult<TModel> result, Expression<Func<TModel, float?>> selector, short prec = 0, short scale = 0, bool nullable = false, string type = null) where TModel : class { var column = new Column { Name = GetPropertyName(selector) }; if (result.Table.Columns.Contains(column)) { result.Table[column.Name].Prec = prec; result.Table[column.Name].Scale = scale; result.Table[column.Name].Nullable = nullable; if (!string.IsNullOrEmpty(type)) result.Table[column.Name].Type = type; } else { result.Table.Columns.Add(column); } return result; } } }
JavaScript
UTF-8
1,843
2.640625
3
[]
no_license
import React, { Component } from 'react'; import WhiteCard from './WhiteCard'; import BlackCard from './BlackCard'; class Player extends Component { renderCards() { return this.props.cards.map((text, index) => { return ( <WhiteCard key={index} handleCardSelection={this.props.handleCardSelection} selection={this.props.cardSelection[text]} text={text} gameStarted={this.props.gameStarted} /> ) }); } renderSelection() { let sortedSelection = []; let cardSelection = this.props.cardSelection; for (let i = 0; i < this.props.blackCard.pick; i++) { sortedSelection.push(['', i + 1]); for (let text in cardSelection) { if (cardSelection[text] === sortedSelection[i][1]) { sortedSelection[i][0] = text; } } } return sortedSelection.map((card) => { return ( <div key={card[1]} className='selected-card' onClick={() => this.props.handleCardSelection(card[0])}> <p><span>{card[1]} </span>{card[0]}</p> </div> ) }) } render() { return ( <div className='player'> {this.props.blackCard ? <BlackCard text={this.props.blackCard.text} /> : '' } <div className='message'> <p>{this.props.message}</p> </div> <div className='selection'> {this.props.blackCard ? this.renderSelection() : ''} </div> <div className='white-cards'> {this.renderCards()} </div> {this.props.gameStarted && (Object.keys(this.props.cardSelection).length === this.props.blackCard.pick) ? <button onClick={this.props.handleCardSelectionSubmit}>OK</button> : '' } </div> ) } } export default Player;
Python
UTF-8
422
2.609375
3
[ "Apache-2.0" ]
permissive
class A: pass def foo(): pass class B: """""" pass def bar(): """""" pass class C: @property def x(self): return 42 @x.setter def x(self, value): pass @x.deleter def x(self): pass class Parent: """ Parent class doc """ def foo(self): """ Parent foo doc """ pass class Child(Parent): def foo(self): pass
Java
UTF-8
2,976
2.53125
3
[]
no_license
package com.project.teamup.service; import com.project.teamup.dao.TechnologyRepository; import com.project.teamup.model.Technology; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.context.SpringBootTest; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; /** * Junit Tests for the Technology Service. * Technology Repository is mocked. * @author Sonya * */ @RunWith(MockitoJUnitRunner.class) @SpringBootTest public class TechnologyServiceTest { @InjectMocks private TechnologyService technologyService; @Mock private TechnologyRepository technologyRepository; private Technology technology1; private Technology technology2; @Test public void getAll() { when(technologyRepository.findAll()).thenReturn(null); assertNull(technologyService.getAll()); List<Technology> technologies = new ArrayList<>(); technologies.add(technology1); technologies.add(technology2); when(technologyRepository.findAll()).thenReturn(technologies); assertEquals(2, technologyService.getAll().size()); Technology technology3 = new Technology(); technologies.add(technology3); assertNotEquals(2, technologyService.getAll().size()); } @Test public void save() { technology1 = new Technology(); technology1.setId(1L); technology1.setName("Java"); technology2 = new Technology(); technology2.setId(2L); technology2.setName("C#"); when(technologyRepository.save(technology1)).thenReturn(technology1); when(technologyRepository.save(technology2)).thenReturn(technology2); assertEquals("Java", technologyService.save(technology1).getName()); assertEquals(technology2.getId(), technologyService.save(technology2).getId()); } @Test public void delete() { technologyService.delete(1L); technologyService.delete(2L); Mockito.verify(technologyRepository).deleteById(1L); Mockito.verify(technologyRepository, times(2)).deleteById(any()); } @Test public void findById() { when(technologyRepository.findById(3L)).thenReturn(Optional.empty()); technology2 = new Technology(); technology2.setId(2L); technology2.setName("Java"); when(technologyRepository.findById(2L)).thenReturn(Optional.of(technology2)); assertTrue(technologyService.findById(2L).isPresent()); assertEquals(technology2.getName(), technologyService.findById(2L).get().getName()); assertFalse(technologyService.findById(3L).isPresent()); } }
Python
UTF-8
5,042
2.703125
3
[]
no_license
from urllib import request from PIL import Image import os from math import cos, sin, pi, log, atan, exp, floor import math from itertools import chain import re # 40.792801, -73.967553, 40.775645, -73.960642 BASEURL = 'http://ecn.t0.tiles.virtualearth.net/tiles/a{}.jpeg?g=8549' min_lat = 41.885108 min_lon = -87.615195 max_lat = 41.893812 max_lon = -87.597778 IMAGEMAXSIZE = 8192 * 8192 * 8 # max width/height in pixels for the retrived image TILESIZE = 256 # in Bing tile system, one tile image is in size 256 * 256 pixels class TileSystem: def __init__(self): self.EarthRadius = 6378137 self.MinLatitude, self.MaxLatitude = -85.05112878, 85.05112878 self.MinLongitude, self.MaxLongitude = -180., 180. self.MaxLevel = 20 def clip(self, val, minval, maxval): return min(max(val, minval), maxval) def map_size(self, level): return 256 << level def ground_resolution(self, lat, level): lat = self.clip(lat, self.MinLatitude, self.MaxLatitude) return cos(lat * pi / 180) * 2 * pi * self.EarthRadius / self.map_size(level) def map_scale(self, lat, level, screenDpi): return self.ground_resolution(lat, level) * screenDpi / 0.0254 def latlong_to_pixelXY(self, lat, long, level): lat = self.clip(lat, self.MinLatitude, self.MaxLatitude) long = self.clip(long, self.MinLongitude, self.MaxLongitude) x = (long + 180) / 360 sinlat = sin(lat * pi / 180) y = 0.5 - log((1 + sinlat) / (1 - sinlat)) / (4 * pi) mapsize = self.map_size(level) pixelX, pixelY = floor(self.clip(x * mapsize + 0.5, 0, mapsize - 1)), \ floor(self.clip(y * mapsize + 0.5, 0, mapsize - 1)) return pixelX, pixelY def pixelXY_to_latlong(self, pixelX, pixelY, level): mapsize = self.map_size(level) x = self.clip(pixelX, 0, mapsize - 1) / mapsize - 0.5 y = 0.5 - 360 * self.clip(pixelY, 0, mapsize - 1) / mapsize lat = 90 - 360 * atan(exp(-y * 2 * pi)) / pi long = 360 * x return lat, long def pixelXY_to_tileXY(self, pixelX, pixelY): return floor(pixelX / 256), floor(pixelY / 256) def tileXY_to_pixelXY(self, tileX, tileY): return tileX * 256, tileY * 256 def tileXY_to_quadkey(self, tileX, tileY, level): tileXbits = '{0:0{1}b}'.format(tileX, level) tileYbits = '{0:0{1}b}'.format(tileY, level) quadkeybinary = ''.join(chain(*zip(tileYbits, tileXbits))) return ''.join([str(int(num, 2)) for num in re.findall('..?', quadkeybinary)]) # return ''.join(i for j in zip(tileYbits, tileXbits) for i in j) def quadkey_to_tileXY(self, quadkey): quadkeybinary = ''.join(['{0:02b}'.format(int(num)) for num in quadkey]) tileX, tileY = int(quadkeybinary[1::2], 2), int(quadkeybinary[::2], 2) return tileX, tileY def horizontal_retrieval_and_stitch_image(tileX_start, tileX_end, tileY, level): imagelist = [] for tileX in range(tileX_start, tileX_end + 1): quadkey = tile_system.tileXY_to_quadkey(tileX, tileY, level) with request.urlopen(BASEURL.format(quadkey)) as file: image = Image.open(file) imagelist.append(image) result = Image.new('RGB', (len(imagelist) * TILESIZE, TILESIZE)) for i, image in enumerate(imagelist): result.paste(image, (i * TILESIZE, 0)) return result def main(): for level in range(tile_system.MaxLevel, 0, -1): print(level) X1, Y1 = tile_system.latlong_to_pixelXY(min_lat, min_lon, level) X2, Y2 = tile_system.latlong_to_pixelXY(max_lat, max_lon, level) X_min, X_max = min(X1, X2), max(X1, X2) Y_min, Y_max = min(Y1, Y2), max(Y1, Y2) if abs(X1 - X2) <= 1 or abs(Y1 - Y2) <= 1: break if abs(X1 - X2) * abs(Y1 - Y2) > IMAGEMAXSIZE: continue tileX1, tileY1 = tile_system.pixelXY_to_tileXY(X_min, Y_min) tileX2, tileY2 = tile_system.pixelXY_to_tileXY(X_max, Y_max) # Stitch the tile images together result = Image.new('RGB', ((tileX2 - tileX1 + 1) * TILESIZE, (tileY2 - tileY1 + 1) * TILESIZE)) retrieve_sucess = False for tileY in range(tileY1, tileY2 + 1): horizontal_image = horizontal_retrieval_and_stitch_image(tileX1, tileX2, tileY, level) result.paste(horizontal_image, (0, (tileY - tileY1) * TILESIZE)) # Crop the image based on the given bounding box leftup_cornerX, leftup_cornerY = tile_system.tileXY_to_pixelXY(tileX1, tileY1) retrieve_image = result.crop((X_min - leftup_cornerX, Y_min - leftup_cornerY, \ X_max - leftup_cornerX, Y_max - leftup_cornerY)) print("Finish the aerial image retrieval at", level) filename = os.path.join('images', 'aerialImage_{}.jpeg'.format(level)) retrieve_image.save(filename) if __name__ == '__main__': tile_system = TileSystem() main()
JavaScript
UTF-8
2,212
2.515625
3
[]
no_license
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; // action creators import { fetchPopularMovies } from '../actions'; // components import SearchBar from './SearchBar'; import Loading from './Loading'; import FetchMore from './FetchMore'; class MoviesList extends Component { componentDidMount() { const { movies = [] } = this.props; // if we haven't done a search yet then fetch for popular movies if (movies.length === 0) { this.props.fetchPopularMovies(); } } renderMovies() { const { isLoading, movies = [] } = this.props; if (isLoading) { return <Loading />; } if (movies.length === 0) { return ( <div className="alert alert-warning" role="alert"> No movies were found for the term , please check the spelling and try again! </div> ); } return movies.map(movie => { return ( <div className="card" key={movie.id}> <img className="card-img-top" src={`https://image.tmdb.org/t/p/w300${movie.poster_path}`} alt="..." /> <div className="card-body"> <h3 className="card-title">{movie.original_title}</h3> <p className="card-text">{movie.overview}</p> <Link to={`/detail/${movie.id}`} className="btn btn-outline-secondary">Read More &gt;</Link> </div> </div> ); }); } renderFetchMore() { const { isPopular } = this.props; if (!isPopular) { return <FetchMore />; } } render() { const moviesList = this.props.movies || []; return ( <div> <SearchBar /> <div className="container"> <div className={moviesList.length > 0 ? 'card-columns' : ''}> {this.renderMovies()} </div> {this.renderFetchMore()} </div> </div> ); } } function mapStateToProps(state) { return { movies: state.movies.moviesData.results, isLoading: state.movies.isLoading, isPopular: state.movies.isPopular }; } export default connect(mapStateToProps, {fetchPopularMovies})(MoviesList);
Rust
UTF-8
981
3.078125
3
[]
no_license
use crate::models::{SensorId, ReadingId, Bytes}; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Reading { pub sensor_id: SensorId, pub reading_id: ReadingId, pub data: Bytes, } impl Reading { pub fn new() -> Self { Reading { sensor_id: SensorId::default(), reading_id: ReadingId::default(), data: Bytes::default(), } } pub fn with_sensor_id(mut self, id: SensorId) -> Self { self.sensor_id = id; self } pub fn with_reading_id(mut self, id: ReadingId) -> Self { self.reading_id = id; self } pub fn with_data(mut self, data: Bytes) -> Self { self.data = data; self } pub fn get_sensor_id(&self) -> &SensorId { &self.sensor_id } pub fn get_reading_id(&self) -> &ReadingId { &self.reading_id } pub fn get_data(&self) -> &Bytes { &self.data } }
Markdown
UTF-8
768
2.953125
3
[]
no_license
# 31 (1501-1550) [โฌ€](https://leetcode.com/problemset/all/#page-31) | ID | Problem statement | Solution | |------|-------------------------------------------------------------------------------------------------------------------------------------|------------------------------| | 1502 | [1502. Can Make Arithmetic Progression From Sequence](https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/) | [1502/main.js](1502/main.js) | | 1507 | [1507. Reformat Date](https://leetcode.com/problems/reformat-date/) | [1507/main.js](1507/main.js) |
Java
UTF-8
689
2.828125
3
[]
no_license
//package com.igorhenss.SliceNdiceS.SliceNdiceS.enemies; // //import com.igorhenss.SliceNdiceS.SliceNdiceS.entity.Enemy; // //import javax.swing.*; //import java.awt.*; // //public class Goblin extends Enemy { // // public Goblin(Integer posX, Integer posY) { // super(posX, posY); // } // // public void update() { // // } // // public void draw(Graphics2D graphics2D) { // graphics2D.drawImage(getEnemyImage(), posX, posY, null); // } // // public Image getEnemyImage() { // ImageIcon sprite = new ImageIcon("C:/personal_files/SliceNdiceS/src/main/resources/images/archer_goblin_resized.png"); // return sprite.getImage(); // } // //}
Python
UTF-8
2,535
2.765625
3
[]
no_license
import string, random, math, time, os from hashlib import md5 import managers class VDOM_id: """id generation class""" def hexstr(self, s): """convert byte array to hex string""" h = string.hexdigits r = "" for c in s: i = ord(c) r = r + h[(i >> 4) & 0xF] + h[i & 0xF] return r def new(self): """generate new id""" md5obj = md5(str(time.time() + random.random() + math.sin(random.random()))) return self.hexstr(md5obj.digest()) def random_string(self, length): """generate random string of the specified length""" h = string.hexdigits r = "" for i in xrange(length): a = random.randint(0, 255) r = r + h[a & 0xF] return r def vdomid(): """generate new id""" return md5(b''.join([str(time.time()),_urandom(),str(math.sin(random.random()))])).hexdigest() def hexstr(s): """convert byte array to hex string""" h = string.hexdigits r = "" for c in s: i = ord(c) r = r + h[(i >> 4) & 0xF] + h[i & 0xF] return r def _urandom(): if hasattr(os, 'urandom'): return os.urandom(30) return text_type(random()).encode('ascii') def generate_key(salt=None): if salt is None: salt = repr(salt).encode('ascii') return sha1(b''.join([ salt, str(time.time()).encode('ascii'), _urandom() ])).hexdigest() def guid2mod(guid): """transform guid to module name""" return "module_" + "_".join(guid.split("-")) #def id2res(owner_id, res_id, res_type): # """transform owner id and resource id to resource name""" # return "res_" + owner_id + "_" + res_id + "." + res_type def id2link(res_id): """transform resource id to resource URL""" return "/%s.res"%res_id def id2link1(res_id): """transform resource id to resource URL""" o = managers.resource_manager.get_resource(None, res_id) if not o: return "" return "".join(["/", res_id, ".", o.res_format]) #def id2tempres(owner_id, tempres_id, res_type): #"""transform owner id and temporary resource id to temporary resource name""" #return "temp_" + owner_id + "_" + tempres_id + "." + res_type def is_valid_identifier(value): if value is "": return False first = value[0] if not ('_' == first or first.isalpha()): return False last = value[1:] for i in last: if not ('_' == i or i.isalnum()): return False return True
Swift
UTF-8
1,059
2.859375
3
[]
no_license
// // Bundle+Ext.swift // // // Created by Tiziano Cialfi on 19/01/21. // import Foundation public extension Bundle { private static let nameKey = "CFBundleName" private static let versionKey = "CFBundleShortVersionString" private static let buildKey = "CFBundleVersion" enum BundleError: Error { case valueNotFoundInInfoDictionary(String) } static func appBundleName() throws -> String { return try infoDictionaryValue(from: nameKey) } static func appVersion() throws -> String { return try infoDictionaryValue(from: versionKey) } static func appBuild() throws -> String { return try infoDictionaryValue(from: buildKey) } private static func infoDictionaryValue(from key: String) throws -> String { guard let dictionary = Bundle.main.infoDictionary, let value = dictionary[key] as? String else { throw BundleError.valueNotFoundInInfoDictionary(buildKey) } return value } }
C++
UTF-8
672
2.96875
3
[]
no_license
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { if (s.empty() || dict.empty()) return false; int len = s.length(); vector<bool> opt(len+1, false); opt[0] = true; for (int i = 0; i < len; i++) { for (int j = i; j >= 0; j--) { if (opt[j]) { string sub = subString(s, j, i); if (dict.count(sub) > 0) opt[i+1] = true; } } } return opt[len]; } string subString(string s, int begin, int end) { string res; for (int i = begin; i <= end; i++) res += s[i]; return res; } };
C++
UTF-8
1,892
2.671875
3
[]
no_license
#include "matching.h" #include <fstream> #include <ZGeom/util.h> std::vector<std::pair<int, int> > MatchPair::ToPairVector(const std::vector<MatchPair>& vmp) { std::vector<std::pair<int, int> > vp; for (const MatchPair& mp : vmp) vp.push_back((std::pair<int, int>)mp); return vp; } void MatchResult::write( const std::string& file ) const { std::ofstream ofs(file.c_str()); ofs << mMatchedPairs.size() << std::endl; for (auto p : mMatchedPairs) { ofs << p.first << ' ' << p.second << std::endl; } ofs.close(); } void MatchResult::read( const std::string& file ) { std::ifstream ifs(file.c_str()); ZGeom::runtime_assert(ifs.good(), "File " + file + " not exist!"); int size, idx1, idx2; ifs >> size; for (int i = 0; i < size; ++i) { ifs >> idx1 >> idx2; mMatchedPairs.insert(std::make_pair(idx1, idx2)); } ifs.close(); } void MatchEvaluation::printStats( bool withGroundTruth, bool withRelativeError, std::ostream& ostr /*= std::cout */ ) const { ostr << "** Match Evaluation Results **" << std::endl; ostr << "Matched count: " << mMatchedCount << "/" << mTotalToMatch << "(" << double(mMatchedCount)/mTotalToMatch << ")" << std::endl; if (withGroundTruth) { ostr << "Precise match count: " << mMatch0Count << "(" << double(mMatch0Count)/mTotalToMatch << ")" << std::endl; ostr << "1-ring match count: " << mMatch1Count << "(" << double(mMatch1Count)/mTotalToMatch << ")" << std::endl; ostr << "2-ring match count: " << mMatch2Count << "(" << double(mMatch2Count)/mTotalToMatch << ")" << std::endl; ostr << "Large error count: " << mLargeErrorCount << "(" << double(mLargeErrorCount)/mTotalToMatch << ")" << std::endl; ostr << "Average error by edge length: " << mAvgErrInEdgeLength << std::endl; } if (withRelativeError) ostr << "Average relative error: " << mAvgRelativeError << std::endl; ostr << "******************************" << std::endl; }
C++
GB18030
1,061
2.953125
3
[ "MIT" ]
permissive
#ifndef _IGRAPHICS_H #define _IGRAPHICS_H #include <map> using namespace std; class IGraphics { private: CRITICAL_SECTION cs; static IGraphics * instance; IGraphics() { InitializeCriticalSection(&cs); //สผูฝ }; ~IGraphics() { LeaveCriticalSection(&cs);//๋ฟชูฝ DeleteCriticalSection(&cs);//ษพูฝ }; public: map<CObject*,CGraphics*> graphics; static IGraphics * getInstance() { return instance; } void addGraph(CObject * stage) { EnterCriticalSection(&cs); LeaveCriticalSection(&cs); } void removeGraph(CObject * stage) { EnterCriticalSection(&cs); graphics.erase(stage); LeaveCriticalSection(&cs); } CGraphics * getGraph(CObject * stage) { CGraphics * graph = NULL; EnterCriticalSection(&cs); graph = graphics[stage]; LeaveCriticalSection(&cs); return graph; } }; IGraphics * IGraphics::instance=new IGraphics(); //รฝำฟฺตศซึธ IGraphics * iGraphics = IGraphics::getInstance(); #endif
C#
UTF-8
774
2.890625
3
[]
no_license
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AreaCalculator { public class FormFactory { public AreaCalculatorForm GetAreaCalculatorForm(string shapeType) { AreaCalculatorForm areaCalculatorForm; switch (shapeType) { case "Circle": areaCalculatorForm = new CircleAreaCalculator(); break; case "Rectangle": areaCalculatorForm = new RecatangleAreaCalculator(); break; default: throw new NotSupportedException(); } return areaCalculatorForm; } } }
Python
UTF-8
7,081
2.515625
3
[]
no_license
# Uncomment and execute once - this is used to downgrade the pip version to one that doesn't cause an exception in keras # https://github.com/tensorflow/tensorflow/issues/28102#issuecomment-487612628 #!pip install numpy==1.16.2 import logging logging.getLogger('tensorflow').disabled = True import warnings # Importing numpy and Keras (specifically TensorFlow) causes printing of deprecation warnings. # We suppress the warnings by filtering and by disabling the tensorflow logger and with warnings.catch_warnings(): warnings.simplefilter("ignore") import numpy as np import keras from enum import Enum import os MODEL_1_PATH = os.path.join("models", "model_1.hdf5") MODEL_2_PATH = os.path.join("models", "model_2.hdf5") MODEL_3_PATH = os.path.join("models", "model_3.hdf5") MODEL_4_PATH = os.path.join("models", "model_4.hdf5") MODEL_5_PATH = os.path.join("models", "model_5.hdf5") # Pre-loading models models = [] print("Loading model 1") models.append(keras.models.load_model(MODEL_1_PATH)) print("Loading model 2") models.append(keras.models.load_model(MODEL_2_PATH)) print("Loading model 3") models.append(keras.models.load_model(MODEL_3_PATH)) print("Loading model 4") models.append(keras.models.load_model(MODEL_4_PATH)) print("Loading model 5") models.append(keras.models.load_model(MODEL_5_PATH)) MAX_LEN = 1000 OOV_WORD_INDEX = 2 class Label(Enum): POSITIVE = 0 NEGATIVE = 1 def predict_review_label(review, model): words = review.split() word_index = keras.datasets.imdb.get_word_index() my_index = [] for word in words: if word in word_index: my_index.append(word_index[word]) else: my_index.append(OOV_WORD_INDEX) seq = np.array(my_index) padded_seq = keras.preprocessing.sequence.pad_sequences([seq], maxlen=MAX_LEN, dtype='int32', padding='pre') return model.predict_classes(padded_seq) def predict_review_prob(review, model): words = review.split() word_index = keras.datasets.imdb.get_word_index() my_index = [] for word in words: if word in word_index: my_index.append(word_index[word]) else: my_index.append(OOV_WORD_INDEX) seq = np.array(my_index) padded_seq = keras.preprocessing.sequence.pad_sequences([seq], maxlen=MAX_LEN, dtype='int32', padding='pre') return model.predict_proba(padded_seq) def getProbAndLabel(review): print("\n======================================================\n") predicted_labels = [] predicted_probs = [] for i in range(len(models)): print("Testing model {0} out of {1}".format(i+1, len(models))) try: predicted_labels.append(predict_review_label(review, models[i])[0][0]) prob = predict_review_prob(review, models[i])[0][0] # The probability is for the label 1, so we need to adjust it if the label is 0 if predicted_labels[-1] == 0: prob = 1 - prob predicted_probs.append(prob) print("label: {}".format(Label(predicted_labels[-1]).name)) print("prob: {}".format(predicted_probs[-1])) except Exception as e: print("Unknown word:") print(e) pass # If for some reason none of the models succeed to evaluate the given review, # return pre-defined values if len(predicted_labels) == 0: return {'final_label' : Label.POSITIVE.name, "final_prob" : 0.5} final_label = Label.POSITIVE \ if predicted_labels.count(Label.POSITIVE.value) > predicted_labels.count(Label.NEGATIVE.value) \ else Label.NEGATIVE print("Final label: {}".format(Label(final_label).name)) # Calculate the average label probability, using only the probabilities of the # chosen label. final_prob = 0 counted_probs = 0 for i in range(len(predicted_probs)): if predicted_labels[i] == final_label.value: final_prob += predicted_probs[i] counted_probs += 1 final_prob /= float(counted_probs) print("Final prob: {}".format(final_prob)) reviewProbAndLabel = {'final_label' : Label(final_label).name, "final_prob" : final_prob} return reviewProbAndLabel if __name__ == '__main__': # 1 -> good, 2 -> good, 3 -> bad, 4 -> bad, 5 -> bad, 6 -> good reviews = [ """Hobbs and Shaw is fresh and feels like a standalone. You really don't need to watch the other films to enjoy it, but if you want to learn the history off Hobbs and Shaw then feel free to go back and watch the last 3 installments. There is no Dominic Toretto and his crew. Fresh new story, characters, and theme. Vanessa Kirby shines as Hattie, Idris Elba shines as black superman, Hobbs and Shaw shines, Ezia Gonzalez shines as Madam M. I really love that they have put more focus into Hobbs and his daughter Samantha's relationship. I also love that they're teasing a romantic relationship between Luke Hobbs and Hattie Shaw which happens to be the sister of Owen and Deckard. Btw she kicks major behind. There are two BIG cameos in this film, a bunch of easter eggs, and a crazy fight sequence that takes place in Samoa, Hobbs homeland. It's a really good action-packed heartfelt film and I think you'd enjoy it. 8/10 The summer is almost over so sit back and enjoy Hobbs and Shaw for what it is.""", """Just saw it, Great movie with Great chemistry between Jason and the Rock. The movie was packed with a lot of action Great lines and Some wonderful suprises. A must see for the fast and furious fans!""", """No story. And Nothing new n too boring. Super Villain was super human but hob n shaw were like robots who cant get injured even. Its total money waste.""", """This is a seriously bad movie. I liked the look of the trailers but the movie itself was overlong and bad.""", """Its was just waste of time. Simple words. A display of pathetic movie, with all the hype created. Pity!""", """Great job from fast and furious must watch in cinema only to enjoy the sounds !!! Amazing night""", ] for review in reviews: #review = "Hobbs and Shaw is fresh and feels like a standalone. You really don't need to watch the other films to enjoy it, but if you want to learn the history off Hobbs and Shaw then feel free to go back and watch the last 3 installments. There is no Dominic Toretto and his crew. Fresh new story, characters, and theme. Vanessa Kirby shines as Hattie, Idris Elba shines as black superman, Hobbs and Shaw shines, Ezia Gonzalez shines as Madam M. I really love that they have put more focus into Hobbs and his daughter Samantha's relationship. I also love that they're teasing a romantic relationship between Luke Hobbs and Hattie Shaw which happens to be the sister of Owen and Deckard. Btw she kicks major behind. There are two BIG cameos in this film, a bunch of easter eggs, and a crazy fight sequence that takes place in Samoa, Hobbs homeland. It's a really good action-packed heartfelt film and I think you'd enjoy it. 8/10 The summer is almost over so sit back and enjoy Hobbs and Shaw for what it is." print(getProbAndLabel(review))
Shell
UTF-8
1,210
2.609375
3
[]
no_license
#!/bin/bash cd "$(dirname "$0")" # Install DHT22 Service sudo cp dht22.service /etc/systemd/system/dht22.service sudo cp dht22-mqtt.service /etc/systemd/system/dht22-mqtt.service #sudo systemctl enable dht22.service #sudo systemctl enable dht22-mqtt.service # Install L3GD20 Service sudo cp l3gd20.service /etc/systemd/system/l3gd20.service sudo cp l3gd20-mqtt.service /etc/systemd/system/l3gd20-mqtt.service #sudo systemctl enable l3gd20.service #sudo systemctl enable l3gd20-mqtt.service # Install LSM303 Service sudo cp lsm303.service /etc/systemd/system/lsm303.service sudo cp lsm303.service /etc/systemd/system/lsm303-mqtt.service #sudo systemctl enable lsm303.service #sudo systemctl enable lsm303-mqtt.service # Install MTK3339 Service sudo cp mtk3339.service /etc/systemd/system/mtk3339.service sudo cp mtk3339-mqtt.service /etc/systemd/system/mtk3339-mqtt.service #sudo systemctl enable mtk3339.service #sudo systemctl enable mtk3339-mqtt.service # Install TSL2591 Service sudo cp tsl2591.service /etc/systemd/system/tsl2591.service sudo cp tsl2591-mqtt.service /etc/systemd/system/tsl2591-mqtt.service #sudo systemctl enable tsl2591.service #sudo systemctl enable tsl2591-mqtt.service
Java
UTF-8
434
2.953125
3
[]
no_license
public class ExcelSheetColumnNumber { public int titleToNumber(String s) { if (s==null||s.length()==0) return 0; int length=1; int total=0; for (int i = s.length()-1; i >=0 ; i--,length*=26) { if (length==1) total+=s.charAt(i)-'A'+1; else { total+=(s.charAt(i)-'A'+1)*length; } } return total; } }
Markdown
UTF-8
16,875
3.296875
3
[]
no_license
ะžัะฝะพะฒะฝั‹ะต ัƒั‡ะตะฑะฝั‹ะต ะทะฐะดะฐั‡ะธ ั€ะตะฐะปะธะทะพะฒะฐะฝะฝั‹ะต ะฝะฐ ะฟั€ะธะฝั†ะธะฟั‹ OOP: 1. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั ั ะธะผะตะฝะตะผ Address. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ั‚ั€ะตะฑัƒะตั‚ัั ัะพะทะดะฐั‚ัŒ ะฟะพะปั: index, country, city, street, house, apartment. ะ”ะปั ะบะฐะถะดะพะณะพ ะฟะพะปั, ัะพะทะดะฐั‚ัŒ ัะฒะพะนัั‚ะฒะพ ั ะดะฒัƒะผั ะผะตั‚ะพะดะฐะผะธ ะดะพัั‚ัƒะฟะฐ. ะกะพะทะดะฐั‚ัŒ ัะบะทะตะผะฟะปัั€ ะบะปะฐััะฐ Address. ะ’ ะฟะพะปั ัะบะทะตะผะฟะปัั€ะฐ ะทะฐะฟะธัะฐั‚ัŒ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะฟะพั‡ั‚ะพะฒะพะผ ะฐะดั€ะตัะต. ะ’ั‹ะฒะตะดะธั‚ะต ะฝะฐ ัะบั€ะฐะฝ ะทะฝะฐั‡ะตะฝะธั ะฟะพะปะตะน, ะพะฟะธัั‹ะฒะฐัŽั‰ะธั… ะฐะดั€ะตั. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/blob/master/Lesson1_Homework/AdditionalTask/Program.cs 2. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั ั ะธะผะตะฝะตะผ Rectangle. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐั‚ัŒ ะดะฒะฐ ะฟะพะปั, ะพะฟะธัั‹ะฒะฐัŽั‰ะธะต ะดะปะธะฝั‹ ัั‚ะพั€ะพะฝ double side1, side2. ะกะพะทะดะฐั‚ัŒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะธะน ะบะพะฝัั‚ั€ัƒะบั‚ะพั€ Rectangle(double side1, double side2), ะฒ ั‚ะตะปะต ะบะพั‚ะพั€ะพะณะพ ะฟะพะปั side1 ะธ side2 ะธะฝะธั†ะธะฐะปะธะทะธั€ัƒัŽั‚ัั ะทะฝะฐั‡ะตะฝะธัะผะธ ะฐั€ะณัƒะผะตะฝั‚ะพะฒ. ะกะพะทะดะฐั‚ัŒ ะดะฒะฐ ะผะตั‚ะพะดะฐ, ะฒั‹ั‡ะธัะปััŽั‰ะธะต ะฟะปะพั‰ะฐะดัŒ ะฟั€ัะผะพัƒะณะพะปัŒะฝะธะบะฐ - double AreaCalculator() ะธ ะฟะตั€ะธะผะตั‚ั€ ะฟั€ัะผะพัƒะณะพะปัŒะฝะธะบะฐ - double PerimeterCalculator(). ะกะพะทะดะฐั‚ัŒ ะดะฒะฐ ัะฒะพะนัั‚ะฒะฐ double Area ะธ double Perimeter ั ะพะดะฝะธะผ ะผะตั‚ะพะดะพะผ ะดะพัั‚ัƒะฟะฐ get. ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฟั€ะธะฝะธะผะฐะตั‚ ะพั‚ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั ะดะปะธะฝั‹ ะดะฒัƒั… ัั‚ะพั€ะพะฝ ะฟั€ัะผะพัƒะณะพะปัŒะฝะธะบะฐ ะธ ะฒั‹ะฒะพะดะธั‚ ะฝะฐ ัะบั€ะฐะฝ ะฟะตั€ะธะผะตั‚ั€ ะธ ะฟะปะพั‰ะฐะดัŒ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/blob/master/Lesson1_Homework/Task2/Program.cs 3. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั Book. ะกะพะทะดะฐั‚ัŒ ะบะปะฐััั‹ Title, Author ะธ Content, ะบะฐะถะดั‹ะน ะธะท ะบะพั‚ะพั€ั‹ั… ะดะพะปะถะตะฝ ัะพะดะตั€ะถะฐั‚ัŒ ะพะดะฝะพ ัั‚ั€ะพะบะพะฒะพะต ะฟะพะปะต ะธ ะผะตั‚ะพะด void Show(). ะ ะตะฐะปะธะทัƒะนั‚ะต ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะดะพะฑะฐะฒะปะตะฝะธั ะฒ ะบะฝะธะณัƒ ะฝะฐะทะฒะฐะฝะธั ะบะฝะธะณะธ, ะธะผะตะฝะธ ะฐะฒั‚ะพั€ะฐ ะธ ัะพะดะตั€ะถะฐะฝะธั. ะ’ั‹ะฒะตะดะธั‚ะต ะฝะฐ ัะบั€ะฐะฝ ั€ะฐะทะฝั‹ะผะธ ั†ะฒะตั‚ะฐะผะธ ะฟั€ะธ ะฟะพะผะพั‰ะธ ะผะตั‚ะพะดะฐ Show() ะฝะฐะทะฒะฐะฝะธะต ะบะฝะธะณะธ, ะธะผั ะฐะฒั‚ะพั€ะฐ ะธ ัะพะดะตั€ะถะฐะฝะธะต. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson1_Homework/Task3 4. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐััั‹ Point ะธ Figure. ะšะปะฐัั Point ะดะพะปะถะตะฝ ัะพะดะตั€ะถะฐั‚ัŒ ะดะฒะฐ ั†ะตะปะพั‡ะธัะปะตะฝะฝั‹ั… ะฟะพะปั ะธ ะพะดะฝะพ ัั‚ั€ะพะบะพะฒะพะต ะฟะพะปะต. ะกะพะทะดะฐั‚ัŒ ั‚ั€ะธ ัะฒะพะนัั‚ะฒะฐ ั ะพะดะฝะธะผ ะผะตั‚ะพะดะพะผ ะดะพัั‚ัƒะฟะฐ get. ะกะพะทะดะฐั‚ัŒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะธะน ะบะพะฝัั‚ั€ัƒะบั‚ะพั€, ะฒ ั‚ะตะปะต ะบะพั‚ะพั€ะพะณะพ ะฟั€ะพะธะฝะธั†ะธะฐะปะธะทะธั€ัƒะนั‚ะต ะฟะพะปั ะทะฝะฐั‡ะตะฝะธัะผะธ ะฐั€ะณัƒะผะตะฝั‚ะพะฒ. ะšะปะฐัั Figure ะดะพะปะถะตะฝ ัะพะดะตั€ะถะฐั‚ัŒ ะบะพะฝัั‚ั€ัƒะบั‚ะพั€ั‹, ะบะพั‚ะพั€ั‹ะต ะฟั€ะธะฝะธะผะฐัŽั‚ ะพั‚ 3-ั… ะดะพ 5-ั‚ะธ ะฐั€ะณัƒะผะตะฝั‚ะพะฒ ั‚ะธะฟะฐ Point. ะกะพะทะดะฐั‚ัŒ ะดะฒะฐ ะผะตั‚ะพะดะฐ: double LengthSide(Point A, Point B), ะบะพั‚ะพั€ั‹ะน ั€ะฐััั‡ะธั‚ั‹ะฒะฐะตั‚ ะดะปะธะฝัƒ ัั‚ะพั€ะพะฝั‹ ะผะฝะพะณะพัƒะณะพะปัŒะฝะธะบะฐ; void PerimeterCalculator(), ะบะพั‚ะพั€ั‹ะน ั€ะฐััั‡ะธั‚ั‹ะฒะฐะตั‚ ะฟะตั€ะธะผะตั‚ั€ ะผะฝะพะณะพัƒะณะพะปัŒะฝะธะบะฐ. ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฒั‹ะฒะพะดะธั‚ ะฝะฐ ัะบั€ะฐะฝ ะฝะฐะทะฒะฐะฝะธะต ะธ ะฟะตั€ะธะผะตั‚ั€ ะผะฝะพะณะพัƒะณะพะปัŒะฝะธะบะฐ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson1_Homework/Task4 5. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั User, ัะพะดะตั€ะถะฐั‰ะธะน ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะต (ะปะพะณะธะฝ, ะธะผั, ั„ะฐะผะธะปะธั, ะฒะพะทั€ะฐัั‚, ะดะฐั‚ะฐ ะทะฐะฟะพะปะฝะตะฝะธั ะฐะฝะบะตั‚ั‹). ะŸะพะปะต ะดะฐั‚ะฐ ะทะฐะฟะพะปะฝะตะฝะธั ะฐะฝะบะตั‚ั‹ ะดะพะปะถะฝะพ ะฑั‹ั‚ัŒ ะฟั€ะพะธะฝะธั†ะธะฐะปะธะทะธั€ะพะฒะฐะฝะพ ั‚ะพะปัŒะบะพ ะพะดะธะฝ ั€ะฐะท (ะฟั€ะธ ัะพะทะดะฐะฝะธะธ ัะบะทะตะผะฟะปัั€ะฐ ะดะฐะฝะฝะพะณะพ ะบะปะฐััะฐ) ะฑะตะท ะฒะพะทะผะพะถะฝะพัั‚ะธ ะตะณะพ ะดะฐะปัŒะฝะตะนัˆะตะณะพ ะธะทะผะตะฝะตะฝะธั. ะ ะตะฐะปะธะทัƒะนั‚ะต ะฒั‹ะฒะพะด ะฝะฐ ัะบั€ะฐะฝ ะธะฝั„ะพั€ะผะฐั†ะธะธ ะพ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปะต. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson2_Homework/Lesson2/Additional%20task 6. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั Converter. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐั‚ัŒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะธะน ะบะพะฝัั‚ั€ัƒะบั‚ะพั€, ะบะพั‚ะพั€ั‹ะน ะฟั€ะธะฝะธะผะฐะตั‚ ั‚ั€ะธ ะฒะตั‰ะตัั‚ะฒะตะฝะฝั‹ั… ะฐั€ะณัƒะผะตะฝั‚ะฐ, ะธ ะธะฝะธั†ะธะฐะปะธะทะธั€ัƒะตั‚ ะฟะพะปั ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธะต ะบัƒั€ััƒ 3-ั… ะพัะฝะพะฒะฝั‹ั… ะฒะฐะปัŽั‚, ะฟะพ ะพั‚ะฝะพัˆะตะฝะธัŽ ะบ ะณั€ะธะฒะฝะต โ€“ public Converter(double usd, double eur, double rub). ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฑัƒะดะตั‚ ะฒั‹ะฟะพะปะฝัั‚ัŒ ะบะพะฝะฒะตั€ั‚ะฐั†ะธัŽ ะธะท ะณั€ะธะฒะฝั‹ ะฒ ะพะดะฝัƒ ะธะท ัƒะบะฐะทะฐะฝะฝั‹ั… ะฒะฐะปัŽั‚, ั‚ะฐะบะถะต ะฟั€ะพะณั€ะฐะผะผะฐ ะดะพะปะถะฝะฐ ะฟั€ะพะธะทะฒะพะดะธั‚ัŒ ะบะพะฝะฒะตั€ั‚ะฐั†ะธัŽ ะธะท ัƒะบะฐะทะฐะฝะฝั‹ั… ะฒะฐะปัŽั‚ ะฒ ะณั€ะธะฒะฝัƒ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson2_Homework/Lesson2/Task2 7. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั Employee. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐั‚ัŒ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒัะบะธะน ะบะพะฝัั‚ั€ัƒะบั‚ะพั€, ะบะพั‚ะพั€ั‹ะน ะฟั€ะธะฝะธะผะฐะตั‚ ะดะฒะฐ ัั‚ั€ะพะบะพะฒั‹ั… ะฐั€ะณัƒะผะตะฝั‚ะฐ, ะธ ะธะฝะธั†ะธะฐะปะธะทะธั€ัƒะตั‚ ะฟะพะปั, ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธะต ั„ะฐะผะธะปะธะธ ะธ ะธะผะตะฝะธ ัะพั‚ั€ัƒะดะฝะธะบะฐ. ะกะพะทะดะฐั‚ัŒ ะผะตั‚ะพะด ั€ะฐััั‡ะธั‚ั‹ะฒะฐัŽั‰ะธะน ะพะบะปะฐะด ัะพั‚ั€ัƒะดะฝะธะบะฐ (ะฒ ะทะฐะฒะธัะธะผะพัั‚ะธ ะพั‚ ะดะพะปะถะฝะพัั‚ะธ ะธ ัั‚ะฐะถะฐ) ะธ ะฝะฐะปะพะณะพะฒั‹ะน ัะฑะพั€. ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฒั‹ะฒะพะดะธั‚ ะฝะฐ ัะบั€ะฐะฝ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ัะพั‚ั€ัƒะดะฝะธะบะต (ั„ะฐะผะธะปะธั, ะธะผั, ะดะพะปะถะฝะพัั‚ัŒ), ะพะบะปะฐะด ะธ ะฝะฐะปะพะณะพะฒั‹ะน ัะฑะพั€. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson2_Homework/Lesson2/Task3 8. ะ’ ะบะปะฐััะต MyClass ั€ะตะฐะปะธะทัƒะนั‚ะต ะผะตั‚ะพะด IsLuckyTicket, ะบะพั‚ะพั€ั‹ะน ะดะพะปะถะตะฝ ะฟั€ะธะฝะธะผะฐั‚ัŒ ะฝะฐ ะฒั…ะพะด ัั‚ั€ะพะบะพะฒะพะต ะฟั€ะตะดัั‚ะฐะฒะปะตะฝะธะต ัˆะตัั‚ะธะทะฝะฐั‡ะฝะพะณะพ ะฝะพะผะตั€ะฐ ะปะพั‚ะตั€ะตะนะฝะพะณะพ ะฑะธะปะตั‚ะฐ, ะธ ะฒะพะทะฒั€ะฐั‰ะฐั‚ัŒ ะทะฝะฐั‡ะตะฝะธะต, ัะฒะปัะตั‚ัั ะปะธ ะพะฝ ยซัั‡ะฐัั‚ะปะธะฒั‹ะผยป - ั‚ะพ ะตัั‚ัŒ, ั€ะฐะฒะฝะฐ ะปะธ ััƒะผะผะฐ ะฟะตั€ะฒั‹ั… ั‚ั€ะตั… ั†ะธั„ั€ ััƒะผะผะต ะพัั‚ะฐะปัŒะฝั‹ั… ั‚ั€ะตั…. ะะฐะฟั€ะธะผะตั€: โ€œ123006โ€ โ€“ ัั‡ะฐัั‚ะปะธะฒั‹ะน, ะฐ โ€œ345123โ€ โ€“ ะฝะตั‚. ะะฐ ะปัŽะฑัƒัŽ ะฝะตะบะพั€ั€ะตะบั‚ะฝัƒัŽ ะฒั…ะพะดะฝัƒัŽ ัั‚ั€ะพะบัƒ ะผะตั‚ะพะด ะดะพะปะถะตะฝ ะฒะพะทะฒั€ะฐั‰ะฐั‚ัŒ ะทะฝะฐั‡ะตะฝะธะต false. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/blob/master/Lesson2_Homework/Lesson2/Task3_trenagor/Program.cs 9. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั Invoice. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐั‚ัŒ ั‚ั€ะธ ะฟะพะปั int account, string customer, string provider, ะบะพั‚ะพั€ั‹ะต ะดะพะปะถะฝั‹ ะฑั‹ั‚ัŒ ะฟั€ะพะธะฝะธั†ะธะฐะปะธะทะธั€ะพะฒะฐะฝั‹ ะพะดะธะฝ ั€ะฐะท (ะฟั€ะธ ัะพะทะดะฐะฝะธะธ ัะบะทะตะผะฟะปัั€ะฐ ะดะฐะฝะฝะพะณะพ ะบะปะฐััะฐ) ะฑะตะท ะฒะพะทะผะพะถะฝะพัั‚ะธ ะธั… ะดะฐะปัŒะฝะตะนัˆะตะณะพ ะธะทะผะตะฝะตะฝะธั. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐั‚ัŒ ะดะฒะฐ ะทะฐะบั€ั‹ั‚ั‹ั… ะฟะพะปั string article, int quantity ะกะพะทะดะฐั‚ัŒ ะผะตั‚ะพะด ั€ะฐัั‡ะตั‚ะฐ ัั‚ะพะธะผะพัั‚ะธ ะทะฐะบะฐะทะฐ ั ะะ”ะก ะธ ะฑะตะท ะะ”ะก. ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฒั‹ะฒะพะดะธั‚ ะฝะฐ ัะบั€ะฐะฝ ััƒะผะผัƒ ะพะฟะปะฐั‚ั‹ ะทะฐะบะฐะทะฐะฝะฝะพะณะพ ั‚ะพะฒะฐั€ะฐ ั ะะ”ะก ะธะปะธ ะฑะตะท ะะ”ะก. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson2_Homework/Lesson2/Task4 10. ะ—ะฐะดะฐะฝะธะต: ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐะนั‚ะต ะบะปะฐัั Printer. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐะนั‚ะต ะผะตั‚ะพะด void Print(string value), ะบะพั‚ะพั€ั‹ะน ะฒั‹ะฒะพะดะธั‚ ะฝะฐ ัะบั€ะฐะฝ ะทะฝะฐั‡ะตะฝะธะต ะฐั€ะณัƒะผะตะฝั‚ะฐ. ะ ะตะฐะปะธะทัƒะนั‚ะต ะฒะพะทะผะพะถะฝะพัั‚ัŒ ั‚ะพะณะพ, ั‡ั‚ะพะฑั‹ ะฒ ัะปัƒั‡ะฐะต ะฝะฐัะปะตะดะพะฒะฐะฝะธั ะพั‚ ะดะฐะฝะฝะพะณะพ ะบะปะฐััะฐ ะดั€ัƒะณะธั… ะบะปะฐััะพะฒ, ะธ ะฒั‹ะทะพะฒะต ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะตะณะพ ะผะตั‚ะพะดะฐ ะธั… ัะบะทะตะผะฟะปัั€ะฐ, ัั‚ั€ะพะบะธ, ะฟะตั€ะตะดะฐะฝะฝั‹ะต ะฒ ะบะฐั‡ะตัั‚ะฒะต ะฐั€ะณัƒะผะตะฝั‚ะพะฒ ะผะตั‚ะพะดะพะฒ, ะฒั‹ะฒะพะดะธะปะธััŒ ั€ะฐะทะฝั‹ะผะธ ั†ะฒะตั‚ะฐะผะธ. ะžะฑัะทะฐั‚ะตะปัŒะฝะพ ะธัะฟะพะปัŒะทัƒะนั‚ะต ะฟั€ะธะฒะตะดะตะฝะธะต ั‚ะธะฟะพะฒ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson%203_HomeWork/Additional%20Task 11. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั, ะฟั€ะตะดัั‚ะฐะฒะปััŽั‰ะธะน ัƒั‡ะตะฑะฝั‹ะน ะบะปะฐัั ClassRoom. ะกะพะทะดะฐะนั‚ะต ะบะปะฐัั ัƒั‡ะตะฝะธะบ Pupil. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐะนั‚ะต ะผะตั‚ะพะดั‹ void Study(), void Read(), void Write(), void Relax(). ะกะพะทะดะฐะนั‚ะต 3 ะฟั€ะพะธะทะฒะพะดะฝั‹ั… ะบะปะฐััะฐ ExcelentPupil, GoodPupil, BadPupil ะพั‚ ะบะปะฐััะฐ ะฑะฐะทะพะฒะพะณะพ ะบะปะฐััะฐ Pupil ะธ ะฟะตั€ะตะพะฟั€ะตะดะตะปะธั‚ะต ะบะฐะถะดั‹ะน ะธะท ะผะตั‚ะพะดะพะฒ, ะฒ ะทะฐะฒะธัะธะผะพัั‚ะธ ะพั‚ ัƒัะฟะตะฒะฐะตะผะพัั‚ะธ ัƒั‡ะตะฝะธะบะฐ. ะšะพะฝัั‚ั€ัƒะบั‚ะพั€ ะบะปะฐััะฐ ClassRoom ะฟั€ะธะฝะธะผะฐะตั‚ ะฐั€ะณัƒะผะตะฝั‚ั‹ ั‚ะธะฟะฐ Pupil, ะบะปะฐัั ะดะพะปะถะตะฝ ัะพัั‚ะพัั‚ัŒ ะธะท 4 ัƒั‡ะตะฝะธะบะพะฒ. ะŸั€ะตะดัƒัะผะพั‚ั€ะธั‚ะต ะฒะพะทะผะพะถะฝะพัั‚ัŒ ั‚ะพะณะพ, ั‡ั‚ะพ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะผะพะถะตั‚ ะฟะตั€ะตะดะฐั‚ัŒ 2 ะธะปะธ 3 ะฐั€ะณัƒะผะตะฝั‚ะฐ. ะ’ั‹ะฒะตะดะธั‚ะต ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ั‚ะพะผ, ะบะฐะบ ะฒัะต ัƒั‡ะตะฝะธะบะธ ัะบะทะตะผะฟะปัั€ะฐ ะบะปะฐััะฐ ClassRoom ัƒะผะตัŽั‚ ัƒั‡ะธั‚ัŒัั, ั‡ะธั‚ะฐั‚ัŒ, ะฟะธัะฐั‚ัŒ, ะพั‚ะดั‹ั…ะฐั‚ัŒ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson%203_HomeWork/Task2 12. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐั‚ัŒ ะบะปะฐัั Vehicle. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐะนั‚ะต ะฟะพะปั: ะบะพะพั€ะดะธะฝะฐั‚ั‹ ะธ ะฟะฐั€ะฐะผะตั‚ั€ั‹ ัั€ะตะดัั‚ะฒ ะฟะตั€ะตะดะฒะธะถะตะฝะธั (ั†ะตะฝะฐ, ัะบะพั€ะพัั‚ัŒ, ะณะพะด ะฒั‹ะฟัƒัะบะฐ). ะกะพะทะดะฐะนั‚ะต 3 ะฟั€ะพะธะทะฒะพะดะฝั‹ั… ะบะปะฐััะฐ Plane, ะกะฐะณ ะธ Ship. ะ”ะปั ะบะปะฐััะฐ Plane ะดะพะปะถะฝะฐ ะฑั‹ั‚ัŒ ะพะฟั€ะตะดะตะปะตะฝะฐ ะฒั‹ัะพั‚ะฐ ะธ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟะฐััะฐะถะธั€ะพะฒ. ะ”ะปั ะบะปะฐััะฐ Ship โ€” ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟะฐััะฐะถะธั€ะพะฒ ะธ ะฟะพั€ั‚ ะฟั€ะธะฟะธัะบะธ. ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฒั‹ะฒะพะดะธั‚ ะฝะฐ ัะบั€ะฐะฝ ะธะฝั„ะพั€ะผะฐั†ะธัŽ ะพ ะบะฐะถะดะพะผ ัั€ะตะดัั‚ะฒะต ะฟะตั€ะตะดะฒะธะถะตะฝะธั. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson%203_HomeWork/Task3 13. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐะนั‚ะต ะบะปะฐัั DocumentWorker. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐะนั‚ะต ั‚ั€ะธ ะผะตั‚ะพะดะฐ OpenDocument(), EditDocument(), SaveDocument(). ั‚ะตะปะพ ะบะฐะถะดะพะณะพ ะธะท ะผะตั‚ะพะดะพะฒ ะดะพะฑะฐะฒัŒั‚ะต ะฒั‹ะฒะพะด ะฝะฐ ัะบั€ะฐะฝ ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธั… ัั‚ั€ะพะบ: "ะ”ะพะบัƒะผะตะฝั‚ ะพั‚ะบั€ั‹ั‚", "ะ ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธะต ะดะพะบัƒะผะตะฝั‚ะฐ ะดะพัั‚ัƒะฟะฝะพ ะฒ ะฒะตั€ัะธะธ ะŸั€ะพ", "ะกะพั…ั€ะฐะฝะตะฝะธะต ะดะพะบัƒะผะตะฝั‚ะฐ ะดะพัั‚ัƒะฟะฝะพ ะฒ ะฒะตั€ัะธะธ ะŸั€ะพ". ะกะพะทะดะฐะนั‚ะต ะฟั€ะพะธะทะฒะพะดะฝั‹ะน ะบะปะฐัั ProDocumentWorker. ะŸะตั€ะตะพะฟั€ะตะดะตะปะธั‚ะต ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธะต ะผะตั‚ะพะดั‹, ะฟั€ะธ ะฟะตั€ะตะพะฟั€ะตะดะตะปะตะฝะธะธ ะผะตั‚ะพะดะพะฒ ะฒั‹ะฒะพะดะธั‚ะต ัะปะตะดัƒัŽั‰ะธะต ัั‚ั€ะพะบะธ: "ะ”ะพะบัƒะผะตะฝั‚ ะพั‚ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝ", "ะ”ะพะบัƒะผะตะฝั‚ ัะพั…ั€ะฐะฝะตะฝ ะฒ ัั‚ะฐั€ะพะผ ั„ะพั€ะผะฐั‚ะต, ัะพั…ั€ะฐะฝะตะฝะธะต ะฒ ะพัั‚ะฐะปัŒะฝั‹ั… ั„ะพั€ะผะฐั‚ะฐั… ะดะพัั‚ัƒะฟะฝะพ ะฒ ะฒะตั€ัะธะธ ะญะบัะฟะตั€ั‚". ะกะพะทะดะฐะนั‚ะต ะฟั€ะพะธะทะฒะพะดะฝั‹ะน ะบะปะฐัั ExpertDocumentWorker ะพั‚ ะฑะฐะทะพะฒะพะณะพ ะบะปะฐััะฐ ProDocumentWorker. ะŸะตั€ะตะพะฟั€ะตะดะตะปะธั‚ะต ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะธะน ะผะตั‚ะพะด. ะŸั€ะธ ะฒั‹ะทะพะฒะต ะดะฐะฝะฝะพะณะพ ะผะตั‚ะพะดะฐ ะฝะตะพะฑั…ะพะดะธะผะพ ะฒั‹ะฒะพะดะธั‚ัŒ ะฝะฐ ัะบั€ะฐะฝ "ะ”ะพะบัƒะผะตะฝั‚ ัะพั…ั€ะฐะฝะตะฝ ะฒ ะฝะพะฒะพะผ ั„ะพั€ะผะฐั‚ะต". ะ’ ั‚ะตะปะต ะผะตั‚ะพะดะฐ Main() ั€ะตะฐะปะธะทัƒะนั‚ะต ะฒะพะทะผะพะถะฝะพัั‚ัŒ ะฟั€ะธะตะผะฐ ะพั‚ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั ะฝะพะผะตั€ะฐ ะบะปัŽั‡ะฐ ะดะพัั‚ัƒะฟะฐ pro ะธ exp. ะ•ัะปะธ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะฝะต ะฒะฒะพะดะธั‚ ะบะปัŽั‡, ะพะฝ ะผะพะถะตั‚ ะฟะพะปัŒะทะพะฒะฐั‚ัŒัั ั‚ะพะปัŒะบะพ ะฑะตัะฟะปะฐั‚ะฝะพะน ะฒะตั€ัะธะตะน (ัะพะทะดะฐะตั‚ัั ัะบะทะตะผะฟะปัั€ ะฑะฐะทะพะฒะพะณะพ ะบะปะฐััะฐ), ะตัะปะธ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะฒะฒะตะป ะฝะพะผะตั€ะฐ ะบะปัŽั‡ะฐ ะดะพัั‚ัƒะฟะฐ pro ะธ exp, ั‚ะพ ะดะพะปะถะตะฝ ัะพะทะดะฐั‚ัŒัั ัะบะทะตะผะฟะปัั€ ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‰ะตะน ะฒะตั€ัะธะธ ะบะปะฐััะฐ, ะฟั€ะธะฒะตะดะตะฝะฝั‹ะน ะบ ะฑะฐะทะพะฒะพะผัƒ โ€“ DocumentWorker. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson%203_HomeWork/Task4 14. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะ˜ะทะผะตะฝะธั‚ัŒ 12 ะฟั€ะธะผะตั€ ะฟะตั€ะฒะพะณะพ ัƒั€ะพะบะฐ (ั€ะฐะฑะพั‚ะฐ ั ะดะพะบัƒะผะตะฝั‚ะพะผ) ะธ ัะพะทะดะฐั‚ัŒ ะพะฑั‰ะธะน ะฐะฑัั‚ั€ะฐะบั‚ะฝั‹ะน ะบะปะฐัั ะดะปั ะฒัะตั… ั‡ะฐัั‚ะตะน ะดะพะบัƒะผะตะฝั‚ะฐ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson4_Homework/Lesson4_Homework 15. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐะนั‚ะต ะบะปะฐัั AbstractHandler. ะ’ ั‚ะตะปะต ะบะปะฐััะฐ ัะพะทะดะฐั‚ัŒ ะผะตั‚ะพะดั‹ void Open(), void Create(), void Chenge(), void Save(). ะกะพะทะดะฐั‚ัŒ ะฟั€ะพะธะทะฒะพะดะฝั‹ะต ะบะปะฐััั‹ XMLHandler, TXTHandler, DOCHandler ะพั‚ ะฑะฐะทะพะฒะพะณะพ ะบะปะฐััะฐ AbstractHandler. ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฑัƒะดะตั‚ ะฒั‹ะฟะพะปะฝัั‚ัŒ ะพะฟั€ะตะดะตะปะตะฝะธะต ะดะพะบัƒะผะตะฝั‚ะฐ ะธ ะดะปั ะบะฐะถะดะพะณะพ ั„ะพั€ะผะฐั‚ะฐ ะดะพะปะถะฝั‹ ะฑั‹ั‚ัŒ ะผะตั‚ะพะดั‹ ะพั‚ะบั€ั‹ั‚ะธั, ัะพะทะดะฐะฝะธั, ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธั, ัะพั…ั€ะฐะฝะตะฝะธั ะพะฟั€ะตะดะตะปะตะฝะฝะพะณะพ ั„ะพั€ะผะฐั‚ะฐ ะดะพะบัƒะผะตะฝั‚ะฐ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson4_Homework/Task2 16. ะ˜ัะฟะพะปัŒะทัƒั Visual Studio, ัะพะทะดะฐะนั‚ะต ะฟั€ะพะตะบั‚ ะฟะพ ัˆะฐะฑะปะพะฝัƒ Console Application. ะขั€ะตะฑัƒะตั‚ัั: ะกะพะทะดะฐะนั‚ะต 2 ะธะฝั‚ะตั€ั„ะตะนัะฐ IPlayable ะธ IRecodable. ะ’ ะบะฐะถะดะพะผ ะธะท ะธะฝั‚ะตั€ั„ะตะนัะพะฒ ัะพะทะดะฐะนั‚ะต ะฟะพ 3 ะผะตั‚ะพะดะฐ void Play() / void Pause() / void Stop() ะธ void Record() / void Pause() / void Stop() ัะพะพั‚ะฒะตั‚ัั‚ะฒะตะฝะฝะพ. ะกะพะทะดะฐะนั‚ะต ะฟั€ะพะธะทะฒะพะดะฝั‹ะน ะบะปะฐัั Player ะพั‚ ะฑะฐะทะพะฒั‹ั… ะธะฝั‚ะตั€ั„ะตะนัะพะฒ IPlayable ะธ IRecodable. ะะฐะฟะธัะฐั‚ัŒ ะฟั€ะพะณั€ะฐะผะผัƒ, ะบะพั‚ะพั€ะฐั ะฒั‹ะฟะพะปะฝัะตั‚ ะฟั€ะพะธะณั€ั‹ะฒะฐะฝะธะต ะธ ะทะฐะฟะธััŒ. ะกัั‹ะปะบะฐ ะฝะฐ ะบะพะด ะฟั€ะพะตะบั‚ะฐ: https://github.com/SergKredo/ITVDN-Csharp_Essential_MyProjects/tree/master/Lesson4_Homework/Task3
JavaScript
UTF-8
2,336
3.984375
4
[]
no_license
class Node { constructor(val) { this.val = val; this.next = null; } } class SinglyLinkedList{ constructor(){ this.head = null; this.tail = null; this.length = 0; } push(val){ let newNode = new Node(val) if (!this.head) { this.head = newNode; this.tail = this.head; } else { this.tail.next = newNode; this.tail = newNode; } this.length++; return this; } shift() { let remove = this.head; if(this.length === 1) { this.head = null; this.tail = null; } else { let nextHead = this.head.next; this.head = nextHead; } this.length--; return remove; } unshift(val) { if (!this.length) { this.head = val; this.tail = val; } let node = new Node(val); node.next = this.head; this.head = node; this.length++; return true; } get(index){ if (index >= this.length || index < 0) return undefined; let target = this.head; for (let i = 0; i < index; i++) { target = target.next; } return target; } insert(index, val) { if (index < 0 || index >= this.length) return false; if(index === 0) return this.unshift(val); let node = new Node(val); let prevNode = this.head; let nextNode = this.head.next; for (let i = 1; i < index; i++) { prevNode = nextNode; nextNode = nextNode.next; } prevNode.next = node; node.next = nextNode; this.length++; return this; } rotate(num) { if (num <= 0 || num > this.length) return false; for (let i = 0; i < num; i++) { let rotate = this.shift(); this.push(rotate.val); } return this; } set(index, val) { if (index < 0 || index >= this.length) return false; let target = this.get(index); target.val = val; return target; } } let list = new SinglyLinkedList(); list.push("1"); list.push("2"); list.push("3"); list.push("4"); list.push("5"); list.push("6"); console.log(list);
Markdown
UTF-8
677
2.515625
3
[]
no_license
### Prerequsites `Ruby version : 2.6.5` <br /> `Rails : 6.0.2.1`<br /> ### Setup clone project `git clone https://github.com/binaythapamagar/boggle-rails.git` <br /> move to project directory `cd boggle-rails`<br /> install necessary bundle `bundle install`<br /> run test `respec`<br /> run project `rails s`<br /> ### API endpoint `GET localhost:3000/word` provides random dashboard word from alphabets response as <br /> `[['A','B','B',''N'],['A','B','B',''N'],['A','B','B',''N'],['A','B','B',''N']]` `POST localhost:3000/validate-word` validates word from a repo as `dictionary.txt` using Binary search and response as <br/> `{isValid:true,message:'is a valid word'}`
PHP
UTF-8
1,215
2.828125
3
[]
no_license
<?php include_once('database/connection.php'); include ('templates/header.php'); try { } catch (PDOException $e) { die($e->getMessage()); } if (isset($_POST['query'])) { $q=$_POST['query']; }else{ $q=''; } $query = "SELECT * FROM events WHERE name like '%".$q."%' OR description like '%".$q."%'"; // $user = $dbh->prepare($query); // $events = $dbh->query($query, PDO::FETCH_ASSOC);//execute(); //$events = $events->fetch(); ?> <table> <tr> <th>#</th> <th></th> <th>Name</th> <th>Description</th> <th>Date</th> <th>Action</th> </tr> <?php foreach ($dbh->query($query) as $key=> $row) { $index = $key+1; echo '<tr> <td style="width:5px;">'.$index.'</td> <td valign="middle" align="center"><img width="400" src="images/'.$row['id'].'"></td> <td style="width:80px;">'.$row['name'].'</td> <td style="width:200px;">'.$row['description'].'</td> <td style="width:70px;margin:0">'.$row['date'].'</td> <td style="width:250px;margin:0"> <a class="action_btn view" href="details.php?id='.$row['id'].'">SEE MORE</a> </td> </tr>'; } ?> </table>
Python
UTF-8
2,850
2.875
3
[]
no_license
from pptx import Presentation,exc import pandas as pd import plotly.express as px from pptx.util import Inches,Pt from datetime import datetime def validate(date_text): try: if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'): raise ValueError return True except ValueError: return False def create_gantt_chart(details, base=None): # Need to write in some checks # Verify that Task are alphabets, Start & Finish are dates, Completion_pct is percentage. print("Hello") if len(details['gantt_data']['Task']) != len(details['gantt_data']['Completion_pct']): return (False, "Couldn't create the Gantt chart due to invalid lengths of Task and Completion percentage lists") elif len(details['gantt_data']['Start']) != len(details['gantt_data']['Finish']): return (False, "Couldn't create the Gantt chart due to invalid lengths of Start and Finish lists") Start_val = list(map(validate, details['gantt_data']['Start'])) Finish_val = list(map(validate, details['gantt_data']['Finish'])) if False in (Start_val): return (False, "Couldn't create the Gantt chart due to invalid formats of Start list") elif False in Finish_val: return (False, "Couldn't create the Gantt chart due to invalid formats of Finish list") df = pd.DataFrame(dict(Task=details['gantt_data']['Task'], Start=details['gantt_data']['Start'], Finish=details['gantt_data']['Finish'], Completion_pct=details['gantt_data']['Completion_pct'])) fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Completion_pct") fig.update_yaxes(autorange="reversed") fig.write_image("fig1.png") try: prs = Presentation('./Final - Presentation.pptx') except exc.PackageNotFoundError as err: prs = Presentation(base) slide = prs.slides.add_slide(prs.slide_layouts[5]) shapes = slide.shapes title = shapes.title title.text = "Gantt chart" left = Inches(1) top = Inches(1) pic = slide.shapes.add_picture("fig1.png", left, top,width = Inches(8),height = Inches(5.0)) prs.save('./Final - Presentation.pptx') return True, "Created the Gantt chart" details = { "gantt_data":{ "Task":[1,2,3], "Start":['2009-01-01','2009-03-05','2009-02-20'], "Finish":['2009-02-28','2009-04-15','2009-07-15'], "Completion_pct":[50,25,75] } } # print(create_gantt_chart(details)) req = { "req":'create_chart', "details": { "create_gantt_chart":True, "gantt_data":{ "Task":['a','b','c'], "Start":['2009-01-01','2009-03-05','2009-02-20'], "Finish":['2009-02-28','2009-04-15','2009-05-30'], "Completion_pct":[50,25,75] } } }
C#
UTF-8
852
2.53125
3
[]
no_license
๏ปฟusing MongoDB.Driver; using Pi.Common; namespace Pi.PiManager.Service.MongoDB { public class MongoDBClient<T> where T : class { protected MongoDBClient() { } /// <summary> /// ่Žทๅ–้›†ๅˆๅฎžไพ‹ /// </summary> /// <param name="host">่ฟžๆŽฅๅญ—็ฌฆไธฒ๏ผŒๅบ“๏ผŒ้›†ๅˆ</param> /// <returns></returns> public static IMongoCollection<T> GetCollectionInstance(string Collection) { string DataBase = AppSettings.Configuration["DbConnection:MongoDBName"]; string ConnectionString = AppSettings.Configuration["DbConnection:MongoDBConnection"]; MongoClient client = new MongoClient(ConnectionString); var dataBase = client.GetDatabase(DataBase); return dataBase.GetCollection<T>(Collection); } } }
Java
UTF-8
14,200
1.6875
2
[]
no_license
/** * ๅฎถ่พน็ฝ‘็ปœ็ง‘ๆŠ€ๆœ‰้™ๅ…ฌๅธ * jiabian-core * com.jiabian.callback.yiwangtong * YwtUtils.java * ๅˆ›ๅปบไบบ:ๆฝ‡ๆด’ * ๆ—ถ้—ด๏ผš2016-11-25-ไธ‹ๅˆ4:29:44 * 2016ๅฎถ่พน็ฝ‘็ปœ็ง‘ๆŠ€ๆœ‰้™ๅ…ฌๅธ-็‰ˆๆƒๆ‰€ๆœ‰ */ package com.jiabian.callback.yiwangtong; import java.io.UnsupportedEncodingException; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.RandomStringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.alibaba.fastjson.JSONObject; import com.jiabian.util.Base64Utils; import com.jiabian.util.ConfigUtil; import com.jiabian.util.Constants; import com.jiabian.util.DateUtil; import com.jiabian.util.PropertiesUtil; import com.jiabian.util.StrTools; /** * YwtUtils ๅˆ›ๅปบไบบ:ๆฝ‡ๆด’ ๆ—ถ้—ด๏ผš2016-11-25-ไธ‹ๅˆ4:29:44 */ public class YwtUtils { private static final Logger logger = LogManager.getLogger(YwtUtils.class .getName()); // ๆˆๅŠŸๆ”ฏไป˜็ป“ๆžœ้€š็Ÿฅๅœฐๅ€,ๅ•†ๆˆทๆŽฅๆ”ถๆˆๅŠŸๆ”ฏไป˜็ป“ๆžœ้€š็Ÿฅ็š„ๅœฐๅ€ใ€‚ public static final String QDY_PAYNOTICEURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/h5businesscontroller/ywtPayNotify").toString(); // ๆˆๅŠŸ็ญพ็บฆ็ป“ๆžœ้€š็Ÿฅๅœฐๅ€ public static final String QDY_SIGNNOTICEURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/h5businesscontroller/ywtSignedNotify").toString(); // ๆˆๅŠŸ้กต่ฟ”ๅ›žๅ•†ๆˆทๅœฐๅ€,ๆ”ฏไป˜ๆˆๅŠŸ้กต้ขไธŠโ€œ่ฟ”ๅ›žๅ•†ๆˆทโ€ๆŒ‰้’ฎ่ทณ่ฝฌๅœฐๅ€ใ€‚ public static final String QDY_RETURNURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/h5/luckyStar/luckyStar.html#/record").toString(); // ๆˆๅŠŸๆ”ฏไป˜็ป“ๆžœ้€š็Ÿฅๅœฐๅ€,ๅ•†ๆˆทๆŽฅๆ”ถๆˆๅŠŸๆ”ฏไป˜็ป“ๆžœ้€š็Ÿฅ็š„ๅœฐๅ€ใ€‚ public static final String SC_PAYNOTICEURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/common/ywtPayNotify").toString(); // ๆˆๅŠŸ็ญพ็บฆ็ป“ๆžœ้€š็Ÿฅๅœฐๅ€ public static final String SC_SIGNNOTICEURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/common/ywtSignedNotify").toString(); // ๆˆๅŠŸ้กต่ฟ”ๅ›žๅ•†ๆˆทๅœฐๅ€,ๆ”ฏไป˜ๆˆๅŠŸ้กต้ขไธŠโ€œ่ฟ”ๅ›žๅ•†ๆˆทโ€ๆŒ‰้’ฎ่ทณ่ฝฌๅœฐๅ€ใ€‚ public static final String SC_RETURNURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/cart/userSelectCart").toString(); // ๆˆๅŠŸๆ”ฏไป˜็ป“ๆžœ้€š็Ÿฅๅœฐๅ€,ๅ•†ๆˆทๆŽฅๆ”ถๆˆๅŠŸๆ”ฏไป˜็ป“ๆžœ้€š็Ÿฅ็š„ๅœฐๅ€ใ€‚ public static final String FUN_PAYNOTICEURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/funpay/ywtPayNotify").toString(); // ๆˆๅŠŸ็ญพ็บฆ็ป“ๆžœ้€š็Ÿฅๅœฐๅ€ public static final String FUN_SIGNNOTICEURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/funpay/ywtSignedNotify").toString(); // ๆˆๅŠŸ้กต่ฟ”ๅ›žๅ•†ๆˆทๅœฐๅ€,ๆ”ฏไป˜ๆˆๅŠŸ้กต้ขไธŠโ€œ่ฟ”ๅ›žๅ•†ๆˆทโ€ๆŒ‰้’ฎ่ทณ่ฝฌๅœฐๅ€ใ€‚ public static final String FUN_RETURNURL = new StringBuilder( PropertiesUtil.getProperties("pay.applink")).append( "/fun/showText#/record").toString(); // ๆŸฅ่ฏขๆ‹›่กŒๅ…ฌ้’ฅAPI(็”Ÿไบง็Žฏๅขƒ) public static final String COMMONKET = "https://b2b.cmbchina.com/CmbBank_B2B/UI/NetPay/DoBusiness.ashx"; // ๆŸฅ่ฏขๅ•็ฌ”่ฎขๅ• public static final String QUERYORDER = "http://218.17.27.197/NetPayment/BaseHttp.dll?QuerySingleOrder"; // ๅ•†ๆˆทๅˆ†่กŒๅท๏ผŒ4ไฝๆ•ฐๅญ— public static final String YWT_BRANCHNO = "YWT_BRANCHNO"; // ๅ•†ๆˆทๅท public static final String YWT_MERCHANTNO = "YWT_MERCHANTNO"; // ็‰ˆๆœฌๅท public static final String VERSION = "1.0"; // ็ญพๅ็ฎ—ๆณ• public static final String SIGNTYPE = "SHA-256"; // ๅ•†ๆˆทๅฏ†้’ฅ public static final String YWT_SECRETKEY = "YWT_SECRETKEY"; // ไบคๆ˜“็ ,ๅ›บๅฎšไธบFBPK,ๆŸฅ่ฏขๆ‹›่กŒๅ…ฌ้’ฅ็”จ public static final String TXCODE = "FBPK"; // ็ญพ็บฆๅ›ž่ฐƒ้€š็Ÿฅ็ฑปๅž‹ public static final String NOTICETYPE = "BKQY"; // ็ญพ็บฆๅ›ž่ฐƒๆ—ถ๏ผŒๅ›ž่ฐƒHTTPๅœฐๅ€ public static final String HTTPMETHOD = "POST"; // ่Žทๅ–ๅ…ฌ้’ฅๅŽ๏ผŒๅญ˜ๅˆฐredis็š„Key public static final String FBPUBKEY = "FBPUBKEY"; // ็ญพ็บฆๆˆๅŠŸๆ—ถ๏ผŒ่ฟ”ๅ›ž็š„ๆ ‡ๆณจ็Šถๆ€ public static final String RSPCODE = "SUC0000"; /** * ๅ่ฎฎๅผ€้€š่ฏทๆฑ‚ๆตๆฐดๅท,ไธ่ถ…่ฟ‡20ไฝ๏ผŒๅปบ่ฎฎ็บฏๆ•ฐๅญ—๏ผŒ้šๆœบไธคไฝๅŠ ๆ—ถ้—ดๆˆณๅŠ ้šๆœบไธคไฝ็ป„ๆˆ */ public static String getMerchantSerialNo() { return StrTools.appendString(RandomStringUtils.randomNumeric(2), new Date().getTime(), RandomStringUtils.randomNumeric(2)); } /** * ๅฎขๆˆทๅ่ฎฎๅท๏ผŒ ๅฟ…้กปไธบ็บฏๆ•ฐๅญ—ไธฒ๏ผŒไธ่ถ…่ฟ‡30ไฝ๏ผŒๆ–ฐ็”จๆˆทๆณจๅ†Œๆ—ถไฝฟ็”จใ€‚้šๆœบไบ”ไฝๅŠ ๆ—ถ้—ดๆˆณๅŠ ้šๆœบไธƒไฝ็ป„ๆˆ */ public static String getAgrNo() { return StrTools.appendString(RandomStringUtils.randomNumeric(5), new Date().getTime(), RandomStringUtils.randomNumeric(7)); } /** * userID,็”จไบŽๆ ‡่ฏ†ๅ•†ๆˆท็”จๆˆท็š„ๅ”ฏไธ€IDใ€‚ไธ่ถ…่ฟ‡20ไฝ,ๆ—ถ้—ดๆˆณๅŠ ้šๆœบๅ…ญไฝ็ป„ๆˆ */ public static String getUserID() { return new StringBuffer().append(new Date().getTime()) .append(RandomStringUtils.randomNumeric(6)).toString(); } /** * ่ฎขๅ•ๅทๅญ—็ฌฆไธฒๆˆชๅ–๏ผŒ่ฎขๅ•ๅท่ฆๆฑ‚ๅไฝ็บฏๆ•ฐๅญ—ใ€‚ไปŽ็ฌฌ4ไฝๅผ€ๅง‹ๆˆชๅ–ๅŽ้ข็š„ๆ•ฐๅญ— */ public static String getOrderNo(String out_trade_no) { return out_trade_no.substring(4, 14); } /** * ๆ—ฅๆœŸ */ public static String getTime() { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); String dateTime = formatter.format(new Date()); return dateTime; } /** * ็ป™็งปๅŠจ็ซฏ็š„ๅ‚ๆ•ฐ * * @param userID * @param agrNo */ public static Map<String, String> reqDataMap(String Amount, String out_trade_no, String agrNo, String userID, String payNoticeUrl, String signNoticeUrl, String returnUrl) { Map<String, String> reqData = new TreeMap<String, String>(); reqData.put("dateTime", getTime()); reqData.put("branchNo", ConfigUtil.getConfig(YWT_BRANCHNO)); reqData.put("merchantNo", ConfigUtil.getConfig(YWT_MERCHANTNO)); reqData.put("date", DateUtil.getShortCurrTimes().replaceAll("-", "")); reqData.put("orderNo", YwtUtils.getOrderNo(out_trade_no)); reqData.put("amount", Amount); reqData.put("payNoticeUrl", payNoticeUrl); reqData.put("agrNo", agrNo); reqData.put("merchantSerialNo", YwtUtils.getMerchantSerialNo()); reqData.put("userID", userID); reqData.put("signNoticeUrl", signNoticeUrl); reqData.put("returnUrl", returnUrl); return reqData; } /** * ็ญพ็บฆๅ›ž่ฐƒๆ‹›่กŒๆœๅŠก็ซฏ่ฟ”ๅ›ž็š„ๅ‚ๆ•ฐ(้ชŒ็ญพ) */ public static Map<String, String> SignedNoticeDataMap( HttpServletRequest request) { String parameter = request.getParameter("jsonRequestData"); logger.info("็ญพ็บฆparameter:" + parameter); JSONObject json = new JSONObject().parseObject(parameter); JSONObject NoticeData = new JSONObject().parseObject(json .getString(("noticeData"))); SortedMap<String, String> signedNoticeData = new TreeMap<>(); signedNoticeData.put("dateTime", (String) NoticeData.get("dateTime")); signedNoticeData.put("rspCode", (String) NoticeData.get("rspCode")); signedNoticeData.put("rspMsg", (String) NoticeData.get("rspMsg")); signedNoticeData.put("noticeType", (String) NoticeData.get("noticeType")); signedNoticeData.put("noticeSerialNo", (String) NoticeData.get("noticeSerialNo")); signedNoticeData.put("branchNo", (String) NoticeData.get("branchNo")); signedNoticeData.put("merchantNo", (String) NoticeData.get("merchantNo")); signedNoticeData.put("noticeUrl", (String) NoticeData.get("noticeUrl")); signedNoticeData.put("httpMethod", (String) NoticeData.get("httpMethod")); signedNoticeData.put("agrNo", (String) NoticeData.get("agrNo")); signedNoticeData.put("noticePara", (String) NoticeData.get("noticePara")); signedNoticeData.put("userID", (String) NoticeData.get("userID")); signedNoticeData.put("userPidType", (String) NoticeData.get("userPidType")); signedNoticeData.put("userPidHash", (String) NoticeData.get("userPidHash")); signedNoticeData.put("noPwdPay", (String) NoticeData.get("noPwdPay")); return signedNoticeData; } /** * ๆ”ฏไป˜ๅ›ž่ฐƒๆ‹›่กŒๆœๅŠก็ซฏ่ฟ”ๅ›ž็š„ๅ‚ๆ•ฐ(้ชŒ็ญพ) */ public static Map<String, String> CallBackNoticeDataMap( HttpServletRequest request) { String parameter = request.getParameter("jsonRequestData"); logger.info("parameter:" + parameter); JSONObject json = new JSONObject().parseObject(parameter); JSONObject backNoticeData = new JSONObject().parseObject(json .getString(("noticeData"))); SortedMap<String, String> noticeData = new TreeMap<>(); noticeData.put("dateTime", (String) backNoticeData.get("dateTime")); noticeData.put("noticeUrl", (String) backNoticeData.get("noticeUrl")); noticeData.put("httpMethod", (String) backNoticeData.get("httpMethod")); noticeData.put("branchNo", (String) backNoticeData.get("branchNo")); noticeData.put("merchantNo", (String) backNoticeData.get("merchantNo")); noticeData.put("noticeType", (String) backNoticeData.get("noticeType")); noticeData.put("noticeSerialNo", (String) backNoticeData.get("noticeSerialNo")); noticeData.put("date", (String) backNoticeData.get("date")); noticeData.put("orderNo", (String) backNoticeData.get("orderNo")); noticeData.put("amount", (String) backNoticeData.get("amount")); noticeData.put("bankDate", (String) backNoticeData.get("bankDate")); noticeData.put("bankSerialNo", (String) backNoticeData.get("bankSerialNo")); noticeData.put("discountFlag", (String) backNoticeData.get("discountFlag")); noticeData.put("discountAmount", (String) backNoticeData.get("discountAmount")); noticeData.put("merchantPara", (String) backNoticeData.get("merchantPara")); noticeData.put("cardType", (String) backNoticeData.get("cardType")); return noticeData; } /** * ๅฏนๅ‚ๆ•ฐๆŒ‰ๅญ—ๅ…ธ้กบๅบๆŽ’ๅบ๏ผŒไธๅŒบๅˆ†ๅคงๅฐๅ†™(KeyๆŽ’ๅบ) */ public static List<String> sortParams(Map<String, String> reqDataMap) { List<String> list = new ArrayList<String>(reqDataMap.keySet()); Collections.sort(list, new Comparator<String>() { public int compare(String o1, String o2) { String[] temp = { o1.toLowerCase(), o2.toLowerCase() }; Arrays.sort(temp); if (o1.equalsIgnoreCase(temp[0])) { return -1; } else if (temp[0].equalsIgnoreCase(temp[1])) { return 0; } else { return 1; } } }); return list; } /** * ๅพ…็ญพๅๅญ—็ฌฆไธฒ */ public static String strToSign(Map<String, String> reqDataMap) { StringBuffer buffer = new StringBuffer(); List<String> keyList = sortParams(reqDataMap); for (String key : keyList) { buffer.append(key).append("=").append(reqDataMap.get(key)) .append("&"); } buffer.append(ConfigUtil.getConfig(YWT_SECRETKEY)); return buffer.toString(); } /** * ๅพ…้ชŒ็ญพๅญ—็ฌฆไธฒ */ public static String verifyStrToSign(Map<String, String> noticeData) { StringBuffer buffer = new StringBuffer(); List<String> keyList = sortParams(noticeData); for (String key : keyList) { buffer.append(key).append("=").append(noticeData.get(key)) .append("&"); } return buffer.toString().substring(0, buffer.toString().length() - 1); } /** * ๅฏนๅ‚ๆ•ฐ็ญพๅ๏ผš * ๅฏนreqDataๆ‰€ๆœ‰่ฏทๆฑ‚ๅ‚ๆ•ฐๆŒ‰ไปŽaๅˆฐz็š„ๅญ—ๅ…ธ้กบๅบๆŽ’ๅˆ—๏ผŒๅฆ‚ๆžœ้ฆ–ๅญ—ๆฏ็›ธๅŒ๏ผŒๆŒ‰็ฌฌไบŒไธชๅญ—ๆฏๆŽ’ๅˆ—๏ผŒไปฅๆญค็ฑปๆŽจใ€‚ๆŽ’ๅบๅฎŒๆˆๅŽๆŒ‰ๅฐ†ๆ‰€ๆœ‰้”ฎๅ€ผๅฏนไปฅโ€œ&โ€็ฌฆๅทๆ‹ผๆŽฅใ€‚ * com.jiabian.callback.yiwangtong ๆ–นๆณ•ๅ๏ผšsign ๅˆ›ๅปบไบบ๏ผšๆฝ‡ๆด’ ๆ—ถ้—ด๏ผš2016-12-1-ไธ‹ๅˆ8:35:58 */ public static String sign(Map<String, String> reqDataMap) { String strToSign = strToSign(reqDataMap); try { // ๅˆ›ๅปบๅŠ ๅฏ†ๅฏน่ฑก MessageDigest messageDigest = MessageDigest.getInstance(SIGNTYPE); // ไผ ๅ…ฅ่ฆๅŠ ๅฏ†็š„ๅญ—็ฌฆไธฒ,ๆŒ‰ๆŒ‡ๅฎš็š„ๅญ—็ฌฆ้›†ๅฐ†ๅญ—็ฌฆไธฒ่ฝฌๆขไธบๅญ—่Š‚ๆต messageDigest.update(strToSign.getBytes(Constants.ENCODING)); byte byteBuffer[] = messageDigest.digest(); // ๅฐ‡ byte่ฝฌๆขไธบ16่ฟ›ๅˆถstring StringBuffer strHexString = new StringBuffer(); for (int i = 0; i < byteBuffer.length; i++) { String hex = Integer.toHexString(0xff & byteBuffer[i]); if (hex.length() == 1) { strHexString.append('0'); } strHexString.append(hex); } return strHexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } /** * ็ป™็งปๅŠจ็ซฏ่ฟ”ๅ›ž็š„ๆ•ฐๆฎ */ public static Response<String, String> jsonRequestData( Map<String, String> reqDataMap, String sign) { Response<String, String> response = new Response<>(); response.setReqData(reqDataMap); response.setSign(sign); return response; } /** * ้ชŒ็ญพ */ public static boolean isValidSignature(String strToSign, String sign, String fbPubKey) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] encodedKey = Base64Utils.decode(fbPubKey); PublicKey pubKey = keyFactory .generatePublic(new X509EncodedKeySpec(encodedKey)); Signature signature = Signature.getInstance("SHA1WithRSA"); signature.initVerify((java.security.PublicKey) pubKey); signature.update(strToSign.getBytes(Constants.ENCODING)); boolean bverify = signature.verify(Base64Utils.decode(sign)); return bverify; } catch (Exception e) { e.printStackTrace(); } return false; } }
C#
UTF-8
2,443
2.71875
3
[]
no_license
using AutoMapper; using Grpc.Core; using GrpcService1.Models; using GrpcService1.Repositories; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace GrpcService1 { public class MovieGRPCService : MovieServiceGRPC.MovieServiceGRPCBase { private readonly ILogger<GreeterService> _logger; private readonly IMapper _mapper; private readonly MovieRepository _movieRepository; public MovieGRPCService(ILogger<GreeterService> logger, MovieRepository movieRepository, IMapper mapper) { _mapper = mapper; _movieRepository = movieRepository; _logger = logger; } public override async Task<CreateMovieResponse> CreateMovie(CreateMovieRequest request, ServerCallContext context) { var newMovie = _mapper.Map<Movie>(request.Movie); var createdMovie = await _movieRepository.CreateAsync(newMovie); return await Task.FromResult(new CreateMovieResponse() { Id = createdMovie?.Id }); } public override async Task<MovieResponse> GetMovie(MovieRequest request, ServerCallContext context) { var movieDto = await _movieRepository.GetAsync(request.Id); var movie = _mapper.Map<MovieGRPC>(movieDto); return new MovieResponse() { Movie = movie }; } public override async Task<MoviesResponse> GetMovies(GetMoviesRequest request, ServerCallContext context) { var moviesDto = await _movieRepository.GetAsync(request); Console.WriteLine("::GRPC--> Before map"); var movies = _mapper.Map<MoviesResponse>(moviesDto); Console.WriteLine("::GRPC--> After add range"); return movies; } public override async Task<CreateMovieResponse> UpdateMovie(CreateMovieRequest request, ServerCallContext context) { var moviesDto = _mapper.Map<Movie>(request.Movie); await _movieRepository.UpdateAsync(request.Movie.Id, moviesDto); return new CreateMovieResponse(); } public override async Task<CreateMovieResponse> RemoveMovie(MovieRequest request, ServerCallContext context) { await _movieRepository.RemoveAsync(request.Id); return new CreateMovieResponse() { Id = "" }; } } }
Java
UTF-8
1,804
2.109375
2
[ "Apache-2.0" ]
permissive
package com.beloo.widget.chipslayoutmanager; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import com.beloo.widget.chipslayoutmanager.anchor.AnchorViewState; public interface IScrollingController { RecyclerView.SmoothScroller createSmoothScroller(@NonNull Context context, int position, int timeMs, AnchorViewState anchor); boolean canScrollVertically(); boolean canScrollHorizontally(); /** * calculate offset of views while scrolling, layout items on new places */ int scrollVerticallyBy(int d, RecyclerView.Recycler recycler, RecyclerView.State state); int scrollHorizontallyBy(int d, RecyclerView.Recycler recycler, RecyclerView.State state); /** changes may cause gaps on the UI, try to fix them */ boolean normalizeGaps(RecyclerView.Recycler recycler, RecyclerView.State state); /** @see ChipsLayoutManager#computeVerticalScrollOffset(RecyclerView.State) */ int computeVerticalScrollOffset(RecyclerView.State state); /** @see ChipsLayoutManager#computeVerticalScrollExtent(RecyclerView.State) */ int computeVerticalScrollExtent(RecyclerView.State state); /** @see ChipsLayoutManager#computeVerticalScrollRange(RecyclerView.State) */ int computeVerticalScrollRange(RecyclerView.State state); /** @see ChipsLayoutManager#computeHorizontalScrollOffset(RecyclerView.State) */ int computeHorizontalScrollOffset(RecyclerView.State state); /** @see ChipsLayoutManager#computeHorizontalScrollExtent(RecyclerView.State) */ int computeHorizontalScrollExtent(RecyclerView.State state); /** @see ChipsLayoutManager#computeHorizontalScrollRange(RecyclerView.State) */ int computeHorizontalScrollRange(RecyclerView.State state); }
Python
UTF-8
957
2.65625
3
[]
no_license
import re import json import urllib.request from pymongo import MongoClient from bs4 import BeautifulSoup from ImageSoup.BaseSoup import BaseSoup from ImageSoup.utils.database import get_year class SpringerSoup(BaseSoup): def _extract_images(self, images): image_meta = {'figures':[]} for image in images: # Title title = image.find('span', attrs={'class': 'CaptionNumber'}).get_text() # Caption caption = image.find('p', attrs={'class': 'SimplePara'}).get_text() # URL img_url = image.find('a').get('href') image_meta['figures'].append({'Image_URL': img_url, 'Caption': caption, 'Title': title}) return image_meta def _parse(self, html_string) -> dict: paper = BeautifulSoup(html_string, 'html.parser') images = paper.find_all('figure') return self._extract_images(images) SpringerImageSoup = SpringerSoup()
Java
UTF-8
186
1.90625
2
[]
no_license
package br.com.thiago.ceep.ui.recycler.adapter.listener; import br.com.thiago.ceep.model.Nota; public interface OnItemClickListener { void onItemClick(Nota nota, int position); }
C++
UTF-8
682
3.453125
3
[]
no_license
#include<iostream> using namespace std; void sort(int* arr,int left,int right){ int x=left,y=right; int cur=arr[(left+right)/2]; do{ while((arr[x]<cur)&&(x<right)) x++; while((arr[y]>cur)&&(left<y)) y--; if(x<=y){ int temp=arr[x]; arr[x]=arr[y]; arr[y]=temp; x++; y--; } }while(x<=y); if(left<y) sort(arr,left,y); if(x<right) sort(arr,x,right); } int main() { int arr[]={1,3,5,7,9,2,4,6,8,4,5,7,8,2,3,9}; // sort(arr,0,15); sort(arr,0,sizeof(arr)/sizeof(int)-1); for(int i=0;i<sizeof(arr)/sizeof(int);i++) cout<<arr[i]<<"\t"; return 0; }
Markdown
UTF-8
4,281
3.203125
3
[]
no_license
**Directions:** Copy this template into your own gist. # Strengths Reflection & Coaching Request ### Read Through Your Theme Definitions 1. What words or phrases stick out to you? How would you define each of your top 5 talents in your own words? 2. Do these top 5 talent themes resonate with you? Why or why not? Yes. They're not necessarily things that I didn't know about myself, but they do help me understand why I approach challenges from certain angles, etc. 3. How have you seen yourself using each of these talents? How often do you see yourself using these talents? I see myself using these talents everyday. They're the things that power both my personal life and professional life. When I was reading the "Achievement" description, it reminded me of my attitude towards working out, and the "Command" description reminded me of my social life. However, talents like "Ideation", "Input", and "Strategic" are probably most prevalent in my work habits. 4. When has it been difficult for me to be aware of this talent? I am sometimes unaware of these talents when I am in an unfamiliar environment or when I am just beginning to learn new material. 5. What talents could you develop further that would help you in your growth at Turing and in your new career as a software developer? I think I could continue to develop my communication skills and my positivity in this environment. I get frustrated with myself easily at times (possibly because I'm achievement-driven) and need to learn ways to step away and calm myself. 6. How would you like to build more awareness around these themes? I think that consciously deciding to work towards building these talents will create more awareness of them in my everyday life. For me, it's a matter of setting aside time out of every day to concentrate on my goals, but also to be present. 7. In which situations would developing these themes be beneficial? These themes will be beneficial in all situations, whether it's at school, at work, or in my personal life. 8. When might you overuse any of these themes? How might you benefit from dialing it down in a certain situation? I see a definite negative side to the Achievement theme because it reads to me that you'll never be truly satisfied. I think that I could benefit from taking time to celebrate small victories. 9. How could you use these themes to help you manage an area in which you might struggle? I could use these themes to become more comfortable in areas in which I am unfamiliar. 10. How can you do more of what you do best every day? I could practice incorporating the positive sides of these themes in my everyday life and try to establish a balance in order to not overdo them. ### Look at the Suggested Action Items 11. What options sound doable? 12. What are some new ways to use these themes that you haven't utilized before? 13. What obstacles are there to trying out any of these options? 14. Shortterm: What is an action step you'd like to commit to help you develop your themes further today? Next week? 15. Longterm: What do you want to learn this module to turn your talents into greater strengths? How will this help you with your professional or personal goals? ### Repeating the Module If you've reflected on your StrengthsFinder results previously, here are some additional questions you may want to consider during this second module: * How did you see yourself using your strengths last module? * When did you overuse any of your strengths? When did you underuse them? * What did you realize about yourself both in your struggles and in your wins last module? * How could you capitalize on your strengths more effectively this time through the module? * How did working with others last module affect how you understand your strengths? * What goals for your personal development do you want to make for this module? How will you know if you've achieved them? ### Next Steps This reflection is for your own growth, and you do not need to turn this in. However, if you would like to have a follow-up coaching session with Allison, please DM this gist to her when you set up your 1-on-1 with her. You can schedule that [here](https://allisonreusinger.youcanbook.me/) or by sending her a DM.
Java
UTF-8
3,777
2.390625
2
[ "Apache-2.0" ]
permissive
package com.appleframework.web.util; import com.alibaba.fastjson.JSON; import com.appleframework.web.bean.Consts; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerFontProvider; import com.itextpdf.tool.xml.XMLWorkerHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; /** * @author tanghc */ public class PDFUtil { private static final Logger log = LoggerFactory.getLogger(PDFUtil.class); private static final String UTF8 = Consts.UTF8; private static final Charset CHARSET_UTF8 = Charset.forName(UTF8); /** * html่ฝฌpdf * @param htmlString htmlๅ†…ๅฎน * @param css cssๆ ทๅผๅ†…ๅฎน * @param out ่พ“ๅ‡บๆต * @param pdfInfo pdfไฟกๆฏ */ public static void htmlToPDF(String htmlString, String css, OutputStream out, PDFInfo pdfInfo) { try { Document document = new Document(PageSize.A4); PdfWriter pdfWriter = PdfWriter.getInstance(document, out); document.open(); if (pdfInfo != null) { document.addAuthor(pdfInfo.getAuthor()); document.addCreator(pdfInfo.getCreator()); document.addSubject(pdfInfo.getSubject()); document.addTitle(pdfInfo.getTitle()); } document.addCreationDate(); XMLWorkerHelper worker = XMLWorkerHelper.getInstance(); InputStream cssInput = new ByteArrayInputStream(css.getBytes(UTF8)); InputStream htmlInput = new ByteArrayInputStream(htmlString.getBytes(UTF8)); worker.parseXHtml(pdfWriter, document, htmlInput, cssInput, CHARSET_UTF8, new AsianFontProvider()); document.close(); } catch (Exception e) { log.error("html่ฝฌpdfๅ‡บ้”™, pdfInfo:{}", pdfInfo == null ? "" : JSON.toJSON(pdfInfo), e); } } public static class PDFInfo { private String author; private String creator; private String subject; private String title; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } public static class AsianFontProvider extends XMLWorkerFontProvider { @Override public Font getFont(final String fontname, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) { try { BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); Font font = new Font(bf, size, style, color); font.setColor(color); return font; } catch (Exception e) { log.error("getFontๅ‡บ้”™", e); } return super.getFont(fontname, encoding, embedded, size, style, color); } } }
C++
UTF-8
1,575
2.640625
3
[]
no_license
// Author: Alexander Thomson (thomson@cs.yale.edu) // // The Storage class provides an interface for writing and accessing data // objects stored by the system. #ifndef _DB_BACKEND_STORAGE_H_ #define _DB_BACKEND_STORAGE_H_ #include <vector> #include "common/types.h" using std::vector; class Storage { public: virtual ~Storage() {} // Loads object specified by 'key' into memory if currently stored // on disk, asynchronously or otherwise. virtual bool Prefetch(const Key &key, double* wait_time) = 0; // Unfetch object on memory, writing it off to disk, asynchronously or // otherwise. virtual bool Unfetch(const Key &key) = 0; // If the object specified by 'key' exists, copies the object into '*result' // and returns true. If the object does not exist, false is returned. virtual Value* ReadObject(const Key& key, int64 txn_id = 0) = 0; // Sets the object specified by 'key' equal to 'value'. Any previous version // of the object is replaced. Returns true if the write succeeds, or false if // it fails for any reason. virtual bool PutObject(const Key& key, Value* value, int64 txn_id = 0) = 0; // Removes the object specified by 'key' if there is one. Returns true if the // deletion succeeds (or if no object is found with the specified key), or // false if it fails for any reason. virtual bool DeleteObject(const Key& key, int64 txn_id = 0) = 0; // TODO(Thad): Something here virtual void PrepareForCheckpoint(int64 stable) {} virtual int Checkpoint() { return 0; } virtual void Initmutex() {} }; #endif // _DB_BACKEND_STORAGE_H_
Markdown
UTF-8
745
2.640625
3
[]
no_license
# Open Badges Specifications A repository for the main Open Badges specifications. * [Assertion](/Assertion/latest.md): Main specification for the badge data. If you want to understand how badges are made and verified, this is the place to look. * [Baking](/Badge-Baking/latest.md): Badge โ€œbakingโ€ is the process of embedding a badge assertion into an image (a PNG or an SVG) so that where ever that image goes, the assertion data goes with it and the badge can be independently verified. * [Backpack](/backpack.md) [**TODO**]: A badge โ€œbackpackโ€ is a web site/application that can take in & export badges. The Open Badges JavaScript API expects endpoints to be in specific or discoverable locations, and this document details that.
Java
UTF-8
3,347
3.046875
3
[]
no_license
import java.util.Set; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; import java.io.IOException; import java.io.PrintStream; import java.io.BufferedReader; public class SServer { public static socket clientSockets = new testHash<Socket>(); public static void main(String[] args) { System.out.println("Server is waiting"); ServerSocket server=null; try { // start Try server = new socket(9090); } catch(IOException e){ e.Tracer(); // calling the method System.out.println("Error occurs"); } while (true) { try{ Socket s = server.accept(); clientSockets.add(s); System.out.println(s.getInputStream()); ServerThread1 st=new ServerThread1(s); st.start(); System.out.println("connection Established with "); } catch(Exception e) { e.tracer(); System.out.println("Error in the connection"); } } } public static void broadcasting(String message) { for (Socket z : sock) { if (z != null) { PrintStream outToClient = null; try { outToClient = new PrintStream(z.sock()); outToClient.println(message); { System.out.println("Caught an IO exception trying to send to TCP connections"); e.tracer(); } } } } static class ServerThread1 extends Thread{ // making the threads BufferedReader is = null; String line=null; Socket s=null; public ServerThread1(Socket s){ this.s=s; } public void run() { try{ is=reader(new InputStreamReader(s.getInputStream())); }catch(IOException e { System.out.println("IO error in server thread"); } try { // end the try while(line.compareTo("Bye")!=0){ broadcasting(line); line=is.readLine(); System.out.println("Response to the clients : "+line); line=is.readLine(); } }catch (ioe) { // open for catch line=this.getName(); System.out.println("IO Error/ Client "+line+" terminated abruptly"); } catch(NullPointerException e){ line=this.getName(); System.out.println("Client "+line+" Closed"); } finally{ try{ System.out.println("Connection is being closed"); if (is!=null) { is.close(); System.out.println(" Closing the socket input stream"); } if (s!=null){ s.close(); System.out.println("The socket has been closed"); } } catch(ioe){ // catch System.out.println("The socket close the error"); } }//here finally ends } } }
TypeScript
UTF-8
1,400
2.796875
3
[]
no_license
import { Lexer, Parser, Token, TokenType } from "../../src"; import { Program } from "../../src/ast/program"; import { ExpressionStatement } from "../../src/ast/statement"; import { AssignmentExpression, VarExpression, LiteralExpression, } from "../../src/ast/expression"; import { generateExpression, generateStatement } from "../helpers"; it("assignment", () => { const source = `x = null;`; const tokens = new Lexer(source).scan(); const program = new Parser(tokens).parse(); expect(program).toEqual( new Program([ generateStatement( new ExpressionStatement( generateExpression( new AssignmentExpression( new Token(TokenType.IDENTIFIER, "x", undefined, 1, 1), generateExpression( new LiteralExpression( new Token(TokenType.NULL, "null", null, 1, 5), ), { line: 1, column: 5 }, { line: 1, column: 9 }, ), ), { line: 1, column: 1 }, { line: 1, column: 9 }, ), ), { line: 1, column: 1 }, { line: 1, column: 10 }, ), ]), ); }); it("missing initializer", () => { const source = `x = ;`; const tokens = new Lexer(source).scan(); expect(() => new Parser(tokens).parse()).toThrow( new Error("Line 1:5 Expect expression"), ); });
TypeScript
UTF-8
541
2.5625
3
[]
no_license
import { BaseEntity, Column, CreateDateColumn, Entity, ManyToOne, PrimaryGeneratedColumn, } from 'typeorm'; import { User } from '../User/model'; @Entity() export class Post extends BaseEntity { @PrimaryGeneratedColumn() id!: number; @Column() title!: string; @Column('text') content!: string; @Column() userId!: number; @ManyToOne(() => User, (user) => user.posts) user: User; @CreateDateColumn() createdAt: Date; @CreateDateColumn() updatedAt: Date; }
JavaScript
UTF-8
2,584
3.34375
3
[]
no_license
"use strict"; // EJERCICIO 1 const button = document.querySelector(".accion"); const paragraph = document.querySelector(".message"); function changeParagraph() { paragraph.innerHTML = "Mi primer click, ยกole yo y la mujer que me pariรณ!"; } button.addEventListener("click", changeParagraph); //EJERCICIO 2 const buttonEje2 = document.querySelector(".eje2"); const inputName = document.querySelector(".fname"); function printName() { console.log(`Hola ${inputName.value}`); } buttonEje2.addEventListener("click", printName); //EJERCICIO 3 let divEje3 = document.querySelector(".eje3"); const paragraphEje3 = document.querySelector(".eje3__paragraph"); function addParagraph() { //divEje3.innerHTML += divEje3.innerHTML; //no me gusta porque no uso el parrafo en sรญ // divEje3.innerHTML += paragraphEje3; ???? divEje3.innerHTML += paragraphEje3.outerHTML; } paragraphEje3.addEventListener("mouseover", addParagraph); //EJERCICIO 4 const divEje4 = document.querySelector(".eje4basic"); const pixelsChange = 250; function handleChangeColor() { if (window.scrollY > pixelsChange) { divEje4.classList.add("eje4scroll"); } else { divEje4.classList.remove("eje4scroll"); } } window.addEventListener("scroll", handleChangeColor); //EJERCICIO 5 const pageSelector = document.querySelector(".page"); function handleColorKeyboard(event) { console.log(event); if (event.target.id === "page") { if (event.key === "r") { pageSelector.classList.toggle("pageR"); } else if (event.key === "m") { pageSelector.classList.toggle("pageM"); } else { } } } pageSelector.addEventListener("keyup", handleColorKeyboard); /* const handleElement = document.querySelector ('.document'); console.log(handleElement) function changeElement(event) { if (event.key === 'r') { handleElement.classList.add('documentR') handleElement.classList.remove('documentM') } else if (event.key === 'm') { handleElement.classList.add('documentM') handleElement.classList.remove('documentR') } console.log(event.key); } handleElement.addEventListener('keydown', changeElement); */ //EJERCICIO 6 const eje6input = document.querySelector(".eje6input"); let eje6parag = document.querySelector(".eje6parag"); function handleWriteParagraph(event) { console.log(event.currentTarget); eje6parag.innerHTML += event.currentTarget.value; } function handleResetValueInput(event) { event.currentTarget.value = ""; } eje6input.addEventListener("change", handleWriteParagraph); eje6input.addEventListener("blur", handleResetValueInput);
JavaScript
UTF-8
4,606
3.171875
3
[]
no_license
var StoreDatabase = require("./StoreDatabase"); var inquirer = require("inquirer"); var Table = require("cli-table"); var storeDB = new StoreDatabase(); function menu() { inquirer.prompt([{ message: "What would you like to do?", type: "list", choices: ["View Products for Sale", "View Low Inventory", "Add to Inventory", "Add New Product"], name: "choice" }]).then(res => { switch (res.choice) { case "View Products for Sale": storeDB.getAllProducts(resultsView); break; case "View Low Inventory": storeDB.getProductsStockLessThan(5, resultsView); break; case "Add to Inventory": addToInventory(); break; case "Add New Product": addNewProduct(); break; } }); } function addToInventory() { var products = []; storeDB.getAllProducts(res => { res.forEach(element => { products.push(element.item_id + " " + element.product_name); }); inquirer.prompt([{ message: "Which item do you want to add inventory for?", type: "list", choices: products, name: "choice" }, { message: "How much do you want to add?", name: "amount", validate: function (input) { var intVal = parseInt(input); if (!Number.isInteger(+input) || intVal < 0) return "Your input must be a postive integer value." return true; } } ]).then(ans => { // Add product quantity storeDB.getProductByID(parseInt(ans.choice.split(" ")[0]), result => { result.stock_quantity += parseInt(ans.amount); storeDB.updateProduct(result, ret => { console.log("Amount Successfully Added."); askContinue(); }); }); }); }) } function addNewProduct() { inquirer.prompt([{ message: "Enter the Product name: ", name: "product_name" }, { message: "Enter the Department name: ", name: "department_name" }, { message: "Enter the price: ", validate: function (input) { if (isNaN(input) || parseFloat(input) < 0) return "Input must be a positive number."; return true; }, name: "price" }, { message: "Enter the quantity: ", validate: function (input) { var intVal = parseInt(input); if (!Number.isInteger(+input) || intVal < 0) return "Your input must be a postive integer value." return true; }, name: "stock_quantity" }]).then(ans => { // Check if a product exists in that department storeDB.getProductByNameAndDepartment(ans.product_name, ans.department_name, res => { if(res){ console.log("Product already exists in that department."); askContinue(); return; } // Get the department we want to add to storeDB.getDepartmentByName(ans.department_name, results => { if(results){ ans.department_id = results.department_id; storeDB.addNewProduct(ans, function() { console.log("Product added."); askContinue(); }); } else { console.log("Department doesn't exist."); askContinue(); } }); }); }) } function askContinue() { inquirer.prompt([ { message: "Would you like to continue?", choices: ["Yes", "No"], type: "list", name: "choice" } ]).then(ans => { if (ans.choice === "Yes") menu(); else { storeDB.close(); } }); } // Results view function for item display. var resultsView = res => { var table = new Table({ head: ["Product ID", "Name", "Department", "Price", "Stock"] }); res.forEach(element => { table.push([element.item_id, element.product_name, element.department_name, element.price.toFixed(2), element.stock_quantity]); }); console.log(table.toString()); askContinue(); }; storeDB.connect(menu);
Ruby
UTF-8
1,847
2.828125
3
[]
no_license
Before do @normalform = NormalForm.new @game_info = {} end Given /^I have a player named "([^"]*)"$/ do |arg1| pending # express the regexp above with the code you wish you had end Then /^the number of players should be (\d+)$/ do |arg1| pending # express the regexp above with the code you wish you had end Given /^I have a tactic called "([^"]*)"$/ do |arg1| pending # express the regexp above with the code you wish you had end Then /^the number of tactics should be (\d+)$/ do |arg1| pending # express the regexp above with the code you wish you had end Given /^I want a game form$/ do pending # express the regexp above with the code you wish you had end When /^I create a rectangle$/ do @normalform.draw_rectangle end Then /^I should have a file named "([^"]*)"$/ do |arg1| output_path = File.dirname(__FILE__) + "/../../examples/" + arg1 File.exists?(output_path).should == true end Given /^I create a line$/ do @normalform.draw_line end Given /^I create an annotation$/ do @normalform.draw_annotation end Given /^I create an label$/ do @normalform.draw_label end Given /^I create rectangle and place (\d+) intersecting lines on it$/ do |arg1| @normalform.draw_foursquare end Given /^I create a game with annotations on it$/ do # @normalform.some_method "26", first_x: 20, first_y: 10, second_x: 80, second_y: 50 @normalform.draw_annotated_game end Given /^I create a normal game with "([^"]*)" columns and "([^"]*)" rows and a width of (\d+) and a height of (\d+)$/ do |arg1, arg2, arg3, arg4| @game_info = @normalform.draw_game(arg1.to_i, arg2.to_i, {width: arg3.to_i, height: arg4.to_i} ) end Then /^the width of the first column should be (\d+)$/ do |arg1| # debugger @game_info[:columns][0][:width].should == arg1.to_i end
Java
UTF-8
893
1.953125
2
[]
no_license
package com.prs; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.JsonTest; import org.springframework.boot.test.json.JacksonTester; import org.springframework.test.context.junit4.SpringRunner; import com.prs.business.PurchaseRequest; @RunWith(SpringRunner.class) @JsonTest public class PurchaseRequestJsonTests { @Autowired private JacksonTester<PurchaseRequest> json; @Test public void serializePurchaseRequestJsonTest() { PurchaseRequest purchaseRequest = new PurchaseRequest(); try { assertThat(this.json.write(purchaseRequest)).extractingJsonPathStringValue("$.deliverytrype").isEqualTo(null); } catch (IOException e) { e.printStackTrace(); } } }
Markdown
UTF-8
4,566
2.8125
3
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
[#]: collector: (lujun9972) [#]: translator: ( ) [#]: reviewer: ( ) [#]: publisher: ( ) [#]: url: ( ) [#]: subject: (Get started with Freeplane, an open source mind mapping application) [#]: via: (https://opensource.com/article/19/1/productivity-tool-freeplane) [#]: author: (Kevin Sonney https://opensource.com/users/ksonney (Kevin Sonney)) Get started with Freeplane, an open source mind mapping application ====== Map your brainstorming sessions with Freeplane, the 13th in our series on open source tools that will make you more productive in 2019. ![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/brain_data.png?itok=RH6NA32X) There seems to be a mad rush at the beginning of every year to find ways to be more productive. New Year's resolutions, the itch to start the year off right, and of course, an "out with the old, in with the new" attitude all contribute to this. And the usual round of recommendations is heavily biased towards closed source and proprietary software. It doesn't have to be that way. Here's the 13th of my picks for 19 new (or new-to-you) open source tools to help you be more productive in 2019. ### Freeplane [Mind maps][1] are one of the more valuable tools I've used for quickly brainstorming ideas and capturing data. Mind mapping is a versatile process that helps show how things are related and can be used to quickly organize interrelated information. From a planning perspective, mind mapping allows you to quickly perform a brain dump around a single concept, idea, or technology. ![](https://opensource.com/sites/default/files/uploads/freeplane-1.png) [Freeplane][2] is a desktop application that makes it easy to create, view, edit, and share mind maps. It is a redesign of [FreeMind][3], which was the go-to mind-mapping application for quite some time. Installing Freeplane is pretty easy. It is a [Java][4] application and distributed as a ZIP file with scripts to start the application on Linux, Windows, and MacOS. At its first startup, its main window includes an example mind map with links to documentation about all the different things you can do with Freeplane. ![](https://opensource.com/sites/default/files/uploads/freeplane-2.png) You have a choice of templates when you create a new mind map. The standard template (likely at the bottom of the list) works for most cases. Just start typing the idea or phrase you want to start with, and your text will replace the center text. Pressing the Insert key will add a branch (or node) off the center with a blank field where you can fill in something associated with the idea. Pressing Insert again will add another node connected to the first one. Pressing Enter on a node will add a node parallel to that one. ![](https://opensource.com/sites/default/files/uploads/freeplane-3.png) As you add nodes, you may come up with another thought or idea related to the main topic. Using either the mouse or the Arrow keys, go back to the center of the map and press Insert. A new node will be created off the main topic. If you want to go beyond Freeplane's base functionality, right-click on any of the nodes to bring up a Properties menu for that node. The Tool pane (activated under the Viewโ€“>Controls menu) contains customization options galore, including line shape and thickness, border shapes, colors, and much, much more. The Calendar tab allows you to insert dates into the nodes and set reminders for when nodes are due. (Note that reminders work only when Freeplane is running.) Mind maps can be exported to several formats, including common images, XML, Microsoft Project, Markdown, and OPML. ![](https://opensource.com/sites/default/files/uploads/freeplane-4.png) Freeplane gives you all the tools you'll need to create vibrant and useful mind maps, getting your ideas out of your head and into a place where you can take action on them. -------------------------------------------------------------------------------- via: https://opensource.com/article/19/1/productivity-tool-freeplane ไฝœ่€…๏ผš[Kevin Sonney][a] ้€‰้ข˜๏ผš[lujun9972][b] ่ฏ‘่€…๏ผš[่ฏ‘่€…ID](https://github.com/่ฏ‘่€…ID) ๆ กๅฏน๏ผš[ๆ กๅฏน่€…ID](https://github.com/ๆ กๅฏน่€…ID) ๆœฌๆ–‡็”ฑ [LCTT](https://github.com/LCTT/TranslateProject) ๅŽŸๅˆ›็ผ–่ฏ‘๏ผŒ[Linuxไธญๅ›ฝ](https://linux.cn/) ่ฃ่ช‰ๆŽจๅ‡บ [a]: https://opensource.com/users/ksonney (Kevin Sonney) [b]: https://github.com/lujun9972 [1]: https://en.wikipedia.org/wiki/Mind_map [2]: https://www.freeplane.org/wiki/index.php/Home [3]: https://sourceforge.net/projects/freemind/ [4]: https://java.com
Python
UTF-8
1,501
3.140625
3
[ "MIT" ]
permissive
#!usr/bin/python3 # Please help making this app better! I would love to get feedback! # Made by Matthew C Lopez # Email: matthew_christ@protonmail.com # MIT License # version 0.1 import os import re import time from colorama import Fore while True: #Makes program loop. time.sleep(2) # nmap is needed with this first version. scan = os.system('sudo nmap -sn 192.168.0.0/24 > nmap.txt') # Nmap scannes the network for divices and puts them into a text file. #registered mac adresses. Matt = ['24:46:C8:4D:36:E4'] Lexi = ['A4:77:33:87:07:94'] print() print(Fore.CYAN) # Lets you know is app is working. print("APP is working!") print() # This will then pull data from the text file. with open ("nmap.txt", "r") as file: find = file.read().replace('\n', '') print() for i in Matt: # If user Matt's mac address is found in text file, program will print 'Matt is here'. if re.search(r'\b{}\b'.format(i),find): print(Fore.GREEN) print('Matt is here') else: print(Fore.RED) print("Can't find user") print(Fore.GREEN) # If matt is not here, it will print "Can't find user". print() for i in Lexi: if re.search(r'\b{}\b'.format(i),find): print('Lexi is here') else: print(Fore.RED) print("Can't find user") print(Fore.GREEN)
Python
UTF-8
2,367
2.6875
3
[]
no_license
#fjeiteg from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request,'index.html') # return HttpResponse('''<h1>hello anchal</h1> <a href=" http://127.0.0.1:8000/about">click me </a>''') # def analyse(request): # return HttpResponse('''<a href=" http://127.0.0.1:8000/removepunch">click me</a> about <a href="/">back</a>''') def analyse(request): djtext=request.GET.get('text') #get the text print(djtext) removepunch= request.GET.get('removepunch', 'off') fullcaps= request.GET.get('fullcaps', 'off') newlineremover = request.GET.get('newlineremover', 'off') extraspaceremover=request.GET.get('extraspaceremover','off') print(removepunch) if (removepunch == "on"): punctuations='''!@#$%^&*()_+|{}":?><;'/.,[]''' analysed="" for char in djtext: if char not in punctuations: analysed =analysed + char param={'purpose':'remove punctuations','analysed_text':analysed} return render(request,'analyse.html',param) elif(fullcaps=="on"): analysed="" for char in djtext: analysed = analysed + char.upper() param = {'purpose': 'changed to upper case', 'analysed_text':analysed} return render(request,'analyse.html',param) elif (extraspaceremover== "on"): analysed = "" for index, char in enumerate(djtext): if not(djtext[index] ==" " and djtext[index+1] == " "): analysed = analysed + char param = {'purpose': 'remove extra space', 'analysed_text': analysed} return render(request, 'analyse.html', param) elif (newlineremover== "on"): analysed = "" for char in djtext: if (char !='\n'): analysed = analysed + char param = {'purpose': 'changed to newline', 'analysed_text': analysed} return render(request, 'analyse.html', param) else: analysed=" " for char in djtext: analysed =analysed + char param = {'purpose': '', 'analysed_text': analysed} return render(request,'analyse.html',param)
Markdown
UTF-8
26,619
3.71875
4
[]
no_license
# ้ซ˜ๆ–ฏ่ฟ‡็จ‹ ## ้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„็†่งฃ ๆ‰ฉๅฑ•ๅˆฐๆ— ้™็ปดๅบฆ, ๅˆ™็งฐไธบ้ซ˜ๆ–ฏ่ฟ‡็จ‹. ![้ซ˜ๆ–ฏ่ฟ‡็จ‹](rc/gaussian_process.png) ๆฏไธ€ไธช็ปดๅบฆไธŠ็š„ๅ€ผ้ƒฝๅฑžไบŽไธ€ไธช้ซ˜ๆ–ฏๅˆ†ๅธƒ, ไธๅŒ็ปดๅบฆไน‹้—ดๆœ‰็›ธไบ’่”็ณป(้€š่ฟ‡kernel/ๅๆ–นๅทฎๆฅ่กจ็คบ). ไธ€ไธชๆ•ฐๆฎๅฐฑๆ˜ฏๆญค้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ไธ€ๆฌก้‡‡ๆ ท. ![้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅฎžไพ‹](rc/gaussian_process_example.png) ้ซ˜ๆ–ฏ่ฟ‡็จ‹ไนŸๅฏไปฅ็†่งฃไธบๆ’ๅ€ผ: 1. ๅฏนไบŽๅ‡ฝๆ•ฐ$f(x)$, ๆฏไธ€ๆฌกไปŽไธๅŒ$x$ๅค„่ง‚ๅฏŸ$f(x)$้ƒฝๅฏไปฅไฝœไธบไธ€ไธช้šๆœบๅ˜้‡ๆฅ็œ‹ๅพ…, ๅฎƒไปฌ้ƒฝๆœไปŽๅ’Œไธ€ไธช$x$ๆ— ๅ…ณ็š„้ซ˜ๆ–ฏๅ™ชๅฃฐๅˆ†ๅธƒ. 2. ๅฏนไบŽไปปๆ„ไธคไธช$x, x'$, ๆˆ‘ไปฌ่ฎคไธบ$x$ๅ’Œ$x'$็š„่ท็ฆปๅ†ณๅฎšไบ†ไป–ไปฌไน‹้—ด็š„็›ธๅ…ณๆ€ง. ไปŽ่€Œ, ไพ‹ๅฆ‚ $x=1, 2, 3$ ๅ‡ๅพ—ๅˆฐไบ†ๆ•ฐๆฎ, ้‚ฃไนˆๆˆ‘ไปฌ่ฆๆŽจๆต‹$x=4$ๅค„็š„ๆ•ฐๆฎๅˆ†ๅธƒ, ๅฐฑๅฏไปฅ้€š่ฟ‡ๅฎƒๅ’Œๅ‰ไธ‰ไธชๆ•ฐๆฎ็š„็›ธๅ…ณๆ€ง, ๆฅๆ‰พๅˆฐไธ€ไธชๅˆ็†็š„bound. ### ไธ€ๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ ๆˆ‘ไปฌไปŽๆœ€็ฎ€ๅ•ๆœ€ๅธธ่ง็š„ไธ€ๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒๅผ€ๅง‹๏ผŒๅ…ถๆฆ‚็އๅฏ†ๅบฆๅ‡ฝๆ•ฐไธบ $$ p(x) = \frac{1}{\sigma\sqrt{2\pi}}\mathrm{exp}(-\frac{(x-\mu)^2}{2\sigma^2}) \tag{1} $$ ๅ…ถไธญ $\mu$ ๅ’Œ $\sigma$ ๅˆ†ๅˆซ่กจ็คบๅ‡ๅ€ผๅ’Œๆ–นๅทฎ๏ผŒ่ฟ™ไธชๆฆ‚็އๅฏ†ๅบฆๅ‡ฝๆ•ฐๆ›ฒ็บฟ็”ปๅ‡บๆฅๅฐฑๆ˜ฏๆˆ‘ไปฌ็†Ÿๆ‚‰็š„้’Ÿๅฝขๆ›ฒ็บฟ๏ผŒๅ‡ๅ€ผๅ’Œๆ–นๅทฎๅ”ฏไธ€ๅœฐๅ†ณๅฎšไบ†ๆ›ฒ็บฟ็š„ๅฝข็Šถใ€‚ ### ๅคšๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ ไปŽไธ€ๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒๆŽจๅนฟๅˆฐๅคšๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒๅ‡่ฎพๅ„็ปดๅบฆไน‹้—ด็›ธไบ’็‹ฌ็ซ‹ $$ p(x_1, x_2, ..., x_n) = \prod_{i=1}^{n}p(x_i)=\frac{1}{(2\pi)^{\frac{n}{2}}\sigma_1\sigma_2...\sigma_n}\mathrm{exp}\left(-\frac{1}{2}\left [\frac{(x_1-\mu_1)^2}{\sigma_1^2} + \frac{(x_2-\mu_2)^2}{\sigma_2^2} + ... + \frac{(x_n-\mu_n)^2}{\sigma_n^2}\right]\right) \tag{2} $$ ๅ…ถไธญ $\mu_1, \mu_2, \cdots$ ๅ’Œ $\sigma_1, \sigma_2, \cdots$ ๅˆ†ๅˆซๆ˜ฏ็ฌฌ 1 ็ปดใ€็ฌฌไบŒ็ปด... ็š„ๅ‡ๅ€ผๅ’Œๆ–นๅทฎใ€‚ๅฏนไธŠๅผๅ‘้‡ๅ’Œ็Ÿฉ้˜ต่กจ็คบไธŠๅผ๏ผŒไปค $$ \boldsymbol{x - \mu}=[x_1-\mu_1, \ x_2-\mu_2,\ โ€ฆ \ x_n-\mu_n]^T $$ $$ K = \begin{bmatrix} \sigma_1^2 & 0 & \cdots & 0\\ 0 & \sigma_2^2 & \cdots & 0\\ \vdots & \vdots & \ddots & 0\\ 0 & 0 & 0 & \sigma_n^2 \end{bmatrix} $$ ๅˆ™ $$\sigma_1\sigma_2...\sigma_n = |K|^{\frac{1}{2}}$$ $$ \frac{(x_1-\mu_1)^2}{\sigma_1^2} + \frac{(x_2-\mu_2)^2}{\sigma_2^2} + ... + \frac{(x_n-\mu_n)^2}{\sigma_n^2}=(\boldsymbol{x-\mu})^TK^{-1}(\boldsymbol{x-\mu}) $$ ไปฃๅ…ฅไธŠๅผๅพ—ๅˆฐ $$ p(\boldsymbol{x}) = (2\pi)^{-\frac{n}{2}}|K|^{-\frac{1}{2}}\mathrm{exp}\left( -\frac{1}{2}(\boldsymbol{x-\mu})^TK^{-1}(\boldsymbol{x-\mu}) \right) \tag{3} $$ ๅ…ถไธญ $ \boldsymbol{\mu} \in \mathbb{R}^n $ ๆ˜ฏๅ‡ๅ€ผๅ‘้‡๏ผŒ $ K \in \mathbb{R}^{n \times n} $ ไธบๅๆ–นๅทฎ็Ÿฉ้˜ต๏ผŒ็”ฑไบŽๆˆ‘ไปฌๅ‡่ฎพไบ†ๅ„็ปดๅบฆ็›ดๆŽฅ็›ธไบ’็‹ฌ็ซ‹๏ผŒๅ› ๆญค $ K $ ๆ˜ฏไธ€ไธชๅฏน่ง’็Ÿฉ้˜ตใ€‚ๅœจๅ„็ปดๅบฆๅ˜้‡็›ธๅ…ณๆ—ถ๏ผŒไธŠๅผ็š„ๅฝขๅผไป็„ถไธ€่‡ด๏ผŒไฝ†ๆญคๆ—ถๅๆ–นๅทฎ็Ÿฉ้˜ต $K$ ไธๅ†ๆ˜ฏๅฏน่ง’็Ÿฉ้˜ต๏ผŒๅชๅ…ทๅค‡ๅŠๆญฃๅฎšๅ’Œๅฏน็งฐ็š„ๆ€ง่ดจใ€‚ไธŠๅผ้€šๅธธไนŸ็ฎ€ๅ†™ไธบ $$ x \sim \mathcal{N}(\boldsymbol{\mu}, K) $$ ### ๆ— ้™ๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŸ ๅœจๅคšๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ็š„ๅŸบ็ก€ไธŠ่ฟ›ไธ€ๆญฅๆ‰ฉๅฑ•๏ผŒๅ‡่ฎพๆœ‰ๆ— ้™ๅคš็ปดๅ‘ข๏ผŸๆˆ‘ไปฌ็”จไธ€ไธชไพ‹ๅญๆฅๅฑ•็คบ่ฟ™ไธชๆ‰ฉๅฑ•็š„่ฟ‡็จ‹๏ผˆๆฅๆบ๏ผš[MLSS 2012: J. Cunningham - Gaussian Processes for Machine Learning](http://www.columbia.edu/~jwp2128/Teaching/E6892/papers/mlss2012_cunningham_gaussian_processes.pdf)๏ผ‰ใ€‚ ๅ‡่ฎพๆˆ‘ไปฌๅœจๅ‘จไธ€ๅˆฐๅ‘จๅ››ๆฏๅคฉ็š„ 7:00 ๆต‹่ฏ•ไบ† 4 ๆฌกๅฟƒ็އ๏ผŒๅฆ‚ๅ›พไธญ 4 ไธช็‚น๏ผŒๅฏ่ƒฝ็š„้ซ˜ๆ–ฏๅˆ†ๅธƒๅฆ‚ๅ›พๆ‰€็คบ๏ผˆ้ซ˜็˜ฆ็š„ๆ›ฒ็บฟ๏ผ‰ใ€‚่ฟ™ๆ˜ฏไธ€ไธชไธ€ๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒๅชๆœ‰ๆฏๅคฉ 7: 00 ๅฟƒ็އ่ฟ™ไธช็ปดๅบฆใ€‚ <!--START figure--> <div class="figure"> <a href="http://ww2.sinaimg.cn/large/006tNc79ly1g5fnrcgixfj31020rwjvm.jpg" data-lightbox="1d_gaussian"> <img src="http://ww2.sinaimg.cn/large/006tNc79ly1g5fnrcgixfj31020rwjvm.jpg" width="50%" alt="1d_gaussian" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> ็Žฐๅœจ่€ƒ่™‘ไธไป…ๅœจๆฏๅคฉ็š„ 7: 00 ๆต‹ๅฟƒ็އ๏ผŒๅœจ 8:00 ๆ—ถไนŸ่ฟ›่กŒๆต‹้‡๏ผŒ่ฟ™ไธชๆ—ถๅ€™ๅ˜ๆˆไธคไธช็ปดๅบฆ๏ผˆไบŒๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผ‰๏ผŒๅฆ‚ๅ›พๆ‰€็คบ <!--START figure--> <div class="figure"> <a href="http://ww4.sinaimg.cn/large/006tNc79ly1g5fnrztkqlj30si0lw41m.jpg" data-lightbox="2d_gaussian"> <img src="http://ww4.sinaimg.cn/large/006tNc79ly1g5fnrztkqlj30si0lw41m.jpg" width="50%" alt="2d_gaussian" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> ๅฆ‚ๆžœๆˆ‘ไปฌๅœจๆฏๅคฉ็š„ๆ— ้™ไธชๆ—ถ้—ด็‚น้ƒฝ่ฟ›่กŒๆต‹้‡๏ผŒๅˆ™ๅ˜ๆˆไบ†ไธ‹ๅ›พ็š„ๆƒ…ๅ†ตใ€‚ๆณจๆ„ไธ‹ๅ›พไธญๆŠŠๆต‹้‡ๆ—ถ้—ดไฝœไธบๆจช่ฝด๏ผŒๅˆ™ๆฏไธช้ขœ่‰ฒ็š„ไธ€ๆก็บฟไปฃ่กจไธ€ไธช๏ผˆๆ— ้™ไธชๆ—ถ้—ด็‚น็š„ๆต‹้‡๏ผ‰ๆ— ้™็ปด็š„้‡‡ๆ ทใ€‚**ๅฝ“ๅฏนๆ— ้™็ปด่ฟ›่กŒ้‡‡ๆ ทๅพ—ๅˆฐๆ— ้™ๅคšไธช็‚นๆ—ถ๏ผŒๅ…ถๅฎžๅฏไปฅ็†่งฃไธบๅฏนๅ‡ฝๆ•ฐ่ฟ›่กŒ้‡‡ๆ ท**ใ€‚ <!--START figure--> <div class="figure"> <a href="http://ww3.sinaimg.cn/large/006tNc79ly1g5fnsa371xj30ss0lcadg.jpg" data-lightbox="infinite_gaussian"> <img src="http://ww3.sinaimg.cn/large/006tNc79ly1g5fnsa371xj30ss0lcadg.jpg" width="50%" alt="infinite_gaussian" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> ๅฝ“ไปŽๅ‡ฝๆ•ฐ็š„่ง†่ง’ๅŽป็œ‹ๅพ…้‡‡ๆ ท๏ผŒ็†่งฃไบ†ๆฏๆฌก้‡‡ๆ ทๆ— ้™็ปด็›ธๅฝ“ไบŽ้‡‡ๆ ทไธ€ไธชๅ‡ฝๆ•ฐไน‹ๅŽ๏ผŒๅŽŸๆœฌ็š„ๆฆ‚็އๅฏ†ๅบฆๅ‡ฝๆ•ฐไธๅ†ๆ˜ฏ็‚น็š„ๅˆ†ๅธƒ ๏ผŒ่€Œๅ˜ๆˆไบ†**ๅ‡ฝๆ•ฐ็š„ๅˆ†ๅธƒ**ใ€‚่ฟ™ไธชๆ— ้™ๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒๅณ็งฐไธบ้ซ˜ๆ–ฏ่ฟ‡็จ‹ใ€‚้ซ˜ๆ–ฏ่ฟ‡็จ‹ๆญฃๅผๅœฐๅฎšไน‰ไธบ๏ผšๅฏนไบŽๆ‰€ๆœ‰ $$ \boldsymbol{x} = [x_1, x_2, \cdots, x_n] $$๏ผŒ$$ f(\boldsymbol{x})=[f(x_1), f(x_2), \cdots, f(x_n)] $$ ้ƒฝๆœไปŽๅคšๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผŒๅˆ™็งฐ $f$ ๆ˜ฏไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹๏ผŒ่กจ็คบไธบ $$ f(\boldsymbol{x}) \sim \mathcal{N}(\boldsymbol{\mu}(\boldsymbol{x}), \kappa(\boldsymbol{x},\boldsymbol{x})) \tag{4} $$ ่ฟ™้‡Œ $$\boldsymbol{\mu}(\boldsymbol{x}): \mathbb{R^{n}} \rightarrow \mathbb{R^{n}} $$ ่กจ็คบๅ‡ๅ€ผๅ‡ฝๆ•ฐ๏ผˆMean function๏ผ‰๏ผŒ่ฟ”ๅ›žๅ„ไธช็ปดๅบฆ็š„ๅ‡ๅ€ผ๏ผ› $$ \kappa(\boldsymbol{x},\boldsymbol{x}) : \mathbb{R^{n}} \times \mathbb{R^{n}} \rightarrow \mathbb{R^{n\times n}} $$ ไธบๅๆ–นๅทฎๅ‡ฝๆ•ฐ Covariance Function๏ผˆไนŸๅซๆ ธๅ‡ฝๆ•ฐ Kernel Function๏ผ‰่ฟ”ๅ›žๅ„ไธช็ปดๅบฆไน‹้—ด็š„ๅๆ–นๅทฎ็Ÿฉ้˜ตใ€‚ไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹ไธบไธ€ไธชๅ‡ๅ€ผๅ‡ฝๆ•ฐๅ’Œๅๆ–นๅทฎๅ‡ฝๆ•ฐๅ”ฏไธ€ๅœฐๅฎšไน‰๏ผŒๅนถไธ”**ไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๆœ‰้™็ปดๅบฆ็š„ๅญ้›†้ƒฝๆœไปŽไธ€ไธชๅคšๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒ**๏ผˆไธบไบ†ๆ–นไพฟ็†่งฃ๏ผŒๅฏไปฅๆƒณ่ฑกไบŒๅ…ƒ้ซ˜ๆ–ฏๅˆ†ๅธƒไธคไธช็ปดๅบฆๅ„่‡ช้ƒฝๆœไปŽไธ€ไธช้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผ‰ใ€‚ ### ๆ ธๅ‡ฝๆ•ฐ๏ผˆๅๆ–นๅทฎๅ‡ฝๆ•ฐ๏ผ‰ ๆ ธๅ‡ฝๆ•ฐๆ˜ฏไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๆ ธๅฟƒ๏ผŒๆ ธๅ‡ฝๆ•ฐๅ†ณๅฎšไบ†ไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๆ€ง่ดจใ€‚ๆ ธๅ‡ฝๆ•ฐๅœจ้ซ˜ๆ–ฏ่ฟ‡็จ‹ไธญ่ตท็š„ไฝœ็”จๆ˜ฏ็”Ÿๆˆไธ€ไธชๅๆ–นๅทฎ็Ÿฉ้˜ต๏ผˆ็›ธๅ…ณ็ณปๆ•ฐ็Ÿฉ้˜ต๏ผ‰๏ผŒ่กก้‡ไปปๆ„ไธคไธช็‚นไน‹้—ด็š„โ€œ่ท็ฆปโ€ใ€‚ๆœ€ๅธธ็”จ็š„ไธ€ไธชๆ ธๅ‡ฝๆ•ฐไธบ้ซ˜ๆ–ฏๆ ธๅ‡ฝๆ•ฐ๏ผŒไนŸๆˆไธบๅพ„ๅ‘ๅŸบๅ‡ฝๆ•ฐ [RBF](https://en.wikipedia.org/wiki/Radial_basis_function_kernel)ใ€‚ๅ…ถๅŸบๆœฌๅฝขๅผๅฆ‚ไธ‹ใ€‚ๅ…ถไธญ $ \sigma$ๅ’Œ $l$ ๆ˜ฏ้ซ˜ๆ–ฏๆ ธ็š„่ถ…ๅ‚ๆ•ฐใ€‚ $$ K(x_i,x_j)=\sigma^2\mathrm{exp}\left( -\frac{\left \|x_i-x_j\right \|_2^2}{2l^2}\right) $$ ไปฅไธŠ้ซ˜ๆ–ฏๆ ธๅ‡ฝๆ•ฐ็š„ python ๅฎž็Žฐๅฆ‚ไธ‹ ```python import numpy as np def gaussian_kernel(x1, x2, l=1.0, sigma_f=1.0): """Easy to understand but inefficient.""" m, n = x1.shape[0], x2.shape[0] dist_matrix = np.zeros((m, n), dtype=float) for i in range(m): for j in range(n): dist_matrix[i][j] = np.sum((x1[i] - x2[j]) ** 2) return sigma_f ** 2 * np.exp(- 0.5 / l ** 2 * dist_matrix) def gaussian_kernel_vectorization(x1, x2, l=1.0, sigma_f=1.0): """More efficient approach.""" dist_matrix = np.sum(x1**2, 1).reshape(-1, 1) + np.sum(x2**2, 1) - 2 * np.dot(x1, x2.T) return sigma_f ** 2 * np.exp(-0.5 / l ** 2 * dist_matrix) x = np.array([700, 800, 1029]).reshape(-1, 1) print(gaussian_kernel_vectorization(x, x, l=500, sigma=10)) ``` ่พ“ๅ‡บ็š„ๅๆ–นๅทฎ็Ÿฉ้˜ตไธบ ``` [[100. 98.02 80.53] [ 98.02 100. 90.04] [ 80.53 90.04 100. ]] ``` ## ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅฎž็Žฐ&ๅฏ่ง†ๅŒ– ไธ‹ๅ›พๆ˜ฏ้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๅฏ่ง†ๅŒ–๏ผŒๅ…ถไธญ่“็บฟๆ˜ฏ้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๅ‡ๅ€ผ๏ผŒๆต…่“่‰ฒๅŒบๅŸŸ 95% ็ฝฎไฟกๅŒบ้—ด๏ผˆ็”ฑๅๆ–นๅทฎ็Ÿฉ้˜ต็š„ๅฏน่ง’็บฟๅพ—ๅˆฐ๏ผ‰๏ผŒๆฏๆก่™š็บฟไปฃ่กจไธ€ไธชๅ‡ฝๆ•ฐ้‡‡ๆ ท๏ผˆ่ฟ™้‡Œ็”จไบ† 100 ็ปดๆจกๆ‹Ÿ่ฟž็ปญๆ— ้™็ปด๏ผ‰ใ€‚ๅทฆไธŠ่ง’็ฌฌไธ€ๅน…ๅ›พๆ˜ฏ้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๅ…ˆ้ชŒ๏ผˆ่ฟ™้‡Œ็”จไบ†้›ถๅ‡ๅ€ผไฝœไธบๅ…ˆ้ชŒ๏ผ‰๏ผŒๅŽ้ขๅ‡ ๅน…ๅ›พๅฑ•็คบไบ†ๅฝ“่ง‚ๆต‹ๅˆฐๆ–ฐ็š„ๆ•ฐๆฎ็‚น็š„ๆ—ถๅ€™๏ผŒ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅฆ‚ไฝ•ๆ›ดๆ–ฐ่‡ช่บซ็š„ๅ‡ๅ€ผๅ‡ฝๆ•ฐๅ’Œๅๆ–นๅทฎๅ‡ฝๆ•ฐใ€‚ <!--START figure--> <div class="figure"> <a href="http://ww1.sinaimg.cn/large/006tNc79ly1g5ey8tww8oj30yr0jnwmq.jpg" data-lightbox="gps_visualization"> <img src="http://ww1.sinaimg.cn/large/006tNc79ly1g5ey8tww8oj30yr0jnwmq.jpg" width="100%" alt="gps_visualization" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> ๆŽฅไธ‹ๆฅๆˆ‘ไปฌ็”จๅ…ฌๅผๆŽจๅฏผไธŠๅ›พ็š„่ฟ‡็จ‹ใ€‚ๅฐ†้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๅ…ˆ้ชŒ่กจ็คบไธบ$f(\boldsymbol{x}) \sim \mathcal{N}(\boldsymbol{\mu}_{f}, K_{ff})$๏ผŒๅฏนๅบ”ๅทฆไธŠ่ง’็ฌฌไธ€ๅน…ๅ›พ๏ผŒๅฆ‚ๆžœ็Žฐๅœจๆˆ‘ไปฌ่ง‚ๆต‹ๅˆฐไธ€ไบ›ๆ•ฐๆฎ $ (\boldsymbol{x^{*}}, \boldsymbol{y^{*}}) $ ๏ผŒๅนถไธ”ๅ‡่ฎพ $ \boldsymbol{y^{*}} $ ไธŽ $ f(\boldsymbol{x}) $ ๆœไปŽ่”ๅˆ้ซ˜ๆ–ฏๅˆ†ๅธƒ $$ \begin{bmatrix} f(\boldsymbol{x})\\ \boldsymbol{y^{*}}\\ \end{bmatrix} \sim \mathcal{N} \left( \begin{bmatrix} \boldsymbol{\mu_f}\\ \boldsymbol{\mu_y}\\ \end{bmatrix}, \begin{bmatrix} K_{ff} & K_{fy}\\ K_{fy}^T & K_{yy}\\ \end{bmatrix} \right) $$ ๅ…ถไธญ $ K_{ff} = \kappa(\boldsymbol{x}, \boldsymbol{x}) $ ๏ผŒ$\$ K_{fy}=\kappa(\boldsymbol{x}, \boldsymbol{x^{*}}) $๏ผŒ$ K_{yy} = \kappa(\boldsymbol{x^{*}}, \boldsymbol{x^{*}}) $ ๏ผŒๅˆ™ๆœ‰ $$ f \sim \mathcal{N}(K_{fy}^{T}K_{ff}^{-1}\boldsymbol{y}+\boldsymbol{\mu_f},K_{yy}-K_{fy}^{T}K_{ff}^{-1}K_{fy}) \tag{5} $$ ๅ…ฌๅผ๏ผˆ5๏ผ‰่กจๆ˜Žไบ†็ป™ๅฎšๆ•ฐๆฎ$(\boldsymbol{x^{*}}, \boldsymbol{y^{*}})$ ไน‹ๅŽๅ‡ฝๆ•ฐ็š„ๅˆ†ๅธƒ $ f $ ไป็„ถๆ˜ฏไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹๏ผŒๅ…ทไฝ“็š„ๆŽจๅฏผๅฏ่ง [Gaussian Processes for Machine Learning](http://www.gaussianprocess.org/gpml/chapters/RW.pdf)ใ€‚่ฟ™ไธชๅผๅญๅฏไปฅ็œ‹ๅ‡บไธ€ไบ›ๆœ‰่ถฃ็š„ๆ€ง่ดจ๏ผŒ**ๅ‡ๅ€ผ $K_{fy}^{T}K_{ff}^{-1}\boldsymbol{y}+\boldsymbol{\mu_f}$ ๅฎž้™…ไธŠๆ˜ฏ่ง‚ๆต‹็‚น $ \boldsymbol{y} $ ็š„ไธ€ไธช็บฟๆ€งๅ‡ฝๆ•ฐ**๏ผŒๅๆ–นๅทฎ้กน $K_{yy}-K_{fy}^{T}K_{ff}^{-1}K_{fy}$ ็š„็ฌฌไธ€้ƒจๅˆ† $ K_{yy} $ ๆ˜ฏๆˆ‘ไปฌ็š„ๅ…ˆ้ชŒ็š„ๅๆ–นๅทฎ๏ผŒ**ๅ‡ๆމ็š„ๅŽ้ข็š„้‚ฃไธ€้กนๅฎž้™…ไธŠ่กจ็คบไบ†่ง‚ๆต‹ๅˆฐๆ•ฐๆฎๅŽๅ‡ฝๆ•ฐๅˆ†ๅธƒไธ็กฎๅฎšๆ€ง็š„ๅ‡ๅฐ‘**๏ผŒๅฆ‚ๆžœ็ฌฌไบŒ้กน้žๅธธๆŽฅ่ฟ‘ไบŽ 0๏ผŒ่ฏดๆ˜Ž่ง‚ๆต‹ๆ•ฐๆฎๅŽๆˆ‘ไปฌ็š„ไธ็กฎๅฎšๆ€งๅ‡ ไนŽไธๅ˜๏ผŒๅไน‹ๅฆ‚ๆžœ็ฌฌไบŒ้กน้žๅธธๅคง๏ผŒๅˆ™่ฏดๆ˜Žไธ็กฎๅฎšๆ€ง้™ไฝŽไบ†ๅพˆๅคšใ€‚ ไธŠๅผๅ…ถๅฎžๅฐฑๆ˜ฏ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’็š„ๅŸบๆœฌๅ…ฌๅผ๏ผŒ้ฆ–ๅ…ˆๆœ‰ไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ…ˆ้ชŒๅˆ†ๅธƒ๏ผŒ่ง‚ๆต‹ๅˆฐไธ€ไบ›ๆ•ฐๆฎ๏ผˆๆœบๅ™จๅญฆไน ไธญ็š„่ฎญ็ปƒๆ•ฐๆฎ๏ผ‰๏ผŒๅŸบไบŽๅ…ˆ้ชŒๅ’Œไธ€ๅฎš็š„ๅ‡่ฎพ๏ผˆ่”ๅˆ้ซ˜ๆ–ฏๅˆ†ๅธƒ๏ผ‰่ฎก็ฎ—ๅพ—ๅˆฐ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅŽ้ชŒๅˆ†ๅธƒ็š„ๅ‡ๅ€ผๅ’Œๅๆ–นๅทฎใ€‚ ### ็ฎ€ๅ•้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’ๅฎž็Žฐ ่€ƒ่™‘ไปฃ็ ๅฎž็Žฐไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’๏ผŒAPI ๆŽฅๅฃ้ฃŽๆ ผ้‡‡็”จ sciki-learn fit-predict ้ฃŽๆ ผใ€‚็”ฑไบŽ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’ๆ˜ฏไธ€็ง้žๅ‚ๆ•ฐๅŒ–็š„ๆ–นๆณ•๏ผŒๆฏๆฌก็š„ inference ้ƒฝ้œ€่ฆๅˆฉ็”จๆ‰€ๆœ‰็š„่ฎญ็ปƒๆ•ฐๆฎ่ฟ›่กŒ่ฎก็ฎ—ๅพ—ๅˆฐ็ป“ๆžœ๏ผŒๅ› ๆญคๅนถๆฒกๆœ‰ไธ€ไธชๆ˜พๅผ็š„่ฎญ็ปƒๆจกๅž‹ๅ‚ๆ•ฐ็š„่ฟ‡็จ‹๏ผŒๆ‰€ไปฅ fit ๆ–นๆณ•ๅช้œ€่ฆๅฐ†่ฎญ็ปƒๆ•ฐๆฎ่ฎฐๅฝ•ไธ‹ๆฅ๏ผŒๅฎž้™…็š„ inference ๅœจ predict ๆ–นๆณ•ไธญ่ฟ›่กŒใ€‚Python ไปฃ็ ๅฆ‚ไธ‹ ```python from scipy.optimize import minimize class GPR: def __init__(self, optimize=True): self.is_fit = False self.train_X, self.train_y = None, None self.params = {"l": 0.5, "sigma_f": 0.2} self.optimize = optimize def fit(self, X, y): # store train data self.train_X = np.asarray(X) self.train_y = np.asarray(y) self.is_fit = True def predict(self, X): if not self.is_fit: print("GPR Model not fit yet.") return X = np.asarray(X) Kff = self.kernel(self.train_X, self.train_X) # (N, N) Kyy = self.kernel(X, X) # (k, k) Kfy = self.kernel(self.train_X, X) # (N, k) Kff_inv = np.linalg.inv(Kff + 1e-8 * np.eye(len(self.train_X))) # (N, N) mu = Kfy.T.dot(Kff_inv).dot(self.train_y) cov = Kyy - Kfy.T.dot(Kff_inv).dot(Kfy) return mu, cov def kernel(self, x1, x2): dist_matrix = np.sum(x1**2, 1).reshape(-1, 1) + np.sum(x2**2, 1) - 2 * np.dot(x1, x2.T) return self.params["sigma_f"] ** 2 * np.exp(-0.5 / self.params["l"] ** 2 * dist_matrix) ``` ```python def y(x, noise_sigma=0.0): x = np.asarray(x) y = np.cos(x) + np.random.normal(0, noise_sigma, size=x.shape) return y.tolist() train_X = np.array([3, 1, 4, 5, 9]).reshape(-1, 1) train_y = y(train_X, noise_sigma=1e-4) test_X = np.arange(0, 10, 0.1).reshape(-1, 1) gpr = GPR() gpr.fit(train_X, train_y) mu, cov = gpr.predict(test_X) test_y = mu.ravel() uncertainty = 1.96 * np.sqrt(np.diag(cov)) plt.figure() plt.title("l=%.2f sigma_f=%.2f" % (gpr.params["l"], gpr.params["sigma_f"])) plt.fill_between(test_X.ravel(), test_y + uncertainty, test_y - uncertainty, alpha=0.1) plt.plot(test_X, test_y, label="predict") plt.scatter(train_X, train_y, label="train", c="red", marker="x") plt.legend() ``` ็ป“ๆžœๅฆ‚ไธ‹ๅ›พ๏ผŒ็บข็‚นๆ˜ฏ่ฎญ็ปƒๆ•ฐๆฎ๏ผŒ่“็บฟๆ˜ฏ้ข„ๆต‹ๅ€ผ๏ผŒๆต…่“่‰ฒๅŒบๅŸŸๆ˜ฏ 95% ็ฝฎไฟกๅŒบ้—ดใ€‚็œŸๅฎž็š„ๅ‡ฝๆ•ฐๆ˜ฏไธ€ไธช cosine ๅ‡ฝๆ•ฐ๏ผŒๅฏไปฅ็œ‹ๅˆฐๅœจ่ฎญ็ปƒๆ•ฐๆฎ็‚น่พƒไธบๅฏ†้›†็š„ๅœฐๆ–น๏ผŒๆจกๅž‹้ข„ๆต‹็š„ไธ็กฎๅฎšๆ€ง่พƒไฝŽ๏ผŒ่€Œๅœจ่ฎญ็ปƒๆ•ฐๆฎ็‚นๆฏ”่พƒ็จ€็–็š„ๅŒบๅŸŸ๏ผŒๆจกๅž‹้ข„ๆต‹ไธ็กฎๅฎšๆ€ง่พƒ้ซ˜ใ€‚ <!--START figure--> <div class="figure"> <a href="http://ww2.sinaimg.cn/large/006tNc79ly1g5f1y505m5j30b8077dg9.jpg" data-lightbox="1d_gpr"> <img src="http://ww2.sinaimg.cn/large/006tNc79ly1g5f1y505m5j30b8077dg9.jpg" width="50%" alt="1d_gpr" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> <br> ### ่ถ…ๅ‚ๆ•ฐไผ˜ๅŒ– ไธŠๆ–‡ๆๅˆฐ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๆ˜ฏไธ€็ง้žๅ‚ๆ•ฐๆจกๅž‹๏ผŒๆฒกๆœ‰่ฎญ็ปƒๆจกๅž‹ๅ‚ๆ•ฐ็š„่ฟ‡็จ‹๏ผŒไธ€ๆ—ฆๆ ธๅ‡ฝๆ•ฐใ€่ฎญ็ปƒๆ•ฐๆฎ็ป™ๅฎš๏ผŒๅˆ™ๆจกๅž‹ๅฐฑ่ขซๅ”ฏไธ€ๅœฐ็กฎๅฎšไธ‹ๆฅใ€‚ไฝ†ๆ˜ฏๆ ธๅ‡ฝๆ•ฐๆœฌ่บซๆ˜ฏๆœ‰ๅ‚ๆ•ฐ็š„๏ผŒๆฏ”ๅฆ‚้ซ˜ๆ–ฏๆ ธ็š„ๅ‚ๆ•ฐ $ \sigma $ ๅ’Œ $ l $ ๏ผŒๆˆ‘ไปฌ็งฐไธบ่ฟ™็งๅ‚ๆ•ฐไธบๆจกๅž‹็š„่ถ…ๅ‚ๆ•ฐ๏ผˆ็ฑปไผผไบŽ k-NN ๆจกๅž‹ไธญ k ็š„ๅ–ๅ€ผ๏ผ‰ใ€‚ ๆ ธๅ‡ฝๆ•ฐๆœฌ่ดจไธŠๅ†ณๅฎšไบ†ๆ ทๆœฌ็‚น็›ธไผผๆ€ง็š„ๅบฆ้‡ๆ–นๆณ•๏ผŒ่ฟ›่กŒๅฝฑๅ“ๅˆฐไบ†ๆ•ดไธชๅ‡ฝๆ•ฐ็š„ๆฆ‚็އๅˆ†ๅธƒ็š„ๅฝข็Šถใ€‚ไธŠ้ข็š„้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’็š„ไพ‹ๅญไธญไฝฟ็”จไบ† $ \sigma=0.2 $ ๅ’Œ $ l=0.5 $ ็š„่ถ…ๅ‚ๆ•ฐ๏ผŒๆˆ‘ไปฌๅฏไปฅ้€‰ๅ–ไธๅŒ็š„่ถ…ๅ‚ๆ•ฐ็œ‹็œ‹ๅ›žๅฝ’ๅ‡บๆฅ็š„ๆ•ˆๆžœใ€‚ <!--START figure--> <div class="figure"> <a href="http://ww2.sinaimg.cn/large/006tNc79ly1g5f2gikjrej30yb08q40y.jpg" data-lightbox="1d_gpr_hyper_parameters"> <img src="http://ww2.sinaimg.cn/large/006tNc79ly1g5f2gikjrej30yb08q40y.jpg" width="100%" alt="1d_gpr_hyper_parameters" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> ไปŽไธŠๅ›พๅฏไปฅ็œ‹ๅ‡บ๏ผŒ$ l $ ่ถŠๅคงๅ‡ฝๆ•ฐๆ›ดๅŠ ๅนณๆป‘๏ผŒๅŒๆ—ถ่ฎญ็ปƒๆ•ฐๆฎ็‚นไน‹้—ด็š„้ข„ๆต‹ๆ–นๅทฎๆ›ดๅฐ๏ผŒๅไน‹ $ l $ ่ถŠๅฐๅˆ™ๅ‡ฝๆ•ฐๅ€พๅ‘ไบŽๆ›ดๅŠ โ€œๆ›ฒๆŠ˜โ€๏ผŒ่ฎญ็ปƒๆ•ฐๆฎ็‚นไน‹้—ด็š„้ข„ๆต‹ๆ–นๅทฎๆ›ดๅคง๏ผ›$ \sigma $ ๅˆ™็›ดๆŽฅๆŽงๅˆถๆ–นๅทฎๅคงๅฐ๏ผŒ$ \sigma $ ่ถŠๅคงๆ–นๅทฎ่ถŠๅคง๏ผŒๅไน‹ไบฆ็„ถใ€‚ ๅฆ‚ไฝ•้€‰ๆ‹ฉๆœ€ไผ˜็š„ๆ ธๅ‡ฝๆ•ฐๅ‚ๆ•ฐ $ \sigma $ ๅ’Œ $ l $ ๅ‘ข๏ผŸ็ญ”ๆกˆๆœ€ๅคงๅŒ–ๅœจ่ฟ™ไธคไธช่ถ…ๅ‚ๆ•ฐไธ‹ $ \boldsymbol{y} $ ๅ‡บ็Žฐ็š„ๆฆ‚็އ๏ผŒ้€š่ฟ‡**ๆœ€ๅคงๅŒ–่พน็ผ˜ๅฏนๆ•ฐไผผ็„ถ๏ผˆMarginal Log-likelihood๏ผ‰ๆฅๆ‰พๅˆฐๆœ€ไผ˜็š„ๅ‚ๆ•ฐ**๏ผŒ่พน็ผ˜ๅฏนๆ•ฐไผผ็„ถ่กจ็คบไธบ $$ \mathrm{log}\ p(\boldsymbol{y}|\sigma, l) = \mathrm{log} \ \mathcal{N}(\boldsymbol{0}, K_{yy}(\sigma, l)) = -\frac{1}{2}\boldsymbol{y}^T K_{yy}^{-1}\boldsymbol{y} - \frac{1}{2}\mathrm{log}\ |K_{yy}| - \frac{N}{2}\mathrm{log} \ (2\pi) \tag{6} $$ ๅ…ทไฝ“็š„ๅฎž็Žฐไธญ๏ผŒๆˆ‘ไปฌๅœจ fit ๆ–นๆณ•ไธญๅขžๅŠ ่ถ…ๅ‚ๆ•ฐไผ˜ๅŒ–่ฟ™้ƒจๅˆ†็š„ไปฃ็ ๏ผŒๆœ€ๅฐๅŒ–่ดŸ่พน็ผ˜ๅฏนๆ•ฐไผผ็„ถใ€‚ ```python from scipy.optimize import minimize class GPR: def __init__(self, optimize=True): self.is_fit = False self.train_X, self.train_y = None, None self.params = {"l": 0.5, "sigma_f": 0.2} self.optimize = optimize def fit(self, X, y): # store train data self.train_X = np.asarray(X) self.train_y = np.asarray(y) # hyper parameters optimization def negative_log_likelihood_loss(params): self.params["l"], self.params["sigma_f"] = params[0], params[1] Kyy = self.kernel(self.train_X, self.train_X) + 1e-8 * np.eye(len(self.train_X)) return 0.5 * self.train_y.T.dot(np.linalg.inv(Kyy)).dot(self.train_y) + 0.5 * np.linalg.slogdet(Kyy)[1] + 0.5 * len(self.train_X) * np.log(2 * np.pi) if self.optimize: res = minimize(negative_log_likelihood_loss, [self.params["l"], self.params["sigma_f"]], bounds=((1e-4, 1e4), (1e-4, 1e4)), method='L-BFGS-B') self.params["l"], self.params["sigma_f"] = res.x[0], res.x[1] self.is_fit = True ``` ๅฐ†่ฎญ็ปƒใ€ไผ˜ๅŒ–ๅพ—ๅˆฐ็š„่ถ…ๅ‚ๆ•ฐใ€้ข„ๆต‹็ป“ๆžœๅฏ่ง†ๅŒ–ๅฆ‚ไธ‹ๅ›พ๏ผŒๅฏไปฅ็œ‹ๅˆฐๆœ€ไผ˜็š„ $ l=1.2 $๏ผŒ$ \sigma_f=0.8 $ <!--START figure--> <div class="figure"> <a href="http://ww2.sinaimg.cn/large/006tNc79ly1g5fgxxpx32j30b007pjrp.jpg" data-lightbox="1d_gpr_opt"> <img src="http://ww2.sinaimg.cn/large/006tNc79ly1g5fgxxpx32j30b007pjrp.jpg" width="50%" alt="1d_gpr_opt" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> ่ฟ™้‡Œ็”จ scikit-learn ็š„ [GaussianProcessRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.GaussianProcessRegressor.html#sklearn.gaussian_process.GaussianProcessRegressor) ๆŽฅๅฃ่ฟ›่กŒๅฏนๆฏ” ```python from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import ConstantKernel, RBF # fit GPR kernel = ConstantKernel(constant_value=0.2, constant_value_bounds=(1e-4, 1e4)) * RBF(length_scale=0.5, length_scale_bounds=(1e-4, 1e4)) gpr = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=2) gpr.fit(train_X, train_y) mu, cov = gpr.predict(test_X, return_cov=True) test_y = mu.ravel() uncertainty = 1.96 * np.sqrt(np.diag(cov)) # plotting plt.figure() plt.title("l=%.1f sigma_f=%.1f" % (gpr.kernel_.k2.length_scale, gpr.kernel_.k1.constant_value)) plt.fill_between(test_X.ravel(), test_y + uncertainty, test_y - uncertainty, alpha=0.1) plt.plot(test_X, test_y, label="predict") plt.scatter(train_X, train_y, label="train", c="red", marker="x") plt.legend() ``` ๅพ—ๅˆฐ็ป“ๆžœไธบ $ l=1.2, \sigma_f=0.6 $๏ผŒ่ฟ™ไธชไธŽๆˆ‘ไปฌๅฎž็Žฐ็š„ไผ˜ๅŒ–ๅพ—ๅˆฐ็š„่ถ…ๅ‚ๆ•ฐๆœ‰ไธ€็‚น็‚นไธๅŒ๏ผŒๅฏ่ƒฝๆ˜ฏๅฎž็Žฐ็š„็ป†่Š‚ๆœ‰ๆ‰€ไธๅŒๅฏผ่‡ดใ€‚ <!--START figure--> <div class="figure"> <a href="http://ww4.sinaimg.cn/large/006tNc79ly1g5fh435oqhj30bh07jmxh.jpg" data-lightbox="sklearn_gpr_compare"> <img src="http://ww4.sinaimg.cn/large/006tNc79ly1g5fh435oqhj30bh07jmxh.jpg" width="50%" alt="sklearn_gpr_compare" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> <br> ### ๅคš็ปด่พ“ๅ…ฅ ๆˆ‘ไปฌไธŠ้ข่ฎจ่ฎบ็š„่ฎญ็ปƒๆ•ฐๆฎ้ƒฝๆ˜ฏไธ€็ปด็š„๏ผŒ้ซ˜ๆ–ฏ่ฟ‡็จ‹็›ดๆŽฅๅฏไปฅๆ‰ฉๅฑ•ไบŽๅคš็ปด่พ“ๅ…ฅ็š„ๆƒ…ๅ†ต๏ผŒ็›ดๆŽฅๅฐ†่พ“ๅ…ฅ็ปดๅบฆๅขžๅŠ ๅณๅฏใ€‚ ```python def y_2d(x, noise_sigma=0.0): x = np.asarray(x) y = np.sin(0.5 * np.linalg.norm(x, axis=1)) y += np.random.normal(0, noise_sigma, size=y.shape) return y train_X = np.random.uniform(-4, 4, (100, 2)).tolist() train_y = y_2d(train_X, noise_sigma=1e-4) test_d1 = np.arange(-5, 5, 0.2) test_d2 = np.arange(-5, 5, 0.2) test_d1, test_d2 = np.meshgrid(test_d1, test_d2) test_X = [[d1, d2] for d1, d2 in zip(test_d1.ravel(), test_d2.ravel())] gpr = GPR(optimize=True) gpr.fit(train_X, train_y) mu, cov = gpr.predict(test_X) z = mu.reshape(test_d1.shape) fig = plt.figure(figsize=(7, 5)) ax = Axes3D(fig) ax.plot_surface(test_d1, test_d2, z, cmap=cm.coolwarm, linewidth=0, alpha=0.2, antialiased=False) ax.scatter(np.asarray(train_X)[:,0], np.asarray(train_X)[:,1], train_y, c=train_y, cmap=cm.coolwarm) ax.contourf(test_d1, test_d2, z, zdir='z', offset=0, cmap=cm.coolwarm, alpha=0.6) ax.set_title("l=%.2f sigma_f=%.2f" % (gpr.params["l"], gpr.params["sigma_f"])) ``` ไธ‹้ขๆ˜ฏไธ€ไธชไบŒ็ปด่พ“ๅ…ฅๆ•ฐๆฎ็š„ๅ‘Šไฝ ่ฟ‡็จ‹ๅ›žๅฝ’๏ผŒๅทฆๅ›พๆ˜ฏๆฒกๆœ‰็ป่ฟ‡่ถ…ๅ‚ไผ˜ๅŒ–็š„ๆ‹Ÿๅˆๆ•ˆๆžœ๏ผŒๅณๅ›พๆ˜ฏ็ป่ฟ‡่ถ…ๅ‚ไผ˜ๅŒ–็š„ๆ‹Ÿๅˆๆ•ˆๆžœใ€‚ <!--START figure--> <div class="figure"> <a href="http://ww4.sinaimg.cn/large/006tNc79ly1g5fm65aifoj30x40e4wpw.jpg" data-lightbox="2d_gpr"> <img src="http://ww4.sinaimg.cn/large/006tNc79ly1g5fm65aifoj30x40e4wpw.jpg" width="100%" alt="2d_gpr" referrerPolicy="no-referrer"/> </a> </div> <!--END figure--> ไปฅไธŠๅฎŒๆ•ด็š„็š„ไปฃ็ ๆ”พๅœจ [toys/GP](https://github.com/borgwang/toys/tree/master/GP)ใ€‚ ### ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’็š„ไผ˜็ผบ็‚น - ไผ˜็‚น - ๏ผˆ้‡‡็”จ RBF ไฝœไธบๅๆ–นๅทฎๅ‡ฝๆ•ฐ๏ผ‰ๅ…ทๆœ‰ๅนณๆป‘ๆ€ง่ดจ๏ผŒ่ƒฝๅคŸๆ‹Ÿๅˆ้ž็บฟๆ€งๆ•ฐๆฎ - ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’ๅคฉ็„ถๆ”ฏๆŒๅพ—ๅˆฐๆจกๅž‹ๅ…ณไบŽ้ข„ๆต‹็š„ไธ็กฎๅฎšๆ€ง๏ผˆ็ฝฎไฟกๅŒบ้—ด๏ผ‰๏ผŒ็›ดๆŽฅ่พ“ๅ‡บๅ…ณไบŽ้ข„ๆต‹็‚นๅ€ผ็š„ๆฆ‚็އๅˆ†ๅธƒ - ้€š่ฟ‡ๆœ€ๅคงๅŒ–่พน็ผ˜ไผผ็„ถ่ฟ™ไธ€็ฎ€ๆด็š„ๆ–นๅผ๏ผŒ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’ๅฏไปฅๅœจไธ้œ€่ฆไบคๅ‰้ชŒ่ฏ็š„ๆƒ…ๅ†ตไธ‹็ป™ๅ‡บๆฏ”่พƒๅฅฝ็š„ๆญฃๅˆ™ๅŒ–ๆ•ˆๆžœ - ็ผบ็‚น - ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๆ˜ฏไธ€ไธช้žๅ‚ๆ•ฐๆจกๅž‹๏ผŒๆฏๆฌก็š„ inference ้ƒฝ้œ€่ฆๅฏนๆ‰€ๆœ‰็š„ๆ•ฐๆฎ็‚น่ฟ›่กŒ๏ผˆ็Ÿฉ้˜ตๆฑ‚้€†๏ผ‰ใ€‚ๅฏนไบŽๆฒกๆœ‰็ป่ฟ‡ไปปไฝ•ไผ˜ๅŒ–็š„้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’๏ผŒnไธชๆ ทๆœฌ็‚นๆ—ถ้—ดๅคๆ‚ๅบฆๅคงๆฆ‚ๆ˜ฏ $\mathcal{O}(n^3)$๏ผŒ็ฉบ้—ดๅคๆ‚ๅบฆๆ˜ฏ $\mathcal{O}(n^2)$๏ผŒๅœจๆ•ฐๆฎ้‡ๅคง็š„ๆ—ถๅ€™้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ˜ๅพ— intractable - ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅ›žๅฝ’ไธญ๏ผŒๅ…ˆ้ชŒๆ˜ฏไธ€ไธช้ซ˜ๆ–ฏ่ฟ‡็จ‹๏ผŒlikelihood ไนŸๆ˜ฏ้ซ˜ๆ–ฏ็š„๏ผŒๅ› ๆญคๅพ—ๅˆฐ็š„ๅŽ้ชŒไปๆ˜ฏ้ซ˜ๆ–ฏ่ฟ‡็จ‹ใ€‚ๅœจ likelihood ไธๆœไปŽ้ซ˜ๆ–ฏๅˆ†ๅธƒ็š„้—ฎ้ข˜ไธญ๏ผˆๅฆ‚ๅˆ†็ฑป๏ผ‰๏ผŒ้œ€่ฆๅฏนๅพ—ๅˆฐ็š„ๅŽ้ชŒ่ฟ›่กŒ approximate ไฝฟๅ…ถไปไธบ้ซ˜ๆ–ฏ่ฟ‡็จ‹ - RBF ๆ˜ฏๆœ€ๅธธ็”จ็š„ๅๆ–นๅทฎๅ‡ฝๆ•ฐ๏ผŒไฝ†ๅœจๅฎž้™…ไธญ้€šๅธธ้œ€่ฆๆ นๆฎ้—ฎ้ข˜ๅ’Œๆ•ฐๆฎ็š„ๆ€ง่ดจ้€‰ๆ‹ฉๆฐๅฝ“็š„ๅๆ–นๅทฎๅ‡ฝๆ•ฐ ## ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅœฐ้ข็‚นๅˆ†็ฆป ### ็ฎ—ๆณ•ไป‹็ป ่ฟ™้‡Œ็ฎ€ๅ•ไป‹็ป: [ๅˆฉ็”จ้ซ˜ๆ–ฏ่ฟ‡็จ‹ๅˆ†็ฆปๅœฐ้ข](http://www.massey.ac.nz/~rwang/publications/13-JINT-Chen.pdf), ่ฏฅ่ฎบๆ–‡ไธญ็š„้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ไฝฟ็”จ. ๆˆ‘ไปฌ็Ÿฅ้“, ๅฏนไบŽๅนณๅฆ็š„ๅœฐ้ข`length-scal`$l$ๅบ”่ฏฅๅ–่พƒๅคงๅ€ผ, ่€ŒๅฏนไบŽ็ฒ—็ณ™็š„ๅœฐ้ขๅˆ™่ฏฅๅ–่พƒๅฐๅ€ผ, ๅœจ่ฏฅ่ฎบๆ–‡ไธญ, ไธบไบ†ๆ้ซ˜ๅˆ†็ฑป็š„็ฒพๅบฆ, ๅฏนไบŽๆฏไธชๆ‰‡ๅŒบ(ๆ‰‡ๅฝขๅŒบๅŸŸ)ไฝฟ็”จ้ž้™ๆ€็š„, ๅ„ๅ‘ๅŒๆ€ง็š„ๅๆ–นๅทฎๅ‡ฝๆ•ฐ: $$ k(r_i, r_j) = \sigma_f^2(l_i^2)^{\frac{1}{4}}(l_j^2)^{\frac{1}{4}}(\frac{l_i^2 + l_j^2}{2})^{-\frac{1}{2}} \times \exp(-\frac{2(r_i - r_j)^2}{l_i^2 + l_j^2}) $$ ไธบๆฏไธ€ไธช$r_i$, ้ƒฝ่ฎก็ฎ—ไธ€ไธชๅ•็‹ฌ็š„$l_i$. ่ฎบๆ–‡ไธญ้‡‡็”จINSAC(Incremental Sample Consensus)็š„ๆ–นๅผ่ฟญไปฃๅœฐ่ฟ›่กŒ้ซ˜ๆ–ฏ่ฟ‡็จ‹, ไปŽ่€ŒๅŒบๅˆ†ๅœฐ้ข็‚นๅ’Œๅค–็‚น. ็ฎ—ๆณ•ๆต็จ‹ๅฆ‚ไธ‹: <div style="text-align:center"> <img src=rc/gp_ground_detect.PNG width=400 /> </div> ่ฟ™้‡Œ, Mๆ˜ฏๆ‰‡ๅŒบ็š„ๆ•ฐ้‡, Nๆ˜ฏๆฏไธชๆ‰‡ๅŒบbin็š„ๆ•ฐ้‡, $PG_i$ๆ˜ฏไปฃ่กจๆ‰‡ๅŒบ, $P_{b_n^m}'$ไปฃ่กจๆ‰‡ๅŒบไธญ็š„bin, ๅœจๆฟ€ๅ…‰่Œƒๅ›ด$B$ๅ†…้ซ˜ๅบฆไธไฝŽไบŽ$T_s$็š„็‚นไฝœไธบ็งๅญ็‚น. ๅœจๅˆคๆ–ญๆ—ถ, ่ฎคไธบๆฏไธชbinไธญๅœฐ้ข็š„้ซ˜ๅบฆๆ˜ฏไธๅ˜็š„(ๅ–ไธ€ไธชๅ‡ๅ€ผ), ไธŽๅœฐ้ข้ซ˜ๅบฆๅทฎ่ถ…่ฟ‡้˜ˆๅ€ผ$T_r$็š„็‚น่ฎคไธบๆ˜ฏ้šœ็ข็‰ฉ็‚น, ๅฆๅˆ™่ฎคไธบๆ˜ฏๅœฐ้ข็‚น. ่ฟ™้‡Œไธไฝœ่ฏฆ็ป†็š„่งฃ้‡Š, ่ฏฆ็ป†ไฟกๆฏๅ‚็œ‹่ฎบๆ–‡ใ€ŠGaussian-Process-Based Real-Time Ground Segmentation for Autonomous Land Vehiclesใ€‹. ### ไปฃ็ ๅฎž็Žฐ ๅœจwavelib็š„ๅฎž็Žฐไธญ, ๅนถๆฒกๆœ‰ไธบๆฏไธ€ไธช$r_i$ๅ•็‹ฌ่ฎก็ฎ—$l_i$, ่€Œๆ˜ฏๅฐ†$l$ไฝœไธบไธ€ไธช่พ“ๅ…ฅๅ‚ๆ•ฐ. ๅฝ“็„ถ, `hyper-parameters`ๅ’Œ$\sigma_n^2$, ไนŸไฝœไธบ่พ“ๅ…ฅๅ‚ๆ•ฐ. ่ฏฅไปฃ็ ๅŸบๆœฌๅฎž็Žฐ่ฏฅ็ฎ—ๆณ•, ๅ…ถไธญ็š„INSAC(Incremental Sample Consensus)ๅ€ผๅพ—ๅ€Ÿ้‰ด. ็ฎ€ๅŒ–ๅŽ็š„ๅ…ฌๅผ: $$ \begin{aligned} k(r_i, r_j) &= \sigma_f^2 \exp(-\frac{(r_i - r_j)^2}{2l^2})\\ K &= k + \sigma_n^2 \mathbf{I} \end{aligned} $$ ๅ„ๅ‚ๆ•ฐ็š„็›ด่ง‚็†่งฃ: $\sigma_f^2$, ็†่งฃไธบไธ็กฎๅฎšๅบฆ็š„ไธ€ไธช็ผฉๆ”พ, $\sigma_f^2$่ถŠๅคง, ไธ็กฎๅฎšๅบฆๆ”พๅคง่ถŠๅฟซ. <div style="text-align:center"> <img src="rc/gp_sigma_sf_0.png" width=600 /> <img src="rc/gp_sigma_sf_0.png" width=600 /> <img src="rc/gp_sigma_sf_0.png" width=600 /> </div> $l$, ็†่งฃไธบไธๅŒ่ท็ฆป็‚นไน‹้—ด็š„็›ธๅ…ณๆ€ง, $l$่ถŠๅคง, ็‚นไธŽ็‚นไน‹้—ด็š„็›ธๅ…ณๆ€ง่ถŠๅผบ, ่ฟ™ไธชๅ›žๅคๅˆฐไธญๅฟƒๅ€ผ็š„้€Ÿๅบฆๅฐฑ่ถŠๆ…ข(้ซ˜ๆ–ฏ่ฟ‡็จ‹ๆœ‰ไธ€ไธชๆขๅคๅˆฐไธญๅฟƒๅ€ผ็š„่ถ‹ๅŠฟ, ่ฟ™้‡Œไธญๅฟƒๅ€ผไธบ0). <div style="text-align:center"> <img src="rc/gp_param_l_0.png" width=600 /> <img src="rc/gp_param_l_1.png" width=600 /> <img src="rc/gp_param_l_2.png" width=600 /> </div> $\sigma_n^2$, ็†่งฃไธบไธ็กฎๅฎšๅบฆ็š„ไธ€ไธชๅŸบ็›ธๅŠ , $\sigma_n^2$่ถŠๅคง. <div style="text-align:center"> <img src="rc/gp_sigma_sn_0.png" width=600 /> <img src="rc/gp_sigma_sn_1.png" width=600 /> </div> ### ไปฃ็ ็š„ไธ€ไบ›ๆ”น่ฟ› 1. ๅ‚่€ƒไบ†..ๆ นๆฎๆขฏๅบฆ้€‰ๅ–็งๅญ็‚น 2. insac่ฟ‡็จ‹ไธญ, ๅˆคๆ–ญ็‚นๆ˜ฏๅฆๆ˜ฏinlier็š„ๆ–นๆณ•ไผ˜ๅŒ– ๅŽŸๅฎž็Žฐ่ฎคไธบ $\frac{|y_{test} - y_{predict}|}{\sigma} < th$ ๅˆ™ไธบinlier, ็”ฑไธŠ้ข็š„ๅ›พๅฏไปฅ็œ‹ๅ‡บ, ๅฝ“่ท็ฆป่ถŠ่ฟœ, $\sigma$่ถŠๅคง(ไธ็กฎๅฎšๅบฆไนŸ่ถŠๅคง), ่ฟ™ๆ ท็š„ๅˆคๆ–ญๆ˜ฏไธๅ‡†็กฎ็š„. ๅŽŸๆ–นๆณ•ไปฃ็ : ```c++ double met = (sig_points[k].height - f_s(k)) / (sqrt(this->params.p_sn + vf * vf)); if (vf < this->params.p_tmodel & std::abs(met) < this->params.p_tdata) { // we have an inlier! ... } ``` ๅœจ่ฟ›่กŒไธ€ๆฌกๆ‹ŸๅˆๅŽ, ๆˆ‘ไปฌๅพ—ๅˆฐไบ†ๆต‹่ฏ•็‚น็š„้ข„ๆต‹ๅˆ†ๅธƒ$\mathcal{N}(y_{predict}, \sigma_{predict})$, ๆŒ‰็…งๆญคๅˆ†ๅธƒ, ๆˆ‘ไปฌ่ฆๆฑ‚ๅœจ $[y_{test} - th, y_{test}+th_{height}]$ ๅŒบ้—ดๅ†…็š„ๆฆ‚็އ่ถ…่ฟ‡ $th_{probility}$. ่ฟ™้‡Œ$th_{height} = 0.1, th_{probility}=0.8$, ๅณ __ๆˆ‘ไปฌๆœ‰80%็š„ๆฆ‚็އ, ็œŸๅฎž็š„ๅœฐ้ข้ซ˜ๅบฆไธŽๆต‹่ฏ•ๅ€ผ็›ธๅทฎๅœจ0.1็ฑณไปฅๅ†…__. <div style="text-align:center"> <img src="rc/gp_insac_th.png" width=600> </div> ็ฎ€ๅŒ–็งฏๅˆ†็š„่ฎก็ฎ—, ไฝฟ็”จ $(P(y_{test} - th) + P(y_{test} + th))*0.5*th$ๆฅ่ฟ‘ไผผ. 3. TODO ่ถ…ๅ‚ๆ•ฐไผ˜ๅŒ– Code: ## Result <div style="text-align:center"> <img src="rc/segmented_res.png"> </div> ## reference - [้ซ˜ๆ–ฏ่ฟ‡็จ‹ Gaussian Processes ๅŽŸ็†ใ€ๅฏ่ง†ๅŒ–ๅŠไปฃ็ ๅฎž็Žฐ](https://zhuanlan.zhihu.com/p/75589452) - [้€šไฟ—ๆ˜“ๆ‡‚ๅœฐไป‹็ปGaussian Process](https://www.zhihu.com/question/46631426) - [้ซ˜ๆ–ฏ่ฟ‡็จ‹็š„ๅŸบๆœฌๅŽŸ็†](https://www.bilibili.com/video/av35626047/) - [ๆœบๅ™จๅญฆไน ไธญ็š„้ซ˜ๆ–ฏ่ฟ‡็จ‹](https://www.datalearner.com/blog/1051459170229238) - [Gaussian Process ็†่ฎบ](http://www.dam.brown.edu/people/mraissi/teaching/2_gaussian_processes_tutorial/) - [Matlab GP example ไปฃ็ ](https://github.com/maziarraissi/TutorialGP) - [GP Ground Segmentation](http://www.massey.ac.nz/~rwang/publications/13-JINT-Chen.pdf) - [GP Ground Segmentation Code Wavelib](https://github.com/wavelab/libwave/tree/master/wave_matching/include/wave/matching) - [Carl Edward Rasmussen - Gaussian Processes for Machine Learning](http://www.gaussianprocess.org/gpml/chapters/RW.pdf) - [MLSS 2012 J. Cunningham - Gaussian Processes for Machine Learning](http://www.columbia.edu/~jwp2128/Teaching/E6892/papers/mlss2012_cunningham_gaussian_processes.pdf) - [Martin Krasser's blog- Gaussian Processes](http://krasserm.github.io/2018/03/19/gaussian-processes/) - [scikit-learn GaussianProcessRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.GaussianProcessRegressor.html)
Java
UTF-8
240
1.804688
2
[]
no_license
package pdf.font; /** * ํ™•์žฅ ์‹œ ๊ณตํ†ต ๋ชจ๋“ˆ ํ™œ์šฉ @Link{ItextFontRegister} * @author pioneer(2016.02.11) * */ public abstract class FontRegisterController{ private FontContainer fontContainer = FontContainer.getInstance(); }
Python
UTF-8
15,743
3.09375
3
[]
no_license
## python version 3.7.4 import openpyxl as openxl from spellchecker import SpellChecker import urllib.parse import urllib.request import os from bs4 import BeautifulSoup import nltk import re from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import numpy as np import scipy as sp from string import ascii_uppercase import seaborn as sns import pandas as pd ## Problem 1 & 2 def read_keywords(excel_file, keywords, cell): # Reads Keywords from an excel(.xlsx) file workbook = openxl.load_workbook(excel_file) sheet = workbook.active spell = SpellChecker() while sheet["A{}".format(cell)].value != None: keywords.append(sheet["A{}".format(cell)].value) keywords[-1] = " ".join([spell.correction(word).capitalize() for word in keywords[-1].split()]) # Ensures that keywords have correct spellings cell += 1 workbook.close() # Keywords are returned as a list return keywords def save_articles(keywords): # facilitates compiling search results, extracting article data and saving them to the file system for word in keywords: values = {'q' : word} data = urllib.parse.urlencode(values) search_url = "{}search?{}".format(url, data) # URL for searching a keyword using BBC's search feature articles = compile_articles(word, "", 0, search_url) # The string 'articles' will contain all data for 100 articles of a certain keyword print("Completed downloading relevant articles for Keyword {}\n".format(word)) with open("data/articles/{}.txt".format(word),"w", encoding = "utf-8") as f: # Data is written to a text file using the name of the keyword f.write(articles) f.close() def compile_articles(keyword, articles, counter, search_url): print("Searching for articles on {}\n".format(keyword)) search_soup = create_soup(search_url) # perform a search on each keyword using bbc's search feature num_pages = find_num_pages(search_soup) # Obtains the number of pages of search results returned on a BBC search query for page in range(1,num_pages+1): print("Searching Page {} for articles on {}".format(page,keyword)) # Loops through each search result page if page != 1: search_soup = create_soup("{}&page={}".format(search_url, page)) links = search_soup.find_all('ul')[3].find_all('a', href = True) # Obtains all article links found on a single search page for link in links: # Loops through each link found on a seach page if "www.bbc.co.uk/news" in link['href']: # All older BBC articles are rejected article = read_article(link['href'], "") # Retrieves all relevant article text if article == None: continue if keyword.lower() not in article: # Ensures that the article contains the keyword if ' ' not in keyword: continue else: key_list, b = [keyword.lower()][0].split(), True for word in key_list: if word not in article: b = False break if b == False: continue articles += article # Validated article gets appended to the string "articles" counter += 1 if counter == num_articles: # If 100 articles have been verified and stored, a string, 'articles' which contains all required data is returned return articles print("{} relevant articles found so far\n".format(counter)) return articles def create_soup(link): # Helper function, facilitatates creation of a soup from raw article data using BeautifulSoup request = urllib.request.Request(link) response = urllib.request.urlopen(request) return BeautifulSoup(response.read(), "html.parser") def find_num_pages(soup): # Finds the number of pages from a search query on a keyword try: num_pages = int(soup.find_all('b')[1].get_text()) except IndexError: num_pages = 1 # Number of Pages is returned return num_pages def read_article(article_link, article_text): # This function downloads the HTML from an article's webpage and then extracts the article's title and content article_soup = create_soup(article_link) # Article's webpage is downloaded(Problem 1) article_lines = [item.text.lower() for item in article_soup.find_all("div", attrs={"data-component" : "text-block"})] # Relevant content from the webpage is stored in the list 'article_lines' if article_lines == []: return None else: article_text += article_soup.find('title').text.replace(" - BBC News ",'.\n').lower() # Title of the article is extracted article_text += '\n'.join(article_lines) article_text += separator return article_text # Article data returned as a String ## Problem 3 model = {} def find_keyword_distances(keywords, data_dictionary, num_words): # facilitates cleaning of raw data and then feeding it to the semantic distance algorithm load_glove_embedding() # GloVe mode loaded semantic_distances = np.zeros((len(keywords),len(keywords)), dtype=float) # sematic_distances(2d array) will store the scores obtained by comparing article data of each keyword for word in keywords: # Reads article data from text files and convert them to an acceptable format with open("data/articles/{}.txt".format(word),"r", encoding = "utf-8") as f: full_dictionary = format_text(f.read(), {}) shortened_dictionary = shorten_dictionary(full_dictionary, {}, num_words) data_dictionary[word] = shortened_dictionary print("Article data for keyword, {} has been loaded and cleaned".format(word)) f.close() for i in range(0, len(keywords)): # Compares article data of every keyword and calculates the semantic distance between them for j in range(i, len(keywords)): distance = calculate_distance(data_dictionary[keywords[i]],data_dictionary[keywords[j]], 0, 0) # distance = distance between ith and jth keyword if i != j: semantic_distances[i][j], semantic_distances[j][i] = distance, distance else: semantic_distances[i][j] = distance print("Finished calculating distances for the keyword, {}".format(keywords[i])) distance_matrix = np.zeros((len(keywords),len(keywords)), dtype=float) # distance_matrix(2d array) will store the similarity between all keywords as a percentage for i in range(0,len(keywords)): for j in range(i, len(keywords)): # Each non-diagonal is divided by the larger of the ith and jth diagonal value to obtain percentage similarity if i == j: distance_matrix[i][j] = 100.0 else: if semantic_distances[i][i] > semantic_distances[j][j]: distance_matrix[i][j] = 100*semantic_distances[i][j]/semantic_distances[i][i] distance_matrix[j][i] = 100*semantic_distances[j][i]/semantic_distances[i][i] else: distance_matrix[i][j] = 100*semantic_distances[i][j]/semantic_distances[j][j] distance_matrix[j][i] = 100*semantic_distances[j][i]/semantic_distances[j][j] return distance_matrix def load_glove_embedding(): # This function loads word vector data from the file glove.6B.50d.txt amd stores it in a dictionary called model nltk.download('stopwords') print("Loading GloVe Word-Vector model") global model with open("data/glove.6B.50d.txt","r", encoding = "utf-8" ) as f: data = f.readlines() for line in data: line = line.split() model[line[0]] = np.array([float(val) for val in line[1:]]) print("Finished loading GloVe model, {} words loaded".format(len(model))) def format_text(raw_text, formatted_dictionary): # Cleans raw article data and stores it in a dictionary words_only = re.sub("[^a-zA-Z]", " ", str(raw_text.replace("'",''))).split() # Removes all non-alphabet characters stopword_list = [w.replace("'","") for w in list(stopwords.words("english"))] # Loads stopwords from nltk.corpus cleaned_words = [w for w in words_only if w not in stopword_list] # Remove stopwords for word in cleaned_words: # Builds dictionary from list of words if word not in formatted_dictionary and len(word) > 2: try: formatted_dictionary[word] = {"frequency": 1, "vector": model[word]} except KeyError: continue elif len(word) > 2: formatted_dictionary[word]["frequency"] += 1 return formatted_dictionary def shorten_dictionary(dictionary, shortened, counter): for word in (sorted(dictionary.items(), key=lambda x: x[1]["frequency"], reverse = True)): # Sort(descending) words by frequency, highest frequency words will be stored within shortened shortened[word[0]] = word[1] counter -=1 if counter == 0: return shortened return shortened def calculate_distance(a1, a2, total, avg): # Computes a semantic score by comparing 2 dictionaries for w1 in a1: p1 = a1[w1] for w2 in a2: # The semantic score is calculated here try: total += ((p1["frequency"]*a2[w2]["frequency"])**0.5)*((0.5*(len(w2)+len(w1)))**0.5)*(1 - sp.spatial.distance.cosine(p1["vector"], a2[w2]["vector"])) avg += ((p1["frequency"]*a2[w2]["frequency"])**0.5)*((0.5*(len(w2)+len(w1)))**0.5) except KeyError: continue except TypeError: break avg = (total/avg) return avg # Below is the main logic of the first(rejected) attempt at the algorithm """def compute_distance(a1, a2): vector_1 = np.mean(calc_mean(a1, []),axis=0) vector_2 = np.mean(calc_mean(a2, []),axis=0) cosine = sp.spatial.distance.cosine(vector_1, vector_2) print('The two keywords are similar to',round((1-cosine)*100,2),'%') return def calc_mean(a, v_list): # global model for word in a: try: v_list.append(model[word]) except: continue return v_list""" def write_distances(input_file, distance_matrix, size, distance_file): # Writes calculated semantic distances to an excel sheet workbook = openxl.load_workbook(input_file) sheet = workbook.active for i in range(0,size): # This function does not work if there are more than 25 keywords for j in range(0,size): sheet["{}{}".format(chr(66+i),2+j)] = distance_matrix[i][j] workbook.save(distance_file) workbook.close() ## Problem 4 def read_distances(distance_file): # Reads keywords names and % semantic similarity between them from an excel file keywords = read_keywords(distance_file, [], 2) size = len(keywords) workbook = openxl.load_workbook(distance_file) sheet = workbook.active distance_matrix = np.zeros((size,size), dtype=int) for i in range(0,size): for j in range(0,size): distance_matrix[i][j] = int(sheet["{}{}".format(chr(66+i),2+j)].value) return keywords, distance_matrix def sns_distance_heatmap(keywords, distance_matrix, is_mask): # Generates a heatmap using the semantic distance between each word df = pd.DataFrame(distance_matrix, index = keywords, columns = keywords) sns.set_theme() sns.set(rc={'figure.figsize':(16.2,14.7)}) if is_mask == True: mask = np.zeros_like(distance_matrix) mask[np.triu_indices_from(mask)] = True for i in range(len(keywords)): mask[i][i] = 0 ax = sns.heatmap(df, cmap="YlGnBu", annot = True, fmt ="d", vmin=50, square=True, mask = mask) else: ax = sns.heatmap(df, cmap="YlGnBu", annot = True, fmt ="d", vmin=50, square=True, mask = None) ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") ax.set_yticklabels(ax.get_xticklabels(), rotation=40, ha="right") ax.tick_params(labelsize=13) disp = ax.get_figure() disp.savefig("data/images/heatmap.png") ax.cla() disp.clf() def sns_distance_bar_chart(keywords, distance_matrix): # Generates a Bar chart for each keyword, using semantic distances as a Y axis for i in range(len(keywords)): df = pd.DataFrame({"Keywords": keywords, "Distance": distance_matrix[i]}) sns.set_theme() sns.set(rc={'figure.figsize':(8,8)}) ax = sns.barplot(data=df, x="Keywords", y="Distance", color= "gray") ax.set_ylabel("Distance", fontsize=20) ax.set_xlabel("Keywords", fontsize=20) ax.set_ylim(50,100) ax.set_title(keywords[i],fontsize=30, pad=20) ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha="right") ax.tick_params(labelsize=12) disp = ax.get_figure() disp.savefig("data/images/bar_charts/{}.png".format(keywords[i])) ax.cla() disp.clf() ## Main def main(): global num_articles keywords_file = "keywords.xlsx" distance_file = "distance.xlsx" num_articles = 100 # Number if articles to be read from BBC keywords = read_keywords(keywords_file, [], 2) print("{} keywords were read:\n{}".format(len(keywords),', '.join(keywords))) save_articles(keywords) # Calling this functions performs the tasks of Problem 1 and 2 num_words = 250 # Maximum number of words to be inputted to the semantic distance algorithm distance_matrix = find_keyword_distances(keywords, {}, num_words) # Performs tasks related to Problem 3 write_distances(keywords_file, distance_matrix, len(keywords), distance_file) # Result of the algorithm is written to an excel file keywords, distance_matrix = read_distances(distance_file) # Inputs for the seaborn visualizations are obtained heatmap_cutoff = True # Decides whether the upper triangle of the heatmap generated should be cutoff sns_distance_heatmap(keywords, distance_matrix, heatmap_cutoff) # Generates a heatmap for the keywords print("Heatmap successfully generated, go to data/images to view the visualization") sns_distance_bar_chart(keywords, distance_matrix) print("Bar-plots successfully generated, go to data/images/bar_plots to view the visualizations") # Generates a bar chart for each keyword if __name__=='__main__': separator = "\n\n\n{}\n{}\n{}\n\n".format(100*'#',100*'#',100*'#') url = "https://www.bbc.co.uk/" global num_articles if os.path.exists("data") == False: os.mkdir("data") if os.path.exists("data/images") == False: os.mkdir("data/images") if os.path.exists("data/articles") == False: os.mkdir("data/articles") if os.path.exists("data/images/bar_charts") == False: os.mkdir("data/images/bar_charts") main()
C#
UTF-8
791
2.921875
3
[ "MIT" ]
permissive
using System; namespace NGravatar.ProfileInformation { /// <summary> /// A photo field in a Gravatar profile. /// </summary> public class GravatarProfilePhoto : GravatarProfilePluralField { /// <summary> /// Creates a new instance of the photo field /// </summary> /// <param name="value">The URI of the photo.</param> public GravatarProfilePhoto(string value) : this(value, null) { } /// <summary> /// Creates a new instance of the photo field. /// </summary> /// <param name="value">The URI of the photo.</param> /// <param name="type">The type of the photo.</param> public GravatarProfilePhoto(string value, string type) : base(value, type) { } } }
JavaScript
UTF-8
568
2.828125
3
[ "MIT" ]
permissive
function nn() { "use strict"; /** * data */ function generator() {} /** * SVG chart elements */ function chart() {} /** * perceptron / neuron */ function neuron() {} /** * generator + neuron + chart */ function build() {} /** * draw the chart to root `<div>` */ function draw() { function drawP(text) { var elem = document.createElement("p"); elem.innerText = text; document.getElementById("root").append(elem); } drawP("(0,0) Note: SVG origin is top left"); } draw(); } nn();
C#
UTF-8
438
3.078125
3
[]
no_license
namespace AdventOfCode2019 { struct Rect { public int xmin, xmax, ymin, ymax; public Rect(int width, int height) { xmin = 0; ymin = 0; xmax = width - 1; ymax = height - 1; } public bool Contains(Point p) { return xmin <= p.x && xmax >= p.x && ymin <= p.y && ymax >= p.y; } } }
PHP
UTF-8
273
3
3
[]
no_license
<?php $tekst1 = "hello world"; $tekst2 = "mijn bestand"; $tekst3 = "mijn bestand nummer2"; $tekst4 = "mijn bestand nummer3"; echo $tekst1; echo PHP_EOL; echo $tekst2; echo PHP_EOL; echo $tekst3; echo PHP_EOL; echo $tekst4; echo PHP_EOL; ?>
C++
UTF-8
1,294
2.578125
3
[ "Zlib", "BSD-3-Clause", "MIT", "LicenseRef-scancode-other-permissive", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <fc/network/http/websocket.hpp> #include <websocketpp/error.hpp> #include <iostream> #include <string> #include <fc/log/logger.hpp> #include <fc/log/console_appender.hpp> int main(int argc, char** argv) { try { // set up logging fc::appender::ptr ca(new fc::console_appender); fc::logger l = fc::logger::get("rpc"); l.add_appender( ca ); fc::http::websocket_client client; fc::http::websocket_connection_ptr s_conn, c_conn; std::string url = argv[1]; wlog( "Connecting to server at url ${url}", ("url", url) ); c_conn = client.connect( "ws://" + url ); std::string echo; c_conn->on_message_handler([&](const std::string& s){ echo = s; }); c_conn->send_message( "hello world" ); fc::usleep( fc::milliseconds(500) ); if (echo != std::string("echo: hello world") ) wlog( "Test1 failed, echo value: [${echo}]", ("echo", echo) ); c_conn->send_message( "again" ); fc::usleep( fc::milliseconds(500) ); if ("echo: again" != echo) wlog( "Test2 failed, echo value: [${echo}]", ("echo", echo) ); } catch (const websocketpp::exception& ex) { elog( "websocketpp::exception thrown: ${err}", ("err", ex.what()) ); } }
PHP
UTF-8
2,896
3.546875
4
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
<?php namespace aldorg\validater; /** * Validater Class * * This is an simple class to validate data types for PHP codes. Using php filters with simple methods to verify info. * * @author Aldo Ruiz */ class Validater{ /** * Validate that an attribute is a boolean. * * @param mixed $boolean * @return bool (string for testing purposes) */ public static function validateBoolean($boolean) { $acceptable = [true, false, 0, 1, '0', '1']; return in_array($boolean, $acceptable, true) ? 'true' : 'false'; } /** * Validate that an attribute is an email based on RFC 822 syntax. * * @param mixed $email * @return bool (string for testing purposes) */ public static function validateEmail($email){ return filter_var($email, FILTER_VALIDATE_EMAIL) ? 'true' : 'false'; } /** * Validate that an attribute is an integer. * * @param mixed $number * @return bool (string for testing purposes) */ public static function validateInteger($number) { return filter_var($number, FILTER_VALIDATE_INT) ? 'true' : 'false'; } /** * Validate that an attribute is an array. * * @param array $array * @return bool */ public static function validateArray($array) { return is_array($array) ? 'true' : 'false'; } /** * Validate that an attribute is numeric. * * @param mixed $number * @return bool */ public static function validateNumeric($number) { return is_numeric($number) ? 'true' : 'false'; } /** * Validate that an attribute is a string. * * @param string $string * @return bool */ public static function validateString($string) { return is_string($string) ? 'true' : 'false'; } /** * Validate that an attribute is a valid URL. * * @param mixed $url * @return bool */ public static function validateUrl($url) { return filter_var($url, FILTER_VALIDATE_URL) !== false; } /** * Validate that an attribute contains only alphabetic characters. * * @param mixed $string * @return bool */ public static function validateAlpha($string) { return preg_match('/^[\pL\pM]+$/u', $string); } /** * Validate that an attribute contains only alpha-numeric characters. * * @param mixed $string * @return bool */ public static function validateAlphaNum($string) { return preg_match('/^[\pL\pM\pN]+$/u', $string); } /** * Validate that an attribute is a valid date. * * @param mixed $date * @return bool */ public static function validateDate($date) { if ($date instanceof DateTime) { return true; } if (strtotime($date) === false) { return false; } $date = date_parse($date); return checkdate($date['month'], $date['day'], $date['year']); } }
C++
UTF-8
4,862
3.328125
3
[]
no_license
/* ะŸะพ ะดะฐะฝะฝั‹ะผ n ะพั‚ั€ะตะทะบะฐะผ ะฝะตะพะฑั…ะพะดะธะผะพ ะฝะฐะนั‚ะธ ะผะฝะพะถะตัั‚ะฒะพ ั‚ะพั‡ะตะบ ะผะธะฝะธะผะฐะปัŒะฝะพะณะพ ั€ะฐะทะผะตั€ะฐ, ะดะปั ะบะพั‚ะพั€ะพะณะพ ะบะฐะถะดั‹ะน ะธะท ะพั‚ั€ะตะทะบะพะฒ ัะพะดะตั€ะถะธั‚ ั…ะพั‚ั ะฑั‹ ะพะดะฝัƒ ะธะท ั‚ะพั‡ะตะบ. ะ’ ะฟะตั€ะฒะพะน ัั‚ั€ะพะบะต ะดะฐะฝะพ ั‡ะธัะปะพ 1โ‰คnโ‰ค100 ะพั‚ั€ะตะทะบะพะฒ. ะšะฐะถะดะฐั ะธะท ะฟะพัะปะตะดัƒัŽั‰ะธั… n ัั‚ั€ะพะบ ัะพะดะตั€ะถะธั‚ ะฟะพ ะดะฒะฐ ั‡ะธัะปะฐ 0โ‰คlโ‰คrโ‰ค109, ะทะฐะดะฐัŽั‰ะธั… ะฝะฐั‡ะฐะปะพ ะธ ะบะพะฝะตั† ะพั‚ั€ะตะทะบะฐ. ะ’ั‹ะฒะตะดะธั‚ะต ะพะฟั‚ะธะผะฐะปัŒะฝะพะต ั‡ะธัะปะพ m ั‚ะพั‡ะตะบ ะธ ัะฐะผะธ m ั‚ะพั‡ะตะบ. ะ•ัะปะธ ั‚ะฐะบะธั… ะผะฝะพะถะตัั‚ะฒ ั‚ะพั‡ะตะบ ะฝะตัะบะพะปัŒะบะพ, ะฒั‹ะฒะตะดะธั‚ะต ะปัŽะฑะพะต ะธะท ะฝะธั… Sample Input 1: 3 1 3 2 5 3 6 Sample Output 1: 1 3 Sample Input 2: 4 4 7 1 3 2 5 5 6 Sample Output 2: 2 3 6 */ #include <iostream> #include <utility> #include <vector> #include <algorithm> typedef std::pair <int, int> Segment; int getFirst (const Segment& sg){ return sg.first; }; int getSecond (const Segment& sg){ return sg.second; }; typedef int (* fGetPoint )(const Segment& sg); void setFirst ( Segment& sg, int value){ sg.first = value; }; void setSecond ( Segment& sg, int value){ sg.second =value; }; typedef void (* fSetPoint )( Segment& sg, int value); struct SPoints{ std::vector <Segment>& points; fGetPoint getPoint; fSetPoint setPoint; SPoints(std::vector <Segment>& segments, fGetPoint getPoint, fSetPoint setPoint); void setNewValue(std::size_t i, std::size_t i_end, int next_point); bool can_setNewValue(std::size_t i, std::size_t i_end, int new_value); bool getNextPoint(int i_curr, int& i, int& value); void shiftPoints(); }; SPoints::SPoints(std::vector <Segment>& segments, fGetPoint getPoint, fSetPoint setPoint ): points(segments),getPoint(getPoint), setPoint(setPoint) { } bool SPoints::can_setNewValue(std::size_t i, std::size_t i_end, int new_value){ for (; i < i_end; i++) { //ะตัะปะธ ะฝะพะฒะพะต ะทะฝะฐั‡ะตะฝะธะต ะฟะพะฟะฐะดะฐะตั‚ ะฒ ะดะธะฐะฟะฐะทะพะฝ; if ( points[i].first <= new_value && points[i].second >= new_value) continue; return false; } return true; } void SPoints::setNewValue(std::size_t i, std::size_t i_end, int next_point){ for (; i < i_end; i++) { setPoint(points[i], next_point); } } bool SPoints::getNextPoint(int i_curr, int& i, int& value){ int curr_point = getPoint(points[i_curr]); i = i_curr; for (; i < points.size(); i++) { if (getPoint(points[i]) == curr_point) continue; value=getPoint(points[i]); return true; } return false; } void SPoints::shiftPoints(){ std::size_t count = points.size(); for (std::size_t i = 0; i < count; ) { int new_value; int i_next; if (!getNextPoint(i, i_next, new_value )) break; while( can_setNewValue(i, i_next, new_value) ){ setNewValue(i, i_next, new_value) ; if (!getNextPoint(i_next, i_next, new_value )) break; } i=i_next; } } std::vector <int> get_covering_set(std::vector <Segment> segments) { std::vector <int> result; /*struct { bool operator()(const Segment& a, const Segment& b) const { return a.first < b.first; } } SortFirst; std::sort (segments.begin(), segments.end(), SortFirst ); SPoints startPoint(segments, getFirst, shiftFirstToRight); startPoint.shiftPoints();*/ struct { bool operator()(const Segment& a, const Segment& b) const { return a.second > b.second; } } SortSecond; std::sort(segments.begin(), segments.end(), SortSecond ); SPoints endPoint(segments, getSecond, setSecond); endPoint.shiftPoints(); if (segments.size() ==0 ) return result; result.push_back(segments[0].second); int last = segments[0].second ; for (std::size_t i = 1; i < segments.size(); i++) { if (last == segments[i].second) continue; result.push_back(segments[i].second); last = segments[i].second ; } return result; } int main(void) { int segments_count; std::cin >> segments_count; std::vector <Segment> segments(segments_count); for (int i = 0; i < segments_count; i++) { std::cin >> segments[i].first >> segments[i].second; } std::vector <int> points = get_covering_set(segments); std::cout << points.size() << std::endl; for (std::size_t i = 0; i < points.size(); i++) { std::cout << points[i] << " "; } std::cout << std::endl; }
C
UTF-8
2,833
3.015625
3
[]
no_license
/* * ePiloto.h * * Created on: Jun 28, 2021 * Author: rodrigo */ #ifndef INC_EPILOTO_H_ #define INC_EPILOTO_H_ #include "../inc/efecha.h" #include <stdlib.h> #include <string.h> #include <stdio.h> typedef struct { int idPiloto; char nombre[128]; }ePiloto; /** * */ ePiloto* ePiloto_new(); /** * */ ePiloto* ePiloto_newParametros(char* idPiloto, char* nombre); /** * */ void ePiloto_delete(ePiloto* this); /** * */ int ePiloto_setIdPiloto(ePiloto* this, int id); /** * */ int ePiloto_getIdPiloto(ePiloto* this, int* id); /** * */ int ePiloto_setNombre(ePiloto* this, char nombre[]); /** * */ int ePiloto_getNombre(ePiloto* this, char* nombre); /** * @fn int ePiloto_showePiloto(ePiloto*) * @brief se muestra un empleado recibido * * @param miEmpleado * @return estado (-1 si falla, 1 si se muestra ok) */ int ePiloto_showePiloto(ePiloto* miEmpleado); /** * @fn int ePiloto_getePiloto(ePiloto*, int*, char*, int*, int*) * @brief se pueblan las variables int y char con los campos del empleado recibido * * @param miEmpleado * @param auxId * @param auxNombre * @param auxHoras * @param auxSueldo * @return estado (-1 si falla, 1 si se carga ok) */ int ePiloto_getePiloto(ePiloto* miPiloto, int* auxIdPiloto, char* auxNombre); /** * @fn int ePiloto_sortId(void*, void*) * @brief se reciben dos punteros void, se castean a ePiloto, se comparan los id de los empleados y se retorna un estado que indica si un id es menor, mayor o igual a otro * * @param e1 * @param e2 * @return estado (-1 si es menor, 1 si es mayor, 0 si es igual) */ //int ePiloto_sortId(void* e1, void* e2); /** * @fn int ePiloto_sortNombre(void*, void*) * @brief se reciben dos punteros void, se castean a ePiloto, se comparan los nombres de los empleados y se retorna un estado que indica si un nombre es menor, mayor o igual a otro * * @param e1 * @param e2 * @return estado (-1 si es menor, 1 si es mayor, 0 si es igual) */ //int ePiloto_sortNombre(void* e1, void* e2); /** * @fn int ePiloto_sortHorasTrabajadas(void*, void*) * @brief se reciben dos punteros void, se castean a ePiloto, se comparan las horas trabajadas de los empleados y se retorna un estado que indica si las horas trabajadas son menores, mayores o iguales a las de otro * * @param e1 * @param e2 * @return estado (-1 si es menor, 1 si es mayor, 0 si es igual) */ //int ePiloto_sortHorasTrabajadas(void* e1, void* e2); /** * @fn int ePiloto_sortSueldo(void*, void*) * @brief se reciben dos punteros void, se castean a ePiloto, se comparan los sueldos de los empleados y se retorna un estado que indica si un sueldo es menor, mayor o igual a otro * * @param e1 * @param e2 * @return estado (-1 si es menor, 1 si es mayor, 0 si es igual) */ //int ePiloto_sortSueldo(void* e1, void* e2); #endif /* INC_EPILOTO_H_ */
C++
UTF-8
3,529
2.703125
3
[]
no_license
/* * Dijkstra with low costs + compression */ #include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <cmath> #include <queue> using namespace std; #define mp make_pair #define pb push_back #define ll long long #define maxN 555 #define maxDir 9 class Buffer { public: Buffer(string name, int _dim) { freopen(name.c_str(), "r", stdin); dim = _dim; data.resize(dim + 2); refill(); } Buffer& operator>>(int &dest) { while (!is_digit(data[pos])) if (++pos == dim) refill(); dest = 0; while (is_digit(data[pos])) { dest = dest * 10 + data[pos] - '0'; if (++pos == dim) refill(); } return *this; } private: int dim, pos; vector<char> data; bool is_digit(char c) { return '0' <= c && c <= '9'; } void refill() { pos = 0; memset(&data[0], 0, dim); fread(&data[0], 1, dim, stdin); } }; Buffer fin("car.in", 1 << 20); int defX[8] = {+1, +1, +1, 0, -1, -1, -1, 0}; int defY[8] = {-1, 0, +1, +1, +1, 0, -1, -1}; int defAng[8] = {0, 1, 2, 3, 4, 5, 6, 7}; int n, m, i, j, x, y, dir; int xs, ys, xd, yd; bool deny[maxN][maxN]; int dist[maxN][maxN][maxDir]; vector<int> H[maxN * maxN * 4 + 10]; int h_cnt, h_pos; int ans; int compress(int x, int y, int dir) { return (x << 12) + (y << 3) + dir; } int decompress(int val, int &x, int &y, int &dir) { dir = val & 7; val >>= 3; y = val & 511; val >>= 9; x = val; } int pay(int ang1, int ang2) { ang1 -= ang2; if (ang1 < 0) ang1 = -ang1; if (ang1 > 4) ang1 = 8 - ang1; return ang1; } int main() { //freopen("car.in","r",stdin); freopen("car.out","w",stdout); fin >> n >> m; fin >> xs >> ys >> xd >> yd; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { fin >> x; if (x) deny[i][j] = true; } } for (i = 0; i <= n + 1; i++) deny[i][0] = deny[i][m + 1] = true; for (i = 0; i <= m + 1; i++) deny[0][i] = deny[n + 1][i] = true; //! start the engine for (i = 0; i < 8; i++) { dist[xs][ys][i] = 1; h_cnt++; H[1].pb(compress(xs, ys, i)); } h_pos = 1; while (h_cnt) { while (H[h_pos].empty()) h_pos++; int now = H[h_pos][ H[h_pos].size() - 1 ]; H[h_pos].pop_back(); h_cnt--; decompress(now, x, y, dir); if (dist[x][y][dir] < h_pos) continue; if (x == xd && y == yd) { ans = h_pos; break; } for (i = 0; i < 8; i++) { int new_pay = dist[x][y][dir] + pay(dir, defAng[i]); if (dist[x][y][i] == 0 || dist[x][y][i] > new_pay) { dist[x][y][i] = new_pay; H[new_pay].pb(compress(x, y, i)); h_cnt++; } } int xx = x + defX[dir]; int yy = y + defY[dir]; if (deny[xx][yy] == false) if (dist[xx][yy][dir] == 0 || dist[xx][yy][dir] > dist[x][y][dir] ) { dist[xx][yy][dir] = dist[x][y][dir]; H[ dist[x][y][dir] ].pb(compress(xx, yy, dir)); h_cnt++; } } if (ans == 0) printf("-1"); else printf("%d", ans - 1); return 0; }
SQL
UTF-8
726
3.671875
4
[]
no_license
-- Ensure you've run SalesOrdersStructure.sql -- and SalesOrdersData.sql in the Sample Databases folder -- in order to run this example. SET SCHEMA SalesOrdersSample; WITH SeqNumTbl(SeqNum) AS (VALUES (1) UNION ALL SELECT SeqNum + 1 FROM SeqNumTbl WHERE SeqNum < 100), SeqList AS (SELECT SeqNum FROM SeqNumTbl) SELECT ' ' AS CustName, ' ' AS CustStreetAddress, ' ' AS CustCityState, ' ' AS CustZipCode FROM SeqList WHERE SeqNum <= 3 UNION ALL SELECT C.CustFirstName CONCAT ' ' CONCAT C.CustLastName AS CustName, C.CustStreetAddress, C.CustCity CONCAT ', ' CONCAT C.CustState CONCAT ' ' CONCAT C.CustZipCode AS CustCityState, C.CustZipCode FROM Customers AS C ORDER BY CustZipCode;
Java
UTF-8
1,416
2.9375
3
[]
no_license
class Tree{ public ArrayList <Integer> verticalSum(Node root) { class QueueN{ public Node node; public int hd; QueueN(Node n, int h){ node=n; hd=h; } } ArrayList<Integer> al = new ArrayList<>(); Queue<QueueN> q= new LinkedList<>(); Map<Integer, Integer> hm= new TreeMap<>(); if(root==null) return al; else q.add( new QueueN(root,0)); while(!q.isEmpty()){ QueueN tmp=q.poll(); if(hm.containsKey(tmp.hd)){ hm.put(tmp.hd, hm.get(tmp.hd)+tmp.node.data); // System.out.print("ok1"); } else{ hm.put(tmp.hd,tmp.node.data); //System.out.print("ok"); } if(tmp.node.left!=null) q.add(new QueueN(tmp.node.left, tmp.hd-1)); if(tmp.node.right!=null) q.add(new QueueN(tmp.node.right, tmp.hd+1)); } for(Map.Entry<Integer,Integer> entry: hm.entrySet()){ al.add(entry.getValue()); } return al; } }
Markdown
UTF-8
1,110
3.703125
4
[ "MIT" ]
permissive
# wireframing The purpose of a wireframe is not so much to tell us how something will look, but to give an idea of: - what data will be present - how the data is grouped and prioritized So obviously the visual aspect is an important one (grouping and prioritizing is achieved visually) but we can still express a lot of this with text. ## Example If we wanted to describe a `Tweet` (subcomponent of a `TwitterTimeline`) we might start by listing the data we need to display: ``` - Author avatar - Author name - Author handle - Time - Body - Number of replies - Number of retweets - Number of likes ``` Next we might split into primary / secondary, to show which fields should be given visual prominance. The split between primary / secondary is dependent on use-case, and we might need to cater for a few of these at once. In this case let's say our user is browsing a timeline, so the "primary" fields should be those which help to scan for interest: ``` primary: - Author avatar - Author name - Body secondary: - Author handle - Time - Number of replies - Number of retweets - Number of likes ```
Markdown
UTF-8
2,799
2.671875
3
[]
no_license
**Item #:** SCP-3290 **Object Class:** Keter **Special Containment Procedures:** Foundation responses to different 3290-Events will depend on different circumstances. These include but are not limited to: 1. Local community standing of the individual affected 2. Global knowledge of the individual affected 3. Social media outreach and influence 4. Prior criminal charges and outcome of said charges 5. Level of involvement in scientific research 6. Believability of accounts given during 3290-Events Foundation personnel working in law enforcement or child-care who are able to identify 3290-Events are to bring it to the attention of Disinformation specialists. Research is to be conducted in order to better predict the location and spread of SCP-3290 beyond the current rate of prediction analytics (42%~). Persons in a position of authority who are likely to be next affected by SCP-3290 are to be monitored in the case of a 3290-Event. **Description:** SCP-3290 is a phenomenon involving a recurring dream that targets one individual at a time. Individuals affected by SCP-3290 experience nightmares in which they are attacked by leeches, mosquitoes, and other hematophagic[1](javascript:;) organisms, resulting in a loss of most of the body's moisture, and subsequent mummification of the individual experiencing the nightmare. Despite experiencing intense discomfort upon waking, individuals targeted by SCP-3290 do not have any physical symptoms related to massive blood loss experienced in the dream. Nightmares will occur during slow-wave sleep (SWS). The exact nature and length of nightmares vary, although barring being disrupted from SWS, nightmares typically last for a minimum of an hour. During the time an individual is asleep, 3290-Events occur. During a 3290-Event, the target's social media will be updated with posts describing crimes of one or more of the following in a fragmented, stream-of-consciousness manner: * Child pornography possession * Sexual assault of a minor * Stalking a minor * Murder of a minor * Use of minors in scientific research[2](javascript:;) The accuracy of these posts is estimated to be approximately 98%; furthermore, regardless of accuracy, all individuals questioned by law enforcement will admit to either committing a crime related to pedophilia or otherwise sexually fetishizing minors. While it has been impossible to pinpoint the person next affected, in most instances, SCP-3290 will select its next target from a previous target's social media contacts, allowing for semi-consistent tracking. It is theorized that individuals with no social media accounts will not be targeted or are otherwise undetectable to the Foundation. Footnotes [1](javascript:;). Blood-consuming. [2](javascript:;). \[DATA EXPUNGED\]
TypeScript
UTF-8
357
3.078125
3
[ "MIT" ]
permissive
function formatValue(value: number): string { return String(value).padStart(2, '0') } export default function convertTime(time: string): string { const [hour, minutes] = time.split(':').map(Number) const AMOrPM = hour >= 12 ? 'PM' : 'AM' const finalHour = hour % 12 || 12 return `${formatValue(finalHour)}:${formatValue(minutes)} ${AMOrPM}` }
Python
UTF-8
3,508
2.859375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Mon Aug 6 13:13:55 2018 @author: jinqiu """ import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import GridSearchCV from sklearn.model_selection import cross_val_score from sklearn import metrics from time import time from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.neighbors import KNeighborsClassifier from xgboost.sklearn import XGBClassifier from matplotlib import pyplot as plt #ๆ•ฐๆฎๅฏผๅ…ฅใ€ๆฃ€ๆŸฅ็ฉบ็ผบๅ€ผ data = pd.read_csv(r'C:/Users/jinqiu/Desktop/data.csv',encoding = "gbk") data.info() data.notnull().sum(axis=0)/data.shape[0] train = data.iloc[:,:-1] label = data.iloc[:,-1] #ๆ•ฐๆฎๆ ‡ๅ‡†ๅŒ– scaler = MinMaxScaler() train = scaler.fit(train).transform(train) #ๅฎšไน‰ๅˆ†็ฑปๅ™จ alg1=DecisionTreeClassifier(random_state=29) alg2=SVC(probability=True,random_state=29) #็”ฑไบŽไฝฟ็”จroc_auc_scoreไฝœไธบ่ฏ„ๅˆ†ๆ ‡ๅ‡†๏ผŒ้œ€ๅฐ†SVCไธญ็š„probabilityๅ‚ๆ•ฐ่ฎพ็ฝฎไธบTrue alg3=RandomForestClassifier(random_state=29) alg4=AdaBoostClassifier(random_state=29) alg5=KNeighborsClassifier(n_jobs=-1) alg6=XGBClassifier(random_state=29,n_jobs=-1) #ๅฎšไน‰่ฐƒๅ‚ๅ‡ฝๆ•ฐ def fit_model(alg,parameters): grid = GridSearchCV(alg,parameters,scoring='f1',cv=5) #ไฝฟ็”จ็ฝ‘ๆ ผๆœ็ดข๏ผŒๅ‡บๅ…ฅๅ‚ๆ•ฐ start=time() #่ฎกๆ—ถ grid=grid.fit(train,label) #ๆจกๅž‹่ฎญ็ปƒ end=time() t=round(end-start,3) print (grid.best_params_ ) #่พ“ๅ‡บๆœ€ไฝณๅ‚ๆ•ฐ print ('searching time for {} is {} s'.format(alg.__class__.__name__,t)) #่พ“ๅ‡บๆœ็ดขๆ—ถ้—ด return grid #่ฟ”ๅ›ž่ฎญ็ปƒๅฅฝ็š„ๆจกๅž‹ #ๅˆ—ๅ‡บ้œ€่ฆ่ฐƒๆ•ด็š„ๅ‚ๆ•ฐ่Œƒๅ›ด parameters1={'max_depth':range(1,10),'min_samples_split':range(2,10)} parameters2 = {"C":range(1,20), "gamma": [0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5]} parameters3_1 = {'n_estimators':range(10,200,10)} parameters3_2 = {'max_depth':range(1,10),'min_samples_split':range(2,10)} parameters4 = {'n_estimators':range(10,200,10),'learning_rate':[i/10.0 for i in range(5,15)]} parameters5 = {'n_neighbors':range(2,10),'leaf_size':range(10,80,20) } parameters6_1 = {'n_estimators':range(10,200,10)} parameters6_2 = {'max_depth':range(1,10),'min_child_weight':range(1,10)} parameters6_3 = {'subsample':[i/10.0 for i in range(1,10)], 'colsample_bytree':[i/10.0 for i in range(1,10)]} #ๅผ€ๅง‹่ฐƒๅ‚ clf1=fit_model(alg1,parameters1) clf2=fit_model(alg2,parameters2) clf3_m1=fit_model(alg3,parameters3_1) alg3=RandomForestClassifier(random_state=29,n_estimators=180) clf3=fit_model(alg3,parameters3_2) clf4=fit_model(alg4,parameters4) clf5=fit_model(alg5,parameters5) clf6_m1=fit_model(alg6,parameters6_1) alg6=XGBClassifier(n_estimators=140,random_state=29,n_jobs=-1) clf6_m2=fit_model(alg6,parameters6_2) alg6=XGBClassifier(n_estimators=140,max_depth=4,min_child_weight=5,random_state=29,n_jobs=-1) clf6=fit_model(alg6,parameters6_3) #ๅฎšไน‰ไบคๅ‰้ชŒ่ฏ def cross_val(clf,train,label): f1 = cross_val_score(clf, train, label, scoring='f1') return np.mean(f1)*100 #ๅˆๅง‹ๅŒ–็ป“ๆžœๅˆ—่กจ results = [] #ๅพช็Žฏๆ‰€ๆœ‰ๆจกๅž‹ models = [clf1,clf2,clf3,clf4,clf5,clf6] for i in models: f1 = cross_val(i,train,label) results.append(f1) name_list = ['DecisionTree','SVM','RandomForest','Adaboost','KNN','XGBOOST'] plt.barh(range(len(results)), results, color='rgb',tick_label=name_list) plt.show()
C++
UTF-8
1,603
3.21875
3
[]
no_license
#include <cstdio> #include <algorithm> #include <list> #include <vector> using namespace std; int N; int com; list<int> b; void show() { for (auto it=b.begin(); it!=b.end(); it++) printf("%d ", *it); printf("\n"); } int findDirection(list<int>::iterator& pos, const int target) { int direction = 1; for (auto it=b.begin(); it!=pos; it++) { if (*it == target) { direction = -1; pos--; break; } } return direction; } int main() { scanf (" %d", &N); vector<int> asc(N+1); for (int i=1; i<=N; i++) { scanf (" %d", &asc[i]); b.push_back(asc[i]); } sort(asc.begin(), asc.end()); int direction = 1; auto pos = b.begin(); auto it = pos; for (int i=1; i<=N; i++) { int target = asc[i]; // pos == begin์ด๋ฉด ์˜ค๋ฅธ์ชฝ // pos + 1 == end ์ด๋ฉด ์™ผ์ชฝ // list.size() 1์ด๋ฉด ์‚ญ์ œ๋งŒ ํ•œ๋‹ค. int c = 0; if (direction == 1) { for (it=pos; it!=b.end(); it++) { if (*it == target) { pos = b.erase(it); com += (c+1); //printf("r: com=%d, c=%d\n", com, c); //show(); direction = findDirection(pos, asc[i+1]); break; } c++; } } else if (direction == -1) { for (it=pos; it!=b.begin(); it--) { if (*it == target) { pos = b.erase(it); com += (c+1); //printf("l: com=%d, c=%d\n", com, c); //show(); direction = findDirection(pos, asc[i+1]); break; } c++; } if (it == b.begin()) { pos = b.erase(it); com += (c+1); //printf("begin: com=%d, c=%d\n", com, c); direction = findDirection(pos, asc[i+1]); } } } printf("%d\n", com); return 0; }
JavaScript
UTF-8
5,350
3
3
[ "MIT" ]
permissive
/** * MIT License * Copyright (c) 2020 JSXGraph * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ "use strict"; /** * * @param {String} elID ID of the HTML element containing JSXGraph * @param {Function} jsxCode JavaScript function containing the construction * @param {Boolean} debug Debug flag. If false the input elements of the formulas question are hidden. */ var JSXQuestion = function (elID, jsxCode, debug) { var that = this, topEl; /** * HTML element containing the board * * @type {String} */ this.elm = document.getElementById(elID); // Get the first ancestor of the board having class ".formulaspart" (should be a div) topEl = this.elm.closest('.formulaspart'); /** * Stores the input tags from the formulas question. * * @type {Array} */ //this.inputs = $(this.elm).closest(".formulaspart").find("input"); this.inputs = topEl.querySelectorAll('input'); // Hide the outcome div // Seems to be useless since the dot before formulaspartoutcome is missing. // $(this.elm).closest(".formulaspart").children("formulaspartoutcome").hide(); // Hide the input elements if (debug !== true) { // this.inputs.hide(); this.inputs.forEach(el => { el.style.display = 'none'; }); } /** * Indicator if the question has been solved. * * @type {Boolean} */ if (this.inputs && this.inputs[0]) { this.isSolved = this.inputs[0].readOnly; } else { this.isSolved = false; } this.solved = this.isSolved; /** * Fill input element of index idx of the formulas question with value. * * @param {Number} idx Index of the input element, starting at 0. * @param {Number} val Number to be set. */ this.set = function (idx, val) { if (!that.isSolved && that.inputs && that.inputs[idx]) { that.inputs[idx].value = Math.round(val * 100) / 100; } }; /** * Set values for all formulas inpout fields * * @param {Array} values Array containing the values to be set. * */ this.setAllValues = function (values) { var idx, len = values.length; for (idx = 0; idx < len; idx++) { if (!that.isSolved && that.inputs && that.inputs[idx]) { that.inputs[idx].value = Math.round(values[idx] * 100) / 100; } } }; /** * Get the content of input element of index idx of the formulas question. * * @param {Number} idx Index of the input form, starting at 0. */ this.get = function (idx) { if (that.inputs && that.inputs[idx]) { var n = parseFloat(that.inputs[idx].value); if (isNaN(n)) { return null; } return n; } return null; }; /** * Fetch all values from the formulas input fields * * @param {Number} number_of_fields Number of formulas input fields * @param {Number} default_value Default values if the fields are empty. * @returns {Array} Array of length number_of_fields containing the entries of the formulas * input fields. */ this.getAllValues = function(number_of_fields, default_value) { var idx, n, values = []; for (idx = 0; idx < number_of_fields; idx++) { n = that.get(idx); if (n === null) { n = default_value; } values.push(n); } return values; }; this.brd = null; this.board = null; // Execute the JSXGraph / JavaScript code jsxCode(this); /** * Reload the construction */ this.reload = function () { jsxCode(that); }; }; // Polyfill for element.closest: if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector; } if (!Element.prototype.closest) { Element.prototype.closest = function(s) { var el = this; do { if (Element.prototype.matches.call(el, s)) return el; el = el.parentElement || el.parentNode; } while (el !== null && el.nodeType === 1); return null; }; }
Python
UTF-8
2,417
3.3125
3
[]
no_license
from search import * from data import Data import time def solve(code: str, show_log: bool = False, print_func = print): print(f'##### {code} Problem #####') print() start_time = time.time() result = uniform_search(Data.problem(code), show_log=show_log) exec_time = time.time() - start_time print(f'Uniform Search Result: {exec_time}') print_func(result) print() start_time = time.time() result = iterative_lengthening_search(Data.problem(code), show_log=show_log) exec_time = time.time() - start_time print(f'Iterative Lengthening Search Result: {exec_time}') print_func(result) print() print('############## End ##############') print() def printBoard(actions) -> None: for row_iter in range(8): line = 'xxxxxxxx' y = actions[row_iter] - 1 line = line[0:y] + 'Q' + line[(y+1):] print(line) def printRGB(actions) -> None: if actions is None: print('No Solution') return from mainProblem.rgbexpress import Dir def arrow(dir: Dir) -> str: if dir == Dir.Stop: return '*' elif dir == Dir.Up: return 'โ†‘' elif dir == Dir.Down: return 'โ†“' elif dir == Dir.Left: return 'โ†' else: return 'โ†’' truck_dict = {} for action_iter in actions: for one_action in action_iter: index, dir, count = one_action if truck_dict.get(index) is None: truck_dict[index] = f"[Truck {index}] " truck_dict[index] += arrow(dir) + '.' * (max(count - 1, 0)) for truck_string in truck_dict.values(): print(truck_string) # exec problem solving show_log = True # solve('Route-Finding', show_log=show_log) # print() # solve('8-Queens', show_log=show_log, print_func=printBoard) # print() """ Main Test Problem: RGB-Express """ # Custom / A-4 / A-9 / B-10 / C-2 / G-8 / P-7 # rgb_testcase = 'Custom' # UCS: 0.004, ILS: 0.004 # rgb_testcase = 'A-4' # UCS: 0.010, ILS: 0.033 rgb_testcase = 'A-9' # UCS: 1.452, ILS: 1.534 # rgb_testcase = 'B-10' # UCS: 0.028, ILS: 0.102 # rgb_testcase = 'C-2' # UCS: 18.610, ILS: 5.367 # rgb_testcase = 'G-8' # UCS: 0.559, ILS: 1.726 # rgb_testcase = 'P-7' # UCS: 567.446, ILS: 45.627 solve(f'RGB-Express {rgb_testcase}', show_log=show_log, print_func=printRGB) print()
Java
UTF-8
614
2.125
2
[]
no_license
package pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; public class BBCSearchPage extends BasePage { @FindBy(xpath = "//p[@class='ssrcss-7sxcrr-PromoHeadline e1f5wbog4']//span") private List<WebElement> searchResultList; public BBCSearchPage(WebDriver driver) { super(driver); } public WebElement getSearchResult(int i) { return searchResultList.get(i); } public String getTextFromSearchResult(int i){ return searchResultList.get(i).getText(); } }
Markdown
UTF-8
2,764
3.1875
3
[]
no_license
#### **Pre-Classical History, and Greco-Roman History** <br return> This reading was very intriguing as it gauged the ideas of history and itsโ€™ existence before what we would consider the modern existence of historical thought and philosophy or rather, the speculative philosophy of history. Lemon makes some interesting insights into historical thought, and ideas in which I, nor many others would probably not have thought of because it is so engrained in us early on to accept History for what it is and the great thinkers of history and philosophy are who we turn to for the answers. <p/> <br return> In the first section of this reading, **_Pre-Classical Ideas on History,_** I found it quite interesting to think that with early philosophers and thinkers, they found ways to incorporate their religious beliefs into their view and explanations of history. Although this is not entirely surprising, given the conversation we had in class recently about the โ€˜agendaโ€™ history textbooks carry and how history is taught in schools, specifically in the United States; the same can be applied to how ancient civilizations viewed and understood the world they inhabited, and that is that they had an explanations for everything around them and their existence, and it was centered around their Christian beliefs. <p/> <br return> One aspect that really gauged my interest was the idea that we try and understand our world and history from the outside, meaning, we separate ourselves as beings from the universe as a whole rather than include ourselves in the equation or existence of it. <br return> In the second section of this readings, classical Greek and roman speculations on history, it was interesting to see how a shift in ideology of history and how humans viewed history from mythical to ideological. It was even more intriguing to read that Lemon suggested that some believe this shift in ideologies has something to do with civilizations shifting from living in rural areas to living in cities. <p/>This concept had me thinking about how we are taught about progress in history books. Progress is always marked by urbanization and expansion as well as the use of tools and science, yet, civilizations that did not have this were seen as lacking progress and savage-like. This is a completely different view of the earliest ancestors at the beginning of the reading and how they viewed their history. They were much more connected to the land and that their existence, history and progress was the peak of what they needed to achieve as a society simply because they existed. This is a far cry from what history teaches us now in that we look to the past to view progression and how as a society we can keep that progression moving forward.
JavaScript
UTF-8
560
3.015625
3
[]
no_license
// JS del menu desplegable const nav = document.querySelector('.header__nav') const burgerButton = document.querySelector('.header__burger') const burgerText = document.querySelector('.header__burger--text') burgerButton.addEventListener('click', hideShow) function hideShow() { if (nav.classList.contains('is_activate')) { nav.classList.remove('is_activate') setTimeout(() => { nav.classList.remove('hide') }, 500) } else { nav.classList.add('hide') setTimeout(()=>{ nav.classList.add('is_activate') },100) } }
Python
UTF-8
493
2.703125
3
[]
no_license
import abc class AbsPreprocessorFactory(metaclass=abc.ABCMeta): """the abstract class to inherit for creating the preprocessor in the factories folder""" @abc.abstractmethod def compute(self, data, columns): """The main body of the preprocessor. To be implemented in the child class Args: data: your dataset columns: list of columns affected Returns: returns the preprocessed dataset """ pass
Markdown
UTF-8
10,965
2.984375
3
[]
no_license
--- layout: layouts/post.njk title: > 252 FS Brent Weaver on Sales Process date: 2017-07-03 04:00:19 episode_number: 252 duration: 58:43 audio_url: https://devchat.cachefly.net/freelancers/FS_252_Brent_Weaver_on_Sales_Process.mp3 podcast: freelancers tags: - freelancers - podcast --- --- #### Brent Weaver on Sales Process On todays episode Phillip and Jonathan chat with Brent Weaver, founder and CEO of UGurus.com. Hear a bit about how Brent started UGurus to help people build their digital agency companies and to offer online courses as well as a bit about his ups and downs running his own digital agency company. Tune in to check it out! ##### How did UGuru get started? Brent talks about a company he ran before UGurus called Business Catalyst and how how he took that companies idea and expanded it to a wider audience of digital agency owners. This expanded version was the starting of UGurus. Brent had ran a digital agency for 12 years starting in high school. He talks about getting into making websites and made a website that had overhead in server costs and so he needed to find a way to cover those costs. He started telling people he could make websites, with his first being a \$500 job that took him a couple days. This job inspired him to quit his day job. He created a company with a friend and to their surprise the business made it for a long time. In 2005 they made the business their full time business. ##### As a passion driven skills based entrepreneur, did you ever dislike the sales part? Brent talks about how he likes working on cool projects with cool people, and it takes selling it to be a part of that. He looks back at his first big pitch, and despite being a natural born salesperson it didnโ€™t go so well. He adds that it was mainly due to a lack of experience as a sales person. He talks about how he didnโ€™t learn the client before getting there and that being a major factor. After being told they didnโ€™t get the job, they went out for drinks and discussed the business as a whole and its viability. It took years of experience to reflect what went wrong during the pitch. It wasnโ€™t until years later that he learned a better sales discovery process. Cold calling and talking about your product doesnโ€™t give the potential customer a chance to talk about their needs and to create a real connection with the salesperson. ##### What are the top things youโ€™d recommend for someone about to do a pitch? Brent talks about coming in with no expectations and being ready to ask questions. The best clients are clients you understands well and those clients often will connect with you in a way that you can continue to do work over time. Getting them to talk about themselves is key. Also, spend at least the same amount of time preparing as you do pitching, learning about who the client was. Learning about them and their industry informs the questions you ask them. Find what the essence of why they are looking for your work in the first place. If there are multiple people in the room, they may all have varying ideas on what the work should do and how itโ€™s important. Sometimes you will need to mediate their own conversation as well. Adding your experience to that facilitation can sometime highlight the reasons they need you and reinforce your value. Sometimes itโ€™s about not having the questions ahead of time and learning them while being there. As a salesperson, if you can get into a consulting range and help create a high value impact in their organization itโ€™s a good position to be in. Jonathan adds that many times when someone calls in a salesperson or consultant and starts to โ€˜brain-dumpโ€™ their issues, it in many cases is because they feel like they are in over their head. ##### โ€œNever Say โ€˜WordPressโ€™ When Selling a Web Design Project.โ€ Brent talks about writing a post called โ€œNever Say Wordpress When Selling a Web Design Projectโ€ and how many clients would self diagnose their situation. He would often have clients come to him and ask him to work on a project and for him to use Wordpress. He would help them dig in to find out if WordPress is actually what they need. Often times their issue isnโ€™t fully understood and many times their solution isnโ€™t actually fitting to the issue. This leaves a good opportunity to sell what services you offer that better fits the issue anyway. ##### What was your decision making process like when needing help or needing to pivot? Brent tells how they had a really nice office and the office was a bit more expensive than they could handle so eventually they reached a point where they had to borrow money to keep the lights on. A client of theirs offered to help them professionally to bring their business back to their feet. They went out to lunch and they doubled their revenue in the 12 months following the conversation and the advice. His advice was around focusing on what was important and what wasnโ€™t. Brent started tracking his time and found out that much of his time was spent on unbilled support and training and busy work. This drained his time as well as his energy. He hired someone else to handle the type of work that ate up his time. With his extra time and energy he repositioned himself in sales. He partner suggested that he โ€˜divide and conquerโ€™ by splitting up work into focused jobs, making his new job focused on sales. He also would bring in consultants when he met anyone who was smart in a field that was useful to the business. Simply asking โ€œwhat can I do better?โ€ He took on consultants for 5 years whenever he could. That process doubled his revenue in the course of a year and allowed him to sell the company with a successful exit. ##### Sales vs Persuasion Sales generally needs a level of persuasion, and it may sometimes look like manipulation, but if the client needs something, be it an item to service, itโ€™s a positive persuasion. He adds that you absolutely cannot make the โ€œSales Saladโ€ without the โ€œPersuasion Sauceโ€. Persuasion is part of non-sales consulting relationships as well. Jonathan adds that If someone pays you to coach them, itโ€™s your job to persuade them into action. Persuasion tends to have a negative connotation but sometimes it should just be seen as inspiring. If a client hires you to help them, they are looking for your expertise and your guidance. Brent talks about the sales person leading the process with confidence, starts with the first interaction. The sales meeting is a trial process, if they are hard to work with in the meeting you learn that they may be hard to work with over time. If you can hold a meeting and they follow the sales leading process you know that they can be a great client. If a client pushes you around during the sales process, expect them to push around when youโ€™re working on the project. ##### Confidence as a Salesperson r a Freelancer. Phillip ask Brent how he has built confidence and has reached a point where he feels strongly about his ability to get work and do the work. Brent says that itโ€™s important to know a process that works or at least be familiar. He talks about having a few processes he offers as courses. He sold it for a few years and would call those customers back to get feedback. For the people who finished it, many of them needed to tweak the course for it to work for them. Brent talks about how that always bothered and that his customers that bought the course didnโ€™t get the that level of confidence. So he decided to offer a video course and weekly calls, with the goals of having the customer getting their first \$10,000 in 12 weeks. In 2014 he launched their 10K bootcamp program to do just that. With the bootcamp, there was a 96% completion. He adds that the person to person interaction is very important. He also talks about having methods of accountability and some basic coaching about the personโ€™s core beliefs. Often people believe that their work is not worth the money, or that the work they are offering is a commodity that can be bought cheaply anywhere. He adds that those sort of beliefs tend to be on a personal level and take some personal coaching to get past. When you beliefs change, confidence is the result. ##### What do you recommend for attracting the right clients? Brent talks about how the way you generate leads is important to creating the right kind of pool of clients. Leads come from your own actions and depending on those actions is where your clients come from. Brent talks about once having a mix of good clients and bad clients and going through the whole pool to figure out where those leads came from. He found that there were certain things that he did that lead him to having good clients as well as certain things he did that generally led to clients without money. For example, picking up business from a new business incubator meeting generally leads to clients without money. To illustrate he gives an example of a business that makes $50,000 annual revenue. If that business follows the Small Business Administration guidelines, they will spent 8% to 9% annual revenue for marketing and so they will have roughly $3500 for a budget for the whole year. If that is your client, the economics are against you. Chances are that client will never give you a \$20,000 project, and if they do, they will be high maintenance and hard to work with. Brent gives a comparing example with one of the previous clients he worked with being a 150 million dollar a year company. Their concerns werenโ€™t focused on the budget, but the project itself. If you want those kind of clients, you have to ask yourself, โ€œWhere do these people hangout?โ€ You may not know the answer but asking and trying to figure it out will be a good way to start finding better clients. ##### โ€œCarrying your own Bag.โ€ Brent adds as a last piece of advice to find the people you you want emulate and create businesses like and reach out to them. Reaching out to those people and trying to create connections to those people can yield more responses than you expect and has been a vital part of his success. --- ##### Picks ###### Brent [\$200 course on sales for free](https://lp.ugurus.com/guest-podcasting-freelancers-show?utm_source=freelancers-show&utm_medium=podcasts&utm_campaign=guest-podcasting&utm_term=podcast-listener&utm_content=wdsk-call-promo) ###### Jonathan [Cashflow podcasting episode with Jonathan](https://cashflowpodcasting.com/cfp-028-ditch-hourly-billing-and-deliver-superior-service-with-jonathan-stark-part-1/)[Fighting Butterflies Article](https://expensiveproblem.com/fighting-butterflies) ###### Phillip [Dev Shop Marketing Briefings - Pia Silva interview](https://philipmorganconsulting.com/dev-shop-marketing-briefings/dsmb-pia-silva-on-increasing-profitability-through-service-redesign/) --- ##### Links [ugurus.com](https://ugurus.com/)[Email Brent](mailto:brent@ugurus.com) --- ### Transcript
Java
UTF-8
4,812
2.265625
2
[]
no_license
package com.interactive.classroom.dao.impl; import com.interactive.classroom.bean.HomeworkBean; import com.interactive.classroom.dao.DaoFactory; import com.interactive.classroom.dao.HomeworkDao; import com.interactive.classroom.dao.filters.FileFilter; import com.interactive.classroom.dao.filters.FilterFactory; import com.interactive.classroom.dao.filters.HomeworkFilter; import com.interactive.classroom.utils.DatabaseHelper; import com.interactive.classroom.utils.Log; import com.interactive.classroom.utils.TextUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.sql.ResultSet; import java.sql.SQLException; /** * @author Z-P-J */ public class HomeworkDaoImpl implements HomeworkDao { @Override public JSONObject queryHomeworks(HomeworkFilter filter) throws SQLException, JSONException { String sql = filter.getQuerySql(TABLE_NAME); Log.d(getClass().getName(), "findHomeworks sql=" + sql); String resultMsg = "ok"; int resultCode = 0; JSONArray jsonArray = new JSONArray(); try { ResultSet rs = DatabaseHelper.executeQuery(sql); while (rs.next()) { JSONObject jsonObj = new JSONObject(); for (String label : LABELS) { jsonObj.put(label, rs.getString(label)); } boolean isOwner = filter.getUserId() != null && filter.getUserId().equals(rs.getString("publisher_id")); jsonObj.put("isOwner", isOwner ? 1 : 0); if (!TextUtil.isEmpty(filter.getHomeworkId())) { FileFilter fileFilter = FilterFactory.getFileFilter() .setUserId(filter.getUserId()) .setUserType(filter.getUserType()) .setHomeworkId(filter.getHomeworkId()) .setOrder(filter.getOrder()); JSONObject jsonObject = DaoFactory.getFileDao().queryFiles(fileFilter); jsonObj.put("file_list", jsonObject.get("aaData")); } jsonArray.put(jsonObj); } rs.close(); } catch (SQLException sqlexception) { sqlexception.printStackTrace(); resultCode = 10; resultMsg = "ๆŸฅ่ฏขๆ•ฐๆฎๅบ“ๅ‡บ็Žฐ้”™่ฏฏ๏ผ" + sqlexception.getMessage(); } JSONObject jsonObj = new JSONObject(); jsonObj.put("aaData", jsonArray); DatabaseHelper.putTableColumnNames(LABELS, LABELS_CH, jsonObj); jsonObj.put("result_msg", resultMsg); jsonObj.put("result_code", resultCode); return jsonObj; } @Override public JSONObject updateHomeworkInfo(HomeworkBean homework) throws JSONException { String sql = "UPDATE " + TABLE_NAME + " set publisher_name=?,homework_title=?,homework_requirement=?,deadline=? where id=" + homework.getId(); boolean isSuccess = DatabaseHelper.executeUpdate( sql, homework.getPublisherName(), homework.getHomeworkTitle(), homework.getHomeworkRequirement(), homework.getDeadline()); JSONObject jsonObj = new JSONObject(); jsonObj.put("result_msg", isSuccess ? "ok" : "ๆ›ดๆ–ฐไฝœไธšไฟกๆฏๅคฑ่ดฅ๏ผ"); jsonObj.put("result_code", isSuccess ? 0 : 10); return jsonObj; } @Override public JSONObject publishHomework(HomeworkBean bean) throws JSONException { String resultMsg = "ok"; int resultCode = 0; String sql = "insert into " + TABLE_NAME + "(publisher_id,publisher_name,homework_title,homework_requirement,publish_time,deadline,course_id,file_name_format) values(" + bean.getPublisherId() + ",'" + bean.getPublisherName() + "','" + bean.getHomeworkTitle() + "','" + bean.getHomeworkRequirement() + "','" + bean.getPublishTime() + "','" + bean.getDeadline() + "'," + bean.getCourseId() + ",'" + bean.getFileNameFormat() + "')"; Log.d(getClass().getName(), "publishAttendance sql=" + sql); DatabaseHelper.executeUpdate(sql); JSONObject jsonObj = new JSONObject(); jsonObj.put("result_msg", resultMsg); jsonObj.put("result_code", resultCode); return jsonObj; } @Override public JSONObject deleteHomework(String[] ids) throws JSONException { for (String id : ids) { String sql = "delete from " + TABLE_NAME + " where id=" + id; DatabaseHelper.executeUpdate(sql); } JSONObject jsonObj = new JSONObject(); jsonObj.put("result_msg", "ok"); jsonObj.put("result_code", 0); return jsonObj; } }
Markdown
UTF-8
1,922
2.84375
3
[]
no_license
--- title: "Using StyleCop to boost my code reviews" date: "2020-10-01" categories: - "coding-practices" - "processes" --- ## What is StyleCop? StyleCop analyses C# source code to help enforce a set of style and consistency rules. This analysis helps teams to develop in a much more consistent way and improves the readability of the code base. ## Setting it up - Copy the .editorconfig and stylecop.json files into the root of your solution - Add the .editorconfig and stylecop.json files as Solution Items in Visual Studio - Add the StyleCop.Analyzers NuGet package to all of the projects you want StyleCop to analyse - Link to the stylecop.json file in all of the projects you want StyleCop to analyse - Change the 'Build Action' property in the properties window to be set to 'C# analyzer additional file' for the stylecop.json files - Edit the project file to set 'TreatWarningsAsErrors' to true. This is optional but it makes it clearer when the StyleCop rules are being violated ## Using StyleCop If all of the above steps have been completed then the StyleCop analysers will run the next time the solution is built. When the 'TreatWarningsAsErrors' flag within your project file is set to true and the analysis fails then you will get a build failure. If the flag is set to false then you will be able to see the failures within the Warnings tab of the Errors window. ## My Rulesets I have added the .editorconfig and stylecop.json files that I currently use below as there are some rules I don't 100% agree. There are also some rules that I don't agree with enough to force this onto anyone who has written their code that way. [https://www.seanstride.co.uk/wp-content/uploads/2020/11/StyleCop.zip](https://www.seanstride.co.uk/wp-content/uploads/2020/11/StyleCop.zip) If you would like to discuss my rulesets, or believe there are rules I have missed then please let me know in the comments below.
Python
UTF-8
173
2.703125
3
[]
no_license
#!/usr/bin/env python import sys for line in sys.stdin: (userID, movieID, rating, timestamp) = line.split('\t') print ('%s\tB\t%s\t%s' % (movieID, userID, rating))
Python
UTF-8
2,522
2.828125
3
[]
no_license
import socket import threading import datetime import os import sqlite3 as sql HOST_SOC = "0.0.0.0" SOC_PORT = 8090 def add_data(conn, data): """ Create a new project into the projects table :param conn: :param project: :return: project id """ sql = ''' INSERT INTO moisture(time,moisture) VALUES(?,?) ''' cur = conn.cursor() cur.execute(sql, data) return cur.lastrowid def socket_server(db_connection): sep = '\n' while(True): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST_SOC, SOC_PORT)) s.listen() conn, addr = s.accept() with conn: print('Connected by', addr) while True: ts = datetime.datetime.now() ts = str(ts) data = conn.recv(8) num = int (data.decode("utf-8")) print(num) if ( num < 900 ): add_data(db_connection, (ts, num)) db_connection.commit() if not data: s.close() s.bind((HOST_SOC, SOC_PORT)) s.listen() conn, addr = s.accept() def database_init(db_file): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sql.connect(db_file) except sql.Error as e: print(e) return conn def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) if __name__ == '__main__': print(os.getcwd()) conn = database_init("/home/callum/Dev/plantproj/moisture.db") sql_create_moisture_table = """ CREATE TABLE IF NOT EXISTS moisture ( id integer PRIMARY KEY AUTOINCREMENT, time text, moisture int ); """ with conn: create_table(conn, sql_create_moisture_table) socket_server(conn)
JavaScript
UTF-8
522
3
3
[]
no_license
function processCommands(cmd) { var res = ""; if(cmd === "date") { res = (new Date()); return res; } if(cmd === "time") { res = (new Date()); return res; } if(cmd === "history") { for(var i = 0; i < cmd_hist.length; i++) { res += i+1 + "&nbsp;"; res += cmd_hist[i]; res += "<br>" } return res; } if(cmd == "exit") { window.history.back(); } //if that command is present it would have been captured by earlier if statements res = cmd+": command not found"; return res; }
Java
UTF-8
203
1.515625
2
[]
no_license
package com.loan.common.dao; import com.loan.common.model.UserBorrow; import org.springframework.stereotype.Repository; @Repository public interface UserBorrowDao extends BaseDao<UserBorrow, Long> { }
PHP
UTF-8
678
3.296875
3
[]
no_license
<?php class UnitOfMeasure { private $id; private $abreviation; private $fullName; function __construct() { $this->id = 0; $this->abreviation = ""; $this->fullName = ""; } public function getId() { return $this->id; } public function setId($data) { $this->id = $data; } public function getAbreviation() { return $this->abreviation; } public function setAbreviation($data) { $this->abreviation = $data; } public function getFullName() { return $this->fullName; } public function setFullName($data) { $this->fullName = $data; } } ?>
Java
UTF-8
2,827
3.21875
3
[]
no_license
package com.spookengine.core.events; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; /** * * @author Oliver Winks */ public final class EventHandler implements Cloneable { private static Map<String, EventHandler> instances = new HashMap<String, EventHandler>(); private Map<String, Queue<Object>> events; private Map<String, List<Action>> actions; public EventHandler() { events = new HashMap<String, Queue<Object>>(); actions = new HashMap<String, List<Action>>(); } public static EventHandler getInstance(String name) { EventHandler eventHandler = instances.get(name); if(eventHandler == null) instances.put(name, eventHandler = new EventHandler()); return eventHandler; } /** * * @param eventType * @param action */ public void listen(String eventType, Action action) { if(!actions.containsKey(eventType)) { actions.put(eventType, new ArrayList<Action>()); } actions.get(eventType).add(action); } /** * * @param eventType * @param action */ public void ignore(String eventType, Action action) { if(actions.containsKey(eventType)) { actions.get(eventType).remove(action); } } public void ignoreAll() { actions.clear(); } /** * Stores the event object in the events buffer, this event is then posted * to all actions listening for events of this type. * * @param eventType This is a developer defined type, it's simply a string * which characterises the event (for example 'touch', 'collision' etc) * @param event The object containing data about the particular event (for * example MotionEvent, KeyEvent etc). */ public void postEvent(String eventType, Object event) { if(!events.containsKey(eventType)) { events.put(eventType, new ConcurrentLinkedQueue<Object>()); } if(event != null) events.get(eventType).add(event); } /** * */ public void update() { // iterate through events for(String eventType : events.keySet()) { if(!events.get(eventType).isEmpty() && actions.containsKey(eventType)) { // perform actions that are listening for these events for(Action action : actions.get(eventType)) action.perform(events.get(eventType)); } // consume all events events.get(eventType).clear(); } } @Override public Object clone() { throw new UnsupportedOperationException("EventHandler is a singleton"); } }
TypeScript
UTF-8
1,611
2.59375
3
[ "MIT" ]
permissive
'use strict'; import * as vscode from 'vscode'; import * as path from 'path'; import * as fs from 'fs'; import { GitCommand } from './GitCommand'; import { getCurrentWorkspaceFolder } from './getFolder'; export class GitPath { gitCommand: GitCommand; gitPath: string | undefined; gitExcludePath: string | undefined; constructor(gitCommand) { this.gitCommand = gitCommand; this.gitPath = this.getGitPath(); this.gitExcludePath = this.getGitExcludePath(); } private getGitExcludePath(): string | undefined { if (!this.gitPath) return undefined; return path.join(this.gitPath, "info", "exclude"); } private getGitPath(): string | undefined { var gitPath = this.gitCommand.runCommand("git rev-parse --git-dir"); if (!gitPath) return undefined; var wf = getCurrentWorkspaceFolder(); return path.resolve(wf, gitPath).trim(); } public prepareGitExclude(): string | null { if (!fs.existsSync(this.gitPath)) { vscode.window.showInformationMessage("Not git repository."); return null; } let exclude = this.gitExcludePath; let gitInfoDir = path.dirname(exclude); // infoใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใ€็„กใ‘ใ‚Œใฐไฝœๆˆ if (!fs.existsSync(gitInfoDir)) fs.mkdirSync(gitInfoDir); if (!fs.existsSync(exclude)) { fs.writeFileSync(exclude, "", 'utf-8'); vscode.window.showInformationMessage("Create new Exclude file."); } return exclude; } }
PHP
UTF-8
2,896
2.734375
3
[]
no_license
<?php namespace TwoDotsTwice\CVWarehouse\XML; use Carbon\Carbon; use DateTimeImmutable; use DateTimeZone; use SimpleXMLElement; use TwoDotsTwice\CVWarehouse\Job; use TwoDotsTwice\CVWarehouse\Job\Description; use TwoDotsTwice\CVWarehouse\Job\Id; use TwoDotsTwice\CVWarehouse\Job\Name; use TwoDotsTwice\CVWarehouse\Job\Url; use TwoDotsTwice\CVWarehouse\Job\Urls; use TwoDotsTwice\CVWarehouse\JobCollection; use Webmozart\Assert\Assert; class Version110Parser implements Parser { const NS = 'http://www.cvwarehouse.com/schemas/cvwarehouse-job-1-10'; public function format() { return new Format('XML', '1.10'); } public function parse($xml) { Assert::string($xml); // The XML sometimes is not well-formed. Replace some things here we // know that are wrong. $replacements = [ '&ltlt;' => 'โ‰ช', ]; $xml = str_replace( array_keys($replacements), array_values($replacements), $xml ); $dom = simplexml_load_string($xml, SimpleXMLElement::class, 0, self::NS); $jobs = []; foreach ($dom->job as $jobElement) { $id = new Id((string) $jobElement->attributes()->id); $name = new Name(trim((string) $jobElement->name)); $description = new Description((string) $jobElement->description); $applicationUrlBranded = new Url($jobElement->urls->applicationUrlBranded); $urls = new Urls($applicationUrlBranded); $job = new Job($id, $name, $description, $urls); if (isset($jobElement->expirationDate) && !isset($jobElement->options->spontaneousApp)) { $expirationDate = $this->parseExpirationDate((string)$jobElement->expirationDate); if ($expirationDate) { $job = $job->withExpirationDate($expirationDate); } } $jobs[] = $job; } return new JobCollection(...$jobs); } /** * Currently the expiration date uses a non-standard based format. * * e.g. 2017-02-15 12:00:00 which actually means 2017-02-15T00:00 * * @param string $dateAsString * * @return null|DateTimeImmutable */ private function parseExpirationDate($dateAsString) { $match = preg_match('@^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})\s@', (string) $dateAsString, $matches); if (!$match) { return null; } $correctedDateAsString = "{$matches['year']}-{$matches['month']}-{$matches['day']} 12:00:00"; $date = Carbon::createFromFormat( 'Y-m-d G:i:s', $correctedDateAsString, new DateTimeZone('Europe/Brussels') ); $date->subDay(1)->endOfDay(); return DateTimeImmutable::createFromMutable($date); } }
Java
UTF-8
3,265
3.359375
3
[]
no_license
import java.awt.Color; import edu.cmu.ri.createlab.terk.robot.finch.Finch; import javax.swing.JOptionPane; import javax.swing.JFrame; public class A2 { // Task 6: Dance static String hex = "", dec = "", bin = ""; static int r, g , b, spdVal; public static void run (String userInput) { hex = userInput; decimal(); binary(); finchCol(); speed(); } public static void main(String[] args) throws InterruptedException { A2_UI ui = new A2_UI(); ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ui.setSize(340,210); ui.setVisible(true); ui.setResizable(false); } public static void decimal() { // Converting hexadecimal to decimal int result = 0; for (int i = 0; i<hex.length() ;i++) { // Checks each digit and converts to decimal equivalent int j = hex.length() - i - 1; // The left digit is 16^1 switch(hex.substring(i, i+1)) { case "1" : result += 1*(Math.pow(16, j)); break; case "2" : result += 2*(Math.pow(16, j)); break; case "3" : result += 3*(Math.pow(16, j)); break; case "4" : result += 4*(Math.pow(16, j)); break; case "5" : result += 5*(Math.pow(16, j)); break; case "6" : result += 6*(Math.pow(16, j)); break; case "7" : result += 7*(Math.pow(16, j)); break; case "8" : result += 8*(Math.pow(16, j)); break; case "9" : result += 9*(Math.pow(16, j)); break; case "A" : result += 10*(Math.pow(16, j)); break; case "B" : result += 11*(Math.pow(16, j)); break; case "C" : result += 12*(Math.pow(16, j)); break; case "D" : result += 13*(Math.pow(16, j)); break; case "E" : result += 14*(Math.pow(16, j)); break; case "F" : result += 15*(Math.pow(16, j)); break; } } dec = Integer.toString(result); } public static void binary() { //Converting decimal to binary using division by 2 with remainder method int number = Integer.parseInt(dec); String x = ""; String remainder = ""; while (number>0) { if(number%2==0) {remainder +="0";} else {remainder +="1";} number = (number - (number%2))/2; } x = strReverse(remainder); bin = x; } static public String strReverse(String y) { //converts the string to an array of characters char[] charOutput = y.toCharArray(); String stringOutput = new String(); for (int i = y.length()-1; i>=0; i--) { stringOutput += (charOutput[i]); } return stringOutput; //returns the array of characters as a string in reverse order } static public void finchCol() { r = Integer.parseInt(dec); g = (Integer.parseInt(dec)%80) + 60; b = (r+g)/2; } static public void speed() { spdVal = Integer.parseInt(dec); // Converting String to integer if (spdVal<80) {spdVal+=30;} // Speed of Finch is equal to Decimal (if below 80, Decimal+30) } public static void danceFabulously() { Finch Jim = new Finch(); Jim.setLED(r,g,b); for (int i=0; i<bin.length(); i++) { String p = bin.substring(i, i+1); int q = Integer.parseInt(p); if (q == 1){ // 1 = Forwards (for 2 seconds) Jim.setWheelVelocities(spdVal,spdVal,2000); } else if (q==0) { //0 = Backwards (for 2 seconds) Jim.setWheelVelocities(-spdVal,-spdVal,2000); } } Jim.quit(); } }
PHP
UTF-8
937
2.890625
3
[]
no_license
<?php require_once '../../dao/DaoEvento.class.php'; require_once '../../modelo/Evento.class.php'; class ControleEvento { private $controle; function __construct() { $this->controle = new DaoEvento(); } function inserir(Evento $evento) { return $this->controle->inserir($evento); } function atualizar(Evento $evento) { return $this->controle->atualizar($evento); } function remover(Evento $evento) { return $this->controle->remover($evento); } function obterTodos() { $sql = "SELECT * FROM Evento "; return $this->controle->obterTodosByParametro($sql); } function obterById($id) { $sql = 'SELECT * FROM Evento WHERE id=:id'; return $this->controle->obter($sql, ':id', $id, PDO::PARAM_INT); } }
Ruby
UTF-8
1,435
3.28125
3
[ "MIT" ]
permissive
module Algorithms module Sorting module BottomUpMergeSort def sort(a) sort!(a.clone) end def sort!(a) return a if a.size <= 1 comparison_size = 1 until comparison_size >= a.size low_start = 0 high_start = low_start + comparison_size until high_start >= a.size low_end = low_start + comparison_size.pred high_end = min((high_start + comparison_size.pred), a.size.pred) merge(a, low_start, low_end, high_start, high_end) low_start = high_end.succ high_start = low_start + comparison_size end comparison_size *= 2 end a end private def min(a, b) a <= b ? a : b end def merge(a, low_start, low_end, high_start, high_end) tmp = a.clone low_i, high_i = low_start, high_start past_low_end = -> { low_i > low_end } past_high_end = -> { high_i > high_end } higher_is_smaller = -> { tmp[high_i] < tmp[low_i] } (low_start..high_end).each do |i| break if past_low_end.call && past_high_end.call if past_low_end.call || (!past_high_end.call && higher_is_smaller.call) a[i] = tmp[high_i] high_i += 1 else a[i] = tmp[low_i] low_i += 1 end end end end end end
Markdown
UTF-8
1,231
2.765625
3
[ "MIT" ]
permissive
# query-stream <img src=https://secure.travis-ci.org/'Dominic Tarr'/query-stream.png?branch=master> create autosuggest widgets with a async function. create a query stream: ``` js var query = require('query-stream') var qs = query(function (query, cb) { //make request to make_query_to_wherever(query, cb) }) ``` then, write queries to it: ``` js qs.write('samestuth') //if you change your query it retries the search qs.write('some stuff') ``` output chunks will look like this: ``` js //assuming get(q, cb) calls back a string "samestuff not found", "CLEAR", //this means new results "stuff1", "stuff2", etc.. ``` `"CLEAR"` is a special message. it means that the following is a new response, and the display should clear previous elements. # UI Pipe a input field into this, and out to a list. NOTE, this stuff isn't implemented yet! But it will look something like this: ``` js //input-stream creates a stream of DOM events. inputStream('#query', 'onchange', function (e) { return e.value }).pipe(qs) //element stream adds elements to a given root Element. .pipe(elementStream('#results', function (e) { if(e === 'CLEAR') return this.root.removeAllChildren() return '<li>'+e+'</li>' }) ## License MIT
Markdown
UTF-8
2,564
2.59375
3
[]
no_license
# Rangle Elm-Workshop ### Prerequisites Before attending the workshop, please clone this repo, install the elm platform, elm-format, and integrate these with your editor of choice. This will help us jump right in! ### Install platform and elm-format **NOTE** There can be some _weirdness_ installing elm with yarn/npm and integrating with you editor if you use npm + nvm + VSCode due to some path stuff. Your best bet is to install the binaries to /usr/local/bin instead, and make sure that's on your path ( if you can run elm / elm-format from the command line, you're good!) If that fails, try the accepted method of `npm install -g elm elm-format` - [Elm 0.19 installer for Mac](https://github.com/elm/compiler/releases/download/0.19.0/installer-for-mac.pkg) - [elm-format binary for Mac](https://github.com/avh4/elm-format/releases/download/0.8.1/elm-format-0.8.1-mac-x64.tgz) ### Integrate with VS Code - Install the Elm language support from the marketplace. - [ Then follow this](https://github.com/avh4/elm-format/tree/0.8.1#visual-studio-code-installation) ### Integrate with Atom - Install language-elm package - Install elm-format package - Install elmjutsu for autocomplete (do not follow the default instructions for language-elm, won't work for 0.19) ### Integrate with other editors `:grimace:` I have no idea :P. Mostly it's important to get elm-make running automatically on save to see compile errors in your editor in real-time, and to have elm-format run to make your code look nice ## Resources - Elm has [an official guide](https://guide.elm-lang.org/) that goes through many topics in this workshop and more. It is a highly recommended read! - https://elm.reddit.com is very active and beginner friendly! - https://elmlang.herokuapp.com/ Elm slack is much the same ## Workshops Links ### Part 1 - Syntax - [Official Elm Syntax Documentation](http://elm-lang.org/docs/syntax) - [Elm vs JS quick comparison](http://elm-lang.org/docs/from-javascript) ### Part 2 & 3 - Rendering HTML + CSS - [elm/html package](http://package.elm-lang.org/packages/elm/html/latest/) - [elm tachyons](https://package.elm-lang.org/packages/justgage/tachyons-elm/latest/) - [elm-style-elements](http://package.elm-lang.org/packages/mdgriffith/style-elements/latest) - [elm-css](https://github.com/rtfeldman/elm-css) - [elm-live dev server](https://github.com/tomekwi/elm-live) - [Tachyons!](http://tachyons.io/) ### Part 4 & 5 - See [elm-guide]((https://guide.elm-lang.org/) and (official elm documentation)[http://elm-lang.org/docs]
JavaScript
UTF-8
1,447
2.65625
3
[]
no_license
const fs= require('fs'); const N3 = require('n3'); const trig_parser = new N3.Parser({ format: 'application/trig' }); const nquads_store = new N3.Store(); var data = fs.readFileSync('./data/test.json.trig', 'utf8'); var quads = trig_parser.parse(data); nquads_store.addQuads(quads); var graphs = nquads_store.getGraphs(); console.log('graphs: ', graphs) var json = []; nquads_store.forGraphs( graph => { var json_graph = { name: graph.id, subjects: [] }; //var triples = store.getQuads(null, null, null, graph); //console.log('triples: ', triples) console.log('GRAPH: ', graph.id); // nquads_store.forSubjects(subject => { var json_subject = { name: subject.id, properties: [] }; console.log('SUBJECT: ', subject.id); nquads_store.forPredicates( predicate => { console.log('PREDICATE: ', predicate.id); nquads_store.forObjects(object => { console.log('object: ',object); json_subject.properties.push({ predicate: predicate.id, object: object.id }) }, subject, predicate, graph); }, subject, null, graph); json_graph.subjects.push(json_subject); }, null, null, graph); json.push(json_graph); }); console.log(JSON.stringify(json));
Java
UTF-8
238
1.554688
2
[]
no_license
package br.com.stark.starkfinanceiro.repository; import org.springframework.data.jpa.repository.JpaRepository; import br.com.stark.starkfinanceiro.model.Pessoa; public interface PessoaRepository extends JpaRepository<Pessoa, Long>{ }
PHP
UTF-8
1,148
2.546875
3
[ "MIT" ]
permissive
<?php /* * 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. */ if (!function_exists('dateIsValid')) { function dateIsValid($str) { if ($str == "") { return false; } $array = explode('/', $str); if (count($array) < 3) { return false; } $day = $array[0]; $month = $array[1]; $year = $array[2]; $isDateValid = checkdate($month, $day, $year); return $isDateValid; } } if(!function_exists('responseJson')){ function responseJson($code, $message = null, $data = array()){ return response()->json([ 'code' => $code, 'message' => $message, 'data' => $data ]); } } if(!function_exists('responseJsonError')){ function responseJsonError($code){ $message = trans('error_message.'.$code); return response()->json([ 'code' => $code, 'message' => $message, 'data' => null ]); } }
JavaScript
UTF-8
1,585
2.828125
3
[]
no_license
let quotes=[]; const colorArray = ['#FF6633', '#FFB399', '#FF33FF', '#FFFF99', '#00B3E6', '#E6B333', '#3366E6', '#999966', '#99FF99', '#B34D4D', '#80B300', '#809900', '#E6B3B3', '#6680B3', '#66991A', '#FF99E6', '#CCFF1A', '#FF1A66', '#E6331A', '#33FFCC', '#66994D', '#B366CC', '#4D8000', '#B33300', '#CC80CC', '#66664D', '#991AFF', '#E666FF', '#4DB3FF', '#1AB399', '#E666B3', '#33991A', '#CC9999', '#B3B31A', '#00E680', '#4D8066', '#809980', '#E6FF80', '#1AFF33', '#999933', '#FF3380', '#CCCC00', '#66E64D', '#4D80CC', '#9900B3', '#E64D66', '#4DB380', '#FF4D4D', '#99E6E6', '#6666FF']; const getQuotes = () => { return fetch("https://type.fit/api/quotes") .then(response => response.json()) .then(data =>{ quotes=data; change(); }) } const change = () =>{ const count=quotes.length; let randomNumber = parseInt(Math.random()*count); document.querySelector("#quotesText").innerText=quotes[randomNumber].text; document.querySelector("#quotesAuthor").innerText="-"+quotes[randomNumber].author; let randomCalor=parseInt(Math.random()*50); document.body.style.backgroundColor=colorArray[randomCalor]; } const shareTwitter= () => { let text = document.querySelector("#quotesText").innerText; window.location.href="https://twitter.com/intent/tweet?hashtags=randomQuotesApp&text="+encodeURIComponent('"'+text+'"'); } getQuotes(); document.querySelector("#changeBtn").addEventListener("click",change); document.querySelector("#twitterBtn").addEventListener("click",shareTwitter);