language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
1,730
3.65625
4
[]
no_license
/* # Boyer_Moore법을 이용하여 문자열에서 문자열을 검색하고 몇번째에 있었는지 표시하기 */ #include<stdio.h> #include<string.h> #include<limits.h> int boyer_moore_scan(char* str, char* letter) { int str_p = 1; //문자열을 검사할 포인터 int let_p = 0; //패턴을 검사할 포인터 int str_len = strlen(str); int let_len = strlen(letter); int skip_p[UCHAR_MAX+1]; //몇번째 문자부터 다시 검색할 지 skip판단 //skip판단 index검사 for (str_p = 0; str_p <= UCHAR_MAX; str_p++) skip_p[str_p] = let_len; for (str_p = 0; str_p < let_len - 1; str_p++) skip_p[letter[str_p]] = let_len - str_p - 1; //문자열 스캔 int jump_str; while (str_p < str_len) { let_p = let_len - 1; while (str[str_p] == letter[let_p]) { if (let_p == 0) return str_p; let_p--; str_p--; } if (skip_p[str[str_p]] > let_len - let_p) { str_p += skip_p[str[str_p]]; } else { str_p += let_len - let_p; } } return -1; } void str_search(char* str, char* letter) { int index; if ((index = boyer_moore_scan(str, letter)) != -1) { printf("[%s]에서 [%s] 검색 성공, 위치 %d\n", str, letter, index + 1); } else { printf("[%s]에서 [%s] 검색 실패\n", str, letter); } } int main() { char* str = "For every dreamer, a dream were unstoppable"; str_search(str, "unstoppable"); str_search(str, "every dreamer"); str_search(str, "dream"); str_search(str, "waiting for love"); //한글 char* str2 = "별빛이 내려오지 마구 내려오지 경고"; str_search(str2, "별빛"); str_search(str2, "저 괴물체는 뭘까"); str_search(str2, "마구 내려오지"); str_search(str2, "내려오지 경고"); return 0; }
Java
UTF-8
2,707
1.859375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2012-2014 eBay Software Foundation and selendroid committers. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.selendroid.standalone.server; import io.selendroid.server.common.BaseRequestHandler; import io.selendroid.server.common.BaseServlet; import io.selendroid.server.common.Response; import io.selendroid.server.common.http.HttpRequest; import io.selendroid.standalone.server.model.ActiveSession; import io.selendroid.standalone.server.model.SelendroidStandaloneDriver; import org.json.JSONException; import org.json.JSONObject; import java.util.logging.Level; import java.util.logging.Logger; public abstract class BaseSelendroidStandaloneHandler extends BaseRequestHandler { private final Logger log = Logger.getLogger(this.getClass().getName()); public BaseSelendroidStandaloneHandler(String mappedUri) { super(mappedUri); } /** * Implement this in subclasses to handle the request. Don't override {@link #handle(HttpRequest)} directly. */ protected abstract Response handleRequest(HttpRequest request, JSONObject payload) throws JSONException; @Override public Response handle(HttpRequest request) throws JSONException { JSONObject payload = getPayload(request); logHandlerCalled(payload); return handleRequest(request, payload); } protected SelendroidStandaloneDriver getSelendroidDriver(HttpRequest request) { return (SelendroidStandaloneDriver) request.data().get(BaseServlet.DRIVER_KEY); } protected ActiveSession getActiveSession(HttpRequest request) { SelendroidStandaloneDriver driver = getSelendroidDriver(request); if (driver == null) { log.warning("Cannot get session, no selendroid driver."); return null; } return driver.getActiveSession(getSessionId(request)); } private void logHandlerCalled(JSONObject payload) { String message = "Selendroid standalone handler: " + this.getClass().getSimpleName(); if (payload != null) { try { message += ", payload:\n" + payload.toString(2); } catch (JSONException e) { log.log(Level.WARNING, "Cannot debug-print request payload", e); } } log.log(Level.FINE, message); } }
JavaScript
UTF-8
348
3.1875
3
[]
no_license
const propiedades = new Set(); propiedades.add("color"); propiedades.add("tamano"); propiedades.add("peso"); propiedades.add("forma"); console.log(propiedades); propiedades.add("color"); console.log(propiedades); const iterador = propiedades.entries(); console.log(iterador.next().value); for(let item of iterador){ console.log(item); }
C++
UTF-8
3,755
3.234375
3
[]
no_license
/* * parser.h * * Created on: Mar 21, 2020 * Author: Jpost */ #include <string> #include <unordered_map> using namespace std; vector<vector<string>> HRML_attr_parser(string tag, string line){ //inputs: tag name and line of source code e.g., <tag1 value = "HelloWorld"> //outputs: vector of two vectors: 1 for attribute names and 1 for attribute values /* [ [attr_name1, attr_name2, ...], [attr_val1, attr_val2, ...] ] */ vector<string> attr_names; vector<string> attr_values; // <tag1 value = "HelloWorld"> unsigned int tag_front = line.find_first_not_of(" ", 1 + tag.length()); unsigned int tag_back = line.find_first_of(" ", tag_front); //next non-space character // cout << "tag_front = " << tag_front << " and tag_back = " << tag_back << endl; while (tag_front < line.length() - 1 ){ //subtract one from length() to ignore ">" character string temp_name(""); string temp_val(""); for(unsigned int i = tag_front; i < tag_back; i++){ temp_name.push_back(line[i]); } tag_front = line.find_first_of("\"", tag_back); // tag_back = line.find_first_of("\"", tag_front + 1); for(unsigned int i = tag_front + 1; i < tag_back; i++){ temp_val.push_back(line[i]); } tag_front = line.find_first_not_of(" ", tag_back + 1); //next non-space character tag_back = line.find_first_of(" ", tag_front); //next non-space character // now push back newly found attribute name and corresponding value into vectors attr_names.push_back(temp_name); attr_values.push_back(temp_val); } vector<vector<string>> attrs; attrs.push_back(attr_names); attrs.push_back(attr_values); return attrs; } bool tagEnd(string line){ //returns true if '/' in src code line string delimiter ("/"); return (line.find(delimiter) != string::npos); } string HRML_tag_parser(string line){ string tag; // all tags are <tag1 adfads...> or </tag1> unsigned int tag_back = line.find_first_of(" "); unsigned int end_tag = line.find_first_of(">"); if (!tagEnd(line)){ if (tag_back < end_tag){ for (unsigned int i = 1; i < tag_back; i++){ tag.push_back(line[i]); } } else { for (unsigned int i = 1; i < end_tag; i++){ tag.push_back(line[i]); } } } else { for (unsigned int i = 2; i < line.find(">"); i++){ tag.push_back(line[i]); } } return tag; } vector<string> queryTagParser(string query){ //query = tag1.tag2~name vector<string> query_tags; string temp_tag; unsigned int tag_front = 0; //first non-space character i.e., tag name unsigned int tag_back = query.find_first_of(".", tag_front); //next period character unsigned int end_tag = query.find_first_of("~"); //next tilda character while (tag_back < end_tag) { temp_tag = ""; for (unsigned int i = tag_front; i < tag_back; i++) { temp_tag.push_back(query[i]); } query_tags.push_back(temp_tag); tag_front = tag_back + 1; // tag_back = query.find_first_of(".", tag_front); // } //grab last possible tag in query temp_tag = ""; for (unsigned int i = tag_front; i < end_tag; i++) { temp_tag.push_back(query[i]); } query_tags.push_back(temp_tag); return query_tags; } string queryAttrParser(string query){ string attribute; unsigned int start_attr = query.find_first_of("~"); //next tilda character for (unsigned int i = start_attr+1; i < query.length(); i++) { attribute.push_back(query[i]); } return attribute; }
C++
UTF-8
1,162
3.546875
4
[]
no_license
#include<bits/stdc++.h> using namespace std; class Stack{ int top; int s[10]; public: Stack() { top=-1; } void push(int x) { if (!isFull()) { s[++top]=x; } else{ cout<<"Stack is Full\n"; cout<<"------------------------------\n"; } } int pop() { if(!isEmpty()) { return(s[top--]); } else{ return '5'; } } bool isFull() { if (top==9) { return true; } else return false; } bool isEmpty() { if (top==-1) { return true; } else return false; } int peek() { if(!isEmpty()) { return(s[top]); } else{ return -99; } } ~Stack(){ delete s; } }; int main() { Stack st; string str="12+"; for(int i=0;i<str.length();i++) { char ch=str[i]; if(ch!='+'&&ch!='-'&&ch!='*'&&ch!='/') { st.push(ch-'0'); } else { int a=st.pop(); int b=st.pop(); if(ch=='+') { st.push(b+a); } else if(ch=='-') { st.push(b-a); } else if(ch=='*') { st.push(b*a); } else if(ch=='/') { st.push(b/a); } } } cout<<endl<<st.pop()<<endl; return 0; }
JavaScript
UTF-8
306
2.796875
3
[]
no_license
const fs = require('fs'); fs.readdir('./node01',(err,dirs)=>{ for(let i of dirs){ if(fixfile(i)){ console.log("--"+i) }else{ console.log("+"+i) } } }) function fixfile(dir){ let stats = fs.statSync('./node01/'+dir) return stats.isFile() }
Java
GB18030
2,384
2.21875
2
[]
no_license
package com.jeffen.note; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; @SuppressLint("NewApi") public class BookMarkActivity extends Activity { private static final int ACTIVITY_NOTE_LIST = 0; public NoteDbAdapter mDbHelper; public Cursor mCursor; public EditText mBookmark; private Long mNoteId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_bookmark_edit); // home button to return ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); mBookmark = (EditText) this.findViewById(R.id.bookmarkET); mDbHelper = new NoteDbAdapter(this); mDbHelper.open(); mNoteId = null; // ÿһintentһBundle͵extrasݡ Bundle extras = getIntent().getExtras(); if (extras != null) { // ݿѯ mNoteId = extras.getLong(NoteDbAdapter.KEY_ROWID); mCursor = mDbHelper.getBookMark(mNoteId); if (mCursor != null && mCursor.moveToFirst()) { mBookmark.setText(mCursor.getString(mCursor .getColumnIndexOrThrow(mDbHelper.BT_BOOKMARK))); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // create action bar menus MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.bookmark, menu); return true; } /** * action bar menu */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.bookmark_menu_save: saveBookMark(); return true; case android.R.id.home: gotoNoteList(); return true; default: return super.onOptionsItemSelected(item); } } /** * 洦 */ public void saveBookMark() { mDbHelper.updateBookMark(mNoteId, mBookmark.getText().toString()); // ɹ Toast.makeText(this, "Saved Successfully!", Toast.LENGTH_SHORT).show(); gotoNoteList(); } /** * תҳ */ public void gotoNoteList() { Intent i = new Intent(this, NoteListActivity.class); startActivityForResult(i, ACTIVITY_NOTE_LIST); } }
Java
UTF-8
2,277
2.6875
3
[]
no_license
package com.fitbank.webpages.util; import java.io.Serializable; import java.util.Collection; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import com.fitbank.webpages.data.Reference; /** * Clase utilitaria para manejar dependencias. * * @author Smart Financial Sysytems CI */ public class ReferenceUtils implements Serializable { private static final long serialVersionUID = 1L; private final Collection<Reference> references; public ReferenceUtils(Collection<Reference> references) { this.references = references; } public Reference getReference(String alias) { return getReference(alias, null); } public void putReference(String alias, String nombre) { getReference(alias, nombre); } public Reference get(String alias) { for (Reference reference : references) { if (reference.getAlias().equals(alias)) { return reference; } } return null; } public Reference getReference(String alias, String tabla) { if (ReferenceUtils.get(references, alias) == null) { if (tabla == null) { throw new RuntimeException(String.format( "Reference alias='%s' no existente y tabla=null.", alias)); } references.add(new Reference(alias, tabla)); } return ReferenceUtils.get(references, alias); } public Reference findReference(String alias) { if (ReferenceUtils.get(references, alias) == null) { return null; } return ReferenceUtils.get(references, alias); } public static Reference get(Collection<Reference> references, String alias) { return new ReferenceUtils(references).get(alias); } public Object size() { return references.size(); } public boolean isEmpty() { return references.isEmpty(); } public Collection<String> getAliasList() { return CollectionUtils.collect(references, new Transformer() { public Object transform(Object input) { return ((Reference) input).getAlias(); } }); } }
C#
UTF-8
1,209
3.375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab03_Okoronko { class Program { static double Fact(double y) { return (y == 0) ? 1 : y * Fact(y - 1); } static void Main(string[] args) { Console.Title = "Циклы с контролем за монотонной велечиной"; Console.Write("Введите переменную х: "); double x = Convert.ToDouble(Console.ReadLine()); Console.Write("Введите точность: "); double точность = Convert.ToDouble(Console.ReadLine()); double s = 0; int k = 0; while (Math.Abs(Math.Pow(-1, k) / (2 * k + 1) * Math.Pow((x / 2), (2 * k + 1)) / Fact(k)) > точность) { s+= Math.Pow(-1, k) / (2*k + 1)*Math.Pow((x/2),(2*k+1))/Fact(k); k++; } string txt = "Сумма слагаемых равна: "; Console.WriteLine(txt+s); Console.ReadLine(); } } }
Python
UTF-8
405
2.6875
3
[]
no_license
class Solution: def totalHammingDistance(self, nums): """ :type nums: List[int] :rtype: int """ ones = [0 for _ in range(32)] N = len(nums) for num in nums: i = 0 while num: ones[i] += num & 1 i += 1 num >>= 1 return sum(ones[i] * (N - ones[i]) for i in range(32))
Java
UTF-8
6,296
1.945313
2
[]
no_license
package ru.adserver.service; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.*; import org.apache.lucene.store.FSDirectory; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.DependsOn; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import ru.adserver.infrastructure.FsReader; import ru.adserver.infrastructure.IndexTask; import ru.adserver.infrastructure.ScanAction; import ru.adserver.infrastructure.Scanner; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Paths; import java.nio.file.WatchService; import java.util.Date; /** * AdsProcessor * * @author Kontsur Alex (bona) * @since 13.11.2015 */ @Service @DependsOn({"segmentNotFoundHacker", "adsManager"}) public class AdsProcessor implements PropertyObserver { private static final Logger logger = LoggerFactory.getLogger(AdsProcessor.class); private static final String ADS_PATH_PROPERTY = "ads.path"; @Value("${ads.path}") private volatile String adsPath; @Value("${index.path}") private String indexPath; @Inject private TaskScheduler scheduler; @Inject private IndexWriter indexWriter; @Inject private AdsManager adsManager; @Inject private FsReader fsReader; private WatchService watchService; @PostConstruct public void init() { long millis = new DateTime().plusSeconds(3).getMillis(); scheduler.schedule(new Runnable() { @Override public void run() { processExistingFiles(); scanAds(); } }, new Date(millis)); } private void processExistingFiles() { File adsFolder = new File(adsPath); if (!adsFolder.exists()) { throw new IllegalStateException("There is no " + adsPath + " directory"); } if (adsFolder.list().length == 0) { return; } try { IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexPath).toFile())); IndexSearcher indexSearcher = new IndexSearcher(reader); File[] files = adsFolder.listFiles(); for (File file : files) { indexFile(indexSearcher, file.getName()); } } catch (Exception e) { logger.error("Error while processExistingFiles ->", e); } } @Scheduled(fixedDelay = 5000, initialDelay = 5000) public void indexAds() { try { IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexPath).toFile())); final IndexSearcher indexSearcher = new IndexSearcher(reader); adsManager.indexAds(new IndexTask() { @Override public boolean execute(String fileName) { return indexFile(indexSearcher, fileName); } }); } catch (Exception e) { logger.error("Error while index Ads ->", e); } } public boolean fileIndexed(IndexSearcher indexSearcher, String num) { BooleanQuery matchingQuery = new BooleanQuery(); matchingQuery.add(new TermQuery(new Term("num", num)), BooleanClause.Occur.SHOULD); try { TopDocs results = indexSearcher.search(matchingQuery, 1); return results.totalHits > 0; } catch (Exception ignored) { } return false; } private boolean indexFile(IndexSearcher indexSearcher, String fileName) { try { String num = fileName.split(".html")[0].trim(); if (fileIndexed(indexSearcher, num)) { return true; } String content = fsReader.read(adsPath + "/" + fileName, false); if (content == null) { return false; } Document doc = new Document(); doc.add(new StringField("num", num, Field.Store.YES)); doc.add(new TextField("content", content, Field.Store.NO)); indexWriter.addDocument(doc); indexWriter.commit(); return true; } catch (Exception e) { logger.error("Error while indexing file \"" + fileName + "\" ->", e); } return false; } @SuppressWarnings("OverlyNestedMethod") private void scanAds() { try { watchService = FileSystems.getDefault().newWatchService(); Scanner scanner = new Scanner(); scanner.startScanning(watchService, adsPath, new ScanAction() { @Override public void execute(String targetPath, String fileName) { String num = fileName.split(".html")[0].trim(); adsManager.addAdInfo(num); } @Override public String description() { return String.format("Start scanning \"%s\" for initing ads", adsPath); } }); } catch (Exception e) { logger.error("Error while scanning folder \"" + adsPath + "\" -> ", e); } } @Override public void propertyChanged(String name, String value) { if (name.equals(ADS_PATH_PROPERTY)) { adsPath = value; try { watchService.close(); scanAds(); } catch (Exception e) { logger.error("Error while initing watchService ->", e); } } } @PreDestroy public void destory() { try { indexWriter.close(); } catch (IOException ignored) { } } }
Python
UTF-8
1,665
3.15625
3
[]
no_license
from utils.file_service import read_file_from_resources from typing import List def part_1(): data_set = get_part_1_data() correct_passwords_count = 0 for item in data_set: occurences = item["query_string"].count(item["desired_character"]) if (occurences >= item["min_occurences"] and occurences <= item["max_occurences"]): correct_passwords_count += 1 return correct_passwords_count def get_part_1_data() -> str: data_set = read_file_from_resources("day_2.txt").split("\n")[0:-1] mapped_data_set = [] for item in data_set: values = item.replace("-", " ").replace(":", "").split(" ") mapped_data_set.append({"min_occurences": int(values[0]), "max_occurences": int( values[1]), "desired_character": values[2], "query_string": values[3]}) return mapped_data_set def part_2(): data_set = get_part_2_data() correct_passwords_count = 0 for item in data_set: if ((item["desired_character"] == item["query_string"][item["first_index"]]) != (item["desired_character"] == item["query_string"][item["second_index"]])): correct_passwords_count += 1 return correct_passwords_count def get_part_2_data() -> str: data_set = read_file_from_resources("day_2.txt").split("\n")[0:-1] mapped_data_set = [] for item in data_set: values = item.replace("-", " ").replace(":", "").split(" ") mapped_data_set.append({"first_index": int(values[0]) - 1, "second_index": int( values[1]) - 1, "desired_character": values[2], "query_string": values[3]}) return mapped_data_set
JavaScript
UTF-8
607
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
function distanceFromHqInBlocks (someValue) { return Math.abs(42 - someValue); } function distanceFromHqInFeet (someValue) { return distanceFromHqInBlocks(someValue) * 264; } function distanceTravelledInFeet(num1, num2) { let dist = Math.abs(num2 - num1); return dist * 264; } function calculatesFarePrice(start, destination) { let dist = distanceTravelledInFeet(start, destination) if(dist < 400){ return 0; } else if (dist > 400 && dist < 2000){ return (dist-400) * 0.02 } else if (dist > 2000 & dist < 2500) { return 25; } else{ return "cannot travel that far" } }
C#
UTF-8
883
2.859375
3
[]
no_license
using System; namespace Zeghs.Events { /// <summary> /// 報價服務啟動或關閉狀態改變所觸發的事件 /// </summary> public sealed class QuoteServiceSwitchChangedEvent : EventArgs { private bool __bRunning = false; private string __sDataSource = null; /// <summary> /// [取得] 報價資料來源名稱 /// </summary> public string DataSource { get { return __sDataSource; } } /// <summary> /// [取得] 是否在運作中 /// </summary> public bool IsRunning { get { return __bRunning; } } /// <summary> /// 建構子 /// </summary> /// <param name="dataSource">報價資料來源名稱</param> /// <param name="isRunning">是否在運作中</param> internal QuoteServiceSwitchChangedEvent(string dataSource, bool isRunning) { __bRunning = isRunning; __sDataSource = dataSource; } } }
SQL
UTF-8
1,389
3.375
3
[]
no_license
set pages 9999 set verify off col Instance heading 'Environment Info' format a100 col sid heading 'Sid' format 999999 col serial# heading 'Serial#' format 999999 col username heading 'Username' format a15 col program heading 'Program' format a30 col event heading 'Event' format a50 col status heading 'Status' col logon_time heading 'Logon Time' tti off select sysdate ||' '|| upper(instance_name)||' running on Server - '|| host_name Instance from v$instance / tti Left 'Cursor: Pin S Wait on X :' skip 2 REM cursor: pin S wait on X. REM A session waits on this event when requesting a mutex for sharable operations REM related to pins (such as executing a cursor), but the mutex cannot be granted because REM it is being held exclusively by another session (which is most likely parsing the cursor). REM The column P2RAW in v$session gives the blocking session for wait event cursor: pin S wait on X. SELECT p2raw,to_number(substr(to_char(rawtohex(p2raw)), 1, 8), 'XXXXXXXX') sid FROM v$session WHERE event = 'cursor: pin S wait on X' / select sid,serial#,username,program,status,logon_time,blocking_session,blocking_session_status,sql_id,action,event from v$session where SID in (SELECT to_number(substr(to_char(rawtohex(p2raw)),1,8),'XXXXXXXX') FROM v$session WHERE event = 'cursor: pin S wait on X') /
C++
UTF-8
2,397
3.734375
4
[]
no_license
/****************************************************************************************** 题目描述 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。 假设输入的数组的任意两个数字都互不相同。 解题思路:例如序列 4, 8, 6, 12, 16, 14, 10 1. 后续遍历的最后一个结点是根节点,因此找到最后一个结点将序列分为左右子树。左子树结点都小于根 右子树结点均大于根。 2. 从序列开始找到比根结点大的位置,即为右子树开始。此时左边的元素均小于根,因此满足左子树要求 3. 判断右子树的结点是不是都小于根,否,则不是二叉搜索树 4. 递归地判断左, 右两边的元素是不是二叉搜索树。 注意:递归终止条件,即当前序列只剩一个元素。 *******************************************************************************************/ class Solution { public: bool VerifySquenceOfBST(vector<int> sequence) { if(sequence.empty()) return false; vector<int>::iterator start = sequence.begin(); vector<int>::iterator end = sequence.end(); return VerifySubSquenceofBST(start, end); } bool VerifySubSquenceofBST(vector<int>::iterator start, vector<int>::iterator end) { if(end - start == 1) //只有一个元素 return true; vector<int>::iterator it = start; int root = *(end - 1); while(it != end) //寻找左右子树分界点,最终it指向右子树第一个元素 { if(*it < root) ++it; else break; } vector<int>::iterator it2 = it; while(it2 != end) //判断右子树结点是否都小于根节点,如果否,则不是二叉搜索树 { if(*it2 < root) return false; ++it2; } bool left = true; if(it != start) left = VerifySubSquenceofBST(start, it); //左子树起始到右子树开头元素 bool right = true; if(left && it != end) right = VerifySubSquenceofBST(it, end - 1); //右子树起始到根节点 return (left && right); } };
Java
UTF-8
2,782
1.960938
2
[]
no_license
package com.joy.xxfy.informationaldxn.module.driving.domain.repository; import com.joy.xxfy.informationaldxn.module.common.domain.repository.BaseRepository; import com.joy.xxfy.informationaldxn.module.common.enums.DailyShiftEnum; import com.joy.xxfy.informationaldxn.module.department.domain.entity.DepartmentEntity; import com.joy.xxfy.informationaldxn.module.driving.domain.entity.DrivingDailyDetailEntity; import com.joy.xxfy.informationaldxn.module.driving.domain.entity.DrivingDailyEntity; import com.joy.xxfy.informationaldxn.module.driving.domain.entity.DrivingFaceEntity; import com.joy.xxfy.informationaldxn.module.driving.domain.vo.SumDrivingDailyDetailVo; import com.joy.xxfy.informationaldxn.module.produce.domain.vo.CmStatisticVo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Date; import java.util.List; public interface DrivingDailyDetailRepository extends BaseRepository<DrivingDailyDetailEntity>, JpaRepository<DrivingDailyDetailEntity, Long> { // 获取日报详情信息 List<DrivingDailyDetailEntity> findAllByDrivingDaily(DrivingDailyEntity drivingDaily); // 更新日报关联的详细信息删除状态 @Modifying @Query("update DrivingDailyDetailEntity d set isDelete = :isDelete where d.drivingDaily = :drivingDaily") void updateIsDeleteByDrivingDaily(@Param("drivingDaily") DrivingDailyEntity drivingDaily, @Param("isDelete") boolean isDelete); // 日报、队伍、同班次 DrivingDailyDetailEntity findAllByDrivingDailyAndDrivingTeamAndShifts(DrivingDailyEntity drivingDailyEntity, DepartmentEntity departmentEntity, DailyShiftEnum shifts); // 统计某个工作面的总已处理长度、总产量以及总人数 @Query("select new com.joy.xxfy.informationaldxn.module.driving.domain.vo.SumDrivingDailyDetailVo(sum(d.doneLength), sum(d.output), sum(d.peopleNumber)) from DrivingDailyDetailEntity d where d.drivingDaily.drivingFace = :drivingFace") SumDrivingDailyDetailVo aggDailyDetail(@Param("drivingFace") DrivingFaceEntity drivingFace); // 统计某个日报的总已处理长度、总产量以及总人数 @Query("select new com.joy.xxfy.informationaldxn.module.driving.domain.vo.SumDrivingDailyDetailVo(sum(d.doneLength), sum(d.output), sum(d.peopleNumber)) from DrivingDailyDetailEntity d where d.drivingDaily = :drivingDaily") SumDrivingDailyDetailVo aggDailyDetail(@Param("drivingDaily") DrivingDailyEntity drivingDailyEntity); }
Markdown
UTF-8
702
3.15625
3
[]
no_license
# Prism Highlight This is an adaptation of the [prismjs](https://github.com/PrismJS/prism) library that works as an Angular component. ## Installation Install `prism-highlight` with your favorite package manager. You will also need to install `prismjs`. Make sure that you import the the libraries and styles you need from PrismJS itself. For example, in `main.ts`: import 'prismjs'; import 'prismjs/components/prism-typescript'; import 'prismjs/themes/prism.css'; import 'prismjs/themes/prism-dark.css'; ## Usage This module exports a single directive, `prism-highlight` that takes the language for highlighting as an input. <pre prism-highlight="typescript">${tsCode}</pre>
Python
UTF-8
4,655
2.828125
3
[ "MIT", "Apache-2.0" ]
permissive
"""AirbrakeHandler module. All functions and types related to python logging should be defined in this module. A function for mapping a LogRecord object https://docs.python.org/2/library/logging.html#logrecord-objects to an Airbrake error should be included here. """ import logging from airbrake.notifier import Airbrake from airbrake.notice import ErrorLevels _FAKE_LOGRECORD = logging.LogRecord('', '', '', '', '', '', '', '') class AirbrakeHandler(logging.Handler): """A handler class which ships logs to airbrake.io. Requires one: * `project_id` AND `api_key` * an instance of airbrake.Airbrake """ # pylint: disable=too-many-arguments def __init__(self, airbrake=None, level=logging.ERROR, project_id=None, api_key=None, **config): """Initialize the Airbrake handler with a default logging level. Default level of logs handled by this class are >= ERROR, which includes ERROR and CRITICAL. To change this behavior supply a different argument for 'level'. """ logging.Handler.__init__(self, level=level) if isinstance(airbrake, Airbrake): self.airbrake = airbrake else: self.airbrake = Airbrake(project_id, api_key, **config) def emit(self, record): """Log the record airbrake.io style. To prevent method calls which invoke this handler from using the global exception context in sys.exc_info(), exc_info must be passed as False. E.g. To prevent AirbrakeHandler from reading the global exception context, (which it may do to find a traceback and error type), make logger method calls like this: LOG.error("Bad math.", exc_info=False) Otherwise, provide exception context directly, though the following contrived example would be a strange way to use the handler: exc_info = sys.exc_info() ... LOG.error("Bad math.", exc_info=exc_info) """ # if record.exc_info[1]: # print("record.exc_info[1], ", record.exc_info[1]) # record.exc_info[1].__context__ # print("wtf?, ", record.exc_info[1].__context__) try: airbrakeerror = airbrake_error_from_logrecord(record) self.airbrake.log(**airbrakeerror) except (KeyboardInterrupt, SystemExit): raise except: # pylint: disable=bare-except self.handleError(record) def airbrake_error_from_logrecord(record): """Create an airbrake error dictionary from a python LogRecord object. For more info on the logging.LogRecord class: https://docs.python.org/2/library/logging.html#logrecord-objects """ airbrakeerror = {} params = { 'logrecord_filename': record.filename, 'levelname': record.levelname, 'created': record.created, # TODO(samstav): make this human readable 'process_id': record.process, 'process_name': record.processName, 'thread_name': record.threadName, 'lineno': record.lineno, 'pathname': record.pathname, 'funcName': record.funcName, 'msg': record.getMessage()} # find params from kwarg 'extra' # See "The second keyword argument is extra" # - https://docs.python.org/2/library/logging.html#logging.Logger.debug for key, val in list(vars(record).items()): if not hasattr(_FAKE_LOGRECORD, key): # handle attribute/field name collisions: # logrecord attrs should not limit or take # precedence over values specified in 'extra' if key in params: # if key "already" in params -> is logrecord attr params["logrecord_" + key] = params.pop(key) # let 'extra' (explicit) take precedence params[key] = val airbrakeerror.update(params) # errtype may be overridden by the notifier if an applicable # exception context is available and exc_info is not False airbrakeerror['errtype'] = "%s:%s" % (record.levelname, record.filename) # if record.exc_info: # getattr(record.exc_info[1], '__context__', None) # # typ, err, tb = record.exc_info # # getattr(err, '__context__', None) airbrakeerror['exc_info'] = record.exc_info airbrakeerror['message'] = record.getMessage() airbrakeerror['filename'] = record.pathname airbrakeerror['line'] = record.lineno airbrakeerror['function'] = record.funcName airbrakeerror['severity'] = getattr(ErrorLevels, record.levelname) return airbrakeerror
Go
UTF-8
2,105
3.171875
3
[]
no_license
package mind type EnrichResult struct { Title string Content string ContentCopyright string ContentSource string ImageUrl string ImageCopyright string ImageSource string Format EnrichFormat } func (e EnrichResult) Enriched() bool { if len(e.Content) > 0 || len(e.ImageUrl) > 0 { return true } return false } type EnrichFormat string var ( EnrichStandard EnrichFormat = "standard" EnrichUrlNoImage EnrichFormat = "url_no_image" EnrichUrlFocusImage EnrichFormat = "url_focus_image" ) type EnrichResults []EnrichResult // Enrichers are the engine allowing to // add many information to a memo in order // to send emails with a lot of information. type Enricher interface { // Fetch the data needed to enrich the // given text using the given Category, // then analyzes the fetched data in order // to return a small description and an image // Url. Enrich(string, Category) (bool, EnrichResult, error) } // Enrich builds an EnrichResult containing description and image // to complete the information guessed from the given text. // The current purpose is to use these information to send contextual // and interesting emails. func Enrich(text string, cat Category) (bool, EnrichResult, error) { es := make([]Enricher, 0) // looks whether the text contains an Url // --------------------- url := rxUrl.FindString(text) if len(url) != 0 { // we have an URL: starts with the Url enricher // because it'll probably be enough. es = append(es, &Url{url: url}) } // other engines // ---------------------- switch cat { // TODO(remy): imdb, allociné // TODO(remy): yelp // TODO(remy): bandcamp ? case Artist, Actor, Movie, Person, Place, Serie, VideoGame, Food: es = append(es, &Wikipedia{}) } // TODO(remy): long text can probably be sent as is in an email. for _, e := range es { if found, result, err := e.Enrich(text, cat); err != nil { return false, EnrichResult{}, err } else if !found { continue } else { return found, result, nil } } return false, EnrichResult{}, nil }
Java
UTF-8
2,352
2.578125
3
[]
no_license
package com.wakaleo.dojo.melbourne1.checkout; import com.sun.tools.doclets.internal.toolkit.util.TextTag; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * A description goes here. * User: john * Date: 18/09/13 * Time: 6:58 PM */ public class WhenScanningAnItem { @Test public void checkout_should_contain_no_items_by_default() { Checkout checkout = new Checkout(new PriceRules()); assertThat(checkout.numItemsScanned(), is(0)); } @Test public void checkout_tracks_the_number_of_items_scanned() { Checkout checkout = new Checkout(new PriceRules()); checkout.scan("AA"); checkout.scan("BB"); assertThat(checkout.numItemsScanned(), is(2)); } @Test public void checkout_should_track_one_item() { Checkout checkout = new Checkout(new PriceRules()); checkout.scan("AA"); assertThat(checkout.numItemsScanned(), is(1)); } @Test public void should_track_total_count_of_each_item() { Checkout checkout = new Checkout(new PriceRules()); checkout.scan("AA"); checkout.scan("AA"); checkout.scan("SH"); checkout.scan("AA"); checkout.scan("SH"); checkout.scan("AA"); assertThat(checkout.countOf("AA"), is(4)); assertThat(checkout.countOf("SH"), is(2)); } @Test public void checkout_should_calculate_total_of_one_item() throws UnknownItemCodeException { PriceRules priceRules = mock(PriceRules.class); when(priceRules.getPriceFor("AA")).thenReturn(100); Checkout checkout = new Checkout(priceRules); checkout.scan("AA"); assertThat(checkout.calculateTotal(), is(100)); } @Test public void checkout_should_calculate_total_of_two_item() throws UnknownItemCodeException { PriceRules priceRules = mock(PriceRules.class); when(priceRules.getPriceFor("AA")).thenReturn(100); when(priceRules.getPriceFor("BB")).thenReturn(10); Checkout checkout = new Checkout(priceRules); checkout.scan("AA"); checkout.scan("BB"); assertThat(checkout.calculateTotal(), is(110)); } }
Java
UTF-8
2,406
2.5625
3
[]
no_license
package tests; import org.testng.Assert; import org.testng.annotations.Test; import base.TestBase; public class LoginPageTests extends TestBase{ @Test(priority = 06) public void verifyLoginPageTitle() { hp.clickSignInLink(); String expectedLoginPageTitle = "Login - My Store"; String actualLoginPageTitle = lp.getLoginPageTitle(); Assert.assertEquals(actualLoginPageTitle, expectedLoginPageTitle, "Login Page title not matched"); System.out.println("Login Page Title is verified"); } @Test(priority=07) public void createAccountwithInvalidEmail() { String exp_CreateAnAccount = "CREATE AN ACCOUNT"; String act_CreateAnAccount = lp.getCreateAnAccountHeadingText(); Assert.assertEquals(act_CreateAnAccount, exp_CreateAnAccount, "Create An Account text not found"); System.out.println("Create An Account is preesent....."); lp.setEmailForCreateAnAccount("test.testing"); lp.clickCreateAnAccountSubmitButton(); System.out.println( " Invalid Email "); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); }; } @Test(priority=8) public void createAnAccountWithValidEmail() { lp.setEmailForCreateAnAccount("uday.brave1@gmail.com"); lp.clickCreateAnAccountSubmitButton(); System.out.println("Account is created successfully........."); } @Test(priority=9) public void verifyloginwithinvalidCredentials(){ String expectedTitle = "ALREADY REGISTERED?"; String actualTitle = lp.getPagesubHeadingAlreadyRegistered(); Assert.assertEquals(actualTitle, expectedTitle, "Login Page not found"); System.out.println("Login page is present"); lp.setEmailForLogin("testing.test@gmail.com"); lp.setPwdForLogin("123456"); lp.clickSignIn(); System.out.println("Invalid username and Password"); } @Test(priority=10) public void verifyForgotPasswordLink() throws InterruptedException { lp.clickForgotPasswordLink(); System.out.println("Redirected to Forgot Password Page"); Thread.sleep(3000); lp.setEmailForForgotPassword("test.testing@gmail.com"); lp.clickRetrievePassword(); String expectedText = "A confirmation email has been sent to your address: test.Testing@gmail.com"; String actualText = lp.getSuccessMessageforForgotPassword(); Assert.assertEquals(actualText, expectedText, "Email sent success message not found");; System.out.println("Forgot password email is sent"); } }
Python
UTF-8
7,113
2.703125
3
[ "MIT" ]
permissive
# coding: utf-8 #------------------------------------------------------------------------------------------# # This file is part of Pyccel which is released under MIT License. See the LICENSE file or # # go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. # #------------------------------------------------------------------------------------------# """ OpenMP has several constructs and directives, and this file contains the OpenMP types that are supported. We represent some types with the OmpAnnotatedComment type. These types are detailed on our documentation: https://github.com/pyccel/pyccel/blob/master/tutorial/openmp.md """ from .basic import Basic __all__ = ('OmpAnnotatedComment', 'OMP_For_Loop', 'OMP_Simd_Construct', 'OMP_TaskLoop_Construct', 'OMP_Distribute_Construct', 'OMP_Parallel_Construct', 'OMP_Task_Construct', 'OMP_Single_Construct', 'OMP_Critical_Construct', 'OMP_Master_Construct', 'OMP_Masked_Construct', 'OMP_Cancel_Construct', 'OMP_Target_Construct', 'OMP_Teams_Construct', 'OMP_Sections_Construct', 'OMP_Section_Construct', 'Omp_End_Clause') class OmpAnnotatedComment(Basic): """Represents an OpenMP Annotated Comment in the code. Parameters ---------- txt: str statement to print combined: List (Optional) constructs to be combined with the current construct Examples -------- >>> from pyccel.ast.omp import OmpAnnotatedComment >>> OmpAnnotatedComment('parallel') OmpAnnotatedComment(parallel) """ __slots__ = ('_txt', '_combined', '_has_nowait') _attribute_nodes = () _is_multiline = False def __init__(self, txt, has_nowait=False, combined=None): self._txt = txt self._combined = combined self._has_nowait = has_nowait super().__init__() @property def is_multiline(self): """Used to check if the construct needs brackets.""" return self._is_multiline @property def has_nowait(self): """Used to check if the construct has a nowait clause.""" return self._has_nowait @has_nowait.setter def has_nowait(self, value): """Used to set the _has_nowait var.""" self._has_nowait = value @property def name(self): """Name of the construct.""" return '' @property def txt(self): """Used to store clauses.""" return self._txt @property def combined(self): """Used to store the combined construct of a directive.""" return self._combined def __getnewargs__(self): """Used for Pickling self.""" args = (self.txt, self.combined) return args def __str__(self): instructions = [self.name, self.combined, self.txt] return '#$ omp '+' '.join(i for i in instructions if i) class OMP_For_Loop(OmpAnnotatedComment): """ Represents an OpenMP Loop construct. """ __slots__ = () def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) @property def name(self): """Name of the construct.""" return 'for' class OMP_Simd_Construct(OmpAnnotatedComment): """ Represents an OpenMP Simd construct""" __slots__ = () def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) @property def name(self): """Name of the construct.""" return 'simd' class OMP_TaskLoop_Construct(OmpAnnotatedComment): """ Represents an OpenMP Taskloop construct""" __slots__ = () def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) @property def name(self): """Name of the construct.""" return 'taskloop' class OMP_Distribute_Construct(OmpAnnotatedComment): """ Represents an OpenMP Distribute construct""" __slots__ = () def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) @property def name(self): """Name of the construct.""" return 'distribute' class OMP_Parallel_Construct(OmpAnnotatedComment): """ Represents an OpenMP Parallel construct. """ __slots__ = () _is_multiline = True @property def name(self): """Name of the construct.""" return 'parallel' class OMP_Task_Construct(OmpAnnotatedComment): """ Represents an OpenMP Task construct. """ __slots__ = () _is_multiline = True def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) class OMP_Single_Construct(OmpAnnotatedComment): """ Represents an OpenMP Single construct. """ __slots__ = () _is_multiline = True def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) @property def name(self): """Name of the construct.""" return 'single' class OMP_Critical_Construct(OmpAnnotatedComment): """ Represents an OpenMP Critical construct. """ __slots__ = () _is_multiline = True def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) class OMP_Master_Construct(OmpAnnotatedComment): """ Represents OpenMP Master construct. """ __slots__ = () _is_multiline = True def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) class OMP_Masked_Construct(OmpAnnotatedComment): """ Represents OpenMP Masked construct. """ __slots__ = () _is_multiline = True @property def name(self): """Name of the construct.""" return 'masked' class OMP_Cancel_Construct(OmpAnnotatedComment): """ Represents OpenMP Cancel construct. """ __slots__ = () def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) class OMP_Target_Construct(OmpAnnotatedComment): """ Represents OpenMP Target construct. """ __slots__ = () _is_multiline = True @property def name(self): """Name of the construct.""" return 'target' class OMP_Teams_Construct(OmpAnnotatedComment): """ Represents OpenMP Teams construct. """ __slots__ = () _is_multiline = True @property def name(self): """Name of the construct.""" return 'teams' class OMP_Sections_Construct(OmpAnnotatedComment): """ Represents OpenMP Sections construct. """ __slots__ = () _is_multiline = True def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) @property def name(self): """Name of the construct.""" return 'sections' class OMP_Section_Construct(OmpAnnotatedComment): """ Represent OpenMP Section construct. """ __slots__ = () _is_multiline = True def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait) class Omp_End_Clause(OmpAnnotatedComment): """ Represents the End of an OpenMP block. """ __slots__ = () def __init__(self, txt, has_nowait): super().__init__(txt, has_nowait)
JavaScript
UTF-8
825
2.625
3
[]
no_license
import prefix from "./prefix.js" import {reisy} from "./index.js" export function use(...args) { const style = {} const classNames = [] args.forEach(processDef) return { className: classNames.join(" "), style: prefix(style), } function processDef(def) { if (!def) { return } if (typeof def === "string") { classNames.push(def) } else if (Array.isArray(def)) { def.forEach(processDef) } else { Object.assign(style, def) } } } export function inject(instance = reisy) { const style = document.createElement("style") document.head.appendChild(style) setCSS() instance.on(setCSS) return () => { instance.off(setCSS) document.head.removeChild(style) } function setCSS() { const css = instance.resolve() style.textContent = css } }
C++
UTF-8
898
2.59375
3
[]
no_license
#ifndef P_H #define P_H #include<iostream> #include<string> #include <unistd.h> #include<stdlib.h> #include<time.h> using namespace std; class pokemon { protected: string type; string name; int chance; int stage; int num; public: pokemon(); void set_type(string t); void set_name(string n); void set_chance(int c); void set_stage(int s); void set_num(int n); string get_type(); string get_name(); int get_chance(); int get_stage(); int get_num(); bool catchp(); }; class rocka:public pokemon { public: rocka(); }; class rockb:public pokemon { public: rockb(); }; class flya:public pokemon { public: flya(); }; class flyb:public pokemon { public: flyb(); }; class psychica:public pokemon { public: psychica(); }; class psychicb:public pokemon { public: psychicb(); }; #endif
Java
UTF-8
574
1.898438
2
[]
no_license
package cmpg.photoshare.repository; import cmpg.photoshare.entity.MemberImage; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.repository.CrudRepository; import javax.transaction.Transactional; import java.util.List; public interface MemberImageRepository extends CrudRepository<MemberImage, Long> { List<MemberImage> getByEmail(String email); @Transactional @Modifying public void deleteByPath(String path); @Transactional @Modifying public void deleteByPathAndEmail(String path, String email); }
C++
UTF-8
658
3.5
4
[]
no_license
/* Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Note: Each element in the result must be unique. The result can be in any order. */ #include <iostream> #include <unordered_set> #include <string> #include <vector> using namespace std; class Solution{ public: vector <int> intersection(vector <int>& nums1, vector<int>& nums2){ unordered_set<int> temp(nums1.begin(),nums1.end()); vector <int> ans; for( auto a:nums2){ if(temp.count(a)){ ans.push_back(a); temp.erase(a); } } return ans; } }; int main(){ }
Java
UTF-8
249
1.789063
2
[]
no_license
package com.jbp.randommaster.gui.common.grouping; import java.util.EventListener; public interface GroupingListener extends EventListener { public void groupNameChanged(GroupingEvent e); public void groupSelected(GroupingEvent e); }
Java
UTF-8
559
1.664063
2
[]
no_license
package data; public class PathData { public static String pId = "choi"; public static String pStoreArea = null; public static String pStoreName = null; public static String pStoreTell = null; public static String pStoreAddress = null; public static String pProductName[] = {"주문상품1","주문상품2","주문상품3","주문상품4"}; public static int pProductCount[] = new int[4]; public static int pProductPrice[] = new int[4]; public static String pOrderImg[]= {"img/imgInit.png","img/imgInit.png","img/imgInit.png","img/imgInit.png"}; }
Java
UTF-8
2,585
3.296875
3
[]
no_license
package com.study.schdule; import java.util.PriorityQueue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; //该队列是一个优先级队列.并且也是一个阻塞队列 public class CustomPriorityQueue extends PriorityQueue<CustomTask>{ public ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private boolean isOk = false; @Override public boolean add(CustomTask e) { final ReentrantLock lock = this.lock; lock.lock(); try { CustomTask ct = this.peek(); // int val = this.size(); boolean res = super.offer(e); //判断是否有线程进入了永久休眠 //调用方法进行唤醒所有.以免线程进入永久休眠(等待) //(如果没有进入永久休眠也不会有影响.类似于notifyAll) // if(ct==null || e.compareTo(ct)<0) if(ct==null && isOk) { condition.signalAll(); } return res; } finally { lock.unlock(); } } public CustomTask take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); //和lock不同的是当阻塞时可被interrupt的锁. // lock.lock(); try { for(;;) { CustomTask ct = this.poll(); //如果线程为空.则进入永久等待. if(ct==null) { // Thread.yield(); isOk=true; condition.await(); } else { // long delay = ct.getDelay(TimeUnit.NANOSECONDS); // if(delay>0) // { //// long tl = condition.awaitNanos(ct.time); // condition.await(1000, TimeUnit.MILLISECONDS); // } // else // { // CustomTask task = this.peek(); // return task; // } if(ct.time>0) { condition.await(ct.time, ct.getUnit()); } CustomTask task = ct; // assert task!=null; // if(this.size()!=0) // { // System.out.println("sdfdsf"); // condition.signalAll(); // } return task; } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } return null; } //获取头部元素.但是不会删除. @Override public synchronized CustomTask peek() { return super.peek(); } //获取头部元素.会删除元素 @Override public synchronized CustomTask poll() { return super.poll(); } //添加元素 @Override public boolean offer(CustomTask e) { return super.offer(e); } }
Java
UTF-8
2,415
2.375
2
[]
no_license
package com.example.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Entity @Table(name = "user") @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"}) public class User implements Serializable { @Id private Long username; private String name; private String school; private Integer class_id; private String qq; private String year; @Transient private Integer new_message; @Transient//属于实体的临时数据,jpa不写在数据库字段里 private List<UserCourse> userCourses; public Long getUsername() { return username; } public void setUsername(Long username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getClass_id() { return class_id; } public void setClass_id(Integer classId) { this.class_id = classId; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public Integer getNew_message() { return new_message; } public void setNew_message(Integer new_message) { this.new_message = new_message; } public List<UserCourse> getUserCourses() { return userCourses; } public void setUserCourses(List<UserCourse> userCourses) { this.userCourses = userCourses; } @Override public String toString() { return "User{" + ", username=" + username + ", name='" + name + '\'' + ", school='" + school + '\'' + ", class_id=" + class_id + ", qq='" + qq + '\'' + ", year='" + year + '\'' + ", new_message=" + new_message + ", userCourses=" + userCourses + '}'; } }
Java
UTF-8
1,823
3.484375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lab8; /** * * @author Louis */ public final class XPoly { // Bai 1. Them mot phuong thuc tinh voi tham so bien doi thuc hien tinh //tong cac tham so truyen vao public static final double sum(double ...x){ double sum = 0; for (double i: x) sum += i; return sum; } // Bai2. Them phuong thuc tinh tim so be nhat va lon nhat public static final double min(double ...x){ double min = x[0]; for (double i: x) min = Math.min(min, i); return min; } public static final double max(double ...x){ double max = x[0]; for (double i: x) max = Math.max(max, i); return max; } // Bai 3. Them phuong thuc In hoa chu cai dau tien cua moi tu public static final String toUpperFirstChar(String s){ String[] words = s.split(" "); for (int i = 0; i < words.length; i++){ char firstChar = words[i].charAt(0); char upperFirstChar = String.valueOf(firstChar).toUpperCase().charAt(0); words[i] = upperFirstChar + words[i].substring(1); } String ss = String.join(" ", words); return ss; } // Chuong trinh chinh public static void main(String[] args){ // Demo day 7.6; 8.9; 0.5 System.out.println("Tong cua cac so: " + XPoly.sum(7.6,8.9,0.5)); System.out.println("Min trong day: " + XPoly.min(7.6,8.9,0.5)); System.out.println("Max trong day: " + XPoly.max(7.6,8.9,0.5)); System.out.println("In hoa chu cai dau moi tu: " + XPoly.toUpperFirstChar("vo xuan vuong")); } }
Java
UTF-8
566
2.015625
2
[]
no_license
package com.lyb.service.impl; import com.lyb.entity.AccWorksheet; import com.lyb.mapper.AccWorksheetMapper; import com.lyb.service.AccWorksheetService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AccWorksheetServiceImpl implements AccWorksheetService { @Autowired private AccWorksheetMapper accWorksheetMapper; @Override public AccWorksheet selectByWorksheetNo(String worksheetno) { return accWorksheetMapper.selectByWorkSheetNo(worksheetno); } }
Java
UTF-8
787
3.15625
3
[]
no_license
package com.oop.animalkingdom; import java.awt.Color; public class Bear extends Critter { private boolean polar; private boolean rightStep=true; public Bear() {}; public Bear(boolean polar) { this.polar = polar; } @Override public Action getMove(CritterInfo info) { return info.frontThreat() ? Action.INFECT : (Neighbor.EMPTY.equals(info.getFront())) ? Action.HOP : Action.LEFT; } public boolean isPolar() { return polar; } public void setPolar(boolean polar) { this.polar = polar; } @Override public Color getColor() { return polar ? Color.WHITE : Color.BLACK; } @Override public String toString() { if(rightStep) { rightStep = false; return "/"; } rightStep = true; return "\\"; } }
Java
UTF-8
647
2.265625
2
[]
no_license
package de.fzi.biggis.api; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import de.fzi.biggis.exceptions.ParameterException; @Provider public class ParameterExceptionHandler implements ExceptionMapper<ParameterException> { public ParameterExceptionHandler() { System.out.println("ParameterExceptionHandler created"); } @Override public Response toResponse(ParameterException e) { System.out.println("ParameterExceptionHandler invoked"); return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build(); } }
TypeScript
UTF-8
643
2.953125
3
[]
no_license
import { CommandConfiguration } from './command-configuration.interface'; import { Executable } from '../interfaces/executable'; /** * Decorator function defining a CLI command * * @param configuration Declaration of a command */ export function Command(configuration: CommandConfiguration): any { return (constructor: any) => { if (constructor.prototype.execute === undefined) { throw new Error('Command decorator requires class to implement Executable'); } return class extends constructor { name = configuration.name; aliases = configuration.aliases; }; }; }
JavaScript
UTF-8
1,673
3
3
[]
no_license
app.service('clientservice', function () { //to create unique client id var uid = 1; //clients array to hold list of all clients var clients = [{ id: 0, 'email': 'hello@gmail.com', // unique identifier 'username': 'Viral', 'fname': 'Viral', 'lname': 'Viral', // ---- // additional parameters // details object definition.. 'clientId': 'vip-973-bc-324', 'phone': '123-2343-44' }]; //save method create a new client if not already exists //else update the existing object this.save = function (client) { if (client.id == null) { //if this is new client, add it in clients array client.id = uid++; clients.push(client); } else { //for existing client, find this client using id //and update it. for (c in clients) { if (clients[c].id == client.id) { clients[c] = client; } } } } //simply search clients list for given id //and returns the client object if found this.get = function (id) { for (c in clients) { if (clients[c].id == id) { return clients[c]; } } } //iterate through clients list and delete //client if found this.delete = function (id) { for (c in clients) { if (clients[c].id == id) { clients.splice(c, 1); } } } //simply returns the clients list this.list = function () { return clients; } });
JavaScript
UTF-8
969
4.03125
4
[]
no_license
// write a function to retrieve a blob of json // make an ajax request! Use FETCH function. //http://rallycoding.herokuapp.com/api/music_albums /*function fetchAlbums() { //es6 fetch('http://rallycoding.herokuapp.com/api/music_albums') //endpoint .then(res => res.json()) //return promise, when resolved, of response json .then(json => console.log(json)); //return promise, when resolved, of json and then log json } fetchAlbums();*/ /*async function fetchAlbums() { //es8 const res = await fetch('http://rallycoding.herokuapp.com/api/music_albums'); //await response from api endpoint const json = await res.json(); //assign json to response.json console.log(json); }*/ const fetchAlbums = async () => { //es8 arrow function const res = await fetch('http://rallycoding.herokuapp.com/api/music_albums'); //await response from api endpoint const json = await res.json(); //assign json to response.json console.log(json); }
Python
UTF-8
19,094
3.34375
3
[]
no_license
# coding=UTF-8 """ ========================================= admin division数据(行政区划数据接口) ========================================= :Author: glen :Date: 2016.11.17 :Tags: mongodb database collection admin division :abstract: admin division数据接口 **类** ================== AdminDivision admin division数据接口 **使用方法** ================== admindivision集合接口 # @property: # - year: 年份 # - version: 版本号 # # - Province: 所有省份 # - Prefecture: 所有地级地区 # - County:所有县级地区 # - ProvincePrefecture:所有省份和地级地区 # - ProvincePrefectureCounty: 所有省份、地级和县级地区 # @method: # - getByAcode(self,acode,year):根据acode和年份得到行政区域,参数acode是行政代码,字符串;year是年份,字符串。 # 返回数据记录,list。 # - __getitem__(self, key):重载运算符[]。其中的key表示表示区域名称,方法如下:(1)省级区域,用名字直接表示, # 例如ad[u'北京']; (2)地级区域,用省级、地级名称表示,例如ad[u'浙江',u'嘉兴']; # (3)县级区域,用省级、地级、县级名称表示,例如ad[u'湖北', u'恩施',u'来凤'];(4) # 如果是本级行政区域加上下级行政区域,下级行政区域用f(first)表示,例如表示浙江省 # 及其所有地级行政区域,用ad[u'浙江',u'f'];5)如果是本级行政区域加上下下级行政区域, # 下下级行政区域用s(second)表示,例如表示浙江省及其所有县级行政区域,用ad[u'浙江',u's']; # (6)如果是本级行政区域加上下级及下下级行政区域,下级及下下级行政区域用b(both)表示, # 例如表示浙江省及其所有地县级行政区域,用ad[u'浙江',u'b']。返回值是数据库中查询得到 # 的行政区划的列表。 **示范代码** ================== :: >>># 连接MongoDB中的ProvinceStat集合 >>>mongo = MongoDB() >>>mdb = MonDatabase(mongodb=mongo, database_name='region') >>>prostat = MonDBProvinceStat(database=mdb) >>># 返回集合中所有变量列表 >>>print(prostat.variables) >>># 查询变量名 >>>for item in prostat.search_variable('法人单位数',exact=True).distinct('variable'): print(item) """ import re from dbadmin.admindivision.class_admindivisiondatabase import AdminDivisionDatabase from pymongo import ASCENDING import pandas as pd class AdminDivision: """ 类AdminData表示行政区划数据 :param str,list year: 年份 :return: 无返回值 """ def __init__(self, year=None): # 设置数据库 self.database = AdminDivisionDatabase() # 设置版本和年份 if year is not None: if isinstance(year,(int,str)): self._year = str(year) elif isinstance(year,(tuple,list)): self._year = [str(y) for y in year] else: self._year = None def __getitem__(self, key): if isinstance(key,str): if re.match('^s$',key): return self.province if re.match('^t$',key): return self.prefecture if re.match('^f$',key): return self.county if re.match('^st$',key): return self.province_and_prefecture if re.match('^sf$',key): return self.province_and_county if re.match('^tf$',key): return self.prefecture_and_county if re.match('^stf$',key): return self.all_region province_found = self.get_province(province=key) if province_found.size > 0: return province_found else: prefecture_found = self.get_prefecture(prefecture=key) if prefecture_found.size > 0: return prefecture_found else: return self.get_county(county=key) elif isinstance(key,tuple): if len(key) < 2: if re.match('^s$', key[0]): return self.province if re.match('^t$', key[0]): return self.prefecture if re.match('^f$', key[0]): return self.county if re.match('^st$', key[0]): return self.province_and_prefecture if re.match('^sf$', key[0]): return self.province_and_county if re.match('^tf$', key[0]): return self.prefecture_and_county if re.match('^stf$', key[0]): return self.all_region province_found = self.get_province(province=key[0]) if province_found.size > 0: return province_found else: prefecture_found = self.get_prefecture(prefecture=key[0]) if prefecture_found.size > 0: return prefecture_found else: return self.get_county(county=key[0]) elif len(key) < 3: if re.match('^f$', key[1]) is not None: return self.get_prefecture_children(province=key[0]) if re.match('^s$', key[1]) is not None: return self.get_county_children(province=key[0]) if re.match('^fs$', key[1]) is not None: return self.get_prefecture_and_county_children(province=key[0]) found = self.get_prefecture(province=key[0],prefecture=key[1]) if found.size < 1: found = self.get_county(province=key[0],county=key[1]) return found elif len(key) < 4: if re.match('^f$', key[2]) is not None: return self.get_county_children(province=key[0],prefecture=key[1]) return self.get_county(province=key[0],prefecture=key[1],county=key[2]) else: print('Too many parameters!') raise Exception def set_year(self,year): """ 设置年份 :param str year: 年份 :return: 无返回值 """ if isinstance(year, (int, str)): self._year = str(year) elif isinstance(year, (tuple, list)): self._year = [str(y) for y in year] def get_province(self, province=None): """ 获得省级行政区划 :param str province: 省级行政区划名称 :return: 返回查询得到的省级行政区划 :rtype: pandas.DataFrame """ if province is not None: return self.province[self.province['region'].apply(lambda x: re.match(''.join(['^',province]), x) is not None)] else: return self.province[self.province['region'].apply(lambda x: re.match('^$', x) is not None)] def get_prefecture(self, province=None, prefecture=None): """ 获得地级行政区划 :param str province: 省级行政区划 :param str prefecture: 地级行政区划 :return: 返回地级行政区划 :rtype: pandas.DataFrame """ prefecture_data = self.get_prefecture_children(province=province) if prefecture_data.size > 0: found = prefecture_data[prefecture_data['region'].apply(lambda x: re.match(prefecture, x) is not None)] if found.size > 0: return found return self.prefecture[self.prefecture['region'].apply(lambda x: re.match(prefecture, x) is not None)] def get_county(self, province=None, prefecture=None, county=None): counties = self.get_county_children(province=province,prefecture=prefecture) if counties.size > 0: county_found = counties[counties['region'].apply(lambda x: re.match(county, x) is not None)] if county_found.size > 0: return county_found return self.county[self.county['region'].apply(lambda x: re.match(county, x) is not None)] def region_table(self,year=None,province=True,prefecture=False,county=False): origin_year = self._year for i in range(len(year)): self._year = str(year[i]) if i == 0: if province and (not prefecture) and (not county): rtable = self.province.loc[:, ['acode', 'region']] elif province and prefecture and (not county): rtable = self.province_and_prefecture.loc[:, ['acode', 'region']] elif province and (not prefecture) and county: rtable = self.province_and_county.loc[:, ['acode', 'region']] elif province and prefecture and county: rtable = self.all_region.loc[:, ['acode', 'region']] elif (not province) and prefecture and (not county): rtable = self.prefecture.loc[:, ['acode', 'region']] elif (not province) and prefecture and county: rtable = self.prefecture_and_county.loc[:, ['acode', 'region']] elif (not province) and (not prefecture) and county: rtable = self.county.loc[:, ['acode', 'region']] rtable.columns.values[rtable.shape[1] - 1] = str(year[i]) else: if province and (not prefecture) and (not county): rtable = pd.merge(rtable, self.province.loc[:, ['acode', 'region']], how='outer', on='acode') elif province and prefecture and (not county): rtable = pd.merge(rtable, self.province_and_prefecture.loc[:, ['acode', 'region']], how='outer', on='acode') elif province and (not prefecture) and county: rtable = pd.merge(rtable, self.province_and_county.loc[:, ['acode', 'region']], how='outer', on='acode') elif province and prefecture and county: rtable = pd.merge(rtable, self.all_region.loc[:, ['acode', 'region']], how='outer', on='acode') elif (not province) and prefecture and (not county): rtable = pd.merge(rtable, self.prefecture.loc[:, ['acode', 'region']], how='outer', on='acode') elif (not province) and prefecture and county: rtable = pd.merge(rtable, self.prefecture_and_county.loc[:, ['acode', 'region']], how='outer', on='acode') elif (not province) and (not prefecture) and county: rtable = pd.merge(rtable, self.county.loc[:, ['acode', 'region']], how='outer', on='acode') rtable.columns.values[rtable.shape[1] - 1] = str(year[i]) self._year = origin_year rtable = rtable.sort_values('acode') rtable.index = range(rtable.shape[0]) return rtable def get_prefecture_children(self, province=None): found_acode = set(self.get_province(province=province)['acode']) if len(found_acode) == 1: found_acode = found_acode.pop() return self.prefecture[self.prefecture['acode'].apply(lambda x: re.match(''.join(['^', found_acode[0:2]]), x) is not None)] else: return self.get_province(province=province) def get_county_children(self, province=None, prefecture=None, county_type='all'): if prefecture is None: province_found = set(self.get_province(province=province)['acode']) if len(province_found) < 1: return self.get_province(province=province) elif len(province_found) < 2: found_acode = province_found.pop() all_county_children = self.county[self.county['acode'].apply( lambda x: x[0:2] == found_acode[0:2])] if county_type == 'direct': prefecture_children = set(self.get_prefecture_children(province=province)['acode']) prefecture_code = set([prefecture[0:4] for prefecture in prefecture_children]) return self.county[self.county['acode'].apply( lambda x: (x[0:2] == found_acode[0:2]) and (x[0:4] not in prefecture_code))] elif county_type == 'indirect': prefecture_children = set(self.get_prefecture_children(province=province)['acode']) prefecture_code = set([prefecture[0:4] for prefecture in prefecture_children]) return self.county[self.county['acode'].apply( lambda x: x[0:4] in prefecture_code)] else: return all_county_children else: print('More than two provinces provided!') raise Exception else: prefecture_found = set(self.get_prefecture(province=province, prefecture=prefecture)['acode']) if len(prefecture_found) < 1: return self.get_prefecture(province=province, prefecture=prefecture) elif len(prefecture_found) < 2: prefecture_code = prefecture_found.pop() return self.county[self.county['acode'].apply( lambda x: x[0:4] == prefecture_code[0:4])] else: print('More than two prefectures provided!') raise Exception def get_prefecture_and_county_children(self, province=None): found_acode = set(self.get_province(province=province)['acode']) if len(found_acode) < 1: return self.get_province(province=province) elif len(found_acode) < 2: found_acode = found_acode.pop() return self.prefecture_and_county[self.prefecture_and_county['acode'].apply( lambda x: found_acode[0:2] == x[0:2])] else: print('More than one province provided!') raise Exception @property def province(self): province_list = list(self.database.find(adminlevel=2, year=self.year, projection={'_id':0,'region':1,'acode':1,'year':1, 'former':1,'uid':1,'parent':1, 'adminlevel':1}, sorts=[('year',ASCENDING),('acode',ASCENDING)])) return pd.DataFrame(province_list,columns=['acode','region','year','uid', 'adminlevel', 'former','parent']) @property def prefecture(self): prefecture_list = list(self.database.find(adminlevel=3, year=self.year, projection={'_id': 0, 'region': 1, 'acode': 1, 'year': 1, 'former': 1, 'uid': 1, 'parent': 1, 'adminlevel': 1}, sorts=[('year', ASCENDING), ('acode', ASCENDING)])) return pd.DataFrame(prefecture_list, columns=['acode', 'region', 'year', 'uid', 'adminlevel', 'former', 'parent']) @property def county(self): county_list = list(self.database.find(adminlevel=4, year=self.year, projection={'_id': 0, 'region': 1, 'acode': 1, 'year': 1, 'former': 1, 'uid': 1, 'parent': 1, 'grandpa': 1, 'adminlevel': 1}, sorts=[('year', ASCENDING), ('acode', ASCENDING)])) return pd.DataFrame(county_list, columns=['acode', 'region', 'year', 'uid', 'adminlevel', 'former', 'parent','grandpa']) @property def province_and_prefecture(self): return self.all_region[self.all_region['adminlevel'].apply(lambda x: x == 2 or x == 3)] @property def province_and_county(self): return self.all_region[self.all_region['adminlevel'].apply(lambda x: x == 2 or x == 4)] @property def prefecture_and_county(self): return self.all_region[self.all_region['adminlevel'].apply(lambda x: x == 3 or x == 4)] @property def all_region(self): region_list = list(self.database.find(year=self.year,adminlevel=[2,3,4], projection={'_id': 0, 'region': 1, 'acode': 1, 'year': 1, 'former': 1, 'uid': 1, 'parent': 1, 'grandpa': 1, 'adminlevel': 1}, sorts=[('year', ASCENDING), ('acode', ASCENDING)])) return pd.DataFrame(region_list, columns=['acode', 'region', 'year', 'uid', 'adminlevel', 'former', 'parent', 'grandpa']) @property def year(self): return self._year @property def period(self): return sorted(list(self.database.collection.find().distinct('year'))) if __name__ == '__main__': adivision = AdminDivision(year=[2009]) print(adivision.all_region) print(adivision.year) print(adivision.period) print(adivision.province) print(adivision.prefecture) print(adivision.county) #adivision.set_year('2008') print(adivision.get_prefecture_children(province='江苏')) prefecture_data = adivision.get_prefecture_children(province='江苏') print(prefecture_data[prefecture_data['region'].apply(lambda x: re.match('无锡', x) is not None)]) print('-'*80) print(adivision.get_prefecture('江苏','苏州')) print(adivision.get_county_children(province='江苏',prefecture='苏州')) print(adivision.get_county_children(province='湖北',county_type='direct')) print(adivision.get_county(province='浙江',county='海宁')) print('-'*80) print(adivision['浙江']) print(adivision['浙江','杭州']) print(adivision['浙江','f']) print(adivision['浙江','嘉兴','海宁']) print(adivision['浙江','海宁']) print(adivision['江苏','昆山','f']) print('-'*80) print(adivision.region_table(year=range(1995,2005),prefecture=True)) print('-'*80) print(adivision.get_prefecture_children()) print(adivision.get_prefecture(province='安徽',prefecture='南京')) print(adivision.get_county_children(province='上海',prefecture='嘉兴')) print(adivision.get_county(province='上海',prefecture='嘉兴',county='海宁')) print(adivision.get_county(province='上海',prefecture='南京',county='昆山')) print(adivision.get_prefecture_and_county_children(province='江苏')) print('='*80) print(adivision['上海','南京','海宁']) print(adivision['吉林市'],type(adivision['吉林市']['region'].values[0])) print(adivision['浙江','海宁']) print('='*80) print(adivision.province_and_prefecture)
Python
UTF-8
6,659
3.09375
3
[]
no_license
## Librairie contenant les fonctions locales utilises ## par l'application import pandas as pd import numpy as np import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet from nltk.tokenize import word_tokenize from sklearn.preprocessing import MultiLabelBinarizer def return_tags_from_question(question, vect, model_clf, labeller): bow = vect.transform(question) return get_tag_from_proba(model_clf.predict_proba(bow), 5, labeller) def line_treatment(line, list_words, tokenizer): """ Fonction qui traite une liste de mots en entrée et ressort un bag of words avec RegexTokenizer """ list_to_include = [] list_to_drop = [] line = line.lower() for mot in list_words: if(mot in line.lower()): list_to_include.append(mot) list_to_drop.append(tokenizer.tokenize(mot)[0]) vocab = tokenizer.tokenize(line) for inc in list_to_include: for w in vocab: if(w == tokenizer.tokenize(inc)[0]): vocab.remove(w) vocab.append(inc) return vocab def remove_stopwords(vocab): """ Fonction qui traite les stopwords contenues dans la chaine de mots vocab """ total_list = list(stopwords.words("English")) custom_list = ["to", "use", "can", "the", "get", "is", "doe", "way", "two" "one", "an", "there", "are", "new", "like", "using", "vs", "without"] total_list = total_list + custom_list vocab_copy = vocab.copy() for w in vocab: if w in total_list: vocab_copy.remove(w) vocab_copy2 = vocab_copy.copy() for w in vocab_copy: if len(w) < 2: vocab_copy2.remove(w) return vocab_copy2 def get_wordnet_pos(treebank_tag): """ return WORDNET POS compliance to WORDENT lemmatization (a,n,r,v) """ if treebank_tag.startswith('J'): return wordnet.ADJ elif treebank_tag.startswith('V'): return wordnet.VERB elif treebank_tag.startswith('N'): return wordnet.NOUN elif treebank_tag.startswith('R'): return wordnet.ADV else: # As default pos in lemmatization is Noun return wordnet.NOUN def lemm_fonction(tokens): """ Fonction qui renvoie une liste lemmatizer""" lemm = [] lemmatizer = WordNetLemmatizer() tagged = nltk.pos_tag(tokens) for word, tag in tagged: wntag = get_wordnet_pos(tag) if wntag is None:# not supply tag in case of None lemma = lemmatizer.lemmatize(word) else: lemma = lemmatizer.lemmatize(word, pos=wntag) if wntag == wordnet.NOUN: lemm.append(lemma) return lemm def tokenizer_idf(text): """Tokenizer traitant nos données d'entrée de tf_idf """ capwork_tokenizer = nltk.tokenize.RegexpTokenizer(r'[a-zA-Z]+') list_words_to_keep = [".net", "c++", "c#","sql-server", "asp.net", 'ruby-on-rails', 'objective-c', 'visual-studio-2008', 'cocoa-touch', 'vb.net', "visual-studio", ] response = line_treatment(text, list_words_to_keep, capwork_tokenizer) response3 = lemm_fonction(response) return remove_stopwords(response3) def count_null(df, x): """Fonction qui compte le % de données nulles dans la colonne x d'un tableau df """ a = round((df[x].count() / df.shape[0] * 100), 2) return float("%.2f" % a) def print_top_words(model, feature_names, n_top_words): """ Fonction qui renvoie les mots les plus fréquents d'un theme identifié par model avec son dictionnaire feature_name s""" for topic_idx, topic in enumerate(model.components_): message = "Topic #%d: " % topic_idx message += " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) print(message) def get_rwk(lamb, phi, pw): """ Fonction renvoyant la relevance des mots contenu dans ne vocabulaire """ rw = np.array(phi) temp = np.array(phi) temp2 = np.array(pw) for w in range(temp.shape[1]): for k in range(temp.shape[0]): rw[k, w] = lamb * np.log(temp[k, w]) + (1-lamb) * np.log(temp[k, w] / temp2[w][0]) return rw def return_relevant_tags(topic, feature_names, rwk, n_top_words): """ Fonction qui renvoie les mots les plus adéquates en fonction du rwk et du topic prédit """ relevance = np.array(rwk) list_tags = list() for i in relevance[topic, :].argsort()[-1: -n_top_words: -1]: list_tags.append(feature_names[i]) return list_tags def return_main_topic(model_out): """ Fonction qui renvoie le topic prédit en allant chercher le thème majoritaire model_out """ list_topics = list() for index, probabilities in enumerate(model_out): list_topics.append(probabilities.argsort()[-1]) return list_topics def return_frame_info(table_df): """Fonction qui renvoie la synthèse des éléments d'un tableau (remplissage, type, valeur unique) """ df = pd.DataFrame(columns=["% de remplissage", "Type", "Unique"], index=table_df.columns) df["% de remplissage"] = df.index df["Type"] = df.index df["% de remplissage"] = df["% de remplissage"].apply(lambda x: count_null(table_df, x)) df["Type"] = df["Type"].apply(lambda x: table_df[x].dtype) df["Unique"] = df.index df["Unique"] = df["Unique"].apply(lambda x: table_df[x].nunique()) return df def traitement_des_tags(list_to_treat, list_tags): """ Fonction qui renvoie la liste des tags filtrées et ordonnées """ for element in list_to_treat: list_to_treat = set(list_to_treat) if (element not in list_tags): list_to_treat.remove(element) list_temp = list(list_to_treat) return sorted(list_temp) def get_tag_from_proba(response_vect, nb_tag, labelizer): """ Fonction qui renvoie les tags correspondants en fonction des probabilités obtenues et du nombre de tags désirés """ list_response = [list(labelizer.classes_[resp.argsort()[-1: -nb_tag - 1: -1]]) for resp in response_vect] return list_response def get_tagging_score(y_tag_true, y_tag_predit): """ Fonction qui renvoie le nombre de tags vrai prédit dans la liste prédite""" score_test = list() for (x, y) in zip(y_tag_true, y_tag_predit): score_test.append(len(set(x) & set(y))/len(set(x))) return sum(score_test)/len(score_test)
Python
UTF-8
1,549
4.3125
4
[]
no_license
""" File: ta10-solution.py Author: Br. Burton This file demonstrates the merge sort algorithm. There are efficiencies that could be added, but this approach is made to demonstrate clarity. """ from random import randint MAX_NUM = 100 def merge_sort(items): """ Sorts the items in the list :param items: The list to sort """ if len(items) > 1: mid = len(items) // 2 lefthalf = items[:mid] righthalf = items[mid:] merge_sort(lefthalf) merge_sort(righthalf) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] <= righthalf[j]: items[k] = lefthalf[i] i += 1 else: items[k] = righthalf[j] j = j + 1 k += 1 while i < len(lefthalf): items[k] = lefthalf[i] i += 1 k += 1 while j < len(righthalf): items[k] = righthalf[j] j += 1 k += 1 def generate_list(size): """ Generates a list of random numbers. """ items = [randint(0, MAX_NUM) for i in range(size)] return items def display_list(items): """ Displays a list """ for item in items: print(item) def main(): """ Tests the merge sort """ size = int(input("Enter size: ")) items = generate_list(size) merge_sort(items) print("\nThe Sorted list is:") display_list(items) if __name__ == "__main__": main()
Java
UTF-8
319
2.578125
3
[]
no_license
package web.card.demon; public class Demon { private String cardId; private int power; public String getCardId() { return cardId; } public void setCardId(String cardId) { this.cardId = cardId; } public int getPower() { return power; } public void setPower(int power) { this.power = power; } }
Java
UTF-8
1,825
2.265625
2
[ "MIT" ]
permissive
package com.catalog.freezer.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.MimeTypeUtils; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.catalog.freezer.model.Person; import com.catalog.freezer.model.request.SignUpRequest; import com.catalog.freezer.service.PersonService; @RestController @RequestMapping("/api/person") public class PersonController { @Autowired PersonService personService; @PostMapping(produces = MimeTypeUtils.APPLICATION_JSON_VALUE) @PreAuthorize("permitAll") public ResponseEntity<Person> register(@Valid @RequestBody SignUpRequest sigUpPerson) { Person person= personService.save(sigUpPerson); return ResponseEntity.status(HttpStatus.CREATED).body(person); } @GetMapping @PreAuthorize("hasRole('ROLE_ADMIN')") public ResponseEntity<List<Person>> getAllPersons() { return ResponseEntity.ok(personService.getAll()); } @GetMapping(path = "/{person-id}") @PreAuthorize("isAuthenticated()") public ResponseEntity<Person> getPersonById(@PathVariable(name = "person-id", required = true ) final Long personId) { Person person = personService.findById(personId); if (person != null) { return ResponseEntity.ok(person); } return ResponseEntity.notFound().build(); } }
C++
UTF-8
657
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { vector<vector<int>> nums(6); int sum = 0; int m = INT_MIN; for (int i = 0; i < 6; i++) { nums[i].resize(6); for (int j = 0; j < 6; j++) { cin >> nums[i][j]; } cin.ignore(numeric_limits<streamsize>::max(), '\n'); } for (int i = 0; i <= 3; i++) { for (int j = 0; j <=3; j++) { sum = nums[i][j] + nums[i][j+1] + nums[i][j+2] + nums[i+2][j] + nums[i+2][j+1] + nums[i+2][j+2] + nums[i+1][j+1]; m = max(m,sum); } } cout << m << endl; return 0; }
Markdown
UTF-8
4,533
3.28125
3
[]
no_license
# Annotation Guideline # Milestone 2 This will be a multi-label annotation, meaning that a text can have multiple annotation labels. Please read this instruction carefully, and for each text select ALL labels that apply. If no labels apply to a particular text, select ‘None of the above’ #### Content - Select Content if a text includes ANY of the following: 1. What the course is about - Examples: - Great course on how to manage Innovation programs - Great theoretical foundation for everyone interested in the field of terrorism and counterterrorism! - Very interesting course about Food & Beverage Mgmt. - A wonderful opportunity to learn about current topics. 2. Theories/concepts/knowledge presented in the course, or the lack of - Examples: - Brilliantly designed to cover many important topics in psychology - Trying to teach statistics without math is a difficult task - I appreciated all the different theories and cases presented in this course - The only thing was missing was a view of morality of Aristotle. 3. Direct mention of the word “content” - Examples: - It is a course with very deep content. #### Course delivery - Select Course delivery if a text includes ANY of the following: 1. Direct mention of instructors, especially how well do they teach, explain, provide feedback or answer things - Examples: - Is a great teacher. - Everything is very well explained. - He is a very wise and clear teacher. 2. Course structure, lecture format, or evaluation methods such as assignments, case studies or quizzes, etc. - Examples: - The course was very thorough and well structured. - Problems with explanations and/or better feedback on quizzes. - The exercises at each end of week are very well crafted. - Course is made in an accurate and, at the same time, entertaining design 3. Presentation of course material or additional resources - Examples: - I love the way that the videos were made. - The fact that there was PDF material for every week, it was really great. #### Usefulness: - Select Usefulness if a text includes ANY of the following: 1. New skillset or knowhow, visions: - Examples: - I have thoroughly enjoyed this online course and have been able to broaden my skill set and understanding accordingly. - its free useful for me to strong my MS Excel skill - This course got me thinking about life in general and brought into context - I have the feeling that it will serve me a lot on my way to becoming a branding expert. 2. Improvement: - Examples: - I have systematically improved my skills in this area. - I have improved my Korean language a lot because of this course. 3. Job-searching/ school application: - Examples: - Strong foundations of project finance concepts which will allow students to either enter the infrastructure financing and investment industry. - You have made her dream of "matriculating" at the Royal (Dick) School of Veterinary Studies come true! #### Difficulty - Select Difficulty if a text includes ANY of the following: 1. Specific Knowledge prerequisites: - Examples: - One doesn't have to have mathematical background to comprehend course materials. - Although the course is a bit mathematical, the ideas are fairly intuitive. 2. Whether it is easy about the questions/homework/ quiz/ test/etc.: - Examples: - The tests at the end of each week are very easy. - I found myself thinking I understood until I got to the quiz. - Most questions are easy, but some require a lot of research. 3. General ideas about the course: - Examples: - This was an extremely difficult course for me that required repeatedly reading the course material and utilizing Wikipedia to access a deeper understanding of the many organ and cell functions. - Interesting course, challenging and informative. #### Workload - Select Workload if a text includes ANY of the following: 1. evaluate the quantity of work: - Examples: - I also appreciated that the course was doable for a working mom at home with a toddler during a pandemic. 2. Amount of time spent for the course: - Examples: - With few hours per week, this course is able to give learners a thorough view and fundamental Excel skills.
Java
UTF-8
212
1.539063
2
[]
no_license
package pl.krzywyyy.ztmwatcher.model; import lombok.Data; @Data public class Ztm { private Float Lat; private Float Lon; private String Time; private String Lines; private String Brigade; }
C++
UTF-8
554
2.875
3
[]
no_license
#include "common.h" class Solution { public: vector<int> inorderTraversal(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> res; if (root == NULL) return res; vector<int> left = inorderTraversal(root->left); res.insert(res.end(), left.begin(), left.end()); res.push_back(root->val); vector<int> right = inorderTraversal(root->right); res.insert(res.end(), right.begin(), right.end()); return res; } };
Markdown
UTF-8
3,624
2.921875
3
[ "Apache-2.0" ]
permissive
--- title: "조금더가설검정" date: 2020-12-19T23:13:07+09:00 Description: "" Tags: ['통계학'] Categories: ['통계학'] DisableComments: false --- t- test 이외에 다른 가설검정을 배워본다. - 독립성 : 두 그룹이 서로 독립적인 것이여야만 한다 - 정규성 : 가설 검정을 하려는 데이터가 정규분포와 일치하는지 - 등분산성 : 비교하고자하는 그룹간에 유사한 수준의 분산을 가지는지 (스케일이 비슷한지) 정규 분포가 아니고 많은 분포가 있을 수 있다. - binomial, negative binomial, geometric, t분포, f분포 …. 정규성(nomality)을 실제로 데이터에서 어떻게 판단 하는가 ? - python normal test - spicy.stats.normaltes : 정규성을 테스트하는 방법 normallty 를 가지지 않는 데이터에 가설검정을 하는 방법 1. 어떤 분포를 가지는지 찾아서 분포에 맞는 가설검정을 한다 (좋지만 현실적이지 않음) 2. non parametric method를 이용해서 가설검정을 한다 비모수적 방법(non parametric method)을 쓰는 경우 - 데이터가 카테고리로 이루어져 있을 때 (통계치가 나올수 없음) - 아웃라이어가 있어서 통계치가 의미가 없을때 parameter estimation 이 필요하지 않기 때문에 non-parametric 이라고 부름 - 비모수적 방법 1 kruskal 실제 상황과 가설 검정 결과가 다른 것인지 확인하는 것 ( Type of Error ) - True Negative - False Negative - False Positive - True Positive 지금까지 배운 가설검정 t-test 는 평균을 이용하는 방법 - 분산, 편차 등 다양한 가설검정 방법들이 존재함 - 그 중 카이스퀘어만 배워보자  카이스퀘어 ( 분포, 빈도, 비율 ) 등에 대해서 검사하는 방법 * one sample 카이스퀘어(chi) : 주어진 데이터가 동일한 혹은 유사한 분포를 나타내는지 확인 - 귀무가설 : 분포가 비슷할것이다. - 대안가설 : 분포가 비슷하지 않을 것이다. 카이스퀘어의 결과값을 해석하는 방법 -> 결과 값을 p-value 로 변경해야함 - 왜냐하면, 표준화된 값이 필요하기 때문임 - one sample chi square: scipy.stats.chisquare 질문 : chisquare 의 인자값이 하나일 땐 어떤 거랑 비교하는 건가요? -> 귀무가설 : 입력 데이터가 균등하게 분포되어 있는 것인가 ex) stats.chisquare([1, 29, 4, 30, 2, 5], f_exp=[16, 16, 16, 16, 16, 10,10]) -> Power_divergenceResult(statistic=60.625, pvalue=9.02720542805885e-12) * two sample 카이스퀘어 - 귀무가설 : 카테고리컬 변수가 연간이 없다 - 대안가설 : 카테고리컬 변수가 연간이 있다 * two sample chi2 square - chi2_contingency 질문 : one sample chi square 의 입력 변수의 size는 같아야하나요? 질문 : two sample 카이스퀘어의 귀무가설 Numerical -> Categorial (1) type casting - numeric 이지만 연속적이지 않을 때 ex 1 , 2, 3 -> 1, 2, 3 - type 만 변경해서 그대로 사용한다 (2) Binning - numerical 이지만 continuous 할 때 - 1.3, 1.4,2.1.2.5 -> 1~2, 2~3 질문 : category 자료형으로 바뀌어도 보이는데 변화가 없는데 다른건가요? - int 형도 category 자료형으로 변경해줘야 하는건가요? 카이스퀘어 검정에서는 똑같은 통계치여도 자유도!에 따라서 영향을 받을 수 밖에 없다 * 자유도(Degrees of Freedom)는 중요하다! * 주어진 통계치를 만들기 위한 가지의 수 * -> 해당 파라미터를 결정짓기 위해 독립적으로 정해질 수 있는 값의 수
Java
UTF-8
2,072
2.34375
2
[]
no_license
package com.cc.shop.dao; import java.util.ArrayList; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.cc.shop.pojo.BillItem; import com.cc.shop.pojo.Product; import com.cc.shop.pojo.ShopCartItem; import com.cc.shop.utils.PageHibernateCallback; public class BillDao extends HibernateDaoSupport { // DAO中的保存商品的方法 public void save(BillItem billItem) { this.getHibernateTemplate().save(billItem); } public void update(BillItem billItem) { this.getHibernateTemplate().update(billItem); } public BillItem findBillItemByPid(Integer pid) { String hql = "from BillItem p where p.product.pid = ?"; List<BillItem> list = this.getHibernateTemplate().find(hql, pid); if (list != null && list.size() > 0) { System.out.println(list.size()); for (int i = 0; i < list.size(); i++) { System.out.println("pid:" + list.get(i).getProduct().getPid()); System.out.println("count" + list.get(i).getCount()); System.out.println("Ptotal" + list.get(i).getPtotal()); } return list.get(0); } return null; } public List<BillItem> findAllBillItem() { String hql = "from BillItem "; List<BillItem> list = this.getHibernateTemplate().find(hql); if (list != null && list.size() > 0) { System.out.println(list.size()); for (int i = 0; i < list.size(); i++) { System.out.println("pid:" + list.get(i).getProduct().getPid()); System.out.println("count" + list.get(i).getCount()); System.out.println("Ptotal" + list.get(i).getPtotal()); } return list; } return list; } public int findCount() { return 1; } // 后台查询所有商品的方法 public List<BillItem> findByPage(int begin, int limit) { String hql = "from BillItem order by product.pid desc"; List<BillItem> list = this.getHibernateTemplate().execute( new PageHibernateCallback<BillItem>(hql, null, begin, limit)); if (list != null && list.size() > 0) { return list; } return null; } }
C#
UTF-8
756
3.265625
3
[]
no_license
using System.IO; using System.Collections.Generic; using System; namespace RegexParser_Example { class Program { static void Main(string[] args) { var users = new List<Entity>(); var parser = new Parser(); using var sr = new StreamReader("Data.txt"); string line; var c = 0; while (!string.IsNullOrEmpty(line = sr.ReadLine())) { var entity = parser.Analize(line); c++; if (entity != null) Console.WriteLine(entity.ToString()); else Console.WriteLine("Line number {0} \"{1}\" wasn't recognized!\n", c, line); } } } }
Go
UTF-8
15,173
2.609375
3
[]
no_license
package support import ( "container/list" "encoding/json" "fmt" "math/rand" "net" "os" "reflect" "strconv" "strings" "time" ) type WorkerStat struct { Reads int64 Writes int64 BytesRead int64 BytesWritten int64 ReadErrors int WriteErrors int Elapsed time.Duration LowResponse time.Duration HighResponse time.Duration AvgResponse time.Duration Histogram *DistroGraph } type SlaveController struct { JobConfig *JobData Name string Printer *Printer SlaveConn net.Conn encode *json.Encoder decode *json.Decoder Stats WorkerStat StatChan chan WorkerStat } type SlaveState struct { printer *Printer SlaveConn net.Conn params *SlaveParams encode *json.Encoder decode *json.Decoder threadRunning bool workerCmpt chan WorkerStat statChan chan *WorkerStat targetDev *os.File removeOnClose bool totalStats WorkerStat } /* * The member names must all start with a capital letter else JSON * will not encode or decode the data correctly. */ type SlaveParams struct { JobName string FileName string IODepth int FileSize int64 Runtime time.Duration AccessPattern string accessPattern *list.List Verbose bool } const ( _ = iota SlaveOpWarmup = iota + 1 SlaveOpStart SlaveOpStop SlaveFinished SlaveFinishedStats SlaveIntermediateStats StatusOkay = 1 StatusError = 2 ) type SlaveOp struct { OpType int } type SlaveResponse struct { RespStatus int RespInfo string } type SlaveStatReply struct { SlaveName string SlaveStats WorkerStat } func (sc *SlaveController) InitDial() error { var err error if sc.SlaveConn, err = net.Dial("tcp", sc.JobConfig.Slave_Host+":6969"); err != nil { return fmt.Errorf("failed to connect to %s, err=%s", sc.JobConfig.Slave_Host, err) } sc.encode = json.NewEncoder(sc.SlaveConn) sc.decode = json.NewDecoder(sc.SlaveConn) sapi := SlaveParams{JobName: sc.Name, FileName: sc.JobConfig.Name, IODepth: sc.JobConfig.IODepth, FileSize: sc.JobConfig.fileSize, Runtime: sc.JobConfig.runtime, AccessPattern: sc.JobConfig.Access_Pattern, Verbose: sc.JobConfig.Verbose} if err = sc.encode.Encode(&sapi); err != nil { return fmt.Errorf("JSON Encode failed on params: %s", err) } var resp SlaveResponse if err = sc.decode.Decode(&resp); err != nil { return fmt.Errorf("JSON decode error on response: %s", err) } if resp.RespStatus != StatusOkay { return fmt.Errorf(resp.RespInfo) } return nil } func (sc *SlaveController) ClientStart() error { slaveOp := SlaveOp{OpType: SlaveOpStart} if err := sc.encode.Encode(&slaveOp); err != nil { return fmt.Errorf("Failed to start slave: %s\n", err) } var resp SlaveResponse if err := sc.decode.Decode(&resp); err != nil { return fmt.Errorf("JSON decode error on response: %s", err) } if resp.RespStatus != StatusOkay { return fmt.Errorf(resp.RespInfo) } return nil } func (sc *SlaveController) ClientWait() error { defer func() { sc.SlaveConn.Close() }() var slaveOp SlaveOp for { if err := sc.decode.Decode(&slaveOp); err != nil { return fmt.Errorf("JSON decode error: %s", err) } switch slaveOp.OpType { case SlaveFinished: return nil case SlaveFinishedStats: var stats SlaveStatReply if err := sc.decode.Decode(&stats); err != nil { return fmt.Errorf("JSON decode error on final stats: %s", err) } sc.Stats = stats.SlaveStats case SlaveIntermediateStats: var stats SlaveStatReply if err := sc.decode.Decode(&stats); err == nil { sc.StatChan <- stats.SlaveStats } } } } func (sc *SlaveController) ClientStop() { slaveOp := SlaveOp{OpType: SlaveOpStop} sc.encode.Encode(&slaveOp) } func (s *SlaveState) SlaveExecute(p *Printer) { var err error defer func() { s.SlaveConn.Close() }() s.encode = json.NewEncoder(s.SlaveConn) s.decode = json.NewDecoder(s.SlaveConn) s.printer = p s.workerCmpt = make(chan WorkerStat, 10) s.statChan = make(chan *WorkerStat, 10) var params SlaveParams if err = s.decode.Decode(&params); err != nil { p.Send("Failed to decode first params: %s\n", err) return } s.params = &params if s.prepTarget() == false { p.Send("Failed to prep target: %s\n", s.params.FileName) return } s.sendReply(&SlaveResponse{StatusOkay, "okay"}) go s.intermediateStats() var slaveOp SlaveOp s.threadRunning = true for s.threadRunning { if err = s.decode.Decode(&slaveOp); err != nil { /* * Look for a means to test the type of error. If the error is EOF * that's expected with the master side closes the connection. However, * other errors which might be a decoding error should have some * status sent to the master. */ return } switch slaveOp.OpType { case SlaveOpWarmup: s.sendReply(&SlaveResponse{StatusOkay, "okay"}) case SlaveOpStart: go s.slaveRun() s.sendReply(&SlaveResponse{StatusOkay, "okay"}) case SlaveOpStop: p.Send("STOP requested\n") s.threadRunning = false s.sendReply(&SlaveResponse{StatusOkay, "okay"}) default: p.Send("Invalid slave operation: %d\n", slaveOp.OpType) s.sendReply(&SlaveResponse{StatusError, fmt.Sprintf("invalid op %d", slaveOp.OpType)}) } } } func (s *SlaveState) prepTarget() bool { var err error var fileInfo os.FileInfo openFLags := os.O_RDWR if _, err := os.Stat(s.params.FileName); err == nil { s.removeOnClose = false } else { s.removeOnClose = true openFLags |= os.O_CREATE } if s.targetDev, err = os.OpenFile(s.params.FileName, openFLags, 0666); err != nil { s.sendReply(&SlaveResponse{RespStatus: StatusError, RespInfo: fmt.Sprintf("%s", err)}) return false } if fileInfo, err = s.targetDev.Stat(); err == nil { if fileInfo.Mode().IsRegular() { if fileInfo.Size() < s.params.FileSize { var bufSize int if s.params.FileSize < (1024 * 1024) { bufSize = int(s.params.FileSize) } else { bufSize = 1024 * 1024 } bp := make([]byte, bufSize) for fillSize := s.params.FileSize; fillSize > 0; fillSize -= int64(bufSize) { if _, err := s.targetDev.Write(bp); err != nil { s.sendReply(&SlaveResponse{StatusError, fmt.Sprintf("failed to fill '%s'", s.params.FileName)}) s.targetDev.Close() return false } } } if s.params.FileSize == 0 { s.params.FileSize = fileInfo.Size() } if s.params.FileSize == 0 { s.sendReply(&SlaveResponse{StatusError, fmt.Sprintf("no file size for '%s'", s.params.FileName)}) s.targetDev.Close() return false } s.targetDev.Seek(0, 0) s.targetDev.Sync() } else { if pos, err := s.targetDev.Seek(0, 2); err != nil { s.sendReply(&SlaveResponse{StatusError, fmt.Sprintf("Unable to find size of device: '%s'", s.params.FileName)}) s.targetDev.Close() return false } else { s.params.FileSize = pos s.targetDev.Seek(0, 0) } } } else { s.sendReply(&SlaveResponse{StatusError, fmt.Sprintf("stat failed after open on '%s'", s.params.FileName)}) } if err := s.parseAccessPattern(); err != nil { s.sendReply(&SlaveResponse{RespStatus: StatusError, RespInfo: fmt.Sprintf("access Pattern err: %s", err)}) } return true } /* * This code is copied directly from config.go. Need to look into using * interface{} so I only have one copy of the code. */ func (s *SlaveState) parseAccessPattern() error { var ok bool total := 0 l := list.New() sections := strings.Split(s.params.AccessPattern, ",") if len(sections) == 0 { sections = []string{s.params.AccessPattern} } for _, sec := range sections { params := strings.Split(sec, ":") if len(params) != 3 { return fmt.Errorf("should be tuple of 3 '%s'", sec) } else { e := AccessPattern{} e.sectionPercent, _ = strconv.Atoi(params[0]) total += e.sectionPercent rwPercentage := strings.Split(params[1], "|") if len(rwPercentage) == 1 { if e.opType, ok = accessType[params[1]]; !ok { return fmt.Errorf("invalid op %s", params[1]) } e.readPercent = 50 } else { if e.opType, ok = accessType[rwPercentage[0]]; !ok { return fmt.Errorf("invalid op %s", rwPercentage[0]) } e.readPercent, _ = strconv.Atoi(rwPercentage[1]) } if e.blkSize, ok = BlkStringToInt64(params[2]); !ok { return fmt.Errorf("invalid blksize: %s", params[2]) } l.PushBack(e) } } if total > 100 { //noinspection GoPlaceholderCount return fmt.Errorf("more than 100%") } if total < 100 { e := AccessPattern{sectionPercent: 100 - total, opType: NoneType, blkSize: 0, readPercent: 0, lastBlk: 0, sectionStart: 0, sectionEnd: 0} l.PushBack(e) } s.params.accessPattern = l currentBlk := int64(0) for e := s.params.accessPattern.Front(); e != nil; e = e.Next() { access := e.Value.(AccessPattern) access.sectionStart = currentBlk currentBlk += s.params.FileSize * int64(access.sectionPercent) / 100 access.sectionEnd = currentBlk - access.blkSize e.Value = access } return nil } func (s *SlaveState) slaveRun() { workersComplete := 0 var avgResponse time.Duration = 0 avgCount := 0 defer func() { s.SlaveConn.Close() if s.removeOnClose { os.Remove(s.params.FileName) } s.targetDev.Close() }() for i := 0; i < s.params.IODepth; i++ { go s.slaveWorker(i) } s.totalStats.LowResponse = time.Hour * 24 s.totalStats.Histogram = DistroInit(nil, "") if s.params.Verbose { DebugEnable() } start := time.Now() for { select { case worker := <-s.workerCmpt: s.addStats(&s.totalStats, &worker) avgResponse += worker.AvgResponse avgCount++ workersComplete++ if workersComplete < s.params.IODepth { continue } s.totalStats.AvgResponse = avgResponse / time.Duration(avgCount) s.totalStats.Elapsed = time.Now().Sub(start) s.sendReply(&SlaveOp{OpType: SlaveFinishedStats}) s.sendReply(&SlaveStatReply{SlaveName: s.params.JobName, SlaveStats: s.totalStats}) s.sendReply(&SlaveOp{OpType: SlaveFinished}) s.threadRunning = false if s.params.Verbose { DebugDisable() } return } } } func (s *SlaveState) intermediateStats() { thrStats := &WorkerStat{} thrStats.Histogram = DistroInit(nil, "") checkin := 0 for { select { case ws := <-s.statChan: s.addStats(thrStats, ws) checkin++ if checkin < s.params.IODepth { continue } checkin = 0 s.sendReply(&SlaveOp{OpType: SlaveIntermediateStats}) s.sendReply(&SlaveStatReply{SlaveName: s.params.JobName, SlaveStats: *thrStats}) thrStats = &WorkerStat{} thrStats.Histogram = DistroInit(nil, "") } } } func (s *SlaveState) addStats(parent, w *WorkerStat) { DebugLog("[]---- addStats ----[]\n") DebugIncrease() classPtr := reflect.ValueOf(parent).Elem() wPtr := reflect.ValueOf(w).Elem() for i := 0; i < classPtr.NumField(); i++ { classField := classPtr.Field(i) wField := wPtr.FieldByName(classPtr.Type().Field(i).Name) switch classField.Kind() { case reflect.Int64: switch classPtr.Type().Field(i).Name { case "LowResponse": DebugLog("Low: class(%d) field(%d)\n", classField.Int(), wField.Int()) if classField.Int() > wField.Int() { classField.SetInt(wField.Int()) } case "HighResponse": DebugLog("High: class(%d) field(%d)\n", classField.Int(), wField.Int()) if classField.Int() < wField.Int() { classField.SetInt(wField.Int()) } default: classField.SetInt(wField.Int() + classField.Int()) } case reflect.Ptr: DebugLog("Name(%s), CanSet(%t), Kind(%s)\n", classPtr.Type().Field(i).Name, classField.CanSet(), classField.Kind()) h := classPtr.Field(i).Addr().Elem().Interface().(*DistroGraph) lh := wPtr.FieldByName(classPtr.Type().Field(i).Name).Addr().Elem().Interface().(*DistroGraph) h.addBins(lh) } } DebugDecrase() } func (s *SlaveState) sendReply(v interface{}) { if err := s.encode.Encode(v); err != nil { s.printer.Send("sendReply error: err=%s\n", err) } } func (s *SlaveState) slaveWorker(id int) { var stats WorkerStat var totalLatency time.Duration = 0 var totalCount = 0 var buf []byte lastBufSize := int64(0) stats.Histogram = DistroInit(nil, "") tick := time.Tick(time.Second) boom := time.After(s.params.Runtime) stats.LowResponse = time.Hour * 24 for s.threadRunning { select { case <-tick: s.statChan <- &stats case <-boom: stats.AvgResponse = totalLatency / time.Duration(totalCount) s.workerCmpt <- stats return default: ad := s.oneAD() if ad.len != lastBufSize { lastBufSize = ad.len buf = make([]byte, lastBufSize) } start := time.Now() switch ad.op { case ReadBaseType: stats.Reads++ stats.BytesRead += ad.len if _, err := s.targetDev.ReadAt(buf, ad.blk); err != nil { stats.ReadErrors++ } case WriteBaseType: stats.Writes++ stats.BytesWritten += ad.len if _, err := s.targetDev.WriteAt(buf, ad.blk); err != nil { stats.WriteErrors++ } } latency := time.Now().Sub(start) if latency < stats.LowResponse { stats.LowResponse = latency } if latency > stats.HighResponse { stats.HighResponse = latency } stats.Histogram.Aggregate(latency) totalCount++ totalLatency += latency } } stats.AvgResponse = totalLatency / time.Duration(totalCount) s.workerCmpt <- stats s.printer.Send("[%d] thread halted\n", id) } func (s *SlaveState) oneAD() AccessData { ad := AccessData{} section := rand.Intn(100) /* * Looping through a linked list in a high call method isn't a good * idea normally. Luckily accessPattern normally is a small list (<3) * that will not add much to the overhead. */ for e := s.params.accessPattern.Front(); e != nil; e = e.Next() { access := e.Value.(AccessPattern) // If the current requested section is less than the percentage // of the section being worked on we've found range to work with. // Otherwise, subtract the current range from the section and // go to the next one. if access.sectionPercent > section { ad.len = access.blkSize // Generate the block number for the next request. switch access.opType { case ReadSeqType, WriteSeqType, RwseqType: access.lastBlk += access.blkSize if access.lastBlk >= access.sectionEnd { access.lastBlk = access.sectionStart } ad.blk = access.lastBlk case ReadRandType, WriteRandType, RwrandType: randBlk := rand.Int63n((access.sectionEnd - access.sectionStart - ad.len) / 512) ad.blk = randBlk*512 + access.sectionStart access.lastBlk = ad.blk default: fmt.Printf("Invalid opType=%d ... should be impossible", access.opType) os.Exit(1) } // We get a copy of the element stored in the list. So, update the element // with any changes that have been made. e.Value = access // Now set the op type. switch access.opType { case ReadRandType, ReadSeqType: ad.op = ReadBaseType case WriteRandType, WriteSeqType: ad.op = WriteBaseType case RwseqType, RwrandType: if rand.Intn(100) < access.readPercent { ad.op = ReadBaseType } else { ad.op = WriteBaseType } } break } else { section -= access.sectionPercent } } return ad }
C#
UTF-8
1,087
2.625
3
[]
no_license
using UnityEngine; /// <summary> /// Script that will teleport the Kid at the Player's location /// </summary> public class Spawn : MonoBehaviour { //Objects public AudioClip laugh; //Variables public float x = 18; public float y = 30; public float z = -28; public int timer = 0; //Use this for initialization private void Start() { timer = 0; } //Update is called once per frame private void Update() { //Check if the timer is more than 20 seconds and teleport the Kid to the Player if(timer*Time.deltaTime > 20) { transform.SetPositionAndRotation(new Vector3(x, y, z), Quaternion.Euler(0,0,0)); GetComponent<CheckSee>().killCount = 0; GetComponent<CheckSee>().safeCount = 0; GetComponent<CheckSee>().enabled = true; GetComponent<AudioSource>().clip = laugh; GetComponent<AudioSource>().Play(); GetComponent<Spawn>().enabled = false; } else { ++timer; } } }
Python
UTF-8
414
3.0625
3
[]
no_license
# -- upsolve N = int(input()) P = list(map(int, input().split())) # 後ろから見ていって、P_n-1 > P_n < P_n+1となるnを探す(ここではj) j = N - 2 while P[j] < P[j + 1]: j -= 1 # P_n < P_kを満たす最小のkを探す k = N - 1 while P[j] < P[k]: k -= 1 # 入れ替える P[j], P[k] = P[k], P[j] # 性質を満たすnまで表示+残りは降順で表示 print(*P[: j + 1], *P[:j:-1])
Java
UTF-8
1,518
2.484375
2
[]
no_license
package com.project.sms.app; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class Inbox extends AppCompatActivity { ListView list; SimpleCursorAdapter adapter; Cursor cursor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inbox); getSupportActionBar().setDisplayHomeAsUpEnabled(true); list = (ListView) findViewById(R.id.listViewInbox); //Create an in box uri Uri uri = Uri.parse("content://sms/inbox"); //List the columns required. String[] reqCols = new String[]{"_id", "address", "body"}; //Get the content resolver object which will deal with the content provider. ContentResolver contentResolver = getContentResolver(); //Fetch the inbox sms messages from built in content resolver. cursor = contentResolver.query(uri,reqCols,null,null,null); //attach the cursor to the adapter and display the same to the list view. adapter = new SimpleCursorAdapter(this,R.layout.list_item_layout,cursor, new String[]{"body","address"}, new int[]{R.id.textViewBody, R.id.textViewAddress}); //set the adapter to our list view. list.setAdapter(adapter); } }
Python
UTF-8
130
2.828125
3
[]
no_license
f = open('out/all_titles_processed.txt', 'r') print(f) titles = f.read() for t in titles.split("'b"): print(str(t.strip()))
Python
UTF-8
1,261
3.078125
3
[]
no_license
# 给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。 # # # # 示例 1: # # # 输入:nums = [1,5,11,5] # 输出:true # 解释:数组可以分割成 [1, 5, 5] 和 [11] 。 # # 示例 2: # # # 输入:nums = [1,2,3,5] # 输出:false # 解释:数组不能分割成两个元素和相等的子集。 # # # # # 提示: # # # 1 <= nums.length <= 200 # 1 <= nums[i] <= 100 # # Related Topics 动态规划 # 👍 813 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def canPartition(self, nums): sums = sum(nums) if sums % 2 == 1: return False dp = [[False] * (sums + 1) for _ in range(len(nums + 1))] for i in range(len(nums + 1)): dp[i][0] = True for i in range(1, len(nums + 1)): for j in range(1, sums + 1): if j - nums[i - 1] < 0: dp[i][j] = dp[i - 1][j] else: dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]] return dp[-1][-1] # leetcode submit region end(Prohibit modification and deletion)
Java
UTF-8
766
3.796875
4
[]
no_license
package Exception; public class CustomException { static void validate(int salary) throws SalaryException{ if(salary < 2000) { throw new SalaryException("You need to work hard!"); } if (salary >= 2000 && salary <= 5000) { throw new SalaryException("You're salary is somewhat good"); } if (salary > 5100 && salary < 9000) { throw new SalaryException("You're salary is very good!"); } else { System.out.println("Excellent salary"); } } public static void main(String[] args) { try { validate(8000); } catch(Exception m) { System.out.println("Exception occured: " + m.getMessage()); } System.out.println("rest of code..."); } } class SalaryException extends Exception{ SalaryException (String s){ super(s); } }
SQL
UTF-8
433
2.8125
3
[]
no_license
SELECT trd_date, st_id, avg(op) avg_op, std(op) std_op, avg(hp) avg_hp, std(hp) std_hp, avg(lp) avg_lp, std(lp) std_lp, avg(cp) avg_cp, std(cp) std_cp, avg(cnt) avg_cnt, std(cnt) std_cnt, avg(amt) avg_amt, std(amt) std_amt, corr(cp,cnt) cp_cnt_corr, corr(amt,cnt) amt_cnt_corr FROM st.min_1 GROUP BY trd_date, st_id;
SQL
UTF-8
1,329
3.0625
3
[ "MIT" ]
permissive
-- --- -- SECTION TEST DATA -- inserts a selection of sections for the courses offered -- --- INSERT INTO section ( created_by, course_id, year, term, period, active ) VALUES ( 1, 1, '2014', 'Trimester 1 - Fall', 'D', 1 ), ( 1, 1, '2014', 'Trimester 2 - Winter', 'G', 1 ), ( 1, 2, '2014', 'Trimester 2 - Winter', 'D', 1 ), ( 1, 2, '2015', 'Trimester 3 - Spring', 'G', 1 ), ( 1, 3, '2014', 'Trimester 1 - Fall', 'A', 1 ), ( 1, 3, '2015', 'Trimester 3 - Spring', 'A', 1 ), ( 1, 4, '2014', 'Trimester 1 - Fall', 'F', 1 ), ( 1, 4, '2014', 'Trimester 2 - Winter', 'F', 1 ), ( 1, 4, '2014', 'Trimester 2 - Spring', 'F', 1 ), ( 1, 5, '1982', 'Trimester 1 - Fall', 'A', 0 ); -- QUESTION AND ANSWER -- --- -- ASSESSMENT TEST DATA -- inserts a selection of assessments -- --- /* INSERT INTO assessment ( created_by, type, section_id, name, active ) VALUES (1, 'problem_set', '1', 'ps0', 1), (1, 'problem_set', '2', 'ps0', 1),*/
Python
UTF-8
102
3.203125
3
[]
no_license
word = input().split("WUB") org = [] for x in word: if len(x)>0: org.append(x) print(*org, sep=' ')
Python
UTF-8
347
4.0625
4
[]
no_license
def calculator(num1,num2): add = num1+num2 subtract = num1-num2 multiply = num1*num2 divide = num1/num2 print("sum:", add, " difference:", subtract, " product:", multiply, " quotient:", int(divide)) number1 = input("please enter first number") number2 = input("please enter second number") calculator(int(number1),int(number2))
Go
UTF-8
2,997
3.15625
3
[]
no_license
// 56 ms, faster than 96.77% // 限制条件 : // 1. 统计每个方块的四个角出现的次数,一定注意,可能次数不不不不不是 1,2,4,可能有3的情况 // 2. 组合后的大面积与小面积相同(注意,不能只看这个条件,比如覆盖面积和缺失面积相同的时候也满足这个条件) // 3. 次数为1的四个点是最大最小的四个点 // [[0,-1,1,0],[0,0,1,1],[0,1,1,2],[0,2,1,3]] // [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] // [[1,1,2,2],[1,1,2,2],[2,1,3,2]] // [[0,0,3,3],[1,1,2,2],[1,1,2,2]] // [[0,0,1,1],[0,0,2,1],[1,0,2,1],[0,2,2,3]] // [[0,0,1,1],[0,1,1,2],[0,2,1,3],[1,0,2,1],[1,0,2,1],[1,2,2,3],[2,0,3,1],[2,1,3,2],[2,2,3,3]] func isRectangleCover(rectangles [][]int) bool { //map 记录各个角出现的次数,因为是偶数次,保留奇数次,所以bool可行 minmaxAngles := getAngles(rectangles[0]) // 记录四个角 // 注意:此处不用string当作key,而是 x<<16+y (int) 注意,x<<16|y坐标可能是负值,导致出错 numMap := make(map[int]int, 0) sumArea := 0 for _, v := range rectangles { sumArea += getArea(v) a := getAngles(v) numMap[a[0][0]<<16+a[0][1]]++ numMap[a[1][0]<<16+a[1][1]]++ numMap[a[2][0]<<16+a[2][1]]++ numMap[a[3][0]<<16+a[3][1]]++ if a[0][0] <= minmaxAngles[0][0] && a[0][1] <= minmaxAngles[0][1] { // ld minmaxAngles[0][0] = a[0][0] minmaxAngles[0][1] = a[0][1] } if a[1][0] >= minmaxAngles[1][0] && a[1][1] >= minmaxAngles[1][1] { // rt minmaxAngles[1][0] = a[1][0] minmaxAngles[1][1] = a[1][1] } if a[2][0] <= minmaxAngles[2][0] && a[2][1] >= minmaxAngles[2][1] { // lt minmaxAngles[2][0] = a[2][0] minmaxAngles[2][1] = a[2][1] } if a[3][0] >= minmaxAngles[3][0] && a[3][1] <= minmaxAngles[3][1] { // rd minmaxAngles[3][0] = a[3][0] minmaxAngles[3][1] = a[3][1] } } cnt := 0 for k, v := range numMap { if v == 1 { cnt++ if k != minmaxAngles[0][0]<<16+minmaxAngles[0][1] && k != minmaxAngles[1][0]<<16+minmaxAngles[1][1] && k != minmaxAngles[2][0]<<16+minmaxAngles[2][1] && k != minmaxAngles[3][0]<<16+minmaxAngles[3][1] { return false } } else if v&1 != 0 { return false } } if cnt != 4 { return false } if sumArea != (minmaxAngles[1][0]-minmaxAngles[0][0])*(minmaxAngles[1][1]-minmaxAngles[0][1]) { return false } return true } // 计算面积 func getArea(a []int) int { return (a[2] - a[0]) * (a[3] - a[1]) } // 计算几个角 func getAngles(a []int) [][]int { // 角的坐标值可能超过byte return [][]int{ []int{a[0], a[1]}, //ld []int{a[2], a[3]}, //rt []int{a[0], a[3]}, //lt []int{a[2], a[1]}, //rd } } // func getAngles(a []int) [][]byte{// 角的坐标值可能超过byte // return [][]byte{ // []byte{byte(a[0])+'0', byte(a[1])+'0'},//ld // []byte{byte(a[2])+'0', byte(a[3])+'0'},//rt // []byte{byte(a[0])+'0', byte(a[3])+'0'},//lt // []byte{byte(a[2])+'0', byte(a[1])+'0'},//rd // } // }
Shell
UTF-8
474
3.234375
3
[ "MIT" ]
permissive
#!/usr/bin/env sh . "${bin}/include/all" connection_details="--defaults-extra-file=${connection_config}" "${mysql}" ${connection_details} -e"quit" >/dev/null code=${?} if [ "${code}" -eq 127 ]; then echo "${COLOR_RED}Could not find mysql binary.${COLOR_NC}" else if [ "${code}" -eq 1 ]; then echo "${COLOR_RED}Could not connect to database.${COLOR_NC}" else echo "${COLOR_GREEN}Successfully connected to database.${COLOR_NC}" fi fi exit ${code}
Python
UTF-8
2,186
2.890625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 12:59:21 2021 @author: Sonu """ import numpy as np import cv2 MIN_MATCH_COUNT = 4 img1 = cv2.imread('left2.jpg',0) #QueryImage img2 = cv2.imread('right2.jpg',0) #TrainImage #Initiating SIFT descriptor sift = cv2.xfeatures2d.SIFT_create() #Finding the keypoints and descriptors with SIFT kp1, des1 = sift.detectAndCompute(img1,None) kp2, des2 = sift.detectAndCompute(img2,None) FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) search_params = dict(checks = 50) #Match object using FLANN based matcher flann = cv2.FlannBasedMatcher(index_params, search_params) #Finding the top two matches for each descriptor using KNN match matches = flann.knnMatch(des1,des2,k=2) #Storing all the good matches as per Lowe's ratio test. good = [] for m,n in matches: if m.distance < 0.7*n.distance: good.append(m) #Homography is possible if atleast 4 sets of match are found if len(good)>MIN_MATCH_COUNT: print('yeah!!') #Finding the keypoints for good matches only src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2) dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2) #Finding the homography between keypoints of matching pair sets using RANSAC M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0) h,w = img1.shape #Warping the query image to align that image along the same plane as the train image. #Bringing both the images in the same perspective view. rectifiedimg1 = cv2.warpPerspective(img1, M, (w,h)) #Creating a stereoSGBM object stereo = cv2.StereoSGBM_create(numDisparities=96, blockSize=5, disp12MaxDiff=20, preFilterCap=16, uniquenessRatio=1, speckleWindowSize=100, speckleRange=20) #Finding the disparity map between the warped query and target image disp = stereo.compute(rectifiedimg1, img2) #Normalizing the dispaity map between the range of 0-255 norm_coeff = 255 / disp.max() disp = disp * norm_coeff / 255 cv2.imshow("disparity", disp) cv2.waitKey(10000) cv2.destroyAllWindows()
C
UTF-8
571
3.171875
3
[]
no_license
/*********************************************************** Function File: F_CI_F.C - MCA Lab Assignment - 3.11 Author: Deepak Shakya Date: 26-09-2009 Description: Stores the function that calculates the compound interest ***********************************************************/ float compound_interest(float int_amt, int years) { float ci=1.0; // Formula for Compound Interest // CI = P((100+R)/100)^Y while(years>0) { //Calculating the value for ((100+R)/100)^Y ci = ci * ((100+RATE)/100); years--; } ci = ci * int_amt; return ci; }
Python
UTF-8
1,034
2.640625
3
[]
no_license
import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) A.append(0) S = [A[0], A[1], A[2], sum(A[3:])] l = 0 r = 2 while r < N-1: if S[2] + A[r+1] <= S[3] - A[r+1]: S[2] += A[r+1] S[3] -= A[r+1] r += 1 else: break S2 = [S[0], S[1], S[2]+A[r+1], S[3]-A[r+1]] ans = min(max(S)-min(S), max(S2)-min(S2)) for m in range(2, N-2): S[1] += A[m] S[2] -= A[m] while r < N-1: if S[2] + A[r+1] <= S[3] - A[r+1]: S[2] += A[r+1] S[3] -= A[r+1] r += 1 else: break while l < m: if S[0] + A[l+1] <= S[1] - A[l+1]: S[0] += A[l+1] S[1] -= A[l+1] l += 1 else: break S1 = [S[0]+A[l+1], S[1]-A[l+1], S[2], S[3]] S2 = [S[0], S[1], S[2]+A[r+1], S[3]-A[r+1]] S3 = [S[0]+A[l+1], S[1]-A[l+1], S[2]+A[r+1], S[3]-A[r+1]] ans = min([ans, max(S)-min(S), max(S1)-min(S1), max(S2)-min(S2), max(S3)-min(S3)]) print(ans)
C
UTF-8
598
3.3125
3
[]
no_license
#include "Arquivao.h" void main(){ int op; int n; do{ printf("\nQuantos valores serão utilizados?\n"); scanf("%d",&n); }while((n>10)||(n<4) ); printf("Qual media deseja calcular?\n 1-Media aritmetica simples\n 2-Media aritmetica ponderada\n 3-Media geometrica\n 4-Media harmonica\n"); scanf("%d",&op); switch (op){ case 1: media1(n); break; case 2: media2(n); break; case 3: media3(n); case 4: media4(n); default: printf("Opção invalida\n"); break; } }
C#
UTF-8
2,640
3.625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* Neben den Delegate-Typen Func und Action gibt es den built-in Delegate-Typ Predicate. * Siehe MSDN Predicate<T> Delegate. * * Der Delegate-Typ Predicate (Aussage) ist in der Bibliothek mscorlib.dll im Namespace System * wie folgt definiert: * * public delegate bool Predicate<T>(T obj); * * Predicate<T> stellt einen generischen Delegate-Typ für Methoden dar, die prüfen, ob * verschiedene Kriterien für das angegebene Objekt vom Typ T erfüllt sind oder nicht. * Sind die Kriterien erfüllt, wird true andernfalls false zurückgeliefert. * Predicate nimmt nur einen Wert entgegen und gibt einen bool zurück */ namespace Delegates_05_Predicate { class Program { static bool IsOnlyUppercase(string txt) { foreach (char item in txt) { if (!char.IsUpper(item)) { return false; } } return true; } static bool IsLastCharN(string txt) => txt.EndsWith("n", true, null) ? true : false; static bool CheckString(Predicate<string> checkMethode, string text) { bool checkResult = checkMethode(text); //Console.WriteLine($"Der Check {checkMethode.Method.Name} (\"{text}\") liefert {checkResult}"); return checkResult; } static void Main(string[] args) { string txt = "Hallo Welt"; Console.WriteLine(IsLastCharN(txt)); Predicate<string> stringTest = IsOnlyUppercase; bool result = stringTest("NNN"); Console.WriteLine(result); stringTest = IsLastCharN; result = stringTest("Saufen"); Console.WriteLine(result); //Die Methode IsOnlyUppercase() als Argument verwenden result = CheckString(IsOnlyUppercase, txt); //Die Methode IsLastCharN() als Argument verwenden CheckString(IsLastCharN, "Saufen"); //Statt des Predicate kann auch eine Function verwendet werden. //Diese Function wird so häufig verwendet, dass dafür der eigene Delegate-Typ Predicate eigeführt wurde. //Bei Predicate muss der bool nicht angegeben werden da er sowieso einen bool zurückgibt. Func<string, bool> func = IsLastCharN; Console.WriteLine(func(txt)); func = IsOnlyUppercase; Console.WriteLine(func("AAAa")); Console.ReadKey(); } } }
Java
UTF-8
2,912
2.40625
2
[]
no_license
package com.testdvdrental.dvdrental.service; import com.testdvdrental.dvdrental.dto.ActorDto; import com.testdvdrental.dvdrental.entity.ActorEntity; import com.testdvdrental.dvdrental.exception.ResourceNotFoundException; import com.testdvdrental.dvdrental.repository.ActorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; @Service @Transactional public class ActorServiceImpl implements ActorService { @Autowired private ActorRepository repository; @Override public List<ActorEntity> getAllActor() { List<ActorEntity> actorEntities = repository.findAll(); return actorEntities; } @Override public ActorEntity getByActorId(Integer actor_id) throws ResourceNotFoundException { try { ActorEntity actorEntity = repository.findByActorId(actor_id); return actorEntity; } catch (Exception e) { throw new ResourceNotFoundException("Resource With Actor Id : " + actor_id + " Not Found!"); } } @Override public List<ActorEntity> getByFirstName(String first_name) { List<ActorEntity> actorEntities = repository.findByFirstName(first_name); return actorEntities; } @Override public List<ActorEntity> getByLastName(String last_name) { List<ActorEntity> actorEntities = repository.findByLastName((last_name)); return actorEntities; } @Override public List<ActorEntity> getByLastUpdate(Date date) { List<ActorEntity> actorEntities = repository.findByLastUpdate(date); return actorEntities; } @Override public List<ActorEntity> getSearch(String b, String c) { List<ActorEntity> actorEntities = repository.findByFirstNameContainingIgnoreCaseOrLastNameContainingIgnoreCase(b,c); return actorEntities; } @Override public ActorEntity postActor(ActorDto dto) { ActorEntity actorEntity = new ActorEntity(); actorEntity.setFirstName(dto.getFirstName()); actorEntity.setLastName(dto.getLastName()); Date date = new Date(); actorEntity.setLastUpdate(date); repository.save(actorEntity); return actorEntity; } @Override public ActorEntity putActor(Integer actor_id, ActorDto dto) { ActorEntity actorEntity = repository.findByActorId(actor_id); actorEntity.setFirstName(dto.getFirstName()); actorEntity.setLastName(dto.getLastName()); repository.save(actorEntity); return actorEntity; } @Override public ActorEntity deleteActor(Integer actor_id) { ActorEntity actorEntity = repository.findByActorId(actor_id); repository.delete(actorEntity); return actorEntity; } }
PHP
UTF-8
747
2.796875
3
[]
no_license
<?php /** * */ class Reservation { private $num,$dated,$datef,$voyage,$client; function __construct($b,$c,$v,$cl) { $this->dated = $b; $this->datef = $c; $this->voyage = $v; $this->client = $cl; } function getnums(){ return $this->num; function getdated(){ return $this->dated; } function getdatef(){ return $this->datef; } function getnumvoyage(){ return $this->voyage->getnumvoyage(); } function getcins(){ return $this->client->getcin(); } function setnums($a){ $this->num=$a; } function setdated($a){ $this->dated=$a; } function setdatef($a){ $this->datef=$a; } function setnumvoyage($a){ $this->voyage->setnumvoyag($a); } function setcins($a){ $this->client->setcin($a); } } ?>
PHP
UTF-8
3,083
2.515625
3
[]
no_license
<?php /** * * ..::.. * ..::::::::::::.. * ::'''''':''::''''':: * ::.. ..: : ....:: * :::: ::: : : :: * :::: ::: : ''' :: * ::::..:::..::.....:: * ''::::::::::::'' * ''::'' * * * NOTICE OF LICENSE * * This source file is subject to the Creative Commons License. * It is available through the world-wide-web at this URL: * http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US * If you are unable to obtain it through the world-wide-web, please send an email * to servicedesk@tig.nl so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade this module to newer * versions in the future. If you wish to customize this module for your * needs please contact servicedesk@tig.nl for more information. * * @copyright Copyright (c) Total Internet Group B.V. https://tig.nl/copyright * @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US */ namespace TIG\PostNL\Service\Shipment\Label\Merge; use TIG\PostNL\Service\Shipment\Label\File; use TIG\PostNL\Service\Pdf\Fpdi; use TIG\PostNL\Service\Pdf\FpdiFactory; class A4Merger implements MergeInterface { /** * @var Fpdi */ private $pdf; /** * @var File */ private $file; /** * @var int */ private $labelCounter = 0; /** * @param FpdiFactory $pdf * @param File $file */ public function __construct( FpdiFactory $pdf, File $file ) { $this->pdf = $pdf->create(); $this->pdf->addPage('L', 'A4'); $this->file = $file; } /** * @param Fpdi[] $labels * * @return Fpdi */ public function files(array $labels) { foreach ($labels as $label) { $this->increaseCounter(); // @codingStandardsIgnoreLine $filename = $this->file->save($label->Output('S')); $this->pdf->setSourceFile($filename); $pageId = $this->pdf->importPage(1); list($xPosition, $yPosition) = $this->getPosition(); $this->pdf->useTemplate($pageId, $xPosition, $yPosition); } $this->file->cleanup(); return $this->pdf; } /** * Adds the page if the counter is too high. */ private function increaseCounter() { $this->labelCounter++; if ($this->labelCounter > 4) { $this->labelCounter = 1; $this->pdf->addPage('L', 'A4'); } } /** * Get the position for the label based on the counter. * * @return array */ private function getPosition() { if ($this->labelCounter == 1) { return [0, 0]; } if ($this->labelCounter == 2) { return [0, Fpdi::PAGE_SIZE_A6_WIDTH]; } if ($this->labelCounter == 3) { return [Fpdi::PAGE_SIZE_A6_HEIGHT, 0]; } if ($this->labelCounter == 4) { return [Fpdi::PAGE_SIZE_A6_HEIGHT, Fpdi::PAGE_SIZE_A6_WIDTH]; } } }
Java
UTF-8
4,072
1.742188
2
[]
no_license
/** */ package petrinetv3Trace.Steps.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import petrinetv3Trace.Steps.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class StepsFactoryImpl extends EFactoryImpl implements StepsFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static StepsFactory init() { try { StepsFactory theStepsFactory = (StepsFactory)EPackage.Registry.INSTANCE.getEFactory(StepsPackage.eNS_URI); if (theStepsFactory != null) { return theStepsFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new StepsFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StepsFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case StepsPackage.PETRINETV3_NET_INITIALIZE: return createPetrinetv3_Net_Initialize(); case StepsPackage.PETRINETV3_NET_RUN: return createPetrinetv3_Net_Run(); case StepsPackage.PETRINETV3_NET_RUN_IMPLICIT_STEP: return createPetrinetv3_Net_Run_ImplicitStep(); case StepsPackage.PETRINETV3_NET_TICK_ENABLED_TRANSITIONS: return createPetrinetv3_Net_TickEnabledTransitions(); case StepsPackage.PETRINETV3_TRANSITION_FIRE: return createPetrinetv3_Transition_Fire(); case StepsPackage.ROOT_IMPLICIT_STEP: return createRootImplicitStep(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Petrinetv3_Net_Initialize createPetrinetv3_Net_Initialize() { Petrinetv3_Net_InitializeImpl petrinetv3_Net_Initialize = new Petrinetv3_Net_InitializeImpl(); return petrinetv3_Net_Initialize; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Petrinetv3_Net_Run createPetrinetv3_Net_Run() { Petrinetv3_Net_RunImpl petrinetv3_Net_Run = new Petrinetv3_Net_RunImpl(); return petrinetv3_Net_Run; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Petrinetv3_Net_Run_ImplicitStep createPetrinetv3_Net_Run_ImplicitStep() { Petrinetv3_Net_Run_ImplicitStepImpl petrinetv3_Net_Run_ImplicitStep = new Petrinetv3_Net_Run_ImplicitStepImpl(); return petrinetv3_Net_Run_ImplicitStep; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Petrinetv3_Net_TickEnabledTransitions createPetrinetv3_Net_TickEnabledTransitions() { Petrinetv3_Net_TickEnabledTransitionsImpl petrinetv3_Net_TickEnabledTransitions = new Petrinetv3_Net_TickEnabledTransitionsImpl(); return petrinetv3_Net_TickEnabledTransitions; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Petrinetv3_Transition_Fire createPetrinetv3_Transition_Fire() { Petrinetv3_Transition_FireImpl petrinetv3_Transition_Fire = new Petrinetv3_Transition_FireImpl(); return petrinetv3_Transition_Fire; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RootImplicitStep createRootImplicitStep() { RootImplicitStepImpl rootImplicitStep = new RootImplicitStepImpl(); return rootImplicitStep; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StepsPackage getStepsPackage() { return (StepsPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static StepsPackage getPackage() { return StepsPackage.eINSTANCE; } } //StepsFactoryImpl
Markdown
UTF-8
478
2.640625
3
[]
no_license
# travel_app ## Explanation: App works on an emulator, but it doesn't quite work on a real device. I'm not sure if I'm continuing this project, because the main objective was to learn how to work with fragments and how to make a single activity application. In addition, I've learned a lot about SQLite databases in Android and how to optimize image rendering within the application using external libraries. In conclusion, I'd say this was a very educational project for me.
C#
UTF-8
13,488
3.265625
3
[]
no_license
using System; using System.Linq; namespace Core { public class MatrixDouble { protected int _Col, _Row; public int Col => _Col; public int Row => _Row; protected double[,] _Data; public double[,] Data { get => _Data; set => _Data = value; } public MatrixDouble(int row, int col, double[] data = null) { _Col = col; _Row = row; _Data = new double[_Row,_Col]; if (data != null) { if (data.Length != row * col) { throw new ArgumentException("Matrix initialize error."); } for (int r = 0, dataPos = 0; r < _Row; ++r) { for (int c = 0; c < _Col; ++c) { _Data[r, c] = data[dataPos++]; } } } } public MatrixDouble(MatrixDouble matrix) { _Col = matrix._Col; _Row = matrix._Row; _Data = new double[_Row,_Col]; Array.Copy(matrix._Data, _Data, _Row * _Col); } public MatrixDouble(MatrixInt32 matrix) { _Col = matrix.Col; _Row = matrix.Row; _Data = new double[_Row,_Col]; for (int r = 0; r < _Row; ++r) { for (int c = 0; c < _Col; ++c) { _Data[r, c] = matrix.Data[r, c]; } } } public MatrixDouble Clone() => new MatrixDouble(this); public static MatrixDouble Zero(int row, int col) { var matrix = new MatrixDouble(row,col); for (int r = 0; r < row; ++r) { for (int c = 0; c < col; ++c) { matrix._Data[r, c] = 0; } } return matrix; } public static MatrixDouble Transpose(MatrixDouble x) { var matrix = new MatrixDouble(x._Col,x._Row); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < x._Col; ++c) { matrix._Data[c, r] = x._Data[r, c]; } } return matrix; } public MatrixDouble T => Transpose(this); public static MatrixDouble operator +(MatrixDouble x) => new MatrixDouble(x); public static MatrixDouble operator -(MatrixDouble x) { var matrix = new MatrixDouble(x._Row, x._Col); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < x._Col; ++c) { matrix._Data[r, c] = -x._Data[r, c]; } } return matrix; } public static MatrixDouble operator +(MatrixDouble x, MatrixDouble y) { if (x._Col != y._Col || x._Row != y._Row) throw new InvalidOperationException("Matrix size error."); var matrix = new MatrixDouble(x._Row, x._Col); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < x._Col; ++c) { matrix._Data[r, c] = x._Data[r, c] + y._Data[r, c]; } } return matrix; } public static MatrixDouble operator -(MatrixDouble x, MatrixDouble y) { if (x._Col != y._Col || x._Row != y._Row) throw new InvalidOperationException("Matrix size error."); var matrix = new MatrixDouble(x._Row, x._Col); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < x._Col; ++c) { matrix._Data[r, c] = x._Data[r, c] - y._Data[r, c]; } } return matrix; } public static MatrixDouble operator *(MatrixDouble x, MatrixDouble y) { if (x._Col != y._Row) throw new InvalidOperationException("Matrix size error."); var matrix = new MatrixDouble(x._Row, x._Col); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < y._Col; ++c) { matrix._Data[r, c] = 0; for (int i = 0; i < x._Col; ++i) { matrix._Data[r, c] += x._Data[r, i] * y._Data[i, c]; } } } return matrix; } public static MatrixDouble operator *(double C, MatrixDouble x) { var matrix = new MatrixDouble(x._Row, x._Col); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < x._Col; ++c) { matrix._Data[r, c] = C * x._Data[r, c]; } } return matrix; } public static MatrixDouble operator *(MatrixDouble x, double C) => C * x; public static MatrixDouble Abs(MatrixDouble x) { var matrix = new MatrixDouble(x._Row, x._Col); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < x._Col; ++c) { matrix.Data[r, c] = x._Data[r, c] >= 0 ? x._Data[r, c] : -x._Data[r, c]; } } return matrix; } public static MatrixInt32 Int(MatrixDouble x) { var matrix = new MatrixInt32(x._Row, x._Col); for (int r = 0; r < x._Row; ++r) { for (int c = 0; c < x._Col; ++c) { matrix.Data[r, c] = (int) x._Data[r, c]; } } return matrix; } public enum ConvolutionChoice { Valid,Same_FillZero,Same_EdgeCopy } private static bool AddUp = true; private static bool AddLeft = true; public MatrixDouble Convolution(MatrixDouble core, ConvolutionChoice choice, int step = 1) { MatrixDouble matrixH, matrixHV; if (choice == ConvolutionChoice.Same_EdgeCopy || choice == ConvolutionChoice.Same_FillZero) { if (step != 1) { throw new NotSupportedException("Only support valid convolution when step is 1."); } } int US, DS, LS, RS; switch (choice) { case ConvolutionChoice.Valid: break; case ConvolutionChoice.Same_FillZero: US = (core._Row - 1) / 2; DS = (core._Row - 1) / 2; LS = (core._Col - 1) / 2; RS = (core._Col - 1) / 2; if (US * 2 != core._Row) { if (AddUp) ++US; else ++DS; AddUp = !AddUp; } if (LS * 2 != core._Col) { if (AddLeft) ++LS; else ++RS; AddLeft = !AddLeft; } matrixH = HorizontalConcatenate(Zero(_Row,LS),this,Zero(_Row,RS)); matrixHV = VerticalConcatenate(Zero(US, matrixH._Col), matrixH, Zero(DS, matrixH._Col)); return matrixHV.Convolution(core, ConvolutionChoice.Valid); case ConvolutionChoice.Same_EdgeCopy: US = (core._Row - 1) / 2; DS = (core._Row - 1) / 2; LS = (core._Col - 1) / 2; RS = (core._Col - 1) / 2; if (US * 2 != core._Row) { if (AddUp) ++US; else ++DS; AddUp = !AddUp; } if (LS * 2 != core._Col) { if (AddLeft) ++LS; else ++RS; AddLeft = !AddLeft; } var AddL = Enumerable.Repeat(GetCol(0), LS); var AddR = Enumerable.Repeat(GetCol(-1), RS); var HorizontalList = AddL.Append(this).Concat(AddR).ToArray(); matrixH = HorizontalConcatenate(HorizontalList); var AddU = Enumerable.Repeat(GetRow(0), US); var AddD = Enumerable.Repeat(GetCol(-1), DS); var VerticalList = AddU.Append(matrixH).Concat(AddD).ToArray(); matrixHV = VerticalConcatenate(VerticalList); return matrixHV.Convolution(core, ConvolutionChoice.Valid); } #region Calculate valid convolution var resultMatrix = Zero(1 + (_Row - core._Row)/step, 1 + (_Col - core._Col)/step); int XDelta = core._Row - 1, YDelta = core._Col - 1, XLen = core._Row, YLen = core._Col; for (int px = 0, sx = 0; px < resultMatrix._Row; ++px, sx+=step) { for (int py = 0, sy = 0; py < resultMatrix._Col; ++py, sy+=step) { for (int x = 0; x < XLen; ++x) { for (int y = 0; y < YLen; ++y) { resultMatrix._Data[px, py] += _Data[sx + x, sy + y] * core._Data[XDelta - x, YDelta - y]; } } } } #endregion return resultMatrix; } public static MatrixDouble HorizontalConcatenate(params MatrixDouble[] matrixArray) { var ColSum = 0; foreach (var m in matrixArray) { if (m._Row != matrixArray[0]._Row) { throw new InvalidOperationException("Matrix size error."); } ColSum += m._Col; } var matrix = new MatrixDouble(matrixArray[0]._Row, ColSum); var ColPos = 0; foreach (var m in matrixArray) { for (int c = 0; c < m._Col; ++c,++ColPos) { for (int r = 0; r < m._Row; ++r) { matrix._Data[r, ColPos] = m._Data[r, c]; } } } return matrix; } public static MatrixDouble VerticalConcatenate(params MatrixDouble[] matrixArray) { var RowSum = 0; foreach (var m in matrixArray) { if (m._Col != matrixArray[0]._Col) { throw new InvalidOperationException("Matrix size error."); } RowSum += m._Row; } var matrix = new MatrixDouble(RowSum, matrixArray[0]._Col); var RowPos = 0; foreach (var m in matrixArray) { for (int r = 0; r < m._Row; ++r,++RowPos) { for (int c = 0; c < m._Col; ++c) { matrix._Data[RowPos, c] = m._Data[r, c]; } } } return matrix; } public MatrixDouble GetRow(int row) => GetRow(row, row); public MatrixDouble GetRow(int begin, int end) { if (begin > end) { throw new ArgumentException("Begin position should not be large than end."); } if (begin < 0) begin = _Row + begin; if (end < 0) end = _Row + end; if (begin < 0 || begin >= _Row || end < 0 || end >= _Row) { throw new ArgumentException("Begin or end position exceed the range."); } var matrix = new MatrixDouble(end - begin + 1, _Col); for (int r = 0; r < matrix._Row; ++r) { for (int c = 0; c < matrix._Col; ++c) { matrix._Data[r, c] = _Data[r + begin, c]; } } return matrix; } public MatrixDouble GetCol(int row) => GetCol(row, row); public MatrixDouble GetCol(int begin, int end) { if (begin > end) { throw new ArgumentException("Begin position should not be large than end."); } if (begin < 0) begin = _Col + begin; if (end < 0) end = _Col + end; if (begin < 0 || begin >= _Col || end < 0 || end >= _Col) { throw new ArgumentException("Begin or end position exceed the range."); } var matrix = new MatrixDouble(_Row, end - begin + 1); for (int r = 0; r < matrix._Row; ++r) { for (int c = 0; c < matrix._Col; ++c) { matrix._Data[r, c] = _Data[r, c + begin]; } } return matrix; } } public class SquareMatrixDouble : MatrixDouble { public SquareMatrixDouble(int size, double[] data = null) : base(size, size, data: data) {} public static SizedMatrix Size(int size) => new SizedMatrix(size); public class SizedMatrix { private int _Size; public SizedMatrix(int size) { _Size = size; } public SquareMatrixDouble GetZero() { var matrix = new SquareMatrixDouble(_Size); for (int r = 0; r < _Size; ++r) { for (int c = 0; c < _Size; ++c) { matrix._Data[r, c] = 0; } } return matrix; } public SquareMatrixDouble GetOne() { var matrix = GetZero(); for (int i = 0; i < _Size; ++i) { matrix._Data[i, i] = 1; } return matrix; } } } }
Python
UTF-8
775
3.078125
3
[ "MIT" ]
permissive
class RestrictingWrapper(object): def __init__(self, wrappee, block): self._wrappee = wrappee self._block = block def __getattr__(self, attr): if attr in self._block: raise RestrictionError(attr) return getattr(self._wrappee, attr) class RestrictionError(Exception): pass if __name__ == '__main__': obj = type("obj", (), {}) obj.restricted_attr = object() obj.public_attr = object() wrapper = RestrictingWrapper(obj, ('restricted_attr', )) assert wrapper.public_attr == obj.public_attr try: wrapper.restricted_attr except RestrictionError: print("restricted_attr is restricted, you can't get it") else: raise RuntimeError("RestrictingWrapper is broken!")
C#
UTF-8
3,066
2.84375
3
[]
no_license
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace LceUnitTest { [TestClass] public class UnitTest1 { [TestMethod] public void TestDivisibleBy3() { //initialize LceLibrary.Lce lce = new LceLibrary.Lce(); List<int> inputList = new List<int> { 3, 6, 9 }; String actual; String expected = "fizz"; inputList.ForEach(i => { //Act actual = lce.ProcessLceForOneInt(i); //Assert/Verify Assert.AreEqual<String>(expected, actual, "DivisibleBy3"); }); } [TestMethod] public void TestDivisibleBy5() { //initialize LceLibrary.Lce lce = new LceLibrary.Lce(); List<int> inputList = new List<int> { 5, 10, 20 }; // Not 15 String actual; String expected = "buzz"; inputList.ForEach(i => { //Act actual = lce.ProcessLceForOneInt(i); //Assert/Verify Assert.AreEqual<String>(expected, actual, "DivisibleBy5"); }); } [TestMethod] public void TestDivisibleBy3And5() { //initialize LceLibrary.Lce lce = new LceLibrary.Lce(); List<int> inputList = new List<int> { 15, 30, 45 }; String actual; String expected = "fizzbuzz"; inputList.ForEach(i => { //Act actual = lce.ProcessLceForOneInt(i); //Assert/Verify Assert.AreEqual<String>(expected, actual, "DivisibleBy3And5"); }); } [TestMethod] public void TestNotDivisibleBy3And5() { //initialize LceLibrary.Lce lce = new LceLibrary.Lce(); List<int> inputList = new List<int> { 1, 2, 4 }; String actual; String expected = String.Empty; inputList.ForEach(i => { //Act actual = lce.ProcessLceForOneInt(i); expected = i.ToString(); //Assert/Verify Assert.AreEqual<String>(expected, actual, "DivisibleBy3And5"); }); } [TestMethod] public void TestConfigurableRules() { //initialize LceLibrary.Lce lce = new LceLibrary.Lce(); List<int> inputList = new List<int> { 2, 4 }; Dictionary<int, String> rules = new Dictionary<int, string>() { {2, "TestD2"}, {3, "TestD3"} }; String actual; String expected = "TestD2"; inputList.ForEach(i => { //Act actual = lce.ProcessLceForOneInt(rules, i); //Assert/Verify Assert.AreEqual<String>(expected, actual, "ConfigurableRules"); }); } } }
Java
UTF-8
14,724
1.9375
2
[]
no_license
package com.boyaa.mf.service.task; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.boyaa.base.hbase.HConnectionSingleton; import com.boyaa.base.hbase.MultiThreadQuery; import com.boyaa.base.utils.CsvUtil; import com.boyaa.base.utils.JSONUtil; import com.boyaa.mf.constants.Constants; import com.boyaa.mf.entity.task.ProcessInfo; import com.boyaa.mf.entity.task.ProcessStatusEnum; import com.boyaa.mf.entity.task.ProcessTypeEnum; import com.boyaa.mf.service.common.HbaseService; import com.boyaa.mf.service.common.HiveHbaseService; import com.boyaa.mf.service.common.HiveJdbcService; import com.boyaa.mf.util.CommonUtil; import com.boyaa.mf.util.HiveUtils; import com.boyaa.service.FileService; import com.boyaa.servlet.ContextServlet; import com.boyaa.servlet.ResultState; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Row; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; @Service public class HbaseProcessSerivce extends ProcessService { static Logger taskLogger = Logger.getLogger("taskLogger"); static Logger errorLogger = Logger.getLogger("errorLogger"); static Logger fatalLogger = Logger.getLogger("fatalLogger"); @Autowired private ProcessInfoService processInfoService; @Autowired private HiveJdbcService hiveJdbcService; @Autowired private HiveHbaseService hiveHbaseService; @Autowired private HbaseService hbaseService; @Override public ResultState execute(ProcessInfo processInfo) { taskLogger.info("hbase查询流程开始执行,type="+processInfo.getType()); if(processInfo.getType()!=null && processInfo.getType().intValue()==ProcessTypeEnum.HBASE_MULTI_QUERY.getValue()){ return executeHbaseMultiQueryProcess(processInfo); }else if(processInfo.getType()!=null && processInfo.getType().intValue()==ProcessTypeEnum.HBASE_SCAN.getValue()){ return executeHbaseScanProcess(processInfo); }else if(processInfo.getType()!=null && processInfo.getType().intValue()==ProcessTypeEnum.HBASE_PUT.getValue()){ return executeHbaseInputProcess(processInfo); } return otherExecute(processInfo); } /** * 执行多线程查询hbase任务 * @param processInfo * @return */ private ResultState executeHbaseMultiQueryProcess(ProcessInfo processInfo) { taskLogger.info("多流程执行:"+processInfo.getId()); JSONObject json=null; String hbaseWFile = "process_"+processInfo.getId() + "_" + new Date().getTime()+".csv"; Map<ProcessInfo,Object> processInstance = ContextServlet.runningTaskInstance.get(processInfo.getTaskId()); if(processInstance==null){ processInstance = new HashMap<ProcessInfo, Object>(); } try { ProcessInfo pi = findById(processInfo.getDependId()); String pcolumnName = pi.getColumnName(); String operation = processInfo.getOperation(); json = JSONUtil.parseObject(operation); String fileColumn = json.getString("file_column"); String newFileColumn = ""; if(fileColumn.indexOf("|")!=-1){ String[] fileColumns = fileColumn.split("\\|"); newFileColumn = fileColumns[0].replace("#pcolumns#",pcolumnName); String[] linkParams = fileColumns[1].split(","); for(int i=0;i<linkParams.length;i++){ String[] links = linkParams[i].split("#"); if(links!=null && links.length==3){ newFileColumn = CommonUtil.replatStr(newFileColumn, links[0], links[2]); } } }else{ newFileColumn = fileColumn.replace("#pcolumns#",pcolumnName); } json.put("file_column", newFileColumn); if(StringUtils.isNotBlank(getTitle(processInfo.getId()))){ json.put("output_title", processInfo.getTitle()); } taskLogger.info("多线程执行json:"+json); MultiThreadQuery mtq = new MultiThreadQuery(HiveUtils.getLoadPath(Constants.FILE_DIR+pi.getPath()),Constants.FILE_DIR+hbaseWFile,json); processInstance.put(processInfo, mtq); ContextServlet.runningTaskInstance.put(processInfo.getTaskId(), processInstance); mtq.query(); //update ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_END.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo("执行完成"); updateProcess.setPath(hbaseWFile); updateProcess.setFileSize(FileService.getFileSize(Constants.FILE_DIR+hbaseWFile)); updateProcess.setId(processInfo.getId()); update(updateProcess); if(processInstance.containsKey(processInfo)){ processInstance.remove(processInfo); } return new ResultState(ResultState.SUCCESS,"执行成功",hbaseWFile); } catch (JSONException e) { errorLogger.error(processInfo.getOperation() + " error: " + e.getMessage()); ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_ERROR.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo("json参数出错:"+e.getMessage()); updateProcess.setId(processInfo.getId()); update(updateProcess); return new ResultState(ResultState.FAILURE,"json参数出错:"+e.getMessage(),null); } } /** * 执行hbase scan查询任务 * @param processInfo * @return */ private ResultState executeHbaseScanProcess(ProcessInfo processInfo) { JSONObject json = null; try { String fileName = "process_"+processInfo.getId() + "_" + new Date().getTime()+".csv"; String path = Constants.FILE_DIR + fileName; json = JSONUtil.parseObject(processInfo.getOperation()); if(StringUtils.isNotBlank(getTitle(processInfo.getId()))){ json.put("output_title", processInfo.getTitle()); } Map<ProcessInfo,Object> processInstance = ContextServlet.runningTaskInstance.get(processInfo.getTaskId()); if(processInstance==null){ processInstance = new HashMap<ProcessInfo, Object>(); } processInstance.put(processInfo, hbaseService); ContextServlet.runningTaskInstance.put(processInfo.getTaskId(), processInstance); ResultState rs = hbaseService.scanData(json,path); if(rs.getOk().intValue()==ResultState.SUCCESS){ //update ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_END.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo("执行完成"); updateProcess.setPath(fileName); updateProcess.setFileSize(FileService.getFileSize(Constants.FILE_DIR+fileName)); updateProcess.setId(processInfo.getId()); update(updateProcess); }else{//这个判断暂时没进行 ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_ERROR.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo(rs.getMsg()); updateProcess.setId(processInfo.getId()); update(updateProcess); } return new ResultState(ResultState.SUCCESS,"执行成功",fileName); } catch (JSONException e) { errorLogger.error(json + " error: " + e.getMessage()); ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_ERROR.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo("json参数解析出错:"+e.getMessage()); updateProcess.setId(processInfo.getId()); update(updateProcess); return new ResultState(ResultState.FAILURE,"hbase导出出现异常",null); } } /** * 把数据插入到hbase中 * @param processInfo * @return */ private ResultState executeHbaseInputProcess(ProcessInfo processInfo) { taskLogger.info("插入hbase执行:"+processInfo.getId()); Map<ProcessInfo,Object> processInstance = ContextServlet.runningTaskInstance.get(processInfo.getTaskId()); if(processInstance==null){ processInstance = new HashMap<ProcessInfo, Object>(); } try { ProcessInfo pi = findById(processInfo.getDependId()); if(pi==null || StringUtils.isBlank(pi.getPath())){ return new ResultState(ResultState.FAILURE,"所依赖的流程不存在或者没有数据",null); } //{'table':'test_putdata','rowkey':'c0_5,c1_10,c2_10',column:'c0_int,c1_long,c2_string,c3_int'} JSONObject operJson = JSONUtil.parseObject(processInfo.getOperation()); String tableName = operJson.getString("table"); BufferedReader br = null; String line = null; String path = HiveUtils.getLoadPath(Constants.FILE_DIR+pi.getPath()); try { br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf-8")); List<Row> rows = new ArrayList<Row>(); while((line = br.readLine()) != null) { String[] values = line.split(","); String[] columns = pi.getColumnName().split(","); String rowkey = getRowKey(operJson.getString("rowkey").split(","),columns,values); Put put = new Put(rowkey.getBytes()); String[] inputColumns = operJson.getString("column").split(","); for(int i=0;i<inputColumns.length;i++){ String[] columnInfo = inputColumns[i].split("\\|"); String value = getValue(columnInfo[0],columns,values); put.addColumn(com.boyaa.base.utils.Constants.COLUMN_FAMILY_BYTE,Bytes.toBytes(columnInfo[0]),convertTo(columnInfo[1],value,"0")); } rows.add(put); if(rows.size()==1000){ putData(tableName,rows); rows.clear(); rows = new ArrayList<Row>(); } } if(rows.size()>0){ putData(tableName,rows); rows.clear(); } } catch (Exception e) { errorLogger.error("插入数据异常: " + e.getMessage()); return new ResultState(ResultState.FAILURE,"插入数据异常: " + e.getMessage()); } finally { try { if(br != null) br.close(); } catch (IOException e) { errorLogger.error("could not close the reader object: " + e.getMessage()); } } return new ResultState(ResultState.SUCCESS,"执行成功"); } catch (JSONException e) { errorLogger.error(processInfo.getOperation() + " error: " + e.getMessage()); ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_ERROR.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo("json参数出错:"+e.getMessage()); updateProcess.setId(processInfo.getId()); update(updateProcess); return new ResultState(ResultState.FAILURE,"json参数出错:"+e.getMessage(),null); } } private String getValue(String column, String[] columns, String[] values) { String value = null; for(int j=0;j<columns.length;j++){ if(column.trim().equals(columns[j].trim())){ value = values[j]; break; } } return value; } private void putData(String tableName,List<Row> rows){ Table table = null; try { table = HConnectionSingleton.create().getTable(TableName.valueOf(tableName)); table.batch(rows,null); } catch (Exception e) { errorLogger.error(e.getMessage()); throw new RuntimeException(e.getMessage()); } finally{ if(table!=null){ try { table.close(); } catch (IOException e) { errorLogger.error(e.getMessage()); } } } } private String getRowKey(String[] keys, String[] columns, String[] values) { String rowkey=""; for(int i=0;i<keys.length;i++){ String name = keys[i].split("\\|")[0]; String size = keys[i].split("\\|")[1]; for(int j=0;j<columns.length;j++){ if(name.trim().equals(columns[j].trim())){ rowkey += StringUtils.leftPad(values[j], Integer.parseInt(size), "0"); break; } } } return rowkey; } public static byte[] convertTo(String type, String value, String defaultValue) { //String v = defaultValue == null ? value : defaultValue; String v = (value==null?defaultValue:value).trim(); byte[] b = null; if("int".equalsIgnoreCase(type)) b = Bytes.toBytes(Integer.valueOf(v)); else if("long".equalsIgnoreCase(type)) b = Bytes.toBytes(Long.valueOf(v)); else if("float".equalsIgnoreCase(type)) b = Bytes.toBytes(Float.valueOf(v)); else if("double".equalsIgnoreCase(type)) b = Bytes.toBytes(Double.valueOf(v)); else b = Bytes.toBytes(v); return b; } /** * hbase入库流程 * @param processInfo * @param json * @return */ public ResultState insert(ProcessInfo processInfo, JSONObject json){ try { String tableName = null; if(json.containsKey("tname")){ tableName = json.getString("tname"); }else{ throw new Exception("param tname is null!"); } ProcessInfo dependProcess = processInfoService.findById(processInfo.getDependId()); String htableName = "temp_process_"+processInfo.getId(); String hcolumns = dependProcess.getColumnName(); String loadDataPath = HiveUtils.getLoadPath(Constants.FILE_DIR + dependProcess.getPath()); hiveJdbcService.createTable(htableName,HiveUtils.getHiveCreateTableColumn(hcolumns),loadDataPath); String hbcolumns = processInfo.getColumnName(); hiveHbaseService.hive2hbase(htableName, hcolumns, hbcolumns); String fileName = "process_"+processInfo.getId() + "_" + new Date().getTime()+".csv"; String path = Constants.FILE_DIR + fileName; StringBuffer hsql = new StringBuffer(); hsql.append("select ").append(HiveUtils.columsSpecialSymbols(hcolumns)).append(" from ").append(htableName); hiveJdbcService.findAndSave(hsql.toString(), CsvUtil.getPrint(path)); ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setId(processInfo.getId()); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_END.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo("执行完成"); updateProcess.setPath(fileName); updateProcess.setFileSize(FileService.getFileSize(path)); processInfoService.update(updateProcess); hiveJdbcService.dropTable(htableName); return new ResultState(ResultState.SUCCESS,"执行成功",fileName); } catch (Exception e) { errorLogger.error(e.getMessage()); ProcessInfo updateProcess = new ProcessInfo(); updateProcess.setStatus(ProcessStatusEnum.EXECUTION_ERROR.getValue()); updateProcess.setEndTime("now"); updateProcess.setLogInfo(e.getMessage()); updateProcess.setId(processInfo.getId()); update(updateProcess); return new ResultState(ResultState.FAILURE, e.getMessage(), null); }finally{ if(hiveJdbcService!=null){ hiveJdbcService.close(); } if(hbaseService!=null){ hbaseService.close(); } } } }
Python
UTF-8
2,573
2.96875
3
[]
no_license
from time import time def get_joker_positions(word): positions = [0] * len(word) queue = [""] prev_q = [""] most_right_subword_end = dict() # [{} for i in range(len(word)+1)] for i in range(len(word)): new_q = [subword+word[i] for subword in queue if len(subword) < subword_len_petrova[CASE]] for subword in new_q: idx = most_right_subword_end.get(subword) if idx == i - len(subword) - 1: try: positions[i + 1] = 1 except: pass positions[idx + 1] = 1 if 0 <= idx - len(subword) < len(positions): positions[idx - len(subword)] = 1 most_right_subword_end[subword] = i new_q += [""] queue, new_q, prev_q = new_q, [], queue #print('MOST LENG', max([len(x) for x in most_right_subword_end])) return positions def clean_dict(dic, i): all_keys = list(dic.keys()) for key in all_keys: if dic[key] < i-len(key)-1: dic.pop(key) return dic def get_fibonacci_codewalk(depth): starts = [("2","1"),("3","1"),("3","2")] replace = dict() replace[starts[CASE][0]] = starts[CASE][0]+starts[CASE][1] replace[starts[CASE][1]] = starts[CASE][0] this_iter = starts[CASE][1] for i in range(depth): new_iter = "".join([replace[x] for x in this_iter]) this_iter = new_iter return this_iter def codewalk_to_string(codewalk): start = "aba" next_let = dict() next_let["ab"] = "c" next_let["ba"] = "c" next_let["ac"] = "b" next_let["ca"] = "b" next_let["bc"] = "a" next_let["cb"] = "a" for letter in codewalk: for i in range(int(letter)): start += next_let[start[-2:]] start += start[-2] return start subword_len_petrova = [5, 3, 7] CASE = 1 def main(): #for i in range(3): #f = open("ans.txt", "a+") for iteration in range(33, 50): t1 = time() print("Fibonacci word #" + str(CASE) + ". Iteration #" + str(iteration) + "\n") cwk = get_fibonacci_codewalk(iteration) word = codewalk_to_string(cwk) mask = get_joker_positions(word) print(len(mask)) #print(mask) count = mask.count(0) print("Dencity = "+str(count/len(word))+"\n") print("Time: {} sec".format(time() - t1)) #f.close() if __name__ == '__main__': main()
Python
UTF-8
2,823
2.53125
3
[]
no_license
# -*- coding:utf-8 -*- import sys import csv import json from bs4 import BeautifulSoup import js2xml from lxml import etree # Async model import aiohttp import asyncio from aiohttp import ClientSession # retry- setting import requests from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter s = requests.Session() retries = Retry(total=15, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504]) s.mount('https://', HTTPAdapter(max_retries=retries)) # write file section async def RunmberCheck(outPutFile: str): conn = aiohttp.TCPConnector(limit=5) session = aiohttp.ClientSession(connector=conn) # start to read file csvFile = open('booking-token.csv', 'r') dict_reader = csv.DictReader(csvFile) # start to write a file with open(outPutFile, mode='w') as csv_write_file: fieldnames = ["Confirmation#", "GAR_Rnumber"] writer = csv.DictWriter(csv_write_file, fieldnames=fieldnames) writer.writeheader() # for loop Getaroom_reservation_token for row in dict_reader: # row["uuid"], this will be the parameter url = 'https://www.getaroom.com/reservations/%s' % (row["number"]) try: response = s.get( url, headers={'Accept-Encoding': 'compress'}, verify=True) soup = BeautifulSoup(response.text, 'lxml') src = soup.select('head script')[6].string src_text = js2xml.parse(src, debug=False) src_tree = js2xml.pretty_print(src_text) selector = etree.HTML(src_tree) # <property name="rv_confirmation_code"> if len(selector.xpath("//property[@name = 'rv_confirmation_code']/string/text()")) > 0: content = selector.xpath( "//property[@name = 'rv_confirmation_code']/string/text()")[0] else: content = "maybe invalid token" except OSError as reason: print('file have error') print('the reason is %s' % str(reason)) content = str(reason) except TypeError as reason: print('function error?') print('the reason is %s' % str(reason)) content = str(reason) writer.writerow({ "Confirmation#": row["number"], "GAR_Rnumber": content }) print("Just processed Getaroom_reservation_token: " + row["number"]) csvFile.close() # excute function loop = asyncio.get_event_loop() loop.run_until_complete( RunmberCheck( outPutFile="Rnumber_4.17.2021.csv" ) ) loop.close()
C++
GB18030
1,394
3.953125
4
[]
no_license
/* * */ #include "stdio.h" //ȡֵȷм int getMax(int arr[], int len){ int i, max; max = arr[0]; for(i=1;i<len;i++) { if(arr[i]>max) max = arr[i]; } return max; } void count_Sort(int arr[], int len, int exp) { int i; int temp[len];//ʱ //ʮͰ int bucket[10] = { 0 }; for(i = 0; i < len; i++) bucket[(arr[i] / exp) % 10]++; // tempԪصλ for(i = 1; i < 10; i++) bucket[i] += bucket[i - 1]; //Ӻǰ׳temp for(i = len-1; i >= 0; i--) { temp[bucket[(arr[i] / exp) % 10 ] - 1] = arr[i]; bucket[(arr[i] / exp) % 10]--; } //ֵԭ for(i = 0; i < len; i++) arr[i] = temp[i]; } void radixSort(int arr[], int len) { int exp; int max = getMax(arr, len); for(exp = 1; max / exp > 0; exp *= 10) count_Sort(arr, len, exp); } int main(){ int arr[] = {2,1,9,5,3,2,1,0}; int len = (int)sizeof(arr)/sizeof(*arr); printf("ǰ:\n"); for(int i = 0; i < len; i++) { printf("%d ", arr[i]); } radixSort(arr, len); printf("\n:\n"); for(int i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\nlength:%d\n", len); return 0; }
C++
UTF-8
3,895
2.703125
3
[]
no_license
#pragma once #include "libtcod.hpp" #include "dungeonMap.h" #include "direction.h" #include "mapRectangle.h" #include <algorithm> #include <vector> /* TODO Implement "room" class for use in map generation, probably also later during gameplay e.g. for use with lineOfRooms function; return set of generated rooms so that you can fill out contents of rooms easily instead of leaving them empty or wasting lots of effort relocating them or writing overly specific versions of the function also use for quick bounds checking of room generation; lineOfRooms currently has no bounds checking for example improve fit of lineOfRooms rooms to actual underlying line; figure out number of rooms that fit to line and then center roughly on line, instead of centering first room on x1, y1 and just hoping last room winds up near x2,y2 fit is particularly atrocious for large rooms outsource tile defs to json? or too soon? not that hard, but harder to do right. needed for pretty generation of stuff like streets begin working towards implementing stuff you need to make a city; fitted versions of lineOfRooms full of apartments, apartment builders, intersection makers, shops alleys in lineOfrooms etc. regardless of all this, lineOfRooms looks like it has big potential for city roguelike. highfive! */ bool spaceshipGenerator(); //Meant to generate a random city/district layout bool cityGenerator(); //Recursive function to subdivide city interiors into buildings and streets void cityBSP(TCODRandom* mRNG, std::vector<mapRectangle> &lots, mapRectangle current); //Used to test possible city layout features bool cityTester(); //Builds rowhouses in the specified lot void rowhousesBuilder(TCODRandom* mRNG, mapRectangle rowhouse); //Randomly replaces individual tiles in designated area with newTile at specified chance of each replacement void randomFill(unsigned x, unsigned y, unsigned width, unsigned height, std::string newTile, int percent, TCODRandom* mRNG); //Similar, but never affects tiles that are not of the same type as targetTiles void randomFill(unsigned x, unsigned y, unsigned width, unsigned height, std::string newTile, std::string targetTiles, int percent, TCODRandom* mRNG); //Creates a rectangle in designated area with different tiles on border and interior void borderedRectangle(unsigned x, unsigned y, unsigned width, unsigned height, std::string border, std::string interior); //Creates a rectangle without touching the insides of the rectangle void borderBuilder(unsigned x, unsigned y, unsigned width, unsigned height, std::string border); //Creates a room with a door at a random point on the wall that isn't a corner //If doorWall is specified, places door on that wall of the room void oneDoorRoom(unsigned x, unsigned y, unsigned width, unsigned height, std::string border, std::string interior, std::string door, TCODRandom* mRNG, direction doorWall = NO_DIRECTION); //These functions are a WIP, and abandoned :/ //Meant to allow streets to run along diagonals for less structured-seeming city layouts //Creates a series of adjacent oneDoorRooms centered along a line //Thickness and roomSize are the dimensions of the room //Thickness is the dimension closer to perpendicular to the line (so increasing it makes the line thicker) //Roomsize is closer to parallel to the line, and so has less or no effect on the line's thickness //If doorwall is set, all rooms will have their one door on the specified wall //Otherwise, all rooms have a door on one of the two walls parallel to the line (or closer to parallel) void lineOfRoomsv2(int x1, int y1, int x2, int y2, unsigned thickness, unsigned roomSize, TCODRandom * mRNG, direction doorWall = NO_DIRECTION); void lineOfRooms(int x1, int y1, int x2, int y2, unsigned thickness, unsigned roomSize, TCODRandom * mRNG, direction doorWall = NO_DIRECTION);
Java
UTF-8
1,106
2.984375
3
[]
no_license
package com.core.aop; import java.util.HashMap; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.lang.time.StopWatch; /** * 记录方法的执行时间 * * @author ljs */ public class MethodTimeAdvice implements MethodInterceptor { /** * 拦截要执行的目标方法 */ public Object invoke(MethodInvocation invocation) throws Throwable { HashMap retMap = null; Long functionTime = 0l;// 调用方法时间 Object result = null; // 用 StopWatch 计时 StopWatch clock = new StopWatch(); clock.start(); // 计时开始 try { // 方法进行 result = invocation.proceed(); clock.stop();// 计时结束 functionTime = clock.getTime();// 获取方法的运行时间 if (result instanceof java.util.HashMap) { retMap = (HashMap) result; // 检查MAP中是否有该异常值,有的话抛出异常 if (retMap.get("Exception") != null) { throw new Exception(String.valueOf(retMap.get("Exception"))); } } } catch (Exception e) { } return result; } }
JavaScript
UTF-8
1,133
2.515625
3
[]
no_license
const {animate,dp,ease_cubicinout,lerp,between,color,golden,enframe,blur} = require('./animate'); function ease_linearinout(t) { return 1-2*Math.abs(t-0.5); } const SIZE = 6; const x_order = [0,3,2,1,4]; const y_order = [4,0,1,3,2]; const GAP = 20; const w = 100/SIZE; const g = GAP/SIZE; function draw(ctx,t1,t2) { ctx.fillRect(0,0,100,100); blur(t1,t2,ctx,dt => { const t = between(0.05,0.95,ease_linearinout(dt)); for(let x=0;x<SIZE;x++) { for(let y=0;y<SIZE;y++) { ctx.fillStyle = color(golden(360,360,y*SIZE+x),70,70); let dy = 0; let dx = 0; for(let i=0;i<SIZE-1;i++) { dx += ease_cubicinout(between(i/SIZE,(i+1/2)/SIZE,t))*(x<=x_order[(i+y)%x_order.length] ? g : 0); dy += ease_cubicinout(between((i+1/2)/SIZE,(i+1)/SIZE,t))*(y<=y_order[(i+x)%y_order.length] ? g : 0); } ctx.fillRect(x*w+g/2+dx,y*w+g/2+dy,w-g,w-g); } } }); } animate({ draw: draw, runtime: 5, fps: 60, size: 1000, makemovie: true });
Python
UTF-8
3,478
2.515625
3
[ "Unlicense" ]
permissive
from flask import Blueprint, render_template, request, redirect, url_for from foodtracker.models import Food, Log from foodtracker.extensions import db from datetime import datetime main = Blueprint('main', __name__) @main.route('/') def index(): logs = Log.query.order_by(Log.date.desc()).all() log_dates = [] for log in logs: proteins = 0 carbs = 0 fats = 0 calories = 0 for food in log.foods: proteins += food.proteins carbs += food.carbs fats += food.fats calories += food.calories log_dates.append({ 'log_date' : log, 'proteins' : proteins, 'carbs' : carbs, 'fats' : fats, 'calories' : calories }) return render_template('index.html', log_dates=log_dates) @main.route('/create_log', methods=['POST']) def create_log(): date = request.form.get('date') log = Log(date=datetime.strptime(date, '%Y-%m-%d')) db.session.add(log) db.session.commit() return redirect(url_for('main.view', log_id=log.id)) @main.route('/add') def add(): foods = Food.query.all() return render_template('add.html', foods=foods, food=None) @main.route('/add', methods=['POST']) def add_post(): food_name = request.form.get('food-name') proteins = request.form.get('protein') carbs = request.form.get('carbohydrates') fats = request.form.get('fat') food_id = request.form.get('food-id') if food_id: food = Food.query.get_or_404(food_id) food.name = food_name food.proteins = proteins food.carbs = carbs food.fats = fats else: new_food = Food( name=food_name, proteins=proteins, carbs=carbs, fats=fats ) db.session.add(new_food) db.session.commit() return redirect(url_for('main.add')) @main.route('/delete_food/<int:food_id>') def delete_food(food_id): food = Food.query.get_or_404(food_id) db.session.delete(food) db.session.commit() return redirect(url_for('main.add')) @main.route('/edit_food/<int:food_id>') def edit_food(food_id): food = Food.query.get_or_404(food_id) foods = Food.query.all() return render_template('add.html', food=food, foods=foods) @main.route('/view/<int:log_id>') def view(log_id): log = Log.query.get_or_404(log_id) foods = Food.query.all() totals = { 'protein' : 0, 'carbs' : 0, 'fat' : 0, 'calories' : 0 } for food in log.foods: totals['protein'] += food.proteins totals['carbs'] += food.carbs totals['fat'] += food.fats totals['calories'] += food.calories return render_template('view.html', foods=foods, log=log, totals=totals) @main.route('/add_food_to_log/<int:log_id>', methods=['POST']) def add_food_to_log(log_id): log = Log.query.get_or_404(log_id) selected_food = request.form.get('food-select') food = Food.query.get(int(selected_food)) log.foods.append(food) db.session.commit() return redirect(url_for('main.view', log_id=log_id)) @main.route('/remove_food_from_log/<int:log_id>/<int:food_id>') def remove_food_from_log(log_id, food_id): log = Log.query.get(log_id) food = Food.query.get(food_id) log.foods.remove(food) db.session.commit() return redirect(url_for('main.view', log_id=log_id))
Java
UTF-8
2,184
2.34375
2
[]
no_license
package com.demo.xf.filter; import org.springframework.core.annotation.Order; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * @Author: Xiong Feng * @Date: 2020/6/24 9:48 * @Description: 自定义过滤器,用于学习测试 */ //@WebFilter(filterName = "filter", urlPatterns = "/*", // initParams = { // @WebInitParam(name="URL_LIST", value = "classpath:config/filterConfig.properties") // }) @Order(1) public class CustomFilter implements Filter { private List list; @Override public void init(FilterConfig filterConfig){ String url = filterConfig.getInitParameter("URL_LIST"); this.list = Arrays.asList(url.split(",")); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("我是过滤器,我拦截了方法了"); HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; String uri = request.getRequestURI(); HttpSession session = request.getSession(); System.out.println("我拦截的路径是:"+request.getServletPath()+" 拦截的URI是:"+uri); if (list.contains(uri)){ if (session != null && session.getAttribute("token") != null){ if (session.getAttribute("token").equals("123")) { filterChain.doFilter(servletRequest, servletResponse); }else { response.sendRedirect("/toLogin"); } }else { response.sendRedirect("/index"); } }else { filterChain.doFilter(servletRequest, servletResponse); } } @Override public void destroy() { System.out.println("I AM Done"); } }
C++
UTF-8
1,078
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int election[32]; string parties[32]; int main() { string s; getline(cin, s); int t = atoi(s.c_str()); while(t--) { getline(cin, s); getline(cin, s); int n = atoi(s.c_str()); map<string, int> mt; for(int i = 0; i < n; i++) { string name, party; getline(cin, name); mt[name] = i; getline(cin, party); parties[mt[name]] = party; } getline(cin, s); int m = atoi(s.c_str()); memset(election, 0, sizeof(election)); for(int i = 0; i < m; i++) { string name; getline(cin, name); if(mt.count(name)) election[mt[name]]++; } int best = 0; for(int i = 1; i < n; i++) if(election[best] < election[i]) best = i; bool tie = false; for(int i = 0; i < n; i++) { if(i == best) continue; if(election[i] == election[best]) { tie = true; break; } } string ans = tie? "tie" : parties[best]; cout << ans << endl; if(t) cout << endl; } return 0; }
Go
UTF-8
563
2.625
3
[]
no_license
package main import( "html/template" "path/filepath" "net/http" ) type Page struct { Title string Body []byte } type vue struct{ Title string } type donne struct{ IsCo bool Name string Ar interface{} } func jointure(r *http.Request,w http.ResponseWriter,are donne,ar ...string){ var joins []string are.IsCo = isRegister(r) for _,ok := range ar { joins = append(joins,filepath.Join("static", ok)) } tmpl, _ := template.ParseFiles(joins...) tmpl.ExecuteTemplate(w, "layout", are) } func Title(r string)(v string){ v = "gopiko " return }
Markdown
UTF-8
3,146
3.0625
3
[]
no_license
--- layout: post title: 3D dinosaur scene date: 2018-05-08 permalink: /projects/dinosaur3D/ --- # 3D engine : dinosaur scene (Python / OpenGL4) _Contributors: Mathieu Tillet_ <hr /> This project was the final assignment for the **3D computer graphics** course. We were required to create a 3D engine, providing solutions for the modeling, rendering, animation and interaction of a prehistoric dinosaur scene, with animated and/or interactive elements. Click the image to see a small demo of the result: [![](/static/projects/dino/dino_demo_cover.jpg){: .center-image}](/static/projects/dino/dino_demo.mp4) I was responsible for : * Modeling : heightmap generated ground * Rendering : all light and texturing effects * Phong lighting model * Fog effect in the distance * Skybox * Water using DuDv and normal mapping, Fresnel effect, specular light, border smoothing * Animation : day/night sky keyframes animations * Gameplay : 3rd person camera tracking and character keyboard controls ## Controls The rendered scene shows a keyboard controlled raptor on an deserted island.\\ \\ The user have some basic controls over the scene : * **Raptor controls** :\\ The raptor can be controlled by the user via the keyboard : ZQSD movement, Shift to run and R to roar. The raptor cannot move into the water after a certain depth. * **Camera controls** :\\ The 3rd person camera automatically tracks the raptor movement and can be tweaked using the mouse to change zoom, inclination and rotate around the raptor. ## Rendering effects This project was the opportunity to implement and try several rendering effects, most of them dealt with in the shaders. **Fog**\\ To prevent abrupt disappearance of object when they go out of the camera viewing distance, a fog effect applies on all objects of the scene, making them seem to disappear gradually. **Water**\\ The water requires 3 pass to be rendered. The first two passes allow to store respectively everything above and below the water in buffers. These two textures are then used as reflection and refraction textures for final rendering.\\ For more realism, several effects have been added to the water. A normal map, determine the normal of the water surface and amplifies its relief. The water is also animated using a DuDv map, allowing to distort directly in the shader the textures, giving an illusion of movement. Similarly, a Fresnel effect has been added: depending on the camera's inclination with respect to the water, refraction and reflection more or less predominate in the final texture of the water. Effects of specular light have also been added. Finally, water depth is taken into account for several effects, in particular the softening of the edges: the closer we get to the water/land boundaries, the more transparent the water becomes, allowing a smooth transition with the terrain. ## Improvements to be added Some effects still need some work and might be added at a further time : * **Collision detection** : the current implementation is too slow and was therefore disabled until optimized. * **Shadow mapping**
C
UTF-8
5,105
4.0625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "linkedlist.h" // Initialize an empty list void initList(List* list_pointer){ list_pointer->head = NULL; list_pointer->tail = NULL; } // Create node containing item, return reference of it. Node* createNode(void* item){ Node* new_node = (Node*)malloc(sizeof(Node)); new_node->item = item; new_node->next = NULL; return new_node; } // Insert new item at the end of list. void insertAtTail(List* list_pointer, void* item){ Node * node; node = createNode((void*)item); //if list is empty. if(list_pointer->head == NULL) { list_pointer->head = node; list_pointer->tail = node; } else { list_pointer->tail->next = node; list_pointer->tail = list_pointer->tail->next; } /* Node* new_tail = createNode(item); if(list_pointer->head == NULL){ list_pointer->head = new_tail; list_pointer->tail = new_tail; } list_pointer->tail->next = new_tail; list_pointer->tail = new_tail; */ } // Insert item at start of the list. void insertAtHead(List* list_pointer, void* item){ Node * node; node = createNode(item); //if list is empty. if(list_pointer->head == NULL) { list_pointer->head = node; list_pointer->tail = node; } else { node->next = list_pointer->head; list_pointer->head = node; } /* Node* new_head = createNode(item); if(list_pointer->head == NULL){ list_pointer->head = new_head; list_pointer->tail = new_head; } new_head->next = list_pointer->head; list_pointer->head = new_head; */ } // Insert item at a specified index. void insertAtIndex(List* list_pointer, int index, void* item){ Node * to_insert; to_insert = createNode(item); int i = 0; Node* prev; Node* node = list_pointer->head; while (node != NULL) { if (i == index) { prev->next = to_insert; to_insert->next = node; return; } else if (i > index) { return; } else { i++; prev = node; node = node->next; } } /* Node* new_node = createNode(item); Node* current = list_pointer->head; if(index == 0){ insertAtHead(list_pointer, item); } else{ for(int i=0;i<index-1;i++){ current = current->next; } Node* left_node = current; Node* right_node = current->next; new_node->next = right_node; left_node->next = new_node; } */ } // Remove item from the end of list and return a reference to it void* removeTail(List* list_pointer){ Node * temp; int i = 0; void* item; if(list_pointer->tail == NULL) { // List is Empty return NULL; } else { temp = list_pointer->head; // Iterate to the end of the list while(temp->next != list_pointer->tail) { temp = temp->next; } item = list_pointer->tail->item; Node* old_tail = list_pointer->tail; list_pointer->tail = temp; list_pointer->tail->next = NULL; free(old_tail); } return item; /* if(list_pointer->head == NULL){ return list_pointer->head->item; } Node* current = (Node*) list_pointer->head; Node* after_current = current->next; while(after_current->next != NULL){ current = current->next; after_current = current->next; } void* removed = after_current->item; free(current->next); list_pointer->tail = current; return removed; */ } // Remove item from start of list and return a reference to it void* removeHead(List* list_pointer){ Node* current = (Node*)list_pointer->head; void* removed = current->item; current = current->next; free(list_pointer->head); list_pointer->head = current; return removed; } // Insert item at a specified index and return a reference to it void* removeAtIndex(List* list_pointer, int index){ int i = 0; Node* prev; Node* node = list_pointer->head; while (node != NULL) { if (i == index) { prev->next = node->next; void* item = node->item; free(node); return item; } else if (i > index) { // List is too short return NULL; } else { i++; prev = node; node = node->next; } } /* Node* current = list_pointer->head; if(index == 0){ void* removed = removeHead(list_pointer); return removed; } else{ for(int i=0;i<index-1;i++){ current = current->next; } Node* left_node = current; Node* remove_node = current->next; Node* right_node = remove_node->next; void* removed = remove_node->item; free(remove_node); left_node->next = right_node; return removed; } */ } // Return item at index void* itemAtIndex(List* list_pointer, int index){ Node* current = list_pointer->head; if(index == 0){ return current->item;; } else{ for(int i=0;i<index;i++){ current = current->next; } return current->item; } } void printList(List* list) { Node* node; // Handle an empty node. Just print a message if(list->head == NULL) { printf("\nEmpty List"); return; } // Start with the head. node = (Node*) list->head; printf("\nList: \n\n\t"); while(node != NULL) { printf("[ %p ]", node->item); // Move to the next node node = (Node*) node->next; if(node !=NULL) { printf("-->"); } } printf("\n\n"); }
Python
UTF-8
1,267
2.765625
3
[]
no_license
from random import randint import asyncio from asyncio_pool import AioPool from scapy.sendrecv import sr1, send, srp, srp1, sr from scapy.layers.inet import IP, ICMP, TCP,UDP def udp_task(): #随机产生一个1-65535的IP的id位 ip_id=randint(1,65535) #随机产生一个1-65535的icmp的id位 icmp_id=randint(1,65535) #随机产生一个1-65535的icmp的序列号 icmp_seq=randint(1,65535) pkt = IP(dst='192.168.214.129') / UDP(dport="53") # 发送包,超时时间为1秒,如果对端没有响应,则返回None,有响应则返回响应包 res = sr1( pkt, timeout=1, verbose=False )/b"hello" # res = sr1(pkt, timeout=1, verbose=False) return res async def udp_worker(): loop = asyncio.get_running_loop() res = await loop.run_in_executor(None, udp_task) print(res) return res async def spawn(work_num, size): """ @param: work_num 总任务数量 @param: size 每秒执行任务数 """ futures = [] async with AioPool(size=size) as pool: for i in range(work_num): f = await pool.spawn(udp_worker()) futures.append(f) if __name__ == "__main__": asyncio.get_event_loop().run_until_complete(asyncio.gather(spawn(1000000000000, 50)))
Java
UTF-8
1,071
2.0625
2
[]
no_license
package com; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger; import javax.sql.CommonDataSource; /** * * <p>Copyright: Copyright (c) 2017</p> * <p>Company: 熠道大数据</p> * @ClassName: ResourceManagement * @Description: TODO(管理器) * @author liuhonbin * @date 2018年4月24日 */ public class ResourceManagement extends LogResourceManagement { public ResourceManagement() { // TODO Auto-generated constructor stub } public <T> T unwrap(Class<T> iface) throws SQLException { // TODO Auto-generated method stub return null; } public boolean isWrapperFor(Class<?> iface) throws SQLException { // TODO Auto-generated method stub return false; } public void setLoginTimeout(int seconds) throws SQLException { // TODO Auto-generated method stub } public int getLoginTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } }
Java
UTF-8
1,035
2.234375
2
[ "MIT" ]
permissive
package org.serverct.parrot.parrotx.command; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.serverct.parrot.parrotx.utils.i18n.I18n; public interface PCommand extends CommandExecutor { String getPermission(); default String getDescription() { return "没有介绍"; } default String[] getHelp() { return new String[0]; } default String[] getParams(int arg) { return new String[0]; } boolean execute(CommandSender sender, String[] args); default String optionalParam(String param) { return I18n.color(" &7[&f" + param + "&7]"); } default String requiredParam(String param) { return I18n.color(" &7<&f" + param + "&7>"); } @Override default boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { return execute(sender, args); } }
C#
UTF-8
555
2.5625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MHWarBand : MonoBehaviour { // Use this for initialization void Start() { MHumanoid human = new MHumanoid(); MHumanoid enemy = new MHEnemy(); MHumanoid orc = new MHOrc(); // Notice how each Humanoid variable contains a reference to a different class in the inheritance hierarchy, // yet each of them calls the Humanoid Yell() method. human.Yell(); enemy.Yell(); orc.Yell(); } }
Java
UTF-8
5,957
2.234375
2
[ "Apache-2.0" ]
permissive
package com.example.oigami.twimpt; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.example.oigami.twimpt.twimpt.room.TwimptRoom; /** * Created by oigami on 2014/10/02 */ public class RoomListActivity extends ActionBarActivity { DataApplication globals; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.room_list_activity); globals = (DataApplication) this.getApplication(); Resources res = getResources(); /* type値をhashとして扱う ただし、TwimptRoomの中のhashはnullのまま */ //monologueは例外扱い TwimptRoom monologueRoom = new TwimptRoom(); monologueRoom.type = "monologue"; monologueRoom.name = res.getString(R.string.monologue_name); globals.twimptRooms.put(monologueRoom.type, monologueRoom); //publicは例外扱い TwimptRoom publicRoom = new TwimptRoom(); publicRoom.type = "public"; publicRoom.name = res.getString(R.string.public_name); globals.twimptRooms.put(publicRoom.type, publicRoom); getSupportActionBar().setTitle(res.getString(R.string.room_list_name)); final String[] members = { res.getString(R.string.public_name), res.getString(R.string.monologue_name), res.getString(R.string.recent_created_name), // res.getString(R.string.recent_opened_name), res.getString(R.string.recent_posted_name) }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, members); final ListView listView = (ListView) findViewById(R.id.room_list); // アダプターを設定します listView.setAdapter(adapter); // リストビューのアイテムがクリックされた時に呼び出されるコールバックリスナーを登録します listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(RoomListActivity.this, item, Toast.LENGTH_LONG).show(); String[] hash = {"public", "monologue"}; String roomHash; Intent intent; switch (position) { case 0: case 1: roomHash = hash[position]; intent = new Intent(RoomListActivity.this, RoomActivity.class); intent.putExtra(RoomActivity.INTENT_ROOM_NAME_HASH, roomHash); //intent.putExtra("keyword", globals.twimptRooms.get(now_room)); startActivity(intent); return; case 2: case 3: case 4: intent = new Intent(RoomListActivity.this, RecentRoomActivity.class); intent.putExtra(RecentRoomActivity.INTENT_ROOM_RECENT_NAME, members[position]); //intent.putExtra("keyword", globals.twimptRooms.get(now_room)); startActivity(intent); return; default: Toast.makeText(RoomListActivity.this, "未実装", Toast.LENGTH_LONG).show(); } } }); // リストビューのアイテムが選択された時に呼び出されるコールバックリスナーを登録します listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView) parent; // 選択されたアイテムを取得します String item = (String) listView.getSelectedItem(); Toast.makeText(RoomListActivity.this, item, Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.room_list, menu); // メニューの要素を追加 return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); SharedPreferences sharedPref; String accessToken, accessTokenSecret; switch (id) { case R.id.action_auth: sharedPref = getSharedPreferences("token", MODE_PRIVATE); accessToken = sharedPref.getString("access_token", ""); accessTokenSecret = sharedPref.getString("access_token_secret", ""); if (accessToken.equals("") || accessTokenSecret.equals("")) { Intent intent = new Intent(RoomListActivity.this, TwimptAuthActivity.class); startActivity(intent); } else { Toast.makeText(this, "すでに認証しています", Toast.LENGTH_LONG).show(); } break; case R.id.action_deauthentication: { sharedPref = getSharedPreferences("token", MODE_PRIVATE); accessToken = sharedPref.getString("access_token", ""); accessTokenSecret = sharedPref.getString("access_token_secret", ""); if (accessToken.equals("") || accessTokenSecret.equals("")) { Toast.makeText(this, "認証されていません", Toast.LENGTH_LONG).show(); } else { SharedPreferences.Editor e = sharedPref.edit(); e.clear(); e.commit(); Toast.makeText(this, "認証を解除しました", Toast.LENGTH_LONG).show(); } break; } } return super.onOptionsItemSelected(item); } }
Python
UTF-8
1,769
2.859375
3
[ "MIT" ]
permissive
from django.test import TestCase from books.models import Book, BookDetails class TestDeletingBook(TestCase): """When a book is deleted, the corresponding BookDetails object (if any) should be automatically deleted as well. This is not a built-in feature since Book has a OneToOneField for BookDetails, not the other way around. Possibly I should have set it up the other way. Who knows. In any case, I was able to work around this using a pre-delete signal.""" def setUp(self): details = BookDetails.objects.create( goodreads_id='1234', ) Book.objects.create( title="With Details", slug='with-details', details=details, ) Book.objects.create( title="Without Details", slug='without-details', ) def test_deleting_book_with_details(self): self.assertEqual( 1, BookDetails.objects.count(), '1 BookDetails object should exist before deletion' ) book = Book.objects.get(slug='with-details') book.delete() self.assertEqual( 0, BookDetails.objects.count(), 'No BookDetails objects should exist after deletion' ) def test_deleting_book_without_details(self): # This is a book not from goodreads self.assertEqual( 1, BookDetails.objects.count(), '1 BookDetails object should exist before deletion' ) book = Book.objects.get(slug='without-details') book.delete() self.assertEqual( 1, BookDetails.objects.count(), '1 BookDetails objects should still exist after deletion' )
Java
UTF-8
4,649
2.21875
2
[]
no_license
package com.zx.order.activity; import android.app.Activity; import android.support.design.widget.TabLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import com.zx.order.R; import org.xutils.view.annotation.ViewInject; import org.xutils.x; import java.util.ArrayList; /** * 预约 * 作者:JHJ * 日期:2018/10/12 9:26 * Q Q: 1320666709 */ public class ReservationCla { private ReservationHolder holder; private Activity mContext; // tab页面 private FrozenFruitsCla frozenCla; // 冻品 private FrozenFruitsCla fruitsCla; // 水果 private IndividualCla individualCla; // 单选预约 // 子布局 private View layFrozen, layFruits, layIndividual; // View列表 private ArrayList<View> views; // tab页面是否首次加载 private boolean firstLoadTab2 = true, firstLoadTab3 = true; private String[] str = new String[]{"冻品", "水果", "单项预约"}; public ReservationCla(Activity mContext, View layout) { this.mContext = mContext; holder = new ReservationHolder(); x.view().inject(holder, layout); } /** * 赋值 */ public void setDate() { initTabPageData(); initButtonTabData(); initViewPageData(); } /** * 初始化Tab页面信息 */ private void initTabPageData() { // 将要分页显示的View装入数组中 LayoutInflater viewLI = LayoutInflater.from(mContext); layFrozen = viewLI.inflate(R.layout.layout_public_list, null); layFruits = viewLI.inflate(R.layout.layout_public_list, null); layIndividual = viewLI.inflate(R.layout.layout_individual, null); //每个页面的view数据 views = new ArrayList<>(); views.add(layFrozen); views.add(layFruits); views.add(layIndividual); frozenCla = new FrozenFruitsCla(mContext, layFrozen); fruitsCla = new FrozenFruitsCla(mContext, layFruits); individualCla = new IndividualCla(mContext, layIndividual); } /** * 初始化顶部菜单 */ private void initButtonTabData() { holder.tlTop.addTab(holder.tlTop.newTab().setText(str[0])); holder.tlTop.addTab(holder.tlTop.newTab().setText(str[1])); holder.tlTop.addTab(holder.tlTop.newTab().setText(str[2])); } /** * 初始化ViewPage */ private void initViewPageData() { holder.vpReservation.setOnPageChangeListener(new MyOnPageChangeListener()); holder.vpReservation.setAdapter(mPagerAdapter); holder.vpReservation.setCurrentItem(0); holder.tlTop.setupWithViewPager(holder.vpReservation); frozenCla.setDate("0"); fruitsCla.setDate("1"); individualCla.setDate(); } /** * 填充ViewPager的数据适配器 */ private PagerAdapter mPagerAdapter = new PagerAdapter() { @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getCount() { return views.size(); } @Override public void destroyItem(View container, int position, Object object) { ((ViewPager) container).removeView(views.get(position)); } @Override public Object instantiateItem(View container, int position) { ((ViewPager) container).addView(views.get(position)); return views.get(position); } @Override public CharSequence getPageTitle(int position) { return str[position]; } }; /** * 页卡切换监听 */ private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener { @Override public void onPageSelected(int arg0) { /*if (arg0 == 1 && firstLoadTab2) { firstLoadTab2 = false; fruitsCla.setDate("2"); } else if (arg0 == 2 && firstLoadTab3) { firstLoadTab3 = false; individualCla.setDate(); }*/ } @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } } /** * 容纳器 */ private class ReservationHolder { @ViewInject(R.id.tlTop) private TabLayout tlTop; @ViewInject(R.id.vpReservation) private ViewPager vpReservation; } }
Java
UTF-8
1,361
2.671875
3
[]
no_license
package entity; public class Empl_Proj { private Long employeeId; private Long prijectId; public Empl_Proj(){} public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public Long getPrijectId() { return prijectId; } public void setPrijectId(Long prijectId) { this.prijectId = prijectId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((employeeId == null) ? 0 : employeeId.hashCode()); result = prime * result + ((prijectId == null) ? 0 : prijectId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Empl_Proj other = (Empl_Proj) obj; if (employeeId == null) { if (other.employeeId != null) return false; } else if (!employeeId.equals(other.employeeId)) return false; if (prijectId == null) { if (other.prijectId != null) return false; } else if (!prijectId.equals(other.prijectId)) return false; return true; } @Override public String toString() { return "Empl_Proj [employeeId=" + employeeId + ", prijectId=" + prijectId + "]"; } }
Rust
UTF-8
6,572
2.59375
3
[]
no_license
use crate::prelude::*; use super::util::*; use super::gfx::{Gfx, ui}; use crate::task::{PlayerCommand, ControllerMode, Promise}; use crate::gamestate::GameState; use crate::room::Room; pub struct MapView { door_views: [DoorView; 4], player_move_in_progress: bool, full_map_view_requested: bool, in_main_mode: bool, mode_change: Option<ControllerMode>, full_map_promise: Option<Promise<()>>, interact_hoverable: ui::Hoverable, close_map_hoverable: ui::Hoverable, } impl MapView { pub fn new(gfx: &mut Gfx) -> MapView { MapView { door_views: [ DoorView::new(Vec2::zero(), Direction::North), DoorView::new(Vec2::zero(), Direction::East), DoorView::new(Vec2::zero(), Direction::South), DoorView::new(Vec2::zero(), Direction::West), ], player_move_in_progress: false, full_map_view_requested: false, in_main_mode: true, mode_change: None, full_map_promise: None, interact_hoverable: Default::default(), close_map_hoverable: Default::default(), } } pub fn init(&mut self, gamestate: &GameState) { self.on_player_move(gamestate); } pub fn update(&mut self, gfx: &mut Gfx, gamestate: &GameState) { if self.full_map_view_requested { self.full_map_view_requested = false; gfx.camera.start_zoom_to(10.0); gfx.camera.start_rotate_to(PI/30.0, -PI/3.0); } match self.mode_change.take() { Some(ControllerMode::Main) => { gfx.camera.start_zoom_to(1.2); gfx.camera.start_rotate_to(PI/8.0, -PI/6.0); } Some(ControllerMode::Battle) | Some(ControllerMode::Merchant) => { gfx.camera.start_zoom_to(0.9); gfx.camera.start_rotate_to(PI/5.0, -PI/9.0); } None => {} } build_map(gfx, &gamestate.map); if self.player_can_move() { for view in self.door_views.iter_mut() { view.update(gfx); } let player_loc = gamestate.player.location; let current_room = gamestate.map.get(player_loc).unwrap(); if current_room.has_interactable() { use crate::controller::main::PlayerCommand::*; let size = Vec2::splat(0.2); let pos = location_to_world(player_loc).to_x0z() + Vec3::new(0.7, 0.01, 0.7); let region = ui::Region::new_ground(pos, size); let clicked = gfx.ui.update_interact_region( &mut self.interact_hoverable, &region, || Interact ); let color = ui::palette().map.color(self.interact_hoverable.state()); gfx.ui.quad(region, color); } } if self.full_map_promise.is_some() { let size = Vec2::splat(0.2); let pos = Vec3::new(0.11, -0.11, 0.0); let region = ui::Region::new(pos, size, ui::Context::ScreenTopLeft); let clicked = gfx.ui.update_immediate_interact_region( &mut self.close_map_hoverable, &region ); let color = ui::palette().map.color(self.close_map_hoverable.state()); gfx.ui.quad(region, color); if clicked { gfx.camera.start_zoom_rotate_to_default(); self.full_map_promise.take() .unwrap() .fulfill(()); } } } fn player_can_move(&self) -> bool { self.in_main_mode && !self.player_move_in_progress && self.full_map_promise.is_none() } pub fn on_mode_change(&mut self, mode: ControllerMode) { self.in_main_mode = matches!(mode, ControllerMode::Main); self.mode_change = Some(mode); } pub fn on_player_move(&mut self, gamestate: &GameState) { assert!(self.player_can_move()); self.player_move_in_progress = true; let world_pos = location_to_world(gamestate.player.location); let room = gamestate.map.get(gamestate.player.location).unwrap(); for view in self.door_views.iter_mut() { view.set_enabled(room.door(view.dir)); view.pos = world_pos; } } pub fn show_map(&mut self, promise: Promise<()>) { assert!(self.full_map_promise.is_none()); self.full_map_promise = Some(promise); self.full_map_view_requested = true; } // TODO: this whole deal would probably be better off as a future // what we're effectively waiting for is the player move animation to // finish, and for encounters to run pub fn on_awaiting_player_command(&mut self) { self.player_move_in_progress = false; } } fn build_room(gfx: &mut Gfx, pos: Vec2, room: Room, visited: bool) { let room_color = Color::grey(0.2); let visited_room_color = Color::grey(0.4); let color = if visited { visited_room_color } else { room_color }; gfx.ui.quad((pos.to_x0z(), Vec2::splat(1.0), ui::Context::Ground), color); for dir in room.iter_neighbor_directions().map(direction_to_offset) { let pos = pos + dir * 0.5; let size = dir + dir.perp() * 0.4; gfx.ui.quad((pos.to_x0z(), size, ui::Context::Ground), color); } } fn build_map(gfx: &mut Gfx, map: &crate::map::Map) { for (location, room) in map.iter() { let visited = map.visited(location); build_room(gfx, location_to_world(location), room, visited); } } fn direction_to_offset(d: Direction) -> Vec2 { match d { Direction::North => Vec2::from_y(-1.0), Direction::South => Vec2::from_y( 1.0), Direction::East => Vec2::from_x( 1.0), Direction::West => Vec2::from_x(-1.0), } } use super::gfx::ui::{Hoverable, HoverState}; struct DoorView { enabled: bool, pos: Vec2, dir: Direction, hoverable: Hoverable, } impl DoorView { fn new(pos: Vec2, dir: Direction) -> Self { Self { enabled: true, pos, dir, hoverable: Hoverable::new(0.1, 0.1), } } fn set_enabled(&mut self, enabled: bool) { self.enabled = enabled; if self.enabled { self.hoverable.reset(); } } fn position(&self) -> Vec2 { self.pos + direction_to_offset(self.dir) * 0.75 } fn update(&mut self, gfx: &mut Gfx) { if !self.enabled { return } use crate::controller::main::PlayerCommand::*; let dir = self.dir; let region = ui::Region::new_ground(self.position().to_x0z(), Vec2::splat(0.6)); gfx.ui.update_interact_region( &mut self.hoverable, &region, || match dir { Direction::North => GoNorth, Direction::East => GoEast, Direction::South => GoSouth, Direction::West => GoWest, } ); use HoverState::*; let size = match self.hoverable.state() { Idle => 0.6, HoverEnter(v) | HoverExit(v) => 0.6 + v*0.02, Hovering => 0.62, Clicked(v) => 0.6 + 0.02, }; let size = Vec2::splat(size); let color = ui::palette().movement.color(self.hoverable.state()); let shadow_color = Color::grey_a(0.1, 0.1); let shadow_pos = self.position().to_x0z() + Vec3::from_y(0.005); let main_pos = shadow_pos + Vec3::from_y(0.05); gfx.ui.arrow((shadow_pos, size, ui::Context::Ground), self.dir, shadow_color); gfx.ui.arrow((main_pos, size, ui::Context::Ground), self.dir, color); } }
Swift
UTF-8
1,228
2.53125
3
[]
no_license
// // CategoriesRequestService.swift // Pets // // Created by Valerii Petrychenko on 5/20/20. // Copyright © 2020 Valerii. All rights reserved. // import Foundation final class CategoriesRequestService { static func getCategories(callBack: @escaping (_ categories: [Category]?, _ error: Error?) -> Void) { var urlString = AccountManager.ApiUrl() urlString.append(Api.version.rawValue) urlString.append(Api.categories.rawValue) var request = URLRequest(url: URL(string: urlString)!) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue(AccountManager.ApiKey(), forHTTPHeaderField: "x-api-key") request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { callBack(nil, error) } else if let data = data { do { let categories = try JSONDecoder().decode([Category].self, from: data) callBack(categories, nil) } catch { callBack(nil, error) } } } task.resume() } }
Go
UTF-8
3,428
3.03125
3
[ "BSD-3-Clause" ]
permissive
// -*- coding:utf-8; indent-tabs-mode:nil; -*- // Copyright 2014, Wu Xi. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package logex import ( "bytes" "errors" "fmt" "runtime" "strconv" "strings" "testing" ) func TestNormalOutput(t *testing.T) { buf := new(bytes.Buffer) SetOutput(buf) SetLevel(DEBUG) _, _, line, _ := runtime.Caller(0) Fatal("hello", "world") if err := check(buf, FATAL, line+1, "hello world\n"); err != nil { t.Error(err) } buf.Reset() _, _, line2, _ := runtime.Caller(0) Debugf("abc %d xyz\n", 123) if err := check(buf, DEBUG, line2+1, "abc 123 xyz\n"); err != nil { t.Error(err) } } func TestLogLevel(t *testing.T) { buf := new(bytes.Buffer) SetOutput(buf) SetLevel(NONE) // will not write any bytes in buf Fatal("hello", "world") if buf.Len() > 0 { t.Errorf("expect writes nothing, but actually writes %q", buf.String()) } // will output nothing but fatal and warning: SetLevel(WARNING) buf.Reset() _, _, line, _ := runtime.Caller(0) Fatal("abc") if err := check(buf, FATAL, line+1, "abc\n"); err != nil { t.Error(err) } buf.Reset() _, _, line2, _ := runtime.Caller(0) Warning("def") if err := check(buf, WARNING, line2+1, "def\n"); err != nil { t.Error(err) } buf.Reset() Notice("abc") if buf.Len() > 0 { t.Errorf("expect writes nothing, but actually writes %q", buf.String()) } buf.Reset() Trace("abc") if buf.Len() > 0 { t.Errorf("expect writes nothing, but actually writes %q", buf.String()) } buf.Reset() Debug("abc") if buf.Len() > 0 { t.Errorf("expect writes nothing, but actually writes %q", buf.String()) } } func TestOutputGoid(t *testing.T) { buf := new(bytes.Buffer) SetOutput(buf) SetLevel(DEBUG) gid := strconv.Itoa(int(goid())) Fatal("abc") if err := checkLogGoid(buf, gid); err != nil { t.Error(err) } c := make(chan bool) var gid2 string = "nil" go func() { defer func() { c <- true }() gid2 = strconv.Itoa(int(goid())) if gid == gid2 { t.Fatalf("wrong gid in goroutine: gid=%q gid2=%q", gid, gid2) } buf.Reset() Fatal("def") if err := checkLogGoid(buf, gid2); err != nil { fmt.Printf("gid=%q gid2=%q buf=%q\n", gid, gid2, buf) t.Error(err) } }() <-c } // check log output line // line eg: "FATAL", "08-09 17:03:11.994", "3", "log_test.go:24", "hello world\n" func check(b *bytes.Buffer, level Level, lineno int, msg string) error { a := strings.SplitN(b.String(), ": ", 5) if len(a) != 5 { return errors.New("wrong log line format") } if levelStr[level] != a[0] { return errors.New(fmt.Sprintf("expect level=%q but actually is %q", levelStr[level], a[0])) } gid := strconv.Itoa(int(goid())) if gid != a[2][2:] { return errors.New(fmt.Sprintf("expect gid=%q but actually is %q", gid, a[2][2:])) } s := fmt.Sprintf("log_test.go:%d", lineno) if s != a[3] { return errors.New(fmt.Sprintf("expect file:line=%q but actually is %q", s, a[3])) } if msg != a[4] { return errors.New(fmt.Sprintf("expect msg=%q but actually is %q", msg, a[4])) } return nil } func checkLogGoid(b *bytes.Buffer, gid string) error { a := strings.SplitN(b.String(), ": ", 5) if len(a) != 5 { return errors.New("wrong log line format") } if gid != a[2][2:] { return errors.New(fmt.Sprintf("expect gid=%q but actually is %q", gid, a[2][2:])) } return nil }