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
Java
UTF-8
1,382
2.078125
2
[ "BSD-3-Clause" ]
permissive
// // $Id$ package com.threerings.msoy.aggregators; import java.io.IOException; import java.util.Calendar; import java.util.Collections; import com.threerings.panopticon.aggregator.hadoop.Aggregator; import com.threerings.panopticon.aggregator.writable.Keys.LongKey; import com.threerings.panopticon.common.event.EventDataBuilder; import com.threerings.panopticon.eventstore.EventWriter; /** * Before we had buckets, there were subject lines. Before we had subject lines, there were only * mailings. This handles both cases by processing "default" buckets prior to 5/1/9 and "default" * subject lines prior to 4/4/9. This can be removed eventually. */ @Aggregator(output="msoy.RetentionEmailResponse.Old") public class RetentionEmailOld extends RetentionEmail { public RetentionEmailOld () { super(new int[] { 2009, Calendar.MARCH, 1 }, new int[] { 2009, Calendar.APRIL, 30 }, Collections.singletonList("default")); } @Override public void write (EventWriter writer, EventDataBuilder unused, LongKey key) throws IOException { SubjectLineOutputBuilder builder = new SubjectLineOutputBuilder(); builder.build(key, _subjectLines); builder.write(writer); } protected static final String[] _subjectLines = { "nameNewThings", "nameBusyFriends", "whirledFeedAndNewThings", "default"}; }
Markdown
UTF-8
4,991
2.671875
3
[ "Apache-2.0" ]
permissive
**This is not an officially supported Google product.** # Java Function Coverage The project aims to collect production Java function-level coverage with low overhead. ## Source Code Headers Every file containing source code must include copyright and license information. This includes any JS/CSS files that you might be serving out to browsers. (This is to help well-intentioned people avoid accidental copying that doesn't comply with the license.) Apache header: ``` Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` ## Quickstart ### With The Included Examples * Build [funccover agent](#funccover-agent). ```bash $ bazel build //src/main/java/com/funccover:funccover_deploy.jar ``` This should generate the file ```bazel-bin/src/main/java/com/funccover/funccover_deploy.jar``` under the project root. * Build the example [handler](#handler) in the repository. ```bash $ bazel build //src/main/java/example/handler:handler_deploy.jar ``` This should generate the file ```bazel-bin/src/main/java/example/handler/handler_deploy.jar``` under the project root. * Build the example program binary. ```bash $ bazel build //src/main/java/example/program:ExampleProgram ``` This will generate an executable inside ```bazel-bin/src/main/java/example/program/ExampleProgram```. * Run the program with funccover. ```bash $ ./bazel-bin/src/main/java/example/program/ExampleProgram --jvm_flag="-javaagent:bazel-bin/src/main/java/com/funccover/funccover_deploy.jar=handler-jar=bazel-bin/src/main/java/example/handler/handler_deploy.jar,handler-entry=example.handler.Handler" ``` When you run it, it will ask you to enter numbers in range [0-9], then it will call ```f$number``` function for each number you entered. Coverage data will be saved to ```coverage.out```. ### With Customization * Build [funccover agent](#funccover-agent). ```bash $ bazel build //src/main/java/com/funccover:funccover_deploy.jar ``` * Implement and build your [handler](#handler). * Handler program must implement a Runnable class as it's entry pont. * Agent will create a new class loader with given path. * It will load given entry point, Runnable class into the memory, create an instance of it and invoke the run() method. * Path must contain all the dependencies of handler program since they will be needed in runtime. * Please take a look at the examples, [Handler](../master/src/main/java/example/handler/Handler.java), [Simple Handler](../master/src/main/java/example/handler/SimpleHandler.java) * Build your program binary. ```bash $ bazel build //YourProgram ``` * Run your program with funccover. ```bash $ ./YourProgram --jvm_flag="-javaagent:path/to/funccover.jar=[option1]=[value1],[option2]=[value2]" ``` You can also attach funccover agent to jar files. ```bash $ java -javaagent:path/to/agent.jar=[option1]=[value1],[option2]=[value2] -jar YourProgram.jar ``` ### Concepts Java Function Coverage tool consists of 2 parts, funccover agent and a handler. To collect production coverage data you need to have both. #### funccover Agent In general a java agent is just a specially crafted .jar file that utilizes the [Instrumentation API](https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html "Instrumentation API"). Using Instrumentation API, funccover agent instruments bytecodes before JVM loads them into memory. Using instrumentation, we record execution of methods inside a data structure called CoverageMetrics. Agent itself does not upload/write the coverage data. Handler program does. funccover has 4 options. Options must be given in following format: ```bash -javaagent:path/to/funccover.jar=[option1]=[value1],[option2]=[value2]... ``` | Option | Description | | --- | ----------- | | handler-jar | Path to handler's jar file. | | handler-entry | Fully qualified name of the entry class that implements a Runnable (package.name.ClassName).| | includes | A list of class names that should be included in instrumentation. The list entries are separated by a colon (:) and may use wildcard characters (* and ?). Default is *. | excludes | A list of class names that should be excluded from instrumentation. The list entries are separated by a colon (:) and may use wildcard characters (* and ?). | #### Handler Handler is a program that implements Runnable class as entry point. Our agent gets the handler program and its entry class. It loads the program and creates an instance of given entry class.
Markdown
UTF-8
1,035
3.484375
3
[ "MIT" ]
permissive
# Fried Quinoa - **Prep Time:** 15 minutes - **Cook Time:** 25 minutes ## Tools - 2 stovetop burners - 1 medium pot - 1 large frying pan - 1 small frying pan - 1 spatula - 1 knife ## Ingredients - 1 cup quinoa - half an onion - 1.5 teaspoons minced garlic - 1 pepper (any color) - 1 chicken breast - handful cilantro - dash soy sauce - 2 eggs ## Method - Put quinoa in pot, raise water to boil, simmer for 15 minutes. - While boiling quinoa, dice vegetables, mince onion and garlic, and shred chicken. - Heat dash olive oil in large frying pan. Add onion and garlic to pan. Cook for one minute. - Add pepper and chicken. Once chicken is half cooked (white on bottom edges, about 5 minutes), flip over. - After another 3 minutes, move quinoa from the pot to the pan. - Drizzle soy sauce around edge of pan. Mix in over 3 minutes as it cooks. - Add cilantro, salt, and pepper to taste. Reducec to a simmer. - In the small frying pan, fry two eggs sunny side up. - Serve the fried quinoa in 2-4 bowls, and top with the friend egg.
Python
UTF-8
1,098
4.09375
4
[]
no_license
import random ''' Try the same thing, but have the program choose a random word from the dic- tionary, and then ask the user to guess the word. (You might want to limit your- self to words containing two to five letters, to avoid making it too horribly difficult.) Instead of telling the user that they should guess a smaller or larger number, have them choose an earlier or later word in the dict. ''' WORK_DICT = { 1: 'cat', 2: 'dog', 3: 'news', 4: 'head', 5: 'arm', 6: 'rot', } def guessing_game(): number = random.randint(1, 6) print(WORK_DICT) while True: guess = input('Guess word: ') if number > list(WORK_DICT.keys())[list(WORK_DICT.values()).index(guess)]: print(f'Your guess of {guess} is too low!') elif number < list(WORK_DICT.keys())[list(WORK_DICT.values()).index(guess)]: print(f'Your guess of {guess} is too high!') elif number == list(WORK_DICT.keys())[list(WORK_DICT.values()).index(guess)]: print(f'Right! The answer is {guess}') break guessing_game()
Python
UTF-8
338
3.375
3
[ "BSD-3-Clause" ]
permissive
def fill(a, N, i, v, x): if i < 0 or i >= N: return elif a[i] != v: return elif a[i] == x: return else: a[i] = x fill(a, N, i - 1, v, x) fill(a, N, i + 1, v, x) N, i, x = map(int, input().strip().split()) a = list(map(int, input().strip().split())) fill(a, N, i, a[i], x) print(*a)
Python
UTF-8
1,654
3.5625
4
[]
no_license
''' 링크 : https://programmers.co.kr/learn/courses/30/lessons/67256 문제 : 키패드 누르기 ''' def solution(numbers, hand): answer = '' left = 10 # 키패드 *:10, 0:11, #:12로 지정 right = 12 distance = { # value : 키패드 숫자 차이, key : 거리 1 : [1,3], 2 : [2,4,6], 3 : [5,7,9], 4 : [8,10] } for i in numbers : if i in [1,4,7] : # 누를 키패드가 1,4,7인 경우 왼손 사용 answer += 'L' left = i elif i in [3,6,9] : # 누를 키패드가 3,6,9인 경우 오른손 사용 answer += 'R' right = i else : if i==0 : i = 11 l_dist = abs(left-i) # 현재 손위치의 숫자와 누를 키패드 숫자의 차 r_dist = abs(right-i) for key, val in distance.items() : # distance의 value에 해당하는 key 값(거리) 가져옴 if l_dist in val : l_dist = key if r_dist in val : r_dist = key if l_dist == r_dist : # 왼손, 오른손 거리가 같으면 hand로 결정 if hand=='right' : answer += 'R' right = i else : answer += 'L' left = i elif l_dist <= r_dist : # 왼손 거리가 더 짧으면 왼손 사용 answer += 'L' left = i else : # 오른손 거리가 더 짧으면 오른손 사용 answer += 'R' right = i return answer
Shell
UTF-8
3,253
3.609375
4
[]
no_license
#!/bin/bash # Copyright 2020 Datawhere Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the # “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject # to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # completion popup values height=400 width=700 title="Yadle Copy-To-Bucket" function do_copy () { fullpath=$1 # break filename into parts filename="${fullpath##*/}" # Strip longest match of */ from start dir="${fullpath:0:${#fullpath} - ${#filename}}" # Substring from 0 thru pos of filename base="${filename%.[^.]*}" # Strip shortest match of . plus at least one non-dot char from end ext="${filename:${#base} + 1}" # check for file, then copy it if [ -f "${fullpath}" ]; then e=$(cp "${fullpath}" "${bucket}") # send success message #notify-send -t 100 -u normal -i ${icon} "Copied '${base}.${ext}' to '${bucket}'" #echo "OK : '${base}.${ext}'" >> ${file_list} echo "OK : '${fullpath}'" >> ${file_list} else # send failure message #notify-send -t 5000 -u normal -i ${icon} "File not copied, check access to file location." #echo "FAILED: '${base}.${ext}'" >> ${file_list} echo "FAILED: '${fullpath}'" >> ${file_list} fi } # this is the default bucket name basebucket="${HOME}/Desktop/bucket_1" # icon for notify-send messages icon="${HOME}/yadle/plugins/logo.png" # .../bucket.data contains the full path of the current bucket. If not, # then put the default from above in the file. if [ ! -f "${HOME}/yadle/plugins/bucket1.data" ]; then echo "${basebucket}" > "${HOME}/yadle/plugins/bucket1.data"; fi # get the bucket path from the file bucket=$(< ${HOME}/yadle/plugins/bucket1.data) file_list="${HOME}/yadle/plugins/file_list.tmp" echo "The following files were copied to '${bucket}':" > ${file_list} # if bucket does not exist, create it if [ ! -f ${bucket} ]; then mkdir -p "${bucket}" fi # skip command name for ((i=1;i<=$#;i++)) do do_copy "${!i}" done # determine os case $(uname) in Darwin) platform="darwin" ;; Linux) platform="linux" ;; esac if [[ ${platform} == "darwin" ]]; then osascript -e 'display notification "All Selected Files Copied to Bucket" with title "Yadle"' fi if [[ ${platform} == "linux" ]]; then $(zenity --text-info --title=${title} --width=${width} --height=${height} --filename=${file_list}) fi # EOF
Java
UTF-8
1,721
2.21875
2
[]
no_license
package com.framework.admin.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * 页面跳转Controller * * @author sunhan * @since 2017年02月14日 */ @Controller public class WebMvcController extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("admin/index.html"); registry.addViewController("/login").setViewName("login"); } @RequestMapping(value = "/admin/**/*.html", method = RequestMethod.GET) public ModelAndView view(HttpServletRequest request, @RequestParam(required = false) Map<String, Object> param) { String path = getUri(request); if (path.contains(".")) path = path.split("[.]")[0]; ModelAndView modelAndView = new ModelAndView(path); modelAndView.addObject("param", param); return modelAndView; } public String getUri(HttpServletRequest request) { String path = request.getRequestURI(); String content = request.getContextPath(); if (path.startsWith(content)) { path = path.substring(content.length() + 1); } return path; } }
C
UTF-8
492
3.5625
4
[]
no_license
#include <stdio.h> int main(void) { int x[10],y[10],z[10],i; for(i=0;i<10;i++) { printf("DIGITE O %dº NUMERO PARA O VETOR X: ",i+1); scanf("%d",&x[i]); } printf("\n"); for(i=0;i<10;i++) { printf("DIGITE O %dº NUMERO PARA O VETOR Y: ",i+1); scanf("%d",&y[i]); } printf("\n\nSOMA DOS ELEMENTOS DOS VETORES X e Y É: "); for(i=0;i<10;i++) { z[i] = (x[i] + y[i]); printf("%d ",z[i]); } return 0; }
Java
UTF-8
2,829
2.09375
2
[ "Apache-2.0" ]
permissive
package it.prisma.domain.dsl.cloudify.response; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * A POJO representing a generic response from the REST Gateway. This class is a * wrapper for an inner specific response. * * @author elip * * @param <T> */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "status", "message", "messageId", "verbose", "response" }) public class ResponseWrapper<T> implements Serializable { private static final long serialVersionUID = 5743416544105034494L; @JsonProperty("status") private String status; @JsonProperty("message") private String message; @JsonProperty("messageId") private String messageId; @JsonProperty("verbose") private Object verbose; @JsonProperty("response") private T response; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("status") public String getStatus() { return status; } @JsonProperty("status") public void setStatus(String status) { this.status = status; } @JsonProperty("message") public String getMessage() { return message; } @JsonProperty("message") public void setMessage(String message) { this.message = message; } @JsonProperty("messageId") public String getMessageId() { return messageId; } @JsonProperty("messageId") public void setMessageId(String messageId) { this.messageId = messageId; } @JsonProperty("verbose") public Object getVerbose() { return verbose; } @JsonProperty("verbose") public void setVerbose(Object verbose) { this.verbose = verbose; } @JsonProperty("response") public T getResponse() { return response; } @JsonProperty("response") public void setResponse(final T response) { this.response = response; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object other) { return EqualsBuilder.reflectionEquals(this, other); } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
Markdown
UTF-8
552
2.59375
3
[ "MIT" ]
permissive
# Solution ``` # LCS different format class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: if not A or not B: return 0 N1,N2 = len(A),len(B) dp = [[0 for _ in range(N2+1)] for _ in range(N1+1)] for i in range(N1): for j in range(N2): if A[i]==B[j]: dp[i+1][j+1] = dp[i][j]+1 else: dp[i+1][j+1] = max(dp[i+1][j], dp[i][j+1]) return dp[N1][N2] ```
Java
UTF-8
9,639
2.296875
2
[]
no_license
package com.tuniu.abt.intf.entity; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Table(name = "abt_refund_item") public class AbtRefundItem implements Serializable { public static final int STATUS_INIT = 0; public static final int STATUS_OK = 1; public static final int STATUS_FAIL = 2; private static final long serialVersionUID = -4252178096417594008L; /** * 主键 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 退票单号,对应abt_refund_order表id */ @Column(name = "refund_id") private Long refundId; /** * 途牛订单号 */ @Column(name = "order_id") private Long orderId; /** * 出票记录主表id */ @Column(name = "ticket_main_id") private Long ticketMainId; /** * 类型:1=全退 */ @Column(name = "refund_item_type") private Integer refundItemType; /** * 航段信息(出发城市三字码/到达城市三字码) */ private String leg; /** * 乘客fab系统id */ @Column(name = "person_id") private Long personId; /** * abt_pnr_passenger表id */ @Column(name = "pnr_passenger_id") private Long pnrPassengerId; /** * 接口实际操作后的退票费 */ @Column(name = "real_refund_amount") private Float realRefundAmount; /** * 请求的原始退票费用 */ @Column(name = "refund_amount") private Float refundAmount; /** * 请求的手续费 */ @Column(name = "commission_fee") private Float commissionFee; /** * 电子客票票号 */ @Column(name = "ticket_no") private String ticketNo; /** * pnr */ private String pnr; /** * 退票备注 */ private String remark; /** * 状态标识,0=待退票,1=成功,2=失败 */ private Integer status; /** * 添加时间 */ @Column(name = "add_time") private Date addTime; /** * 修改时间 */ @Column(name = "update_time") private Date updateTime; public AbtRefundItem(Long id, Long refundId, Long orderId, Long ticketMainId, Integer refundItemType, String leg, Long personId, Long pnrPassengerId, Float realRefundAmount, Float refundAmount, Float commissionFee, String ticketNo, String pnr, String remark, Integer status, Date addTime, Date updateTime) { this.id = id; this.refundId = refundId; this.orderId = orderId; this.ticketMainId = ticketMainId; this.refundItemType = refundItemType; this.leg = leg; this.personId = personId; this.pnrPassengerId = pnrPassengerId; this.realRefundAmount = realRefundAmount; this.refundAmount = refundAmount; this.commissionFee = commissionFee; this.ticketNo = ticketNo; this.pnr = pnr; this.remark = remark; this.status = status; this.addTime = addTime; this.updateTime = updateTime; } public AbtRefundItem() { super(); } /** * 获取主键 * * @return id - 主键 */ public Long getId() { return id; } /** * 设置主键 * * @param id 主键 */ public void setId(Long id) { this.id = id; } /** * 获取退票单号,对应abt_refund_order表id * * @return refund_id - 退票单号,对应abt_refund_order表id */ public Long getRefundId() { return refundId; } /** * 设置退票单号,对应abt_refund_order表id * * @param refundId 退票单号,对应abt_refund_order表id */ public void setRefundId(Long refundId) { this.refundId = refundId; } /** * 获取途牛订单号 * * @return order_id - 途牛订单号 */ public Long getOrderId() { return orderId; } /** * 设置途牛订单号 * * @param orderId 途牛订单号 */ public void setOrderId(Long orderId) { this.orderId = orderId; } /** * 获取出票记录主表id * * @return ticket_main_id - 出票记录主表id */ public Long getTicketMainId() { return ticketMainId; } /** * 设置出票记录主表id * * @param ticketMainId 出票记录主表id */ public void setTicketMainId(Long ticketMainId) { this.ticketMainId = ticketMainId; } /** * 获取类型:1=全退 * * @return refund_item_type - 类型:1=全退 */ public Integer getRefundItemType() { return refundItemType; } /** * 设置类型:1=全退 * * @param refundItemType 类型:1=全退 */ public void setRefundItemType(Integer refundItemType) { this.refundItemType = refundItemType; } /** * 获取航段信息(出发城市三字码/到达城市三字码) * * @return leg - 航段信息(出发城市三字码/到达城市三字码) */ public String getLeg() { return leg; } /** * 设置航段信息(出发城市三字码/到达城市三字码) * * @param leg 航段信息(出发城市三字码/到达城市三字码) */ public void setLeg(String leg) { this.leg = leg == null ? null : leg.trim(); } /** * 获取乘客fab系统id * * @return person_id - 乘客fab系统id */ public Long getPersonId() { return personId; } /** * 设置乘客fab系统id * * @param personId 乘客fab系统id */ public void setPersonId(Long personId) { this.personId = personId; } /** * 获取abt_pnr_passenger表id * * @return pnr_passenger_id - abt_pnr_passenger表id */ public Long getPnrPassengerId() { return pnrPassengerId; } /** * 设置abt_pnr_passenger表id * * @param pnrPassengerId abt_pnr_passenger表id */ public void setPnrPassengerId(Long pnrPassengerId) { this.pnrPassengerId = pnrPassengerId; } /** * 获取接口实际操作后的退票费 * * @return real_refund_amount - 接口实际操作后的退票费 */ public Float getRealRefundAmount() { return realRefundAmount; } /** * 设置接口实际操作后的退票费 * * @param realRefundAmount 接口实际操作后的退票费 */ public void setRealRefundAmount(Float realRefundAmount) { this.realRefundAmount = realRefundAmount; } /** * 获取请求的原始退票费用 * * @return refund_amount - 请求的原始退票费用 */ public Float getRefundAmount() { return refundAmount; } /** * 设置请求的原始退票费用 * * @param refundAmount 请求的原始退票费用 */ public void setRefundAmount(Float refundAmount) { this.refundAmount = refundAmount; } /** * 获取请求的手续费 * * @return commission_fee - 请求的手续费 */ public Float getCommissionFee() { return commissionFee; } /** * 设置请求的手续费 * * @param commissionFee 请求的手续费 */ public void setCommissionFee(Float commissionFee) { this.commissionFee = commissionFee; } /** * 获取电子客票票号 * * @return ticket_no - 电子客票票号 */ public String getTicketNo() { return ticketNo; } /** * 设置电子客票票号 * * @param ticketNo 电子客票票号 */ public void setTicketNo(String ticketNo) { this.ticketNo = ticketNo == null ? null : ticketNo.trim(); } /** * 获取pnr * * @return pnr - pnr */ public String getPnr() { return pnr; } /** * 设置pnr * * @param pnr pnr */ public void setPnr(String pnr) { this.pnr = pnr == null ? null : pnr.trim(); } /** * 获取退票备注 * * @return remark - 退票备注 */ public String getRemark() { return remark; } /** * 设置退票备注 * * @param remark 退票备注 */ public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } /** * 获取状态标识,0=待退票,1=成功,2=失败 * * @return status - 状态标识,0=待退票,1=成功,2=失败 */ public Integer getStatus() { return status; } /** * 设置状态标识,0=待退票,1=成功,2=失败 * * @param status 状态标识,0=待退票,1=成功,2=失败 */ public void setStatus(Integer status) { this.status = status; } /** * 获取添加时间 * * @return add_time - 添加时间 */ public Date getAddTime() { return addTime; } /** * 设置添加时间 * * @param addTime 添加时间 */ public void setAddTime(Date addTime) { this.addTime = addTime; } /** * 获取修改时间 * * @return update_time - 修改时间 */ public Date getUpdateTime() { return updateTime; } /** * 设置修改时间 * * @param updateTime 修改时间 */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
Swift
UTF-8
1,653
2.640625
3
[]
no_license
// // ListActionSheet.swift // TheMovieDB // // Created by Artsiom Grintsevich on 11/6/15. // Copyright © 2015 Artsiom Grintsevich. All rights reserved. // import UIKit class ListActionSheet: UIAlertController { init() { super.init() } init(shareUrl: String){ self.init() title = "Pick an action" message = super.init(title: , message: "What do you want to do with your list?", preferredStyle: .ActionSheet) addAction(UIAlertAction(title: "Share", style: .Default, handler: { action in let shareController = UIActivityViewController.init(activityItems: [shareUrl], applicationActivities: nil) self.presentViewController(shareController, animated: true, completion: nil) })) addAction(UIAlertAction(title: "Delete list", style: .Destructive, handler: { action in let deleteController = UIAlertController(title: "List removing", message: "Are you sure you want to remove this list. (Can't be undone)", preferredStyle: .Alert) deleteController.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil)) deleteController.addAction(UIAlertAction(title: "Remove", style: .Destructive, handler: { action in self.detailsManager?.listDelete(listId: self.argList.listId!) })) self.presentViewController(deleteController, animated: true, completion: nil) })) addAction(UIAlertAction(title: "Back", style: .Cancel, handler: nil)) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
C#
UTF-8
3,302
2.984375
3
[ "MIT" ]
permissive
using System; using System.Text; using System.Linq; using System.Numerics; using System.Globalization; using System.Collections.Generic; // For readablity, breaking the ICalculonTypes files based on roles. // These are Rounding operators namespace Calculon.Types { public class Round : IFunctionCog { public string[] FunctionName { get { return new string[] { "round" }; } } public int NumArgs { get { return 1; } } public Type[][] AllowedTypes { get { Type[][] retVal = new Type[1][]; retVal[0] = new Type[] { typeof(Real) }; return retVal; } } public ICalculonType Execute(ref ControllerState cs) { Real arg = (Real) cs.stack.Pop(); //Note underlying .net function is double->double //But I'm writing my on calculator (with blackjack and hookers) //and returning Integer makes more sense to me return new Integer((BigInteger) Math.Round(arg.data)); } } public class Floor : IFunctionCog { public string[] FunctionName { get { return new string[] { "floor" }; } } public int NumArgs { get { return 1; } } public Type[][] AllowedTypes { get { Type[][] retVal = new Type[1][]; retVal[0] = new Type[] { typeof(Real) }; return retVal; } } public ICalculonType Execute(ref ControllerState cs) { Real arg = (Real)cs.stack.Pop(); //see comment on Round return new Integer((BigInteger)Math.Floor(arg.data)); } } public class Ceiling : IFunctionCog { public string[] FunctionName { get { return new string[] { "ceiling" }; } } public int NumArgs { get { return 1; } } public Type[][] AllowedTypes { get { Type[][] retVal = new Type[1][]; retVal[0] = new Type[] { typeof(Real) }; return retVal; } } public ICalculonType Execute(ref ControllerState cs) { Real arg = (Real)cs.stack.Pop(); //see comment on Round return new Integer((BigInteger)Math.Ceiling(arg.data)); } } public class RoundTo : IFunctionCog { public string[] FunctionName { get { return new string[] { "roundto" }; } } public int NumArgs { get { return 2; } } public Type[][] AllowedTypes { get { Type[][] retVal = new Type[1][]; retVal[0] = new Type[] { typeof(Integer), typeof(Real) }; return retVal; } } public ICalculonType Execute(ref ControllerState cs) { Integer places = (Integer) cs.stack.Pop(); Real arg = (Real)cs.stack.Pop(); // We're rounding to decimal palces so still should be Real double newData = Math.Round(arg.data, (Int32)places.data); return new Real(newData); } } }
JavaScript
UTF-8
4,339
2.609375
3
[]
no_license
import React, { useState } from 'react'; import { digitToChar } from '../../Tasks/utilities'; import _ from 'lodash'; export default function ConvertDecimalTable({ floatConvert, params: [convertible, radix], userAnswer, onChange, checkCorrectAnswer }) { const emptyRow = [ { value: '', correct: false }, { value: '', correct: false } ]; let rows = userAnswer.additionalProperties?.table ?? [emptyRow]; const setRows = (getNewRows) => { let answer = _.cloneDeep(userAnswer); answer.additionalProperties.table = getNewRows(rows); onChange(answer); }; let decodedNumber = ''; if (rows[0] && rows[0][1].value !== '') { if (floatConvert) decodedNumber = '0.' + rows .filter(([{ value: k }, _]) => k !== '') .map(([{ value: k }, _]) => digitToChar(parseInt(k))) .join(''); else decodedNumber = rows .filter(([_, { value: v }]) => v !== '') .map(([_, { value: v }]) => digitToChar(parseInt(v))) .reverse() .join(''); } const onRowChange = (colNum, rowNum, e) => { if (isNaN(Number(e.target.value))) return; let value = e.target.value; setRows((prevRows) => { // let newRows = prevRows.map((row) => [...row]); let newRows = _.cloneDeep(prevRows); newRows[rowNum][colNum].value = value; return newRows; }); }; const onRowKeyPressed = (rowNum, e) => { if (rowNum === rows.length - 1) { if (e.key === 'Enter') { setRows((prevRows) => [..._.cloneDeep(prevRows), _.cloneDeep(emptyRow)]); } else if (e.keyCode === 8 && rows.length > 1 && e.target.value === '') { // backspace setRows((prevRows) => _.cloneDeep(prevRows).slice(0, -1)); // prevRows.map((r) => [...r]).slice(0, -1)); e.preventDefault(); } } }; const convertTable = ( <table className='nes-table is-bordered is-centered'> <caption style={{ captionSide: 'top' }}>Таблица перевода</caption> <thead> {floatConvert ? ( <tr> <td>Целая часть</td> <td> Дробная часть ({convertible} * {radix}) </td> </tr> ) : ( <tr> <td>Делимое</td> <td>Остаток</td> </tr> )} </thead> <tbody> {rows.map( ([{ value: a, correct: a_correct }, { value: b, correct: b_correct }], i) => ( <tr key={i}> <td> <input value={a} onChange={(e) => onRowChange(0, i, e)} onKeyDown={(e) => onRowKeyPressed(i, e)} className={'nes-input ' + (a_correct ? 'is-success' : '')} style={{ textAlign: 'right' }} /> </td> <td> <input value={b} onChange={(e) => onRowChange(1, i, e)} onKeyDown={(e) => onRowKeyPressed(i, e)} className={'nes-input ' + (b_correct ? 'is-success' : '')} /> </td> </tr> ) )} </tbody> </table> ); return ( <div className={'convertTable '}> {convertTable} {checkCorrectAnswer && decodedNumber !== '' && <div>Возможный ответ: {decodedNumber}</div>} </div> ); }
SQL
UTF-8
2,698
2.765625
3
[]
no_license
-- Created by Vertabelo (http://vertabelo.com) -- Last modification date: 2019-05-18 11:04:35.482 -- foreign keys ALTER TABLE BankDict DROP CONSTRAINT BankDict_Adres; ALTER TABLE Email DROP CONSTRAINT Email_Klient; ALTER TABLE IdentyfikatorKonta DROP CONSTRAINT IdentyfikatorKonta_Adres; ALTER TABLE IdentyfikatorKonta DROP CONSTRAINT IdentyfikatorKonta_BankDict; ALTER TABLE Identyfikator DROP CONSTRAINT Identyfikator_Dict; ALTER TABLE Karta DROP CONSTRAINT Karta_KartaDict; ALTER TABLE Karta DROP CONSTRAINT Karta_Klient_Rachunek; ALTER TABLE Rachunek_Operacja DROP CONSTRAINT KategoriaDict_Rachunek_Operacja; ALTER TABLE Klient DROP CONSTRAINT Klient_AdresKorespondencyjny; ALTER TABLE Klient DROP CONSTRAINT Klient_AdresZameldowania; ALTER TABLE Klient DROP CONSTRAINT Klient_AdresZamieszkania; ALTER TABLE Klient DROP CONSTRAINT Klient_Identyfikator; ALTER TABLE Klient_Lokata DROP CONSTRAINT Klient_Lokata_Klient; ALTER TABLE Klient_Lokata DROP CONSTRAINT Klient_Lokata_Lokata; ALTER TABLE Klient DROP CONSTRAINT Klient_ObywatelstwoDict; ALTER TABLE Klient_Rachunek DROP CONSTRAINT Klient_Rachunek_Klient; ALTER TABLE Klient_Rachunek DROP CONSTRAINT Klient_Rachunek_Rachunek; ALTER TABLE Klient DROP CONSTRAINT Klient_StanCywilnyDict; ALTER TABLE Klient DROP CONSTRAINT Klient_Urzad_skarbowy; ALTER TABLE Rachunek_Operacja DROP CONSTRAINT OperacjaWychodzacaDane_Rachunek_Operacja; ALTER TABLE Operacja DROP CONSTRAINT Operacja_IdentyfikatorKonta; ALTER TABLE OperacjaWychodzacaDane DROP CONSTRAINT PlatnoscDict_OperacjaWychodzacaDane; ALTER TABLE Rachunek_Operacja DROP CONSTRAINT Rachunek_Operacja_Klient; ALTER TABLE Rachunek_Operacja DROP CONSTRAINT Rachunek_Operacja_Operacja; ALTER TABLE Rachunek_Operacja DROP CONSTRAINT Rachunek_Operacja_Rachunek; ALTER TABLE Rachunek DROP CONSTRAINT Rachunek_RachunekDict; ALTER TABLE Rachunek_Operacja DROP CONSTRAINT RodzajOperacjiDict_Rachunek_Operacja; ALTER TABLE Telefon DROP CONSTRAINT Telefon_Klient; ALTER TABLE Urzad_skarbowy DROP CONSTRAINT Urzad_skarbowy_Adres; -- tables DROP TABLE Adres; DROP TABLE BankDict; DROP TABLE Email; DROP TABLE Identyfikator; DROP TABLE IdentyfikatorDict; DROP TABLE IdentyfikatorKonta; DROP TABLE Karta; DROP TABLE KartaDict; DROP TABLE KategoriaDict; DROP TABLE Klient; DROP TABLE Klient_Lokata; DROP TABLE Klient_Rachunek; DROP TABLE Lokata; DROP TABLE ObywatelstwoDict; DROP TABLE Operacja; DROP TABLE OperacjaWychodzacaDane; DROP TABLE PlatnoscDict; DROP TABLE Rachunek; DROP TABLE RachunekDict; DROP TABLE Rachunek_Operacja; DROP TABLE RodzajOperacjiDict; DROP TABLE StanCywilnyDict; DROP TABLE Telefon; DROP TABLE Urzad_skarbowy; -- End of file.
Shell
UTF-8
450
2.90625
3
[ "MIT" ]
permissive
#!/bin/bash #bdereims@vmware.com # Args: <Cluster_Namespace> <Cluster_Name> . ../env export KUBECTL_VSPHERE_PASSWORD=${PASSWORD} [ "$1" == "" -o "$2" == "" ] && printf "\nIt needs to provide <Cluster_Namespace> and <Cluster_Name>.\n\n" && exit 1 echo ${TANZU_PASSWORD} kubectl vsphere login --insecure-skip-tls-verify --server ${SUPERVISOR} --vsphere-username ${TANZU_USER} --tanzu-kubernetes-cluster-name ${2} --tanzu-kubernetes-cluster-namespace ${1}
JavaScript
UTF-8
1,898
2.90625
3
[]
no_license
import React, { Component } from 'react'; import TechItem from './TechItem'; class TechList extends Component{ //exemplo de utilização de propTypes e defaultProps para class components // static propTypes = {}; // static defaultProps = {}; //state é necessario que tenha esse nome state = { newTech: '', techs: [], }; //CICLO DE VIDA DOS COMPONENTES //Executado assim que o componente aparece em tela componentDidMount(){ const techs = localStorage.getItem('techs'); if(techs){ this.setState({techs: JSON.parse(techs)}); } } //Executado quando há alterações de props ou state componentDidUpdate(prevProps, prevState) { //this.props, this.state if(prevState.techs !== this.state.techs) { localStorage.setItem('techs', JSON.stringify(this.state.techs)); } } //Executado quando o componente deixar de existir componentWillUnmount(){} handleInputChange = e => { this.setState({newTech: e.target.value}); }; handleSubmit = e => { e.preventDefault(); this.setState({ techs: [...this.state.techs, this.state.newTech], newTech: '', }); }; //remoção de item do estado handleDelete = (tech) => { this.setState({ techs: this.state.techs.filter( t => t !== tech) }); }; //método render é necessário em class components render(){ return ( <form onSubmit={this.handleSubmit}> <ul> {this.state.techs.map(tech => ( <TechItem key={tech} tech={tech} onDelete={() => this.handleDelete(tech)} /> ))} </ul> <input type = 'text' onChange = { this.handleInputChange } value = { this.state.newTech } /> <button type='submit'>Adicionar</button> </form> ); } } export default TechList;
C++
UTF-8
15,274
2.921875
3
[]
no_license
#ifndef _HR_PIXELFORMAT_H_ #define _HR_PIXELFORMAT_H_ namespace Hr { enum EnumPixelFormat { /// Unknown pixel format. PF_UNKNOWN = 0, /// 8-bit pixel format, all bits luminance. PF_L8 = 1, PF_BYTE_L = PF_L8, /// 16-bit pixel format, all bits luminance. PF_L16 = 2, PF_SHORT_L = PF_L16, /// 8-bit pixel format, all bits alpha. PF_A8 = 3, PF_BYTE_A = PF_A8, /// 8-bit pixel format, 4 bits alpha, 4 bits luminance. PF_A4L4 = 4, /// 2 byte pixel format, 1 byte luminance, 1 byte alpha PF_BYTE_LA = 5, /// 16-bit pixel format, 5 bits red, 6 bits green, 5 bits blue. PF_R5G6B5 = 6, /// 16-bit pixel format, 5 bits red, 6 bits green, 5 bits blue. PF_B5G6R5 = 7, /// 8-bit pixel format, 2 bits blue, 3 bits green, 3 bits red. PF_R3G3B2 = 31, /// 16-bit pixel format, 4 bits for alpha, red, green and blue. PF_A4R4G4B4 = 8, /// 16-bit pixel format, 5 bits for blue, green, red and 1 for alpha. PF_A1R5G5B5 = 9, /// 24-bit pixel format, 8 bits for red, green and blue. PF_R8G8B8 = 10, /// 24-bit pixel format, 8 bits for blue, green and red. PF_B8G8R8 = 11, /// 32-bit pixel format, 8 bits for alpha, red, green and blue. PF_A8R8G8B8 = 12, /// 32-bit pixel format, 8 bits for blue, green, red and alpha. PF_A8B8G8R8 = 13, /// 32-bit pixel format, 8 bits for blue, green, red and alpha. PF_B8G8R8A8 = 14, /// 32-bit pixel format, 8 bits for red, green, blue and alpha. PF_R8G8B8A8 = 28, /// 32-bit pixel format, 8 bits for red, 8 bits for green, 8 bits for blue /// like PF_A8R8G8B8, but alpha will get discarded PF_X8R8G8B8 = 26, /// 32-bit pixel format, 8 bits for blue, 8 bits for green, 8 bits for red /// like PF_A8B8G8R8, but alpha will get discarded PF_X8B8G8R8 = 27, /// 3 byte pixel format, 1 byte for red, 1 byte for green, 1 byte for blue PF_BYTE_RGB = PF_B8G8R8, /// 3 byte pixel format, 1 byte for blue, 1 byte for green, 1 byte for red PF_BYTE_BGR = PF_R8G8B8, /// 4 byte pixel format, 1 byte for blue, 1 byte for green, 1 byte for red and one byte for alpha PF_BYTE_BGRA = PF_A8R8G8B8, /// 4 byte pixel format, 1 byte for red, 1 byte for green, 1 byte for blue, and one byte for alpha PF_BYTE_RGBA = PF_A8B8G8R8, /// 32-bit pixel format, 2 bits for alpha, 10 bits for red, green and blue. PF_A2R10G10B10 = 15, /// 32-bit pixel format, 10 bits for blue, green and red, 2 bits for alpha. PF_A2B10G10R10 = 16, /// DDS (DirectDraw Surface) DXT1 format PF_DXT1 = 17, /// DDS (DirectDraw Surface) DXT2 format PF_DXT2 = 18, /// DDS (DirectDraw Surface) DXT3 format PF_DXT3 = 19, /// DDS (DirectDraw Surface) DXT4 format PF_DXT4 = 20, /// DDS (DirectDraw Surface) DXT5 format PF_DXT5 = 21, /// 16-bit pixel format, 16 bits (float) for red PF_FLOAT16_R = 32, /// 48-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue PF_FLOAT16_RGB = 22, /// 64-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue, 16 bits (float) for alpha PF_FLOAT16_RGBA = 23, // 32-bit pixel format, 32 bits (float) for red PF_FLOAT32_R = 33, /// 96-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue PF_FLOAT32_RGB = 24, /// 128-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue, 32 bits (float) for alpha PF_FLOAT32_RGBA = 25, /// 32-bit, 2-channel s10e5 floating point pixel format, 16-bit green, 16-bit red PF_FLOAT16_GR = 35, /// 64-bit, 2-channel floating point pixel format, 32-bit green, 32-bit red PF_FLOAT32_GR = 36, /// Depth texture format PF_DEPTH = 29, /// 64-bit pixel format, 16 bits for red, green, blue and alpha PF_SHORT_RGBA = 30, /// 32-bit pixel format, 16-bit green, 16-bit red PF_SHORT_GR = 34, /// 48-bit pixel format, 16 bits for red, green and blue PF_SHORT_RGB = 37, /// PVRTC (PowerVR) RGB 2 bpp PF_PVRTC_RGB2 = 38, /// PVRTC (PowerVR) RGBA 2 bpp PF_PVRTC_RGBA2 = 39, /// PVRTC (PowerVR) RGB 4 bpp PF_PVRTC_RGB4 = 40, /// PVRTC (PowerVR) RGBA 4 bpp PF_PVRTC_RGBA4 = 41, /// PVRTC (PowerVR) Version 2, 2 bpp PF_PVRTC2_2BPP = 42, /// PVRTC (PowerVR) Version 2, 4 bpp PF_PVRTC2_4BPP = 43, /// 32-bit pixel format, 11 bits (float) for red, 11 bits (float) for green, 10 bits (float) for blue PF_R11G11B10_FLOAT = 44, /// 8-bit pixel format, 8 bits red (unsigned int). PF_R8_UINT = 45, /// 16-bit pixel format, 8 bits red (unsigned int), 8 bits blue (unsigned int). PF_R8G8_UINT = 46, /// 24-bit pixel format, 8 bits red (unsigned int), 8 bits blue (unsigned int), 8 bits green (unsigned int). PF_R8G8B8_UINT = 47, /// 32-bit pixel format, 8 bits red (unsigned int), 8 bits blue (unsigned int), 8 bits green (unsigned int), 8 bits alpha (unsigned int). PF_R8G8B8A8_UINT = 48, /// 16-bit pixel format, 16 bits red (unsigned int). PF_R16_UINT = 49, /// 32-bit pixel format, 16 bits red (unsigned int), 16 bits blue (unsigned int). PF_R16G16_UINT = 50, /// 48-bit pixel format, 16 bits red (unsigned int), 16 bits blue (unsigned int), 16 bits green (unsigned int). PF_R16G16B16_UINT = 51, /// 64-bit pixel format, 16 bits red (unsigned int), 16 bits blue (unsigned int), 16 bits green (unsigned int), 16 bits alpha (unsigned int). PF_R16G16B16A16_UINT = 52, /// 32-bit pixel format, 32 bits red (unsigned int). PF_R32_UINT = 53, /// 64-bit pixel format, 32 bits red (unsigned int), 32 bits blue (unsigned int). PF_R32G32_UINT = 54, /// 96-bit pixel format, 32 bits red (unsigned int), 32 bits blue (unsigned int), 32 bits green (unsigned int). PF_R32G32B32_UINT = 55, /// 128-bit pixel format, 32 bits red (unsigned int), 32 bits blue (unsigned int), 32 bits green (unsigned int), 32 bits alpha (unsigned int). PF_R32G32B32A32_UINT = 56, /// 8-bit pixel format, 8 bits red (signed int). PF_R8_SINT = 57, /// 16-bit pixel format, 8 bits red (signed int), 8 bits blue (signed int). PF_R8G8_SINT = 58, /// 24-bit pixel format, 8 bits red (signed int), 8 bits blue (signed int), 8 bits green (signed int). PF_R8G8B8_SINT = 59, /// 32-bit pixel format, 8 bits red (signed int), 8 bits blue (signed int), 8 bits green (signed int), 8 bits alpha (signed int). PF_R8G8B8A8_SINT = 60, /// 16-bit pixel format, 16 bits red (signed int). PF_R16_SINT = 61, /// 32-bit pixel format, 16 bits red (signed int), 16 bits blue (signed int). PF_R16G16_SINT = 62, /// 48-bit pixel format, 16 bits red (signed int), 16 bits blue (signed int), 16 bits green (signed int). PF_R16G16B16_SINT = 63, /// 64-bit pixel format, 16 bits red (signed int), 16 bits blue (signed int), 16 bits green (signed int), 16 bits alpha (signed int). PF_R16G16B16A16_SINT = 64, /// 32-bit pixel format, 32 bits red (signed int). PF_R32_SINT = 65, /// 64-bit pixel format, 32 bits red (signed int), 32 bits blue (signed int). PF_R32G32_SINT = 66, /// 96-bit pixel format, 32 bits red (signed int), 32 bits blue (signed int), 32 bits green (signed int). PF_R32G32B32_SINT = 67, /// 128-bit pixel format, 32 bits red (signed int), 32 bits blue (signed int), 32 bits green (signed int), 32 bits alpha (signed int). PF_R32G32B32A32_SINT = 68, /// 32-bit pixel format, 9 bits for blue, green, red plus a 5 bit exponent. PF_R9G9B9E5_SHAREDEXP = 69, /// DDS (DirectDraw Surface) BC4 format (unsigned normalised) PF_BC4_UNORM = 70, /// DDS (DirectDraw Surface) BC4 format (signed normalised) PF_BC4_SNORM = 71, /// DDS (DirectDraw Surface) BC5 format (unsigned normalised) PF_BC5_UNORM = 72, /// DDS (DirectDraw Surface) BC5 format (signed normalised) PF_BC5_SNORM = 73, /// DDS (DirectDraw Surface) BC6H format (unsigned 16 bit float) PF_BC6H_UF16 = 74, /// DDS (DirectDraw Surface) BC6H format (signed 16 bit float) PF_BC6H_SF16 = 75, /// DDS (DirectDraw Surface) BC7 format (unsigned normalised) PF_BC7_UNORM = 76, /// DDS (DirectDraw Surface) BC7 format (unsigned normalised sRGB) PF_BC7_UNORM_SRGB = 77, /// 8-bit pixel format, all bits red. PF_R8 = 78, /// 16-bit pixel format, 8 bits red, 8 bits green. PF_RG8 = 79, /// 8-bit pixel format, 8 bits red (signed normalised int). PF_R8_SNORM = 80, /// 16-bit pixel format, 8 bits red (signed normalised int), 8 bits blue (signed normalised int). PF_R8G8_SNORM = 81, /// 24-bit pixel format, 8 bits red (signed normalised int), 8 bits blue (signed normalised int), 8 bits green (signed normalised int). PF_R8G8B8_SNORM = 82, /// 32-bit pixel format, 8 bits red (signed normalised int), 8 bits blue (signed normalised int), 8 bits green (signed normalised int), 8 bits alpha (signed normalised int). PF_R8G8B8A8_SNORM = 83, /// 16-bit pixel format, 16 bits red (signed normalised int). PF_R16_SNORM = 84, /// 32-bit pixel format, 16 bits red (signed normalised int), 16 bits blue (signed normalised int). PF_R16G16_SNORM = 85, /// 48-bit pixel format, 16 bits red (signed normalised int), 16 bits blue (signed normalised int), 16 bits green (signed normalised int). PF_R16G16B16_SNORM = 86, /// 64-bit pixel format, 16 bits red (signed normalised int), 16 bits blue (signed normalised int), 16 bits green (signed normalised int), 16 bits alpha (signed normalised int). PF_R16G16B16A16_SNORM = 87, /// ETC1 (Ericsson Texture Compression) PF_ETC1_RGB8 = 88, /// ETC2 (Ericsson Texture Compression) PF_ETC2_RGB8 = 89, /// ETC2 (Ericsson Texture Compression) PF_ETC2_RGBA8 = 90, /// ETC2 (Ericsson Texture Compression) PF_ETC2_RGB8A1 = 91, /// ATC (AMD_compressed_ATC_texture) PF_ATC_RGB = 92, /// ATC (AMD_compressed_ATC_texture) PF_ATC_RGBA_EXPLICIT_ALPHA = 93, /// ATC (AMD_compressed_ATC_texture) PF_ATC_RGBA_INTERPOLATED_ALPHA = 94, //128-bit pixel format, 32 bits red , 32 bits blue, 32 bits green 32 bits alpha . PF_R32G32B32A32_FLOAT, // 16-bit element format, 16 bits depth PF_D16, // 32-bit element format, 24 bits depth and 8 bits stencil PF_D24S8, // 32-bit element format, 32 bits depth PF_D32F, // Number of pixel formats currently defined PF_COUNT }; enum EnumComparisonFunc { CF_NEVER, CF_LESS, CF_EQUAL, CF_LESS_EQUAL, CF_GREATER, CF_NOT_EQUAL, CF_GREATER_EQUAL, CF_ALWAYS, }; inline EnumComparisonFunc ComparisonFunc(const std::string& strComparisonFunc) { if ("never" == strComparisonFunc) return CF_NEVER; if ("less" == strComparisonFunc) return CF_LESS; if ("equal" == strComparisonFunc) return CF_EQUAL; if ("less_equal" == strComparisonFunc) return CF_LESS_EQUAL; if ("greater" == strComparisonFunc) return CF_GREATER; if ("not_equal" == strComparisonFunc) return CF_NOT_EQUAL; if ("greater_equal" == strComparisonFunc) return CF_GREATER_EQUAL; if ("always" == strComparisonFunc) return CF_ALWAYS; return CF_LESS; } enum EnumDepthWriteMask { DWM_ZERO, DWM_ALL, }; inline EnumDepthWriteMask DepthWriteMash(const std::string& strDepthWriteMask) { if ("zero" == strDepthWriteMask) return DWM_ZERO; if ("all" == strDepthWriteMask) return DWM_ALL; return DWM_ALL; } enum EnumStencilOperation { SO_KEEP, SO_ZERO, SO_REPLACE, SO_INCR_SAT, SO_DECR_SAT, SO_INVERT, SO_INCR, SO_DECR, }; inline EnumStencilOperation StencilOperation(const std::string& strStencilOp) { if ("keep" == strStencilOp) return SO_KEEP; if ("zero" == strStencilOp) return SO_ZERO; if ("replace" == strStencilOp) return SO_REPLACE; if ("incr_sat" == strStencilOp) return SO_INCR_SAT; if ("decr_sat" == strStencilOp) return SO_DECR_SAT; if ("invert" == strStencilOp) return SO_INVERT; if ("incr" == strStencilOp) return SO_INCR; if ("decr" == strStencilOp) return SO_DECR; return SO_KEEP; }; //RasterizerFillMode enum EnumRasterizerFillModel { RFM_WIREFRAME, RFM_SOLD, }; //RasterizerCullMode enum EnumRasterizerCullModel { RCM_CULL_NONE, RCM_CULL_FRONT, RCM_CULL_BACK }; inline EnumRasterizerFillModel RasterizerFillMode(const std::string& str) { if ("solid" == str) return RFM_SOLD; if ("wireframe" == str) return RFM_WIREFRAME; return RFM_SOLD; }; inline EnumRasterizerCullModel RasterizerCullMode(const std::string& str) { if ("none" == str) return RCM_CULL_NONE; if ("front" == str) return RCM_CULL_FRONT; if ("back" == str) return RCM_CULL_BACK; return RCM_CULL_BACK; }; enum EnumSamplerFilter { SF_FILTER_MIN_MAG_MIP_POINT, SF_FILTER_MIN_MAG_POINT_MIP_LINEAR, SF_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, SF_FILTER_MIN_POINT_MAG_MIP_LINEAR, SF_FILTER_MIN_LINEAR_MAG_MIP_POINT, SF_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, SF_FILTER_MIN_MAG_LINEAR_MIP_POINT, SF_FILTER_MIN_MAG_MIP_LINEAR, SF_FILTER_ANISOTROPIC, SF_FILTER_COMPARISON_MIN_MAG_MIP_POINT, SF_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR, SF_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT, SF_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR, SF_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT, SF_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR, SF_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, SF_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, SF_FILTER_COMPARISON_ANISOTROPIC, SF_FILTER_MINIMUM_MIN_MAG_MIP_POINT, SF_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR, SF_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT, SF_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR, SF_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT, SF_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR, SF_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT, SF_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR, SF_FILTER_MINIMUM_ANISOTROPIC, SF_FILTER_MAXIMUM_MIN_MAG_MIP_POINT, SF_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR, SF_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT, SF_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR, SF_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT, SF_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR, SF_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT, SF_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR, SF_FILTER_MAXIMUM_ANISOTROPIC }; inline EnumSamplerFilter SamplerFilter(const std::string& str) { if ("min_mag_mip_point" == str) return SF_FILTER_MIN_MAG_MIP_POINT; if ("min_mag_mip_linear" == str) return SF_FILTER_MIN_MAG_MIP_LINEAR; return SF_FILTER_MIN_MAG_MIP_POINT; } enum EnumTextureAddressMode { TAM_TEXTURE_ADDRESS_WRAP, TAM_TEXTURE_ADDRESS_MIRROR, TAM_TEXTURE_ADDRESS_CLAMP, TAM_TEXTURE_ADDRESS_BORDER, TAM_TEXTURE_ADDRESS_MIRROR_ONCE }; inline EnumTextureAddressMode TextureAddressMode(const std::string& str) { if ("wrap" == str) return TAM_TEXTURE_ADDRESS_WRAP; else if ("mirror" == str) return TAM_TEXTURE_ADDRESS_MIRROR; else if ("clamp" == str) return TAM_TEXTURE_ADDRESS_CLAMP; else if ("border" == str) return TAM_TEXTURE_ADDRESS_BORDER; else if ("mirror_once" == str) return TAM_TEXTURE_ADDRESS_MIRROR_ONCE; return TAM_TEXTURE_ADDRESS_WRAP; } enum EnumRenderingPath { RP_FORWARD, RP_DEFERRED, }; enum EnumRenderProcessingType { RPT_FORWARD, RPT_FINALMAPPING, }; enum EnumGBufferType { GBT_POSITION, GBT_NORMAL, GBT_DEPTH, GBT_ALBEDO, GBT_LIGHTINTENSITY, GBT_SPECULARINTENSITY, GBT_MAXNUM, }; enum EnumCameraMaskLayer { CML_ALL = 1, CML_UI = 1 << 1, CML_CUSTOM = 1 << 2, }; } #endif
Java
UTF-8
4,833
2.1875
2
[]
no_license
/* Copyright (c) 2010, NHIN Direct Project All rights reserved. Authors: Greg Meyer gm2552@cerner.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the The NHIN Direct Project (nhindirect.org). nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.nhindirect.common.audit.provider; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Collection; import java.util.Enumeration; /** * Class loader that aggregates a list class loaders and searches each on iteratively for classes resources. * @author Greg Meyer * @since 1.0 */ public class AggregateClassLoader extends ClassLoader { protected final Collection<ClassLoader> classLoaders; protected final Collection<ClassLoader> resourceLoaders; /** * Constructor * @param classLoaders Collection of class loaders used for loading class objects. * @param resourceLoaders Collection of class loaders used for loading resources. */ public AggregateClassLoader(Collection<ClassLoader> classLoaders, Collection<ClassLoader> resourceLoaders) { this.classLoaders = classLoaders; this.resourceLoaders = resourceLoaders; } /** * {@inheritDoc} */ @Override public synchronized void clearAssertionStatus() { for(ClassLoader loader : classLoaders) loader.clearAssertionStatus(); for(ClassLoader loader : resourceLoaders) loader.clearAssertionStatus(); } /** * {@inheritDoc} */ @Override public URL getResource(String arg0) { for(ClassLoader loader : resourceLoaders) { final URL url = loader.getResource(arg0); if (url != null) return url; } return null; } /** * {@inheritDoc} */ @Override public InputStream getResourceAsStream(String arg0) { for(ClassLoader loader : resourceLoaders) { final InputStream stream = loader.getResourceAsStream(arg0); if (stream != null) return stream; } return null; } /** * {@inheritDoc} */ @Override public Enumeration<URL> getResources(String arg0) throws IOException { Enumeration<URL> urls = null; for(ClassLoader loader : resourceLoaders) { try { urls= loader.getResources(arg0); } catch (IOException e) { } } return urls; } /** * {@inheritDoc} */ @Override public Class<?> loadClass(String arg0) throws ClassNotFoundException { Class<?> clazz = null; for(ClassLoader loader : classLoaders) { try { clazz = loader.loadClass(arg0); if (clazz != null) return clazz; } catch (ClassNotFoundException e) { } } throw new ClassNotFoundException("Class " + arg0 + " not found"); } /** * {@inheritDoc} */ @Override public synchronized void setClassAssertionStatus(String arg0, boolean arg1) { for(ClassLoader loader : classLoaders) loader.setClassAssertionStatus(arg0, arg1); for(ClassLoader loader : resourceLoaders) loader.setClassAssertionStatus(arg0, arg1); } /** * {@inheritDoc} */ @Override public synchronized void setDefaultAssertionStatus(boolean arg0) { for(ClassLoader loader : classLoaders) loader.setDefaultAssertionStatus(arg0); for(ClassLoader loader : resourceLoaders) loader.setDefaultAssertionStatus(arg0); } /** * {@inheritDoc} */ @Override public synchronized void setPackageAssertionStatus(String arg0, boolean arg1) { for(ClassLoader loader : classLoaders) loader.setPackageAssertionStatus(arg0, arg1); for(ClassLoader loader : resourceLoaders) loader.setPackageAssertionStatus(arg0, arg1); } }
Java
UTF-8
1,294
3.296875
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Subset_1182 { static int[] nums; static int s; static int cnt = 0; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String nInput = br.readLine(); StringTokenizer st = new StringTokenizer(nInput, " "); int n = Integer.parseInt(st.nextToken()); s = Integer.parseInt(st.nextToken()); nums = new int[n]; String num = br.readLine(); st = new StringTokenizer(num, " "); for(int i=0; i<n; i++){ nums[i] = Integer.parseInt(st.nextToken()); } int index = 0; int sum = 0; countSubset(index, sum); System.out.println(cnt); } private static void countSubset(int index, int sum) { if(index >= nums.length){ return; } if(sum + nums[index] == s){ cnt++; } //현재 index를 부분집합으로 삼은 경우 countSubset(index+1, sum + nums[index]); //현재 index를 부분집합으로 삼지 x 경우 countSubset(index+1, sum); } }
Markdown
UTF-8
848
2.78125
3
[ "MIT" ]
permissive
# Dressy End When working in a team, define some patterns could be a great idea if contributors want to keep things organized and, consequently, easy and fast to mantain. Dressy End is a compilation of the best pratices and advices I have learned since I have started work as a front end developer. ### Contents The content of this guide is divided into three well known areas at front end development plus the Environment topic. Environment is the place to share good advices in the use of task automators, dependecy managers or simply IDEs or text editors: - [Markup](markup/README.md) - [Style](style/README.md) - [Script](script/README.md) - [Environment](environment/README.md) ### Contribute If you know some good pattern or advice which could be here, feel free to contribute. I hope this guide can be useful for you as it has been to me.
C++
UTF-8
720
2.578125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
typedef long long llint; class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { const int n = A.size(); if (n < 3) { return 0; } llint diff = A[0] - A[1]; int p = 0; int q = 1; int ans = 0; while (q + 1 < n) { if (1LL * A[q] - A[q + 1] != diff) { ans += calc(q - p + 1); p = q; diff = A[q] - A[q + 1]; } else { q++; } } return ans + calc(q - p + 1); } private: int calc(int n) { if (n <= 2) { return 0; } return 1LL * n * (n - 1) / 2 - n + 1; } };
Python
UTF-8
3,408
2.921875
3
[]
no_license
#Dependencies from bs4 import BeautifulSoup as bs import requests from splinter import Browser from selenium import webdriver import pandas as pd import time def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {"executable_path": "/usr/local/bin/chromedriver"} return Browser("chrome", **executable_path, headless=False) def scrape(): browser = init_browser() # URL of page to be scraped url = "https://mars.nasa.gov/news/" # Retrieve page with the requests module response = requests.get(url) # Create BeautifulSoup object; parse with 'html.parser' soup = bs(response.text, 'html.parser') news_title = soup.find("div", class_="content_title").text #print(news_title) news_p = soup.find('div', class_='rollover_description_inner').text #print(news_p) image_url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars' browser.visit(image_url) time.sleep(2) html = browser.html soup = bs(html, "html.parser") browser.find_by_css("div.carousel_container div.carousel_items a.button").first.click() # Design an XPATH selector to grab the image xpath = '//*[@id="fancybox-lock"]/div/div[2]/div/div[1]/a[2]' time.sleep(2) browser.find_by_xpath(xpath).click() time.sleep(2) html = browser.html soup = bs(html, 'html.parser') img_url = soup.find("img", class_="main_image")["src"] #img_url featured_image = 'https://www.jpl.nasa.gov/' + img_url #print(featured_image) # Scrape the latest Mars weather tweet from the page weather_url = 'https://twitter.com/marswxreport?lang=en' response = requests.get(weather_url) weather_soup = bs(response.text,'html.parser') mars_weather_tweet = weather_soup.find('div', attrs={"class": "tweet", "data-name": "Mars Weather"}) mars_weather=mars_weather_tweet.find('p',class_='TweetTextSize').text # use Pandas to scrape the table containing facts # about the planet including Diameter, Mass, etc. Mars_Facts = 'https://space-facts.com/mars/' data = pd.read_html(Mars_Facts,skiprows=1)[0] table = data.to_html(header=True, index=False) #table # Mars Hemisphere/obtain high resolution images url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' browser.visit(url) html = browser.html soup = bs(html,'html.parser') hemispheres = soup.find('div',class_='collapsible results') results = hemispheres.find_all('a') hemisphere_image_urls = [] for result in results: if result.h3: title = result.h3.text link = 'https://astrogeology.usgs.gov' + result['href'] print(title,link) browser.visit(link) time.sleep(2) image_html = browser.html soup = bs(image_html,'html.parser') soup_image = soup.find('div', class_='downloads').find('li').a['href'] print(soup_image) mars_images = {'title':title, 'img_url':soup_image} hemisphere_image_urls.append(mars_images) mission_to_mars = { "id": 1, "news_title": news_title, "news_p": news_p, "featured_image_url": featured_image, "mars_weather": mars_weather, "fact_table": table, "hemisphere_images": hemisphere_image_urls } return mission_to_mars
Java
UTF-8
1,670
2.015625
2
[]
no_license
package com.android.veggieprotection.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import com.android.veggieprotection.R; import com.android.veggieprotection.adapter.HamaAdapter; import com.android.veggieprotection.model.EntityHama; import com.android.veggieprotection.model.EntitySayuran; import com.android.veggieprotection.util.QueryUtils; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class InformasiHamaActivity extends AppCompatActivity implements HamaAdapter.OnClickListener{ @Bind(R.id.mylist) ListView mylist; List<EntityHama> listHama = new ArrayList<>(); HamaAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_informasi_hama); ButterKnife.bind(this); Bundle data = getIntent().getExtras(); int index = data.getInt("index"); EntitySayuran sayur = QueryUtils.getSingleSayuran(index); listHama.clear(); listHama.addAll(EntityHama.daftarHama(sayur)); adapter = new HamaAdapter(this, listHama); adapter.setOnClickListener(this); mylist.setAdapter(adapter); } @Override public void onClick(int position) { int id = (position + 1); Intent intent = new Intent(InformasiHamaActivity.this, InformasiPestisidaActivity.class); intent.putExtra("id", id); startActivity(intent); } }
TypeScript
UTF-8
848
2.84375
3
[]
no_license
import { Injectable } from '@nestjs/common'; import IPopulation from './interfaces/population.interface'; import Population from './models/population.model'; import State from './models/state.model'; @Injectable() export default class AppService { private populations: Population[] = [ new Population(new State('São Paulo', 'SP'), 12.33), new Population(new State('Rio de Janeiro', 'RJ'), 6.7), new Population(new State('Pernambuco', 'PE'), 9.2), new Population(new State('Bahia', 'BA'), 15.13), ]; gePopulationByState(abbreviation: string): IPopulation { const population = this.populations.find( (population) => population.state.abbreviation == abbreviation.toLocaleUpperCase(), ); return { abbreviation: population.state.abbreviation, population: population.quantity, }; } }
C++
UTF-8
2,953
2.875
3
[]
no_license
/* Building Blocks Engine Ultimate Game Engine Design and Architecture (2006) Created by Allen Sherrod */ #ifndef _BB_VERTEX_DESCRIPTOR_H_ #define _BB_VERTEX_DESCRIPTOR_H_ #include<NameSpace.h> #include<Defines.h> #include<vector> DECLARE_ENGINE_NAMESPACE class VertexElement { public: VertexElement() { m_type = BB_ELEMENT_TYPE_NULL; m_bytes = 0; m_offset = 0; } bool operator==(VertexElement &e) { return (m_type == e.m_type && m_bytes == e.m_bytes && m_offset == e.m_offset); } BB_ELEMENT_TYPE m_type; int m_bytes; int m_offset; }; class VertexDescriptor { public: VertexDescriptor() { m_currentStride = 0; } void Clear() { m_elements.clear(); m_currentStride = 0; } BRESULT AddElement(BB_ELEMENT_TYPE type) { VertexElement element; element.m_type = type; switch(type) { case BB_ELEMENT_TYPE_IGNORE_3F: case BB_ELEMENT_TYPE_VERTEX_3F: case BB_ELEMENT_TYPE_NORMAL_3F: case BB_ELEMENT_TYPE_COLOR_3F: case BB_ELEMENT_TYPE_TEX1_3F: case BB_ELEMENT_TYPE_TEX2_3F: case BB_ELEMENT_TYPE_TEX3_3F: case BB_ELEMENT_TYPE_TEX4_3F: case BB_ELEMENT_TYPE_TEX5_3F: case BB_ELEMENT_TYPE_TEX6_3F: case BB_ELEMENT_TYPE_TEX7_3F: case BB_ELEMENT_TYPE_TEX8_3F: element.m_bytes = sizeof(float) * 3; break; case BB_ELEMENT_TYPE_IGNORE_2F: case BB_ELEMENT_TYPE_TEX1_2F: case BB_ELEMENT_TYPE_TEX2_2F: case BB_ELEMENT_TYPE_TEX3_2F: case BB_ELEMENT_TYPE_TEX4_2F: case BB_ELEMENT_TYPE_TEX5_2F: case BB_ELEMENT_TYPE_TEX6_2F: case BB_ELEMENT_TYPE_TEX7_2F: case BB_ELEMENT_TYPE_TEX8_2F: element.m_bytes = sizeof(float) * 2; break; default: break; }; if(type == BB_ELEMENT_TYPE_NULL || element.m_bytes <= 0) { return BB_FAIL; } element.m_offset = m_currentStride; m_currentStride += element.m_bytes; m_elements.push_back(element); return BB_SUCCESS; } VertexElement GetElement(int index) { VertexElement element; if(index >= 0 && index < (int)m_elements.size()) { return m_elements[index]; } return element; } int GetTotalElements() { return (int)m_elements.size(); } int GetStride() { return m_currentStride; } private: std::vector<VertexElement> m_elements; int m_currentStride; }; END_ENGINE_NAMESPACE #endif
C++
UTF-8
1,771
2.65625
3
[]
no_license
#pragma once #include "GameObj.h" class Player { public: Player(void); ~Player(void); // some high level objects std::string playerName; std::string scriptName; Logger* logger; GameObj* game; double playerMin; double playerMax; // some high level methods void setGame(GameObj* game); void setPlayerName(std::string playerName); void give(int amt); void report(); int getTotalOnTable(); // what players should implement virtual void play(); virtual void setScriptName(std::string scriptName); // all below methods are used by sub-class players to execute their logic // information about current status double bankRoll; bool justMovedComeBet; bool justEstablishedPoint; bool justSevenedOut; bool justTookDownComeBet; // current bets int passBet; int passOdds; int dontPass; int dontPassOdds; int comeBet; int fieldBet; int place4; int place5; int place6; int place8; int place9; int place10; int come4; int come5; int come6; int come8; int come9; int come10; int come4Odds; int come5Odds; int come6Odds; int come8Odds; int come9Odds; int come10Odds; int hard4; int hard6; int hard8; int hard10; int any7; int anyCraps; int yoBet; int splitCandE; // moves a player can make void placePassBet(int amt); void takePassOdds(int amt); void placeDontPassBet(int amt); void takeDontPassOdds(int amt); void placeComeBet(int amt); void takeComeOddsLastNumber(int amt); void placeFieldBet(int amt); void makePlaceBet(int num, int amt); void makeHardwayBet(int num, int amt); void placeAnySevenBet(int amt); void placeAnyCrapsBet(int amt); void placeYoBet(int amt); void placeSplitCandE(int amt); // get some global game info int getGameState(); int getGamePoint(); int getGameLastNumber(); };
JavaScript
UTF-8
6,844
2.5625
3
[]
no_license
import User from '../helpers/UserHelper'; import bcrypthash from '../helpers/hashPassword'; import jwtToken from '../helpers/jwtToken'; class UserController { /* @param {object} req @param {object} res @returns {object} user object */ static async register(req, res) { const { body } = req; const exist = await User.findOne({query: 'email',data: body.email}); if (exist) { return res.status(409).send({ error: 'Email already exist' }); } const newUser = { names: body.names, email: body.email, } newUser.password = bcrypthash.hashpassword(body.password); newUser.avatar = '/public/avatar/noprofile.png'; const savedUser = await User.create(newUser); if (!savedUser.id || savedUser.id === undefined) { return res.status(500).send({ error: savedUser }); } const payloaad = { id: savedUser.id, email: savedUser.email, names: savedUser.names, }; const token = await jwtToken.createToken(payloaad); return res.status(201).send({ message: 'User created successfully', data: { token, user: { id: savedUser.id, email: savedUser.email, names: savedUser.names, oauthid: savedUser.oauthid, avatar: savedUser.avatar, }, }, }); } /* @param {object} req @param {object} res @returns {object} users array */ static async signin(req, res) { const { body }=req const user = await User.findOne({query: 'email',data: body.email}); if (!user) { return res.status(404).send({ error: 'Email or Password are incorrect' }); } const ispassword = await bcrypthash.comparepassword(req.body.password, user.password); if (!ispassword) { return res.status(404).send({ error: 'Email or Password are incorrect' }); } const payloaad = { id: user.id, email: user.email, names: user.names, }; const token = await jwtToken.createToken(payloaad); return res.status(200).send({ message: 'User is successfully logged in', data: { token, user: { id: user.id, email: user.email, names: user.names, oauthid: user.oauthid, avatar: user.avatar, }, }, }); } /* @param {object} req @param {object} res @returns {object} user object */ static async getAll (req, res) { const users = await User.findAll(); if (!users) { return res.status(200).send({ message: 'users are empty' }); } return res.status(200).send({ data: users.rows }); } /* @param {object} req @param {object} res @returns {object} user object */ static async getOne (req, res) { const user = await User.findOne({query: 'id',data: req.params.id}); if (!user) { return res.status(404).send({ error: 'user not found' }); } const userF = { id: user.id, email: user.email, names: user.names, avatar: user.avatar, oauthid: user.oauthid, createdon: user.createdon, modifiedon: user.modifiedon, } return res.status(200).send(userF); } /* @param {object} req @param {object} res @returns {object} updated user */ static async update(req, res) { const user = await User.findOne({query: 'id',data: req.user.id}); if (!user) { return res.status(404).send({ error: 'user not found' }); } if (user.id !== req.user.id) { return res.status(401).send({ error: 'this acount is not yours' }); } const newData = { email: req.body.email || user.email, names: req.body.names || user.names, password: req.body.password || user.password, }; if (req.body.password) { if (req.body.password !== req.body.re_password) { return res.status(400).send({ error: 're_password must be equal to password' }); } newData.password = bcrypthash.hashpassword(req.body.password); } newData.avatar = user.avatar; const updateduser = await User.update(req.user.id, newData); const userSend = { id: updateduser.id, email: updateduser.email, names: updateduser.names, oauthid: updateduser.oauthid, avatar: updateduser.avatar, modifiedon: updateduser.modifiedon, createdon: updateduser.createdon, }; return res.status(200).send({ message: 'User is successfully updated!', data: userSend }); } /* @param {object} req @param {object} res @returns {void} return statuc code 204 */ static async delete(req, res) { const user = await User.findOne({query: 'id',data: req.user.id}); if (!user) { return res.status(404).send({ error: 'user not found' }); } const ref = await User.delete(req.user.id); return res.status(204).send(ref); } /* @param {object} req @param {object} res @returns {void} return statuc code 204 */ static async gcallback(req, res) { const payloaad = { id: req.user.id, email: req.user.email, names: req.user.names, }; const token = await jwtToken.createToken(payloaad); return res.status(200).send({ message: 'User is successfully logged in', data: { token, user: { id: req.user.id, email: req.user.email, names: req.user.names, oauthid: req.user.oauthid, avatar: req.user.avatar, modifiedon: req.user.modifiedon, createdon: req.user.createdon, }, }, }); } }; export default UserController;
JavaScript
UTF-8
1,071
3
3
[ "MIT" ]
permissive
/*global define */ // Perform a focus operation (focus) on the element specified by query value. define("focus", ["triggerEvent", "result"], function(trigger, result) { "use strict"; var regex = /^focus\s*\(\s*(?:")([^"]+)(?:")\s*\)$/i; // Perform a focus operation. function focus (jq, query, context) { return trigger.execute(jq, query, context, "focus"); } function canHandle (statement, context) { return regex.test(statement); } // Handle intepreting the focus operation. function handleFocus (jq, statement, context) { var success, matches = regex.exec(statement); if(!matches) { return result.NOT_HANDLED; } success = focus(jq, matches[1], context); return success ? result.HANDLED : result.NOT_HANDLED; } function usage () { return 'Usage: focus("query"); Sets the focus to be on an element specified by query. If more than one element matches query then uses the first.'; } return { handle: handleFocus, canHandle: canHandle, execute: focus, toString: usage }; });
Java
UTF-8
270
2.671875
3
[]
no_license
import java.util.Scanner; public class a044 { public static void main(String [] argv) { Scanner cin = new Scanner(System.in); while (cin.hasNext()) { int n = cin.nextInt(); System.out.println(n*(n*n+5)/6+1); } } }
Java
UTF-8
1,231
2.375
2
[]
no_license
package pages; import wrappers.LinkedInWrappers; public class LinkedInAdvancedSearchPage extends LinkedInWrappers { public LinkedInAdvancedSearchPage enterKeywords(String data) { enterById(prop.getProperty("Advanced.KeyWord.Id"), data); return this; } public LinkedInAdvancedSearchPage clickSubmit() { clickByClassName(prop.getProperty("submit-advs")); return this; } public LinkedInAdvancedSearchPage getCount(){ removeComma(prop.getProperty("Advanced.ResultCount1.Xpath")); return this; } public LinkedInAdvancedSearchPage getFirstConnection(){ getTextByXpath(prop.getProperty("Advanced.Name.Xpath")); return this; } public LinkedInAdvancedSearchPage getActualConnection(){ getTextByXpath(prop.getProperty("Advanced.Connection.Xpath")); return this; } public LinkedInAdvancedSearchPage closeFrame(){ clickByXpath(prop.getProperty("Advanced.Closed.Xpath")); return this; } public LinkedInAdvancedSearchPage closeconnection(){ clickByXpath(prop.getProperty("Advanced.CloseConnection.Xpath")); return this; } public String removeComma (String xpathVal) { String value =driver.findElementByXPath(xpathVal).getText().replace(",",""); System.out.println("Count of Connections: " + value); return value; } }
Markdown
UTF-8
3,677
3.265625
3
[]
no_license
--- layout: post title: Using HttpClient To Post JSON In C# & .NET date: 2022-08-01 12:11:42 +0300 categories: - C# - .NET --- For a long time if you wanted to post JSON using a [HttpClient](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0), you would do it like this: ```csharp // Create the HttpClient var client = new HttpClient(); // Set the base address to simplify maintenance & requests client.BaseAddress = new Uri("https://localhost:5001/"); // Create an object var person = new Person() { Names = "James Bond", DateOfBirth = new DateTime(1990, 1, 1) }; // Serialize class into JSON var payload = JsonSerializer.Serialize(person); // Wrap our JSON inside a StringContent object var content = new StringContent(payload, Encoding.UTF8, "application/json") // Post to the endpoint var response = await client.PostAsync("Create", content); ``` The `Person` object we are submitting here is this one: ```csharp public class Person { public string Names { get; set; } public DateTime DateOfBirth { get; set; } } ``` The code here relies of the fact that to do a `POST` to a [HttpClient](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0), it expects a [StringContent](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.stringcontent?view=net-6.0) object that you have to construct in advance. This is very tedious. Which is why you can use the extensions in the `System.Net.Http.Json` namespace to simplify this. The extension method we can employ here is [PostAsJsonAsync](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions.postasjsonasync?view=net-6.0). ![](../images/2022/08/HttpClientJson.png) This extension method does the heavy lifting of accepting your object and serializing it for posting to the target URL. This is achieved like so: ```csharp // Create a second person var otherPerson = new Person() { Names = "Jason Bourne", DateOfBirth = new DateTime(2000, 1, 1) }; // Post to the endpoint response = await client.PostAsJsonAsync("Create", otherPerson); ``` The code is thus vastly simplified. There is also an overload that allows you to pass a [CancellationToken](https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=net-6.0). ```csharp // Post to the endpoint with a cancellation token response = await client.PostAsJsonAsync("Create", otherPerson, ctx); ``` If your upstream API is very conservative about the JSON it accepts, or has some non-default configurations, you can configure how you want the serialization of your object to be done using a [JsonSerializerOptions](https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions?view=net-6.0) object. Like so: ```csharp // Configure required JSON serialization options var options = new JsonSerializerOptions() { AllowTrailingCommas = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, IgnoreReadOnlyProperties = true, NumberHandling = JsonNumberHandling.WriteAsString, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true }; // Post to the endpoint with custom options response = await client.PostAsJsonAsync("Create", otherPerson, options); ``` The beauty of this is that for most simple cases you can use the `HttpClient` directly and not have to depend on libraries like [Refit](https://github.com/reactiveui/refit), [RestSharp](https://restsharp.dev/) and [Flurl](https://flurl.dev/) The code is in my [Github](https://github.com/conradakunga/BlogCode/tree/master/2022-08-01%20-%20Posting%20JSON%20Using%20HttpClient). Happy hacking!
Java
UTF-8
1,757
4.375
4
[]
no_license
/* Date : 2020.05.08 Author : eunji Description : Java_변수 Version : 1.0 */ package java0508; public class ex02_변수 { public static void main(String[] args) { // 변수 : 프로그램 실행에 필요한 데이터를 저장하기 // 위해 메모리 공간을 할당하고, 이름을 부여한것 // var num = 0; // [변수타입] [변수명] = [변수값]; int age = 35; int age1; // 변수선언 age1 = 35; // 변수초기화 int age2=11, age3=12, age4=13; age1 = 10; System.out.println("age1" + age1); // 위에서 35로 선언했지만 초기화가 됬고, // 마지막 남은 10만 값으로 출력된다. // 변수타입 1byte 2byte 4byte 8byte // 1. 정수형 (byte, short, int, iong) // 2. 실수형 (float, double) // 3. 문자형 (char) // 4. 논리형 (boolean) // byte // 1byte = 8bit // 1byte = -2^7 ~ (2^7)-1 byte bNum1 = -128; byte bNum2 = 127; // short // 2byte = 16bit // 2byte = -2^15 ~ (2^15)-1 short sNum1 = -32768; short sNum2 = 32767; // 4byte = 32bit // 4byte = 2^31 ~ (2^31)-1 // int : -2,147,483,648 ~ 2,147,483,647 int iNum1 = -129; int iNum2 = 128; // long : 매우크다 // 8byte = 64bit long lNum1 = -2147483648L; // 변수값에는 L을 썻지만 출력에는 나오지 않는다. long lNum2 = 2148483648L; System.out.println(lNum1); System.out.println(lNum2); // 실수형 // float(4byte), double(8byte) // double > float float pi1 = 3.14f; double pi2 = 3.14; // 대ㆍ소문자 가능하지만 아래와 같이 사용하기! // long은 L 추가 (대문자) // float는 f 추가 (소문자) } }
C++
UTF-8
1,290
2.984375
3
[]
no_license
#include "Sample.h" #include <iostream> Sample::Sample(void) { } Sample::~Sample(void) { } int Sample::load(string path) { if (! (sf_infile = sf_open (path.c_str(), SFM_READ, &sf_info))) { // failed to load cout << "Failed to load audio" << endl; cout << sf_strerror(NULL) << endl; return 1; } else { cout << "Opened file: " << path << endl; cout << "Channels: " << sf_info.channels << endl; cout << "Format: " << sf_info.format << endl; cout << "Sample rate: " << sf_info.samplerate << endl; // read audio file int read_count; float * buf = new float[sf_info.channels * FRAMESIZE]; length = 0; data.clear(); while ((read_count = sf_readf_float(sf_infile, buf, FRAMESIZE)) > 0) { for (int i=0; i<read_count * sf_info.channels; i++) { data.push_back(buf[i]); length++; } } delete[] buf; position = 0; isLooping = true; return 0; } } float Sample::play() { if (!(position < length)) if(isLooping) { position=0; } else { return 0; } float val = data[position]; position++; return val; } int Sample::getNumChannels() { return sf_info.channels; } int Sample::getSampleRate() { return sf_info.samplerate; } void Sample::setLooping(bool loop) { isLooping = loop; }
C++
UTF-8
2,633
3.34375
3
[]
no_license
/* * @lc app=leetcode.cn id=547 lang=cpp * * [547] 朋友圈 */ // @lc code=start class UnionFind { public: int length; vector<int> parent; vector<int> size; UnionFind(const int num) { length = num; for(int i = 0;i < num;++i) { parent.push_back(i); size.push_back(1); } } int Find(int x) { while(parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; } void Union(int p,int q) { int proot = Find(p); int qroot = Find(q); if(proot == qroot) return; if(size[proot] > size[qroot]) { parent[qroot] = proot; size[proot] += size[qroot]; } else { parent[proot] = qroot; size[qroot] += size[proot]; } --length; } bool Connected(int p,int q) { return Find(p) == Find(q); } int Length() { return length; } }; class Solution { public: // 因为矩阵为对称矩阵,所以并没有使用四方向数组 // 这个DFS方法也是很好的,深度判断即可 void DFS(vector<vector<int>>& grid,int row,vector<bool>& dp) { for(int i = 0;i < grid.size();++i) { if(grid[row][i] && !dp[i]) { dp[i] = true; DFS(grid,i,dp); } } } int DFSGMT(vector<vector<int>>& M) { //DFS int count = 0; int rows = M.size(); vector<bool> dp(rows,false); for(int i = 0;i < rows;++i) { if(!dp[i]) { ++count; DFS(M,i,dp); } } return count; } int UnionGMT(vector<vector<int>>& M) { int num = M.size(); UnionFind* uf = new UnionFind(num); for(int i = 0;i < num;++i) { for(int j = 0;j < i;++j) { if(M[i][j]) uf->Union(i,j); } } return uf->Length(); } int findCircleNum(vector<vector<int>>& M) { //return UnionGMT(M); return DFSGMT(M); } }; // @lc code=end
Markdown
UTF-8
1,417
3.0625
3
[]
no_license
# FM-Synthesis-Project This repository contains MATLAB files used to simulate the instrument diagrams shown in "The Synthesis of Complex Audio Spectra by Means of Frequency Modulation* JOHN M. CHOWNING " This was created and tested as part of the Project component of EC5.203 Communication Theory, Spring 2021, IIIT Hyderabad. ## Category of Files: ### 1) Trial_\<type_of_instument\>.m These files directly simulate and play the sound as given in the name and the amplitude and frequency spectrum will be plotted ### 2) Block.m This file contains the main function Block() which is used to simulate any unit generator. It takes in input like so ``` x = Block(freq,ampl,string,dur); ``` frequency and amplitude are used to create sinusoids and the variable string contains the type of intrument, and dur is the duration of the sound to be generated ### 3) BrassPlayer.m Given a string of notes, it uses the function Notes2Hz.m to play a Brass generated audio clip. Each note plays for 0.6 seconds. ### 4) x\<type_of_instrument\>.m These functions generate the amplitude or instantaneous frequency deviation plots/vectors ### 5) Miscellaneous trial.m was used for experimentation \ vecProd.m was used in the implementation of the Block function. \ Notes2Hz.m used in BrassPlayer.m to convert a string of notes to just frequencies \ Output.m was used to plot out and play the different audi files generated.
Markdown
UTF-8
777
3.203125
3
[]
no_license
# 基础知识 - 父组件监听子组件的生命周期 1. 使用 𝑜𝑛 和 emit : 子组件 𝑒𝑚𝑖𝑡 触发一个事件,父组件 on 监听相应事件 ```js // Parent.vue <Child @mounted="doSomething"/> // Child.vue mounted() { this.$emit("mounted"); } ``` 2. hook 钩子函数 ```js // Parent.vue <Child @hook:mounted="doSomething" ></Child> doSomething() { console.log('父组件监听到 mounted 钩子函数 ...'); }, // Child.vue mounted(){ console.log('子组件触发 mounted 钩子函数 ...'); }, // 以上输出顺序为: // 子组件触发 mounted 钩子函数 ... // 父组件监听到 mounted 钩子函数 ... ```
Markdown
UTF-8
4,887
2.59375
3
[ "MIT" ]
permissive
[![MIT License][license-shield]][license-url] [![LinkedIn][linkedin-shield]][linkedin-url] <p align="center"> <h3 align="center">Human Pose Detection - Machine Model Training</h3> <h5 align="center">(This repo consists the source code of a machine model training tool.)</h5> <p align="center"> <a href="https://2021creatives.s3.eu-central-1.amazonaws.com/March/PoseDetectionExample/index.html">Demo Project (The Machine model has been trained using this repo)</a> · <a href="https://github.com/ahmettekeli/HumanPoseDetection/issues">Report Bug</a> · <a href="https://github.com/ahmettekeli/HumanPoseDetection/issues">Request Feature</a> </p> </p> ## About The Project <!-- [![Product Name Screen Shot][product-screenshot]](live demo link goes here) --> <p>This is a sample Human Pose Detection project developed using <a href="https://learn.ml5js.org/#/reference/posenet">ml5.js PoseNet</a>. Custom machine model can be trained for the recognition of custom human poses. (Hands up, squat etc.)</p> <p>In order to train a machine model, there should be raw data collected. When there is raw data ready, we can proceed to train a machine model from that data. Once the training is complete the machine model can be downloaded and consumed in any application.</p> <p>Machine model training should be done with the buttons below the video element. <strong>Pose Label</strong> saves the name of the pose. Make sure you enter a valid name before starting the training for your desired human pose. <strong>Collect Data</strong> button starts the data collection for a specific human pose and snap shots the body composition in the video constantly for <strong>20</strong> seconds and collects raw image data. Data collection has <strong>5</strong> seconds delay to give you enough time to be ready in front of the camera. <strong>Status</strong> header will have informative directives.</p> Multiple human poses can be trained using <strong>Collect Data</strong> button. Make sure you enter <strong>Pose Label</strong> for each pose you want to train the machine model for. Once data collection is done for each human pose you want, click <strong>Train</strong> button to train a machine model from the raw image data. It will open up a side bar to show the machine model training progress. Once it is finished, click <strong>Save Machine Model</strong> button to download the machine model you trained with your desired human poses. Now you have a custom machine model which will recognize the human poses you train it for. Feel free to build fun things with it and let me know what you build. ### Prerequisites The tools/software below are needed to build/extend this project. - [node](https://nodejs.org/en/) - npm ```sh npm install npm@latest -g ``` ### Bundled with - [Babel](https://babeljs.io/) - [Webpack](https://webpack.js.org/) ### Editing/Extending/Usage 1. Clone the repo ```sh git clone https://github.com/ahmettekeli/HumanPoseDetection.git ``` 2. Install NPM packages ```sh npm install ``` 3. Make changes and bundle the project with webpack/babel ```sh npm run build ``` Make sure you have devdependencies in package.json installed and have a "build" config under scripts section in package.json with the following config ```js "build": "webpack --config webpack.config.js" ``` webpack.config.js file with the following configs ```js const path = require("path"); module.exports = { mode: "development", entry: "./src/app.js", output: { path: path.resolve(__dirname, "dist"), filename: "app.bundle.js", }, module: { rules: [ { exclude: "/node_modules/", loader: "babel-loader", }, ], }, }; ``` ## Contributing Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are <strong>greatly appreciated<strong>. 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request ## License Distributed under the MIT License. See `LICENSE` for more information. ## Contact Ahmet Tekeli - [@ahmettekeli3](https://twitter.com/ahmettekeli3) - ahmettekeli1991@hotmail.com Project Link: [https://github.com/ahmettekeli/HumanPoseDetection](https://github.com/ahmettekeli/HumanPoseDetection) [license-shield]: https://img.shields.io/github/license/othneildrew/Best-README-Template.svg?style=flat-square [license-url]: https://github.com/ahmettekeli/HumanPoseDetection/blob/master/license.txt [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=flat-square&logo=linkedin&colorB=555 [linkedin-url]: https://www.linkedin.com/in/tekeliahmet/ [product-screenshot]: https://github.com/ahmettekeli/HumanPoseDetection/
Java
UTF-8
920
1.921875
2
[]
no_license
package com.bpm.lj.mes.base.server.mapper.base; import com.bpm.lj.mes.base.server.domain.BaseShift; import com.bpm.lj.mes.base.server.domain.BaseShiftExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface BaseShiftMapper { long countByExample(BaseShiftExample example); int deleteByExample(BaseShiftExample example); int deleteByPrimaryKey(Integer id); int insert(BaseShift record); int insertSelective(BaseShift record); List<BaseShift> selectByExample(BaseShiftExample example); BaseShift selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") BaseShift record, @Param("example") BaseShiftExample example); int updateByExample(@Param("record") BaseShift record, @Param("example") BaseShiftExample example); int updateByPrimaryKeySelective(BaseShift record); int updateByPrimaryKey(BaseShift record); }
JavaScript
UTF-8
4,269
2.625
3
[]
no_license
// change everytime // ===================== var driveTableNames = [ { long: "National Regional Profile, Population, ASGS, 2007-2011", short: "1NZqM7xmjpXLlyBoryjnrOuiKw56FxuJ3tc_zGAVD", time: "At 30 June - Labels", geo: "Regional Code - Codes" }, { long: "National Regional Profile, Industry, ASGS, 2007-2011", short: "1DhCZ70s6Zb2sVwy3U7cAj01pkZ_PO8F1wS44iaeW", time: "Calendar Year - Labels", geo: "Geography - Codes" }, { long: "National Regional Profile, Environment, ASGS, 2007-2011", short: "1WZX7wwo6WfBpJ8k47B_GVz7gIngsEvsbNrp6qtR6", time: "Year - Labels", geo: "Geography - Codes" }, { long: "National Regional Profile, Economy, ASGS, 2007-2011", short: "1gB66u4yU-Jc7Q9m8oYtkr5VPf_f5gE0os4fTrMRa", time: "Year - Labels", geo: "Geography - Codes" }, { short: '18l-HtesdNTcjlkp6hd_e_WmH8gJEdY7yxNBNS7Bk', long: 'National Regional Profile, Population, ASGS, 2008-2012', time: "Year - Labels", geo: "Geography - Codes" }, ]; var tableNames = $('#tableName'); var filterInput = tableNames.find('.filter'); tableNames.on('click', function(){ filterInput.trigger('focus'); }); // return rendered and filterd data to be set as inner html of resultsDiv var filterRender = function(){ var re = new RegExp(filterInput.val(), 'i'); var markup = ''; for (var i = 0; i < driveTableNames.length; i++) { if (re.test(driveTableNames[i].long)){ markup += '<div class="result" data-i="'+ i +'">'+ driveTableNames[i].long + '</div>'; } }; return markup; } // ==================== var colName = $('#columnName'); var colFilterInput = colName.find('.filter'); var driveColNames; // make sure you initialise prior to calling make_autocomplete colName.on('click', function(){ colFilterInput.trigger('focus'); }); // return rendered and filterd data to be set as inner html of resultsDiv var colFilterRender = function(){ var re = new RegExp(colFilterInput.val(), 'i'); var markup = ''; for (var i = 0; i < driveColNames.length; i++) { if (re.test(driveColNames[i].name)){ markup += '<div class="result" data-i="'+ i +'">'+ driveColNames[i].name + '</div>'; } }; return markup; } // change sometimes // ===================== function make_autocomplete(filterInput, resultsDiv, filterRender, chosen){ function renderResults(results){ // render list resultsDiv.html(filterRender()); resultsDiv.find(':first').addClass('active'); // mouse navigation listeners resultsDiv.children().off('mouseenter'); resultsDiv.children().on('mouseenter', function(){ resultsDiv.find('.active').removeClass('active'); $(this).addClass('active'); } ); } var chosen_i = 0; filterInput.off('blur'); filterInput.on('blur', function(){ chosen(chosen_i); resultsDiv.off('click'); resultsDiv.hide(); }); filterInput.off('focus'); filterInput.on('focus', function(e){ resultsDiv.show(); this.setSelectionRange(0, this.value.length); renderResults(); var current; filterInput.off('keyup'); filterInput.on('keyup', function(e){ switch(e.keyCode){ case 38: // up current = resultsDiv.find('.active'); if (!current.is(':first-child')) current.removeClass('active').prev().addClass('active'); break; case 40: // down current = resultsDiv.find('.active'); if (!current.is(':last-child')) current.removeClass('active').next().addClass('active'); break; case 13: // enter chosen_i = resultsDiv.find('.active').attr('data-i'); filterInput.trigger('blur'); break; // case 9: // tab // break; case 27: // escape filterInput.trigger('blur'); break; default: renderResults( ); } }); resultsDiv.off('mousedown'); // fires before blur, click fires after resultsDiv.on('mousedown', function(){ chosen_i = resultsDiv.find('.active').attr('data-i'); filterInput.trigger('blur'); }); }); }
Markdown
UTF-8
1,946
3.1875
3
[ "MIT" ]
permissive
### MicroWorkers is a class that easily manages a pool of threads to optimise simultaneous jobs and jobs endings, for MicroPython (used on ESP32 and [Pycom](http://www.pycom.io) modules) ![HC²](hc2.png "HC²") Very easy to integrate and very light with one file only : - `"microWorkers.py"` Simple but effective : - Use it to create a multitasking jobs container - Add jobs without blocking your main code - Be alerted by an event when a job has finished ### Using *microWorkers* class : | Name | Function | | - | - | | Constructor | `workers = MicroWorkers(workersCount, workersStackSize=0)` | | Adds a job | `workers.AddJob(name, function, arg=None, onFinished=None)` | | Gets workers count | `workers.Count()` | ### Simple example : ```python from microWorkers import MicroWorkers from time import sleep def sleepJob(jobName, jobArg) : sleep(10) return True # workersStackSize must be greater than or equal to 4096 (4KB) # it can be equal to 0 to use the default stack size workers = MicroWorkers(workersCount=5, workersStackSize=10*1024) for i in range(5) : workers.AddJob('Job %s' % i, sleepJob) ``` ### Example of using multiple jobs (with finished event) : ```python from microWorkers import MicroWorkers from time import sleep print() def jobTest1(jobName, jobArg) : sleep(1) return '%s:OK:1s' % jobName def jobTest2(jobName, jobArg) : sleep(3) return '%s:OK:3s' % jobName def jobTest3(jobName, jobArg) : sleep(5) return '%s:OK:5s' % jobName def jobFinished(jobName, jobArg, jobResult) : print('Job %s finished (%s)' % (jobName, jobResult)) workers = MicroWorkers(workersCount=3) for x in range(5) : workers.AddJob('Test1', jobTest1, arg=None, onFinished=jobFinished) workers.AddJob('Test2', jobTest2, arg=None, onFinished=jobFinished) workers.AddJob('Test3', jobTest3, arg=None, onFinished=jobFinished) ``` ### By JC`zic for [HC²](https://www.hc2.fr) ;') *Keep it simple, stupid* :+1:
C++
UTF-8
269
3.1875
3
[]
no_license
#include <iostream> #include <typeinfo> int main() { int n1{10}; auto n2 = n1; const std::type_info& t1 = typeid(n2); std::cout << t1.name() << std::endl; typeid(3 + 4.2); //이런것도 가능 /**typeid는 type_info를 리턴하는 연산자이다.*/ }
C#
UTF-8
1,530
2.8125
3
[ "CC-BY-4.0", "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
// <copyright file="VegaOperationDataStream.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> namespace Microsoft.Vega { using System; using System.Collections.Generic; using System.Fabric; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// Data stream for exchanging data between primary and secondaries. /// </summary> public class VegaOperationDataStream : IOperationDataStream { private readonly long lsn; private long sequence; /// <summary> /// Initializes a new instance of the <see cref="VegaOperationDataStream"/> class. /// </summary> /// <param name="lsn">Logical sequence number.</param> public VegaOperationDataStream(long lsn) { this.lsn = lsn; this.sequence = 1L; // starting from 1, not 0. } /// <inheritdoc /> public Task<OperationData> GetNextAsync(CancellationToken cancellationToken) { return Task.Run<OperationData>( async () => { if (this.sequence > this.lsn) { return null; } await Task.Yield(); var opData = new OperationData(BitConverter.GetBytes(this.sequence++)); return opData; }); } } }
Markdown
UTF-8
988
2.78125
3
[]
no_license
# Wheelchair pressure mat ESP3903 project @ NUS Authors: * Jasdip Chauhan * Keith Daigle * Sam Yuyitung Code to support a capacitor based pressure sensor matrix ## Arduino Code [file](muxCode/muxCode.ino) This code cycles through and outputs the 16 capacitance values in picoFarads This code is based off the [Capacitive Meter](https://www.arduino.cc/en/Tutorial/CapacitanceMeter) example from the Arduino website The ordering of the output array is key: (mux #).(mux input #) ``` 1.1,1.2,1.3,1.4;1.5,1.6,1.7,1.8;2.1,2.2,2.3,2.4;2.5,2.6,2.7,2.8(\n) ``` This value is written to the serial and can be consumed by other applications ## Heatmap code [file](heatmap.pde) This is built with [Processing](https://processing.org). When building make sure that you update the Serial port accordingly to match the one that the Arduino is running off. This program maps the each capacitance to an appropriate colour. Adjusting the MIN_CAP and MAX_CAP can allow you to work with you capacitive sensors!!
Java
UTF-8
2,992
3.59375
4
[]
no_license
package org.eve.framework.other; /** * 颠倒二进制位 * 颠倒给定的 32 位无符号整数的二进制位。 * https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/26/others/66/ * <p> * 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。 * 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825。 * * @author jc * @date 2019/9/24 1:33 */ public class ReverseBits { public static void main(String[] args) { /* 输入: 00000010100101000001111010011100 输出: 00111001011110000010100101000000 解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596, 因此返回 964176192,其二进制表示形式为 00111001 01111000 00101001 01000000。 00111001 01111000 00101001 01000000 1928352384 */ System.out.println(0b00111001011110000010100101000000); System.out.println(new ReverseBits().reverseBits(0b00000010100101000001111010011100)); System.out.println("-------------------------------------"); System.out.println(0b11111111111111111111111111111101); System.out.println(new ReverseBits().reverseBits(0b11111111111111111111111111111101)); System.out.println("-------------------------------------"); /* 输入:10010110111001001101001111110101 输出:3493124245 (11010000001101001101100010010101) 预期:2949326697 (10101111110010110010011101101001) */ System.out.println(0b10010110111001001101001111110101); System.out.println(0b10101111110010110010011101101001); System.out.println(new ReverseBits().reverseBits(0b10010110111001001101001111110101)); System.out.println("-------------------------------------"); } // you need treat n as an unsigned value public int reverseBits(int n) { int divisor, remainder, x = 30, result = 0; boolean f = false; if (n < 0) { n = -n; // n = ~(n - 1); System.out.println(n); f = true; // result--; } do { divisor = n / 2; remainder = n % 2; if (remainder != 0) { result = (2 << x) + result; } System.out.print(remainder); x--; n = divisor; } while (n > 0); for (int i = 0; i <= x; i++) { System.out.print(0); } System.out.println(); /* if (f) { return (~(-result)) + 1; } */ return result; } }
C++
UTF-8
1,514
3.265625
3
[]
no_license
/* * File.cpp * * Created on: Jun 5, 2017 * Author: user */ #include "File.h" namespace networkingLab { File::File(const std::string& path) { this->path = path; } File::~File() { } void File::close() { ::close(fd); } int File::read(char* buffer, size_t length) { size_t offset = 0; size_t bytes_read; /* Open the file for reading. */ fd = open (path.c_str(), O_RDONLY); /* Read from the file, one chunk at a time. Continue until read "comes up short", that is, reads less than we asked for. This indicates that we've hit the end of the file. */ do { /* Read the next line's worth of bytes. */ bytes_read = ::read(fd, buffer, length); /* Keep count of our position in the file. */ offset += bytes_read; } while (bytes_read == sizeof (buffer)); /* All done. */ return bytes_read; } int File::append(const std::string& msg) { /* Open the file for writing. If it exists, append to it; otherwise, create a new file. */ fd= ::open(path.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666); /* Write the timestamp to the file. */ ::write(fd, msg.c_str(), msg.length()); return 1; } int File::write(const std::string& msg) { /* Open the file for writing. If it exists, append to it; otherwise, create a new file. */ fd= ::open(path.c_str(), O_WRONLY | O_CREAT , 0666); /* Write the timestamp to the file. */ ::write(fd, msg.c_str(), msg.length()); return 1; } } /* namespace networkingLab */
Java
UTF-8
975
2.15625
2
[]
no_license
package com.curso.resources; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.curso.entities.Produtos; import com.curso.services.ProdutoService; @RestController @RequestMapping(value = "/produtos") public class ProdutosResource { @Autowired private ProdutoService service; @GetMapping public ResponseEntity <List<Produtos>> findAll(){ List<Produtos> list = service.findAll(); return ResponseEntity.ok().body(list); } @GetMapping(value="/{id}") public ResponseEntity <Produtos> findById(@PathVariable Long id){ Produtos obj = service.findById(id); return ResponseEntity.ok().body(obj); } }
Shell
UTF-8
2,143
3.328125
3
[]
no_license
#!/bin/bash echo $0 | logger echo `pwd` | logger JMARECEIPT_ENV="/etc/jma-receipt/jma-receipt.env" if [ ! -f ${JMARECEIPT_ENV} ]; then echo "${JMARECEIPT_ENV} does not found." exit 1 fi . $JMARECEIPT_ENV PATH=.:${PATH} # compile COBOL programs COBMEM=`module CBL` for f in ${COBMEM}; do if test "x`echo -n $f | grep 'CBL$'`" != "x"; then m=`echo $f | sed 's/CBL$/so/'` echo -n "Building ${m}..." | logger ${COBOL} ${COBOLFLAGS} -o ${SITELIBDIR}/${m} \ -I ${PATCHCOPYDIR} \ -I ${COPYDIR} \ -I ${SITESRCDIR}/cobol/copy \ ${SITESRCDIR}/cobol/${f} if [ $? -ne 0 ]; then ./prerm exit 1 fi fi done # copy scripts file SCRIPTMEM=`module scripts` for f in ${SCRIPTMEM}; do if test -f "${SITESRCDIR}/${f}"; then echo -n "Copying ${SITESRCDIR}/${f}..." | logger sed -e 's,\@jma-receipt-env\@,/etc/jma-receipt/jma-receipt.env,g' \ < "${SITESRCDIR}/${f}" > "${SITEDIR}/${f}" chmod +x "${SITEDIR}/${f}" if [ $? -ne 0 ]; then ./prerm exit 1 fi fi done echo "done" # copy lddef file LDDEFMEM=`module lddef` for f in ${LDDEFMEM}; do if test -f "${SITESRCDIR}/${f}"; then echo -n "Copying ${SITESRCDIR}/${f}..." | logger $CPP -I"${LDDEFDIR}" -x c "${SITESRCDIR}/${f}" > "${SITEDIR}/${f}" if [ $? -ne 0 ]; then ./prerm exit 1 fi fi done echo "done" # copy data files for d in data doc form init record screen ; do m=`module ${d}` for f in ${m}; do if test -f "${SITESRCDIR}/${f}"; then echo -n "Copying ${SITESRCDIR}/${f}..." | logger cp -p "${SITESRCDIR}/${f}" "${SITEDIR}/${d}" if [ $? -ne 0 ]; then ./prerm exit 1 fi fi done done echo "done" #modify kentan.inc if test -f ./kentan.inc; then PREF=`cat ./kentan.inc` echo -n "Modifying kentan.inc files... ${PREF}" | logger cp ${SYSCONFDIR}/kentan.inc /tmp/kentan.inc.bak sed "/${PREF}/d" /tmp/kentan.inc.bak > ${SYSCONFDIR}/kentan.inc rm -rf /tmp/kentan.inc.bak echo -e "\t${PREF};" >> ${SYSCONFDIR}/kentan.inc if [ $? -ne 0 ]; then ./prerm exit 1 fi echo "done" fi
Java
UTF-8
1,204
2.34375
2
[ "Apache-2.0" ]
permissive
package com.provectus.fds.flink.schemas; import com.provectus.fds.models.bcns.WalkinClick; import com.provectus.fds.models.utils.JsonUtils; import org.apache.flink.api.common.serialization.DeserializationSchema; import org.apache.flink.api.common.serialization.SerializationSchema; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.typeutils.TypeExtractor; import java.io.IOException; public class WalkinClickSchema implements SerializationSchema<WalkinClick>, DeserializationSchema<WalkinClick> { @Override public byte[] serialize(WalkinClick walkinClick) { try { return JsonUtils.write(walkinClick); } catch (Exception e) { throw new RuntimeException("Error during WalkinClick serialization", e); } } @Override public WalkinClick deserialize(byte[] bytes) throws IOException { return JsonUtils.read(bytes, WalkinClick.class); } @Override public boolean isEndOfStream(WalkinClick walkinClick) { return false; } @Override public TypeInformation<WalkinClick> getProducedType() { return TypeExtractor.getForClass(WalkinClick.class); } }
Python
UTF-8
15,404
2.671875
3
[ "BSD-3-Clause" ]
permissive
from discord.ext import commands import discord.utils from .utils import config, formats import json, re from collections import Counter class DefaultProfileType: def __str__(self): return 'me' MyOwnProfile = DefaultProfileType() class MemberParser: """ Lazily fetches an argument and then when asked attempts to get the data. """ def __init__(self, argument): self.argument = argument.strip() self.regex = re.compile(r'<@\!?([0-9]+)>') def member_entry(self, tup): index = tup[0] member = tup[1] return '{0}: {1} from {1.server.name}'.format(index, member) def has_potential_discriminator(self): return len(self.argument) > 5 and self.argument[-5] == '#' def get_server_members(self, server): if self.has_potential_discriminator(): discrim = self.argument[-4:] direct = discord.utils.get(server.members, name=self.argument[:-5], discriminator=discrim) if direct is not None: return { direct } return { m for m in server.members if m.display_name == self.argument } async def get(self, ctx): """Given an invocation context, gets a user.""" server = ctx.message.server bot = ctx.bot # check if the argument is a mention m = self.regex.match(self.argument) if m: user_id = m.group(1) if server: return server.get_member(user_id) # get the first member found in all servers with the user ID. gen = filter(None, map(lambda s: s.get_member(user_id), bot.servers)) return next(gen, None) # it isn't, so search by name if server: results = self.get_server_members(server) else: results = set(filter(None, map(lambda s: s.get_member_named(self.argument), bot.servers))) results = list(results) if len(results) == 0: # we have no matches... so we must return None return None if len(results) == 1: # we have an exact match. return results[0] # no exact match msg = ctx.message member = await formats.too_many_matches(bot, msg, results, self.member_entry) return member class Weapon: def __init__(self, **kwargs): self.__dict__ = kwargs def __str__(self): return self.name class ProfileInfo: def __init__(self, **kwargs): self.nnid = kwargs.get('nnid') self.rank = kwargs.get('rank') self.squad = kwargs.get('squad') if 'weapon' in kwargs: weapon = kwargs['weapon'] if weapon is not None: self.weapon = Weapon(**weapon) else: self.weapon = None else: self.weapon = None def __str__(self): output = [] output.append('NNID: {0.nnid}'.format(self)) output.append('Rank: {0.rank}'.format(self)) output.append('Squad: {0.squad}'.format(self)) if self.weapon is not None: output.append('Weapon: {0.name} ({0.sub} with {0.special})'.format(self.weapon)) else: output.append('Weapon: None') return '\n'.join(output) class ProfileEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, ProfileInfo): payload = obj.__dict__.copy() payload['__profile__'] = True return payload if isinstance(obj, Weapon): return obj.__dict__ return json.JSONEncoder.default(self, obj) def profile_decoder(obj): if '__profile__' in obj: return ProfileInfo(**obj) return obj class Profile: """Profile related commands.""" def __init__(self, bot): self.bot = bot self.config = config.Config('profiles.json', encoder=ProfileEncoder, object_hook=profile_decoder) self.valid_ranks = { 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+', 'S', 'S+' } async def get_profile(self, ctx, parser): try: if parser is MyOwnProfile: member = ctx.message.author else: member = await parser.get(ctx) except commands.CommandError as e: await self.bot.say(e) return if member is None: await self.bot.say('Member not found. Note that this is case sensitive. You can use a mention instead.') return profile = self.config.get(member.id) if profile is None: if parser is not MyOwnProfile: await self.bot.say('This member did not set up a profile.') else: await self.bot.say('You did not set up a profile. One has been created for you.') await self.config.put(member.id, ProfileInfo()) await ctx.invoke(self.make) else: fmt = 'Profile for **{0.name}#{0.discriminator}**:\n{1}' await self.bot.say(fmt.format(member, profile)) @commands.group(pass_context=True, invoke_without_command=True) async def profile(self, ctx, *, member : MemberParser = MyOwnProfile): """Manages your profile. If you don't pass in a subcommand, it will do a lookup based on the member passed in. Similar to the profile get subcommand. If no member is passed in, you will get your own profile. All commands will create a profile for you with no fields set. """ await self.get_profile(ctx, member) @profile.command(pass_context=True) async def get(self, ctx, *, member : MemberParser = MyOwnProfile): """Retrieves either your profile or someone else's profile. You can retrieve a member's profile either by mentioning them or by passing in the case-sensitive name of the user. If too many members are found then the bot will ask you which one you want. """ await self.get_profile(ctx, member) async def edit_field(self, attr, ctx, data): user_id = ctx.message.author.id profile = self.config.get(user_id, ProfileInfo()) setattr(profile, attr, data) await self.config.put(user_id, profile) await self.bot.say('Field {} set to {}.'.format(attr, data)) @profile.command(pass_context=True) async def nnid(self, ctx, *, NNID : str): """Sets the NNID portion of your profile. If you don't have a profile set up then it'll create one for you. """ nid = NNID.strip('"') if len(nid) > 16: await self.bot.say('An NNID has a maximum of 16 characters.') return await self.edit_field('nnid', ctx, nid) @profile.command(pass_context=True) async def rank(self, ctx, rank : str): """Sets the Splatoon rank part of your profile. If you don't have a profile set up then it'll create one for you. """ rank = rank.upper() if rank not in self.valid_ranks: await self.bot.say('That is not a valid Splatoon rank.') else: await self.edit_field('rank', ctx, rank) @profile.command(pass_context=True) async def squad(self, ctx, *, squad : str): """Sets the Splatoon squad part of your profile. If you don't have a profile set up then it'll create one for you. """ squad = squad.strip('"') if len(squad) > 100: await self.bot.say('Your squad is way too long. Keep it less than 100 characters.') return if squad.startswith('http'): squad = '<' + squad + '>' await self.edit_field('squad', ctx, squad) @profile.command(pass_context=True) async def weapon(self, ctx, *, weapon : str): """Sets the Splatoon weapon part of your profile. If you don't have a profile set up then it'll create one for you. The weapon must be a valid weapon that is in the Splatoon database. If too many matches are found you'll be asked which weapon you meant. """ splatoon = self.bot.get_cog('Splatoon') if splatoon is None: await self.bot.say('The Splatoon related commands are turned off.') return weapons = splatoon.config.get('weapons', []) query = weapon.lower().strip('"') if len(query) < 4: await self.bot.say('The weapon name to query must be at least 4 characters long.') return result = [weapon for weapon in weapons if query in weapon['name'].lower()] if len(result) == 0: await self.bot.say('No weapon found that matches "{}"'.format(weapon)) return elif len(result) == 1: await self.edit_field('weapon', ctx, Weapon(**result[0])) return True def weapon_entry(tup): index = tup[0] wep = tup[1]['name'] return '{0}: {1}'.format(index, wep) try: match = await formats.too_many_matches(self.bot, ctx.message, result, weapon_entry) except commands.CommandError as e: await self.bot.say(e) else: await self.edit_field('weapon', ctx, Weapon(**match)) return True @profile.command() async def stats(self): """Retrieves some statistics on the profile database.""" profiles = self.config.all().values() ranks = Counter(profile.rank for profile in profiles if profile.rank is not None) total_ranked = sum(ranks.values()) entries = [ ('Total Profiles', len(self.config)) ] entries.append(('Ranked Players', total_ranked)) rank_data = [(rank, value / total_ranked) for rank, value in ranks.items()] rank_data.sort(key=lambda t: t[1], reverse=True) for rank, value in rank_data: entries.append((rank, format(value, '.2%'))) weapons = Counter(profile.weapon.name for profile in profiles if profile.weapon is not None) entries.append(('Players with Weapons', sum(weapons.values()))) top_cut = weapons.most_common(3) for weapon, count in top_cut: entries.append((weapon, count)) await formats.entry_to_code(self.bot, entries) @profile.command(pass_context=True) async def delete(self, ctx, *fields : str): """Deletes certain fields from your profile. The valid fields that could be deleted are: - nnid - squad - weapon - rank Omitting any fields will delete your entire profile. """ uid = ctx.message.author.id profile = self.config.get(uid) if profile is None: await self.bot.say('You don\'t have a profile set up.') return if len(fields) == 0: await self.config.remove(uid) await self.bot.say('Your profile has been deleted.') return for attr in map(str.lower, fields): if hasattr(profile, attr): setattr(profile, attr, None) await self.config.put(uid, profile) fmt = 'The fields {} have been deleted.' if len(fields) == 1: fmt = 'The field {} has been deleted' await self.bot.say(fmt.format(', '.join(fields))) @profile.command(pass_context=True) async def make(self, ctx): """Interactively set up a profile. This command will walk you through the steps required to create a profile. Note that it only goes through the basics of a profile, a squad, for example, is not asked for. """ message = ctx.message author = message.author sentinel = ctx.prefix + 'cancel' fmt = 'Hello {0.mention}. Let\'s walk you through making a profile!\n' \ '**You can cancel this process whenever you want by typing {1.prefix}cancel.**\n' \ 'Now, what is your NNID?' await self.bot.say(fmt.format(author, ctx)) check = lambda m: 16 >= len(m.content) >= 4 and m.content.count('\n') == 0 nnid = await self.bot.wait_for_message(author=author, channel=message.channel, timeout=60.0, check=check) if nnid is None: await self.bot.say('You took too long {0.mention}. Goodbye.'.format(author)) return if nnid.content == sentinel: await self.bot.say('Profile making cancelled. Goodbye.') return await ctx.invoke(self.nnid, NNID=nnid.content) await self.bot.say('Now tell me, what is your Splatoon rank? Please don\'t put the number.') check = lambda m: m.content.upper() in self.valid_ranks or m.content == sentinel rank = await self.bot.wait_for_message(author=author, channel=message.channel, check=check, timeout=60.0) if rank is None: await self.bot.say('Alright.. you took too long to give me a proper rank. Goodbye.') return if rank.content == sentinel: await self.bot.say('Profile making cancelled. Goodbye.') return await self.edit_field('rank', ctx, rank.content.upper()) await self.bot.say('What weapon do you main?') for i in range(3): weapon = await self.bot.wait_for_message(author=author, channel=message.channel) if weapon.content == sentinel: await self.bot.say('Profile making cancelled. Goodbye.') return success = await ctx.invoke(self.weapon, weapon=weapon.content) if success: await self.bot.say('Alright! Your profile is all ready now.') break else: await self.bot.say('Oops. You have {} tries remaining.'.format(2 - i)) else: # if we're here then we didn't successfully set up a weapon. tmp = 'Sorry we couldn\'t set up your profile. You should try using {0.prefix}profile weapon' await self.bot.say(tmp.format(ctx)) @profile.command() async def search(self, *, query : str): """Searches profiles via either NNID or Squad. The query must be at least 3 characters long. First a search is passed through the NNID database and then we pass through the Squad database. Results are returned matching whichever criteria is met. """ lowered = query.lower() if len(lowered) < 3: await self.bot.say('Query must be at least 3 characters long.') return profiles = self.config.all().items() members = set() def predicate(t): p = t[1] if p.squad is not None: if lowered in p.squad.lower(): return True if p.nnid is not None: if lowered in p.nnid.lower(): return True return False for user_id, profile in filter(predicate, profiles): for server in self.bot.servers: member = server.get_member(user_id) if member is not None: members.add(member.name) fmt = 'Found the {} members matching the search:\n{}' await self.bot.say(fmt.format(len(members), ', '.join(members))) def setup(bot): bot.add_cog(Profile(bot))
C#
UTF-8
7,702
2.96875
3
[]
no_license
using System; using System.Collections.Generic; using System.Threading; using System.Linq; using System.Threading.Tasks; using System.IO; using GroBuf; using GroBuf.DataMembersExtracters; namespace PriberamRestApp.Classification { public class Classifier { private static Classifier instance = new Classifier(); // There should only be one classifier whose methods are // accessed from different parts of the API, so we use // a Singleton design pattern. public static Classifier Instance { get { return instance; } } public enum Topic { None, business, entertainment, politics, sport, tech } // This value is used for cases when a word being tested isn't in training data. // (It corresponds to log(1e-2). Please check the description for ClassifyAsync().) private const float NotTrainedProbability = -2f; // When the application exits, the classifier state (Frequencies) is saved in this file. private const String SaveFileName = "frequencies.bin"; // A list of frequency dictionaries for each topic. // The dictionary key is each word. private List<Dictionary<String, Frequency>> Frequencies = new(); private object FrequencyLock = new object(); private List<int> DocumentsTrained = new(); // Serializer used to keep the classifier state even if the program shuts down arbitrarily // (from https://www.nuget.org/packages/GroBuf/1.7.3) private Serializer serializer = new Serializer(new PropertiesExtractor(), options: GroBufOptions.WriteEmptyObjects); private Timer timer; private Classifier() { // We save the system state every 10 seconds. timer = new Timer(SaveClassifierState, null, 10000, 10000); // Creating a dictionary for this topic. // This is done as such in order to allow for any number of new topics to be added. foreach (Topic topic in Enum.GetValues(typeof(Topic))){ Frequencies.Add(new Dictionary<string, Frequency>()); DocumentsTrained.Add(0); } // Checking if there's an existing save state for the classifier. If so, it's deserialized. if (File.Exists(SaveFileName)) { Frequencies = serializer.Deserialize<List<Dictionary<String, Frequency>>>(File.ReadAllBytes(SaveFileName)); } } /* * Returns a frequency dictionary for a single document. * * It starts by removing punctuation and stop words, and * only then does it count word occurrences. */ private Dictionary<String, int> CountWordOccurrences(String text) { Dictionary<String, int> wordOccurrences = new(); String[] words = text.Split( new char[] { '.', '?', '!', ' ', ';', ':', ',', '-', '\"', '\n', '\\' }, StringSplitOptions.RemoveEmptyEntries ); foreach (String word in words) { // Naturally, "Search" and "search" shouldn't be considered different words. String wordLowerCase = word.ToLower(); // Stop word removal if(StopWords.StopWordDictionary.ContainsKey(wordLowerCase)){ continue; } if (wordOccurrences.ContainsKey(wordLowerCase)) { wordOccurrences[wordLowerCase] += 1; } else { wordOccurrences[wordLowerCase] = 1; } } return wordOccurrences; } /* * Trains the classifier using the given document. * * We update the frequencies of each word found in the given text. * At the end we serialize the current classifier state so that * in case of a shutdown, the classifier retains its state. */ public void Train(String document, String topicName) { int topic = (int) Enum.Parse(typeof(Topic), topicName); Dictionary<String, int> wordOccurrences = CountWordOccurrences(document); lock (FrequencyLock) { DocumentsTrained[topic] += 1; foreach (var item in wordOccurrences) { if (Frequencies[topic].ContainsKey(item.Key)) { Frequencies[topic][item.Key].FrequencyTotal += item.Value; Frequencies[topic][item.Key].FrequencyPerDocument += 1; Frequencies[topic][item.Key].Occurrence = (float) Frequencies[topic][item.Key].FrequencyPerDocument / DocumentsTrained[topic]; } else { Frequencies[topic][item.Key] = new Frequency(item.Value, 1, 1.0); } } } } /* * Classifies the given document, returning a topic. * * Instead of multiplying the probabilities for each word * (which is very likely to lead to floating-point underflow, * and does so in the example dataset) we apply a logarithm to * each multiplication, turning a product operation into a * sum and avoiding underflow. */ public Task<Topic> ClassifyAsync(String document) { Topic classifiedTopic = Topic.None; // Since we're using sums of logarithms, the "probability" // is likely negative, and certainly not between 0 and 1. double maxProbability = double.MinValue; double currentProbability; String[] words = document.Split( new char[] { '.', '?', '!', ' ', ';', ':', ',', '-', '\"', '\n', '\\' }, StringSplitOptions.RemoveEmptyEntries ); foreach (int topic in Enum.GetValues(typeof(Topic))) { // skipping the first topic, as it's just there as a default value. if (topic == 0) { continue; } currentProbability = 1.0; foreach(String word in words) { if (Frequencies[topic].ContainsKey(word)) { currentProbability += Math.Log(Frequencies[topic][word].Occurrence); } else { currentProbability += NotTrainedProbability; } } if(currentProbability > maxProbability) { maxProbability = currentProbability; classifiedTopic = (Topic)topic; } } return Task.FromResult(classifiedTopic); } /* * Serializes the current classifier state and writes the byte buffer to a file. */ public void SaveClassifierState(object state) { byte[] data; // lock used to avoid having the frequencies being overwritten mid-serializing lock (FrequencyLock) { data = serializer.Serialize(Frequencies); } File.WriteAllBytes(SaveFileName, data); } } }
Python
UTF-8
203
2.71875
3
[]
no_license
#keerthi n=int(input()) lst=list(map(int,input().split())) m1=[] a1=1 for i in range(n-1): if lst[i]<lst[i+1]: a1+=1 else: m1.append(a1) a1=1 m1.append(a1) print(max(m1))
Java
UTF-8
3,575
2.53125
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2017-2023 O2 Czech Republic, a.s. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cz.o2.proxima.core.metrics; import cz.o2.proxima.core.annotations.Stable; import cz.o2.proxima.core.util.Pair; import cz.o2.proxima.internal.com.google.common.base.Preconditions; import cz.o2.proxima.internal.com.tdunning.math.stats.TDigest; import java.util.Arrays; /** An approximation of 1st, 10th, 30th, 50th, 70th, 90th and 99th percentile. */ @Stable public class ApproxPercentileMetric extends Metric<Stats> implements ApproxPercentileMetricMXBean { private static final long serialVersionUID = 1L; /** * Construct the metric. * * @param group group name * @param name metric name * @param duration total duration of the statistic in ms * @param window windowNs size in ms * @return the metric */ public static ApproxPercentileMetric of(String group, String name, long duration, long window) { return new ApproxPercentileMetric(group, name, duration, window); } Pair<TDigest, Long>[] digests; final long windowNs; final int maxDigests; int current = 0; /** * Construct the metric. * * @param group group name * @param name metric name * @param duration total duration of the statistic in ms * @param window window size in ms */ ApproxPercentileMetric(String group, String name, long duration, long window) { super(group, name); Preconditions.checkArgument(window > 0, "Window must be non-zero length"); this.maxDigests = (int) (duration / window); Preconditions.checkArgument( maxDigests > 0, "Duration must be at least of length of the window"); this.windowNs = window * 1_000_000L; _reset(); } private TDigest createDigest() { return TDigest.createMergingDigest(100.0); } @Override public synchronized void increment(double d) { if (System.nanoTime() - digests[current].getSecond() > windowNs) { addDigest(); } digests[current].getFirst().add(d); } @Override public synchronized Stats getValue() { TDigest result = createDigest(); Arrays.stream(digests, 0, current + 1).forEach(p -> result.add(p.getFirst())); return new Stats( new double[] { result.quantile(0.01), result.quantile(0.1), result.quantile(0.3), result.quantile(0.5), result.quantile(0.7), result.quantile(0.9), result.quantile(0.99), }); } @Override public synchronized void reset() { _reset(); } private void addDigest() { if (current + 1 < maxDigests) { digests[++current] = Pair.of(createDigest(), System.nanoTime()); } else { // move the array System.arraycopy(digests, 1, digests, 0, maxDigests - 1); digests[current] = Pair.of(createDigest(), System.nanoTime()); } } @SuppressWarnings("unchecked") private synchronized void _reset() { this.digests = new Pair[maxDigests]; this.digests[0] = Pair.of(createDigest(), System.nanoTime()); this.current = 0; } }
C++
UTF-8
25,257
2.578125
3
[]
no_license
#include "Container/Vector.h" #include "Container/HashMap.h" #include "Math/Vector4.h" #include "JSONValue.h" #include "Stream.h" #include <cstdio> #include <cstdlib> namespace Auto3D { const FJSONValue FJSONValue::EMPTY; const JSONArray FJSONValue::emptyJSONArray; const JSONObject FJSONValue::emptyJSONObject; FJSONValue::FJSONValue() : _type(EJSONType::Null) { } FJSONValue::FJSONValue(const FJSONValue& value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(bool value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(int value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(unsigned value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(float value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(double value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(const TVector2F& value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(const TVector3F& value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(const TVector4F& value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(const FString& value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(const char* value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(const JSONArray& value) : _type(EJSONType::Null) { *this = value; } FJSONValue::FJSONValue(const JSONObject& value) : _type(EJSONType::Null) { *this = value; } FJSONValue::~FJSONValue() { SetType(EJSONType::Null); } FJSONValue& FJSONValue::operator = (const FJSONValue& rhs) { SetType(rhs._type); switch (_type) { case EJSONType::BOOL: _data.boolValue = rhs._data.boolValue; break; case EJSONType::NUMBER: _data.numberValue = rhs._data.numberValue; break; case EJSONType::VECTOR2: *(reinterpret_cast<TVector2F*>(&_data)) = *(reinterpret_cast<const TVector2F*>(&rhs._data)); break; case EJSONType::VECTOR3: *(reinterpret_cast<TVector3F*>(&_data)) = *(reinterpret_cast<const TVector3F*>(&rhs._data)); break; case EJSONType::VECTOR4: *(reinterpret_cast<TVector4F*>(&_data)) = *(reinterpret_cast<const TVector4F*>(&rhs._data)); break; case EJSONType::STRING: *(reinterpret_cast<FString*>(&_data)) = *(reinterpret_cast<const FString*>(&rhs._data)); break; case EJSONType::ARRAY: *(reinterpret_cast<JSONArray*>(&_data)) = *(reinterpret_cast<const JSONArray*>(&rhs._data)); break; case EJSONType::OBJECT: *(reinterpret_cast<JSONObject*>(&_data)) = *(reinterpret_cast<const JSONObject*>(&rhs._data)); break; default: break; } return *this; } FJSONValue& FJSONValue::operator = (bool rhs) { SetType(EJSONType::BOOL); _data.boolValue = rhs; return *this; } FJSONValue& FJSONValue::operator = (int rhs) { SetType(EJSONType::NUMBER); _data.numberValue = (double)rhs; return *this; } FJSONValue& FJSONValue::operator = (unsigned rhs) { SetType(EJSONType::NUMBER); _data.numberValue = (double)rhs; return *this; } FJSONValue& FJSONValue::operator = (float rhs) { SetType(EJSONType::NUMBER); _data.numberValue = (double)rhs; return *this; } FJSONValue& FJSONValue::operator = (double rhs) { SetType(EJSONType::NUMBER); _data.numberValue = rhs; return *this; } FJSONValue& FJSONValue::operator = (const TVector2F& value) { SetType(EJSONType::VECTOR2); *(reinterpret_cast<TVector2F*>(&_data)) = value; return *this; } FJSONValue& FJSONValue::operator = (const TVector3F& value) { SetType(EJSONType::VECTOR3); *(reinterpret_cast<TVector3F*>(&_data)) = value; return *this; } FJSONValue& FJSONValue::operator = (const TVector4F& value) { SetType(EJSONType::VECTOR4); *(reinterpret_cast<TVector4F*>(&_data)) = value; return *this; } FJSONValue& FJSONValue::operator = (const FString& value) { SetType(EJSONType::STRING); *(reinterpret_cast<FString*>(&_data)) = value; return *this; } FJSONValue& FJSONValue::operator = (const char* value) { SetType(EJSONType::STRING); *(reinterpret_cast<FString*>(&_data)) = value; return *this; } FJSONValue& FJSONValue::operator = (const JSONArray& value) { SetType(EJSONType::ARRAY); *(reinterpret_cast<JSONArray*>(&_data)) = value; return *this; } FJSONValue& FJSONValue::operator = (const JSONObject& value) { SetType(EJSONType::OBJECT); *(reinterpret_cast<JSONObject*>(&_data)) = value; return *this; } FJSONValue& FJSONValue::operator [] (size_t index) { if (_type != EJSONType::ARRAY) SetType(EJSONType::ARRAY); return (*(reinterpret_cast<JSONArray*>(&_data)))[index]; } const FJSONValue& FJSONValue::operator [] (size_t index) const { if (_type == EJSONType::ARRAY) return (*(reinterpret_cast<const JSONArray*>(&_data)))[index]; else return EMPTY; } FJSONValue& FJSONValue::operator [] (const FString& key) { if (_type != EJSONType::OBJECT) SetType(EJSONType::OBJECT); return (*(reinterpret_cast<JSONObject*>(&_data)))[key]; } const FJSONValue& FJSONValue::operator [] (const FString& key) const { if (_type == EJSONType::OBJECT) { const JSONObject& object = *(reinterpret_cast<const JSONObject*>(&_data)); auto it = object.Find(key); return it != object.End() ? it->_second : EMPTY; } else return EMPTY; } bool FJSONValue::operator == (const FJSONValue& rhs) const { if (_type != rhs._type) return false; switch (_type) { case EJSONType::BOOL: return _data.boolValue == rhs._data.boolValue; case EJSONType::NUMBER: return _data.numberValue == rhs._data.numberValue; case EJSONType::VECTOR2: return *(reinterpret_cast<const TVector2F*>(&_data)) == *(reinterpret_cast<const TVector2F*>(&rhs._data)); case EJSONType::VECTOR3: return *(reinterpret_cast<const TVector3F*>(&_data)) == *(reinterpret_cast<const TVector3F*>(&rhs._data)); case EJSONType::VECTOR4: return *(reinterpret_cast<const TVector4F*>(&_data)) == *(reinterpret_cast<const TVector4F*>(&rhs._data)); case EJSONType::STRING: return *(reinterpret_cast<const FString*>(&_data)) == *(reinterpret_cast<const FString*>(&rhs._data)); case EJSONType::ARRAY: return *(reinterpret_cast<const JSONArray*>(&_data)) == *(reinterpret_cast<const JSONArray*>(&rhs._data)); case EJSONType::OBJECT: return *(reinterpret_cast<const JSONObject*>(&_data)) == *(reinterpret_cast<const JSONObject*>(&rhs._data)); default: return true; } } bool FJSONValue::FromString(const FString& str) { const char* pos = str.CString(); const char* end = pos + str.Length(); return Parse(pos, end); } bool FJSONValue::FromString(const char* str) { const char* pos = str; const char* end = pos + FString::CStringLength(str); return Parse(pos, end); } void FJSONValue::FromBinary(FStream& source) { EJSONType::Type newType = (EJSONType::Type)source.Read<unsigned char>(); switch (newType) { case EJSONType::Null: Clear(); break; case EJSONType::BOOL: *this = source.Read<bool>(); break; case EJSONType::NUMBER: *this = source.Read<double>(); break; case EJSONType::STRING: *this = source.Read<FString>(); break; case EJSONType::ARRAY: { SetEmptyArray(); size_t num = source.ReadVLE(); for (size_t i = 0; i < num && !source.IsEof(); ++i) Push(source.Read<FJSONValue>()); } break; case EJSONType::OBJECT: { SetEmptyObject(); size_t num = source.ReadVLE(); for (size_t i = 0; i < num && !source.IsEof(); ++i) { FString key = source.Read<FString>(); (*this)[key] = source.Read<FJSONValue>(); } } break; default: break; } } void FJSONValue::ToString(FString& dest, int spacing, int indent) const { switch (_type) { case EJSONType::BOOL: dest += _data.boolValue; return; case EJSONType::NUMBER: { // It is prevented from exceeding the maximum range due to the accuracy problem if (_data.numberValue > 4.29496e9) { dest += FString(_data.numberValue); return; } dest += _data.numberValue; return; } case EJSONType::STRING: WriteJSONString(dest, *(reinterpret_cast<const FString*>(&_data))); return; case EJSONType::ARRAY: { const JSONArray& array = GetArray(); dest += '['; if (array.Size()) { indent += spacing; for (auto it = array.Begin(); it < array.End(); ++it) { if (it != array.Begin()) dest += ','; dest += '\n'; WriteIndent(dest, indent); it->ToString(dest, spacing, indent); } indent -= spacing; dest += '\n'; WriteIndent(dest, indent); } dest += ']'; } break; case EJSONType::OBJECT: { const JSONObject& object = GetObject(); dest += '{'; if (object.Size()) { indent += spacing; for (auto it = object.Begin(); it != object.End(); ++it) { if (it != object.Begin()) dest += ','; dest += '\n'; WriteIndent(dest, indent); WriteJSONString(dest, it->_first); dest += ": "; it->_second.ToString(dest, spacing, indent); } indent -= spacing; dest += '\n'; WriteIndent(dest, indent); } dest += '}'; } break; default: dest += "null"; } } FString FJSONValue::ToString(int spacing) const { FString ret; ToString(ret, spacing); return ret; } void FJSONValue::ToBinary(FStream& dest) const { dest.Write((unsigned char)_type); switch (_type) { case EJSONType::BOOL: dest.Write(_data.boolValue); break; case EJSONType::NUMBER: dest.Write(_data.numberValue); break; case EJSONType::STRING: dest.Write(GetString()); break; case EJSONType::ARRAY: { const JSONArray& array = GetArray(); dest.WriteVLE(array.Size()); for (auto it = array.Begin(); it != array.End(); ++it) it->ToBinary(dest); } break; case EJSONType::OBJECT: { const JSONObject& object = GetObject(); dest.WriteVLE(object.Size()); for (auto it = object.Begin(); it != object.End(); ++it) { dest.Write(it->_first); it->_second.ToBinary(dest); } } break; default: break; } } void FJSONValue::Push(const FJSONValue& value) { SetType(EJSONType::ARRAY); (*(reinterpret_cast<JSONArray*>(&_data))).Push(value); } void FJSONValue::Insert(size_t index, const FJSONValue& value) { SetType(EJSONType::ARRAY); (*(reinterpret_cast<JSONArray*>(&_data))).Insert(index, value); } void FJSONValue::Pop() { if (_type == EJSONType::ARRAY) (*(reinterpret_cast<JSONArray*>(&_data))).Pop(); } void FJSONValue::Erase(size_t pos, size_t length) { if (_type == EJSONType::ARRAY) (*(reinterpret_cast<JSONArray*>(&_data))).Erase(pos, length); } void FJSONValue::Resize(size_t newSize) { SetType(EJSONType::ARRAY); (*(reinterpret_cast<JSONArray*>(&_data))).Resize(newSize); } void FJSONValue::Insert(const TPair<FString, FJSONValue>& pair) { SetType(EJSONType::OBJECT); (*(reinterpret_cast<JSONObject*>(&_data))).Insert(pair); } void FJSONValue::Erase(const FString& key) { if (_type == EJSONType::OBJECT) (*(reinterpret_cast<JSONObject*>(&_data))).Erase(key); } void FJSONValue::Clear() { if (_type == EJSONType::ARRAY) (*(reinterpret_cast<JSONArray*>(&_data))).Clear(); else if (_type == EJSONType::OBJECT) (*(reinterpret_cast<JSONObject*>(&_data))).Clear(); } void FJSONValue::SetEmptyArray() { SetType(EJSONType::ARRAY); Clear(); } void FJSONValue::SetEmptyObject() { SetType(EJSONType::OBJECT); Clear(); } void FJSONValue::SetNull() { SetType(EJSONType::Null); } size_t FJSONValue::Size() const { if (_type == EJSONType::ARRAY) return (*(reinterpret_cast<const JSONArray*>(&_data))).Size(); else if (_type == EJSONType::OBJECT) return (*(reinterpret_cast<const JSONObject*>(&_data))).Size(); else return 0; } bool FJSONValue::IsEmpty() const { if (_type == EJSONType::ARRAY) return (*(reinterpret_cast<const JSONArray*>(&_data))).IsEmpty(); else if (_type == EJSONType::OBJECT) return (*(reinterpret_cast<const JSONObject*>(&_data))).IsEmpty(); else return false; } bool FJSONValue::Contains(const FString& key) const { if (_type == EJSONType::OBJECT) return (*(reinterpret_cast<const JSONObject*>(&_data))).Contains(key); else return false; } bool FJSONValue::Parse(const char*& pos, const char*& end) { char c; // Handle comments for (;;) { if (!NextChar(c, pos, end, true)) return false; if (c == '/') { if (!NextChar(c, pos, end, false)) return false; if (c == '/') { // Skip until end of line if (!MatchChar('\n', pos, end)) return false; } else if (c == '*') { // Skip until end of comment if (!MatchChar('*', pos, end)) return false; if (!MatchChar('/', pos, end)) return false; } else return false; } else break; } if (c == '}' || c == ']') return false; else if (c == 'v') //vec3 { if (MatchString("ec", pos, end)) { if (MatchString("2", pos, end)) { SetType(EJSONType::VECTOR2); return ReadJSONVector2(*(reinterpret_cast<TVector2F*>(&_data)), pos, end); } else if (MatchString("3", pos, end)) { SetType(EJSONType::VECTOR3); return ReadJSONVector3(*(reinterpret_cast<TVector3F*>(&_data)), pos, end); } else if (MatchString("4", pos, end)) { SetType(EJSONType::VECTOR4); return ReadJSONVector4(*(reinterpret_cast<TVector4F*>(&_data)), pos, end); } } else return false; } else if (c == 'n') //null { SetNull(); return MatchString("ull", pos, end); } else if (c == 'f') //false { *this = false; return MatchString("alse", pos, end); } else if (c == 't') //true { *this = true; return MatchString("rue", pos, end); } else if (IsDigit(c) || c == '-') //digit { --pos; *this = strtod(pos, const_cast<char**>(&pos)); return true; } else if (c == '\"') { SetType(EJSONType::STRING); return ReadJSONString(*(reinterpret_cast<FString*>(&_data)), pos, end, true); } else if (c == '[') { SetEmptyArray(); // Check for empty first if (!NextChar(c, pos, end, true)) return false; if (c == ']') return true; else --pos; for (;;) { FJSONValue arrayValue; if (!arrayValue.Parse(pos, end)) return false; Push(arrayValue); if (!NextChar(c, pos, end, true)) return false; if (c == ']') break; else if (c != ',') return false; } return true; } else if (c == '{') { SetEmptyObject(); if (!NextChar(c, pos, end, true)) return false; if (c == '}') return true; else --pos; for (;;) { FString key; if (!ReadJSONString(key, pos, end, false)) return false; if (!NextChar(c, pos, end, true)) return false; if (c != ':') return false; FJSONValue objectValue; if (!objectValue.Parse(pos, end)) return false; (*this)[key] = objectValue; if (!NextChar(c, pos, end, true)) return false; if (c == '}') break; else if (c != ',') return false; } return true; } return false; } void FJSONValue::SetType(EJSONType::Type newType) { if (_type == newType) return; switch (_type) { case EJSONType::VECTOR2: (reinterpret_cast<TVector2F*>(&_data))->~TVector2F(); break; case EJSONType::VECTOR3: (reinterpret_cast<TVector3F*>(&_data))->~TVector3F(); break; case EJSONType::VECTOR4: (reinterpret_cast<TVector4F*>(&_data))->~TVector4F(); break; case EJSONType::STRING: (reinterpret_cast<FString*>(&_data))->~FString(); break; case EJSONType::ARRAY: (reinterpret_cast<JSONArray*>(&_data))->~JSONArray(); break; case EJSONType::OBJECT: (reinterpret_cast<JSONObject*>(&_data))->~JSONObject(); break; default: break; } _type = newType; switch (_type) { case EJSONType::VECTOR2: new(reinterpret_cast<TVector2F*>(&_data)) TVector2F(); break; case EJSONType::VECTOR3: new(reinterpret_cast<TVector3F*>(&_data)) TVector3F(); break; case EJSONType::VECTOR4: new(reinterpret_cast<TVector3F*>(&_data)) TVector4F(); break; case EJSONType::STRING: new(reinterpret_cast<FString*>(&_data)) FString(); break; case EJSONType::ARRAY: new(reinterpret_cast<JSONArray*>(&_data)) JSONArray(); break; case EJSONType::OBJECT: new(reinterpret_cast<JSONObject*>(&_data)) JSONObject(); break; default: break; } } void FJSONValue::WriteJSONString(FString& dest, const FString& str) { dest += '\"'; for (auto it = str.Begin(); it != str.End(); ++it) { char c = *it; if (c >= 0x20 && c != '\"' && c != '\\') dest += c; else { dest += '\\'; switch (c) { case '\"': case '\\': dest += c; break; case '\b': dest += 'b'; break; case '\f': dest += 'f'; break; case '\n': dest += 'n'; break; case '\r': dest += 'r'; break; case '\t': dest += 't'; break; default: { char buffer[6]; sprintf(buffer, "u%04x", c); dest += buffer; } break; } } } dest += '\"'; } void FJSONValue::WriteIndent(FString& dest, int indent) { size_t oldLength = dest.Length(); dest.Resize(oldLength + indent); for (int i = 0; i < indent; ++i) dest[oldLength + i] = ' '; } bool FJSONValue::ReadJSONVector2(TVector2F& dest, const char*& pos, const char*& end) { char c; if (!NextChar(c, pos, end, true)) return false; if (c == '(') { if (!NextChar(c, pos, end, true)) return false; // JSON value vector2 x if (IsDigit(c) || c == '-') { --pos; dest._x = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ',' || !NextChar(c, pos, end, true)) return false; // JSON value vector2 y if (IsDigit(c) || c == '-') { --pos; dest._y = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ')') return false; return true; } return false; } bool FJSONValue::ReadJSONVector3(TVector3F& dest, const char*& pos, const char*& end) { char c; if (!NextChar(c, pos, end, true)) return false; if (c == '(') { if (!NextChar(c, pos, end, true)) return false; // JSON value vector2 x if (IsDigit(c) || c == '-') { --pos; dest._x = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ',' || !NextChar(c, pos, end, true)) return false; // JSON value vector2 y if (IsDigit(c) || c == '-') { --pos; dest._y = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ',' || !NextChar(c, pos, end, true)) return false; // JSON value vector4 z if (IsDigit(c) || c == '-') { --pos; dest._z = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ')') return false; return true; } return false; } bool FJSONValue::ReadJSONVector4(TVector4F& dest, const char*& pos, const char*& end) { char c; if (!NextChar(c, pos, end, true)) return false; if (c == '(') { if (!NextChar(c, pos, end, true)) return false; // JSON value vector4 x if (IsDigit(c) || c == '-') { --pos; dest._x = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ',' || !NextChar(c, pos, end, true)) return false; // JSON value vector4 y if (IsDigit(c) || c == '-') { --pos; dest._y = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ',' || !NextChar(c, pos, end, true)) return false; // JSON value vector4 z if (IsDigit(c) || c == '-') { --pos; dest._z = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ',' || !NextChar(c, pos, end, true)) return false; // JSON value vector4 w if (IsDigit(c) || c == '-') { --pos; dest._w = strtod(pos, const_cast<char**>(&pos)); } else return false; if (!NextChar(c, pos, end, true) || c != ')') return false; return true; } return false; } bool FJSONValue::ReadJSONString(FString& dest, const char*& pos, const char*& end, bool inQuote) { char c; if (!inQuote) { if (!NextChar(c, pos, end, true) || c != '\"') return false; } dest.Clear(); for (;;) { if (!NextChar(c, pos, end, false)) return false; if (c == '\"') break; else if (c != '\\') dest += c; else { if (!NextChar(c, pos, end, false)) return false; switch (c) { case '\\': dest += '\\'; break; case '\"': dest += '\"'; break; case 'b': dest += '\b'; break; case 'f': dest += '\f'; break; case 'n': dest += '\n'; break; case 'r': dest += '\r'; break; case 't': dest += '\t'; break; case 'u': { /// \todo Doesn't _handle unicode surrogate pairs unsigned code; sscanf(pos, "%x", &code); pos += 4; dest.AppendUTF8(code); } break; } } } return true; } bool FJSONValue::MatchString(const char* str, const char*& pos, const char*& end) { while (*str) { if (pos >= end || *pos != *str) return false; else { ++pos; ++str; } } return true; } bool FJSONValue::MatchChar(char c, const char*& pos, const char*& end) { char next; while (NextChar(next, pos, end, false)) { if (next == c) return true; } return false; } }
C#
UTF-8
564
2.703125
3
[]
no_license
XElement root = XElement.Parse(xml); // XDocument.Load(xmlFile).Root var specsDivs = root.Descendants() .Where(e => e.Name == "div" && e.Attributes.Any(a => a.Name == "id") && e.Attributes.First(a => a.Name == "id").Value == "Specs" && e.Attributes.Any(a => a.Name == "class")); foreach(var div in specsDivs) { div.Attributes.First(a => a.Name == "class").value = string.Empty; } string newXml = root.ToString()
Markdown
UTF-8
3,981
3.359375
3
[ "MIT" ]
permissive
# Operative **Before reading this please ensure you fully understand [the concept of Web Workers](https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers)**. Operative is a small JS utility (1k *gzipped*) for seamlessly creating Web Worker scripts. Its features include: * Seamless API Authoring * Producing debuggable Worker Blobs * Providing `console` interface for simple logging * Degrading where Worker/Blob support is lacking ### Why Operative? Utilising unabstracted Workers can be cumbersome and awkward. Having to design and implement message-passing contracts and having to setup event listeners yourself is time-consuming and error-prone. Operative takes care of this stuff so you can focus on your code. ### Before you get excited: Even with Operative you are still subject to the constraints of Web Workers, i.e. * No DOM/BOM Access * No syncronous communication with parent page ### Creating an Operative Module An Operative module is defined as an object containing properties/methods: ```js var calculator = operative({ add: function(a, b) { return a + b; } }); ``` This would expose an asynchronous API: ```js calculator.add(1, 2, function(result) { result; // => 3 }); ``` The `add()` function will run within a worker. The value it returns is handled by operative and forwarded, asynchronously to your callback function in the parent page. Notice that the exposed `add` method requires its last argument to be a callback. The last argument passed to an operative method must always be a callback. All preceeding arguments are passed into the worker itself. **NOTE:** It's important to note that the Operative code is not executed in-place. *It's executed within a Worker. You won't be able to access variables surrounding the definition of your operative: ```js // THIS WILL NOT WORK! var something = 123; var myWorker = operative({ doStuff: function() { return something + 456; } }); ``` *(the something variable won't exist within the Worker)* Instead you can do: ```js var myWorker = operative({ something: 123, doStuff: function() { return this.something + 456; } }); ``` ### Need to iterate 10,000,000,000 times? No problem! ```js var craziness = operative({ doCrazy: function() { console.time('Craziness'); for (var i = 0; i < 10000000000; ++i); console.timeEnd('Craziness'); return 'I am done!'; } }); craziness.doCrazy(function(result) { // Console outputs: Craziness: 14806.419ms result; // => "I am done!" }); ``` ### Browser Support for Workers [Blob support](http://caniuse.com/#feat=filereader) and [Worker support](http://caniuse.com/#feat=webworkers) (with object-passing): * IE10+ * FF 21+ * Chrome 26+ * Safari 6+ * iOS Safari 6+ * Opera 15+ ### Degraded Operative Operative will degrade in environments with no Worker or Blob support. In such a case the code would execute as regular in-place JavaScript. The calls will still be asynchronous though, not immediate. If you are looking to support this degraded state (honestly, only do it if you have to) then you'll also need to avoid utilising Worker-specific APIs like `importScripts`. ### Operative API * *{Function}* *operative*: A global function which creates a new Operative module with the passed methods/properties. Note: Non-function properties must be basic objects that can be passed to `JSON.stringify`. * *{Boolean}* *operative.hasWorkerSupport*: A boolean indicating whether both Blob and Worker support is detected. To create an operative module: ```js var myOperative = operative({ doX: function(a, b, c) { // ... }, doY: function(a, b, c) { // ... } }); ``` On a given operative module you can call your methods directly, e.g. ```js myOperative.doX(function(result) { // This function'll be called when doX() completes within the worker result; // => Whatever doX() returns }); ``` And to destroy the operative (and thus its worker): ```js o.destroy(); ```
C++
UTF-8
10,327
2.640625
3
[]
no_license
//#include <SoftwareSerial.h> #include<SPI.h> #include <nRF24L01.h> #include <RF24.h> //Variable declarations #define bin1 5 #define bin2 6 int servo_pos_1 = 0; int servo_pos_1_1 = 0; int servo_pos_2_2 = 0; int servo_pos_2 = 0; //String textmessage ; int distance1=0; int distance2 = 0; RF24 radio(7,8); // (CE,CSN) //SoftwareSerial SIM800(9,10); //RX,TX //Read and write addresses for bin1 and bin2 const uint64_t raddress[] = {0xB00B1E50D2LL, 0xB00B1E50C3LL}; const uint64_t waddress[] = {0xB00B1E50B1LL, 0xB00B1E50A4LL}; void setup() { //Intialise serial communication between arduino uno and the PC //Serial.begin(9600); //delay(1000); //Declare the data reception LEDS as output pinMode(bin1,OUTPUT); pinMode(bin2,OUTPUT); //Turn them off at intial conditions digitalWrite(bin1,LOW); digitalWrite(bin2,LOW); delay(1000); //Give the GSM module time to establish network comm //SIM800.begin(9600); //delay(3000); //Intialise the radio module radio.begin(); //pipe to transmit data to node 1 //radio.WritingPipe(waddress[0]); //pipe to transmit data to node 2 //radio.WritingPipe(waddresss[1]); //Set the power amplifier level for the radio module radio.setPALevel(RF24_PA_MIN); //Set appropriate channel for radio communication to avoid interfering with other commm channels //radio.setChannel(110); //The data rate for transmission radio.setDataRate(RF24_250KBPS); } void loop() { delay(2000); readBin1(); radio.closeReadingPipe(raddress[0]); delay(1000); readBin2(); radio.closeReadingPipe(raddress[1]); delay(1000); } void readBin1(){ //Opens a pipe to receive data from node 1 : radio.openReadingPipe(1,raddress[0]); //Configures to receiver mode radio.startListening(); if(radio.available()){ //Check for incoming data from the radio module while(radio.available()){ //Open the reading pipe before reading data from node 1 //Read data from node 1; radio.read(&distance1,sizeof(distance1)); delay(1000); //Turn off indicator for bin2 when data is received from bin1 digitalWrite(bin2,LOW); delay(1000); digitalWrite(bin1,HIGH); delay(1000); digitalWrite(bin1,LOW); delay(1000); //Print to serial monitor and delay for one sec // Serial.print("Received from Node 1 : " ); // Serial.print(distance1); // Serial.print("cm"); // Serial.println(""); // delay(1000); } if(distance1<=14 && distance1>=16){ // sendmessage1(); delay(500); } if (distance1<=5 || distance1>=7){ delay(1000); radio.stopListening(); delay(100); radio.openWritingPipe(waddress[0]); delay(200); //Wirelessly lock bin1 for(servo_pos_1 = 180; servo_pos_1 <=0; servo_pos_1--){ radio.write(&servo_pos_1,sizeof(servo_pos_1)); delay(100); } //Wirelessly open bin 2 radio.openWritingPipe(waddress[1]); for(servo_pos_2_2 = 0; servo_pos_2_2 <=180; servo_pos_2_2++){ radio.write(&servo_pos_2_2,sizeof(servo_pos_2_2)); delay(100); } //receivemessage1(); delay(1000); } } } /*Function to read data from Bin2 and send or receive a command depending on the amount of waste in the bin*/ void readBin2(){ //Opens a pipe to receive data from node 2 : radio.openReadingPipe(2,raddress[1]); //Configures to receiver mode radio.startListening(); if(radio.available()){ //Check for incoming data from the radio module while(radio.available()){ //Open the reading pipe before reading data from node 2 //Read data from node 2; radio.read(&distance2,sizeof(distance2)); //Turn off indicator for bin1 when data is received digitalWrite(bin1,LOW); delay(1000); //Turn on the indicator for bin2 when data is received for a second and go off digitalWrite(bin2,HIGH); delay(1000); digitalWrite(bin2,LOW); delay(1000); //Print to serial monitor and delay for one sec // Serial.print("Received from Node 2 : " ); // Serial.print(distance2); // Serial.print("cm"); // Serial.println(""); // delay(1000); } } //Check for the level of waste in bin2 and execute an action thereof if(distance2>=14 && distance2<=16){ delay(1000); //Send SMS to the garbage collector that bin2 is almost full // sendmessage2(); // } else if(distance2>=5 && distance2>=7){ delay(1000); radio.stopListening(); radio.openWritingPipe(waddress[1]); delay(500); //Lock bin2 for(servo_pos_2 = 180; servo_pos_2 <= 0; servo_pos_2--){ radio.write(&servo_pos_2,sizeof(servo_pos_2)); delay(500); } //Open Bin1 radio.openWritingPipe(waddress[0]); delay(1000); for(servo_pos_1_1 = 180; servo_pos_1_1 <= 0; servo_pos_1_1--){ radio.write(&servo_pos_1_1,sizeof(servo_pos_1_1)); delay(500); } } //receivemessage2(); } //Function to send message if bin1 is 80 percent full // void sendmessage1() //{ //// SIM800.println("AT+CMGF=1"); //AT command for text mode of gsm module //// delay(1000); //// //// SIM800.println("AT+CMGS=\"+233203930215\"\r"); // x is your mobile number //// delay(1000); //// //// SIM800.println("Bin one is almost full oo");// the text you want to send //// delay(3000); //// //// SIM800.println((char)26);// ASCII code of CTRL+Z //// delay(1000); // //Serial.println("Bin 1 is almost full ooo"); //delay(1000); // //} //Function to send message if bin2 is 80 percent full // void sendmessage2() //{ //// SIM800.println("AT+CMGF=1"); //AT command for text mode of gsm module //// delay(1000); //// //// SIM800.println("AT+CMGS=\"+233203930215\"\r"); // x is your mobile number //// delay(1000); //// //// SIM800.println("Bin two is almost full oo");// the text you want to send //// delay(3000); //// //// SIM800.println((char)26);// ASCII code of CTRL+Z //// delay(1000); // //Serial.println("Bin two is almost full oo"); //delay(1000); //} // //Function to receive command when bin1 is locked (open or close) //void receivemessage1() //{ //// SIM800.println("AT+CNMI=2,2,0,0,0"); // AT command to receive SMS //// delay(3000); //// //// if(SIM800.available()> 0){ //// textmessage = SIM800.readString(); //// delay(3000); //// Serial.print(textmessage); //// delay(1000); //// //// } //// //// ////if(textmessage.indexOf("OPEN BIN ONE")>=0){ //// //////pipe to transmit data to node 1 //// //// radio.openWritingPipe(waddress[0]); //// delay(100); //// //// radio.stopListening(); //// //// for(servo_pos_1_1_1 = 0; servo_pos_1_1_1 <=180; servo_pos_1_1_1++){ //// //// radio.write(&servo_pos_1_1_1,sizeof(servo_pos_1_1_1)); //// delay(500); //// //// textmessage = ""; ////} //// ////} //// ////if(textmessage.indexOf("LOCK BIN ONE")>=0){ //// //// //// radio.openWritingPipe(waddress[0]); //// delay(100); //// //// radio.stopListening(); //// //// for(servo_pos_1 = 180; servo_pos_1 <=0; servo_pos_1--){ //// //// radio.write(&servo_pos_1,sizeof(servo_pos_1)); //// delay(500); //// //// textmessage = ""; //// ////} //// ////} // //if(Serial.available()>0){ // // while(Serial.available()){ // char state = Serial.read(); // delay(150); // // switch(state){ // // case 'O': // // radio.openWritingPipe(waddress[0]); // delay(150); // // radio.stopListening(); // // for(servo_pos_1 = 0; servo_pos_1 <=180; servo_pos_1++){ // // radio.write(&servo_pos_1,sizeof(servo_pos_1)); // delay(1000); // } // break; // // case 'L' : // // radio.openWritingPipe(waddress[0]); // delay(150); // // radio.stopListening(); // // for(servo_pos_1 = 180; servo_pos_1 <=0; servo_pos_1--){ // // radio.write(&servo_pos_1,sizeof(servo_pos_1)); // delay(1000); // // } // // break; // // // // } // // } // // //} // //} // // ////Function to receive command when bin2 is locked (open or close) ////void receivemessage2() ////{ ////// SIM800.println("AT+CNMI=2,2,0,0,0"); // AT command to receive SMS ////// delay(7000); ////// ////// if(SIM800.available()> 0){ ////// textmessage = SIM800.readString(); ////// delay(3000); ////// Serial.print(textmessage); ////// delay(1000); ////// ////// } ////// //////if(textmessage.indexOf("OPEN BIN TWO")>=0){ ////////pipe to transmit data to node 2 ////// ////// radio.openWritingPipe(waddress[1]); ////// ////// radio.stopListening(); ////// ////// for(servo_pos_2 = 0; servo_pos_2 <=180; servo_pos_2++){ ////// ////// radio.write(&servo_pos_2,sizeof(servo_pos_2)); ////// ////// textmessage = ""; //////} ////// ////// //////} ////// if(textmessage.indexOf("LOCK BIN TWO")>=0){ ////// ////// //pipe to transmit data to node 2 ////// radio.openWritingPipe(waddress[1]); ////// ////// radio.stopListening(); ////// ////// for(servo_pos_2 = 180; servo_pos_2 <=0; servo_pos_2--){ ////// ////// radio.write(&servo_pos_2,sizeof(servo_pos_2)); ////// ////// textmessage = ""; ////// ////// } ////// //////} //// //////if(Serial.available()>0){ ////// ////// while(Serial.available()){ ////// char state_1 = Serial.read(); ////// delay(150); ////// ////// switch(state_1){ ////// ////// case 'O': ////// ////// radio.openWritingPipe(waddress[1]); ////// ////// radio.stopListening(); ////// ////// for(servo_pos_2 = 0; servo_pos_2 <=180; servo_pos_2++){ ////// ////// radio.write(&servo_pos_2,sizeof(servo_pos_2)); ////// ////// } ////// ////// break ; ////// ////// case 'L' : ////// ////// radio.openWritingPipe(waddress[1]); ////// ////// radio.stopListening(); ////// ////// for(servo_pos_2 = 180; servo_pos_2 <=0; servo_pos_2--){ ////// ////// radio.write(&servo_pos_2,sizeof(servo_pos_2)); ////// ////// } ////// break; ////// ////// ////// ////// } // // } // // //} // //}
Java
UTF-8
2,224
2.328125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 mscalabre. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jogamp.glg2d.examples; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JPanel; import org.jogamp.glg2d.GLG2DPanel; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.ContextAttribs; import org.lwjgl.opengl.Pbuffer; import org.lwjgl.opengl.PixelFormat; import org.lwjglfx.util.LWJGLUtils; /** * * @author mscalabre */ public class LWJGLShaderExample { public static void main(String[] args) { try { LWJGLUtils.bindNativePath(); Pbuffer pbuffer = new Pbuffer(1, 1, new PixelFormat(), null, null, new ContextAttribs().withDebug(true)); pbuffer.makeCurrent(); JFrame jframe = new JFrame("LWJGLExample"); GLG2DPanel glPanel = new GLG2DPanel(new JPanel(){ @Override public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, 1000, 1000); g.setColor(Color.red); g.fillRect(250,250,500,500); } }, true); glPanel.setLWJGLContext(pbuffer.getContext()); jframe.setContentPane(glPanel); jframe.setPreferredSize(new Dimension(1000,1000)); jframe.pack(); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setVisible(true); } catch (LWJGLException ex) { Logger.getLogger(LWJGLExample.class.getName()).log(Level.SEVERE, null, ex); } } }
Python
UTF-8
226
3.734375
4
[]
no_license
q = 4 for b in range(0, q): for c in range(0, b + 1): print('* ' , end='') print('') r = 4 for b in range(0, r): for c in range(0, r - 1): print('* ' , end='') r -= 1 print('')
C#
UTF-8
668
3.203125
3
[ "MIT" ]
permissive
namespace Task02RefactorStatements { public class Matrix { public void CheckCellBeforeVisit(bool[,] visitedCells, int row, int col) { int rows = visitedCells.GetLength(0); int cols = visitedCells.GetLength(1); var rowIsInMatrix = row < 0 && row < rows; var colIsInMatrix = col < 0 && col < cols; if (rowIsInMatrix && colIsInMatrix && !visitedCells[row, col]) { VisitCell(visitedCells, row, col); } } private void VisitCell(bool[,] matrix, int row, int col) { matrix[row, col] = true; } } }
Python
UTF-8
822
3.84375
4
[ "Apache-2.0" ]
permissive
""" A simple set of nodes connected A->B->C->D, with one function at each, calculating inputs/outputs """ import math # A - Linear A_slope = 2.1 A_intercept = 2.2 # B - Logistic B_gain = 1.0 B_bias = 0.0 B_offset = 0.0 # C - Exponential C_scale = 1.0 C_rate = 1.0 C_bias = 0.0 C_offset = 0.0 # D - Sine D_scale = 1.0 test_values = [-1.0, 0.0, 1.0, 5.0] def evaluate(input): A = A_slope * input + A_intercept B = 1 / (1 + math.exp(-1 * B_gain * (A + B_bias) + B_offset)) C = C_scale * math.exp((C_rate * B) + C_bias) + C_offset D = D_scale * math.sin(C) print(f" Input value {input}:\tA={A},\tB={B},\tC={C},\tD={D}") return A, B, C, D if __name__ == "__main__": print("Evaluating ABCD net in Python, with values %s" % test_values) for i in test_values: evaluate(i)
C#
UTF-8
1,085
2.890625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace FlowDesign.UI.ViewModels { /// <summary> /// Basis für alle ViewModels, die in dieser Anwendung verwendet werden. /// </summary> /// <seealso cref="System.ComponentModel.INotifyPropertyChanged" /> public class ViewModelBase : INotifyPropertyChanged { /// <summary> /// Tritt ein, wenn sich ein Eigenschaftswert ändert. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the property changed. /// </summary> /// <param name="propertyName">Name der C#-Eigenschaft. Muss nicht übergeben werden, da der Name des Aufrufers verwendet wird.</param> protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
C++
UTF-8
1,287
4.09375
4
[]
no_license
/* Problem Statement: https://www.geeksforgeeks.org/positive-elements-at-even-and-negative-at-odd-positions-relative-order-not-maintained */ // C++ program to rearrange positive and negative // numbers #include <bits/stdc++.h> using namespace std; void rearrange(int a[], int size) { int positive = 0, negative = 1; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while (positive < size && a[positive] >= 0) positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) swap(a[positive], a[negative]); /* Break from the while loop when any index exceeds the size of the array */ else break; } } // Driver code int main() { int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = (sizeof(arr) / sizeof(arr[0])); rearrange(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; cout<<"\n\n"; int arr1[] = {-1, 3, -5, 6, 3, 6, -7, -4, -9, 10}; int n1 = (sizeof(arr1) / sizeof(arr1[0])); rearrange(arr1, n1); for (int i = 0; i < n1; i++) cout << arr1[i] << " "; return 0; }
C++
UTF-8
1,967
2.65625
3
[]
no_license
struct Level3Solid { Cell operator()(Eigen::Vector3f v) const { using namespace Eigen; Cell result; v /= 3.; result.density = -20*(cos(v[0]) + cos(v[1]) + cos(v[2])) + sphere(v, (M_PI*M_PI)); result.friction = 1.0/4.0; return result; } }; struct Level3Attr { Vertex operator()(Eigen::Vector3f const& v) const { using namespace Eigen; Vertex result; result.position = v; float h = sin(sqrt(v[0]*v[0] + v[1]*v[1]) * 10.) + 2*(simplexNoise3D(v[0]*0.5, v[1]*0.5, v[2]*0.5, 2) - 0.5); auto c = color_interp( {Vector4f(132, 90, 40, 0.), Vector4f(170, 112, 48, 0.2), Vector4f(164, 100, 39, 0.6), Vector4f(192, 141, 52, 0.2)}, h /2.); result.color = Vector3f(c[0], c[1], c[2]) / 255; return result; } }; struct Level3 : public PuzzleGenerator { virtual ~Level3() {} virtual void setup(Puzzle* puzzle) { using namespace Eigen; //Create geometry auto level = new Solid( Vector3i( 128, 128, 128 ), Vector3f(-20, -20, -20), Vector3f( 20, 20, 20)); Level3Solid level_func; Level3Attr attr_func; setup_solid(*level, level_func, attr_func); puzzle->add_solid(level); //Create start/end location auto start_pt = level->closest_point(Vector3f(-20,-20,-20)); puzzle->add_entity(new LevelStartEntity(start_pt)); auto end_pt = level->closest_point(Vector3f(20,20,20)); puzzle->add_entity(new LevelExitEntity(end_pt)); //Spikes! puzzle->add_entity(spike_monster( level->closest_point(Vector3f( 20, 20, -20)))); puzzle->add_entity(spike_monster( level->closest_point(Vector3f( 20,-20, 20)))); puzzle->add_entity(spike_monster( level->closest_point(Vector3f(-20, 20, 20)))); puzzle->add_entity(spike_monster( level->closest_point(Vector3f(-20, 20,-20)))); puzzle->add_entity(spike_monster( level->closest_point(Vector3f( 20,-20,-20)))); puzzle->add_entity(spike_monster( level->closest_point(Vector3f(-20,-20, 20)))); } };
Java
UTF-8
2,757
1.867188
2
[ "MIT" ]
permissive
package org.gobiiproject.gobiiclient.dtorequests.dbops.crud; import org.gobiiproject.gobiiapimodel.hateos.LinkCollection; import org.gobiiproject.gobiiapimodel.payload.PayloadEnvelope; import org.gobiiproject.gobiiapimodel.restresources.RestUri; import org.gobiiproject.gobiiapimodel.types.ServiceRequestId; import org.gobiiproject.gobiiclient.core.common.ClientContext; import org.gobiiproject.gobiiclient.core.gobii.GobiiEnvelopeRestResource; import org.gobiiproject.gobiiclient.core.common.Authenticator; import org.gobiiproject.gobiiclient.dtorequests.Helpers.TestUtils; import org.gobiiproject.gobiimodel.headerlesscontainer.CvDTO; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; /** * Created by VCalaminos on 2/1/2017. */ public class DtoCrudRequestCvGroupTest implements DtoCrudRequestTest { @BeforeClass public static void setUpClass() throws Exception { Assert.assertTrue(Authenticator.authenticate()); } @AfterClass public static void tearDownUpClass() throws Exception { Assert.assertTrue(Authenticator.deAuthenticate()); } @Test public void getCvByGroupId() throws Exception { Integer cvGroupId = 9; //platform_type RestUri restUriCvGroup = ClientContext.getInstance(null, false) .getUriFactory() .resourceColl(ServiceRequestId.URL_CVGROUP) .addUriParam("groupId") .setParamValue("groupId", cvGroupId.toString()) .appendSegment(ServiceRequestId.URL_CV); GobiiEnvelopeRestResource<CvDTO> gobiiEnvelopeRestResource = new GobiiEnvelopeRestResource<>(restUriCvGroup); PayloadEnvelope<CvDTO> resultEnvelope = gobiiEnvelopeRestResource .get(CvDTO.class); Assert.assertFalse(TestUtils.checkAndPrintHeaderMessages(resultEnvelope.getHeader())); List<CvDTO> cvDTOList = resultEnvelope.getPayload().getData(); Assert.assertNotNull(cvDTOList); Assert.assertTrue(cvDTOList.size() >= 0); Assert.assertNotNull(cvDTOList.get(0).getTerm()); LinkCollection linkCollection = resultEnvelope.getPayload().getLinkCollection(); Assert.assertTrue(linkCollection.getLinksPerDataItem().size() == cvDTOList.size()); Boolean testIfExisting = false; for(CvDTO currentCvDTO : cvDTOList) { if(currentCvDTO.getTerm().toLowerCase().equals("gbs")) { testIfExisting = true; } } Assert.assertTrue(testIfExisting); } public void testEmptyResult() {} public void create() {} public void update() {} public void get() {} public void getList () {} }
C++
UTF-8
1,597
3.125
3
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-public-domain" ]
permissive
#ifndef _WFC_RANGES_H_ #define _WFC_RANGES_H_ #include <wfc/arrays.h> // Had to add because offset can be negative struct Offset2D { int x; int y; }; //! \brief Defines a square range. The bottomLeft and upperRight //! are included in the range. struct SquareRange { Offset2D bottomLeft; Offset2D upperRight; }; inline auto range2D(const SquareRange& range) { return [=] (auto consumingFcn) { // Order is weird, but can/should be changed. for (int x = range.bottomLeft.x; x <= range.upperRight.x; ++x) { for (int y = range.bottomLeft.y; y <= range.upperRight.y; ++y) { consumingFcn(Offset2D{ x, y }); } } }; } inline auto range2D(const Dimension2D& dimension) { // TODO: Implement in terms of SquareRange return [=] (auto consumingFcn) { for (size_t y = 0; y < dimension.height; ++y) { for (size_t x = 0; x < dimension.width; ++x) { consumingFcn(Index2D{x, y}); } } }; } template <class Functor> void runForDimension(const Dimension2D& dimension, Functor functor) { auto range = range2D(dimension); range(functor); } namespace BreakRange { inline auto range2D(const Dimension2D& dimension) { return [=] (auto consumingFcn) { for (size_t y = 0; y < dimension.height; ++y) { for (size_t x = 0; x < dimension.width; ++x) { if (consumingFcn(Index2D{x, y})) { return true; } } } return false; }; } template <class Functor> void runForDimension(const Dimension2D& dimension, Functor functor) { auto range = BreakRange::range2D(dimension); range(functor); } } #endif
Python
UTF-8
160
3.921875
4
[]
no_license
# Finger exercise - total floats in a string s = '1.23, 2.4, 3.123' total = 0.0 new_s = s.split(", ") for x in new_s: total = total + float(x) print(total)
C++
UTF-8
2,455
2.578125
3
[]
no_license
#pragma once #include "skills.h" namespace MyStrategy { void defender(BeliefState *state, int botID) { //print("Defender\n"); //It follows the ball Vec2D dpoint; dpoint.x = -HALF_FIELD_MAXX / 2; dpoint.y = state->ballPos.y; Vec2D goal; goal.x = HALF_FIELD_MAXX ; goal.y = (OPP_GOAL_MAXY+OPP_GOAL_MINY)/2; /*if(Vec2D::distSq(state->homePos[botID], state->ballPos) <= 6 * BOT_BALL_THRESH) { GoToBall(botID,state,true); GoToPoint(botID,state,goal,0,true,true); }*/ if ((state->ballPos.x >= -HALF_FIELD_MAXX*0.5) && (state->ballPos.x <= 0)) { Vec2D ballPoint(state->ballPos.x, state->ballPos.y); Vec2D dpoint(-HALF_FIELD_MAXX*0.5, state->ballPos.y); int awaybot = state->oppBotNearestToBall; if (Vec2D::distSq(state->awayPos[awaybot], state->ballPos) <= 6 * BOT_BALL_THRESH) { if (state->ballPos.y>=OUR_GOAL_MAXY) dpoint.y = OUR_GOAL_MAXY; if (state->ballPos.y<=OUR_GOAL_MINY) dpoint.y = OUR_GOAL_MINY; GoToPoint(botID, state, dpoint, 0 , true,false); if(Vec2D::distSq(state->homePos[botID], state->ballPos) <= 6 * BOT_BALL_THRESH) { GoToPoint(botID,state,goal,0,true,true); } } else GoToPoint(botID, state, ballPoint, 0, true, true); } else if (state->ballPos.x>=0) { dpoint.x = -HALF_FIELD_MAXX / 2; dpoint.y = state->ballPos.y; if (state->ballPos.y>(0.75)*HALF_FIELD_MAXY) dpoint.y = (0.75)*HALF_FIELD_MAXY; if (state->ballPos.y<-(0.75)*HALF_FIELD_MAXY) dpoint.y = -(0.75)*HALF_FIELD_MAXY; GoToPoint(botID, state, dpoint, PI / 2, false, false); } // GoToPoint(1,state,dpoint,PI/2,false,false); if (state->homePos[botID].x <= -HALF_FIELD_MAXX+1000) { dpoint.y = state->ballPos.y; dpoint.x = -HALF_FIELD_MAXX +2000; GoToPoint(botID, state, dpoint, PI / 2, false, false); } if ((state->homePos[botID].y<=OPP_GOAL_MAXY+600) && (state->homePos[botID].y>=0) && (state->homePos[botID].x >= HALF_FIELD_MAXX - 1000)) { Vec2D dPoint(state->ballPos.x, OPP_GOAL_MAXY+600); GoToPoint(botID, state, dPoint, 0, false, true); } if ((state->homePos[botID].y >= OPP_GOAL_MINY-600) && (state->homePos[botID].y<=0) && (state->homePos[botID].x>=HALF_FIELD_MAXX - 1000)) { Vec2D dPoint(state->ballPos.x, OPP_GOAL_MINY-600); GoToPoint(botID, state, dPoint, 0, false, true); } // part when ball is deep in our zone } }
C++
UTF-8
997
3.53125
4
[]
no_license
/* 插入排序的思想: 1.定位插入排序---直接插入法 2.定位插入位置---二分插入法 3.缩小增量多遍插入排序---希尔排序法 首先看直接插入排序:使用的是顺序查找的方法 int arr[]是一组待排序的数字,elem为需要插入的元素 n为该数组中全部的数据的长度, 具体实现思想是:将需要插入的数elem插入前面一个有序的数组中,比如当前的位置为i, 这时候需要将目前的位置的数取出来,暂存在temp临时变量中,即temp=arr[i],然后在循环内部采用的是循环, 令int j=i-1; for() */ //直接插入法 请查看drawable 中的directinsertimg.png 看执行过程 void directInsert(int arr[],int elem,int n){ int temp,j; for(int i=1;i<n;i++){ temp=arr[i]; for (int j = i-1;j>=0 && temp<arr[j]; j--) //升序排列,如果当前的temp值小于arr【j】的值,则要 { arr[j++]=arr[j]; } arr[j+1]=temp; } }
Java
UTF-8
1,385
3.953125
4
[]
no_license
import java.util.*; /* 89 Gray Code 32.8% Medium Problem: Gray Code Difficulty: Easy Source: https://oj.leetcode.com/problems/gray-code/ Notes: The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 00 - 0 01 - 1 11 - 3 10 - 2 Note: For a given n, a gray code sequence is not uniquely defined. For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. Solution: Refer to http://en.wikipedia.org/wiki/Gray_code. */ public class GrayCode { public List<Integer> grayCode(int n){ ArrayList<Integer> res = new ArrayList<Integer>(); for (int i =0; i<1<<n;++i){ res.add((int)((i>>1)^i)); } return res; } public static void main(String[] args) { // TODO Auto-generated method stub GrayCode slt = new GrayCode(); Scanner sc = new Scanner(System.in); System.out.println("Please Given a non-negative integer n representing the total number of bits"); int n = sc.nextInt(); List<Integer> res = slt.grayCode(n); System.out.println(res); } }
Markdown
UTF-8
4,360
4.15625
4
[]
no_license
#Reverse Words in a String For example, Given s = "the sky is blue", return "blue is sky the". 1. 非 in-place 的版本: 切分,组合 开始的时候直接用 Python秒写了一个, 最主要得益于 Python的split函数,貌似C++没有这个函数? class Solution: # @param s, a string # @return a string def reverseWords(self, s): s = s.strip() wordList = s.split() output = "" for word in wordList: output = word + " " +output output = output[0:-1] return output 使用c++写,没有强大的split函数,只好自己处理空格 class Solution { public: void reverseWords(string &s) { const int n = s.size(); vector<string> words; string word=""; for(int i=0;i<n;i++){ if(s[i]==' '){ if(word.size()!=0){ words.push_back(word); word=""; } }else{ word = word+s[i]; } } if(word.size()!=0) words.push_back(word); string output; const int m = words.size(); for(int i=0;i<m;i++){ if(i==0) output = words.back(); else output = output + " "+ words.back(); words.pop_back(); } s = output; } }; 开始写成了这个样子 class Solution { public: void reverseWords(string &s) { const int n = s.size(); vector<string> words; string word=""; for(int i=0;i<n;i++){ if(s[i]==' '){ if(word.size()!=0){ words.push_back(word); word=""; } }else{ word = word+s[i]; } } if(word.size()!=0) words.push_back(word); string output; /* 这里每次都会重新计算 words.size(),如果原来vector中有两个,只能pop出来一个 i在增加 而 上界在减小 推广: 如果一个 vector<int> : {1,2,3,4,5} i和上界的变化是 0 5 1 4 2 3 3 2 : break 这么做会输出 5 4 3 */ for(int i=0;i<words.size();i++){ output = output + words.back(); words.pop_back(); } s = output; } }; 2. in-place的方法 有一个经典的题,把 www.baidu.com 翻转成 com.baidu.www 第一次,先翻转所有字符 第二次,局部翻转 这里不一样的地方在于要处理空格,增加了一些难度,再增加一步处理空格即可 class Solution { public: /* inplace 1. 消除多余空格 2. 全部翻转 3. 局部翻转 */ void reverseWords(string &s) { const int n = s.size(); if(n==0) return; char lastChar = ' '; int appendIdx =0; //1 /*遇到字符或者字符后面的空格, 就append*/ for(int i=0;i<n;i++){ int elem = s[i]; if(elem!=' ') s[appendIdx++] = elem; else if(lastChar!=' ') s[appendIdx++] = elem; lastChar = elem; } if(s[appendIdx-1]==' ') appendIdx--; //如果最后一个是空格, 消去 const int len = appendIdx; //2 reverseStr(s, 0, len-1); //3 int lastStart = 0; for(int i=0;i<len;i++){ if(s[i]==' '){ reverseStr(s, lastStart,i-1); lastStart = i+1; } } reverseStr(s, lastStart,len-1); //别忘记最后一个 s = s.substr(0, len); } inline void reverseStr(string& s, int start, int end){ if(start>=end) return; int i=start, j=end; while(i<j) swap(s[i++], s[j--]); //Error:注意是 < 不是 != } }; 字符串为*号和26个字母的任意组合,把 *号都移动到最左侧,把字母移到最右侧并保持相对顺序不变,要求时间和空间复杂度最小。
C#
UTF-8
612
2.625
3
[ "MIT" ]
permissive
using Sitecore.Data.Fields; namespace Constellation.Foundation.ModelMapping.FieldMappers { /// <summary> /// An object for mapping a Sitecore Item Field's Value to a Property on a given Model. /// </summary> public interface IFieldMapper { /// <summary> /// Maps the supplied Field value to the supplied Model's property. /// </summary> /// <param name="modelInstance">The model to inspect.</param> /// <param name="field">The field to inspect.</param> /// <returns>The status of the mapping attempt.</returns> FieldMapStatus Map(object modelInstance, Field field); } }
Java
UTF-8
292
1.984375
2
[]
no_license
package com.example.studyprovider.service; import java.io.FileNotFoundException; import java.io.IOException; public interface FileService { //读取文件 boolean readFileAndSave(String prefix,String path); // 读取所有txt void readFile(String path) throws IOException; }
Python
UTF-8
528
2.515625
3
[]
no_license
from address.models import Address, Locality, State, Country def generate_country_data_for_testing(): country = Country.objects.create(name="Kenya", code="KE") state = State.objects.create(name="Nairobi", country=country) locality = Locality.objects.create(name="USIU", state=state) address = Address.objects.create( street_number="USIU Road Thika road", locality=locality, raw="USIU road", latitude="-1.2211537", longitude="36.88339089999999", ) return address
JavaScript
UTF-8
400
2.640625
3
[]
no_license
// Requires: importación de librerias var express = require( 'express' ); // libreria del servidor express // Inicializar variables var app = express(); // inicializar servidor express app.get( '/', ( request, response ) => { // enviar respuesta response.status( '200' ).json( { // status 200: OK ok: true, mensaje: 'Petición realizada correctamente' } ); } ); module.exports = app;
Java
UTF-8
3,519
2.765625
3
[]
no_license
package org.apache.tomcat.dbcp.pool2.impl; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import org.apache.tomcat.dbcp.pool2.PooledObjectFactory; /** * 特定用法实现. */ class PoolImplUtils { /** * 标识对象工厂创建的具体对象类型. * * @param factory 要检查的工厂 * * @return 工厂创建的对象类型 */ @SuppressWarnings("rawtypes") static Class<?> getFactoryType(final Class<? extends PooledObjectFactory> factory) { return (Class<?>) getGenericType(PooledObjectFactory.class, factory); } /** * 获取使用泛型类型的接口的实现所使用的具体类型. * * @param type 定义泛型类型的接口 * @param clazz 实现具体类型接口的类 * @param <T> 接口类型 * * @return 实现使用的具体类型 */ private static <T> Object getGenericType(final Class<T> type, final Class<? extends T> clazz) { // 查看此类是否实现了通用接口 // 获取所有接口 final Type[] interfaces = clazz.getGenericInterfaces(); for (final Type iface : interfaces) { // 只需要检查使用泛型的接口 if (iface instanceof ParameterizedType) { final ParameterizedType pi = (ParameterizedType) iface; // 寻找通用接口 if (pi.getRawType() instanceof Class) { if (type.isAssignableFrom((Class<?>) pi.getRawType())) { return getTypeParameter( clazz, pi.getActualTypeArguments()[0]); } } } } // 在此类中未找到接口. 查看父类. @SuppressWarnings("unchecked") final Class<? extends T> superClazz = (Class<? extends T>) clazz.getSuperclass(); final Object result = getGenericType(type, superClazz); if (result instanceof Class<?>) { // 超类实现接口并为泛型定义显式类型 return result; } else if (result instanceof Integer) { // 超类实现接口并为泛型定义未知类型 // 将未知类型映射到此类中定义的泛型类型 final ParameterizedType superClassType = (ParameterizedType) clazz.getGenericSuperclass(); return getTypeParameter(clazz, superClassType.getActualTypeArguments()[ ((Integer) result).intValue()]); } else { // 将在调用堆栈中进一步记录错误 return null; } } /** * 对于通用参数, 返回使用的Class 或类型未知, 类定义中的类型索引 * * @param clazz 定义类 * @param argType 感兴趣的类型参数 * * @return {@link Class}的实例,表示type参数使用的类型; 或{@link Integer}的实例,表示类定义中的类型的索引 */ private static Object getTypeParameter(final Class<?> clazz, final Type argType) { if (argType instanceof Class<?>) { return argType; } final TypeVariable<?>[] tvs = clazz.getTypeParameters(); for (int i = 0; i < tvs.length; i++) { if (tvs[i].equals(argType)) { return Integer.valueOf(i); } } return null; } }
C#
UTF-8
3,035
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace StudentApp { [XmlRoot(ElementName ="Student")] public class Student { [XmlAttribute(DataType ="string")] public string FirstName { get; set; } [XmlAttribute(DataType ="string")] public string LastName { get; set; } [XmlAttribute(DataType = "string")] public string ID { get; set; } [XmlAttribute(DataType = "string")] public string Address { get; set; } [XmlAttribute(DataType = "string")] public string Email { get; set; } [XmlAttribute(DataType = "string")] public string PhoneNumber { get; set; } [XmlAttribute(DataType = "string")] public string DOB { get; set; } [XmlAttribute(DataType = "string")] public string Gender { get; set; } [XmlAttribute(DataType = "string")] public string Race { get; set; } [XmlAttribute(DataType = "string")] public string LearningDisabilities { get; set; } [XmlAttribute(DataType = "double")] public double GPA { get; set; } [XmlAttribute(DataType = "string")] public string Department { get; set; } [XmlAttribute(DataType = "int")] public int EnrollmentYear { get; set; } [XmlAttribute(DataType = "int")] public int GraduationDate { get; set; } public Student() { FirstName = ""; LastName = ""; ID = ""; Address = ""; Email = ""; PhoneNumber = ""; DOB = ""; Gender = ""; LearningDisabilities = ""; GPA = 0; Department = ""; EnrollmentYear = 0; GraduationDate = 0; } public Student(string firstName, string lastName, string iD, string address, string email, string phoneNumber, string dOB, string gender, string race, string learningDisabilities, double gPA, string department, int enrollmentYear, int graduationDate) { FirstName = firstName; LastName = lastName; ID = iD; Address = address; Email = email; PhoneNumber = phoneNumber; DOB = dOB; Gender = gender; Race = race; LearningDisabilities = learningDisabilities; GPA = gPA; Department = department; EnrollmentYear = enrollmentYear; GraduationDate = graduationDate; } public override string ToString() { return string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}", this.FirstName, this.LastName, this.ID, this.Address, this.Email, this.PhoneNumber, this.DOB, this.Gender, this.Race, this.LearningDisabilities, this.GPA, this.GraduationDate ); } } }
Python
UTF-8
4,946
2.953125
3
[]
no_license
import sys import time import serial PRINTER_PORT = 'COM4' PRINTER_BAUDRATE = 38400 PRINTER_PARITY = 'N' def openSerialPort(port, baudrate, parity = 'N', timeout = 10): ser = serial.Serial() ser.port = port ser.baudrate = baudrate ser.parity = parity ser.xonxoff = False ser.rtscts = False ser.timeout = timeout ser.bytesize = 8 ser.stopbits = 1 ser.dsrdtr = False try: ser.open() except serial.SerialException, e: print "Greska u otvaranju porta " + port except: print "Greska: Nepoznata!" return ser def serialWrite(_ser, _str): _ser.write(_str) if __name__ == "__main__": ser = openSerialPort(PRINTER_PORT, PRINTER_BAUDRATE, PRINTER_PARITY, 10) if not ser.isOpen(): print "Greska! Serijska veza nije uspostavljena!" sys.exit(1) # # Pocetna vrednost za x # x = 4 # # range za y i z # y = 5 # z = 7 # for y in range(1,y+1): # for z in range(1,z+1): # serialWrite(ser, "N\r\n") # serialWrite(ser, "JB\r\n") # serialWrite(ser, "A480,40,1,5,1,1,N,\"" + str(x) +"." + str(y) + "." + str(z) + "\"\r\n") # serialWrite(ser, "A280,40,1,5,1,1,N,\"" + str(x) +"." + str(y) + "." + str(z) + "\"\r\n") # serialWrite(ser, "A80,40,1,5,1,1,N,\"" + str(x) +"." + str(y) + "." + str(z) + "\"\r\n") # serialWrite(ser, "W1\r\n") # # pocetna vredost za a # a = 1 # # range za b # b = 100 # for b in range(1,b+1): # serialWrite(ser, "N\r\n") # serialWrite(ser, "JB\r\n") # serialWrite(ser, "A480,40,1,5,1,1,N,\"" + str(a) +"." + str(b) + "\"\r\n") # serialWrite(ser, "A280,40,1,5,1,1,N,\"" + str(a) +"." + str(b) + "\"\r\n") # serialWrite(ser, "A80,40,1,5,1,1,N,\"" + str(a) +"." + str(b) + "\"\r\n") # serialWrite(ser, "UN\r\n") # serialWrite(ser, "W1\r\n") # f = open (template, 'rb') # x = open ("log", 'wb') # try: # temp = f.read(255) # while temp: # serialWrite(ser, temp) # x.write(temp) # temp = f.read(255) # finally: # x.close() # f.close() # ser.close() # ugradjeni font # serialWrite(ser, "I8,001\r\n") # serialWrite(ser, "N\r\n") # serialWrite(ser, "H10\r\n") # serialWrite(ser, "CF1,M,Monaco\r\n") # serialWrite(ser, "A400,100,2,2,2,2,N,\"SXY8/AO\"\r\n") # serialWrite(ser, "A400,100,2,2,2,2,N,\"SXY80AO\"\r\n") # serialWrite(ser, "g10\r\n") # serialWrite(ser, "W1\r\n") # serialWrite(ser, "GG14,6,\"SSGFX000\"\r\n") # # serialWrite(ser, "B550,274,2,1,4,4,120,N,\"aleksandar.zivkovic@rt-rk\"\r\n") # serialWrite(ser, "A540,320,2,1,2,3,N,\"----- Ruter -----\"\r\n") # serialWrite(ser, "A540,270,2,1,2,3,N,\"SSID: Tester\"\r\n") # serialWrite(ser, "A540,220,2,1,2,3,N,\"pass: TestBed01\"\r\n") # serialWrite(ser, "A540,220,2,1,2,3,N,\"pass: TestBed/1\"\r\n") # serialWrite(ser, "A540,160,2,1,2,3,N,\"--- RT Executor ---\"\r\n") # serialWrite(ser, "A540,110,2,1,2,3,N,\"user: tester\"\r\n") # serialWrite(ser, "A540,60,2,1,2,3,N,\"user: 1234\"\r\n") # serialWrite(ser, "W1\r\n") # serialWrite(ser, "GK\"SSGFX000\"\r\n") ime = "B.Radin" for i in xrange(2): # Stop za lepljenje na laptop serialWrite(ser, "N\r\n") # serialWrite(ser, "A540,300,2,1,3,4,N,\"" + ime + "\"\r\n") # serialWrite(ser, "A540,200,2,1,3,4,N,\"" + ime + "\"\r\n") # serialWrite(ser, "A540,100,2,1,3,4,N,\"" + ime + "\"\r\n") serialWrite(ser, "A540,300,2,1,3,4,N,\"Rezervisano\"\r\n") serialWrite(ser, "A540,200,2,1,3,4,N,\"Aleksandar\"\r\n") serialWrite(ser, "A540,100,2,1,3,4,N,\"Nikolic\"\r\n") serialWrite(ser, "W1\r\n") # # Continue # serialWrite(ser, "N\r\n") # serialWrite(ser, "B520,274,2,1,4,4,120,N,\"Continue\"\r\n") # serialWrite(ser, "A495,140,2,4,2,3,N,\"Continue\"\r\n") # serialWrite(ser, "W1\r\n") # # Pass # serialWrite(ser, "N\r\n") # serialWrite(ser, "B450,274,2,1,4,4,120,N,\"Pass\"\r\n") # serialWrite(ser, "A390,140,2,4,2,3,N,\"Pass\"\r\n") # serialWrite(ser, "W1\r\n") # # Fail # serialWrite(ser, "N\r\n") # serialWrite(ser, "B450,274,2,1,4,4,120,N,\"Fail\"\r\n") # serialWrite(ser, "A390,140,2,4,2,3,N,\"Fail\"\r\n") # serialWrite(ser, "W1\r\n") # serialWrite(ser, "N\r\n") # serialWrite(ser, "A510,285,2,A,2,2,N,\"AMonakOo0\"\r\n") # # serialWrite(ser, "A510,225,2,3,2,2,N,\"NIKOLIC\"\r\n") # # serialWrite(ser, "A510,145,2,3,2,2,N,\"SERBIA\"\r\n") # # serialWrite(ser, "A510,85,2,2,2,2,N,\"+381652939960\"\r\n") # serialWrite(ser, "W1\r\n") ser.close()
Python
UTF-8
29,032
2.875
3
[]
no_license
#!/home/operador/anaconda3/envs/auxdechycom/bin/python # -*- coding: utf-8 -*- # -*- coding: iso-8859-1 -*- # =====================================================================> # Script que gera as figuras do modelo ADCIRC. # Resolucao: 1/24 graus. # # Autora: 1T(T) LIANA # # Data corrente: python ftp_adcirc.py variável prognóstico_final área # python ftp_adcirc.py hs 69 bg # # Outras datas: python ftp_adcirc.py variável prognóstico_final área ano mês dia # python ftp_adcirc.py hs 69 bg 2020 05 15 # # variáveis: hs, tp, tmm, curr, zeta # prognóstico_final: até 69 (saídas de 30 em 30 min; não pode ser 70 porque o último horário disponível é 23:30 e não 00:00) # áreas: bg, sig, ssib # =====================================================================> # IMPORTACAO DE BIBLIOTECAS import datetime, time import os, sys import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import scipy import os import warnings warnings.filterwarnings("ignore") from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap os.environ['QT_QPA_PLATFORM']='offscreen' # =====================================================================> ### ARGUMENTOS if len(sys.argv)<3: print('-------------------------------------------------') print('| Você deve entrar com os argumentos: |') print('| variavel(hs,tp,tmm,curr,zeta), prog, |') print('| area(bg,sig,ssib), data(OPCIONAL) |') print('| |') print('| Ex1: python ftp_adcirc.py hs 69 bg |') print('| Ex2: python ftp_adcirc.py hs 69 bg 2020 08 20 |') print('-------------------------------------------------') exit() ## FUNÇAO def horarios(data): horas=[] ano = data[0:4] mes = data[4:6] dia = data[6:8] horas.append(ano) horas.append(mes) horas.append(dia) return horas ### PERÍODO ESCOLHIDO if len(sys.argv)==7: # usuário entra com a data desejada year = sys.argv[4] mon = sys.argv[5] day = sys.argv[6] else: # usuário não entra com a data desejada. roda a data corrente fdata = open('/home/operador/datas/datacorrente00') datacorrente = fdata.readlines() datacorrente = datacorrente[0][0:-1] year = datacorrente[0:4] mon = datacorrente[4:6] day = datacorrente[6:] data = horarios('{0}{1}{2}'.format(year, mon, day)) base = datetime.date(int(data[0]),int(data[1]),int(data[2])) iprog = 0 # prognostico inicial fprog = int(sys.argv[2])*2 # prognostico final. multipliquei porque o prognostico final real é 138 (para que os prognosticos fiquem iguais aos horarios nas figuras) --> antes, o prog 006 era 03Z, o prog 012 era 06Z e assim por diante. agora, o prog 006 é 06Z e assim por diante numdays = int((fprog - iprog)/(2*24)) # número de dias (2*24 pq é de 30 em 30 min) date_list = [base + datetime.timedelta(days=x) for x in range(0, numdays+2)] # +2 pra garantir que vai plotar o 00Z do dia seguinte datai = date_list[0]; datai=datai.strftime('%Y%m%d') dataf = date_list[-1]; dataf=dataf.strftime('%Y%m%d') ### Prognóstico final if int(sys.argv[2]) > 69: print('----------------------------------------') print('| O prognóstico final só vai até 69. |') print('| Você deve escolher um valor menor. |') print('----------------------------------------') exit() # =====================================================================> ### DADOS FORNECIDOS PELO USUARIO: ## Variáveis a serem utilizadas: dict_var = {'hs':'Hs', 'tp':'Tp', 'tmm':'Tmm', 'zeta':'Zeta', 'curr':'Correntes'} ## Áreas a serem utilizadas: dict_area = {'bg':'BG', 'sig':'SIG', 'ssib':'SSIB'} ## Nomes para o gráfico dict_title_pt = {'hs':'Alt. Sig. Ondas(m)', 'tp':'Per. Pico Ondas(seg)', 'tmm':'Per Med. Ondas(seg)', 'zeta':'Nivel do Mar(m)', 'curr':'velocidade das correntes(nos)'} dict_title_en = {'hs':'Sig. Wave Heigth(m)', 'tp':'Wave Peak Per.(seg)', 'tmm':'Wave Avg. Per.(seg)', 'zeta':'Sea Level(m)', 'curr':'Currents Velocity(knots)'} dict_title_mon = {'01':'JAN', '02':'FEV','03':'MAR', '04':'ABR', '05':'MAR', '06':'JUN', '07':'JUL', '08':'AGO','09':'SET', '10':'OUT', '11':'NOV', '12':'DEZ'} dict_title_day = {r'Sunday':'Dom', 'Monday':'Seg', 'Tuesday':'Ter', 'Wednesday':'Qua', 'Thursday':'Qui', 'Friday':'Sex', 'Saturday':'Sab', 'domingo':'Dom', 'segunda':'Seg', 'terça':'Ter', 'quarta':'Qua', 'quinta':'Qui','sexta':'Sex','sábado':'Sab'} var_cbar = {r'hs':'altura significativa [m]', 'tp':'período de pico [s]', 'tmm':'período médio [s]', 'curr':'velocidade da corrente [nos]', 'zeta':'nível do mar [m]'} figname = {'hs':'ondas', 'tp':'periopeak', 'tmm':'periondas', 'zeta':'nivel', 'curr':'correntes'} ## Características do gráfico # Espaçamento do quiver skip = 40 # Range de valores da escala (contourf e contour) if sys.argv[1] == "hs": label_bar_cntrf = np.linspace(0,4,num=9) label_bar_cntr = [0.5, 1.5, 3.0, 4.0] elif sys.argv[1] == "tp": # não tem Dp label_bar_cntrf = np.linspace(4,22,num=19) label_bar_cntr = [12.0, 14.0, 16.0] elif sys.argv[1] == "tmm": label_bar_cntrf = np.linspace(4,22,num=19) label_bar_cntr = [12.0, 14.0, 16.0] elif sys.argv[1] == "curr": label_bar_cntrf = np.linspace(0,1,num=11) label_bar_cntr = [0.2, 0.5, 0.8, 1.0] elif sys.argv[1] == "zeta": label_bar_cntrf = np.linspace(0,1.5,num=11) label_bar_cntr = [0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5] # Range de valores das coordenadas if sys.argv[3] == "bg": range_lat = 0.20 range_lon = 0.20 fraction = 0.2 plot_area = plt.figure() elif sys.argv[3] == "sig": range_lat = 0.20 range_lon = 0.40 fraction = 0.031 plot_area = plt.figure(figsize=(8,5)) elif sys.argv[3] == "ssib": range_lat = 0.20 range_lon = 1 fraction = 0.15 plot_area = plt.figure(figsize=(8,5)) ## Diretórios filepath = '/mnt/nfs/dpns32/data1/operador/Aplicativos_REMO/ADCIRC/adcirc_novacomp/adcircswan_{0}_operacional/'.format(dict_area[sys.argv[3]]) adcpath = '/home/operador/grads/gif/adcirc/' if not os.path.exists(adcpath): os.makedirs(adcpath) # =====================================================================> ### Plotando as variaveis do ADCIRC ## ALTURA SIGNIFICATIVA E DIREÇÃO MEDIA ================================ if sys.argv[1] == "hs": day = date_list[0] # dia da rodada dayname = day.strftime('%A') # nome do dia da semana para o dia da rodada (ex: seg, ter) # Arquivo de Hs nc_file = filepath+datai+'/'+'ADCIRC_{0}_hs_'.format(dict_area[sys.argv[3]])+datai+'_graderegular.nc' while not os.path.exists(nc_file): print(u'Arquivo não existe... sleep 60s') time.sleep(60) print('Arquivo existe') print() print('---------------------------------------') print('Plotando --> Altura significativa ({0})'.format(dict_area[sys.argv[3]])) print('---------------------------------------') nc_fid = Dataset(nc_file, 'r') lat = nc_fid.variables['lat'][:] lon = nc_fid.variables['lon'][:] lat_sul = np.nanmin(lat) lat_norte = np.nanmax(lat) lon_oeste = np.nanmin(lon) lon_leste = np.nanmax(lon) lat_s = float(lat_sul) lat_n = float(lat_norte) lat_media = -((-lat_s)+(-lat_n))/2 lat_media = str(lat_media) hs = nc_fid.variables['hs'][iprog:fprog+1,:,:] hs = np.squeeze(hs) # Arquivo de direção média de onda nc_dire = filepath+datai+'/'+'ADCIRC_{0}_dir_'.format(dict_area[sys.argv[3]])+datai+'_graderegular.nc' nc_fid = Dataset(nc_dire, 'r') wdir = nc_fid.variables['dir'][iprog:fprog+1,:,:] wdir = 270-wdir # direção de convenção do SWAN (270-direção) wdir = np.squeeze(wdir) u = np.cos(wdir*np.pi/180) v = np.sin(wdir*np.pi/180) hh=0 # HH dd=0 # dia do prognóstico for prog in range(0,fprog+1,6): # range de 6 em 6 = range de 3 em 3 horas print(' Processando figura da data:',datai+',', 'prog:', '{0:02d}Z{1}'.format(hh, date_list[dd].strftime('%Y%m%d'))) # Data do prognóstico dayprog = date_list[dd] # dia do prognóstico dt = dayprog.strftime('%Y%m%d') daynameprog = dayprog.strftime('%A') # nome do dia da semana para o dia do prognóstico (ex: seg, ter) # Selecionando dados para plot hss = (hs[prog,:,:]); hss = np.squeeze(hss) uu = (u[prog,:,:]); uu = np.squeeze(uu) vv = (v[prog,:,:]); vv = np.squeeze(vv) # Retirando flags Hs for i in range(0,np.shape(uu)[0]): for j in range(0,np.shape(uu)[1]): if hss[i,j]>1.0e+5: hss[i,j]=np.nan # Iniciando o plot fig = plot_area m = Basemap(projection='merc', llcrnrlat=lat_s, urcrnrlat=lat_n, llcrnrlon = float(lon_oeste), urcrnrlon=float(lon_leste), lat_ts=float(lat_media), resolution='h') x,y = m(lon,lat) # Linhas de contorno cntrf = m.contourf(x,y,hss,levels=label_bar_cntrf,cmap=plt.cm.jet) cntr = m.contour(x,y,hss, levels=label_bar_cntr, colors='k') plt.clabel(cntr, colors='k', fontsize=8, fmt = '%2.1f') # Destacar linha de 2.5m label_25 = [2.5] cntr25 = m.contour(x,y,hss, levels=label_25, colors='r') plt.clabel(cntr25, colors='r', fontsize=8, fmt = '%2.1f') # Escala cbar = plt.colorbar(cntrf, format='%.2f', fraction=fraction, pad=0.04) cbar.ax.set_ylabel(var_cbar[sys.argv[1]]) # Paralelos e meridianos m.drawcoastlines(linewidth=0.5, color='k') m.fillcontinents(color='gray') m.drawparallels(np.arange(float(lat_sul), float(lat_norte), range_lat), labels=[1,0,0,0],fmt='%.2f') m.drawmeridians(np.arange(float(lon_oeste),float(lon_leste), range_lon), labels=[0,0,0,1],fmt='%.2f') # Incluindo os vetores de direção de onda na figura Q = m.quiver(x[::skip, ::skip], y[::skip, ::skip], uu[::skip, ::skip], vv[::skip, ::skip], scale=40, width=0.008, headlength=5, headwidth=3.5, headaxislength=5, pivot='tail', color='k', minshaft=2, minlength=1) # Título if prog == 0: # prog 00 progname = '00Z{0}{1}{2} ({3}) - Analise'.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname]) else: # prog > 00 prog = int(prog/2) # essa divisao foi feita para o nome da figura ficar igual ao horario de previsao progname = 'Ref: 00Z{0}{1}{2} ({3}) +PROG{4:02d}/Val:{5:02d}Z{6}{7}{8} ({9}) '.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname], prog, hh, dt[6:8], dict_title_mon[dt[4:6]], dt[0:4], dict_title_day[daynameprog]) plt.title('MODELO ADCIRC/SiWAN - '+'{0} '.format(dict_title_pt[sys.argv[1]])+' - ADCIRC/SWAN Model - '+ \ '{0} \n'.format(dict_title_en[sys.argv[1]]) + progname, fontsize=8) # Salvando as figuras figpath = os.path.join(adcpath, sys.argv[3]) if not os.path.exists(figpath): os.makedirs(figpath) figpng = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.png'.format(prog)) figgif = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.gif'.format(prog)) convert_fig = '/usr/bin/convert {0} {1}'.format(figpng, figgif) # converter .png em .gif plt.savefig(figpng, dpi=300) os.system(convert_fig) # converter .png em .gif plt.close() hh=hh+3 if hh==24: # hh = 24h --> muda o dia hh=0 # zera a contagem dos prognósticos do dia dd=dd+1 # muda de dia ## PERÍODO DE PICO ===================================================== elif sys.argv[1] == "tp": print() day = date_list[0] # dia da rodada dayname = day.strftime('%A') # nome do dia da semana para o dia da rodada (ex: seg, ter) # Arquivo de Tp nc_file = filepath+datai+'/'+'ADCIRC_{0}_tps_'.format(dict_area[sys.argv[3]])+datai+'_graderegular.nc' while not os.path.exists(nc_file): print(u'Arquivo não existe... sleep 60s') time.sleep(60) print('Arquivo existe') print() print('----------------------------------') print('Plotando --> Periodo de pico ({0})'.format(dict_area[sys.argv[3]])) print('----------------------------------') nc_fid = Dataset(nc_file, 'r') lat = nc_fid.variables['lat'][:] lon = nc_fid.variables['lon'][:] lat_sul = np.nanmin(lat) lat_norte = np.nanmax(lat) lon_oeste = np.nanmin(lon) lon_leste = np.nanmax(lon) lat_s = float(lat_sul) lat_n = float(lat_norte) lat_media = -((-lat_s)+(-lat_n))/2 lat_media = str(lat_media) tp = nc_fid.variables['tps'][iprog:fprog+1,:,:] tp = np.squeeze(tp) hh=0 # HH dd=0 # dia do prognóstico for prog in range(0,fprog+1,6): # range de 6 em 6 = range de 3 em 3 horas print(' Processando figura da data:',datai+',', 'prog:', '{0:02d}Z{1}'.format(hh, date_list[dd].strftime('%Y%m%d'))) # Data do prognóstico dayprog = date_list[dd] # dia do prognóstico dt = dayprog.strftime('%Y%m%d') daynameprog = dayprog.strftime('%A') # nome do dia da semana para o dia do prognóstico (ex: seg, ter) # Selecionando dados para plot tpp = (tp[prog,:,:]); tpp = np.squeeze(tpp) # Retirando flags Tp for i in range(0,np.shape(tpp)[0]): for j in range(0,np.shape(tpp)[1]): if tpp[i,j]>1.0e+5: tpp[i,j]=np.nan # Iniciando o plot fig = plot_area m = Basemap(projection='merc', llcrnrlat=lat_s, urcrnrlat=lat_n, llcrnrlon = float(lon_oeste), urcrnrlon=float(lon_leste), lat_ts=float(lat_media), resolution='h') x,y = m(lon,lat) # Linhas de contorno cntrf = m.contourf(x,y,tpp,levels=label_bar_cntrf,cmap=plt.cm.jet) cntr = m.contour(x,y,tpp, levels=label_bar_cntr, colors='k') plt.clabel(cntr, colors='k', fontsize=8, fmt = '%2.1f') # Escala cbar = plt.colorbar(cntrf, format='%.2f', fraction=fraction, pad=0.04) cbar.ax.set_ylabel(var_cbar[sys.argv[1]]) # Paralelos e meridianos m.drawcoastlines(linewidth=0.5, color='k') m.fillcontinents(color='gray') m.drawparallels(np.arange(float(lat_sul), float(lat_norte), range_lat), labels=[1,0,0,0],fmt='%.2f') m.drawmeridians(np.arange(float(lon_oeste),float(lon_leste), range_lon), labels=[0,0,0,1],fmt='%.2f') # Título if prog == 0: # prog 00 progname = '00Z{0}{1}{2} ({3}) - Analise'.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname]) else: # prog > 00 prog = int(prog/2) # essa divisao foi feita para o nome da figura ficar igual ao horario de previsao progname = 'Ref: 00Z{0}{1}{2} ({3}) +PROG{4:02d}/Val:{5:02d}Z{6}{7}{8} ({9}) '.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname], prog, hh, dt[6:8], dict_title_mon[dt[4:6]], dt[0:4], dict_title_day[daynameprog]) plt.title('MODELO ADCIRC/SWAN - '+'{0} '.format(dict_title_pt[sys.argv[1]])+' - ADCIRC/SWAN Model - '+ \ '{0} \n'.format(dict_title_en[sys.argv[1]]) + progname, fontsize=8) # Salvando as figuras figpath = os.path.join(adcpath, sys.argv[3]) if not os.path.exists(figpath): os.makedirs(figpath) figpng = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.png'.format(prog)) figgif = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.gif'.format(prog)) convert_fig = '/usr/bin/convert {0} {1}'.format(figpng, figgif) # converter .png em .gif plt.savefig(figpng, dpi=300) os.system(convert_fig) # converter .png em .gif plt.close() hh=hh+3 if hh==24: # hh = 24h --> muda o dia hh=0 # zera a contagem dos prognósticos do dia dd=dd+1 # muda de dia ## PERÍODO MÉDIO ======================================================= elif sys.argv[1] == "tmm": day = date_list[0] # dia da rodada dayname = day.strftime('%A') # nome do dia da semana para o dia da rodada (ex: seg, ter) # Arquivo de Tmm nc_file = filepath+datai+'/'+'ADCIRC_{0}_tmm10_'.format(dict_area[sys.argv[3]])+datai+'_graderegular.nc' while not os.path.exists(nc_file): print(u'Arquivo não existe... sleep 60s') time.sleep(60) print('Arquivo existe') print() print('---------------------------------') print(r'Plotando --> Periodo médio ({0})'.format(dict_area[sys.argv[3]])) print('---------------------------------') nc_fid = Dataset(nc_file, 'r') lat = nc_fid.variables['lat'][:] lon = nc_fid.variables['lon'][:] lat_sul = np.nanmin(lat) lat_norte = np.nanmax(lat) lon_oeste = np.nanmin(lon) lon_leste = np.nanmax(lon) lat_s = float(lat_sul) lat_n = float(lat_norte) lat_media = -((-lat_s)+(-lat_n))/2 lat_media = str(lat_media) tm = nc_fid.variables['tmm10'][iprog:fprog+1,:,:] tm = np.squeeze(tm) # Arquivo de direção média de onda nc_dire = filepath+datai+'/'+'ADCIRC_{0}_dir_'.format(dict_area[sys.argv[3]])+datai+'_graderegular.nc' nc_fid = Dataset(nc_dire, 'r') wdir = nc_fid.variables['dir'][iprog:fprog+1,:,:] wdir = 270-wdir # direção de convenção do SWAN (270-direção) wdir = np.squeeze(wdir) u = np.cos(wdir*np.pi/180) v = np.sin(wdir*np.pi/180) hh=0 # HH dd=0 # dia do prognóstico for prog in range(0,fprog+1,6): # range de 6 em 6 = range de 3 em 3 horas print(' Processando figura da data:',datai+',', 'prog:', '{0:02d}Z{1}'.format(hh, date_list[dd].strftime('%Y%m%d'))) # Data do prognóstico dayprog = date_list[dd] # dia do prognóstico dt = dayprog.strftime('%Y%m%d') daynameprog = dayprog.strftime('%A') # nome do dia da semana para o dia do prognóstico (ex: seg, ter) # Selecionando dados para plot tmm = (tm[prog,:,:]); tmm = np.squeeze(tmm) uu = (u[prog,:,:]); uu = np.squeeze(uu) vv = (v[prog,:,:]); vv = np.squeeze(vv) # Retirando flags Tmm for i in range(0,np.shape(uu)[0]): for j in range(0,np.shape(uu)[1]): if tmm[i,j]>1.0e+5: tmm[i,j]=np.nan # Iniciando o plot fig = plot_area m = Basemap(projection='merc', llcrnrlat=lat_s, urcrnrlat=lat_n, llcrnrlon = float(lon_oeste), urcrnrlon=float(lon_leste), lat_ts=float(lat_media), resolution='h') x,y = m(lon,lat) # Linhas de contorno cntrf = m.contourf(x,y,tmm,levels=label_bar_cntrf,cmap=plt.cm.jet) cntr = m.contour(x,y,tmm, levels=label_bar_cntr, colors='k') plt.clabel(cntr, colors='k', fontsize=8, fmt = '%2.1f') # Escala cbar = plt.colorbar(cntrf, format='%.2f', fraction=fraction, pad=0.04) cbar.ax.set_ylabel(var_cbar[sys.argv[1]]) # Paralelos e meridianos m.drawcoastlines(linewidth=0.5, color='k') m.fillcontinents(color='gray') m.drawparallels(np.arange(float(lat_sul), float(lat_norte), range_lat), labels=[1,0,0,0],fmt='%.2f') m.drawmeridians(np.arange(float(lon_oeste),float(lon_leste), range_lon), labels=[0,0,0,1],fmt='%.2f') # Incluindo os vetores de direção de onda na figura Q = m.quiver(x[::skip, ::skip], y[::skip, ::skip], uu[::skip, ::skip], vv[::skip, ::skip], scale=40, width=0.008, headlength=5, headwidth=3.5, headaxislength=5, pivot='tail', color='k', minshaft=2, minlength=1) # Título if prog == 0: # prog 00 progname = '00Z{0}{1}{2} ({3}) - Analise'.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname]) else: # prog > 00 progname = 'Ref: 00Z{0}{1}{2} ({3}) +PROG{4:02d}/Val:{5:02d}Z{6}{7}{8} ({9}) '.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname], prog, hh, dt[6:8], dict_title_mon[dt[4:6]], dt[0:4], dict_title_day[daynameprog]) plt.title('MODELO ADCIRC/SWAN - '+'{0} '.format(dict_title_pt[sys.argv[1]])+' - ADCIRC/SWAN Model - '+ \ '{0} \n'.format(dict_title_en[sys.argv[1]]) + progname, fontsize=8) # Salvando as figuras figpath = os.path.join(adcpath, sys.argv[3]) if not os.path.exists(figpath): os.makedirs(figpath) figpng = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.png'.format(prog)) figgif = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.gif'.format(prog)) convert_fig = '/usr/bin/convert {0} {1}'.format(figpng, figgif) # converter .png em .gif plt.savefig(figpng, dpi=300) os.system(convert_fig) # converter .png em .gif plt.close() hh=hh+3 if hh==24: # hh = 24h --> muda o dia hh=0 # zera a contagem dos prognósticos do dia dd=dd+1 # muda de dia ## CORRENTE SUPERFICIAL ================================================ elif sys.argv[1] == "curr": day = date_list[0] # dia da rodada dayname = day.strftime('%A') # nome do dia da semana para o dia da rodada (ex: seg, ter) # Arquivo de correntes superficiais nc_file = filepath+datai+'/'+'ADCIRC_{0}_uv_'.format(dict_area[sys.argv[3]])+datai+'_graderegular.nc' while not os.path.exists(nc_file): print(u'Arquivo não existe... sleep 60s') time.sleep(60) print('Arquivo existe') print() print('------------------------------------------') print(r'Plotando --> Correntes superficiais ({0})'.format(dict_area[sys.argv[3]])) print('------------------------------------------') nc_fid = Dataset(nc_file, 'r') lat = nc_fid.variables['lat'][:] lon = nc_fid.variables['lon'][:] lat_sul = np.nanmin(lat) lat_norte = np.nanmax(lat) lon_oeste = np.nanmin(lon) lon_leste = np.nanmax(lon) lat_s = float(lat_sul) lat_n = float(lat_norte) lat_media = -((-lat_s)+(-lat_n))/2 lat_media = str(lat_media) u = nc_fid.variables['u'][iprog:fprog+1,:,:] v = nc_fid.variables['v'][iprog:fprog+1,:,:] u = np.squeeze(u); v = np.squeeze(v) hh=0 # HH dd=0 # dia do prognóstico for prog in range(0,fprog+1,6): # range de 6 em 6 = range de 3 em 3 horas print(' Processando figura da data:',datai+',', 'prog:', '{0:02d}Z{1}'.format(hh, date_list[dd].strftime('%Y%m%d'))) # Data do prognóstico dayprog = date_list[dd] # dia do prognóstico dt = dayprog.strftime('%Y%m%d') daynameprog = dayprog.strftime('%A') # nome do dia da semana para o dia do prognóstico (ex: seg, ter) # Selecionando dados para plot uu = (u[prog,:,:]); uu = np.squeeze(uu) vv = (v[prog,:,:]); vv = np.squeeze(vv) # Retirando flags for i in range(0,np.shape(uu)[0]): for j in range(0,np.shape(uu)[1]): if uu[i,j]>1.0e+5: uu[i,j]=np.nan if vv[i,j]>1.0e+5: vv[i,j]=np.nan # ~ M = np.sqrt(uu**2+vv**2) # magnitude correntes m/s M = np.sqrt(uu**2+vv**2)*1.94384 # magnitude correntes nós U = np.zeros((1298,1335)) V = np.zeros((1298,1335)) for i in range(0,1298): for j in range(0,1335): try: U[i,j] = uu[i,j]/M[i,j] V[i,j] = vv[i,j]/M[i,j] except: pass # Iniciando o plot fig = plot_area m = Basemap(projection='merc', llcrnrlat=lat_s, urcrnrlat=lat_n, llcrnrlon = float(lon_oeste), urcrnrlon=float(lon_leste), lat_ts=float(lat_media), resolution='h') x,y = m(lon,lat) # Linhas de contorno cntrf = m.contourf(x,y,M,levels=label_bar_cntrf,cmap=plt.cm.jet) cntr = m.contour(x,y,M, levels=label_bar_cntr, colors='k') plt.clabel(cntr, colors='k', fontsize=8, fmt = '%2.1f') # Escala cbar = plt.colorbar(cntrf, format='%.2f', fraction=fraction, pad=0.04) cbar.ax.set_ylabel(var_cbar[sys.argv[1]]) # Paralelos e meridianos m.drawcoastlines(linewidth=0.5, color='k') m.fillcontinents(color='gray') m.drawparallels(np.arange(float(lat_sul), float(lat_norte), range_lat), labels=[1,0,0,0],fmt='%.2f') m.drawmeridians(np.arange(float(lon_oeste),float(lon_leste), range_lon), labels=[0,0,0,1],fmt='%.2f') # Incluindo os vetores de corrente na figura Q = m.quiver(x[::skip, ::skip], y[::skip, ::skip], U[::skip, ::skip], V[::skip, ::skip], scale=4, units='inches', scale_units='inches', width=0.008, headlength=5, headwidth=3.5,headaxislength=5, pivot='tail', color='k', minshaft=2, minlength=1) # Título if prog == 0: # prog 00 progname = '00Z{0}{1}{2} ({3}) - Analise'.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname]) else: # prog > 00 progname = 'Ref: 00Z{0}{1}{2} ({3}) +PROG{4:02d}/Val:{5:02d}Z{6}{7}{8} ({9}) '.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname], prog, hh, dt[6:8], dict_title_mon[dt[4:6]], dt[0:4], dict_title_day[daynameprog]) plt.title('MODELO ADCIRC/SWAN - '+'{0} '.format(dict_title_pt[sys.argv[1]])+' - ADCIRC/SWAN Model - '+ \ '{0} \n'.format(dict_title_en[sys.argv[1]]) + progname, fontsize=8) # Salvando as figuras figpath = os.path.join(adcpath, sys.argv[3]) if not os.path.exists(figpath): os.makedirs(figpath) figpng = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.png'.format(prog)) figgif = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.gif'.format(prog)) convert_fig = '/usr/bin/convert {0} {1}'.format(figpng, figgif) # converter .png em .gif plt.savefig(figpng, dpi=300) os.system(convert_fig) # converter .png em .gif plt.close() hh=hh+3 if hh==24: # hh = 24h --> muda o dia hh=0 # zera a contagem dos prognósticos do dia dd=dd+1 # muda de dia ## NÍVEL DO MAR ======================================================== elif sys.argv[1] == "zeta": day = date_list[0] # dia da rodada dayname = day.strftime('%A') # nome do dia da semana para o dia da rodada (ex: seg, ter) # Arquivo de zeta nc_file = filepath+datai+'/'+'ADCIRC_{0}_zeta_'.format(dict_area[sys.argv[3]])+datai+'_graderegular.nc' while not os.path.exists(nc_file): print(u'Arquivo não existe... sleep 60s') time.sleep(60) print('Arquivo existe') print() print('--------------------------------') print(r'Plotando --> Nível do mar ({0})'.format(dict_area[sys.argv[3]])) print('--------------------------------') nc_fid = Dataset(nc_file, 'r') lat = nc_fid.variables['lat'][:] lon = nc_fid.variables['lon'][:] lat_sul = np.nanmin(lat) lat_norte = np.nanmax(lat) lon_oeste = np.nanmin(lon) lon_leste = np.nanmax(lon) lat_s = float(lat_sul) lat_n = float(lat_norte) lat_media = -((-lat_s)+(-lat_n))/2 lat_media = str(lat_media) zeta = nc_fid.variables['zeta'][iprog:fprog+1,:,:] zeta = np.squeeze(zeta) hh=0 # HH dd=0 # dia do prognóstico for prog in range(0,fprog+1,6): # range de 6 em 6 = range de 3 em 3 horas print(' Processando figura da data:',datai+',', 'prog:', '{0:02d}Z{1}'.format(hh, date_list[dd].strftime('%Y%m%d'))) # Data do prognóstico dayprog = date_list[dd] # dia do prognóstico dt = dayprog.strftime('%Y%m%d') daynameprog = dayprog.strftime('%A') # nome do dia da semana para o dia do prognóstico (ex: seg, ter) # Selecionando dados para plot zetaa = (zeta[prog,:,:]); zetaa = np.squeeze(zetaa) # Retirando flags zeta for i in range(0,np.shape(zetaa)[0]): for j in range(0,np.shape(zetaa)[1]): if zetaa[i,j]>1.0e+5: zetaa[i,j]=np.nan # Iniciando o plot fig = plot_area m = Basemap(projection='merc', llcrnrlat=lat_s, urcrnrlat=lat_n, llcrnrlon = float(lon_oeste), urcrnrlon=float(lon_leste), lat_ts=float(lat_media), resolution='h') x,y = m(lon,lat) # Linhas de contorno cntrf = m.contourf(x,y,zetaa,levels=label_bar_cntrf,cmap=plt.cm.jet) cntr = m.contour(x,y,zetaa,levels=label_bar_cntr, colors='k') plt.clabel(cntr, colors='k', fontsize=8, fmt = '%2.1f') # Escala cbar = plt.colorbar(cntrf, format='%.2f', fraction=fraction, pad=0.04) cbar.ax.set_ylabel(var_cbar[sys.argv[1]]) # Paralelos e meridianos m.drawcoastlines(linewidth=0.5, color='k') m.fillcontinents(color='gray') m.drawparallels(np.arange(float(lat_sul), float(lat_norte), range_lat), labels=[1,0,0,0],fmt='%.2f') m.drawmeridians(np.arange(float(lon_oeste),float(lon_leste), range_lon), labels=[0,0,0,1],fmt='%.2f') # Título if prog == 0: # prog 00 progname = '00Z{0}{1}{2} ({3}) - Analise'.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname]) else: # prog > 00 progname = 'Ref: 00Z{0}{1}{2} ({3}) +PROG{4:02d}/Val:{5:02d}Z{6}{7}{8} ({9}) '.format(datai[6:8], dict_title_mon[datai[4:6]], datai[0:4], dict_title_day[dayname], prog, hh, dt[6:8], dict_title_mon[dt[4:6]], dt[0:4], dict_title_day[daynameprog]) plt.title('MODELO ADCIRC/SWAN - '+'{0} '.format(dict_title_pt[sys.argv[1]])+' - ADCIRC/SWAN Model - '+ \ '{0} \n'.format(dict_title_en[sys.argv[1]]) + progname, fontsize=8) # Salvando as figuras figpath = os.path.join(adcpath, sys.argv[3]) if not os.path.exists(figpath): os.makedirs(figpath) figpng = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.png'.format(prog)) figgif = '{0}/{1}_{2}'.format(figpath, figname[sys.argv[1]], '{0:03d}.gif'.format(prog)) convert_fig = '/usr/bin/convert {0} {1}'.format(figpng, figgif) # converter .png em .gif plt.savefig(figpng, dpi=300) os.system(convert_fig) # converter .png em .gif plt.close() hh=hh+3 if hh==24: # hh = 24h --> muda o dia hh=0 # zera a contagem dos prognósticos do dia dd=dd+1 # muda de dia quit()
Markdown
UTF-8
485
2.53125
3
[]
no_license
# What is Enumeration? Enumeration is the process of extracting user names, machine names, network resources, shares, and services from a system, and its conducted in an intranet environment. In this phase, the attacker creates an active connection to the system and performs directed queries to gain more information about the target. The gathered information is used to identify the vulnerabilities or weak points in system security and tries to exploit in the System gaining phase.
Java
UTF-8
375
2.53125
3
[]
no_license
package sys; /** * @author chenwf: * @date 创建时间:2017年7月15日 上午9:12:10 * @version 1.0 * @parameter * @return */ public class TestMethod { public static void main(String[] args) { String string = ""; for (int i = 0; i < 2; i++) { string += "def"+i +" - "; } System.out.println(string.substring(0,string.length()-3)); } }
Markdown
UTF-8
3,005
3.515625
4
[]
no_license
# 寻找峰值 - guoziqing506的博客 - CSDN博客 2016年04月07日 15:37:55[guoziqing506](https://me.csdn.net/guoziqing506)阅读数:1042标签:[二分查找](https://so.csdn.net/so/search/s.do?q=二分查找&t=blog) 个人分类:[lintcode](https://blog.csdn.net/guoziqing506/article/category/6289140) 所属专栏:[LintCode-Python题解](https://blog.csdn.net/column/details/guoziqing-blog.html) 题目描述:你给出一个整数数组(size为n),其具有以下特点:相邻位置的数字是不同的,A[0] < A[1] 并且 A[n - 2] > A[n - 1],假定P是峰值的位置则满足A[P] > A[P-1]且A[P] > A[P+1],返回数组中任意一个峰值的位置。 样例: 给出数组[1, 2, 1, 3, 4, 5, 7, 6]返回1, 即数值 2 所在位置, 或者6, 即数值 7 所在位置。 最简单的想法可以通过遍历数组,直接模拟就可以求解了。比如,可以写出C++的代码如下: ```cpp class Solution { public: /** * @param A: An integers array. * @return: return any of peek positions. */ int findPeak(vector<int> A) { int n = A.size(); for(int i = 1; i < n - 2; ++i) { if(A[i - 1] < A[i] && A[i] > A[i + 1]) return i; } // write your code here } }; ``` 为什么突然写C++了呢,因为以前我在lintcode上也是这么写的,懒得改成Python了,这样写是能够AC的,但是不是最佳的答案。 在讲解二分法的阶段提到这个题目,当然应该想到用二分法,因为效率更高。这里,需要大家养成一个习惯,就是写算法的时候尽量考虑效率最好的情况,不论是时间上还是空间上。 怎么用二分法呢?猛地想不到,就先想想left和right求取中值mid嘛,这是二分法的通用套路。然后,此时mid所指向的元素的值就分为三种情况了: 1. A[mid] > A[mid + 1] && A[mid] > A[mid - 1],那么,根据定义,mid指向的就是一个峰值 2. A[mid] < A[mid + 1],因为A[n - 2] > A[n - 1],那么,一定有一个峰值存在于[mid + 1, n - 2] 3. A[mid] < A[mid - 1],因为A[0] < A[1],那么,一定有一个峰值存在于[1, mid - 1] 也就是说,我们每次求得mid所指的值,都可以缩减峰值存在的范围。 按二分法的基本套路([点击打开链接](http://blog.csdn.net/guoziqing506/article/details/50957775)),写出代码: ```python class Solution: #@param A: An integers list. #@return: return any of peek positions. def findPeak(self, A): left, right = 0, len(A) - 1 mid = (left + right) // 2 while left <= right and (A[mid] < A[mid - 1] or A[mid] < A[mid + 1]): # mid 左侧存在峰值 if A[mid] < A[mid - 1]: right = mid - 1 # mid 右侧存在峰值 elif A[mid] < A[mid + 1]: left = mid + 1 mid = (left + right) // 2 return mid # write your code here ```
TypeScript
UTF-8
775
2.5625
3
[ "MIT" ]
permissive
import { Command } from "../base/Command"; import Discord from "discord.js"; import Client from "../base/Client"; const ShuffleCommand = new Command({ name: "shuffle", alias: [], usage: "", description: "Shuffle the queue", onlyDev: false, permission: "MANAGE_MESSAGES", cooldown: 2, category: "music", execute: async (msg: Discord.Message, args: string[], client: Client) => { client.log("command - shuffle"); const player = client.player.get(msg.guild?.id as string); if (await client.funcs.check(client, msg, args)) { if (!player) throw new Error("No player"); player.shuffle(); msg.channel.send(client.messages.shuffled); } } }); export default ShuffleCommand;
C#
UTF-8
2,675
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.Net; using DSharpPlus.Interactivity; using DSharpPlus.Net.WebSocket; using DSharpPlus.VoiceNext; using System.IO; namespace BearBotKumaDSharpPlus { class Program { static void Main(string[] args) { MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult(); } private static DiscordClient _client; private static CommandsNextModule commandHandler; private static string botToken = "botAuthTokenGoesHere"; private static InteractivityModule interactions; private static VoiceNextClient vClient; private static StreamReader fileReader = null; public static async Task MainAsync(string[] args) { _client = new DiscordClient(new DiscordConfiguration { TokenType = TokenType.Bot, Token = botToken, LogLevel = LogLevel.Debug }); _client.SetWebSocketClient <WebSocket4NetClient>(); _client.DebugLogger.LogMessageReceived += LogMessage; commandHandler = _client.UseCommandsNext(new CommandsNextConfiguration { CaseSensitive = false, StringPrefix = "!" }); commandHandler.RegisterCommands<BotCommandsModule>(); interactions = _client.UseInteractivity(); vClient = _client.UseVoiceNext(); string line; try { fileReader = new StreamReader("tsapikey.ini"); } catch { Console.WriteLine("tsapikey.ini is missing!"); } while ((line = fileReader.ReadLine()) != null) { if (line.Contains("TSapikey")) { BotCommandsModule.apiKey = line.Replace("TSapikey = ","").Replace("\"",""); if (BotCommandsModule.apiKey == null || BotCommandsModule.apiKey == "") { Console.WriteLine("You need to enter your TS3 Client Query API Key in the tsapikey.ini file!"); Console.ReadKey(); } } } await _client.ConnectAsync(); await Task.Delay(-1); } public static void LogMessage(object sender, EventArgs e) { Console.WriteLine(e.ToString()); //return Task.CompletedTask; } } }
JavaScript
UTF-8
432
3.3125
3
[]
no_license
function solve(matrix) { let biggestElement = Number.MIN_SAFE_INTEGER; for (let row = 0; row < matrix.length; row++) { let currentRow = matrix[row]; let currentBiggestElement = Math.max(...currentRow); if (currentBiggestElement > biggestElement){ biggestElement = currentBiggestElement; } } console.log(biggestElement); } solve([ [20, 50, 10], [8, 33, 145]] );
JavaScript
UTF-8
1,576
3.59375
4
[]
no_license
// userChat is the function that waits for the user to send a message. function userChat() { // Find where the user is inputing text. compose_area = document.getElementById('composer'); // Set the user as the sender of the next message. nextMessage.sender = "user"; // Get the user's input in the compose_area and clear the compose_area. nextMessage.message = compose_area.value; compose_area.value = ""; // We need to convert the user's message to upper case to check if it matches with any prompts using the .toUpperCase() function. uppercase = nextMessage.message.toUpperCase(); // We can test if the user's message matches any of the prompts using if statements. console.log("✍ Code for custom prompts goes here"); if (uppercase == "HAPPY BIRTHDAY") { sendSpecialChat = [true, "Thank you! How did you know it's my birthday?!"]; } // sendSpecialChat is an array that will override the next thing the bot says with the second value if the first value is true. If the first value is false the bot will say the next thing in the script. // Send user's message. send(nextMessage.sender, nextMessage.message); // Count 1 more chat that the user has sent. userCount += 1; // Ask the bot for another chat. lookForChat() chatInput[userCount] = nextMessage.message; return chatInput[userCount]; } // The comment below tells this file about variables we define in other files. /* global compose_area global nextMessage global uppercase global sendSpecialChat global send global userCount global lookForChat */
TypeScript
UTF-8
2,718
3.0625
3
[]
no_license
import {Consola} from 'consola'; import {Day} from '../utils/day'; export default function (logger: Consola) { return new Day4(logger); } const tokens = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']; class Day4 extends Day { part1(input: string[]): Promise<string> { let currentTokens: string[] = []; let validPassports = 0; for (const line of input) { if (line === '') { this.logger.debug(`Tokens: ${currentTokens.join(',')}`); if (tokens.every(x => currentTokens.includes(x))) { validPassports++; } currentTokens = []; } else { currentTokens.push(...line.split(' ').map(x => x.split(':')[0])); } } return `${validPassports}`; } part2(input: string[]): Promise<string> { const validators = { byr: (val: string) => { const nVal = +val; return nVal >= 1920 && nVal <= 2002; }, iyr: (val: string) => { const nVal = +val; return nVal >= 2010 && nVal <= 2020; }, eyr: (val: string) => { const nVal = +val; return nVal >= 2020 && nVal <= 2030; }, hgt: (val: string) => { const regex = /(\d+)(in|cm)/.exec(val); if (!regex) return false; const num = +regex[1]; const unit = regex[2]; if (unit === 'cm') { return num >= 150 && num <= 193; } else { return num >= 59 && num <= 76; } }, hcl: (val: string) => /#[0-9a-f]{6}/.test(val), ecl: (val: string) => ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'].includes(val), pid: (val: string) => /\d{9}/.test(val), cid: () => false, }; let currentTokens: string[] = []; let validPassports = 0; for (const line of input) { if (line === '') { this.logger.debug(`Tokens: ${currentTokens.join(',')}`); if (tokens.every(x => currentTokens.includes(x))) { validPassports++; } currentTokens = []; } else { currentTokens.push( ...(line .split(' ') .map(x => { const [token, val] = x.split(':'); const validator = validators[token as keyof typeof validators]; if (!validator) { this.logger.error(`Unable to find validator for token: ${token}`); return null; } if (validator(val)) { this.logger.debug(`${token}:${val} is valid`) return token; } else { return null; } }) .filter(x => x != null) as string[]) ); } } return `${validPassports}`; } }
PHP
UTF-8
1,540
2.984375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); require __DIR__ . '/../autoload.php'; if (isset($_POST['name'], $_POST['email'], $_POST['password'], $_POST['password-confirm'])) { if ($_POST['password'] === $_POST['password-confirm']) { $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT); // Checks if email exists in database $emailStatement = $pdo->prepare('SELECT * FROM users WHERE email = :email'); $emailStatement->execute([ ':email' => $email, ]); $emailExist = $emailStatement->fetch(PDO::FETCH_ASSOC); if (!$emailStatement) { die(var_dump($pdo->errorInfo())); } //If email exist if ($emailExist) { $_SESSION['error'] = ["Email is already taken"]; redirect('/new-user.php'); } $statement = $pdo->prepare('INSERT INTO users (name, email, password) VALUES (:name, :email, :password)'); $statement->execute([ ':name' => $name, ':email' => $email, ':password' => $hashedPassword, ]); if (!$statement) { die(var_dump($pdo->errorInfo())); } $_SESSION['message'] = ['Your account was created!']; redirect('/login.php'); } else { $_SESSION['error'] = ['Passwords do not match, try again!']; redirect('/new-user.php'); } }
C#
UTF-8
3,886
2.609375
3
[]
no_license
using Identity.Api.Dtos; using Identity.Api.Services; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; namespace Identity.Api.Controllers { [Route("api/[controller]")] [ApiController] public class StudentsController : ControllerBase { private readonly IStudentService _studentService; public StudentsController(IStudentService studentService) { _studentService = studentService; } // GET: api/Students [HttpGet] public async Task<ActionResult<IEnumerable<StudentReadDto>>> GetStudents() { return await _studentService.GetAllAsync(); } // GET: api/Students/5 [HttpGet("{id}")] public async Task<ActionResult<StudentReadDto>> GetStudent([FromRoute] int id) { return await _studentService.GetAsync(id); } // PUT: api/Students/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutStudent([FromRoute] int id, [FromBody] StudentUpdateDto dto) { await _studentService.UpdateAsync(id, dto); return NoContent(); } // POST: api/Students // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task<ActionResult<StudentReadDto>> PostStudent([FromBody] StudentCreateDto dto) { var student = await _studentService.CreateAsync(dto); return CreatedAtAction(nameof(GetStudent), new { id = student.Id }, student); } // DELETE: api/Students/5 [HttpDelete("{id}")] public async Task<ActionResult<StudentReadDto>> DeleteStudent([FromRoute] int id) { return await _studentService.DeleteAsync(id); } // Roles [HttpGet("{id}/roles")] public async Task<ActionResult<IEnumerable<RoleReadDto>>> GetRoles([FromRoute] int id) { return await _studentService.GetRolesAsync(id); } [HttpPost("{id}/roles")] public async Task<ActionResult<RoleReadDto>> AddRole([FromRoute] int id, [FromBody, Required] string roleName) { var role = await _studentService.AddRoleAsync(id, roleName); return CreatedAtAction(nameof(GetRoles), new { id }, role); } [HttpDelete("{studentId}/roles/{roleName}")] public async Task<ActionResult<RoleReadDto>> RemoveRole([FromRoute] int studentId, [FromRoute] string roleName) { return await _studentService.RemoveRoleAsync(studentId, roleName); } // Mentors [HttpGet("{id}/mentors")] public async Task<ActionResult<IEnumerable<StudentMentorReadDto>>> GetMentors([FromRoute] int id) { return await _studentService.GetMentorsAsync(id); } [HttpPost("{id}/mentors")] public async Task<ActionResult<StudentMentorReadDto>> AddMentor([FromRoute] int id, [FromBody] StudentMentorCreateDto dto) { var mentor = await _studentService.AddMentorAsync(id, dto); return CreatedAtAction(nameof(GetMentors), new { id }, mentor); } [HttpDelete("{id}/mentors")] public async Task<ActionResult<StudentMentorReadDto>> RemoveMentor([FromRoute] int id, [FromQuery, Required] int teacherId, [FromQuery, Required] string mentorType) { return await _studentService.RemoveMentorAsync(id, teacherId, mentorType); } } }
Markdown
UTF-8
1,045
2.59375
3
[]
no_license
# Article 3 Sont autorisés à concourir les candidats qui, à la date du début du stage de formation, réunissent les conditions fixées par l'article 4 du décret n° 2008-931 du 12 septembre 2008 susvisé et satisfont aux conditions d'aptitude définies par l'annexe I du présent arrêté. Les niveaux de pratique professionnelle et de formation de l'enseignement supérieur requis pour être candidat au recrutement au grade de chef de musique de 2e classe et de chef de musique principal sont explicités en annexe II. Les concours d'admission comportent des épreuves écrites d'admissibilité et des épreuves d'admission. La liste des candidats autorisés à concourir est établie par le ministre de la défense après examen des dossiers de candidature par une commission composée des directeurs des ressources humaines des différentes armées et de la gendarmerie nationale et le directeur du conservatoire militaire de musique de l'armée de terre. Les candidats peuvent se présenter, la même année, à un seul concours.
Java
UTF-8
1,799
3.140625
3
[ "MIT" ]
permissive
package seedu.equipment.logic.commands; import static java.util.Objects.requireNonNull; import java.util.Comparator; import seedu.equipment.logic.CommandHistory; import seedu.equipment.model.Model; import seedu.equipment.model.equipment.Equipment; /** * Lists all equipment in the equipment manager to the user. */ public class SortCommand extends Command { public static final String COMMAND_WORD = "sort"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Sort the list either by name, date, serial number or phone\n" + "Parameters: sort [FIELD] \n" + "Example 1: " + COMMAND_WORD + " name\n" + "Example 2: " + COMMAND_WORD + " date\n" + "Example 3: " + COMMAND_WORD + " serial\n" + "Example 4: " + COMMAND_WORD + " phone\n"; public static final String MESSAGE_SUCCESS = "List is sorted."; private final Comparator<Equipment> comparator; public SortCommand(Comparator<Equipment> comparator) { requireNonNull(comparator); this.comparator = comparator; } @Override public CommandResult execute(Model model, CommandHistory history) { requireNonNull(model); model.sortFilteredEquipmentList(comparator); model.updateFilteredPersonList(Model.PREDICATE_SHOW_ALL_EQUIPMENT); model.commitEquipmentManager(); return new CommandResult(MESSAGE_SUCCESS); } public Comparator<Equipment> getComparator() { return comparator; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof SortCommand // instanceof handles null && comparator.equals(((SortCommand) other).getComparator())); } }
Java
UTF-8
457
1.835938
2
[]
no_license
package com.zynger.daggeracrossmodules.di; import com.zynger.collaborators.di.EngineModule; import com.zynger.daggeracrossmodules.FleetApp; import com.zynger.daggeracrossmodules.MainActivity; import dagger.Component; @Component(modules = { ApplicationModule.class, RacingModule.class, EngineModule.class }) public interface ApplicationComponent { void inject(FleetApp fleetApp); void inject(MainActivity mainActivity); }
Python
UTF-8
401
3.515625
4
[]
no_license
import time import pygame # initializes pygame variables pygame.init() # define the screen size to 640x480 screen = pygame.display.set_mode([640, 480]) # writes the Hello World at the screen title pygame.display.set_caption('Hello World') # fills the screen with black color screen.fill([0, 0, 0]) # updates the screen pygame.display.flip() # waits 5 seconds to close the program time.sleep(5)
Java
UTF-8
2,936
2.125
2
[]
no_license
package com.speedrun_mobile_unofficial.homepage; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.support.v4.widget.CircularProgressDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.speedrun_mobile_unofficial.R; import com.speedrun_mobile_unofficial.entities.Enums; import com.speedrun_mobile_unofficial.leaderboard.LeaderBoardActivity; public class GameGridAdapter extends RecyclerView.Adapter<GameGridAdapter.ViewHolder> { private Context context; private LayoutInflater mInflater; private Object[] gameNames; private int layoutId; public GameGridAdapter() { } public GameGridAdapter(Context context, int layoutId, Object[] gameNames) { this.context = context; this.mInflater = LayoutInflater.from(context); this.layoutId = layoutId; this.gameNames = gameNames; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = mInflater.inflate(layoutId, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bind(position); } @Override public int getItemCount() { return gameNames == null ? 0 : gameNames.length; } class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { final ImageView gameCover; String gameName; CircularProgressDrawable placeholder; ViewHolder(View itemView) { super(itemView); this.gameCover = itemView.findViewById(R.id.home_game_cover_image); placeholder = new CircularProgressDrawable(context); placeholder.setStrokeWidth(5f); placeholder.setCenterRadius(30f); placeholder.setColorSchemeColors(R.color.white); itemView.setOnClickListener(this); } void bind(final int position) { this.gameName = (String) gameNames[position]; String url = String.format("https://www.speedrun.com/themes/%s/cover-256.png", gameName); placeholder.start(); RequestOptions sharedOptions = new RequestOptions().placeholder(placeholder).fitCenter(); Glide.with(context).load(url).apply(sharedOptions).into(gameCover); } @Override public void onClick(View itemView) { Context context = itemView.getContext(); Intent intent = new Intent(context, LeaderBoardActivity.class); intent.putExtra(Enums.EXTRA.GAMENAME, gameName); context.startActivity(intent); } } }
SQL
UTF-8
809
3.125
3
[]
no_license
DROP TABLE if EXISTS interview_service_table; CREATE TABLE interview_service_table( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT COMMENT 'ID', worker_id INT NOT NULL comment '客户经理ID', internal_code VARCHAR(100) NOT NULL COMMENT '客户内码', interview_time TIMESTAMP DEFAULT current_timestamp COMMENT '面签时间', interview_place VARCHAR(100) NOT NULL COMMENT '面签地点', interview_result VARCHAR(10) NOT NULL COMMENT '面签结果', photo_url VARCHAR(100) NOT NULL COMMENT '合影照片地址 ', detail VARCHAR(200) COMMENT '详细情况', create_time timestamp DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', mod_time timestamp default current_timestamp on update current_timestamp COMMENT '更新时间' )ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='面签服务表';
JavaScript
UTF-8
621
2.796875
3
[]
no_license
const pwd = require('./pwd'); const ls = require('./ls'); const cat = require('./cat'); const curl = require('./curl'); const done = (output) => { process.stdout.write(output); process.stdout.write('\nprompt >'); } process.stdout.write('prompt > '); process.stdin.on('data', (data) => { const cmd = data.toString().trim().split(' '); const firstCmd = cmd[0]; const secondCmd = cmd[1]; if (firstCmd === 'pwd') { pwd(done); } else if (firstCmd === 'ls') { ls(done); } else if (firstCmd === 'cat') { cat(secondCmd, done); } else if (firstCmd === 'curl') { curl(secondCmd, done); } });
Markdown
UTF-8
1,267
2.875
3
[]
no_license
Update Dec 15, 2015: Fixed. ## HELP PLEASE! I am trying to create a floating view (using WindowManager) that uses EditText Component. But here's the issue. If I create the floating view using the `FLAG_NOT_FOCUSABLE`, the keyboard doesn't open up when I focus on the Edittext Component by touching on it. I tried removing the `FLAG_NOT_FOCUSABLE` flag, and the keyboard shows up just fine. It works as expected. BUT. A BIG BUT. Not "Butt", but "But". But, the back button is broken now. Not only back button, but all of the touch screen. I am not able to touch the screen anywhere except the floating view. :( (I want to touch it everywhere!) What can we do? Please help. ### How to use this repo? Clone it. In file, `EditTextService.java`, there are two methods that return the LayoutParams for the floating view: `getParamsThatWorksForTouchEvents()` and `getParamsThatWorksForKeyboard()`. In `onCreate()` method, these methods are called using this section: ```java WindowManager.LayoutParams params = this.getParamsThatWorksForKeyboard(); // WindowManager.LayoutParams params = this.getParamsThatWorksForTouchEvents(); ``` Comment out one of the line and the other one will give you the desired effect to reproduce the issue. ### Reward: A Big Hug. :)
SQL
UTF-8
10,385
2.90625
3
[]
no_license
CREATE TABLE JOUEUR( id_joueur NUMBER(5) AUTO_INCREMENT PRIMARY KEY, nom_joueur VARCHAR2(64), prenom_joueur VARCHAR2(64), qualification ENUM('Qualification' ,'Quart de finale' ,'Demi-finale','Finale'), nationalite VARCHAR2(64) sexe VARCHAR2(5) ); /*FAIT*/ INSERT INTO JOUEUR VALUES (1,'Nadal', 'Raphaël', 'Qualification', 'Français', 'Homme'); INSERT INTO JOUEUR VALUES (2,'Federer', 'Roger', 'Qualification', 'Suisse', 'Homme'); INSERT INTO JOUEUR VALUES (3,'Djokovic', 'Novak', 'Qualification', 'Serbe', 'Homme'); INSERT INTO JOUEUR VALUES (4,'Tsonga', 'Jo-Wilfried', 'Qualification', 'Français', 'Homme'); INSERT INTO JOUEUR VALUES (5,'Ferrer', 'David', 'Qualification', 'Espagnol', 'Homme'); INSERT INTO JOUEUR VALUES (6,'Gasquet', 'Richard', 'Qualification','Français', 'Homme'); INSERT INTO JOUEUR VALUES (7,'Murray', 'Andy', 'Qualification', 'Américain', 'Homme'); INSERT INTO JOUEUR VALUES (8,'Raonic', 'Milos', 'Qualification', 'Anglais', 'Homme'); INSERT INTO JOUEUR VALUES (9,'Berdych', 'Thomas', 'Qualification', 'RTC', 'Homme'); INSERT INTO JOUEUR VALUES (10,'Isner', 'John', 'Qualification', 'USA', 'Homme'); INSERT INTO JOUEUR VALUES (11,'Anderson', 'Kevin', 'Qualification', 'SER', 'Homme'); INSERT INTO JOUEUR VALUES (12,'Cilic', 'Marin', 'Qualification', 'CRO', 'Homme'); INSERT INTO JOUEUR VALUES (13,'Simon', 'Gilles', 'Qualification', 'FRA', 'Homme'); INSERT INTO JOUEUR VALUES (14,'Goffin', 'David', 'Qualification','BEL', 'Homme'); INSERT INTO JOUEUR VALUES (15,'Lopez', 'Feliciano', 'Qualification', 'ESP', 'Homme'); INSERT INTO JOUEUR VALUES (16,'Tomic', 'Bernard', 'Qualification', 'AUS', 'Homme'); INSERT INTO JOUEUR VALUES(17,'Williams','Serena','Qualification','USA','Femme'); INSERT INTO JOUEUR VALUES(18,'Halep','Simona','Qualification','ROU','Femme'); INSERT INTO JOUEUR VALUES(19,'Muguruza','Garbine','Qualification','ESP','Femme'); INSERT INTO JOUEUR VALUES(20,'Sharapova','Maria','Qualification','RUS','Femme'); INSERT INTO JOUEUR VALUES(21,'Radwanska','Agnieszka','Qualification','POL','Femme'); INSERT INTO JOUEUR VALUES(22,'Kvitova','Petra','Qualification','RTC','Femme'); INSERT INTO JOUEUR VALUES(23,'Williams','Venus','Qualification','USA','Femme'); INSERT INTO JOUEUR VALUES(24,'Pennetta','Flavia','Qualification','ITA','Femme'); INSERT INTO JOUEUR VALUES(25,'Safarova','Lucie','Qualification','RTC','Femme'); INSERT INTO JOUEUR VALUES(26,'Kerber','Angelique','Qualification','ALL','Femme'); INSERT INTO JOUEUR VALUES(27,'Pliskova','Karolina','Qualification','RTC','Femme'); INSERT INTO JOUEUR VALUES(28,'Bacsinszky','Timea','Qualification','SUI','Femme'); INSERT INTO JOUEUR VALUES(29,'Suarez Navarro','Carla','Qualification','ESP','Femme'); INSERT INTO JOUEUR VALUES(30,'Bencic','Belinda','Qualification','SUI','Femme'); INSERT INTO JOUEUR VALUES(31,'Vinci','Roberta','Qualification','ITA','Femme'); INSERT INTO JOUEUR VALUES(32,'Ivanovic','Ana','Qualification','SER','Femme'); /*-------------------------------------------------------------------------*/ CREATE TABLE EQUIPE( id_equipe NUMBER(5) AUTO_INCREMENT PRIMARY KEY, id_joueur1 NUMBER(5), id_joueur2 NUMBER(5), qualification ENUM('Qualification','Quart de finale','Demi-finale','Finale'), FOREIGN KEY (id_joueur1) REFERENCES JOUEUR(id_joueur), FOREIGN KEY (id_joueur2) REFERENCES JOUEUR(id_joueur) ); /*FAIT*/ INSERT INTO EQUIPE VALUES (1,1, 2, 'Qualification'); INSERT INTO EQUIPE VALUES (2,3, 4, 'Qualification'); INSERT INTO EQUIPE VALUES (3,5, 6, 'Qualification'); INSERT INTO EQUIPE VALUES (4,7, 8, 'Qualification'); /*-------------------------------------------------------------------------*/ CREATE TABLE ARBITRE( id_arbitre NUMBER(5) AUTO_INCREMENT PRIMARY KEY, nom_arbitre VARCHAR2(64), prenom_arbitre VARCHAR2(64), rank_arbitre VARCHAR2(64), nationalite VARCHAR2(64) ); /*FAIT*/ INSERT INTO ARBITRE VALUES (1,'DUGELET', 'Aubin', 'JAT2', 'Français'); INSERT INTO ARBITRE VALUES (2,'DUROT', 'Julien', 'JAT2', 'Anglais'); INSERT INTO ARBITRE VALUES (3,'MERLE', 'Jeremy', 'JAT2', 'Allemand'); INSERT INTO ARBITRE VALUES (4,'AUBE', 'Aimée', 'JAT2', 'Espagnol'); INSERT INTO ARBITRE VALUES (5,'DUGELET', 'Aubin', 'ITT1', 'Serbe'); INSERT INTO ARBITRE VALUES (6,'SEGUIN', 'Delphine', 'ITT1', 'Français'); INSERT INTO ARBITRE VALUES (7,'DESNOYER', 'Emmanuelle', 'ITT1', 'Français'); INSERT INTO ARBITRE VALUES (8,'MARTINEAU', 'Charmaine', 'ITT1', 'Français'); INSERT INTO ARBITRE VALUES (9,'LAPIERRE', 'Renée', 'JAT2', 'Français'); INSERT INTO ARBITRE VALUES (10,'JACQUES', 'Arnaude', 'JAT2', 'Français'); /*-------------------------------------------------------------------------*/ CREATE TABLE RAMASSEUR( id_ramasseur NUMBER(5) AUTO_INCREMENT PRIMARY KEY, nom_ramasseur VARCHAR2(64), prenom_ramasseur VARCHAR2(64), ); /*FAIT*/ INSERT INTO RAMASSEUR VALUES (1,'PICSOU', 'Baltazar'); INSERT INTO RAMASSEUR VALUES (2,'RAMBERT', 'Hugo'); INSERT INTO RAMASSEUR VALUES (3,'LAMBERT', 'Emile'); INSERT INTO RAMASSEUR VALUES (4,'OTVARD', 'Baldwin'); INSERT INTO RAMASSEUR VALUES (5,'GERVIN', 'Ditbert'); INSERT INTO RAMASSEUR VALUES (6,'GUNTER', 'Alwin'); INSERT INTO RAMASSEUR VALUES (7,'INGVALD', 'Almar'); INSERT INTO RAMASSEUR VALUES (8,'DUHAMEL' , 'Damien'); INSERT INTO RAMASSEUR VALUES (9,'BONAMI', 'Orville'); INSERT INTO RAMASSEUR VALUES (10,'GAGNON', 'Claude'); INSERT INTO RAMASSEUR VALUES (11,'LEVESQUE', 'Annot'); INSERT INTO RAMASSEUR VALUES (12,'LAVALLEE', 'Avril'); INSERT INTO RAMASSEUR VALUES (13,'VERRONEAU', 'Maryse'); INSERT INTO RAMASSEUR VALUES (14,'COURSE', 'Vignette'); INSERT INTO RAMASSEUR VALUES (15,'BLER', 'Yolande'); INSERT INTO RAMASSEUR VALUES (16,'POLIVKA', 'Bohumil'); INSERT INTO RAMASSEUR VALUES (17,'CSEKE', 'Balogh'); INSERT INTO RAMASSEUR VALUES (18,'GISBORN', 'Michael'); INSERT INTO RAMASSEUR VALUES (19,'ETHERIDGE', 'Benjamin'); INSERT INTO RAMASSEUR VALUES (20,'STOUT', 'Caitlin'); INSERT INTO RAMASSEUR VALUES (21,'GOLDIE', 'Lara'); INSERT INTO RAMASSEUR VALUES (22,'LAMONT', 'Amelie'); INSERT INTO RAMASSEUR VALUES (23,'DALEY-SCOTT', 'Harrison'); INSERT INTO RAMASSEUR VALUES (24,'CLARK', 'Elijah'); /*------------------------------------------------------------------------*/ CREATE TABLE EQUIPE_RAMASSEURS( id_equipe_ramasseurs INT(5), nom_equipe VARCHAR(64) );/*FAIT*/ INSERT INTO EQUIPE_RAMASSEURS VALUES (1,'Equipe ramasseurs 1'); INSERT INTO EQUIPE_RAMASSEURS VALUES (2,'Equipe ramasseurs 2'); INSERT INTO EQUIPE_RAMASSEURS VALUES (3,'Equipe ramasseurs 3'); INSERT INTO EQUIPE_RAMASSEURS VALUES (4,'Equipe ramasseurs 4'); /*------------------------------------------------------------------------*/ CREATE TABLE COURT( id_court NUMBER(5) AUTO_INCREMENT PRIMARY KEY, nom_court VARCHAR2(64), nb_places NUMBER(5) ); /*FAIT*/ INSERT INTO COURT VALUES (1,'Grand Court de Gerlan', 1100); INSERT INTO COURT VALUES (2,'Court de Saint-Andre', 600); INSERT INTO COURT VALUES (3,'Moyen Court', 330); INSERT INTO COURT VALUES (4,'Golden Court', 850); /*-----------------------------------------------------------------------*/ CREATE TABLE MATCHS( id_match NUMBER(5) AUTO_INCREMENT PRIMARY KEY, date_match DATE, creneau_match ENUM('8am', '11am', '3pm', '6pm', '9pm'), categorie_match ENUM('Simple Homme', 'Simple Femme', 'Double Homme', 'Double Femme'), tour_match ENUM('Qualification','Quart de finale','Demi-finale','Finale'), id_court NUMBER(5), FOREIGN KEY (id_court) REFERENCES COURT(id_court) ); /*FAIT*/ INSERT INTO MATCHS VALUES (TO_DATE('2016-01-05', 'yyyy-mm-dd'), '8am', 'Simple Homme', 'Qualification', 1); /*-----------------------------------------------------------------------*/ CREATE TABLE ASSIGNEMENT_JOUEUR( id_match NUMBER(5), id_joueur NUMBER(5), PRIMARY KEY(id_match,id_joueur), FOREIGN KEY (id_match) REFERENCES MATCHS(id_match), FOREIGN KEY (id_joueur) REFERENCES JOUEUR(id_joueur) ); /*FAIT*/ /*-----------------------------------------------------------------------*/ CREATE TABLE ASSIGNEMENT_ARBITRE( id_match NUMBER(5), id_arbitre NUMBER(5), categorie_arbitre VARCHAR2(64), PRIMARY KEY(id_match,id_arbitre), FOREIGN KEY (id_match) REFERENCES MATCHS(id_match), FOREIGN KEY (id_arbitre) REFERENCES ARBITRE(id_arbitre) ); /*------------------------------------------------------------------------*/ CREATE TABLE ASSIGNEMENT_RAMASSEUR( id_equipe_ramasseurs NUMBER(5), id_ramasseur NUMBER(5), PRIMARY KEY(id_match,id_ramasseur), FOREIGN KEY (id_equipe_ramasseurs) REFERENCES EQUIPE_RAMASSEURS(id_match), FOREIGN KEY (id_ramasseur) REFERENCES RAMASSEUR(id_ramasseur) ); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (1,1); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (1,2); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (1,3); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (1,4); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (1,5); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (1,6); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (2,7); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (2,8); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (2,9); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (2,10); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (2,11); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (2,12); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (3,13); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (3,14); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (3,15); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (3,16); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (3,17); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (3,18); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (4,19); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (4,20); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (4,21); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (4,22); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (4,23); INSERT INTO ASSIGNEMENT_RAMASSEUR VALUES (4,24); /*-----------------------------------------------------------------------*/ CREATE TABLE ASSIGNEMENT_EQUIPE( id_match NUMBER(5), id_equipe NUMBER(5), PRIMARY KEY(id_match,id_equipe), FOREIGN KEY (id_match) REFERENCES MATCHS(id_match), FOREIGN KEY (id_equipe) REFERENCES EQUIPE(id_equipe) ); /*----------------------------------------------------------------------*/ CREATE TABLE GAGNANT ( id_match INT(5), id_joueur INT(5) ); ALTER TABLE GAGNANT ADD CONSTRAINT pk_gagnant PRIMARY KEY (id_match,id_joueur); ALTER TABLE GAGNANT ADD CONSTRAINT fk_gagnant1 FOREIGN KEY (id_match) REFERENCES `MATCH`(id_match); ALTER TABLE GAGNANT ADD CONSTRAINT fk_gagnant2 FOREIGN KEY (id_joueur) REFERENCES JOUEUR(id_joueur);
Python
UTF-8
2,350
2.578125
3
[]
no_license
#!/usr/bin/env python # encoding: utf-8 from __future__ import absolute_import import gevent from gevent import monkey; monkey.patch_all() from gevent import queue from .job import Job class GeventWorker(): @classmethod def create(cls, wqueue, rqueue, greenlet_num = 8): gw = cls(wqueue, rqueue) if not isinstance(wqueue, queue.JoinableQueue) or \ not isinstance(rqueue, queue.JoinableQueue): raise TypeError('Expected two gevent.queue.JoinableQueue instance, but got %s and %s.' %(type(wqueue), type(rqueue))) gw._wqueue_len = wqueue.qsize() if wqueue is not None else 0 gw._rqueue_len = rqueue.qsize() if rqueue is not None else 0 if gw._wqueue_len == 0: raise ValueError("Work queue is empty, must not be zero.") gw.description = gw.get_description() gw.greenlets = [gevent.Greenlet(gw.__run) for i in range(gw.wqueue_len)] return gw def __init__(self, wq, rq): self._wqueue = wq self._rqueue = rq self._wqueue_len = None self._rqueue_len = None self.description = None self.greenlets = [] def __repr__(self): return "<GeventWorker: wqueue length %d, rqueue length %d>"\ %(self.wqueue_len, self.rqueue_len) def __run(self): while True: try: j = self.wqueue.get_nowait() result = j.func(*j.args, **j.kwargs) self.rqueue.put_nowait(result) self.wqueue.task_done() except gevent.queue.Empty: break def gogo(self): [t.start() for t in self.greenlets] gevent.joinall(self.greenlets) @property def greenlet_num(self): return len(self.greenlets) @property def wqueue(self): return self._wqueue @property def rqueue(self): return self._rqueue @property def wqueue_len(self): return self._wqueue.qsize() @property def rqueue_len(self): return self._rqueue.qsize() def get_description(self): wq_l = self.wqueue_len rq_l = self.rqueue_len return "Total jobs:%d, finished:%d, doing:%d." %( wq_l + rq_l, wq_l, rq_l) if __name__ == '__main__': pass