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
2,908
2.8125
3
[ "MIT" ]
permissive
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { JSONSchema7 } from 'json-schema' import { compare, applyPatch } from 'fast-json-patch' import toJSONSchema from 'to-json-schema' import { defaultObjectForSchema } from './defaults' import { Patch, applyLensToPatch } from './patch' import { LensSource } from './lens-ops' import { updateSchema } from './json-schema' /** * importDoc - convert any Plain Old Javascript Object into an implied JSON Schema and * a JSON Patch that sets every value in that document. * @param inputDoc a document to convert into a big JSON patch describing its full contents */ export function importDoc(inputDoc: any): [JSONSchema7, Patch] { const options = { postProcessFnc: (type, schema, obj, defaultFnc) => ({ ...defaultFnc(type, schema, obj), type: [type, 'null'], }), objects: { postProcessFnc: (schema, obj, defaultFnc) => ({ ...defaultFnc(schema, obj), required: Object.getOwnPropertyNames(obj), }), }, } const schema = toJSONSchema(inputDoc, options) as JSONSchema7 const patch = compare({}, inputDoc) return [schema, patch] } /** * applyLensToDoc - converts a full document through a lens. * Under the hood, we convert your input doc into a big patch and the apply it to the targetDoc. * This allows merging data back and forth with other omitted values. * @property lensSource: the lens specification to apply to the document * @property inputDoc: the Plain Old Javascript Object to convert * @property inputSchema: (default: inferred from inputDoc) a JSON schema defining the input * @property targetDoc: (default: {}) a document to apply the contents of this document to as a patch */ export function applyLensToDoc( lensSource: LensSource, // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types inputDoc: any, inputSchema?: JSONSchema7, // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types targetDoc?: any ): any { const [impliedSchema, patchForOriginalDoc] = importDoc(inputDoc) if (inputSchema === undefined || inputSchema === null) { inputSchema = impliedSchema } // construct the "base" upon which we will apply the patches from doc. // We start with the default object for the output schema, // then we add in any existing fields on the target doc. // TODO: I think we need to deep merge here, can't just shallow merge? const outputSchema = updateSchema(inputSchema, lensSource) const base = Object.assign(defaultObjectForSchema(outputSchema), targetDoc || {}) // return a doc based on the converted patch. // (start with either a specified baseDoc, or just empty doc) // convert the patch through the lens const outputPatch = applyLensToPatch(lensSource, patchForOriginalDoc, inputSchema) return applyPatch(base, outputPatch).newDocument }
Python
UTF-8
289
3.609375
4
[]
no_license
num1=int(input("enter num1")) num2=int(input("enter num2")) num3=int(input("enter num3")) if(num1>num2) & (num1>num3): print("num1 is max") elif(num2>num3)& (num2>num1): print("num2 is max") elif(num3>num1) &(num3>num2): print("num3 is max") else: print("numbers are same")
Python
UTF-8
1,106
3.15625
3
[]
no_license
from bs4 import BeautifulSoup import os def text_to_html(folder): filenames = os.listdir(folder) for file in filenames: if file.endswith('.html'): file_in = open("./"+folder+ "/" + file, 'rb') # Pasamos el contenido HTML a un objeto BeautifulSoup html = BeautifulSoup(file_in) file_in.close() # Obtenemos todos los párrafos para capturar el texto. parrafos = html.find_all('p') # Generamos el texto a procesar uniendo los párrafos detectados. text = "" for parrafo in parrafos: text = text + parrafo.getText() + "\n" if not os.path.isdir('./CorpusNoticiasPractica1718/'): os.mkdir('./CorpusNoticiasPractica1718/') # Generamos el fichero de CorpusNoticiasPractica1718 file_out = open("./CorpusNoticiasPractica1718/" + file.strip(".html") + ".txt", "w") file_out.write(text) file_out.close() if __name__ == "__main__": folder_input = "Corpus" text_to_html(folder_input)
C#
UTF-8
1,322
3.6875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; namespace Applied_Arithmetics { class Program { static void Main(string[] args) { int[] numbers = Console.ReadLine() .Split() .Select(int.Parse) .ToArray(); Func<int, int> operationAdd = x => x + 1; Func<int, int> operationMultiply = x => x * 2; Func<int, int> operationSubtract = x => x - 1; string input = Console.ReadLine(); while (input != "end") { if (input == "add") { numbers = numbers.Select(operationAdd).ToArray(); } else if (input == "multiply") { numbers = numbers.Select(operationMultiply).ToArray(); } else if (input == "subtract") { numbers = numbers.Select(operationSubtract).ToArray(); } else if (input == "print") { Console.WriteLine(string.Join(" ", numbers)); } input = Console.ReadLine(); } } } }
C
UTF-8
7,175
3.28125
3
[]
no_license
#include<stdio.h> #include<stdlib.h> typedef struct Node SLL; struct Node { int coff; int expo; SLL *next; }; SLL *head1=NULL; SLL *head2=NULL; SLL *head3=NULL; SLL *head4=NULL; SLL *head5=NULL; int n1; int n2; int Read_No_Nodes(); void Traverse_SLL(SLL **); void Insert_End(SLL **, int,int); void add(); void subtract(); void multiply(); void Delete_X(SLL **, int,int); void remove_duplicate(SLL *); void bubbleSort(SLL *); void swap(SLL *,SLL*); void reverse(SLL **); int main() { printf("ENTER THE NUMBER OF TERMS IN THE FIRST POLYNOMIAL="); n1 = Read_No_Nodes(); printf("\nENTER THE COFFICIENT AND EXPONENT OF TERMS=\n"); for(int i=0;i<n1;i++) { int coff,expo; scanf("%d",&coff); scanf("%d",&expo); Insert_End(&head1, coff,expo); } remove_duplicate(head1); bubbleSort(head1); reverse(&head1); Traverse_SLL(&head1); printf("ENTER THE NUMBER OF TERMS IN THE SECOND POLYNOMIAL="); n2 = Read_No_Nodes(); printf("\nENTER THE COFFICIENT AND EXPONENT OF TERMS RESPECTIVELY FOR EACH TERM=\n"); for(int i=0;i<n2;i++) { int coff,expo; scanf("%d",&coff); scanf("%d",&expo); Insert_End(&head2, coff,expo); } remove_duplicate(head2); bubbleSort(head2); reverse(&head2); Traverse_SLL(&head2); printf("<<<<<<<<<<<<<-----------------------------ADDITION-------------------------------------->>>>>>>>>>>>>>>>>> \n"); add(); Traverse_SLL(&head3); printf("<<<<<<<<<<<<<-----------------------------SUBTRACTION-------------------------------------->>>>>>>>>>>>>>>>>> \n"); subtract(); Traverse_SLL(&head4); printf("<<<<<<<<<<<<<-----------------------------MULTIPLICATION-------------------------------------->>>>>>>>>>>>>>>>>> \n"); multiply(); Traverse_SLL(&head5); return EXIT_SUCCESS; } int Read_No_Nodes() { int s; scanf("%d",&s); return s; } void Traverse_SLL(SLL **h) { int i; SLL *t; if(*h==NULL) printf("\nList is empty\n"); else { printf("\nThe equation are...\n"); t = *h; while(t!=NULL) { printf("%dx^%d",t->coff,t->expo); if(t->next!=NULL&&t->next->coff>0){ printf("+"); } t = t->next; } printf("\n"); } } void Insert_End(SLL **h, int c,int e) { SLL * newNode=(SLL *)malloc(sizeof(SLL)); newNode->coff=c; newNode->expo=e; newNode->next=NULL; if(*h==NULL){ *h=newNode; } else{ SLL * temp=*h; while(temp->next!=NULL){ temp=temp->next; } temp->next=newNode; } } void add() { SLL *temp1=head1; SLL *temp2=head2; while(temp1!=NULL && temp2!=NULL) { int c,e; if(temp1->expo > temp2->expo) { e = temp1->expo; c = temp1->coff; temp1 = temp1->next; } else if(temp1->expo < temp2->expo) { e = temp2->expo; c = temp2->coff; temp2 = temp2->next; } else { e = temp1->expo; c = temp1->coff+temp2->coff; temp1 = temp1->next; temp2 = temp2->next; } Insert_End(&head3,c,e); } while(temp1!=NULL || temp2!=NULL) { int c,e; if(temp1!=NULL) { e = temp1->expo; c = temp1->coff; temp1 = temp1->next; } if(temp2!=NULL) { e = temp2->expo; c = temp2->coff; temp2 = temp2->next; } Insert_End(&head3,c,e); } } void subtract() { SLL *temp1=head1; SLL *temp2=head2; while(temp1!=NULL && temp2!=NULL) { int c,e; if(temp1->expo > temp2->expo) { e = temp1->expo; c = temp1->coff; temp1 = temp1->next; } else if(temp1->expo < temp2->expo) { e = (temp2->expo); c = -(temp2->coff); temp2 = temp2->next; } else { e = temp1->expo; c = temp1->coff-temp2->coff; temp1 = temp1->next; temp2 = temp2->next; } Insert_End(&head4,c,e); } while(temp1!=NULL || temp2!=NULL) { int c,e; if(temp1!=NULL) { e = temp1->expo; c = temp1->coff; temp1 = temp1->next; } if(temp2!=NULL) { e = -(temp2->expo); c = -(temp2->coff); temp2 = temp2->next; } Insert_End(&head4,c,e); } } void multiply(){ SLL *temp1=head1; SLL *temp2=head2; while(temp1!=NULL){ temp2=head2; while (temp2!=NULL) { int proCoff=temp1->coff*temp2->coff; int proexp=temp1->expo+temp2->expo; Insert_End(&head5,proCoff,proexp); temp2=temp2->next; } temp1=temp1->next; } remove_duplicate(head5); } void Delete_X(SLL **h, int c,int e) { SLL *curr=*h; SLL *prev=NULL; if(curr->expo==e && curr->coff==c) { *h=curr->next; return; } while(curr!=NULL) { if(curr->expo==e && curr->coff==c){ break;} prev=curr; curr=curr->next; } prev->next=curr->next; } void remove_duplicate(SLL *temp3){ while(temp3!=NULL){ SLL *temp4=temp3->next; while(temp4!=NULL){ if(temp3->expo==temp4->expo){ temp3->coff=temp3->coff+temp4->coff; Delete_X(&temp3, temp4->coff,temp4->expo); } temp4=temp4->next; } temp3=temp3->next; } } void bubbleSort(struct Node *start) { int swapped, i; struct Node *ptr1; struct Node *lptr = NULL; if (start == NULL) return; do { swapped = 0; ptr1 = start; while (ptr1->next != lptr) { if (ptr1->expo > ptr1->next->expo) { swap(ptr1, ptr1->next); swapped = 1; } ptr1 = ptr1->next; } lptr = ptr1; } while (swapped); } void swap(struct Node *a, struct Node *b) { int c = a->coff; int e = a->expo; a->expo=b->expo; a->coff=b->coff; b->coff=c; b->expo=e; } void reverse(struct Node** head_ref) { struct Node* prev = NULL; struct Node* cur = *head_ref; struct Node* next = NULL; while (cur != NULL) { next = cur->next; cur->next = prev; prev = cur; cur = next; } *head_ref = prev; }
TypeScript
UTF-8
1,036
2.859375
3
[ "MIT" ]
permissive
import type Store from '../store'; import { Family, FamilyType } from '../types'; import { min, prop } from './index'; import { withType } from './family'; import { getUnitX } from './units'; const alignGenerations = (families: readonly Family[], root: Family): void => { const parents = families.find(family => family.cid === root.id); if (parents) { const shift = ( getUnitX(parents, parents.children[0]!) - getUnitX(root, root.parents[0]!) ); families .filter(withType(FamilyType.child, FamilyType.root)) .forEach(family => family.X += shift); } }; const correct = (families: readonly Family[], coordinate: 'X' | 'Y'): void => { const shift = min(families.map(prop(coordinate))) * -1; if (shift !== 0) families.forEach(family => family[coordinate] += shift); }; export const correctPositions = (store: Store): Store => { const families = store.familiesArray; alignGenerations(families, store.rootFamily); correct(families, 'Y'); correct(families, 'X'); return store; };
Python
UTF-8
2,708
2.796875
3
[]
no_license
#encoding=utf-8 #处理抽取出来的乐谱,删除太短和单一的部分,进行分段 import os import shutil def ext(root, dist, filename): f = open(root + filename, 'r') c = 0 b = False strr = '' n = 0 for line in f: if '-' not in line and b == False: fw = open(dist+str(c)+filename, 'w') b = True strr = '' n = 1 if b: if '-' not in line: strr += line else: b = False ll = len(strr.split('\n')) if ll > 64: fw.write(strr) c += 1 if n != 0: ll = len(strr.split('\n')) if ll > 64: fw.write(strr) fw.write(strr) ''' root = 'C:\\Users\\v-honzhu\\Desktop\\t1\\' dist = 'C:\\Users\\v-honzhu\\Desktop\\test2\\' for p, d, filenames in os.walk(root): for filename in filenames: ext(root, dist, filename) ''' # 处理数据 抽取合适的乐谱 def norm_data(root, dist, filename): f = open(root+filename, 'r') c = 0 s = 0 strr = '' g = 0 for line in f: l = line.split(' ') if g == 0: s = float(l[1].strip()) g += 1 if abs(float(l[1].strip())-s) <= 10: s = float(l[1].strip()) strr += line else: fw = open(dist + str(c)+ filename, 'w') fw.write(strr) strr = '' s = float(l[1].strip()) c += 1 fw = open(dist + str(c) + filename, 'w') fw.write(strr) def ext_by_length(root, dist, filename): f = open(root+filename, 'r') c = 0 for i in f: c += 1 if c > 50: shutil.copy(root+filename, dist+filename) def pro_diff(root, dist, filename): f = open(root + filename, 'r') fw = open(dist + filename, 'w') c = 0 for line in f: if c == 0: l = float((line.split(' '))[1].strip()) else: break c += 1 f = open(root + filename, 'r') for line in f: strr = '' line = line.split(' ') x1 = float(line[1].strip()) - l x2 = float(line[2].strip()) - l if x1 < 0: x1 = 0.0 if x2 < 0: print('err') strr += line[0].strip()+' '+str(x1)+' '+str(x2) fw.write(strr) fw.write('\n') #root = 'C:\\Users\\v-honzhu\\Desktop\\guitar_txt\\' root = 'C:\\Users\\v-honzhu\\Desktop\\test2\\' dist = 'C:\\Users\\v-honzhu\\Desktop\\t1\\' for p, d, filenames in os.walk(root): for filename in filenames: pro_diff(root, dist, filename)
Python
UTF-8
1,250
3.0625
3
[]
no_license
# coding=utf-8 import io import os import random import base64 from PIL import Image, ImageDraw, ImageFont class Captcha(object): @classmethod def get_captcha(cls): width = 90 height = 32 img1 = Image.new(mode="RGB", size=(width, height), color=(202, 202, 202)) draw1 = ImageDraw.Draw(img1, mode="RGB") font_path = os.path.dirname(__file__) font = ImageFont.truetype(os.path.join(font_path, 'comic.ttf'), 26) s = "" for x in range(width): for y in range(height): draw1.point((x, y), fill=(random.randint(200, 255), random.randint(200, 255), random.randint(200, 255))) for i in range(4): char1 = random.choice([chr(random.randint(65, 90)), str(random.randint(0, 9))]) color1 = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) draw1.text([i * 20 + 5, 0], char1, font=font, fill=color1) s += char1 output = io.BytesIO() img1.save(output, format='JPEG') image_base64 = str(base64.b64encode(output.getvalue()), encoding='utf-8') return image_base64, s if __name__ == "__main__": img1, s = Captcha.get_captcha() print(img1, s)
Java
UTF-8
9,726
1.640625
2
[ "Apache-2.0" ]
permissive
package org.ovirt.engine.ui.userportal.client.protocols; import org.ovirt.engine.core.compat.Event; import org.ovirt.engine.ui.frontend.Frontend; import com.google.gwt.core.client.GWT; public class RdpConnector { private String server; private Boolean fullScreen = true; private String fullScreenTitle; private Integer width = 640; private Integer height = 480; private Integer authenticationLevel = 2; private Boolean enableCredSspSupport = false; // Disable 'Credential Security Support Provider (CredSSP)' to enable // SSO. private Boolean redirectDrives = false; private Boolean redirectPrinters = false; private Boolean redirectClipboard = false; private Boolean redirectSmartCards = false; private Event disconnectedEvent; public RdpConnector() { } public RdpConnector(String server, Event disconnectedEvent) { setServer(server); setDisconnectedEvent(disconnectedEvent); } public Event getDisconnectedEvent() { return disconnectedEvent; } public void setDisconnectedEvent(Event disconnectedEvent) { this.disconnectedEvent = disconnectedEvent; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public Boolean getFullScreen() { return fullScreen; } public void setFullScreen(Boolean fullScreen) { this.fullScreen = fullScreen; } public String getFullScreenTitle() { return fullScreenTitle; } public void setFullScreenTitle(String fullScreenTitle) { this.fullScreenTitle = fullScreenTitle; } public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } public Integer getAuthenticationLevel() { return authenticationLevel; } public void setAuthenticationLevel(Integer authenticationLevel) { this.authenticationLevel = authenticationLevel; } public Boolean getEnableCredSspSupport() { return enableCredSspSupport; } public void setEnableCredSspSupport(Boolean enableCredSspSupport) { this.enableCredSspSupport = enableCredSspSupport; } public Boolean getRedirectDrives() { return redirectDrives; } public void setRedirectDrives(Boolean redirectDrives) { this.redirectDrives = redirectDrives; } public Boolean getRedirectPrinters() { return redirectPrinters; } public void setRedirectPrinters(Boolean redirectPrinters) { this.redirectPrinters = redirectPrinters; } public Boolean getRedirectClipboard() { return redirectClipboard; } public void setRedirectClipboard(Boolean redirectClipboard) { this.redirectClipboard = redirectClipboard; } public Boolean getRedirectSmartCards() { return redirectSmartCards; } public void setRedirectSmartCards(Boolean redirectSmartCards) { this.redirectSmartCards = redirectSmartCards; } public String getRdpCabURL() { return GWT.getModuleBaseURL() + "msrdp.cab"; } public String getVdcUserNameAndDomain() { String username = Frontend.getLoggedInUser().getUserName(); String domain = Frontend.getLoggedInUser().getDomainControler(); return username.contains("@") ? username : username + "@" + domain; } public String getVdcUserName() { return Frontend.getLoggedInUser().getUserName(); } public String getVdcUserPassword() { return Frontend.getLoggedInUser().getPassword(); } public String getVdcUserDomainController() { return Frontend.getLoggedInUser().getDomainControler(); } public native void init() /*-{ var server = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getServer()(); var rdpCabURL = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRdpCabURL()(); var connectAreaDiv = document.createElement("<div style='display: none' id='connectArea'/>"); //var objStr = "<object id='MsRdpClient_" + server + "' onReadyStateChange='OnControlLoad()' onError='OnControlLoadError()' classid='CLSID:4eb89ff4-7f78-4a0f-8b8d-2bf02e94e4b2' width='800' height='600'></object>"; var objStr = "<object id='MsRdpClient_" + server + "' codebase='" + rdpCabURL + "' classid='CLSID:4eb89ff4-7f78-4a0f-8b8d-2bf02e94e4b2' width='800' height='600'></object>"; var client = document.createElement(objStr); connectAreaDiv.appendChild(client); document.body.appendChild(connectAreaDiv); function OnControlLoad() { } function OnControlLoadError() { } }-*/; public native void connect() /*-{ function OnConnected() { } function OnDisconnected(disconnectCode) { var extendedDiscReason = MsRdpClient.ExtendedDisconnectReason; var errorCodeEventArgs = @org.ovirt.engine.ui.uicommon.models.vms.ErrorCodeEventArgs::new(I)(disconnectCode); disconnectedEvent.@org.ovirt.engine.core.compat.Event::raise(Ljava/lang/Object;Lorg/ovirt/engine/core/compat/EventArgs;)(model, errorCodeEventArgs); $wnd.document.body.removeChild(MsRdpClient); } var server = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getServer()(); var fullScreen = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getFullScreen()(); var fullScreenTitle = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getFullScreenTitle()(); var width = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getWidth()(); var height = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getHeight()(); var authenticationLevel = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getAuthenticationLevel()(); var enableCredSspSupport = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getEnableCredSspSupport()(); var redirectDrives = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectDrives()(); var redirectPrinters = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectPrinters()(); var redirectClipboard = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectClipboard()(); var redirectSmartCards = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getRedirectSmartCards()(); var disconnectedEvent = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getDisconnectedEvent()(); var userName = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getVdcUserNameAndDomain()(); var password = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getVdcUserPassword()(); var domain = this.@org.ovirt.engine.ui.userportal.client.protocols.RdpConnector::getVdcUserDomainController()(); var model = this; // var MsRdpClient = document.getElementById("MsRdpClient_"+server); //TODO: Only in DEBUG mode // alert("Server [" + server + "] fullScreen? [" + fullScreen + "], FullScreen Title [" + // fullScreenTitle + "], width [" + width + "], height [" + height + "], auth level [" + authenticationLevel + "] enableCredSSPSupport? [" + // enableCredSspSupport + "] redirect drives? [" + redirectDrives + "], redirect printers? [" + redirectPrinters + "], redirect clipboard? [" + // redirectClipboard + "], redirect SmartCards [" + redirectSmartCards + "]"); // Remove previous client object var previousMsRdpClient = $wnd.document.getElementById('MsRdpClient_' + server); if (previousMsRdpClient) $wnd.document.body.removeChild(previousMsRdpClient); var MsRdpClient = $wnd.document.createElement("object"); $wnd.document.body.appendChild(MsRdpClient); MsRdpClient.id = "MsRdpClient_" + server; MsRdpClient.classid = "CLSID:4eb89ff4-7f78-4a0f-8b8d-2bf02e94e4b2"; MsRdpClient.server = server; MsRdpClient.FullScreen = fullScreen; MsRdpClient.desktopWidth = screen.width; MsRdpClient.desktopHeight = screen.height; MsRdpClient.width = 1; MsRdpClient.height = 1; MsRdpClient.UserName = userName; MsRdpClient.AdvancedSettings.ClearTextPassword = password; MsRdpClient.AdvancedSettings5.AuthenticationLevel = authenticationLevel; MsRdpClient.AdvancedSettings7.EnableCredSspSupport = enableCredSspSupport; MsRdpClient.AdvancedSettings2.RedirectDrives = redirectDrives; MsRdpClient.AdvancedSettings2.RedirectPrinters = redirectPrinters; MsRdpClient.AdvancedSettings2.RedirectClipboard = redirectClipboard; MsRdpClient.AdvancedSettings2.RedirectSmartCards = redirectSmartCards; MsRdpClient.AdvancedSettings2.ConnectionBarShowRestoreButton = false; MsRdpClient.attachEvent('OnConnected', OnConnected); MsRdpClient.attachEvent('OnDisconnected', OnDisconnected); MsRdpClient.connect(); }-*/; }
Python
UTF-8
2,770
2.65625
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
''' # # Run with python3 # Script that generates the Logos xclangspec # # xclangspec_generator is a script created by pr0crustes (https://github.com/pr0crustes) # that is provided as it is, without any warranty. # pr0crustes @ 2018 - all rights reserved. # ''' import os global_new_keywords = [ "// Start Logos Keywords", "%group", "%hook", "%new", "%subclass", "%property", "%end", "%config", "%hookf", "%ctor", "%dtor", "%init", "%class", "%c", "%orig", "%log", "// End Logos Keywords", "// Start Other Keywords", "NSLog", "NSString", "NSInteger", "NSObject", "// End Other Keywords" ] global_ident1 = "Words = (" global_ident2 = "Chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";" global_ident3 = "StartChars = \"@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_\";" class XClangGenerator(object): def __init__(self): self.objc_spec_file = "/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/ObjectiveC.xclangspec" self.objc_spec_content = [] self.new_lines = [] def __get_loaded_file(self): print("Reading File...") for line in open(self.objc_spec_file, 'r'): if line.strip() and not line.strip().startswith("/"): self.objc_spec_content.append(line) def __get_parsed_file(self): print("Parsing File...") for i in range(len(self.objc_spec_content)): line = self.objc_spec_content[i].replace("objc", "logos") self.new_lines.append(line) if global_ident1 in line and i > 3 and global_ident2 in self.objc_spec_content[i-1] and global_ident3 in self.objc_spec_content[i-2]: print("Inserting Logos Keywords Into New File...") for new_word in global_new_keywords: if new_word.strip().startswith("//"): self.new_lines.append("\t\t\t\t" + new_word + "\n") else: self.new_lines.append("\t\t\t\t\"" + new_word + "\",\n") def __save_file(self): print("Saving New File...") with open("Logos.xclangspec", "w") as file: file.write("// Logos xclangspec was generated by spec_gen\n") file.write("// Script made by pr0crustes\n") for line in self.new_lines: file.write(line) def execute(self): self.__get_loaded_file() self.__get_parsed_file() self.__save_file() print("XClangSpec Generator was successfully runned.") if __name__ == '__main__': os.rename("Logos.xc", "Logos.xclangspec") gen = XClangGenerator() gen.execute()
C#
UTF-8
3,660
3.125
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace C_SharpNote.Helper { public static class HolidayHelper { public static bool IsHolidays(DateTime date) { // 週休二日 if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) return true; // 國定假日(國曆) if (date.ToString("MM/dd").Equals("01/01")) return true; if (date.ToString("MM/dd").Equals("02/28")) return true; if (date.ToString("MM/dd").Equals("04/04")) return true; if (date.ToString("MM/dd").Equals("04/05")) return true; if (date.ToString("MM/dd").Equals("05/01")) return true; if (date.ToString("MM/dd").Equals("10/10")) return true; // 國定假日(農曆) if (GetLeapDate(date, false).Equals("12/" + GetDaysInLeapMonth(date))) return true; if (GetLeapDate(date, false).Equals("1/1")) return true; if (GetLeapDate(date, false).Equals("1/2")) return true; if (GetLeapDate(date, false).Equals("1/3")) return true; if (GetLeapDate(date, false).Equals("1/4")) return true; if (GetLeapDate(date, false).Equals("1/5")) return true; if (GetLeapDate(date, false).Equals("5/5")) return true; if (GetLeapDate(date, false).Equals("8/15")) return true; // 公司假日 //日期是否在特定節日,資料庫有資料則為假日 //if (CheckHoliday(date)) return true; //日期是否在公司設定節日,資料庫有資料則為假日 //if (CheckDeductionSh(date)) return true; return false; } ///<summary> /// 取得農曆日期 ///</summary> public static string GetLeapDate(DateTime Date, bool bShowYear = true, bool bShowMonth = true) { int L_ly, nLeapYear, nLeapMonth; ChineseLunisolarCalendar MyChineseLunisolarCalendar = new ChineseLunisolarCalendar(); nLeapYear = MyChineseLunisolarCalendar.GetYear(Date); nLeapMonth = MyChineseLunisolarCalendar.GetMonth(Date); if (MyChineseLunisolarCalendar.IsLeapYear(nLeapYear)) //判斷此農曆年是否為閏年 { L_ly = MyChineseLunisolarCalendar.GetLeapMonth(nLeapYear); //抓出此閏年閏何月 if (nLeapMonth >= L_ly) { nLeapMonth--; } } else { nLeapMonth = MyChineseLunisolarCalendar.GetMonth(Date); } if (bShowYear) { return "" + MyChineseLunisolarCalendar.GetYear(Date) + "/" + nLeapMonth + "/" + MyChineseLunisolarCalendar.GetDayOfMonth(Date); } else if (bShowMonth) { return "" + nLeapMonth + "/" + MyChineseLunisolarCalendar.GetDayOfMonth(Date); } else { return "" + MyChineseLunisolarCalendar.GetDayOfMonth(Date); } } ///<summary> /// 取得某一日期的該農曆月份的總天數 ///</summary> public static string GetDaysInLeapMonth(DateTime date) { ChineseLunisolarCalendar MyChineseLunisolarCalendar = new ChineseLunisolarCalendar(); return "" + MyChineseLunisolarCalendar.GetDaysInMonth(MyChineseLunisolarCalendar.GetYear(date), date.Month); } } }
Markdown
UTF-8
642
2.796875
3
[]
no_license
--- layout: blog title: How to mock localhost IP address for geocoding in Rails --- # {{ page.title }} This took me a while to figure out, so I figured I'd write down my solution in case someone else is trying to do the same thing. I'm using the Geocoder gem for [Townstage](http://townstage.com), and when testing locally, it can't geocode my location because my ip address is localhost: 127.0.0.1. I'd much prefer to hard code the ip address so when testing locally, it thinks I'm always in, say, Ann Arbor. Here's how I did it: {% highlight ruby %} class Rack::Request def ip '98.209.117.83' end end {% endhighlight %} Voila!
Markdown
UTF-8
821
2.625
3
[]
no_license
# toyexample An MVC-inspired multiplayer "game" for educational purposes. Part of the Web Development course at Harokopio University in Athens (http://www.dit.hua.gr) Essentially it is only an attempt to have a server managing client connections and user actions by calculating the state of the model, i.e. one square for each user moving around. The client is receiving the model (array of objects) every 40 ms and draws them in a canvas. "Installation" Clone or download project and run npm install so as to install the needed npm modules "Execution" npm start OR nodejs server.js run the client at http://localhost:3000/client.html The server is listening on port 3000 and the domain is hardcoded in the client's request for a websocket connection to "localhost". Make sure to adapt accordingly.
Java
UTF-8
211
1.734375
2
[]
no_license
package behavioral.State; public final class StateSet { public static int NEW = 1; public static int RUNNABLE = 1; public static int RUNNING = 1; public static int BLOCK = 1; public static int DEAD = 1; }
C
UTF-8
573
3.1875
3
[]
no_license
struct Node{ { int data; Node* left; Node* right; }; /*Your code here*/ #include<vector> void func1(Node *root,vector<int> &v) { if(root==NULL) return; v.push_back(root->data); func1(root->left,v); func1(root->right,v); } void func2(Node *root,vector<int> &v,int &c) { if(root==NULL) return; func2(root->left,v,c); root->data=v[c]; c++; func2(root->right,v,c); } Node *binaryTreeToBST (Node *root) { vector<int> v; func1(root,v); int c=0; sort(v.begin(),v.end()); func2(root,v,c); return root; }
Shell
UTF-8
1,122
3.046875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash set -e if [[ "$OSTYPE" == "darwin"* ]]; then if [[ -z ${VM_DRIVER+x} ]]; then VM_DRIVER=hyperkit fi fi if [[ ! -z ${VM_DRIVER+x} ]]; then VM_DRIVER_SWITCH="--vm-driver=${VM_DRIVER}" fi if [[ -n "${KUBE_VER}" ]]; then MINIKUBE_KUBE_VERSION="--kubernetes-version=${KUBE_VER}" fi if [[ "$OSTYPE" == "darwin"* ]]; then minikube start ${VM_DRIVER_SWITCH} ${MINIKUBE_KUBE_VERSION} --extra-config=apiserver.v=4 else CHANGE_MINIKUBE_NONE_USER=true sudo minikube start ${VM_DRIVER_SWITCH} ${MINIKUBE_KUBE_VERSION} --extra-config=apiserver.v=4 fi JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}'; until kubectl get nodes -o jsonpath="$JSONPATH" 2>&1 | grep -q "Ready=True"; do sleep 1; echo "waiting for kubernetes node to be available" done JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}'; until kubectl -n kube-system get pods -lk8s-app=kube-dns -o jsonpath="$JSONPATH" 2>&1 | grep -q "Ready=True"; do sleep 1;echo "waiting for kube-dns to be available"; done
Python
UTF-8
2,046
2.75
3
[]
no_license
import numpy as np from keras.models import Sequential from keras.layers import Dense, Conv1D, MaxPooling1D, Dropout, LSTM from keras.layers.embeddings import Embedding from keras.preprocessing import sequence from keras.datasets import imdb top_words = 20000 (training_data, training_targets), (testing_data, testing_targets) = imdb.load_data(num_words=top_words) data = np.concatenate((training_data, testing_data), axis=0) targets = np.concatenate((training_targets, testing_targets), axis=0) targets = np.array(targets).astype("float32") # test_x = data[:10000] # test_y = targets[:10000] # train_x = data[10000:] # train_y = targets[10000:] max_review_length = 500 # train_x = sequence.pad_sequences(train_x, maxlen=max_review_length) # test_x = sequence.pad_sequences(test_x, maxlen=max_review_length) embedding_vector_length = 128 for i in range(0, 5): test_x = data[i * 10000:(i + 1) * 10000] test_y = targets[i * 10000:(i + 1) * 10000] train_x = np.concatenate([data[:i * 10000], data[(i + 1) * 10000:]], axis=0) train_y = np.concatenate([targets[:i * 10000], targets[(i + 1) * 10000:]], axis=0) train_x = sequence.pad_sequences(train_x, maxlen=max_review_length) test_x = sequence.pad_sequences(test_x, maxlen=max_review_length) model = Sequential() model.add(Embedding(top_words, embedding_vector_length, input_length=max_review_length)) model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu')) model.add(MaxPooling1D(pool_size=2)) model.add(LSTM(128, return_sequences=True)) model.add(Dropout(0.5)) model.add(LSTM(64)) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(train_x, train_y, validation_data=(test_x, test_y), epochs=3, batch_size=64) model.save('model' + str(i) + '.h5') # models.append(model) # scores = model.evaluate(test_x, test_y, verbose=False) # print("Accuracy: %.2f%%" % (scores[1]*100))
Python
UTF-8
5,490
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- import pickle from collections import OrderedDict import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy.stats import gaussian_kde from astropy.cosmology import WMAP9 as cosmo from scipy.ndimage.filters import gaussian_filter1d from matplotlib.font_manager import FontProperties DATA_DIR = "data/" def make_kde(val, rg=None, bins=None,): ax = np.linspace(rg[0], rg[1], 2 * bins + 1)[1::2] kde = gaussian_kde(val[np.isfinite(val)],) return ax, kde(ax) def get_attributes(data_file, rowmask_file): """ Uses redshift and labels & returns redshifts, valid redshifts, and idxf idxf is map from each class name to a list that is the same length as the number of samples in the dataset. for each one, it is True or False, based on whether that sample contains that label. """ data = np.load(DATA_DIR + data_file, allow_pickle=True) rowmask = np.load(DATA_DIR + rowmask_file, allow_pickle=True) z = data['redshift'] valid_z = np.isfinite(z) idxf = {r: rowmask[r] == 1 for r in list(rowmask.dtype.names)} return z, valid_z, idxf if __name__ == '__main__': """ Catalog is assembled-v6.npy which is a Numpy recarray, it contains a column for 'redshift' which has the corresponding redshift for each sample 'typerowmask-v6.npy' contains information about the labels for each sample in the catalog. It's basically a list of one hot vectors. The ordering of each Numpy array is the same as rowmask.dtype.names and idxf.keys() """ zred, valid_z, idxf = get_attributes( data_file='orig_assembled-v6.npy', rowmask_file='orig_typerowmask-v6.npy') allmags_zred, allmags_valid_z, allmags_idxf = get_attributes( data_file='allmags_data.npy', rowmask_file='allmags_rowmask.npy') submags_zred, submags_valid_z, submags_idxf = get_attributes( data_file='subsetmags_data.npy', rowmask_file='subsetmags_rowmask.npy') # read simulated LSST events. with open('lsst-sims.pk', 'rb') as f: lsst_sims = pickle.load(f) bin_range = { 'Ia': (0., 1.25), 'Ia-91bg': (0., 0.60), 'Ia-02cx': (0., 0.80), 'II': (0., 1.00), 'Ibc': (0., 0.80), 'SLSN-I': (0., 3.25), 'TDE': (0., 1.75), } N_bins = { 'Ia': 48, 'Ia-91bg': 32, 'Ia-02cx': 24, 'II': 48, 'Ibc': 32, 'SLSN-I': 16, 'TDE': 24, } alt_keys = { 'Ibc': idxf['SE'], 'TDE': idxf['TDE'], } allmags_alt_keys = { 'Ibc': allmags_idxf['SE'], 'TDE': allmags_idxf['TDE'], } submags_alt_keys = { 'Ibc': submags_idxf['SE'], 'TDE': submags_idxf['TDE'], } # draw panels. # fig = plt.figure(figsize=(12., 12.), dpi=80, sharex=True) fig, axes = plt.subplots(3, 2, sharex=True, sharey=True, figsize=(12, 12)) cmap = mpl.cm.get_cmap('Set1') classes = ['Ia', 'Ia-91bg', 'II', 'Ibc', 'SLSN-I', 'TDE'] i_tp = 0 for i, row in enumerate(axes): for j, cell in enumerate(row): tp_i = classes[i_tp] i_tp += 1 objid_i, zred_tp_i, snr_max_i, snr_min_i = lsst_sims[tp_i] idxf_i = alt_keys[tp_i] if tp_i in alt_keys else idxf[tp_i] allmags_idxf_i = allmags_alt_keys[ tp_i] if tp_i in allmags_alt_keys else allmags_idxf[tp_i] submags_idxf_i = submags_alt_keys[ tp_i] if tp_i in submags_alt_keys else submags_idxf[tp_i] axi = axes[i, j] if i == 2: axi.xaxis.set_major_formatter(mpl.ticker.FormatStrFormatter('%.1f')) axi.set_xlabel("Redshift") if j == 0: axi.set_ylabel("Normalized density") fixed_width = 1.2 # All mags axi.hist(allmags_zred[allmags_valid_z * allmags_idxf_i], color="#4187e8", label=tp_i + ' (all-features)', range=bin_range[tp_i], bins=N_bins[tp_i], density=True, histtype='bar', stacked=True) axi.hist(submags_zred[submags_valid_z * submags_idxf_i], color="#66ff66", label=tp_i + ' (g-W2)', range=bin_range[tp_i], bins=N_bins[tp_i], density=True, histtype='bar', stacked=True) axi.hist(zred_tp_i, color="#ff99ff", label=tp_i + ' (LSST, All)', range=bin_range[tp_i], bins=N_bins[tp_i], density=True, histtype='step', stacked=True) axi.hist(zred_tp_i[snr_min_i > 25], color="#660066", linewidth=fixed_width, label=tp_i + ' (LSST, SNR > 25)', range=bin_range[tp_i], bins=N_bins[tp_i], density=True, histtype='step', stacked=True) axi.legend(loc='upper right') plt.xlim(0, 1.5) plt.xticks(np.linspace(0, 1.5, 15)) plt.savefig('redshift_dist_data_vs_lsst.png') plt.show()
Python
UTF-8
3,287
2.546875
3
[]
no_license
import locale import requests from django import template from requests.auth import HTTPBasicAuth import ast register = template.Library() @register.filter(name='multiply') def multiply(value, arg): return value * arg @register.filter(name='thousand') def thousand(number): locale.setlocale(locale.LC_NUMERIC, 'pl_PL') number = format(number, 'n') return number @register.filter(name='get_image') def get_business_image(img): URL = "https://api.yelp.com/v3/businesses/" + img headers = { "Authorization": "Bearer XxMwpmqG1ZCITKpSg35VNpTFGHOXyFcttiQwC87xV1wLcVdm1-jeJRztnOX4q9LAMxZUaWovmYtWJeFGs5zWUqRYjHskMkaI-3IGXvjhq66oHGlQPhmsFmkvNnrJXnYx"} request = requests.get(url=URL, headers=headers).json() request = dict(request) first = list(request.keys())[0] if first == "id": return request['image_url'] else: return "https://image.freepik.com/vecteurs-libre/restaurant-logo-modele_1236-155.jpg" @register.filter(name='size') def get_friends_size(friends_list): if not friends_list: return 0 else: tab = friends_list.split(",") return len(tab) @register.filter(name='get_date') def get_friends_size(date): date = date[0:10] return date @register.filter(name='sort_day') def sort_day(hours): mapping = {'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6} hours = sorted(hours.items(), key=lambda x: mapping[x[0]]) return hours @register.filter(name='sort_month') def sort_month(months): mapping = {'January': 0, 'February': 1, 'March': 2, 'April': 3, 'May': 4, 'June': 5, 'July': 6, 'August': 7, 'September': 8, 'October': 9, 'November': 10, 'December': 11} months = sorted(months.items(), key=lambda x: mapping[x[0]]) return months @register.filter(name="vf") def vf(att): if att == "True": return "Yes" if att == "False": return "No" else: return att @register.filter(name="get_name") def get_name(user_id): ENDPOINT = 'http://47.91.72.40:9200/' auth = HTTPBasicAuth('elastic', 'Couronne3...') URL = ENDPOINT + 'yelp-user*' + '/_search' filter_path = 'hits.hits._source' query = 'user_id:"' + user_id + '"' field = 'name' PARAMS = {'filter_path': filter_path, 'q': query, '_source_includes': field} request = requests.get(url=URL, params=PARAMS, auth=auth) data = request.json() name = data['hits']['hits'][0]['_source']['name'] if name: return name else: return "Unknown" @register.filter(name='get_3') def get_friends_size(day): day = day[0:3] return day @register.filter(name='get_value') def get_value(value): if value.startswith('{'): return True else: return False @register.filter(name='convert_list') def convert_list(value): value_list = list() value = ast.literal_eval(value) for k, v in value.items(): if v == False: v = "No" if v == True: v = "Yes" new_value = str(k) + ' : ' + str(v) value_list.append(new_value) return value_list @register.filter(name='replace_str') def replace_str(value): value = value.replace("u'", "") value = value.replace("'", "") return value @register.filter(name='int') def convert_int(value): return int(value)
Java
UTF-8
4,382
2.25
2
[]
no_license
package com.szc.netty.learn.rpc.remoting.client; import static com.szc.netty.learn.rpc.utils.GloabalConstants.DEFAULT_IO_THREADS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.szc.netty.learn.rpc.codec.Request; import com.szc.netty.learn.rpc.codec.RpcDecoder; import com.szc.netty.learn.rpc.codec.RpcEncoder; import com.szc.netty.learn.rpc.remoting.RemotingException; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * NettyClient. */ public class NettyClient extends AbstractClient { private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); private NioEventLoopGroup nioEventLoopGroup; private Bootstrap bootstrap; private Channel channel; public NettyClient(String host, Integer port, int connectTimeout) throws RemotingException { super(host, port, connectTimeout); } @Override protected void doOpen() throws Throwable { NettyClientHandler nettyClientHandler = new NettyClientHandler(this); bootstrap = new Bootstrap(); nioEventLoopGroup = new NioEventLoopGroup(DEFAULT_IO_THREADS, new DefaultThreadFactory("NettyClientWorker", true)); bootstrap.group(nioEventLoopGroup) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()) .channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline() .addLast(new RpcDecoder()) .addLast(new RpcEncoder()) .addLast(nettyClientHandler); } }); } @Override protected void doConnect() throws Throwable { ChannelFuture future = bootstrap.connect(getConnectAddress()); try { boolean ret = future.awaitUninterruptibly(3000L, MILLISECONDS); if (ret && future.isSuccess()) { Channel newChannel = future.channel(); try { // Close old channel // copy reference Channel oldChannel = NettyClient.this.channel; if (oldChannel != null) { try { if (logger.isInfoEnabled()) { logger.info( "Close old netty channel " + oldChannel + " on create new netty channel " + newChannel); } oldChannel.close(); } finally { // NettyChannel.removeChannelIfDisconnected(oldChannel); } } } finally { if (NettyClient.this.isClosed()) { try { if (logger.isInfoEnabled()) { logger .info("Close new netty channel " + newChannel + ", because the client closed."); } newChannel.close(); } finally { NettyClient.this.channel = null; } } else { NettyClient.this.channel = newChannel; } } } } finally { // just add new valid channel to NettyChannel's cache if (!isConnected()) { //future.cancel(true); } } } @Override protected void doClose() throws Throwable { nioEventLoopGroup.shutdownGracefully(); } @Override protected void doDisConnect() throws Throwable { } @Override protected Channel getChannel() { return channel; } @Override public DefaultFuture send(Object msg) throws Throwable { Request request = (Request) msg; if (!isConnected()) { connect(); } DefaultFuture f = DefaultFuture.newFuture(getChannel(), request, 300000); try { getChannel().writeAndFlush(msg); } catch (Exception e) { f.cancel(); } return f; } }
Java
UTF-8
691
3.53125
4
[]
no_license
package com.fastdata.algorithm.easy.tree; /** * @Author: Lucky * @Description: https://leetcode.com/problems/trim-a-binary-search-tree/ * @Date: create in 1/13/21 - 12:47 PM */ public class TrimABinarySearchTree { public TreeNode trimBST(TreeNode root, int low, int high) { // base case if (root == null) return null; /** * 根据BST的定义,左子树小于右子树 */ if (root.val < low) return trimBST(root.right, low, high); if (root.val > high) return trimBST(root.left, low, high); root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high); return root; } }
C
UTF-8
1,090
3.546875
4
[]
no_license
//Merge sort is better for larger size arrays than quick sort #include <stdio.h> #include <stdlib.h> void merge(long *arr,int l,int mid,int r) { long *temp=(long *)malloc(sizeof(long)*(r-l+1)); int l1=l,r1=mid+1,i=0; while(l1<=mid&&r1<=r) { if(arr[l1]>arr[r1]){ temp[i]=arr[r1]; r1++; } else{ temp[i]=arr[l1]; l1++; } i++; } while(l1<=mid) { temp[i]=arr[l1]; l1++; i++; } while(r1<=r) { temp[i]=arr[r1]; r1++; i++; } i=0; for(l1=l;l1<=r;l1++) { arr[l1]=temp[i]; i++; } } void mergesort(long *arr,int l,int r) { if(r>l) { int mid=(l+r)/2; mergesort(arr,l,mid); mergesort(arr,mid+1,r); merge(arr,l,mid,r); } } int main(void) { int n,i; long arr[100001]; scanf("%d",&n); for(i=0;i<n;i++) scanf("%ld",&arr[i]); mergesort(&arr[0],0,n-1); for(i=0;i<n;i++) printf("%ld ",arr[i]); printf("%d",i); return 0; }
SQL
UTF-8
689
4.65625
5
[]
no_license
SELECT CONCAT(to_char(weeks.week_start, 'YYYY-MM-DD'), ' - ', to_char(weeks.week_end, 'YYYY-MM-DD')) AS week, coffeeshops.name, employees.name, max_revenue.revenue FROM ( SELECT DISTINCT ON(week_id) week_id, employee_id, revenue FROM ( SELECT t.week_id, t.employee_id, SUM(t.price) AS revenue FROM transactions AS t GROUP BY t.week_id, t.employee_id ORDER BY t.week_id, revenue DESC ) AS t ) AS max_revenue INNER JOIN weeks ON max_revenue.week_id = weeks.id INNER JOIN employees ON max_revenue.employee_id = employees.id INNER JOIN coffeeshops ON coffeeshops.id = employees.coffeeshop_id ORDER BY weeks.id
Python
UTF-8
21,684
2.625
3
[]
no_license
import util import string from emptyContainer import EmptyContainer from tkinter import * from tkinter import messagebox class AnamneseContainer(EmptyContainer): def __init__(self, father, nome, dir): super().__init__() self.father = father self.nome = nome self.dir = dir # ____ FRAME PRINCIPAL self.root = Frame(self) self.root.pack(fill="both", expand="True") # ____ FRAME DA ESQUERDA self.frameLeft = Frame(self.root, border=1, relief="groove") self.frameLeft.grid(column=0, row=0, sticky=N + S + E + W) # NOME Label(self.frameLeft, font='bold', text="Nome").grid(row=0, column=0, sticky=W, padx=5, pady=5) self.eNome = Entry(self.frameLeft, width=20, font='bold') self.eNome.grid(row=0, column=1, sticky=W + E, padx=5, pady=5) self.labelExame = Label(self.frameLeft, font='bold', text="Exame") self.labelExame.grid(row=1, column=0, sticky=W, padx=5, pady=5) self.eExame = Entry(self.frameLeft, width=13, font='bold', state=DISABLED) self.eExame.grid(row=1, column=1, sticky=W + E, padx=5, pady=5) Label(self.frameLeft, font=("Helvetica", 18, "bold"), text="Status").grid(row=2, column=0, columnspan=2, sticky=W + E + N, padx=5, pady=5) self.varExame = BooleanVar() self.varExame.set(False) self.checkExame = Checkbutton(self.frameLeft, var=self.varExame, state=DISABLED, offvalue=False, onvalue=True) self.checkExame.grid(row=3, column=0, sticky=N + S + E, padx=3, pady=3) Label(self.frameLeft, font=("Helvetica", 18), justify=LEFT, text="Exame").grid(row=3, column=1, sticky=N + S + W) self.varProcessamento = BooleanVar() self.varProcessamento.set(False) self.checkProcessamento = Checkbutton(self.frameLeft, var=self.varProcessamento, state=DISABLED, offvalue=False, onvalue=True) self.checkProcessamento.grid(row=6, column=0, sticky=N + S + E, padx=3, pady=3) Label(self.frameLeft, font='bold', justify=LEFT, text="Processamento").grid(row=6, column=1, sticky=N + S + W) self.varResultados = BooleanVar() self.varResultados.set(False) self.checkResultados = Checkbutton(self.frameLeft, var=self.varResultados, state=DISABLED, offvalue=False, onvalue=True) self.checkResultados.grid(row=7, column=0, sticky=N + S + E, padx=3, pady=3) Label(self.frameLeft, font='bold', justify=LEFT, text="Resultados").grid(row=7, column=1, sticky=N + S + W) Label(self.frameLeft, height=19, text=" ").grid(row=9, column=0, sticky=N + S + W + E) self.frameButtons = Frame(self.frameLeft) self.frameButtons.grid(column=0, row=10, columnspan=2, sticky=N + S + E + W) # Botão de próxima etapa e etapa anterior self.btnAnterior = Button(self.frameButtons, text="Atapa anterior", state=DISABLED) self.btnAnterior.grid(column=0, row=0, padx=15, pady=5, sticky=N + S + W) self.btnProxima = Button(self.frameButtons, text="Próxima etapa", command=lambda: self._proximaEtapa(), state=DISABLED) self.btnProxima.grid(column=1, row=0, padx=15, pady=5, sticky=N + S + W) # ____ FRAME DA DIREITA self.frameRight = Frame(self.root) self.frameRight.grid(column=1, row=0, sticky=N + S + E + W) # LINHA 0 # FRAME DE ANAMNESE 1 fAnamnese1 = Frame(self.frameRight, border=1, relief="groove") fAnamnese1.pack() # Anamnese linha 1 Label(fAnamnese1, text="Possui problema de saúde?").grid(row=1, column=0, sticky=W, padx=3, pady=3) self.vPSaude = StringVar() self.vPSaude.set("N") self.radioSPSaude = Radiobutton(fAnamnese1, text="Sim", state=DISABLED, variable=self.vPSaude, value="S", command=self._changePSaude) self.radioSPSaude.grid(row=1, column=1, sticky=W, padx=3, pady=3) self.radioNPSaude = Radiobutton(fAnamnese1, text="Não", state=DISABLED, variable=self.vPSaude, value="N", command=self._changePSaude) self.radioNPSaude.grid(row=1, column=2, sticky=W, padx=3, pady=3) Label(fAnamnese1, text="Qual?").grid(row=1, column=3, sticky=W, padx=3, pady=3) self.ePSaude = Entry(fAnamnese1, width=48, state=DISABLED) self.ePSaude.config(state='disabled') self.ePSaude.grid(row=1, column=4, sticky=W + E, padx=3, pady=3) # Anamnese linha 2 Label(fAnamnese1, text="Usa algum medicamento?").grid(row=2, column=0, sticky=W, padx=3, pady=3) self.vMedicamento = StringVar() self.vMedicamento.set("N") self.radioSMedicamento = Radiobutton(fAnamnese1, text="Sim", state=DISABLED, variable=self.vMedicamento, value="S", command=self._changeMedicamento) self.radioSMedicamento.grid(row=2, column=1, sticky=W, padx=3, pady=3) self.radioNMedicamento = Radiobutton(fAnamnese1, text="Não", state=DISABLED, variable=self.vMedicamento, value="N", command=self._changeMedicamento) self.radioNMedicamento.grid(row=2, column=2, sticky=W, padx=3, pady=3) Label(fAnamnese1, text="Qual?").grid(row=2, column=3, sticky=W, padx=3, pady=3) self.eMedicamento = Entry(fAnamnese1, state=DISABLED) self.eMedicamento.config(state='disabled') self.eMedicamento.grid(row=2, column=4, sticky=W + E, padx=3, pady=3) # Anamnese linha 3 Label(fAnamnese1, text="Está sob algum tratamento médico?").grid(row=3, column=0, sticky=W, padx=3, pady=3) self.vTratamento = StringVar() self.vTratamento.set("N") self.radioSTratamento = Radiobutton(fAnamnese1, text="Sim", state=DISABLED, variable=self.vTratamento, value="S", command=self._changeTratamento) self.radioSTratamento.grid(row=3, column=1, sticky=W, padx=3, pady=3) self.radioNTratamento = Radiobutton(fAnamnese1, text="Não", state=DISABLED, variable=self.vTratamento, value="N", command=self._changeTratamento) self.radioNTratamento.grid(row=3, column=2, sticky=W, padx=3, pady=3) Label(fAnamnese1, text="Por que?").grid(row=3, column=3, sticky=W, padx=3, pady=3) self.eTratamento = Entry(fAnamnese1, state=DISABLED) self.eTratamento.config(state='disabled') self.eTratamento.grid(row=3, column=4, sticky=W + E, padx=3, pady=3) # Anamnese linha 4 Label(fAnamnese1, text="Possui alergia a algum medicamento?").grid(row=4, column=0, sticky=W, padx=3, pady=3) self.vAlergia = StringVar() self.vAlergia.set("N") self.radioSAlergia = Radiobutton(fAnamnese1, text="Sim", state=DISABLED, variable=self.vAlergia, value="S", command=self._changeAlergia) self.radioSAlergia.grid(row=4, column=1, sticky=W, padx=3, pady=3) self.radioNAlergia = Radiobutton(fAnamnese1, text="Não", state=DISABLED, variable=self.vAlergia, value="N", command=self._changeAlergia) self.radioNAlergia.grid(row=4, column=2, sticky=W, padx=3, pady=3) Label(fAnamnese1, text="Qual?").grid(row=4, column=3, sticky=W, padx=3, pady=3) self.eAlergia = Entry(fAnamnese1, state=DISABLED) self.eAlergia.config(state='disabled') self.eAlergia.grid(row=4, column=4, sticky=W + E, padx=3, pady=3) # Anamnese linha 5 Label(fAnamnese1, text="Usa lentes corretivas?").grid(row=5, column=0, sticky="W", padx=3, pady=3) self.vLentes = StringVar() self.vLentes.set("N") self.radioLLentes = Radiobutton(fAnamnese1, text="Lentes", state=DISABLED, variable=self.vLentes, value="L") self.radioLLentes.grid(row=5, column=1, sticky=W, padx=3, pady=3) self.radioOLentes = Radiobutton(fAnamnese1, text="Óculos", state=DISABLED, variable=self.vLentes, value="O") self.radioOLentes.grid(row=5, column=2, sticky=W, padx=3, pady=3) self.radioNLentes = Radiobutton(fAnamnese1, text="Não", state=DISABLED, variable=self.vLentes, value="N") self.radioNLentes.grid(row=5, column=3, sticky=W, padx=3, pady=3) # FRAME DE ANAMNESE 2 fAnamnese2 = Frame(self.frameRight, border=1, relief="groove") fAnamnese2.pack() textTam = 830 self.varAnamnese1 = BooleanVar() self.varAnamnese1.set(False) self.checkAnamnese1 = Checkbutton(fAnamnese2, var=self.varAnamnese1, state=DISABLED, offvalue=False, onvalue=True) self.checkAnamnese1.grid(row=0, column=0, sticky=N + S + W, padx=3, pady=5) Label(fAnamnese2, justify=LEFT, wraplength=textTam, text="Nistagmo não fatigável?").grid(row=0, column=1, sticky=N + S + W, padx=5, pady=5) self.varAnamnese2 = BooleanVar() self.varAnamnese2.set(False) self.checkAnamnese2 = Checkbutton(fAnamnese2, var=self.varAnamnese2, state=DISABLED, offvalue=False, onvalue=True) self.checkAnamnese2.grid(row=1, column=0, sticky=N + S + W, padx=3, pady=5) Label(fAnamnese2, justify=LEFT, wraplength=textTam, text="Nistagmo posicional é vertical puro e pode mudar de direção à mudança da posição da cabeça?").grid(row=1, column=1, sticky=N + S + W, padx=5, pady=5) self.varAnamnese3 = BooleanVar() self.varAnamnese3.set(False) self.checkAnamnese3 = Checkbutton(fAnamnese2, var=self.varAnamnese3, state=DISABLED, offvalue=False, onvalue=True) self.checkAnamnese3.grid(row=2, column=0, sticky=N + S + W, padx=3, pady=5) Label(fAnamnese2, justify=LEFT, wraplength=textTam, text="Nistagmo posicional é contínuo se o posicionamento desencadeante é mantido, com ou sem mudança de direção nas diferentes posições da cabeça?").grid(row=2, column=1, sticky=N + S + W, padx=5, pady=5) self.varAnamnese4 = BooleanVar() self.varAnamnese4.set(False) self.checkAnamnese4 = Checkbutton(fAnamnese2, var=self.varAnamnese4, state=DISABLED, offvalue=False, onvalue=True) self.checkAnamnese4.grid(row=3, column=0, sticky=N + S + W, padx=3, pady=5) Label(fAnamnese2, justify=LEFT, wraplength=textTam, text="Vertigem acompanhada ou não de desequilíbrio transitório ou duradouro à marcha? (Em episódios agudos, pode acompanhar nistagmo espontâneo, posicional ou de posicionamento, náuseas e vômitos)").grid(row=3, column=1, sticky=N + S + W, padx=5, pady=5) self.varAnamnese5 = BooleanVar() self.varAnamnese5.set(False) self.checkAnamnese5 = Checkbutton(fAnamnese2, var=self.varAnamnese5, state=DISABLED, offvalue=False, onvalue=True) self.checkAnamnese5.grid(row=4, column=0, sticky=N + S + W, padx=3, pady=5) Label(fAnamnese2, justify=LEFT, wraplength=textTam, text="Acompanha crises de nevralgia do trigêmio, espasmo facial e nevralgia glossofaríngea? A intensa vertigem posicional ou de posicionamento é acompanhada de desequilíbrio e osciloscopia?").grid(row=4, column=1, sticky=N + S + W, padx=5, pady=5) self.varAnamnese6 = BooleanVar() self.varAnamnese6.set(False) self.checkAnamnese6 = Checkbutton(fAnamnese2, var=self.varAnamnese6, state=DISABLED, offvalue=False, onvalue=True) self.checkAnamnese6.grid(row=5, column=0, sticky=N + S + W, padx=3, pady=5) Label(fAnamnese2, justify=LEFT, wraplength=textTam, text="Vertigens são posicionais intensas, acompanhadas de nistagmo posicional e/ou de posicionamento, sucedendo quadro clínico de vertigem aguda, por trombose da artéria vestibular anterior?").grid(row=5, column=1, sticky=N + S + W, padx=5, pady=5) self.btnExame = Button(self.frameRight, text="Realizar exame", font="bold", command=lambda: self._gravar()) self.btnExame.pack(fill=BOTH, expand=1) self.btnProxima["state"] = NORMAL # ___ SE FOR UM NOVO EXAME if(self.dir is None): self.eNome["state"] = NORMAL self.eNome.delete(0, END) self.eNome.insert(0, self.nome) self.eNome["state"] = DISABLED self.labelExame.destroy() self.eExame.destroy() self.frameButtons.destroy() Label(self.frameLeft, height=5, text=" ").grid(row=10, column=0, sticky=N + S + W + E) self.radioSPSaude["state"] = NORMAL self.radioNPSaude["state"] = NORMAL self.radioSMedicamento["state"] = NORMAL self.radioNMedicamento["state"] = NORMAL self.radioSTratamento["state"] = NORMAL self.radioNTratamento["state"] = NORMAL self.radioSAlergia["state"] = NORMAL self.radioNAlergia["state"] = NORMAL self.radioLLentes["state"] = NORMAL self.radioOLentes["state"] = NORMAL self.radioNLentes["state"] = NORMAL self.checkAnamnese1["state"] = NORMAL self.checkAnamnese2["state"] = NORMAL self.checkAnamnese3["state"] = NORMAL self.checkAnamnese4["state"] = NORMAL self.checkAnamnese5["state"] = NORMAL self.checkAnamnese6["state"] = NORMAL # ___ SE FOR UM EXAME JÁ FEITO else: # Pega os dados da anamnese dadosExame = util.getExame(self.dir) # Nome self.eNome["state"] = NORMAL self.eNome.delete(0, END) self.eNome.insert(0, dadosExame['nome']) self.eNome["state"] = DISABLED # Número do exame self.eExame["state"] = NORMAL self.eExame.delete(0, END) self.eExame.insert(0, dadosExame['numero']) self.eExame["state"] = DISABLED # Checks de status if (str(dadosExame['exame']) is "S"): self.checkExame["state"] = NORMAL self.varExame.set(True) self.checkExame["state"] = DISABLED if (str(dadosExame['processamento']) is "S"): self.checkProcessamento["state"] = NORMAL self.varProcessamento.set(True) self.checkProcessamento["state"] = DISABLED if (str(dadosExame['resultados']) is "S"): self.checkResultados["state"] = NORMAL self.varResultados.set(True) self.checkResultados["state"] = DISABLED # Checks da anamnese 1 if (str(dadosExame['problemaSaude']) is "S"): self.radioSPSaude["state"] = NORMAL self.vPSaude.set("S") self.radioSPSaude["state"] = DISABLED self.ePSaude["state"] = NORMAL self.ePSaude.delete(0, END) self.ePSaude.insert(0, str(dadosExame['tProblemaSaude'])) self.ePSaude["state"] = DISABLED if (str(dadosExame['medicamento']) is "S"): self.radioSMedicamento["state"] = NORMAL self.vMedicamento.set("S") self.radioSMedicamento["state"] = DISABLED self.eMedicamento["state"] = NORMAL self.eMedicamento.delete(0, END) self.eMedicamento.insert(0, str(dadosExame['tMedicamento'])) self.eMedicamento["state"] = DISABLED if (str(dadosExame['tratamento']) is "S"): self.radioSTratamento["state"] = NORMAL self.vTratamento.set("S") self.radioSTratamento["state"] = DISABLED self.eTratamento["state"] = NORMAL self.eTratamento.delete(0, END) self.eTratamento.insert(0, str(dadosExame['tTratamento'])) self.eTratamento["state"] = DISABLED if (str(dadosExame['alergia']) is "S"): self.radioSAlergia["state"] = NORMAL self.vAlergia.set("S") self.radioSAlergia["state"] = DISABLED self.eAlergia["state"] = NORMAL self.eAlergia.delete(0, END) self.eAlergia.insert(0, str(dadosExame['tAlergia'])) self.eAlergia["state"] = DISABLED if (str(dadosExame['lentes']) is "L"): self.radioLLentes["state"] = NORMAL self.vLentes.set("L") self.radioLLentes["state"] = DISABLED if (str(dadosExame['lentes']) is "O"): self.radioOLentes["state"] = NORMAL self.vLentes.set("O") self.radioOLentes["state"] = DISABLED # Checks da anamnese 2 if (str(dadosExame['fatigavel']) is "S"): self.checkAnamnese1["state"] = NORMAL self.varAnamnese1.set(True) self.checkAnamnese1["state"] = DISABLED if (str(dadosExame['mudaPosicao']) is "S"): self.checkAnamnese2["state"] = NORMAL self.varAnamnese2.set(True) self.checkAnamnese2["state"] = DISABLED if (str(dadosExame['continuo']) is "S"): self.checkAnamnese3["state"] = NORMAL self.varAnamnese3.set(True) self.checkAnamnese3["state"] = DISABLED if (str(dadosExame['vertigem']) is "S"): self.checkAnamnese4["state"] = NORMAL self.varAnamnese4.set(True) self.checkAnamnese4["state"] = DISABLED if (str(dadosExame['navralgia']) is "S"): self.checkAnamnese5["state"] = NORMAL self.varAnamnese5.set(True) self.checkAnamnese5["state"] = DISABLED if (str(dadosExame['intensas']) is "S"): self.checkAnamnese6["state"] = NORMAL self.varAnamnese6.set(True) self.checkAnamnese6["state"] = DISABLED self.btnExame["text"] = "O exame já foi realizado" self.btnExame["state"] = DISABLED def _changePSaude(self): if self.vPSaude.get() is "S": self.ePSaude.config(state='normal') else: self.ePSaude.delete(0, END) self.ePSaude.config(state='disabled') def _changeMedicamento(self): if self.vMedicamento.get() is "S": self.eMedicamento.config(state='normal') else: self.eMedicamento.delete(0, END) self.eMedicamento.config(state='disabled') def _changeTratamento(self): if self.vTratamento.get() is "S": self.eTratamento.config(state='normal') else: self.eTratamento.delete(0, END) self.eTratamento.config(state='disabled') def _changeAlergia(self): if self.vAlergia.get() is "S": self.eAlergia.config(state='normal') else: self.eAlergia.delete(0, END) self.eAlergia.config(state='disabled') def _validate(self): if (self.vPSaude.get() == "S" and self.ePSaude.get() == ""): messagebox.showerror("Erro", "Expecificar o problema de saúde") self.ePSaude.focus_set() return False if (self.vMedicamento.get() == "S" and self.eMedicamento.get() == ""): messagebox.showerror("Erro", "Expecificar o medicamento") self.eMedicamento.focus_set() return False if (self.vTratamento.get() == "S" and self.eTratamento.get() == ""): messagebox.showerror("Erro", "Expecificar o tratamento") self.eTratamento.focus_set() return False if (self.vAlergia.get() == "S" and self.eAlergia.get() == ""): messagebox.showerror("Erro", "Expecificar qual medicament possui alergia") self.eAlergia.focus_set() return False return True def _gravar(self): if (self._validate()): # Cria o dicionário com os dados da anamnese exame = { "nome": self.eNome.get(), "exame": "S", "processamento": "N", "resultados": "N", "numero": "", "data": "", "hora": "", "problemaSaude": self.vPSaude.get(), "tProblemaSaude": self.ePSaude.get(), "medicamento": self.vMedicamento.get(), "tMedicamento": self.eMedicamento.get(), "tratamento": self.vTratamento.get(), "tTratamento": self.eTratamento.get(), "alergia": self.vAlergia.get(), "tAlergia": self.eAlergia.get(), "lentes": self.vLentes.get(), "fatigavel": self.varAnamnese1.get(), "mudaPosicao": self.varAnamnese2.get(), "continuo": self.varAnamnese3.get(), "vertigem": self.varAnamnese4.get(), "navralgia": self.varAnamnese5.get(), "intensas": self.varAnamnese6.get(), "t1": "", "t2": "", "t3": "", "t4": "", "t5": "", "t6": "", "t7": "", "t8": "", "frames": "", "fps": "" } self.father._gravar(exame, self.dir) def _etapaAnterior(self): print("Etapa anterior") def _proximaEtapa(self): self.father._preProcessamento(self.dir)
C++
UTF-8
421
3.09375
3
[]
no_license
/// LCM = (multiplication of 2 number) / gcd; #include<bits/stdc++.h> using namespace std; int main() { int a,b,t; while(cin>>a>>b) { int multi = a*b; while(b) { t = a; b = b%a; if(!b) break; a = b; b = t; } int gcd = a; int lcm = multi / gcd; cout<<lcm<<endl; } return 0; }
C++
UTF-8
1,417
3.03125
3
[]
no_license
// errors.hpp /**\file */ #pragma once #include <boost/system/error_code.hpp> namespace ss { using error_code = boost::system::error_code; namespace error { enum SessionError { Success = 0, PartialData, // in buffer contains partial request Size, }; class SessionErrorCategory final : public boost::system::error_category { public: SessionErrorCategory() : boost::system::error_category{0x5e3bf594e03e6721} { } const char *name() const noexcept override { return "SessionErrorCategory"; } std::string message(int ev) const override { SessionError condition = static_cast<SessionError>(ev); switch (condition) { case SessionError::Success: return "success"; case SessionError::PartialData: return "partial data in request buffer"; default: return "Unkhnown error condition: " + std::to_string(ev); } } }; const SessionErrorCategory sessionErrorCategory; constexpr error_code make_error_code(SessionError ev) noexcept { return boost::system::error_code{static_cast<int>(ev), sessionErrorCategory}; } inline bool isSessionErrorCategory(const boost::system::error_category &category) noexcept { return sessionErrorCategory == category; } } // namespace error } // namespace ss namespace boost::system { template <> struct is_error_code_enum<ss::error::SessionError> { static const bool value = true; }; } // namespace boost::system
C
UHC
256
4.0625
4
[]
no_license
// i -5 ʱȭ , Ʈ Ͽ i 0 α׷ ۼϼ. #include <stdio.h> void main(void) { int i = -5; printf("i = %d\n", i); i = i ^ i; printf("i = %d\n", i); }
PHP
UTF-8
869
2.84375
3
[]
no_license
<?php namespace PiotrJaworski\InternalLinking\Helper; /** * LinkBuilder class * * @author Piotr Jaworski */ class LinkBuilder implements \PiotrJaworski\InternalLinking\Helper\LinkBuilderInterface { /** * Build a link HTML * * @param array $link * @return string */ public function toHtml(array $link) { if(!$link['url']){ return $link['keyword']; } $css = $link['css_class'] ? "class='".$link['css_class']."'" : ""; $style = $link['style'] ? "style='".$link['style']."'" : ""; return "<a href='".$link['url']."' ".$css." ".$style." " . "target='". \PiotrJaworski\InternalLinking\Model\Link::getTargetValueById($link['target'])."' " . "title='".$link['keyword']."'>".$link['keyword']."</a>"; } }
Java
UTF-8
2,203
1.8125
2
[]
no_license
package com.dz.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.dz.dao.IEvaluateDao; import com.dz.entity.Evaluate; import com.dz.service.IEvaluateService; /** * 登陆业务实现类 * * @author GJ * @date 2015年4月15日 */ @Transactional(readOnly = false) @Service("evaluateService") public class EvaluateServiceImpl implements IEvaluateService { @Autowired IEvaluateDao evaluateDao; @Override public List<Evaluate> evaluateList(Evaluate evaluate) { String sql = "SELECT o FROM Evaluate o WHERE 1=1"; return evaluateDao.evaluateList(sql); } @Override public List<Evaluate> userevaluate(int userid, int start, int limit) { return evaluateDao.userevaluate(userid, start, limit); } @Override public void delete(Evaluate evaluate) { evaluateDao.delete(evaluate); } @Override public void saveORupdate(final Evaluate evaluate) { evaluateDao.saveORupdate(evaluate); } @Override public List<Evaluate> getevaluate(String type, int customId) { return evaluateDao.getevaluate(type, customId); } @Override public List<Evaluate> getevaluate(String type, int customId,int start, int limit) { return evaluateDao.getevaluate(type, customId, start, limit); } @Override public List<Evaluate> getevaluate(String type, int customId, String typeClass, String isReply) { return evaluateDao.getevaluate(type, customId, typeClass, isReply); } @Override public List<Evaluate> getIsReply(String type, int customId) { return evaluateDao.getIsReply(type, customId); } @Override public List<Evaluate> getTypeClass(String type, int customId) { return evaluateDao.getTypeClass(type, customId); } @Override public List<Evaluate> getTypeClass(String type, int customId, String typeClass, int start, int limit) { return evaluateDao.getTypeClass(type, customId, typeClass, start, limit); } @Override public List<Evaluate> getevaluate(int orderId) { return evaluateDao.getevaluate(orderId); } @Override public Evaluate get(int id) { return evaluateDao.get(id); } }
Java
UTF-8
1,429
2.484375
2
[]
no_license
package com.pawan.oauth2authorizationserver.security; /*package com.pawan.jsonwebtokensecurity.security; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.pawan.jsonwebtokensecurity.model.Role; import com.pawan.jsonwebtokensecurity.model.User; import com.pawan.jsonwebtokensecurity.repository.RoleRepository; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @Component public class JWTGenerator { @Autowired private RoleRepository roleRepository; public String generate(User user) { System.out.println("User inside the JWTGenerator:: " + user); System.out.println("roleRepository inside the JWTGenerator:: " + roleRepository); List<Role> roleList = roleRepository.getRoleByUsername(user.getUsername()); System.out.println("Role inside the JWTGenerator:: " + roleList); Role role=roleList.size()>1 ? roleList.get(0):null; if(role==null){ throw new RuntimeException("There is no any role mapped with provided user"); } System.out.println("RoleName inside the JWTGenerator:: " + role.getRoleName()); Claims claim = Jwts.claims().setSubject(user.getUsername()); claim.put("userId", user.getUserId()); claim.put("role", role.getRoleName()); return Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.HS512, "amazon").compact(); } } */
PHP
UTF-8
3,556
2.859375
3
[ "MIT" ]
permissive
<?php /* * Modificata da Angelo Caputo * 26/11/16 00:40 */ class StatoAnnuncio{ const REVISIONE = "revisione"; const ATTIVO = "attivo"; const SEGNALATO = "segnalato"; const DISATTIVATO = "disattivato"; const RICORSO = "ricorso"; const ELIMINATO = "eliminato"; const AMMINISTRATORE = "amministratore"; const REVISIONE_MODIFICA = "revisione_modifica"; } class TipoAnnuncio{ const DOMANDA = "domanda"; const OFFERTA = "offerta"; } class Annuncio { private $id; private $idUtente; private $data; private $titolo; private $descrizione; private $luogo; private $stato; private $retribuzione; private $tipologia; /** * Annuncio constructor. * @param $id * @param $idUtente * @param $data * @param $titolo * @param $descrizione * @param $luogo * @param $stato * @param $retribuzione * @param $tipologia */ public function __construct($id, $idUtente, $data, $titolo, $descrizione, $luogo, $stato, $retribuzione, $tipologia) { $this->id = $id; $this->idUtente = $idUtente; $this->data = $data; $this->titolo = $titolo; $this->descrizione = $descrizione; $this->luogo = $luogo; $this->stato = $stato; $this->retribuzione = $retribuzione; $this->tipologia = $tipologia; } /** * @return mixed */ public function getId() { return $this->id; } /** * @return mixed */ public function getIdUtente() { return $this->idUtente; } /** * @return mixed */ public function getData() { return $this->data; } /** * @return mixed */ public function getTitolo() { return $this->titolo; } /** * @return mixed */ public function getDescrizione() { return $this->descrizione; } /** * @return mixed */ public function getLuogo() { return $this->luogo; } /** * @return mixed */ public function getStato() { return $this->stato; } /** * @return mixed */ public function getRetribuzione() { return $this->retribuzione; } /** * @return mixed */ public function getTipologia() { return $this->tipologia; } /** * @param mixed $data */ public function setData($data) { $this->data = $data; } /** * @param mixed $titolo */ public function setTitolo($titolo) { $this->titolo = $titolo; } /** * @param mixed $descrizione */ public function setDescrizione($descrizione) { $this->descrizione = $descrizione; } /** * @param mixed $luogo */ public function setLuogo($luogo) { $this->luogo = $luogo; } /** * @param mixed $stato */ public function setStato($stato) { $this->stato = $stato; } /** * @param mixed $retribuzione */ public function setRetribuzione($retribuzione) { $this->retribuzione = $retribuzione; } /** * @param mixed $tipologia */ public function setTipologia($tipologia) { $this->tipologia = $tipologia; } }
Markdown
UTF-8
1,117
3.046875
3
[ "MIT" ]
permissive
--- layout: post title: "영지(territory) 선택 : (large)" date: 2020-11-07 13:31:29 +0900 categories: Algorithm tags: [Implement] --- # 영지(territory) 선택 : (large) ### 코드 ```c #include <stdio.h> #include <vector> using namespace std; int a[701][701], dy[701][701]; int main() { int h, w, i, j, n, m, tmp, max = -2147000; scanf("%d %d", &h, &w); for (i = 1; i <= h; i++) { for (j = 1; j <= w; j++) { scanf("%d", &a[i][j]); dy[i][j] = dy[i - 1][j] + dy[i][j - 1] - dy[i - 1][j - 1] + a[i][j]; } } scanf("%d %d", &n, &m); for (i = n; i <= h; i++) { for (j = m; j <= w; j++) { tmp = dy[i][j] - dy[i - n][j] - dy[i][j - m] + dy[i - n][j - m]; if (tmp > max) max = tmp; } } printf("%d\n", max); return 0; } ``` <br/> <img src="/assets/images/501.png" style="zoom:53%;" /> <img src="/assets/images/502.png" style="zoom:53%;" /> <img src="/assets/images/503.png" style="zoom:53%;" /> <img src="/assets/images/504.png" style="zoom:53%;" />
Java
UTF-8
5,168
2
2
[ "MIT" ]
permissive
package com.auth.service.impl; import com.auth.model.AccountRegisterRequest; import com.auth.model.Customer; import com.auth.model.User; import com.auth.repository.AccountRegisterRequestRepository; import com.auth.repository.CustomerRepository; import com.auth.repository.UserRepository; import com.auth.service.AccountRegisterRequestService; import com.java.service.CommonService; import com.java.service.CustomEmail; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.UUID; @Service @Transactional public class AccountRegisterRequestServiceImpl implements AccountRegisterRequestService { private CustomEmail customEmail; private AccountRegisterRequestRepository accountRegisterRequestRepository; private CommonService commonService; private UserRepository userRepository; private CustomerRepository customerRepository; @Value("${server.url}") private String serverUrl; public AccountRegisterRequestServiceImpl( CustomEmail customEmail, AccountRegisterRequestRepository accountRegisterRequestRepository, CommonService commonService, UserRepository userRepository, CustomerRepository customerRepository ) { this.customEmail = customEmail; this.accountRegisterRequestRepository = accountRegisterRequestRepository; this.commonService = commonService; this.userRepository = userRepository; this.customerRepository = customerRepository; } @Override public void processCustomerRegistration(AccountRegisterRequest accountRegisterRequest) throws Exception { //check if already registered from this email AccountRegisterRequest existAccountRegisterRequest = accountRegisterRequestRepository.findFirstByEmail(accountRegisterRequest.getEmail()); if(existAccountRegisterRequest != null){ if(existAccountRegisterRequest.getRegistered() == 1){ throw new Exception("This email already registered."); }else{ accountRegisterRequest.setId(existAccountRegisterRequest.getId()); } } // //generate verify code Boolean isCreatedNewVerifyCode = false; String verifyCode = null; while(!isCreatedNewVerifyCode){ verifyCode = UUID.randomUUID().toString(); AccountRegisterRequest alreadyInVerifyCodeRecord = accountRegisterRequestRepository.findFirstByVerifyCode(verifyCode); if(alreadyInVerifyCodeRecord == null){ isCreatedNewVerifyCode = true; } } // String encodePassword = commonService.passwordEncoder(accountRegisterRequest.getPassword()); accountRegisterRequest.setVerifyCode(verifyCode); accountRegisterRequest.setPassword(encodePassword); accountRegisterRequestRepository.save(accountRegisterRequest); String redirectUrlAfterVerify = serverUrl+"/account-register-request/no-auth/verify/"+verifyCode; //send email String html = "<div style=\"width: 100%;padding:20px;text-align: center;background: #f9f6f6\">\n" + " <div style=\"\n" + " background: white;\n" + " width: 500px;\n" + " margin: auto;\n" + " padding: 40px;\n" + " \">\n" + " <h2>Thank you for signing in</h2>\n" + " <h1>Verify your email address</h1>\n" + " <p style=\"margin-bottom: 40px;\">Please confirm that you want to use this as your email address.</p>\n" + "\n" + " <a\n" + " style=\"\n" + " background: #0cae38;\n" + " padding: 14px 80px;\n" + " border: 0;\n" + " border-radius: 3px;\n" + " color: white;\n" + " font-size: 24px;\n" + " margin-top: 10px;\n" + " text-decoration: none;\n" + " \"\n" + " href=\""+redirectUrlAfterVerify+"\">Verify my email</a>\n" + " </div>\n" + "</div>"; String[] sendTo = new String[]{accountRegisterRequest.getEmail()}; customEmail.sendHtmlEmail( "Verification", sendTo, null, null, html ); } @Override public void verifyCustomerFromVerifyCode(String verifyCode) throws Exception { AccountRegisterRequest existAccountRegisterRequest = accountRegisterRequestRepository.findFirstByVerifyCode(verifyCode); if(existAccountRegisterRequest == null){ throw new Exception("Verification request was expired."); } if(existAccountRegisterRequest.getRegistered() == 1){ throw new Exception("This account was already verified."); } //set registered status existAccountRegisterRequest.setRegistered(1); accountRegisterRequestRepository.save(existAccountRegisterRequest); //create user User user = new User(); user.setEmail(existAccountRegisterRequest.getEmail()); user.setPassword(existAccountRegisterRequest.getPassword()); user.setStatus(true); userRepository.save(user); //create customer Customer customer = new Customer(); customer.setIsActive(true); customer.setUserId(user.getId()); customerRepository.save(customer); } }
Python
UTF-8
480
3.09375
3
[]
no_license
# -*- coding:utf-8 -*- def solve(): N = int(input()) As = list(map(int, input().split())) total = 0 # 踏み台の高さ pre_a = As[0] for i in range(1, N): diff = pre_a - As[i] if diff > 0: # 前の人のほうが高い total += diff As[i] += diff else: # 後ろの人のほうが高い pass pre_a = As[i] print(total) if __name__ == "__main__": solve()
Markdown
UTF-8
5,430
2.78125
3
[]
no_license
--- description: You've got questions - we have answers --- # FAQs ## What is LiDAR? LiDAR stands for Light Detection And Ranging. LiDAR is a method for measuring distances using a laser and optical sensor combination device. A LiDAR device functions by measuring the time between shining the laser on an object and the optical sensor detecting the laser light reflected back by object. Using the speed of light and the time measurement, the LiDAR device is able to calculate the distance to the object reflecting the laser light. #### LiDAR is commonly used in: * Autonomous vehicles * Warehouse automation * Floor planning and mapping * Drone and robot obstacle avoidance ## What is lighthouse? **lighthouse** is a solution to providing developers and consumers with an easy and ready to use LiDAR device. Users can download apps built for lighthouse and immediately start using lighthouse. For Developers; lighthouse is a lightweight and easy to integrate solution for building LiDAR apps. ## How does lighthouse compare to other existing LiDAR products? **lighthouse** is a consumer ready product. It's battery powered and connectable via Bluetooth while still maintaining a price which is inline with LiDAR devices which need integration into a full product. **lighthouse** is ready for the consumer and developer right out of the box - just turn it on and connect! We've noticed a lack in documentation for existing LiDAR devices and so we've made it our goal to provide as much developer support and documentation as possible in order to expand accessibility to LiDAR technology. ## How long does the battery last? You should expect roughly 3 hours while **lighthouse** is spinning \(running and collecting data\). Or 6 hours while on stand-by \(not spinning or collecting data\). Charging should take about 1 hour for a completely drained battery. ## Does lighthouse support IOS or MacOS? At this time **lighthouse** does not support IOS. {% hint style="info" %} We have planned to add IOS integration in the near future! In order to support IOS, we will need to allow connections to Lighthouse using Bluetooth and Wifi. Currently, Lighthouse only supports Bluetooth connections, however, IOS restricts data transferring over Bluetooth for non-Apple-approved products. Thus, we will need to add functionality to transfer data to IOS devices over Wifi instead. We also plan on releasing a MacOS version which will allow users to plug the LiDAR module into their Mac with a USB adapter. {% endhint %} ## What can I do with lighthouse? There are plenty of applications for LiDAR, we would love to see what you can do! * Room mapping/Floor planning * Robot navigation and automation * Security * Virtual touchscreen, human computer interface * Social distancing Let us know what you've built and we'll feature it here! ## Do you offer discounts for educators and researchers? Yes! Please get in touch with us: support@curiolighthouse.com ## Does lighthouse work in the dark? Yes. Due to the way LiDAR works, **lighthouse** will actually provide better results when in dim light environments. ## Can I modify the hardware or integrate with the Raspberry Pi GPIO pins? No, not without voiding your warranty. The reasoning behind this decision is because the Raspberry Pi Zero W is a fairly sensitive device - accidentally switching the power wires or other small errors can kill the board, even if the connection occurred for just a mere second. ## Why can't I buy the battery powered Lighthouse outside the US? Due to the restrictions on shipping batteries and battery powered devices internationally, we chosen not to offer the battery powered Lighthouse to international customers. International customers are still able to purchase the USB powered Lighthouse device or Build-Your-Own kits! ## Is there a battery powered Build-Your-Own kit? No. Batteries can be pretty destructive devices if shorted and mistakenly connected. As such, we've decided against having a Build-Your-Own kit with a battery. ## How is the Build-Your-Own Lighthouse powered? Micro USB. ## Do I need to know how to code for the Build-Your-Own kits? Absolutely not! The Build-Your-Own kits are designed for anyone and everyone to easily build their own Lighthouse device! ## Do the Build-Your-Own kits include a Raspberry Pi or Micro SD card? The Build-Your-Own kits do not include a Raspberry Pi or Micro SD card. You will need your own Raspberry Pi Zero W and Micro SD card. We didn't want to make customers who already have a Raspberry Pi Zero W or Micro SD card available have to buy another. Re-use your Raspberry Pi Zero W and SD cards across projects! ## Can I remove my Raspberry Pi Zero W from Lighthouse You can only remove the Raspberry Pi Zero W from the **Build-Your-Own** kits. The preassembled Lighthouse has an internal Raspberry Pi that is soldered in place and the case is sealed. ## Where is Curio LiDAR LLC located? We are located in Rochester, NY! ## Do you accept returns? Orders can be returned within 5 days of delivery to the original US destination. **International orders cannot be returned**. Read how to qualify and file a return on the [Returns Page](returns.md) {% hint style="warning" %} For Warranty claims, please visit our [Warranty Page](warranty.md) {% endhint %} ## Can I use a Raspberry Pi Zero W with headers for the Build-Your-Own kit? Yes you can.
Rust
UTF-8
784
3.5
4
[]
no_license
use std::ops::Not; type StockId = String; #[derive(Debug)] pub enum Command { Create { id: StockId }, Update { id: StockId, qty: u32 }, } #[derive(Debug, Default, Clone)] pub struct Stock { pub id: StockId, pub qty: u32, } impl Stock { pub fn handle(self, cmd: &Command) -> Stock { match cmd { Command::Create { id } => if self.id.is_empty() && id.is_empty().not() { Stock { id: id.clone(), ..self } } else { self } Command::Update { id, qty } => if id.is_empty().not() && self.id.eq(id) { Stock { qty: *qty, ..self } } else { self } } } }
Shell
UTF-8
459
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
set -e shopt -s extglob TEMP_PATH="docs/.temp" # build docs yarn doc:build # prepare deploy mkdir $TEMP_PATH cd $TEMP_PATH git init git pull git@github.com:ddnlink/ddn.git gh-pages # rm -rf * cp -r ../../dist/* . # git config git config user.email "limsbase@163.com" git config user.name "limsbase" # commit and push changes git add -A git commit --am -m "build: deploy documentation" git push -f git@github.com:ddnlink/ddn.git master:gh-pages # clean cd - rm -rf $TEMP_PATH
Python
UTF-8
2,083
2.734375
3
[ "MIT" ]
permissive
import seaborn as sns; sns.set() import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams sns.set_context("poster",font_scale=1.2,rc={"font":"helvetica"}); sns.set_style("white"); cp = sns.color_palette("colorblind") cp = sns.color_palette() rcParams["savefig.dpi"] = 200 rcParams['mathtext.fontset'] = 'stix' rcParams['font.family'] = 'STIXGeneral' rcParams['font.weight'] = "normal" rcParams["axes.formatter.useoffset"] = False rcParams['xtick.major.width']=1 rcParams['xtick.major.size']=7 rcParams['xtick.minor.width']=1 rcParams['xtick.minor.size']=4 rcParams['ytick.major.width']=1 rcParams['ytick.major.size']=7 rcParams['ytick.minor.width']=1 rcParams['ytick.minor.size']=4 def plot_transit_with_model(x,y,yerr,yresidual=None,xmodel=None,ymodel=None,offset=0.99,ax=None, label_data="Data",label_model="Model",label_residual="Residual",alpha=0.7,markersize=4.): """ Plot transit with a transit model, residual and errorbars INPUT: x - time coordinate, BJD y - normalized flux yerr - yresidual - residual xmodel - x coordinate of model ymodel - y coordinate of model OUTPUT: Plots a nice transit plot plot NOTES: """ if ax is None: fig, ax = plt.subplots() # Plot Data ax.errorbar(x,y,yerr,elinewidth=0.3,lw=0,alpha=alpha,marker="o", barsabove=True,markersize=markersize,mew=1.,capsize=4.,capthick=0.5,label=label_data,color=cp[0]) # Plot Residual if yresidual is not None: ax.errorbar(x,yresidual+offset,yerr,elinewidth=0.3,lw=0,alpha=0.5,marker="o", barsabove=True,markersize=4,mew=1.,capsize=4,capthick=0.5,label=label_residual,color="dimgray") # Plot Model if xmodel is not None and ymodel is not None: ax.plot(xmodel,ymodel,label=label_model,color="crimson",alpha=0.7) ax.minorticks_on() ax.set_xlabel("BJD") ax.set_ylabel("Normalized flux") ax.grid(lw=0.5,alpha=0.5)
Java
UTF-8
242
2.765625
3
[]
no_license
package enumeration; public enum Category { PUPPY, ADULT, OLD; public static Category getCategoryByAge(double age) { if (age<1.0) return PUPPY; else if (age<8.0) return ADULT; else return OLD; } }
JavaScript
UTF-8
3,329
2.765625
3
[ "MIT" ]
permissive
function colorinvert(){ if (document.body.style.getPropertyValue('--bg-color') != "black"){ document.body.style.setProperty('--bg-color' , "black" ); document.body.style.setProperty('--element-color' , "white" ); } else { document.body.style.setProperty('--bg-color' , "white" ); document.body.style.setProperty('--element-color' , "black" ); } } function randomColors(){ // 16777215 == ffffff in decimal // 16 -> hex val of number var randomElement = Math.floor(Math.random()*16777215).toString(16); if (randomElement.length != 6) randomElement = Math.floor(Math.random()*16777215).toString(16); document.body.style.setProperty('--element-color' , "#"+randomElement ); var randomBackground = Math.floor(Math.random()*16777215).toString(16); if (randomBackground.length != 6) randomBackground = Math.floor(Math.random()*16777215).toString(16); document.body.style.setProperty('--bg-color' , "#"+randomBackground ); } // color selection functions // set background colorPicker var bgcolorPicker = new iro.ColorPicker("#color-bg-container", { width: 100, color: 'rgb(255, 64, 100)', //initial color wheelLightness: false, handleRadius:7, sliderHeight:7, sliderMargin:7 }); // set text colorPicker var textcolorPicker = new iro.ColorPicker("#color-text-container", { width: 100, color: '#000000', //initial color wheelLightness: false, handleRadius:7, sliderHeight:7, sliderMargin:7 }); function bgColorSelector(){ // toggle selector var selectorDiv = document.getElementById("color-bg-container"); if (selectorDiv.style.display != "block") { selectorDiv.style.display = "block"; } else { selectorDiv.style.display = "none"; } // hide other selector document.getElementById("color-text-container").style.display = "none"; // set initial color to current color (if not first time defining color) var currBgColor = document.body.style.getPropertyValue('--bg-color'); if (currBgColor != "") bgcolorPicker.color.set(currBgColor); // change color on traverse bgcolorPicker.on(["color:init", "color:change"], function(color){ var bgCurrColor = bgcolorPicker.color.hexString; // already string ready document.body.style.setProperty('--bg-color' , bgCurrColor ); }); } function textColorSelector(){ // toggle selector var selectorDiv = document.getElementById("color-text-container"); if (selectorDiv.style.display != "block") { selectorDiv.style.display = "block"; } else { selectorDiv.style.display = "none"; } // hide other selector document.getElementById("color-bg-container").style.display = "none"; // set initial color to current color (if not first time defining color) var currElemColor = document.body.style.getPropertyValue('--element-color'); if (currElemColor != "") textcolorPicker.color.set(currElemColor); // change color on traverse textcolorPicker.on(["color:init", "color:change"], function(color){ var elemCurrColor = textcolorPicker.color.hexString; // already string ready document.body.style.setProperty('--element-color' , elemCurrColor ); }); } // note: In chrome apps, Content Security Policy does not allow inline javascript. // https://stackoverflow.com/questions/36324333/refused-to-execute-inline-event-handler-because-it-violates-csp-sandbox/36349056
Java
UTF-8
6,236
3.359375
3
[]
no_license
// Creators: Sadiq Hussain, Nathan Chung // This is the champion class used to define the traits of a champion package League; import java.util.*; public class Champion { // Initialize protected int fields (stats): protected String name; protected String tribe; protected String type; //Array to stor names of all stats private String[] statNames = {"Health","Attack Speed","Attack Damage","Armor","Crit","Magic Damage","Magic Resistance", "Mana","Mana Regen","Movement Speed","Tenacity","maxHealth","maxMana"}; //Array to store values of all coresponding stats private double[] statValues = new double[13]; // Initialize private booleans (effects): private boolean frozen = false; private boolean poisoned = false; protected Ability[] abilities = new Ability[3]; public Champion() { } public Champion(String champName, String champType, String champTribe , String ability1, String ability2, String ability3) throws Exception { name = champName; type = champType; tribe = champTribe; //Adding champions abilities abilities[0] = new Ability(ability1); abilities[1] = new Ability(ability2); abilities[2] = new Ability(ability3); } //Getters public String getName() { return name; } public double getHealth() { return statValues[0]; } public double getAtkSpd() { return statValues[1]; } public double getAtkDmg() { return statValues[2]; } public double getArmor() { return statValues[3]; } public double getCrit() { return statValues[4]; } public double getMagicDmg() { return statValues[5]; } public double getMagicRes() { return statValues[6]; } public double getMana() { return statValues[7]; } public double getManaReg() { return statValues[8]; } public double getMoveSpd() { return statValues[9]; } public double getTenacity() { return statValues[10]; } public double getMaxHealth(){ return statValues[11]; } public double getMaxMana(){ return statValues[12]; } public String getTribe() { return tribe; } public String getType() { return type; } public String[] getStatNames(){ return statNames; } public double[] getStatValues(){ return statValues; } //Setters public void setHealth(double newHealth) { //Make ssure health does not exceed max health if (newHealth < this.getMaxHealth()) { statValues[0] = this.getMaxHealth(); } else { statValues[0] = newHealth; } } public void setAtkSpd(double newAtkSpd) { statValues[1] = newAtkSpd; } public void setAtkDmg(double newAtkDmg) { statValues[2] = newAtkDmg; } public void setArmor(double newArmor) { statValues[3] = newArmor; } public void setCrit(double newCrit) { statValues[4] = newCrit; } public void setMagicDmg(double newMagicDmg) { statValues[5] = newMagicDmg; } public void setMagicRes(double newMagicRes) { statValues[6] = newMagicRes; } public void setMana(double newMana) { //if new mana exceeds the max then set it to max if(newMana < this.getMaxMana()){ statValues[7] = this.getMaxMana(); }else { statValues[7] = newMana; } } public void setManaReg(double newManaReg) { statValues[8] = newManaReg; } public void setMoveSpd(double newMoveSpd) { statValues[9] = newMoveSpd; } public void setTenacity(double newTenacity) { statValues[10] = newTenacity; } public void setMaxHealth(double maxHealth){ statValues[11]=maxHealth; } public void setMaxMana(double maxMana){ statValues[12]=maxMana; } public void setStatValues(double[] newStats){ for(int i=0;i<newStats.length;i++){ statValues[i]=newStats[i]; } } //Adding/Removing status effects public boolean isFrozen() { return frozen; } public boolean isPoisoned() { return poisoned; } public void addPoison() { poisoned = true; } public void removePoison() { poisoned = false; } public void addFrozen() { frozen = true; } public void removeFrozen() { frozen = false; } //Methods public void applyType(Champion champion, Ability ability) { } public void attack (int abilityName, Champion champ, Champion enemy){ abilities[abilityName - 1].attack(champ, enemy); } public String toString() { return "\nName: " + name + "\nType: " + type + "\nTribe: " +tribe + "\nHealth: " + statValues[0] + "\nAttack Speed: " + statValues[1] + "\nAttack Damage: " + statValues[2] + "\nArmor: " + statValues[3] + "\nCrit: " + statValues[4] + "\nMagic Damage: " + statValues[5] + "\nMagic Res: " + statValues[6] + "\nMana: " + statValues[7] + "\nMana Regen: " + statValues[8] + "\nMove Speed: " + statValues[9] + "\nTenacity: " + statValues[10]; } //Regenerates mana as required public void regen() { setMana(getMana()+getManaReg()); //Makes sure the champion dosent surpass their maximum mana if(getMana()>getMaxMana()){ setMana(getMaxMana()); } } //Checks if champion is dead public boolean isDead() { return this.getHealth()<=0; } public void printAbilities(){ int counter = 0; for(int i=0; i<abilities.length; i++) { counter++; double totalAtkDmg = this.getAtkDmg() + abilities[i].getBaseAttack(); double totalMagicDmg = this.getMagicDmg() + abilities[i].getBaseMagic(); System.out.println(counter + ". " + abilities[i].getName()); System.out.println("Mana Cost: " + abilities[i].getManaCost()); if(abilities[i].getBaseAttack()>=0){ System.out.print("Attack damage: "+ totalAtkDmg + "\n"); } if(abilities[i].getBaseMagic()>=0){ System.out.print("Magic damage:" + totalMagicDmg + "\n"); } } } }
Swift
UTF-8
2,403
3.03125
3
[]
no_license
// // FirstViewController.swift // FoodApp // // Created by Connor Donegan on 1/29/20. // Copyright © 2020 Connor Donegan. All rights reserved. // import UIKit class FirstViewController: UIViewController { @IBOutlet weak var Numberfood: UILabel! @IBOutlet weak var Image: UIImageView! @IBOutlet weak var ViewLabel: UILabel! var position = 0 var current = 0 var imageName = ["taco","pasta","icecreamm","goat","generic"] var label = ["Tacos","Pasta", "Ice Cream", "Goat"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func nextButton(_ sender: Any) { position = position + 1 current = position % label.count if current > imageName.count - 1{ Image.image = UIImage(named: imageName[imageName.count - 1]) } else{ Image.image = UIImage(named: imageName[current]) } Numberfood.text = "My #\(current + 1) favorite food is..." ViewLabel.text = label[current] } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "fromAddToAddFood") { let secondVC = segue.destination as! AddFoodViewController secondVC.countOfFood = label.count } } @IBAction func unwindFromSecondView (sender: UIStoryboardSegue) { let secondVC = sender.source as! AddFoodViewController let saveFlag = secondVC.saveFlag let cancelFlag = secondVC.cancelFlag //var newFood: String? if cancelFlag == 1 { performSegue(withIdentifier: "unwindSecondView", sender: nil) } else if let newFood = secondVC.newFood {//once inside this loop you must store the new food in label and add it to the slideshow label.append(newFood) print("added to label") print(label.count) } else if saveFlag > 0 { performSegue(withIdentifier: "unwindSecondView", sender: nil) } // called everytme cancel or save is tapped // if cancel > 0 it was tapped and return //else save the text and add it to the label array } }
Java
UTF-8
1,603
2.59375
3
[ "MIT" ]
permissive
package com.plooh.adssi.dial.twindow; import java.time.Instant; import java.time.temporal.ChronoUnit; import com.plooh.adssi.dial.data.Twindow; import com.plooh.adssi.dial.parser.TimeFormat; public class TwindowUtils { public static final Twindow twindow(Instant now, String antecedentHash, String antecedentClosing) { Twindow twindow = twindow(now); twindow.setA_hash(antecedentHash); twindow.setA_closing(antecedentClosing); return twindow; } public static final Twindow twindow(Instant now) { Instant start = now.truncatedTo(ChronoUnit.DAYS); Instant end = start.plus(1, ChronoUnit.DAYS); String startFormated = TimeFormat.format(start); String endFormated = TimeFormat.format(end); Twindow twindow = new Twindow(); twindow.setStart(startFormated); twindow.setEnd(endFormated); return twindow; } public static final Instant openingTwindowRecordDate(Instant now) { return now.truncatedTo(ChronoUnit.DAYS); } public static final Instant closingTwindowRecordDate(Instant now) { return now.truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS).minus(1, ChronoUnit.SECONDS); } public static final Twindow antecedantTwindow(String antecedantClosing) { Instant start = Instant.parse(antecedantClosing).minus(1, ChronoUnit.DAYS); String startFormated = TimeFormat.format(start); Twindow twindow = new Twindow(); twindow.setStart(startFormated); twindow.setEnd(antecedantClosing); return twindow; } }
Java
UTF-8
1,948
2.75
3
[]
no_license
package fr.fresnel.fourPolar.algorithm.preprocess.fov; import fr.fresnel.fourPolar.core.imagingSetup.imageFormation.fov.IFieldOfView; import fr.fresnel.fourPolar.core.physics.polarization.Polarization; /** * An interface for calculating the {@link IFieldOfView} of a particular * {@link Camera}, */ public interface IFoVCalculator { /** * Set the x and y coordinate of minimum point (starting point) of this * polarization. * * @param x is the x coordiante. * @param y is the y coordinate. * @param pol is the polarization. * * @throws IllegalArgumentException if the x and y points are negative or are * outside the boundary of this polarization * dimension. */ public void setMin(long x, long y, Polarization pol); /** * Set the x and y coordinate of maximum point (end point) of this polarization. * * @param x is the x coordiante. * @param y is the y coordinate. * @param pol is the polarization. * * @throws IllegalArgumentException if the x and y points are negative or are * outside the boundary of this polarization * dimension. */ public void setMax(long x, long y, Polarization pol); /** * Calculate fov using the minimum and maximum points for each polarization. * * @return the field of view. * * @throws IllegalStateException if the top and bottom point is not provided for * all polarizations. */ public IFieldOfView calculate(); /** * Return a copy of polarization fov max point. */ public long[] getMaxPoint(Polarization polarization); /** * Return a copy of polarization fov min point. */ public long[] getMinPoint(Polarization polarization); }
Java
UTF-8
3,142
3.46875
3
[]
no_license
package string; import java.util.*; /** * Date 09/08/17 * * @author Ankit Jain */ public class LongestUncommonSubsequenceII { public static void main(String[] args) { LongestUncommonSubsequenceII longestUncommonSubsequenceII = new LongestUncommonSubsequenceII(); System.out.println(longestUncommonSubsequenceII.findLUSlength(new String[]{"abc", "adc"})); } public int findLUSlength(String[] strs) { int res = -1; int j = 0; int n = strs.length; for (int i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (i == j) continue; if (subcheck(strs[i], strs[j])) break; } if (j == n) res = Math.max(res, (int) strs[i].length()); } return res; } boolean subcheck(String a, String b) { int i = 0; char[] arr = a.toCharArray(); char[] brr = b.toCharArray(); for (char c : brr) { if (c == arr[i]) i++; if (i == arr.length) break; } return i == arr.length; } public int findLUSlength2(String[] strs) { Map<String, Integer> subseqFreq = new HashMap<>(); for (String s : strs) for (String subSeq : getSubseqs(s)) subseqFreq.put(subSeq, subseqFreq.getOrDefault(subSeq, 0) + 1); int longest = -1; for (Map.Entry<String, Integer> entry : subseqFreq.entrySet()) if (entry.getValue() == 1) longest = Math.max(longest, entry.getKey().length()); return longest; } public static Set<String> getSubseqs(String s) { Set<String> res = new HashSet<>(); if (s.length() == 0) { res.add(""); return res; } Set<String> subRes = getSubseqs(s.substring(1)); res.addAll(subRes); for (String seq : subRes) res.add(s.charAt(0) + seq); return res; } public int findLUSlength1(String[] strs) { Arrays.sort(strs, new Comparator<String>() { @Override public int compare(String a, String b) { return b.length() - a.length(); } }); Set<String> dup = findDup(strs); for (int i = 0; i < strs.length; i++) { if (!dup.contains(strs[i])) { if (i == 0) return strs[i].length(); for (int j = 0; j < i; j++) { if (isSubseq(strs[j], strs[i])) break; if (i - 1 == j) return strs[i].length(); } } } return -1; } private boolean isSubseq(String st1, String st2) { int i = 0, j = 0; while (i < st1.length() && j < st2.length()) { if (st1.charAt(i) == st2.charAt(j)) j++; i++; } return j == st2.length(); } private Set<String> findDup(String[] strs) { Set<String> dup = new HashSet<>(); Set<String> val = new HashSet<>(); for (String st : strs) { if (val.contains(st)) dup.add(st); val.add(st); } return dup; } }
Java
UTF-8
7,210
1.953125
2
[]
no_license
package stealme.client.location; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; public class LocationHandler { private static float threshold = 0.002f; private static int interval = 1000; //private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1; // in Meters //private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000; // in Milliseconds private static final long POINT_RADIUS = 15; // in Meters private static final long PROX_ALERT_EXPIRATION = -1; private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY"; private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY"; private static final String PROX_ALERT_INTENT = "com.javacodegeeks.android.lbs.ProximityAlert"; private static PendingIntent _lastProximityIntent; private static ILocationListener listener; private static boolean _waitingForFirstAccurateLocation = true; private static LocationManager locManager; private static Boolean supported; private static boolean running = false; public static boolean isListening() { return running; } public static void stopListening() { running = false; try { if (locManager != null && listener != null) { locManager.removeUpdates(locListener); } } catch (Exception e) { } } public static boolean isSupported() { if (supported == null) { } return supported; } public static void configure(int threshold, int interval) { LocationHandler.threshold = threshold; LocationHandler.interval = interval; } public static void startListening(ILocationListener smLocationListener) { Handler mHandler = new Handler(Looper.getMainLooper()); final ILocationListener finListener = smLocationListener; mHandler.post(new Runnable() { public void run() { try{ locManager = (LocationManager) finListener.getContext().getSystemService(Context.LOCATION_SERVICE); locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, finListener.getInterval() * 1000, 0,locListener); _waitingForFirstAccurateLocation = true; listener = finListener; } catch(Exception ex) { Log.e("SM", ex.getMessage()); } } }); } public static void startListening( ILocationListener smLocationListener, int threshold, int interval) { configure(threshold, interval); startListening(smLocationListener); } private static void addProximityAlert(double latitude, double longitude) { if(_lastProximityIntent != null) locManager.removeProximityAlert(_lastProximityIntent); Intent intent = new Intent(PROX_ALERT_INTENT); _lastProximityIntent = PendingIntent.getBroadcast(listener.getContext(), 0, intent, 0); locManager.addProximityAlert( latitude, // the latitude of the central point of the alert region longitude, // the longitude of the central point of the alert region POINT_RADIUS, // the radius of the central point of the alert region, in meters PROX_ALERT_EXPIRATION, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration _lastProximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected ); IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT); listener.getContext().registerReceiver(new ProximityIntentReceiver(), filter); } public static LocationListener locListener = new LocationListener() { private Location currentLoc; public void onLocationChanged(Location location) { if(location.getAccuracy() < POINT_RADIUS) { _waitingForFirstAccurateLocation = false; addProximityAlert(location.getLatitude(), location.getLongitude()); } if (isBetterLocation(location, this.currentLoc)) { //Location is changed - it's time to notify our listener! LocationHandler.listener.onLocationChanged(location); } } public void onProviderDisabled(String provider) { //GPS Off } public void onProviderEnabled(String provider) { //GPS On } public void onStatusChanged(String provider, int status, Bundle extras) { //We don't need this kind of sillyness :) } private static final int HALF_MINUTE = 1000 * 30; protected boolean isBetterLocation(Location location, Location currentBestLocation) { if(location == null) { return false; } if (currentBestLocation == null) { // A new location is always better than no location return true; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > HALF_MINUTE; boolean isSignificantlyOlder = timeDelta < -HALF_MINUTE; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use // the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be // worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation .getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and // accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } /** Checks whether two providers are the same */ private boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } }; public static class ProximityIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String key = LocationManager.KEY_PROXIMITY_ENTERING; Boolean entering = intent.getBooleanExtra(key, false); if (entering) { Log.d(getClass().getSimpleName(), "entering"); } else { listener.Alert(); Log.d(getClass().getSimpleName(), "exiting"); } } } }
C++
UTF-8
1,097
2.84375
3
[]
no_license
#include<cstdio> #include<cstdlib> #include<iostream> using namespace std; char place; int n,k,temp=0,remain; int num[26]; struct node{ char c; node *nex,*rev; node() {c=0;nex=rev=NULL;} }*head,*tail; inline void ins(char key){ node *p=new(node); p->c=key; p->nex=tail;p->rev=tail->rev; tail->rev->nex=p;tail->rev=p; ++num[key-'a']; } inline void del(node *key){ key->nex->rev=key->rev; key->rev->nex=key->nex; } inline void read(){ char cc=getchar(); while(cc<'a'||cc>'z') cc=getchar(); for(;cc>='a'&&cc<='z';cc=getchar()){ ins(cc); } } int main(){ head=new(node);tail=new(node); head->nex=tail;head->rev=NULL; tail->nex=NULL;tail->rev=head; scanf("%d%d",&n,&k); read(); for(char c='a';c<='z';++c){ temp+=num[c-'a'];`1 if(temp>=k) {place=c;remain=num[c-'a']-temp+k;break;} } for(node *p=head->nex;p!=tail;p=p->nex){ if(p->c>='a'&&p->c<place){ p=p->rev; del(p->nex); } } for(node *p=head->nex;p!=tail&&remain;p=p->nex){ if(p->c==place){ p=p->rev;--remain; del(p->nex); } } for(node *p=head->nex;p!=tail;p=p->nex) printf("%c",p->c); return 0; }
C#
UTF-8
4,008
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Proyecto_algoritmos { public partial class Form3 : Form { public Form1 f1; public int n; public Form3() { InitializeComponent(); } private void Form3_Load(object sender, EventArgs e) { if (n == 0) { MessageBox.Show("No hay vertices insertados"); this.Close(); } button3.Enabled = false; textBox4.Enabled = false; } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void textBox3_KeyPress(object sender, KeyPressEventArgs e) { Validacion.SoloNumeros(e); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { Validacion.SoloNumeros(e); } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { Validacion.SoloNumeros(e); } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text.Length != 0 && textBox2.Text.Length != 0 && textBox3.Text.Length != 0) { int i = Convert.ToInt32(textBox3.Text); int x = Convert.ToInt32(textBox1.Text); int y = Convert.ToInt32(textBox2.Text); if (n >= i && i >= 1 && 1145 >= x && x >= 25 && 705 >= y && y >= 25) { if (f1.detecta_posicion(x, y)) { f1.cambiarVertice(x, y, i, false, 0); this.Close(); } else MessageBox.Show("La posición insertada se interpone con otro vértice\n"); } else MessageBox.Show("El rango de los campos son los siguientes\nel vertice va de 1 a" + n + "\nx de 25 a 1145\ny de 25 a 705"); } else MessageBox.Show("Los campos tienen que estar llenos"); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if(checkBox1.Checked) { button3.Enabled = true; button1.Enabled = false; button4.Enabled = false; textBox4.Enabled = true; } else { button3.Enabled = false; button1.Enabled = true; button4.Enabled = true; textBox4.Enabled = false; } } private void button3_Click(object sender, EventArgs e) { if (textBox1.Text.Length != 0 && textBox2.Text.Length != 0 && textBox3.Text.Length != 0 && textBox4.Text.Length != 0) { int i = Convert.ToInt32(textBox3.Text); int x = Convert.ToInt32(textBox1.Text); int y = Convert.ToInt32(textBox2.Text); int t = Convert.ToInt32(textBox4.Text); if (n >= i && i >= 1 && 1145 >= x && x >= 25 && 705 >= y && y >= 25) { if (f1.detecta_posicion(x, y)) { f1.cambiarVertice(x, y, i, true, t); this.Close(); } else MessageBox.Show("La posición insertada se interpone con otro vértice\n"); } else MessageBox.Show("El rango de los campos son los siguientes\nel vertice va de 1 a" + n + "\nx de 25 a 1145\ny de 25 a 705"); } else MessageBox.Show("Los campos tienen que estar llenos"); } } }
C++
UTF-8
8,174
3.03125
3
[]
no_license
#include <string> #include <fstream> #include <iostream> #include "Household.h" #include "ZipCodeList.h" #include "BSTree.h" #include "List.h" using namespace std; Household::Household() { lastName=""; streetAddress=""; stateInitials=""; zipCode=""; numOccupants=0; } void Household::setLastName(string LastName) { this->lastName=LastName; } void Household::setStreeAddress(string streetAddress) { this->streetAddress=streetAddress; } void Household::setStateInitials(string stateInitials) { this->stateInitials=stateInitials; } void Household::setZipCode(string zipCode) { this->zipCode=zipCode; } void Household::setnumOccupants(int numOccupants) { this->numOccupants=numOccupants; } string Household::getLastName() { return lastName; } string Household::getStreeAddress() { return streetAddress; } string Household::getStateInitials() { return stateInitials; } string Household::getZipCode() { return zipCode; } int Household::getnumOccupants() { return numOccupants; } bool Household:: operator <(Household rhsH) { if(lastName<rhsH.lastName) return true; return false; } bool Household:: operator <=(Household rhsH) { if(lastName<rhsH.lastName) return true; return false; } bool Household:: operator !=(Household rhsH) { if(lastName<rhsH.lastName) return true; return false; } bool Household:: operator >(Household rhsH) { if(lastName<rhsH.lastName) return true; return false; } bool Household:: operator >=(Household rhsH) { if(lastName<rhsH.lastName) return true; return false; } bool Household:: operator ==(Household rhsH) { if(lastName<rhsH.lastName) return true; return false; } string Household::toString() const { stringstream s; string strA; s << lastName << " " <<streetAddress <<" "<<stateInitials<<" "<<zipCode<<" "<<numOccupants<<endl; strA = s.str(); return strA; } ostream & operator <<(ostream &out, const Household &p) { out<<p.toString(); return out; } int printMenu(); void InitializeTreeFromFile(string filename, BSTree<ZipCodeList<Household>> a) { ifstream in; in.open(filename); int i=0; while(in){ Household h1; string ln,ad,st,zc,no,ex; getline(in,ln); getline(in,ad); getline(in,ex); string sp = " "; int it=0; } } //void addHousehold(BSTree a); //void deleteHousehold(BSTree a); int main() { BSTree<ZipCodeList<Household>> a; int selection; string fileName; cout << "Programmed by Virender Singh\n\n"; cout << "Enter the file to load the tree: "; getline(cin, fileName); InitializeTreeFromFile(fileName, a); do { selection = printMenu(); switch (selection) { case 1: a.printTree(); break; case 2: //addHousehold(a); break; case 3: //deleteHousehold(a); break; case 4: break; default: cout << "Invalid selection! Please Re-enter!\n"; } }while (selection != 4); return 0; return 0; /* //Household Test Code List<Household> a; Household h1; h1.setLastName("Tetzner"); h1.setnumOccupants(4); h1.setStateInitials("IL"); h1.setStreeAddress("100 State Road"); Household h2; h2.setLastName("Smith"); h2.setnumOccupants(5); h2.setStateInitials("IL"); h2.setStreeAddress("250 Castle Road"); a.insert(h1); a.insert(h2); if(h1<h2) cout<<"h1 is less"; else { cout<<"bef"<<endl; } a.printList(); cout<<h1.toString(); cout<<h2.toString(); // List Test code List<int> trial; trial.insert(18); trial.insert(20); trial.insert(15); trial.insert(12); trial.insert(17); trial.insert(25); trial.insert(20); trial.insert(22); cout << "Initial" << endl; trial.printList(); List<int>trial2(trial); trial2.insert(21); cout << "Test Copy Constructor" << endl; cout << "Trial" <<endl; trial.printList(); cout << "Trial2" <<endl; trial2.printList(); cout << "Test Deletes" << endl; int x; if(trial.deleteAndPassBackListItem(17, x)) cout << "Removed" << x << " from list" <<endl; else { cout << "17 not in list" <<endl; } trial.printList(); if(trial.deleteAndPassBackListItem(4, x)) cout << "Removed " << x << " from list" << endl; else { cout << "4 not in list" << endl; } trial.printList(); if(trial.deleteFirstAndPassBackListItem(x)) { cout << "Removed " << x << " from list" << endl; } else { cout << "list is empty." << endl; } trial.deleteListItem(25); trial.deleteListItem(12); trial.deleteListItem(22); trial.printList();*/ /*BSTree<int> rt; rt.insert(12); rt.insert(67); rt.insert(34); rt.insert(10); rt.insert(5); rt.insert(7); rt.insert(38); rt.insert(11); rt.insert(69); BSTree<int> rt2; rt2 = rt; rt2.printTree(); //cout<<"done"; //rt.deleteTree(); //rt.printTree(); Household h1; h1.setLastName("Tetzner"); h1.setnumOccupants(4); h1.setStateInitials("IL"); h1.setStreeAddress("100 State Road"); Household h2; h2.setLastName("Smith"); h2.setnumOccupants(5); h2.setStateInitials("IL"); h2.setStreeAddress("250 Castle Road"); Household h3; h3.setLastName("Apple"); h3.setnumOccupants(6); h3.setStateInitials("IL"); h3.setStreeAddress("111 Stone Road"); Household h4; h4.setLastName("Zebra"); h4.setnumOccupants(7); h4.setStateInitials("IL"); h4.setStreeAddress("54 Runner Road"); Household h5; h5.setLastName("Show"); h5.setnumOccupants(8); h5.setStateInitials("IL"); h5.setStreeAddress("1458 Tree St"); Household h6; h6.setLastName("Umbrella"); h6.setnumOccupants(9); h6.setStateInitials("IL"); h6.setStreeAddress("5 Elm St"); cout<<"begin"; ZipCodeList<Household> list1; list1.setZipCode("22222"); list1.insertIntoList(h1); list1.insertIntoList(h2); list1.insertIntoList(h3); cout<<"1"; ZipCodeList<Household> list2; list2.setZipCode("11111"); list2.insertIntoList(h4); list2.insertIntoList(h5); list2.insertIntoList(h6); cout<<"2"; ZipCodeList<Household> list3; list3.insertIntoList(h1); list3.insertIntoList(h2); list3.insertIntoList(h3); list3.setZipCode("33333"); list3.insertIntoList(h4); list3.insertIntoList(h5); list3.insertIntoList(h6); ZipCodeList<Household> list4; list4.setZipCode("44444"); list4.insertIntoList(h4); BSTree<ZipCodeList<Household>> tree1; cout<<"tree"; tree1.insert(list1); tree1.insert(list2); tree1.insert(list3); cout<<"ts"; cout << "Tree to begin" << endl; tree1.printTree(); ZipCodeList<Household> tmp; if(tree1.deleteNodePassBackData(list2, tmp)) { cout<<"Deleted:"<<endl; cout<<tmp; } else { cout<<"Could not delete: "<<endl; cout<<tmp; } if(tree1.deleteNodePassBackData(list4, tmp)) { cout<<"Deleted:"<<endl; cout<<tmp; } else { cout<<"Could not delete: "<<endl; cout<<list4; } cout<<endl<<"After Deleting"<<endl; tree1.printTree(); */ } int printMenu() { string schoice; cout << endl; cout << "1.\tPrint census by zipcode" << endl; cout << "2.\tAdd household to zipcode" << endl; cout << "3.\tDelete household from zipcode" << endl; cout << "4.\tExit" << endl; cout << "Enter your selection: "; getline(cin,schoice); int choice = stoi(schoice); return choice; }
JavaScript
UTF-8
14,189
2.609375
3
[]
no_license
var lists = document.querySelectorAll("li .attribute1-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute1-click")[0]; if (this.className == "attribute1-unclick") { if (clicked) clicked.className = "attribute1-unclick"; this.className = "attribute1-click"; var text = this.innerHTML; var dicti = { Bell: 0, Conical: 1, Convex: 2, Flat: 3 }; document.getElementById("cap_shape").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute2-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute2-click")[0]; if (this.className == "attribute2-unclick") { if (clicked) clicked.className = "attribute2-unclick"; this.className = "attribute2-click"; var text = this.innerHTML; var dicti = { Fibrous: 0, Grooves: 1, Scaly: 2, Smooth: 3 }; document.getElementById("cap_surface").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute3-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute3-click")[0]; if (this.className == "attribute3-unclick") { if (clicked) clicked.className = "attribute3-unclick"; this.className = "attribute3-click"; var text = this.innerHTML; var dicti = { Brown: 0, Buff: 1, Cinnamon: 2, Gray: 3, Green: 4, Pink: 5, Purple: 6, Red: 7, White: 8, Yellow: 9 }; document.getElementById("cap_color").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute4-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute4-click")[0]; if (this.className == "attribute4-unclick") { if (clicked) clicked.className = "attribute4-unclick"; this.className = "attribute4-click"; var text = this.innerHTML; var dicti = { Bruises: 0, No: 1 }; document.getElementById("bruises").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute5-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute5-click")[0]; if (this.className == "attribute5-unclick") { if (clicked) clicked.className = "attribute5-unclick"; this.className = "attribute5-click"; var text = this.innerHTML; var dicti = { Almond: 0, Anise: 1, Creosote: 2, Fishy: 3, Foul: 4, Musty: 5, None: 6, Pungent: 7, Spicy: 8 }; document.getElementById("odor").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute6-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute6-click")[0]; if (this.className == "attribute6-unclick") { if (clicked) clicked.className = "attribute6-unclick"; this.className = "attribute6-click"; var text = this.innerHTML; var dicti = { Attached: 0, Descending: 1, Free: 2, Notched: 3 }; document.getElementById("gill_attachment").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute7-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute7-click")[0]; if (this.className == "attribute7-unclick") { if (clicked) clicked.className = "attribute7-unclick"; this.className = "attribute7-click"; var text = this.innerHTML; var dicti = { Close: 0, Crowded: 1, Distant: 2 }; document.getElementById("gill_spacing").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute8-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute8-click")[0]; if (this.className == "attribute8-unclick") { if (clicked) clicked.className = "attribute8-unclick"; this.className = "attribute8-click"; var text = this.innerHTML; var dicti = { Broad: 0, Narrow: 1 }; document.getElementById("gill_size").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute9-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute9-click")[0]; if (this.className == "attribute9-unclick") { if (clicked) clicked.className = "attribute9-unclick"; this.className = "attribute9-click"; var text = this.innerHTML; var dicti = { Black: 0, Brown: 1, Buff: 2, Chocolate: 3, Gray: 4, Green: 5, Orange: 6, Pink: 7, Purple: 8, Red: 9, White: 10, Yellow: 11 }; document.getElementById("gill_color").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute10-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute10-click")[0]; if (this.className == "attribute10-unclick") { if (clicked) clicked.className = "attribute10-unclick"; this.className = "attribute10-click"; var text = this.innerHTML; var dicti = { Enlarging: 0, Tapering: 1 }; document.getElementById("stalk_shape").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute11-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute11-click")[0]; if (this.className == "attribute11-unclick") { if (clicked) clicked.className = "attribute11-unclick"; this.className = "attribute11-click"; var text = this.innerHTML; var dicti = { Bulbous: 0, Club: 1, Cup: 2, Equal: 3, Rhizomorphs: 4, Rooted: 5 }; document.getElementById("stalk_root").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute12-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute12-click")[0]; if (this.className == "attribute12-unclick") { if (clicked) clicked.className = "attribute12-unclick"; this.className = "attribute12-click"; var text = this.innerHTML; var dicti = { Fibrous: 0, Scaly: 1, Silky: 2, Smooth: 3 }; document.getElementById("stalk_surface_above_ring").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute13-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute13-click")[0]; if (this.className == "attribute13-unclick") { if (clicked) clicked.className = "attribute13-unclick"; this.className = "attribute13-click"; var text = this.innerHTML; var dicti = { Fibrous: 0, Scaly: 1, Silky: 2, Smooth: 3 }; document.getElementById("stalk_surface_below_ring").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute14-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute14-click")[0]; if (this.className == "attribute14-unclick") { if (clicked) clicked.className = "attribute14-unclick"; this.className = "attribute14-click"; var text = this.innerHTML; var dicti = { Brown: 0, Buff: 1, Cinnamon: 2, Gray: 3, Orange: 4, Pink: 5, Red: 6, White: 7, Yellow: 8 }; document.getElementById("stalk_color_above_ring").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute15-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute15-click")[0]; if (this.className == "attribute15-unclick") { if (clicked) clicked.className = "attribute15-unclick"; this.className = "attribute15-click"; var text = this.innerHTML; var dicti = { Brown: 0, Buff: 1, Cinnamon: 2, Gray: 3, Orange: 4, Pink: 5, Red: 6, White: 7, Yellow: 8 }; document.getElementById("stalk_color_belowove_ring").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute16-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute16-click")[0]; if (this.className == "attribute16-unclick") { if (clicked) clicked.className = "attribute16-unclick"; this.className = "attribute16-click"; var text = this.innerHTML; var dicti = { Partial: 0, Universal: 1 }; document.getElementById("veil_type").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute17-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute17-click")[0]; if (this.className == "attribute17-unclick") { if (clicked) clicked.className = "attribute17-unclick"; this.className = "attribute17-click"; var text = this.innerHTML; var dicti = { Brown: 0, Orange: 1, White: 2, Yellow: 3 }; document.getElementById("veil_color").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute18-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute18-click")[0]; if (this.className == "attribute18-unclick") { if (clicked) clicked.className = "attribute18-unclick"; this.className = "attribute18-click"; var text = this.innerHTML; var dicti = { None: 0, One: 1, Two: 2 }; document.getElementById("ring_number").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute19-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute19-click")[0]; if (this.className == "attribute19-unclick") { if (clicked) clicked.className = "attribute19-unclick"; this.className = "attribute19-click"; var text = this.innerHTML; var dicti = { Cobwebby: 0, Evanescent: 1, Flaring: 2, Large: 3, One: 4, Pendant: 5, Sheathing: 6, Zone: 7 }; document.getElementById("ring_type").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute20-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute20-click")[0]; if (this.className == "attribute20-unclick") { if (clicked) clicked.className = "attribute20-unclick"; this.className = "attribute20-click"; var text = this.innerHTML; var dicti = { Black: 0, Brown: 1, Buff: 2, Chocolate: 3, Green: 4, Orange: 5, Purple: 6, White: 7, Yellow: 8 }; document.getElementById("spore_print_color").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute21-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute21-click")[0]; if (this.className == "attribute21-unclick") { if (clicked) clicked.className = "attribute21-unclick"; this.className = "attribute21-click"; var text = this.innerHTML; var dicti = { Abundant: 0, Clustered: 1, Numerous: 2, Scattered: 3, Several: 4, Solitary: 5 }; document.getElementById("population").value = dicti[text]; } } } var lists = document.querySelectorAll("li .attribute22-unclick"); for (list in lists) { lists[list].onclick = function () { var clicked = document.querySelectorAll(".attribute22-click")[0]; if (this.className == "attribute22-unclick") { if (clicked) clicked.className = "attribute22-unclick"; this.className = "attribute22-click"; var text = this.innerHTML; var dicti = { Grasses: 0, Leaves: 1, Meadows: 2, Paths: 3, Urban: 4, Waste: 5, Woods: 6 }; document.getElementById("habitat").value = dicti[text]; } } } function submit() { document.getElementById("cap_shape").value document.getElementById("cap_surface").value document.getElementById("cap_color").value document.getElementById("bruises").value document.getElementById("odor").value document.getElementById("gill_attachment").value document.getElementById("gill_spacing").value document.getElementById("gill_size").value document.getElementById("gill_color").value document.getElementById("stalk_shape").value document.getElementById("stalk_root").value document.getElementById("stalk_surface_above_ring").value document.getElementById("stalk_surface_below_ring").value document.getElementById("stalk_color_above_ring").value document.getElementById("stalk_color_below_ring").value document.getElementById("veil_type").value document.getElementById("veil_color").value document.getElementById("ring_number").value document.getElementById("ring_type").value document.getElementById("spore_print_color").value document.getElementById("population").value document.getElementById("habitat").value }
Java
UTF-8
838
2.078125
2
[ "Unlicense" ]
permissive
package code.example; import com.google.inject.ProvisionException; import com.google.inject.servlet.ServletModule; import com.philips.app.boot.PhilipsInjector; import java.io.IOException; import java.io.InputStream; /** * Created by aweise on 30/12/16. */ public class GuiceModuleTest extends ServletModule { @Override protected void configureServlets() { // install(loadBootConfig(0).withModules()); bind(ServerRequest.class); } // static PhilipsInjector loadBootConfig(final int port){ // try(InputStream is = GuiceStart.class.getResourceAsStream("/configuration.yml")){ // return PhilipsInjector.fromStream(is).configBoot(cs -> cs.withPort(port)); // } catch (IOException e) { // throw new ProvisionException("not found configuration", e); // } // } }
C#
UTF-8
1,723
2.65625
3
[ "MIT" ]
permissive
namespace ClicksAndDrive.Services.Data { using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using ClicksAndDrive.Data; using ClicksAndDrive.Data.Models; using ClicksAndDrive.Services.Data.Contracts; using Microsoft.AspNetCore.Http; public class ImageService : IImageService { public const string IMAGEPATH = "wwwroot/images/CardId/{0}.jpg"; private readonly ApplicationDbContext db; public ImageService(ApplicationDbContext db) { this.db = db; } public async Task UploadImage(IFormFile formImage, string path) { this.DeleteImage(path); using (var stream = new FileStream(path, FileMode.Create)) { await formImage.CopyToAsync(stream); } } public void DeleteImage(string imagePath) { if (imagePath != null) { System.IO.File.Delete(imagePath); } } public async Task UploadImages(IList<IFormFile> formImages, int count, string id) { var imageUrls = new List<string>(); for (int i = 0; i < formImages.Count; i++) { var urlName = $"Id{id}_{count + i}"; var imagePath = string.Format(IMAGEPATH, urlName); await this.UploadImage(formImages[i], imagePath); var image = new Image() { ImageUrl = imagePath, UserId = id, }; this.db.Images.Add(image); await this.db.SaveChangesAsync(); } } } }
Python
UTF-8
698
3.5
4
[]
no_license
class Solution: def findTotalFruit(self, tree): """ :type tree: List[int] :rtypr: int """ j = 0 m = {} for i in range(0, len(tree)): if tree[i] in m: m[tree[i]]+=1 else: m[tree[i]]=1 print(m) while len(m)>2 and j<=i: print(m) m[tree[j]]-=1 if m[tree[j]]==0: del m[tree[j]] j+=1 return i-j+1 if __name__ == '__main__': s = Solution() tree = [1,2,3,2,2] result = s.findTotalFruit(tree) print(result)
Python
UTF-8
935
2.84375
3
[]
no_license
#!/bin/python3 import math import os import random import re import sys from itertools import combinations # Complete the maxMin function below. def maxMin(k, arr): arr.sort() '''mini = 999999999 arr.sort() li = list(combinations(arr,k)) for i in li: mins = max(i)-min(i) if(mins<mini): mini = mins''' #sort and do max - min, no need to find max and min as array is sorted so i+kth #element will always be the max and ith will always be min return min([arr[i+k-1]-arr[i] for i in range(len(arr)-k+1)]) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) k = int(input()) arr = [] for _ in range(n): arr_item = int(input()) arr.append(arr_item) result = maxMin(k, arr) #res = list(map(str,result)) #print(' '.join(res)) fptr.write(str(result) + '\n') fptr.close()
Java
UTF-8
11,481
2.109375
2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
/* * AllBinary Open License Version 1 * Copyright (c) 2011 AllBinary * * By agreeing to this license you and any business entity you represent are * legally bound to the AllBinary Open License Version 1 legal agreement. * * You may obtain the AllBinary Open License Version 1 legal agreement from * AllBinary or the root directory of AllBinary's AllBinary Platform repository. * * Created By: Travis Berthelot * */ package org.allbinary.business.init; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.Vector; import org.allbinary.business.init.db.DatabaseConnectionInfoInterface; import org.allbinary.business.init.db.DbConnectionInfo; import org.allbinary.logic.basic.string.CommonSeps; import org.allbinary.logic.basic.string.StringUtil; import org.allbinary.logic.basic.string.StringValidationUtil; import org.allbinary.logic.communication.log.PreLogUtil; import org.allbinary.logic.communication.log.config.type.LogConfigType; import org.allbinary.logic.communication.log.config.type.LogConfigTypes; public class InitSql { private DbConnectionInfo databaseConnectionInfoInterface; private String userid; private String password; private String tableName; private Connection conn; private boolean useridAndPassword; public InitSql(DbConnectionInfo databaseConnectionInfoInterface) { this.setDatabaseConnectionInfoInterface(databaseConnectionInfoInterface); } public void setTable(String tableName) { this.tableName = tableName; } public void setDatabaseConnectionInfoInterface( DbConnectionInfo databaseConnectionInfoInterface) { this.databaseConnectionInfoInterface = databaseConnectionInfoInterface; } public boolean createTable(String tableData) { try { this.executeSQLStatement(tableData); return true; } catch(Exception e) { if(LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("error","InitSql","createTables()",e); } return false; } } public boolean dropTable() { String sqlStatement = "DROP TABLE " + tableName; try { this.executeSQLStatement(sqlStatement); return true; } catch(Exception e) { if(LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("Failed to Drop","InitSql","dropTables()",e); } return false; } } public HashMap getRow(HashMap keysAndValues) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("SELECT *"); stringBuffer.append(" FROM "); stringBuffer.append(this.tableName); stringBuffer.append(" WHERE "); try { HashMap result = null; Set set = keysAndValues.keySet(); Iterator iter = set.iterator(); while (iter.hasNext()) { String key = (String) iter.next(); String value = new String((String) keysAndValues.get(key)); stringBuffer.append(key); stringBuffer.append(" = \""); stringBuffer.append(this.getValue(value)); stringBuffer.append("\""); if (iter.hasNext()) { stringBuffer.append(" AND "); } } if (LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGING)) { PreLogUtil.put("SQL Statement: " + stringBuffer, this, "getRow"); } String sqlStatement = stringBuffer.toString(); ResultSet rset = this.executeSQLStatement(sqlStatement); ResultSetMetaData resultSetMetaData = rset.getMetaData(); while (rset.next()) { result = new HashMap(); Vector columnNames = new Vector(); int columnCount = resultSetMetaData.getColumnCount(); for (int index = 1; index <= columnCount; index++) { String columnName = resultSetMetaData.getColumnName(index); String field = rset.getString(columnName); result.put(columnName, field); } if (LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGING)) { PreLogUtil.put("Row Value: " + result.toString(), this, "getRow"); } return result; } return null; } catch (Exception e) { if (LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("Failed\nSQL Statement: " + stringBuffer, this, "getRow", e); } return null; } } public synchronized void updateWhere(String key, String value, HashMap updatedKeyValuePairs) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("UPDATE "); stringBuffer.append(this.tableName); stringBuffer.append(" SET "); try { Iterator iter = updatedKeyValuePairs.keySet().iterator(); while (iter.hasNext()) { String columnName = iter.next().toString(); stringBuffer.append(CommonSeps.getInstance().SPACE); stringBuffer.append(columnName); stringBuffer.append("=\""); String columnValue = (String) updatedKeyValuePairs.get(columnName); if (columnValue == null) { columnValue = StringUtil.getInstance().EMPTY_STRING; } else { } stringBuffer.append(this.getValue(columnValue)); stringBuffer.append("\""); if (iter.hasNext()) { stringBuffer.append(","); } } stringBuffer.append(" WHERE "); stringBuffer.append(key); stringBuffer.append(" = \""); stringBuffer.append(this.getValue(value)); stringBuffer.append("\""); String sqlStatement = stringBuffer.toString(); this.executeSQLStatement(sqlStatement); if (LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGING)) { PreLogUtil.put("Update Succeeded\nSQL Statement: " + sqlStatement, this, "updateWhere"); } } catch (Exception e) { if (LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("Update Failed\nSQL Statement: " + stringBuffer, this, "updateWhere", e); } } } public void insert(Vector values) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("INSERT INTO "); stringBuffer.append(this.tableName); stringBuffer.append(" VALUES ('"); try { //Iterator iter = values.iterator(); for (int i = 0; i < values.size() - 1; i++) { String value = this.getValue((String) values.get(i)); stringBuffer.append(value); stringBuffer.append("','"); } String value = this.getValue((String) values.lastElement()); stringBuffer.append(value); stringBuffer.append("')"); String sqlStatement = stringBuffer.toString(); this.executeSQLStatement(sqlStatement); if (LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGING)) { PreLogUtil.put("Insert Succeeded\nSQL Statement: " + sqlStatement, this, "insert"); } } catch (Exception e) { if (LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("Insert Failed\nSQL Statement: " + stringBuffer.toString(), this, "insert", e); } } } private synchronized String getValue(String value) { if (StringValidationUtil.getInstance().isEmpty(value)) { return StringUtil.getInstance().EMPTY_STRING; } else { return value; } } public ResultSet executeSQLStatement(String statement) throws Exception, SQLException { try { if(conn == null) { initialize(); } Statement stmt = conn.createStatement(); //ResultSet rset = stmt.executeQuery(statement); //TWB- Changes For GAE JIQL stmt.execute(statement); ResultSet rset = stmt.getResultSet(); stmt.close(); return rset; } catch(SQLException e) { if(LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("SQL error","InitSql","executeSQLStatement()",e); } throw e; } catch(Exception e) { if(LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("SQL error","InitSql","executeSQLStatement()",e); } throw e; } } private void createConnection() throws SQLException { try { if(useridAndPassword==true) { conn = DriverManager.getConnection( this.getDatabaseConnectionInfoInterface().getUrl(), userid, password); } else { conn = DriverManager.getConnection( this.getDatabaseConnectionInfoInterface().getUrl()); } } catch(SQLException se) { PreLogUtil.put("error","InitSql","createConnection()",se); throw se; } } private void initialize() throws Exception { try { try { Class.forName(this.getDatabaseConnectionInfoInterface().getJdbcDriver()).newInstance(); //Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch(Exception e) { if(LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("Load mySQL Driver Failed: " + this.getDatabaseConnectionInfoInterface().getJdbcDriver(), "InitSql","initialization()",e); } throw e; } if(userid == null && password == null) { useridAndPassword=true; } this.createConnection(); } catch(Exception se) { if(LogConfigTypes.LOGGING.contains(LogConfigType.SQLLOGGINGERROR)) { PreLogUtil.put("Error","InitSql","initialization()",se); } throw se; } } public DatabaseConnectionInfoInterface getDatabaseConnectionInfoInterface() { return databaseConnectionInfoInterface; } }
C
UTF-8
192
3
3
[ "MIT" ]
permissive
#include <stdio.h> int main() { char a[]="hello"; a[0]='X'; printf("1"); printf("a[]= %s\n",a); char *p="world"; printf("1"); // p[0]='X'; printf("*p= %s\n",p); return 0; }
Python
UTF-8
1,616
3.015625
3
[]
no_license
""" It loads the npz file, not the corpus """ import numpy as np import json def load_data(path_to_npz, vocab_file_path): """ Solver will take this object and work it out inside """ # ['train_sentences', 'W_embed', 'dev_sentences', 'test_sentences', # 'y_dev', 'y_train', 'word_idx_map', 'y_test', 'idx_word_map'] data = np.load(path_to_npz) # we need to store those into Python variables (into memory) print "loading source sentences..." train_src_sentences = data['train_src_sentences'] dev_src_sentences = data['dev_src_sentences'] test_src_sentences = data['test_src_sentences'] print "loading target sentences..." train_tgt_sentences = data['train_tgt_sentences'] dev_tgt_sentences = data['dev_tgt_sentences'] test_tgt_sentences = data['test_tgt_sentences'] y_train = data['y_train'] y_dev = data['y_dev'] y_test = data['y_test'] print "loading embeddings..." W_embed = data['W_embed'] with open(vocab_file_path, 'r') as f: vocab = json.load(f) word_idx_map = vocab['word_idx_map'] idx_word_map = vocab['idx_word_map'] return { 'train_src_sentences': train_src_sentences, 'W_embed': W_embed, 'dev_src_sentences': dev_src_sentences, 'test_src_sentences': test_src_sentences, 'train_tgt_sentences': train_tgt_sentences, 'dev_tgt_sentences': dev_tgt_sentences, 'test_tgt_sentences': test_tgt_sentences, 'y_dev': y_dev, 'y_train': y_train, 'word_idx_map': word_idx_map, 'y_test': y_test, 'idx_word_map': idx_word_map }
PHP
UTF-8
654
2.796875
3
[]
no_license
<?php class Forum{ private $_id; private $_idCat; private $_name; private $_description; private $_ordre; private $_lastPost; private $_nbTopic; private $_nbPost; public function id(){return $this->_id;} public function idCat(){return $this->_idcat;} public function name(){return $this->_name;} public function description(){return $this->_description;} public function Ordre(){return $this->_ordre;} public function lastPost(){return $this->_lastPost;} public function nbTopic(){return $this->_nbTopic;} public function nbPost(){return $this->_nbPost;} public function __construct(){ } } ?>
Markdown
UTF-8
2,172
2.71875
3
[]
no_license
# AJAXistic => AJAX + fantaSTIC <p align="center"> <img src="https://i.imgur.com/13792LE.png" align="center" width="800" height="500"></img> </p> <p align="center"> Live Link: <a href="http://ajaxistic.co.uk" alt="Ajaxistic"/>Ajaxistic</a></p> ## AJAX ✏️ - stands for Aysnchronus Javascript And XML - is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and JavaScript. - is a web browser technology independent of web server software - updates a web page without reloading the page - requests data from a server - after the page has loaded - receives data from a server - after the page has loaded - sends data to a server - in the background ## My AJAX Workflow ✨ ✔️ First, I will open a web page as usual with a synchronous request. ✔️ Next, I will click on a DOM element usually either a button or link which initiates an asynchronous request to the back-end server. ✔️ I will not notice this, since the call is made asynchronously and doesn’t refresh the browser. ✔️ In response to my AJAX request, the server may return XML, JSON, or HTML string data. ✔️ I will parse the responsed data using JavaScript/JQuery. ✔️ This parsed data is updated in the web page's DOM. ✔️ My web page now is updated with real-time data from the server without the browser reloading.✌️ ## Technologies & Tools I used for this project 🛠️ - Front-end -> HTML, CSS, JQuery - Back-end -> PHP - Free API's -> <a href="https://www.geonames.org/">GeoNames</a> - Free Favicons -> <a href="https://favicon.io/">Favicon</a> - Minified CSS & JS -> <a href="https://www.minifier.org/">Minify</a> - Domain Registration, Web Hosting at -> <a href="https://www.ionos.co.uk/">IONOS</a> - Generated a report using Chrome Dev Tools Lighthouse. Identified and fixed common problems that are affecting site's performance, accessibility, and user experience. At the end, achieved 100% across all but BEST Practices, that's due to the absense of secure connection(https) which I didn't buy. ## References I used 🙏🙏🙏 - <a href="https://www.google.com/">Google</a>
Java
UTF-8
1,999
2.265625
2
[]
no_license
package dataservice.orderdataservice; import dataservice.DataServiceParent; import po.order.ReviewPO; import po.order.OrderPO; import util.OrderType; import util.ResultMessage; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.ArrayList; /** * Created by Hiki on 2016/10/16. */ public interface OrderDataService extends Remote{ // 增加订单 public ResultMessage insert(OrderPO orderPO) throws RemoteException; // 更新订单 public ResultMessage update(OrderPO orderPO) throws RemoteException; // 显示订单列表 public ArrayList<OrderPO> findAll() throws RemoteException; // 根据ID查找订单 public OrderPO findByOrderID(String orderID) throws RemoteException; // 根据hotelID查找订单 public ArrayList<OrderPO> findByHotelID(long hotelID) throws RemoteException; // 根据OrderType查找订单 public ArrayList<OrderPO> findByType(OrderType orderType) throws RemoteException; // 根据hotelID和OrderType查找订单 public ArrayList<OrderPO> findByHotelIDAndType(long hotelID, OrderType orderType) throws RemoteException; // 根据username查找订单 public ArrayList<OrderPO> findByUsername(String username) throws RemoteException; // 根据username和OrderType查找订单 public ArrayList<OrderPO> findByUsernameAndType(String username, OrderType orderType) throws RemoteException; // 根据username和hotelID查找订单 public ArrayList<OrderPO> findByUsernameAndHotelID(String username, long hotelID) throws RemoteException; // // 根据筛选条件(订单类型、用户名、酒店ID)查找订单 // public ArrayList<OrderPO> findByConditions(OrderPO orderPO) throws RemoteException; // // 根据hotelID获得订单中的reviews // public ArrayList<ReviewPO> findReviewByHotelID(long hotelID) throws RemoteException; // // // 获得所有订单的reviews // public ArrayList<ReviewPO> findAllReviews() throws RemoteException; }
Python
UTF-8
852
2.953125
3
[]
no_license
import unittest from .disjoint_set import DisjointSetNode class TestCase(unittest.TestCase): def setUp(self) -> None: self.set_a = DisjointSetNode("Set A") self.set_c = DisjointSetNode("Set C") self.set_d = DisjointSetNode("Set D") self.set_b = DisjointSetNode("Set B") def test_disjoint_set(self) -> None: self.assertIsNot( self.set_a.find_set(), self.set_b.find_set(), ) self.set_a.union(self.set_c) self.assertEqual( self.set_a.find_set(), self.set_c.find_set(), ) self.assertIsNot( self.set_c.find_set(), self.set_d.find_set(), ) self.set_c.union(self.set_d) self.assertEqual( self.set_a.find_set(), self.set_d.find_set(), )
Java
UTF-8
542
2.15625
2
[]
no_license
package com.github.zhuangzhao.distributeduniqueid.zookeeper; import lombok.Data; import java.io.File; /** * @author zhuangzhao.zhu, <zhuangzhao2726@gmail.com> * @date 2019-05-26. */ @Data public class ZookeeperNode { private String nameSpace; private String relativePath; private String zkPath; public ZookeeperNode() { } public ZookeeperNode(String nameSpace, String separator, String relativePath) { this.nameSpace = nameSpace; this.relativePath = relativePath; this.zkPath = nameSpace + separator + relativePath; } }
Java
UTF-8
2,554
2.578125
3
[]
no_license
package sample.ejb; import javax.annotation.Resource; import javax.ejb.Local; import javax.ejb.Stateless; import javax.jms.*; @Local @Stateless public class MessageConsumerBean implements MessageConsumer { // TODO: SLSB should not have state private static QueueConnection conn; private static QueueSession session; @Resource(mappedName = "java:/ConnectionFactory") private ConnectionFactory cf; @Resource(mappedName = "/queue/HelloQueue") private Queue queue; private volatile boolean isRunning; @Override public void start() { if (isRunning) { System.out.println("HelloQueue-receiver-thread already running"); return; } try { this.conn = (QueueConnection) cf.createConnection(); this.session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); final QueueReceiver receiver = session.createReceiver(queue); conn.start(); this.isRunning = true; new Thread(new Runnable() { @Override public void run() { while (true) { try { Message message = receiver.receive(5000); if (message != null) { TextMessage text = (TextMessage) message; try { System.out.println("MessageConsumerBean: " + text.getText() + ", instance: " + System.getProperty("jboss.home.dir")); } catch (JMSException e) { e.printStackTrace(); } } else { System.out.println("no message HelloQueue"); } } catch (JMSException e) { e.printStackTrace(); } if (!isRunning) { JmsUtil.close(session); JmsUtil.close(conn); System.out.println("stop message consume loop"); break; } } } }, "HelloQueue-receiver-thread").start(); } catch (JMSException e) { e.printStackTrace(); } } public void stop() { this.isRunning = false; } }
TypeScript
UTF-8
416
2.546875
3
[]
no_license
import { IGameUserRoundInfo, getNullGameUserRoundInfo } from "./game-user-round-info"; import { IUser } from "./user"; export interface IGameUser { user: IUser; points: number; roundInfo: IGameUserRoundInfo; } export class GameUser implements IGameUser { constructor( public user: IUser, public points: number = 0, public roundInfo: IGameUserRoundInfo = getNullGameUserRoundInfo() ) {} }
Markdown
UTF-8
3,135
2.96875
3
[]
no_license
## 42장 ### 사제들의 방 1 그는 나를 북쪽의 바깥뜰로 데리고 나가서, 마당으로 난, 곧 북쪽 건물을 비스듬히 마주한 방들이 있는 곳으로 갔다. 2 그 방들은 북쪽 면의 길이가 백 암마이고 너비는 쉰 암마였다. 3 안뜰에서 스무 암마 되는 지점, 바깥뜰의 돌을 깐 바닥 맞은쪽에 삼 층으로 얹은 회랑이 있었다. 4 그리고 그 방들 앞에는 안쪽으로 복도가 있었는데, 너비가 열 암마, 길이가 백 암마였으며, 입구들은 북쪽에 나 있었다. 5 위층의 방들이 가장 좁았는데, 그것은 회랑이 건물의 아래층과 가운데 층에서보다 자리를 더 차지하였기 때문이다. 6 이 방들은 삼 층으로 되어 있는데다, 거기에는 바깥뜰의 기둥들과 같은 기둥이 없었다. 그래서 위층이 아래층과 가운데 층보다 땅바닥에서 안으로 더 들어가 있었다. 7 이 방들 앞에는, 바깥뜰 쪽으로 이 방들과 나란히 바깥담이 있는데, 그 길이가 쉰 암마였다. 8 바깥뜰로 난 방들의 길이가 쉰 암마였기 때문이다. 반면에 성소 쪽으로 난 방들의 길이는 백 암마였다. 9 이 방들 아래에는 동쪽에서 들어오는 통로가 있었는데, 바깥뜰에서 그리로 들어오게 되어 있었다. 10 뜰에 있는 벽과 나란히, 남쪽으로 마당과 건물을 마주하고 방들이 있었다. 11 그 방들 앞에는 북쪽에 있는 방들과 같은 식으로 길이 나 있었는데, 그 길이도 같고 너비도 같았으며, 나가는 곳도 그것들의 구조도 들어가는 곳도 마찬가지였다. 12 남쪽으로 난 이 방들 아래, 보호 벽이 시작하는 길 어귀에, 동쪽에서 들어오는 입구가 있었다. 13 그가 나에게 말하였다. “마당 맞은쪽에 있는 북쪽 방들과 남쪽 방들은 거룩한 방들로서, 주님께 가까이 나아가는 사제들이 가장 거룩한 제물을 먹는 곳이다. 그 방들은 거룩한 곳이니, 가장 거룩한 제물과 곡식 제물과 속죄 제물과 보상 제물을 그곳에 두어야 한다. 14 사제들이 성소에 들어가면, 그곳에서는 곧바로 바깥뜰로 나가지 못한다. 그들이 주님을 섬길 때에 입는 옷이 거룩하기 때문에, 그 옷을 거기에 벗어 놓고 다른 옷으로 갈아입은 다음에야, 백성이 모이는 곳으로 가까이 갈 수 있다.” ### 안뜰의 넓이 15 주님의 집 안쪽을 모두 잰 다음, 그는 동쪽 대문으로 나를 데리고 나와서 사방을 재었다. 16 그가 측량 장대로 동쪽을 재니, 측량 장대로 오백 암마였고, 17 북쪽을 재니 측량 장대로 또 오백 암마였다. 18 그리고 남쪽을 재니 측량 장대로 또 오백 암마였다. 19 그런 다음 그가 서쪽으로 돌아 그것을 재니, 측량 장대로 또 오백 암마였다. 20 그는 이렇게 사방을 재었다. 거기에는 사방으로 길이가 오백 암마, 너비가 오백 암마 되는 담이 둘러 있었는데, 이는 거룩한 것과 속된 것을 분리하기 위한 담이었다.
Java
UTF-8
823
3.40625
3
[]
no_license
package thread; public class MainClass { public static void main(String[] args) { // TODO Auto-generated method stub CounterThread t =new CounterThread(); t.start(); //after this run() method is executing its task try { Thread.sleep(2000); } catch (InterruptedException e) {} // t.stopped=true; t.interrupt();// we must set t thread is Deamon then we can use interrupt method to stop it System.out.println("exit"); } } class CounterThread extends Thread { public CounterThread() { // TODO Auto-generated constructor stub setDaemon(true); } public boolean stopped=false; int count=0; @Override public void run() { // TODO Auto-generated method stub while(!stopped) { try { sleep(100); } catch(InterruptedException e) { } System.out.println(count++); } } }
Java
UTF-8
821
2.75
3
[]
no_license
package learnrxjava.types; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public interface ComposableList<T> extends Iterable<T> { <R> ComposableList<R> map(Function<T, R> projectionFunction); ComposableList<T> filter(Predicate<T> predicateFunction); <R> ComposableList<R> concatMap(Function<T, ComposableList<R>> projectionFunctionThatReturnsList); ComposableList<T> reduce(BiFunction<T, T, T> combiner); <R> ComposableList<R> reduce(R initialValue, BiFunction<R, T, R> combiner); // <T0,T1,R> ComposableList<R> zip(ComposableList<T0> left, ComposableList<T1> right, BiFunction<T0, T1, R> combiner); int size(); void forEach(Consumer<? super T> action); T get(int index); }
Java
UTF-8
8,635
2.25
2
[]
no_license
package dji.midware.aoabridge; import dji.fieldAnnotation.EXClassNullAway; import dji.midware.aoabridge.AoaController; import dji.midware.aoabridge.DJIBaseCommData; import dji.midware.data.manager.P3.DataEvent; import dji.midware.data.manager.P3.ServiceManager; import dji.midware.util.DJIEventBusUtil; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; @EXClassNullAway public class ProxyEventServer { /* access modifiers changed from: private */ public EventClientInfo curClient; private DataEvent dataEvent = DataEvent.ConnectLose; /* access modifiers changed from: private */ public Map<String, EventClientInfo> ipMap; private int port = -1; private ServerSocket server; public ProxyEventServer(int port2) { this.port = port2; } public void init() { new Thread("ProxyEvent") { /* class dji.midware.aoabridge.ProxyEventServer.AnonymousClass1 */ public void run() { ProxyEventServer.this.initSocket(); } }.start(); } public void uninit() { closeServer(); DJIEventBusUtil.unRegister(this); } public void switchClient(String packageName) { EventClientInfo info = getEventClientInfo(packageName); if (info != null && info != this.curClient) { if (this.curClient != null && ServiceManager.getInstance().isConnected()) { sendEvent(AoaController.RcEvent.DisConnected); } this.curClient = info; if (ServiceManager.getInstance().isConnected()) { sendEvent(AoaController.RcEvent.Connected); } } } /* access modifiers changed from: private */ public void sendEvent() { AoaController.RcEvent event; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } boolean isConnected = ServiceManager.getInstance().isConnected(); if (ServiceManager.getInstance().isConnected()) { event = AoaController.RcEvent.Connected; } else { event = AoaController.RcEvent.DisConnected; } sendEvent(event); } public EventClientInfo getEventClientInfo(String packageName) { if (packageName == null) { return null; } for (String ip : this.ipMap.keySet()) { EventClientInfo info = this.ipMap.get(ip); if (packageName.equals(info.packageName)) { return info; } } return null; } private void sendEvent(AoaController.RcEvent event) { DJIBaseCommData commData = new DJIBaseCommData(); commData.setNumberWithTag(5, DJIBaseCommData.DJIBaseCommDataTag.DJIBaseCommData_Who.ordinal()); commData.setNumberWithTag(event.ordinal(), DJIBaseCommData.DJIBaseCommDataTag.DJIBaseCommData_Event.ordinal()); byte[] data = commData.packedData(); sendByte(data, data.length); } /* access modifiers changed from: private */ public void initSocket() { DJIEventBusUtil.register(this); try { this.ipMap = new HashMap(); this.server = new ServerSocket(this.port); while (true) { Socket socket = this.server.accept(); if (socket != null) { EventClientInfo info = new EventClientInfo(socket, socket.getInputStream(), socket.getOutputStream()); this.ipMap.put(info.ip, info); info.start(); } else { return; } } } catch (Exception e) { e.printStackTrace(); } } private void closeServer() { closeServerSocket(); try { if (this.server != null) { this.server.close(); } } catch (Exception e) { e.printStackTrace(); } } private void closeServerSocket() { String[] ips = new String[this.ipMap.size()]; this.ipMap.keySet().toArray(ips); for (String ip : ips) { this.ipMap.get(ip).closeClientSocket(); } } private void sendByte(byte[] data, int len) { if (this.ipMap.size() != 0) { if (this.curClient == null) { Iterator<String> it2 = this.ipMap.keySet().iterator(); if (it2.hasNext()) { this.curClient = this.ipMap.get(it2.next()); } } if (this.curClient != null) { this.curClient.sendByte(data, len); } } } @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onEvent3BackgroundThread(DataEvent event) { sendEvent(); } public void updateClientInfo(String packageName, int port2) { String ipPort = String.format(Locale.US, "%s:%d", Utils.getIp(), Integer.valueOf(port2)); if (this.ipMap.containsKey(ipPort)) { this.ipMap.get(ipPort).packageName = packageName; } } public boolean containApp(String packageName) { return getEventClientInfo(packageName) != null; } private class EventClientInfo extends Thread { /* renamed from: in reason: collision with root package name */ public InputStream f6in; public String ip; public OutputStream out; public String packageName; public Socket socket; public EventClientInfo(Socket socket2, InputStream in2, OutputStream out2) { setName("EventClientInfoThread"); this.socket = socket2; this.f6in = in2; this.out = out2; if (socket2.getInetAddress() != null && socket2.getInetAddress().getAddress() != null && socket2.getInetAddress().getAddress().length == 4) { byte[] address = socket2.getInetAddress().getAddress(); this.ip = String.format(Locale.US, "%d.%d.%d.%d:%d", Integer.valueOf(address[0] & 255), Integer.valueOf(address[1] & 255), Integer.valueOf(address[2] & 255), Integer.valueOf(address[3] & 255), Integer.valueOf(socket2.getPort())); } } public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } ProxyEventServer.this.sendEvent(); DJIBaseCommData commData = new DJIBaseCommData(); commData.setNumberWithTag(99, DJIBaseCommData.DJIBaseCommDataTag.DJIBaseCommData_Who.ordinal()); commData.setNumberWithTag(0, DJIBaseCommData.DJIBaseCommDataTag.DJIBaseCommData_Event.ordinal()); byte[] noUseData = commData.packedData(); while (sendByte(noUseData, noUseData.length)) { try { Thread.sleep(500); } catch (Exception e2) { e2.printStackTrace(); } } closeClientSocket(); } /* access modifiers changed from: private */ public void closeClientSocket() { try { if (this.out != null) { this.out.close(); this.out = null; } if (this.f6in != null) { this.f6in.close(); this.f6in = null; } if (this.socket != null) { this.socket.close(); this.socket = null; } if (ProxyEventServer.this.ipMap.containsKey(this.ip)) { ProxyEventServer.this.ipMap.remove(this.ip); if (ProxyEventServer.this.curClient == this) { EventClientInfo unused = ProxyEventServer.this.curClient = null; } } } catch (Exception ex) { ex.printStackTrace(); } } public boolean sendByte(byte[] data, int len) { try { this.out.write(data, 0, len); this.out.flush(); return true; } catch (Exception e) { e.printStackTrace(); closeClientSocket(); return false; } } } }
Java
UTF-8
962
2.109375
2
[]
no_license
package com.way2invoice.bms.service.dto; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import com.way2invoice.bms.web.rest.TestUtil; public class AccountTaxInfoDTOTest { @Test public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(AccountTaxInfoDTO.class); AccountTaxInfoDTO accountTaxInfoDTO1 = new AccountTaxInfoDTO(); accountTaxInfoDTO1.setId(1L); AccountTaxInfoDTO accountTaxInfoDTO2 = new AccountTaxInfoDTO(); assertThat(accountTaxInfoDTO1).isNotEqualTo(accountTaxInfoDTO2); accountTaxInfoDTO2.setId(accountTaxInfoDTO1.getId()); assertThat(accountTaxInfoDTO1).isEqualTo(accountTaxInfoDTO2); accountTaxInfoDTO2.setId(2L); assertThat(accountTaxInfoDTO1).isNotEqualTo(accountTaxInfoDTO2); accountTaxInfoDTO1.setId(null); assertThat(accountTaxInfoDTO1).isNotEqualTo(accountTaxInfoDTO2); } }
C++
UTF-8
1,045
2.78125
3
[ "MIT" ]
permissive
/**************************************************************************** ** ** Copyright (C) 2019 Xiaohai <xiaohaidotpro@outlook.com>. ** Contact: http://xiaohai.pro ** ** This file is part of cplusplus-general-programming ** ** ****************************************************************************/ #include "bits/stdc++.h" #include "TemplateTemplateParameters.hpp" int main(int /* argc */, char** /* argv */) { Stack<int> iStack; Stack<float> fStack; iStack.push(1); iStack.push(2); std::cout << "iStack.top(): " << iStack.top() << std::endl; fStack.push(3.3f); std::cout << "fStack.top(): " << fStack.top() << std::endl; fStack = iStack; fStack.push(4.4f); Stack<double, std::vector> vStack; vStack.push(5.5); vStack.push(6.6); std::cout << "vStack.top(): " << vStack.top() << std::endl; vStack = fStack; std::cout << "vStack: "; while (!vStack.empty()) { std::cout << vStack.top() << " "; vStack.pop(); } std::cout << std::endl; return 0; }
Python
UTF-8
1,824
4.125
4
[]
no_license
from random import * from math import * def multiplication_grille(x): b = "" if x==0: return else: for i in range(1,11): a = i * x b = b + str(a) + " | " print(b) return multiplication(x-1) def justePrix(): x = randint(0,1000) guess = int(input("Entrez votre juste prix")) while guess != x : if guess > x: guess = int(input("C'est moins !")) else: guess = int(input("C'est plus")) if guess == x: print("Félication vous etes un gros k-sos") def multiplication(x,y): rslt = 0 for i in range(y): rslt = rslt +x return rslt def premier(n): prems = [3] # liste des nombres premiers initialisée à 3 i = 5 while len(prems) < n: pmax = int(sqrt(i)) # inutile de tester au delà de sqrt(i) for prem in prems: if prem>pmax: # i est premier: on le garde et on passe au i suivant prems.append(i) break if i%prem==0: # i n'est pas 1er: on passe au i suivant break i = i+2 print(prems) premier(100) def guessFirst(n): element = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" passwd = "" for i in range(n): passwd = passwd + element[randint(0, len(element) - 1)] print(passwd) element = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" dico="" while dico!=passwd: for j in range(n): dico = dico + element[randint(0, len(element) - 1)] print(dico) if len(dico)==len(passwd) and dico!=passwd: dico="" print (passwd,dico) guessFirst(3)
Python
UTF-8
610
2.859375
3
[]
no_license
import os import time print("let's make some clocks") for i in range(10): lastClock = os.fork() if lastClock == 0: os.execlp("/usr/bin/xclock", "xclock") else: print("i made one clock!") time.sleep(1) print("i wanna kill time!") def isInt(s): try: int(s) return True except ValueError: return False proc = "/proc" subdirs = os.listdir(proc) for pid in subdirs: if not isInt(pid): continue comm = proc + "/" + pid + "/comm" fd = open(comm, "r") name = fd.readline() fd.close() if "xclock" in name: os.kill(int(pid), 9) print("one clock killed!") print("all clocks killed B)")
JavaScript
UTF-8
1,796
3.484375
3
[]
no_license
let val; const list = document.querySelector('ul.collection'); const listItem = document.querySelector('li.collection-item:first-child'); val = listItem; val = list; //Properties attached to these nodes //get child nodes val = list.childNodes; //returns NodeList // val = list.childNodes[0]; // val = list.childNodes[0].nodeName; // val = list.childNodes[3].nodeType; // 6:00mins // 1 - Element // 2 - Attribute (deprecated) // 3 - Text node // 8 - Comment // 9 - Document itself // 10 - DocType //LOOP through to find all comments from the children of 'list' // let elements = Array.from(val); // let arrayOfComments = new Array(); // for(let i = 0; i < elements.length; i++){ // if(elements[i].nodeType == 8){ // arrayOfComments.push(elements[i]); // } // } // console.log(arrayOfComments); //get children element nodes only val = list.children; //returns HTMLCollection val = list.children[0]; list.children[1].textContent = 'Hello'; // children of children val = list.children[3].children; val = list.children[3].children[0]; list.children[3].children[0].id = 'test-link'; // FIRST child val = list.firstChild; //#text val = list.firstElementChild; //element, not text // LAST child val = list.lastChild; //#text val = list.lastElementChild; //COUNT val = list.childElementCount; //5, not including text val = listItem.parentNode; //<ul class="collection"></ul> val = listItem.parentElement; // val = listItem.parentElement.parentElement; //<div class="card-action"></div> //GET next SIBLING val = listItem.nextSibling; //#text val = listItem.nextElementSibling;// <li class="collection-item"></li> //GET PREVIOUS Sibling val = listItem.previousSibling; // #text val = listItem.previousElementSibling; //null, no previous siblings console.log(val);
C++
UTF-8
673
3.8125
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; // This is a PASS BY VALUE function in which a copy of the function argument is made inside the function; void f (int a){ cout << "a = " << a << endl; a = 5; cout << "a = " << a << endl; } // This is a PASS BY REFERENCE function, the argument is a pinter which can be refferenced at runtime // *p is the value that p pints to // p is the address of *p void fp(int* p){ cout << "p = " << p << endl; cout << "*p = " << *p << endl; *p = 5; cout << "*p = " << *p << endl; } int main() { int x=55; cout << "X = " << x << endl; fp(&x); cout << "X = " << x << endl; return 0; }
Java
UTF-8
472
2.703125
3
[]
no_license
package web.model; import java.util.*; public class BeerExpert { public List getBrands(String color) { List brands=new ArrayList(); if(color.equals("light")) { brands.add("Pale"); brands.add("KingFisher"); } else if(color.equals("amber")) { brands.add("5000"); brands.add("Knockout"); } else if(color.equals("brown")) { brands.add("Foster"); brands.add("Tuborg"); } else { brands.add("Local"); } return brands; } }
Java
UTF-8
4,372
1.765625
2
[]
no_license
package ar.uba.fi.nicodiaz.mascota.mismascotas; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import ar.uba.fi.nicodiaz.mascota.R; import ar.uba.fi.nicodiaz.mascota.mascotasgenerales.adopcion.AdopcionPublicarActivity; import ar.uba.fi.nicodiaz.mascota.mascotasgenerales.encontradas.EncontradasPublicarActivity; import ar.uba.fi.nicodiaz.mascota.mascotasgenerales.perdidas.PerdidasPublicarActivity; import ar.uba.fi.nicodiaz.mascota.mismascotas.adopcion.MisAdopcionesFragment; import ar.uba.fi.nicodiaz.mascota.mismascotas.encontradas.MisEncontradasFragment; import ar.uba.fi.nicodiaz.mascota.mismascotas.perdidas.MisPerdidasFragment; /** * Created by nicolas on 09/10/15. */ public class MisMascotasFragment extends Fragment { private static final String TAG = "MisMascotasFragment"; private Context activity; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { activity = getActivity(); ((AppCompatActivity) activity).getSupportActionBar().setSubtitle(null); setHasOptionsMenu(true); // View: View view = inflater.inflate(R.layout.fragment_mis_mascotas, container, false); view.setTag(TAG); ImageButton my_adopt_button = (ImageButton) view.findViewById(R.id.adoptions_button); my_adopt_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frame, new MisAdopcionesFragment()); ft.addToBackStack(null); ft.commit(); } }); ImageButton my_missing_button = (ImageButton) view.findViewById(R.id.missing_button); my_missing_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frame, new MisPerdidasFragment()); ft.addToBackStack(null); ft.commit(); } }); ImageButton my_found_button = (ImageButton) view.findViewById(R.id.found_button); my_found_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frame, new MisEncontradasFragment()); ft.addToBackStack(null); ft.commit(); } }); ImageButton add_adopt_button = (ImageButton) view.findViewById(R.id.add_adoption_button); add_adopt_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(activity, AdopcionPublicarActivity.class); startActivity(i); } }); ImageButton add_missing_button = (ImageButton) view.findViewById(R.id.add_missing_button); add_missing_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(activity, PerdidasPublicarActivity.class); startActivity(i); } }); ImageButton add_found_button = (ImageButton) view.findViewById(R.id.add_found_button); add_found_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(activity, EncontradasPublicarActivity.class); startActivity(i); } }); return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.clear(); super.onCreateOptionsMenu(menu, inflater); } }
Markdown
UTF-8
1,688
2.625
3
[]
no_license
--- title: "Manufatti - Potenza del Padre dei Draghi - Schinieri di Ossa di Drago" permalink: /artifacts/Dragonbone Greaves/ excerpt: "Era of Chaos Potenza del Padre dei Draghi - Schinieri di Ossa di Drago. Schinieri realizzati con le tibie del Re dei Draghi. Uno dei componenti della Potenza del Padre dei Draghi." last_modified_at: 2021-08-04 locale: it ref: "Dragonbone Greaves.md" toc: false classes: wide --- ## Dettagli **Descrizione:** Schinieri realizzati con le tibie del Re dei Draghi. Uno dei componenti della Potenza del Padre dei Draghi. **Part of Artifact:** ![Potenza del Padre dei Draghi](/images/t/icon_artifact_40.png) [Potenza del Padre dei Draghi](/it/artifacts/Power of the Dragon Father/){: .btn .btn--era5} **Dismantle: 225x** [Essenza di manufatto](/ItemsIT/con_905/) **Related Item**: [Schinieri di Ossa di Drago](/ItemsIT/art_145/) **Quality:** [Orange Artifact Components](/it/artifacts/Orange Artifact Components/){: .btn .btn--era5} **Upgrade cost:** [Artifact component upgrade cost](/it/artifacts/Artifact Component Upgrade/) ## Artifact Component Bonus **Punti ferita unità**: 8+(LEVEL\*3.2) %<br/>**Danno magico**: 2+(LEVEL\*0.8) %<br/>**Sapienza eroe**: 12+(LEVEL\*4.8) | Level | Type | Extra bonus | |:--------|:-----|:----------------| | **2** | Affects **9-man** unit | **ATK**: +130 | | **5** | Affects **9-man** unit | **HP**: +2460 | | **8** | Affects **9-man** unit | **ATK**: +280 | | **11** | Affects **9-man** unit | **HP**: +4770 | | **14** | Affects **9-man** unit | **ATK**: +520 | | **17** | Affects **9-man** unit | **HP**: +7090 | | **20** | Affects **9-man** unit | **ATK**: +610 |
C++
UTF-8
3,483
3.484375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <queue> #include <vector> using namespace std; typedef struct Cell { int X,Y; Cell* parent; }Cell; Cell* newCell(int x, int y) { Cell* newCell = (Cell*)malloc(sizeof(Cell)); newCell->X = x; newCell->Y = y; return newCell; } int** initialize_maze(int N) { int ** arr = (int**) malloc(N*sizeof(int*)); for(int i =0; i<N; i++) { arr[i] = (int*) malloc(N*sizeof(int)); } return arr; } bool checkIfLegalcell(Cell* currentCell, int**maze, bool isVisited, int a, int b) { if (maze[currentCell->X+a][currentCell->Y+b] == 0) { if (!isVisited) return true; } return false; } void printPath(Cell* currentCell) { vector<Cell*> path; while (currentCell->parent != NULL) { path.push_back(currentCell); currentCell = currentCell->parent; } path.push_back(currentCell); for (int i = path.size()-1; i > 0; i--) { printf("\(%d,%d\),",*(path[i])); } printf("\(%d,%d\)\n",*(path[0])); } void getPath(int** maze,int N) { if (maze[0][0] == 1 || maze[N-1][N-1] == 1) { printf("No path found\n"); return; } bool visited[N][N]; queue<Cell*> q; Cell* currentCell = newCell(0,0); q.push(currentCell); visited[0][0] = true; while(!q.empty()) { currentCell = q.front(); q.pop(); if (currentCell->Y-1 >= 0) { if (checkIfLegalcell(currentCell,maze,visited[currentCell->X][currentCell->Y-1],0,-1)) { Cell* temp = newCell(currentCell->X, currentCell->Y-1); q.push(temp); temp->parent = currentCell; visited[temp->X][temp->Y] = true; } } if (currentCell->Y+1 < N) { if (checkIfLegalcell(currentCell,maze,visited[currentCell->X][currentCell->Y+1],0,1)) { Cell* temp = newCell(currentCell->X, currentCell->Y+1); q.push(temp); temp->parent = currentCell; visited[temp->X][temp->Y] = true; } } if (currentCell->X-1 >= 0) { if (checkIfLegalcell(currentCell,maze,visited[currentCell->X-1][currentCell->Y],-1,0)) { Cell* temp = newCell(currentCell->X-1, currentCell->Y); q.push(temp); temp->parent = currentCell; visited[temp->X][temp->Y] = true; } } if (currentCell->X+1 < N) { if (checkIfLegalcell(currentCell,maze,visited[currentCell->X+1][currentCell->Y],1,0)) { Cell* temp = newCell(currentCell->X+1, currentCell->Y); q.push(temp); temp->parent = currentCell; visited[temp->X][temp->Y] = true; } } if (currentCell->X == N-1 && currentCell->Y == N-1) break; } if (!visited[N-1][N-1]) { printf("No path found\n"); return; } printPath(currentCell); } void Part2() { int N; printf("please enter N:\n"); scanf("%d", &N); printf("please enter values for maze:\n"); int** maze = initialize_maze(N); for(int i=0; i<N; i++) { for(int j=0; j<N; j++) scanf("%d", &maze[i][j]); } printf("Solution:\n"); getPath(maze,N); }
Java
UTF-8
10,742
3.03125
3
[]
no_license
/************************************************************************ * Alice Chang (avc2120), Phillip Godzin (pgg2105), Martin Ong (mo2454) * Computational Aspects of Robotics * FALL 2015 **************************************************************************/ import javax.swing.*; import java.awt.*; import java.io.*; import java.util.*; import java.util.List; public class PathPlanning extends JFrame { private static Vertex start; private static Vertex goal; private static Obstacle room; private static ArrayList<Obstacle> obstacles = new ArrayList<Obstacle>(); private static ArrayList<Obstacle> grown_obstacles = new ArrayList<Obstacle>(); private static ArrayList<Vertex> grown_vertices = new ArrayList<Vertex>(); private static ArrayList<ArrayList<Vertex>> paths = new ArrayList<ArrayList<Vertex>>(); public static final double robot_width = 0.50; public PathPlanning() { setTitle("Path Planning"); setSize(new Dimension(650, 350)); setVisible(true); } public static void main(String[] args) { readStartGoal("hw4_start_goal.txt"); System.out.println("Successfully Read Start and Goal File"); readObstacles("hw4_world_and_obstacles_convex.txt"); System.out.println("Successfully Read Obstacles File"); for(Obstacle o: obstacles.subList(1, obstacles.size())) { Obstacle grownObstacle = o.convexHull(); grownObstacle = grownObstacle.growObstacles(robot_width/2); grown_obstacles.add(grownObstacle); grown_vertices.addAll(grownObstacle.getVertices()); } System.out.println("Successfuly Grown Obstacles"); buildAdjacency(grown_vertices); System.out.println("Successfully Built Adjacency Matrix"); dijkstra(start); System.out.println("Successfully Finished Dijkstra's"); for(Vertex v: grown_vertices) { ArrayList<Vertex> path = getShortestPathTo(v); paths.add(path); } PathPlanning pathPlanning = new PathPlanning(); writePathsToFile("path.txt"); } public static void writePathsToFile(String fileName) { try { FileWriter fw = new FileWriter(fileName); ArrayList<Vertex> path = getShortestPathTo(goal); for (Vertex v : path) { fw.write(v.toString() + "\n"); } fw.close(); } catch (IOException e) { e.printStackTrace(); } } public static void readStartGoal(String fileName) { try { FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); Scanner in = new Scanner(bufferedReader); if(in.hasNext()) { String line = in.nextLine(); String[] points = line.split(" "); start = new Vertex(Double.parseDouble(points[0]), Double.parseDouble(points[1])); grown_vertices.add(start); } if(in.hasNext()) { String line = in.nextLine(); String[] points = line.split(" "); goal = new Vertex(Double.parseDouble(points[0]), Double.parseDouble(points[1])); grown_vertices.add(goal); } in.close(); } catch(FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } } public static void readObstacles(String fileName) { try { FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader); Scanner in = new Scanner(bufferedReader); int num_obstacles = in.nextInt(); in.nextLine(); for(int i = 0; i < num_obstacles; i++) { int num_vertices = in.nextInt(); in.nextLine(); ArrayList<Vertex> object_vertices = new ArrayList<Vertex>(); for(int j = 0; j < num_vertices; j++) { String[] points = in.nextLine().split(" "); object_vertices.add(new Vertex(Double.parseDouble(points[0]), Double.parseDouble(points[1]))); } obstacles.add(new Obstacle(object_vertices)); if(i == 0) { room = new Obstacle(object_vertices); } } in.close(); } catch(FileNotFoundException ex) { System.out.println("Unable to open file '" + fileName + "'"); } } public static void dijkstra(Vertex start) { //set initial source minimum distance to 0 start.minDistance = 0.0; //priority queue sorted by minimum distance PriorityQueue<Vertex> queue = new PriorityQueue<Vertex>(); //put start into queue queue.add(start); while (!queue.isEmpty()) { Vertex u = queue.poll(); for (Edge e : u.adjacencies) { Vertex v = e.target; double dist = u.minDistance + e.weight; //if found new better path, add it to the queue if (dist < v.minDistance) { queue.remove(v); v.minDistance = dist; v.previous = u; queue.add(v); } } } } public static ArrayList<Vertex> getShortestPathTo(Vertex target) { ArrayList<Vertex> path = new ArrayList<Vertex>(); //iterates through the shortest path to specified vertex backwards for (Vertex vertex = target; vertex != null; vertex = vertex.previous) { path.add(vertex); } //reverse list to get path from start Collections.reverse(path); return path; } public static void displayAdjacency(Graphics g) { double maxw = 0.0; for (Vertex v : grown_vertices) { for (Edge e : v.adjacencies) { if(e.weight != Double.POSITIVE_INFINITY) { maxw = Math.max(e.weight, maxw); } } } for(Vertex v: grown_vertices) { for(Edge e: v.adjacencies) { Vertex dest = e.target; Color color = e.weight == Double.POSITIVE_INFINITY? new Color(0,0,0,0):Color.blue; g.setColor(color); g.drawLine((int) (v.y * 40 + 160), (int) (v.x * 40 + 180), (int) (dest.y * 40 + 160), (int) (dest.x * 40 + 180)); } } } public static void buildAdjacency(List<Vertex> grown_vertices) { for (Vertex v : grown_vertices) { for (Vertex ov : grown_vertices.subList(grown_vertices.indexOf(v), grown_vertices.size())) { if (!ov.equals(v)) { boolean edge_added = false; for(Obstacle obs: grown_obstacles) { Vertex mid = v.translate(ov).multiply(0.5); //If vertex not in room if(obs.isInterior(mid) && !obs.equals(room)) { v.adjacencies.add(new Edge(ov, Double.POSITIVE_INFINITY)); edge_added = true; break; } //If not adjacent points in obstacle else if(obs.notAdjPointsInObstacle(v, ov)) { v.adjacencies.add(new Edge(ov, Double.POSITIVE_INFINITY)); edge_added = true; break; } else if (!room.isInterior(v) || !room.isInterior(ov) || room.intersectObstacle(v, ov)) { v.adjacencies.add(new Edge(ov, Double.POSITIVE_INFINITY)); edge_added = true; break; } // //If intersect other polygons else if(obs.intersectObstacle(ov, v)) { v.adjacencies.add(new Edge(ov, Double.POSITIVE_INFINITY)); edge_added = true; break; } } if(edge_added == false) { double dist = Vertex.distance(v, ov); v.adjacencies.add(new Edge(ov, dist)); ov.adjacencies.add(new Edge(v, dist)); } } } } } public void paint(Graphics g) { //draws original obstacles g.setColor(Color.cyan); for (Obstacle o : obstacles) { // draw obstacles List<Vertex> vertices = o.getVertices(); for (int i = 0; i < vertices.size() - 1; i++) { g.drawLine((int) (vertices.get(i).y * 40 + 160), (int) (vertices.get(i).x * 40 + 180), (int) (vertices.get(i + 1).y * 40 + 160), (int) (vertices.get(i + 1).x * 40 + 180)); } g.drawLine((int) (vertices.get(0).y * 40 + 160), (int) (vertices.get(0).x * 40 + 180), (int) (vertices.get(vertices.size() - 1).y * 40 + 160), (int) (vertices.get(vertices.size() - 1).x * 40 + 180)); } //draws grown objects g.setColor(Color.black); for (Obstacle o : grown_obstacles) { // draw obstacles List<Vertex> vertices = o.getVertices(); for (int i = 0; i < vertices.size() - 1; i++) { g.drawLine((int) (vertices.get(i).y * 40 + 160), (int) (vertices.get(i).x * 40 + 180), (int) (vertices.get(i + 1).y * 40 + 160), (int) (vertices.get(i + 1).x * 40 + 180)); } g.drawLine((int) (vertices.get(0).y * 40 + 160), (int) (vertices.get(0).x * 40 + 180), (int) (vertices.get(vertices.size() - 1).y * 40 + 160), (int) (vertices.get(vertices.size() - 1).x * 40 + 180)); } g.setColor(Color.blue); displayAdjacency(g); //draw start and end point g.setColor(Color.red); g.drawArc((int) (start.y * 40 + 155), (int) (start.x * 40 + 175), 10, 10, 0, 360); g.drawArc((int) (goal.y * 40 + 155), (int) (goal.x * 40 + 175), 10, 10, 0, 360); //draw paths g.setColor(Color.green); ArrayList<Vertex> path = getShortestPathTo(goal); for (int i = 0; i < path.size()-1; i++) { Vertex v = path.get(i); Vertex ov = path.get(i+1); g.drawLine((int) (v.y * 40 + 160), (int) (v.x * 40 + 180), (int) (ov.y * 40 + 160), (int) (ov.x * 40 + 180)); } } public void printObstacles(ArrayList<Obstacle> obstacles) { for(Obstacle o: obstacles) { System.out.println(o); } } public void drawAllShortestPathToEachVertex(Graphics g) { for (ArrayList<Vertex> path: paths) { if(paths.indexOf(path) == paths.size()-1) { g.setColor(Color.yellow); } for(int i = 0; i < path.size()-1; i++) { Vertex v = path.get(i); Vertex ov = path.get(i+1); g.drawLine((int) (v.y * 40 + 160), (int) (v.x * 40 + 180), (int) (ov.y * 40 + 160), (int) (ov.x * 40 + 180)); } } } }
Rust
UTF-8
2,961
2.921875
3
[ "BSD-3-Clause" ]
permissive
use super::*; use alloc::sync::{Arc, Weak}; use fs::channel::{Channel, Consumer, Producer}; pub type Endpoint = Arc<Inner>; /// Constructor of two connected Endpoints pub fn end_pair(nonblocking: bool) -> Result<(Endpoint, Endpoint)> { let (pro_a, con_a) = Channel::new(DEFAULT_BUF_SIZE)?.split(); let (pro_b, con_b) = Channel::new(DEFAULT_BUF_SIZE)?.split(); let mut end_a = Arc::new(Inner { addr: RwLock::new(None), reader: con_a, writer: pro_b, peer: Weak::default(), }); let end_b = Arc::new(Inner { addr: RwLock::new(None), reader: con_b, writer: pro_a, peer: Arc::downgrade(&end_a), }); unsafe { Arc::get_mut_unchecked(&mut end_a).peer = Arc::downgrade(&end_b); } end_a.set_nonblocking(nonblocking); end_b.set_nonblocking(nonblocking); Ok((end_a, end_b)) } /// One end of the connected unix socket pub struct Inner { addr: RwLock<Option<Addr>>, reader: Consumer<u8>, writer: Producer<u8>, peer: Weak<Self>, } impl Inner { pub fn addr(&self) -> Option<Addr> { self.addr.read().unwrap().clone() } pub fn set_addr(&self, addr: &Addr) { *self.addr.write().unwrap() = Some(addr.clone()); } pub fn peer_addr(&self) -> Option<Addr> { self.peer.upgrade().map(|end| end.addr().clone()).flatten() } pub fn set_nonblocking(&self, nonblocking: bool) { self.reader.set_nonblocking(nonblocking); self.writer.set_nonblocking(nonblocking); } pub fn nonblocking(&self) -> bool { let cons_nonblocking = self.reader.is_nonblocking(); let prod_nonblocking = self.writer.is_nonblocking(); assert_eq!(cons_nonblocking, prod_nonblocking); cons_nonblocking } pub fn read(&self, buf: &mut [u8]) -> Result<usize> { self.reader.pop_slice(buf) } pub fn write(&self, buf: &[u8]) -> Result<usize> { self.writer.push_slice(buf) } pub fn readv(&self, bufs: &mut [&mut [u8]]) -> Result<usize> { self.reader.pop_slices(bufs) } pub fn writev(&self, bufs: &[&[u8]]) -> Result<usize> { self.writer.push_slices(bufs) } pub fn bytes_to_read(&self) -> usize { self.reader.items_to_consume() } pub fn shutdown(&self, how: HowToShut) -> Result<()> { if !self.is_connected() { return_errno!(ENOTCONN, "The socket is not connected."); } if how.to_shut_read() { self.reader.shutdown() } if how.to_shut_write() { self.writer.shutdown() } Ok(()) } fn is_connected(&self) -> bool { self.peer.upgrade().is_some() } } // TODO: Add SO_SNDBUF and SO_RCVBUF to set/getsockopt to dynamcally change the size. // This value is got from /proc/sys/net/core/rmem_max and wmem_max that are same on linux. pub const DEFAULT_BUF_SIZE: usize = 208 * 1024;
Java
UTF-8
439
3.46875
3
[]
no_license
import java.util.Scanner; public class task3 { public static void main() { int my = 60 * 24 * 365; Scanner input = new Scanner(System.in); System.out.print("Input the number of minutes: "); int min = input.nextInt(); long years =(min / my); int days =(min / 60 / 24) % 365; System.out.println(min + " minutes is approximately " + years + " years and " + days + " days"); } }
Python
UTF-8
860
3.46875
3
[]
no_license
import sqlite3 # conexion y se creara si no existe la BBDD conexion = sqlite3.connect("ejemplo.db") cursor = conexion.cursor() # cursor.execute("CREATE TABLE usuarios (nombre VARCHAR(100), edad INT, email VARCHAR(100))") # cursor.execute( "INSERT INTO usuarios VALUES ('Pablo',34,'myemail@gmail.com')" ) # cursor.execute( "SELECT * FROM usuarios" ) # usu = cursor.fetchone() # recupera el primero en forma de tupla, no se puede modificar # print(usu) # print(usu[0]) """ usuarios = [ ('Ana', 33, 'afrodita@gmail.com'), ('Lucas', 5, 'lucas@gmail.com'), ('Marina', 3, 'marina@gmail.com') ] cursor.executemany( "INSERT INTO usuarios VALUES (?,?,?)", usuarios ) """ cursor.execute( "SELECT * FROM usuarios" ) usuarios = cursor.fetchall() # recupera el primero en forma de tupla, no se puede modificar for u in usuarios: print(u[0], u[1], u[-1]) conexion.commit() conexion.close()
C#
UTF-8
1,028
2.921875
3
[]
no_license
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FadeInOut.cs"> // Copyright (c) Yifei Xu . All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Assets.Scripts.Shared { /// <summary> /// A black over canvas to control fade in/out /// </summary> public class FadeInOut { /// <summary> /// Creates a new instance of the <see cref="FadeInOut"/> class /// </summary> public FadeInOut() { FadeInOut.CurrentInstance = this; } /// <summary> /// Gets the current instance of the <see cref="FadeInOut"/> class /// </summary> public static FadeInOut CurrentInstance { get; private set; } /// Causes the black to appear /// </summary> public void FadeIn() { } } }
Markdown
UTF-8
536
2.578125
3
[]
no_license
# liri-node-app This application takes in the following node commands and prints out to the console as well as to the file log.txt information about the subject searched. **The commands are:** **spotify-this-song** {choose a song name here} **movie-this** {choose a movie name here} **concert-this** {choose a band/artist name to see their next show} **do-what-it-says** (this command reads the command form the random.txt file) Click [Here](/assets/images-vids/liri-walk-through.mov) for a video walk-throuh of the app.
PHP
UTF-8
4,571
3.234375
3
[ "MIT" ]
permissive
<?php require_once('includes.php'); class sudokuTest extends PHPUnit_Framework_TestCase { public function testSudokuConstruct () { $s = new sudoku(); //Ensure data has 9 elements and all are instances of grid for ($i = 1; $i <= 9; $i++) { $test = FALSE; if (isset($s->data[$i])) { $test = TRUE; } $this->assertEquals(TRUE, $test); $test = $s->data[$i] instanceof grid; $this->assertEquals(TRUE, $test); } //Ensure the placementArr has 81 items $this->assertEquals(81, count($s->placementArr)); //Ensure the first item is 1 and the last is 81 $this->assertEquals(1, $s->placementArr[0]); $this->assertEquals(81, $s->placementArr[(count($s->placementArr)-1)]); //Ensure there is no gap in the values $foundGap = FALSE; foreach ($s->placementArr as $i => $v) { if (isset($s->placementArr[$i]) && isset($s->placementArr[$i+1])) { if (abs($s->placementArr[$i] - $s->placementArr[$i+1]) > 1) { $foundGap = TRUE; } } } $this->assertEquals(FALSE, $foundGap); //Ensure we default to a NOT solved state $this->assertEquals(FALSE, $s->solved); } public function testSudokuClone () { $s1 = new sudoku(); $s2 = clone $s1; //Ensure both objects are instances of sudoku and have different hashes $hash1 = spl_object_hash($s1); $hash2 = spl_object_hash($s2); $test = ($hash1 == $hash2)?TRUE:FALSE; $this->assertEquals(FALSE, $test); //Ensure grid count matches $this->assertEquals(count($s1->data), count($s2->data)); //Ensure all the children are cloned too for ($i = 1; $i <= 9; $i++) { //Ensure proper object types $test = ($s1->data[$i] instanceof grid)?TRUE:FALSE; $this->assertEquals(TRUE, $test); $test = ($s2->data[$i] instanceof grid)?TRUE:FALSE; $this->assertEquals(TRUE, $test); //Ensure the objects are different $hash1 = spl_object_hash($s1->data[$i]); $hash2 = spl_object_hash($s2->data[$i]); $test = ($hash1 == $hash2)?TRUE:FALSE; $this->assertEquals(FALSE, $test); } } public function testGetGrid () { $s = new sudoku(); //Ensure direct access and method access return the same thing for ($i = 1; $i <= 9; $i++) { $hash1 = spl_object_hash($s->data[$i]); $hash2 = spl_object_hash($s->getGrid($i)); $test = ($hash1 == $hash2)?TRUE:FALSE; $this->assertEquals(TRUE, $test); } } public function testGenerate () { $s = new sudoku(); //Ensure we return true $this->assertEquals(TRUE, $s->generate()); } public function testGetPrintableGrid () { $s = new sudoku(); //Ensure a grid populated with a known arrangment prints as it should (compare hashes) $knownMd5 = '374b41e354e21a40428be1b93a0f82a5'; for ($i = 1; $i <= 9; $i++) { $g = $s->getGrid($i); $g->setCell($i, $i); } $this->assertEquals($knownMd5, md5($s->getPrintableGrid())); } public function testLookupCoords () { $s = new sudoku(); //Ensure a few lookups are correct $test = md5(serialize([1,1])); $this->assertEquals($test, md5(serialize($s->lookupCoords(1)))); $test = md5(serialize([2,2])); $this->assertEquals($test, md5(serialize($s->lookupCoords(11)))); $test = md5(serialize([3,3])); $this->assertEquals($test, md5(serialize($s->lookupCoords(21)))); $test = md5(serialize([4,4])); $this->assertEquals($test, md5(serialize($s->lookupCoords(31)))); $test = md5(serialize([5,5])); $this->assertEquals($test, md5(serialize($s->lookupCoords(41)))); $test = md5(serialize([6,6])); $this->assertEquals($test, md5(serialize($s->lookupCoords(51)))); $test = md5(serialize([7,7])); $this->assertEquals($test, md5(serialize($s->lookupCoords(61)))); $test = md5(serialize([8,8])); $this->assertEquals($test, md5(serialize($s->lookupCoords(71)))); $test = md5(serialize([9,9])); $this->assertEquals($test, md5(serialize($s->lookupCoords(81)))); } }
Java
UTF-8
4,159
3.671875
4
[]
no_license
//*********************** //NAME: <Dennis Vo> //ID: <A12347682> //LOGIN: <cs12srk> //*********************** package hw7; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * This tester file tests the methods of BSTree.java * @version 1.0 * @author Dennis Vo * @since 2016-05-15 */ public class BSTreeTester { private BSTree<String> stringTree; private BSTree<Integer> numTree; private BSTree<String> myTree; // used for testing In Order Traversal /** * This sets up multiple BSTrees to use for testing. */ @Before public void setUp() { stringTree = new BSTree<String>(); stringTree.insert("Dennis", "Vo"); numTree = new BSTree<Integer>(); numTree.insert(1234, 4321); myTree = new BSTree<String>(); } /** * Catch exception for invalid arg and checks if correct root is given. */ @Test public void testGetRoot() { try { stringTree.getRoot(0); fail("invalid arg"); } catch (IllegalArgumentException e) {} assertEquals("Dennis", stringTree.getRoot(1).getElem()); assertEquals("Vo", stringTree.getRoot(2).getElem()); assertEquals(new Integer(1234), numTree.getRoot(1).getElem()); assertEquals(new Integer(4321), numTree.getRoot(2).getElem()); } /** * Tester for getting size of a tree. Also tests after inserting. */ @Test public void testSize() { assertEquals(1, numTree.getSize()); numTree.insert(5678, 8765); assertEquals(2, numTree.getSize()); } /** * Using this method to catch the NullPointerException. Insert will pretty * much be tested implicitly in the other tests. */ @Test public void testInsert() { try { stringTree.insert(null, "2"); fail("adding null object"); } catch (NullPointerException e) {} } /** * Checks boolean statements for whether or not an element is found in the * trees. */ @Test public void testFindElem() { assertTrue(!stringTree.findElem("name")); assertTrue(stringTree.findElem("Dennis")); assertTrue(numTree.findElem(new Integer(1234))); } /** * This tests a method where you search for the matching element for a * particular element. */ @Test public void testFindMoreInfo() { try { stringTree.findMoreInfo(null); fail("looking for null"); } catch (NullPointerException e) {} try { stringTree.findMoreInfo("name"); fail("arg isn't in any tree"); } catch (IllegalArgumentException e) {} assertEquals("Dennis", stringTree.findMoreInfo("Vo")); assertEquals("Vo", stringTree.findMoreInfo("Dennis")); assertEquals(new Integer(4321), numTree.findMoreInfo(1234)); } /** * This prints out a tree in sorted order. It depends on what choice you * choose as well. Choosing 1 will print the element in the first tree first, * then it's matching element will be printed next. The print out will make * up an array. */ @Test public void testPrint() { String[] array1 = new String[18]; String[] array2 = new String[18]; try { myTree.printToArray(array1,1); fail("tree is empty"); } catch (NullPointerException e) {} try { stringTree.printToArray(array2,0); fail("invalid arg"); } catch (IllegalArgumentException e) {} myTree.insert("Richard","Tran"); myTree.insert("Pooja", "Bhat"); myTree.insert("Zach", "Meyer"); myTree.insert("Marina", "Langlois"); myTree.insert("Thiago", "Marback"); myTree.insert("Siwei", "Xu"); myTree.insert("Annie", "Xiao"); myTree.insert("Don", "Vo"); myTree.insert("Haoran", "Sun"); System.out.println("Printing Choice 1:"); myTree.printToArray(array1, 1); assertEquals("Annie", array1[0]); assertEquals("Xiao", array1[1]); assertEquals("Don", array1[2]); assertEquals("Vo", array1[3]); System.out.println("Printing Choice 2:"); myTree.printToArray(array2, 2); assertEquals("Bhat", array2[0]); assertEquals("Pooja", array2[1]); assertEquals("Langlois", array2[2]); assertEquals("Marina", array2[3]); } }
C#
UTF-8
363
2.78125
3
[]
no_license
var keyHandlers = new Dictionary<Keys, Action>(); keyHandlers.Add(Keys.Back, () => Console.WriteLine("Handler for backspace")); keyHandlers.Add(Keys.Enter, () => { //some other statements, //maybe set some class-level property Console.WriteLine("Handler for enter "); }); keyHandlers.Add(3, NameOfMethodThatMatchesActionDelegateSignature);
C#
UTF-8
7,427
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using RoyT.AStar; using SettlementSimulation.AreaGenerator.Models; using SettlementSimulation.Engine.Enumerators; using SettlementSimulation.Engine.Interfaces; using SettlementSimulation.Engine.Models; namespace SettlementSimulation.Engine.Helpers { public class RoadPointsGenerator : IRoadGenerator { public IEnumerable<Point> Generate(RoadGenerationTwoPoints model) { var grid = new Grid(model.Fields.GetLength(0), model.Fields.GetLength(1), 1.0f); for (int i = 0; i < model.Fields.GetLength(0); i++) { for (int j = 0; j < model.Fields.GetLength(1); j++) { if (!model.Fields[i, j].InSettlement || (model.Fields[i, j].IsBlocked.HasValue && model.Fields[i, j].IsBlocked.Value)) { grid.BlockCell(new Position(i, j)); } } } var positions = grid.GetPath( new Position(model.Start.X, model.Start.Y), new Position(model.End.X, model.End.Y), MovementPatterns.LateralOnly); return positions.Select(p => new Point(p.X, p.Y)); } public IEnumerable<Point> GenerateStraight(RoadGenerationTwoPoints model) { var (minX, maxX) = model.Start.X < model.End.X ? (model.Start.X, model.End.X) : (model.End.X, model.Start.X); var (minY, maxY) = model.Start.Y < model.End.Y ? (model.Start.Y, model.End.Y) : (model.End.Y, model.Start.Y); var positions = new List<Point>(); if (model.Start.X.Equals(model.End.X)) { for (int i = minY; i <= maxY; i++) { positions.Add(new Point(model.Start.X, i)); } } else { for (int i = minX; i <= maxX; i++) { positions.Add(new Point(i, model.Start.Y)); } } var toRemove = positions .OrderByDescending(p => p.DistanceTo(model.Start)) .TakeWhile(s => !model.Fields[s.X, s.Y].InSettlement || (model.Fields[s.X, s.Y].IsBlocked.HasValue && model.Fields[s.X, s.Y].IsBlocked.Value)) .ToList(); toRemove.ForEach(r => positions.Remove(r)); return positions; } public IEnumerable<Point> GenerateAttached(RoadGenerationAttached model) { var roads = new List<IRoad>(model.Roads); var possiblePositions = model.Road .GetPossibleRoadPositions(new PossibleRoadPositions(roads) { MinDistanceBetweenRoads = model.MinDistanceBetweenRoads }); possiblePositions.RemoveAll(p => p.X <= 0 || p.Y < 0 || p.X >= model.Fields.GetLength(0) || p.Y >= model.Fields.GetLength(1)); possiblePositions.RemoveAll(p => model.Fields[p.X, p.Y].DistanceToMainRoad < 10);//to remove possibility of adjacent roads if (!possiblePositions.Any()) return new List<Point>(); Point roadStart = possiblePositions[RandomProvider.Next(possiblePositions.Count)]; var minRoadLength = model.MinRoadLength; var maxRoadLength = model.MaxRoadLength; var roadLength = RandomProvider.Next(minRoadLength, maxRoadLength); var segment = model.Road.Segments.Single(s => s.Position.X == roadStart.X || s.Position.Y == roadStart.Y); Point roadEnd; Direction direction; if (segment.Position.X.Equals(roadStart.X))//vertical road { if (segment.Position.Y > roadStart.Y) { roadEnd = new Point(segment.Position.X, roadStart.Y - roadLength); direction = Direction.Down; } else { roadEnd = new Point(segment.Position.X, roadStart.Y + roadLength); direction = Direction.Up; } if (roadEnd.Y < 0) roadEnd.Y = 0; if (roadEnd.Y >= model.Fields.GetLength(1)) roadEnd.Y = model.Fields.GetLength(1) - 1; } else//horizontal road { if (segment.Position.X <= roadStart.X) { roadEnd = new Point(segment.Position.X + roadLength, roadStart.Y); direction = Direction.Right; } else { roadEnd = new Point(segment.Position.X - roadLength, roadStart.Y); direction = Direction.Left; } if (roadEnd.X < 0) roadEnd.X = 0; if (roadEnd.X >= model.Fields.GetLength(0)) roadEnd.X = model.Fields.GetLength(0) - 1; } var roadPoints = this.GenerateStraight(new RoadGenerationTwoPoints() { Start = roadStart, End = roadEnd, Fields = model.Fields }).ToList(); var intersectPoints = roads .SelectMany(r => r.Segments.Select(s => s.Position)) .Intersect(roadPoints) .ToList(); if (!intersectPoints.Any()) return roadPoints; Point? selectedPoint = null; switch (direction) { case Direction.Up: { selectedPoint = intersectPoints .OrderBy(p => p.Y).Cast<Point?>().FirstOrDefault(p => p.Value.DistanceTo(roadStart) >= minRoadLength); break; } case Direction.Down: { selectedPoint = intersectPoints .OrderByDescending(p => p.Y).Cast<Point?>().FirstOrDefault(p => p.Value.DistanceTo(roadStart) >= minRoadLength); break; } case Direction.Right: { selectedPoint = intersectPoints .OrderBy(p => p.X).Cast<Point?>().FirstOrDefault(p => p.Value.DistanceTo(roadStart) >= minRoadLength); break; } case Direction.Left: { selectedPoint = intersectPoints .OrderByDescending(p => p.X).Cast<Point?>().FirstOrDefault(p => p.Value.DistanceTo(roadStart) >= minRoadLength); break; } } if (!selectedPoint.HasValue) return new List<Point>(); roadPoints = roadPoints.Take(roadPoints.IndexOf(selectedPoint.Value)).ToList(); return roadPoints; } } }
Markdown
UTF-8
5,705
3.515625
4
[]
no_license
# Linear Methods ## Principal Component Analysis \(PCA\) A way to linearly transform a set of d-dimensional vector $$x\_1, x\_2, ..., x\_n$$ into another set of m-dimensional vectors The main idea is that high information corresponds to high variance, the direction of max variance is parallel to the eigenvector, corresponding to the largest eigenvalue of the covariance matrix of the sample matrix A. Let $$R = A^TA$$ be the covariance matrix of $$A$$ where A is normalized by substracting mean, R is symmetric positive definite it eigenvlues are real and positive. Now we apply an orthogonal transformation to R to diagonalize it: $$ \begin{equation} CRC^T = \Lambda_d \end{equation} $$ The sorted eigenvalues of R is $$\lambda\_1 \ge \lambda\_2...\ge \lambda\_d \ge 0$$ _Note:_ we can choose $$m$$ by $$ \begin{equation} r_m = \frac{\sum_{i=1}^m \lambda_i }{\sum_{i=1}^d \lambda_i} \ge \tau \end{equation} $$ e.g. choosing $$\tau = 0.95$$ will ensures that 95% of the variance is retained in the new space. _Note:_ Covariance matrix $$R = A^TA$$ is $$d\times d$$ matrix which make the computation too complex, we can use singular value decomposition instead. ### Singular Value Decomposition The matrix A can be decomposed using SVD $$A\_{n\times d} = USV^T$$ where * U is a $$n\times d$$ matrix of orthonomal columns $$U^TU = I$$ * V is a $$n\times d$$ matrix of orthonomal columns $$V^TV = I$$ * S is a $$d\times d$$ diagonal matrix of singular values SVD can be used to obtain PCA, Now $$R = A^TA = VS^2V^T$$ * PCA is _optimal_ in the sense of minimize sum of square of errors. It mainly rotates the coordinates to find new axes that have the max variance. * The PCA may not be the best for discriminating between classes. PCA认为一个随机信号最有用的信息体包含在方差里,为此我们需要找到一个方向 $$w\_{1}$$,使得随机信号x在该方向上的投影$w\_1^T x$的方差最大化 通过PCA,我们可以得到一列不相关的随机变量,至于这些随机变量是不是真的有意义,那必须根据具体情况具体分析。最常见的例子是,如果x的各分量的单位(量纲)不同,那么一般不能直接套用PCA。比如,若x的几个分量分别代表某国GDP, 人口,失业率,政府清廉指数,这些分量的单位全都不同,而且可以自行随意选取:GDP的单位可以是美元或者日元;人口单位可以是人或者千人或者百万人;失业率可以是百分比或者千分比,等等。对同一个对象(如GDP)选用不同的单位将会改变其数值,从而改变PCA的结果;而依赖“单位选择”的结果显然是没有意义的。 量纲对PCA影响比较大,数据最好应当Normalization. ## Independent Component Analysis \(ICA\) PCA uses 2nd order stats \(mean and variance\) Linear Projection methods can use higher order stats so they can be used for non-Gaussian distributed data: e.g. ICA ICA was proposed for blind source separation of signals, it finds projections that are independent but may not be orthogonal. 设有 d 个独立的标量信号源发出信号,其在时刻t发出的声音可表示为 $$s_t=\(s_{1t},s_{2t},...,s_{dt}\)$$ 。同样地,有 d 个观测器在进行采样,其在时刻 t 记录的信号可表示为:$$x\_t \in R^d$$ 。认为二者满足下式,其中矩阵 A 被称为mixing matrix,反映信道衰减参数: $$ \begin{equation} x_t = As_t \end{equation} $$ 显然,有多少个采样时刻,就可以理解为有多少个样本;而信号源的个数可以理解为特征的维数。ICA的目标就是从 x 中提取出 d 个独立成分,也就是找到矩阵unmixing matrix $$W = A^{-1}$$ Typically, ICA is not used for reducing dimensionality but for separating superimposed signals. Since the ICA model does not include a noise term, for the model to be correct, **whitening must be applied**. This can be done internally using the whiten argument or manually using one of the PCA variants. * Projection pursuit uses a measure of interestingness of a projection * Data is reduced by removing componets along the projection of Gaussian distribution \(去噪声\) * Extract signal is as non-Gaussian as possible, so we can maximize the negative entropy \(Gaussian is the maximum entropy distribution\) ## Linear Descriminant Analysis \(LDA\), Supervised If we know the labels of the data \(classes\) we can use discriminant analysis. The intuition is maximize the between-class scatter while holding fixed within-class scatter. ### Fisher Linear Discriminant \(2-Class LDA\) FLD is a special case of LDA when consider the 2 class problem, we have n samples x each of d dimensions divided into 2 classes, where C1 has n1 samples, C2 has n2 samples. We want to project these onto a line w such that the projected n points y are divided into 2 classes $$y = w^Tx$$, have a projection that separates the projected points into 2 classes. ![](../.gitbook/assets/lda.png) ### Generalization of FLD to K classes Given K classes, we find a projection into \(K-1\) dimensional subspace, we the problem reduces to find a $$\(K-1\) \times d$$ projection matrix such that the projected sample poins are well separated $$y = W^Tx$$ ![PCA vs LDA](../.gitbook/assets/pcavslda.png) 当样本数量远小于样本的特征维数,样本与样本之间的距离变大使得距离度量失效,使LDA算法中的类内、类间离散度矩阵奇异,不能得到最优的投影方向,在人脸识别领域中表现得尤为突出 * LDA不适合对非高斯分布的样本进行降维 * LDA在样本分类信息依赖方差而不是均值时,效果不好 * LDA可能过度拟合数据
Java
UTF-8
580
1.71875
2
[]
no_license
package com.github.yuanluoji.mbye.modules.goods; import com.github.yuanluoji.mbye.support.AbstractEntity; import lombok.Data; import org.springframework.data.relational.core.mapping.Table; /** * Copyright (c) 2020. All Rights Reserved. * * @author yuanluoji * @Description TODO * @date 2020/10/16 */ @Data @Table("goods_basic") public class GoodsBasic extends AbstractEntity { private String code; private String barcode; private String shortName; private String photos; private String properties; private String unit; private Integer state; }
Markdown
UTF-8
3,825
3.125
3
[]
no_license
@title New in NetNewsWire 6: iCloud Syncing @pubDate 2021-03-17 17:22:50 -0700 @modDate 2021-03-17 17:24:43 -0700 We’ve added — in addition to support for a bunch of online RSS systems — iCloud syncing in NetNewsWire 6. (Latest beta [6.0b3 is recommended](https://nnw.ranchero.com/2021/03/16/netnewswire-b-for.html) at this writing.) This is great for people who use only NetNewsWire for reading feeds — it means you don’t need an additional service or login aside from iCloud itself, which you’re almost certainly already using. Here are some things to know… #### It Reads Feeds Directly An iCloud sync account is like an On My Mac account in that it reads feeds directly from the sources instead of going through a separate RSS system such as Feedbin or Feedly. Many people prefer this, for privacy reasons — it means their feeds list isn’t stored on some RSS syncing system. But some people prefer — also for privacy reasons — *not* to read feeds directly: they like having a system that goes directly to the sources. This way the sources don’t see their requests. Consider your own preference when choosing to use iCloud sync or not. Another issue with this model: you could miss articles in fast-moving feeds. (This is true for both iCloud and On My Mac accounts.) Imagine a feed that updates a hundred times a day. Say you take a Monday off and don’t launch NetNewsWire on any device. By Tuesday, when you launch NetNewsWire, some of the articles from Monday have already fallen off the feed. You’ll never see those articles. If you used an online system you would not miss those, because online systems never take a day off. #### It Works with NetNewsWire Only Other RSS readers include iCloud syncing. But you can’t sync those apps with NetNewsWire via iCloud — Apple’s CloudKit doesn’t allow for that. Each app gets its own storage, and other apps can’t see that storage. (Which makes sense.) If you want to use NetNewsWire on one machine and another app on another, you’ll need to choose an RSS syncing system that both apps support. (Which shouldn’t be difficult.) #### NetNewsWire Supports Multiple Accounts This is not new in NetNewsWire 6, but it’s worth pointing out: you can have an iCloud sync account *and* (for instance) a Feedbin account. NetNewsWire is designed for this, just as Mail is designed for multiple email accounts. Being able to choose which feeds are synced where is powerful. But do note that you can have only one iCloud account in NetNewsWire. (Because of how iCloud works.) #### It May Be Slow at First NetNewsWire itself is very fast. But syncing happens at the speed of iCloud — and iCloud sometimes throttles the app: it tells NetNewsWire to back off and try again later. This can be especially noticeable when you’re just starting off with iCloud in NetNewsWire, or whenever you add a big number of feeds, because there will be a ton of data to upload. So: be patient right at first and whenever you’re adding a bunch of feeds to your iCloud account. #### We’re Shipping the Mac App Before the iOS App This feature will come to NetNewsWire for iOS too, of course. Our plan is to ship NetNewsWire 6 for Mac first, and then start TestFlight builds for the iOS app, and then ship NetNewsWire 6 for iOS. The good news: the iCloud sync code is shared between the two apps, which means it’s already getting a thorough test. You might ask why we’re not shipping Mac and iOS at the same time. Our wonderful, remarkable team of volunteers — working during their spare time *during a pandemic and multiple other crises* — could have handled shipping both at the same time. But splitting it up this way is my call — it’s easier for me personally to manage, and I ask for your understanding. Thanks!
Shell
UTF-8
2,696
3.4375
3
[]
no_license
#!/bin/sh -e set -e #set -x if [ -f /usr/share/debconf/confmodule ]; then . /usr/share/debconf/confmodule fi if [ -f /usr/share/dbconfig-common/dpkg/postrm.mysql ]; then . /usr/share/dbconfig-common/dpkg/postrm.mysql dbc_go obs-api $@ fi pathfind() { OLDIFS="$IFS" IFS=: for p in $PATH; do if [ -x "$p/$*" ]; then IFS="$OLDIFS" return 0 fi done IFS="$OLDIFS" return 1 } reload_apache() { if apache2ctl configtest 2>/dev/null; then if `pathfind defoma-font`; then invoke-rc.d apache2 $1 3>/dev/null || true else /etc/init.d/apache2 $1 3>/dev/null || true fi else echo "Your Apache 2 configuration is broken, so we're not restarting it for you." fi } if [ "$1" = "purge" ]; then # ucf follows the symlink under /etc #rm -f /etc/obs/api/config/database.yml if which ucf >/dev/null 2>&1; then ucf --purge /etc/obs/api/config/database.yml fi rm -rf /etc/obs/api rm -rf /usr/share/obs/api rm -rf /usr/share/obs/overview rm -rf /var/cache/obs # Remove log files rm -f /var/log/obs/apache_access_log* rm -f /var/log/obs/apache_error_log* rm -f /var/log/obs/access.log* rm -f /var/log/obs/backend_access.log* rm -f /var/log/obs/db_setup.log* rm -f /var/log/obs/delayed_job.log* rm -f /var/log/obs/error.log* rm -f /var/log/obs/lastevents.access.log* rm -f /var/log/obs/production.log* rm -f /var/log/obs/production.searchd.log* rm -f /var/log/obs/production.searchd.query.log* rm -f /var/log/obs/production.sphinx.pid rm -f /var/log/obs/clockworkd.clock.output* rmdir /var/log/obs 2> /dev/null || true # Test whether a2dissite is available (and thus also apache2ctl). if `pathfind a2dissite`; then # Disable the obs site if not already disabled a2dissite obs.conf > /dev/null || true fi # Delete obsapi user and group deluser --system --quiet obsapi || true delgroup --system --quiet obsapi || true # Restart Apache to really unload obs.conf reload_apache restart fi # Automatically added by dh_installinit/11.4.1 if [ "$1" = "purge" ] ; then update-rc.d obsapidelayed remove >/dev/null fi # End automatically added section # Automatically added by dh_installdebconf/11.4.1 if [ "$1" = purge ] && [ -e /usr/share/debconf/confmodule ]; then . /usr/share/debconf/confmodule db_purge fi # End automatically added section # Automatically added by dh_installdebconf/11.4.1 if [ "$1" = purge ] && [ -e /usr/share/debconf/confmodule ]; then . /usr/share/debconf/confmodule db_purge fi # End automatically added section
Java
UTF-8
1,266
2.96875
3
[]
no_license
package battleships.domain; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class ShipTest { Ship ship; @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { ship = new Ship(); } @After public void tearDown() { } @Test public void setTypeWorks(){ ship.setShipType(ShipType.CARRIER); assertEquals(ShipType.CARRIER, ship.getShipType()); } @Test public void constructorWorks(){ ship = new Ship(ShipType.DESTROYER, 1); assertEquals(ShipType.DESTROYER, ship.getShipType()); } @Test public void getSizeWorks(){ ship.setShipType(ShipType.CRUISER); int size = ship.getShipType().getSize(); assertEquals(3, size); } @Test public void setOwnerWorks(){ ship.setOwner(1); assertEquals(1, ship.getOwner()); } @Test public void lengthIsCorrect(){ ship.setShipType(ShipType.CARRIER); assertEquals(5, ship.length()); } }
PHP
UTF-8
338
3.28125
3
[]
no_license
<?php $t = 5; if ($t == 1) { echo 1; } elseif ($t == 2) { echo 2; } elseif ($t == 3) { echo 3; } else { echo 'undefined'; } echo '<br>'; $t = 2; switch ($t) { case 1: echo 1; break; case 2: echo 2; break; case 3: echo 3; break; default: echo 4; }
Java
UTF-8
331
2.078125
2
[]
no_license
package com.uday.learning.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.FORBIDDEN) public class NotAuthorizedException extends RuntimeException { public NotAuthorizedException(String msg) { super(msg); } }
C#
UTF-8
3,430
2.734375
3
[ "MIT" ]
permissive
using System; using System.Collections; using System.Collections.Generic; namespace CommandLine.Options { public class OptionValueCollection : IList, IList<string> { private readonly List<string> values = new List<string> (); private readonly OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized => (values as ICollection).IsSynchronized; object ICollection.SyncRoot => (values as ICollection).SyncRoot; #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count => values.Count; public bool IsReadOnly => false; #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize => false; object IList.this [int index] { get => this [index]; set => (values as IList)[index] = value; } #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException (nameof(index)); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set => values [index] = value; } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } }
Markdown
UTF-8
22,797
2.6875
3
[]
no_license
# Opinion Poll by Research Affairs for ÖSTERREICH, 16–21 August 2019 <p align="center"><a href="#voting-intentions">Voting Intentions</a> | <a href="#seats">Seats</a> | <a href="#coalitions">Coalitions</a> | <a href="#technical-information">Technical Information</a></p> ## Voting Intentions ![Graph with voting intentions not yet produced](2019-08-21-ResearchAffairs.png "Voting Intentions") ### Confidence Intervals | Party | Last Result | Poll Result | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:-----:|:-----------:|:-----------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | Österreichische Volkspartei | 31.5% | 35.0% | 32.4–37.8% |31.7–38.6% |31.0–39.3% |29.8–40.7% | | Sozialdemokratische Partei Österreichs | 26.9% | 21.0% | 18.8–23.5% |18.2–24.2% |17.7–24.8% |16.7–26.0% | | Freiheitliche Partei Österreichs | 26.0% | 19.0% | 16.9–21.4% |16.3–22.1% |15.8–22.7% |14.9–23.9% | | Die Grünen–Die Grüne Alternative | 3.8% | 11.1% | 9.5–13.1% |9.0–13.6% |8.6–14.1% |7.9–15.1% | | NEOS–Das Neue Österreich und Liberales Forum | 5.3% | 7.9% | 6.6–9.7% |6.2–10.2% |5.9–10.6% |5.3–11.5% | | JETZT–Liste Pilz | 4.4% | 2.0% | 1.4–3.0% |1.2–3.3% |1.1–3.6% |0.9–4.2% | *Note:* The poll result column reflects the actual value used in the calculations. Published results may vary slightly, and in addition be rounded to fewer digits. ## Seats ![Graph with seats not yet produced](2019-08-21-ResearchAffairs-seats.png "Seats") ![Graph with seating plan not yet produced](2019-08-21-ResearchAffairs-seating-plan.png "Seating Plan") ### Confidence Intervals | Party | Last Result | Median | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:-----:|:-----------:|:------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | <a href="#österreichische-volkspartei">Österreichische Volkspartei</a> | 62 | 67 | 61–72 |60–74 |58–75 |56–78 | | <a href="#sozialdemokratische-partei-österreichs">Sozialdemokratische Partei Österreichs</a> | 52 | 40 | 35–45 |34–46 |33–47 |31–50 | | <a href="#freiheitliche-partei-österreichs">Freiheitliche Partei Österreichs</a> | 51 | 36 | 32–40 |31–42 |30–43 |28–45 | | <a href="#die-grünen–die-grüne-alternative">Die Grünen–Die Grüne Alternative</a> | 0 | 21 | 18–24 |17–26 |16–27 |14–28 | | <a href="#neos–das-neue-österreich-und-liberales-forum">NEOS–Das Neue Österreich und Liberales Forum</a> | 10 | 15 | 12–18 |11–19 |11–20 |10–22 | | <a href="#jetzt–liste-pilz">JETZT–Liste Pilz</a> | 8 | 0 | 0 |0 |0 |0–7 | ### Österreichische Volkspartei *For a full overview of the results for this party, see the [Österreichische Volkspartei](party-österreichischevolkspartei.html) page.* ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-seats-pmf-österreichischevolkspartei.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 53 | 0% | 100% | | | 54 | 0.1% | 99.9% | | | 55 | 0.2% | 99.8% | | | 56 | 0.4% | 99.6% | | | 57 | 0.7% | 99.3% | | | 58 | 1.2% | 98.5% | | | 59 | 2% | 97% | | | 60 | 3% | 95% | | | 61 | 4% | 93% | | | 62 | 5% | 89% | Last Result | | 63 | 7% | 83% | | | 64 | 8% | 77% | | | 65 | 9% | 69% | | | 66 | 10% | 60% | | | 67 | 8% | 50% | Median | | 68 | 9% | 42% | | | 69 | 8% | 33% | | | 70 | 7% | 25% | | | 71 | 6% | 19% | | | 72 | 4% | 13% | | | 73 | 3% | 9% | | | 74 | 2% | 6% | | | 75 | 1.5% | 4% | | | 76 | 0.9% | 2% | | | 77 | 0.6% | 1.2% | | | 78 | 0.3% | 0.7% | | | 79 | 0.2% | 0.3% | | | 80 | 0.1% | 0.2% | | | 81 | 0% | 0.1% | | | 82 | 0% | 0% | | ### Sozialdemokratische Partei Österreichs *For a full overview of the results for this party, see the [Sozialdemokratische Partei Österreichs](party-sozialdemokratischeparteiösterreichs.html) page.* ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-seats-pmf-sozialdemokratischeparteiösterreichs.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 29 | 0.1% | 100% | | | 30 | 0.2% | 99.9% | | | 31 | 0.4% | 99.7% | | | 32 | 0.8% | 99.3% | | | 33 | 2% | 98.5% | | | 34 | 3% | 97% | | | 35 | 5% | 94% | | | 36 | 6% | 89% | | | 37 | 8% | 82% | | | 38 | 10% | 74% | | | 39 | 11% | 65% | | | 40 | 11% | 53% | Median | | 41 | 10% | 42% | | | 42 | 9% | 32% | | | 43 | 8% | 23% | | | 44 | 5% | 15% | | | 45 | 4% | 10% | | | 46 | 2% | 6% | | | 47 | 2% | 4% | | | 48 | 1.0% | 2% | | | 49 | 0.5% | 1.0% | | | 50 | 0.3% | 0.5% | | | 51 | 0.1% | 0.2% | | | 52 | 0.1% | 0.1% | Last Result | | 53 | 0% | 0% | | ### Freiheitliche Partei Österreichs *For a full overview of the results for this party, see the [Freiheitliche Partei Österreichs](party-freiheitlicheparteiösterreichs.html) page.* ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-seats-pmf-freiheitlicheparteiösterreichs.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 26 | 0.1% | 100% | | | 27 | 0.2% | 99.9% | | | 28 | 0.6% | 99.6% | | | 29 | 1.3% | 99.0% | | | 30 | 2% | 98% | | | 31 | 4% | 95% | | | 32 | 6% | 91% | | | 33 | 8% | 85% | | | 34 | 10% | 77% | | | 35 | 11% | 67% | | | 36 | 12% | 55% | Median | | 37 | 10% | 44% | | | 38 | 10% | 33% | | | 39 | 8% | 23% | | | 40 | 6% | 16% | | | 41 | 4% | 10% | | | 42 | 2% | 6% | | | 43 | 2% | 4% | | | 44 | 0.9% | 2% | | | 45 | 0.5% | 1.0% | | | 46 | 0.2% | 0.4% | | | 47 | 0.1% | 0.2% | | | 48 | 0.1% | 0.1% | | | 49 | 0% | 0% | | | 50 | 0% | 0% | | | 51 | 0% | 0% | Last Result | ### Die Grünen–Die Grüne Alternative *For a full overview of the results for this party, see the [Die Grünen–Die Grüne Alternative](party-diegrünen–diegrünealternative.html) page.* ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-seats-pmf-diegrünen–diegrünealternative.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0% | 100% | | | 6 | 0% | 100% | | | 7 | 0% | 100% | | | 8 | 0% | 100% | | | 9 | 0% | 100% | | | 10 | 0% | 100% | | | 11 | 0% | 100% | | | 12 | 0% | 100% | | | 13 | 0.1% | 100% | | | 14 | 0.4% | 99.9% | | | 15 | 1.0% | 99.5% | | | 16 | 3% | 98.5% | | | 17 | 5% | 96% | | | 18 | 9% | 91% | | | 19 | 12% | 82% | | | 20 | 15% | 70% | | | 21 | 15% | 55% | Median | | 22 | 13% | 40% | | | 23 | 10% | 28% | | | 24 | 8% | 18% | | | 25 | 4% | 10% | | | 26 | 3% | 6% | | | 27 | 1.2% | 3% | | | 28 | 0.8% | 1.3% | | | 29 | 0.2% | 0.5% | | | 30 | 0.2% | 0.3% | | | 31 | 0% | 0.1% | | | 32 | 0% | 0% | | ### NEOS–Das Neue Österreich und Liberales Forum *For a full overview of the results for this party, see the [NEOS–Das Neue Österreich und Liberales Forum](party-neos–dasneueösterreichundliberalesforum.html) page.* ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-seats-pmf-neos–dasneueösterreichundliberalesforum.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 8 | 0.1% | 100% | | | 9 | 0.4% | 99.9% | | | 10 | 2% | 99.5% | Last Result | | 11 | 4% | 98% | | | 12 | 8% | 94% | | | 13 | 13% | 86% | | | 14 | 16% | 72% | | | 15 | 17% | 57% | Median | | 16 | 15% | 39% | | | 17 | 10% | 24% | | | 18 | 7% | 14% | | | 19 | 3% | 7% | | | 20 | 2% | 3% | | | 21 | 0.9% | 1.5% | | | 22 | 0.4% | 0.6% | | | 23 | 0.1% | 0.2% | | | 24 | 0% | 0.1% | | | 25 | 0% | 0% | | ### JETZT–Liste Pilz *For a full overview of the results for this party, see the [JETZT–Liste Pilz](party-jetzt–listepilz.html) page.* ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-seats-pmf-jetzt–listepilz.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 99.2% | 100% | Median | | 1 | 0% | 0.8% | | | 2 | 0% | 0.8% | | | 3 | 0% | 0.8% | | | 4 | 0% | 0.8% | | | 5 | 0% | 0.8% | | | 6 | 0% | 0.8% | | | 7 | 0.3% | 0.8% | | | 8 | 0.4% | 0.5% | Last Result | | 9 | 0.1% | 0.1% | | | 10 | 0% | 0% | | ## Coalitions ![Graph with coalitions seats not yet produced](2019-08-21-ResearchAffairs-coalitions-seats.png "Coalitions Seats") ### Confidence Intervals | Coalition | Last Result | Median | Majority? | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:---------:|:-----------:|:------:|:---------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | Österreichische Volkspartei – Sozialdemokratische Partei Österreichs | 114 | 106 | 99.9% | 100–113 | 99–114 | 97–116 | 94–119 | | Österreichische Volkspartei – Die Grünen–Die Grüne Alternative – NEOS–Das Neue Österreich und Liberales Forum | 72 | 103 | 99.2% | 96–109 | 95–111 | 93–112 | 91–115 | | Österreichische Volkspartei – Freiheitliche Partei Österreichs | 113 | 103 | 99.2% | 96–109 | 95–111 | 93–112 | 91–115 | | Österreichische Volkspartei – Die Grünen–Die Grüne Alternative | 62 | 88 | 20% | 82–94 | 80–95 | 79–97 | 76–100 | | Österreichische Volkspartei – NEOS–Das Neue Österreich und Liberales Forum | 72 | 82 | 2% | 76–87 | 74–89 | 73–91 | 70–93 | | Sozialdemokratische Partei Österreichs – Die Grünen–Die Grüne Alternative – NEOS–Das Neue Österreich und Liberales Forum | 62 | 76 | 0% | 70–82 | 68–83 | 67–85 | 65–88 | | Sozialdemokratische Partei Österreichs – Freiheitliche Partei Österreichs | 103 | 76 | 0% | 70–82 | 69–84 | 67–85 | 65–87 | | Österreichische Volkspartei | 62 | 67 | 0% | 61–72 | 60–74 | 58–75 | 56–78 | | Sozialdemokratische Partei Österreichs – Die Grünen–Die Grüne Alternative | 52 | 61 | 0% | 56–66 | 54–68 | 53–69 | 50–72 | | Sozialdemokratische Partei Österreichs | 52 | 40 | 0% | 35–45 | 34–46 | 33–47 | 31–50 | ### Österreichische Volkspartei – Sozialdemokratische Partei Österreichs ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-övp–spö.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 91 | 0% | 100% | | | 92 | 0.1% | 99.9% | Majority | | 93 | 0.1% | 99.9% | | | 94 | 0.3% | 99.7% | | | 95 | 0.4% | 99.5% | | | 96 | 0.7% | 99.0% | | | 97 | 1.2% | 98% | | | 98 | 2% | 97% | | | 99 | 2% | 95% | | | 100 | 4% | 93% | | | 101 | 4% | 89% | | | 102 | 6% | 85% | | | 103 | 7% | 79% | | | 104 | 7% | 73% | | | 105 | 8% | 66% | | | 106 | 8% | 58% | | | 107 | 8% | 50% | Median | | 108 | 7% | 42% | | | 109 | 7% | 34% | | | 110 | 7% | 27% | | | 111 | 5% | 21% | | | 112 | 4% | 15% | | | 113 | 3% | 11% | | | 114 | 3% | 8% | Last Result | | 115 | 2% | 5% | | | 116 | 1.2% | 3% | | | 117 | 0.8% | 2% | | | 118 | 0.4% | 1.0% | | | 119 | 0.3% | 0.6% | | | 120 | 0.1% | 0.3% | | | 121 | 0.1% | 0.1% | | | 122 | 0% | 0.1% | | | 123 | 0% | 0% | | ### Österreichische Volkspartei – Die Grünen–Die Grüne Alternative – NEOS–Das Neue Österreich und Liberales Forum ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-övp–grüne–neos.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 72 | 0% | 100% | Last Result | | 73 | 0% | 100% | | | 74 | 0% | 100% | | | 75 | 0% | 100% | | | 76 | 0% | 100% | | | 77 | 0% | 100% | | | 78 | 0% | 100% | | | 79 | 0% | 100% | | | 80 | 0% | 100% | | | 81 | 0% | 100% | | | 82 | 0% | 100% | | | 83 | 0% | 100% | | | 84 | 0% | 100% | | | 85 | 0% | 100% | | | 86 | 0% | 100% | | | 87 | 0% | 100% | | | 88 | 0.1% | 99.9% | | | 89 | 0.1% | 99.9% | | | 90 | 0.2% | 99.7% | | | 91 | 0.3% | 99.5% | | | 92 | 0.7% | 99.2% | Majority | | 93 | 1.2% | 98% | | | 94 | 2% | 97% | | | 95 | 2% | 95% | | | 96 | 3% | 93% | | | 97 | 3% | 90% | | | 98 | 5% | 87% | | | 99 | 8% | 81% | | | 100 | 10% | 73% | | | 101 | 6% | 63% | | | 102 | 6% | 57% | | | 103 | 7% | 51% | Median | | 104 | 8% | 45% | | | 105 | 11% | 36% | | | 106 | 7% | 26% | | | 107 | 4% | 19% | | | 108 | 3% | 15% | | | 109 | 3% | 12% | | | 110 | 3% | 9% | | | 111 | 3% | 5% | | | 112 | 1.3% | 3% | | | 113 | 0.6% | 2% | | | 114 | 0.3% | 1.0% | | | 115 | 0.3% | 0.6% | | | 116 | 0.2% | 0.4% | | | 117 | 0.1% | 0.2% | | | 118 | 0% | 0.1% | | | 119 | 0% | 0% | | ### Österreichische Volkspartei – Freiheitliche Partei Österreichs ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-övp–fpö.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 87 | 0% | 100% | | | 88 | 0.1% | 99.9% | | | 89 | 0.1% | 99.9% | | | 90 | 0.2% | 99.8% | | | 91 | 0.4% | 99.5% | | | 92 | 0.7% | 99.2% | Majority | | 93 | 1.1% | 98% | | | 94 | 2% | 97% | | | 95 | 3% | 96% | | | 96 | 3% | 93% | | | 97 | 4% | 90% | | | 98 | 6% | 86% | | | 99 | 6% | 80% | | | 100 | 7% | 75% | | | 101 | 8% | 67% | | | 102 | 9% | 60% | | | 103 | 7% | 50% | Median | | 104 | 8% | 43% | | | 105 | 7% | 35% | | | 106 | 7% | 28% | | | 107 | 6% | 22% | | | 108 | 4% | 16% | | | 109 | 4% | 12% | | | 110 | 3% | 8% | | | 111 | 2% | 5% | | | 112 | 2% | 4% | | | 113 | 0.8% | 2% | Last Result | | 114 | 0.5% | 1.2% | | | 115 | 0.3% | 0.7% | | | 116 | 0.2% | 0.3% | | | 117 | 0.1% | 0.2% | | | 118 | 0% | 0.1% | | | 119 | 0% | 0% | | ### Österreichische Volkspartei – Die Grünen–Die Grüne Alternative ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-övp–grüne.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 62 | 0% | 100% | Last Result | | 63 | 0% | 100% | | | 64 | 0% | 100% | | | 65 | 0% | 100% | | | 66 | 0% | 100% | | | 67 | 0% | 100% | | | 68 | 0% | 100% | | | 69 | 0% | 100% | | | 70 | 0% | 100% | | | 71 | 0% | 100% | | | 72 | 0% | 100% | | | 73 | 0% | 100% | | | 74 | 0.1% | 99.9% | | | 75 | 0.2% | 99.8% | | | 76 | 0.3% | 99.6% | | | 77 | 0.6% | 99.3% | | | 78 | 1.1% | 98.7% | | | 79 | 1.5% | 98% | | | 80 | 3% | 96% | | | 81 | 3% | 94% | | | 82 | 4% | 91% | | | 83 | 5% | 87% | | | 84 | 7% | 81% | | | 85 | 7% | 74% | | | 86 | 8% | 67% | | | 87 | 9% | 59% | | | 88 | 8% | 50% | Median | | 89 | 9% | 43% | | | 90 | 7% | 34% | | | 91 | 7% | 27% | | | 92 | 5% | 20% | Majority | | 93 | 5% | 15% | | | 94 | 3% | 11% | | | 95 | 3% | 8% | | | 96 | 2% | 5% | | | 97 | 1.2% | 3% | | | 98 | 0.7% | 2% | | | 99 | 0.4% | 1.0% | | | 100 | 0.2% | 0.5% | | | 101 | 0.2% | 0.3% | | | 102 | 0.1% | 0.2% | | | 103 | 0% | 0.1% | | | 104 | 0% | 0% | | ### Österreichische Volkspartei – NEOS–Das Neue Österreich und Liberales Forum ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-övp–neos.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 67 | 0% | 100% | | | 68 | 0.1% | 99.9% | | | 69 | 0.1% | 99.8% | | | 70 | 0.3% | 99.7% | | | 71 | 0.6% | 99.4% | | | 72 | 0.9% | 98.8% | Last Result | | 73 | 1.5% | 98% | | | 74 | 2% | 96% | | | 75 | 3% | 94% | | | 76 | 4% | 91% | | | 77 | 5% | 87% | | | 78 | 7% | 82% | | | 79 | 8% | 75% | | | 80 | 8% | 67% | | | 81 | 8% | 59% | | | 82 | 9% | 51% | Median | | 83 | 8% | 42% | | | 84 | 8% | 34% | | | 85 | 6% | 26% | | | 86 | 6% | 20% | | | 87 | 4% | 14% | | | 88 | 3% | 10% | | | 89 | 2% | 7% | | | 90 | 2% | 4% | | | 91 | 1.1% | 3% | | | 92 | 0.7% | 2% | Majority | | 93 | 0.4% | 0.8% | | | 94 | 0.2% | 0.5% | | | 95 | 0.1% | 0.3% | | | 96 | 0.1% | 0.1% | | | 97 | 0% | 0.1% | | | 98 | 0% | 0% | | ### Sozialdemokratische Partei Österreichs – Die Grünen–Die Grüne Alternative – NEOS–Das Neue Österreich und Liberales Forum ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-spö–grüne–neos.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 62 | 0.1% | 100% | Last Result | | 63 | 0.1% | 99.9% | | | 64 | 0.2% | 99.8% | | | 65 | 0.5% | 99.5% | | | 66 | 0.7% | 99.0% | | | 67 | 1.3% | 98% | | | 68 | 2% | 97% | | | 69 | 3% | 95% | | | 70 | 4% | 92% | | | 71 | 5% | 88% | | | 72 | 6% | 83% | | | 73 | 7% | 77% | | | 74 | 10% | 70% | | | 75 | 8% | 60% | | | 76 | 8% | 52% | Median | | 77 | 9% | 43% | | | 78 | 8% | 35% | | | 79 | 6% | 27% | | | 80 | 5% | 21% | | | 81 | 5% | 15% | | | 82 | 3% | 10% | | | 83 | 3% | 7% | | | 84 | 2% | 4% | | | 85 | 1.1% | 3% | | | 86 | 0.8% | 2% | | | 87 | 0.5% | 1.0% | | | 88 | 0.3% | 0.5% | | | 89 | 0.1% | 0.3% | | | 90 | 0.1% | 0.1% | | | 91 | 0% | 0.1% | | | 92 | 0% | 0% | Majority | ### Sozialdemokratische Partei Österreichs – Freiheitliche Partei Österreichs ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-spö–fpö.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 62 | 0.1% | 100% | | | 63 | 0.1% | 99.9% | | | 64 | 0.2% | 99.8% | | | 65 | 0.3% | 99.5% | | | 66 | 0.6% | 99.2% | | | 67 | 1.1% | 98.6% | | | 68 | 2% | 97% | | | 69 | 3% | 95% | | | 70 | 4% | 92% | | | 71 | 4% | 88% | | | 72 | 6% | 84% | | | 73 | 7% | 78% | | | 74 | 10% | 71% | | | 75 | 8% | 61% | | | 76 | 8% | 53% | Median | | 77 | 7% | 45% | | | 78 | 9% | 37% | | | 79 | 7% | 28% | | | 80 | 7% | 21% | | | 81 | 4% | 14% | | | 82 | 2% | 10% | | | 83 | 3% | 8% | | | 84 | 2% | 5% | | | 85 | 1.4% | 3% | | | 86 | 0.9% | 2% | | | 87 | 0.3% | 0.8% | | | 88 | 0.2% | 0.5% | | | 89 | 0.1% | 0.3% | | | 90 | 0.1% | 0.2% | | | 91 | 0% | 0.1% | | | 92 | 0% | 0% | Majority | | 93 | 0% | 0% | | | 94 | 0% | 0% | | | 95 | 0% | 0% | | | 96 | 0% | 0% | | | 97 | 0% | 0% | | | 98 | 0% | 0% | | | 99 | 0% | 0% | | | 100 | 0% | 0% | | | 101 | 0% | 0% | | | 102 | 0% | 0% | | | 103 | 0% | 0% | Last Result | ### Österreichische Volkspartei ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-övp.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 53 | 0% | 100% | | | 54 | 0.1% | 99.9% | | | 55 | 0.2% | 99.8% | | | 56 | 0.4% | 99.6% | | | 57 | 0.7% | 99.3% | | | 58 | 1.2% | 98.5% | | | 59 | 2% | 97% | | | 60 | 3% | 95% | | | 61 | 4% | 93% | | | 62 | 5% | 89% | Last Result | | 63 | 7% | 83% | | | 64 | 8% | 77% | | | 65 | 9% | 69% | | | 66 | 10% | 60% | | | 67 | 8% | 50% | Median | | 68 | 9% | 42% | | | 69 | 8% | 33% | | | 70 | 7% | 25% | | | 71 | 6% | 19% | | | 72 | 4% | 13% | | | 73 | 3% | 9% | | | 74 | 2% | 6% | | | 75 | 1.5% | 4% | | | 76 | 0.9% | 2% | | | 77 | 0.6% | 1.2% | | | 78 | 0.3% | 0.7% | | | 79 | 0.2% | 0.3% | | | 80 | 0.1% | 0.2% | | | 81 | 0% | 0.1% | | | 82 | 0% | 0% | | ### Sozialdemokratische Partei Österreichs – Die Grünen–Die Grüne Alternative ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-spö–grüne.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 48 | 0.1% | 100% | | | 49 | 0.1% | 99.9% | | | 50 | 0.3% | 99.8% | | | 51 | 0.5% | 99.5% | | | 52 | 1.1% | 99.0% | Last Result | | 53 | 1.5% | 98% | | | 54 | 3% | 96% | | | 55 | 3% | 93% | | | 56 | 5% | 90% | | | 57 | 7% | 85% | | | 58 | 7% | 78% | | | 59 | 9% | 71% | | | 60 | 8% | 61% | | | 61 | 10% | 53% | Median | | 62 | 9% | 43% | | | 63 | 8% | 34% | | | 64 | 8% | 26% | | | 65 | 5% | 19% | | | 66 | 5% | 14% | | | 67 | 3% | 9% | | | 68 | 2% | 6% | | | 69 | 2% | 4% | | | 70 | 0.9% | 2% | | | 71 | 0.5% | 1.2% | | | 72 | 0.4% | 0.8% | | | 73 | 0.2% | 0.3% | | | 74 | 0.1% | 0.2% | | | 75 | 0% | 0.1% | | | 76 | 0% | 0% | | ### Sozialdemokratische Partei Österreichs ![Graph with seats probability mass function not yet produced](2019-08-21-ResearchAffairs-coalitions-seats-pmf-spö.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 29 | 0.1% | 100% | | | 30 | 0.2% | 99.9% | | | 31 | 0.4% | 99.7% | | | 32 | 0.8% | 99.3% | | | 33 | 2% | 98.5% | | | 34 | 3% | 97% | | | 35 | 5% | 94% | | | 36 | 6% | 89% | | | 37 | 8% | 82% | | | 38 | 10% | 74% | | | 39 | 11% | 65% | | | 40 | 11% | 53% | Median | | 41 | 10% | 42% | | | 42 | 9% | 32% | | | 43 | 8% | 23% | | | 44 | 5% | 15% | | | 45 | 4% | 10% | | | 46 | 2% | 6% | | | 47 | 2% | 4% | | | 48 | 1.0% | 2% | | | 49 | 0.5% | 1.0% | | | 50 | 0.3% | 0.5% | | | 51 | 0.1% | 0.2% | | | 52 | 0.1% | 0.1% | Last Result | | 53 | 0% | 0% | | ## Technical Information ### Opinion Poll + **Polling firm:** Research Affairs + **Commissioner(s):** ÖSTERREICH + **Fieldwork period:** 16–21 August 2019 ### Calculations + **Sample size:** 505 + **Simulations done:** 1,048,576 + **Error estimate:** 0.93%
Python
UTF-8
313
4.46875
4
[]
no_license
# Listas lista = [] print(type(lista)) print(len(lista)) lista.append(1) lista.append(3) lista.append(5) lista.append([7, 9, 11, 13, 15, 17]) print(lista) new_list = [1, 3, 5, 'Jefferson', 'Luis'] print(new_list) print(len(new_list)) new_list.remove(5) print(new_list) new_list.reverse() print(new_list)
PHP
UTF-8
1,673
2.8125
3
[]
no_license
<?php //\Codeception\Subscriber\Console::beforeStep = function(StepEvent $e) //{ // if (!$this->steps or !$e->getTest() instanceof ScenarioDriven) { // return; // } // $this->output->writeln("* " . $e->getStep()); //}; global $ssI; $ssI = new AcceptanceTester($scenario); /** * This function is to replace PHP's extremely buggy realpath(). * @param string The original path, can be relative etc. * @return string The resolved path, it might not exist. */ function truepath($path){ // whether $path is unix or not $unipath=strlen($path)==0 || $path{0}!='/'; // attempts to detect if path is relative in which case, add cwd if(strpos($path,':')===false && $unipath) $path=getcwd().DIRECTORY_SEPARATOR.$path; // resolve path parts (single dot, double dot and double delimiters) $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path); $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen'); $absolutes = array(); foreach ($parts as $part) { if ('.' == $part) continue; if ('..' == $part) { array_pop($absolutes); } else { $absolutes[] = $part; } } $path=implode(DIRECTORY_SEPARATOR, $absolutes); // resolve any symlinks if(file_exists($path) && linkinfo($path)>0)$path=readlink($path); // put initial separator that could have been lost $path=!$unipath ? '/'.$path : $path; return $path; } $path = truepath( getcwd(). '/../../../../../test' ); if( file_exists( $path . '/test.php' ) ) { require $path . '/test.php'; //} else { // require '../../../../../../test/test.php'; } $ssI->wait(3);
PHP
UTF-8
1,043
2.515625
3
[]
no_license
<?php /**** * Look for users base on name and last_name ****/ require_once("../templates/template.php"); $db = getBD(); $utils = new Utils_datos(); if(isset($_REQUEST["alias"])){ $sql = "SELECT * FROM siq_data WHERE alias = '".$_REQUEST["alias"]."' AND codigoestado='100' "; $data = $db->GetRow($sql); } else { $data = $utils->getDataEntity("data",$_REQUEST["id"]); } $cat = $utils->getDataEntity("categoriaData",$data["categoria"]); if($data["tipo_data"]==1){ include("../datos/".$cat["alias"]."/filtrosClass.php"); $filters = new filtrosClass(); } else { include("../informacion/".$cat["alias"]."/filtrosInfoClass.php"); $filters = new filtrosInfoClass(); } $filtros = array(); $metodo = 'getFiltros'.ucfirst($data["alias"]); if(method_exists($filters,$metodo)){ $filtros = $filters->$metodo(); } $users = array(); forEach($filtros as $key => $value) { $res['label']=$value; $res['value']=$key; array_push($users,$res); } // return the array as json echo json_encode($users); ?>