language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
362
3.21875
3
[]
no_license
import math def AA(): n = int(raw_input()) if n % 2 == 0 or n % 5 == 0 or n < 0 or n > 10000: print 0 i = 1 while i >= 0: if sumNum(i) % n == 0: break else: i += 1 print i def sumNum(m): i = 0 sum = 0 while i < m: sum += math.pow(10, i) i += 1 return sum AA()
Python
UTF-8
1,531
2.53125
3
[]
no_license
from PIL import Image import numpy as np from sklearn.neural_network import MLPClassifier from sklearn.metrics import confusion_matrix import mnist, pandas as pd from tensorflow.keras import layers, Sequential, callbacks, optimizers x_train = mnist.train_images() y_train = mnist.train_labels() x_test = mnist.test_images() y_test = mnist.test_labels() print(x_train) x_train = x_train.reshape((-1, 28*28)) print(x_train) x_test = x_test.reshape((-1, 28*28)) x_train = x_train/256 x_test = x_test/256 clf = MLPClassifier(solver='adam', activation='relu', hidden_layer_sizes=(64, 64)) clf.fit(x_train, y_train) prediction = clf.predict(x_test) accuracy_1 = confusion_matrix(y_test, prediction).trace()/confusion_matrix(y_test, prediction).sum() dnn = Sequential([ layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(64, activation='relu'), layers.Dense(10, activation='softmax') ]) dnn.compile(loss='sparse_categorical_crossentropy', optimizer=optimizers.Adam(0.0001)) dnn.fit(x_train, y_train, epochs=100, validation_split=0.2, verbose=0, callbacks=[callbacks.EarlyStopping(patience=10, monitor='val_loss')]) predictions = dnn.predict(x_test) predictions = np.array([np.argmax(predictions[i]) for i in range(len(y_test))]) count = 0 for i in range(len(predictions)): if predictions[i] - np.array(y_test)[i] == 0: count += 1 print("accuracy using sklearn dnn: ", accuracy_1) print("accuracy using keras dnn: ", count/len(predictions))
Markdown
UTF-8
468
2.734375
3
[ "MIT" ]
permissive
# rpi-beep-boot Ansible script to make bootable SDCard for RPI4 with [Ubuntu ARM](https://ubuntu.com/download/raspberry-pi) image ## Requirements: - [ansible](https://www.ansible.com/) - Any linux distro ## Usage: **⚠️!!Warning!!⚠️ This will wipe all your data so ensure that the device is safe to be wiped out.** Before running the script, update `vars.yml` to change/update devices that needs to be bootable. ```sh ansible-playbook playbook.yml -K ```
Java
UTF-8
6,237
2.90625
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 Tessi lab. * * 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.tessilab.oss.openutils.dictionary; import io.tessilab.oss.openutils.distance.words.Distance; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * This class in an implementation of a Burkhard-Keller tree in Java. The * BK-Tree is a tree structure to quickly finding close matches to any defined * object. * * The BK-Tree was first described in the paper: * "Some Approaches to Best-Match File Searching" by W. A. Burkhard and R. M. * Keller It is available in the ACM archives. * * Another good explanation can be found here: * http://blog.notdot.net/2007/4/Damn-Cool-Algorithms-Part-1-BK-Trees * * Searching the tree yields O(logn), which is a huge upgrade over brute force * * @author Josh Clemm * */ public class BKTree<E> { private Node root; private HashMap<E, Double> matches; private Distance<E> distance; protected E bestTerm; protected BKTree() { } public BKTree(Distance<E> distance) { root = null; this.distance = distance; } public void add(E term) { if (root != null) { root.add(term); } else { root = new Node(term); } } /** * This method will find all the close matching Objects within a certain * threshold. For instance, for search for similar strings, threshold set to * 1 will return all the strings that are off by 1 edit distance. * * @param searchObject * @param threshold * @return */ public Map<E, Double> query(E searchObject, double threshold) { matches = new HashMap<>(); root.query(searchObject, threshold, matches); return matches; } /** * Attempts to find the closest match to the search term. * * @param term * @return the edit distance of the best match */ public double find(E term) { return root.findBestMatch(term, Double.MAX_VALUE); } /** * Attempts to find the closest match to the search term. * * @param term * @return a match that is within the best edit distance of the search term. */ public E findBestWordMatchWithinDistance(E term, double threshold) { bestTerm = null; root.findBestMatch(term, threshold); return root.getBestTerm(); } /** * Attempts to find the closest match to the search term. * * @param term * @return a match that is within the best edit distance of the search term. */ public E findBestWordMatch(E term) { root.findBestMatch(term, Integer.MAX_VALUE); return root.getBestTerm(); } /** * Attempts to find the closest match to the search term. * * @param term * @return a match that is within the best edit distance of the search term. */ public Map<E, Double> findBestWordMatchWithDistance(E term) { double d = root.findBestMatch(term, Double.MAX_VALUE); Map<E, Double> returnMap = new HashMap<>(); returnMap.put(root.getBestTerm(), d); return returnMap; } private class Node { E term; TreeMap<Double, Node> children; public Node(E term) { this.term = term; children = new TreeMap<>(); } public void add(E term) { double score = distance.getDistance(term, this.term); Node child = children.get(score); if (child != null) { child.add(term); } else { children.put(score, new Node(term)); } } public double findBestMatch(E term, double bestDistance) { double distanceAtNode = distance.getDistance(term, this.term); double bestDistance2 = bestDistance; if (distanceAtNode <= bestDistance2) { bestDistance2 = distanceAtNode; bestTerm = this.term; } double possibleBest; for (Map.Entry<Double, Node> entry : children.subMap(distanceAtNode - bestDistance2, true, distanceAtNode + bestDistance2, true).entrySet()) { Double score = entry.getKey(); if (score < distanceAtNode - bestDistance2) continue; if (score > distanceAtNode + bestDistance2) break; possibleBest = entry.getValue().findBestMatch(term, bestDistance2); if (possibleBest < bestDistance2) { bestDistance2 = possibleBest; // return early if perfect match if (bestDistance2 < 1e-4) { return 0; } } } return bestDistance2; } public E getBestTerm() { return bestTerm; } public void query(E term, double threshold, Map<E, Double> collected) { double distanceAtNode = distance.getDistance(term, this.term); if (distanceAtNode <= threshold) { collected.put(this.term, distanceAtNode); } for (Map.Entry<Double, Node> entry : children.entrySet()) { double dist = entry.getKey(); if (dist <= distanceAtNode + threshold && dist >= distanceAtNode - threshold) entry.getValue().query(term, threshold, collected); } } } }
Markdown
UTF-8
3,199
3.28125
3
[ "MIT" ]
permissive
--- title: throw a exception author: lijiabao date: 2021-02-21 15:12:22.365892800 +0800 category: JavaNotebook categories: JavaNotebook tags: JavaNotebook --- 如何指定可被方法抛出的异常:使用throw关键字`throw throwableException;` throw关键字后面跟着的对象需要是Throwable的子类(直接子类或者间接子类) 直接子类:Throwable的直接子类有两个,Error,Exception 间接子类:Exception的子类,RuntimeException。 ```java // 如何抛出一个异常 public String readDate(Scanner in) throws EOFException{ while (..){ if (encount a error){ throw new EOFException(); } } } ``` 抛出异常的步骤是找到一个合适的异常类,在方法中指出可能遇到的异常,然后创建这个异常类的对象,然后将对象抛出 1. find a appropriate exception class 2. create a object of the exception 3. throw it #### chained exceptions 有些应用通常在响应处理某个异常的时候,会抛出另外一个异常。 实际上是第一个异常造成第二个异常的出现。 所以知道什么时候一个异常造成另外一个异常是很有帮助的。 ==chained exception==可以做到,下面是几个在Throwable中支持chained exceptions的方法和构造器: 传入构造器和initCause方法的Throwable是造成当前异常的异常 - `Throwable(String, Throwable)`: - `Throwable(Throwable)` - `Throwable getCause()`:返回的是造成当前错误的异常 - `Throwable initCause(Throwable)`:设置造成当前异常的异常 #### 获取Stack Trace信息 **statck trace**:提供的提供当前线程的执行历史并且列出当异常发生的时候调用的类和方法名字。当异常发生的时候,stack trace是很有用的debug工具 ```java catch(Exception cause){ StackTraceElement[] elements = cause.getStackTrace(); for(int i = 0, n = elements.length;i < n; i++){ System.err.println(elements[i].getFileName() + ":" +elements[i].getLineNumber()+ ":"+elements[i].getMethodName()); } } ``` #### logging API 使用logging API除了可以将错误异常信息打印,其可以将异常信息导出到文件中。使用:`java.util.logging` ```java try{ Handler handler = new FileHandler("output.log") Logger.getLogger("").addHandler(handler); }catch (IOException e){ Logger logger = Logger.getLogger(package.name); StackTraceElement[] elements = e.getStackTrace(); for (StackTraceElement element:elements){ logger.log(Level.WARNING, element.getMethodName()); } } ``` #### 需要自己写异常类的情况 - 需要写一个在Java平台中没有提供的异常的时候 - 如果用户可以区分你写的异常类和其他vendor写的类的时候 - 你的代码是否抛出好几个相关的异常 - 如果使用了别人的异常,是否用户有那些异常的访问权限,也就是说你的包是否是独立且self-contained ==选择超类==:创建自己异常的时候应该考虑使用哪个作为父类更合适,Error通常用作严重的硬件错误时使用(如那些使得JVM停止运行的错误),大部分时候都选择Exception作为父类(为了可读性考虑,最好将继承Exception的类后面都加上Exception)
JavaScript
UTF-8
4,767
2.625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
(function() { var DateInput = kendo.ui.DateInput, dateinput, div, input; describe("kendo.ui.DateInput API", function() { beforeEach(function() { div = $("<div />").appendTo(Mocha.fixture); input = $("<input />").appendTo(Mocha.fixture); }); afterEach(function() { dateinput.destroy(); kendo.destroy(Mocha.fixture); }); it("min() should return min value", function() { var value = new Date(2000, 10, 22); dateinput = input.kendoDateInput({ min: value }).data("kendoDateInput"); var result = dateinput.min(); assert.equal(+result, +value); }); it("max() should return max value", function() { var value = new Date(2000, 10, 22); dateinput = input.kendoDateInput({ max: value }).data("kendoDateInput"); var result = dateinput.max(); assert.equal(+result, +value); }); it("min(value) set min value", function() { var value = new Date(2000, 10, 22); dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.min(value); var result = dateinput.min(); assert.equal(+result, +value); }); it("max(value) set max value", function() { var value = new Date(2000, 10, 22); dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.max(value); var result = dateinput.max(); assert.equal(+result, +value); }); it("value() should return value", function() { var value = new Date(2000, 10, 22); dateinput = input.kendoDateInput({ value: value }).data("kendoDateInput"); var result = dateinput.value(); assert.equal(+result, +value); }); it("value(value) set value", function() { var value = new Date(2000, 10, 22); dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.value(value); var result = dateinput.value(); assert.equal(+result, +value); }); it("value(value) is not set if outside min range", function() { var value = new Date(1550, 10, 22); dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.value(value); var result = dateinput.value(); assert.equal(+result, +value); }); it("value(value) is not set if outside max range", function() { var value = new Date(3001, 10, 22); dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.value(value); var result = dateinput.value(); assert.equal(+result, +value); }); it("value(value) is set correctly in min/max range after changing min/max", function() { var value = new Date(1565, 10, 22); var min = new Date(1560, 10, 22); var max = new Date(1570, 10, 22); dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.min(min); dateinput.max(max); dateinput.value(value); var result = dateinput.value(); assert.equal(+result, +value); }); it("value(value) is not set if outside min/max range after changing min/max", function() { var value = new Date(2010, 10, 22); var min = new Date(1560, 10, 22); var max = new Date(1570, 10, 22); dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.min(min); dateinput.max(max); dateinput.value(value); var result = dateinput.value(); assert.equal(+result, +value); }); it("Setting the dateinput as readonly does not add disabled styles", function() { dateinput = input.kendoDateInput().data("kendoDateInput"); dateinput.readonly(true); assert.isOk(!dateinput.wrapper.hasClass("k-state-disabled")); assert.isOk(dateinput.element.attr("readonly")); }); it("DateInput should update time according to the specified interval", function () { var e = $.Event('keypress'); e.which = kendo.keys.UP; dateinput = input.kendoDateInput({ interval: 15, value: new Date(2000, 1, 1), format: "mm" }).data("kendoDateInput"); input.select(); dateinput._keydown({ keyCode: 38, preventDefault: function () { } }); assert.equal(input.val(), '15'); }); }); }());
C++
GB18030
2,498
2.515625
3
[]
no_license
#include "stdafx.h" #include "func.h" #include "KBASE.h" Func::Func(void) { } Func::~Func(void) { } #ifdef WIN32 #else #include <iconv.h> int Func::code_convert(char *from_charset,char *to_charset,char *inbuf,int inlen,char *outbuf,int outlen) { iconv_t cd; int rc; char **pin = &inbuf; char **pout = &outbuf; size_t in_len = (size_t)inlen; size_t out_len = (size_t)outlen; cd = iconv_open(to_charset,from_charset); if (cd==0) { LOG::INF("iconv_open is failed!\n"); iconv_close(cd); return -1; } memset(outbuf,0,out_len); if (iconv(cd, pin,&in_len,pout,&out_len)==-1) { LOG::INF("iconv is failed! inbuf:%s, outbut:%s\n", *pin,pout ); iconv_close(cd); return -1; } iconv_close(cd); return 0; } #endif //_WIN32 std::string Func::UTF8toGB2312(const char *utf8) { #ifdef WIN32 std::string result; WCHAR *strSrc; char *szRes; //ʱĴС int i = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0); strSrc = new WCHAR[i+1]; MultiByteToWideChar(CP_UTF8, 0, utf8, -1, strSrc, i); //ʱĴС i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL); szRes = new char[i+1]; WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL); result = szRes; delete []strSrc; delete []szRes; return result; #else std::string gb2312 = utf8; int utf_len = strlen(utf8); int gb_len = utf_len*2 + 1; char* gb_buf = new char[gb_len]; if (gb_buf) { code_convert("utf-8","gb2312",(char*)utf8, utf_len, gb_buf, gb_len); gb2312 = gb_buf; delete [] gb_buf; } return gb2312; #endif //WIN32 } std::string Func::GB2312toUTF8(const char *gb2312) { #ifdef WIN32 std::string result; WCHAR *strSrc; char *szRes; //ʱĴС int i = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0); strSrc = new WCHAR[i+1]; MultiByteToWideChar(CP_ACP, 0, gb2312, -1, strSrc, i); //ʱĴС i = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, NULL, 0, NULL, NULL); szRes = new char[i+1]; int j=WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, szRes, i, NULL, NULL); result = szRes; delete []strSrc; delete []szRes; return result; #else std::string utf = gb2312; int gb_len = strlen(gb2312); int utf_len = gb_len * 2 + 1; char * utf_buf = new char[utf_len]; if (utf_buf) { code_convert("gb2312","utf-8",(char*)gb2312,gb_len,utf_buf,utf_len); utf = utf_buf; delete [] utf_buf; } return utf; #endif //WIN32 }
Rust
UTF-8
1,105
3.1875
3
[ "MIT", "Apache-2.0" ]
permissive
//! ## Built-In Profiler //! //! To get a summary of latency histograms relating to different operations //! you've used on a sled database, sled can print a nice table when the Db is //! dropped by disabling the `no_metrics` default feature and setting //! `print_profile_on_drop(true)` on a `ConfigBuilder`: //! //! ```rust //! let config = sled::ConfigBuilder::new() //! .print_profile_on_drop(true) //! .build(); //! //! let db = sled::Db::start(config).unwrap(); //! ``` //! //! This is useful for finding outliers, general percentiles about usage, and //! especially for debugging performance issues if you create an issue on //! github. //! //! ## Use jemalloc //! //! jemalloc can dramatically improve performance in some situations, but you //! should always measure performance before and after using it, because maybe //! for some use cases it can cause regressions. //! //! Cargo.toml: //! ```toml //! [dependencies] //! jemallocator = "0.1" //! ``` //! //! `your_code.rs`: //! ```rust //! #[global_allocator] //! static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; //! ```
Ruby
UTF-8
990
2.75
3
[]
no_license
#require 'net/http' require 'open-uri' require 'nokogiri' require 'date' require_relative 'event.rb' class Scraper attr_accessor :url, :events def initialize(url) @url = url scrape end def scrape import_xml(open(@url).read) end # Reads Google Calendar XML and populates fields def import_xml(raw) doc = Nokogiri::XML(raw) @events = [] doc.css('entry').each do |entry| fields = { :id => entry.css('id').text, :published => entry.css('published').text, :title => entry.css('title').text, :summary => entry.css('content').text, :start => DateTime.parse(entry.xpath('gd:when').first['startTime']), :end => DateTime.parse(entry.xpath('gd:when').first['endTime']), :where => entry.xpath('gd:where').first['valueString'], :url => entry.css('link').first['href'] } @events << Event.new(fields) end return @events end end
Java
UTF-8
227
1.914063
2
[]
no_license
package iServicesRemote; import javax.ejb.Remote; import entites.Reclamation; @Remote public interface ReclamationServiceRemote { public void ajouterReclamation(Reclamation p); public void supprimer(int id ); }
Java
UTF-8
375
2.234375
2
[]
no_license
package com.loki.astream.stubs;import com.jenzz.pojobuilder.api.Builder;import com.jenzz.pojobuilder.api.Ignore; @Builder public class SampleClass1037 { @Ignore private SampleClass1038 sampleClass; public SampleClass1037(){ sampleClass = new SampleClass1038(); } public String getClassName() { return sampleClass.getClassName(); } }
SQL
UTF-8
15,000
2.53125
3
[ "MIT" ]
permissive
CREATE TABLE country (id VARCHAR(2) NOT NULL, name VARCHAR(64) NOT NULL, PRIMARY KEY(id)); INSERT INTO "country" ("id", "name") VALUES ('AF', 'afganistáŋ'); INSERT INTO "country" ("id", "name") VALUES ('ZA', 'afrik anǝ a sud'); INSERT INTO "country" ("id", "name") VALUES ('AL', 'albaní'); INSERT INTO "country" ("id", "name") VALUES ('DZ', 'aljɛrí'); INSERT INTO "country" ("id", "name") VALUES ('US', 'amɛrika'); INSERT INTO "country" ("id", "name") VALUES ('AD', 'andɔrǝ'); INSERT INTO "country" ("id", "name") VALUES ('AI', 'angiya'); INSERT INTO "country" ("id", "name") VALUES ('AO', 'angóla'); INSERT INTO "country" ("id", "name") VALUES ('AG', 'antiga ri barbúda'); INSERT INTO "country" ("id", "name") VALUES ('AN', 'antíyǝ nɛlandé'); INSERT INTO "country" ("id", "name") VALUES ('SA', 'arabí saodí'); INSERT INTO "country" ("id", "name") VALUES ('AR', 'arjǝntín'); INSERT INTO "country" ("id", "name") VALUES ('AM', 'armɛní'); INSERT INTO "country" ("id", "name") VALUES ('AW', 'aruba'); INSERT INTO "country" ("id", "name") VALUES ('HT', 'ayiti'); INSERT INTO "country" ("id", "name") VALUES ('AZ', 'azabecán'); INSERT INTO "country" ("id", "name") VALUES ('BB', 'baabaadǝ'); INSERT INTO "country" ("id", "name") VALUES ('BS', 'baamás'); INSERT INTO "country" ("id", "name") VALUES ('BD', 'baŋladɛ́c'); INSERT INTO "country" ("id", "name") VALUES ('BH', 'barǝ́n'); INSERT INTO "country" ("id", "name") VALUES ('AE', 'bǝlɔŋ bǝ kaksa bɛ táatáaŋzǝn'); INSERT INTO "country" ("id", "name") VALUES ('BM', 'bɛɛmúdǝ'); INSERT INTO "country" ("id", "name") VALUES ('BY', 'bɛlaris'); INSERT INTO "country" ("id", "name") VALUES ('BZ', 'bɛliz'); INSERT INTO "country" ("id", "name") VALUES ('BE', 'bɛljík'); INSERT INTO "country" ("id", "name") VALUES ('BJ', 'bɛnǝ́n'); INSERT INTO "country" ("id", "name") VALUES ('BW', 'botswana'); INSERT INTO "country" ("id", "name") VALUES ('BO', 'bɔɔlíví'); INSERT INTO "country" ("id", "name") VALUES ('BA', 'bɔsnyɛ ri hɛrsǝgɔvín'); INSERT INTO "country" ("id", "name") VALUES ('BR', 'brɛsíl'); INSERT INTO "country" ("id", "name") VALUES ('BN', 'brunǝ́'); INSERT INTO "country" ("id", "name") VALUES ('BF', 'bukína fǝ́ asɔ'); INSERT INTO "country" ("id", "name") VALUES ('BG', 'bulgarí'); INSERT INTO "country" ("id", "name") VALUES ('BI', 'burundí'); INSERT INTO "country" ("id", "name") VALUES ('BT', 'bután'); INSERT INTO "country" ("id", "name") VALUES ('TD', 'caád'); INSERT INTO "country" ("id", "name") VALUES ('CZ', 'cɛ́k'); INSERT INTO "country" ("id", "name") VALUES ('CL', 'cíli'); INSERT INTO "country" ("id", "name") VALUES ('CN', 'cín'); INSERT INTO "country" ("id", "name") VALUES ('CY', 'cíprɛ'); INSERT INTO "country" ("id", "name") VALUES ('DK', 'danmak'); INSERT INTO "country" ("id", "name") VALUES ('DE', 'djɛrman'); INSERT INTO "country" ("id", "name") VALUES ('DM', 'dɔminik'); INSERT INTO "country" ("id", "name") VALUES ('DO', 'dɔminik rɛpublík'); INSERT INTO "country" ("id", "name") VALUES ('DJ', 'dyibutí'); INSERT INTO "country" ("id", "name") VALUES ('EG', 'ɛjípt'); INSERT INTO "country" ("id", "name") VALUES ('EC', 'ɛkwatɛǝ́'); INSERT INTO "country" ("id", "name") VALUES ('ER', 'ɛritrɛ́'); INSERT INTO "country" ("id", "name") VALUES ('EE', 'ɛstoní'); INSERT INTO "country" ("id", "name") VALUES ('ET', 'ɛtyɔpí'); INSERT INTO "country" ("id", "name") VALUES ('FJ', 'fíji'); INSERT INTO "country" ("id", "name") VALUES ('PH', 'filipǝ́n'); INSERT INTO "country" ("id", "name") VALUES ('FI', 'fínlan'); INSERT INTO "country" ("id", "name") VALUES ('GA', 'gabɔŋ'); INSERT INTO "country" ("id", "name") VALUES ('GM', 'gambí'); INSERT INTO "country" ("id", "name") VALUES ('GH', 'gána'); INSERT INTO "country" ("id", "name") VALUES ('GN', 'ginɛ́'); INSERT INTO "country" ("id", "name") VALUES ('GW', 'ginɛ́ bisɔ́'); INSERT INTO "country" ("id", "name") VALUES ('GQ', 'ginɛ́ ɛkwatɔrial'); INSERT INTO "country" ("id", "name") VALUES ('GR', 'grɛ́k'); INSERT INTO "country" ("id", "name") VALUES ('GD', 'grɛnadǝ'); INSERT INTO "country" ("id", "name") VALUES ('GL', 'grínlan'); INSERT INTO "country" ("id", "name") VALUES ('GY', 'guyán'); INSERT INTO "country" ("id", "name") VALUES ('GF', 'guyán i pɛrɛsǝ́'); INSERT INTO "country" ("id", "name") VALUES ('GP', 'gwadɛlúp'); INSERT INTO "country" ("id", "name") VALUES ('GU', 'gwám'); INSERT INTO "country" ("id", "name") VALUES ('GT', 'gwátǝmala'); INSERT INTO "country" ("id", "name") VALUES ('IE', 'ilán'); INSERT INTO "country" ("id", "name") VALUES ('IN', 'indí'); INSERT INTO "country" ("id", "name") VALUES ('ID', 'indonɛsí'); INSERT INTO "country" ("id", "name") VALUES ('IQ', 'irák'); INSERT INTO "country" ("id", "name") VALUES ('IR', 'iráŋ'); INSERT INTO "country" ("id", "name") VALUES ('IL', 'israɛ́l'); INSERT INTO "country" ("id", "name") VALUES ('IT', 'italí'); INSERT INTO "country" ("id", "name") VALUES ('JM', 'jamaík'); INSERT INTO "country" ("id", "name") VALUES ('JP', 'japɔ́ŋ'); INSERT INTO "country" ("id", "name") VALUES ('GI', 'jibraltá'); INSERT INTO "country" ("id", "name") VALUES ('JO', 'jɔrdán'); INSERT INTO "country" ("id", "name") VALUES ('GE', 'jɔrjí'); INSERT INTO "country" ("id", "name") VALUES ('NC', 'kalɛdoní anyɔ́n'); INSERT INTO "country" ("id", "name") VALUES ('KH', 'kambodj'); INSERT INTO "country" ("id", "name") VALUES ('CM', 'kamɛrún'); INSERT INTO "country" ("id", "name") VALUES ('CA', 'kanada'); INSERT INTO "country" ("id", "name") VALUES ('CV', 'kapvɛr'); INSERT INTO "country" ("id", "name") VALUES ('QA', 'katá'); INSERT INTO "country" ("id", "name") VALUES ('KZ', 'kazakstáŋ'); INSERT INTO "country" ("id", "name") VALUES ('NL', 'kǝlɔŋ kǝ ázǝ'); INSERT INTO "country" ("id", "name") VALUES ('GB', 'kǝlɔŋ kǝ kǝtáatáaŋzǝn'); INSERT INTO "country" ("id", "name") VALUES ('KE', 'kɛnya'); INSERT INTO "country" ("id", "name") VALUES ('KG', 'kigistáŋ'); INSERT INTO "country" ("id", "name") VALUES ('KI', 'kiribáti'); INSERT INTO "country" ("id", "name") VALUES ('CO', 'kolɔmbí'); INSERT INTO "country" ("id", "name") VALUES ('KM', 'komɔr'); INSERT INTO "country" ("id", "name") VALUES ('KP', 'korɛanɔ́r'); INSERT INTO "country" ("id", "name") VALUES ('KR', 'korɛasud'); INSERT INTO "country" ("id", "name") VALUES ('CG', 'kɔngó'); INSERT INTO "country" ("id", "name") VALUES ('CD', 'kɔngó anyɔ́n'); INSERT INTO "country" ("id", "name") VALUES ('CR', 'kɔstaríka'); INSERT INTO "country" ("id", "name") VALUES ('CI', 'kɔtiwuár'); INSERT INTO "country" ("id", "name") VALUES ('ES', 'kpanyá'); INSERT INTO "country" ("id", "name") VALUES ('HR', 'krwasí'); INSERT INTO "country" ("id", "name") VALUES ('CU', 'kuba'); INSERT INTO "country" ("id", "name") VALUES ('KW', 'kuwɛit'); INSERT INTO "country" ("id", "name") VALUES ('LA', 'laɔs'); INSERT INTO "country" ("id", "name") VALUES ('LS', 'lǝsóto'); INSERT INTO "country" ("id", "name") VALUES ('LV', 'lɛtoní'); INSERT INTO "country" ("id", "name") VALUES ('LB', 'libáŋ'); INSERT INTO "country" ("id", "name") VALUES ('LR', 'libɛrya'); INSERT INTO "country" ("id", "name") VALUES ('LY', 'libí'); INSERT INTO "country" ("id", "name") VALUES ('LI', 'lictɛnstɛ́n'); INSERT INTO "country" ("id", "name") VALUES ('LT', 'litwaní'); INSERT INTO "country" ("id", "name") VALUES ('LU', 'luksɛmbúr'); INSERT INTO "country" ("id", "name") VALUES ('MG', 'madagaska'); INSERT INTO "country" ("id", "name") VALUES ('MW', 'malawi'); INSERT INTO "country" ("id", "name") VALUES ('MV', 'maldivǝ'); INSERT INTO "country" ("id", "name") VALUES ('MY', 'malɛsí'); INSERT INTO "country" ("id", "name") VALUES ('ML', 'mali'); INSERT INTO "country" ("id", "name") VALUES ('MT', 'maltǝ'); INSERT INTO "country" ("id", "name") VALUES ('MA', 'marɔk'); INSERT INTO "country" ("id", "name") VALUES ('MK', 'másǝdwán'); INSERT INTO "country" ("id", "name") VALUES ('MQ', 'matiník'); INSERT INTO "country" ("id", "name") VALUES ('YT', 'mayɔ́t'); INSERT INTO "country" ("id", "name") VALUES ('MX', 'mɛksík'); INSERT INTO "country" ("id", "name") VALUES ('FM', 'mikronɛ́si'); INSERT INTO "country" ("id", "name") VALUES ('MC', 'monako'); INSERT INTO "country" ("id", "name") VALUES ('MZ', 'mosambík'); INSERT INTO "country" ("id", "name") VALUES ('MD', 'mɔldaví'); INSERT INTO "country" ("id", "name") VALUES ('MS', 'mɔnsɛrat'); INSERT INTO "country" ("id", "name") VALUES ('MN', 'mɔŋolí'); INSERT INTO "country" ("id", "name") VALUES ('MU', 'mwarís'); INSERT INTO "country" ("id", "name") VALUES ('MR', 'mwaritaní'); INSERT INTO "country" ("id", "name") VALUES ('MM', 'myanmár'); INSERT INTO "country" ("id", "name") VALUES ('NA', 'namibí'); INSERT INTO "country" ("id", "name") VALUES ('NP', 'nɛpal'); INSERT INTO "country" ("id", "name") VALUES ('NE', 'nijɛ́r'); INSERT INTO "country" ("id", "name") VALUES ('NG', 'nijɛ́rya'); INSERT INTO "country" ("id", "name") VALUES ('NI', 'níkarágwa'); INSERT INTO "country" ("id", "name") VALUES ('NU', 'niwɛ́'); INSERT INTO "country" ("id", "name") VALUES ('NO', 'nɔrvɛjǝ'); INSERT INTO "country" ("id", "name") VALUES ('NR', 'nwarú'); INSERT INTO "country" ("id", "name") VALUES ('OM', 'oman'); INSERT INTO "country" ("id", "name") VALUES ('AT', 'otric'); INSERT INTO "country" ("id", "name") VALUES ('HN', 'ɔnduras'); INSERT INTO "country" ("id", "name") VALUES ('HU', 'ɔngrí'); INSERT INTO "country" ("id", "name") VALUES ('AU', 'ɔstralí'); INSERT INTO "country" ("id", "name") VALUES ('PK', 'pakistáŋ'); INSERT INTO "country" ("id", "name") VALUES ('PW', 'palwa'); INSERT INTO "country" ("id", "name") VALUES ('PA', 'panama'); INSERT INTO "country" ("id", "name") VALUES ('PG', 'papwazí ginɛ́ anyɔ́n'); INSERT INTO "country" ("id", "name") VALUES ('PY', 'paragwɛ́'); INSERT INTO "country" ("id", "name") VALUES ('FR', 'pɛrɛsǝ́'); INSERT INTO "country" ("id", "name") VALUES ('PE', 'pɛrú'); INSERT INTO "country" ("id", "name") VALUES ('PN', 'pitkɛ́n'); INSERT INTO "country" ("id", "name") VALUES ('PL', 'polɔ́n'); INSERT INTO "country" ("id", "name") VALUES ('PT', 'portugál'); INSERT INTO "country" ("id", "name") VALUES ('PF', 'pɔlinɛsí a pɛrɛsǝ́'); INSERT INTO "country" ("id", "name") VALUES ('PR', 'pɔtoríko'); INSERT INTO "country" ("id", "name") VALUES ('RE', 'rɛunyɔŋ'); INSERT INTO "country" ("id", "name") VALUES ('RU', 'risí'); INSERT INTO "country" ("id", "name") VALUES ('RO', 'rɔmaní'); INSERT INTO "country" ("id", "name") VALUES ('RW', 'rwanda'); INSERT INTO "country" ("id", "name") VALUES ('SV', 'salvadɔr'); INSERT INTO "country" ("id", "name") VALUES ('WS', 'samɔa'); INSERT INTO "country" ("id", "name") VALUES ('AS', 'samɔa a amɛrika'); INSERT INTO "country" ("id", "name") VALUES ('CF', 'santrafrík'); INSERT INTO "country" ("id", "name") VALUES ('ST', 'saotomɛ́ ri priŋsib'); INSERT INTO "country" ("id", "name") VALUES ('SC', 'sɛcɛl'); INSERT INTO "country" ("id", "name") VALUES ('SN', 'sɛnɛgal'); INSERT INTO "country" ("id", "name") VALUES ('KN', 'sɛnkrǝstɔ́f ri nyɛ́vǝ'); INSERT INTO "country" ("id", "name") VALUES ('SM', 'sɛnmarǝn'); INSERT INTO "country" ("id", "name") VALUES ('PM', 'sɛnpyɛr ri mikɛlɔŋ'); INSERT INTO "country" ("id", "name") VALUES ('SH', 'sɛntɛ́len'); INSERT INTO "country" ("id", "name") VALUES ('LC', 'sɛntlísí'); INSERT INTO "country" ("id", "name") VALUES ('VC', 'sɛnvǝnsǝŋ ri grɛnadín'); INSERT INTO "country" ("id", "name") VALUES ('CS', 'sɛrbí ri mɔntǝnɛgro'); INSERT INTO "country" ("id", "name") VALUES ('SG', 'siŋapó'); INSERT INTO "country" ("id", "name") VALUES ('SY', 'sirí'); INSERT INTO "country" ("id", "name") VALUES ('SK', 'slovakí'); INSERT INTO "country" ("id", "name") VALUES ('SI', 'slovɛní'); INSERT INTO "country" ("id", "name") VALUES ('SO', 'somalí'); INSERT INTO "country" ("id", "name") VALUES ('LK', 'srílaŋka'); INSERT INTO "country" ("id", "name") VALUES ('SD', 'sudan'); INSERT INTO "country" ("id", "name") VALUES ('SR', 'surinam'); INSERT INTO "country" ("id", "name") VALUES ('SZ', 'swazilan'); INSERT INTO "country" ("id", "name") VALUES ('SE', 'swɛdǝ'); INSERT INTO "country" ("id", "name") VALUES ('CH', 'swís'); INSERT INTO "country" ("id", "name") VALUES ('SL', 'syɛraleon'); INSERT INTO "country" ("id", "name") VALUES ('TJ', 'tadjikistaŋ'); INSERT INTO "country" ("id", "name") VALUES ('TZ', 'tanzaní'); INSERT INTO "country" ("id", "name") VALUES ('TH', 'tɛlan'); INSERT INTO "country" ("id", "name") VALUES ('TT', 'tɛrinitɛ ri tobago'); INSERT INTO "country" ("id", "name") VALUES ('TW', 'tɛwán'); INSERT INTO "country" ("id", "name") VALUES ('TL', 'timor anǝ á ɛst'); INSERT INTO "country" ("id", "name") VALUES ('TR', 'tirkí'); INSERT INTO "country" ("id", "name") VALUES ('TM', 'tirkmɛnistaŋ'); INSERT INTO "country" ("id", "name") VALUES ('TG', 'togo'); INSERT INTO "country" ("id", "name") VALUES ('TK', 'tokǝlao'); INSERT INTO "country" ("id", "name") VALUES ('TO', 'tɔŋa'); INSERT INTO "country" ("id", "name") VALUES ('TN', 'tunɛsí'); INSERT INTO "country" ("id", "name") VALUES ('TV', 'tuwalu'); INSERT INTO "country" ("id", "name") VALUES ('UG', 'uganda'); INSERT INTO "country" ("id", "name") VALUES ('UA', 'ukrain'); INSERT INTO "country" ("id", "name") VALUES ('UY', 'urugwɛ́'); INSERT INTO "country" ("id", "name") VALUES ('UZ', 'usbɛkistaŋ'); INSERT INTO "country" ("id", "name") VALUES ('WF', 'walis ri futuna'); INSERT INTO "country" ("id", "name") VALUES ('VU', 'wanwatu'); INSERT INTO "country" ("id", "name") VALUES ('VA', 'watikáŋ'); INSERT INTO "country" ("id", "name") VALUES ('VE', 'wɛnǝzwɛla'); INSERT INTO "country" ("id", "name") VALUES ('VN', 'wyɛtnám'); INSERT INTO "country" ("id", "name") VALUES ('YE', 'yɛmɛn'); INSERT INTO "country" ("id", "name") VALUES ('ZM', 'zambí'); INSERT INTO "country" ("id", "name") VALUES ('VI', 'zǝ bɛ gɔn inɛ á amɛrika'); INSERT INTO "country" ("id", "name") VALUES ('VG', 'zǝ bɛ gɔn inɛ a ingɛrís'); INSERT INTO "country" ("id", "name") VALUES ('KY', 'zǝ i gan'); INSERT INTO "country" ("id", "name") VALUES ('IS', 'zǝ i glás'); INSERT INTO "country" ("id", "name") VALUES ('MH', 'zǝ i marcál'); INSERT INTO "country" ("id", "name") VALUES ('IO', 'zǝ ingɛrís ncɔ́m wa indi'); INSERT INTO "country" ("id", "name") VALUES ('FK', 'zǝ maalwín'); INSERT INTO "country" ("id", "name") VALUES ('MP', 'zǝ maryánnɔ́r'); INSERT INTO "country" ("id", "name") VALUES ('PS', 'zǝ palɛstínǝ'); INSERT INTO "country" ("id", "name") VALUES ('SB', 'zǝ salomɔ́n'); INSERT INTO "country" ("id", "name") VALUES ('TC', 'zǝ tirk ri kakɔs'); INSERT INTO "country" ("id", "name") VALUES ('CK', 'zɛ i kúk'); INSERT INTO "country" ("id", "name") VALUES ('NF', 'zɛ nɔ́fɔlk'); INSERT INTO "country" ("id", "name") VALUES ('NZ', 'zɛlan anyɔ́n'); INSERT INTO "country" ("id", "name") VALUES ('ZW', 'zimbabwɛ́');
Markdown
UTF-8
1,035
3.03125
3
[ "MIT" ]
permissive
+++ title = "PositionRestraint" weight = 10000 +++ # PositionRestraint It restrains a particle to a fixed point in a space via harmonic potential. ## Example ```toml [[forcefields.external]] interaction = "PositionRestraint" potential = "Harmonic" parameters = [ {index = 0, position = [0.0, 0.0, 0.0], k = 0.1, v0 = 10.0}, # ... ] ``` ## Input Reference - `interaction`: String - Name of the interaciton. Here, it is `"PositionRestraint"`. - `potential`: String - Name of the potential. Currently, only the harmonic potential is available. - `parameters`: Table - `index`: Integer - The index of the particle. The index is 0-based. - `offset`: Integer (Optional. By default, 0.) - The offset value for the index. - `position`: Array of Floatings - The cartesian coordinate (x, y, and z in this order) of the position. - `k`: Floating - The strength of the restraint. - `v0`: Floating - The native distance from the point. - To restrain a particle exactly at the position, set 0.
Markdown
UTF-8
505
2.546875
3
[ "MIT" ]
permissive
# About Hey there 👋, my name is [Luan](https://twitter.com/LuanGjokaj) a UX Engineer & Designer. ReactFondue came as a side project, driven by the necessity to have a solid infrastructure using React, ready to go in no time 🚀. The goal is to have a clean and minimal setup out of the box, SEO friendly and optimized. A development environment with all the ingredients. Supporting code splitting, hot module reload and server side rendering. It is an open source project, contributions are welcome!
JavaScript
UTF-8
2,473
2.84375
3
[ "MIT" ]
permissive
$(() => { refreshList(); }) /* function to refresh vendor list */ function refreshList(){ $('#vendorList').empty() $('#vendorName').val('') $('#vendorEmail').val('') $.get('/vendors', (data) => { if(data.length == 0){ $('#vendorList').append("<b> No Vendors Listed for now..! </b>"); } else{ for(let vendor of data){ $('#vendorList').append( `<li class="list-group-item "><div class="row" align="center"><div class="col-md-10"> Vendor Name: <b>${vendor.name}</b> <br> Email: ${vendor.email}</div> <div class="col-md-2"> <button type="button" class="btn btn-danger btn-lg" onclick=DelVendor(${vendor.id})> <span class="glyphicon glyphicon-remove-circle"></span> Remove </button></div> </div><li>` ) } } } ) } /* function to add new vendor */ function addVendor(){ let mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(($('#vendorName').val()).toString() === ''){ alert("Please enter vendor name...!"); } if(!($('#vendorEmail').val()).match(mailformat)){ alert("Please enter valid vendor email...!"); } else{ $.post('/vendors', { vendorName: $('#vendorName').val().toLowerCase(), vendorEmail: $('#vendorEmail').val().toLowerCase(), qty:'' }, (data) => { if (data.success) { refreshList() } else { alert('Some error occurred....!!') } } ) } } /* function to delete an existing vendor */ function DelVendor(id){ $.ajax({ url:`/vendors/${id}`, method: 'DELETE', contentType:'application/json', success: function(data){ refreshList() }, error: function(request, msg, error){ alert('Oops...Something went wrong...!') refreshList() } }) refreshList() }
Java
UTF-8
3,556
2.390625
2
[]
no_license
package org.usfirst.frc.team4229.robot; import java.util.ArrayList; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import edu.wpi.cscore.AxisCamera; import edu.wpi.cscore.CvSink; import edu.wpi.cscore.CvSource; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc.team4229.robot.GRIPGreenMaskPipeline; import org.usfirst.frc.team4229.robot.FURetro; import org.usfirst.frc.team4229.robot.RetroPipe; public class CameraThread extends Thread { //Thread visionThread; Object imglock; RetroPipe pipe; AxisCamera camera; CvSink cvSink; CvSource outputStream2; Mat mat; double FOVDegrees; double tanFOV; public CameraThread(){ this.setDaemon(true); } public void init() { // Get the UsbCamera from CameraServer camera = CameraServer.getInstance().addAxisCamera("axis-camera.local"); camera.setResolution(1600, 800); /** //Create a pipeline that will filter out all but green //GRIPGreenMaskPipeline greenmask = new GRIPGreenMaskPipeline(); //Create a pipeline to detect contours pipe = new RetroPipe(); // Set the resolution camera.setResolution(640, 480); // Get a CvSink. This will capture Mats from the camera cvSink = CameraServer.getInstance().getVideo(); // Setup a CvSource. This will send images back to the Dashboard outputStream2 = CameraServer.getInstance().putVideo("Mask", 640, 480); //CvSource outputStream3 = CameraServer.getInstance().putVideo("Countours", 640, 480); // Mats are very memory expensive. Lets reuse this Mat. mat = new Mat(); double FOVDegrees =39.513843575; double tanFOV = Math.tan(Math.toRadians(FOVDegrees)); SmartDashboard.putNumber("tan", tanFOV); SmartDashboard.putNumber("distance", 1); // This cannot be 'true'. The program will never exit if it is. This // lets the robot stop this thread when restarting robot code or // deploying. } public double distance(double PixelHeight){ //TargetHeight return 0; } public void run(){ while (!Thread.interrupted()) { // Tell the CvSink to grab a frame from the camera and put it // in the source mat. If there is an error notify the output. if (cvSink.grabFrame(mat) == 0) { // Send the output the error. outputStream2.notifyError(cvSink.getError()); //outputStream3.notifyError(cvSink.getError()); // skip the rest of the current iteration continue; } //Make Green Mask //greenmask.process(mat); // REQUIRED! pipe.process(mat); //furetro.convertArrays(furetro.filterContoursOutput()); // Put a rectangle on the image //Imgproc.rectangle(furetro.hsvThresholdOutput(), new Point(50, 50), new Point(200, 240), //new Scalar(255, 255, 255), 5); // Give the output stream a new image to display outputStream2.putFrame(pipe.maskOutput()); if (pipe.filterContoursOutput().size()>0){ double recth = Imgproc.boundingRect(pipe.filterContoursOutput().get(0)).height; SmartDashboard.putNumber("pixH", recth); SmartDashboard.putNumber("distance", (1.0/12.0)*480.0/(2.0*recth*tanFOV)); } //Alright, let's grab some crap here and do some math //Rect r = Imgproc.boundingRect(greenmask.filterContoursOutput().get(0)); // synchronized (imglock){ // int x = r.x; // int y = r.y; // int h = r.height; // int w =r.width; //} } **/ } }
Markdown
UTF-8
1,226
4.21875
4
[]
no_license
# 链接 https://leetcode-cn.com/problems/valid-parentheses/ # 题目 ``` 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。   示例 1: 输入:s = "()" 输出:true 示例 2: 输入:s = "()[]{}" 输出:true 示例 3: 输入:s = "(]" 输出:false 示例 4: 输入:s = "([)]" 输出:false 示例 5: 输入:s = "{[]}" 输出:true ``` # 思路 - 栈的常规思路,若新括号匹配到栈顶的括号,则栈顶括号弹出,新括号丢弃;未匹配到则新括号入栈 ```go func isValid(s string) bool { stack := make([]byte, 0, len(s)) for i := 0; i < len(s); i++ { if len(stack) == 0 { stack = append(stack, s[i]) continue } if (s[i] == ')' && stack[len(stack) - 1] == '(') || (s[i] == ']' && stack[len(stack) - 1] == '[') || (s[i] == '}' && stack[len(stack) - 1] == '{') { stack = stack[:len(stack) - 1] } else { stack = append(stack, s[i]) } } return len(stack) == 0 } ```
Python
UTF-8
1,507
4.1875
4
[]
no_license
""" The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from math import sqrt def is_prime(a): if a == 1: return False elif a == 2 or a == 3: return True elif a % 2 == 0 or a % 3 == 0: return False else: for div in range(5, int(sqrt(a))+1, 2): if a % div == 0: return False return True def truncate_right(a): a_str = str(a) return int(a_str[:-1]) def truncate_left(a): a_str = str(a) return int(a_str[1:]) def are_truncates_prime(n): len_n = len(str(n)) n_right = n n_left = n for i in range(len_n - 1): n_right = truncate_right(n_right) n_left = truncate_left(n_left) #print("n_right is {}".format(n_right)) #print("n_left is {}".format(n_left)) if not is_prime(n_right) or not is_prime(n_left): return False return True def loop(): n = 0 num = 13 lst = [] while n < 11: if is_prime(num): if are_truncates_prime(num): lst.append(num) n += 1 num += 2 return lst import sys if __name__ == '__main__': print(sum(loop()))
SQL
UTF-8
723
2.59375
3
[]
no_license
-- Generated via bigquery_etl.glean_usage CREATE OR REPLACE VIEW `moz-fx-data-shared-prod.org_mozilla_fenix_nightly.baseline_clients_last_seen` AS SELECT `moz-fx-data-shared-prod`.udf.pos_of_trailing_set_bit(days_seen_bits) AS days_since_seen, `moz-fx-data-shared-prod`.udf.pos_of_trailing_set_bit( days_created_profile_bits ) AS days_since_created_profile, `moz-fx-data-shared-prod`.udf.pos_of_trailing_set_bit( days_seen_session_start_bits ) AS days_since_seen_session_start, `moz-fx-data-shared-prod`.udf.pos_of_trailing_set_bit( days_seen_session_end_bits ) AS days_since_seen_session_end, * FROM `moz-fx-data-shared-prod.org_mozilla_fenix_nightly_derived.baseline_clients_last_seen_v1`
Java
UTF-8
879
2.078125
2
[]
no_license
package org.geosatis.surveillancemanager.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.security.Principal; @Controller @RequestMapping(path="/") public class MainController { @RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET) public String loginPage(Model model) { return "userTemplates/loginPage"; } @RequestMapping(value = "/logoutSuccessful", method = RequestMethod.GET) public String logoutSuccessfulPage(Model model) { return "userTemplates/loginPage"; } @RequestMapping(value = "/403", method = RequestMethod.GET) public String accessDenied(Model model, Principal principal) { return "403Page"; } }
Python
UTF-8
511
2.609375
3
[]
no_license
import numpy as np from numpy.core.defchararray import chararray from allfunctions import * loop=1 while loop: fichier = input("Please type the name of the file:") nbnodes, nbedges, edges = readfromtxt(fichier) AdjMat = CreateAdjMat(nbnodes,nbedges,edges) print("AdjMat is:") printMat(AdjMat,nbnodes) # print("AdjMat is:") # print (AdjMat) L,P = FloydWarshall(AdjMat,nbnodes) # print(L) FindCircuitsAbso(L, nbnodes) loop=int(input("Do you want to continue(0/1):"))
Java
UTF-8
1,140
3.09375
3
[]
no_license
package nl.tue.win.ga.algorithms.iterators; import java.util.Iterator; import java.util.List; import java.util.Random; import nl.tue.win.ga.model.LineSegment; /** * Iterator to randomly select a line segment. * * @author maikel */ public class RandomIterator implements Iterator<LineSegment> { private final List<LineSegment> linesegments; private final Random generator = new Random(0); public RandomIterator(List<LineSegment> linesegments) { this.linesegments = linesegments; } @Override public boolean hasNext() { return !linesegments.isEmpty(); } @Override public LineSegment next() { if (linesegments == null) { return null; } else { int index = generator.nextInt(linesegments.size()); final LineSegment result = linesegments.get(index); linesegments.remove(result); return result; } } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
C++
UTF-8
2,589
3
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
#include <piksi_multi_cpp/device/device.h> #include <piksi_multi_cpp/device/device_dummy.h> #include <piksi_multi_cpp/device/device_factory.h> #include <piksi_multi_cpp/device/device_tcp.h> #include <piksi_multi_cpp/device/device_usb.h> #include <ros/console.h> #include <regex> namespace piksi_multi_cpp { /* Creates device based on a unique identifier string * Examples: * usb:// * All USB devices (without space between slash + star) * usb://<serial number> USB device with given serial number * tcp://<host>:<port> TCP devices on that host with that port * * To be implemented in the future: * serial:///dev/ttyUSBx Device on Serial port /dev/ttyUSBx * */ std::vector<Device::Ptr> DeviceFactory::createByIdentifier( const piksi_multi_cpp::Identifier& id) { std::regex rgx("^(.+):\\/\\/(.+)$"); // check if id is of type protocol://id std::smatch match; if (std::regex_search(id, match, rgx) && match.size() > 1) { // if string is match. std::string protocol = match.str(1); std::string protocol_address = match.str(2); if (protocol == "usb") { if (protocol_address == "*") { // Autodiscovery of USB const Identifiers ids = DeviceUSB::discoverAllSerialNumbers(); return createByIdentifiers(ids); // recursive call of parent function. } else { // Specific USB device return {Device::Ptr(new DeviceUSB(protocol_address))}; } } else if (protocol == "serial") { return {Device::Ptr(new DeviceSerial(protocol_address))}; } else if (protocol == "tcp") { // Specific TCP device return {Device::Ptr(new DeviceTCP(protocol_address))}; } else if (protocol == "dummy") { return {Device::Ptr(new DeviceDummy(protocol_address))}; } else { ROS_WARN_STREAM("Warning, unknown device Protocol " << protocol); return {}; } } else { return {}; } } std::vector<Device::Ptr> DeviceFactory::createByIdentifiers( const piksi_multi_cpp::Identifiers& ids) { std::vector<Device::Ptr> devices; for (const auto& id : ids) { ROS_INFO_STREAM(id); auto devs = createByIdentifier(id); // copy valid devices into devices vector std::copy_if(devs.begin(), devs.end(), std::back_inserter(devices), [](auto dev_ptr) { return dev_ptr.get(); }); } ROS_WARN_COND(devices.empty(), "No device created."); return devices; } std::vector<Device::Ptr> DeviceFactory::createAllDevicesByAutodiscovery() { return createByIdentifier("usb://*"); } } // namespace piksi_multi_cpp
C++
UTF-8
546
2.84375
3
[]
no_license
#include <string> #include "redefine.h" /* BASIC INSTANTIATION AND SETUP */ redefine::redefine(){ size=0; } int redefine::getsize(){ return size; } void redefine::setsize(int n){ use_num=new int[n]; use=new string[n]; } /* SET & GET USES */ void redefine::set_use(string s){ use[size]=s; } void redefine::set_use_num(int n){ use_num[size]=n; size++; } string redefine::get_use(int i){ return use[i]; } int redefine::get_use_num(int i){ return use_num[i]; } ///////////////EOF///////////////
C++
UTF-8
9,249
2.53125
3
[]
no_license
#pragma once /*+ ________________________________________________________________________ (C) dGB Beheer B.V.; (LICENSE) http://opendtect.org/OpendTect_license.txt Author: N. Hemstra Date: May 2003 ________________________________________________________________________ -*/ #include "generalmod.h" #include "refcount.h" #include "position.h" #include "notify.h" #include "bufstring.h" #include "uistring.h" class BufferStringSet; class MenuItem; class MenuHandler; mExpClass(General) MenuItemHolder : public CallBacker { public: MenuItemHolder(); virtual ~MenuItemHolder(); Notifier<MenuItemHolder> removal; /*!< triggers when class is deleted */ virtual void addItem(MenuItem*,bool manage=false); /*!<\param manage specified wether the class will delete the item when it's not needed any longer. Mostly used when doing: \code item->addItem(new MenuItem("Menu text"),true); \endcode. Each item will get a unique id, that is the mechanism to see which item was selected in the menu. */ void removeItems(); int nrItems() const; const MenuItem* getItem(int idx) const; MenuItem* getItem(int idx); int itemIndex(const MenuItem*) const; int itemIndex(int id) const; MenuItem* findItem(int id); const MenuItem* findItem(int id) const; MenuItem* findItem(const char*); //!<Seaches for untranslated text const MenuItem* findItem(const char*) const; //!<Seaches for untranslated text const ObjectSet<MenuItem>& getItems() const; protected: friend class MenuHandler; void itemIsDeletedCB(CallBacker*); virtual void assignItemID(MenuItem&); /*!< Get a unique id for this item. */ MenuItemHolder* parent_; private: ObjectSet<MenuItem> items_; BoolTypeSet manageitems_; }; /*!A generic representation of an item in a menu. */ mExpClass(General) MenuItem : public MenuItemHolder { public: MenuItem(const uiString& text=uiString::emptyString(), int placement=-1); MenuItem(const uiString& text, CallBack cb,int placement=-1); MenuItem(const uiString& text, const char* iconnm, const uiString& tooltip, CallBack cb=CallBack(), int placement=-1); void createItems(const BufferStringSet&); void createItems(const uiStringSet&); uiString text; /*< The text that should be on the item. */ int placement; /*!< Gives the system an indication where in the menu the item should be placed. Items will be placed in increasing order of placement. */ int id; /*!< This item's unique id. */ bool checkable; /*!< If true, a check-mark can be placed */ bool checked; /*!< If true, a check-mark will be put infront of the items text */ bool enabled; /*!< If false, the item will be visble, but not selectable. */ BufferString iconfnm; //*!< Icon identifier uiString tooltip; //*!< Tooltip if item is used in toolbar CallBack cb; //*!< Callback function to be called }; mExpClass(General) SeparatorItem : public MenuItem { mODTextTranslationClass(SeparatorItem); public: SeparatorItem(int plmnt=-1) : MenuItem(tr("Separator"),plmnt) {} }; /*! A generic representation of a menu. It allows anyone to add their own custom menuitems to it. The principle is that the menu triggers it's createnotifier just before the menu should be displayed, and the application adds the items it wants into the menu. When the user has clicked on something in the menu, the handlenotifier is triggered and the application checks what should be done. Usage: \code menu->createnotifier.notify( mCB(this,myclass,createMenuCB) ); menu->handlenotifier.notify( mCB(this,myclass,handleMenuCB) ); \endcode Upon a create notification, your class might do something like this: \code void myclass::createMenuCB( CallBacker* callback ) { mDynamicCastGet( MenuHandler*, menu, callback ); mAddMenuItem( menu, &mymenuitem, true, false ); mAddMenuItem( menu, &mysubmenu, true, false ); mAddMenuItem( &mysubmenu, &mysubmenuitem1, true, false ); mAddMenuItem( &mysubmenu, &mysubmenuitem2, true, false ); } \endcode The code will make a menu with two items, and the second item will have a submenu with two items. The first boolean says whether the item should be enabled, the second one says where there should be a check before it. The menuitems are instantiations of MenuItem and should be stored in your class. They hold information about the item itself (like text, enabled or not enabled, checked or not checked, information on where in the menu it should be placed. In addition, it has an unique id that is set when the item is inserted into the menu. Upon a handle notification, your class might do something like this: \code void myclass::handleMenuCB(CallBacker* callback ) { mCBCapsuleUnpackWithCaller( int, mnuid, caller, callback ); mDynamicCastGet( MenuHandler*, menu, caller ); if ( mnuid==-1 || menu->isHandled() ) return; bool ishandled = true; if ( mnuid==mymenuitem.id ) do_something(); else if ( mnuid==mysubmenuitem1.id ) do_something_else(); else if ( mnuid==mymenusubitem2.id ) do_something_else(); else ishandled = false; menu->setIsHandled(ishandled); } \endcode */ mExpClass(General) MenuHandler : public RefCount::Referenced , public MenuItemHolder { public: MenuHandler( int id ); virtual bool executeMenu() = 0; int menuID() const { return id_; } /*<Each menu has an unique id where the that identifies it. */ void setMenuID( int newid ) { id_=newid; } Notifier<MenuHandler> initnotifier; Notifier<MenuHandler> createnotifier; CNotifier<MenuHandler,int> handlenotifier; bool isHandled() const; /*!< Should be called as the first thing from callbacks that is triggered from uiMenuHandler::handlenotifier. If isHandled() returns true, the callback should return immediately. */ void setIsHandled(bool); /*!<Should be called from callbacks that are triggered from uiMenuHandler::handlenotifier if they have found the menu id they are looking for. */ int queueID() const { return queueid_; } /*!<After a menu is executed, it will execute a queue, identified by this id. */ protected: ~MenuHandler(); void assignItemID(MenuItem&); void executeQueue(); int id_; bool ishandled_; int queueid_; }; /*! handles the MenuItem insertion automaticly. If the menu is selected, a callback is triggered. Default behaviour is that the menu item is added every time the menu is built, and that it's enabled but not checked. That can be changes by setting the doadd_, isenabled_ and ischecked_ or by an inheriting object in the shouldAddMenu(), shouldBeEnabled() and shouldBeChecked() functions. */ mExpClass(General) MenuItemHandler : public CallBacker { public: MenuItemHandler(MenuHandler&,const uiString& nm, const CallBack&,const char* parenttxt=0, int placement=-1); ~MenuItemHandler(); bool doadd_; /*!<Item is added if true AND shouldAddMenu() retuns true. Default is true. */ bool isenabled_; /*!<Item is enabled if true AND shouldBeEnabled() retuns true. Default is true. */ bool ischecked_; /*!<Item is checked if true OR shouldBeChecked() retuns true. Default is false. */ void setIcon(const char* fnm); protected: virtual void createMenuCB(CallBacker*); virtual void handleMenuCB(CallBacker*); virtual bool shouldAddMenu() const { return true; } virtual bool shouldBeEnabled() const { return true;} virtual bool shouldBeChecked() const { return false;} MenuItem menuitem_; MenuHandler& menuhandler_; CallBack cb_; BufferString parenttext_; }; #define mResetMenuItem( item ) \ { \ (item)->enabled = true; \ (item)->checked = false; \ (item)->id = -1; \ (item)->removeItems(); \ } #define mAddMenuItemWithManageFlag( parent, item, manage, enab, check ) \ { \ MenuItem* _item = item; \ MenuItemHolder* _parent = parent; \ if ( _parent && (_parent)->itemIndex(_item)==-1 ) \ (_parent)->addItem( _item ); \ \ (_item)->enabled = (enab); \ (_item)->checked = (check); \ } #define mAddMenuItem( parent, item, enab, check ) \ mAddMenuItemWithManageFlag( parent, item, false, enab, check ) #define mAddManagedMenuItem( parent, item, enab, check ) \ mAddMenuItemWithManageFlag( parent, item, true, enab, check ) #define mAddMenuItemCond( menu, item, enab, check, cond ) { \ if ( menu && cond ) \ mAddMenuItem( menu, item, enab, check ) \ else \ mResetMenuItem( item ) } \ //Macro that can poplulate both a toolbar and a menu. #define mAddMenuOrTBItem( istoolbar, tbparent, popupparent, item, enab, check )\ mAddMenuItem( \ istoolbar?(MenuItemHolder*)(tbparent):(MenuItemHolder*)(popupparent), \ item, enab, check )
Python
UTF-8
1,323
2.6875
3
[]
no_license
import numpy as np import pandas as pd sid_all = [1,4,5,7 ] sid_yb = [0,2,3,15] sid_floors = [8,10] sid_none = [6,9,11,12,13,14] raw_data = pd.read_csv('data/building_metadata.csv') print(raw_data.info(verbose=True),'\n') raw_data_sid_all = raw_data[raw_data['site_id'].isin(sid_all)] raw_data_sid_all['year_built'].fillna(raw_data_sid_all['year_built'].mean(), inplace = True) raw_data_sid_all['floor_count'].fillna(raw_data_sid_all['floor_count'].mean(), inplace = True) raw_data_sid_yb = raw_data[raw_data['site_id'].isin(sid_yb)] raw_data_sid_yb['year_built'].fillna(raw_data_sid_yb['year_built'].mean(), inplace = True) raw_data_sid_yb['floor_count'] = 0 raw_data_sid_floors = raw_data[raw_data['site_id'].isin(sid_floors)] raw_data_sid_floors['year_built'] = 0 raw_data_sid_floors['floor_count'].fillna(raw_data_sid_floors['floor_count'].mean(), inplace = True) raw_data_sid_none = raw_data[raw_data['site_id'].isin(sid_none)] raw_data_sid_none['year_built'] = 0 raw_data_sid_none['floor_count'] = 0 raw_data_comb = pd.concat([raw_data_sid_all, raw_data_sid_yb, raw_data_sid_floors, raw_data_sid_none]) print(raw_data_comb.info(verbose=True)) raw_data_comb.to_csv('building_fixed.csv', index = False)
Java
UTF-8
4,456
3.390625
3
[]
no_license
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Simulation { //Metoda do tworzenia pliku. public File createFile(String fileName) { File file = new File(fileName); return file; } //Metoda pobierająca listę rzeczy z pliku i ładująca ją do ArrayList<Item>. public ArrayList<Item> loadItems(File file) throws FileNotFoundException { //tworzenie Obiektu Scanner czytającego plik podany przez użytkownika. Scanner scanner = new Scanner(file); //ArrayList przechowująca listę zawierającą Obiekty Item. ArrayList<Item> listOfItem = new ArrayList<>(); //Pętla działająca tak długo jak będą jakieś wiersze tekstu w pliku, //odziela od siebie nazwę i wagę przedmiotu za pomocą separatora '=', //Tworzy obiekt typu Item i łąduje go do listOfItem. while (scanner.hasNextLine()) { String nameOfItem; int weight; String line = scanner.nextLine(); String splittedLine[] = line.split("="); nameOfItem = splittedLine[0]; weight = Integer.parseInt(splittedLine[1]); Item item = new Item(nameOfItem, weight); listOfItem.add(item); } return listOfItem; } //Metoda służąca załadowaniu i tworzeniu rakiet typu U1 do momentu aż wszystkie rzeczy z listy nie zostaną załadowanę //Rakiekta nie może być przeładowana. public ArrayList<U1> loadU1(ArrayList<Item> listOfItem) { //Tworzy listę zawierającą listę zapełnionych Rakiet typu U1 ArrayList<U1> listOfRocketU1 = new ArrayList<>(); int i = 0; //Pętla sprawdzająca czy w liście rzeczy są jeszcze rzeczy do załadowania. while (listOfItem.size() > 0) { //inkrementuje i aby każda rakieta miała swoją specyficzną nazwę. i++; U1 rocketU1 = new U1("U1shark" + i, 10000, 18000); //Pętla sprawdzająca czy załadowanie rakiety nie spowoduje przeciążenia maksymalnego załadunku. while (listOfItem.size() > 0 && rocketU1.canCarry(listOfItem.get(0))) { rocketU1.carry(listOfItem.get(0)); listOfItem.remove(0); } listOfRocketU1.add(rocketU1); } return listOfRocketU1; } public ArrayList<U2> loadU2(ArrayList<Item> listOfItem) { //Tworzy listę zawierającą listę zapełnionych Rakiet typu U1 ArrayList<U2> listOfRocketU2 = new ArrayList<>(); int i = 0; //Pętla sprawdzająca czy w liście rzeczy są jeszcze rzeczy do załadowania. while (listOfItem.size() > 0) { //inkrementuje i aby każda rakieta miała swoją specyficzną nazwę. i++; U2 rocketU2 = new U2("U2whale" + i, 18000, 29000); //Pętla sprawdzająca czy załadowanie rakiety nie spowoduje przeciążenia maksymalnego załadunku. while (listOfItem.size() > 0 && rocketU2.canCarry(listOfItem.get(0))) { rocketU2.carry(listOfItem.get(0)); listOfItem.remove(0); } listOfRocketU2.add(rocketU2); } return listOfRocketU2; } public int runSimulationU1(ArrayList<U1> listOfRockets) { int budget = 0; for (int i = 0; i < listOfRockets.size(); i++) { boolean land = false; while (land == false) { if (listOfRockets.get(i).launch()) { land = listOfRockets.get(i).land(); budget += listOfRockets.get(i).getRocketCost(); } else { budget += listOfRockets.get(i).getRocketCost(); } } } return budget; } public int runSimulationU2(ArrayList<U2> listOfRockets) { int budget = 0; for (int i = 0; i < listOfRockets.size(); i++) { boolean land = false; while (land == false) { if (listOfRockets.get(i).launch()) { land = listOfRockets.get(i).land(); budget += listOfRockets.get(i).getRocketCost(); } else { budget += listOfRockets.get(i).getRocketCost(); } } } return budget; } }
Python
UTF-8
17,632
2.703125
3
[]
no_license
import math import numpy as np import tensorflow as tf from tensorflow.python.framework import ops import gzip as gz import pickle numpts = 10000 #total number of points in file is 767928, but can be reduced for now, for training #################################################################################### #################### UPLOAD DATA AND LABELS FROM FILE ######################### #################################################################################### labels = np.zeros((numpts,18)) data = np.zeros((numpts,1000,4,1)) goodGenes = [] verbose = True with open('data/chr1_bp.txt','r') as f: genDict = {'n':4,'a':0, 'c':1,'t':2, 'g':3} badGenes = [] geneCount = 0 i = 0 while (i < numpts): file_content = f.readline() file_content = f.readline() geneseq = list(file_content) geneseq = geneseq[0:-1] if np.mod(i,int(numpts/10))==0: print(geneseq[0:10]) basecount = 0 #create single gene dataSingleGene = data[i,:,:,0] #print(dataSingleGene.shape) skipGene = False for base in geneseq: genInd = genDict[base.lower()] if genInd!=4: dataSingleGene[basecount,genInd] = 1 else: skipGene = True #print(i) basecount += 1 #add to data if its a good gene if not skipGene: data[i,:,:,0] = dataSingleGene i += 1 else: print(geneCount) badGenes.append(geneCount) geneCount += 1 with gz.open('hema_model_jason_only_oct17_idr_K562_GM12878_CV_corePeakSize_500_totalPeakSize_1000_neg_flank_offset_500_Sequential_1D_model_binaryPeaks.txt.gz', 'rb') as f: file_content = f.readline() file_content = str(file_content[0:-3]) print(file_content) file_content = file_content.split('\\t') file_content[0] = file_content[0][2:-1] file_content[-1] = file_content[-1][0:-2] i=0 geneCount = 0 while i< numpts: file_content = f.readline() file_content = str(file_content[0:-1]) file_content = file_content.split('\\t') file_content[0] = file_content[0][2:-1] file_content[-1] = file_content[-1][0:-1] if geneCount not in badGenes: labels[i][:] = [int(cont) for cont in file_content[4:]] if np.mod(i,int(numpts/10))==0 and verbose: print(i,len(file_content[4:]),file_content[0], labels[i]) i += 1 geneCount += 1 print("there are ",len(badGenes)," bad genes with 'N' in them") #################################################################################### #################### BEGIN MODEL ############################################## #################################################################################### #code taken largely from Coursera class 4 on CNN's in tensorflow def save_params(parameters, file): '''saves parameters to file as in main model code''' with open(file, 'wb') as f: pickle.dump(parameters, f) def load_params(file): '''loads and returns parameters from file as in main model code''' with open(file, 'rb') as f: parameters = pickle.load(f) return parameters def shuffle_data(X,Y): '''first index of both X and Y will be shuffled in unison''' shuffleXY = [(X[i],Y[i]) for i in range(X.shape[0])] np.random.seed(1) np.random.shuffle(shuffleXY) X_shuffle = np.zeros(X.shape) Y_shuffle = np.zeros(Y.shape) for i in range(X.shape[0]): X_shuffle[i] = shuffleXY[i][0] Y_shuffle[i] = shuffleXY[i][1] return(X_shuffle,Y_shuffle) def create_placeholders(n_H0, n_W0, n_C0, n_y): '''create placeholders for tensorflow X and Y''' X = tf.placeholder("float",shape=(None,n_H0,n_W0,n_C0)) Y = tf.placeholder("float",shape=(None,n_y)) return X, Y def initialize_parameters(use_saved_params): '''create CNN filters. If initP is present, use the given values, else use xavier initialization''' W1 = tf.get_variable("W1",[6,4,1,50]) W2 = tf.get_variable("W2",[32,1,50,50]) W3 = tf.get_variable("W3",[16,1,50,50]) W4 = tf.get_variable("W4",[8,1,50,1]) parameters = {"W1": W1, "W2": W2, "W3": W3, "W4": W4} return parameters def forward_propagation(X, parameters, keep_prob_conv, keep_prob_fc): '''propogate X forward through the network of two convolutional steps and a fully connected layer''' # Retrieve the parameters from the dictionary "parameters" W1 = parameters['W1'] W2 = parameters['W2'] W3 = parameters['W3'] W4 = parameters['W4'] # CONV2D: XX = tf.nn.conv2d(X,W1,strides=[1,1,1,1], padding='VALID') XX = tf.contrib.layers.batch_norm(XX) XX = tf.nn.relu(XX) XX = tf.nn.max_pool(XX, [1,4,1,1],[1,4,1,1], 'VALID') # CONV2D: XX = tf.nn.dropout(XX,keep_prob_conv) XX = tf.nn.conv2d(XX,W2,strides=[1,1,1,1], padding='VALID') XX = tf.contrib.layers.batch_norm(XX) XX = tf.nn.relu(XX) XX = tf.nn.max_pool(XX, [1,4,1,1],[1,4,1,1], 'VALID') # CONV2D: XX = tf.nn.dropout(XX,keep_prob_conv) XX = tf.nn.conv2d(XX,W3,strides=[1,1,1,1], padding='VALID') XX = tf.contrib.layers.batch_norm(XX) XX = tf.nn.relu(XX) # CONV1D: Bottleneck XX = tf.nn.dropout(XX,keep_prob_conv) XX = tf.nn.conv2d(XX,W4,strides=[1,1,1,1], padding='VALID') XX = tf.contrib.layers.batch_norm(XX) XX = tf.nn.relu(XX) # FLATTEN XX = tf.contrib.layers.flatten(XX) # FULLY-CONNECTED layers with non-linear activation functions. # 18 neurons in output layer. Hint: one of the arguments should be "activation_fn=None" XX = tf.nn.dropout(XX,keep_prob_fc) XX = tf.contrib.layers.fully_connected(XX,50,activation_fn=None) XX = tf.contrib.layers.batch_norm(XX) XX = tf.nn.sigmoid(XX) XX = tf.nn.dropout(XX,keep_prob_fc) Z3 = tf.contrib.layers.fully_connected(XX,18,activation_fn=None) return Z3 def compute_cost(Z3, Y): '''compute the cost of forward propagation''' cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=Z3,labels=Y)) return cost ########################################################################################### ################### Execute the model and Train data ##################################### ########################################################################################### #partition training/test data by 70/20/10 ratio numTrain = int(numpts*.7) numDev = int(numpts*.2) numTest = numpts - numTrain - numDev print("shuffling data with train/dev/dest ",numTrain,numDev,numTest) (X_shuffle,Y_shuffle) = shuffle_data(data,labels) X_train = X_shuffle[0:numTrain] Y_train = Y_shuffle[0:numTrain] X_dev = X_shuffle[numTrain:numTrain+numDev] Y_dev = Y_shuffle[numTrain:numTrain+numDev] #only test data will be used, but this is done for consistency with main model X_test = X_shuffle[numTrain+numDev:] Y_test = Y_shuffle[numTrain+numDev:] #test the model def test_model_multi_confusion_matrix(confInds, X_test = X_test, Y_test = Y_test): '''uses the test data to generate a confusion matrix from the given indices confInds -- array of ints e.g. [0,1,2] would generate the confusion matrix for the first three cell types of the 18 cell types. returns a confustion matrix of size 2**len(confInds)''' ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables (m, n_H0, n_W0, n_C0) = X_test.shape n_y = Y_test.shape[1] # Create Placeholders of the correct shape X, Y = create_placeholders(n_H0,n_W0,n_C0,n_y) # Initialize saved parameters parameters = initialize_parameters(True) # Forward propagation: Build the forward propagation in the tensorflow graph keep_prob_conv = 1 keep_prob_fc = 1 Z3 = forward_propagation(X, parameters, keep_prob_conv, keep_prob_fc) cost = compute_cost(Z3,Y) predict_op = tf.sigmoid(Z3) correct_prediction = tf.equal(tf.round(predict_op), Y) # Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) auROC, roc_update_op = tf.metrics.auc(Y, predict_op, curve = 'ROC') auPRC, prc_update_op = tf.metrics.auc(Y, predict_op, curve = 'PR') print(Y.shape,predict_op.shape) # combine rows of the data X, so that a confusion matrix can be easily created by tensorflow if len(confInds)<2: print("you should pick more than one output index for this function") i = 0 thresh = 0 Ymulti = tf.reduce_mean(tf.slice(tf.cast(Y, dtype=tf.int32),[0,confInds[i]],[m,confInds[i]+1]),axis=1) #extract the first label predmulti = tf.reduce_mean(tf.slice(tf.cast(tf.round(predict_op)+thresh, dtype=tf.int32),[0,confInds[i]],[m,confInds[i]+1]),axis=1) #extract the first label while i<len(confInds)-1: i = i + 1 Ymulti = Ymulti + (2**i) * tf.reduce_mean(tf.slice(tf.cast(Y, dtype=tf.int32),[0,confInds[i]],[m,confInds[i]+1]),axis=1) predmulti = predmulti + (2**i) * tf.reduce_mean(tf.slice(tf.cast(tf.round(predict_op)+thresh, dtype=tf.int32),[0,confInds[i]],[m,confInds[i]+1]),axis=1) #extract the first label #create confusion matrix conf_mat = tf.confusion_matrix(Ymulti, predmulti, num_classes = (2**len(confInds))) #spec_of_sens = tf.metrics.specificity_at_sensitivity(Y, predict_op, thresh) # Initialize all the variables globally init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) # Add ops to save and restore all the variables. saver = tf.train.Saver() # Start the session to compute the tensorflow graph with tf.Session() as sess: # Run the initialization sess.run(init) # Calculate the correct predictions saver.restore(sess, "best_metric_parameters3/model.ckpt") print("Model restored.") test_accuracy = accuracy.eval({X: X_test, Y: Y_test}) sess.run([roc_update_op,prc_update_op], feed_dict = {X: X_test, Y: Y_test}) test_auROC, test_auPRC = sess.run([auROC, auPRC], feed_dict = {X: X_test, Y: Y_test}) #test_metric = (1/2)*(test_auROC + test_auPRC) test_metric = test_auPRC #per Peyton's recommendation print ("Test Accuracy:", test_accuracy, "auROC:", test_auROC, "auPRC:", test_auPRC, "test_metric", test_metric) test_mat = conf_mat.eval({X: X_test, Y: Y_test}) print(Ymulti.eval({X: X_test, Y: Y_test})) print(predmulti.eval({X: X_test, Y: Y_test})) return test_mat #test the model def test_model_average_confusion_matrix(X_test = X_test, Y_test = Y_test): ''' generate a confusion matrix for each of the 18 cell types and average them all to get one 2 by 2 confusion matrix returns a 2 by 2 array of the confusion matrix''' ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables (m, n_H0, n_W0, n_C0) = X_test.shape n_y = Y_test.shape[1] # Create Placeholders of the correct shape X, Y = create_placeholders(n_H0,n_W0,n_C0,n_y) # Initialize saved parameters parameters = initialize_parameters(True) # Forward propagation: Build the forward propagation in the tensorflow graph keep_prob_conv = 1 keep_prob_fc = 1 Z3 = forward_propagation(X, parameters, keep_prob_conv, keep_prob_fc) cost = compute_cost(Z3,Y) predict_op = tf.sigmoid(Z3) correct_prediction = tf.equal(tf.round(predict_op), Y) # Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) auROC, roc_update_op = tf.metrics.auc(Y, predict_op, curve = 'ROC') auPRC, prc_update_op = tf.metrics.auc(Y, predict_op, curve = 'PR') print(Y.shape,predict_op.shape) conf_mats = [] for conf_mat_ind in range(18): Yslice = tf.slice(tf.cast(Y, dtype=tf.int32),[0,0],[m,1]) Yslice = tf.reduce_mean(Yslice, axis = 1) predslice = tf.slice(tf.cast(tf.round(predict_op),dtype=tf.int32),[0,0],[m,1]) predslice = tf.reduce_mean(predslice, axis = 1) conf_mat = tf.confusion_matrix(Yslice, predslice, num_classes = 2) conf_mats.append(conf_mat) #spec_of_sens = tf.metrics.specificity_at_sensitivity(Y, predict_op, thresh) # Initialize all the variables globally init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) # Add ops to save and restore all the variables. saver = tf.train.Saver() # Start the session to compute the tensorflow graph with tf.Session() as sess: # Run the initialization sess.run(init) # Calculate the correct predictions saver.restore(sess, "best_metric_parameters3/model.ckpt") print("Model restored.") test_accuracy = accuracy.eval({X: X_test, Y: Y_test}) sess.run([roc_update_op,prc_update_op], feed_dict = {X: X_test, Y: Y_test}) test_auROC, test_auPRC = sess.run([auROC, auPRC], feed_dict = {X: X_test, Y: Y_test}) #test_metric = (1/2)*(test_auROC + test_auPRC) test_metric = test_auPRC #per Peyton's recommendation print ("Test Accuracy:", test_accuracy, "auROC:", test_auROC, "auPRC:", test_auPRC, "test_metric", test_metric) #save_path = saver.save(sess, "best_model_parameters/model.ckpt") #print("Model saved in path: %s" % save_path) avg_mat = np.zeros((2,2)) for i in range(18): print("doing conf matrix ",i) avg_mat += conf_mats[i].eval({X: X_test, Y: Y_test}) avg_mat = avg_mat*(1/(1000*18)) return avg_mat #test the model def test_model_sens_spec_curve(X_test = X_test, Y_test = Y_test): ''' generates a sensitivity and specificity curve from the test data returns sensitivity_values, specificity_values each between 0 and 1 that can be plotted''' ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables (m, n_H0, n_W0, n_C0) = X_test.shape n_y = Y_test.shape[1] # Create Placeholders of the correct shape X, Y = create_placeholders(n_H0,n_W0,n_C0,n_y) # Initialize saved parameters parameters = initialize_parameters(True) # Forward propagation: Build the forward propagation in the tensorflow graph keep_prob_conv = 1 keep_prob_fc = 1 Z3 = forward_propagation(X, parameters, keep_prob_conv, keep_prob_fc) cost = compute_cost(Z3,Y) predict_op = tf.sigmoid(Z3) correct_prediction = tf.equal(tf.round(predict_op), Y) # Calculate accuracy on the test set accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) auROC, roc_update_op = tf.metrics.auc(Y, predict_op, curve = 'ROC') auPRC, prc_update_op = tf.metrics.auc(Y, predict_op, curve = 'PR') print(Y.shape,predict_op.shape) specs = [] sens = np.linspace(0,1,101) for i in range(101): sen = sens[i] specs.append(tf.metrics.specificity_at_sensitivity(Y, predict_op, sen)) #spec_of_sens = tf.metrics.specificity_at_sensitivity(Y, predict_op, thresh) # Initialize all the variables globally init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) # Add ops to save and restore all the variables. saver = tf.train.Saver() # Start the session to compute the tensorflow graph with tf.Session() as sess: # Run the initialization sess.run(init) # Calculate the correct predictions saver.restore(sess, "best_metric_parameters3/model.ckpt") print("Model restored.") test_accuracy = accuracy.eval({X: X_test, Y: Y_test}) sess.run([roc_update_op,prc_update_op], feed_dict = {X: X_test, Y: Y_test}) test_auROC, test_auPRC = sess.run([auROC, auPRC], feed_dict = {X: X_test, Y: Y_test}) #test_metric = (1/2)*(test_auROC + test_auPRC) test_metric = test_auPRC #per Peyton's recommendation print ("Test Accuracy:", test_accuracy, "auROC:", test_auROC, "auPRC:", test_auPRC, "test_metric", test_metric) specificity_values = np.zeros(101) sensitivity_values = np.linspace(0,1,101) for i in range(101): print(i) spec = specs[i][1].eval({X: X_test, Y: Y_test}) specificity_values[i] = spec return sensitivity_values, specificity_values #print(test_model_multi_confusion_matrix())
C++
UTF-8
833
3.265625
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution{ public: int integersplit(int n) { //基本思想:动态规划,dp[i][j]表示数字i拆分出最大值j的拆分可能的情况数 vector<vector<int>> dp(n+1,vector<int>(n+1,0)); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(i==1||j==1) dp[i][j]=1; else if(i==j) dp[i][j]=dp[i][j-1]+1; else if(i<j) dp[i][j]=dp[i][i]; else if(i>j) dp[i][j]=dp[i-j][j]+dp[i][j-1]; } } return dp[n][n]; } }; int main() { Solution solute; int n=50; cout<<solute.integersplit(n)<<endl; return 0; }
Markdown
UTF-8
4,891
2.75
3
[ "MIT" ]
permissive
<!-- * @version: * @Author: steven * @Date: 2020-06-09 22:49:27 * @LastEditors: steven * @LastEditTime: 2020-06-09 23:00:19 * @Description: --> Windows用户 第一次运行需要完整完成下面5个步骤。如果是再次运行,可以忽略前面3步的下载和安装,直接跳转到第四步和第五步。 第一步是根据操作系统下载并安装Miniconda,在安装过程中需要勾选“Add Anaconda to the system PATH environment variable”选项(如当conda版本为4.6.14时)。 第二步是下载包含本书全部代码的压缩包。我们可以在浏览器的地址栏中输入 https://zh.d2l.ai/d2l-zh-1.1.zip 并按回车键进行下载。下载完成后,创建文件夹“d2l-zh”并将以上压缩包解压到这个文件夹。在该目录文件资源管理器的地址栏输入cmd进入命令行模式。 第三步是使用conda创建虚拟(运行)环境。conda和pip默认使用国外站点来下载软件,我们可以配置国内镜像来加速下载(国外用户无须此操作)。 # 配置清华PyPI镜像(如无法运行,将pip版本升级到>=10.0.0) pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple 接下来使用conda创建虚拟环境并安装本书需要的软件。这里environment.yml是放置在代码压缩包中的文件。使用文本编辑器打开该文件,即可查看运行压缩包中本书的代码所依赖的软件(如MXNet和d2lzh包)及版本号。 conda env create -f environment.yml 若使用国内镜像后出现安装错误,首先取消PyPI镜像配置,即执行命令pip config unset global.index-url。然后重试命令conda env create -f environment.yml。 第四步是激活之前创建的环境。激活该环境是能够运行本书的代码的前提。如需退出虚拟环境,可使用命令conda deactivate(若conda版本低于4.4,使用命令deactivate)。 conda activate gluon # 若conda版本低于4.4,使用命令activate gluon 第五步是打开Jupyter记事本。 jupyter notebook 这时在浏览器打开 http://localhost:8888 (通常会自动打开)就可以查看和运行本书中每一节的代码了。 2. Linux/macOS用户 第一步是根据操作系统下载Miniconda,它是一个sh文件。打开Terminal应用进入命令行来执行这个sh文件,例如: # 以Miniconda官方网站上的安装文件名为准 sh Miniconda3-latest-Linux-x86_64.sh 安装时会显示使用条款,按“↓”继续阅读,按“Q”退出阅读。之后需要回答下面几个问题(如当conda版本为4.6.14时): Do you accept the license terms? [yes|no] [no] >>> yes Do you wish the installer to initialize Miniconda3 by running conda init? [yes|no] [no] >>> yes 安装完成后,需要让conda生效。Linux用户需要运行一次source ~/.bashrc或重启命令行应用;macOS用户需要运行一次source ~/.bash_profile或重启命令行应用。 第二步是下载包含本书全部代码的压缩包,解压后进入文件夹。运行以下命令。Linux用户如未安装unzip,可运行命令sudo apt install unzip安装。 mkdir d2l-zh && cd d2l-zh curl https://zh.d2l.ai/d2l-zh-1.1.zip -o d2l-zh.zip unzip d2l-zh.zip && rm d2l-zh.zip 第三步至第五步可参考前面Windows下的安装步骤。若conda版本低于4.4,其中第四步需将命令替换为source activate gluon,并使用命令source deactivate退出虚拟环境。 3. 使用GPU版的MXNet 通过前面介绍的方式安装的MXNet只支持CPU计算。本书中部分章节需要或推荐使用GPU来运行。如果你的计算机上有NVIDIA显卡并安装了CUDA,建议使用GPU版的MXNet。 第一步是卸载CPU版本MXNet。如果没有安装虚拟环境,可以跳过此步。如果已安装虚拟环境,需要先激活该环境,再卸载CPU版本的MXNet。 pip uninstall mxnet 然后退出虚拟环境。 第二步是更新依赖为GPU版本的MXNet。使用文本编辑器打开本书的代码所在根目录下的文件environment.yml,将里面的字符串“mxnet”替换成对应的GPU版本。例如,如果计算机上装的是8.0版本的CUDA,将该文件中的字符串“mxnet”改为“mxnet-cu80”。如果计算机上安装了其他版本的CUDA(如7.5、9.0、9.2等),对该文件中的字符串“mxnet”做类似修改(如改为“mxnet-cu75”“mxnet-cu90”“mxnet-cu92”等)。保存文件后退出。 第三步是更新虚拟环境,执行命令 conda env update -f environment.yml 之后,我们只需要再激活安装环境就可以使用GPU版的MXNet运行本书中的代码了。需要提醒的是,如果之后下载了新代码,那么还需要重复这3步操作以使用GPU版的MXNet。 2.1.4. 小结 为了能够动手学深度学习,需要获取本书的代码并安装运行环境。 建议大家定期更新代码和运行环境。
Markdown
UTF-8
570
2.796875
3
[]
no_license
# Digit recognition app An web app created using flask and a deep CNN model to identify hand-drawn digits. You can find the model at CNN folder. Deployed the app in heroku at <a href="https://digit-recognition-app.herokuapp.com" target=_blank>https://digit-recognition-app.herokuapp.com</a> (P.S. sometimes, the link takes a while to load). Currently, it is only supported on PCs and laptops. <img width="1303" alt="Screen Shot 2021-03-17 at 10 32 40 PM" src="https://user-images.githubusercontent.com/46661726/111564799-435bd980-8792-11eb-9de2-be6dcdcc5626.png">
Java
UTF-8
1,151
2.4375
2
[]
no_license
package com.synaptix.swing.roulement; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import com.synaptix.swing.DayDate; public interface RoulementTimelineTaskRenderer { /** * Pourcentage de la hauteur prise par la tache * * @return valeur entre 0 et 1 */ public abstract double getSelectionHeightPourcent(); /** * Dessine la tache * * @param g * @param rect * @param simpleDaysTimeline * @param task * @param isSelected * @param hasFocus * @param resource */ public abstract void paintTask(Graphics g, Rectangle rect, JRoulementTimeline simpleDaysTimeline, RoulementTask task, boolean isSelected, boolean hasFocus, int resource); /** * Donner le tooltips selon la date et la position du point * * @param rect * @param simpleDaysTimeline * @param task * @param resource la ligne selon l'affichage * @param dayDate le jour * @param point la position exacte dans le rectangle * @return */ public abstract String getToolTipText(Rectangle rect, JRoulementTimeline simpleDaysTimeline, RoulementTask task, int resource, DayDate dayDate, Point point); }
TypeScript
UTF-8
2,538
2.53125
3
[]
no_license
import { Directive, ElementRef, Input, HostListener } from '@angular/core'; import { TooltipService } from "./tooltip.service"; @Directive({ selector: '[xTooltip]' }) export class TooltipDirective { @Input('content') content: string; @Input('tooltipBind') tooltipBind: string; enabled: Boolean; focused: Boolean; private id: string; constructor(private tooltipService: TooltipService, private eRef: ElementRef) { this.enabled = false; this.focused = false; this.id = Math.random()*9999+""; } private GetTooltip(): any { let self = this; let myTooltip = this.tooltipService.tooltips.find(function(element) { return element.id == self.id; }); return myTooltip; } @HostListener("document:mousedown", ["$event"]) onmousedown(event) { let myTooltip = this.GetTooltip(); if (this.eRef.nativeElement.contains(event.target)) { myTooltip ? this.hide(true) : this.display(true); } else if (!(myTooltip && myTooltip.eRef.nativeElement.contains(event.target))) { myTooltip ? this.hide(true) : null; } } @HostListener("focus", ['$event']) onfocus(event) { this.focused = true; } @HostListener("blur", ['$event']) onblur(event) { this.focused = false; } @HostListener("document:keydown", ['$event']) onkeydown(event) { let myTooltip = this.GetTooltip(); if (event.keyCode === 13 || event.keyCode === 32) { if (this.focused) { myTooltip ? this.hide() : this.display(); } } else if (event.keyCode === 27) { this.hide(true); } } display(force?: Boolean): void { if (this.enabled && !force) {return;} this.enabled = true; let bindElm = null; if (this.tooltipBind) { bindElm = this.eRef.nativeElement.querySelector(this.tooltipBind); if (!bindElm) { bindElm = this.eRef.nativeElement.parentElement.querySelector(this.tooltipBind); } if (!bindElm) { bindElm = this.eRef.nativeElement.closest(this.tooltipBind); } } let obj = { id: this.id, ref: this.eRef, bindRef: bindElm, content: this.content }; this.tooltipService.tooltips = []; this.tooltipService.tooltips.push(obj); } hide(force?: Boolean): void { if (!this.enabled && !force) {return;} this.enabled = false; let self = this; let ind = this.tooltipService.tooltips.findIndex(function(element) { return element.id === self.id; }); this.tooltipService.tooltips.splice(ind,1); } }
Python
UTF-8
3,224
3.625
4
[]
no_license
import fodboldtur # En decorator som vedhæfter en forklaring til en funktion def described(description: str): def decorator(target: callable): target.description = description return target return decorator @described("Vis hvor meget hver person har indbetalt") def print_payments(): for name, paid in fodboldtur.paid_all(): if paid < fodboldtur.total_amount: print(f"{name}: indebetalt: {paid / 100} kr., manglende: {(fodboldtur.total_amount - paid) / 100} kr.") else: print(f"{name}: indebetalt: {paid / 100} kr., fuldt betalt!") @described("Vis dem som har betalt mindst") def print_worst_payers(): # Jeg har valgt at lade brugeren vælge hvor mange personer de vil se def input_how_many(): try: number = int(input("Antal personer: ")) except ValueError: print("Antallet er ikke gyldigt") return input_how_many() else: if number <= 0: print("Antal skal være over 0") return input_how_many() else: return number how_many = input_how_many() worst = fodboldtur.worst_payers(how_many) for name, paid in worst: if paid == 0: print(f"{name} har ikke betalt noget som helst!") else: print(f"{name} har kun betalt {paid / 100} kr.") print("Puuuha, det er simpelthen for dårligt!") @described("Indbetal eller tilbagefør beløb") def deposit(): # Jeg har valgt at tillade negative indbetalinger def input_amount() -> int: amount_string = input("Beløb (kr.): ") valid, error = fodboldtur.validate_amount(name, amount_string) if not valid: print(error) return input_amount() else: converted_amount = round(float(amount_string) * 100) return converted_amount def input_name() -> str: name_input = input("Navn: ") if name_input not in fodboldtur.names(): print("Navn findes ikke") return input_name() else: return name_input name = input_name() amount = input_amount() fodboldtur.deposit(name, amount) print( f"{name} har i alt indbetalt {fodboldtur.paid(name) / 100} kr., " f"og mangler dermed at betale {(fodboldtur.total_amount - fodboldtur.paid(name)) / 100} kr." ) @described("Gem og afslut") def save_and_quit(): fodboldtur.save() print("Programmet er afsluttet!") quit() def menu(): commands = { "1": print_payments, "2": print_worst_payers, "3": deposit, "4": save_and_quit } def input_command(): input_string = input("Indtast dit valg: ") if input_string in commands: return input_string else: print("Denne kommando er ikke gyldig") return input_command() while True: print("\nMENU") for key, function in commands.items(): print(f"{key}: {function.description}") command = input_command() function = commands[command] function() if __name__ == "__main__": menu()
Java
UTF-8
1,257
2.625
3
[]
no_license
public class ConfigParams { private int epochs; public boolean isShowFood() { return showFood; } public void setShowFood(boolean showFood) { this.showFood = showFood; } private boolean showFood; public int getEpochs() { return epochs; } public void setEpochs(int epochs) { this.epochs = epochs; } public int getLifeProbability() { return lifeProbability; } public void setLifeProbability(int lifeProbability) { this.lifeProbability = lifeProbability; } public int getMaxFood() { return maxFood; } public void setMaxFood(int maxFood) { this.maxFood = maxFood; } public int getFoodIncrease() { return foodIncrease; } public void setFoodIncrease(int foodIncrease) { this.foodIncrease = foodIncrease; } public int getFoodDecrease() { return foodDecrease; } public void setFoodDecrease(int foodDecrease) { this.foodDecrease = foodDecrease; } private int lifeProbability; private int maxFood; private int foodIncrease; private int foodDecrease; public boolean validate(){ return lifeProbability>0 && maxFood>0; } }
Java
UTF-8
623
2.140625
2
[]
no_license
package pl.spring.module6; import java.text.ParseException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pl.spring.module6.service.TaskService; public class Runner { public static void main(String[] args) throws ParseException { ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/app-context.xml"); TaskService taskService = context.getBean(TaskService.class); taskService.addTask("Zadanie 200", "2016-12-24", "2016-12-25"); taskService.findAllTasks(); } }
Java
UTF-8
567
2.21875
2
[]
no_license
package org.usfirst.frc4919.Robot2018.commands; import org.usfirst.frc4919.Robot2018.Robot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; public class LiftCube extends Command { public LiftCube() { requires(Robot.armMotor); } @Override protected boolean isFinished() { // TODO Auto-generated method stub return isTimedOut(); } protected void initialize() { Timer.delay(3); setTimeout(1); } protected void execute() { Robot.armMotor.liftArm(); } protected void end() { Robot.armMotor.armStop(); } }
Python
UTF-8
1,330
4.28125
4
[]
no_license
# defining a function called hotel cost with argument called nights def hotel_cost(nights): # hotel cost p/n return nights*140 # defining a function called plane ride cost that takes city as a string def plane_ride_cost(city): # returns different prices depending on location if "cape town" == city: return 2500 elif "durban" == city: return 2300 elif "jhb" == city: return 2000 elif "bfn" == city: return 1800 # defining function called rental car cost with days as argument def rental_car_cost(days): # cost of renting car p/d car_cost = 40 * days # discount of R50 if car is rented for longer than 7 days if days >= 7: car_cost= car_cost - 50 # discount of R20 if car is rented for more than 3 days but less than 7 days elif days >= 3 and days < 7: car_cost = car_cost - 20 return car_cost # defining a function called trip cost with three arguments city, days and spending money def trip_cost(city, days, spending_money): # returning all functions return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money # printing the trip costs print(trip_cost("bfn", 2, 1800)) print(trip_cost("cape town", 2, 2500)) print(trip_cost("jhb", 2, 2000)) print(trip_cost("durban", 2, 2300))
C++
UTF-8
897
2.765625
3
[]
no_license
#include <GameState.h> #include <SPIManager.h> #include "Dummy.h" GameState game; Dummy module(&game); SPIManager spiManager(&game); void setup() { Serial.begin(115200); module.start(); spiManager.setModuleType(ModuleType::Control); } void loop() { while (Serial.available()) { switch (Serial.read()) { case 'a': spiManager.strikeModule(); Serial.println("strikeModule()"); break; case 'b': spiManager.disarmModule(); Serial.println("disarmModule()"); break; case 'c': spiManager.playSound(PlaySound::Strike); Serial.println("playSound()"); break; case 'd': spiManager.startGame(); Serial.println("startGame()"); break; case 'e': spiManager.stopGame(); Serial.println("stopGame()"); break; default: break; } } }
Markdown
UTF-8
1,012
3.46875
3
[]
no_license
# jQuery Trivia Game Using jQuery and the The Open Trivia Database API (https://opentdb.com/) create a trivia game. It must meet the following requirements: <ul> <li>Uses jQuery </li> <li>Uses the Open Trivia Database API</li> <li>Incorporates at least one jQuery Plugin</li> <li>Support two players where each player gets X number of questions and then is scored. </li> <li>The winner is the player with the highest score</li> </ul> Incorporate Classes for the following with suggested methods and attributes: <ul> <li>Game</li> <ul> <li>game.start()</li> <li>game.players</li> </ul> <li>Player</li> <ul> <li>player.name</li> <li>player.score</li> <li>player.wins</li> <li>player.losses</li> <li>player.questions</li> </ul> <li>Question</li> <ul> <li>question.answers</li> <li>question.correct_answer</li> <li>question.answer_is_correct(ans)</li> </ul> </ul> To make things easier to start, constrain your questions to one type.
C
UTF-8
5,787
3.46875
3
[]
no_license
/* * Author - Apoorv Bhargava * File Name - client.h */ #include "client.h" struct arguments argument= {"","","","",FALSE,FALSE,FALSE,FALSE}; /* Assigning default values to the arguments struct */ /* * Function : usage - Prints the usage instructions * Parameter : None * Return : NULL */ void usage(){ printf("Usage:\n"); printf("\tclient --server <server ip [or hostname]> --user <username>\ --password <password> --exec <program to execute>\n"); printf("\tSupports the following command line options.\n"); printf("\t\t-s, --server : Server IP address.\n"); printf("\t\t-u, --username : Username.\n"); printf("\t\t-p, --password : Password.\n"); printf("\t\t-c, --exec : Execution Command.\n\n"); } /* * Function : ClientConnection - Creates a TCP connection with SERVER and sends the command it. * Parameter : char server_ip[MAXLEN] * char username[MAXLEN] * char password[MAXLEN] * char command[MAXLEN] * Return : NULL */ int ClientConnection(char server_ip[MAXLEN],char username[MAXLEN], char password[MAXLEN],char command[MAXLEN]){ /* Declaring variable -- Start */ int serverConnection; int bytesSent=0,bytesReceived=0; struct sockaddr_in serverSocketAddress; struct hostent *serverIP; char sendBuff[3*MAXLEN]; char recvBuff[3*MAXLEN]; /* Declaring variable -- End */ /* Create server socket */ serverConnection = socket(AF_INET, SOCK_STREAM, 0); /* Check if socket created */ if (serverConnection < 0){ printf("ERROR: Unable to open socket.\n"); return 0; } /* Check if valid IP address -- Start */ if(inet_pton(AF_INET, server_ip, &(serverSocketAddress.sin_addr)) <= 0){ /* If invalid IP then the user might have given hostname */ serverIP = gethostbyname(server_ip); if(serverIP == NULL){ printf("ERROR: Invalid IP address/Host name provided\n"); return 0; }else{ bcopy((char *)serverIP->h_addr, (char *) &serverSocketAddress.sin_addr.s_addr, serverIP->h_length); } } /* Check if valid IP address -- End */ /* Set serverSocketAddress -- Start */ serverSocketAddress.sin_family = AF_INET; serverSocketAddress.sin_port = htons(SERVER_PORT); /* Set serverSocketAddress -- End */ /* Connect to Server -- Start */ if (connect(serverConnection,(struct sockaddr *) &serverSocketAddress, sizeof(serverSocketAddress)) < 0){ printf("ERROR: Unable to connect to Server\n"); return 0; } /* Connect to Server -- End */ /* Re-initialize variables -- Start */ bytesSent=0;bytesReceived=0; memset(sendBuff, '\0' ,sizeof(sendBuff)); memset(recvBuff, '\0' ,sizeof(recvBuff)); /* Re-initialize variables -- End */ /* Send request to Server -- Start */ sprintf(sendBuff, "u`%s,p`%s,c`%s", username,password,command); bytesSent = write(serverConnection, (void*)&sendBuff, sizeof(sendBuff)); if (bytesSent < 0){ printf("ERROR: unable to send request Server."); return 0; } /* Send request to Server -- End */ /* Receive result from Server -- Start */ while(1){ memset(recvBuff, '\0' ,sizeof(recvBuff)); bytesReceived=recv(serverConnection, &recvBuff, sizeof(recvBuff), 0); if(bytesReceived < 0){ printf("ERROR: Error in receiving data from Server."); return 0; } if(strstr(recvBuff,"***The End***") != NULL){ /* If the last message -- Strip the ending message */ /* Weird way but using backspace reduces string manipulation, though not a scalable way but for current scenario this solution seems to be a fitting one */ printf("%s\b\b\b\b\b\b\b\b\b\b\b\b\b",recvBuff); return 0; } fputs(recvBuff, stdout); } printf("\n"); /* Receive result from Server -- End */ /* Closing the TCP connection */ close(serverConnection); return 0; } /* * Function : main - Initiate client, reads the argument, establishes TCP connection with server and sends command to server. * Parameter : arguments * Return : 0 */ int main(int argc, char** argv){ int opt = 0; /* CommandLine argument handler */ /* Handling command line arguments */ static struct option cmdLongOpts[] = { {"server", required_argument, 0, 's'}, {"user", required_argument, 0, 'u'}, {"password", required_argument, 0, 'p'}, {"exec", required_argument, 0, 'c'}, {NULL, 0, NULL, 0} }; /* Parse the arguments -- Start */ while ((opt = getopt_long(argc, argv,"s:u:p:c:",cmdLongOpts, NULL)) != -1){ switch(opt) { case 's': argument.has_server=TRUE; strncpy(argument.server, optarg, MAXLEN); break; case 'p': argument.has_password=TRUE; strncpy(argument.password, optarg, MAXLEN); break; case 'u': argument.has_username=TRUE; strncpy(argument.username, optarg, MAXLEN); break; case 'c': if(strlen(optarg) > MAXLEN){ printf("Please provide Execution Command\ less than %d.\n\n",MAXLEN); usage(); exit(0); } argument.has_command=TRUE; strncpy(argument.command, optarg, MAXLEN); break; default: printf("Please provide valid arguments.\n\n"); usage(); exit(0); } } /* Parse the arguments -- End */ /* Check if all required arguments provided -- Start */ if(!argument.has_server){ printf("Please provide Server Address.\n\n"); usage(); exit(0); } if(!argument.has_username || !argument.has_password){ printf("Please provide username and password.\n\n"); usage(); exit(0); } if(!argument.has_command){ printf("Please provide Execution Command.\n\n"); usage(); exit(0); } /* Check if all required arguments provided -- End */ /* Create connection to server and send request -- Start */ ClientConnection(argument.server,argument.username, argument.password,argument.command); /* Create connection to server and send request -- End */ return 0; }
JavaScript
UTF-8
863
2.546875
3
[]
no_license
const shortid = require('shortid'); const fs = require('fs'); const path = require('path'); const uploadAudio = async (audioFile, relativePath) => { let audioLink; try { const absolutePath = path.join(__dirname, '../../static', relativePath); fs.mkdirSync(absolutePath, { recursive: true, }); const fileName = audioFile.name.trim(); const indexOfDot = fileName.lastIndexOf('.'); const temp = fileName.slice(0, indexOfDot) + shortid.generate() + fileName.slice(indexOfDot, fileName.length); const newName = temp.split(' ').join('-'); const filePath = `${absolutePath}/${newName}`; await audioFile.mv(filePath); audioLink = `${relativePath}/${newName}`; } catch (err) { throw new Error(`Can't store audio + ${audioFile.name}`); } return audioLink; }; module.exports = uploadAudio;
Markdown
UTF-8
2,414
2.796875
3
[ "MIT" ]
permissive
# Overview This code contains various machine learning methods for discovering dimensionless groups from simulation/experimental data. Check out the details in the Arxiv paper: [Dimensionally Consistent Learning with Buckingham Pi](https://arxiv.org/abs/2202.04643). Here's the abstract: ## Abstract In the absence of governing equations, dimensional analysis is a robust technique for extracting insights and finding symmetries in physical systems. Given measurement variables and parameters, the Buckingham Pi theorem provides a procedure for finding a set of dimensionless groups that spans the solution space, although this set is not unique. We propose an automated approach using the symmetric and self-similar structure of available measurement data to discover the dimensionless groups that best collapse this data to a lower dimensional space according to an optimal fit. We develop three data-driven techniques that use the Buckingham Pi theorem as a constraint: (i) a constrained optimization problem with a non-parametric input-output fitting function, (ii) a deep learning algorithm (BuckiNet) that projects the input parameter space to a lower dimension in the first layer, and (iii) a technique based on sparse identification of nonlinear dynamics (SINDy) to discover dimensionless equations whose coefficients parameterize the dynamics. We explore the accuracy, robustness and computational complexity of these methods as applied to three example problems: a bead on a rotating hoop, a laminar boundary layer, and Rayleigh-Bénard convection. # Content summary - `testcases`: tests all the methods on various problems: Blasius boundary layer, bead on a rotating hoop, Rayleigh-Benard problem. Showing basic usage and examples. - `src`: contains the main machine learning code for methods: Constrained optimization, BuckiNet and other helper functions. - `solvers`: contains numerical solvers to generate simulation data - `data`: contains data that is simulated outside this code, i.e. the Rayleigh-Benard problem (the full simulation data is too large to include in this repo and is available upon request). # Requirements Tested with the following: - Software dependencies: numpy 1.21, scipy 1.6, matplotlib 3.1, tensorflow 2.8, IPython 7.13, sklearn 0.24.1, sympy 1.8. - OS: Unix (should work on windows but hasn't been tested). - Hardware: GPUs are use if available but are not required.
JavaScript
UTF-8
3,443
3.28125
3
[]
no_license
var $noteTitle = $(".note-title"); var $noteText = $(".note-textarea"); var $saveNoteBtn = $(".save-note"); var $newNoteBtn = $(".new-note"); var $noteList = $(".list-container .list-group"); // activeNote is used to keep track of the note in the textarea var activeNote = {}; // A function for getting all notes from the db var getNotes = function() { $.ajax({ type: "GET", url: "/api/notes" }).then(res => { return res; }; // A function for saving a note to the db var saveNote = function(note) { $.ajax({ type: "POST", url: "/api/notes", data: {note} }).then(res => { if (res) { console.log("Note Saved!"); } }; // A function for deleting a note from the db var deleteNote = function(title) { $.ajax({ url: "/api/notes", method: 'DELETE', data: { title } }).then(res => { if (res) { console.log("Note Deleted!"); } }); }; // If there is an activeNote, display it, otherwise render empty inputs var renderActiveNote = function() { if(activeNote != null) { $noteText.text = activeNote; } else $noteText.text = ""; }; // Get the note data from the inputs, save it to the db and update the view var handleNoteSave = function() { saveNote(activeNote); handleNewNoteView(); handleRenderSaveBtn(); renderNoteList(); }; // Delete the clicked note var handleNoteDelete = function(event) { let itemToRemove = document.getElementById(event); itemToRemove.parentNode.removeChild(itemToRemove); deleteNote(event); }; // Sets the activeNote and displays it var handleNoteView = function() { let x = $("list-group-item").id; $noteTitle.text = getNotes[x].title; $noteText.text = getNotes[x].text; activeNote = {title: $noteTitle.text, text: $noteText.text}; }; // Sets the activeNote to an empty object and allows the user to enter a new note var handleNewNoteView = function() { activeNote = {}; }; // If a note's title or text are empty, hide the save button // Or else show it var handleRenderSaveBtn = function() { if ($noteTitle == '' || $noteText == '') { $saveNoteBtn.hide(); } else $saveNoteBtn.show(); }; // Renders the list of note titles var renderNoteList = function(notes) { let notes = getNotes(); for (let i = 0; i < notes.length; i++) { let $note = $('<div>') let $title = $('<div>') let $text = $('<div>') let $delBtn = $('<button>') $note.attr('class', 'card') $title.text(notes[i].title); $title.attr('class', 'note-title card-header') $title.attr('id', `title${i}`) $txt.text(notes[i].text) $txt.attr('class', 'note-textarea card-body') $dltBtn.text('Delete') $dltBtn.attr('class', 'delete-note'); $dltBtn.attr('id', i) $note.append($title); $note.append($text); $note.append($delBtn); $("#noteList").append($note); } }; // Gets notes from the db and renders them to the sidebar var getAndRenderNotes = function() { let notes = getNotes(); $('#noteList').clear(); renderNoteList(); }; $saveNoteBtn.on("click", handleNoteSave); $noteList.on("click", ".list-group-item", handleNoteView); $newNoteBtn.on("click", handleNewNoteView); $noteList.on("click", ".delete-note", handleNoteDelete); $noteTitle.on("keyup", handleRenderSaveBtn); $noteText.on("keyup", handleRenderSaveBtn); // Gets and renders the initial list of notes getAndRenderNotes();
Markdown
UTF-8
1,881
3.4375
3
[]
no_license
# 题目描述 <div><b>【问题描述】</b></div> <div>N个政党的领导人参加一次圆桌会议讨论政治问题,但是某些领导人不愿意与其他某些政党的领导人坐在一起。这N个领导人用1,2,…,N来表示。I不愿意与J坐在一起不一定表示J不愿意与I坐在一起,但是在这种情况下,I与J还是不能坐在一起,因为I不喜欢J。<br/> 用一个以1开头的1,2,…,N的排列来表示一种安排座位的方案,假定排列的最后一个数字与1是相邻的。排列的方案要以字典顺序输出。而且,顺时针和逆时针的情况被认为是相同的。<br/> 写一个程序,输出所有可行的座位安排方案。</div> <div><b>【</b>输入格式】</div> <div>输入格式(输入文件名dislike.in)<br/> 输入文件包含多组数据。<br/> 每组数据的第1行是数据编号C和领导人的数目N(N&lt;=40)。<br/> 接下来是一个N行N列的矩阵D,如果I不愿意与J坐在一起,那么矩阵的第,行的第J个数为1,否则为0。同行整数之间用一个空格分隔。<br/> 当C=0时输入文件结束。</div> <div><b>【</b>输出格式】</div> <div>输出格式(输出文件名dislike.out)<br/> 对于输入的每一组数据,首先在一行输出数据编号C和所有可行的安排方案的总数K。<br/> 接下来的K行按字典顺序输出每种可行的方案。两组相邻的输出数据间用一个空行分隔</div> <div>(注:输出数据顺序与输入数据一致即可)</div> <div><b>【</b>输入输出样例】</div> <div>输入(dislike.in)<br/> 1 5<br/> 1 1 0 1 0<br/> 0 1 0 0 1<br/> 0 0 1 0 0<br/> 1 0 0 1 0<br/> 0 1 0 1 1<br/> 2 6<br/> 1 0 1 1 0 0<br/> 0 1 0 0 0 1<br/> 1 0 1 0 0 0<br/> 1 0 0 1 1 0<br/> 0 0 1 0 1 1<br/> 0 1 0 0 1 1<br/> 0<br/> 输出(dislike.out)<br/> 1 0<br/> 2 2<br/> 1 5 2 3 4 6<br/> 1 5 2 4 3 6</div>
Java
UTF-8
3,079
3.640625
4
[]
no_license
package initializationAndCleanupChapter5; import java.lang.reflect.Type; public class InitClean { //Ex. 3,4 InitClean() { System.out.println("Hello!"); } InitClean(String str) { System.out.println("Hello, " + str); } //Ex. 19 static void f(String[] strs, String... args) { for (String s: strs) { System.out.println(s); } for (String s: args) { System.out.println(s); } } public static void main(String[] args) throws Throwable { InitClean ic1 = new InitClean("howdy?"); InitClean ic2 = new InitClean(); Dog dog = new Dog(7); dog.bark(5, 'g'); // dog.bark('R', 10); // dog.bark(false); //Ex. 11 try { dog.finalize(); } catch (Throwable e) { return; } Tank tk = new Tank(); tk.add(10); tk.finalize(); System.out.println("---------"); //Ex. 16 String[] strs = new String[]{"hello", "my", "dear"}; for (String s : strs) { System.out.println(s); } StrString[] strings; f(strs, args); //Ex. 21 for (TypesOfBanknouts type : TypesOfBanknouts.values()) { System.out.println(type + " " + type.ordinal()); } TypesOfBanknouts type = TypesOfBanknouts.SECOND; //Ex. 22 switch (type) { case FIRST: break; case SECOND: System.out.println(type); break; default: System.out.println("Nothing match"); } } } //Ex. 17 class StrString{ StrString(String s) { System.out.println(s); } } //Ex. 12 class Tank { int capacity; void add(int num) { capacity += num; } void toEmpty() { System.out.println("toEmpty()"); capacity = 0; } @Override protected void finalize() throws Throwable{ this.toEmpty(); super.finalize(); } } //Ex. 6 class Dog { //Ex. 9 Dog() { //this(7); System.out.println("Dog()"); } Dog(int num) { this(); System.out.println("Dog(" + num + ")"); } //Ex. 8 void bark(int i, char c) { System.out.println("Bark " + i + " times " + c); bark(c,i); this.bark(c,i); } void bark(char c, int n) { for(int i = 0; i < n; i ++) { System.out.print(c); } System.out.println(" " + n + " times"); } void bark(boolean b) { if (b) { System.out.println("True to barking"); }else { System.out.println("Faaalse!!"); } } //Ex. 10 @Override protected void finalize() throws Throwable { System.out.println("finalize()"); //not working super.finalize(); } }
JavaScript
UTF-8
707
4.875
5
[]
no_license
/* Write a function that takes a non-empty string argument, and returns * the middle character(s) of the string. If the string has an odd length, * you should return exactly one character. If the string has an even * length, you should return exactly two characters. */ function centerOf(string) { const isOdd = string.length % 2 === 1; const midpoint = Math.ceil(string.length / 2) - 1; if (isOdd) { return string[midpoint]; } else { return string[midpoint] + string[midpoint + 1]; } } centerOf('I Love JavaScript'); // "a" centerOf('Launch School'); // " " centerOf('Launch'); // "un" centerOf('Launchschool'); // "hs" centerOf('x'); // "x"
SQL
UTF-8
9,797
3.421875
3
[]
no_license
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for access -- ---------------------------- CREATE TABLE `access` ( `role_id` smallint(6) unsigned NOT NULL, `node_id` smallint(6) unsigned NOT NULL, `level` tinyint(1) NOT NULL, `module` varchar(50) DEFAULT NULL, KEY `groupId` (`role_id`), KEY `nodeId` (`node_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for attachment -- ---------------------------- CREATE TABLE `attachment` ( `aid` int(10) unsigned NOT NULL AUTO_INCREMENT, `file_name` varchar(200) NOT NULL DEFAULT '', `file_size` int(11) NOT NULL DEFAULT '0' COMMENT '字节数', `file_suffix` varchar(10) NOT NULL, `path_name` varchar(100) NOT NULL, `width` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '度宽, 图片、视频', `height` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '高度', `play_sec` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '播放时间, 视频', `status` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '@预留字段 1=新增,2=审核中,3=审核通过,4=审核失败', `remark` varchar(50) NOT NULL DEFAULT '' COMMENT '@预留字段 审核备注', `is_delete` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '@预留字段 1 表示删除', `createtime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `user_account` varchar(50) NOT NULL DEFAULT '', PRIMARY KEY (`aid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for category -- ---------------------------- CREATE TABLE `category` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `enable` tinyint(1) NOT NULL DEFAULT '0', `createtime` datetime NOT NULL, `updatetime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for file_type -- ---------------------------- CREATE TABLE `file_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `title` varchar(100) NOT NULL, `enable` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for files -- ---------------------------- CREATE TABLE `files` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `account` varchar(50) NOT NULL DEFAULT '' COMMENT '账号', `title` varchar(100) NOT NULL DEFAULT '' COMMENT '视频名称', `tag` varchar(50) NOT NULL DEFAULT '' COMMENT '视频标签', `play_sec` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '播放时间,预留', `file_name` varchar(200) NOT NULL DEFAULT '原文件名称', `file_suffix` varchar(10) NOT NULL COMMENT '文件名后缀', `video_path` varchar(100) NOT NULL DEFAULT '' COMMENT '视频路径', `video_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '视频大小', `video_width` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '视频宽度', `video_height` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '视频高度', `img_path` varchar(100) NOT NULL DEFAULT '' COMMENT '图片路径', `img_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '图片大小', `img_width` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '图片宽度', `img_height` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '图片高度', `product_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '产品ID', `product_name` varchar(100) NOT NULL DEFAULT '' COMMENT '产品名称', `project_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '项目ID', `project_name` varchar(100) NOT NULL DEFAULT '' COMMENT '项目名称', `category_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '分类ID', `category_name` varchar(100) NOT NULL DEFAULT '' COMMENT '分类名称', `status` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '1=新增,2=审核中,3=审核通过,4=审核失败', `remark` varchar(50) NOT NULL DEFAULT '' COMMENT '审核备注', `is_delete` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '1 表示删除', `createtime` datetime NOT NULL COMMENT '创建时间', `updatetime` datetime NOT NULL COMMENT '更新时间', `create_user` varchar(50) NOT NULL DEFAULT '' COMMENT '创建者', `update_user` varchar(50) NOT NULL DEFAULT '' COMMENT '更新者', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for folder -- ---------------------------- CREATE TABLE `folder` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `project_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `enable` tinyint(1) NOT NULL DEFAULT '0', `createtime` datetime NOT NULL, `updatetime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for node -- ---------------------------- CREATE TABLE `node` ( `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `title` varchar(50) DEFAULT NULL, `status` tinyint(1) DEFAULT '0', `remark` varchar(255) DEFAULT NULL, `sort` smallint(6) unsigned DEFAULT NULL, `pid` smallint(6) unsigned NOT NULL, `level` tinyint(1) unsigned NOT NULL, PRIMARY KEY (`id`), KEY `level` (`level`), KEY `pid` (`pid`), KEY `status` (`status`), KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for product -- ---------------------------- CREATE TABLE `product` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `user_id` int(11) NOT NULL, `enable` tinyint(1) NOT NULL DEFAULT '0', `createtime` datetime NOT NULL, `updatetime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for project -- ---------------------------- CREATE TABLE `project` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `product_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `enable` tinyint(1) NOT NULL DEFAULT '0', `createtime` datetime NOT NULL, `updatetime` datetime NOT NULL, PRIMARY KEY (`id`), KEY `i_name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for role -- ---------------------------- CREATE TABLE `role` ( `id` smallint(6) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `pid` smallint(6) DEFAULT NULL, `status` tinyint(1) unsigned DEFAULT NULL, `remark` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), KEY `pid` (`pid`), KEY `status` (`status`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for role_user -- ---------------------------- CREATE TABLE `role_user` ( `role_id` mediumint(9) unsigned DEFAULT NULL, `user_id` char(32) DEFAULT NULL, KEY `group_id` (`role_id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for user -- ---------------------------- CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `account` varchar(50) NOT NULL, `nickname` varchar(60) NOT NULL DEFAULT '' COMMENT '用户名称', `password` varchar(30) NOT NULL DEFAULT '' COMMENT '用户密码', `project` varchar(40) NOT NULL DEFAULT '' COMMENT '项目', `category` varchar(40) NOT NULL DEFAULT '' COMMENT '分类', `createtime` datetime NOT NULL, `updatetime` datetime NOT NULL, `type` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user type 0:client,1:admin', `enable` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `u_account` (`account`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; INSERT INTO `user` VALUES ('1', 'admin', 'Admin', 'point9*', '', '', '2012-12-15 12:17:00', '0000-00-00 00:00:00', '1', '1'); CREATE TABLE `site_column` ( `code` varchar(50) NOT NULL, `title` varchar(50) NOT NULL DEFAULT '', `url` varchar(100) NOT NULL DEFAULT '', PRIMARY KEY (`code`), UNIQUE KEY `u_title_idx` (`title`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; INSERT INTO `site_column` VALUES ('Home Page', 'Home Page', '/'); INSERT INTO `site_column` VALUES ('About Page', 'About Page', '/About/'); INSERT INTO `site_column` VALUES ('Work Page', 'Work Page', '/Work/'); INSERT INTO `site_column` VALUES ('Services Page', 'Services Page', '/Services/'); INSERT INTO `site_column` VALUES ('Contact Page', 'Contact Page', '/Contact/'); alter table attachment add index sit_column_key (remark) ; alter table files add index file_name_idx (file_name) ; --------------------------------------------------------- -- 2013-05-02 --------------------------------------------------------- CREATE TABLE `file_auth` ( `auth_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `rid` int(10) unsigned NOT NULL COMMENT 'files 表中的 id 外键', `user_id` int(10) unsigned NOT NULL COMMENT 'user 表中 id 外键', `auth_type` varchar(50) NOT NULL COMMENT '权授类型, view,share,download,每一种授权用逗号分隔,在一行记录其所拥有的权限列表', `createtime` datetime NOT NULL COMMENT '创建时间', `updatetime` datetime NOT NULL COMMENT '后最更新时间', `create_user` varchar(50) NOT NULL COMMENT '建创者', `update_user` varchar(50) NOT NULL COMMENT '更新者', `is_expired` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '0 表示当前生效值 , 1 表示过期', PRIMARY KEY (`auth_id`), KEY `rid_idx` (`rid`), KEY `user_id_idx` (`user_id`), KEY `expired_idx` (`is_expired`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; alter table files add index is_delete_idx (is_delete) ; alter table files add index account_idx (account) ; alter table files add index project_id_idx (project_id) ;
Python
UTF-8
2,876
3.296875
3
[]
no_license
# -*- coding: UTF-8 -*- """ @Time: 2018/6/8 15:38 @Author: TingTing W """ """ 利用高德地图api实现地址和经纬度的转换 """ import random import time import requests import xlrd import xlwt def read_excel(): # 创建一个workbook 设置编码 workbook = xlwt.Workbook(encoding='utf-8') # 创建一个worksheet worksheet = workbook.add_sheet('Worksheet') # 读取excel ExcelFile = xlrd.open_workbook(r'E:\city_info.xlsx') # 获取目标EXCEL文件sheet名 # print(ExcelFile.sheet_names()) # 获取sheet内容【1.根据sheet索引2.根据sheet名称】 # sheet=ExcelFile.sheet_by_index(1) sheet = ExcelFile.sheet_by_name('city_info') print(sheet.nrows) # sheet.nrows for row_number in range(1, sheet.nrows + 1): row_values_new = [] # 将要写入excel的一行数据保存在一个字典里 row_values = sheet.row_values(row_number) # 获取原excel中的一行数据 # 失踪人现在所在地 now_location = row_values[0] # 将省和市拼接在一起 geocode_result = geocode(now_location) if geocode_result is not None: now_location_latlng = geocode_result.split(',') else: print('\033[1;31;m' + 'None' + '\033[0m') continue # 将数据添加到row_values_new中 row_values_new.append(now_location) row_values_new.append(now_location_latlng[0]) row_values_new.append(now_location_latlng[1]) # 控制台输出row_values_new print(row_values_new) # 写入excel # 参数对应 行, 列, 值 worksheet.write(row_number, 0, row_values_new[0]) # 往第row_number行第0列写入数据row_values_new[0] worksheet.write(row_number, 1, row_values_new[1]) worksheet.write(row_number, 2, row_values_new[2]) # 保存excel workbook.save('城市经纬度.xls') print('\033[1;32;m' + '写入成功: 第' + str( row_number) + '个' + '\033[0m') def geocode(address): random_sleep_time = random.uniform(0.200002, 0.5000001) time.sleep(random_sleep_time) count = 20 while count > 0: try: parameters = {'address': address, 'key': 'a5717efe281fea54c2a03cc00310ae08'} base = 'http://restapi.amap.com/v3/geocode/geo' # 响应请求 response = requests.get(base, parameters, timeout=2) answer = response.json() print(answer) if answer is not None: # print(answer['geocodes'][0]['location']) return answer['geocodes'][0]['location'] else: return None except: count -= 1 print('\033[1;31;m' + 'error' + '\033[0m') return None if __name__ == '__main__': read_excel() # geocode("潮汕地区")
Python
UTF-8
243
2.75
3
[]
no_license
from random import randint i = randint(0,52) f = open('C:/programs/Python/randomGameGenerator/gameList.txt', 'r') game = f.readlines() print game[i] f = open('C:/programs/Python/randomGameGenerator/lastFinishedGame.txt', 'w') f.write(game[i])
Java
UTF-8
2,260
1.742188
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2018-present Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.sonatype.goodies.dropwizard.config; import javax.validation.Validator; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheckRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.AbstractModule; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.setup.AdminEnvironment; import io.dropwizard.setup.Environment; import static com.google.common.base.Preconditions.checkNotNull; /** * Adds various bindings for {@link Environment} properties. * * @since 1.0.0 */ public class EnvironmentModule extends AbstractModule { private final Environment environment; public EnvironmentModule(final Environment environment) { this.environment = checkNotNull(environment); } @Override protected void configure() { bind(Environment.class).toInstance(environment); bind(MetricRegistry.class).toInstance(environment.metrics()); bind(HealthCheckRegistry.class).toInstance(environment.healthChecks()); bind(ObjectMapper.class).toInstance(environment.getObjectMapper()); bind(Validator.class).toInstance(environment.getValidator()); bind(JerseyEnvironment.class).toInstance(environment.jersey()); bind(ServletEnvironment.class).toInstance(environment.servlets()); bind(LifecycleEnvironment.class).toInstance(environment.lifecycle()); bind(AdminEnvironment.class).toInstance(environment.admin()); } }
JavaScript
UTF-8
1,813
2.5625
3
[ "MIT" ]
permissive
$(document).ready(function (e) { //Set the correct selected value for dropdown. $('.chkRole').change(function () { var cb = $(this); if (!cb.is(":checked")) { var roleId = $(this).attr("name"); var userId = $(this).data("chkFor"); console.log("UserId: " + userId + " roleid: " + roleId); RemoveRole(userId, roleId, $(this)); } else { var roleId = $(this).attr("name"); var userId = $(this).data("chkFor"); console.log("UserId: " + userId + " roleid: " + roleId); AddRole(userId, roleId,$(this)); } }); function RemoveRole(userId, roleId,sender) { console.log("removing"); console.log("UserId: " + userId + " roleid: " + roleId); $.ajax({ url: '/Manage/RemoveUserRole', type: 'POST', data: { id: userId, value: roleId }, success: function (e) { sender.css({ "text-decoration": "underline" }); }, error: function (e) { console.log($(this).data("chkFor") + " " + $(this).val()); console.log(e); alert("error"); } }); } function AddRole(userId, roleId,sender) { console.log("adding"); $.ajax({ url: '/Manage/AddUserRole', type: 'POST', data: { id: userId, value: roleId }, success: function (e) { sender.css({ "text-decoration": "underline" }); }, error: function (e) { console.log($(this).data("chkFor") + " " + $(this).val()); console.log(e); alert("error"); } }); } });
C
UTF-8
1,285
3.5625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> int arr[5000]; int findmax(int a,int b) { if(a>b) return a; else return b; } int findmin(int a,int b) { if(a<b) return a; else return b; } void rmaxmin(int n,int m,int *max,int *min) { int mid,gmax,gmin,hmax,hmin; if(n==m) { *max=arr[n]; *min=arr[n]; } else if(n==(m-1)) { if(arr[n]<arr[m]) { *max=arr[m]; *min=arr[n]; } else { *max=arr[n]; *min=arr[m]; } } else { mid=(n+m)/2; rmaxmin(n,mid,&gmax,&gmin); rmaxmin(mid+1,m,&hmax,&hmin); *max=findmax(gmax,hmax); *min=findmin(gmin,hmin); } } int main() { int max,min,n,m; int q,i,j; printf("Enter the number if elements\n"); scanf("%d",&q); for(i=0;i<q;i++) { arr[i]=rand(); } printf("Array stored due to random functions\n"); for(i=0;i<q;i++) { printf("%d\n",arr[i]); } rmaxmin(0,q-1,&max,&min); printf ("the max element in the given array is %d\n",max); printf ("the min element in the given array is %d\n",min); }
Java
UTF-8
1,281
2.578125
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 Networking.Requests; import Database.DatabaseHandler; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author root */ public class RegisterAccount extends Request { private String username; private String password; public RegisterAccount(String username, String password) { super(RequestType.REGISTER_ACCOUNT); this.username = username; this.password = password; } @Override public void execute(ObjectOutputStream outputStream) { try { if (DatabaseHandler.getInstance().findName(username)) outputStream.writeObject(new BooleanResponse(false)); else { outputStream.writeObject(new BooleanResponse(true)); DatabaseHandler.getInstance().pushPlayer(username, password); } outputStream.flush(); } catch (IOException ex) { Logger.getLogger(LoginAccount.class.getName()).log(Level.SEVERE, null, ex); } } }
Python
UTF-8
3,025
2.703125
3
[]
no_license
import sys from form import * from secondary_functions import * import pytesseract import threading from form import * pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe' class MyWin(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QWidget.__init__(self, parent=None) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.test_run) self.ui.pushButton_2.clicked.connect(self.record) self.ui.pushButton_3.clicked.connect(self.set_event) self.exit_event = threading.Event() def set_event(self): """ Устанавливает Threading.Event в позицию Set у класса myapp(MyWin) """ self.exit_event.set() def test_run(self): """ Запускается при нажатии на кнопку ТЕСТ """ #Обновление данных с формы coordinate_initialization(myapp) cut_initialization(myapp) # Проверка на возможные ошибки и остановка выполнения, если ошибки были error_data_coordinate = check_correct_input_coordinate(myapp) if type(error_data_coordinate) != type(None): return sent_error(myapp, error_data_coordinate) error_data_cut = check_correct_input_cut(myapp) if type(error_data_cut) != type(None): return sent_error(myapp, error_data_cut) convert_data(myapp, flag = 0) # Пробный ран test(myapp) def record(self): """ Запускается при нажатии кнопки СТАРТ """ #Обновление данных с формы coordinate_initialization(myapp) cut_initialization(myapp) name_and_time_initialization(myapp) # Проверка на возможные ошибки и остановка выполнения, если ошибки были error_data_coordinate = check_correct_input_coordinate(myapp) if type(error_data_coordinate) != type(None): return sent_error(myapp, error_data_coordinate) error_data_cut = check_correct_input_cut(myapp) if type(error_data_cut) != type(None): return sent_error(myapp, error_data_cut) error_data_name_and_time = check_for_correct_name_and_time(myapp) if type(error_data_name_and_time) != type(None): return sent_error(myapp, error_data_name_and_time) # Конвертация аргументов класса convert_data(myapp, flag = 1) # Считывание и запись record(myapp) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) myapp = MyWin() myapp.show() sys.exit(app.exec_())
C
UTF-8
1,348
2.84375
3
[]
no_license
#include "myLib.h" #include <stdlib.h> unsigned short *videoBuffer = (unsigned short *)0x6000000; void setPixel(int row, int col, unsigned short color) { videoBuffer[OFFSET(row, col, 240)] = color; } void drawRect(int row, int col, int height, int width, unsigned short color) { for(int r=0; r<height; r++) { DMA[3].src = &color; DMA[3].dst = videoBuffer + OFFSET(row+r, col, 240); DMA[3].cnt = width | DMA_SOURCE_FIXED | DMA_ON; } } void drawImage3(int x, int y, int width, int height, const unsigned short *image) { for (int i = 0; i < height; i++) { DMA[3].src = &image[OFFSET(i, 0, width)]; DMA[3].dst = &videoBuffer[OFFSET(x + i, y,240)]; DMA[3].cnt = DMA_ON | width ; } } void waitForVblank() { while(SCANLINECOUNTER > 160); while(SCANLINECOUNTER<160); } int collisionH(u16 color, u16 barColor, int col, int barCol) { if (((col+10) >= barCol) && ((col+10) <= barCol + 10) && (color != barColor)) { return 0; } if (((barCol+10) >= col) && ((barCol+10) <= col + 10) && (color != barColor)) { return 0; } return 1; } int collisionV(u16 color, u16 barColor, int row, int barRow) { if (((row+10) >= barRow) && ((row+10) <= barRow + 10) && (color != barColor)) { return 0; } if (((barRow+10) >= row) && ((barRow+10) <= row + 10) && (color != barColor)) { return 0; } return 1; }
Swift
UTF-8
5,648
2.625
3
[]
no_license
// // UIValueSlider.swift // LocationFinder // // Created by Weiyu Huang on 11/25/15. // Copyright © 2015 SITA CORP. All rights reserved. // import UIKit @IBDesignable class UIValueSlider: UIControl { let trackLayer = CALayer() let thumbLayer = ThumbView() var minimumValue: CGFloat = 0 var maximumValue: CGFloat = 10 var thumbXOffsetConstraint: NSLayoutConstraint! var value: CGFloat { get { return (maximumValue - minimumValue)/(bounds.width - thumbLayer.frame.width)*(thumbLayer.frame.minX - bounds.minX) } set { let validValue = max(minimumValue, min(maximumValue, newValue)) //guard validValue != value else { return } thumbLayer.frame.origin.x = (validValue-minimumValue)/(maximumValue - minimumValue)*(bounds.width - thumbLayer.frame.width) + bounds.minX sendActionsForControlEvents(.ValueChanged) } } override init(frame: CGRect) { super.init(frame: frame) setup() setupLayers() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() setupLayers() } private func setup() { //layer.backgroundColor = UIColor.clearColor().CGColor layer.addSublayer(trackLayer) addSubview(thumbLayer) thumbLayer.userInteractionEnabled = false } func setupLayers() { let trackHeight = CGFloat(2) let thumbHeight = CGFloat(6) let thumbWidth = CGFloat(16) trackLayer.frame = CGRect(x: bounds.minX + thumbWidth/2, y: bounds.midY - trackHeight/2, width: bounds.width - thumbWidth, height: trackHeight) trackLayer.backgroundColor = UIColor.blackColor().CGColor //thumbLayer.frame = CGRect(x: bounds.minX, y: bounds.midY - thumbHeight/2, width: thumbWidth, height: thumbHeight) thumbXOffsetConstraint = thumbLayer.leadingAnchor.constraintEqualToAnchor(leadingAnchor, constant: 0) thumbXOffsetConstraint.active = true thumbLayer.topAnchor.constraintEqualToAnchor(centerYAnchor, constant: thumbHeight/2).active = true //thumbLayer.backgroundColor = UIColor.blackColor() } override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { if thumbLayer.frame.contains(touch.locationInView(self)) { thumbLayer.selected = true } return thumbLayer.selected } override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { let newLoc = touch.locationInView(self) if newLoc.x >= bounds.minX && newLoc.x <= bounds.maxX && thumbLayer.selected { CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) thumbXOffsetConstraint.constant = newLoc.x layoutIfNeeded() CATransaction.commit() } return thumbLayer.selected } override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { thumbLayer.selected = false } } class ThumbView: UIView { var selected = false var textLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { backgroundColor = UIColor.clearColor() translatesAutoresizingMaskIntoConstraints = false addSubview(textLabel) textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.textColor = UIColor.whiteColor() textLabel.text = "0 M" textLabel.leadingAnchor.constraintEqualToAnchor(leadingAnchor, constant: 8).active = true textLabel.trailingAnchor.constraintEqualToAnchor(trailingAnchor, constant: -8).active = true textLabel.topAnchor.constraintEqualToAnchor(topAnchor, constant: 8+CONSTANT.SLIDER.TIP_ARROW_HEIGHT).active = true textLabel.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: -8).active = true } override func drawRect(rect: CGRect) { let path = outerBounds(rect) //CONSTANT.COLOR_SCHEME.TINT.setFill() UIColor.blackColor().setFill() path.fill() } func outerBounds(bound: CGRect) -> UIBezierPath { let cornerRadius = CONSTANT.SLIDER.CORNER_RADIUS guard bound.width-2*cornerRadius > 0 else { return UIBezierPath(roundedRect: bound, cornerRadius: cornerRadius)} var contentRect = bound contentRect.origin.y += CONSTANT.SLIDER.TIP_ARROW_HEIGHT contentRect.size.height -= CONSTANT.SLIDER.TIP_ARROW_HEIGHT let path = UIBezierPath(roundedRect: contentRect, cornerRadius: CONSTANT.SLIDER.CORNER_RADIUS) let arrowHalfWidth = CONSTANT.SLIDER.TIP_ARROW_HALF_WIDTH let arrowLeftX = max(contentRect.minX+cornerRadius, contentRect.midX-arrowHalfWidth) let arrowRightX = contentRect.midX*2 - arrowLeftX let arrowPath = UIBezierPath() arrowPath.moveToPoint(CGPoint(x: contentRect.midX, y: bounds.minY)) arrowPath.addLineToPoint(CGPoint(x: arrowLeftX, y: contentRect.minY)) arrowPath.addLineToPoint(CGPoint(x: arrowRightX, y: contentRect.minY)) arrowPath.closePath() path.appendPath(arrowPath) return path } } class ThumbLayer: CALayer { var selected = false }
Python
UTF-8
1,463
2.625
3
[]
no_license
import jieba from wordcloud import WordCloud import image import pandas import numpy as np import matplotlib.pyplot as plt from wordcloud import WordCloud,ImageColorGenerator from os import listdir from os.path import isfile, join lyrics = [f for f in listdir("lyric") if isfile(join("lyric", f))] content=[] for lyric in lyrics: for line in open("lyric/"+lyric,'r'): content.append(line) text="" for i in content: text=text+i segs=jieba.cut(text) segment = [] for seg in segs: if len(seg) > 1 and seg!='\r\n' and seg not in ["我会","没有","一样","何必","只有","一切","知道","北京","我们","一个","妈妈","已经","如果","什么","那些","只是","不会","无法","小屋"]: segment.append(seg) # print(segment) print(len(segment)) #去停用词 words_df=pandas.DataFrame({'segment':segment}) words_df.head() words_stat=words_df.groupby(by=['segment'])['segment'].agg({"number":np.size}) words_stat=words_stat.reset_index().sort_values(by="number",ascending=False) from scipy.misc import imread import matplotlib.pyplot as plt from wordcloud import WordCloud,ImageColorGenerator bimg=imread('caihong.jpg') wordcloud=WordCloud(background_color="black",mask=bimg,font_path='msyh.ttf') wordcloud=wordcloud.fit_words(words_stat.head(39769).itertuples(index=False)) bimgColors=ImageColorGenerator(bimg) plt.figure(figsize=(20,15)) plt.axis("off") plt.imshow(wordcloud.recolor(color_func=bimgColors)) plt.show()
Markdown
UTF-8
3,181
3.90625
4
[]
no_license
<!-- * @Author: your name * @Date: 2020-03-02 21:49:13 * @LastEditTime: 2020-06-29 23:05:14 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: /leetcode_fe/268_缺失数字.md --> # 141. 环形链表 ### 题目描述(难度:简单) + 给定一个链表,判断链表中是否有环。 + 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 + 示例1: ``` 输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。 ``` + 示例2: ``` 输入:head = [1,2], pos = 0 输出:true 解释:链表中有一个环,其尾部连接到第一个节点。 ``` + 示例3: ``` 输入:head = [1], pos = -1 输出:false 解释:链表中没有环。 ``` ### 思路1: + 双指针 - 双指针,即快慢指针。我们定义两个指针,初始位置都是在链表的头部,两个指针同时出发,快指针一次可以前进两步,而慢指针一次只能前进一步。会出现以下几种情况 1. 链表为空,肯定不是环形链表; 2. 链表不为空,快指针走到了链表的结尾,也可以判断不是环形链表; 3. 链表不为空,快指针和慢指针相遇,则证明此链表是环形链表 ### 代码1 ```js /** * @param {ListNode} head * @return {boolean} */ const hasCycle = function (head) { if(!head) return false; let fast = head; let slow = head; while(fast && fast.next){ fast = fast.next.next; slow = slow.next; if(fast === slow) return true } return false; }; ``` ### 思路 2 + 哈希表 - 创建一个空 Map 对象并遍历链表中的所有节点,每遍历一个节点,就像空对象里插入一条组键值对为 { 当前节点: 1 }。 1. 如果遍历完成,该 Map 对象中不存在相同节点,那么不是环形链表。 2. 遍历中,发现该 Map 对象中存在相同节点且值为 1,即该节点已经遍历过了,那么链表是环形链表 ### 代码2 ```js /** * @param {ListNode} head * @return {boolean} */ const hasCycle = function (head) { if(!head) return false; const newData = new Map(); while(head){ if(newData.has(head)) return true; newData.set(head,1) head = head.next; } return false; }; ``` ### 思路 + symbol。 - 和哈希表不一样的是,哈希表是将遍历过节点存到一个 Map 对象中,若循环到一个节点,且对象中存在该节点,则证明为环形链表。而这个方法是将当前节点的 val 值改为用 Symbol 创建的一个独一无二的值,若链表循环过程中存在节点的 val 全等于这个值,那么证明当前不是第一次循环到该节点,即链表为环形链表,反之不是。 ### 代码 3 ```js /** * @param {ListNode} head * @return {boolean} */ const hasCycle = function (head) { if(!head) return false; const newData = Symbol('') while(head){ if(head.val === newData ) return true; head.val = newData; head = head.next; } return false; }; ```
JavaScript
UTF-8
3,514
2.703125
3
[ "MIT" ]
permissive
import fetchJsonp from 'fetch-jsonp'; import cheerio from 'cheerio'; import qrNameMap from '../data/cardnameMap.json'; function getSurugaya(keyword) { const url = `https://www.suruga-ya.jp/search?category=5&search_word=${keyword}`; return new Promise(resolve => { fetchJsonp('https://script.google.com/macros/s/AKfycbyGqtJYxOIgvFgYW-xZRW4ZGQAfwPunJGzm6WwiCetbI56CGJWh/exec?url=' + encodeURIComponent(url), { jsonpCallback: 'callback', timeout: 10000 }) .then(response => { return response.json(); }) .then(json => { const ret = scrapeSurugaya(json.htmlStr, keyword); resolve({ data: ret }); }) .catch(error => { resolve({ error }); }); }); } /** * 駿河屋の商品データをスクレイピングする * @param {string} htmlStr * @param {string} keyword * @return {object} スクレイピング結果 */ function scrapeSurugaya(htmlStr, keyword) { if (htmlStr.match('検索結果は0件です') !== null) throw `駿河屋の検索結果が0件です。(${keyword})`; const $ = cheerio.load(htmlStr); const surugayaResult = []; $('.item').each((index, elem) => { /** 商品名 */ const name = $(elem) .find('a') .text(); /** 商品URL */ const itemUrl = $(elem) .find('a') .attr('href'); // 画像URL // 変換する // 元:https://www.suruga-ya.jp/database/photo.php?shinaban=g5358519&size=m // 小さい方:https://www.suruga-ya.jp/pics/boxart_m/g5358519m.jpg // 大きい方:https://www.suruga-ya.jp/database/pics/game/g5358519.jpg const shinaban = $(elem) .find('img') .attr('src') .match(/(g[0-9]+)/); let imageUrl = ''; if (shinaban) { imageUrl = `https://www.suruga-ya.jp/pics/boxart_m/${shinaban[0]}m.jpg`; } /** 価格 */ const price = $(elem) .find('.price') .text(); surugayaResult.push({ name, itemUrl, imageUrl, price }); }); return surugayaResult; } function getCardInfoFromQr(qrcode) { return new Promise(resolve => { // TODO:旧カツカードのQRと照合する // if (qrcode.indexOf('http://aikatsu.com/qr') > -1) return { error: '旧アイカツカードにはまだ対応してないよ' }; if (qrNameMap[qrcode]) { resolve({ data: qrNameMap[qrcode] }); } // スターズ以降のカードは、QRにアクセスして名前を取得 fetchJsonp('https://script.google.com/macros/s/AKfycbyGqtJYxOIgvFgYW-xZRW4ZGQAfwPunJGzm6WwiCetbI56CGJWh/exec?url=' + encodeURIComponent(qrcode), { jsonpCallback: 'callback', timeout: 10000 }) .then(response => { return response.json(); }) .then(json => { const ret = scrapeAikatsu(json.htmlStr); resolve({ data: ret }); }) .catch(error => { resolve({ error }); }); }); } /** * QR読み取り結果をスクレイピングする * @param {string} htmlStr * @return {object} スクレイピング結果 */ function scrapeAikatsu(htmlStr) { const $ = cheerio.load(htmlStr); let cardName = ''; // アイカツフレンズ cardName = $('.cardName').text(); if (cardName === '') { // アイカツスターズ cardName = $('.dress-detail-title') .find('h4') .text(); } if (cardName === '') throw { message: 'データが見つかりません' }; return cardName; } export default { getSurugaya, getCardInfoFromQr };
Markdown
UTF-8
776
2.921875
3
[]
no_license
# Bootstrap Script to quickly switch between source code branches or ramp-up a new development environment, resulting in a live functioning application workstation. (Best used with a centralized vcs (svn) versus distributed versions (i.e., git or mercurial) that already provide quick branch management functionality) ## Prerequisites 1. Installed Developer IDE. 1. Installed application servers. 1. Installed source code control client (i.e., svn) ## Bootstrap process Single command: 1. Fetch latest source code per configured branch (Usually HEAD development) 1. Update configuration files for application servers based upon target environment: Dev, Test, etc. 1. Build the source. 1. Test the deliverables. 1. Deploy locally the application(s). 1. Start servers.
Python
UTF-8
7,318
3.171875
3
[]
no_license
import os.path import time def show_items(a): ''' This Function Is For Displaying Items ''' if os.path.isfile('items.txt'): fin=open('items.txt','r') items=eval(fin.read()) fin.close() print('We Are Having --> ') choice='y' cart=[] cart1={} while choice=='y': if a[2]<10: print('Your Wallet Balance Is Low') ct=input('Press y to play game and earn money ').lower() if ct=='y': import game game.instruction_of_game() score=game.game_algo()*5 fin=open('wallet.txt','r') data=eval(fin.read()) fin.close() fin=open('wallet.txt','w') data[a[1]]+=score a[2]=data[a[1]] fin.write(str(data)) fin.close() log_details=['played_game',a[1],'cash_gained -- '+str(score),time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() for i in items: print(str(i)+' ----> '+str(items[i])+'$') print('Amount In Your Wallet --> ',a[2]) print('Items in your cart --> ',len(cart)) print('Enter name of item to buy or press n to exit store. ') char=input().lower() if char=='n': log_details=['logout',a[1],time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() print('Thanks For Coming') return True else: cart.append(items[char]) if char not in cart1: cart1[char]=[items[char]] else: cart1[char].append(items[char]) choice=input('Press y to purchase more or n to end shopping ').lower() if choice=='n': if a[2]>=sum(cart): print('Your Bill Is --> ',sum(cart)) print('Your Amount Left --> ',a[2]-sum(cart)) print('Your purchaising is successful','Thanks For Coming',sep='\n') fin=open('wallet.txt','r') d=eval(fin.read()) fin.close() log_details=['purchase',a[1],cart1,time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() fin=open('wallet.txt','w') d[a[1]]=a[2]-sum(cart) fin.write(str(d)) fin.close() log_details=['logout',a[1],time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() else: print('You are not having sufficient balance in your account.') print('Transaction Cancelled...') log_details=['logout_insufficient_balance',a[1],time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() return True else: log_details=['logout_server_error',a[1],time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() print('Server Error Quiting...') return True def wallet(user_name): ''' This function returns wallet statement of user ''' if os.path.isfile('wallet.txt'): fin=open('wallet.txt','r') d=eval(fin.read()) fin.close() if user_name in d: return d[user_name] else: fin=open('wallet.txt','w') d[user_name]=40 fin.write(str(d)) fin.close() print('Congrats!!! You received $40 Bonus') return 40 else: d={} fin=open('wallet.txt','w') d[user_name]=40 fin.write(str(d)) fin.close() print('Congrats!!! You received $40 Bonus') return 40 def login_page(): ''' this function is for logging in user ''' user_name=input('Enter Username --> ') password=input('Enter Password --> ') if os.path.isfile('login_data.txt'): fin=open('login_data.txt','r') d=eval(fin.read()) fin.close() if user_name in d: if d[user_name]==password: return (True,user_name) else: print('Either Username or Password Not Found') else: print('Either Username or Password Not Found') else: print('Please create account first') return (False,user_name) return (False,user_name) def sign_up_page(): ''' this function is for signing up user ''' user_name=input('Enter username --> ') password=input('Enter Password --> ') if os.path.isfile('login_data.txt'): fin=open('login_data.txt','r') d=eval(fin.read()) fin.close() if user_name in d: print('Sorry, Username Exist.') return False else: d[user_name]=password fin=open('login_data.txt','w') fin.write(str(d)) fin.close() return (True,user_name) else: d={} d[user_name]=password fin=open('login_data.txt','w') fin.write(str(d)) fin.close() return (True,user_name) if __name__=='__main__': print(' Dummy Merchant ') a=(False,) while not a[0]: print('Press 1 for sign up or 2 for login or 3 for exit') n=int(input()) if n==1: a=list(sign_up_page()) if a[0]== True: log_details=['sign_up',a[1],time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() money=wallet(a[1]) a.append(money) b=show_items(a) if b==True: break elif n==2: a=list(login_page()) if a[0]== True: log_details=['login',a[1],time.time()] fin=open('log_of_'+a[1]+'.txt','a') fin.write(str(log_details)+'\n') fin.close() money=wallet(a[1]) a.append(money) b=show_items(a) if b==True: break else: a=(True,)
Markdown
UTF-8
499
2.546875
3
[]
no_license
# Por que pastas 'fonts' e 'images' dentro deste diretório? * Os diretórios 'fonts' e 'images' são necessários EXATAMENTE aqui, pois os arquivos CSS do GroupDocs necessitam deles nestes locais. * Modificar os arquivos CSS para apontarem para outro caminho **NÃO É UMA OPÇÃO**, já que isso prejudica manter o GroupDocs atualizado. Se atualizarmos um CSS, por exemplo, teremos que atualizar novamente os caminhos que apontam para fontes e imagens que foram mudados de lugar em outro momento.
JavaScript
UTF-8
4,801
2.71875
3
[]
no_license
$(() => { var vuelta = 1; var correctas = 0; var preguntas = [ { pregunta:"¿Dónde surgió la filosofía?", opciones: ['Grecia', 'España', 'Egipto', 'Japón'], respuesta: 'Grecia' }, { pregunta:"¿Cuántos versos tiene un soneto?", opciones: ['14', '16', '8', '20'], respuesta: '14' },{ pregunta:"¿Qué odia Mafalda?", opciones: ['La sopa', 'El pájaro Loco', 'Los panqueques', 'A Manolito'], respuesta: 'La sopa' },{ pregunta:"¿Quién compuso la famosa canción Bohemian Rhapsody?", opciones: ['Freddy Mercury', 'Elton John', 'David Bowie', 'John Lennon'], respuesta: 'Freddy Mercury' },{ pregunta:"¿Cuántos cuadros tiene un tablero de ajedres?", opciones: ['64', '128', '76', '32'], respuesta: '64' },{ pregunta:"¿Cuántos soldados argentinos murieron en la Guerra de las Malvinas?", opciones: ['649', '200', '987', '1452'], respuesta: '649' },{ pregunta:"¿Quién es la mascota de SEGA?", opciones: ['Sonic', 'Mario', 'Ryu', 'Pac Man'], respuesta: 'Sonic' },{ pregunta:"¿Qué personaje de Disney perdió su zapato de cristal?", opciones: ['Cenicienta', 'Tiana', 'Blancanieves', 'La Sirenita'], respuesta: 'Cenicienta' },{ pregunta:"¿Qué estudia la icitología?", opciones: ['Los peces', 'Las rocas', 'Las erupciones cutáneas', 'Los insectos'], respuesta: 'Los peces' },{ pregunta:"¿Cuántos países hay en el mundo?", opciones: ['196', '192', '189', '214'], respuesta: '196' }]; $(document).keydown((event) =>{ if(vuelta==1){ $('#one').removeAttr('id'); $('.box').remove(); $('#container').append('<div id="vuelta" class="box"><h2>Pregunta ' + vuelta + '</h2></div>'); $('#vuelta').append('<p id="pregunta">'+ preguntas[vuelta-1].pregunta+'</p>'); $('#vuelta').append('<div id="opciones"></div>'); shuffle(preguntas[vuelta-1].opciones).forEach(opcion => { $('#opciones').append('<button class="btn btn-outline-primary">' + opcion + '</button>'); }); $('#score').remove(); $('footer').append('<p id="score">Pregunta '+ vuelta +'/10</p>'); vuelta ++; pressed(); } }); var pressed = ()=> {$('.btn-outline-primary').click(function(event) { if(vuelta != 11){ if(esCorrecta($(this).text())){ $(this).attr('class', 'btn btn-success'); correctas++; }else{ $(this).attr('class', 'btn btn-danger'); } setTimeout(function(){ $('.box').remove(); $('#container').append('<div id="vuelta" class="box"><h2>Pregunta ' + vuelta + '</h2></div>'); $('#vuelta').append('<p id="pregunta">'+ preguntas[vuelta-1].pregunta+'</p>'); $('#vuelta').append('<div id="opciones"></div>'); shuffle(preguntas[vuelta-1].opciones).forEach(opcion => { $('#opciones').append('<button class="btn btn-outline-primary">' + opcion + '</button>'); }); $('#score').remove(); $('footer').append('<p id="score">Pregunta '+ vuelta +'/10</p>'); vuelta ++; pressed(); }, 500); }else{ setTimeout(function(){ if(esCorrecta($(event.target).text())){ console.log('entre'); $(event.target).removeClass('btn btn-outline-primary'); $(event.target).addClass('btn btn-success'); correctas++; }else{ console.log('entre mal'); $(event.target).attr('class', 'btn btn-danger'); } $('.box').remove(); $('#container').append('<div id="resultados" class="box"><h2>Respuestas Correctas: '+ correctas +'/10</h2></div>'); }, 500); } }); } function shuffle(opciones) { for (let i = opciones.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [opciones[i], opciones[j]] = [opciones[j], opciones[i]]; } return opciones; } var esCorrecta = (rta) =>{ return rta == preguntas[vuelta-2].respuesta; } });
Java
UTF-8
412
1.960938
2
[]
no_license
package ru.myx.ae3.e4.vm; import ru.myx.ae3.exec.ExecProcess; import ru.myx.ae3.exec.ExecStateCode; /** * * @author myx * */ public interface AeVmInstruction extends VmInstruction<ExecStateCode, ExecProcess> { /** * null - instruction finished normally. * * @param ctx * @return state code * @throws Exception */ @Override ExecStateCode execCall( ExecProcess ctx) throws Exception; }
Python
UTF-8
1,597
2.875
3
[]
no_license
from __future__ import print_function import sys import samsara try: token = sys.argv[1] except IndexError as e: print('Please provide an access token. For example:') print('python {program} <access token>'.format(program=sys.argv[0])) sys.exit() # Create an ApiClient client = samsara.ApiClient( header_name='Authorization', header_value='Bearer {token}'.format(token=token)) # Create an instance of the API api = samsara.DefaultApi(api_client=client) # List all vehicles # Save their Samsara IDs in a VIN:ID dictionary # Save the Samsara IDs of any vehicles without VINs vin_to_id = {} vehicles_with_no_vins = [] cursor = None has_next_page = True while has_next_page: res = api.list_vehicles(after=cursor) for vehicle in res.data: print(vehicle.name) if vehicle.vin is not None: print("VIN: {vin}".format(vin=vehicle.vin)) vin_to_id[vehicle.vin] = vehicle.id else: print("Vehicle does not have a VIN") vehicles_with_no_vins.append(vehicle.id) print("======================================") cursor = res.pagination.end_cursor has_next_page = res.pagination.has_next_page # Update all the vehicles with VIN external IDs for vin in vin_to_id: vehicle_update_request = samsara.UpdateVehicleRequest( external_ids={ 'vin': vin } ) api.update_vehicle(vin_to_id[vin], vehicle_update_request) # Retrieve a vehicle by its VIN arbitrary_vin = list(vin_to_id)[0] res = api.get_vehicle("vin:{vin}".format(vin=arbitrary_vin)) print(res.data)
Java
UTF-8
1,823
1.953125
2
[]
no_license
package com.xuke.popupwindow.entity; public class XEntity { /** * classId : 001770-0008-0001-0001-0001-0002 * phone : 17671787110 * studentNumber : 20160905 * fullName : 武汉大学-武汉自动创建学院5-测试专业-2018-测试2班 * studyId : 13f725492e564ea7a720e7478a5de56b * email : * alumnusId : 05161755032000926 */ private String classId; private String phone; private String studentNumber; private String fullName; private String studyId; private String email; private String alumnusId; private boolean checked; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getStudentNumber() { return studentNumber; } public void setStudentNumber(String studentNumber) { this.studentNumber = studentNumber; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getStudyId() { return studyId; } public void setStudyId(String studyId) { this.studyId = studyId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAlumnusId() { return alumnusId; } public void setAlumnusId(String alumnusId) { this.alumnusId = alumnusId; } }
Java
UTF-8
2,365
2.140625
2
[]
no_license
package com.example.aaronbrecher.shoppinglist.dependencyinjection; import android.app.Application; import android.arch.lifecycle.ViewModelProvider; import android.arch.persistence.room.Room; import android.content.Context; import android.content.SharedPreferences; import com.example.aaronbrecher.shoppinglist.database.ListItemDao; import com.example.aaronbrecher.shoppinglist.database.ListItemRepository; import com.example.aaronbrecher.shoppinglist.database.ShoppingListDao; import com.example.aaronbrecher.shoppinglist.database.ShoppingListDatabase; import com.example.aaronbrecher.shoppinglist.database.ShoppingListRepository; import com.example.aaronbrecher.shoppinglist.viewmodel.CustomViewModelFactory; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; /** * Created by aaronbrecher on 2/19/18. * Module to supply for injection all Room related classes * used by Dagger 2 */ @Module public class RoomModule { Application application; public RoomModule(Application application) { this.application = application; } @Provides @Singleton ShoppingListDatabase provideShoppingListDatabase(Application application){ return Room.databaseBuilder(application, ShoppingListDatabase.class, "shopping-list-database") .allowMainThreadQueries() .build(); } @Provides @Singleton ShoppingListDao provideShoppingListDao(ShoppingListDatabase database){ return database.shoppingListDao(); } @Provides @Singleton ListItemDao provideListItemDao(ShoppingListDatabase database){ return database.listItemDao(); } @Provides @Singleton ShoppingListRepository provideShoppingListRepository(ShoppingListDao shoppingListDao){ return new ShoppingListRepository(shoppingListDao); } @Provides @Singleton ListItemRepository provideListItemRepository(ListItemDao listItemDao){ return new ListItemRepository(listItemDao); } @Provides @Singleton ViewModelProvider.Factory provideViewModelFactory(ListItemRepository listItemRepository, ShoppingListRepository shoppingListRepository, SharedPreferences sharedPreferences){ return new CustomViewModelFactory(listItemRepository, shoppingListRepository, sharedPreferences); } }
Markdown
UTF-8
6,424
3.265625
3
[]
no_license
# **Production Management** : This application is for an industry focused on production. The purpose of this application is, simplicity, productivity, and save time by putting everything related to production in one place. The application can be used by all employees. Those who work in production and those who plan production. All employees in production can interact with all the data flow related to production. Can also be used by service technicians if they need to report on machine availability for production. It would need an admin dashboard For further development in the near future, to be able to restrict administratively to a supervisor, service technicians, or manager to be able to administrative application content by adding, delete and update (production, product, machine, and employee). # **UX** : This application manages data about the production (product, machine, employee) related to the company and its products. Application is for all employees on that company who want to interact with data related to they were producing. And to help them to get all information about the production. ### **User Stories**: - As a machine operator, I want to retrieve and record all data related to production in one place. To save time, simplicity, and more productive. - As a supervisor or manager, I want to plan and add which product to be produced in which machine to be made and in what order priority and which of the machine operator who has done this work. This gives me more control and an overview of all the data flow that applies to any specific product. - As a service technician, I want to report in the application which machines are available and which ones are under maintenance. So that all employees related to production get this information that others can plan faster and easier for the next production. Check out the **[Mockup](https://drive.google.com/file/d/10KxjV2618YYJ-KW08vb-ygie0cIeCmtr/view?usp=sharing)** that I have created as part of the design process and the design of **[database schema MongoDB](https://drive.google.com/file/d/1HhRcZZc9dld6TTAjd23tcvx-GHrFv2cU/view?usp=sharing?target=_blank)**. # **Existing Features** There are five general pages (home, add production, products, machines status, employees.) and subpages like edit, add, delete, register. On the home page, products, machines status, employees that present all data about the productions, products, machines, and employees. All other subpages are about to getting or edit and post the data. # Features Left to Implement - **Admin Dashboard**: to be able to the administrative application by the person who has the planning role by edit and deletes. - **Authentication user**: to give verifying the identity of the employee who has to register the production. - **Search function**: to search for a specific production. # Technologies Used - Codeinstitute: materials and homework and projector during the lesson. - HTML: by using HTML language to markup web pages in this project. - CSS: to perform style for the WepApp. - Materializecss: to perform style and responsive for the WepApp. - Google fonts: to add fonts to the webApp. - JavaScript and jQuery to perform: 1. Navbar links. 2. Mobile Navigation(navbar responsive for the mobile). 3. Collapsibles accordion: for the production webpage. 4. Datepicker: To register the production. - Websites like: ( **Stackoverflow** , **css-tricks** , **w3schools** , **github** , **youtube** ). # Testing During testing my project with my mentor, we have fix it some issue. - Select multiple employees in html registering production. Employees could not be displayed after registration. After the Mentor Guidance Session 2 - Middle of project call. Initially, I got some feedback and I made a little change: - Add production numbers to the list (All Production) above production name. - Correct spelling for some text. - Align products name in products list. - Remove all production from the first page (Home) and change it so that it would appear as Landing page. And change it in navbar from Add production to Production. - Remove register production button when production is registered. - HTML formatted. - Fix it an issue that make employees nickname double when to make edit after registration the production. # Deployment I have chosen to deploy my project in Heroku instead of GitHub. Why Heroku? I need a server to handle the request which GitHub Pages cannot support at this moment. Heroku offers a lot of features and flexibility, all for free. Some of the benefits include: - Easy setup(deployment). - Good cooperation and communication using Git and heroku. - Free hosting. ### Deployment On Heroku: Click New on the top right corner and select &quot;Create new app&quot;. Give the application a name (This will be included in the public URL for the application) and click Create app. Now we open the project in Gitpod. Login to Heroku through terminal. What we are doing here is we&#39;re creating a connection between our Gitpod application and Heroku that would allow us to push our changes using Git to update the application at any given time. Then, we create a new Git repository using git init. And then is add our files to the repository. And then we are going to associate the Heroku application as our master branch, or remote master branch by using those tow commands (1. heroku git:remote -a production-management. 2. git push heroku master). Now we need the requirements text will contain a list of the applications that are required for Heroku to run the application. The Procfile is also needed to get our application live in Heroku. The Procfile is an instruction to Heroku as to which file is used as our entry point at the application, which file we use to call the application to get it up and running. So we have write this command (heroku ps:scale web=1) over to the Heroku app to tell it to get up and running. And the last step is specifying our IP and our port that the server instance on Heroku will know how to run our Flask application to do that in Heroku home page, we&#39;re going to go to settings \&gt; click on Reveal Config Vars and on the input field Key we should write IP and in input field Value write the IP address which is in my case(0.0.0.0) and do the same with port:5000 in my case. And click on the top right corner &quot;Open app&quot; and the application should be live.
C
UTF-8
451
3.59375
4
[]
no_license
/* * Daniel Goncalves > 1151452@isep.ipp.pt * ARQCP - Turma 2DK * * compress_shorts.c */ #include <stdio.h> /* * Compresses a array of shorts to an array of integers * short *shorts - array of shorts. * int n_shorts - array of shorts. * int *integers - array of integers. * */ void compress_shorts(short* shorts, int n_shorts, int* integers) { short *ptr = (short *) integers; int i; for(i = 0; i < n_shorts; i ++) { *(ptr + i) = *(shorts + i); } }
Java
UTF-8
1,822
2.203125
2
[]
no_license
package com.mfodepositorsacc.dto; import java.math.BigDecimal; /** * Created by berz on 15.05.15. */ public class DepositMarketingDTO { private BigDecimal inYear; private BigDecimal inMonth; private BigDecimal inWeek; private BigDecimal inDay; private BigDecimal percentsInYear; private BigDecimal percentsInMonth; private BigDecimal percentsInWeek; private BigDecimal percentsInDay; public BigDecimal getInYear() { return inYear; } public void setInYear(BigDecimal inYear) { this.inYear = inYear; } public BigDecimal getInMonth() { return inMonth; } public void setInMonth(BigDecimal inMonth) { this.inMonth = inMonth; } public BigDecimal getInWeek() { return inWeek; } public void setInWeek(BigDecimal inWeek) { this.inWeek = inWeek; } public BigDecimal getInDay() { return inDay; } public void setInDay(BigDecimal inDay) { this.inDay = inDay; } public BigDecimal getPercentsInYear() { return percentsInYear; } public void setPercentsInYear(BigDecimal percentsInYear) { this.percentsInYear = percentsInYear; } public BigDecimal getPercentsInMonth() { return percentsInMonth; } public void setPercentsInMonth(BigDecimal percentsInMonth) { this.percentsInMonth = percentsInMonth; } public BigDecimal getPercentsInWeek() { return percentsInWeek; } public void setPercentsInWeek(BigDecimal percentsInWeek) { this.percentsInWeek = percentsInWeek; } public BigDecimal getPercentsInDay() { return percentsInDay; } public void setPercentsInDay(BigDecimal percentsInDay) { this.percentsInDay = percentsInDay; } }
Markdown
UTF-8
7,644
3.90625
4
[]
no_license
# ECMA6 - ARROW FUNCTION ## 1. SYNTAX ARROW FUNCTION(화살표 함수)는 FUNCTION 키워드 대신 화살표(=>)를 사용하여 간략한 방법으로 함수를 선언할 수 있다. > 모든 경우 사용할 수 있는 것은 아니다. ```javascript // 매개변수 지정 방법 () => { ... } // 매개변수가 없을 경우 x => { ... } // 매개변수가 한개인 경우, 소괄호를 생략할 수 있다. (x, y) => { ... } // 매개변수가 여러개인 경우 // 함수 몸체 지정 방법 x => { return x * x } // single line block x => x * x // 함수 몸체가 한줄의 표현식이라면 중괄호를 생략할 수 있으며 자동으로 return된다. 위 표현과 동일하다. () => { return { a: 1 }; } () => ({ a: 1 }) // 위 표현과 동일하다. 객체 반환시 소괄호를 사용한다. () => { // multi line block. const x = 10; return x * x; }; ``` ## 2. ARROW FUNCTION 의 호출 ARROW FUNCTION은 익명함수로만 사용할 수 있다. > ARROW 함수를 호출하기 위해선 함수표현식을 사용한다. ```javascript // ES5 var pow = function (x) { return x * x; }; console.log(pow(10)); // 100 // ES6 const pow = x => x * x; console.log(pow(10)); // 100 ``` >또는 콜백함수로 사용할 수 있다. 이경우 일반적인 함수 표현식보다 표현이 간결하다. ```javascript // ES5 var arr = [1, 2, 3]; var pow = arr.map(function (x) { // x는 요소값 return x * x; }); console.log(pow); // [ 1, 4, 9 ] // ES6 const arr = [1, 2, 3]; const pow = arr.map(x => x * x); console.log(pow); // [ 1, 4, 9 ] ``` ## 3. Arguments와 rest 파라미터 arguments 객체는 함수 호출시 전달된 arguments의 정보를 담고있는 순회가능한 유사배열 객체이다. > 함수 객체의 arguments 프로퍼티는 arguments객체를 값으로 가지며 함수 내부에서 지역변수처럼 사용된다. ```javascript // ES5 var foo = function () { console.log(arguments); }; foo(1, 2); // { '0': 1, '1': 2 } ``` > arguments객체는 유사배열이기 때문에 배열메소드를 사용하려면 function.prototpye.call, function.prototype.apply를 사용하여야 하는 번거러움이 있다. ```javascript / ES5 function sum() { // 가변 인자 함수의 경우, 파라미터를 통해 인수를 전달받는 것이 불가능하므로 arguments 객체를 활용하여 인수를 전달받는다. // arguments 객체를 배열로 변환 var array = Array.prototype.slice.call(arguments); return array.reduce(function (pre, cur) { return pre + cur; }); } console.log(sum(1, 2, 3, 4, 5)); // 15 var es5 = function () {}; console.log(es5.hasOwnProperty('arguments')); // true const es6 = () => {}; console.log(es6.hasOwnProperty('arguments')); // false // ES6 const sum = (...args) => { // console.log(arguments); // Uncaught ReferenceError: arguments is not defined console.log(Array.isArray(args)); // true return args.reduce((pre, cur) => pre + cur); }; console.log(sum(1, 2, 3, 4, 5)); // 15 ``` ## 4. this fucntion키워드를 사용해 생선한 일반 함수와 arrow function와의 가장큰 차이점은 this이다. ### 1. 일반함수의 this 일반 함수의 경우, 해당함수 호출 패턴에 따라 this에 바인딩 되는 객체가 달라진다. > 콜백함수 내부의 this는 전역 객체 window를 가리킨다. ```javascript function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { // (A) return arr.map(function (x) { return this.prefix + ' ' + x; // (B) }); }; var pre = new Prefixer('Hi'); console.log(pre.prefixArray(['Lee', 'Kim'])); ``` - A에서의 THIS 는 생성자 함수 PREFIXER가 생성한 객체, 즉 생성자 함수의 인스턴스이다. - 생성자함수 : 가장먼저, 빈객체를 만든다. - 빈객체에대해서 property를 set해준다. - 선두에서 만든 빈객체에 set된 객체를 리턴한다. - 단, new와 함께 사용됬을 경우이다. - B에서의 THIS는 아마도 생성자 함수 PREFIXER가 생성한 객체일 것으로 기대하였겠지만 이곳에서 TIHS는 전역객체 WINDOW를 가리킨다. - 이는 생성자함수와 객체의 메소드를 제외한 모든함수의 내부의 THIS는 전역객체를 가리키기 때문이다. > 콜백함수 내부의 THIS가 메소드를 호출한 객체를 가리키게 하기 위한 해결법 - 1. ```javascript // Solution 1: that = this function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { var that = this; // this: Prefixer 생성자 함수의 인스턴스 return arr.map(function (x) { return that.prefix + ' ' + x; }); }; var pre = new Prefixer('Hi'); console.log(pre.prefixArray(['Lee', 'Kim'])); ``` - 2. ```javascript // Solution 2: map(func, this) function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map(function (x) { return this.prefix + ' ' + x; }, this); // this: Prefixer 생성자 함수의 인스턴스 }; var pre = new Prefixer('Hi'); console.log(pre.prefixArray(['Lee', 'Kim'])); ``` - 3. ```javascript // Solution 3: bind(this) function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map(function (x) { return this.prefix + ' ' + x;; }.bind(this)); // this: Prefixer 생성자 함수의 인스턴스 }; var pre = new Prefixer('Hi'); console.log(pre.prefixArray(['Lee', 'Kim'])); ``` ### 2. ARROW FUNCTION의 THIS ARROW 함수는 언제나 자신을 포함하는 외부 SCOPE에서 THIS를 계승받는다. > ARROW 함수는 자신만의 THIS를 생성하지 않고 자신을 포함하고 있는 컨텍스트로부터 THIS를 계승받는다. `이를 LEXICAL THIS라 한다.` ```javascript function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map(x => `${this.prefix} ${x}`); }; const pre = new Prefixer('Hi'); console.log(pre.prefixArray(['Lee', 'Kim'])); ``` ## 5. ARROW 함수를 사용해서는 안되는 경우 LEXICAL THIS를 지원하므로 콜백함수에 사용하기 편리하다. > ARROW FUNCTION을 사용하는 것이 오히려 혼란을 불러오는 경우도 있기 때문에 주의하여야 한다. ### 1. 메소드 메소드 정의시 ARROW 함수를 사용하는 것은 피해야 한다. ```javascript // Bad const obj = { name: 'Lee', sayHi: () => console.log(`Hi ${this.name}`) }; obj.sayHi(); // Hi undefined ``` 수정하기 ```javascript // Good const obj = { name: 'Lee', sayHi() { // === sayHi: function() { console.log(`Hi ${this.name}`); } }; obj.sayHi(); // Hi Lee ``` ### 2. prototype 메소드로 사용했을 때와 동일한 문제가 발생한다. ```javascript // Bad const obj = { name: 'Lee', }; Object.prototype.sayHi = () => console.log(`Hi ${this.name}`); obj.sayHi(); // Hi undefined ``` 같은 문제 발생 (수정하기) ```javascript // Good const obj = { name: 'Lee', }; Object.prototype.sayHi = function() { console.log(`Hi ${this.name}`); }; obj.sayHi(); // Hi Lee ``` ### 3. 생성자 함수 생성자 함수로 사용할 수 없다. > prototype 프로퍼티를 가지며 prototype 프로퍼티가 가리키는 프로토타입 객체의 constructor를 사용하지만 arrow함수는 prototype프로퍼티를 가지고 있지 않다. ```javascript const Foo = () => {}; // Arrow Function은 prototype 프로퍼티가 없다 console.log(Foo.hasOwnProperty('prototype')); // false const foo = new Foo(); // TypeError: Foo is not a constructor ```
Java
UTF-8
1,603
2.5
2
[ "MIT" ]
permissive
package net.jackw.olep.common; import org.junit.Assume; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.*; public class DatabaseConfigTest { @Test public void testBootstrapServersDefault() throws IOException { DatabaseConfig config = DatabaseConfig.create("test"); assertEquals("127.0.0.1:9092", config.getBootstrapServers()); } @Test public void testBootstrapServersOne() throws IOException { DatabaseConfig config = DatabaseConfig.create(getPath("one-bootstrap-server-test-config.yml"), "test"); assertEquals("127.8.9.10", config.getBootstrapServers()); } @Test public void testBootstrapServersMultiple() throws IOException { DatabaseConfig config = DatabaseConfig.create(getPath("multiple-bootstrap-servers-test-config.yml"), "test"); assertEquals("127.8.9.10,10.1.1.1", config.getBootstrapServers()); } @Test(expected = IllegalStateException.class) public void testGetMysqlUserWhenNoConfig() throws IOException { Assume.assumeTrue(System.getenv("MYSQL_USER") == null); DatabaseConfig config = DatabaseConfig.create("test"); config.getMysqlUser(); } @Test public void testGetMysqlUserWhenConfigured() throws IOException { DatabaseConfig config = DatabaseConfig.create(getPath("mysql-test-config.yml"), "test"); assertEquals("theuser", config.getMysqlUser()); } private String getPath(String configFile) { return DatabaseConfigTest.class.getClassLoader().getResource(configFile).getPath(); } }
C#
UTF-8
852
3.859375
4
[]
no_license
using System; using System.Collections.Generic; namespace Exercise4_5 { static class Bezier { public static double Approx(int n, double t, List<double> x) { double sum = 0; for (int i = 0; i < x.Count; i++) { sum += x[i] * F(i, n, t); } return sum; } public static double F(int i, int n, double t) { return C(i, n) * Math.Pow(t, i) * Math.Pow(1 - t, n - i); } public static double C(int k, int n) { return (Factorial(n) / (Factorial(k) * Factorial(n - k))); } public static int Factorial(int i) { if (i <= 1) return 1; return i * Factorial(i - 1); } } }
TypeScript
UTF-8
1,381
2.671875
3
[]
no_license
import type { APIGatewayEvent, APIGatewayProxyResult } from 'aws-lambda' import type { MongoClient } from 'mongodb' import type { CactusItem, DbResponse } from '../../types' import dbConnection from './mongo-connect' // Get data from db const getData = async (id: string): Promise<DbResponse> => { const client: MongoClient = dbConnection() const where: { id?: string } = {} if (id) { where.id = id } try { await client.connect() const data: Array<CactusItem> = await client .db('db') .collection('cactuses') .find(where) .toArray() return { err: false, data, } } catch (err) { console.log(err) return { err: true, message: "We are sorry, there's problem on the server.", } } finally { await client.close() } } // GET /cactus // GET /cactus?id=1 export const getCactuses = async ( event: APIGatewayEvent ): Promise<APIGatewayProxyResult> => { // Load data from db const response: DResponse = await getData(event.queryStringParameters.id) if (response.err) { return { statusCode: 500, body: JSON.stringify(response), } } return { statusCode: 200, body: JSON.stringify(response.data), } }
C++
UTF-8
1,123
2.640625
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
// ydb_map.h // Author: Allen Porter <allen@thebends.org> // // A mapping of string key/value pairs, the underlying data storage for ydb. A // Ydb_Map can be accessed concurrently by multiple threads after the // initialization, but relies on Ydb_LockTable to protect concurrency of the // underlying data. // // TODO(aporter): Checkpoint command? #ifndef _YDB_MAP_H_ #define _YDB_MAP_H_ //#include <map> #include "ythread/mutex.h" #include "ydb_base.h" #include "ydb_tree.h" class Ydb_Map { public: ~Ydb_Map(); static Ydb_Map* Open(const string& directory); // Returns the value for the key. Returns false is the key does not exist. bool Get(const string& key, string* value); // Updates the key with the value. void Put(const string& key, const string& value); // Deletes the key. Returns false if the key did not already exist. bool Del(const string& key); void Dump(); private: // typedef map<string, string> ymap; // Ydb_Map cannot be instantiated directly. See open() static method. Ydb_Map(); ythread::Mutex mutex_; Ydb_Tree db_; // ymap db_; string db_file_; }; #endif // _YDB_MAP_H_
Java
UTF-8
1,032
2.671875
3
[]
no_license
package com.vertx101.eventstreams; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class StockFeed { private String name; private double value; private double prevValue; private String updatedOn; // Replace with lombok public String getName() { return this.name; } public void setName(String name) { this.name = name; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public double getPrevValue() { return prevValue; } public void setPrevValue(double prevValue) { this.prevValue = prevValue; } public String getUpdatedOn() { return updatedOn; } public void setUpdatedOn(String updatedOn) { this.updatedOn = updatedOn; } public void setValues(String name, double value) { this.prevValue = this.value; this.name = name; this.value = value; this.updatedOn = DateTimeFormatter.ofPattern("yyyy-mm-dd HH:mm:ss").format(LocalDateTime.now()); } }
JavaScript
UTF-8
1,004
3.484375
3
[]
no_license
'use strict'; //------------------------------------------------------------ console.log('----------'); // Hello World console.log('Hello World'); //------------------------------------------------------------ console.log('----------'); // 引数の出力 // i = 0 の場合 → node.js のパス // i = 1 の場合 → 実行スクリプトのパス // i = 2 以上 の場合 → アプリの引数 // バッチファイルにファイルをドラッグ&ドロップなどで引数を渡す。 for (var i = 0; i < process.argv.length; i ++) { console.log(i, process.argv[i]); } //------------------------------------------------------------ console.log('----------'); // 変数の初期化 var cnt = 0; var max = 5; // 繰り返し処理 setInterval(function() { if (cnt >= max) { // process.exit() で、処理の途中で終了 // exitの引数 // 0 → 'success' code // その他の数 → 'failure' code process.exit(0); } console.log(cnt); cnt ++; }, 500);
Python
UTF-8
6,268
2.59375
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import os import re import logging import pkg_resources import json # import codecs from seabird.exceptions import CNVError module_logger = logging.getLogger("seabird.utils") def make_file_list(inputdir, inputpattern=r".*\.cnv"): """Search inputdir recursively for inputpattern""" inputfiles = [] for dirpath, dirnames, filenames in os.walk(inputdir): for filename in filenames: if re.match(inputpattern, filename): inputfiles.append(os.path.join(dirpath, filename)) inputfiles.sort() return inputfiles def basic_logger(logger=None): if logger is not None: assert type(logger) is logging.Logger else: # create logger logger = logging.getLogger("CNV logger") logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) return logger def press2depth(press, latitude): """calculate depth from pressure http://www.seabird.com/application_notes/AN69.htm ATENTION, move it to fluid. """ import numpy as np x = np.sin((np.pi / 180) * latitude / 57.29578) ** 2 g = 9.780318 * (1.0 + (5.2788e-3 + 2.36e-5 * x) * x) + 1.092e-6 * press depth = ( -( (((-1.82e-15 * press + 2.279e-10) * press - 2.2512e-5) * press + 9.72659) * press ) / g ) return depth def load_rule(raw_text): """Load the adequate rules to parse the data It should try all available rules, one by one, and use the one which fits. """ rules_dir = "rules" rule_files = pkg_resources.resource_listdir(__name__, rules_dir) rule_files = [f for f in rule_files if re.match(r"^cnv.*\.json$", f)] for rule_file in rule_files: text = pkg_resources.resource_string( __name__, os.path.join(rules_dir, rule_file) ) rule = json.loads(text.decode("utf-8")) # Should I load using codec, for UTF8?? Do I need it? # f = codecs.open(rule_file, 'r', 'utf-8') # rule = yaml.load(f.read()) # Transitioning for the new rules concept for regexp. if "sep" in rule: r = rule["header"] + rule["sep"] + rule["data"] else: r = ( "(?P<header> " + rule["header"] + ")" + "(?P<data> (?:" + rule["data"] + ")+)" ) content_re = re.compile(r, re.VERBOSE) if re.search(r, raw_text, re.VERBOSE): # logging.debug("Using rules from: %s" % rule_file) # self.rule = rule parsed = content_re.search(raw_text).groupdict() return rule, parsed # If haven't returned a rule by this point, raise an exception. # logging.error("No rules able to parse it") raise CNVError(tag="noparsingrule") def seabird_dir(subdir=None): """Return the local support/config directory Returns a local directory used to store testing data. The default path (~/.config/seabird) can be overwritten by the environment variable SEABIRD_DIR. """ spath = os.getenv("SEABIRD_DIR", "~/.config/seabird") return os.path.expanduser(spath).replace("/", os.path.sep) def sampledata(filename=None, dtype=None): """Return the full path to local sample data The first time it will download the sample data files into the default seabird directory. Check seabird_dir() if you want to modify that. """ try: from supportdata import download_file except ImportError: module_logger.error( "Missing package supportdata. Try:\npip install supportdata" ) outputdir = os.path.join(seabird_dir(), "sampledata") if not os.path.exists(outputdir): os.makedirs(outputdir) src = "https://raw.githubusercontent.com/castelao/seabird/dev/sampledata" filesdb = { "PIRA001.cnv": {"dtype": "CTD", "md5": "5ded777144300b63c8775b1d7f033f92"}, "dPIRX003.cnv": {"dtype": "CTD", "md5": "4b941b902a3aea7d99e1cf4c78c51877"}, "dPIRX010.cnv": {"dtype": "CTD", "md5": "8691409accb534c83c8bd412afbdd285"}, "Hotin.cnv": {"dtype": "CTD", "md5": "814dc769c0775327bbe5b0f489dfb571"}, "missing_whitespace.cnv": { "dtype": "CTD", "md5": "c1f00cebb5f00f6aaebc316bac3fd86a", }, "SK287_CTD05.cnv": {"dtype": "CTD", "md5": "08e974c46ed603442eecf9145031a6c4"}, "sta0860.cnv": {"dtype": "CTD", "md5": "1c788c4d9b82b527ebf0c2fb9200600e"}, #'more_after_file_type.cnv': { # 'dtype': "CTD", 'md5': "e5bffcfdcaf52333773bbe7abe98b06d"}, # ['CTD', 'laurynas.cnv', '6f188d53ac2d7aaaf4ce69c0e5c514ec'], # 'TSG_PIR_001.cnv': { # 'dtype': "TSG", 'md5': "2950ccb9f77e0802557b011c63d2e39b"}, # 'TSG_PIR_010.cnv': { # 'dtype': "TSG", 'md5': "d87cea33bfe37e22dc8e563f77cbf307"}, # 'MI18MHDR.btl': { # 'dtype': "btl", 'md5': "775f2a6c6585f1cffb0038111580e5a1"}, } if dtype is not None: for f in [f for f in filesdb if filesdb[f]["dtype"] != dtype]: del filesdb[f] if filename is None: datafile = [] for f in filesdb: print(f) download_file( outputdir=outputdir, url=os.path.join(src, filesdb[f]["dtype"], f), filename=f, md5hash=filesdb[f]["md5"], ) datafile.append(os.path.join(outputdir, f)) return datafile elif filename in filesdb: download_file( outputdir=outputdir, url=os.path.join(src, filesdb[filename]["dtype"], filename), filename=filename, md5hash=filesdb[filename]["md5"], ) return os.path.join(outputdir, filename) else: module_logger.error("%s is not a valid test file" % filename)
C
UTF-8
12,416
2.796875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <dirent.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <fcntl.h> #include <string.h> #include <memory.h> #include <pthread.h> #include <time.h> #include "client.h" #include "utility.h" /* * 在port模式下接受连接 */ int port_connect_data() { //port模式 struct sockaddr_in client_fd; unsigned int size_sock = sizeof(struct sockaddr_in); if ((data_fd = accept(data_lis_port, (struct sockaddr *) &client_fd, &size_sock)) == -1) { printf("Error accept(): %s(%d)\n", strerror(errno), errno); return 1; } return 0; } /* * 在pasv模式下开始连接 */ int pasv_connect_data() { if (connect(data_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { printf("Error connect(): %s(%d)\n", strerror(errno), errno); return 1; } return 0; } /* * 初始化客户端 */ int client_init() { struct sockaddr_in addr; //创建socket if ((control_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { printf("Error socket(): %s(%d)\n", strerror(errno), errno); return 1; } //设置目标主机的ip和port memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(control_port); //转换ip地址:点分十进制-->二进制 if (inet_pton(AF_INET, server_ip, &addr.sin_addr) <= 0) { printf("Error inet_pton(): %s(%d)\n", strerror(errno), errno); return 1; } //连接上目标主机(将socket和目标主机连接)-- 阻塞函数 if (connect(control_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { printf("Error connect(): %s(%d)\n", strerror(errno), errno); return 1; } return 0; } /* * port模式,客户端创建套接字data_lis_port,监听所选的端口 * 这里的addr是临时的,(监听来源严格一点应该是服务器端IP) */ int cmd_port(char* para){ int h1,h2,h3,h4,p1,p2; if (sscanf(para, "%d,%d,%d,%d,%d,%d", &h1, &h2, &h3, &h4, &p1, &p2) != 6) { printf("input error\n"); return 1; } struct sockaddr_in addr;//临时设置的地址,为bind准备 if (data_lis_port > 0){ close(data_lis_port); data_lis_port = 0; } //创建socket if ((data_lis_port = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { printf("Error socket(): %s(%d)\n", strerror(errno), errno); return 1; } //设置本机的ip和port memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(p1*256 + p2); //监听任何来源 addr.sin_addr.s_addr = htonl(INADDR_ANY); //将本机的ip和port与socket绑定 if (bind(data_lis_port, (struct sockaddr*)&addr, sizeof(addr)) == -1) { printf("Error bind(): %s(%d)\n", strerror(errno), errno); return 1; } //开始监听socket if (listen(data_lis_port, 1) == -1) { printf("Error listen(): %s(%d)\n", strerror(errno), errno); return 1; } is_pasv = 0; return 0; } /* * Passive 模式,服务器发过来其地址,将其保存在server_addr * 创建data_fd作为数据端口的套接字 * 服务器测试结果:PASV结束后要去连接服务器 */ int cmd_pasv(char* sentence) { int h1,h2,h3,h4,p1,p2; int i = 0; int len = strlen(sentence); int ret_code; if (sscanf(sentence, "%d", &ret_code) != 1) return 1; if (ret_code != 227) { printf("ret code not 227\n"); return 1; } //第一个空格 while (i < len) { if (sentence[i] == ' ') break; else i++; } if (i == len) { printf("Error with server's reply: %s\n", sentence); return 1; } //之后的第一个数字 while (i < len) { if (sentence[i] >= '0' && sentence[i] <= '9') break; else i++; } if (i == len) { printf("Error with server's reply: %s\n", sentence); return 1; } sscanf(sentence + i, "%d,%d,%d,%d,%d,%d", &h1, &h2, &h3, &h4, &p1, &p2); //创建socket if (data_fd > 0) { close(data_fd); data_fd = 0; } if ((data_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { printf("Error socket(): %s(%d)\n", strerror(errno), errno); return 1; } //设置目标主机的ip和port memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(p1 * 256 + p2); //转换ip地址:点分十进制-->二进制 if (inet_pton(AF_INET, server_ip, &server_addr.sin_addr) <= 0) { printf("Error inet_pton(): %s(%d)\n", strerror(errno), errno); return 1; } if (pasv_connect_data()) return 1; is_pasv = 1; return 0; } /* * 用于多线程接口 */ void* download_file_pthread(void* ptr) { download_file(*(int*)ptr); return NULL; } /* * 用于多线程 */ void* upload_file_pthread(void *ptr) { upload_file(*(int*)ptr); return NULL; } /* * 下载文件 */ void download_file(int file) { //开始接收 int temp_size; char* buff = (char*)malloc(4096); while (1) { temp_size = read(data_fd, buff, 4096); write(file, buff, temp_size); if (temp_size == 0) break; // if (temp_size < 4096) { // break; // } } //传输完成 close(data_fd); data_fd = 0; if (is_pasv == 0) { //port模式 close(data_lis_port); data_lis_port = 0; } close(file); free(buff); return; } /* * 上传文件函数 */ void upload_file(int file) { struct stat file_stat; fstat(file, &file_stat); long long bytes_to_send = file_stat.st_size; char* buff = (char*)malloc(4096); while (bytes_to_send) { int temp_size = bytes_to_send > 4096 ? 4096 : bytes_to_send; int read_size = read(file, buff, temp_size); if (read_size) { write(data_fd, buff, read_size); } bytes_to_send -= read_size; } free(buff); //传输完成,关闭连接 close(data_fd); data_fd = 0; if (is_pasv == 0) { //pasv模式 close(data_lis_port); data_lis_port = 0; } close(file); return; } /* * 显示list函数,多线程,传输给端口 */ void* show_list() { char* buff = (char*)malloc(4096); while (1) { int size = read(data_fd, buff, 4096); if (size < 4096){ buff[size] = '\0'; printf("%s", buff); break; } else printf("%s\n", buff); } free(buff); close(data_fd); data_fd = 0; if (is_pasv == 0) { //pasv模式 close(data_lis_port); data_lis_port = 0; } return NULL; } /* * retr指令,此时要开始从data端口接收东西 * 但是需要使用多线程形式 */ int cmd_retr(char* sentence, char* para) { int ret_code; if (sscanf(sentence, "%d", &ret_code) != 1) return 1; if (ret_code != 150) { printf("ret code not 150\n"); return 1; } if (is_pasv == -1) { printf("no connection made.\n"); return 1; } if (is_pasv == 0) { //port 模式,需要此时去连接 if (port_connect_data()) return 1; } //打开文件 char* file_root = get_absolute_dir(root_directory, para, -1); int file = open(file_root, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU | S_IXGRP | S_IROTH | S_IXOTH | S_IRGRP); if (file == -1) { printf("No such file\n"); return 1; } free(file_root); //开始下载 pthread_t thid; pthread_create(&thid, NULL, (void*)download_file_pthread, (void*)&file); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); sscanf(sentence, "%d", &ret_code); if (ret_code == 226) pthread_join(thid, NULL); else { pthread_cancel(thid); close(data_fd); data_fd = 0; if (is_pasv == 0) { //pasv模式 close(data_lis_port); data_lis_port = 0; } close(file); } is_pasv = -1; return 0; } /* * stor指令,和retr相似 */ int cmd_stor(char* sentence, char* para) { int ret_code; if (sscanf(sentence, "%d", &ret_code) != 1) return 1; if (ret_code != 150) { printf("ret code not 150\n"); return 1; } if (is_pasv == -1) { printf("no connection made.\n"); return 1; } if (is_pasv == 0) { //port 模式,需要此时去连接 if (port_connect_data()) return 1; } //打开文件 char* file_root = get_absolute_dir(root_directory, para, -1); int file = open(file_root, O_RDONLY); free(file_root); if (file <= 0) { close(data_fd); data_fd = 0; if (is_pasv == 0) { //pasv模式 close(data_lis_port); data_lis_port = 0; } close(file); } //开始上传 pthread_t thid; pthread_create(&thid, NULL, (void*)upload_file_pthread, (void*)&file); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); sscanf(sentence, "%d", &ret_code); if (ret_code == 226) pthread_join(thid, NULL); else { pthread_cancel(thid); close(data_fd); data_fd = 0; if (is_pasv == 0) { //pasv模式 close(data_lis_port); data_lis_port = 0; } close(file); } is_pasv = -1; return 0; } /* * list指令的主控制 */ int cmd_list(char* sentence) { int ret_code; if (sscanf(sentence, "%d", &ret_code) != 1) return 1; if (ret_code != 150) { printf("ret code not 150\n"); return 1; } if (is_pasv == -1) { printf("no connection made.\n"); return 1; } if (is_pasv == 0) { //port 模式,需要此时去连接 if (port_connect_data()) return 1; } pthread_t thid; pthread_create(&thid, NULL, (void*)show_list, NULL); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); sscanf(sentence, "%d", &ret_code); if (ret_code == 226) pthread_join(thid, NULL); else { pthread_cancel(thid); close(data_fd); data_fd = 0; if (is_pasv == 0) { //pasv模式 close(data_lis_port); data_lis_port = 0; } } is_pasv = -1; return 0; } int main(int argc, char **argv) { if (client_init()) return 1; char sentence[8192]; int len; //初始连接成功的提示 int m = recv(control_fd, sentence, 8192, 0); if (!m){ printf("Not getting message from server\n"); return 1; } sentence[m] = '\0'; printf("%s", sentence); char* cmd = (char*)malloc(256); char* para = (char*)malloc(256); while (1) { printf("my_ftpclient-> "); //获取键盘输入 fgets(sentence, 4096, stdin); len = strlen(sentence); if (len < 2) { printf("no input given.\n"); continue; } sentence[len - 1] = '\r'; sentence[len] = '\n'; sentence[len + 1] = '\0'; len++; sscanf(sentence, "%s %s", cmd, para); if (strcmp(cmd, "PORT") == 0) { //首先根据输入开始监听,如果错误则不会发消息 if (cmd_port(para)) continue; //send msg to server send(control_fd, sentence, len, MSG_WAITALL); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); } else if (strcmp(cmd, "PASV") == 0) { //pasv模式,首先发给服务器 send(control_fd, sentence, len, MSG_WAITALL); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); cmd_pasv(sentence); } else if (strcmp(cmd, "RETR") == 0) { //下载文件,首先直接将消息发给服务器 send(control_fd, sentence, len, MSG_WAITALL); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); if (cmd_retr(sentence, para)) { int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); } } else if (strcmp(cmd, "STOR") == 0) { //上传文件,首先直接将消息发给服务器 send(control_fd, sentence, len, MSG_WAITALL); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); if (cmd_stor(sentence, para)) { int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); } } else if (strcmp(cmd, "LIST") == 0) { //首先直接将消息发给服务器 send(control_fd, sentence, len, MSG_WAITALL); int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); if (cmd_list(sentence)) { int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); } } else { //正常情况,直接显示服务器返回的消息 //首先直接将消息发给服务器 send(control_fd, sentence, len, MSG_WAITALL); int ret_code; int m = recv(control_fd, sentence, 8192, 0); sentence[m] = '\0'; printf("FROM SERVER: %s", sentence); if (sscanf(sentence, "%d", &ret_code) != 0) if (ret_code == 221) break; } } free(cmd); free(para); close(control_fd); return 0; }
Python
UTF-8
1,021
2.65625
3
[]
no_license
import socket import subprocess import numpy as np import cv2 host = 'localhost' port = 6969 vlc_location = '/Applications/VLC.app/Contents/MacOS/VLC' def recieve(): usr = input('ingrese el usuario: ') pwd = input('ingrese la contraseña: ') print('Canales:\n 1.Hubbabubbaklubb - Mopedbart\n 2.The Killers - Human') canal = input('ingrese el numero del canal que desea ver: ') s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.connect((host,port)) s.send((usr + '///' + pwd + '///' + canal).encode('utf-8')) print('Conectado por el puerto', port) encoded_frame = s.recv(1024) queue = [] while True: encoded_frame += s.recv(1024) if(len(encoded_frame)) == 2764800: frame = np.frombuffer(encoded_frame, dtype=np.uint8).reshape(720,1280,3) queue.append(frame) cv2.imshow(('Canal'+ str(canal)), frame) encoded_frame = s.recv(1024) if __name__ == "__main__": recieve() cv2.destroyAllWindows()
PHP
GB18030
861
2.546875
3
[ "Apache-2.0" ]
permissive
<?php namespace app\json\controller; use think\Controller; use app\json\model\RoleModel; use think\Request; class Role extends Controller{ //ɫӿ public function index(){ $result = (new RoleModel())->lists(); return json($result); } public function add(){ //ӽɫ $request = Request::instance(); if ($request->isPost()){ $role_id = $request->post('role_id'); $rs = (new RoleModel())->addRole($role_id); return json($rs); } } public function delete(){ //ɾɫ $request = Request::instance(); if ($request->isPost()){ $id = $request->post('id'); $rs = (new RoleModel())->deleteRole($id); return json($rs); } } }
Markdown
UTF-8
761
2.59375
3
[]
no_license
## Term Projects I put my class projects here * [Optics project](Optics/) * [Neutron beta decay](Neutrinos/) * [Variational method in electrodynamics](Variational/) ## My Undergraduate Project In the [discs](\discs) folder, you can find some of the codes I wrote for my undergraduate project. It's mostley optimizing data and plotting lightcurves of microlensing events. Here's a link to the paper we (My professor and I) published: [arxiv:2008.02847](https://arxiv.org/abs/2008.02847) ## CV And here you can find my CV: [My CV](CV/Ali_Salehi_CV.pdf) ## Manim clips I made a few short [manim](https://github.com/3b1b/manim) clips about special relativity, microlensing and geometrical congruence. you can find them in [Manim clips](Manim_clips/) folder.
Markdown
UTF-8
10,202
2.59375
3
[]
no_license
第二回 金龙密令(8) 南宫平面容苍白,全无血色,身形僵木,全不动弹,目光呆滞地望着高髻道人,只见他语气渐渐衰微,双睛却渐渐突出,眼珠渐灰渐白,眼白却渐红渐紫,最后望了南宫平一眼,手掌渐松,嘴唇一张,身躯微微向左转了半圈,噗地,倒在地上! 接着,又是“噗”地一声,南宫平手掌一软,棺盖落下,他失神地望着地上的尸身又失神地望着掌中的长剑,是后一滴鲜血,自剑尖滴落,长剑仍然碧如秋水! 他只觉心头一软,几乎忍不住有一种冲动,要将掌中这柄利器,抛落万丈深渊之下,然而,他却始终忍住,只是呆呆地站在那里,心中反反复复地在低念着一句话:“我终于杀了人了……我终于杀了……人了!”生平第一次,他体验到杀人后的感觉,也体会出杀人的感觉原来竟是这般难受! 望着地上鲜血淋漓的尸身,他只觉头脑一阵晕眩,胃腹一阵翻腾,此人与他仅是一次见面,他们甚至连彼此间的姓名都不知道,而这条陌生的性命,此刻却已死在他的剑下。 他茫然向前走了两步,然后又转回头,茫然托起地上的棺木,迎着扑面而来的山风,也不知走了多久,他蹒跚来到苍龙岭尽头,却又茫然顿住脚步,口中喃喃道:“我该将他的尸骨埋葬的……”突地放足狂奔,奔回原处,地上的血渍仍在,但是——那神秘、奇诡,而又可怜的高髻道人的尸身,此刻竟然不知去向。 山风在耳边呼啸、白云在眼前飘舞,南宫平茫然立在这山风呼啸,白云飞舞的孤脊上,耳中却什么也听不见,眼中什么都看不见,良久良久,他目光方自投落到那冥冥寞寞、深不见底的万丈绝壑中去,然后便将胸中的痛苦与忏悔,都化做了一声悠长沉重的叹息。 他口中虽无言,心中却在暗自祈祷,希望那被山风吹下绝壑的幽魂,能够得到安息,又不知过了许久,他只觉高处风寒,身上竟有些寒意,于是他手托棺木,回转身,走下苍龙岭,山腰处,风声渐息,寂寞的华山,便更加寂寞。 他紊乱的心情,却更加紊乱,除了那份对死者的忏悔与痛苦之外,他心中还有着许多无法解释的疑团!令他最思疑和迷惑的是,他直至此刻,还猜不透这具看来平凡的紫檀棺木内,究竟隐藏着什么秘密?多少秘密? 寻了处幽静的山林,他将掌中所托的棺木,轻轻放到虽已渐呈枯萎,却仍柔软如茵的草地上,掀开棺盖,看了一眼,棺中的确空无一物,他仔细地再看了两眼,只觉这棺外观虽大,棺内却显得甚为浅窄,在那深紫色的木板上,似乎还有几点似乎是油渍般的污痕,不经细看,绝难察觉。 然而,纵是如此,他仍然看不出,这棺木有丝毫特异之处。 他以手支额,坐在树下,树上的秋叶,已自萧萧凋落,使得这寂寞深山中的初秋天气,更平添了几分肃杀之意,也使得这初秋天气中的寂寞少年,平添了几分凄凉心境! 他苦苦思索着这些他无法解释的疑团,竟忘却了探究他的同门兄妹为何直到此刻还未下山的原因,伸手入怀,他取出了那条淡黄的丝绢,也触及了那只不知是太多的愚笨,抑或是太多的智慧方自使得它自撞山石而死的山鸟那冰凉的羽毛。 于是他悲哀地、自嘲地微笑了一下,握紧丝绢,取出死鸟,展开丝绢,那苍劲而熟悉的字迹,立刻又在他心底引起一股冲激的悲哀浪潮,他合上眼帘,叹息一声,再张开,只见上面写的是: “余一生虽杀人无数,然所杀者无不可杀之人,是以余生平虽然可曰无憾……” 南宫平为之长叹一声,他仔细地体会这“无憾”两字其中的滋味,暗中不禁长叹自语:“这两字看来虽平凡,其实却不知要花多少精力,忍耐多少痛苦才能做到,而我呢……’ 他想起方才死在他剑下的道人:“我伤了此人,心中能否无憾?”他也想起那道人方才的言语,“师傅他老人家一生无憾,怎会做出他口中所说那样的事!” 于是他信心恢复,宽然一笑,接着下看:“然余无憾之中,亦有一事,可称遗憾……” 南宫平心头一冷,立即下看:“十余年前,武林中盛传一人劣迹昭彰,余心久已深恨之,适逢其人又伤余一友,是以余仗剑而出,将之毙于剑下,然事后余却知此事实乃余友之错,而那平素恶行极多之人,于此事中,反是清白无辜,是以余……” 下面的字迹,突地为一片鸟血所染,再也看不清楚! 南宫平方自看到紧要之处,此刻自是急怒交集,但鸟血已干,纵然洗去,字迹亦将模糊不清,他剑眉双轩,双拳紧握丝绢,呆呆地愕了半晌,心中突又一颤:“难道这片血迹,是自师傅他老人家身上流出的!” 一念至此,胸中热血倏然上涌,倏然长身而起,只觉满怀悲激,无可宣白,方待仰天长啸一声,目光突地瞥见那只鲜血淋漓的死鸟尸体! 一时之间,他不知是该大笑三声,抑或是该大哭三声,颓然坐回地上,目光凝注死鸟,发出一声无可奈何的叹息,只得跳过那片血渍,往下接看,鸟血的下面,写的是—— “是以余将此人交托于汝,望汝好生看待于她……” 南宫平双眉一皱,诧声自语:“她……?她……她是谁?” 愕了半晌,再往下看: “临行匆匆,余亦不能将此事尽告于汝,然汝日后必有一日,能尽知其中真相,余往日不能善于待汝,亦是余生平一憾,惟望汝日后戒言戒恶,奋发图强,勿负余对汝之期望!” 这寥寥数十字,南宫平翻来覆去,竟不知看了多久,只觉这淡黄丝绢上的字迹,越看越见模糊,吹在他身上的山风,寒意也越来越重! “临行匆匆……”他口中喃喃自语:“难道……难道师傅他老人家真的死了么?……”于是,两行热泪,终于夺眶而出。 悲哀,加上怀疑,这滋味的确令他无法忍受,“日后必有一日,能尽知此事真相……” 但这一日,何时方至?“余往日不能善于待汝,亦是余生平一憾……”他伸手一拭面上泪痕,仰天呼道:“师傅,你老人家一直对我是极好的,我也一直感激你老人家,你老人家难道不知道么?” 他茫然地用自己的手掌,在浅浅的草地上掘了个浅浅的土坑! 然后,便将那只死鸟,仔细地埋葬在这浅浅的土坑里。 他纤长而苍白的手掌,都已沾满了褐黄色的泥土,土坑拍平,一声叹息,他任凭泥土留在手掌上,口中却又不禁喃喃自语:“我与你终是有缘,是么?否则世界如此之大,你怎会偏偏落入我的手掌里?这土坑虽浅,但已可为你聊蔽风雨……” 一声沉重的叹息,他倏然顿住语声,因为他心中突地想起了那被他一剑刺死的道人,那一具碧绿的尸身,今后岂非将长久暴露于无底的绝壑中,永恒的风露下,于是他以纤长的手掌,划开面前那一片青青的山草,正如他冀望以他无形的利剑,划开他心中的积郁。 青草虽分,积郁仍在,他黯然合上眼帘,冀求这份黑暗的宁静,能使他心中杂乱的思潮澄清,于是一层沉重的疲倦,便也随着眼帘的落下,而布满到他全身,为着今晨的决战,“止郊山庄”的门人弟子,昨宵已彻夜未眠,何况南宫平刚才与那高髻道人一番苦斗,更耗尽了他体内所有的真力! 生理的疲倦,使得他心理的紧张渐渐松弛,也使得他身心进人一种恬适的虚无境界,也不知过了多久…… 西山日薄,晚霞满林,黄昏渐至,树林中突地发出“咯”地一声轻响,那平凡而神秘的紫檀棺木,棺盖竟缓缓向上掀丁开来—— 宁静的山林中,这声响虽然轻微,却已足够震动了南宫平的心弦,他霍然张开眼睛,正巧看到这一幅骇人的景象——无人的棺木中,竟有一双莹白如玉的纤纤玉手,缓缓将棺盖托开! 南宫平这一惊之下,睡意立刻全被惊散,只见那棺盖越升越高…… 接着出现的,是一络如云的秀发,然后是一张苍白的面庞。 满天夕阳,其红如血,映在这张苍白的面庞上,竟不能为她增加半分血色,南宫平纵然胆大,此刻却也不禁自心底升起一阵寒意,沉声道:“你……你是……谁?”他虽然鼓足勇气,但语声仍在微微颤抖。 棺中的绝色丽人,此刻已白棺中缓缓长身而起,她那纤弱而动人的美丽身躯,被裹在一件正如她面容一样纯白的长袍里,山风吹动,白袍飞舞,她身躯竟似业要随风飞去,然而她一双明媚的眼睛,却有如南宫平座下的华山一般坚定! 她轻抬莲足,自棺中缓缓跨出,袍袖之下,掩住她一双玉掌,一步一步地向南宫平走了过来,她面上既无半分笑容,更没有半分血色,甚至连她那小巧的樱唇,都是苍白的,空山寂寂,骤然看见了她,谁都会无法判断她来自人间,抑或是来自幽冥! 南宫平双拳紧握,只觉自己掌心俱已冰冷,气纳丹田,大喝一声:“你是谁?”方待自地上一跃而起,哪知这棺中的绝色丽人,突然地轻轻一笑,柔声说道:“你怕什么?难道你以为我是……”再次轻笑一声,倏然住口不语。 她语声竟有如三月春风中的柳絮那么轻柔,那般令人沉醉,她那温柔的一笑,更能令铁石心肠的人见了都为之动心,她所有自棺中带出的那种令人悚栗的寒意,刹那之间,便在她这温柔的笑语中化去。
Java
GB18030
1,788
2.921875
3
[]
no_license
import java.sql.*; public class BatchTester{ public static void main(String args[])throws Exception{ Connection con=new ConnectionProvider().getConnection(); try{ con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.addBatch("delete from ACCOUNTS"); stmt.addBatch("insert into ACCOUNTS(ID,NAME,BALANCE)" +"values(1,'Tom',1000)"); stmt.addBatch("insert into ACCOUNTS(ID,NAME,BALANCE)" +"values(2,'Jack',1000)"); stmt.addBatch("update ACCOUNTS set BALANCE=900 where ID=1"); stmt.addBatch("update ACCOUNTS set BALANCE=1100 where ID=2"); int[] updateCounts=stmt.executeBatch(); for (int i = 0; i < updateCounts.length; i++) { System.out.print(updateCounts[i] + " "); } con.commit(); }catch(BatchUpdateException ex) { System.err.println( "----BatchUpdateException----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println( "Vendor: " + ex.getErrorCode()); System.err.print("Update counts: "); int [] updateCounts = ex.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { System.err.print(updateCounts[i] + " "); } System.err.println(""); con.rollback(); }catch(SQLException ex) { con.rollback(); }finally{ con.close(); } } } /**************************************************** * ߣ * * Դ<<Java̾>> * * ַ֧www.javathinker.org * ***************************************************/
Markdown
UTF-8
2,076
2.9375
3
[]
no_license
# PostgreSQL common commands ## 1. Create new users and databases ### Accessing a Postgres Prompt Without Switching Accounts ```shell $ sudo -u postgres psql ``` You can exit the interactive Postgres session by typing: ```shell postgres=# \q ``` ### Create a New Role ```shell $ sudo -u postgres createuser --interactive ``` ### Create a New Database ```shell $ sudo -u postgres createdb my_db ``` ### Check the Connection Information ```shell sammy=# \conninfo ``` ### References - [How To Install and Use PostgreSQL on Ubuntu 16.04](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-16-04) ## 2. Rename a Column of a Table ### Single Column ```shell ALTER TABLE table_name RENAME COLUMN column_name TO new_column_name; ``` ### Multiple Columns ```shell ALTER TABLE table_name RENAME column_name_1 TO new_column_name_1, RENAME column_name_2 TO new_column_name_2, ...; ``` ## 3. Rename a Database ```shell ALTER DATABASE "old_name" RENAME TO "new_name"; ``` ## 4. Add New Columns to a table ```shell ALTER TABLE table_name ADD COLUMN new_column_name_1 data_type constraint, ADD COLUMN new_column_name_2 data_type constraint, ... ADD COLUMN new_column_name_n data_type constraint; ``` ## 5. List tables ```shell \dt ``` or ```shell SELECT * FROM pg_catalog.pg_tables; ``` ## 6. Dump and restore [PostgreSQL Documentation: `pg_dump`](https://www.postgresql.org/docs/current/app-pgdump.html) ### Dump ```shell $ sudo -u my_dba pg_dump my_db > my_db_dump.sql ``` ### Restore <!-- Attention: you may need to change the file mode to allow the dba user allowed to read the dumped file `my_db_dump.sql`. If your current user is `derek`, then you can achieve this by: ``` # chgrp my_dba my_db_dump.sql # usermod -aG my_dba derek ``` Then both `my_dba` and `derek` (who are now both in the `my_dba` group) can read the file `my_db_dump.sql` --> Create a new database `my_db`: ```shell $ sudo -iu postgres createdb -O my_dba my_db ``` Script: ```shell $ sudo -iu my_dba psql -d my_db -f my_db_dump.sql ```
C#
UTF-8
2,585
2.6875
3
[]
no_license
using System.Collections.Generic; using UnityEngine; public class TileMap<T> { public Layout Layout { get { return layout; } set { layout = value; } } public RectangleInt Bounds { get { return bounds; } } public int2 SpawnPoint { get; set; } public int2 ExitPoint { get; set; } private Dictionary<int2, T> tiles; private Layout layout; private RectangleInt bounds = new RectangleInt(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue); private int2 accessor = int2.zero; private bool dirty; private int2[] cachedPresentTiles; public TileMap() { dirty = true; tiles = new Dictionary<int2, T>(); layout = new Layout(); } public T this[int x, int y] { get { return this[accessor.Set(x, y)]; } set { this[accessor.Set(x, y)] = value; } } public T this[int2 position] { get { if (tiles.ContainsKey(position)) { return tiles[position]; } else { return default(T); } } set { if (tiles.ContainsKey(position)) { tiles[position] = value; } else { Add(position, value); } } } public bool Add(int x, int y, T tile) { return Add(accessor.Set(x, y), tile); } public bool Add(int2 position, T tile) { bool result = false; if (!tiles.ContainsKey(position)) { tiles[position] = tile; UpdateBounds(position); result = true; dirty = true; } return result; } public void AddSet(Dictionary<int2, T> tileGroup) { var enumerator = tileGroup.GetEnumerator(); while (enumerator.MoveNext()) { this[enumerator.Current.Key.x, enumerator.Current.Key.y] = enumerator.Current.Value; } } public T GetTile(int x, int y) { return this[x, y]; } public int2[] GetPresentTiles() { if (dirty) { cachedPresentTiles = new int2[tiles.Keys.Count]; var enumerator = tiles.GetEnumerator(); int i = 0; while (enumerator.MoveNext()) { cachedPresentTiles[i] = enumerator.Current.Key; i++; } dirty = false; } return cachedPresentTiles; } public Dictionary<int2, T>.Enumerator GetEnumerator() { return tiles.GetEnumerator(); } protected void UpdateBounds(int2 newTile) { int xMin = Mathf.Min(newTile.x, bounds.Min.x); int xMax = Mathf.Max(newTile.x + 1, bounds.Max.x); int yMin = Mathf.Min(newTile.y, bounds.Min.y); int yMax = Mathf.Max(newTile.y + 1, bounds.Max.y); if (xMin < bounds.Min.x || xMax > bounds.Max.x || yMin < bounds.Min.y || yMax > bounds.Max.y) { bounds = new RectangleInt(xMin, yMin, xMax - xMin, yMax - yMin); } } }
Go
UTF-8
209
3.046875
3
[ "MIT" ]
permissive
package main import "fmt" var pow2 = []int{1, 2, 3, 4, 5, 6, 7, 8} func main_range1() { for i, v := range pow2 { fmt.Printf("the index %d ,the value id %+v\n", i, v) } } func main() { main_range1() }
C++
UTF-8
549
3.203125
3
[]
no_license
#include <iostream> #include "listNode.h" using namespace std; ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode* cur = dummy; while (l1 && l2) { if (l1 -> val > l2 -> val) { cur -> next = l2; l2 = l2 -> next; cur = cur -> next; } else { cur -> next = l1; l1 = l1 -> next; cur = cur -> next; } } if (l1) cur -> next = l1; if (l2) cur -> next = l2; return dummy -> next; }
Markdown
UTF-8
861
2.78125
3
[ "Apache-2.0" ]
permissive
# SmartAM Connect Awesome Miner API to SmartThings ## Installation ### Option 1: Github integration The best way to get updates is to enable GitHub integration and add this repository. 1. Open the IDE and navigate to `My SmartApps` 2. Select `Settings` 3. Select `Add new repository` 4. Enter the following details: * Owner: `kenibarwick` * Name: `SmartAM` * Branch: `master` Now whenever you need to update to the latest version, you can choose `↓ Update from Repo`, select the app or device handler, and get your updates. ### Option 2: Manual Install You can also install it manually. 1. Navigate to the app or device handler you want to install and copy the code. 2. Follow the instructions from the [ThingsThatAreSmart.wiki](http://thingsthataresmart.wiki/index.php?title=Using_Custom_Code#Using_a_Custom_SmartApp) on how to install a SmartApp.
PHP
UTF-8
2,096
2.578125
3
[]
no_license
<?php class ControllerPrilOperator extends Controller { public function index() { require_once 'function.php'; $operator = '0'; $key_pril = '100-200'; foreach (object_to_array(retrieveJsonPostData()) as $pril_key => $pril_value) { switch ($pril_key) { case 'operator': $operator = $pril_value; break; case 'key_pril': $key_pril = $pril_value; break; } } if ($operator == '' || $key_pril == '') { echo "Данные переданы не верно!"; exit; } $this->load->model('pril/android'); $customer = $this->model_pril_android->getCustomer($key_pril); if (!$customer) { print_r("Ошибка!"); exit; } $arr_customer = object_to_array(json_decode($customer[0]['custom_field'])); define('APIKEY_USERSIDE', $arr_customer[1]); define('USERSIDE', $arr_customer[2]); if ($operator != "0") { $operator_data = array( 'key' => APIKEY_USERSIDE, 'cat' => 'operator', 'action' => 'get', 'id' => $operator, ); $operator_arr = object_to_array(json_decode(create_ticket($operator_data, USERSIDE))); if ($operator_arr['Result'] == 'OK') { if ($operator_arr['data'][$operator]['staff_id'] != '') { $staff_data = array( 'key' => APIKEY_USERSIDE, 'cat' => 'staff', 'action' => 'get_data', 'id' => $operator_arr['data'][$operator]['staff_id'], ); $staff_arr = object_to_array(json_decode(create_ticket($staff_data, USERSIDE))); if ($staff_arr['Result'] == 'OK') { $staff = $operator_arr['data'][$operator]['staff_id']; print_r($staff_arr['data'][$staff]['name']); } else { print_r("Ошибка! Не могу найти персонал с таким ID."); } } else { print_r("Ошибка! У данного сотрудника нет staff_ID"); } } else { print_r("Ошибка! ID оператора не верный."); } } else { print_r("Служебный"); } } }
Python
UTF-8
1,093
2.59375
3
[]
no_license
from sys import stdin, setrecursionlimit def main(): mod = 10 ** 9 + 7 n, k = map(int, stdin.readline().split()) a = list(map(int, stdin.readline().split())) a.sort() ans = 0 m = n + 1 fac = [0] * m finv = [0] * m inv = [0] * m def initialize_cmb(m): fac[0] = 1 finv[0] = 1 if m > 1: fac[1] = 1 finv[1] = 1 inv[1] = 1 for i in range(2, m): fac[i] = fac[i-1] * i % mod inv[i] = mod - inv[mod % i] * (mod // i) % mod finv[i] = finv[i - 1] * inv[i] % mod def cmb(n, k, mod=10 ** 9 + 7): if n < k: return 0 if n < 0 or k < 0: return 0 return fac[n] * (finv[k] * finv[n - k] % mod) % mod initialize_cmb(m) for i in range(n - k + 1): ans -= a[i] * cmb(n - 1 - i, k - 1) ans %= mod for i in range(k - 1, n): ans += a[i] * cmb(i, k - 1) ans %= mod print(ans % mod) if __name__ == "__main__": setrecursionlimit(10000) main()
PHP
UTF-8
3,217
2.640625
3
[]
no_license
<?php /** * @category BKozlic * @package BKozlic\ProductTabs * @author Berin Kozlic - berin.kozlic@gmail.com * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ namespace BKozlic\ProductTabs\Api\Data; use BKozlic\ProductTabs\Api\Data\ProductTabExtensionInterface; use Magento\Framework\Api\ExtensibleDataInterface; /** * Interface ProductTabInterface */ interface ProductTabInterface extends ExtensibleDataInterface { const TAB_ID = 'tab_id'; const IS_ACTIVE = 'is_active'; const TAB_SORT = 'tab_sort'; const TITLE = 'title'; const TAB_CLASS = 'tab_class'; const CONTENT = 'content'; const CREATION_TIME = 'creation_time'; const UPDATE_TIME = 'update_time'; /** * Returns tab id * * @return int */ public function getId(); /** * Set ID * * @param int $id * @return ProductTabInterface */ public function setId($id); /** * Returns tab class * * @return string|null */ public function getClass(); /** * Set class * * @param string $class * @return ProductTabInterface */ public function setClass($class); /** * Returns content * * @return string|null */ public function getContent(); /** * Set content * * @param string $content * @return ProductTabInterface */ public function setContent($content); /** * Returns is active data * * @return bool */ public function getIsActive(); /** * Set is active * * @param bool $isActive * @return ProductTabInterface */ public function setIsActive($isActive); /** * Returns tab sort number * * @return int */ public function getTabSort(); /** * Set tab order * * @param int $order * @return ProductTabInterface */ public function setTabSort($order); /** * Returns title * * @return string */ public function getTitle(); /** * Set title * * @param string $title * @return ProductTabInterface */ public function setTitle($title); /** * Returns tab creation time * * @return string */ public function getCreationTime(); /** * Set creation time * * @param string $creationTime * @return ProductTabInterface */ public function setCreationTime($creationTime); /** * Returns tab update time * * @return string */ public function getUpdateTime(); /** * Set update time * * @param string $updateTime * @return ProductTabInterface */ public function setUpdateTime($updateTime); /** * Retrieve existing extension attributes object or create a new one. * * @return ProductTabExtensionInterface|null */ public function getExtensionAttributes(); /** * Set an extension attributes object. * * @param ProductTabExtensionInterface $extensionAttributes * @return $this */ public function setExtensionAttributes(ProductTabExtensionInterface $extensionAttributes); }
Markdown
UTF-8
16,210
3
3
[]
no_license
# Adding Movie Genres ### Adding Genre Field To hold Movie genres we need a lookup table. For *Kind* field we used an enumeration but this time genres might not be that *static* to declare them as an enumeration. As usual, we start with a migration. *Modules/Common/Migrations/DefaultDB/ DefaultDB_20160519_154700_GenreTable.cs*: ```cs using FluentMigrator; using System; namespace MovieTutorial.Migrations.DefaultDB { [Migration(20160519154700)] public class DefaultDB_20160519_154700_GenreTable : Migration { public override void Up() { Create.Table("Genre").InSchema("mov") .WithColumn("GenreId").AsInt32().NotNullable() .PrimaryKey().Identity() .WithColumn("Name").AsString(100).NotNullable(); Alter.Table("Movie").InSchema("mov") .AddColumn("GenreId").AsInt32().Nullable() .ForeignKey("FK_Movie_GenreId", "mov", "Genre", "GenreId"); } public override void Down() { } } } ``` We also added a *GenreId* field to *Movie* table. > Actually a movie can have multiple genres so we should keep it in a separate *MovieGenres* table. But for now, we think it as single. We'll see how to change it to multiple later. ### Generating Code For Genre Table Fire sergen.exe using Package Manager Console again and generate code for *Genre* table with the parameters shown below: > Use parameters shown with `dotnet sergen g` if you are using ASP.NET Core version. ![Genre Code Generation](img/mdb_movie_genretable.png) > This screenshot belongs to an older version of Sergen, just use parameters shown in new version Rebuild solution and run it. We'll get a new page like this: ![Genre Initial Page](img/mdb_genre_initial.png) As you see in screenshot, it is generated under a new section *MovieDB* instead of the one we renamed recently: *Movie Database*. This is because *Sergen* has no idea of what customizations we performed on our *Movie* page. So we need to movie it under *Movie Database* manually. Open *Modules/Movie/GenrePage.cs*, cut the navigation link shown below: ```cs [assembly:Serenity.Navigation.NavigationLink(int.MaxValue, "MovieDB/Genre", typeof(MovieTutorial.MovieDB.Pages.GenreController))] ```` And move it to *Modules/Common/Navigation/NavigationItems.cs*: ```cs //... [assembly: NavigationMenu(2000, "Movie Database", icon: "icon-film")] [assembly: NavigationLink(2100, "Movie Database/Movies", typeof(MovieDB.MovieController), icon: "icon-camcorder")] [assembly: NavigationLink(2200, "Movie Database/Genres", typeof(MovieDB.GenreController), icon: "icon-pin")] //... ``` ### Adding Several Genre Definitions Now let's add some sample genres. I'll do it through migration, to not to repeat it in another PC, but you might want to add them manually through Genre page. ```cs using FluentMigrator; using System; namespace MovieTutorial.Migrations.DefaultDB { [Migration(20160519181800)] public class DefaultDB_20160519_181800_SampleGenres : Migration { public override void Up() { Insert.IntoTable("Genre").InSchema("mov") .Row(new { Name = "Action" }) .Row(new { Name = "Drama" }) .Row(new { Name = "Comedy" }) .Row(new { Name = "Sci-fi" }) .Row(new { Name = "Fantasy" }) .Row(new { Name = "Documentary" }); } public override void Down() { } } } ``` ### Mapping GenreId Field in MovieRow As we did with *Kind* field before, *GenreId* field needs to be mapped in *MovieRow.cs*. ```cs namespace MovieTutorial.MovieDB.Entities { // ... public sealed class MovieRow : Row, IIdRow, INameRow { [DisplayName("Kind"), NotNull, DefaultValue(1)] public MovieKind? Kind { get { return (MovieKind?)Fields.Kind[this]; } set { Fields.Kind[this] = (Int32?)value; } } [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } [DisplayName("Genre"), Expression("g.Name")] public String GenreName { get { return Fields.GenreName[this]; } set { Fields.GenreName[this] = value; } } // ... public class RowFields : RowFieldsBase { // ... public readonly Int32Field Kind; public readonly Int32Field GenreId; public readonly StringField GenreName; public RowFields() : base("[mov].Movie") { LocalTextPrefix = "MovieDB.Movie"; } } } } ``` Here we mapped *GenreId* field and also declared that it has a foreign key relation to *GenreId* field in *[mov].Genre* table using *ForeignKey* attribute. > If we did generate code for Movie table after we added this Genre table, Sergen would understand this relation by checking foreign key definition at database level, and generate similar code for us. We also added another field, *GenreName* that is not actually a field in *Movie* table, but in *Genre* table. Serenity entities are more like SQL views. You can bring in fields from other tables with joins. By adding *LeftJoin("g")* attribute to MovieId property, we declared that whenever Genre table needs to be joined to, its alias will be *g*. So when Serenity needs to select from *Movies* table, it will produce an SQL query like this: ```sql SELECT t0.MovieId, t0.Kind, t0.GenreId, g.Name as GenreName FROM Movies t0 LEFT JOIN Genre g on t0.GenreId = g.GenreId ``` > This join will only be performed if a field from Genre table requested to be selected, e.g. its column is visible in a data grid. By adding *Expression("g.Name")* on top of *GenreName* property, we specified that this field has an SQL expression of *g.Name*, thus it is a view field originating from our *g* join. ### Adding Genre Selection To Movie Form Let's add GenreId field to our form in *MovieForm.cs*: ```cs namespace MovieTutorial.MovieDB.Forms { //... [FormScript("MovieDB.Movie")] [BasedOnRow(typeof(Entities.MovieRow))] public class MovieForm { //... public Int32 GenreId { get; set; } public MovieKind Kind { get; set; } } } ``` Now if we build and run application, we'll see that a Genre field is added to our form. The problem is, it accepts data entry as an integer. We want it to use a dropdown. It's clear that we need to change editor type for GenreId field. ### Declaring a Lookup Script for Genres To show an editor for *Genre* field, list of genres in our database should be available at client side. For enumeration values, it was simple, we just run T4 templates, and they copied enum declaration to script side. Here we can't do the same. Genre list is a database based dynamic list. Serenity has notion of *dynamic scripts* to make dynamic data available to script side in the form of runtime generated scripts. > Dynamic scripts are similar to web services, but their outputs are dynamic javascript files that can be cached on client side. > > The *dynamic* here corresponds to the data they contain, not their behavior. Unlike web services, dynamic scripts can't accept any parameters. And their data is shared among all users of your site. They are like singletons or static variables. > > You shouldn't try to write a dynamic script (e.g. lookup) that acts like a web service. To declare a dynamic lookup script for Genre table, open *GenreRow.cs* and modify it like below: ```cs namespace MovieTutorial.MovieDB.Entities { // ... [ConnectionKey("Default"), DisplayName("Genre"), InstanceName("Genre"), TwoLevelCached] [ReadPermission("Administration")] [ModifyPermission("Administration")] [JsonConverter(typeof(JsonRowConverter))] [LookupScript("MovieDB.Genre")] public sealed class GenreRow : Row, IIdRow, INameRow { // ... } ``` We just added line with *[LookupScript("MovieDB.Genre")]*. Rebuild your project, launch it, after logging in, open developer console by *F12*. Type *Q.getLookup('MovieDB.Genre')* and you will get something like this: ![Movies Genre Lookup from Console](img/mdb_genre_getlookup.png) Here *MovieDB.Genre* is the lookup key we assigned to this lookup script when declaring it with: > [LookupScript("MovieDB.Genre")] This step was just to show how to check if a lookup script is available client side. > Lookup key, *"MovieDB.Genre"* is case sensitive. Make sure you type exact same case everywhere. ### Using LookupEditor for Genre Field There are two places to set editor type for GenreId field. One is MovieForm.cs, other is MovieRow.cs. I usually prefer the latter, as it is the central place, but you may choose to set it on a form, if that editor type is specific to that form only. > Information defined on a form can't be reused. For example, grids use information in XYZColumn.cs / XYZRow.cs while dialogs use information in XYZForm.cs / XYZRow.cs. So it's usually better to define things in XYZRow.cs. Open MovieRow.cs and add *LookupEditor* attribute to *GenreId* property as shown below: ```cs [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor("MovieDB.Genre")] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } ``` After we build and launch our project, we'll now have a searchable dropdown (Select2.js) on our Genre field. ![Movie Form With Genre Editor](img/mdb_genre_dropdown.png) While defining [LookupEditor] we hardcoded the lookup key. It's also possible to reuse information on GenreRow: ```cs [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor(typeof(GenreRow))] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } ``` This is functionally equivalent. I'd prefer latter. Here, Serenity will locate the [LookupScript] attribute on GenreRow, and get lookup key information from there. If we had no [LookupScript] attribute on GenreRow, you'd get an error on application startup: ``` Server Error in '/' Application. 'MovieTutorial.MovieDB.Entities.GenreRow' type doesn't have a [LookupScript] attribute, so it can't be used with a LookupEditor! Parameter name: lookupType ``` > Forms are scanned at application startup, so there is no way to handle this error without fixing the issue. ### Display Genre in Movie Grid Currently, movie genre can be edited in the form but is not displayed in Movie grid. Edit MovieColumns.cs to show GenreName (not GenreId). ```cs namespace MovieTutorial.MovieDB.Columns { // ... public class MovieColumns { //... [Width(100)] public String GenreName { get; set; } [DisplayName("Runtime in Minutes"), Width(150), AlignRight] public Int32 Runtime { get; set; } } } ``` Now GenreName is shown in the grid. ![Movie Gid With Genre Column](img/mdb_genre_incolumn.png) ### Making It Possible To Define A New Genre Inplace While setting genre for our sample movies, we notice that *The Good, the Bad and the Ugly* is *Western* but there is no such genre in *Genre* dropdown yet (so I had to choose Drama). One option is to open Genres page, add it, and come back to movie form again. Not so pretty... Fortunately, Serenity has integrated inplace item definition ability for lookup editors. Open MovieRow.cs and modify *LookupEditor* attribute like this: ```cs [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor(typeof(GenreRow), InplaceAdd = true)] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } ``` Now we can define a new Genre by clicking star/pen icon next to genre field. ![Defining Genre Inplace](img/mdb_genre_inplace.png) > Here we also see that we can use a dialog from another page (GenreDialog) in the movies page. In Serenity applications, all client side objects (dialogs, grids, editors, formatters etc.) are self-contained reusable components (widgets) that are not bound to any page. It is also possible to start typing in genre editor, and it will provide you with an option to add a new genre. ![Defining Genre By Searching](img/movies_genre_search_add.png) ### How Did It Determine Which Dialog Type To Use You probably didn't notice this detail. Our lookup editor for genre selection, automatically opened a new *GenreDialog* when you wanted to add a new genre inplace. Here, our lookup editor made use of a convention. Because its lookup key is *MovieDB.Genre*, it searched for a dialog class with full names below: ``` MovieDB.GenreDialog MovieTutorial.MovieDB.GenreDialog ... ... ``` Luckily, we have a GenreDialog, which is defined in *Modules/Genre/GenreDialog.ts* and its full name is *MovieTutorial.MovieDB.GenreDialog*. ```ts namespace MovieTutorial.MovieDB { @Serenity.Decorators.registerClass() @Serenity.Decorators.responsive() export class GenreDialog extends Serenity.EntityDialog<GenreRow, any> { protected getFormKey() { return GenreForm.formKey; } protected getIdProperty() { return GenreRow.idProperty; } protected getLocalTextPrefix() { return GenreRow.localTextPrefix; } protected getNameProperty() { return GenreRow.nameProperty; } protected getService() { return GenreService.baseUrl; } protected form = new GenreForm(this.idPrefix); } } ``` If, lookup key for *GenreRow* and its dialog class didn't match, we would get an error in browser console, as soon as we click the inplace add button: ``` Uncaught MovieDB.GenreDialog dialog class is not found! ``` But this is not the case as they match. In such a case, either you'd have to use a compatible lookup key like "*ModuleName*.*RowType*", or you'd need to specify dialog type explicitly: ```cs [DisplayName("Genre"), ForeignKey("[mov].Genre", "GenreId"), LeftJoin("g")] [LookupEditor(typeof(GenreRow), InplaceAdd = true, DialogType = "MovieDB.Genre")] public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } ``` > You shouldn't specify *Dialog* suffix, nor the full namespace, e.g. *MovieTutorial.MovieDB.Genre*, as Serenity automatically searches for them. ### Adding Quick Filter for Genre To Grid As our list of movies becomes larger, we might need to filter movies based on values of some fields, besides the quick search functionality. Serenity has several filtering methods. One of them is Quick Filter, which we'll use on Genre field. Edit *Modules/MovieDB/Movie/MovieColumns.cs* to add a [QuickFilter] attribute on top of GenreName field: ```cs public class MovieColumns { //... public DateTime ReleaseDate { get; set; } [Width(100), QuickFilter] public String GenreName { get; set; } [DisplayName("Runtime in Minutes"), Width(150), AlignRight] public Int32 Runtime { get; set; } } ``` Build and navigate to Movies page. You'll a quick filtering dropdown for genre field is available: ![Genre Quick Filter](img/mdb_movie_genrequick.png) The field that is filtered is actually *GenreId* not *GenreName* that we attached this attribute to. Serenity is clever enough to understand this relation, and determined editor type to use by looking at attributes of *GenreId* property in *GenreRow.cs*. ### Re-runing T4 Templates As we added a new entity to our application, we should run T4 templates after building solution.
TypeScript
UTF-8
1,819
2.59375
3
[ "MIT" ]
permissive
import { createSlice } from '@reduxjs/toolkit' import { sideWindowPaths } from '../../domain/entities/sideWindow' import type { PayloadAction } from '@reduxjs/toolkit' export enum SideWindowStatus { CLOSED = 'closed', HIDDEN = 'hidden', VISIBLE = 'visible' } export interface SideWindowState { // TODO Replace with an enum once `sideWindowPaths` is converted to an enum. currentPath: string hasBeenRenderedOnce: boolean showConfirmCancelModal: boolean status: string } const INITIAL_STATE: SideWindowState = { currentPath: sideWindowPaths.MISSIONS, hasBeenRenderedOnce: false, showConfirmCancelModal: false, status: SideWindowStatus.CLOSED } const sideWindowReducerSlice = createSlice({ initialState: INITIAL_STATE, name: 'sideWindowReducer', reducers: { close(state) { state.status = SideWindowStatus.CLOSED }, /** * Open the side window and set its route path */ // TODO Replace with an enum once `sideWindowPaths` is converted to an enum. focusAndGoTo(state, action: PayloadAction<string>) { state.currentPath = action.payload state.status = SideWindowStatus.VISIBLE state.showConfirmCancelModal = false }, onChangeStatus(state, action: PayloadAction<SideWindowStatus>) { state.status = action.payload }, onConfirmCancelModal(state) { state.status = SideWindowStatus.VISIBLE state.showConfirmCancelModal = false }, setCurrentPath(state, action: PayloadAction<string>) { state.currentPath = action.payload }, setShowConfirmCancelModal(state, action: PayloadAction<boolean>) { state.showConfirmCancelModal = action.payload } } }) export const sideWindowActions = sideWindowReducerSlice.actions export const sideWindowReducer = sideWindowReducerSlice.reducer
C
UTF-8
2,290
3.34375
3
[]
no_license
int partition(int array[], int start, int end) { int pivot; int i = start - 1; int temp, j; pivot = (start + end) / 2; temp = array[pivot]; array[pivot] = array[end]; array[end] = temp; pivot = array[end]; for ( j = start; j <= end - 1; j++ ) { if ( array[j] <= pivot ) { i += 1; temp = array[i]; array[i] = array[j]; array[j] = temp; } } temp = array[i+1]; array[i+1] = array[j]; array[j] = temp; return i + 1; } int main() { int start = 0; int end = 5; int len = 6; int i; int array[] = { 2, 1, 0, 3, 4, 5 }; for ( i = 0; i < len; i++ ) { printf("%d ", array[i]); } printf("\n"); partition(array, start, end); for ( i = 0; i < len; i++ ) { printf("%d ", array[i]); } printf("\n"); return 0; } // В качестве опорного элемента брать среднее арифметическое между start и end с округлением вниз. // ==== Input ===== // 6 // 0 5 // 0 1 2 3 4 5 // ==== Result ==== // pivot = 5 // array = 0 1 2 3 4 5 // === Expected === // pivot = 2 // array = 0 1 2 3 4 5 // ==== Input ===== // 6 // 0 5 // -5 -4 -3 -2 -1 0 // ==== Result ==== // pivot = 5 // array = -5 -4 -3 -2 -1 0 // === Expected === // pivot = 2 // array = -5 -4 -3 -2 -1 0 // ==== Input ===== // 6 // 0 5 // 2 1 0 3 4 5 // ==== Result ==== // pivot = 5 // array = 2 1 0 3 4 5 // === Expected === // pivot = 0 // array = 0 1 5 3 4 2 // ==== Input ===== // 6 // 0 5 // 5 4 3 2 1 0 // ==== Result ==== // pivot = 0 // array = 0 4 3 2 1 5 // === Expected === // pivot = 3 // array = 0 2 1 3 5 4 // ==== Input ===== // 6 // 0 5 // 1 0 3 2 5 4 // ==== Result ==== // pivot = 4 // array = 1 0 3 2 4 5 // === Expected === // pivot = 3 // array = 1 0 2 3 5 4 // ==== Input ===== // 10 // 2 7 // 999 999 0 1 2 3 4 5 999 999 // ==== Result ==== // pivot = 7 // array = 999 999 0 1 2 3 4 5 999 999 // === Expected === // pivot = 4 // array = 999 999 0 1 2 3 4 5 999 999 // (test diffs truncated due to length...)
Markdown
UTF-8
1,522
2.921875
3
[ "MIT" ]
permissive
# Visitor Access The Visitor Access App was designed to help hospitals controlling the access of visitors to the patients. The application can be used by hospital guards or administrators. It contains a questionnaire with a few health-related questions. These questions determine whether visitors have certain conditions that might prevent them from visiting a patient (i.e. cough or temperature). Based on the answers, the hospital guard or administrator either grants the permission for a visit or declines it. The procedure of checking visitors includes the following steps: asking for the patient's name and floor and then asking the visitor to go through the questionnaire. If the visitor is allowed to visit, the system will display the exact time of the visit and the person responsible for granting access. # Tech Stack ### Frontend, Mobile application - [React](https://github.com/facebook/react) / [React Native](https://facebook.github.io/react-native/) - [React Navigation](https://github.com/react-community/react-navigation) - [Redux](https://redux.js.org/) - [Redux-Persist](https://github.com/rt2zz/redux-persist) ### Backend - [Express](https://github.com/expressjs/express) - [Sequelize](https://github.com/sequelize/sequelize) - [Swagger](https://github.com/swagger-api/swagger-node) # Architecture ![image](assets/architecture.png) # Use case diagram ![image](assets/usecases.png) # Contact information <contact@kandasoft.com> # License This code is distributed under the terms and conditions of the [MIT](LICENSE)
Python
UTF-8
6,457
2.59375
3
[]
no_license
# -*- coding: utf-8 -*- #OddballTaskSound.py #by J.Yagi 2019/06/03 #P300を誘発するためのオドホール課題実行用のプログラム,指定した間隔での刺激の提示と時間同期のためにLSLへの出力ができる #スペースを押すと実験開始,スペースを押すと途中で止められる,刺激の提示後スペースで終了 #LSLには,ターゲット刺激:[2],スタンダード刺激:[1],なにもない時:[0]を出力する import sys import random #import winsound as ws import pygame #サウンド用 from time import perf_counter as pc #高精度のタイマ from pylsl import StreamInfo, StreamOutlet #Python用のLSLライブラリ from PyQt5.QtWidgets import QApplication, QDesktopWidget, QLabel, QWidget #GUI用のライブラリ from PyQt5.QtGui import QPainter, QColor, QFont, QPen, QPixmap from PyQt5.QtCore import Qt, QTimer, QRectF, pyqtSignal #################################################################### ##この部分の値を適宜変更して使ってください. #################################################################### frameRate = 10 #タイマーのフレームレート(表示間隔) printsec = 2 #1刺激の表示時間 sumOfStimulus = 10 #刺激の総数 ratioOfTarget = 0.2 #刺激の総数に占めるターゲットの割合 targetSound = "stimulus/sound1.mp3" #ターゲット刺激のファイル名 standardSound = "stimulus/sound2.mp3" #スタンダード刺激のファイル名 #################################################################### class Stimulus: def __init__(self,stimulusOrder): self.on = 0 #LSLに出力する提示刺激の状態 self.stimulusOrder = stimulusOrder self.counterStimulus = 0 self.counterSound = -1 self.next_time = pc() + printsec def resetTimer(self): self.next_time = pc() + printsec def draw(self, ctime): painter = QPainter(window) pygame.mixer.init() if (((self.on == 1) or (self.on == 2)) and (self.counterSound != self.counterStimulus)): if self.stimulusOrder[self.counterStimulus] == 0: #ws.PlaySound( 'SystemHand', ws.SND_ALIAS ) music = pygame.mixer.music music.load(targetSound) music.play(1) elif self.stimulusOrder[self.counterStimulus] == 1: #ws.PlaySound( 'SystemExit', ws.SND_ALIAS ) music = pygame.mixer.music music.load(standardSound) music.play(1) self.counterSound = self.counterSound + 1 if ctime >= self.next_time: #刺激を一定時間ごとに切り替えるための処理 self.next_time += printsec if (self.on == 1) or (self.on == 2): #print(pc()) # コメントアウトを外せば,時間をコンソールに表示できる self.counterStimulus = self.counterStimulus + 1 self.on = 0 print(self.counterStimulus) #何刺激目か表示 else: if self.stimulusOrder[self.counterStimulus] == 0: self.on = 1 elif self.stimulusOrder[self.counterStimulus] == 1: self.on = 2 class MainWindow(QWidget): def __init__(self): super().__init__() print("### [Space] to Start and Pause/Unpause ###") self.base_time = pc() self.OrderStimulus() self.initStimulus() self.initUI() self.show() info = StreamInfo('Oddballstimulus', 'stimulation', 1, 100, 'float32', 'oddballstimu20190531') self.outlet = StreamOutlet(info) def initUI(self): self.setWindowTitle("Oddball-Task Stimulus") self.timer = QTimer(self) self.timer.timeout.connect(self.update) #updateでpaintEventメソッドを更新 #割合が決まった刺激をランダムに並び替えたリストを作るメソッド def OrderStimulus(self): self.stimulusOrder = list() #作成するリスト sumOfTarget = int(sumOfStimulus*ratioOfTarget) for i in range(sumOfTarget): self.stimulusOrder.append(0) for i in range(sumOfStimulus-sumOfTarget): self.stimulusOrder.append(1) random.shuffle(self.stimulusOrder) #要素をシャッフル # 刺激を定義するメソッド def initStimulus(self): self.stim = Stimulus(self.stimulusOrder) #キーが押される度に実行されるメソッド def keyPressEvent(self, e): if e.key() == Qt.Key_Space: if (self.stim.counterStimulus >= sumOfStimulus):#終了するときのキー操作 self.timer.start() sys.exit() elif self.timer.isActive(): #実行途中で止めるときのキー操作 self.timer.stop() else: #実行途中で再開するときのキー操作 self.stim.resetTimer() self.timer.start(frameRate) #frameRateは,いらないかも #updateされるたびに実行されるメソッド def paintEvent(self, QPaintEvent): curr_time = pc() if (self.stim.counterStimulus >= sumOfStimulus): #stim.~でclass Stimulus側(1つのインスタンス)の値を持ってこれる print("### [Space] to Exit from This App ###") self.timer.stop() else: self.stim.draw(curr_time) stimu = [int(self.stim.on)] self.outlet.push_sample(stimu) #print(stimu) #コメントアウトを外せば,LSLに出力する値を確認できる if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() #MainWindowのインスタンスを生成 window.resize(700, 700) #画面サイズを変更できる sys.exit(app.exec_())
Python
UTF-8
1,017
3.53125
4
[ "MIT" ]
permissive
from typing import List class Solution: # Time complexity: O(n) where n is the length of the seats array # Space complexity: O(1) # Note: It is crucial to take care of the edge cases of # a prefix/suffix of empty seats in the seats array def maxDistToClosest(self, seats: List[int]) -> int: left = -1 max_dist = 1 for right, el in enumerate(seats): if el == 0: if left == -1: max_dist = max(max_dist, right+1) else: if (right - left) % 2 == 0: # even max_dist = max(max_dist, (right-left) // 2) else: # odd max_dist = max(max_dist, (right-left+1) // 2) else: left = right # taking care of a trailing empy seat sub array that ends with an empy seat if seats[-1] == 0: max_dist = max(max_dist, len(seats) - left-1) return max_dist
Swift
UTF-8
815
3
3
[ "MIT" ]
permissive
// // UIBarButtonItem-Extension.swift // DouYuBroad // // Created by 贾卯 on 2017/8/9. // Copyright © 2017年 贾卯. All rights reserved. // import UIKit extension UIBarButtonItem{ //便利构造函数 1.以convenience开头 2.在构造函数中必须调用一个设计构造函数(self) convenience init(imageName: String,higiImageName: String = "",size: CGSize = CGSize.zero){ let btn = UIButton() btn.setImage(UIImage(named:imageName), for: .normal) if higiImageName != "" { btn.setImage(UIImage(named:higiImageName), for: .highlighted) } if size != CGSize.zero { btn.frame = CGRect(origin: CGPoint.zero, size: size) } else{ btn.sizeToFit() } self.init(customView:btn) } }