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
TypeScript
UTF-8
623
2.890625
3
[]
no_license
import ApiHandler from 'common/types/ApiHandler'; import Handler from 'common/types/Handler'; import ApiFailure from 'common/types/ApiFailure'; export type HandlerHook<T> = { onSuccess: (callback: Handler<T>) => void; onFailure: (callback: Handler<ApiFailure>) => void; }; export default function useHandlerHook<T>(): [ApiHandler<T>, HandlerHook<T>] { const handler: ApiHandler<T> = {}; const onSuccess = (callback: Handler<T>) => { handler.success = callback; }; const onFailure = (callback: Handler<ApiFailure>) => { handler.failure = callback; }; return [handler, { onSuccess, onFailure }]; }
JavaScript
UTF-8
1,123
4
4
[]
no_license
// Creeaza o functie polimorfica pentru calcularea suprafetelor. Daca primeste un parametru, sa calculeze suprafata unui patrat. Daca primeste doi, a unui dreptunghi. Daca primeste trei, sa calculeze suprafata totala a paralelipipedului. Foloseste structura switch. // Creeaza o functie numita calculateCircleArea() si afiseaza suprafata unor cercuri cu raza de 2, 20 si 16. function calculateSurface (L, l, h) { let argumentLength = arguments.length; switch (argumentLength) { case 1: return L * L; break; case 2: return L * l; break; case 3: return (L * h + l * h + L * l) * 2; break; default: console.log('Introdu dimensiunile pentru calcularea ariei.'); } }; console.log(`Aria unui patrat: ${calculateSurface(2)}.`); console.log(`Aria unui dreptunghi: ${calculateSurface(2, 6)}.`); console.log(`Aria unui paralelipiped: ${calculateSurface(2, 6, 4)}.`); console.log(calculateSurface()); function calculateCircleArea (r) { return (Math.PI * Math.pow(r, 2)).toFixed(2); } console.log(calculateCircleArea(2.20)); console.log(calculateCircleArea(16));
Shell
UTF-8
1,366
3.875
4
[ "MIT" ]
permissive
#!/bin/bash # # File: sanity.sh # Author: shaharf # # Created on Sep 6, 2018, 3:22:09 PM # function panic() { echo "PANIC: $*" > /dev/stderr exit 1 } function load_to_cache() { cat $f > /dev/null } function echodo() { echo "$*" eval "$*" } function dotest() { local msg=$1 shift 1 local cmd=$* echo "$msg" load_to_cache d=$t.$RANDOM time echodo "$cmd" cmp $f $m$d || panic "cmp $f to $m$d failed!!!" rm -f $m$d } LOG="-L pcp.log" f=$(mktemp) echo "# Generating 1GB random data file" dd bs=1M count=1024 if=/dev/urandom of=$f t=`basename $f` PCP=./pcp m="./" [ -r $f ] || panic "no src file '$f'" dotest "# cp local -> local copy " '(cp $f $d; sync)' dotest "# pcp local -> local" '($PCP $LOG -f $f $d; sync)' dotest "# pcp stream -> local" '(cat $f | $PCP $LOG -f - $d; sync)' dotest "# pcp local -> stream" '($PCP $LOG $f - | cat > $d; sync)' dotest "# pcp local -> local (SYNC)" '($PCP $LOG -s -f $f $d; sync)' dotest "# pcp stream -> local (SYNC)" '(cat $f | $PCP $LOG -s -f - $d; sync)' echo "# mkdir a new dir and 3 symlink" m1=dir1-$RANDOM m2=dir2-$RANDOM m3=dir3-$RANDOM real=dir-$RANDOM mkdir -p $real ln -s $real $m1 ln -s $real $m2 ln -s $real $m3 m="$real/" # for cmp dotest "# pcp local -> local (multipath)" '($PCP -f $f -- $m1/$d $m2/$d $m3/$d; sync)' echo "# rm data file $f" rm -f $f
C
WINDOWS-1252
2,580
2.828125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ll long long #define rep(i,l,r)for(ll i=(l);i<(r);i++) #define repp(i,l,r,k)for(ll i=(l);i<(r);i+=(k)) #define INF ((1LL<<62)-(1LL<<31)) #define max(p,q)((p)>(q)?(p):(q)) #define min(p,q)((p)<(q)?(p):(q)) #define bit(n,m)(((n)>>(m))&1) int upll(const void*a, const void*b){return*(ll*)a<*(ll*)b?-1:*(ll*)a>*(ll*)b?1:0;} int downll(const void*a, const void*b){return*(ll*)a<*(ll*)b?1:*(ll*)a>*(ll*)b?-1:0;} void sortup(ll*a,int n){qsort(a,n,sizeof(ll),upll);} void sortdown(ll*a,int n){qsort(a,n,sizeof(ll),downll);} ll pom(ll a,ll n,int m){ll x=1;for(a%=m;n;n/=2)n&1?x=x*a%m:0,a=a*a%m;return x;} //#define MOD 998244353 #define MOD 1000000007 #define invp(a,p)pom(a,p-2,p) ll deg[100010]; //????????????? typedef struct edge{ll s,g;}E; typedef struct graph{ int vcnt,ecnt; E e[200010];//????? int id[100010];//????? }G; int esort(const void*a,const void*b){ E*p=(E*)a,*q=(E*)b; if((*p).s<(*q).s)return -1; if((*p).s>(*q).s)return 1; if((*p).g<(*q).g)return -1; return 1; } G g; void readgraph(){ //????? ll n,m; scanf("%lld%lld",&n,&m); rep(i,0,m){ ll x,y; scanf("%lld%lld",&x,&y); x--,y--; g.e[2*i].s=x; g.e[2*i].g=y; g.e[2*i+1].s=y; g.e[2*i+1].g=x; deg[x]++; deg[y]++; } g.vcnt=n; g.ecnt=2*m; qsort(g.e,g.ecnt,sizeof(E),esort); int p=0; rep(i,0,g.vcnt){ while(p<g.ecnt&&g.e[p].s<i)p++; g.id[i]=p; } g.id[g.vcnt]=g.ecnt;//?? } int f(int v1,int v2){ int cnt=0;//???? rep(i,0,4){ int pre=v1; int t=g.e[g.id[v1]+i].g; while(t!=v1&&t!=v2){ if(g.e[g.id[t]].g!=pre){ pre=t; t=g.e[g.id[t]].g; }else{ pre=t; t=g.e[g.id[t]+1].g; } } if(t==v2)cnt++; } return cnt==2; } int main(){ readgraph(); int flag=0; rep(i,0,g.vcnt){ if(deg[i]%2){ puts("No"); return 0; } if(deg[i]==4)flag++; if(deg[i]>=6)flag=3; } if(flag>=3)puts("Yes"); else if(flag<=1)puts("No"); else { //4?????2?????? int v1=-1,v2=-1; rep(i,0,g.vcnt){ if(deg[i]==4){ if(v1==-1)v1=i; else{ v2=i; puts(f(v1,v2)?"Yes":"No"); return 0; } } } } } ./Main.c: In function readgraph: ./Main.c:41:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%lld%lld",&n,&m); ^ ./Main.c:44:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%lld%lld",&x,&y); ^
Python
UTF-8
399
2.609375
3
[]
no_license
import sys CBC_key = "140b41b22a29beb4061bda66b6747e14" CBC_Ciphertext_1 = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81" from Crypto.Cipher import AES from Crypto import Random IV = Random.new().read(16) obj2 = AES.new(CBC_key, AES.MODE_CBC, IV) deciphered = obj2.decrypt(CBC_Ciphertext_1) print(deciphered)
Markdown
UTF-8
10,500
2.921875
3
[ "MIT" ]
permissive
# A0127570H ###### /DeveloperGuide.md ``` md The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the command `delete /t 1`. <img src="images/SDforDeleteTask.png" width="800"> >Note how the `Model` simply raises a `ModelChangedEvent` when the model is changed, instead of asking the `Storage` to save the updates to the hard disk. The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time. <br> <img src="images/SDforDeleteTaskEventHandling.png" width="800"> > Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components. The sections below give more details of each component. ### UI component <img src="images/UiClassDiagram.png" width="800"><br> **API** : [`Ui.java`](../src/main/java/seedu/task/ui/Ui.java) The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `TaskListPanel`, `EventListPanel`, `CalendarView`, `StatusBarFooter` etc. All these, including the `MainWindow` inherits from the abstract `UiPart` class and they can be loaded using the `UiPartLoader`. The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder.<br> For example, the layout of the [`MainWindow`](../src/main/java/seedu/task/ui/MainWindow.java) is specified in [`MainWindow.fxml`](../src/main/resources/view/MainWindow.fxml) The `UI` component, * Executes user commands using the `Logic` component. * Binds itself to some data in the `Model` so that the UI can auto-update when data in the `Model` change. * Responds to events raises from various parts of the App and updates the UI accordingly. ``` ###### /DeveloperGuide.md ``` md ### Model component <img src="images/ModelClassDiagram.png" width="800"><br> **API** : [`Model.java`](../src/main/java/seedu/task/model/Model.java) The `Model`, * Stores a `UserPref` object that represents the user's preferences * Stores the `Dowat` data * Exposes a `UnmodifiableObservableList<ReadOnlyTask>` as well as `UnmodifiableObservableList<ReadOnlyEvent>` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. * Does not depend on any of the other three components. ### Storage component <img src="images/StorageClassDiagram.png" width="800"><br> **API** : [`Storage.java`](../src/main/java/seedu/task/storage/Storage.java) The `Storage` component, * Saves `UserPref` objects in json format and read it back. * Saves `Dowat` data in xml format and read it back. ``` ###### /DeveloperGuide.md ``` md #### Use case 1: Add task/event **MSS** 1. User requests to add task/event of specified parameters 2. `Dowat` adds task/event to system Use case ends. The use case of adding a task is elaborated by the SD as follows. <img src="images/addtask.png" width="700"><br> <img src="images/addtaskSD.png" width="700"><br> The SD for adding a task is similar to adding an event. **Extensions** 1a. The add task/event request has invalid format > 1a1. `Dowat` displays an error message Use case resumes at step 1 <br> ``` ###### /DeveloperGuide.md ``` md #### Use case 3: Edit task/event details **MSS**<br> 1. User requests to list tasks/events<br> 2. `Dowat` displays a list of tasks/events<br> 3. User requests to edit task/event in the list with new specified parameters with the index of task/event in the list<br> 4. `Dowat` edits existing task/event in database according to new specified parameters<br> Use case ends. The use case of editing an event is elaborated by the SD as follows. <img src="images/editevent.png" width="700"><br> <img src="images/editeventSD.png" width="700"><br> The SD for editing an event is similar to editing a task. **Extensions**<br> 3a. The given index is invalid > 3a1. `Dowat` displays an error message that task/event cannot be found Use case resumes at step 2 <br> ``` ###### /DeveloperGuide.md ``` md ------ ####Todo.txt **Summary:** > Todo.txt prides itself in its simplicity and ease of use for users. Currently, Todo.txt is available on mobile platforms as well as for desktop use. The lists are automatically synchronised across platforms whenever the list is updated. **Strength:** > 1. Available for use across platforms: mobile phones and desktop > 2. Automatic synchronisation of Todo.txt across multiple platforms via connection with Dropbox > 3. Simple text based UI with numerous functionalities > 4. Allows for association with Projects (Tag the task with ‘+’) > 5. Allows for adding of context; where and with what, (Tag the task with ‘@’) > 6. Archives completed tasks to Done.txt for future reference > 7. Suitable for programmers with intuitive UNIX commands such as ‘ls’ > 8. Able to list all tasks, tasks affiliated to a certain project, keyword in a task or a combination of the above > 9. Able to prioritise tasks and associate a different colour to the different priorities **Weakness:** > 1. Unable to constantly view a list of all tasks > 2. Not aesthetically pleasing for use on the computer, especially to users who are not familiar with programming > 3. Priorities are tagged to alphabetical characters and not priority levels (Ie. High, Medium, Low) > 4. Unable to set deadlines for task to be completed *** ####Fantastical2 **Summary:** > Fantastical 2 is developed by Flexibits with the aim to create Apps that remove frustration and to make the lives of users better. Fantastical 2 is a powerful, yet simple to use, app encompassing multiple features for the Apple iPhone and Mac platforms. It combines and synchronises Apple Reminders, To-Do-List and Calendar across multiple devices.. **Strength:** > 1. Can be synchronised across multiple device platforms > 2. Voice recognition software for verbal input of tasks > 3. Able to set deadlines for task > 4. Clear colour coding for different categories of tasks and events as set by user > 5. Able to set reminder for tasks and events > 6. Good integration between tasks, events and calendar > 7. Display of tasks, events and calendar is available in the UI **Weakness:** > 1. Cannot easily key in the duration of an event, user will have to state start and end time > 2. Requires user to use Apple products for mobile phones and laptop as the app is limited to the Apple community ``` ###### /UserGuide.md ``` md #### Adding a task Adds a task to Dowat<br> Format: `add TASK_NAME [/desc DESCRIPTION] [/by DEADLINE_DATETIME]` <br> > Words in `UPPER_CASE` are the parameters, parameters will follow behind their corresponding keyword. > With the exception of `TASK_NAME`, all other parameters are optional. The order of parameters are not fixed. > `DEADLINE_DATETIME` can be entered in any natural language format. > For date, entering words like today, tomorrow and day after are recognised. > Dates entered in numeric form must be in the format of MM-DD-YYYY. > Only valid dates are recognised correctly. > For time, entering 7pm, 1900 or 19.00 are recognised. > If no time is entered, it is assumed to be due at 23:59 hours. Examples: * `add CS2103 V0.4 /by 30 Dec` <br> Adds a task "CS2103 V0.4" with deadline "23:59 30 December 2016" * `add heat transfer quiz /desc IVLE /by tomorrow 8pm` <br> <img src="images/addtask.gif" width="700"> #### Adding an event Similar to adding a task, you can also add an event to Dowat<br> Format: `add EVENT_NAME /from START_DATETIME [/to END_DATETIME] [/desc DESCRIPTION]` <br> > With the exception of `EVENT_NAME` and `START_DATETIME`, all other parameters are optional. The order of parameters are not fixed. > `START_DATETIME` and `END_DATETIME` can be entered in natural language. > For date, entering words like today, tomorrow and day after are recognised. > Dates entered in numeric form must be in the format of MM-DD-YYYY. > Only valid dates are recognised correctly. > For time, entering 7pm, 1900 or 19.00 are recognised. > If no start time is entered, it is assumed to start at 00:00 hours. > If `END_DATETIME` is not provided, the start and end dates will be the same, the default timing will be set 1 hour apart. Examples: * `add CS2103 Exam @ MPSH3 /from 30 December 4pm /to 6pm` <br> Adds an event "CS2103 Exam @ MPSH3" with duration from "16:00 30 December 2016" to "18:00 30 December 2016" * `add Doctor Strange /desc @ The Cathay /from friday 7pm /to friday 9pm` <br> <img src="images/addevent.gif" width="700"> ``` ###### /UserGuide.md ``` md #### Editing a task Edits an existing task in Dowat<br> Format: `edit /t INDEX [/name NEW_NAME] [/desc NEW_DESCRIPTION] [/by NEW_DEADLINE]` <br> > Edits the task at the specified `INDEX`. The index refers to the index number shown in the most recent listing of tasks. > Edits at least 1 field of the task. This includes name and/or description and/or deadline. > The order of the fields are flexible. > `NEW_DEADLINE` can be entered in natural language. > Edited tasks are automatically marked as uncompleted. Examples: * `edit /t 1 /desc CS2103 Project /by 12-30-16`<br> Edits the description of the 1st task to “CS2103 Project” and the deadline to "30 December 2016" * `edit /t 1 /name Heat Transfer Test /by today 6pm /desc @ E6 LT3`<br> <img src="images/edittask.gif" width="700"> #### Editing an event Edits an existing event in Dowat<br> Format: `edit /e INDEX [/name NEW_NAME] [/desc NEW_DESCRIPTION] [/from NEW_START_DATETIME] [/to NEW_END_DATETIME]` > Edits the event at the specified `INDEX`. The index refers to the index number shown in the most recent listing of events. > Edits any number of fields of the event. This includes name and/or description and/or start time and/or end time. > The order of the fields are flexible. > `NEW_START_DATETIME` and `NEW_END_DATETIME` can be entered in natural language. Examples: * `edit /e 1 /desc CS2103 Workshop /from 10-03-16 0000 /to 10-05-16 2359` Edits the description of the 1st event to “CS2103 Workshop” and the duration to the period of 0000 hours, 3-10-16 to 2359 hours, 5-10-16 * `edit /e 1 /desc @ Serangoon Nex` <img src="images/editevent.gif" width="700"> ```
Python
UTF-8
609
2.890625
3
[]
no_license
def found(string,s,n): ct = 0 for i in range(len(string)): if string[i] == s: ct += 1 if ct == n: return i return -1 def ReBWT(Lst): length = len(Lst) result = [' ' for x in range(length)] Fst = ''.join(sorted([k for k in Lst])) pos = 0 for num in range(length-1,-1,-1): result[num] = Lst[pos] pos = found(Fst,Lst[pos],Lst[:pos+1].count(Lst[pos])) return ''.join(result[1:])+'$' with open('rosalind_ba9j.txt') as f: string = '' for line in f: string += line.rstrip() print(ReBWT(string))
C++
UTF-8
8,106
2.671875
3
[]
no_license
/* * Includes */ #include <jnif.hpp> #include <iostream> #include <fstream> using namespace std; using namespace jnif; using namespace jnif::model; using jnif::JnifError; static void testException() { try { throw Exception("arg1: ", 1, ", arg2: ", "2", ", arg3: ", 3.4); } catch (const Exception& ex) { assertEquals(ex.message, string("arg1: 1, arg2: 2, arg3: 3.4")); } } static void testConstPool() { ConstPool cp; auto si = cp.addString("String Test"); auto ii = cp.addInteger(1); auto fi = cp.addFloat(2.1); auto li = cp.addLong(3); auto di = cp.addDouble(4.2); assertEquals(cp.size(), 9u); assertEquals(string("String Test"), string(cp.getString(si))); assertEquals(cp.getInteger(ii), 1); assertEquals(cp.getFloat(fi), 2.1f); assertEquals(cp.getLong(li), 3l); assertEquals(cp.getDouble(di), 4.2); } class UnitTestClassPath : public jnif::model::IClassPath { public: string getCommonSuperClass(const string&, const string&) { return "java/lang/Object"; } }; static void testEmptyModel() { ClassFile cf("jnif/EmptyModel"); assertEquals(string("java/lang/Object"), string(cf.getSuperClassName())); assertEquals(Version(51, 0), cf.version); } static void testPrinterModel() { ClassFile emptyCf("jnif/test/generated/Class1", ClassFile::OBJECT); ofstream os; os << emptyCf; ClassFile cf2("jnif/test/generated/Class2", "jnif/test/generated/Class"); cf2.addMethod("main", "([Ljava/lang/String;)V", Method::STATIC | Method::PUBLIC); ofstream os2; os2 << cf2; } static void testJoinFrameObjectAndEmpty() { UnitTestClassPath cp; const Type& s = TypeFactory::objectType("TypeS"); const Type& t = TypeFactory::objectType("TypeT"); Frame lhs; lhs.setVar2(0, s, nullptr); lhs.setVar2(1, t, nullptr); Frame rhs; rhs.setVar2(0, s, nullptr); lhs.join(rhs, &cp); Frame res; res.lva.resize(2, std::make_pair(TypeFactory::topType(), std::set<Inst*>())); res.setVar2(0, s, nullptr); JnifError::assertEquals(res, lhs); } static void testJoinFrameException() { UnitTestClassPath cp; const Type& classType = TypeFactory::objectType("testunit/Class"); const Type& exType = TypeFactory::objectType("java/lang/Exception"); Frame lhs; lhs.setVar2(0, TypeFactory::nullType(), nullptr); lhs.setVar2(1, exType, nullptr); Frame rhs; rhs.setVar2(0, classType, nullptr); lhs.join(rhs, &cp); Frame res; res.lva.resize(2, std::make_pair(TypeFactory::topType(), std::set<Inst*>())); res.setVar2(0, classType, nullptr); JnifError::assertEquals(res, lhs); } static void testJoinFrame() { UnitTestClassPath cp; ClassFile cf("testunit/Class", ClassFile::OBJECT); Method& m = cf.addMethod("method", "()Ltestunit/Class;", Method::PUBLIC | Method::STATIC); ConstPool::Index cidx = cf.addUtf8("Code"); CodeAttr* code = new CodeAttr(cidx, &cf); m.attrs.add(code); InstList& instList = m.codeAttr()->instList; ConstPool::Index idx = cf.addClass("testunit/Class"); ConstPool::Index exidx = cf.addClass("java/lang/Exception"); ConstPool::Index initidx = cf.addMethodRef(idx, "<init>", "()V"); LabelInst* l = instList.createLabel(); LabelInst* tryLabel = instList.createLabel(); tryLabel->isTryStart = true; LabelInst* endLabel = instList.createLabel(); // endLabel->isTryEnd = true; LabelInst* handlerLabel = instList.createLabel(); handlerLabel->isCatchHandler = true; instList.addLabel(tryLabel); instList.addType(Opcode::NEW, idx); instList.addZero(Opcode::dup); instList.addInvoke(Opcode::invokespecial, initidx); instList.addZero(Opcode::astore_0); instList.addLabel(endLabel); instList.addJump(Opcode::GOTO, l); instList.addLabel(handlerLabel); instList.addZero(Opcode::astore_1); instList.addZero(Opcode::aconst_null); instList.addZero(Opcode::astore_0); instList.addLabel(l); instList.addZero(Opcode::aload_0); instList.addZero(Opcode::areturn); code->exceptions.push_back({tryLabel, endLabel, handlerLabel, exidx}); cout << cf; cf.computeFrames(&cp); } static void testJoinStack() { ClassFile cf("testunit/Class", ClassFile::OBJECT); ConstPool::Index emptyString = cf.addString(""); Method& m = cf.addMethod("method", "()Ltestunit/Class;", Method::PUBLIC); auto cidx = cf.addUtf8("Code"); CodeAttr* code = new CodeAttr(cidx, &cf); m.attrs.add(code); InstList& instList = m.codeAttr()->instList; auto idx = cf.addClass("testunit/Class"); auto exidx = cf.addClass("java/lang/Throwable"); auto useidx = cf.addMethodRef(idx, "use", "(Z)V"); auto loopHeader = instList.createLabel(); auto loopExit = instList.createLabel(); auto ifTrue = instList.createLabel(); auto ifEnd = instList.createLabel(); auto afterTry = instList.createLabel(); auto tryStart = instList.createLabel(); tryStart->isTryStart = true; auto tryEnd = instList.createLabel(); // tryEnd->isTryEnd = true; auto catchHandler = instList.createLabel(); catchHandler->isCatchHandler = true; // 0: ( 1) aconst_null // 1: ( 76) astore_1 // label loopHeader, B: Yes, TS: No, TE: No, C: No // 2: ( 43) aload_1 // 3: (199) ifnonnull label: loopExit // label tryStart, B: No, TS: Yes, TE: No, C: No // 6: ( 42) aload_0 // 7: ( 43) aload_1 // 8: (198) ifnull label: ifTrue // 11: ( 4) iconst_1 // 12: (167) goto label: ifEnd // label ifTrue, B: Yes, TS: No, TE: No, C: No // 15: ( 3) iconst_0 // label ifEnd, B: Yes, TS: No, TE: No, C: No // 16: (182) invokevirtual #2 frheapagent/UtilMain.use: (Z)V // label tryEnd, B: No, TS: No, TE: Yes, C: No // 19: (167) goto label: afterTry // label catchHandler, B: No, TS: No, TE: No, C: Yes // 22: ( 77) astore_2 // label afterTry, B: Yes, TS: No, TE: No, C: No // 23: ( 18) ldc #4 // 25: ( 76) astore_1 // 26: (167) goto label: loopHeader // label loopExit, B: Yes, TS: No, TE: No, C: No // 29: (177) return instList.addZero(Opcode::aconst_null); instList.addZero(Opcode::astore_1); instList.addLabel(loopHeader); instList.addZero(Opcode::aload_1); instList.addJump(Opcode::ifnonnull, loopExit); instList.addLabel(tryStart); instList.addZero(Opcode::aload_0); instList.addZero(Opcode::aload_1); instList.addJump(Opcode::ifnull, ifTrue); instList.addZero(Opcode::iconst_1); instList.addJump(Opcode::GOTO, ifEnd); instList.addLabel(ifTrue); instList.addZero(Opcode::iconst_0); instList.addLabel(ifEnd); instList.addInvoke(Opcode::invokevirtual, useidx); instList.addLabel(tryEnd); instList.addJump(Opcode::GOTO, afterTry); instList.addLabel(catchHandler); instList.addZero(Opcode::astore_2); instList.addLabel(afterTry); instList.addLdc(Opcode::ldc, emptyString); instList.addZero(Opcode::astore_1); instList.addJump(Opcode::GOTO, loopHeader); instList.addLabel(loopExit); instList.addZero(Opcode::RETURN); code->exceptions.push_back({tryStart, tryEnd, catchHandler, exidx}); UnitTestClassPath cp; try { cf.computeFrames(&cp); } catch (const Exception& ex) { //ofstream os("build/stack.dot"); //cf.dot(os); throw ex; } } typedef void (TestFunc)(); static void run(TestFunc* testFunc, const string& testName) { cerr << "Running test " << testName << " "; try { testFunc(); } catch (const Exception& ex) { cerr << ex << endl; exit(1); } cerr << " [OK]" << endl; } #define RUN(testName) run(&testName, #testName) int main(int, const char* []) { RUN(testException); RUN(testEmptyModel); RUN(testPrinterModel); RUN(testJoinFrameObjectAndEmpty); RUN(testJoinFrameException); RUN(testJoinFrame); RUN(testJoinStack); RUN(testConstPool); return 0; }
Markdown
UTF-8
7,042
3.078125
3
[]
no_license
二九 “老实说,我不明白为什么要——猜。不知道反而好多了。我们全都可以像往常一样继续生活下去。” “噢不,我们不能,”菲利普说。“这正是你错的地方,亲爱的。已经开始腐败了。” “你是什么意思?” “呃,拿海斯特和她的年轻人来说——热切、年轻的唐纳德医生。好青年,认真,却在担心。他并不真的认为是她干的——但是他并不真的确定不是她于的!因此他焦虑地看着她,在他认为她不注意的时候。但是她是注意到了,因此就这么一回事!也许确实是她干的——你比我清楚——但是如果不是她干的,她又能拿她的年轻人怎么办?不停的说: “请相信我,不是我?不过反正她是会这样说没错。” “真是的,菲利普,我认为你是在想象。” “你却完全无法想象,波丽。再来说到可怜的老里奥。跟关妲的结婚钟声正在逐渐消失到远方去,她非常心烦,难道你没注意到?” “我真的不明白父亲在他那种年纪还想再结婚干什么。” “他倒是明白!但是他也明白任何他跟关妲相恋的暗示都足以构成他们俩一级谋杀的动机罪名。难堪!” “认为父亲谋杀了母亲真是捕风捉影!”玛丽说。“这种事不会发生。” “会,会发生。看看报纸。” “我们这种人不会。” “谋杀可是不势利眼的,波丽。再来是麦可,是有什么在腐蚀他没错。他是个怪异,充满怨气的少年。蒂娜看起来好像没问题,不担心,不受影响。但是她有一张道地的扑克脸。再来是可怜的老克斯蒂——” 玛丽脸上微微出现生气。 “这可能是个解答!” “克斯蒂?” “是的,毕竟,她是外国人。而且我相信她过去一两年患了非常严重的头痛症……看来她比我们任何一个有可能多了。” “可怜的家伙,”菲利普说,“难道你不明白这正是她在对她自己说?说我们全都同意是她干的?为了方便。因为她不是家人之一。难道你看不出她今天晚上担心死了?她的处境虽和海斯特一样,她能说什么或做什么?对我们大家说‘我真的没有杀死我的朋友和雇主’?这样说有什么分量?或许对她来说,处境比任何其他人更糟……因为她是孤单单的一个人。她会在心里仔细想过她曾经说过的每一句话,每一个她投给你母亲的生气眼光——想着这一切都会被记起来而对她不利。无助地证明她的无辜。” “我真希望你冷静下来,菲。毕竟,我们又能怎么样?” “只有尽力查明真相。” “可是那怎么可能?” “可能有一些方法,我倒想试试看。” 玛丽显得不安。 “什么样的方法?” “噢,说一些话——观察别人的反应——是可以想出一些话来”——他停顿下来,他的心思运转着——“一些对有罪的人具有意义的话,但是对无辜的人来说无意义……”他再度沉默下来,忙着在心里想主意。他抬起头来说:“难道你不想帮助无辜的人,玛丽?” “不。”爆炸性的一声。她过来跪在他的轮椅旁。“我不想要你扯进这一切里,菲。不要开始说一些话设下陷阱。不要去管它。噢,看在老天的份上,不要去管它!” 菲利普双盾上扬。 “好——吧。”他说。他一手搁在平滑的金头发上。 麦可·阿吉尔躺着睡不着,凝视着一片漆黑。 他的心思不停地绕着过去打转,就像关在笼子里的松鼠一般,为什么他无法把过去的一切忘掉?为什么他得一辈子拖着过去的包袱?那一切到底有什么重要?为什么他得记得这么清楚、伦敦贫民区那个闷不通风,讨厌的房间,还有他“我们的麦可”随意、令人亢奋的气氛!街道上的欢乐!团结起来对抗其他的男孩!他母亲亮丽的金发(廉价的洗发精,他成年以后猜想),她痛打他一顿时的突发性怒气,(杜松子酒,当然!)还有她心情好时的狂欢。有鱼有薯条的可爱晚餐,而且她会唱歌——多情的民谣。有时候他们会去看电影。总是有一些“叔叔”,当然——他总是得那样称呼他们。他自己的爸爸在他能记得他之前就出走了……但是他母亲受不了当天过夜的“叔叔”碰他一下。“不要动我们麦可,”她会说。 然后是战争的兴奋。期待希特勒的轰炸机——不见炸弹的警报声。呼啸的迫击炮声。躲到地下铁道去过夜。好玩!整条街的人都在那里,带着三明治和瓶瓶罐罐的汽水饮料。整个晚上火车忙着进进出出。那才是生活,那!身处各种事情当中! 然后他来到这里——来到乡下。一个像死了一般什么鸟事都没发生过的地方! “你会回来的,亲爱的,一切都过去的时候。”他母亲说过,但是说得像不是真的一样轻率。她好像不关心他离开。而且为什么她不来?多的是街上的小孩跟他们妈妈一起撤退。但是他母亲不想走。她要到北方(跟当时的“叔叔”一起,哈利“叔叔”)的军火厂去工作。 他应该当时就知道了,尽管她深情的道别。她并不真的关心……杜松子酒,他想,才是她关心的一切,杜松子酒和那些“叔叔”……而他来到了这里,被“俘虏”来了,吃着没有味道、不熟悉的东西;不可思议的,六点就上床,在吃下可笑的牛奶和饼干晚餐之后,躺着睡不着,哭,头埋在毯子里,哭着要妈妈和回家。 是那个女人!她得到了他不放他走。说一大堆娘娘腔的话。老是要他玩一些可笑的游戏。对他有所要求。要求他决心不给她的东西。“没关系,他会等,他会耐心的等!然后有一天——极为美好的一天,他会回家,回到街道上去,那些小男孩,壮观的红色巴士还有地下铁,鱼和薯条,来往的汽车和附近地区的小猫——他的心思渴望地绕着这一切欢乐打转。他必须等待,战争不可能继续下去。他被困在这个可笑的地方,而炸弹却落遍了伦敦,而且半个伦敦都着了火!一定是很壮观的火景,而有人被炸死,房屋被炸毁了。 他在心中看见这一切壮观的鲜明彩色画面。 没关系,战争结束他就可以回家去找妈妈了。她会惊讶的看见他长大了。 麦可·阿吉尔在黑暗中长长的嘘了一口气。 战争结束了。他们打垮了希特勒和墨索……有些孩子回家去了。快了……而“她”从伦敦回来,说他将留在阳岬做她的孩子…… 他说:“我妈妈呢?是不是被炸弹炸到了?”
JavaScript
UTF-8
1,749
3.03125
3
[]
no_license
import React from 'react'; import ReactDOM from 'react-dom'; class NewMessage extends React.Component { constructor(props) { super(props); this.state = { alias: '', complaint: '', age: '', entries: [] }; this.aliasChange = this.aliasChange.bind(this); this.ageChange = this.ageChange.bind(this); this.complaintChange = this.complaintChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } aliasChange(event) { this.setState({alias: event.target.value}); console.log(this.state.alias +' --alias') } complaintChange(event) { this.setState({complaint: event.target.value}); } ageChange(event) { this.setState({age: event.target.value}); } handleSubmit(event) { // alert('Complaint received, have a nice day!'); entries.push([this.state.alias,this.state.complaint,this.state.age]) console.log(this.state.alias +this.state.complaint +this.state.age + "submitted") } render() { return ( <div className="center"> <form> <ul> <label> Name: <input name="alias" type= "text" value={this.state.alias} onChange={this.aliasChange} /> </label> <label> Age: <input name="age" type= "number" value={this.state.age} onChange={this.ageChange} /> </label> <label> Complaint: <textarea value={this.state.complaint} onChange={this.complaintChange} /> </label> <input type="submit" value="Submit" /> </ul> </form> </div> ); } } // submit button needs to send data to the server // save data to the database. //how does mongo save info //async request export default NewMessage;
JavaScript
UTF-8
1,804
2.671875
3
[ "MIT" ]
permissive
/*globals test, expect*/ import { renderHook, act } from "@testing-library/react-hooks" import useFormist from "../src/useFormist" test("no change", async () => { const initialValues = { firstName: "John", age: 23 } let submittedValues = {} const { result } = renderHook(() => useFormist(initialValues, { onSubmit: values => (submittedValues = values), }), ) await act(() => result.current.submit()) expect(submittedValues).toStrictEqual(initialValues) }) test("one change", async () => { const initialValues = { firstName: "John", age: 23 } let submittedValues = {} const { result } = renderHook(() => useFormist(initialValues, { onSubmit: values => (submittedValues = values), }), ) await act(async () => { await result.current.change("firstName", "Fred") await result.current.submit() }) expect(submittedValues).toStrictEqual({ firstName: "Fred", age: 23 }) }) test("form submit", async () => { const initialValues = { firstName: "John", age: 23 } let submitted = false const { result } = renderHook(() => useFormist(initialValues, { onSubmit: () => (submitted = true), }), ) await act(() => result.current.getFormProps().onSubmit(event())) return expect(submitted).toBe(true) }) test("submit button click", async () => { const initialValues = { firstName: "John", age: 23 } let submitted = false const { result } = renderHook(() => useFormist(initialValues, { onSubmit: () => (submitted = true), }), ) await act(() => result.current.getSubmitButtonProps().onClick(event())) return expect(submitted).toBe(true) }) const event = () => ({ preventDefault() {} })
C
UTF-8
656
3.671875
4
[]
no_license
#include <memory.h> #include <stdlib.h> /** * Note: The returned array must be malloced, assume caller calls free(). */ int* decrypt(int *code, int codeSize, int k, int *returnSize) { int *res = (int*)malloc(sizeof(int) * codeSize); memset(res, 0, sizeof(int) * codeSize); *returnSize = codeSize; int beg = 1, end = k, sum = 0; if (k < 0) { beg = codeSize + k; end = codeSize - 1; } for (int i = beg; i <= end; i++) sum += code[i]; for (int i = 0; i < codeSize; i++) { res[i] = sum; sum -= code[(beg++) % codeSize]; sum += code[(++end) % codeSize]; } return res; }
C++
UTF-8
651
2.984375
3
[]
no_license
#include<iostream> #include<stack> #include<string> using namespace std; int main() { int T, i; string br; stack<char> st; cin >> T; while (T--) { cin >> br; i = 0; while(i<br.length()) { if (br[i] == '(') { st.push(br[i]); } else if (br[i] == ')') { if (st.size() != 0 && st.top() == '(') { st.pop(); } else { while (!st.empty()) { st.pop(); } cout << "NO\n"; break; } } i++; if (i == br.length() && !st.empty()) { cout << "NO\n"; while (!st.empty()) { st.pop(); } } else if(i==br.length() && st.empty()) cout << "YES\n"; } } return 0; }
Java
UTF-8
3,695
2.78125
3
[]
no_license
package threecats.zhang.domoment.Helper; import android.widget.DatePicker; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.Calendar; import java.util.Date; /** * 由 zhang 于 2017/8/15 创建 */ public class DateTimeHelper { public DateTimeHelper(){ } public static void setCalendarDate(Calendar date, int year, int month, int day){ date.set(Calendar.YEAR, year); date.set(Calendar.MONTH, month); date.set(Calendar.DAY_OF_MONTH, day); } public static Calendar getTomorrow(){ Calendar day = Calendar.getInstance(); day.add(Calendar.DATE, 1); return day; } public static Calendar getAfterTomorrow(){ Calendar day = Calendar.getInstance(); day.add(Calendar.DATE, 2); return day; } public static boolean isCurrentYear(Date date){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR); } public static boolean isCurrentYear(Calendar calendar){ return calendar.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR); } public static boolean isCurrentMonth(Date date){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); boolean currentMonth; if (isCurrentYear(date)) { currentMonth = calendar.get(Calendar.MONTH) == Calendar.getInstance().get(Calendar.MONTH); } else { currentMonth = false; } return currentMonth; } public static void setCalendarFromDatePicker(Calendar date, DatePicker datePicker){ date.set(Calendar.YEAR, datePicker.getYear()); date.set(Calendar.MONTH, datePicker.getMonth()); date.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth()); } public static boolean sameYearMonth(Calendar c1, Calendar c2){ return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH); } public static boolean sameYMD(Calendar c1, Calendar c2){ return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH); } public static String getYearFormatStr(Date date){ return isCurrentYear(date) ? "" : "yyyy "; } public static String getYearFormatStr(Calendar date){ return isCurrentYear(date) ? "" : "yyyy "; } public static String getDateWeekStr(Calendar date){ SimpleDateFormat dateFormat = new SimpleDateFormat("MMMdd E"); return dateFormat.format(date.getTime()); } public static Calendar buildTimePoint(int shiftDays){ Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE,shiftDays); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); return calendar; } public LocalDate makeTimePoint(long days){ LocalDate timePoint = LocalDate.now(); timePoint.plusDays(days); return timePoint; } public static int getDayOfWeek(Calendar day){ int Site = day.get(Calendar.DAY_OF_WEEK); if (Site == 1) Site = 8; return --Site; } public static int getDayOfWeek(LocalDate day){ //DayOfWeek dayOfWeek = DayOfWeek.MONDAY; return day.getDayOfWeek().ordinal(); } public static boolean isCurrentDateChanged(){ return ! Calendar.getInstance().before(buildTimePoint(1)); } }
Java
UTF-8
1,299
3.40625
3
[]
no_license
package dataStructures.set; import java.util.LinkedList; import java.util.Iterator; public class LinkedListSet <T> implements Set <T>{ private LinkedList<T> elements; public LinkedListSet() { elements = new LinkedList<>(); // TODO Auto-generated constructor stub } @Override public Iterator<T> iterator() { // TODO Auto-generated method stub return elements.iterator(); } @Override public boolean isElem(T el) { // TODO Auto-generated method stub return elements.contains(el); } @Override public void insert(T el) { if(!isElem(el))elements.add(el); // TODO Auto-generated method stub } @Override public void delete(T el) { elements.remove(el); // TODO Auto-generated method stub } @Override public boolean isEmpty() { // TODO Auto-generated method stub return elements.isEmpty(); } @Override public int size() { // TODO Auto-generated method stub return elements.size(); } public String toString() { String className = getClass().getName().substring(getClass().getPackage().getName().length()+1); String text = className+"("; Iterator<T> it = elements.iterator(); while(it.hasNext()) { text += it.next() + (it.hasNext() ? "," : ""); } return text + ")"; } }
Java
UTF-8
615
2.390625
2
[]
no_license
package com.example.root.facialdetection.Model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; @JsonIgnoreProperties(ignoreUnknown = true) abstract class BaseModel { public Map<String, Object> toDictionary() { ObjectMapper mapper = new ObjectMapper(); return mapper.convertValue(this, Map.class); } public static <T extends BaseModel> T fromDictionary(Object dictionary, Class<T> t){ ObjectMapper mapper = new ObjectMapper(); return mapper.convertValue(dictionary, t); } }
C
UTF-8
488
2.859375
3
[]
no_license
/************************************************************************* > File Name: hzol101.c > Author: bianyilin > Mail: 732406982@qq.com > Created Time: 2019年06月12日 星期三 19时21分53秒 ************************************************************************/ #include <stdio.h> int main(){ int n,q,b,s,g,sum; scanf("%d",&n); q = n / 1000; b = n % 1000 / 100; s = n % 100 / 10; g = n % 10; sum = q+b+s+g; printf("%d\n",sum); return 0; }
Java
UTF-8
3,820
2.125
2
[]
no_license
package com.jiaoke.oa.service; import com.jiake.utils.DateUtil; import com.jiaoke.oa.bean.OaActEngage; import com.jiaoke.oa.bean.OaCollaboration; import com.jiaoke.oa.dao.OaActEngageMapper; import com.jiaoke.oa.dao.OaCollaborationMapper; import com.jiaoke.oa.dao.UserInfoMapper; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; /** * 职称(技术等级)评聘申请表 * * @author lihui * @version 1.0 * @date 2019-6-5 2:02 */ @Service public class OaActEngageServiceImpl implements OaActEngageService { @Resource private OaActEngageMapper oaActEngageMapper; @Resource private OaCollaborationMapper oaCollaborationMapper; @Resource private UserInfoMapper userInfoMapper; @Override public int insert(OaActEngage oaActEngage, Integer userId, String randomId, Integer state) { oaActEngage.setId(randomId); oaActEngage.setCreateTime(new Date()); oaActEngage.setPromoter(userId); oaActEngage.setUrl("engage"); oaActEngage.setState(0); if (oaActEngageMapper.insertSelective(oaActEngage) < 0) { return -1; } else { OaCollaboration oaCollaboration = new OaCollaboration(); oaCollaboration.setCorrelationId(randomId); oaCollaboration.setPromoter(userId); oaCollaboration.setTitle(oaActEngage.getTitle()); oaCollaboration.setUrl("engage"); oaCollaboration.setTable("oa_act_engage"); oaCollaboration.setStatusCode("协同"); oaCollaboration.setName("职称(技术等级)评聘申请表"); oaCollaboration.setDataOne("拟评聘职称(技术等级)名称:" + oaActEngage.getUndoutedly()); oaCollaboration.setDataTwo("考试时间:" + oaActEngage.getExamTime()); oaCollaboration.setState(state); oaCollaboration.setCreateTime(new Date()); oaCollaborationMapper.insertData(oaCollaboration); return 1; } } @Override public int edit(OaActEngage oaActEngage) { oaActEngage.setState(0); oaActEngage.setPrincipal(""); oaActEngage.setPrincipalDate(""); oaActEngage.setPrincipalContent(""); oaActEngage.setPrincipalT(""); oaActEngage.setPrincipalDateT(""); oaActEngage.setPrincipalContentT(""); oaActEngage.setSupervisor(""); oaActEngage.setSupervisorDate(""); oaActEngage.setSupervisorContent(""); oaActEngage.setPersonnel(""); oaActEngage.setPersonnelDate(""); oaActEngage.setPersonnelContent(""); oaActEngage.setCompanyPrincipal(""); oaActEngage.setCompanyPrincipalDate(""); oaActEngage.setCompanyPrincipalContent(""); oaActEngage.setUndoutedlyTeam(""); oaActEngage.setRankAllowance(""); oaActEngage.setRankDate(""); oaActEngage.setRankName(""); oaActEngage.setCreateTime(new Date()); if (oaActEngageMapper.updateByPrimaryKeySelective(oaActEngage) < 0) { return -1; } else { return 1; } } @Override public OaActEngage selectByPrimaryKey(String id) { OaActEngage oaActEngage = oaActEngageMapper.selectByPrimaryKey(id); oaActEngage.setCreateTimeStr(DateUtil.dateConvertYYYYMMDDHHMMSS(oaActEngage.getCreateTime())); oaActEngage.setPromoterStr(userInfoMapper.getNicknameById(oaActEngage.getPromoter())); return oaActEngage; } @Override public int deleteData(String id) { return oaActEngageMapper.deleteByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(OaActEngage oaActEngage) { return oaActEngageMapper.updateByPrimaryKeySelective(oaActEngage); } }
Java
UTF-8
1,573
2.21875
2
[]
no_license
package masco.mis.software.mascoapproval.chat.pojo; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * Created by ARMAN on 03-Dec-16. */ public class ChatWeiget { public String emp_ImgUrl; public String emp_Code; public String emp_Name; public String emp_Designation; public String chat_MessageStatus; public String chat_MessageTime; public ChatWeiget() { } public String getemp_ImgUrl() { return emp_ImgUrl; } public void setemp_ImgUrl(String emp_ImgUrl) { this.emp_ImgUrl = emp_ImgUrl; } public ChatWeiget(String emp_ImgUrl, String emp_Code, String emp_Name, String emp_Designation, String chat_MessageStatus, String chat_MessageTime) { this.emp_ImgUrl = emp_ImgUrl; this.emp_Code = emp_Code; this.emp_Name = emp_Name; this.emp_Designation = emp_Designation; this.chat_MessageStatus = chat_MessageStatus; this.chat_MessageTime =chat_MessageTime; } //demo list item get method public static ArrayList<ChatWeiget> getChatWeigetList() { ArrayList<ChatWeiget> chatWeiget = new ArrayList<ChatWeiget>(); SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm a"); String formattedDate = dateFormat.format(new Date()).toString(); chatWeiget.add(new ChatWeiget("http://mis.mascoknit.com:421/Images/EmpImage/13044", "20772","Md. Arman Hossain", "Executive,MIS","1 unread message",formattedDate)); return chatWeiget; } }
JavaScript
UTF-8
15,368
2.875
3
[ "Zlib" ]
permissive
define(['jquery', 'markup', 'utils/selectors', 'utils/customelements'], function($, TwineMarkup, Selectors) { "use strict"; var // Used by lockProperties lockDesc = { configurable: 0, writable: 0 }, // Used to cache t8n animation times t8nAnimationTimes = { "transition-in": Object.create(null), "transition-out": Object.create(null) }, //A binding for the cached <tw-story> reference (see below). storyElement; /** A static class with helper methods used throughout Harlowe. @class Utils @static */ var Utils = { /** Make object properties immutable and impossible to delete, without preventing the object from being extended. Does not do a 'deep' lock - object properties may, in themselves, be modified. @method lockProperties @param {Object} obj Object to lock @return The locked object */ lockProperties: function (obj) { var i, prop, keys = Object.keys(obj), propDesc = {}; for (i = 0; i < keys.length; i++) { prop = keys[i]; propDesc[prop] = lockDesc; } return Object.defineProperties(obj, propDesc); }, /** Locks a particular property of an object. @method lockProperty @param {Object} obj Object @param {String} prop Property to lock @param {String} value A value to set the property to @return The affected object */ lockProperty: function (obj, prop, value) { // Object.defineProperty does walk the prototype chain // when reading a property descriptor dict. var propDesc = Object.create(lockDesc); value && (propDesc.value = value); Object.defineProperty(obj, prop, propDesc); return obj; }, /** Retrieve a property descriptor for an object, searching through the prototype chain. @method getInheritedPropertyDescriptor @param {Object} obj The object @param {String} prop The property to investigate. @return The descriptor, or null. */ getInheritedPropertyDescriptor: function(obj, prop) { while(obj && !obj.hasOwnProperty(prop)) { obj = Object.getPrototypeOf(obj); } return (obj && Object.getOwnPropertyDescriptor(obj, prop)) || null; }, /* String utilities */ /* In some places, it's necessary to print numbers, strings and arrays of primitives as JS literals. This is a semantic shortcut for a certain built-in method that can accomplish this easily. @method toJSLiteral @return {String} */ toJSLiteral: JSON.stringify, /* Conversely, this rarer function produces a TwineScript string literal using the given string. @method toTSStringLiteral @return {String} */ toTSStringLiteral: function(str) { var consecutiveGraves = Math.max.apply( 0, /* This finds the length of the longest run of ` characters in the string. */ (str.match(/(`+)/g) || []).map(function(e) { return e.length; }).concat(0) ) + 1; return "`".repeat(consecutiveGraves) + str + "`".repeat(consecutiveGraves); }, /** Takes a string argument, expressed as a CSS time, and returns the time in milliseconds that it equals. Or, when given an array, takes all valid strings contained and returns an array of times in milliseconds. If the string can't be parsed as a time, then this returns 0. @method cssTimeUnit @param s either string, or array of strings @return either single string or array of times */ cssTimeUnit: function (s) { var ret; if (typeof s === "string") { s = s.toLowerCase(); if (s.slice(-2) === "ms") return (+s.slice(0, -2)) || 0; if (s.slice(-1) === "s") return (+s.slice(0, -1)) * 1000 || 0; } else if (Array.isArray(s)) { ret = []; s.forEach(function (e) { var time = Utils.cssTimeUnit(e); (time > 0 && ret.push(time)); }); return ret; } return 0; }, /** A quick method for turning a number into an "nth" string. @method nth @param {String|Number} num @return {String} */ nth: function (num) { var lastDigit = (num + '').slice(-1); return num + ( lastDigit === "1" ? "st" : lastDigit === "2" ? "nd" : lastDigit === "3" ? "rd" : "th"); }, /** A quick method for adding an 's' to the end of a string that comes in the form "[num] [noun]". @method plural @param {Number} num The quantity @param {String} noun The noun to possibly pluralise @return {String} */ plural: function (num, noun) { return num + " " + noun + (num > 1 ? "s" : ""); }, /* HTML utilities */ /** Unescape HTML entities. @method unescape @param {String} text Text to convert @return {String} converted text */ unescape: function(text) { return text.replace(/&(?:amp|lt|gt|quot|nbsp|zwnj|#39|#96);/g, function(e) { return { '&amp;' : '&', '&gt;' : '>', '&lt;' : '<', '&quot;' : '"', '&#39;' : "'", "&nbsp;" : String.fromCharCode(160), "&zwnj;" : String.fromCharCode(8204) }[e]; }); }, /** HTML-escape a string. @method escape @param {String} text Text to escape @return {String} converted text */ escape: function(text) { return text.replace(/[&><"']/g, function(e) { return { '&' : '&amp;', '>' : '&gt;', '<' : '&lt;', '"' : '&quot;', "'" : '&#39;', }[e]; }); }, /** Some names are case-insensitive, AND dash-insensitive. This method converts such names to all-lowercase and lacking underscores and hyphens. @method insensitiveName @param {String} text Text to convert. @return {String} converted text */ insensitiveName: function (e) { return (e + "").toLowerCase().replace(/-|_/g, ""); }, /** @method wrapHTMLTag @param {String} text Text to wrap. @param {String} tagName Name of the HTML tag to wrap in. @return {String} The wrapped text. */ wrapHTMLTag: function(text, tagName) { return '<' + tagName + '>' + text + '</' + tagName + '>'; }, /** Takes a string containing a character or HTML entity, and wraps it into a <tw-char> tag, converting the entity if it is one. Currently (Dec. 2014) unused. @method charToSpan @param {String} character @return {String} Resultant HTML */ charToSpan: function(c) { // Use single-quotes if the char is a double-quote. var quot = (c === "&#39;" ? '"' : "'"), value = Utils.unescape(c); switch(value) { case ' ': { value = "space"; break; } case '\t': { value = "tab"; break; } } return "<tw-char value=" + quot + value + quot + ">" + c + "</tw-char>"; }, /** Converts an entire string into individual characters, each enclosed by a <tw-char>. Currently (Dec. 2014) unused. @method charSpanify @param {String} text Source string @return {String} Resultant HTML */ charSpanify: function(text) { if (typeof text !== "string") { throw new Error("charSpanify received a non-string:" + text); } return text.replace(/&[#\w]+;|./g, Utils.charToSpan); }, /* Element utilities */ /** Quick utility function that calls .filter(q).add(q).find(q), which is similar to just .find() but includes the top element if it also matches. @method findAndFilter @private @param q jQuery to search, or initialising string/element for $() @param {String} selector Query string @return {jQuery} jQuery result */ findAndFilter: function (q, selector) { q = $(q || Utils.storyElement); return q.filter(selector).add(q.find(selector)); }, /** Find the closest enclosing hook span(s) for the passed jQuery object, if any. @method closestHookSpan @param elems jQuery object */ closestHookSpan: function (elems) { var ret = elems.closest(Selectors.hook + "," + Selectors.pseudoHook); return (ret.length ? ret : elems); }, /** Replaces oldElem with newElem while transitioning between both. @method transitionReplace @param oldElem a jQuery object currently in the DOM or a DOM structure @param [newElem] an unattached jQuery object to attach @param transIndex transition to use @return this */ transitionReplace: function (oldElem, newElem, transIndex) { var container1, container2a, container2b; oldElem = Utils.closestHookSpan(oldElem); // Create a transition-main-container container1 = $('<tw-transition-container>').css('position', 'relative'); // Insert said container into the DOM (next to oldElem) container1.insertBefore(oldElem.first()); if (newElem) { // Create a transition-in-container container2a = $('<tw-transition-container>').appendTo(container1); // Insert new element newElem.appendTo(container2a); } // Create a transition-out-container // and insert it into the transition-main-container. container2b = $('<tw-transition-container>').css('position', 'absolute') .prependTo(container1); // Insert the old element into the transition-out-container oldElem.detach().appendTo(container2b); // Transition-out the old element, removing it Utils.transitionOut(container2b, transIndex); // Transition-in the new element if (newElem) { Utils.transitionIn(container2a, transIndex, function () { // Remove container1 and container2a container2a.unwrap().children().first().unwrap(); }); } }, /** Transition an element out. @method transitionOut @param {jQuery} el jQuery collection to transition out @param (String) transIndex transition to use */ transitionOut: function (el, transIndex) { var delay, /* If the element is not a tw-hook or tw-passage, we must wrap it in a temporary element first, which can thus be animated using CSS. */ mustWrap = el.length > 1 || ['tw-hook','tw-passage'].indexOf(el.tag()) === -1; /* The default transition callback is to remove the element. */ function onComplete() { el.remove(); } /* As mentioned above, we must, in some cases, wrap the nodes in containers. */ if (mustWrap) { el = el.wrapAll('<tw-transition-container>').parent(); } /* Now, apply the transition. */ el.attr("data-t8n", transIndex).addClass("transition-out"); /* Ideally I'd use this: .one("animationend webkitAnimationEnd MSAnimationEnd", function(){ oldElem.remove(); }); but in the event of CSS being off, these events won't trigger - whereas the below method will simply occur immedately. */ delay = Utils.transitionTime(transIndex, "transition-out"); !delay ? onComplete() : window.setTimeout(onComplete, delay); }, /** Transition an element in. @method transitionIn @param {jQuery} el jQuery collection to transition out @param (String) transIndex Transition to use */ transitionIn: function (el, transIndex) { var delay, /* If the element is not a tw-hook or tw-passage, we must wrap it in a temporary element first, which can thus be animated using CSS. */ mustWrap = el.length > 1 || ['tw-hook','tw-passage'].indexOf(el.tag()) === -1; /* The default transition callback is to remove the transition-in class. (#maybe this should always be performed???) */ function onComplete () { /* If it's a text node, then the element is just a wrapper - discard it. */ if (mustWrap) { el.contents().unwrap(); } /* Otherwise, remove the transition attributes. */ else { el.removeClass("transition-in").removeAttr("data-t8n"); } } /* As mentioned above, we must, in some cases, wrap the nodes in containers. */ if (mustWrap) { el = el.wrapAll('<tw-transition-container>').parent(); } /* Now, perform the transition by assigning these attributes and letting the built-in CSS take over. */ el.attr("data-t8n", transIndex).addClass("transition-in"); delay = Utils.transitionTime(transIndex, "transition-in"); !delay ? onComplete() : window.setTimeout(onComplete, delay); }, /** Caches the CSS time (duration + delay) for a particular transition, to save on costly $css() lookups. @method transitionTime @param (String) transIndex Transition to use @param {String} className Either "transition-in" or "transition-out" @return this */ transitionTime: function(transIndex, className) { var p; if (!t8nAnimationTimes[className][transIndex]) { p = $('<p>').appendTo(document.body).attr("data-t8n", transIndex).addClass(className); t8nAnimationTimes[className][transIndex] = Utils.cssTimeUnit(p.css("animation-duration")) + Utils.cssTimeUnit(p.css("animation-delay")); p.remove(); } return t8nAnimationTimes[className][transIndex]; }, /** Runs a jQuery selector, but: - uses the <tw-story> element as context, unless one was given. - ignores elements that are transitioning out. @method $ @param str jQuery selector @param context jQuery context */ $: function (str, context) { return $(str, context || Utils.storyElement).not(".transition-out, .transition-out *"); }, /* Logging utilities */ /** Internal logging function. Currently a wrapper for console.log. This should be used for basic event logging. @method log @param data line to log */ log: function (data) { console.log(data); }, /** Internal error logging function. Currently a wrapper for console.error. This should be used for engine errors beyond the story author's control. @method impossible @param {String} where Name of the calling method. @param data Line to log */ impossible: function (where, data) { console.error(where + "(): " + data); }, /** Standard assertion function. @method assert @param {Boolean} assertion */ assert: function(assertion) { if (!assertion) { console.error("Assertion failed!"); } }, /** Asserts that an object doesn't lack a necessary property. This and the next method provide some shape-checking to important functions. @method assertMustHave @param {Object} object @param {Array} props */ assertMustHave: function(object, props) { for(var i = 0; i < props.length; i += 1) { if(!(props[i] in object)) { console.error("Assertion failed: " + object + " lacks property " + props[i]); } } }, /** Asserts that an object has no property extensions. @method assertOnlyHas @param {Object} object @param {Array} props */ assertOnlyHas: function(object, props) { for(var i in object) { if (props.indexOf(i) === -1) { console.error("Assertion failed: " + object + " had unexpected property '" + i + "'!"); } } }, /* Constants */ /** This is used as a more semantic shortcut to the <tw-story> element. @property storyElement @static */ get storyElement() { return storyElement; }, }; /* The reference to the <tw-story> should be set at startup, so that it can be used even when it is disconnected from the DOM (which occurs when a new passage is being rendered into it). */ $(document).ready(function() { storyElement = $(Selectors.story); }); return Object.freeze(Utils); });
SQL
UTF-8
1,700
3.0625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jan 16, 2018 at 02:06 AM -- Server version: 10.1.13-MariaDB -- PHP Version: 7.0.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `ojt` -- -- -------------------------------------------------------- -- -- Table structure for table `timeSheet` -- CREATE TABLE `timeSheet` ( `id` int(11) NOT NULL, `student` varchar(100) NOT NULL, `date` varchar(100) NOT NULL, `timeIn` datetime NOT NULL, `timeOut` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `timeSheet` -- INSERT INTO `timeSheet` (`id`, `student`, `date`, `timeIn`, `timeOut`) VALUES (1, 'ricardo', '2017-12-22', '2017-12-22 08:55:00', '2017-12-22 16:00:00'), (2, 'ricardo', '2017-12-23', '2017-12-23 08:25:00', '2017-12-23 17:55:00'), (3, 'ricardo', '2017-12-23 ', '2017-12-23 09:56:00', '2017-12-23 16:23:00'); -- -- Indexes for dumped tables -- -- -- Indexes for table `timeSheet` -- ALTER TABLE `timeSheet` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `timeSheet` -- ALTER TABLE `timeSheet` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
1,307
2.453125
2
[]
no_license
package ar.com.dbgrid; import java.lang.reflect.InvocationTargetException; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; import ar.com.dbgrid.dao.AlumnoDao; import ar.com.dbgrid.modelo.ConversorResultSetADefaultTableModel; import ar.com.dbgrid.vista.FormularioAlumnos; public class Principal { public static void main(String[] args) { try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { createAndShowUI(); } }); } catch (InvocationTargetException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void createAndShowUI() { JFrame frame = new JFrame("Alumnos"); DefaultTableModel modelo = new DefaultTableModel(); FormularioAlumnos form = new FormularioAlumnos(); frame.add(form); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); AlumnoDao alumnosResultSet = new AlumnoDao(); frame.setVisible(true); ConversorResultSetADefaultTableModel.rellena(alumnosResultSet.getAllAlumnos(), modelo); form.tomaDatos(modelo); } }
Python
UTF-8
556
4.125
4
[]
no_license
#question 3 def check(g,n): if g < n: return "Too low" elif g > n: return "Too high" else: return "Correct" def main(): # question 3 number = randint(0,99) guess = 0 finished = False count = 0 guess = int(input("Guess a number between 0 and 99: ")) while not finished: count += 1 if guess < number: guess = int(input("Too low, Guess again: ")) elif guess > number: guess = int(input("To high, Guess again: ")) else: finished = True print("Correct. It took you ",count, " guesses") if __name__ == "__main__": main()
Java
UTF-8
2,725
2.03125
2
[]
no_license
package br.com.delos.config; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.springframework.beans.factory.config.CustomScopeConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.resource.GzipResourceResolver; import org.springframework.web.servlet.resource.PathResourceResolver; import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import br.com.delos.scope.spring.ViewScope; import br.com.delos.utils.core.BeanSuportFactory; @Configuration @EnableWebMvc @ComponentScan("br.com.delos.controller") public class MvcConfig extends WebMvcConfigurerAdapter { private static final Logger log = Logger.getLogger(MvcConfig.class); public MvcConfig() { log.info("::::Inicialização do MVC Config e Escaneamento dos Controladores::::"); } @Bean public InternalResourceViewResolver internalResourceViewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/pages/"); resolver.setSuffix(".xhtml"); return resolver; } @Bean public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { return new ResourceUrlEncodingFilter(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/resources/") .setCachePeriod(0) .resourceChain(true) .addResolver(new GzipResourceResolver()) .addResolver(new PathResourceResolver()); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public static CustomScopeConfigurer customScopeConfigurer(){ CustomScopeConfigurer view = new CustomScopeConfigurer(); Map<String,Object> scopes = new HashMap<String,Object>(); scopes.put("view",new ViewScope()); view.setScopes(scopes); return view; } @Bean public static BeanSuportFactory beanSuportFactory() { BeanSuportFactory bsf = new BeanSuportFactory(); return bsf; } }
Python
UTF-8
7,828
2.53125
3
[ "MIT" ]
permissive
from typing import List, Tuple import numpy as np from highway_env import utils from highway_env.road.road import Road, RoadNetwork from highway_env.road.lane import StraightLane from highway_env.vehicle.controller import ControlledVehicle, MDPVehicle from highway_env.vehicle.kinematics import Vehicle, Obstacle from highway_env.vehicle.l012vehicles import Pedestrian class RegulatedRoad(Road): YIELDING_COLOR: Tuple[float, float, float] = None REGULATION_FREQUENCY: int = 2 YIELD_DURATION: float = 0. def __init__(self, network: RoadNetwork = None, vehicles: List[Vehicle] = None, obstacles: List[Obstacle] = None, np_random: np.random.RandomState = None, record_history: bool = False) -> None: super().__init__(network, vehicles, obstacles, np_random, record_history) self.steps = 0 self.intersection_order = [] def step(self, dt: float) -> None: self.steps += 1 if self.steps % int(1 / dt / self.REGULATION_FREQUENCY) == 0: self.enforce_road_rules() return super().step(dt) def enforce_road_rules(self) -> None: """Find conflicts and resolve them by assigning yielding vehicles and stopping them.""" if False: # go one by one in intersection n_veh_in_intersection = 0 closest = None closest_dist = 1e9 threshold = 10 # threshold to start braking if theres someone in intersection threshold_arrival = 50 # threshold to be detected as arriving to intersection # prevent vehicles from entering intersection if there's already one vehicle in for v in self.vehicles: origin, dest, _ = lane = self.network.get_closest_lane_index(v.position) lane_geometry = self.network.get_lane(lane) if origin.startswith("o"): # going towards intersection assert isinstance(lane_geometry, StraightLane) _, lane_end = lane_geometry.start, lane_geometry.end v_dist = np.linalg.norm(lane_end - v.position) # distance to intersection if v_dist < closest_dist: closest_dist = v_dist closest = v if v_dist < threshold: # vehicle getting close to intersection -> brake v.target_speed = 0 if v_dist < threshold_arrival: if v not in self.intersection_order: self.intersection_order.append(v) elif origin.startswith("i") and dest.startswith("i"): # vehicle in intersection n_veh_in_intersection += 1 if n_veh_in_intersection == 0 and len(self.intersection_order) > 0: # and closest is not None: # if intersection is empty, last vehicle arrived is allowed to go v_go = self.intersection_order.pop(0) v_go.target_speed = v_go.lane.speed_limit # # if intersection is empty, vehicle closest to intersection is allowed to go # closest.target_speed = closest.lane.speed_limit # Unfreeze previous yielding vehicles for v in self.vehicles: if getattr(v, "is_yielding", False): if v.yield_timer >= self.YIELD_DURATION * self.REGULATION_FREQUENCY: v.target_speed = v.lane.speed_limit # if hasattr(v, "color"): # delattr(v, "color") v.is_yielding = False else: v.yield_timer += 1 # Find new conflicts and resolve them for i in range(len(self.vehicles) - 1): for j in range(i+1, len(self.vehicles)): # avoid crashes # but not with pedestrians if isinstance(self.vehicles[i], Pedestrian) or isinstance(self.vehicles[j], Pedestrian): continue if self.is_conflict_possible(self.vehicles[i], self.vehicles[j]): yielding_vehicle = self.respect_priorities(self.vehicles[i], self.vehicles[j]) if yielding_vehicle is not None and \ isinstance(yielding_vehicle, ControlledVehicle) and \ not isinstance(yielding_vehicle, MDPVehicle): # yielding_vehicle.color = self.YIELDING_COLOR yielding_vehicle.target_speed = 0 yielding_vehicle.is_yielding = True yielding_vehicle.yield_timer = 0 # if ped is crossing, slow down if False: self.check_ped_crossing(self.vehicles[i], self.vehicles[j]) @staticmethod def respect_priorities(v1: Vehicle, v2: Vehicle) -> Vehicle: """ Resolve a conflict between two vehicles by determining who should yield :param v1: first vehicle :param v2: second vehicle :return: the yielding vehicle """ if v1.lane.priority > v2.lane.priority: return v2 elif v1.lane.priority < v2.lane.priority: return v1 else: # The vehicle behind should yield return v1 if v1.front_distance_to(v2) > v2.front_distance_to(v1) else v2 @staticmethod def is_conflict_possible(v1: ControlledVehicle, v2: ControlledVehicle, horizon: int = 3, step: float = 0.25) -> bool: times = np.arange(step, horizon, step) positions_1, headings_1 = v1.predict_trajectory_constant_speed(times) positions_2, headings_2 = v2.predict_trajectory_constant_speed(times) for position_1, heading_1, position_2, heading_2 in zip(positions_1, headings_1, positions_2, headings_2): # Fast spherical pre-check if np.linalg.norm(position_2 - position_1) > v1.LENGTH: continue # Accurate rectangular check if utils.rotated_rectangles_intersect((position_1, 1.5*v1.LENGTH, 0.9*v1.WIDTH, heading_1), (position_2, 1.5*v2.LENGTH, 0.9*v2.WIDTH, heading_2)): return True @staticmethod def check_ped_crossing(v1: ControlledVehicle, v2: ControlledVehicle) -> bool: times_veh = np.arange(0.1, 1, 0.1) times_ped = np.arange(0.1, 5, 0.1) if v1.LENGTH < 3 and v2.LENGTH > 3: ped, veh = v1, v2 elif v1.LENGTH > 3 and v2.LENGTH < 3: ped, veh = v2, v1 else: return False for pos1 in ped.predict_trajectory_constant_speed(times_ped)[0]: for pos2 in veh.predict_trajectory_constant_speed(times_veh, use_lane_speed=True)[0]: if np.linalg.norm(pos1 - pos2) < 5 and \ isinstance(veh, ControlledVehicle) and \ not isinstance(veh, MDPVehicle): veh.target_speed = 0 veh.is_yielding = True veh.yield_timer = 0 return True return False def is_ped_crossing(self, crossing: int) -> bool: """whether a pedestrian is crossing on the specified crossing. crossing ids = 0: east crossing 1: south crossing 2: west crossing 3: north crossing""" for v in self.vehicles: if type(v.lane) is StraightLane: if v.lane_index[0].startswith(f'p{crossing}'): if np.max(v.lane.local_coordinates(v.position)) > 95 and np.max(v.lane.local_coordinates(v.position)) < 115: return True return False
C++
UTF-8
975
3.078125
3
[]
no_license
#include <algorithm> #include <iostream> #include <set> #include <string> #include <vector> using namespace std; int main() { string text; cin >> text; vector<string> patts; string in; while (cin >> in) { if (in == "break") break; patts.push_back(in); } vector<pair<string, int>> suffs; for (int i = 0; i < text.size(); i++) { suffs.push_back({ text.substr(i), i }); } sort(suffs.begin(), suffs.end(), [](const pair<string, int>& lhs, const pair<string, int>& rhs) { return lhs.first < rhs.first; }); set<int> finds; for (int i = 0; i < suffs.size(); i++) { for (const string& patt : patts) { if (suffs[i].first.starts_with(patt)) { finds.insert(suffs[i].second); } } } for (const int pos : finds) { cout << pos << ' '; } return 0; }
Python
UTF-8
1,307
2.90625
3
[]
no_license
import argparse import sys import prediction.SpotifyClassifier as sc import prediction.YoutubeNeuronNetwork as ffn SPOTIFY_DATASET_PATH = './Business Analysis/data/spotify_metadata_playlist.xlsx' YOUTUBE_DATASET_PATH = './Business Analysis/data/youtube_metadata_per_user.csv' def main(platform='spotify', users=[]): if(platform == 'spotify'): sc.classify(SPOTIFY_DATASET_PATH, users) elif(platform == 'youtube'): ffn.classify(YOUTUBE_DATASET_PATH, users) print("Add youtube classifier") # Predict regarding all users for spotify: PredictionMainClass.py -p spotify # Predict regarding user 16 for spotify: PredictionMainClass.py -p spotify -u 16 # Predict regarding all users for youtube: PredictionMainClass.py -p youtube # Predict regarding user 16 for youtube: PredictionMainClass.py -p youtube -u 16 if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--platform', '-p', help="spotify or youtube", type=str) parser.add_argument('--users', '-u', help="id(s) of users separated by commas", type=int, default=0) args = parser.parse_args(sys.argv[1:]) platform = args.platform #spotify or youtube users = str(args.users).split(',') #for all users the empty parameter is translated to ['0'] main(platform, users)
Ruby
UTF-8
3,300
2.859375
3
[ "MIT" ]
permissive
require "subshell_command/version" require "open3" module SubshellCommand class Command attr_reader :command_string attr_reader :env_hash, :current_directory attr_reader :success_callback, :failure_callback attr_reader :redirect_stderr_to_stdout def initialize(command_string) @command_string = command_string @env_hash = {} @current_directory = Dir.pwd @success_callback = ->{} @failure_callback = ->{} @redirect_stderr_to_stdout = false end def cmd=(command_string) @command_string = command_string end def env=(env_hash) @env_hash = env_hash end def current_directory=(directory_string) @current_directory = directory_string end def on_success=(callback) @success_callback = callback end def on_failure=(callback) @failure_callback = callback end def redirect_stderr_to_stdout=(value) @redirect_stderr_to_stdout = value end end class Result attr_accessor :success, :stdout_value, :stderr_value def initialize @success = nil @stdout_value = nil @stderr_value = nil end def success? @success end end class StandardOutputStreamsExecutor attr_reader :command_object, :result def initialize(command_object, result) @command_object = command_object @result = result end def execute Open3.popen3( command_object.env_hash, command_object.command_string, chdir: command_object.current_directory, ) do |stdin, stdout, stderr, wait_thr| exit_status = wait_thr.value result.stdout_value = stdout.read result.stderr_value = stderr.read result.success = exit_status.success? end end end class CombinedOutputStreamsExecutor attr_reader :command_object, :result def initialize(command_object, result) @command_object = command_object @result = result end def execute Open3.popen2e( command_object.env_hash, command_object.command_string, chdir: command_object.current_directory, ) do |stdin, output_streams, wait_thr| exit_status = wait_thr.value output_value = output_streams.read result.stdout_value = output_value result.stderr_value = output_value result.success = exit_status.success? end end end class CommandExecutor attr_reader :command_object EXECUTORS = { true => CombinedOutputStreamsExecutor, false => StandardOutputStreamsExecutor, } def initialize(command_object) @command_object = command_object end def execute result = Result.new EXECUTORS[command_object.redirect_stderr_to_stdout].new(command_object, result).execute execute_callbacks(result) result end private def execute_callbacks(result) if result.success? command_object.success_callback.call(result) else command_object.failure_callback.call(result) end end end class << self def execute(command_string = nil, &block) command = Command.new(command_string) block.call(command) if block_given? CommandExecutor.new(command).execute end end end
Java
UTF-8
1,280
3.484375
3
[]
no_license
import java.util.Scanner; class Solution { public static int getHeight(Node root) { //Write your code here Node node = root; int height_left = 0; int height_right = 0; if (node.left == null && node.right == null) return 0; else { if (node.left != null) height_left = getHeight(node.left) + 1; if (node.right != null) height_right = getHeight(node.right) + 1; return Math.max(height_left, height_right); } } public static Node insert(Node root, int data) { if (root == null) { return new Node(data); } else { Node cur; if (data <= root.data) { cur = insert(root.left, data); root.left = cur; } else { cur = insert(root.right, data); root.right = cur; } return root; } } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); Node root = null; while (T-- > 0) { int data = sc.nextInt(); root = insert(root, data); } int height = getHeight(root); System.out.println(height); } }
C#
UTF-8
1,469
3.484375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPatternsLibrary { public enum cars { AUDI, BMW} class Program { static void Main(string[] args) { ICarFactory facotry = null; bool rightCommand = true; while (rightCommand) { string command = Console.ReadLine().ToLower(); switch (command) { case "audi": facotry = new AudiFactory(); rightCommand = false; break; case "bmw": facotry = new BMWFactory(); rightCommand = false; break; default: Console.WriteLine("Wrong Command"); break; } } ICarFactory factory = LoadFactory(facotry); var car = factory.CreateLuxaryCar(); Console.WriteLine(car.ToString()); car = factory.CreateSportsCar(); Console.WriteLine(car.ToString()); car = factory.CreateEconomyCar(); Console.WriteLine(car.ToString()); } static ICarFactory LoadFactory(ICarFactory facotry) { return facotry as ICarFactory; } } }
C
UTF-8
345
3.65625
4
[]
no_license
#include <stdio.h> unsigned setbits(unsigned x, int p, int n, int y); int main() { unsigned x = 42; x = setbits(x, 0, 0, 0); printf("%u", x); return 0; } /* set n bits of x beginning at position p to the right-most n bits of y, * leaving the other bits unchanged */ unsigned setbits(unsigned x, int p, int n, int y) { return x; }
Python
UTF-8
1,259
2.671875
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env pytest-3 # -*- coding: utf-8 -*- from pybgl.automaton import Automaton from pybgl.graphviz import graph_to_html from pybgl.html import html from pybgl.ipynb import in_ipynb from pybgl.suffix_trie import BOTTOM, factors, make_suffix_trie from pybgl.trie import Trie def test_factors(): d = { "": {""}, "ab": {"", "a", "b", "ab"}, "ananas": { "", "a", "n", "s", "an", "na", "as", "ana", "nan", "nas", "anan", "nana", "anas", "anana", "nanas", "ananas" } } for (w, expected) in d.items(): obtained = {factor for factor in factors(w)} assert expected == obtained def check(word, expected_num_vertices, max_len=None): t = make_suffix_trie(word, max_len=max_len) if in_ipynb(): html(graph_to_html(t)) assert t.num_vertices() == expected_num_vertices for q in t.vertices(): assert t.is_final(q) assert not t.is_final(BOTTOM) def test_make_suffix_tree(): check("ananas", 16) def test_make_suffix_tree_max_len(): check("ananas", 10, max_len=3) def test_max_suffix_tree_g(): g = Trie() make_suffix_trie("ananas", g=g) assert g.num_vertices() == 16
Python
UTF-8
628
3.671875
4
[]
no_license
# BASIC LOGGING import logging def main(): # use basicConfig to configure logging logging.basicConfig(level=logging.DEBUG, filename="output.log", filemode="w") # try each of the log levels logging.debug("This is a debug message") logging.info("This is a info message") logging.warning("This is a warning message") logging.error("This is an error message") logging.critical("This is a critical message") # output formatted strings to the log logging.info("Here is a {} variable and an int:".format("string",10)) if __name__ == "__main__": main()
C#
UTF-8
2,821
2.71875
3
[]
no_license
namespace Mudanzas.Helpers.Templates { public class UsuarioEmailTemplate { public static string bienvenidoProspecto(string nombre, string codigoVerificacion, string link) { string template = $"" + $"<h2>Bienvenido {nombre}</h2>, <br> para continuar con tu registro introduce este codigo en la aplicación<br>" + $"<strong>{codigoVerificacion}</strong><br>" + $"<a href=\"{link}\">Link a la aplicacion</a>" + $""; return template; } public static string prospectoAceptado(string nombre, string link, string token) { string template = $"" + $"<h2>Hola {nombre}</h2>, ¡Bienvenido a ProyWeb! <br> Actualmente posees una cuenta que te permitirá reservar servicios de mudanza. <br>" + $"<h3> Para ingresar a tu cuenta entra a <a href=\"{link}/cambiopass?token={token}\">Mudanzas Proyweb</a> y elige tu contraseña.</h3><br>" + $"<h3>Atentamente, <br> el equipo de </h3>" + $"<a href=\"{link}\">Mudanzas Proyweb</a>" + $""; return template; } public static string cambioContrasena(string nombre, string link, string token) { string template = $"" + $"<h2>Hola {nombre}</h2>, <br> Has pedido un reestablecimiento de tu contraseña de acceso a ProyWeb. <br> " + $"<h3> Para cambiar la contraseña de acceso a tu cuenta entra a <a href=\"{link}/cambiopass?token={token}\">Mudanzas Proyweb</a> y elige tu nueva contraseña.</h3><br>" + $"<h3>Atentamente, <br> el equipo de </h3>" + $"<a href=\"{link}\">Mudanzas Proyweb</a>"; return template; } public static string detalleReservacion(string nombre, string folioReservacion, string numAutorizacionPago, string origen, string destino, string tipoCamion, string fechaReservacion, string link) { string template = $"" + $"<h2>Gracias por elegirnos, {nombre}</h2><br>" + $"<h6>Folio de resevación: <strong>{folioReservacion}</strong></h6><br>" + $"<h6>Número de autorizacion de pago: <strong>{numAutorizacionPago}</strong></h6><br>" + $"<h6>Ciudad origen: <strong>{origen}</strong></h6><br>" + $"<h6>Ciudad destino: <strong>{destino}</strong></h6><br>" + $"<h6>Tipo de camión: <strong>{tipoCamion}</strong></h6><br>" + $"<h6>Fecha de resevacion: <strong>{fechaReservacion}</strong></h6><br>" + $"<h3>Atentamente, <br> el equipo de </h3>" + $"<a href=\"{link}\">Mudanzas Proyweb</a>" + $""; return template; } } }
Java
UTF-8
2,163
2.5
2
[]
no_license
package com.example.invoice.model; import com.sun.istack.NotNull; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import java.time.LocalDate; import java.util.Objects; @Entity @Table(name = "invoice") public class Invoice { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Length(min = 2, max = 8) private Long amount; @NotNull private LocalDate issued; @NotNull private LocalDate due; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "order_id", referencedColumnName = "id") private Order order; public Invoice() { } public Invoice(Long id, Long amount, LocalDate issued, LocalDate due, Order order) { this.id = id; this.amount = amount; this.issued = issued; this.due = due; this.order = order; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public LocalDate getIssued() { return issued; } public void setIssued(LocalDate issued) { this.issued = issued; } public LocalDate getDue() { return due; } public void setDue(LocalDate due) { this.due = due; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Invoice invoice = (Invoice) o; return Objects.equals(id, invoice.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "Invoice{" + "id=" + id + ", amount=" + amount + ", issued=" + issued + ", due=" + due + ", order=" + order + '}'; } }
C#
UTF-8
1,140
2.546875
3
[]
no_license
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace RECIManagementSoftware { class InsertNewAccount { private static string _computerName = Environment.MachineName; private static DateTime _today = DateTime.Today; public InsertNewAccount() { Login login = new(); _connectionString = String.Format ( "Server={0}\\{1};" + "Database=reci;" + "Integrated Security=True;" + "Connect Timeout=30", _computerName, login.textBox_ServerName.Text ); var insertQuery = String.Format("INSERT INTO [reci].[Account] " + "VALUES('NewUser', 'pass1234', 'place-holder', '{0}')", _today); using(SqlConnection connection = new(_connectionString)) using(SqlDataAdapter adapter = new(insertQuery, connection)) { } } private string _connectionString; } }
JavaScript
UTF-8
1,602
3.15625
3
[]
no_license
import React from "react"; import WeatherIcon from "./WeatherIcon.js"; export default function WeatherForecastInformation(props){ function hours(){ let date= new Date(props.data.dt * 1000 ); let hours = date.getHours(); // if hour is 0 it displays as 12 if (hours === 0){hours = 12;} // if hours is over 12 subracts 12 and returns with PM. Otherwise shows AM after time. if (hours > 12){hours -=12; return (<span className="hours">{hours}:00 PM</span>);} else {return(<span className="hours">{hours}:00 AM</span>);}} // Rounds temperature sent from Weather.js and returns in Farenheit function temperature(){ let temperature = Math.round(props.data.main.temp); return(`${temperature}°F`);} // If unit is farenheit displays WeatherForecastInformation in farenheit measurements if (props.unit === "farenheit") { return ( <div className="WeatherForecastInformation col"> {hours()} <WeatherIcon code={props.data.weather[0].icon} /> <span className="temperature"> {temperature()} </span> </div> ); } // Displays WeatherForecastInformation in Celsius measurements. Converts farenheit temp to celsius. else { let temperature = Math.round(((props.data.main.temp - 32) * 5) / 9); return ( <div className="WeatherForecastInformation col"> {hours()} <WeatherIcon code={props.data.weather[0].icon} /> <span className="temperature"> {temperature}°C</span> </div> ); } }
Java
UTF-8
2,452
2.015625
2
[]
no_license
package com.qy.business.main.login.bean; public class LoginReturnDataBean { private String user_id;//用户编号 private String user_name;//用户名 private String parent_id;//父账号ID private String parent_name;//父账号名 private String user_type;//用户类型 private String subordinate;//是否顶级账户或员工账户 private String nickname;//昵称 private String qq;//用户QQ private String fullname;//真实姓名 private String email;//邮箱 private String phone_bind;//是否绑定手机 private String phone;//手机 private String last_time;//上次登录时间 private String user_money;//余额 public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getUser_type() { return user_type; } public void setUser_type(String user_type) { this.user_type = user_type; } public String getSubordinate() { return subordinate; } public void setSubordinate(String subordinate) { this.subordinate = subordinate; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone_bind() { return phone_bind; } public void setPhone_bind(String phone_bind) { this.phone_bind = phone_bind; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getLast_time() { return last_time; } public void setLast_time(String last_time) { this.last_time = last_time; } public String getUser_money() { return user_money; } public void setUser_money(String user_money) { this.user_money = user_money; } public String getParent_id() { return parent_id; } public void setParent_id(String parent_id) { this.parent_id = parent_id; } public String getParent_name() { return parent_name; } public void setParent_name(String parent_name) { this.parent_name = parent_name; } }
Go
UTF-8
21,456
2.9375
3
[]
no_license
package ai import ( "github.com/timsims1717/cg_rogue_go/internal/actions" "github.com/timsims1717/cg_rogue_go/internal/floor" "github.com/timsims1717/cg_rogue_go/internal/selector" "github.com/timsims1717/cg_rogue_go/pkg/world" "math/rand" ) type RandomWalker struct { *AbstractAI } func NewRandomWalker(character *floor.Character) *AbstractAI { newAI := &AbstractAI{ Character: character, decision: -1, currValues: selector.ActionValues{ Source: character, }, } walker := &RandomWalker{ newAI, } newAI.AI = walker return newAI } func (ai *RandomWalker) Decide() { orig := ai.Character.Coords movCheck := floor.PathChecks{ NotFilled: true, Unoccupied: true, NonEmpty: true, EndUnoccupied: true, HonorClaim: true, Orig: orig, } atkCheck := floor.PathChecks{ NotFilled: true, Unoccupied: false, NonEmpty: false, Orig: orig, } var choice int neighbors := orig.Neighbors() indexList := make([]int, 0) for i, n := range neighbors { if m := floor.CurrentFloor.IsLegal(n, movCheck); m != nil { a := world.NextHexLine(orig, n) atkCheck.Orig = a if h := floor.CurrentFloor.IsLegal(a, atkCheck); h != nil { indexList = append(indexList, i) } } } if len(indexList) > 0 { choice = indexList[rand.Intn(len(indexList))] } else { choice = rand.Intn(len(neighbors)) } mov := neighbors[choice] path := []world.Coords{ orig, mov, } atk := []world.Coords{ mov, world.NextHexLine(orig, mov), } atkCheck.Orig = mov ai.currValues.Damage = 1 ai.currValues.Move = 1 ai.Actions = []*AIAction{ { Path: path, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }, { Path: atk, PathCheck: floor.PathChecks{}, TargetArea: []world.Coords{world.Origin}, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTriangleEffect{}, ai.currValues), }, } } func (ai *RandomWalker) TakeTurn() { for i, act := range ai.TempActions { switch i % 2 { case 0: AddToBot(actions.NewMoveSeriesAction(ai.currValues.Source, ai.currValues.Source, act.Area), act.Effect) case 1: AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) } } } // If the player is further than 6 tiles, 50% chance to move 1-2 tiles // Otherwise, chases the player: // If w/in 3, move 2 and attack // Otherwise move 2 // After 3 attacks, must rest type FlyChaser struct { *AbstractAI atkCnt int } func NewFlyChaser(character *floor.Character) *AbstractAI { newAI := &AbstractAI{ Character: character, decision: -1, currValues: selector.ActionValues{ Source: character, }, } flyChaser := &FlyChaser{ newAI, 0, } newAI.AI = flyChaser return newAI } func (ai *FlyChaser) Decide() { if ai.atkCnt >= 3 { ai.Actions = []*AIAction{} ai.atkCnt = 0 return } orig := ai.Character.Coords movCheck := floor.PathChecks{ NotFilled: true, Unoccupied: false, NonEmpty: true, EndUnoccupied: true, HonorClaim: true, Orig: orig, } atkCheck := floor.PathChecks{ NotFilled: true, Unoccupied: false, NonEmpty: false, EndUnoccupied: false, Orig: orig, } targets := floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 6) if len(targets) > 0 { for i := 0; i < 3; i++ { choice := targets[rand.Intn(len(targets))] if path, d, legal := floor.CurrentFloor.FindPathWithinOne(orig, choice, movCheck); legal { if d > 2 { tPath := floor.CurrentFloor.LongestLegalPath(path, 3, movCheck) if len(tPath) > 0 { ai.Actions = []*AIAction{ { Path: tPath, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveEffect{ End: true, }, ai.currValues), IsMove: true, }, } return } } else { ai.currValues.Damage = 1 ai.Actions = []*AIAction{ { Path: path, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveEffect{ End: true, }, ai.currValues), IsMove: true, }, { Path: []world.Coords{path[len(path)-1], choice}, PathCheck: floor.NoCheck, TargetArea: []world.Coords{world.Origin}, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTriangleEffect{}, ai.currValues), }, } ai.atkCnt++ return } } } } if rand.Intn(2) > 0 { // 50% chance random walk within, _ := world.Remove(orig, floor.CurrentFloor.AllWithin(orig, 2, movCheck)) if len(within) > 0 { for i := 0; i < 3; i++ { choice := within[rand.Intn(len(within))] if path, d, legal := floor.CurrentFloor.FindPath(orig, choice, movCheck); legal && d <= 2 { ai.Actions = []*AIAction{ { Path: path, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveEffect{ End: true, }, ai.currValues), IsMove: true, }, } } } } } } func (ai *FlyChaser) TakeTurn() { for i, act := range ai.TempActions { switch i % 2 { case 0: AddToBot(actions.NewMoveSeriesAction(ai.Character, ai.Character, act.Area), act.Effect) case 1: AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) } } } // If the player is further than 10 tiles, patrols between two points // If the player is between 8-10 tiles, gets w/in 8 // If the player is between 4-7 tiles, strafe and attack from range // If the player is between 2-3 tiles, retreat // Otherwise, plink the player type Skirmisher struct { *AbstractAI patrol []world.Coords patrolling int } func NewSkirmisher(character *floor.Character) *AbstractAI { newAI := &AbstractAI{ Character: character, decision: -1, currValues: selector.ActionValues{ Source: character, }, } skirm := &Skirmisher{ newAI, []world.Coords{}, 0, } newAI.AI = skirm return newAI } func (ai *Skirmisher) Decide() { orig := ai.Character.Coords movCheck := floor.PathChecks{ NotFilled: true, Unoccupied: true, NonEmpty: true, EndUnoccupied: true, HonorClaim: true, Orig: orig, } atkCheck := floor.PathChecks{ NotFilled: true, Unoccupied: false, NonEmpty: false, EndUnoccupied: false, Orig: orig, } ai.currValues.Damage = 1 if len(ai.patrol) == 0 { patrolCand, _ := world.Remove(orig, floor.CurrentFloor.AllWithin(orig, 6, movCheck)) ordered := world.ReverseList(world.OrderByDistSimple(orig, patrolCand)) choice := 0 if len(ordered) > 8 { choice = rand.Intn(len(ordered) / 8) } chosen := ordered[choice] ai.patrol = []world.Coords{ orig, chosen, } ai.patrolling = 1 } targets := floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 1) if len(targets) > 0 { choice := 0 if len(targets) > 1 { choice = rand.Intn(len(targets)) } ai.Actions = []*AIAction{ { Path: []world.Coords{orig, targets[choice]}, PathCheck: floor.NoCheck, TargetArea: []world.Coords{world.Origin}, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTriangleEffect{}, ai.currValues), }, } ai.decision++ return } targets = floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 3) if len(targets) > 0 { dist := world.OrderByDistSimple(orig, targets) path, _, legal := floor.CurrentFloor.FindPathAwayFrom(orig, dist[0], 3, movCheck) if legal { ai.Actions = []*AIAction{ { Path: path, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }, } ai.decision = 0 return } } targets = floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 7) if len(targets) > 0 { choice := 0 if len(targets) > 1 { choice = rand.Intn(len(targets)) } path, _, legal := floor.CurrentFloor.FindPathPerpendicularTo(orig, targets[choice], 3, 7, movCheck, atkCheck) if legal { ai.Actions = []*AIAction{ { Path: path, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }, } end := path[len(path)-1] atkPath := floor.CurrentFloor.LongestLegalPath(floor.CurrentFloor.Line(end, targets[choice], 7), 7, atkCheck) if world.CoordsIn(targets[choice], atkPath) { ai.Actions = append(ai.Actions, &AIAction{ Path: []world.Coords{end, targets[choice]}, PathCheck: atkCheck, TargetArea: []world.Coords{world.Origin}, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTargetEffect{}, ai.currValues), }) } } ai.decision = 2 return } targets = floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 10) if len(targets) > 0 { choice := targets[rand.Intn(len(targets))] if path, _, legal := floor.CurrentFloor.FindPathWithinOne(orig, choice, movCheck); legal { tPath := floor.CurrentFloor.LongestLegalPath(path, 3, movCheck) if len(tPath) > 0 { ai.Actions = []*AIAction{ { Path: tPath, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }, } ai.decision = 0 return } } } if len(ai.patrol) > 1 { if path, _, legal := floor.CurrentFloor.FindPath(orig, ai.patrol[ai.patrolling], movCheck); legal { tPath := floor.CurrentFloor.LongestLegalPath(path, 3, movCheck) if len(tPath) > 0 { ai.Actions = []*AIAction{ { Path: tPath, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }, } ai.decision = 0 if tPath[len(tPath)-1] == ai.patrol[ai.patrolling] { ai.patrolling = (ai.patrolling + 1) % 2 } } } else { ai.patrol = []world.Coords{} } } } func (ai *Skirmisher) TakeTurn() { if len(ai.TempActions) > 0 { switch ai.decision { case 0: act := ai.TempActions[0] AddToBot(actions.NewMoveSeriesAction(ai.Character, ai.Character, act.Area), act.Effect) case 1: act := ai.TempActions[0] AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) case 2: for i, act := range ai.TempActions { if i == 0 { AddToBot(actions.NewMoveSeriesAction(ai.Character, ai.Character, act.Area), act.Effect) } else { AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) } } } } } // If the player is further than 10 tiles, do nothing, maybe random walk? // If the player is between 4-10 tiles, do bombard strike or scatter bomb // If the player is between 1-3 tiles, blast in a cone // bombard strike and scatter bomb can be done twice, then rest // always rest after blast in a cone type Grenadier struct { *AbstractAI atkCnt int } func NewGrenadier(character *floor.Character) *AbstractAI { newAI := &AbstractAI{ Character: character, decision: -1, currValues: selector.ActionValues{ Source: character, }, } gren := &Grenadier{ newAI, 0, } newAI.AI = gren return newAI } func (ai *Grenadier) Decide() { if ai.atkCnt > 1 { ai.atkCnt = 0 return } orig := ai.Character.Coords movCheck := floor.PathChecks{ NotFilled: true, Unoccupied: true, NonEmpty: true, EndUnoccupied: true, HonorClaim: true, Orig: orig, } atkCheck := floor.PathChecks{ NotFilled: true, Unoccupied: false, NonEmpty: false, EndUnoccupied: false, Orig: orig, } ai.currValues.Damage = 0 targets := floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 3) if len(targets) > 0 { ai.decision = 2 choice := 0 if len(targets) > 1 { choice = rand.Intn(len(targets)) } ai.Actions = []*AIAction{} area := floor.CurrentFloor.AllInSextant(orig, targets[choice], 3, atkCheck) if world.CoordsIn(targets[choice], area) { ai.currValues.Damage = 3 ai.Actions = append(ai.Actions, &AIAction{ Path: []world.Coords{orig}, PathCheck: atkCheck, TargetArea: area, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTriangleEffect{}, ai.currValues), }) ai.atkCnt += 2 } return } targets = floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 10) if len(targets) > 0 { dec := 0 if ai.decision == 0 { dec = 1 } else if ai.decision != 1 { dec = rand.Intn(2) } ai.decision = dec choice := 0 if len(targets) > 1 { choice = rand.Intn(len(targets)) } ai.Actions = []*AIAction{} atkPath := floor.CurrentFloor.LongestLegalPath(floor.CurrentFloor.Line(orig, targets[choice], 10), 10, atkCheck) if world.CoordsIn(targets[choice], atkPath) { switch ai.decision { case 0: // bombard var best []world.Coords pts := -3 n := world.RandomizeList(targets[choice].Neighbors()) if len(n) > 1 { for _, c := range n { tpts := 0 if cha := floor.CurrentFloor.Get(c).GetOccupant(); cha != nil { if cha.Diplomacy == floor.Ally { tpts += 1 } else { tpts -= 1 } } next := world.NextHexRot(c, targets[choice], true) if cha := floor.CurrentFloor.Get(next).GetOccupant(); cha != nil { if cha.Diplomacy == floor.Ally { tpts += 1 } else { tpts -= 1 } } if tpts > pts || len(best) == 0 { best = []world.Coords{c, next} pts = tpts } } ai.currValues.Damage = 2 ai.Actions = append(ai.Actions, &AIAction{ Path: []world.Coords{orig, targets[choice]}, PathCheck: atkCheck, TargetArea: append([]world.Coords{targets[choice]}, best...), TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTargetEffect{ Center: true, }, ai.currValues), }) ai.atkCnt += 1 } case 1: // scatter shot atkCheck.Orig = targets[choice] s, _ := world.Remove(targets[choice], floor.CurrentFloor.AllWithin(targets[choice], 2, atkCheck)) n := world.RandomizeList(s) count := len(n) / 3 if count > 3 { count = 3 } var hits []world.Coords for i := 0; i < count; i++ { hits = append(hits, n[rand.Intn(len(n)-1)]) } ai.currValues.Damage = 2 ai.Actions = append(ai.Actions, &AIAction{ Path: []world.Coords{orig, targets[choice]}, PathCheck: atkCheck, TargetArea: append([]world.Coords{targets[choice]}, hits...), TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTargetEffect{}, ai.currValues), }) ai.atkCnt += 1 } } path, _, legal := floor.CurrentFloor.FindPathPerpendicularTo(orig, targets[choice], 3, 10, movCheck, atkCheck) if legal { ai.Actions = append(ai.Actions, &AIAction{ Path: path, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }) } } } func (ai *Grenadier) TakeTurn() { for i, act := range ai.TempActions { if i == 0 { AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) } else { AddToBot(actions.NewMoveSeriesAction(ai.Character, ai.Character, act.Area), act.Effect) } } } // If the player is further than 10 tiles, do nothing, maybe random walk? // If the player is between 4-10 tiles, chase player (slowly) // If the player is between 2-3 tiles, approach and whack is small area // If the player is 1 tile away, whack in 5 wide ring w/small range boost in front // Rest after 3-4 attacks type Bruiser struct { *AbstractAI atkCnt int } func NewBruiser(character *floor.Character) *AbstractAI { newAI := &AbstractAI{ Character: character, decision: -1, currValues: selector.ActionValues{ Source: character, }, } bruiser := &Bruiser{ newAI, 0, } newAI.AI = bruiser return newAI } func (ai *Bruiser) Decide() { b := rand.Intn(2) if ai.atkCnt > 3+b { ai.atkCnt = 0 return } orig := ai.Character.Coords movCheck := floor.PathChecks{ NotFilled: true, Unoccupied: true, NonEmpty: true, EndUnoccupied: true, HonorClaim: true, Orig: orig, } atkCheck := floor.PathChecks{ NotFilled: true, Unoccupied: false, NonEmpty: false, EndUnoccupied: false, Orig: orig, } targets := floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 1) if len(targets) > 0 { ai.decision = 1 choice := 0 if len(targets) > 1 { choice = rand.Intn(len(targets)) } ai.Actions = []*AIAction{} area := []world.Coords{orig} n1, _ := world.Remove(world.NextHexLine(targets[choice], orig), world.OrderByDist(targets[choice], orig.Neighbors())) n2 := targets[choice].Neighbors() area = world.Combine(area, world.Combine(n1, n2)) if world.CoordsIn(targets[choice], area) { ai.currValues.Damage = 4 ai.Actions = append(ai.Actions, &AIAction{ Path: []world.Coords{orig}, PathCheck: atkCheck, TargetArea: area, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTriangleEffect{}, ai.currValues), }) ai.atkCnt++ } return } targets = floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 3) if len(targets) > 0 { ai.decision = 2 choice := 0 if len(targets) > 1 { choice = rand.Intn(len(targets)) } if path, d, legal := floor.CurrentFloor.FindPathWithinOne(orig, targets[choice], movCheck); legal { if d <= 3 { ai.Actions = []*AIAction{ { Path: path, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }, } tOrig := path[len(path)-1] next := world.NextHexLine(tOrig, targets[choice]) ai.currValues.Damage = 2 ai.Actions = append(ai.Actions, &AIAction{ Path: []world.Coords{tOrig}, PathCheck: floor.NoCheck, TargetArea: []world.Coords{tOrig, targets[choice], next}, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTriangleEffect{}, ai.currValues), }) ai.atkCnt++ return } } } targets = floor.CurrentFloor.GetDiplomatic(floor.Ally, orig, 10) if len(targets) > 0 { ai.decision = 0 choice := 0 if len(targets) > 1 { choice = rand.Intn(len(targets)) } if path, _, legal := floor.CurrentFloor.FindPathWithinOne(orig, targets[choice], movCheck); legal { tPath := floor.CurrentFloor.LongestLegalPath(path, 2, movCheck) ai.Actions = append(ai.Actions, &AIAction{ Path: tPath, PathCheck: movCheck, TargetArea: nil, TargetCheck: floor.PathChecks{}, Effect: selector.NewSelectionEffect(&selector.MoveSeriesEffect{}, ai.currValues), IsMove: true, }) } } } func (ai *Bruiser) TakeTurn() { if len(ai.TempActions) > 0 { if ai.decision == 0 { act := ai.TempActions[0] AddToBot(actions.NewMoveSeriesAction(ai.Character, ai.Character, act.Area), act.Effect) } else if ai.decision == 1 { act := ai.TempActions[0] AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) } else { for i, act := range ai.TempActions { if i == 0 { AddToBot(actions.NewMoveSeriesAction(ai.Character, ai.Character, act.Area), act.Effect) } else { AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) } } } } } // Every other turn, attack each tile around the enemy type Stationary struct { *AbstractAI decision int } func NewStationary(character *floor.Character) *AbstractAI { newAI := &AbstractAI{ Character: character, currValues: selector.ActionValues{ Source: character, }, } stat := &Stationary{ newAI, 0, } newAI.AI = stat return newAI } func (ai *Stationary) Decide() { if ai.decision == 0 { orig := ai.Character.Coords atkCheck := floor.PathChecks{ NotFilled: true, Unoccupied: false, NonEmpty: false, EndUnoccupied: false, Orig: orig, } ai.currValues.Damage = 2 area := append([]world.Coords{orig}, orig.Neighbors()...) ai.Actions = []*AIAction{ { Path: []world.Coords{orig}, PathCheck: floor.NoCheck, TargetArea: area, TargetCheck: atkCheck, Effect: selector.NewSelectionEffect(&selector.AttackTriangleEffect{}, ai.currValues), }, } ai.decision = 1 } else { ai.decision = 0 } } func (ai *Stationary) TakeTurn() { if len(ai.TempActions) > 0 { act := ai.TempActions[0] AddToBot(actions.NewDamageHexAction(act.Area, ai.currValues), act.Effect) } }
Java
UTF-8
701
2.65625
3
[]
no_license
package com.zhaofan.studaydemo.enviroment; /** * @author ChengJingQiang * @copyright:2019 * @project Wepay * @date 2019/4/17 * description: */ public class Context { public static final State STATE1 = new ConcreteState1(); public static final State STATE2 = new ConcreteState2(); private State currentStates; public State getCurrentStates(){ return currentStates; } public void setCurrentStates(State currentStates){ this.currentStates = currentStates; this.currentStates.setContext(this); } public void handle1(){ this.currentStates.handle1(); } public void handle2(){ this.currentStates.handle2(); } }
Swift
UTF-8
1,376
2.703125
3
[]
no_license
// // Rainbow_GrapherTests.swift // Rainbow GrapherTests // // Created by Sylvan Martin on 10/16/21. // import XCTest @testable import Rainbow_Grapher class Rainbow_GrapherTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let (xAxis, yAxis) = (Line<CGPoint>.horizontalAxis(width: 1), Line<CGPoint>.verticalAxis(width: 1)) print("DONE INITIALIZING") for x in -10...10 { let point = CGPoint(x1: Double(x), x2: 0) assert(xAxis.contains(point)) } for y in -10...10 { let point = CGPoint(x1: 0, x2: Double(y)) assert(yAxis.contains(point)) } } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
C
UTF-8
931
2.71875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> #include <string.h> #include <time.h> #include <math.h> int msg = 0; int getCurrentTime() { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); int timeInMilliseconds = (int)(ts.tv_nsec/1000000); return timeInMilliseconds; } void Proc7(int signo, siginfo_t *siginfo, void *context) { //usleep(100000); printf("%d. PID = %d PPID = %d TIME = %i PROC4 PUT SIGUSR1\n", msg, getpid(), getppid(), getCurrentTime()); printf("%d. PID = %d PPID = %d TIME = %i PROC7 GET SIGUSR1 FROM %d\n", msg++, getpid(), getppid(), getCurrentTime(), siginfo->si_pid); usleep(100000); kill(getpid() + 1, SIGUSR1); } int main(void) { struct sigaction sa7; memset(&sa7, '\0', sizeof(sa7)); sa7.sa_sigaction = &Proc7; sa7.sa_flags = SA_SIGINFO; sigaction(SIGUSR1, &sa7, NULL); for (;;) pause(); exit(0); }
JavaScript
UTF-8
445
2.5625
3
[]
no_license
$("document").ready(function(){ $("#amount").slider({ range: true, min: 0, max: 500, values: [50, 100], slide: function(evt, elem) { $("#amtVal1").text(elem.values[0]); $("#amtVal2").text(elem.values[1]); } }); $("#amtVal1").text($("#amount").slider("values", 0)); $("#amtVal2").text($("#amount").slider("values", 1)); });
JavaScript
UTF-8
1,265
3.984375
4
[]
no_license
console.log('4-fizzbuzz-algorithms'); /* <h3>Write a function which checks given input/parameter:</h3> <ul> <li>If input/parameter is divisible by 3 print => Fizz</li> <li>If input/parameter is divisible by 5 print => Buzz</li> <li>If input/parameter is divisible by 3 or 5 print => FizzBuzz</li> <li>If input/parameter is NOT divisible by 3 or 5 print => given Input Number/Value</li> <li>If input/parameter is other than Number/Value print => 'Nan - Not a Number! Please Input Number' </li> </ul> */ function isfizzBuzz(arg){ if(typeof arg !== 'number'){ return ('Nan - Not a Number! Please Input Number'); } if((arg % 3 === 0) && (arg % 5 === 0)) { return 'FizzBuzz'; } if(arg % 3 === 0) { return 'Fizz'; } if(arg % 5 === 0) { return 'Buzz'; } else { return 'Some odd number entered: ' + arg; } } let checkFizzBuzz1 = isfizzBuzz('one'); console.log(checkFizzBuzz1); let checkFizzBuzz2 = isfizzBuzz(true); console.log(checkFizzBuzz2); let checkFizzBuzz3 = isfizzBuzz(9); console.log(checkFizzBuzz3); let checkFizzBuzz4 = isfizzBuzz(10); console.log(checkFizzBuzz4); let checkFizzBuzz5 = isfizzBuzz(30); console.log(checkFizzBuzz5); let checkFizzBuzz6 = isfizzBuzz(11); console.log(checkFizzBuzz6);
C++
UTF-8
6,115
3.234375
3
[]
no_license
#pragma once #include <cmath> #include <iostream> #include <assert.h> #include "../Utils/Random.hpp" class Vec3 { public: Vec3(): e{0, 0, 0} {} Vec3(double x, double y, double z): e{x, y, z} {} double x() const { return e[0]; } double y() const { return e[1]; } double z() const { return e[2]; } inline Vec3 operator-() const; inline Vec3& operator+=(const Vec3 &v); inline Vec3& operator-=(const Vec3 &v); inline Vec3& operator*=(double t); inline Vec3& operator*=(const Vec3 &v); inline Vec3& operator/=(double t); inline friend std::ostream& operator<<(std::ostream& os, const Vec3& v); inline Vec3 operator+(const Vec3 &v) const; inline Vec3 operator-(const Vec3 &v) const; inline Vec3 operator*(double t) const; inline Vec3 operator*(const Vec3 &v) const; inline Vec3 operator/(double t) const; inline double operator[](size_t idx) const; double mag_sq() const; double mag() const; bool near_zero() const; static Vec3 normalize(const Vec3 &v); static double dot(const Vec3 &a, const Vec3 &b); static Vec3 cross(const Vec3 &a, const Vec3 &b); static Vec3 lerp(const Vec3 &a, const Vec3 &b, double t); static Vec3 rotateX(const Vec3 &v, const Vec3 &o, double tx); static Vec3 rotateY(const Vec3 &v, const Vec3 &o, double ty); static Vec3 rotateZ(const Vec3 &v, const Vec3 &o, double tz); static Vec3 rotate(const Vec3 &v, const Vec3 &o, const Vec3 &t); static Vec3 random(); static Vec3 random(double min, double max); static Vec3 random_in_unit_sphere(); static Vec3 random_in_hemisphere(const Vec3& n); static Vec3 random_in_unit_disk(); static Vec3 random_unit_vector(); static Vec3 reflect(const Vec3& v, const Vec3& n); static Vec3 refract(const Vec3& v, const Vec3& n, double refractionRatio); public: double e[3]; }; inline Vec3 Vec3::operator-() const { return Vec3(-e[0], -e[1], -e[2]); } inline Vec3& Vec3::operator+=(const Vec3 &v) { e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2]; return *this; } inline Vec3& Vec3::operator-=(const Vec3 &v) { e[0] -= v.e[0]; e[1] -= v.e[1]; e[2] -= v.e[2]; return *this; } inline Vec3& Vec3::operator*=(double t) { e[0] *= t; e[1] *= t; e[2] *= t; return *this; } inline Vec3& Vec3::operator*=(const Vec3 &v) { e[0] *= v.e[0]; e[1] *= v.e[1]; e[2] *= v.e[2]; return *this; } inline Vec3& Vec3::operator/=(double t) { e[0] /= t; e[1] /= t; e[2] /= t; return *this; } inline std::ostream& operator<<(std::ostream& os, const Vec3& v) { os << "[ " << v.e[0] << ", " << v.e[1] << ", " << v.e[2] << " ]"; return os; } inline Vec3 Vec3::operator+(const Vec3 &v) const { return Vec3(e[0] + v.e[0], e[1] + v.e[1], e[2] + v.e[2]); } inline Vec3 Vec3::operator-(const Vec3 &v) const { return Vec3(e[0] - v.e[0], e[1] - v.e[1], e[2] - v.e[2]); } inline Vec3 Vec3::operator*(double t) const { return Vec3(e[0] * t, e[1] * t, e[2] * t); } inline Vec3 Vec3::operator*(const Vec3 &v) const { return Vec3(e[0] * v.e[0], e[1] * v.e[1], e[2] * v.e[2]); } inline Vec3 Vec3::operator/(double t) const { return Vec3(e[0] / t, e[1] / t, e[2] / t); } inline double Vec3::operator[](size_t idx) const { return e[idx]; } inline Vec3 operator*(double t, const Vec3 &v) { return v * t; } inline double Vec3::mag_sq() const { return e[0] * e[0] + e[1] * e[1] + e[2] * e[2]; } inline double Vec3::mag() const { return sqrt(mag_sq()); } inline bool Vec3::near_zero() const { return fabs(e[0]) < 1e-8 && fabs(e[1]) < 1e-8 && fabs(e[2]) < 1e-9; } inline Vec3 Vec3::normalize(const Vec3 &v) { return v / v.mag(); } inline double Vec3::dot(const Vec3 &a, const Vec3 &b) { return a.e[0] * b.e[0] + a.e[1] * b.e[1] + a.e[2] * b.e[2]; } inline Vec3 Vec3::cross(const Vec3 &a, const Vec3 &b) { return Vec3(a.e[1] * b.e[2] - a.e[2] * b.e[1], a.e[2] * b.e[0] - a.e[0] * b.e[2], a.e[0] * b.e[1] - a.e[1] * b.e[0]); } inline Vec3 Vec3::lerp(const Vec3 &a, const Vec3 &b, double t) { return (1 - t) * a + t * b; } inline Vec3 Vec3::rotateX(const Vec3 &v, const Vec3 &o, double tx) { Vec3 rotated; Vec3 vo = v - o; rotated.e[0] = vo.e[0]; rotated.e[1] = vo.e[1] * cos(tx) + vo.e[2] * sin(tx); rotated.e[2] = vo.e[2] * cos(tx) - vo.e[1] * sin(tx); return rotated + o; } inline Vec3 Vec3::rotateY(const Vec3 &v, const Vec3 &o, double ty) { Vec3 rotated; Vec3 vo = v - o; rotated.e[0] = vo.e[0] * cos(ty) - vo.e[2] * sin(ty); rotated.e[1] = vo.e[1]; rotated.e[2] = vo.e[2] * cos(ty) + vo.e[0] * sin(ty); return rotated + o; } inline Vec3 Vec3::rotateZ(const Vec3 &v, const Vec3 &o, double tz) { Vec3 rotated; Vec3 vo = v - o; rotated.e[0] = vo.e[0] * cos(tz) - vo.e[1] * sin(tz); rotated.e[1] = vo.e[1] * cos(tz) + vo.e[0] * sin(tz); rotated.e[2] = vo.e[2]; return rotated + o; } inline Vec3 Vec3::rotate(const Vec3 &v, const Vec3 &o, const Vec3 &t) { return Vec3::rotateZ(Vec3::rotateY(Vec3::rotateX(v, o, t.e[0]), o, t.e[1]), o, t.e[2]); } inline Vec3 Vec3::random() { return Vec3(random_double(), random_double(), random_double()); } inline Vec3 Vec3::random(double min, double max) { return Vec3(random_double(min, max), random_double(min, max), random_double(min, max)); } inline Vec3 Vec3::random_in_unit_sphere() { while (true) { Vec3 p = Vec3::random(-1, 1); if (p.mag_sq() >= 1) continue; return p; } } inline Vec3 Vec3::random_in_hemisphere(const Vec3& n) { Vec3 inUnitSphere = Vec3::random_in_unit_sphere(); return Vec3::dot(inUnitSphere, n) > 0.0 ? inUnitSphere : -inUnitSphere; } inline Vec3 Vec3::random_in_unit_disk() { while (true) { Vec3 p = Vec3(random_double(-1, 1), random_double(-1, 1), 0); if (p.mag_sq() >= 1) continue; return p; } } inline Vec3 Vec3::random_unit_vector() { return Vec3::normalize(Vec3::random_in_unit_sphere()); } inline Vec3 Vec3::reflect(const Vec3& v, const Vec3& n) { return v - 2 * Vec3::dot(v, n) * n; } inline Vec3 Vec3::refract(const Vec3& v, const Vec3& n, double refractionRatio) { auto cosT = fmin(Vec3::dot(-v, n), 1.0); Vec3 rOutY = refractionRatio * (v + cosT * n); Vec3 rOutX = -sqrt(fabs(1.0 - rOutY.mag_sq())) * n; return rOutX + rOutY; }
Java
UTF-8
286
2.921875
3
[]
no_license
public class TestRegEx { public static void main(String args[]){ String data = "boo1. and2. foo3"; String[] tokens = data.split("\\.\\S*"); for(String s: tokens){ System.out.println(s); } System.out.format("Pi is approximately %f", Math.PI); } }
Python
UTF-8
3,450
4.0625
4
[]
no_license
""" For this activity I'm going to use DFS because DFS goes to the children before goes to the neighbors """ from util import Stack, Queue # These may come in handy class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex_id): """ Add a vertex to the graph. """ # TODO self.vertices[vertex_id]=set() def add_edge(self, v1, v2): """ Add a directed edge to the graph. """ # TODO if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) else: raise ValueError('Error') def get_neighbors(self, vertex_id): """ Get all neighbors (edges) of a vertex. """ # TODO return self.vertices[vertex_id] def earliest_ancestor(ancestors, starting_node): """ Write a function that: Given the dataset and the ID of an individual in the dataset, returns their earliest known ancestor – the one at the farthest distance from the input individual. If there is more than one ancestor tied for "earliest", return the one with the lowest numeric ID. If the input individual has no parents, the function should return -1. Test ancestors is list of pair test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)] input: (earliest_ancestor(test_ancestors, 1) """ # Instantiate my graph graph = Graph() for (parent,child) in ancestors: print('ancestor',(parent,child) ) # each element has a pair , add those elements to the vertex graph.add_vertex(parent) graph.add_vertex(child) # child to parent for (parent, child) in ancestors: # Add edges graph.add_edge(child, parent) # Create an empty stack stack = Stack() # Put the starting point in the stack stack.push([starting_node]) # Make a set to keep track of vertices visited visited = set() earliest_ancestor_path = [starting_node] print('long0',earliest_ancestor_path) while stack.size() > 0: #pop first item path = stack.pop() vertex = path[-1] if vertex not in visited: print('vertex',vertex) visited.add(vertex) print('visited',visited) print('long1',earliest_ancestor_path) print('get neighbors',graph.get_neighbors(vertex)) for deep_vertex in graph.get_neighbors(vertex): print('entre') new_path = path.copy() new_path.append(deep_vertex) print('new_path',new_path) stack.push(new_path) if len(earliest_ancestor_path) < len(new_path): earliest_ancestor_path = new_path if len(earliest_ancestor_path) == len(new_path) and earliest_ancestor_path[-1] != new_path[-1]: earliest_ancestor_path = new_path if earliest_ancestor_path[-1] == starting_node: return -1 else: return earliest_ancestor_path[-1] # test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)] # print(earliest_ancestor(test_ancestors, 3))
Python
UTF-8
415
3.46875
3
[]
no_license
male = [ #en lista med mansnamn " Erik ", " Lars ", " Karl ", " Anders ", " Johan " ] female = [ #en lista med flicknamn " Maria ", " Anna ", " Margareta ", " Elisabeth ", "Eva" ] del male[2] del male[2] del male[2] del female[0] del female[0] del female[1] #raderar de mans och kvinnonamnen som skulle bort print ("Män:", male ) print ("Kvinnor:", female ) #skriver ut vilka namn som finns kvar i listorna
JavaScript
UTF-8
4,006
2.609375
3
[]
no_license
var refreshRate = 45; var gravity = 10 / refreshRate; var canvas = document.getElementById('HTMLCanvas'); var context = canvas.getContext('2d'); var scene = { balls: [], lines: [], droppers: [] }; function display() { display_clear(); var dead = []; var i; for (i=scene.balls.length-1; i>=0; i--) { scene.balls[i].update(); if (scene.balls[i].isNowDead(scene)) { dead[dead.length] = i; continue; } scene.balls[i].applyGravity(); scene.balls[i].draw(context); } for (i=dead.length-1; i>0; i--) { scene.balls.splice(dead[i],1); } for (i=scene.droppers.length-1; i>=0; i--) { scene.droppers[i].draw(context); } for (i=scene.lines.length-1; i>=0; i--) { scene.lines[i].draw(context); } hittest(); setTimeout(display, refreshRate); } function display_clear() { context.clearRect(0, 0, canvas.width, canvas.height); context.fillStyle='#fff'; context.fillRect(0, 0, canvas.width, canvas.height); } function hittest() { var i,j; for (i=scene.balls.length-1; i>=0; i--) { for (j=scene.lines.length-1; j>=0; j--) { if (scene.balls[i].intersects(scene.lines[j])) { scene.balls[i].bounceOffLine(scene.lines[j]); scene.lines[j].ding(); } } } } var lineStart = false; var lineMove = null; var droppedPoint = {}; var lineHalfx, lineHalfy; function init() { var thickness = 10; //test thickness setTimeout(display, refreshRate); scene.width = canvas.width; scene.height = canvas.height; scene.droppers[scene.droppers.length] = new Dropper(150, 150, 1000, scene); document.oncontextmenu = function () {return false;}; document.onmouseup = function (e) { if (e.button==2) scene.droppers[scene.droppers.length] = new Dropper(e.pageX - 10, e.pageY - 10, 500, scene); else if (e.button==0) { if (lineStart) { if (Math.pow(lineHalfx - e.pageX, 2) + Math.pow(lineHalfy - e.pageY, 2) > Math.pow(thickness, 2)) { scene.lines[scene.lines.length] = new Line(lineHalfx, lineHalfy, e.pageX, e.pageY); scene.lines[scene.lines.length-1].ding(); } lineStart = false; } else if (lineMove != null) { var xMove = droppedPoint['x'] - e.pageX; var yMove = droppedPoint['y'] - e.pageY; xMove = Math.abs(xMove) > thickness ? xMove : 0; yMove = Math.abs(yMove) > thickness ? yMove : 0; lineMove.x1 -= xMove; lineMove.x2 -= xMove; lineMove.y1 -= yMove; lineMove.y2 -= yMove; lineMove.recompute(); lineMove.color = lineMove.BASE_COLOR; lineMove = null; } else { lineHalfx = e.pageX; lineHalfy = e.pageY; lineStart = true; } } }; document.onmousedown = function(e) { if (e.button == 0 && !lineStart) { for (var i = 0; i < scene.lines.length; i++) { if (intersects(e.pageX, e.pageY, scene.lines[i], thickness)) { droppedPoint['x'] = e.pageX; droppedPoint['y'] = e.pageY; lineMove = scene.lines[i]; lineMove.color = '#B0171F'; return; } } } } document.ondblclick = function(e) { lineStart = false; lineMove = null; dead = []; for (var i = 0; i < scene.lines.length; i++) { if (intersects(e.pageX, e.pageY, scene.lines[i], thickness)) { dead[dead.length] = i; } } for (var i = dead.length-1; i >= 0; i--) { scene.lines.splice(dead[i], 1); } } } init();
Python
UTF-8
1,274
3.484375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 """ Author : Maxpayyne Date : 2020-02-28 Purpose: Hamming Assignment """ import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description="", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( "file", help="Input file", metavar="FILE", type=argparse.FileType("r"), default=None, ) parser.add_argument( "-m", "--min", help="A named integer argument", metavar="int", type=int, default="0", ) return parser.parse_args() # -------------------------------------------------- def main(): """This is tacky""" args = get_args() for line in args.file: word1, word = line.split() line_no = abs(len(word1) - len(word)) char = list(zip(word1, word)) dist = 0 for pre, post in char: if pre != post: dist += 1 tot_num = line_no + dist if tot_num >= args.min: print(f"{tot_num:8}:{word1:20}{word:20}") # -------------------------------------------------- if __name__ == "__main__": main()
Java
UTF-8
20,403
1.898438
2
[]
no_license
package com.yidu.sevensecondmall.utils; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.support.v4.content.FileProvider; import android.text.TextUtils; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.yidu.sevensecondmall.R; import com.yidu.sevensecondmall.SevenSecondApplication; import com.yidu.sevensecondmall.views.widget.DensityUtils; import com.yidu.sevensecondmall.views.widget.tagview.FlowLayout; import net.qiujuer.genius.kit.handler.Run; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Created by Administrator on 2017/4/7. * view工具 */ public class ViewUtils { //截屏函数 public static File CutSreen(View v,Context context){ View view = v.getRootView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); //测一下 int currentVersion = Build.VERSION.SDK_INT; File dir = new File(Environment.getExternalStorageDirectory() + "/my_image/"); if (!dir.exists()) dir.mkdirs(); File file = new File(dir,System.currentTimeMillis() + ".jpg"); Uri uri; // if(currentVersion >24){ // context.getExternalCacheDir(); // uri = FileProvider.getUriForFile(context, "com.yidu.sevensecondmall.fileprovider", file); // }else { uri = Uri.fromFile(file); // } writeToFile(bitmap,uri); return file; } public static void writeToFile(Bitmap bitmap, Uri imageUri) { if (bitmap == null) return; File file = new File(imageUri.getPath()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(bos.toByteArray()); bos.flush(); fos.flush(); } catch (java.io.IOException e) { e.printStackTrace(); } finally { if (fos != null) try { fos.close(); if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } } } // //截图分享 // public static void CutScreenShare(View v, Activity context, String text, boolean img){ // File file = CutSreen(v.getRootView(),(Context)context); //// UMImage image = new UMImage((Context)context,file); // // // } // public static void manThreadToast(final String msg){ // Run.onUiAsync(new Action() { // @Override // public void call() { // Toast.makeText(SevenSecondApplication.getInstance(),msg,Toast.LENGTH_SHORT).show(); // } // }); // // } public static void toast(String msg){ Toast.makeText(SevenSecondApplication.getInstance(),msg,Toast.LENGTH_SHORT).show(); } public static void toast(int resId){ Toast.makeText(SevenSecondApplication.getInstance(),resId,Toast.LENGTH_SHORT).show(); } public static Dialog makeDialogBottom(Context context, View view){ final Dialog dialog = new Dialog(context, R.style.DialogBottom); dialog.setCanceledOnTouchOutside(true); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); windowParams.x = 0; //window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE ); windowParams.gravity = Gravity.BOTTOM; //设置window的布局参数 window.setAttributes(windowParams); // window.setBackgroundDrawableResource(R.drawable.alert_dialog_background); // 显示的大小是contentView 的大小 dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); return dialog; } public static Dialog makeDialogCenter(Context context,View view){ final Dialog dialog = new Dialog(context, R.style.Dialog); dialog.setCanceledOnTouchOutside(true); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); int width = (int)(window.getWindowManager().getDefaultDisplay().getWidth()*0.9); windowParams.x = 0; windowParams.width = width; window.setAttributes(windowParams); // dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, // WindowManager.LayoutParams.WRAP_CONTENT); return dialog; } /** * * @param context * @param msg * @param buttonText 按钮文字,默认是"确定" * @param callback 点击确定的回掉,没有传null * @return */ public static Dialog makeAlert(Context context,String title,String msg,String buttonText,final OKButtonCallback callback){ final Dialog dialog = new Dialog(context,R.style.Dialog); if(callback == null) { dialog.setCanceledOnTouchOutside(true); }else{ dialog.setCanceledOnTouchOutside(false); } View view = View.inflate(context,R.layout.dialog_alert,null); TextView tvMsg = (TextView)view.findViewById(R.id.tv_msg); TextView tvOk = (TextView)view.findViewById(R.id.tv_ok); TextView alertTitle = (TextView) view.findViewById(R.id.alertTitle); if(title == null){ alertTitle.setVisibility(View.GONE); }else{ alertTitle.setText(title); } tvMsg.setText(msg); if(!TextUtils.isEmpty(buttonText)){ tvOk.setText(buttonText); } tvOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (callback != null) { callback.onPositive(dialog); } } }); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); int width = (int)(window.getWindowManager().getDefaultDisplay().getWidth()*0.7); windowParams.x = 0; windowParams.width = width; window.setAttributes(windowParams); return dialog; } /** * * @param context * @param msg * @param positiveText 确定按钮文字,默认"确定" * @param negativeText 取消按钮文字,默认"取消" * @param callback 按钮点击回掉 * @return */ public static Dialog makeConfirm(Context context,String msg , String positiveText,String negativeText,final ButtonCallback callback){ final Dialog dialog = new Dialog(context,R.style.Dialog); dialog.setCanceledOnTouchOutside(true); View view = View.inflate(context,R.layout.dialog_confirm,null); TextView tvMsg = (TextView)view.findViewById(R.id.tv_msg); TextView tvOk = (TextView)view.findViewById(R.id.tv_ok); TextView tvCancel = (TextView)view.findViewById(R.id.tv_cancel); tvMsg.setText(msg); if(!TextUtils.isEmpty(positiveText)){ tvOk.setText(positiveText); } if(!TextUtils.isEmpty(negativeText)){ tvCancel.setText(negativeText); } tvOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(callback!=null){ callback.onPositive(dialog); } } }); tvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(callback!=null){ callback.onNegative(dialog); } } }); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); int width = (int)(window.getWindowManager().getDefaultDisplay().getWidth()*0.8); windowParams.x = 0; windowParams.width = width; window.setAttributes(windowParams); return dialog; } public static Dialog pop_img(Context context,String img_url ,final ButtonCallback callback){ final Dialog dialog = new Dialog(context,R.style.Dialog); dialog.setCanceledOnTouchOutside(true); View view = View.inflate(context,R.layout.layout_pop_image,null); ImageView imageView = (ImageView) view.findViewById(R.id.iv_instructions); ImageView iv_close = (ImageView) view.findViewById(R.id.iv_close); if(img_url != null){ imageView.setImageURI(Uri.parse(img_url)); } iv_close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(callback!=null){ callback.onNegative(dialog); } } }); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); int width = (int)(window.getWindowManager().getDefaultDisplay().getWidth()*0.8); windowParams.x = 0; windowParams.width = width; windowParams.height = FlowLayout.LayoutParams.MATCH_PARENT; window.setAttributes(windowParams); return dialog; } public static Dialog makeUpdate(Context context,String title,String msg , String positiveText,String negativeText,boolean is_must,final ButtonCallback callback){ final Dialog dialog = new Dialog(context,R.style.Dialog); if(!is_must) { dialog.setCanceledOnTouchOutside(true); }else{ dialog.setCanceledOnTouchOutside(false); } View view = View.inflate(context,R.layout.dialog_update,null); TextView tvTitle = (TextView)view.findViewById(R.id.tv_title); TextView tvMsg = (TextView)view.findViewById(R.id.tv_msg); TextView tvOk = (TextView)view.findViewById(R.id.tv_ok); TextView tvCancel = (TextView)view.findViewById(R.id.tv_cancel); tvTitle.setText(title); tvMsg.setText(msg); if(!TextUtils.isEmpty(positiveText)){ tvOk.setText(positiveText); } if(!TextUtils.isEmpty(negativeText)){ tvCancel.setText(negativeText); } tvOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(callback!=null){ callback.onPositive(dialog); } } }); tvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(callback!=null){ callback.onNegative(dialog); } } }); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); int width = (int)(window.getWindowManager().getDefaultDisplay().getWidth()*0.8); windowParams.x = 0; windowParams.width = width; window.setAttributes(windowParams); dialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){ return true; } return false; } }); return dialog; } public interface OKButtonCallback { void onPositive(Dialog d) ; } public interface ButtonCallback{ void onPositive(Dialog d); void onNegative(Dialog d); } public static Dialog makeChoice(Context context,final String[] items , final OnChoiceClickListener listener){ final Dialog dialog = new Dialog(context, R.style.DialogBottom); final int padding = DensityUtils.dip2px(context,15); dialog.setCanceledOnTouchOutside(true); View view = View.inflate(context,R.layout.dialog_choice,null); final LinearLayout llItems = (LinearLayout)view.findViewById(R.id.ll_items); TextView tvCannel = (TextView)view.findViewById(R.id.tv_cannel); if(items!=null){ for (int i = 0;i<items.length;i++){ TextView tv = new TextView(context); tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); tv.setPadding(padding,padding,padding,padding); tv.setGravity(Gravity.CENTER); tv.setText(items[i]); tv.setBackgroundResource(R.drawable.item_selector); final int index = i; tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(listener!=null){ listener.onClick(index,items[index]); } } }); llItems.addView(tv); } } tvCannel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); windowParams.x = 0; //window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE ); windowParams.gravity = Gravity.BOTTOM; //设置window的布局参数 window.setAttributes(windowParams); // window.setBackgroundDrawableResource(R.drawable.alert_dialog_background); // 显示的大小是contentView 的大小 dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); return dialog; } public interface OnChoiceClickListener{ void onClick(int index,String item); } public static void takePhoto(Context context, final TakePhotoListener listener){ final Dialog dialog = new Dialog(context, R.style.DialogBottom); dialog.setCanceledOnTouchOutside(true); View view = View.inflate(context,R.layout.dialog_choose_photo,null); TextView tvPhoto = (TextView)view.findViewById(R.id.tv_photo); TextView tvCamera = (TextView)view.findViewById(R.id.tv_camera); TextView tvCannel = (TextView)view.findViewById(R.id.tv_cannel); tvPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(listener!=null){ listener.takeByPhoto(); } } }); tvCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if(listener!=null){ listener.takeByCamera(); } } }); tvCannel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.setContentView(view); Window window = dialog.getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); windowParams.x = 0; //window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE ); windowParams.gravity = Gravity.BOTTOM; //设置window的布局参数 window.setAttributes(windowParams); // window.setBackgroundDrawableResource(R.drawable.alert_dialog_background); // 显示的大小是contentView 的大小 dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); dialog.show(); } public interface TakePhotoListener{ void takeByPhoto(); void takeByCamera(); } public interface ReportUserListener{ void select(Dialog dialog,int i); } // public static void reportUser(Context context,final ReportUserListener listener){ // final Dialog dialog = new Dialog(context, R.style.DialogBottom); // dialog.setCanceledOnTouchOutside(true); // View view = View.inflate(context,R.layout.dialog_report_user,null); // TextView zhengzhi = (TextView) view.findViewById(R.id.zhengzhi); // TextView seqing = (TextView) view.findViewById(R.id.seqing); // TextView nonage = (TextView) view.findViewById(R.id.nonage); // TextView driving = (TextView) view.findViewById(R.id.driving); // TextView other = (TextView) view.findViewById(R.id.other); // TextView cancel = (TextView) view.findViewById(R.id.cancel); // zhengzhi.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (listener!=null){ // listener.select(dialog,0); // } // } // }); // seqing.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (listener!=null){ // listener.select(dialog,1); // } // } // }); // nonage.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (listener!=null){ // listener.select(dialog,2); // } // } // }); // driving.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (listener!=null){ // listener.select(dialog,3); // } // } // }); // other.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (listener!=null){ // listener.select(dialog,4); // } // } // }); // cancel.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (listener!=null){ // dialog.dismiss(); // } // } // }); // dialog.setContentView(view); // Window window = dialog.getWindow(); // WindowManager.LayoutParams windowParams = window.getAttributes(); // windowParams.x = 0; // int width = (int) (window.getWindowManager().getDefaultDisplay().getWidth() * 0.9); // windowParams.width = width; // //window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE ); // windowParams.gravity = Gravity.BOTTOM; // //设置window的布局参数 // window.setAttributes(windowParams); // // window.setBackgroundDrawableResource(R.drawable.alert_dialog_background); // dialog.show(); // } }
Java
UTF-8
2,280
2.5
2
[ "MIT" ]
permissive
package wimf.services.jaxrs; import org.junit.Test; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat; // TODO: this doesn't work with JUnit 4 - but might potentially work with http://junit.org/junit5 public interface ValidFilterTestsMixin { String getPath(); WebTarget target(final String path); @Test default void it_returns_bad_request_for_invalid_filters() { // given the database contains 5 inspections // when get all with an improperly formatted filter final Response malformed = target(getPath()) .queryParam("limit", "5") .queryParam("offset", "0") .queryParam("filter", "grade-A") .request(MediaType.APPLICATION_JSON_TYPE) .get(); // then a 400 error is returned assertThat(malformed.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(malformed.readEntity(String.class)).contains("Malformed filter `grade-A`"); // when get all with an unknown filter final Response unknownFilter = target(getPath()) .queryParam("limit", "5") .queryParam("offset", "0") .queryParam("filter", "foo=bar") .request(MediaType.APPLICATION_JSON_TYPE) .get(); // then a 400 error is returned assertThat(unknownFilter.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(unknownFilter.readEntity(String.class)).contains("Unknown filter field `foo`"); // when get all with an invalid filter value (score must be an integer) final Response invalidValue = target(getPath()) .queryParam("limit", "5") .queryParam("offset", "0") .queryParam("filter", "score=bar") .request(MediaType.APPLICATION_JSON_TYPE) .get(); // then a 400 error is returned assertThat(invalidValue.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(invalidValue.readEntity(String.class)).contains("Invalid filter value `bar`"); } }
Java
UTF-8
888
2.359375
2
[]
no_license
package com.example.aria.commonsocialapp.base; import android.content.Context; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import java.util.List; public abstract class BasePagerAdapter<T> extends FragmentStatePagerAdapter{ protected List<T> itemList; protected Context context; public BasePagerAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; initData(); } protected abstract void initData(); @Override public int getCount() { return itemList.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return getTitle(position); } protected abstract String getTitle(int pos); }
Java
UTF-8
5,115
2.328125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sg.floorm.service; import com.sg.floorm.dao.FloorMConfigDao; import com.sg.floorm.dao.FloorMOrderDao; import com.sg.floorm.dao.FloorMPersistenceException; import com.sg.floorm.dao.FloorMProductDao; import com.sg.floorm.dao.FloorMTaxDao; import com.sg.floorm.dto.Order; import com.sg.floorm.dto.Product; import com.sg.floorm.dto.TaxRate; import java.math.BigDecimal; import static java.math.RoundingMode.HALF_UP; import java.util.List; public class FloorMServiceLayerImpl implements FloorMServiceLayer { private final FloorMOrderDao oDao; private final FloorMProductDao pDao; private final FloorMTaxDao tDao; private final FloorMConfigDao cDao; public FloorMServiceLayerImpl(FloorMOrderDao orderDao, FloorMProductDao productDao, FloorMTaxDao taxDao, FloorMConfigDao configDao) { this.oDao = orderDao; this.pDao = productDao; this.tDao = taxDao; this.cDao = configDao; } @Override public Order addOrder(Order order) { return oDao.addOrder(order); } @Override public List<Order> getOrdersByDate(String date) { return oDao.getOrdersByDate(date); } @Override public Order getOrder(int orderNum) { return oDao.getOrderByNumber(orderNum); } @Override public void readAllData() throws FloorMPersistenceException { oDao.readOData(); pDao.readPData(); tDao.readTData(); } @Override public void writeAllData() throws FloorMPersistenceException { oDao.writeOData(); } @Override public Order calcOrderNum(Order orderToAdd) { List<Order> orderList = oDao.getAllOrders(); int orderNumMax = 0; for (Order currentOrder : orderList) { if (currentOrder.getOrderNum() > orderNumMax) { orderNumMax = currentOrder.getOrderNum(); } } int orderNumQueued = orderNumMax + 1; orderToAdd.setOrderNum(orderNumQueued); return orderToAdd; } @Override public Order calcCosts(Order order) throws InvalidTaxRateException, InvalidProductException { List<Product> productList = pDao.getAllProducts(); List<TaxRate> taxStatelist = tDao.getAllTaxRates(); for (Product product : productList) { if (product.getProductType().equalsIgnoreCase(order.getProductType())){ BigDecimal materialSqFootCost = product.getMaterialSqFtCost(); materialSqFootCost = materialSqFootCost.setScale(2 , HALF_UP); order.setCostSqFt(materialSqFootCost); BigDecimal laborSqFootCost = product.getLaborSqFtCost(); laborSqFootCost = laborSqFootCost.setScale(2, HALF_UP); order.setLaborCostSqFt(laborSqFootCost); BigDecimal matCost = order.getCostSqFt().multiply(order.getArea()); matCost = matCost.setScale(2 , HALF_UP); order.setMatCost(matCost); BigDecimal labCost = order.getLaborCostSqFt().multiply(order.getArea()); labCost = labCost.setScale(2 , HALF_UP); order.setLabCost(labCost); } } for (TaxRate taxState : taxStatelist) { if (taxState.getTaxStateName().equalsIgnoreCase(order.getState())){ order.setTaxRate(taxState.getTax()); } } BigDecimal tempTotal = order.getLabCost().add(order.getMatCost()); tempTotal = tempTotal.setScale(2 , HALF_UP); BigDecimal taxRate = order.getTaxRate().divide(new BigDecimal("100")); BigDecimal tTax = tempTotal.multiply(taxRate); tTax = tTax.setScale(2 , HALF_UP); order.settTax(tTax); BigDecimal tCost = order.gettTax().add(tempTotal); tCost = tCost.setScale(2 , HALF_UP); order.settCost(tCost); return order; } @Override public Order deleteOrder(Order order, String date, int orderNum) { List<Order> ordersByDate = this.getOrdersByDate(date); Order orderToDelete = new Order(); for (Order currentOrder : ordersByDate) { if (currentOrder.getOrderNum() == orderNum) { orderToDelete = oDao.deleteOrder(order); } } return orderToDelete; } @Override public List<TaxRate> getAllTaxRates() { List<TaxRate> states = tDao.getAllTaxRates(); return states; } @Override public List<Product> getAllProducts() { List<Product> products = pDao.getAllProducts(); return products; } @Override public List<Order> getAllOrders() { return oDao.getAllOrders(); } @Override public void readConfig() throws FloorMPersistenceException { cDao.readConfig(); } @Override public String getConfig() { return cDao.getConfig(); } }
Markdown
UTF-8
13,318
2.78125
3
[]
no_license
# Vue.js - day06 ## 反馈 1. 做路由,组件一复杂起来,上上下下,上上下下查代码,晕死我了 2. 悔不该杀那华佗----------- ~~~~(>_<)~~~~ ~~~~(>_<)~~~~ ---------------头疼的要紧 3. 🐕🐕🐕🐕🐕🐕🐕🐕🐕🐕🐕🐕🐕🐕🐕 4. 路由还是有些模糊,可能是代码多了,有点懵逼 5. 每一块分开写就还好 凑一起又要配合挖坑就有点混乱 过滤器老师再讲一下 用的不习惯 6. 做得好乱呀 7. 网易云的接口数据好多 一层套一层 密密麻麻. 工作中后端给我们的也是这样的接口吗? 8. 麻烦老师细讲一下怎样区分--什么样的方法写在组件的methods中--什么样的方法是写在vue的methods中的 9. 黑色星期六,这是一个非常难受的日子,感觉脑袋一直都在转圈圈,请明天花姐带给我快乐 阿门 10. 唉..... 11. 老师 axios的post请求怎么写? 12. 花姐,我发现一个问题: 文本框第一次输入内容搜索的时候,页面可以读取到数据,也会渲染到页面上..不过再次输入内容,点击搜索,页面数据不会更新,只有刷新页面,数据才会更新,求解????? 1. create只执行了一次 13. 编程式的导航,动态路由,好模糊.........................啊~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 14. 感觉我是废了 嘤嘤嘤 15. 为什么在搜索结果里直接搜歌,搜不出来,切到播放页面,回来搜索页面又成了空白 16. 花姐,像这种长的案例可以按步骤分几个文件写麽,这样看文档的时候可以清楚的知道对应的代码 17. 就很头大 18. 1.还是要早点睡觉,上课吸收就好很多! 2.老师动态路由匹配后,组件里面就自动把路径参数添加到data的$route的params里面了,为什么呢? 1. vue-router 解析url 把url后面的值 设置给$route中的params 19. 速度太快,跟不上节奏 20. 老师,路由组件和全局组件有啥不一样吗? 为什么路由里面定义组件可以不用Vue.component来注册的? 歌词用正则改掉去掉时间好像好像可以这样写/\[\d{2}\:\d{2}\.\d{2,3}\]/ 21. 老师,那个页面只要搜了一首歌之后,在当前页面再搜第二首歌回车后就得手动刷新一遍才能发请求显示,怎么解决------老师,能否每写一个大功能,就复制一遍文件夹标注一下,写新的功能在另一个文件夹里写,只有一个文件,一起看代码,有点懵 1. watch 2. git 22. 1. 动态路由匹配不是很明白 2. 时不时报一些跨域的错误 代码里发现2个bug : 1. 接口 多个人查询同一个数据 3. bug1标题: 刷新页面歌曲列表没有清空 重现步骤: 1. a 打开页面, 输入"神话"; 2. b 按下enter键 3. c 待页面加载出结果后, 按F5刷新页面 结果: 页面歌曲列表没有清空 期望: 刷新后清空歌曲列表 4. bug2标题 : 页面无法进行多次歌曲搜索 重现步骤: 1. a 打开页面,在输入框输入"神话" 2. b 按下enter键搜索歌曲列表 3. c 待加载出歌曲列表后,搜索"我相信"歌曲 结果: 搜索歌曲"我相信", 页面没有列出对应的歌曲列表 期望: 搜索歌曲"我相信", 页面列出对应的歌曲列表 1. watch(侦听器)实现 23. 难啊难,难于上青天 24. 花姐 过滤器的主要作用是什么 他的适用场景是什么地方 25. 啥时候开始讲大项目呀 26. 苍天啊,大地啊,迷茫啊~~~~ 27. 代码冗余 我需要多看看 28. 建议老师写代码的时候,用不到的代码全删掉,注释也是,特别是复制上一份代码的时候,本来这个要讲的内容只需要用到一部分代码,那些复制过来的代码多,看起来很乱... 29. 一直报错,好烦啊,怎么做啊 30. 从歌曲播放切换到搜索结果,列表就被清空了,是进行了空搜索嘛? 1. 动态路由匹配,router-link中没有数据 ## 回顾 1. 过滤器 1. 不修改 原始数据的情况下,修改数据的显示形式 2. filters :和data,methods平级,属性名是固定的 3. 过滤器添加在filters属性的内部 ``` filters:{ formatStr(value){ 拼接,截取 return 数据 }, formatTime(value){ 返回固定值 return 数据} } ``` 2. Vue实例属性 1. data是对象 3. Vue组件属性 1. data是函数 2. template是模板,结构 3. 其他部分和Vue实例一样 4. 格式化的好习惯 1. 自己好 2. 对其他接手你工作的人也好 3. 跟利于后期维护 4. 格式化不了,有可能代码的语法有问题 ## 单文件组件 1. 后缀名是`.vue` 2. 快速生成内部三个结构 代码是`scaffold ` 3. 结构 4. 一个文件包含所有组件内容,更利于代码的拆分编码和维护 5. 今天开始写这个!! ```vue <template> <!-- 结构 --> </template> <script> // 逻辑代码 export default { } </script> <style> /* 样式 */ </style> ``` ## Vue-cli 安装 作用 1. Vue-cli 也叫 官方脚手架 2. 把xxx.vue翻译为 浏览器可以识别的内容 3. 自动浏览器刷新 4. 自动打包代码 5. 自动压缩代码 6. js高版本翻译为低版本 7. .... 安装 1. [下载](https://cli.vuejs.org/zh/guide/installation.html) 2. 打开小黑窗,执行命令`npm install -g @vue/cli` 3. 小黑窗的路径无所谓 ### 注意点 1. 第一次安装 最终提示的是add ![1562463519737](assets/1562463519737.png) 2. 安装过,重新安装 会提示updated ![1562463573516](assets/1562463573516.png) 3. 查看版本 `vue --version ` 最新版本是 3.9.2 ![1562463659453](assets/1562463659453.png) ## Vue-cli项目创建 [创建项目](https://cli.vuejs.org/zh/guide/creating-a-project.html) 项目名不要用中文 不要有大写字母 ``` vue create 项目名 ``` 执行命令之后,用默认的设置即可 ![1562464243876](assets/1562464243876.png) 等待安装成功之后 ![1562464380948](assets/1562464380948.png) 说明搞定了 ### 运行项目 1. 终端中进入项目文件夹 `cd 项目名` 2. 执行命令运行项目 `npm run serve` 3. 如下提示,说明成功了 ![1562464506880](assets/1562464506880.png) 4. 通过提示的地址访问项目 ### 注意点 1. ![1562464636844](assets/1562464636844.png) 2. 提示你速度较慢,要不要切换为一个更快的地址下载 可以输入`y`回车 ![1562464674775](assets/1562464674775.png) 创建的项目中有大量的第三方模块,git如果托管会比较消耗性能,选择`不在显示`,项目完全创建完毕之后,会忽略node的模块的, ![1562464751292](assets/1562464751292.png) 1. 网络问题导致安装失败: 1. 换个网络环境:比如手机wifi 2. npm缓存导致安装失败 1. `npm cache clean -f ` 先执行这个命令 2. 在重新创建项目 3. 电脑权限导致安装失败 1. 打开小黑窗的时候,使用管理员模式 2. 根据图中进行选择 3. ![1562464900996](assets/1562464900996.png) ![1562464946135](assets/1562464946135.png) 1. 尝试重新创建项目 换个名字试试 ![1562465019923](assets/1562465019923.png) 1. 要先cd到项目的目录下 2. 在执行`npm run serve` ## Vue-cli项目结构 ![1562465277330](assets/1562465277330.png) 1. 项目创建好之后,自动生成这个结构 2. 自动下载模块 3. 无需自己设置 ## Vue-cli项目编码位置 **src文件夹中** 1. xxx.vue中:单文件`组件` 1. template中 结构:一个根节点 2. script中:逻辑 `export default{}` 写在这个对象中 1. data是方法 3. style:样式 2. 每次写完保存,浏览器自动刷新 ### 注意点 1. 如果开启了自动保存,代码没有写完,自动保存了,报错 2. 电脑在这个阶段开始会越来越烫! 1. 可以关闭自动保存缓解一点点 2. 步骤1没用,清灰 3. 步骤2没用,拆机加散热硅脂 4. 步骤3没用,换风扇 5. 步骤4没用,搞个支架,加个散热器 6. 步骤5没用,就当一个暖宝宝!! ## Vue-cli创建项目注意 1. 执行`vue create 项目名`会创建一个和项目名同名的文件夹 2. 运行项目必须先进入文件夹`cd 项目名` 3. 运行项目的命令是`npm run serve` 4. 下载失败,项目文件夹还是存在的,重新创建项目 1. 删除文件夹,再创建 2. 根据提示进行覆盖 3. 换个名字创建(再多一个文件夹) 5. 提示![1562467222713](assets/1562467222713.png) 1. 没有 cd 进入项目中 6. 无论如何下载都成功不了 1. 可以使用别人创建好的项目 2. 装包运行,一样的! 3. `npm i`成功不了 1. `cnpm i` 2. `yarn` ## Vue-cli 代码结构 1. main.js ```js // es6中的导包的语法 // 等同于 const Vue = require('vue') import Vue from 'vue' // 等同于 const App = require('./App.vue') import App from './App.vue' // 是否打印终端的开发提示 // 提示少一些 // Vue.config.productionTip = false // true 提示多一些 // Vue.config.productionTip = true // 创建Vue实例 new Vue({ // 命中id为#app的标签 // 在 和src平级的 public下面的index.html el:"#app", // 把App这个组件渲染到#app这个vue的内部 render: h => h(App), }) // .$mount('#app') 等同于el:#app ``` 2. App.vue ```vue <template> <div id="app"> <h2 @click="sayHello">你好吗!!</h2> <p v-for="item in arr">{{item}}</p> <input type="text" v-model="food" /> <h3>{{food}}</h3> </div> </template> <script> export default { // 组件的名称,给组件起别名 // 用name命中组件 // vuechrome插件中 可以看到这个名字 // 可以不给,建议设置一下 name: "iamapp", // .vue都是组件 data() { return { arr: ["西兰花超多辣椒", "好好吃", "美味", "完美"], food: "" }; }, // 方法 methods: { sayHello() { alert("阿你很阿瑟哟,欧巴!!!"); } } }; </script> <style> h2 { background-color: hotpink; color: skyblue; border: 1px solid orange; box-shadow: 0 0 10px red; } </style> ``` 3. 编码位置,全部写到单文件组件中 ## 全局组件的注册 1. main.js中使用 2. `Vue.component('组件名',值)` 3. 所有的地方都可以用 ```js // 导入自己写的组件 import number from './components/number.vue' // 全局注册组件 Vue.component('number',number) ``` ### 注意 1. 这种用法,设置一次之后,所有的页面都可以使用,作用范围大 ## 局部组件的注册 1. 哪里用,哪里倒入 2. 导入之后,注册到内部`components`属性中 ```js // 导入 number组件 import number from './components/number.vue' export default { name: "iamapp", // 注册给当前组件组件 让他在app.vue内部可以使用 components:{ number // number:number }, ``` ### 注意 1. 不是全局使用的组件建议用局部注册,作用范围就小 ## 路由组件的注册 1. 装包 2. 导包 3. 用包即可 4. 路由可以使用单文件组件来实现 ![1562469703169](assets/1562469703169.png) ## Vue-cli项目的路由整合 1. 项目创建` vue create 项目名` 2. 运行项目` cd 项目名` `npm run serve` 3. 删除不必要的代码 1. `components/Helloworld.vue` 2. `app.vue`的所有内容 3. 页面所有内容都没有了 4. 整合路由了 1. 安装`vue-router`:`npm i vue-router` 2. main.js中导入路由 3. 必须执行`Vue.use(VueRouter)` 4. 写路由规则 1. 有组件 5. 实例化路由对象 6. 设置给顶级的Vue实例 5. 写组件 1. `components/`创建单文件组件 1. tempalte 2. script 3. style 2. 用的地方 import 即可 6. 添加路由的tab-nav和内容 1. `app.vue`的template里面 7. 添加路由规则,和导航栏 1. 规则:`main.js`中 1. routes:[] 添加对象即可 2. 同步的创建新的组件 2. 导航栏: 1. `app.vue`中 添加router-link ## Vue-cli静态资源使用 1. 静态资源直接丢到`assets/`文件夹下方即可 2. 样式导入 1. style标签中导入 ​ css原生就支持的样式导入语法 ```css /* 导入样式 */ @import url('./assets/reset.css'); ``` 2. main.js中导入样式 ```js // 导入样式 全局导入 // 只导入不适用变量保存 // import './assets/reset.css' // 导入 保存到 reset中 import reset from './assets/reset.css' ``` ## Vue-cli版本的播放器 1. 项目创建 2. cd进入文件夹 3. 运行项目 4. 删除`helloworld.vue` 5. 删除`app.vue`中的代码 6. 整合路由 1. 安装 2. 导入 3. use一下 4. 路由规则 1. 写组件 5. 实例化路由对象 6. 设置给Vue实例 7. 写tab-nav和tab-content 1. `app.vue`的template中 2. router-link 3. rotuer-view ### 结构样式整合 1. 顶级结构添加到`app.vue`中 2. 样式 拷贝到`assets`文件夹中 3. 导入样式 1. main.js中导入 2. style中导入 ## 预习 黑马买买买 黑买 准备好了静态页面及接口文档的项目 axios的抽取 ​ 原型抽取 ​ 基地址抽取`baseURL` ​ axiospost请求 演示地址 <http://111.230.232.110/>
C#
UTF-8
2,193
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace ClinicaFrba.Registro_Resultado { class ConsultasManager { public static List<Consulta> BuscarConsulta(String nombreProfesional, String apellidoProfesional, String numeroPaciente, String numeroTurno) { List<Consulta> consultas = new List<Consulta>(); Server server = Server.getInstance(); String query = "select c.id as 'idConsulta', c.fecha,t.id as 'idTurno',t.idPaciente from GESTIONAME_LAS_VACACIONES.ConsultasMedicas c join GESTIONAME_LAS_VACACIONES.Turnos t on t.id = c.idTurno join GESTIONAME_LAS_VACACIONES.Profesionales p on p.id = t.idProfesional where "; int cantParametros = 0; if (nombreProfesional != "") { query += "p.nombre like '" + nombreProfesional + "'"; cantParametros++; } if(apellidoProfesional != ""){ if(cantParametros >0 ) query += " and "; query += "p.apellido like '" + apellidoProfesional+ "'"; cantParametros++; } if(numeroTurno != ""){ if(cantParametros >0 ) query += " and "; query += "t.id = " +numeroTurno; cantParametros ++; } if(numeroPaciente != ""){ if (cantParametros > 0) query += " and "; query += "t.idPaciente = " + numeroPaciente; } query += "and CAST('" + Program.horarioSistema.ToString() + "' as datetime) > t.fecha "; SqlDataReader read = server.query(query); while (read.Read()) { Consulta con = new Consulta(); con.id = Convert.ToInt32(read["idConsulta"]); con.IdTurno = Convert.ToInt32(read["idTurno"]); con.fecha = Convert.ToDateTime(read["fecha"]); consultas.Add(con); } read.Close(); return consultas; } } }
Java
UTF-8
274
1.953125
2
[]
no_license
package com.whp.ex_0725; /** * @Author: wanghp * @Date: 2021/7/25 2:01 下午 * @Describe 1、 普通属性原子类操作,比反射块,直接操作二进制码 * @Version V1.0 */ public class VarHandleTest { public static void main(String[] args) { } }
Markdown
UTF-8
1,097
2.6875
3
[]
no_license
--- title: 'Souder 2 fils sur la carte Olimex' --- ## Matériel nécessaire * Carte Olimex A20 * 10 cm de fil de cuivre **étamé** rouge * 10 cm de fil de cuivre **étamé** noir * Fer à souder ## Assemblage 1. Repérez la face arrière de la catre Olimex. La partie arrière de la carte est la partie ou le dissipateur de chaleur n'est pas visible. Cherchez ensuite une série de 3 petits boutons poussoirs situé sur une des extrémités de la carte 2. Etamer la pastille marqué GND juste au dessous de l'interrupteur ![](_MG_5258.JPG) 3. Souder le fil noir de 10 cm sur la pastille GND ![](_MG_5259.JPG) 4. Le fil noir soudé sur la pastille GND ![](_MG_5260.JPG) 5. Souder le fil rouge de 10 cm sur le connecteur de l'interrupteur noté **PWR**. >>>>Souder le fil rouge sur le premier connecteur (+) et non le sedond (-). Vérifier que l'étain ne chevauche pas les deux soudures existantes. ![](_MG_5261.JPG) >>>> ne pas faire chauffer trop longtemps les composants de la carte. 6. Vu sur le dos de la carte avec les 2 fil rouge et noir soudé ![](_MG_5262.JPG)
Python
UTF-8
462
2.78125
3
[]
no_license
import gate_detector.number_poles as numpoles import gate_detector.two_pole_detect as twopole import cv2 import time import sys start = time.time() img = cv2.imread(sys.argv[1], 1) if numpoles.execute(img) == 2: width, coord, img = twopole.execute(img) print(width, coord) cv2.imshow("Detected", img) else: print("Not 2 Poles") end = time.time() print("You could use around " + str(int(1/(end-start))) + " FPS") cv2.waitKey(0) cv2.destroyAllWindows()
Go
UTF-8
769
3.40625
3
[]
no_license
package array import "math" /* Company: Apple(2); Google(3), Microsoft(2); Adobe(5), Facebook(2) Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] */ func findDisappearedNumbers448(nums []int) []int { res := []int{} for _, v := range nums { if newIndex := int(math.Abs(float64(v))) - 1; nums[newIndex] > 0 { nums[newIndex] *= -1 } } for i := 1; i <= len(nums); i++ { if nums[i-1] > 0 { res = append(res, i) } } return res }
JavaScript
UTF-8
2,117
2.703125
3
[]
no_license
#!/usr/bin/env node var open = require('open') var md = require('cli-md') var i = require('inquirer') var issues = require('issues-for-url') var concat = require('concat-stream') var deck = require('deck') var chalk = require('chalk') var issuePage = 'https://github.com/nodeschool/discussions/issues' var todos = deck.shuffle([ { name: 'Issues with no labels', desc: 'Add labels to this issues. They are explained here: https://github.com/nodeschool/discussions#about-labels', link: issuePage + '?q=is%3Aopen+is%3Aissue+no%3Alabel' }, { name: 'Issues with no comments', desc: 'Think of an answer for an unanswered issue.', link: issuePage + '?q=is%3Aopen+is%3Aissue+comments%3A0+' }, { name: 'Issues that `need-some-love`', desc: 'Try to think how to resolve those because they need your love!', link: issuePage + '?q=is%3Aopen+is%3Aissue+label%3Aneeds-some-love' }, { name: 'Issues that are old', desc: 'Look at some least recently updated issues and see if you can close them. Use the `probably-self-resolved` label where appropriate', link: issuePage + '?q=is%3Aopen+is%3Aissue+sort%3Acreated-asc+-label%3A%22discussion+thread%22+' } ]) var currentTodo = 0 function printTodo() { if(currentTodo === todos.length) return console.log('All done! :)') var help = todos[currentTodo] currentTodo++ console.log(md([ '# ' + help.name, help.desc, help.link].join('\n')).trim()) var question = { type: 'list', message: 'Choose an issue', name: 'issue' } issues(help.link).pipe(concat(function (issueList) { if(issueList.length === 0) return printTodo() question.choices = issueList.slice(0,5).map(function (issue) { return { name: issue.title + chalk.grey(' #' + issue.url.split('/').pop()), value: issue.url } }) question.choices.push('NEXT') question.choices.push('EXIT') i.prompt([question], function (answers) { if(answers.issue === 'NEXT') printTodo() if(answers.issue === 'EXIT') process.exit() open(answers.issue) }) })) } printTodo()
C#
UTF-8
2,106
2.796875
3
[]
no_license
using SQLite.Net.Attributes; using System; using System.ComponentModel; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; namespace List.Models { public class ListItem : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public string Id { get; set; } public string ImgPath { get; set; } public ImageSource Img { get; set; } public double Size { get; set; } public string Title { get; set; } public string Detail { get; set; } public DateTimeOffset Date { get; set; } public bool? Finish { get; set; } public ListItem(string id, ImageSource img, string imgPath, double size, string title, string detail, DateTimeOffset date) { this.Id = id== "" ? Guid.NewGuid().ToString(): id; this.Img = (img == null ? new BitmapImage(new Uri("ms-appx:///Assets\\pic1.ico")) : img); this.ImgPath = imgPath; this.Size = size; this.Date = date; this.Title = title; this.Detail = detail; this.Finish = false; } private void NotityPropertyChanged(string propertyname) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname)); } } public class ListItemDB { [PrimaryKey] public string Id { get; set; } public string ImgPath { get; set; } public double Size { get; set; } public string Title { get; set; } public string Detail { get; set; } public DateTimeOffset Date { get; set; } public bool? Finish { get; set; } public ListItemDB() { } public ListItemDB(string id, string imgPath, double size, string title, string detail, DateTimeOffset date, bool? finish) { this.Id = id; this.ImgPath = imgPath; this.Size = size; this.Date = date; this.Title = title; this.Detail = detail; this.Finish = finish; } } }
Markdown
UTF-8
1,616
2.90625
3
[]
no_license
Trip-specific Vehicle Reccomendations from Data ======================================================== author: Samadin date: 21 Septemebr 2014 Who's driving? ======================================================== You've decided to go on a road trip. You've picked out your destination. All that's left is to pick a car! But which one will you decide? - Some cars are faster than other, reducing the total transit time - time = money - However, cars have varying fuel economy - gas costs money **If only there was a tool to help you determine the most economical choice...** Our app takes care of transit time ======================================================== ##### Just enter your state of origin and destination. - The app uses the latitude and longitude of the center of each state - A drop down window allows you to choose from one of over 30 prospective rides - Using motor trend data, we estimate the transit time based specifically on the vehicles specifications (e.g. quarter mile time) - Version 0.2 will integrate fuel economy meansured in miles per gallon! Optimization Algorithm (v0.1) ======================================================== Using vehicle specs, we can come up with an efficieny of transit index. Analyzing our data with both gas prices and the value of your time in mind, we can compare this index among the 32 cars in our data set. ![plot of chunk unnamed-chunk-1](present-figure/unnamed-chunk-1.png) The top performer is the Camaro Z28 Check it out! ======================================================== Customize your experience by adding your destination
Java
UTF-8
2,416
2.640625
3
[]
no_license
package io.copart.books; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.springframework.stereotype.Service; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @Service public class BookService { private List<Book> books= new ArrayList<>( Arrays.asList( new Book("java", "java1","java.com", "12", false), new Book("html", "html1","html.com", "15", false), new Book("spring", "javaspring1","javaspring.com", "22", false), new Book("jax", "uhji","springjax.com", "29", false), new Book("python", "jupiter","anaconda.com", "32", false) )); public List<Book> getAllBooks(String column,String sort) { if (sort.equals("desc") ) { if(column.equals("author") ) { Collections.sort(books, Book.COMPARE_BY_AUTHOR_DESC); } else if(column.equals("cost") ) { Collections.sort(books, Book.COMPARE_BY_COST_DESC); } else if(column.equals("bookurl") ) { Collections.sort(books, Book.COMPARE_BY_BOOKURL_DESC); } else { Collections.sort(books, Book.COMPARE_BY_TITLE_DESC); } } else { if(column.equals("author") ) { Collections.sort(books, Book.COMPARE_BY_AUTHOR); } else if(column.equals("cost") ) { Collections.sort(books, Book.COMPARE_BY_COST); } else if(column.equals("bookurl") ) { Collections.sort(books, Book.COMPARE_BY_BOOKURL); } else { Collections.sort(books, Book.COMPARE_BY_TITLE); } } // String json_string = new Gson().toJson(books); // return toPrettyFormat(json_string); // //Collections.sort(books,Collections.reverseOrder()); return books; } // public static String toPrettyFormat(String jsonString) // { // JsonParser parser = new JsonParser(); // JsonObject json = parser.parse(jsonString).getAsJsonObject(); // // Gson gson = new GsonBuilder().setPrettyPrinting().create(); // String prettyJson = gson.toJson(json); // // System.out.println(json); // System.out.println(prettyJson); // return prettyJson; // } public Book getBook(String title){ return books.stream().filter(t -> t.getTitle().equals(title)).findFirst().get(); } public void addBook(Book book) { books.add(book); } }
Java
UTF-8
1,851
1.953125
2
[]
no_license
package com.xht.android.serverhelp; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.xht.android.serverhelp.model.PersonBean; import com.xht.android.serverhelp.view.ClearEditText; import java.util.ArrayList; import java.util.List; /** * 通讯录界面 */ public class TxlFragment extends Fragment { private static final String TAG = "TxlFragment"; private MainActivity mActivity; private ListView listview; private List<PersonBean> mTXLContacts; private TextView mCollectContacts; private TextView mClientContacts; private TextView mInsideContacts; private FrameLayout mFrameList; @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = (MainActivity) activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_txl, container, false); mCollectContacts = (TextView)view.findViewById(R.id.mCollectContacts); mClientContacts = (TextView)view.findViewById(R.id.mClientContacts); mInsideContacts = (TextView) view.findViewById(R.id.mInsideContacts); mFrameList = (FrameLayout) view.findViewById(R.id.mFrameList); return view; } @Override public void onResume() { super.onResume(); } @Override public void onDestroy() { super.onDestroy(); } }
C++
UTF-8
5,078
3.25
3
[ "BSD-2-Clause" ]
permissive
#pragma once #include "Assertions.h" #include "Types.h" namespace AK { template<typename T> class InlineLinkedList; template<typename T> class InlineLinkedListIterator { public: bool operator!=(const InlineLinkedListIterator& other) const { return m_node != other.m_node; } bool operator==(const InlineLinkedListIterator& other) const { return m_node == other.m_node; } InlineLinkedListIterator& operator++() { m_node = m_node->next(); return *this; } T& operator*() { return *m_node; } T* operator->() { return &m_node; } bool is_end() const { return !m_node; } static InlineLinkedListIterator universal_end() { return InlineLinkedListIterator(nullptr); } private: friend InlineLinkedList<T>; explicit InlineLinkedListIterator(T* node) : m_node(node) { } T* m_node; }; template<typename T> class InlineLinkedListNode { public: InlineLinkedListNode(); void set_prev(T*); void set_next(T*); T* prev() const; T* next() const; }; template<typename T> inline InlineLinkedListNode<T>::InlineLinkedListNode() { set_prev(0); set_next(0); } template<typename T> inline void InlineLinkedListNode<T>::set_prev(T* prev) { static_cast<T*>(this)->m_prev = prev; } template<typename T> inline void InlineLinkedListNode<T>::set_next(T* next) { static_cast<T*>(this)->m_next = next; } template<typename T> inline T* InlineLinkedListNode<T>::prev() const { return static_cast<const T*>(this)->m_prev; } template<typename T> inline T* InlineLinkedListNode<T>::next() const { return static_cast<const T*>(this)->m_next; } template<typename T> class InlineLinkedList { public: InlineLinkedList() {} bool is_empty() const { return !m_head; } size_t size_slow() const; void clear(); T* head() const { return m_head; } T* remove_head(); T* remove_tail(); T* tail() const { return m_tail; } void prepend(T*); void append(T*); void remove(T*); void append(InlineLinkedList<T>&); bool contains_slow(T* value) const { for (T* node = m_head; node; node = node->next()) { if (node == value) return true; } return false; } using Iterator = InlineLinkedListIterator<T>; friend Iterator; Iterator begin() { return Iterator(m_head); } Iterator end() { return Iterator::universal_end(); } using ConstIterator = InlineLinkedListIterator<const T>; friend ConstIterator; ConstIterator begin() const { return ConstIterator(m_head); } ConstIterator end() const { return ConstIterator::universal_end(); } private: T* m_head { nullptr }; T* m_tail { nullptr }; }; template<typename T> inline size_t InlineLinkedList<T>::size_slow() const { size_t size = 0; for (T* node = m_head; node; node = node->next()) ++size; return size; } template<typename T> inline void InlineLinkedList<T>::clear() { m_head = 0; m_tail = 0; } template<typename T> inline void InlineLinkedList<T>::prepend(T* node) { if (!m_head) { ASSERT(!m_tail); m_head = node; m_tail = node; node->set_prev(0); node->set_next(0); return; } ASSERT(m_tail); m_head->set_prev(node); node->set_next(m_head); node->set_prev(0); m_head = node; } template<typename T> inline void InlineLinkedList<T>::append(T* node) { if (!m_tail) { ASSERT(!m_head); m_head = node; m_tail = node; node->set_prev(0); node->set_next(0); return; } ASSERT(m_head); m_tail->set_next(node); node->set_prev(m_tail); node->set_next(0); m_tail = node; } template<typename T> inline void InlineLinkedList<T>::remove(T* node) { if (node->prev()) { ASSERT(node != m_head); node->prev()->set_next(node->next()); } else { ASSERT(node == m_head); m_head = node->next(); } if (node->next()) { ASSERT(node != m_tail); node->next()->set_prev(node->prev()); } else { ASSERT(node == m_tail); m_tail = node->prev(); } } template<typename T> inline T* InlineLinkedList<T>::remove_head() { T* node = head(); if (node) remove(node); return node; } template<typename T> inline T* InlineLinkedList<T>::remove_tail() { T* node = tail(); if (node) remove(node); return node; } template<typename T> inline void InlineLinkedList<T>::append(InlineLinkedList<T>& other) { if (!other.head()) return; if (!head()) { m_head = other.head(); m_tail = other.tail(); other.clear(); return; } ASSERT(tail()); ASSERT(other.head()); T* other_head = other.head(); T* other_tail = other.tail(); other.clear(); ASSERT(!m_tail->next()); m_tail->set_next(other_head); ASSERT(!other_head->prev()); other_head->set_prev(m_tail); m_tail = other_tail; } } using AK::InlineLinkedList; using AK::InlineLinkedListNode;
Java
UTF-8
12,366
1.5625
2
[]
no_license
package ch.hsr.ifs.sconsolidator.core.managed; import static ch.hsr.ifs.sconsolidator.core.base.utils.CollectionUtil.orderPreservingSet; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.cdt.core.CCProjectNature; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.cdtvariables.CdtVariableException; import org.eclipse.cdt.core.cdtvariables.ICdtVariableManager; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.cdt.core.settings.model.ICFolderDescription; import org.eclipse.cdt.core.settings.model.ICLanguageSetting; import org.eclipse.cdt.core.settings.model.ICLanguageSettingEntry; import org.eclipse.cdt.core.settings.model.ICProjectDescription; import org.eclipse.cdt.core.settings.model.ICSettingEntry; import org.eclipse.cdt.core.settings.model.ICSourceEntry; import org.eclipse.cdt.core.settings.model.util.CDataUtil; import org.eclipse.cdt.managedbuilder.core.BuildException; import org.eclipse.cdt.managedbuilder.core.IConfiguration; import org.eclipse.cdt.managedbuilder.core.IOption; import org.eclipse.cdt.managedbuilder.core.ITool; import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import ch.hsr.ifs.sconsolidator.core.SConsPlugin; import ch.hsr.ifs.sconsolidator.core.base.utils.PythonUtil; import ch.hsr.ifs.sconsolidator.core.base.utils.StringUtil; public class ProjectSettingsReader { private static String CPP_LINKER_ID = "cdt.managedbuild.tool.gnu.cpp.linker"; private static String C_LINKER_ID = "cdt.managedbuild.tool.gnu.c.linker"; private static String CPP_COMPILER_ID = "cdt.managedbuild.tool.gnu.cpp.compiler"; private static String C_COMPILER_ID = "cdt.managedbuild.tool.gnu.c.compiler"; private static String EMPTY_STRING = ""; private static String PROJECT_TYPE_STATIC_LIBRARY = "a"; private static String PROJECT_TYPE_SHARED_LIBRARY = "so"; private static String PROJECT_TYPE_EXECUTABLE = "exe"; private final List<ICLanguageSetting> languageSettings; private final IProject project; private final IWorkspaceRoot root; private final IConfiguration config; private boolean hasCCNature; public ProjectSettingsReader(IProject project) throws CoreException { this.project = project; languageSettings = new LinkedList<ICLanguageSetting>(); root = ResourcesPlugin.getWorkspace().getRoot(); config = getDefaultConfig(); initLanguageSettings(project); } private IConfiguration getDefaultConfig() { return ManagedBuildManager.getBuildInfo(project).getDefaultConfiguration(); } private void initLanguageSettings(IProject project) throws CoreException { ICProjectDescription prjDesc = CoreModel.getDefault().getProjectDescription(project); if (prjDesc == null) throw new IllegalArgumentException("No valid CDT project given!"); ICConfigurationDescription activeConfig = prjDesc.getActiveConfiguration(); if (activeConfig == null) throw new IllegalArgumentException("No valid active configuration found!"); String[] extensionsToInclude = getExtensionsToInclude(project); ICFolderDescription folderDesc = activeConfig.getRootFolderDescription(); for (ICLanguageSetting ls : folderDesc.getLanguageSettings()) { String[] extensions = ls.getSourceExtensions(); Arrays.sort(extensions); if (Arrays.equals(extensionsToInclude, extensions)) { languageSettings.add(ls); } } } private String[] getExtensionsToInclude(IProject project) throws CoreException { String contentType = determineContentType(project); String[] extensionsToInclude = CDataUtil.getExtensionsFromContentTypes(project, new String[] { contentType }); Arrays.sort(extensionsToInclude); return extensionsToInclude; } private String determineContentType(IProject project) throws CoreException { String contentType; if (project.hasNature(CCProjectNature.CC_NATURE_ID)) { contentType = CCorePlugin.CONTENT_TYPE_CXXSOURCE; hasCCNature = true; } else { contentType = CCorePlugin.CONTENT_TYPE_CSOURCE; hasCCNature = false; } return contentType; } public String getArtifactName() { return config.getArtifactName().equalsIgnoreCase("${ProjName}") ? project.getName() : config.getArtifactName(); } public String getProjectType() { String buildArtefactTypeId = config.getBuildArtefactType().getId(); if (buildArtefactTypeId.equals(ManagedBuildManager.BUILD_ARTEFACT_TYPE_PROPERTY_EXE)) return PROJECT_TYPE_EXECUTABLE; else if (buildArtefactTypeId.equals(ManagedBuildManager.BUILD_ARTEFACT_TYPE_PROPERTY_SHAREDLIB)) return PROJECT_TYPE_SHARED_LIBRARY; else if (buildArtefactTypeId.equals(ManagedBuildManager.BUILD_ARTEFACT_TYPE_PROPERTY_STATICLIB)) return PROJECT_TYPE_STATIC_LIBRARY; else throw new IllegalArgumentException("Project type not supported!"); } public String getDefaultConfigurationName() { return config.getName(); } public String getToolchainName() { return config.getToolChain().getName(); } public Collection<File> getIncludes() { Collection<File> paths = new LinkedList<File>(); String workspacePath = getWorkspacePath(); for (ICLanguageSetting languageSetting : languageSettings) { ICLanguageSettingEntry[] includePathSettings = languageSetting.getSettingEntries(ICSettingEntry.INCLUDE_PATH); for (ICLanguageSettingEntry e : includePathSettings) { if (!e.isBuiltIn()) { appendFile(paths, workspacePath, e); } } } return paths; } private String getWorkspacePath() { return project.getWorkspace().getRoot().getLocation().toOSString(); } public Map<String, String> getSourceDirsAndExclusionPatterns() { ICSourceEntry[] sources = config.getSourceEntries(); Map<String, String> dirsAndExclusions = new LinkedHashMap<String, String>(); for (ICSourceEntry s : sources) { String path = s.getFullPath().segmentCount() == 0 ? project.getName() : s.getFullPath().toString(); dirsAndExclusions.put(path, transformExclusionPatterns(s.getExclusionPatterns())); } return dirsAndExclusions; } private String transformExclusionPatterns(IPath[] paths) { return PythonUtil.toPythonList(Arrays.asList(paths)); } private void appendFile(Collection<File> paths, String workspacePath, ICLanguageSettingEntry includePath) { String includePathValue = includePath.getValue(); includePathValue = replaceCdtVariables(includePathValue); File path = new File(includePathValue); if ((includePath.getFlags() & ICSettingEntry.VALUE_WORKSPACE_PATH) == ICSettingEntry.VALUE_WORKSPACE_PATH) { path = new File(workspacePath, path.toString()); } IFile file = root.getFileForLocation(new Path(path.toString())); if (file != null) { path = file.getLocation().toFile(); } paths.add(path); } private String replaceCdtVariables(String pathValue) { ICdtVariableManager varManager = CCorePlugin.getDefault().getCdtVariableManager(); try { ICConfigurationDescription activeConfiguraiton = CoreModel.getDefault().getProjectDescription(project).getActiveConfiguration(); pathValue = varManager.resolveValue(pathValue, "", null, activeConfiguraiton); } catch (CdtVariableException e) { SConsPlugin.log(e); } return pathValue; } private String[] replaceAllCdtVariables(String[] paths) { String[] replacedStrings = new String[paths.length]; for (int i = 0; i < paths.length; i++) { replacedStrings[i] = replaceCdtVariables(paths[i]); } return replacedStrings; } public String getCompilerName() { for (ITool tool : config.getToolChain().getTools()) { if (isToolCompiler(tool)) return tool.getToolCommand(); } return EMPTY_STRING; } public String getCompilerCFlags() throws BuildException { return getCompilerFlags(C_COMPILER_ID); } public String getCompilerCxxFlags() throws BuildException { return getCompilerFlags(CPP_COMPILER_ID); } private String getCompilerFlags(String compiler) throws BuildException { for (ITool tool : config.getToolChain().getTools()) { if (tool.getId().startsWith(compiler)) return tool.getToolCommandFlagsString(null, null); } return EMPTY_STRING; } private boolean isToolCompiler(ITool tool) { String nature = hasCCNature ? CPP_COMPILER_ID : C_COMPILER_ID; return tool.getSuperClass().getId().startsWith(nature); } private boolean isToolLinker(ITool tool) { String linkerId = hasCCNature ? CPP_LINKER_ID : C_LINKER_ID; return tool.getSuperClass().getId().startsWith(linkerId); } public Map<String, String> getMacros() { Map<String, String> macros = new LinkedHashMap<String, String>(); for (ICLanguageSetting ls : languageSettings) { for (ICLanguageSettingEntry ms : ls.getSettingEntries(ICSettingEntry.MACRO)) { if (ms.isBuiltIn()) { continue; } macros.put(ms.getName(), ms.getValue()); } } return macros; } public String getPrebuildStep() { return config.getPrebuildStep(); } public String getPostbuildStep() { return config.getPostbuildStep(); } public String getPreannouncebuildStep() { return config.getPreannouncebuildStep(); } public String getPostannouncebuildStep() { return config.getPostannouncebuildStep(); } public Collection<String> getLibraryPaths() { return getLinkerOptionValues(IOption.LIBRARY_PATHS); } public Collection<String> getLibraries() { return getLinkerOptionValues(IOption.LIBRARIES); } private Collection<String> getLinkerOptionValues(int linkerOption) { for (ITool tool : config.getToolChain().getTools()) { if (!isToolLinker(tool)) { continue; } for (IOption o : tool.getOptions()) { try { if (o.getValueType() != linkerOption) { continue; } String[] libraries = linkerOption == IOption.LIBRARY_PATHS ? o.getLibraryPaths() : o.getLibraries(); return orderPreservingSet(replaceAllCdtVariables(libraries)); } catch (BuildException e) {} } } return Collections.emptySet(); } public String getLinkerFlags() { for (ITool t : config.getToolChain().getTools()) { if (!isToolLinker(t)) { continue; } try { Set<String> flags = orderPreservingSet(t.getOptionBySuperClassId("gnu.cpp.link.option.other").getStringListValue()); if (!flags.isEmpty()) return String.format("-Xlinker %s", StringUtil.join(flags, " -Xlinker ")); } catch (BuildException e) {} } return EMPTY_STRING; } }
JavaScript
UTF-8
3,084
2.734375
3
[ "MIT" ]
permissive
window.onload = function () { // navbar shadow on scroll window.onscroll = function () { windowOnScroll(); }; function windowOnScroll() { if ( document.body.scrollTop > 50 || document.documentElement.scrollTop > 50 ) { document.querySelector("#header-container").className = "floatingNav"; } else { document.querySelector("#header-container").className = ""; } } // dropdown menu let homeLink = document.querySelector("#home-link"); let menuButton = document.querySelector("#menu-button"); let closeButton = document.querySelector("#close-button"); let navbar = document.querySelector("#navbar"); homeLink.onclick = function () { homeOnClick(); }; menuButton.onclick = function () { menuOnClick(); }; closeButton.onclick = function () { closeOnClick(); }; function homeOnClick() { // prevent on desktop version let windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if (windowWidth >= 576) return; navbar.classList.add("navbarClosed"); navbar.classList.remove("navbarOpened"); closeButton.classList.add("hidden"); menuButton.classList.remove("hidden"); } function menuOnClick() { navbar.classList.add("navbarOpened"); navbar.classList.remove("navbarClosed"); menuButton.classList.add("hidden"); closeButton.classList.remove("hidden"); } function closeOnClick() { navbar.classList.add("navbarClosed"); navbar.classList.remove("navbarOpened"); closeButton.classList.add("hidden"); menuButton.classList.remove("hidden"); } // hide dropdown menu on link clicked let navlinks = document.querySelectorAll(".nav-link"); navlinks.forEach(function (navlink) { navlink.onclick = function () { navlinkOnClick(); }; }); function navlinkOnClick() { // prevent on desktop version let windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if (windowWidth >= 576) return; navbar.classList.add("navbarClosed"); navbar.classList.remove("navbarOpened"); closeButton.classList.add("hidden"); menuButton.classList.remove("hidden"); } // hide dropdown on desktop version // onload let windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if (windowWidth >= 576) { navbar.classList.remove("navbarClosed"); navbar.classList.remove("navbarOpened"); } // onresize window.onresize = function () { windowOnResize(); }; function windowOnResize() { let windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if (windowWidth >= 576) { navbar.classList.remove("navbarClosed"); navbar.classList.remove("navbarOpened"); } else { navbar.classList.add("navbarClosed"); closeButton.classList.add("hidden"); menuButton.classList.remove("hidden"); } } };
Java
UTF-8
1,717
3.546875
4
[]
no_license
package tech.bitboo.stone.collection; public class SinglyLinkedList<T> { private int size; public Node root; public Node tail; protected SinglyLinkedList() { root = new Node(); tail = root; } public int size() { return this.size; } public void append(T element) { Node to_append = new Node(); to_append.data = element; tail.next = to_append; tail = to_append; size++; } public T delete_first() { if (size == 0) { throw new IndexOutOfBoundsException(); } Node temp = root.next; root.next = root.next.next; size--; return temp.data; } public T delete_last() { if (size == 0) { throw new IndexOutOfBoundsException(); } Node near_last = find_near_last(); Node last = near_last.next; tail = near_last; near_last.next = null; size--; return last.data; } private Node find_near_last() { Node temp = root; while (temp.next.next != null) { temp = temp.next; } return temp; } public void reverse() { if (size > 1) { Node former = root.next; Node cur = root.next.next; while (cur != null) { Node next = cur.next; cur.next = root.next; root.next = cur; former.next = next; cur = next; } tail = former; } } class Node { T data; Node next; } }
Python
UTF-8
164
3.421875
3
[ "MIT" ]
permissive
def gcd(a, b): while a%b !=0: c = a%b a, b = b, c return b def lcm(a, b): return (a*b)//gcd(a, b) a, b = [int(x) for x in input().split()] print(lcm(a, b))
C#
UTF-8
2,684
3.1875
3
[ "MIT" ]
permissive
using System; using System.Text; namespace EventHubDemo.Sender { public class MyArgs { public MyArgs() { } public string eventHubName { get; set; } public int numberOfDevices { get; set; } public int numberOfMessages { get; set; } public int numberOfPartitions { get; set; } public int sleepSeconds { get; set; } public int iterations { get; set; } public void ParseArgs(string[] args) { if (args.Length != 6) { throw new ArgumentException("Incorrect number of arguments. Expected 6 args <eventhubname> <NumberOfDevices> <NumberOfMessagesToSend> <NumberOfPartitions> <sleepSeconds> <iterations>", args.ToString()); } else { eventHubName = args[0]; numberOfDevices = Int32.Parse(args[1]); numberOfMessages = Int32.Parse(args[2]); numberOfPartitions = Int32.Parse(args[3]); sleepSeconds = int.Parse(args[4]); iterations = int.Parse(args[5]); } } internal string GetHelp() { StringBuilder sb = new StringBuilder(); sb.AppendLine("Usage: Sender.exe EventHubName NumberOfDevices NumberOfMessagesToSend NumberOfPartitions SleepSeconds Iterations"); sb.AppendLine(); sb.AppendLine("Parameters:"); sb.AppendLine("\tEventHubName:\t\tName of the Event Hub to send messages to"); sb.AppendLine("\tNumberOfDevices:\t\tNumber of devices to simulate"); sb.AppendLine("\tNumberOfMessagesToSend:\t\tNumber of messages to send"); sb.AppendLine("\tNumberOfPartitions:\t\tNumber of Event Hub partitions"); sb.AppendLine("\tSleepSeconds:\t\tNumber of seconds to sleep between iterations (0 to send as fast as possible)"); sb.AppendLine("\tIterations:\t\tNumber of iterations (-1 to continuously send)"); sb.AppendLine(); return sb.ToString(); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine("Event Hub name: " + eventHubName); sb.AppendLine("Number of devices: " + numberOfDevices); sb.AppendLine("Number of messages: " + numberOfMessages); sb.AppendLine("Number of partitions: " + numberOfPartitions); sb.AppendLine("Seconds to sleep between iterations: " + sleepSeconds); sb.AppendLine("Number of iterations: " + iterations); return sb.ToString(); } } }
Python
UTF-8
611
3.078125
3
[]
no_license
import numpy as np fake_a_b = [3, 76] data = [[2, 81], [4, 93], [6, 91], [8, 97]] x = [i[0] for i in data] y = [i[1] for i in data] def predict(x): return fake_a_b[0] * x + fake_a_b[1] def mse(y, y_hat): return ((y - y_hat) ** 2).mean() def mse_val(predict_result, y): return mse(np.array(predict_result), np.array(y)) predict_result = [] for i in range(len(x)): predict_result.append(predict(x[i])) print('공부시간=%.f, 실제점수=%.f, 예측점수=%.f' % (x[i], y[i], predict(x[i]))) print('MSE 최종값: ' + str(mse_val(predict_result, y)))
Python
UTF-8
2,471
2.734375
3
[]
no_license
#!/usr/bin/python import mechanize from pyquery import PyQuery as pq import sys import cPickle import os import re class Database: def __init__(self, path = None): self.protocol = 2 if path is None: path = os.path.dirname(__file__) self.path = path self.scores = {} self._load() def add(self, movie, score): self.scores[movie] = score def _load(self): if not os.path.exists(self._picklepath()): self.scores = {} return fileio = file(self._picklepath(), "rb") unpickler = cPickle.Unpickler(fileio) self.scores = unpickler.load() fileio.close() def _picklepath(self): return os.path.join( self.path, 'scores.pkl') def flush(self): fileio = file(self._picklepath(), "wb") pickler = cPickle.Pickler(fileio, protocol=self.protocol) pickler.dump(self.scores) fileio.close() def movies_list(): root = "http://www.metacritic.com" path = '/browse/movies/release-date/theaters/date' all_releases_by_metascore = '/browse/dvds/release-date/available/metascore?view=condensed' req_path = root + all_releases_by_metascore browser = mechanize.Browser() response = browser.open(req_path) if response is None: print "Unable to open path %s" % req_path return None html = response.read() cache = file("response.html", "w") cache.write(html) cache.close() return pq(html) def harvest(): db = Database() movies = movies_list() for movie in movies('li.product'): movieq = pq(movie) movie = movieq('.product_title').text() scorestring = movieq('.score_wrap span.metascore').text() if scorestring is None: print "Unable to decipher score for movie '%s'" % movie continue matches = re.match( '^\w*(\d+)\w*$', scorestring ) if matches is None: print "Unable to find score for %s" % movie continue score = int( matches.group(0) ) db.add(movie, score) print "Discovered %s: %s" % (movie, score) db.flush() def persisted(): db = Database() for movie in db.scores.keys(): print "%s: %s" % (movie, db.scores[movie]) if __name__ == '__main__': # harvest() persisted()
Java
UTF-8
15,611
2.375
2
[]
no_license
import java.nio.ByteBuffer; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; public class HireMe { private static int[] b2i(byte... bytes) { int[] arr = new int[bytes.length]; for (int i = 0; i < arr.length; i++) { arr[i] = bytes[i] & 255; } return arr; } private static int[] l2i(long... longs) { int[] arr = new int[longs.length]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) longs[i]; } return arr; } private static byte[] i2b(int... ints) { byte[] b = new byte[ints.length]; for (int i = 0; i < b.length; i++) { b[i] = (byte) ints[i]; } return b; } public static byte[] sequence = i2b( 0x66,0xd5,0x4e,0x28,0x5f,0xff,0x6b,0x53,0xac,0x3b,0x34,0x14,0xb5,0x3c,0xb2,0xc6, 0xa4,0x85,0x1e,0x0d,0x86,0xc7,0x4f,0xba,0x75,0x5e,0xcb,0xc3,0x6e,0x48,0x79,0x8f ); public static final int[] conf = { 0xac, 0xd1, 0x25, 0x94, 0x1f, 0xb3, 0x33, 0x28, 0x7c, 0x2b, 0x17, 0xbc, 0xf6, 0xb0, 0x55, 0x5d, 0x8f, 0xd2, 0x48, 0xd4, 0xd3, 0x78, 0x62, 0x1a, 0x02, 0xf2, 0x01, 0xc9, 0xaa, 0xf0, 0x83, 0x71, 0x72, 0x4b, 0x6a, 0xe8, 0xe9, 0x42, 0xc0, 0x53, 0x63, 0x66, 0x13, 0x4a, 0xc1, 0x85, 0xcf, 0x0c, 0x24, 0x76, 0xa5, 0x6e, 0xd7, 0xa1, 0xec, 0xc6, 0x04, 0xc2, 0xa2, 0x5c, 0x81, 0x92, 0x6c, 0xda, 0xc6, 0x86, 0xba, 0x4d, 0x39, 0xa0, 0x0e, 0x8c, 0x8a, 0xd0, 0xfe, 0x59, 0x96, 0x49, 0xe6, 0xea, 0x69, 0x30, 0x52, 0x1c, 0xe0, 0xb2, 0x05, 0x9b, 0x10, 0x03, 0xa8, 0x64, 0x51, 0x97, 0x02, 0x09, 0x8e, 0xad, 0xf7, 0x36, 0x47, 0xab, 0xce, 0x7f, 0x56, 0xca, 0x00, 0xe3, 0xed, 0xf1, 0x38, 0xd8, 0x26, 0x1c, 0xdc, 0x35, 0x91, 0x43, 0x2c, 0x74, 0xb4, 0x61, 0x9d, 0x5e, 0xe9, 0x4c, 0xbf, 0x77, 0x16, 0x1e, 0x21, 0x1d, 0x2d, 0xa9, 0x95, 0xb8, 0xc3, 0x8d, 0xf8, 0xdb, 0x34, 0xe1, 0x84, 0xd6, 0x0b, 0x23, 0x4e, 0xff, 0x3c, 0x54, 0xa7, 0x78, 0xa4, 0x89, 0x33, 0x6d, 0xfb, 0x79, 0x27, 0xc4, 0xf9, 0x40, 0x41, 0xdf, 0xc5, 0x82, 0x93, 0xdd, 0xa6, 0xef, 0xcd, 0x8d, 0xa3, 0xae, 0x7a, 0xb6, 0x2f, 0xfd, 0xbd, 0xe5, 0x98, 0x66, 0xf3, 0x4f, 0x57, 0x88, 0x90, 0x9c, 0x0a, 0x50, 0xe7, 0x15, 0x7b, 0x58, 0xbc, 0x07, 0x68, 0x3a, 0x5f, 0xee, 0x32, 0x9f, 0xeb, 0xcc, 0x18, 0x8b, 0xe2, 0x57, 0xb7, 0x49, 0x37, 0xde, 0xf5, 0x99, 0x67, 0x5b, 0x3b, 0xbb, 0x3d, 0xb5, 0x2d, 0x19, 0x2e, 0x0d, 0x93, 0xfc, 0x7e, 0x06, 0x08, 0xbe, 0x3f, 0xd9, 0x2a, 0x70, 0x9a, 0xc8, 0x7d, 0xd8, 0x46, 0x65, 0x22, 0xf4, 0xb9, 0xa2, 0x6f, 0x12, 0x1b, 0x14, 0x45, 0xc7, 0x87, 0x31, 0x60, 0x29, 0xf7, 0x73, 0x2c, 0x97, 0x72, 0xcd, 0x89, 0xa6, 0x88, 0x4c, 0xe8, 0x83, 0xeb, 0x59, 0xca, 0x50, 0x3f, 0x27, 0x4e, 0xae, 0x43, 0xd5, 0x6e, 0xd0, 0x99, 0x7b, 0x7c, 0x40, 0x0c, 0x52, 0x86, 0xc1, 0x46, 0x12, 0x5a, 0x28, 0xa8, 0xbb, 0xcb, 0xf0, 0x11, 0x95, 0x26, 0x0d, 0x34, 0x66, 0x22, 0x18, 0x6f, 0x51, 0x9b, 0x3b, 0xda, 0xec, 0x5e, 0x00, 0x2a, 0xf5, 0x8f, 0x61, 0xba, 0x96, 0xb3, 0xd1, 0x30, 0xdc, 0x33, 0x75, 0xe9, 0x6d, 0xc8, 0xa1, 0x3a, 0x3e, 0x5f, 0x9d, 0xfd, 0xa9, 0x31, 0x9f, 0xaa, 0x85, 0x2f, 0x92, 0xaf, 0x67, 0x78, 0xa5, 0xab, 0x03, 0x21, 0x4f, 0xb9, 0xad, 0xfe, 0xf3, 0x42, 0xfc, 0x17, 0xd7, 0xee, 0xa3, 0xd8, 0x80, 0x14, 0x2e, 0xa0, 0x47, 0x55, 0xc4, 0xff, 0xe5, 0x13, 0x3f, 0x81, 0xb6, 0x7a, 0x94, 0xd0, 0xb5, 0x54, 0xbf, 0x91, 0xa7, 0x37, 0xf1, 0x6b, 0xc9, 0x1b, 0xb1, 0x3c, 0xb6, 0xd9, 0x32, 0x24, 0x8d, 0xf2, 0x82, 0xb4, 0xf9, 0xdb, 0x7d, 0x44, 0xfb, 0x1e, 0xd4, 0xea, 0x5d, 0x35, 0x69, 0x23, 0x71, 0x57, 0x01, 0x06, 0xe4, 0x55, 0x9a, 0xa4, 0x58, 0x56, 0xc7, 0x4a, 0x8c, 0x8a, 0xd6, 0x6a, 0x49, 0x70, 0xc5, 0x8e, 0x0a, 0x62, 0xdc, 0x29, 0x4b, 0x42, 0x41, 0xcb, 0x2b, 0xb7, 0xce, 0x08, 0xa1, 0x76, 0x1d, 0x1a, 0xb8, 0xe3, 0xcc, 0x7e, 0x48, 0x20, 0xe6, 0xf8, 0x45, 0x93, 0xde, 0xc3, 0x63, 0x0f, 0xb0, 0xac, 0x5c, 0xba, 0xdf, 0x07, 0x77, 0xe7, 0x4e, 0x1f, 0x28, 0x10, 0x6c, 0x59, 0xd3, 0xdd, 0x2d, 0x65, 0x39, 0xb2, 0x74, 0x84, 0x3d, 0xf4, 0xbd, 0xc7, 0x79, 0x60, 0x0b, 0x4d, 0x33, 0x36, 0x25, 0xbc, 0xe0, 0x09, 0xcf, 0x5b, 0xe2, 0x38, 0x9e, 0xc0, 0xef, 0xd2, 0x16, 0x05, 0xbe, 0x53, 0xf7, 0xc2, 0xc6, 0xa2, 0x24, 0x98, 0x1c, 0xad, 0x04 }; public static final int[][][] iconf = inverseConf(); private static int[][][] inverseConf() { int[][][] res = new int[256][2][0]; for (int i = 0; i < conf.length; i++) { res[conf[i]][i >= 256 ? 1 : 0] = arrAdd(res[conf[i]][i >= 256 ? 1 : 0], i); } return res; } public static final int[] diff = { 0xf26cb481, 0x16a5dc92, 0x3c5ba924, 0x79b65248, 0x2fc64b18, 0x615acd29, 0xc3b59a42, 0x976b2584, 0x6cf281b4, 0xa51692dc, 0x5b3c24a9, 0xb6794852, 0xc62f184b, 0x5a6129cd, 0xb5c3429a, 0x6b978425, 0xb481f26c, 0xdc9216a5, 0xa9243c5b, 0x524879b6, 0x4b182fc6, 0xcd29615a, 0x9a42c3b5, 0x2584976b, 0x81b46cf2, 0x92dca516, 0x24a95b3c, 0x4852b679, 0x184bc62f, 0x29cd5a61, 0x429ab5c3, 0x84256b97 }; public static byte[] forwardOriginal(byte[] input) { byte[] in = Arrays.copyOf(input, input.length); byte[] out = new byte[32]; for (int i = 0; i < 256; i++) { for (byte j = 0; j < 32; j++) { out[j] = i2b(conf)[in[j] & 255]; in[j] = 0; } for (byte j = 0; j < 32; j++) { for (byte k = 0; k < 32; k++) { in[j] ^= out[k] * ((diff[j] >> k) & 1); } } } for (byte i = 0; i < 16; i++) { out[i] = (byte) (conf[in[i * 2] & 255] ^ conf[(in[i * 2 + 1] & 255) + 256]); } return Arrays.copyOf(out, 16); } public static int[] beastep1(int[] input) { int[] out = new int[32]; for (int j = 0; j < 32; j++) { out[j] = conf[input[j]]; } return out; } public static Stream<int[]> beastep1Back(int[] target) { Stream<int[]> res = Stream.of(new int[0]); for (int j = 0; j < 32; j++) { final int fj = j; res = res.flatMap(a -> Arrays.stream(iconf[target[fj]][0]).mapToObj(b -> arrAdd(a, b))); } return res; } public static int[] beastep2(int[] input) { return mmul(input, diff); } public static Stream<int[]> beastep2Back(int[] target) { return Stream.of(msolve(diff, target)); } public static int[] beastep(int[] input) { return beastep2(beastep1(input)); } public static Stream<int[]> beastepBack(int[] target) { return beastep2Back(target).flatMap(HireMe::beastep1Back); } public static byte[] beast(byte[] input) { int[] in = b2i(input); for (int i = 0; i < 256; i++) { in = beastep(in); } return i2b(in); } public static Stream<byte[]> beastBack(byte[] target) { Stream<int[]> res = Stream.of(b2i(target)); for (int i = 0; i < 256; i++) { res = res.flatMap(HireMe::beastepBack); } return res.map(HireMe::i2b); } public static byte[] beauty(byte[] input) { int[] in = b2i(input); int[] out = new int[input.length / 2]; for (int i = 0; i < out.length; i++) { out[i] = conf[in[2*i]] ^ conf[in[2*i + 1] + 256]; } return i2b(out); } public static Stream<byte[]> beautyBack(byte[] target) { int[] out = b2i(target); Stream<int[]> res = Stream.of(new int[0]); for (int i = 0; i < target.length; i++) { int fi = i; res = res.flatMap(a -> IntStream.range(0, 256) .boxed() .flatMap(j -> Arrays.stream(iconf[conf[j] ^ out[fi]][1]) .mapToObj(p -> arrAdd(a, j, p - 256)) ) ); } return res.map(HireMe::i2b); } public static byte[] forward(byte[] input) { return beauty(beast(input)); } public static Stream<byte[]> backward(byte[] target) { while (true) { return beautyBack(target).flatMap(HireMe::beastBack); } } public static void main(String[] args) throws Exception { byte[] input = sequence; byte[] target = "Hire me!!!!!!!!\0".getBytes(StandardCharsets.US_ASCII); System.out.println(); System.out.println(); System.out.println(); System.out.println(); // System.out.println(Arrays.toString(beauty(new byte[] { 'a', 'b' }))); // System.out.println(Arrays.toString(beautyBack(beauty(new byte[] { 'a', 'b' })))); try { byte[] bwdInput = backward(target).findAny().orElse(new byte[32]); System.out.println("Input: " + renderByteArr(input)); System.out.println("Backward: " + renderByteArr(bwdInput)); System.out.println("Backward forward: " + renderByteArr(forward(bwdInput))); System.out.println("Target: " + renderByteArr(target)); System.out.println(); System.out.println("Original forward: " + renderByteArr(forwardOriginal(input))); System.out.println("Forward: " + renderByteArr(forward(input))); System.out.println(); } catch (Exception e) { System.err.println("Exception occured!"); e.printStackTrace(); } renderTestI("Beastep1", HireMe::beastep1, HireMe::beastep1Back); renderTestI("Beastep2", HireMe::beastep2, HireMe::beastep2Back); renderTestI("Beastep", HireMe::beastep, HireMe::beastepBack); renderTestB("Beast", HireMe::beast, HireMe::beastBack); renderTestB("Beauty", HireMe::beauty, HireMe::beautyBack); renderTestB("Forward", HireMe::forward, HireMe::backward); System.out.println(); System.out.println(); } private static String renderByteArr(byte[] arr) throws Exception { if (arr == null) { return "null"; } CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder(); decoder.onMalformedInput(CodingErrorAction.IGNORE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .replaceWith("�"); return bytesToHex(arr) + ": " + decoder.decode(ByteBuffer.wrap(arr)).toString(); } private static void renderTestB(String name, Function<byte[], byte[]> forward, Function<byte[], Stream<byte[]>> backward) { System.out.print(name + " test: "); try { byte[] expected = forward.apply(sequence); for (byte[] arr : backward.apply(expected).limit(1000).toArray(byte[][]::new)) { byte[] fwa = forward.apply(arr); if (!Arrays.equals(expected, fwa)) { System.out.println("FAILED with wrong output! expected:\n " + renderByteArr(expected) + "\n actual:\n " + renderByteArr(fwa)); return; } } System.out.println("Success!"); } catch (Exception e) { System.out.println("FAILED with exception! " + e.getClass().getName() + " - " + e.getMessage()); } } private static void renderTestI(String name, Function<int[], int[]> forward, Function<int[], Stream<int[]>> backward) { System.out.print(name + " test: "); try { int[] expected = forward.apply(b2i(sequence)); for (int[] arr : backward.apply(expected).limit(1000).toArray(int[][]::new)) { int[] fwa = forward.apply(arr); if (!Arrays.equals(expected, fwa)) { System.out.println("FAILED with wrong output! expected:\n " + renderByteArr(i2b(expected)) + "\n actual:\n " + renderByteArr(i2b(fwa))); return; } } System.out.println("Success!"); } catch (Exception e) { System.out.println("FAILED with exception! " + e.getClass().getName() + " - " + e.getMessage()); return; } } // Thanks maybeWeCouldStealAVan and Jemenake for this snippet // https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } private static int[] mmul(int[] a, int[] matrix) { int[] res = new int[matrix.length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < a.length; j++) { res[i] ^= a[j] * ((matrix[i] >> j) & 1); } } return res; } private static int[] msolve(int[] squareMatrix, int[] b) { long[] matrix = Arrays.stream(squareMatrix).mapToLong(a -> a & (1l << 32) - 1).toArray(); int[] a = Arrays.copyOf(b, b.length); int[] p = IntStream.range(0, matrix.length).toArray(); // triangular matrix for (int i = 0; i < matrix.length; i++) { // find pivot int pivotIndex = -1; for (int j = i; j < matrix.length; j++) { if ((matrix[p[j]] >>> (matrix.length - i - 1) & 1) == 1) { pivotIndex = j; break; } } if (pivotIndex < 0) { throw new RuntimeException("Matrix not diagonalizable!"); } swap(p, i, pivotIndex); for (int j = i + 1; j < matrix.length; j++) { if ((matrix[p[j]] >>> (matrix.length - i - 1) & 1) == 1) { matrix[p[j]] ^= matrix[p[i]]; a[p[j]] ^= a[p[i]]; } } } // diagonalize for (int i = a.length - 1; i >= 0; i--) { for (int j = i - 1; j >= 0; j--) { if ((matrix[p[j]] >>> (matrix.length - i - 1) & 1) == 1) { matrix[p[j]] ^= matrix[p[i]]; a[p[j]] ^= a[p[i]]; } } } return mmul(a, l2i(mtr(matrix))); } private static long[] mtr(long[] matrix) { long[] t = new long[matrix.length]; for (int i = 0; i < t.length; i++) { for (int j = 0; j < t.length; j++) { t[j] |= (matrix[i] >>> (t.length - j - 1) & 1) << (t.length - i - 1); } } return t; } private static void swap(int[] arr, int i, int j) { int el = arr[i]; arr[i] = arr[j]; arr[j] = el; } private static int[] arrAdd(int[] arr, int... el) { int[] res = Arrays.copyOf(arr, arr.length + el.length); System.arraycopy(el, 0, res, arr.length, el.length); return res; } }
Java
UTF-8
182
1.9375
2
[]
no_license
package vn.edu.nlu.fit.model; import java.sql.Date; public class Invoice{ int Id ; String Status ; int Id_product ; double Total ; String Biller ; Date DateOfInvoice ; }
C#
UTF-8
1,436
2.78125
3
[ "MIT" ]
permissive
using System; using System.IO; using NReco.Data; namespace SqliteDemo.SqlLogging { class Program { static void Main(string[] args) { // configure ADO.NET and NReco.Data components var dbFactory = new LoggingDbFactory(Microsoft.Data.Sqlite.SqliteFactory.Instance) { LastInsertIdSelectText = "SELECT last_insert_rowid()" }; var dbCmdBuilder = new DbCommandBuilder(dbFactory); var dbConn = dbFactory.CreateConnection(); dbConn.ConnectionString = "Data Source="+Path.Combine(Directory.GetCurrentDirectory(), "northwind.db"); var dbAdapter = new DbDataAdapter(dbConn, dbCmdBuilder); // lets perform some queries to illustrate that logging works var employeesCnt = dbAdapter.Select(new Query("Employees").Select(QField.Count)).Single<int>(); dbConn.Open(); // open connection for transaction try { using (var tr = dbConn.BeginTransaction()) { dbAdapter.Transaction = tr; // some updates dbAdapter.Insert("Employees", new { EmployeeID = 1001, FirstName = "Test", LastName = "Test" }); var deleted = dbAdapter.DeleteAsync(new Query("Employees", (QField)"EmployeeID">(QConst)1000)).Result; tr.Rollback(); // do not save these changes dbAdapter.Transaction = null; // clear transaction context } } finally { dbConn.Close(); } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
C
UTF-8
834
3.8125
4
[]
no_license
/* * Preprocessor.c * * Created on: Sep 21, 2017 * Author: Assunta */ #include <stdio.h> // this works like a constant. It will set the value of PI to 3.14159265 everywhere it is used in the program. #define PI 3.14159265 //defining the macro here will make it easier to use the formula. It's like a mini-function #define AreaCircle( r ) ( PI * r * r ) #define Debug int main(int argc, char **argv) { //computing the area of a circle int Radius; printf( "Enter a radius: " ); scanf( "%d", &Radius ); //if Debug is defined above, it will run this code. #ifdef Debug printf( "The radius entered was %d\n", Radius ); #endif //using the macros here cleans up the code. double Area = AreaCircle(Radius); printf( "\nThe Area is: %f\n", Area ); return (0); }
C++
UTF-8
1,002
2.875
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <sstream> #include <vector> #include <functional> #include <cassert> namespace cmd { enum CommandPlaceHolder { cmd, path, param, value }; const char* getString(CommandPlaceHolder); class Command; struct CommandDescription { std::string name; std::string help; std::vector<CommandPlaceHolder> placeholders; std::function<Command*()> newInstanceFunc; Command* create() const; }; class Command { public: virtual ~Command() = 0; virtual std::string execute() = 0; std::string parseArguments(std::istream& stream); std::ostream& serialize(std::ostream& stream) const; inline const CommandDescription& getDescription() const { assert(m_pDescription); return *m_pDescription; } protected: virtual std::string doParseArguments(std::istream& stream); virtual std::ostream& doSerialize(std::ostream& stream) const; friend struct CommandDescription; const CommandDescription* m_pDescription; }; } // namespace cmd
Java
UTF-8
8,498
2.1875
2
[]
no_license
package ru.gekov.web; import com.fasterxml.jackson.annotation.JsonView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; import org.springframework.http.ResponseEntity; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import ru.gekov.model.Restaurant; import ru.gekov.service.RestaurantService; import ru.gekov.to.RestaurantVoteCountTo; import ru.gekov.web.json.View; import javax.validation.Valid; import java.net.URI; import java.time.LocalDate; import java.util.List; import static org.springframework.format.annotation.DateTimeFormat.*; import static org.springframework.http.MediaType.*; import static ru.gekov.util.ValidationUtil.*; @RestController @RequestMapping(RestaurantController.REST_URL) @CrossOrigin("*") public class RestaurantController { static final String REST_URL = "/restaurants"; private final Logger log = LoggerFactory.getLogger(getClass()); private final RestaurantService service; @Autowired public RestaurantController(RestaurantService restaurantService) { this.service = restaurantService; } @GetMapping(produces = APPLICATION_JSON_VALUE) public List<Restaurant> getAll() { log.info("get all restaurants"); return service.getAll(); } @GetMapping(value = "/menus", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithMenu.class) public List<Restaurant> getAllWithMenuDishes() { log.info("get all restaurants with menuDishes"); return service.getAllWithMenuDishes(); } @GetMapping(value = "/votes", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithVote.class) @Secured("ROLE_ADMIN") public List<Restaurant> getAllWithVotes() { log.info("get all restaurants with votes"); return service.getAllWithVotes(); } @GetMapping(value = "/menus-and-votes") @JsonView(View.JsonRestaurantsWithMenuAndVotes.class) @Secured("ROLE_ADMIN") public List<Restaurant> getAllWithMenuDishesAndVotes() { log.info("get all restaurants with menuDishes and votes"); return service.getAllWithMenuDishesAndVotes(); } @GetMapping(value = "/{id}", produces = APPLICATION_JSON_VALUE) public Restaurant getById(@PathVariable Integer id) { log.info("get restaurant with id={}", id); return service.get(id); } @GetMapping(value = "/{id}/menus", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithMenu.class) public Restaurant getByIdWithAllMenus(@PathVariable Integer id) { log.info("get restaurant with id={} with menuDishes", id); return service.getWithMenuDishesById(id); } @GetMapping(value = "/{id}/votes", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithVote.class) @Secured("ROLE_ADMIN") public Restaurant getByIdWithAllVotes(@PathVariable Integer id) { log.info("get restaurant with id={} with votes", id); return service.getWithVotesById(id); } @GetMapping(value = "/{id}/menus-and-votes", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithMenuAndVotes.class) @Secured("ROLE_ADMIN") public Restaurant getByIdWithMenusAndVotes(@PathVariable Integer id) { log.info("get restaurant with id={} with menus and votes", id); return service.getWithMenuDishesAndVotesById(id); } //Get restaurants (without menuDishes) that have menu for date @GetMapping(value = "/haveMenu", params = "date", produces = APPLICATION_JSON_VALUE) public List<Restaurant> getHaveMenuByDate(@RequestParam @DateTimeFormat(iso = ISO.DATE) LocalDate date) { log.info("get restaurants that have menu by date {}", date); return service.getByMenuDate(date); } @GetMapping(value = "/menus", params = "date", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithMenu.class) public List<Restaurant> getAllWithMenuByDate(@RequestParam("date") @DateTimeFormat(iso = ISO.DATE) LocalDate date) { log.info("get restaurants with menuDishes by date {}", date); return service.getWithMenuDishesByDate(date); } @GetMapping(value = "/votes", params = "date", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithVote.class) @Secured("ROLE_ADMIN") public List<Restaurant> getAllWithVotesByDate(@RequestParam("date") @DateTimeFormat(iso = ISO.DATE) LocalDate date) { log.info("get restaurants with votes by date {}", date); return service.getWithVotesByDate(date); } @GetMapping(value = "/{id}/menus", params = "date", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithMenu.class) public Restaurant getWithMenuByIdAndDate(@PathVariable("id") Integer id, @DateTimeFormat(iso = ISO.DATE) @RequestParam("date") LocalDate date) { log.info("get restaurant with id={} with menuDishes by date {}", id, date); return service.getWithMenuDishesByIdAndDate(id, date); } @GetMapping(value = "/{id}/votes", params = "date", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithVote.class) @Secured("ROLE_ADMIN") public Restaurant getWithVotesByIdAndDate(@PathVariable Integer id, @DateTimeFormat(iso = ISO.DATE) @RequestParam("date") LocalDate date) { log.info("get restaurant with id={} with votes by date {}", id, date); return service.getWithVotesByIdAndDate(id, date); } @GetMapping(value = "/{id}/menus-and-votes", params = "date", produces = APPLICATION_JSON_VALUE) @JsonView(View.JsonRestaurantsWithMenuAndVotes.class) @Secured("ROLE_ADMIN") public Restaurant getWithMenuAndVotesByIdAndDate(@PathVariable Integer id, @DateTimeFormat(iso = ISO.DATE) @RequestParam("date") LocalDate date) { log.info("get restaurant with id={} with menuDishes and votes by date {}", id, date); return service.getWithMenuDishesAndVotesByIdAndDate(id, date); } @GetMapping(value = "/{id}/votes-count", params = "date", produces = APPLICATION_JSON_VALUE) public RestaurantVoteCountTo getWithVotesCountByIdAndDate(@PathVariable Integer id, @DateTimeFormat(iso = ISO.DATE) @RequestParam("date") LocalDate date) { log.info("get restaurant with id={} with votes count by date {}", id, date); return service.getWithVotesCountByIdAndDate(id, date); } @GetMapping(value = "/votes-count", params = "date", produces = APPLICATION_JSON_VALUE) public List<RestaurantVoteCountTo> getWithVotesCountByDate(@DateTimeFormat(iso = ISO.DATE) @RequestParam("date") LocalDate date) { log.info("get restaurants with votes count by date {}", date); return service.getWithVotesCountByDate(date); } @DeleteMapping(value = "/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) @Secured("ROLE_ADMIN") public void delete(@PathVariable int id) { log.info("delete restaurant with id={}", id); service.delete(id); } @PostMapping(consumes = APPLICATION_JSON_VALUE) @Secured("ROLE_ADMIN") public ResponseEntity<Restaurant> createWithNewUri(@Valid @RequestBody Restaurant restaurant) { log.info("create {}", restaurant); checkNew(restaurant); Restaurant created = service.create(restaurant); URI newResourceUri = ServletUriComponentsBuilder .fromCurrentContextPath() .path(REST_URL + "/{id}") .buildAndExpand(created.getId()) .toUri(); return ResponseEntity.created(newResourceUri).body(created); } @PutMapping(value = "/{id}", consumes = APPLICATION_JSON_VALUE) @ResponseStatus(value = HttpStatus.NO_CONTENT) @Secured("ROLE_ADMIN") public void update(@Valid @RequestBody Restaurant restaurant, @PathVariable Integer id) { log.info("update {} with id={}", restaurant, id); assureEntityIdConsistent(restaurant, id); service.update(restaurant); } }
C++
UTF-8
806
2.59375
3
[]
no_license
#include "stdafx.h" #include "Window.h" #include "Canvas.h" CWindow::CWindow(IPainter & painter, CPictureDraft & pictureDraft) : m_painter(painter) , m_pictureDraft(pictureDraft) , m_canvas(std::make_unique<CCanvas>()) { } void CWindow::OnWindowEvent(const SDL_Event &event) { } void CWindow::OnUpdateWindow(float deltaSeconds) { SetBackgroundColor(glm::vec4(1.0, 1.0, 1.0, 1.0)); (void)deltaSeconds; } void CWindow::OnDrawWindow(const glm::ivec2 & size) { SetupView(size); m_painter.DrawPicture(m_pictureDraft, *m_canvas); } void CWindow::SetupView(const glm::ivec2 & size) { const glm::mat4 matrix = glm::ortho<float>(0, float(size.x), float(size.y), 0); glViewport(0, 0, size.x, size.y); glMatrixMode(GL_PROJECTION); glLoadMatrixf(glm::value_ptr(matrix)); glMatrixMode(GL_MODELVIEW); }
Python
UTF-8
882
3.703125
4
[]
no_license
print "1.SUM" print "2.AVG" print "X.EXIT" cho = str(raw_input('Which one did you what choice ?')) def fun_sum(): 'sum function' num1 = float(raw_input('Enter your number:')) num2 = float(raw_input('Enter your number:')) num3 = float(raw_input('Enter your number:')) num4 = float(raw_input('Enter your number:')) num5 = float(raw_input('Enter your number:')) print int(num1+num2+num3+num4+num5) def fun_ave(): 'ave_funciton' num1 = float(raw_input('Enter your number:')) num2 = float(raw_input('Enter your number:')) num3 = float(raw_input('Enter your number:')) num4 = float(raw_input('Enter your number:')) num5 = float(raw_input('Enter your number:')) print float(((num1+num2+num3+num4+num5) / 5)) if cho == str(1): fun_sum() elif cho == str(2): fun_ave() elif cho == str("X"): exit else: print 'None !'
PHP
UTF-8
8,488
2.640625
3
[]
no_license
<?php include('../database_connection.php'); include('../staff/error_array.php'); session_start(); if(isset($_POST['insert'])){ //button is pressed //---------------------end of file upload $error=0; //------------------check for errors (when button is pressed)------------------ if(!empty($_POST["staff_id"])) { $temp = $_POST["staff_id"]; $query = "SELECT DISTINCT * FROM staff WHERE staff_id = '$temp' "; $result = mysqli_query($conn, $query); if(mysqli_num_rows($result)) { $error=1; $errors['staff_id_err'] = 'Duplicate staff ID. Please leave blank or enter another one.'; } else if (!preg_match('/^[1-9][0-9]*$/', $temp)){ //if address contains non digits $errors['staff_id_err'] = 'Staff ID must contain digits only'; $error=1; } } else { $error=1; $errors['staff_id_err'] = 'Staff ID cannot be empty';} if(!empty($_POST["store_id"])) { //----------FK $temp = $_POST["store_id"]; if (!preg_match('/^[1-9][0-9]*$/', $temp)){ $errors['store_id_err'] = 'Store ID must only contain digits'; $error=1; } $query = "SELECT DISTINCT * FROM store WHERE store_id = '$temp' "; $result = mysqli_query($conn, $query); if(!mysqli_num_rows($result)) { $error=1; $errors['store_id_err'] = 'Invalid store ID'; } } else { $error=1; $errors['store_id_err'] = 'Store ID cannot be empty';} if(!empty($_POST["first_name"])) { $temp = $_POST["first_name"]; if (!preg_match('/^[a-zA-Z\s-]+$/', $temp)){ $errors['first_name_err'] = 'First name must contain only alphabets and - '; $error=1; } } else { $error=1; $errors['first_name_err'] = 'First name cannot be empty';} if(!empty($_POST["last_name"])) { $temp = $_POST["last_name"]; if (!preg_match('/^[a-zA-Z\s-]+$/', $temp)){ $errors['last_name_err'] = 'Last name must contain only alphabets and - '; $error=1; } } else { $error=1; $errors['last_name_err'] = 'Last name cannot be empty';} if(!empty($_POST["email"])) { $temp = $_POST["email"]; if (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i', $temp)){ $errors['email_err'] = 'Please enter a valid email'; $error=1; } } else { $error=1; $errors['email_err'] = 'Email cannot be empty';} if(!empty($_POST["address_id"])) { //----------FK $temp = $_POST["address_id"]; if (!preg_match('/^[1-9][0-9]*$/', $temp)){ $errors['address_id_err'] = 'Address ID must only contain digits'; $error=1; } $query = "SELECT DISTINCT * FROM address WHERE address_id = '$temp' "; $result = mysqli_query($conn, $query); if(!mysqli_num_rows($result)) { $error=1; $errors['address_id_err'] = 'Invalid address ID'; } } else { $error=1; $errors['address_id_err'] = 'Address ID cannot be empty';} if(!empty($_POST["active"])) { $temp = $_POST["active"]; if (!preg_match('/^[0-1]+$/', $temp)){ $errors['active_err'] = 'You are only allowed to select between 0 for not active and 1 for active'; $error=1; } } else { $error=1; $errors['active_err'] = 'Active column cannot be empty';} if (!empty($_POST["username"])){ $temp=$_POST["username"]; $query = "SELECT DISTINCT * FROM staff WHERE username = '$temp' "; $result = mysqli_query($conn, $query); if(mysqli_num_rows($result)) { $error=1; $errors['username_err'] = 'Duplicate username. Please pick another one.'; } else if(strlen($temp)>4){ $error=1; $errors['username_err'] = 'Username must only have a maximum of 4 characters';} } else { $error=1; $errors['username_err'] = 'Username column cannot be empty';} if (empty($_POST["password"])){ $error=1; $errors['password_err'] = 'Password cannot be empty'; } //-----------------------end error check----------------------- if($error==0){ $staff_id = "'".$_POST["staff_id"]."'"; $store_id = "'".$_POST["store_id"]."'" ; $first_name = "'".$_POST["first_name"]."'" ; $last_name = "'".$_POST["last_name"]."'" ; $email = "'".$_POST["email"]."'" ; $address_id = "'".$_POST["address_id"]."'" ; $active = "'".$_POST["active"]."'"; $_SESSION['id'] = $staff_id; $username = "'".$_POST["username"]."'"; $password = "'".$_POST["password"]."'"; $sql="INSERT INTO staff (staff_id,first_name,last_name,address_id, email,store_id,active,username,password,last_update) VALUES ($staff_id, $first_name, $last_name, $address_id, $email, $store_id, $active, $username, $password,NOW())"; try{ if(mysqli_query($conn, $sql)) { echo("<script>alert('Staff information successfully added.')</script>"); echo("<script>window.location = 'image_upload.php';</script>"); } } catch (Exception $e) { echo ("<script>alert('Staff ID value too large. Please try again.')</script>"); echo("<script>window.location = '../staff/index.php';</script>"); } } //---------------------------------------end of insert-------------------------------------- } ?> <html> <head> <link href="https://fonts.googleapis.com/css2?family=Caveat:wght@400;700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Ubuntu+Condensed&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Acme&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://hcysa2.mercury.nottingham.edu.my/hcykn3/sakila/test.css" /> <title>New Staff</title> <meta charset="utf-8"> </head> <!-- Insert --> <body class=page> <h3 align=center> New Staff </h3> <form action="../staff/insert.php" method="post" > <p> <label for="staff_id">Staff ID:</label><br> <input type="text" name="staff_id" id="staff_id" > <div class="red-text"><?php echo $errors['staff_id_err']; ?></div> </p> <p> <label for="first_name">First Name:</label><br> <input type="text" name="first_name" id="first_name"> <div class="red-text"><?php echo $errors['first_name_err']; ?></div> </p> <p> <label for="last_name">Last Name:</label><br> <input type="text" name="last_name" id="last_name" > <div class="red-text"><?php echo $errors['last_name_err']; ?></div> <p> <label for="address_id">Address ID:</label><br> <input type="text" name="address_id" id="address_id"> <div class="red-text"><?php echo $errors['address_id_err']; ?></div> </p> <p> <label for="email">Email:</label><br> <input type="text" name="email" id="email" > <div class="red-text"><?php echo $errors['email_err']; ?></div> <p> <label for="store_id">Store ID:</label><br> <input type="text" name="store_id" id="store_id" > <div class="red-text"><?php echo $errors['store_id_err']; ?></div> </p> </p> <p> <label for="active">Active:</label><br> <input type="text" name="active" id="active"> <div class="red-text"><?php echo $errors['active_err']; ?></div> </p> <p> <label for="username">Username:</label><br> <input type="text" name="username" id="username"> <div class="red-text"><?php echo $errors['username_err']; ?></div> </p> <p> <label for="password">Password:</label><br> <input type="text" name="password" id="password"> <div class="red-text"><?php echo $errors['password_err']; ?> </p> <input type="submit" name="insert"> </form> </body>
Java
ISO-8859-15
2,992
3.359375
3
[]
no_license
package no.hvl.dat102; import no.hvl.dat102.adt.*; import java.util.Scanner; public class Meny { private Tekstgrensesnitt tekstgr; private FilmarkivADT filmer; public Meny(FilmarkivADT filmer) { this.filmer = filmer; tekstgr = new Tekstgrensesnitt(); } // TODO: Tilbake i meny public void start() { System.out.println("\nVelg et alternativ:"); System.out.println("1 - Opprette nytt arkiv?"); System.out.println("2 - Jobbe med eksisterende arkiv?"); Scanner leser = new Scanner(System.in); int valg1 = Integer.parseInt(leser.nextLine()); System.out.println("Skriv filnavn for filmarkivet"); String filnavn = leser.nextLine(); // nytt arkiv if (valg1 == 1) { Fil.skrivTilFil(filmer, filnavn); System.out.println("Nytt arkiv " + "\"" + filnavn + "\"" + " opprettet."); } // valg1 == 1 // eksisterende arkiv if (valg1 == 2) { filmer = Fil.lesFraFil(filnavn); if (filmer != null) { System.out.println("Hva nsker du gjre?"); System.out.println("1 - Utfre endringer"); System.out.println("2 - Skrive ut informasjon"); int valg2 = Integer.parseInt(leser.nextLine()); // utfre endringer if (valg2 == 1) { System.out.println("Hvilken endring nsker du utfre?"); System.out.println("1 - Legg til film"); System.out.println("2 - Slett film"); int valg3 = Integer.parseInt(leser.nextLine()); if (valg3 == 1) { Film film = tekstgr.lesFilm(); filmer.leggTilFilm(film); System.out.println("Filmen er n lagt til."); Fil.skrivTilFil(filmer, filnavn); } // valg3 == 1 if (valg3 == 2) { System.out.println("Skriv inn filmnr du nsker slette:"); int filmnr = Integer.parseInt(leser.nextLine()); if (filmer.slettFilm(filmnr)) { Fil.skrivTilFil(filmer, filnavn); } else { System.out.println("Ingen film med dette nr. ble slettet."); } } // valg3 == 2 } // valg2 == 1 // skrive ut informasjon if (valg2 == 2) { System.out.println("Hvilken informasjon vil du ha?"); System.out.println("1 - Filmstatistikk"); System.out.println("2 - Sk opp tittel"); System.out.println("3 - Sk opp produsent"); int valg3 = Integer.parseInt(leser.nextLine()); // skriv ut statistikk if (valg3 == 1) { tekstgr.skrivUtStatistikk(filmer); } // sk opp tittel if (valg3 == 2) { System.out.println("Skriv inn delstreng til filmen du leter etter:"); String filmstr = leser.nextLine(); tekstgr.skrivUtFilmDelstrengITittel(filmer, filmstr); } // sk opp produsent if (valg3 == 3) { System.out.println("Skriv inn delstreng til produsenten du leter etter:"); String filmstr = leser.nextLine(); tekstgr.skrivUtFilmProdusent(filmer, filmstr); } // valg3 == 3 } // filmer != null } // valg2 == 2 } // valg1 == 1 leser.close(); } }
Markdown
UTF-8
3,037
2.6875
3
[ "MIT" ]
permissive
# Firebase IoT Demo with ESP8266 This project uses ESP8266 to read sensors, connect to Firebase and push data to Realtime Database. Temperature and Humidity data is read from DHT11 sensor, Gas leak detection is read from MQ5 Gas sensor finally device heartbeat is sent every 2 secondes to Firebase to ensure device cinnection. Note that you can simulate the sensors with random values by uncommenting 'DONT_HAVE_SENSORS' define. ## Getting Started These instructions will get you a copy of the project up and running on your ESP8266 for development and testing purposes. ### Prerequisites This project uses the Arduino framework and PlatformIO IDE for building and flashing the app into ESP8266. The data sent from the device is stored in Firebase Realtime Database. * Setup [PlatformIO](https://platformio.org/install/ide?install=vscode) extension with VSCode * Setup a new [Firebase](https://console.firebase.google.com/) project in Firebase console ### Installing Once installed PlatformIO and created firebase project, download this project ```bash git clone https://github.com/kaizoku-619/firebase-iot-demo.git ``` #### Setup credentials ```bash cd firebase-iot-demo/include ``` Inside 'include' directory create a new file named 'Creds.h' and replace with the values of your WiFi SSID, Password and Firebase host of your Firebase project and Firebase Auth which you can find them in this link by replacing [###########] with your Firebase project name. https://console.firebase.google.com/project/[###########]/settings/serviceaccounts/databasesecrets ```C #define SSID "XXXXXXXXXXX" #define PASSWORD "XXXXXXXXXXXXXXX" #define FIREBASE_HOST "XXXXXXXXXXXXX.firebaseio.com" #define FIREBASE_AUTH "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ``` #### Simulate Sensors If you don't have sensors attached to your ESP8266 or you want to quickly test the application and consult data in Firebase database without the need of attaching sensors, you can simply uncomment DONT_HAVE_SENSORS define. ```C #define DONT_HAVE_SENSORS ``` #### Update Firebase Fingerprint Build the project using PlatformIO, Once project built you'll see .piolibdeps folder created with the 3 new libraries installed: * DHT sensor library * Adafruit Unified Sensor * FirebaseArduino Open FirebaseArduino/src/FirebaseHttpClient.h and scroll to the end of the page, you'll find FirebaseFingerprint[] which its value need to be changed. To generate a fingerprint, go to this [website](https://www.grc.com/fingerprints.htm) and copy your Firebase host link without the https part (your might look something like this your-prject-name.firebaseio.com) and click on Fingerprint Site. Copy the newly generated fingerprint in the place of the FirebaseFingerprint[] value and replace the columns with spaces. Upload the code and you're good to go. ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details ## References * [Fingerprints](https://www.grc.com/fingerprints.htm) * [PlatformIO](https://platformio.org/platformio-ide)
Python
UTF-8
1,397
3.34375
3
[]
no_license
#!/usr/bin/python3 ############################################################################### # File: billtable_test.py # Author: Nate Lao (lao.nathan95@gmail.com) # Language: python3 # Description: # Unit Test for the BillTable class. ############################################################################### import sys import os sys.path.append(os.getcwd() + '/..') import random import classes_temp as classes def randomItem(): cost = random.randint(0,255) + random.uniform(0.0,1.0) quant = random.randint(0,255) return (cost,quant) # Generate random values for the table, discount rate and tax rate # Check to see if the values calculate appropriately if __name__ == "__main__": table = classes.BillTable() sum = 0 # Generate a list of random items for i in range(0,10): item = randomItem() table.add("item"+str(i),item[0],item[1]) sum += item[0]*item[1] taxRate = random.randint(0,255) + random.uniform(0.0,1.0) discountRate = random.randint(0,255) + random.uniform(0.0,1.0) taxAmount = taxRate * sum discountAmount = discountRate * sum finalAmount = sum - discountAmount + taxAmount print(str(table)) table.setDiscountRate(discountRate) table.setTaxRate(taxRate) print("Expected total balance = " + str(finalAmount)) print("Actual total balance = " + str(table.calcTotalBalance())) assert finalAmount == table.calcTotalBalance() # TODO # test remove()
C#
UTF-8
504
2.734375
3
[ "MIT" ]
permissive
using ClashSharp.Interface; using System; namespace ClashSharp.Service { public class ClanTagService : IClanTagService { public string EncodeClanTag(string clanTag) { // make sure our clan tag starts with a # if (clanTag.StartsWith("#") == false) { throw new ApplicationException("Clan tag starts with '#'"); } // encode our clanTag return clanTag.Replace("#", "%23"); } } }
Java
UTF-8
2,743
2.5625
3
[]
no_license
package com.cybertek.Day4; import com.cybertek.utilities.HRTestBase; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import javax.swing.*; import java.util.List; import static io.restassured.RestAssured.*; import static org.junit.jupiter.api.Assertions.*; public class ORDSApiTestWithPath extends HRTestBase { @DisplayName("GET request to /countries with Query Param") @Test public void test1() { Response response = given().accept(ContentType.JSON) .and().queryParam("q", "{\"region_id\":2}") .when() .get("/countries"); assertEquals(200, response.statusCode()); //print limit result System.out.println("response limit = " + response.path("limit")); System.out.println("response hasMore = " + response.path("hasMore")); //print first CountryId String firstCountryId = response.path("items[0].country_id"); System.out.println("first CountryId = " + firstCountryId); //print second country name String secondCountryName = response.path("items[1].country_name"); System.out.println("second Country name = " + secondCountryName); //print "http://3.239.15.23:1000/ords/hr/countries/CA" String hrefValue = response.path("items[2].links[0].href"); System.out.println("hrefValue = " + hrefValue); //get me all country names List<String> countryNames = response.path("items.country_name"); System.out.println("Country Names = " + countryNames); //assert that all regions ids are equal to 2 List<Integer> allRegionsIDs = response.path("items.region_id"); for (Integer regionsID : allRegionsIDs) { System.out.println("regionsID = " + regionsID); assertEquals(2, regionsID); } } @DisplayName("GET request to /employees with Query Param") @Test public void test2() { Response response = given().accept(ContentType.JSON) .and().queryParam("q", "{\"job_id\": \"IT_PROG\"}") .when().get("/employees"); assertEquals(200, response.statusCode()); assertEquals("application/json", response.header("Content-Type")); assertTrue(response.body().asString().contains("IT_PROG")); //make sure we have only IT_PROG as a job_id List<String> allJobIDs = response.path("items.job_id"); for (String jobID : allJobIDs) { System.out.println("jobID = " + jobID); assertEquals("IT_PROG", jobID); } //TASK //Print each Name of IT_PROGs } }
JavaScript
UTF-8
2,678
3.28125
3
[]
no_license
export default class AtomicType { _getString = uint8array => uint8array ? new TextDecoder().decode(uint8array) : null; _getImage = uint8array => { const blob = new Blob([uint8array], { type: "image/jpeg" }); return URL.createObjectURL(blob); }; _getBool = uint8array => !!uint8array[0]; t12ora2jsDate = uint8array => { console.log("Date array:", uint8array); return null; // let year = "" + (uint8array[0] - 100) + (uint8array[1] - 100); // let month = uint8array[2]; // let day = uint8array[3]; // let hour = uint8array[4] - 1; // let minute = uint8array[5] - 1; // let seconds = uint8array[6] - 1; //[0, 34, 121, 72, 184, 115, 216, 8] //console.log(`year: ${year}, month: ${month}, day: ${day}, hour: ${hour}, minute: ${minute}, sec: ${seconds}`); //return new Date(year, month - 1, day, hour, minute, seconds); }; _getDate = uint8array => { //console.log("Date ar:", uint8array); const to2d = (int) => int.toString().padStart(2,'0'); const h = "0x" + uint8array.reverse().reduce((acc, val) => acc + val.toString("16").padStart(2, "0"), ''); //console.log("Date hex:", h, "Date:", +h, "BIDate", window.BigInt(h)); const d = new Date((+h) / 10000 - 62135596800000); //dd.mm.yyyy hh24:mi:ss //console.log("Date:", d.toLocaleString()); return `${to2d(d.getDay())}.${to2d(d.getMonth()+1)}.${to2d(d.getFullYear())} ${to2d(d.getHours()-3)}:${to2d(d.getMinutes())}:${to2d(d.getSeconds())}`; } _AtomicTypes = { 0: { name: "string", //"Undefined", value: this._getString }, 1: { name: "string", value: this._getString }, 2: { name: "number", value: (ar) => +(this._getString(ar)) }, 3: { name: "date", value: this._getDate //(ar) => new Date(+("0x" + ar.reduce((acc, val) => acc + val.toString("16").padStart(2, "0"), '')) / 10000 - 62135596800000) }, 4: { name: "image", value: this._getImage }, 5: { name: "string", //"Custom", value: () => null }, 6: { name: "boolean", value: this._getBool } } _value = null; _type = null; constructor(type, uint8array) { try { if(type) { this._type = this._AtomicTypes[type].name; } if(uint8array.length > 0) { this._value = this._AtomicTypes[type].value(uint8array); } } catch (e){ console.error(`Error parsing type ${type}: ${e.message}`) } } getType() { return this._type; } getValue() { return this._value; } toObject() { return { type: this._type, value: this._value } } }
C++
UTF-8
1,641
2.78125
3
[ "MIT" ]
permissive
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> using namespace std; string windowIDSearch(char* input) { char* match; string winId; char* pch = strtok (input," "); while (pch != NULL){ if(strstr(pch,"0x")){ winId = pch; break; } pch = strtok (NULL, " "); } return winId; } void acceptUseTerms(string win){ ostringstream ss,action; action << "DISPLAY=:1 xdotool windowfocus --sync " << win; int xdo_result = system(action.str().c_str()); action.str(std::string()); action << "DISPLAY=:1 xdotool click --window " << win << " 1"; xdo_result = system(action.str().c_str()); action.str(std::string()); action << "DISPLAY=:1 xdotool mousemove --window " << win << " 340 240"; xdo_result = system(action.str().c_str()); action.str(std::string()); action << "DISPLAY=:1 xdotool click --window " << win << " 1"; xdo_result = system(action.str().c_str()); action.str(std::string()); } void acceptTerms(){ FILE *fpipe; char line[512]; if ( !(fpipe = (FILE*)popen("DISPLAY=:1 xwininfo -tree -root","r")) ) { perror("Pipe is leaking..."); exit(1); } string win; while ( fgets( line, sizeof line, fpipe)) { if(strstr(line,"Terms of Use")){ win = windowIDSearch(line); cout << "Window: " << win << endl; acceptUseTerms(win); break; } } pclose(fpipe); } int main(int argc, char *argv[]) { acceptTerms(); return 0; }
Java
UTF-8
2,631
1.914063
2
[]
no_license
package gob.inamhi.bean; import gob.inamhi.bean.util.JsfUtil; import gob.inamhi.domain.Escat; import gob.inamhi.domain.Parm; import gob.inamhi.session.EscatFacade; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; @ManagedBean(name = "escatController") @ViewScoped public class EscatController extends AbstractController<Escat> implements Serializable { @EJB private EscatFacade ejbFacade; @ManagedProperty(value = "#{parmController}") private ParmController controladorParametros; private List<Parm> parametros; private List<Parm> parametrosNuevos; private Escat inputEscat = new Escat(); public EscatController() { super(Escat.class); } @PostConstruct public void init() { super.setFacade(ejbFacade); } public void selectListener1() { setParametros(getSelected().getCatiId().getTipoId().getTipoId()); } public void selectListener2() { setParametrosNuevos(getInputEscat().getCatiId().getTipoId().getTipoId()); } public void setControladorParametros(ParmController controladorParametros) { this.controladorParametros = controladorParametros; } public ParmController getControladorParametros() { return controladorParametros; } public void setParametros(int tipo) { this.parametros = controladorParametros.buscarParametrosPorTipo(tipo); } public List<Parm> getParametros() { return parametros; } public void guardarEscat() { getInputEscat().setEscatuing("ADMIN"); this.ejbFacade.create(getInputEscat()); JsfUtil.addSuccessMessage("Configuración Ingresada Exitosamente"); setInputEscat(new Escat()); setItems(null); parametros = null; } public void cancelarEscat() { setInputEscat(new Escat()); setItems(null); parametros = null; //setSelected(null); parametrosNuevos = null; } public void cancelarEditarEscat() { setInputEscat(new Escat()); setItems(null); } public Escat getInputEscat() { return inputEscat; } public void setInputEscat(Escat inputEscat) { this.inputEscat = inputEscat; } public List<Parm> getParametrosNuevos() { return parametrosNuevos; } public void setParametrosNuevos(int tipo) { this.parametrosNuevos = controladorParametros.buscarParametrosPorTipo(tipo); } }
Java
UTF-8
1,040
2.53125
3
[ "Apache-2.0" ]
permissive
package org.smartframework.cloud.starter.core.support.bean; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.AnnotationBeanNameGenerator; import org.springframework.util.StringUtils; /** * 生成bean名称的规则 * * @author liyulin * @date 2019-04-22 */ public class UniqueBeanNameGenerator extends AnnotationBeanNameGenerator { @Override public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { if (definition instanceof AnnotatedBeanDefinition) { String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition); if (StringUtils.hasText(beanName)) { // Explicit bean name found. return beanName; } } // 如果该bean名称没有指定,则按照“package+className”的规则生成 return definition.getBeanClassName(); } }
JavaScript
UTF-8
1,970
2.75
3
[]
no_license
// set custom tip CustomTooltip = function(parent,tip_content,cs){ this.tip = $a(null,'div','custom_tooltip',cs); this.tip.innerHTML = tip_content; // append tip to body, to get the height and width of tip $(this.tip).appendTo('body'); this.parent = parent; $y(this.parent,{position:'relative'}); // set parameters this.set_param(); // on hover this.onhover(); } // set parameters CustomTooltip.prototype.set_param = function(){ this.parent.tip = this.tip; // tip width this.parent.width = $(this.tip).outerWidth(); // tip height this.parent.height = $(this.tip).outerHeight(); // parent width var pw = $(this.parent).outerWidth(); this.parent.parent_width = pw ? pw : 16; // if parent width set before rendering(i.e. 0px) // parent height var ph = $(this.parent).outerHeight(); this.parent.parent_height = ph ? ph : 16; // if parent height set before rendering(i.e. 0px) // remove tip from body $(this.tip).remove(); } // on hover CustomTooltip.prototype.onhover = function(){ // on hover $(this.parent).hover( // mouseover function(e){ // repositioning of tip to avoid striping on the corners of window if required this.screen_width = $(window).width(); this.screen_bottom = $(window).scrollTop() + $(window).height(); this.offset = $(this).offset(); // append to parent $(this.tip).appendTo(this) $y(this.tip,{width:this.width + 'px'}) // set position if(this.offset.left + this.parent_width + this.width > this.screen_width){ this.left = - this.width; } else this.left = this.parent_width; if(this.offset.top + this.parent_height + this.height > this.screen_bottom){ this.top = - this.height; } else this.top = this.parent_height; $(this.tip) .css('top', this.top + 'px') .css('left', this.left + 'px') .css('display', 'block') }, // mouseout function(e){ $(this.tip) .css('display','none'); } ) }
Java
UTF-8
1,055
3.1875
3
[]
no_license
package Logic.Records; public class ArtistRecord { private int artistID; private String artistName; public ArtistRecord(int artistID, String artistName) { this.artistID = artistID; this.artistName = artistName; } public int getArtistID() { return artistID; } public void setArtistID(int artistID) { this.artistID = artistID; } public String getArtistName() { return artistName; } public void setArtistName(String artistName) { this.artistName = artistName; } @Override public boolean equals(Object obj) { boolean returnBoolean = false; if (obj instanceof ArtistRecord){ ArtistRecord other = (ArtistRecord) obj; if (this.artistID == other.artistID) { returnBoolean = true; } } return returnBoolean; } @Override public int hashCode() { return artistID; } @Override public String toString() { return artistName; } }
Go
UTF-8
518
2.90625
3
[ "BSD-3-Clause" ]
permissive
package work // Args is how parameters are passed to jobs type Args map[string]interface{} // Handler is executed a a Work for a given Job. It also defines the interface // for handlers that can be used by middleware adapters type Handler func(j *Job) error // Adapter defines the adaptor middleware type type Adapter func(Handler) Handler // Adapt a handler with provided middlware adapters func Adapt(h Handler, adapters ...Adapter) Handler { for _, adapter := range adapters { h = adapter(h) } return h }
JavaScript
UTF-8
1,312
2.609375
3
[]
no_license
import React, { useState, useEffect } from "react"; import getWeatherData from "../api"; import Loader from "./Loader"; const WeatherCard = (props) => { const { location, error, setError, tempUnit } = props; const [weatherData, setWeatherData] = useState(null); if (!weatherData && !error) getWeatherData(location, tempUnit) .then((data) => { console.log(tempUnit); setWeatherData(data); }) .catch(({ response }) => { const { status, data: { message }, } = response; setError({ status, message }); }); useEffect(() => { setWeatherData(null); }, [location, tempUnit]); if (!weatherData && !error) return <Loader />; return ( !error && ( <div className="weather-card"> <h2> {weatherData.name}, {weatherData.sys.country} </h2> <p className="location-temp"> {Math.round(weatherData.main.temp)} °{tempUnit ? "C" : "F"} </p> <img src={`https://openweathermap.org/img/wn/${weatherData.weather[0].icon}@2x.png`} alt={weatherData.weather[0].main} /> <p className={"weather-description"}> {weatherData.weather[0].description} </p> </div> ) ); }; export default WeatherCard;
Markdown
UTF-8
12,287
2.65625
3
[]
no_license
--- title: "问卷介绍-有关用户对抖音软件的满意度调查" date: 2019-11-08 09:09:20 tags: [毕业问卷, 问卷设计, 问卷互填, 问卷大全, 问卷收集] --- ### 问卷指导语 亲爱的同学,您好!目前我们正在进行抖音短视频对抖音用户生活影响的调查。为了解大学生对抖音短视频APP的使用情况,进而分析对用户生活产生的影响及短视频APP的发展前景,特开展此次调查问卷。本问卷采用匿名方式,所有数据只用于统计分析,请放心填写。感谢您的协助与支持! 该问卷主要用于计量经济学、教育学、心理学、行为经济学、统计学专业的样本收集。 <!-- more --> ### 自我介绍 为了帮助毕业生和高效科研人员快速收集网络问卷的数据, 并且保证信效度, 收集高质量的数据, 我组织了一批人专门进行问卷的填写。 目前QQ群有21个, 每个群都是千人大群。 可以快速搜集大量样本数据,并且如果客户有要求, 可以对客户的数据进行初审, 主动删除一些填写不认真的数据, 这样就可以保证研究人员收集的数据的信效度了。 ### 快速添加问卷题目 我已经把这个问卷编辑成了特殊的格式, 可以批量导入到问卷星, 面得你自己创建题目了。 你只需要将下面的题目复制到问卷星的题目编辑页面即可, 想知道如何快速导入问卷星题目, 可以看这篇文章: [问卷星如何快速批量添加题目](https://mlln.cn/2019/06/01/%E9%97%AE%E5%8D%B7%E6%98%9F%E5%A6%82%E4%BD%95%E5%BF%AB%E9%80%9F%E6%B7%BB%E5%8A%A0%E6%89%B9%E9%87%8F%E9%A2%98%E7%9B%AE/index.html)。 {% raw %} <textarea rows="40" style="width: 100%;">1. 您的性别是*[单选题] 男 女 2. 您的年龄是*[单选题] 18以下 19-25 26-35 36岁及以上 3. 您的职业是什么*[单选题] 学生 企业员工 事业单位 个体 自由职业 待业 其他 4. 您的受教育程度*[单选题] 小学及以下 初/高中 大/中专 本科 硕士及以上 5. 您是通过什么渠道了解到这个APP的* 【多选题】[多选题] 广告吸引 朋友推荐 网页浏览 其他 6. 您是否使用过抖音*[单选题] 使用过 没用过 下载过又删除了 7. 您平时都是在什么时候打开抖音* 【多选题】[多选题] 早上起床 睡觉前 走路 坐车 上洗手间 上课时间 其他 8. 您使用了多长时间抖音*[单选题] 半年以下 半年以上一年以下 一年到两年 两年以上 9. 您每天使用多长时间抖音*[单选题] 半小时以内 一小时以内 两小时以内 两小时以上 10. 您比较关注哪些短视频* 【多选题】[多选题] 广告 教程 美食 音乐 明星 搞笑 萌宠 恐怖 动画 剧情 其他 11. 您最常使用哪些功能*[单选题] 短视频观看 制作传播视频 社交聊天功能 转发分享功能 其他 12. 抖音满足了您哪些需求* 【多选题】[多选题] 娱乐减压 获取社会新闻 获得系统的知识技能 获取日常生活相关信息 观看直播 提高新媒体运营技能 13. 您觉得抖音内容如何*[单选题] 很好 较好 一般 不好 14. 您对抖音满意度如何*[单选题] 十分满意 比较满意 一般 不太满意 不满意 15. 您会继续使用抖音吗*[单选题] 很喜欢,会继续使用下去 比较喜欢,可以会继续使用 不一定 不太喜欢,可能不会继续使用 越来越不懂喜欢,不会再用了 16. 您的日常消费会受到短视频广告营销的影响*[单选题] 完全受到影响 经常 偶尔 没有影响 17. 您认为抖音最应该改进的项目是什么[填空题] 18. 您认为抖音有什么好玩的项目[填空题] 19. 您对抖音有什么建议吗[填空题] </textarea> {% endraw %} ### 有关用户对抖音软件的满意度调查的主要内容 以下是所有的问卷题目及其选项, 建议大家尽量使用"问卷星"作为网络问卷平台, 支持的题型更多, 更好用, 数据分析更方便。 >>> 需要快速收集问卷数据请看下面 {% raw %} <div class="qitem"> <h4>第1题:您的性别是*[单选题][必须填]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>男</td></tr> <tr><td>2</td><td>女</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第2题:您的年龄是*[单选题][必须填]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>18以下</td></tr> <tr><td>2</td><td>19-25</td></tr> <tr><td>3</td><td>26-35</td></tr> <tr><td>4</td><td>36岁及以上</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第3题:您的职业是什么*[单选题][必答题]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>学生</td></tr> <tr><td>2</td><td>企业员工</td></tr> <tr><td>3</td><td>事业单位</td></tr> <tr><td>4</td><td>个体</td></tr> <tr><td>5</td><td>自由职业</td></tr> <tr><td>6</td><td>待业</td></tr> <tr><td>7</td><td>其他</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第4题:您的受教育程度*[单选题][不能为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>小学及以下</td></tr> <tr><td>2</td><td>初/高中</td></tr> <tr><td>3</td><td>大/中专</td></tr> <tr><td>4</td><td>本科</td></tr> <tr><td>5</td><td>硕士及以上</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第5题:您是通过什么渠道了解到这个APP的* 【多选题】[多选题][可以为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>广告吸引</td></tr> <tr><td>2</td><td>朋友推荐</td></tr> <tr><td>3</td><td>网页浏览</td></tr> <tr><td>4</td><td>其他</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第6题:您是否使用过抖音*[单选题][不能为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>使用过</td></tr> <tr><td>2</td><td>没用过</td></tr> <tr><td>3</td><td>下载过又删除了</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第7题:您平时都是在什么时候打开抖音* 【多选题】[多选题][可以为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>早上起床</td></tr> <tr><td>2</td><td>睡觉前</td></tr> <tr><td>3</td><td>走路 坐车</td></tr> <tr><td>4</td><td>上洗手间</td></tr> <tr><td>5</td><td>上课时间</td></tr> <tr><td>6</td><td>其他</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第8题:您使用了多长时间抖音*[单选题][必须填]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>半年以下</td></tr> <tr><td>2</td><td>半年以上一年以下</td></tr> <tr><td>3</td><td>一年到两年</td></tr> <tr><td>4</td><td>两年以上</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第9题:您每天使用多长时间抖音*[单选题][不能为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>半小时以内</td></tr> <tr><td>2</td><td>一小时以内</td></tr> <tr><td>3</td><td>两小时以内</td></tr> <tr><td>4</td><td>两小时以上</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第10题:您比较关注哪些短视频* 【多选题】[多选题][选填]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>广告</td></tr> <tr><td>2</td><td>教程</td></tr> <tr><td>3</td><td>美食</td></tr> <tr><td>4</td><td>音乐</td></tr> <tr><td>5</td><td>明星</td></tr> <tr><td>6</td><td>搞笑</td></tr> <tr><td>7</td><td>萌宠</td></tr> <tr><td>8</td><td>恐怖</td></tr> <tr><td>9</td><td>动画</td></tr> <tr><td>10</td><td>剧情</td></tr> <tr><td>11</td><td>其他</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第11题:您最常使用哪些功能*[单选题][不能为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>短视频观看</td></tr> <tr><td>2</td><td>制作传播视频</td></tr> <tr><td>3</td><td>社交聊天功能</td></tr> <tr><td>4</td><td>转发分享功能</td></tr> <tr><td>5</td><td>其他</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第12题:抖音满足了您哪些需求* 【多选题】[多选题][可以为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>娱乐减压</td></tr> <tr><td>2</td><td>获取社会新闻</td></tr> <tr><td>3</td><td>获得系统的知识技能</td></tr> <tr><td>4</td><td>获取日常生活相关信息</td></tr> <tr><td>5</td><td>观看直播</td></tr> <tr><td>6</td><td>提高新媒体运营技能</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第13题:您觉得抖音内容如何*[单选题][必答题]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>很好</td></tr> <tr><td>2</td><td>较好</td></tr> <tr><td>3</td><td>一般</td></tr> <tr><td>4</td><td>不好</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第14题:您对抖音满意度如何*[单选题][必答题]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>十分满意</td></tr> <tr><td>2</td><td>比较满意</td></tr> <tr><td>3</td><td>一般</td></tr> <tr><td>4</td><td>不太满意</td></tr> <tr><td>5</td><td>不满意</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第15题:您会继续使用抖音吗*[单选题][不能为空]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>很喜欢,会继续使用下去</td></tr> <tr><td>2</td><td>比较喜欢,可以会继续使用</td></tr> <tr><td>3</td><td>不一定</td></tr> <tr><td>4</td><td>不太喜欢,可能不会继续使用</td></tr> <tr><td>5</td><td>越来越不懂喜欢,不会再用了</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第16题:您的日常消费会受到短视频广告营销的影响*[单选题][必答题]</h4> <table class="table"> <thead> <tr><td>选项值</td><td>选项标签</td></tr> </thead> <tbody> <tr><td>1</td><td>完全受到影响</td></tr> <tr><td>2</td><td>经常</td></tr> <tr><td>3</td><td>偶尔</td></tr> <tr><td>4</td><td>没有影响</td></tr> </tbody> </table> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第17题:您认为抖音最应该改进的项目是什么[填空题][选填]</h4> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第18题:您认为抖音有什么好玩的项目[填空题][非必答题]</h4> </div> {% endraw %} {% raw %} <div class="qitem"> <h4>第19题:您对抖音有什么建议吗[填空题][选填]</h4> </div> {% endraw %} <!-- --- title: 心理教育医学的问卷免费下载 date: 2019-05-23 08:59:15 tags: [问卷星, 问卷网, 问卷下载, 问卷互填, 问卷设计, 问卷模板, 毕业问卷, 问卷数据分析, 问卷代填, ] --- --> ### 联系方式 如果你有以下需求都可以联系我们: - 有淘宝运营经验想跟我们合作 - 问卷数据分析(文字结论和三线表格) - 问卷设计(帮你针对论文设计问卷) - 问卷代填(大概0.1元一份问卷) - 有数据分析经验想跟我们合作 - 问卷互填(大学生问卷诚信互填群) 你都可以联系我们, 加我们的扣扣(1!5!6!4!7!9!9!5!6!6(请自觉忽略"!"))
C#
UTF-8
1,666
3.40625
3
[]
no_license
using System; using System.Linq; using Chess.Core; using Chess.Core.Players; using Chess.Core.Enums; using Chess.Core.Pieces; namespace ChessConsole { class Program { static void Main(string[] args) { var game = new Game(); var playerOne = new HumanPlayer("PlayerOne", PieceColor.White); var playerTwo = new HumanPlayer("PlayerTwo", PieceColor.Black); game.AddPlayer(playerOne); game.AddPlayer(playerTwo); game.StartGame(); PrintBoard(game.Board); Console.WriteLine("Piece: {0}", game.Board.Pieces[7]); Console.WriteLine("Color: {0}", game.Board.Pieces[7].Color); Console.WriteLine("Position: {0}", game.Board.Pieces[7].Square); GetAvailableMoves(game.Board.Pieces[7], game.Board); Console.Read(); } public static void PrintBoard(Board board) { var squares = board.GetSquares(); for(var y = 0; y < 8; y++) { for(var x = 0; x < 8; x++) { var piece = board.Pieces .FirstOrDefault(p => p.Square.X == x && p.Square.Y == y); Console.Write("[{0}]", piece?.ToString().Substring(0, 1) ?? " "); } Console.WriteLine(); } } public static void GetAvailableMoves(Piece piece, Board board) { foreach(var move in piece.GetPossibleMoves(board)) { Console.WriteLine("Possible move: {0}", move.EndSquare); } } } }
Markdown
UTF-8
1,430
2.671875
3
[]
no_license
# Webpack 4. Полный курс 2020 На основании этого видео [![Основное видео](http://img.youtube.com/vi/eSaF8NXeNsA/0.jpg)](https://www.youtube.com/watch?v=eSaF8NXeNsA "Основное видео") ## Основные команды `npx webpack` - Собрать приложение `npm run dev` - Собрать в режиме разработки `npm run build` - Собрать в режиме продукта ## Плагины ### `html-webpack-plugin` Работа с html шаблоном и подключение всех сгенеренных скриптов Установка npm i -D html-webpack-plugin Использование, подключаем в `webpack.config.js` ```js const HtmlWebPackPlugin = require('html-webpack-plugin') module.exports = { ... plugins: [ new HtmlWebPackPlugin({ title: 'Webpack generate', template: './src/index.html' }) ] } ``` ### `clean-webpack-plugin` Очистка старых скриптов и стилей npm i -D clean-webpack-plugin Использование, подключаем в `webpack.config.js` ```js const HtmlWebPackPlugin = require('html-webpack-plugin') module.exports = { ... plugins: [ new HtmlWebPackPlugin({ title: 'Webpack generate', template: './src/index.html' }) ] } ```
Python
UTF-8
1,349
2.953125
3
[]
no_license
# -*- coding: utf-8 -*- ## cscrub.py ################################################################### ## scrubs characters from text files so bookr ################################## ## displays things properly #################################################### ################################################################################ from sys import argv if(__name__=="__main__"): script, filename = argv fileTarget = open(filename, 'r') fileContents = fileTarget.read() fileContents = fileContents.replace("’", "'") fileContents = fileContents.replace("“", '"') fileContents = fileContents.replace("”", '"') fileContents = fileContents.replace("—", '-') fileContents = fileContents.replace("–", '-') ## not the same character, although they do look quite similar fileContents = fileContents.replace("‘", "'") fileContents = fileContents.replace("è", 'e') fileContents = fileContents.replace("é", 'e') ## think there must be a better option available than this, but I havent ## tested bookrs support for non-english special characters ## fixing the double quotes is already a huge boost in readability ## as far as I am concerned fileContents = fileContents.replace("…", '...') fileTarget.close() fileTarget = open(filename, 'w') fileTarget.write(fileContents) fileTarget.close()
Java
UTF-8
7,584
1.859375
2
[]
no_license
package com.flea.modules.report.action; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.alibaba.fastjson.JSONObject; import com.flea.common.Common; import com.flea.common.pojo.Page; import com.flea.common.pojo.Role; import com.flea.common.pojo.User; import com.flea.common.util.DateUtils; import com.flea.common.util.FileUtils; import com.flea.common.util.JsonUtil; import com.flea.common.util.ShiroUtils; import com.flea.modules.report.pojo.SearchResult; import com.flea.modules.report.pojo.VLibraryBook; import com.flea.modules.report.pojo.vo.QueryCriteria; import com.flea.modules.report.service.VLibraryBookService; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * 藏书、编目统计Controller * @author bruce * @version 2016-07-09 */ @Controller @RequestMapping(value = "report/vLibraryBook") public class VLibraryBookController { @Autowired private VLibraryBookService vLibraryBookService; @RequestMapping(value = {""}) public ModelAndView list(QueryCriteria query,HttpServletRequest request, HttpServletResponse response, Model model) { User user = ShiroUtils.getCurrentUser(); Role role = user.getRoles().get(0); String le = role.getLevel(); Page<VLibraryBook> page=new Page<VLibraryBook>(); if(Common.ROLE_FIRST_LEVLE.equals(le)){ model.addAttribute("area",null); model.addAttribute("lib",vLibraryBookService.getAllLibLevel()); model.addAttribute("hall",null); model.addAttribute("isCustomer",false); query.setArea("区"); query.setLib(""); }else{ Map<String, List<String>> map = vLibraryBookService.showTopSelect(query.getArea(),query.getLib()); model.addAttribute("area",map.get("area")); model.addAttribute("lib",vLibraryBookService.getAllLibLevel()); model.addAttribute("hall",new ArrayList<String>()); model.addAttribute("isCustomer",true); query.setArea(map.get("area").get(0)); query.setLib(map.get("lib").get(0)); } // page=vLibraryBookService.find(new Page<VLibraryBook>(request,response),query); page.setCont(page.toString().replaceAll("page","pageTo")); model.addAttribute("page",page); model.addAttribute("query",query); return new ModelAndView("report/count_librarybook"); } @RequestMapping("list") @ResponseBody public String getQueryInfo(QueryCriteria qc,HttpServletRequest req, HttpServletResponse resp, HttpSession session) { Page<VLibraryBook> page = vLibraryBookService.find(new Page<VLibraryBook>(req,resp), qc, session); page.setCont(page.toString().replaceAll("page","pageTo")); Gson gson = new GsonBuilder().setDateFormat("yyyyMMdd").create(); return gson.toJson(page); } @RequestMapping("data") @ResponseBody public String getListByCategory(QueryCriteria query,HttpServletRequest req, HttpServletResponse resp) { SearchResult<VLibraryBook> dataList=vLibraryBookService.findLibraryDataList(query); Gson gson = new Gson(); return gson.toJson(dataList); } @RequestMapping("exportList") public void exprotListPDF(QueryCriteria query,HttpServletRequest request, HttpServletResponse response,HttpSession session) { String realPath = session.getServletContext().getRealPath("/"); realPath = realPath.replace("library\\", ""); realPath =realPath +"/pdf/"+ShiroUtils.getCurrentUser().getUserName()+DateUtils.getDate("yyyyMMdd")+".pdf"; vLibraryBookService.exportLibraryBookPDF(query, realPath); // File file = new File(realPath); // 取得文件名。 try { String filename = "藏书统计"+DateUtils.getDate("yyyyMMdd")+".pdf"; InputStream fis = new BufferedInputStream(new FileInputStream(realPath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1")); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/pdf"); toClient.write(buffer); toClient.flush(); toClient.close(); FileUtils.deleteFile(realPath); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping("exportData") public void exprotDataPDF(QueryCriteria query,HttpServletRequest request, HttpServletResponse response,HttpSession session) { String realPath = session.getServletContext().getRealPath("/"); realPath = realPath.replace("library\\", ""); realPath =realPath +"/pdf/"+ShiroUtils.getCurrentUser().getUserName()+DateUtils.getDate("yyyyMMdd")+".pdf"; vLibraryBookService.exportCategoryDataPDF(query, realPath); // 取得文件名。 try { String filename = "藏书类别统计"+DateUtils.getDate("yyyyMMdd")+".pdf"; InputStream fis = new BufferedInputStream(new FileInputStream(realPath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1")); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/pdf"); toClient.write(buffer); toClient.flush(); toClient.close(); FileUtils.deleteFile(realPath); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping(value = "form") public String form(VLibraryBook vLibraryBook, Model model) { model.addAttribute("vLibraryBook", vLibraryBook); return "report/vLibraryBookForm"; } @RequestMapping(value = "save") public ModelAndView save(VLibraryBook vLibraryBook, Model model) { vLibraryBookService.saveOne(vLibraryBook); return new ModelAndView("redirect:list.html"); } @RequestMapping(value = "del") @ResponseBody public JSONObject delete(Integer id, RedirectAttributes redirectAttributes) { return JsonUtil.createSuccessJson(vLibraryBookService.deleteById(id)); } @RequestMapping("getMore") public void getSelectMore(String area,String lib,String t,HttpServletResponse reps) { try { area = java.net.URLDecoder.decode(area,"utf8"); if(lib!=null){ lib = java.net.URLDecoder.decode(lib,"utf8"); } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } reps.setContentType("text/html"); String aa = vLibraryBookService.getSelectMore(area, lib); try { reps.getWriter().write(aa); } catch (IOException e) { e.printStackTrace(); } // return vLibraryBookService.getSelectMore(area, lib); } }