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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 717 | 3.40625 | 3 |
[] |
no_license
|
## Machine Learning Lesson
This is an exercise that corresponds to a lesson on using Jupyter notebooks.
This notebook demonstrates how to to use scikit-learn for performing both a linear-regression and random-forest model for prediction.
In the linear regression model, we use sample data of weight and heights of 10,000 individuals, and see if we can develop a model to predict how much someone might weight based on their height. (Purposely used this data to explain the pitfalls of such a model.)
In the random forest data, we use sample data of 13,000 recipes from Epicurious to see if we can develop a model that would predict the rating (1 to 5) of a recipe given a particular set of nutritional values.
|
Python
|
UTF-8
| 3,451 | 4.03125 | 4 |
[] |
no_license
|
#! /usr/bin/python3
import itertools
import random
import copy
# NUM_INPUTS | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
# NUM_COMPARATORS | 0 | 1 | 3 | 5 | 9 | 12 | 16 | 19 |
NUM_INPUTS = 4
NUM_COMPARATORS = 5
def is_sorted(array):
"""
Returns True if array is sorted, otherwise False
"""
for i in range(1,len(array)):
if array[i] < array[i-1]:
return False
return True
def generate_evaluation_cases():
"""
Returns a list of all possible unsorted lists of size NUM_INPUTS
that contain only 0's and 1's.
Example:
NUM_INPUTS = 2, [[1,0]]
NUM_INPUTS = 3, [[0,1,0],[1,0,0],[1,0,1],[1,1,0]]
Hint: Think binary numbers
"""
### FILL THIS IN ###
unsorted_lists = []
lst = [list(i) for i in itertools.product([0, 1], repeat=NUM_INPUTS)]
for pair in lst:
for k in range(len(pair)-1):
if pair[k] > pair[k+1]:
#unsorted
unsorted_lists.append(pair)
# print (unsorted_lists) # for testing purposes
return unsorted_lists
class SortingNetwork:
EVALUATION_CASES = generate_evaluation_cases()
def __init__(self):
"""
Creates a random sorting network with NUM_COMPARATORS comparators
to sort an array of size NUM_INPUTS
Note: For all comparators (x,y), x < y
Example:
(0,2) => correct
(4,0) => incorrect
(1,1) => incorrect
Note: Consecutive comparators in list shouldn't be the the same
Example:
[(0,1),(0,2),(1,2)] => correct
[(0,3),(0,3),(0,2)] => incorrect
[(0,3),(0,2),(0,3)] => correct
"""
self.comparators = []
### FILL THIS IN ###
random_sorting_network = []
test=[]
for x in range(NUM_INPUTS):
for y in range(NUM_INPUTS):
if x < y:
tup = (x, y)
test.append(tup)
self.comparators = random.sample(test,NUM_COMPARATORS)
# print (self.comparators)
def __str__(self):
return str(self.comparators)
def apply_on(self, array):
"""
Uses the sorting network to (try to) sort the array
"""
### FILL THIS IN ###
for comparator in self.comparators:
# if they the first number is biggger, then swap
if array[comparator[0]] > array[comparator[1]]:
array[comparator[0]],array[comparator[1]]=array[comparator[1]],array[comparator[0]]
def evaluate(self):
"""
Evaluate sorting network over each case in EVALUATION_CASES.
Returns the percentage that the sorting network correctly sorts.
WARNING: Do not modify the evaluation cases
"""
### FILL THIS IN ###
correct = 0
for i in self.EVALUATION_CASES:
temp = copy.deepcopy(i)
self.apply_on(temp)
if is_sorted(temp):
correct += 1
return correct/len(self.EVALUATION_CASES)
if __name__ == "__main__":
network = SortingNetwork()
#
print("SORTING NETWORK : " + str(network))
print("EVALUATION CASES: " + str(network.EVALUATION_CASES))
percent_correct = network.evaluate()
print(str(percent_correct) + "% of possible inputs sorted correctly")
|
PHP
|
UTF-8
| 375 | 2.953125 | 3 |
[] |
no_license
|
<?php
namespace Nitrogen\Hydrator;
interface HydratorInterface
{
/**
* Hydrate $object with the give $data
*
* @param array $data
* @param object $obj
*/
public function hydrate(array $data, $obj);
/**
* Extract data from an object
*
* @param object $obj
* @return array
*/
public function extract($obj);
}
|
Python
|
UTF-8
| 3,520 | 2.8125 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
from dns import rdatatype, rdataclass, flags, rcode
def parse_query(query, nameserver, duration):
""" Parse a dns response into a dict based on record type.
Should adhere to propsed rfc format:
http://tools.ietf.org/html/draft-bortzmeyer-dns-json-00
"""
flag_list = flags.to_text(query.response.flags)
return {
'Query': get_query(nameserver, duration),
'QuestionSection': get_question(query),
'AnswerSection': get_rrs_from_rrsets(query.response.answer),
'AdditionalSection': get_rrs_from_rrsets(query.response.additional),
'AuthoritySection': get_rrs_from_rrsets(query.response.authority),
'ReturnCode': rcode.to_text(query.response.rcode()),
'ID': query.response.id,
'AA': 'AA' in flag_list,
'TC': 'TC' in flag_list,
'RD': 'RD' in flag_list,
'RA': 'RA' in flag_list,
'AD': 'AD' in flag_list
}
def get_query(nameserver, duration):
return {
"Server": nameserver,
"Duration": duration # this is a float, which deviates from the RFC
}
def get_question(query):
return {
"Qname": str(query.qname),
"Qtype": rdatatype.to_text(query.rdtype),
"Qclass": rdataclass.to_text(query.rdclass)
}
def get_rrs_from_rrsets(rrsets):
"""This works for answer, authority, and additional rrsets"""
rr_list = []
for rrset in rrsets:
common_rr_dict = {
"Name": str(rrset.name),
"Type": rdatatype.to_text(rrset.rdtype),
"Class": rdataclass.to_text(rrset.rdclass),
"TTL": rrset.ttl # TODO: doesn't each rr have it's own ttl?
}
for rr in rrset:
rr_dict = common_rr_dict.copy()
rr_dict.update(get_record_specific_answer_fields(rr))
rr_list.append(rr_dict)
return rr_list
def get_record_specific_answer_fields(rr):
""" Return a json object of fields specific to a given record type for a
given dns answer.
E.g. 'A' records have an 'address' field. 'NS' hava a 'target' field etc.
"""
if rr.rdtype == rdatatype.A or rr.rdtype == rdatatype.AAAA:
return {"Address": rr.address}
if (rr.rdtype == rdatatype.CNAME or
rr.rdtype == rdatatype.PTR or
rr.rdtype == rdatatype.NS):
return {"Target": str(rr.target)}
if rr.rdtype == rdatatype.MX:
return {
"Preference": rr.preference,
"MailExchanger": str(rr.exchange)
}
if rr.rdtype == rdatatype.SOA:
return {
"MasterServerName": str(rr.mname),
"MaintainerName": str(rr.rname),
"Serial": rr.serial,
"Refresh": rr.refresh,
"Retry": rr.retry,
"Expire": rr.expire,
"NegativeTtl": rr.minimum # Note: keyname changes in JSON RFC
}
if rr.rdtype == rdatatype.TXT:
# TXT was not described in the JSON RFC
return {
"TxtData": str(rr),
}
if rr.rdtype == rdatatype.NAPTR:
return {
"Flags": rr.flags,
"Order": rr.order,
"Service": rr.service,
"Preference": rr.preference,
"Regexp": rr.regexp,
"Replacement": str(rr.replacement)
}
if rr.rdtype == rdatatype.LOC:
return {
"Altitude": rr.altitude / 100, # .altitude is in centimeters
"Longitude": rr.longitude,
"Latitude": rr.latitude
}
return {}
|
Java
|
UTF-8
| 2,720 | 2.03125 | 2 |
[] |
no_license
|
package com.alibaba.nb.android.trade.web.interception.base.handler;
import java.util.LinkedHashMap;
import java.util.Map;
public class AliTradeHandlerInfoBuilder
{
private AliTradeHandlerInfo handlerInfo = new AliTradeHandlerInfo();
public static AliTradeHandlerInfoBuilder newHandlerInfo(String paramString)
{
AliTradeHandlerInfoBuilder localAliTradeHandlerInfoBuilder = new AliTradeHandlerInfoBuilder();
localAliTradeHandlerInfoBuilder.handlerInfo.name = paramString;
return localAliTradeHandlerInfoBuilder;
}
public AliTradeHandlerInfoBuilder addHandlerActionParameter(String paramString1, String paramString2)
{
this.handlerInfo.actionParameters.put(paramString1, paramString2);
return this;
}
public AliTradeHandlerInfoBuilder addMatchInfo(String paramString1, String paramString2, String[] paramArrayOfString1, String[] paramArrayOfString2)
{
AliTradeMatchInfo localAliTradeMatchInfo = new AliTradeMatchInfo();
localAliTradeMatchInfo.name = paramString1;
localAliTradeMatchInfo.type = paramString2;
localAliTradeMatchInfo.schemes = paramArrayOfString1;
localAliTradeMatchInfo.values = paramArrayOfString2;
this.handlerInfo.matchInfos.put(paramString1, localAliTradeMatchInfo);
return this;
}
public AliTradeHandlerInfo getHandlerInfo()
{
return this.handlerInfo;
}
public AliTradeHandlerInfoBuilder setHandlerAction(String paramString)
{
this.handlerInfo.action = paramString;
return this;
}
public AliTradeHandlerInfoBuilder setHandlerOrder(Boolean paramBoolean1, Boolean paramBoolean2, String[] paramArrayOfString1, String[] paramArrayOfString2)
{
this.handlerInfo.beforeAll = paramBoolean1;
this.handlerInfo.afterAll = paramBoolean2;
this.handlerInfo.before = paramArrayOfString1;
this.handlerInfo.after = paramArrayOfString2;
return this;
}
public AliTradeHandlerInfoBuilder setHandlerScopes(String[] paramArrayOfString)
{
this.handlerInfo.scopes = paramArrayOfString;
return this;
}
public AliTradeHandlerInfoBuilder setHandlerType(String paramString)
{
this.handlerInfo.type = paramString;
return this;
}
public AliTradeHandlerInfoBuilder setHanlderScenarios(int[] paramArrayOfInt)
{
this.handlerInfo.scenarios = paramArrayOfInt;
return this;
}
public AliTradeHandlerInfoBuilder setUIThread(boolean paramBoolean)
{
this.handlerInfo.uiThread = paramBoolean;
return this;
}
}
/* Location: E:\apk\xiaoenai2\classes-dex2jar.jar!\com\alibaba\nb\android\trade\web\interception\base\handler\AliTradeHandlerInfoBuilder.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
Python
|
UTF-8
| 1,554 | 4 | 4 |
[] |
no_license
|
# 1. Get (a, b) counts
# 2. Make generator that finds solution
# 3. Iterate over generator
# 4. From pattern, string, and a, b lengths
def get_counts(pattern):
a_count, b_count = 0, 0
for c in pattern:
if c=='a':
a_count += 1
else:
b_count += 1
return (a_count, b_count)
def solve_equation(a_count, b_count, str_length):
# a_count*a_length + b_count*b_length = str_Length
for a_length in range(1, str_length):
b_length = (str_length - a_count*a_length) / b_count
if b_length.is_integer():
if a_count*a_length + b_count*b_length == str_length:
if b_length > 0:
yield (int(a_length), int(b_length))
def check_string(a_len, b_len, string, pattern):
a = None
b = None
string_i = 0
for i in range(len(pattern)):
if pattern[i] == 'a':
if a is None:
a = string[string_i:string_i+a_len]
else:
if string[string_i:string_i+a_len] != a:
return False
string_i += a_len
else:
if b is None:
b = string[string_i:string_i+b_len]
print(b)
else:
if string[string_i:string_i+b_len] != b:
return False
string_i += b_len
return (a, b)
def pattern_matching(pattern, value):
a_count, b_count = get_counts(pattern)
for a_length, b_length in solve_equation(a_count, b_count, len(value)):
vals = check_string(a_length, b_length, value, pattern)
if vals:
return vals
break
else:
return False
print(pattern_matching("aabab", "catcatgocatgo"))
|
Python
|
UTF-8
| 6,183 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""class to manage jsonschema type schema."""
import copy
import pkgutil
import json
from jsonschema import Draft7Validator, draft7_format_checker # pylint: disable=import-self
from schema_enforcer.schemas.validator import BaseValidation
from schema_enforcer.validation import ValidationResult, RESULT_FAIL, RESULT_PASS
# TODO do we need to catch a possible exception here ?
v7data = pkgutil.get_data("jsonschema", "schemas/draft7.json")
v7schema = json.loads(v7data.decode("utf-8"))
class JsonSchema(BaseValidation): # pylint: disable=too-many-instance-attributes
"""class to manage jsonschema type schemas."""
schematype = "jsonchema"
def __init__(self, schema, filename, root):
"""Initilize a new JsonSchema object from a dict.
Args:
schema (dict): Data representing the schema. Must be jsonschema valid.
filename (string): Name of the schema file on the filesystem.
root (string): Absolute path to the directory where the schema file is located.
"""
super().__init__()
self.filename = filename
self.root = root
self.data = schema
self.id = self.data.get("$id") # pylint: disable=invalid-name
self.top_level_properties = set(self.data.get("properties"))
self.validator = None
self.strict_validator = None
self.format_checker = draft7_format_checker
def get_id(self):
"""Return the unique ID of the schema."""
return self.id
def validate(self, data, strict=False):
"""Validate a given data with this schema.
Args:
data (dict, list): Data to validate against the schema.
strict (bool, optional): if True the validation will automatically flag additional properties. Defaults to False.
Returns:
Iterator: Iterator of ValidationResult
"""
if strict:
validator = self.__get_strict_validator()
else:
validator = self.__get_validator()
has_error = False
for err in validator.iter_errors(data):
has_error = True
self.add_validation_error(err.message, absolute_path=list(err.absolute_path))
if not has_error:
self.add_validation_pass()
return self.get_results()
def validate_to_dict(self, data, strict=False):
"""Return a list of ValidationResult objects.
These are generated with the validate() function in dict() format instead of as a Python Object.
Args:
data (dict, list): Data to validate against the schema.
strict (bool, optional): if True the validation will automatically flag additional properties. Defaults to False.
Returns:
list of dictionnaries containing the results.
"""
return [
result.dict(exclude_unset=True, exclude_none=True) for result in self.validate(data=data, strict=strict)
]
def __get_validator(self):
"""Return the validator for this schema, create if it doesn't exist already.
Returns:
Draft7Validator: The validator for this schema.
"""
if self.validator:
return self.validator
self.validator = Draft7Validator(self.data, format_checker=self.format_checker)
return self.validator
def __get_strict_validator(self):
"""Return a strict version of the Validator, create it if it doesn't exist already.
To create a strict version of the schema, this function adds `additionalProperties` to all objects in the schema.
Returns:
Draft7Validator: Validator for this schema in strict mode.
"""
# TODO Currently the function is only modifying the top level object, need to add that to all objects recursively
if self.strict_validator:
return self.strict_validator
# Create a copy if the schema first and modify it to insert `additionalProperties`
schema = copy.deepcopy(self.data)
if schema.get("additionalProperties", False) is not False:
print(f"{schema['$id']}: Overriding existing additionalProperties: {schema['additionalProperties']}")
schema["additionalProperties"] = False
# TODO This should be recursive, e.g. all sub-objects, currently it only goes one level deep, look in jsonschema for utilitiies
for prop_name, prop in schema.get("properties", {}).items():
items = prop.get("items", {})
if items.get("type") == "object":
if items.get("additionalProperties", False) is not False:
print(
f"{schema['$id']}: Overriding item {prop_name}.additionalProperties: {items['additionalProperties']}"
)
items["additionalProperties"] = False
self.strict_validator = Draft7Validator(schema, format_checker=self.format_checker)
return self.strict_validator
def check_if_valid(self):
"""Check if the schema definition is valid against JsonSchema draft7.
Returns:
List[ValidationResult]: A list of validation result objects.
"""
validator = Draft7Validator(v7schema, format_checker=self.format_checker)
results = []
has_error = False
for err in validator.iter_errors(self.data):
has_error = True
results.append(
ValidationResult(
schema_id=self.id,
result=RESULT_FAIL,
message=err.message,
absolute_path=list(err.absolute_path),
instance_type="SCHEMA",
instance_name=self.id,
instance_location="",
)
)
if not has_error:
results.append(
ValidationResult(
schema_id=self.id,
result=RESULT_PASS,
instance_type="SCHEMA",
instance_name=self.id,
instance_location="",
)
)
return results
|
Markdown
|
UTF-8
| 962 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
# Azure CLI 2.0 Samples
This is a repo of scripts for illustrating usage of Azure CLI 2.0 and more generally, Azure in Linux.
The intent is to provide real world scripts and scenarios to help folks be successful working with
Azure infrastructure.
If you have an suggestions for scripts or would like to see an example script written, feel free to
create an issue explaining the goals of the script. I'll try to get to your request as soon as possible.
## Samples
- Scale Sets
- [PHP app tier provisioned with Ansible](./scaleset-php-ansible/README.md): build a scale set and deploy out some PHP bits
- Virtual Machines
- [Create VM from custom VHD](./vm-custom-vhd/README.md): upload VHD and create VM from VHD
- [Restart by tag and async VM creation](./vm-restart-by-tag/README.md): build multiple VMs across groups async and restart them by tag
## Contributing
If you would like to contribute a script, please feel free to open a pull request.
|
Markdown
|
UTF-8
| 17,307 | 2.875 | 3 |
[] |
no_license
|
# 686 Usability Research: P2 (Roger O)
### Warm up
- *Tell me a little about yourself*
- 61, live in CT
- Served in the Navy initially as a corpsman, became a flight nurse in the AF reserve at ~26-27 years of service
- Started having issues years ago, went to Vet Center and been going there for 3+ years now
- They got me hooked up into the VA system and I've started getting some disability, started at 30%, went to 50% for a while, recently got moved up to 90%
- Took a lot of courses as a nurse in the reserve, combat nursing, burn course in San Antonio, TX
- Been plugging along, I do these things from time to time if it'll help out other Vets
- I didn't know a lot myself over the years, only through the VSOs and signing up for a lot of different things for the VA that I learned about different programs
- There's a lot of Vets out there that don't know what's available to them
- I'm 61, I've kinda had to learn about the web and computer. My girls were far more well-versed than I was when I went to nursing school
- A lot of older Vets are usually not that savvy when it comes to computers and accessing things. A lot of them still have flip phones. Anything to make it easier for them to learn and understand and access benefits is a good thing.
- *Do you use online services now to access benefits?*
- I have MHV premium, a Vets.gov sign in, and eBenefits sign in
- Just got those within the last year
- I had the healthy benefits for a long time, never really accessed it that much for anything. They have improved that site, you don't have to click to another place for messaging anymore. It seems more user-friendly, user-accessible since they're working on that
- You can access any or all of the sites kinda right now is my understanding
- I still have my access stuff for healthy benefits, Vets.gov, and ebenefits. I have all 3
- *Have your daughters or any other dependents ever used benefits through your VA record?*
- Not my daughters per se, a lot of this stuff has just started in the last year and a half to two years
- It was through the urging of my counselor at the Vet Center to apply for benefits
- I was struggling, out of work a couple of times and lived at my house here for 26 years, almost lost that
- Still walking a tight rope with that
- I'm married, previously divorced
- I have PTSD issues, that doesn't make life all that easy for others around me
- *What information do you currently have about any benefits that your dependents could use through your VA record?*
- I have some books, haven't really looked at it
- I'm taking things one day at a time
- I'm in a couple groups, chaplains group, mens group
- Heard the other guys talk, heard more about benefits once you hit that 100% threshold. You get insurance for the wife if you're married, different things. I've heard more about that, not much about those of us under that 100% threshold
- I do get extra in my disability payment because I am married, that's about the only thing right there
### Intro page
- *What you should see now is a page on Vets.gov. Take a moment to look around this page and tell me what the purpose is*
- It says add dependent to your VA benefits, I guess it's to establish benefits should you have any dependents
- *How would you go about finding out if you're eligible?*
- I'd go through this stuff, I know there's some stuff with kids age 18-23, but my daughters are older and not eligible for that kinda stuff
- When I first got my disability payments, all I did was call in to the 800 line and they helped me and my wife ove the phone, I didn't do it online
- *What was your experience with that?*
- It seemed pretty easy in that regard, they said I could do it online but they took care of it over the phone. Sometimes adding documentation online can be a little difficult because
- I'm not all that familiar with the who what where why's. I'd call my daughter to help me sometimes but she's off in her own place and married now so I don't have my in-house tutor, so to speak
- *How did you find the 800 number when you were ready to add your wife to your benefits?*
- For some reason I can't remember, but I just seemed to remember the number for some reason and I just called it
- *Let's say you were going to add your wife to your VA benefits through the website. Taking a look through this page, do you feel like you have an understanding of what info you would need in order to do that?*
- It says "prepare" here - your SSN, that I know. When I joined up that was the main number. Current and previous marriage details, you'd have to get all that prior marriage information
- Details about Vet's unmarried children, name, SSN, DOB. Then there's at school between 18-23, you gotta get approval of school attendance
- Apparently you can download that form, but that'd be an issue for me because I don't have a printer
- Sometimes filling stuff out online and trying to hook it up with whatever you're doing, there seems to be a disconnect with that
- *If there were an alternate to download that form, how would you expect to fill it out?*
- As part of the application process, just have the form attached right to it and fill it out and do the electronic signature that everyone seems to do right now and make it part of the whole application process
- Don't make it separate, you'd have to fill it out, print it out, attach it. You'd probably lose some people with that
- *Has that happened before with you?*
- Trying to get things attached yeah, not specifically with VA but with other things
- *Let's go ahead and start the process of filling out the application*
- (Scrolling up and down, looking for where to start)
- I guess I should hit this button here. When it always says "respondent burden 15 minutes", I usually add an hour to those things because things don't always work out so well for me
- *You mentioned you'd need to fill out some documents like previous marriage info, would you consider that part of that time you'd add?*
- No, just usually for me you can count on doubling or tripling it. Sometimes I just don't understand things. Respondent burden if you're computer-savvy, yes, but if you're not then sometimes it can be a little bit more
- I have an iphone, and I'd always had a flip phone. I like the iphone because it's on the KISS principle. For me that's good. I've seen the Android phones and they're not all that simple. The iphone does keep it very simple. If you don't know what's going on you can still use the phone and access things. The easier the better.
- Kids these days are so computer technical savvy, but I grew up in a time period where there were no computers
- *Let's go ahead and start the application*
- Ok so I click that button I guess
- Having worked in the ER for almost 20 years, when we go to discharge people we'd have to keep discharge instructions down to a 3rd grade reading level. If they can't read or understand their discharge instructions, you're not gonna get compliance. The simpler it is, you have people all over the place on the spectrum of things. I knew that from working as a nurse in the ER.
### Chapter 1
- *Before you fill out info, whose information is the form asking for?*
- That'd be me - "your first name"
- *For the question "Relationship to the Veteran", why do you think someone would select other?*
- Someone helping them fill it out? I don't know. A Vet rep or VSO, something like that. The other one is a spouse or surviving spouse if they're looking to get benefits under the Veteran, then the unmarried adult child
### Chapter 2
- *Whose information is it asking for?*
- Veteran info, you'd put in your SSN
- *You mentioned you'd memorized your SSN?*
- In the 70s your SSN was on everything, plastered all over creation so people figured out they could steal your identity
- (SSN error) dashes allowed, oh it's telling me I didn't put dashes. Well hopefully that'll be ok now
- *What do you think went wrong since adding dashes didn't correct the error?*
- It must be sensing in the system that that isn't a valid social security number
### Chapter 3
- *On this page, why do you think you're being asked this question?*
- If you're adding dependents, what's your status, you know
- *What other information do you expect you'll be asked based on this?*
- I guess you start adding them if you click "Married"
- Ok so it's asking me my current marriage
- *If you were filling out this form with the intention to add your spouse to your benefits, how would you go about recalling date of marriage and city where you got married?*
- I would say most guys should know that. Unless you're Raymond Barone. That's something you should know but if not you'll have to dig out your marriage certificate. But if not you'd go to the town hall or city hall where you got married?
- *What would you do about this form if you realized you needed to go gather info you didn't have on hand?*
- It says at the bottom save and finish this application later
- *Is that something you'd try?*
- Usually when I try to save something I can't find it later, that hasn't happened to me with the VA but in other areas.
- It's kinda small down there number 1, number 2 if you've had prior bad experiences people may say hell with it, and just close it out
- *And then restart when they have the info?*
- Or just forget about it.
- I know it says at the beginning what you need, but talking to other Vets when they have to start providing more information than they thought they'll get frustrated and sometimes walk away
- If it's not something that's gonna be easy and they can remember, they'll give up on it
- Take the person with more than one marriage, ok? You may not remember your second, third, fourth, or fifth marriage information, so you'd have to get it
- Why are they requesting all this prior marriage info?
- I guess if there's kids and there's child support or alimony, that's the only thing I can think of
- Disability payments aren't something that can be attached or acquired by other people or entities because it's a disability payment, so I don't know
### Chapter 4
- *Whose information is this page asking about?*
- Current spouse
- *Do you have your current spouse's SSN memorized as well?*
- No I have it written down in my wallet
- What happens if she doesn't have a VA file number?
- *Do you think it's something you'd have to put here?*
- We'll find out when I hit continue, won't we?
- *If you entered her SSN do you think that would be sufficient?*
- Possibly. From years ago they used SSN, now they're changing things
### Chapter 5
- *Why are you being asked about unmarried children if you're only trying to add your spouse?*
- They might be eligible for some benefits I guess based on their age and school status
- I guess if you've got more than one child you hit that "add another child" and keep going until you've completed your scenario
- *Whose information are they asking about here?*
- You see the child's name that was inputted above
- *For that "status of this child" question, do the categories make sense?*
- Yes
- Then you'd have to go to that form they talked about in the beginning and fill that out
- "You can send this form later"
- *Would you go back to that form and send it later?*
- I'd prefer not to, I'd prefer to get it out of the way right now. But you'd have to give it to the school don't you?
- *If there was a portion for the school to fill out, how do you imagine that'd work?*
- You need a copy -- that's the problem, if you don't have a printer you're kind a out of luck
- Maybe put something there "if you're unable to print, please check this box and we'll mail you a form"
- Again a lot of older vets may not be computer savvy, have printers, what have you
- Just have something on the side that says "click this button if you're unable to print, be advised we'll mail you a copy of the form that you can take to the school and complete it"
- When I see things like this, for me it's kinda a bump in the road or somewhat of a road block
- Granted I'm 61, I know Vets younger and older than myself, things like that they'd say "heck with it", close it and not come back
### Chapter 6 (Review)
- *Before submitting, what do you imagine you can do on this page?*
- Now I know you can click on the little thing there (accordion) to edit and change things. You can review the information you put in there. That kinda helps you right there
- Ok, let's go down and review it
- Then there's a box about you go to jail and stuff like that, privacy policy that everybody has and I guess you have to check that box and then submit the application
- *Go ahead and submit*
- (Error: some info is missing or not valid)
- I guess I missed something
- *What do you imagine that you missed?*
- I guess it was the form for school? No?
- *What would you do if you saw this? How would you verify that's the form that was missing?*
- It doesn't say here, there's nothing to click on here that tells me what it is
- I'd feel a little ticked off that I went through all this stuff and it's telling me I didn't do something
- It should say if it relates to the school form, the school form is missing. Please check this box to fill it out and return it
- It should say what the issue is, otherwise I have no idea
- It says save and finish later, but I don't know what to finish. It's frustrating
- Maybe you know, but you're not telling me. This probably would be an application process killer right here, seeing this and saying heck with it and leaving
- What is the reason then, was it the school form?
- *That was not the reason, it must have a been a field that you missed. How would you want to know which field you missed?*
- It seems like I've answered all the questions in this quick review thing. Oh it didn't ask about the previous spouse.
- It asked how many times I'd been married before and I said 1. Is that what it's looking for, the previous marriage?
- *If that were the case, would you go back and try to add the information at this point?*
- I'd probably walk away from it, because there were no questions anywhere asking about the first wife. It asked about the current wife, but didn't ask about the previous wife
- There were no questions, every time I clicked continue it sent me through
- If I hadn't filled it out, it would have kicked me out like with the SSN thing
- The simpler it is, the better the response you're gonna get to it, espeically for people in their 40s and beyond
- I was in a clinic one day and this guy brought a neighbor in, telling me about his dad who's 96 and lives alone in FL and talking about all the issues he had. I asked if he'd apply for disability and he said no, he said he's just squeaking by on his own because he has limited financial resources. I said he should talk to a VSO and he could get money that's tax-free to help him live and survive. At 96 he wants to maintain his independence
- I was telling him about the different things, he was appreciative of it. Go to one of them, VFW, American Legion, DAV. Have them talk to your dad and start filling out things. Because he didn't know, the family didn't know. There's a guy who definitely should be getting everything he's entitled to, he fought in WWII.
- When I did the first one (session) we talked for an hour and a half because I brought up all kinds of different issues. If you focus on the KISS principle for everybody out there and keep it on a level. Like I said, all the ERs everything had to be on a third grade level. Sometimes younger people, sometimes older, sometimes parents who spoke another language.
- Anything and everything to help out there. I'm appreciative of what I've gotten. Is VA perfect? No. For a lot of things it's very good. For issues like PTSD, hearing. Men and women coming back with TBIs, multiple system injuries. The VA is very important for that.
- I found something on the web last night, there's a group of over 400 plastic surgeons in the US who will help Veterans with plastic surgery to repair the injuries and scars they have for free. I saved that so when I come across somebody.
- In my mens group a lot of guys don't know things, and I bring up things. Since I was a paramedic and nurse I have a lot more insights than most patients in the VA. I have knowledge and experience they don't have in terms of dealing with the system. I know of different avenues to do things.
- I went out on Choice [program], had Choice appts last Aug and Sep. They finally paid my doctor. Some doctors have been going after the Vets. Even if you go out on Choice, VA couldn't get me an appt so sent me to an outside doc, it still took 60 days. It's tough. Those are kinks and bureaucracy that they need to deal with.
### Closing
- *Recruiting*
- Guys in my mens groups, some are younger, some are older
- Even though they're getting care from the VA, they're very leery of things like this
- I've done some research things with the VA too to help out with trying to improve things for Vets
- In the research studies they came into one of my groups and none of the guys are interested
|
Markdown
|
UTF-8
| 776 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
# React
## Learning patterns etc.
### 1. controlled vs uncontrolled
- 1 How to make simple components
### 2. state management (mobx)
- 1 Make the same components, but usng store state
- 2 When components need to communicate
### 3. hooks
Full components vs presenational
### 4. state management vs hooks
When to use what?
___
# To start run:
### `yarn start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
From there you should be able to access the different learning modules from the menu
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
Java
|
UTF-8
| 342 | 2.859375 | 3 |
[] |
no_license
|
package edu.sbcc.cs105;
public class Program {
public static void main(String[] args) {
StudentRepository repo = new StudentRepositoryMock();
Student s = new Student("Joe", "A", "Gaucho", 1);
repo.saveStudent(s);
Student s1 = repo.getStudent(1);
System.out.printf("%s %s", s1.getFirstName(), s1.getLastName());
}
}
|
C++
|
UTF-8
| 3,213 | 2.84375 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <time.h>
#include "String.hpp"
#include "List.hpp"
using namespace std;
inline char toLower(char ch){return 'A'<=ch&&ch<='Z'?(ch-'A'+'a'):ch;}
void findAllKMP(String const& str, List<String>& patList, int times){
static int init=0;
static List<int*> prefixList;
static List<int> matched;
if(!init){ // Build prefix array for each pattern
for(List<String>::iterator iter=patList.begin();iter!=patList.end();++iter){
prefixList.push_back(new int[iter->size()]);
matched.push_back(0);
int* prefix = prefixList.back();
int pat=1;
int size = iter->size();
prefix[0]=0;
while(pat<size){
int pre=prefix[pat-1];
while(pre>0&&toLower((*iter)[pre])!=toLower((*iter)[pat]))
pre = prefix[pre-1];
prefix[pat]=pre;
if(toLower((*iter)[pre])==toLower((*iter)[pat]))
prefix[pat]++;
pat++;
}
}
init=1;
}
int txt=0;
while(txt<str.size()){ ///KMP
List<int>::iterator mIter=matched.begin();
List<int*>::iterator preIter=prefixList.begin();
for(List<String>::iterator iter=patList.begin();iter!=patList.end();++iter,++mIter,++preIter){
/// Enumerate each pattern once and compare it with text
/// if character match, pattern matched progress incremented
/// if pattern fully matched, output in the specified form
/// if character mismatch or pattern fully matched,
/// back track the pattern matched progress according to prefix array
/// if all pattern enumerated, text matching progress incremented
/// if text matching fully completed, break out of the function
/// go back to first step and loop
bool hold=true;
while(hold){
int& pat = *mIter;
int* prefix = *preIter;
if(toLower(str[txt])==toLower((*iter)[pat])){
pat++;
hold=false;
}
else{
if(pat) pat=prefix[pat-1];
else hold=false;
}
if(pat==(*iter).size()){
printf("%d %d ",times,txt-pat+1+1);
cout<<"\""<<(*iter)<<"\" \""<<str<<"\"\n";
if(pat) pat=prefix[pat-1];
else hold=false;
}
}
}
txt++;
}
}
int main(int argc, char* argv[]){
if(argc<3) return 1;
List<String> patList;
int patSize=0;
ifstream fpat, ftxt;
fpat.open(argv[1],ios::in);
ftxt.open(argv[2],ios::in);
String txt, pat;
clock_t clk;
clk=clock();
while(!fpat.eof()){
patList.push_back(String());
if(getline(fpat,patList.back())==EOF)
patList.pop_back();
}
fpat.close();
for(int times=1;;times++){
if(getline(ftxt,txt)==EOF) break;
findAllKMP(txt, patList, times);
}
cout<<clock()-clk<<"ms\n";
ftxt.close();
return 0;
}
|
Java
|
UTF-8
| 2,637 | 2.453125 | 2 |
[] |
no_license
|
package com.gome.ecmall.util;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
/**
* 百度地图-工具类
*/
public class BaiduMapUtils {
public static final String googleToBaiduUrl = "http://api.map.baidu.com/ag/coord/convert?from=2&to=4&x=#x#&y=#y#";
private static String reverseGeocode(String url) {
try {
HttpGet httpGet = new HttpGet(url);
BasicHttpParams httpParams = new BasicHttpParams();
DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpParams);
HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_OK) {
String charSet = EntityUtils.getContentCharSet(httpResponse.getEntity());
if (null == charSet) {
charSet = "UTF-8";
}
String str = new String(EntityUtils.toByteArray(httpResponse.getEntity()), charSet);
defaultHttpClient.getConnectionManager().shutdown();
return str;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* google to baidu 坐标
* @param x
* @param y
* @return
*/
public static Map<String, Object> googleToBaidu(Double x, Double y) {
Map<String, Object> map = new HashMap<String, Object>();
String relt = reverseGeocode(getGoogleToBaiduUrl(String.valueOf(x), String.valueOf(y)));
if (!TextUtils.isEmpty(relt)) {
JSONObject jsonObj;
try {
jsonObj = new JSONObject(relt);
String xjson = jsonObj.optString("x");
String yjson = jsonObj.optString("y");
map.put("x", Double.parseDouble(new String(Base64.decode(xjson))));
map.put("y", Double.parseDouble(new String(Base64.decode(yjson))));
return map;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
private static String getGoogleToBaiduUrl(String x, String y) {
return googleToBaiduUrl.replace("#x#", x).replace("#y#", y);
}
}
|
Python
|
UTF-8
| 599 | 2.5625 | 3 |
[] |
no_license
|
"""
Shuffles the positions for barcodes -> used to compare null model assumptions
"""
import pandas as pd
positions_in = snakemake.input['positions']
positions_out = snakemake.output['positions']
xmin = snakemake.params['xmin']
xmax = snakemake.params['xmax']
ymin = snakemake.params['ymin']
ymax = snakemake.params['ymax']
positions = pd.read_table(positions_in, index_col=0)
positions = positions.loc[
(positions.iloc[:, 0] >= xmin) &
(positions.iloc[:, 0] <= xmax) &
(positions.iloc[:, 1] >= ymin) &
(positions.iloc[:, 1] <= ymax)
]
positions.to_csv(positions_out, sep='\t')
|
Markdown
|
UTF-8
| 541 | 3.171875 | 3 |
[] |
no_license
|
# workTimer
A simple timer application made with HTML, CSS and Javascript, to remind the user when to take a short break during work. The user can input the amount of time they wish to have working and, how long they wish to take a break in between. The application alerts the user when the timer is up, either to take a break or get back to work. The users preferences are saved in local storage and a dark/light mode is provided for enhanced user experience. Bootstrap and google fonts are also included.

|
Markdown
|
UTF-8
| 9,577 | 4.03125 | 4 |
[
"MIT"
] |
permissive
|
# Coursework Two - Full-time
Java provides several types of numbers, but it does not provide fractions. Your task is to implement a
`Fraction` API (**A**pplication **P**rogrammer's **I**nterface) and write a small program that uses it.
## Purpose of this assignment
* To give you practice with creating classes.
* To give you practice reading the API.
* To give you more practice with string manipulation.
* To give you practice creating `Javadoc` files.
## General idea of the assignment
* Implement a `Fraction` API.
* Write very thorough `JUnit` tests.
Create a package named `fraction`. Your classes, `Fraction`, and `FractionTest`,
will all be within this package.
Declare your class as
```java
public class Fraction implements Comparable<Fraction> {...}
```
(The reason for the "`implements`" part will be explained in class; for now, just do it.)
Note: The `Fraction` class has a lot of methods, but they are all pretty short.
## The API
The following lists some information about your new `Fraction` type:
### Instance variables
Two `private` integers, known as the *numerator* and the *denominator*.
Do not provide getters or setters for
these instance variables; there is no reason for anything outside the `Fraction` class to know about them.
Note: Even though these instance variables are `private`, they are private to the *class*,
not to the object.
This means: Any `Fraction` object can access the private variables of any other `Fraction` object; it's only
outside this class that you cannot access them.
### How written
`n/d`, where `n` is the numerator and `d` is the denominator.
### Restrictions
The denominator may not be zero.
### Normalisation
* The fraction is **always** kept in the lowest terms, that is, the *Greatest Common Divisor* (GCD)
of `n` and `d` is `1` (use Euclid's algorithm).
* The denominator is never negative. (You can give a negative number for the denominator
to the constructor when you create the fraction, but a negative fraction should be represented internally
with a negative numerator.)
* Zero should be represented as `0/1`.
The following lists the constructors you should have:
Constructor | How it uses its parameters
------------|------------
`public Fraction(int numerator, int denominator)` | Parameters are the *numerator* and the *denominator*. **Normalize** the fraction as you create it. For instance, if the parameters are `(8, -12)`, create a `Fraction` with numerator `-2` and denominator `3`. The constructor should throw an `ArithmeticException` if the denominator is zero.
`public Fraction(int wholeNumber)` | The parameter is the numerator and `1` is the implicit denominator.
`public Fraction(String fraction)` | The parameter is a `String` containing either a whole number, such as `"5"` or `"-3"`, or a fraction, such as `"8/-12"`. Allow blanks around (but not within) integers. The constructor should throw an `ArithmeticException` if given a string representing a fraction whose denominator is zero.<br/><br/>You may find it helpful to look at the available [`String`](https://docs.oracle.com/javase/9/docs/api/java/lang/String.html) methods in the [Java API](https://docs.oracle.com/javase/9/docs/api/overview-summary.html).
Notes:
* Java allows you to have more than one constructor, so long as they have different numbers or
types of parameters. For example, if you call `new Fraction(3)` you will get the second constructor
listed above. A `String` is a string, though, so the third constructor will have to distinguish
between `"3"` and `"3/4"`.
* To throw an `Exception`, write a statement such as:
```java
throw new ArithmeticException("Divide by zero");
```
(The `String` parameter is optional.)
* The java method `Integer(string).parseInt()` will return the `int` equivalent of the string
(assuming that the string represents a legal integer).
Malformed input will cause it to throw a `NumberFormatException`.
Method signature | What it does
-----------------|------------
`public Fraction add(Fraction f)` | Returns a new `Fraction` that is the **sum** of `this` and `that`: <br/><br/>`a/b + c/d` is `(ad + bc)/bd`
`public Fraction subtract(Fraction f)` | Returns a new `Fraction` that is the **difference** of `this` minus `that`: <br/><br/> `a/b - c/d` is `(ad - bc)/bd`
`public Fraction multiply(Fraction f)` | Returns a new `Fraction` that is the **product** of `this` and `that`:<br/><br/> `(a/b) * (c/d)` is `(a*c)/(b*d)`
`public Fraction divide(Fraction f)` | Returns a new `Fraction` that is the **quotient** of dividing `this` by `that`:<br/><br/> `(a/b) / (c/d)` is `(a*d)/(b*c)`
`public Fraction abs()` | Returns a new `Fraction` that is the *absolute value* of `this` fraction.
`public Fraction negate()` | Returns a new `Fraction` that has the same numeric value of `this` fraction, but the opposite sign.
`public Fraction inverse()` | The inverse of `a/b` is `b/a`.
`@Override`<br/>`public boolean equals(Object o)` | Returns `true` if `o` is a `Fraction` equal to `this`, and `false` in all other cases.<br/><br/>You need this method for your `assertEquals(expected, actual)` JUnit tests to work! The `assertEquals` method calls *your* `equals` method to do its testing.
`@Override`<br/>`public int compareTo(Fraction o)` |This method returns:<ul><li>A negative `int` if `this` is less than `o`.</li><li>Zero if `this` is equal to `o`.</li><li>A positive `int` if `this` is greater than `o`.</li></ul>If `o` is `null` this method throws an appropriate (unchecked) exception.
`@Override`<br/>`public String toString()` | Returns a `String` of the form `n/d`, where `n` is the *numerator* and `d` is the *denominator*.<br/>However, if `d` is `1`, just return `n` (as a `String`).<br/> The returned `String` should not contain any blanks.<br/>If the fraction represents a negative number, a minus sign should precede `n`.<br/>This should be one of the first methods you write, because it will help you in debugging.
#### Notes:
* All `Fraction`s should be *immutable*, that is, there should be no way to change their components
after the numbers have been created. Most of your methods simply return a new number.
* When you define `equals`, notice that it requires an `Object` as a parameter.
This means that the first thing the method should do is make sure that its parameter is in fact
a `Fraction`, and return `false` if it is not.
* You can test with `o instanceof Fraction`.
* You can use `o` as a `Fraction` by saying `((Fraction)o)`, or you can save it in a `Fraction`
variable by saying `Fraction f =(Fraction)o;` and then using `f`.
* You can create additional "helper" methods (for example, to compute the GCD, or to normalise a fraction),
if you wish; *we recommend doing so*.
If you do, **do not** make these methods `public`, but **do** test them (if you can figure out how).
To put a fraction into its lowest terms, divide both the numerator and the denominator by their
Greatest Common Divisor (GCD); **Euclid's algorithm** finds the GCD of two integers.
It works as follows:
* As long as the two numbers are not equal, replace the larger number with the remainder of dividing
the larger by the smaller (that is, `larger = larger % smaller`).
* When the two numbers are equal, that value is the GCD.
(If this brief explanation isn't enough, look up Euclid's algorithm on the Web.)
## JUnit testing
Your goal in writing the `JUnit` class is to test for *every* possible error.
This includes making sure that the correct `Exception`s are thrown when appropriate.
Most of your tests will have this form:
```java
@Test
public void testAdd() {
// Tests that are expected to succeed
}
```
To test for an exception, use this form:
```java
@Test(expected=ArithmeticException.class)
public void testDivideByZero() {
// test that should throw an ArithmeticException
}
```
You can find the various kinds of assertions you can use in the [JUnit API](http://junit.sourceforge.net/javadoc/).
## Comments
All methods in your `Fraction` class should have `Javadoc` comments.
The methods in your test class do not need to be commented, unless they are particularly
complex or non-obvious.
IntelliJ can help you by writing the `Javadoc` "outline" for you, which you can then complete.
For example, suppose you have written the method stub (you are using TDD, aren't you?):
```java
public Fraction add(Fraction f) {
return null;
}
```
Then IntelliJ can create:
```java
/**
* @param f
* @return
*/
```
which you can then complete; for example:
```java
/**
* Returns the sum of this Fraction and the Fraction f.
* @param f The Fraction to be added to this one.
* @return The sum of the two Fractions.
*/
```
### Javadoc
* Create `Javadoc` comments for all your methods (except your test methods).
IntelliJ will create the skeleton of a method or class comment for you.
You have to complete the details, both the general description and after each `@` tag.
* After writing the comments, use IntelliJ to generate the actual `Javadoc` files.
* Finally, look at the `Javadoc` files, and make sure they are complete and correct.
## Grading
Your grade will be based on:
* How correct and complete your number class is.
* How complete and correct your `JUnit` tests are.
* How complete your `Javadoc` is (and whether you remembered to generate it!)
* Your comments and general programming style.
We will use our own programs and our own unit tests for grading purposes, therefore,
you must adhere to the method names and parameter types shown.
|
Markdown
|
UTF-8
| 3,527 | 2.90625 | 3 |
[] |
no_license
|
# 示例篇
## 前言
上一篇[移动应用遗留系统重构(2)-架构篇](https://juejin.cn/post/6945313969556946980)我们介绍了业内的优秀架构实践以及CloudDisk团队根据业务情况设计的分层架构。
这一篇我们将介绍一个浓缩版的示例,示例中我们设计了一些常见的异常依赖,后续的重构篇我们也将基于这个示例进行操作演示。为了简化代码及对业务上下文的理解,示例中的部分实现都是空实现,重点体现异常的耦合依赖。
仓库地址:[CloudDisk](https://github.com/junbin1011/CloudDisk)
## CloudDisk示例
### 项目概述
CloudDisk是一个类似于Google Drive的云存储应用。该应用主要拥有3大核心业务模块。
1. **文件模块**:用于管理用户云端文件系统。用户能够上传、下载、浏览文件。
2. **动态模块**:类似微信朋友圈,用于可以在动态上分享信息及文件
3. **个人中心模块**:用于管理用户个人信息
### 问题说明
该项目已经维护超过10年以上,目前有用开发人员100+。代码在一个大单体模块中,约30w行左右,编译时间5分钟以上。团队目前主要面临几个问题。
1. 开发效率低,编译时间长,经常出现代码合并冲突
2. 代码质量差,经常修改出新问题
3. 市场响应慢,需要对齐各个模块进行整包发布
### 代码分析
代码在一个Module中,且在一个Git仓中管理。采用"MVC"结构,按功能进行划分Package。
包结构如下:

主要包说明:
| 包名 | 功能说明 |
| :--- | :--- |
| adapter | ViewPager RecycleView等适配器类 |
| callback | 接口回调 |
| controller | 主要的业务逻辑 |
| model | 数据模型 |
| ui | Activity、Fragment相关界面 |
| util | 公用工具类 |
主要类说明:
| 类名 | 功能说明 |
| :--- | :--- |
| MainActivity | 应用主界面,用于加载显示各个模块的Fragment |
| CallBack | 网络接口操作回调 |
| DynamicController | 动态模块主要业务逻辑,包含发布及获取列表 |
| FileController | 文件模块主要业务逻辑,主要包含上传、下载、获取文件列表 |
| UserController | 用户模块主要业务逻辑,主要包含登录,获取用户信息 |
| HttpUtils | 网络请求,用于发送get及post请求 |
| LogUtils | 主要用于进行日志记录 |
详细源码见[CloudDisk](https://github.com/junbin1011/CloudDisk)
> 为了简化业务上下文理解,代码都是空实现,只体现模块的异常依赖,后续的MV\*重构篇会持续补充常见坏味道示例代码。
## 总结
CloudDisk在业务最初发展的时候,采用了单一Module及简单“MVC”架构很好的支持了业务的发展,但随着业务的演化及人员膨胀,这样的模式已经很难高效的支持业务及团队的发展。
前面我们已经分享了“理想”(未来的架构设计)与“现实”(目前的代码现状),接下来在我们开始动手进行重构时,我们首先得知道往理想的设计架构演化,中间存在多少问题。一方面作为开始重构的输入,另外一方面我们有数据指标,也能评估工作量及衡量进度。
下一篇,我们将给大家分享移动应用遗留系统重构(4)-分析篇。介绍常用的分析工具及框架,并对CloudDisk团队目前的代码进行分析。
|
Markdown
|
UTF-8
| 9,337 | 3.5 | 4 |
[] |
no_license
|
# token bot
`token` is a chat bot for acknowledging and thanking peers. It can be used to award prizes to people who have helped others. It was built on the [Hubot][hubot] framework.
## Summary
The bot keeps track of acknowledgment given from one user to another. Each unit of acknowledgment is called a **token**. Everyone starts out with the same number of tokens. Users can `give` one token at a time to other users.
Users can also `revoke` a token. There are a couple reasons why someone may revoke a token. One may decide that the person was not helping as much as hoped. Or one may want to give that token to someone else who has been more helpful.
Users can also ask the bot to show the `status` of a user, and they can ask for a `leaderboard` of who has received the most tokens.
The administrator of the bot can "freeze" the giving and revoking of tokens using the environment variable `TOKENS_CAN_BE_TRANSFERRED`. Details on how to do that, and on what the other environment variables are, are given in the section [Technical information](#technical-information).
The bot was developed for a randomized controlled trial on social networks and entrepreneurship called [The Adansonia Project][adansonia]. At the end of the experiment, each token is a lottery ticket for a prize. Thus, the `token` bot can create incentives for people to help one another.
[hubot]: http://hubot.github.com
[adansonia]: https://adansonia.net/
## Usage
### Format of commands
The bot responds to commands in public channels that begin with its name `token`:
```
token <command>
```
You can also set an alias for the bot, as described in the [Configuration](#configuration) section. For example, if `/` is an alias for the bot's name `token`, then you can also write commands as
```
/<command>
```
Example of commands are given below.
(You can change whether the bot listens for commands in all public channels by changing an environment variable, as explained below [in the configuration section](#create-a-bot-user-in-Rocket.Chat).)
You can also enter commands in a direct message with `@token`, the bot. That way, other people don't need to see your command. When you enter a command in a direct message, you don't need to write `token` (nor an alias such as `/`) at the beginning of the command.
### Giving and revoking tokens
Did `@UsainBolt` help you become a better sprinter? Then `/give` a token to `@UsainBolt` to thank him!
```
/give a token to @UsainBolt
```
The bot responds in the same channel with the message that looks like
```
@Charlie gave one token to @UsainBolt. @Charlie now has 1 token remaining to give to others.
```
You can also simply write `/give @UsainBolt` to give a token to `@UsainBolt`.
Want to thank `@UsainBolt` *even more* for all the gold medals you're winning thanks to him? Then give him more tokens! You can give someone more than one token by using the above command multiple times.
Changed your mind? Or someone else has helped you even more and you've run out of tokens to give them? Then `/revoke` a token from `@UsainBolt`:
```
/revoke a token from @UsainBolt
```
The bot responds in that channel with the message
```
@charlie revoked one token from @UsainBolt. @charlie now has 2 token remaining to give to others.
```
Alternatively, simply write `/revoke @UsainBolt`.
### Status
Want to check how many tokens you have left in your "pocket", how many you've given out (and to whom), and how many you've received (and from whom)? Then use the `/status` command:
```
/status
```
The `@token` bot will then send you a direct message that looks like this:
```
@charlie has 2 tokens remaining to give to others.
@charlie has given 3 tokens to the following people: @UsainBolt (2), @A.Einstein (1)
@charlie has 2 tokens from the following people: @UsainBolt (2)
```
(The response is a direct message because it contains mentions of many other users, and we don't want those users to be bothered by these responses.)
You can also use this command to check the status of any other user:
```
/status @A.Einstein
```
The reply from the `@token` bot will be a direct message that looks just like the example given above of a response to the command `/status`.
### Who still has tokens to give out?
Got time to spare and want to find people to help? Use the following command to see a list of all people who still tokens available to give to others:
```
/show users with tokens
```
(Alternatively, you can write `/who has tokens?`.) The `@token` bot then replies in a direct message with a list of who still has tokens to give out:
```
The following users still have tokens to give. Try to help these users so that they thank you with a token!
@A.Einstein (4 tokens), @UsainBolt (3 tokens)
```
### Leaderboard
Who has been given the most tokens? See who's on top with the `/leaderboard` command, which shows the top 10 users in descending order of the number of tokens received:
```
These 3 users have currently been thanked the most:
1. @UsainBolt (2 tokens)
2. @charlie (2 tokens)
3. @A.Einstein (1 token)
4. @A.Smith (1 token)
5. @Galileo (1 token)
```
Control how large the leaderboard is using the command `/show top 5 list` or `/show top eight`. The bot responds with a direct message that looks like:
```
These 3 users have currently been thanked the most:
1. @UsainBolt (2 tokens)
2. @charlie (2 tokens)
3. @A.Einstein (1 token)
```
### Help - show a list of all commands
Enter the command `token help` to show a list of all commands.
## Technical information
### Generation
This bot was initially generated by [generator-hubot][generator-hubot] and configured to be
deployed on [Heroku][heroku].
[heroku]: http://www.heroku.com
[generator-hubot]: https://github.com/github/generator-hubot
### Adapters
This bot currently uses the [Rocket.Chat Hubot adapter][rocketchat-hubot].
[rocketchat-hubot]: https://github.com/RocketChat/hubot-rocketchat
### Running token Locally
Test the token bot locally by running
% bin/hubot
You'll see some start up output and a prompt:
token> [Mon Jul 18 2016 12:10:53 GMT-0500 (CDT)] INFO hubot-redis-brain: Using default redis on localhost:6379
token>
See a list of commands by typing `token help`.
token> token help
token give a token to @user_name - Gives a token to `@user_name`. The words 'token', 'a' and 'to' are optional.
token help - Displays all of the help commands that token knows about.
...
## Configuration
### Environment variables
The following environment variables can optionally be set:
* `TOKEN_ALLOW_SELF` -- whether people can give tokens to themselves. If not set, the default is `false`.
* `TOKENS_CAN_BE_TRANSFERRED` -- whether tokens can be given and revoked. If not set, the default is `true`. Set this to false if you want to prevent people from giving and revoking tokens.
* `TOKENS_ENDOWED_TO_EACH_USER` -- the number of tokens that each user gets initially. If not set, the default is 5.
* `HUBOT_ALIAS` -- an alias that the bot will respond to when listening for commands. For example, set this variable to '/'.
Examples of how to set these are given below for the case of using Heroku to deploy the bot.
### Deploy on Heroku
To use [Heroku][heroku] to deploy the bot, first follow [these instructions][heroku-hubot]. Then set the environment variables using the following commands in a terminal:
```
heroku config:set TOKEN_ALLOW_SELF=false
heroku config:set TOKENS_CAN_BE_TRANSFERRED=true
heroku config:set TOKENS_ENDOWED_TO_EACH_USER=5
heroku config:set HUBOT_HEROKU_KEEPALIVE_URL=<url-for-your-token-bot>
heroku config:set HUBOT_ALIAS=/
```
where `<url-for-your-token-bot>` is a URL such as `https://token-bot.herokuapp.com/`. If you later want to freeze the giving and revoking of tokens, then run
```
heroku config:set TOKENS_CAN_BE_TRANSFERRED=true
```
#### Create a bot user in Rocket.Chat
First create a bot in your Rocket.Chat instance. The administrator can do this as follows: click on "Administration", then clicking on “+” button, and then choose “Bots” under the pull-down menu “Role”.
Then log into your Heroku account in a terminal and set the following environment variables:
* `heroku config:set ROCKETCHAT_URL="https://<your-rocket-chat-instance-name>.rocket.chat"`
* `heroku config:set ROCKETCHAT_ROOM="general"`
* `heroku config:set LISTEN_ON_ALL_PUBLIC=true`
* `heroku config:set ROCKETCHAT_USER=token`
* `heroku config:set ROCKETCHAT_PASSWORD=<your-password-for-the-bot>`
#### Keep a Heroku bot alive
If you're using the free plan at Heroku, you may want to use this [keep alive script][keep-alive] to keep your bot alive for 18 hour periods each day.
The token bot currently stores its data using redis brain using [this hubot-redis-brain script][hubot-redis-brain]. First create an account at [RedisToGo][redistogo], create an instance, navigate to the webpage for that instance, and find the URL for that Redis instance (it begins with `redis://redistogo:`). Then in a terminal enter
```
heroku config:set REDIS_URL=<your-redis-url>
```
[heroku]: http://www.heroku.com
[heroku-hubot]: https://hubot.github.com/docs/deploying/heroku/
[keep-alive]: https://github.com/hubot-scripts/hubot-heroku-keepalive
[hubot-redis-brain]: https://github.com/hubot-scripts/hubot-redis-brain
[redistogo]: https://redistogo.com/
|
Python
|
UTF-8
| 527 | 3.234375 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def main():
infile = open('berlin.jpg', 'rb') # Would get error if try 'rt' as this is binary and not text file
outfile = open('berlin-copy.jpg', 'wb')
while True:
buf = infile.read(10240) # reading in 10k byte chunks; not wise to read entire file at once
if buf:
outfile.write(buf)
print('.', end='', flush=True)
else: break
outfile.close()
print('\ndone.')
if __name__ == '__main__': main()
|
Markdown
|
UTF-8
| 1,374 | 2.59375 | 3 |
[] |
no_license
|
# Using The Products Package
The package is used to instanciate products object necessary to store in the database.
### Creating a Desktop Object
**Add the class** Desktop using
`var Desktop = require('./Products/Desktop.js')`
**Instanciate** a Desktop with arguments using
`var myDesktop = new Desktop(Model_Number,price,weight,BrandName,HardDriveSize,RAM,CPUCores,dimension,ProcessorType)`
### Creating a Monitor Object
**Add the class** Monitor using
`var Monitor = require('./Products/Monitor.js')`
**Instanciate** a Monitor with arguments using
`var myMonitor = new Monitor(Model_Number, price,weight,BrandName,Size)`
### Creating a Laptop Object Object
**Add the class** laptop using
`var laptop = require(./Products/laptop.js)`
**Instanciate** a laptop with argument using
`var myLaptop = new laptop('Model_Number,price,weight,BrandName,HardDriveSize,RAM,CPUCores,dimension,ProcessorType,DisplaySize,BatteryInformation,OperativeSystem')`
### Creating a Tablet Object
**Add the class** Tablet using
`var Tablet = require('./Products/Tablet.js')`
**Instanciate** a Tablet with arguments using
`var myTablet = new Tablet(Model_Number,price,weight,BrandName,HardDriveSize,RAM,CPUCores,dimension,ProcessorType,DisplaySize,BatteryInformation,OperativeSystem,CameraInformation)`
|
Markdown
|
UTF-8
| 6,276 | 2.859375 | 3 |
[] |
no_license
|
---
layout: post
title: 读文笔记Fast R-CNN
category: blog
description: 阅读Fast R-CNN笔记
---
声明:本博客欢迎转发,但请保留原作者信息!
作者:高伟毅
博客:[https://gwyve.github.io/](https://gwyve.github.io/)
微博:[http://weibo.com/u/3225437531/](http://weibo.com/u/3225437531/)
## 引言
这篇文章属于R-CNN之后的一篇,基本是在R-CNN<sup>1</sup>和SPPnet<sup>2</sup>基础之上的,推荐阅读R-CNN和SPPnet两篇再阅读该文章(我也是先看的这一篇,但是不得已又看了SPPnet)。
## 发表位置
- [ICCV 2015](http://www.cvpapers.com/iccv2015.html)
- [PDF.v2](https://arxiv.org/pdf/1504.08083v2.pdf)
## 问题引入
整篇文章是在R-CNN和SPPnet基础之上的改进,自然就是在与R-CNN和SPPnet进行对比,通过发现R-CNN和SPPnet的缺点来提升,从而形成Fast R-CNN(简称FRCN)。
### R-CNN
- 多阶段训练(Training is a multi-stage pipeline):1、object proposal(SS) 2、object detector(SVM) 3、bounding-box regressor
- 空间时间上花费大:SVM、bounding-box regressor的训练过程需要把特征写于硬盘。
- 目标检索的时候慢:对每一个object proposal都跑一遍CNN(SPP就是发现该问题提升的速度)
### SPPnet
- 多阶段训练
- 在SPP层之前的CNN不随着训练数据更新
## Fast R-CNN结构和训练过程
具体过程如下步骤:
1. 整张图片输入Cnov层和pooling层生成conv feature map
2. 从Feature map推荐生成一定数量的RoI
3. 对每个RoI进入RoI pooling层,生成固定长度的向量。
4. 第3步产生的固定长度向量输入全连接(fc)层,fc层分成两个sibling output layer:一个生成K+1个类的softmax,另一个生成bounding-position的位置。

### RoI pooling layer
这个pooling层跟SPPnet里面的SPP层很类似,只是SPP层是分为多个层次的max pooling(1,4,16....),这里的RoI pooling layer只有一个层次的取样(作者也提到这是一个特殊的SPP)。如果要输出H×W,输入是h×w,那么每个小pooling块的大小就是h/H × w/W。
### 多任务损失
这里从fc直接出来两个损失,是在联合训练。

第一项是跟某个目标对象进行比对,第二项是位置损失函数。
作者在这里说明之前的方法(OverFeat<sup>3</sup>,R-CNN,SPPnet)都是用的stage-wise的方法,Fast R-CNN是用的比他们更优。
### 小批量取样
这里确实是提升速度的一个方法,之前的方法都是用全部数据把模型训练完的,会频繁的访问硬盘,这个小批量只用把这小批量的数据放在内存就可以。这里2张图128RoI。
### 透过RoI pooling前馈传播
他说的这个意思,max pooling只能影响一部分(即生成最大数的这一部分),但是,可以通过这一部分对Conv层的filter产生影响。
我觉得,既然他这个RoI pooling作为特殊的SPP可以传播,那SPP应该也可以传播。
### 截短的SVD
这一块我打算再看一下SVD之后再自己研究
## 实验结果
他使用三个实验模型:S、M、L。
### mAP
在mAP上与R-CNN、SPPnet对比,就像挤牙膏一样。

### 时间
时间上提升很明显的,毕竟说的是fast嘛

## 设计测评
这个就是各种实验,然后亮出数据表,一看有用。这个方法是写论文必用的。
### 截短的SVD
使用该方法,mAP下降0.3%,时间减少30%

### fine-tune哪一层
fine-tune conv层有用,但并非所有的都有用,而且还可能花费更多的训练时间。

### 多任务训练有用吗?
有用

### 尺度不变
这里在考虑是使用多种尺度还是单一尺度,结果是发现多种尺度提升mAP效果一般,速度变慢。所以,作者认为单一尺度是一种速度和准确的权衡,特别是对于很深的模型。

### 需要更多训练数据吗?
训练数据越多mAP越大,那么结果显然
### SVM or softmax
R-CNN、SPPnet使用的SVM,FRCN使用softmax。

虽然svm比softmax稍微好一点,但是它证明了,跟多阶段训练比较,一下子的微调是足够的。softmax引入了各个类的竞争。
我觉得,作者仍然选择使用softmax很可能跟多任务损失有关。
### 更多的proposals有用吗?
一定程度有用,太多了就可能有害了。

又提到AR,但是又说AP要慎重考虑,也确实是这样的。
## 个人总结
### 提升准确率的
- RoI pooling layer可以前馈传播,可以更新Conv的filter
- fc输入两个损失函数,联合训练
### 提升速度的
- 小批量训练:避免数据集频繁访问硬盘
- 截短的SVD
## 个人想法
整片论文确实严谨,不过,在有个地方确实不理解,那就是为什么RoI Pooling layer使用的单一层次的max pooling,如果使用SPP层那样的会怎么样,这里本文作者也并没有指出。
本文有两个版本,强烈建议直接阅读第二个版本,第一个版本不建议读,在第一个版本读到Back-propagation through RoI pooling layers,就彻底懵了。
## 相关
[1]R. Girshick, J. Donahue, T. Darrell, and J. Malik, “Rich feature
hierarchies for accurate object detection and semantic segmentation,”
in CVPR, 2014.
[2]K. He, X. Zhang, S. Ren, and J. Sun. Spatial pyramid pooling
in deep convolutional networks for visual recognition. In
ECCV, 2014. 1
[3]P. Sermanet, D. Eigen, X. Zhang, M. Mathieu, R. Fergus,
and Y. LeCun. OverFeat: Integrated Recognition, Localization and Detection using Convolutional Networks. In ICLR, 2014. 1, 3
|
PHP
|
UTF-8
| 9,447 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
/**
* @copyright Copyright 2017, CitrusFramework. All Rights Reserved.
* @author take64 <take64@citrus.tk>
* @license http://www.citrus.tk/
*/
namespace Citrus;
use Citrus\Configure\Configurable;
use Citrus\Message\Item;
use Citrus\Variable\Singleton;
use Citrus\Variable\Structs;
/**
* メッセージ処理
*/
class Message extends Configurable
{
use Singleton;
use Structs;
/** セッションキー */
const SESSION_KEY = 'messages';
/** @var Item[] メッセージ配列 */
private $items = [];
/**
* メッセージが1件でもあるかどうか
*
* @return bool
*/
public static function exists(): bool
{
return (0 < count(self::sharedInstance()->callItems()));
}
/**
* メッセージの取得
*
* @return Item[]
*/
public static function callItems(): array
{
if (true === self::sharedInstance()->isSession())
{
return (Session::$session->call(self::SESSION_KEY) ?? []);
}
return self::sharedInstance()->items;
}
/**
* メッセージの登録
*
* @param Item[] $items アイテム配列
* @return void
*/
public static function registItems(array $items): void
{
if (true === self::sharedInstance()->isSession())
{
Session::$session->regist(self::SESSION_KEY, $items);
}
self::sharedInstance()->items = $items;
}
/**
* タグでフィルタリングしてメッセージを取得する
*
* @param string $tag
* @return Item[]
*/
public static function callItemsOfTag(string $tag): array
{
return Collection::stream(self::sharedInstance()->callItems())->filter(function ($vl) use ($tag) {
// タグが一致しているかどうか
/** @var Item $vl */
return ($vl->tag === $tag);
})->toList();
}
/**
* タイプでフィルタリングしてメッセージを取得する
*
* @param string $type
* @return Item[]
*/
public static function callItemsOfType(string $type): array
{
return Collection::stream(self::sharedInstance()->callItems())->filter(function ($vl) use ($type) {
// タイプが一致しているかどうか
/** @var Item $vl */
return ($vl->type === $type);
})->toList();
}
/**
* メッセージを取得
*
* @return Item[]
*/
public static function callMessages(): array
{
return self::sharedInstance()->callItemsOfType(Item::TYPE_MESSAGE);
}
/**
* エラーメッセージを取得
*
* @return Item[]
*/
public static function callErrors(): array
{
return self::sharedInstance()->callItemsOfType(Item::TYPE_ERROR);
}
/**
* 成功メッセージを取得
*
* @return Item[]
*/
public static function callSuccesses(): array
{
return self::sharedInstance()->callItemsOfType(Item::TYPE_SUCCESS);
}
/**
* 警告メッセージを取得
*
* @return Item[]
*/
public static function callWarnings(): array
{
return self::sharedInstance()->callItemsOfType(Item::TYPE_WARNING);
}
/**
* メッセージをポップする
*
* @param string $type
* @return Item[]
*/
public static function popItemsForType(string $type): array
{
// 結果
$results = [];
// 走査
$items = self::sharedInstance()->callItems();
foreach ($items as $ky => $vl)
{
// タイプの合うものだけ取得して削除
if ($vl->type === $type)
{
$results[] = $vl;
unset($items[$ky]);
}
}
// 再設定
self::sharedInstance()->registItems($items);
return $results;
}
/**
* メッセージを取得して削除
*
* @return Item[]
*/
public static function popMessages(): array
{
return self::sharedInstance()->popItemsForType(Item::TYPE_MESSAGE);
}
/**
* エラーメッセージを取得して削除
*
* @return Item[]
*/
public static function popErrors(): array
{
return self::sharedInstance()->popItemsForType(Item::TYPE_ERROR);
}
/**
* 成功メッセージを取得して削除
*
* @return Item[]
*/
public static function popSuccesses(): array
{
return self::sharedInstance()->popItemsForType(Item::TYPE_SUCCESS);
}
/**
* 警告メッセージを取得して削除
*
* @return Item[]
*/
public static function popWarnings(): array
{
return self::sharedInstance()->popItemsForType(Item::TYPE_WARNING);
}
/**
* メッセージアイテムの設定
*
* @param Item $item
* @return void
*/
public static function addItem(Item $item): void
{
// 取得
$items = self::sharedInstance()->callItems();
// 追加
$items[] = $item;
// 再設定
self::sharedInstance()->registItems($items);
}
/**
* メッセージ追加
*
* @param string $description 内容
* @param string|null $name 名称
* @param string|null $tag タグ
* @return void
*/
public static function addMessage(string $description, string $name = null, string $tag = null): void
{
self::sharedInstance()->addItem(new Item($description, Item::TYPE_MESSAGE, $name, false, $tag));
}
/**
* エラーメッセージの追加
*
* @param string $description 内容
* @param string|null $name 名称
* @param string|null $tag タグ
* @return void
*/
public static function addError(string $description, string $name = null, string $tag = null): void
{
self::sharedInstance()->addItem(new Item($description, Item::TYPE_ERROR, $name, false, $tag));
}
/**
* 成功メッセージの追加
*
* @param string $description 内容
* @param string|null $name 名称
* @param string|null $tag タグ
* @return void
*/
public static function addSuccess(string $description, string $name = null, string $tag = null): void
{
self::sharedInstance()->addItem(new Item($description, Item::TYPE_SUCCESS, $name, false, $tag));
}
/**
* 警告メッセージの追加
*
* @param string $description 内容
* @param string|null $name 名称
* @param string|null $tag タグ
* @return void
*/
public static function addWarning(string $description, string $name = null, string $tag = null): void
{
self::sharedInstance()->addItem(new Item($description, Item::TYPE_WARNING, $name, false, $tag));
}
/**
* メッセージの全削除
*
* @return void
*/
public static function removeAll(): void
{
// プロパティから削除
self::sharedInstance()->items = [];
// セッションから削除
if (true === self::sharedInstance()->isSession())
{
Session::$session->remove(self::SESSION_KEY);
}
}
/**
* メッセージのタグごと削除
*
* @param string|null $tag
* @return void
*/
public static function removeOfTag(string $tag = null): void
{
// 削除後メッセージを取得
$items = Collection::stream(self::sharedInstance()->callItems())->remove(function ($vl) use ($tag) {
// タグが一致しているかどうか(一致しているものが削除対象)
/** @var Item $vl */
return ($vl->tag === $tag);
})->toList();
// 再設定
self::sharedInstance()->registItems($items);
}
/**
* メッセージのタイプごと削除
*
* @param string|null $type
* @return void
*/
public static function removeOftype(string $type = null): void
{
// 削除後メッセージを取得
$items = Collection::stream(self::sharedInstance()->callItems())->remove(function ($vl) use ($type) {
// タイプが一致しているかどうか(一致しているものが削除対象)
/** @var Item $vl */
return ($vl->tag === $type);
})->toList();
// 再設定
self::sharedInstance()->registItems($items);
}
/**
* セッションを使うかどうか
*
* @return bool true:セッションを使う
*/
public static function isSession(): bool
{
return self::sharedInstance()->configures['enable_session'];
}
/**
* {@inheritDoc}
*/
protected function configureKey(): string
{
return 'message';
}
/**
* {@inheritDoc}
*/
protected function configureDefaults(): array
{
return [
'enable_session' => true,
];
}
/**
* {@inheritDoc}
*/
protected function configureRequires(): array
{
return [
'enable_session',
];
}
}
|
PHP
|
UTF-8
| 1,860 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Repositories\UserProgress;
use App\Models\Setting;
use App\Models\User;
use App\Models\UserProgress;
use App\Repositories\BaseRepository;
/**
* Class ProgressRepository.
*/
class UserProgressRepository extends BaseRepository
{
/**
* related model of this repository.
*
* @var object
*/
public $model;
public function __construct(UserProgress $model)
{
$this->model = $model;
}
public function getUserProgressByUserID($user_id,$exams_list,$exam_id = null){
$query = UserProgress::where('user_id',$user_id);
if($exam_id){
$query->where('exam_id',$exam_id)->first();
}
$progress = $query->latest()->first();
if($progress){
return $this->getCurrentQuestionIndex($exams_list,$progress);
}
}
public function getCurrentQuestionIndex($exams,$progress){
return array_search($progress->question_id,array_column($exams,'id'));
}
public function getCorrectAnswerCount($user_id,$exam_id){
return UserProgress::where('user_id',$user_id)->where('exam_id',$exam_id)->where('is_correct',1)->count();
}
public function getWrongAnswerCount($user_id,$exam_id){
return UserProgress::where('user_id',$user_id)->where('exam_id',$exam_id)->where('is_correct',0)->count();
}
public function updateOrCreate($input){
return UserProgress::firstOrCreate(
[
'user_id' => $input['user_id'],
'exam_id' => $input['exam_id'],
'question_id' => $input['question_id'],
'is_correct' => $input['is_correct']
]
);
}
public function deleteProgress($user_id,$exam_id){
UserProgress::where('user_id',$user_id)->where('exam_id',$exam_id)->delete();
return true;
}
}
|
JavaScript
|
UTF-8
| 1,222 | 3.265625 | 3 |
[] |
no_license
|
const observer = {
next: x => console.log(x),
error: e => console.error(e),
complete: () => console.log('done')
};
function map(transformFn) {
const inputObservable = this;
return createObservable(outputObserver => {
inputObservable.subscribe({
next: x => outputObserver.next(transformFn(x)),
error: e => outputObserver.error(e),
complete: () => outputObserver.complete()
});
});
}
function filter(conditionFn) {
const inputObservable = this;
return createObservable(outputObserver => {
inputObservable.subscribe({
next: x => {
if (conditionFn(x)) {
outputObserver.next(x);
}
},
error: e => outputObserver.error(e),
complete: () => outputObserver.complete()
});
});
}
function createObservable(subscribeFn) {
return {
subscribe: subscribeFn,
map: map,
filter: filter
};
}
const clickObservable = createObservable(function(ob) {
document.addEventListener('click', ob.next);
});
clickObservable
.map(event => event.clientX)
.filter(x => x > 200)
.subscribe(observer);
|
C++
|
UTF-8
| 2,164 | 2.8125 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>
using namespace std;
namespace po = boost::program_options;
template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
return os;
}
int main(int argc, char** argv)
{
int opt;
string config_file = "";
po::options_description generic("Generic options");
generic.add_options()
("version,v", "print version string")
("help", "produce help message")
("config,c", po::value<string>(&config_file)->default_value("multiple_sources.cfg"),
"name of a file of a configuration.");
po::options_description config("Configuration");
config.add_options()
("optimization", po::value<int>(&opt)->default_value(10),
"optimization level")
("include-path,I", po::value<vector<string>>()->composing(),
"include path");
po::options_description hidden("Hidden options");
hidden.add_options()
("input-file", po::value<vector<string>>(), "input file");
po::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
po::options_description config_file_options;
config_file_options.add(config).add(hidden);
po::options_description visible("Allowed options");
visible.add(generic).add(config);
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(cmdline_options)
.positional(p).run(), vm);
po::notify(vm);
ifstream ifs(config_file.c_str());
if (!ifs) {
cout << "cannot open config file: " << config_file << endl;
return 0;
} else {
po::store(po::parse_config_file(ifs, config_file_options), vm);
}
if (vm.count("help")) {
cout << visible << "\n";
return 0;
}
if (vm.count("version")) {
cout << "Multiple source example, version 1.0" << endl;
return 0;
}
if (vm.count("include-path")) {
cout << "Include paths are: " << vm["include-path"].as<vector<string>>() << endl;
}
if (vm.count("input-file")) {
cout << "Input files are: " << vm["input-file"].as<vector<string>>() << endl;
}
cout << "Optimization level is " << opt << endl;
}
|
Java
|
UTF-8
| 7,694 | 3.28125 | 3 |
[] |
no_license
|
import java.util.Scanner;
import java.lang.Math;
public class Orbits {
static Scanner scan = new Scanner(System.in);
static Satellite[] satArray = new Satellite[5];
public static int mainMenu() {
System.out.println("\n––––––––––––––––––––––––––––––––––––––––––––");
System.out.println("|Satellite Orbits Menu |");
System.out.println("|Print all satellites 1|");
System.out.println("|Select a satellite 2|");
System.out.println("|Calculate satellite velocity and period 3|");
System.out.println("|Change satellite orbit type 4|");
System.out.println("|Change satellite power type 5|");
System.out.println("|Quit 0|");
System.out.println("––––––––––––––––––––––––––––––––––––––––––––\n");
return scan.nextInt();
}
public static int powMenu() {
System.out.println("\n––––––––––––––––––––––––––––");
System.out.println("|Please enter a power type |");
System.out.println("|Nuclear 1|");
System.out.println("|Solar 2|");
System.out.println("|Battery 3|");
System.out.println("|Back 0|");
System.out.println("––––––––––––––––––––––––––––\n");
return scan.nextInt();
}
public static int selSat() {
int index;
System.out.println("Enter the array index of a satellite: ");
index = scan.nextInt();
return index;
}
public static void main(String[] args) {
int mainOption = 1;
int powOption;
boolean done = true;
Satellite sat1;
// Satellite sat2, sat3, sat4, sat5;
satArray[0] = new Satellite("ISS", "Low Earth Orbit", 408773);
satArray[1] = new Satellite("Halley's Comet", "Solar Orbit", 5.24789e12);
satArray[2] = new Satellite("Hubble Space Telescope", "Low Earth Orbit", 568000);
satArray[3] = new Satellite("James Webb Space Telescope", "Solar Orbit", 1.511e11);
satArray[4] = new Satellite("Mars Reconnaissance Orbiter", "Mars Orbit", 450000);
sat1 = satArray[0];
while (mainOption != 0) {
mainOption = mainMenu();
switch (mainOption) {
case 1: // prints out the satellites
for (int i = 0; i < satArray.length; i++) {
System.out.println(satArray[i]);
}
break;
case 2: // selects a new satellite
for (int i = 0; i < satArray.length; i++){
System.out.println(i + ". " + satArray[i]);
}
sat1 = satArray[selSat()];
System.out.println("You selected " + sat1.satName);
break;
case 3: // calculates orbit velocity and period
// velocity calculations based on orbit
if (sat1.getOrbitType() == 1) {
sat1.updateVel(Math.sqrt((Satellite.G * Satellite.E_MASS) / (sat1.orbitDist + Satellite.E_RAD)));
}
else if (sat1.getOrbitType() == 2) {
sat1.updateVel(Math.sqrt((Satellite.G * Satellite.M_MASS) / (sat1.orbitDist + Satellite.M_RAD)));
}
else {
sat1.updateVel(Math.sqrt((Satellite.G * Satellite.SOL_MASS) / (sat1.orbitDist + Satellite.SOL_RAD)));
}
System.out.println(sat1.getVel());
// period calculations based on orbit
if (sat1.getOrbitType() == 1) {
sat1.updatePeriod((2 * Math.PI * (sat1.orbitDist + Satellite.E_RAD)) / sat1.getVel());
}
else if (sat1.getOrbitType() == 2) {
sat1.updatePeriod((2 * Math.PI * (sat1.orbitDist + Satellite.M_RAD)) / sat1.getVel());
}
else {
sat1.updatePeriod((2 * Math.PI * (sat1.orbitDist + Satellite.SOL_RAD)) / sat1.getVel());
}
System.out.println(sat1.getPeriod());
break;
case 4:
int oldType = sat1.getOrbitType(), newType;
System.out.println("Current Orbit Type: " + sat1.getOrbitType());
System.out.println("Enter new Orbit Type: ");
newType = scan.nextInt();
sat1.updateOrbitType(newType);
if (newType == oldType) {
break;
}
else if (newType == 0) {
sat1.updateVel(Math.sqrt((Satellite.G * Satellite.SOL_MASS) / (sat1.orbitDist + Satellite.SOL_RAD)));
sat1.updatePeriod((2 * Math.PI * (sat1.orbitDist + Satellite.SOL_RAD)) / sat1.getVel());
}
else if (newType == 1) {
sat1.updateVel(Math.sqrt((Satellite.G * Satellite.E_MASS) / (sat1.orbitDist + Satellite.E_RAD)));
sat1.updatePeriod((2 * Math.PI * (sat1.orbitDist + Satellite.E_RAD)) / sat1.getVel());
}
else if (newType == 2) {
sat1.updateVel(Math.sqrt((Satellite.G * Satellite.M_MASS) / (sat1.orbitDist + Satellite.M_RAD)));
sat1.updatePeriod((2 * Math.PI * (sat1.orbitDist + Satellite.M_RAD)) / sat1.getVel());
}
break;
case 5:
powOption = powMenu();
switch (powOption) {
case 1:
sat1.updatePower("Nuclear");
break;
case 2:
sat1.updatePower("Solar");
break;
case 3:
sat1.updatePower("Battery");
break;
case 0:
break;
default:
System.out.println("Invalid choice");
break;
}
System.out.println("The power type has been changed to " + sat1.getPowType());
break;
case 0:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid choice, try again.");
break;
} // end of switch case
}
}
}
|
SQL
|
UTF-8
| 626 | 2.53125 | 3 |
[] |
no_license
|
/*
Navicat MySQL Data Transfer
Source Server : Locahost
Source Server Version : 50710
Source Host : localhost:3306
Source Database : kahina
Target Server Type : MYSQL
Target Server Version : 50710
File Encoding : 65001
Date: 2016-02-16 17:57:50
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for blog_categorias
-- ----------------------------
DROP TABLE IF EXISTS `blog_categorias`;
CREATE TABLE `blog_categorias` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`categoria` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
Java
|
UTF-8
| 509 | 2.953125 | 3 |
[] |
no_license
|
import java.util.Scanner;
/**
* Created by Lawrence on 2017/8/4.
*/
public class SimpleChat {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入IP地址和端口号,格式如下:IP地址,端口号");
String[] ask = in.nextLine().split(",");
String ip = ask[0];
int port = new Integer(ask[1]);
new Thread(new MySend(ip,port)).start();
new Thread(new MyReceive(port)).start();
}
}
|
Go
|
UTF-8
| 1,367 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
/*
Question:
Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
For example:
For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
For a mass of 1969, the fuel required is 654.
For a mass of 100756, the fuel required is 33583.
The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
What is the sum of the fuel requirements for all of the modules on your spacecraft?
To build and run:
$ go build part1.go
$ cat input.txt | ./part1
*/
package main
import "bufio"
import "fmt"
import "os"
import "strconv"
func max(a int, b int) int {
if a > b {
return a
}
return b
}
func fuel_cost(w int) int {
return max(0, (w/3) - 2)
}
func main() {
var ttl_fuel_cost int
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
mass, err := strconv.Atoi(scanner.Text())
if err != nil {
fmt.Println("ERROR: Cannot parse input: " + scanner.Text())
return
}
ttl_fuel_cost += fuel_cost(mass)
}
fmt.Println(ttl_fuel_cost)
}
|
Markdown
|
UTF-8
| 1,135 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
# 快速缓存
::: tip
- MadFastBuffer.h
- MadFastBuffer.c
:::
## madFBufferCreate
```c
MadFBuffer_t* madFBufferCreate(MadSize_t n, MadSize_t size)
```
新建快速缓存。
| 参数名 | 方向 | 说明 |
| :-| :-:| :-|
| n | in | 指定快速缓存的分块数 |
| size | in | 指定快速缓存的分块尺寸 |
| 返回值 | 说明 |
| :-:| :-|
| 0 | 失败 |
| NZ | 成功(指向快速缓存的指针) |
## madFBufferGet
```c
MadVptr madFBufferGet(MadFBuffer_t *fb)
```
从快速缓存中取得一个分块。
| 参数名 | 方向 | 说明 |
| :-| :-:| :-|
| fb | in | 快速缓存 |
| 返回值 | 说明 |
| :-:| :-|
| 0 | 失败 |
| NZ | 成功(指向可用数据块的指针) |
## madFBufferPut
```c
MadVptr madFBufferPut(MadFBuffer_t *fb, MadVptr buf)
```
将一个分块放回快速缓存中。
| 参数名 | 方向 | 说明 |
| :-| :-:| :-|
| fb | in | 快速缓存 |
| buf | in | 数据块 |
## madFBufferUnusedCount(fb)
返回快速缓存中可用分块的数量。
## madFBufferMaxCount(fb)
返回快速缓存中分块的最大数量。
## madFBufferDelete(fb)
删除一个快速缓存,并将 fb 置 0。
|
Java
|
UTF-8
| 855 | 1.828125 | 2 |
[] |
no_license
|
package com.ubtechinc.alpha.mini.repository.datasource;
import com.ubtechinc.alpha.mini.entity.AlbumItem;
import com.ubtrobot.lib.sync.engine.ResultPacket;
import com.ubtrobot.param.sync.Params;
import java.util.List;
/**
* @作者:liudongyang
* @日期: 18/3/22 14:23
* @描述:
*/
public interface IAlbumsDataSource {
public interface IGetAlbumsItemCallback {
public void onSuccess(List<AlbumItem> items, ResultPacket<Params.PullResponse> pullResponseResultPacket);
public void onError(int code, String msg);
}
public interface IGetAllAlbumsFromDBCallback{
public void onSuccess(List<AlbumItem> items);
public void onError(int code, String msg);
}
public interface IDelteAlbumItemCallback{
public void onSuccess();
public void onError(int code, String msg);
}
}
|
Python
|
UTF-8
| 1,640 | 2.75 | 3 |
[
"Apache-2.0"
] |
permissive
|
import lettria
import json
api_key = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhbmFseXRpY0lkIjoiNWRlOGRiMzBlYzY4YjA1MWNmZmZiZGRjIiwicHJvamVjdElkIjoiNWRlOGRiMzBlYzY4YjA1MWNmZmZiZGRkIiwic3Vic2NyaXB0aW9uSWQiOiI1ZDZkMjExNjExZGM5MDMxMGQ4ZWJhMzIiLCJpYXQiOjE2MTgzMjAyOTAsImV4cCI6MTY2NjcwNDI5MH0.emln3t9ACFTFQH3uChi-fOAvJgBDHEqekzk4PGfYaZA"
nlp = lettria.NLP(api_key, no_print=False)
commentaires = [
'Mr. George Dupont est le boulanger du village.',
"J'ai rencontré Madame Dubois en allant chez le fleuriste.",
"La directrice de l'école est Mme Brigitte Fleur.",
"Le Dr. Blorot m'a demandé si elle avait des antécédents dans ma famille car elle est malade."
]
# nlp.add_document(' '.join(commentaires))
# nlp.add_documents(commentaires)
nlp.load_result('./res_tmp.jsonl')
# nlp.documents[0].replace_coreference(attribute='source', replace=['CLS'])
import streamlit as st
from annotated_text import annotated_text
st.title('Demo coreference resolution')
text = st.text_area('Text input:', value=' '.join(commentaires), height=40)
nlp.add_document(text)
# col1, col2 = st.columns(2)
col1 = st.columns(1)
# with col1:
st.subheader('Text with spans and clusters:')
spans = nlp.documents[-1].spans
clusters = nlp.documents[-1].clusters
text = [[' ' + k.str + ' ' for k in s] for s in nlp.documents[-1].sentences]
for i, cluster in enumerate(clusters):
for s in cluster.spans:
text[s.sentence_idx][s.tokens_idx[0]:s.tokens_idx[-1] + 1] = [(' ' + t.str + ' ', str([sp.cluster_idx for sp in t.spans])) for t in s.tokens]
for sentence in text:
annotated_text(
*sentence
)
st.subheader('Clusters:')
for cl in nlp.documents[-1].clusters:
if len(cl.spans) > 1:
st.markdown(str(cl))
st.subheader("Replacing pronouns with coreference with the head of the cluster in the text:")
text = [' ' + t + ' ' for s in nlp.documents[-1].replace_coreference(attribute='source') for t in s]
annotated_text(
*text
)
|
Java
|
UTF-8
| 4,333 | 1.914063 | 2 |
[] |
no_license
|
package com.canzhang.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.canzhang.sample.base.adapter.ComponentAdapter;
import com.canzhang.sample.base.bean.ComponentItem;
import com.canzhang.sample.manager.AppStatusManager;
import com.canzhang.sample.manager.BrightnessDemoManager;
import com.canzhang.sample.manager.DebugDemoManager;
import com.canzhang.sample.manager.JniDemoManager;
import com.canzhang.sample.manager.OtherTestDemoManager;
import com.canzhang.sample.manager.qrcode.QRCodeActivity;
import com.canzhang.sample.manager.recyclerView.RecyclerViewActivity;
import com.canzhang.sample.manager.rxjava.RxJavaTestDemoManager;
import com.canzhang.sample.manager.viewpager.ViewPagerFragment;
import com.canzhang.sample.manager.viewpager.fql.FqlViewPagerFragment;
import com.canzhang.sample.manager.weex.WeexActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.base.base.BaseActivity;
import java.util.ArrayList;
import java.util.List;
/**
* 各组件应用范例
*/
//@Route(path = "/sample/sampleList")
public class ComponentListActivity extends BaseActivity {
private RecyclerView mRecyclerView;
private List<ComponentItem> mData = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_activity_component_list);
mRecyclerView = findViewById(R.id.rv_test);
initData();
initRecyclerView();
setTitle("组件应用范例");
}
/**
* 在这里添加要调试的组件数据
*/
private void initData() {
mData.add(new ComponentItem("平常测试demo", new OtherTestDemoManager()));
mData.add(new ComponentItem("app前后台检测", new AppStatusManager()));
mData.add(new ComponentItem("rxJava实际应用", new RxJavaTestDemoManager()));
mData.add(new ComponentItem("jni", new JniDemoManager()));
mData.add(new ComponentItem("调试弹窗", new DebugDemoManager()));
mData.add(new ComponentItem("调节亮度测试", new BrightnessDemoManager()));
mData.add(new ComponentItem("多type类型(非原生)", new View.OnClickListener() {
@Override
public void onClick(View v) {
start(RecyclerViewActivity.class);
}
}));
mData.add(new ComponentItem("viewPager", new View.OnClickListener() {
@Override
public void onClick(View v) {
showFragment(new ViewPagerFragment());
}
}));
mData.add(new ComponentItem("fql viewPager", new View.OnClickListener() {
@Override
public void onClick(View v) {
showFragment(new FqlViewPagerFragment());
}
}));
mData.add(new ComponentItem("二维码生成测试", new View.OnClickListener() {
@Override
public void onClick(View v) {
start(QRCodeActivity.class);
}
}));
mData.add(new ComponentItem("weex测试", new View.OnClickListener() {
@Override
public void onClick(View v) {
start(WeexActivity.class);
}
}));
}
BaseQuickAdapter<ComponentItem, BaseViewHolder> adapter;
private void initRecyclerView() {
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(adapter = new ComponentAdapter(R.layout.sample_list_item, mData));
}
private void start(Class clazz) {
startActivity(new Intent(ComponentListActivity.this, clazz));
}
private void showFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fl_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
|
Java
|
UTF-8
| 3,055 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package io.rosensteel.cochrane.crawler;
import io.rosensteel.http.WebReader;
import io.rosensteel.http.WebResult;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
public class CochraneTopics {
private WebReader webReader;
private CochraneTopicLinks topicLinks;
private HashMap<String, CochraneReviews> reviews = new HashMap<>();
public CochraneTopics(WebReader webReader, String topicListUrl) {
try {
this.webReader = webReader;
WebResult topicListPage = webReader.read(topicListUrl);
topicLinks = topicListPage.extractData(CochraneExtractors.topicLinkExtractor);
} catch (Exception e){
System.err.println("Could not read site (" + topicListUrl + ")");
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(1);
}
}
public Set<String> getAllTopicNames() {
return topicLinks.availableTopics();
}
public void crawlTopic(String topicName) {
String lookupLink = topicLinks.get(topicName) + "&resultPerPage=200";
CochraneReviews cochraneReviews = new CochraneReviews();
boolean firstRun = true;
while (!lookupLink.isEmpty()) {
WebResult topicPage = null;
try {
topicPage = webReader.read(lookupLink);
} catch (IOException e) {
System.err.println("Error - could not read site (" + lookupLink + ")");
e.printStackTrace();
System.exit(1);
}
if (firstRun) {
cochraneReviews.setExpectedReviewCount(topicPage.extractData(CochraneExtractors.expectedReviewCountExtractor));
firstRun = false;
}
cochraneReviews.addReviews(topicPage);
lookupLink = cochraneReviews.getNextPageLink(topicPage);
System.out.println("(" + topicName + ") " + "Progress:" + cochraneReviews.reviewCount() + "/" + cochraneReviews.getExpectedReviewCount());
}
System.out.println("(" + topicName + ") " + "Finished:" + cochraneReviews.reviewCount() + "/" + cochraneReviews.getExpectedReviewCount());
if (!cochraneReviews.gotExpectedNumberOfReviews()) {
System.err.println("(" + topicName + ") " + "Error - did not get expected number of reviews");
System.exit(1);
}
reviews.put(topicName, cochraneReviews);
}
public CochraneReviews getReviewsForTopic(String topicName) {
if(reviews.containsKey(topicName)) {
System.out.println("Read from cache: " + topicName);
} else {
System.out.println("Getting reviews for topic: " + topicName);
crawlTopic(topicName);
}
return reviews.get(topicName);
}
public CochraneReviews getCrawledReviews() {
CochraneReviews allReviews = new CochraneReviews();
reviews.forEach((topic, reviews) -> allReviews.addReviews(reviews));
return allReviews;
}
}
|
TypeScript
|
UTF-8
| 1,782 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { error } from 'console';
import { UpdateMerchantDTO } from '../DTO/updateMerchantDTO';
import { Merchant } from '../model/merchant.model';
@Injectable()
export class MerchantService {
constructor(
@InjectModel(Merchant)
private merchantModel: typeof Merchant,
) {}
async findAll(): Promise<Merchant[]> {
return this.merchantModel.findAll();
}
findOne(id: number): Promise<Merchant> {
return this.merchantModel.findOne({ where: { id } });
}
async removeById(id: number): Promise<string> {
const merchantToBeRemove = await this.findOne(id);
await merchantToBeRemove.destroy();
return `Delete No.${id} Merchant Successfully!!!`;
}
async add(merchant: Merchant): Promise<string> {
// const merchantModels = await this.merchantModel.findAll();
// const merchants = merchantModels.map((merchant) => {
// return merchant.name;
// });
// if (merchants.includes(merchant.name)) {
// throw new ConflictException({
// status: HttpStatus.CONFLICT,
// error: `This Merchant: ${merchant.name} is Already Exist!!!`,
// });
// }
return this.merchantModel
.create(merchant)
.then(() => `Add a New Merchant: ${merchant.name} Successfully!!!`)
.catch((error) => console.error(error))
.catch((error) => error);
}
async updateById(
id: number,
targetMerchant: UpdateMerchantDTO,
): Promise<string> {
this.merchantModel.update(
{
name: targetMerchant.name,
address: targetMerchant.address,
phone: targetMerchant.phone,
},
{ where: { id } },
);
return `Update No.${id} Merchant Successfully!`;
}
}
|
C++
|
UTF-8
| 24,705 | 2.515625 | 3 |
[] |
no_license
|
/*
The purpose of this code is to enable the use of the MicroView Arduino to be used as a replacement board for the
2011 Dye Proto Matrix Rail (PMR). The current board is out of production and many of the predetermined settings
are outdated. This code can also be applied in the future to other models of paintball markers as the IO and
settings are universally very similar. Just the electronics and ergonomics would be different.
Developer: Matthew Rodriguez - salsarodriguez@outlook.com
Last update: Aug 28, 2019
ToDo:
- <WRITTEN - 8/23/19 | TESTED - ????> ABS implemented
- <WRITTEN - 8/21/19 | TESTED - ????> Configuration routine (with scrolling option)
- <WRITTEN - 8/23/19 | TESTED - ????> eye power pin on and off
- <WRITTEN - 8/28/19 | TESTED - ????> add ramping as firing mode
- eye error when state doesn't change after firing <?> symbol
- optimaze ROF and dwell to include code timing?
- safety lock feature which turns off on 3 trigger pulls?
- switch from polling to interrupts?
- first shot safety option on semi-auto. bascially doesn't auto on first shot but waits for second trigger pull within certain time
- low battery indicator (need to figure out at waht voltage the gun won't fire)
- bitmaps for battery, eye state, firing mode
- game modes (fastest ROF with disabled firing with a gauge that calculates the ROF and holds the highest value to see who can fire the fastest)
*/
#include <MicroView.h> // for use with the MicroView arduino package
#include <EEPROM.h> // to be able to save variables when power is cycled
#include <Timer.h> // timer for RoF measurment
const int ver = 004; // version number for EEPROM control
// Pin configuration
const int solenoidPin = 1; // the number of the solenoid pin
const int triggerPin = 0; // the number of the trigger pin
const int ledPin = A0; // the number of the LED pin (may not be used)
const int buttonUpPin = 3; // the number of the up botton pin
const int buttonDownPin = 2; // the number of the down button pin
const int eyePin = A1; // the number of the eye pin
const int eyePowerPin = A2; // turn eyes on or off to conserve battery
const int batteryLevel = A3; // the number of the battery voltage pin to determine battery level
// EEPROM and other variables
int triggerState = 1; // variable for reading the pushbutton status
int ROF; // variable for the rate of fire of the marker x10 - EEPROM Address 0
int dwell; // ms for solenoid to stay open - EEPROM Address 1
//int recharge; // this would be the amount of time to wait after dwell for the full firing cycle (dwell+recharge) before marker can fire again and would replace the calculation for ROF (1000ms/ROF - dwell = recharge)
int rampROF; // ROF for ramp mode (wanted to seperate from auto ROF not to kill fun of full auto)
int rampTriggerBPS; // ROF at which is switches from semi to auto
int triggerSensitivity; // ms delay before trigger is considered active (debounce basically)
int ABS; // 0 = OFF, 1 = ON - Anti Bolt Stick enables higher dwell for first shot
int ABStime = 10; // additional time to add to dwell if ABS is enabled
int eyeState = 0; // 0 = Eye empty, 1 = Ball in Eye, 2 = Error - variables for reading the state of the eye
int eyesOnOff; // 0 = Eyes Off, 1 = Eyes On
int firingMode; // 0 = Semi, 1 = Burst, 2 = Auto, 3 = Ramp
int upButtonState = 1; // variable for reading the pushbutton status
int downButtonState = 1; // variable for reading the pushbutton status
int solenoidReset = 0; // variable to marking whether the gun has just been fired and is reset on trigger release
int shotsSincePower = 0; // ball counter
int rampCount = 0; // number of shots fired within ramp ROF trigger time
int bat = 9; // battery voltage level
//int shotsSinceLastMaintenance; // maintenance tracker which stores shots in EEPROM and can be reset (concern is EEPROM read/write limit)
unsigned long timerStart = 0; // the time the delay started
unsigned long buttonHoldTimer = 0; // the time both buttons were pressed
unsigned long gameTimer = 0; // variable for game timer on first shot after resetting ball count
unsigned long screenResetTimer = 0; // timer for resetting the screen after no input for a set time
unsigned long rampTimer = 0; // timer to ramp mode
MicroViewWidget *sliderWidget, *sliderWidgetMenu; // creates widget for slider for configuration routine
void setup() {
// Set pin modes
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output
pinMode(triggerPin, INPUT_PULLUP); // initialize the trigger pin as an input
pinMode(buttonUpPin, INPUT_PULLUP); // initialize the pushbutton pin as an input
pinMode(buttonDownPin, INPUT_PULLUP); // initialize the pushbutton pin as an input
pinMode(solenoidPin, OUTPUT); // initialize the solenoid pin as an output
pinMode(eyePin, INPUT); // initialize the eye pin as an input
pinMode(eyePowerPin, OUTPUT); // initialize the eye LED as an output
// Set splash display on screen
uView.begin(); // start MicroView
uView.clear(PAGE); // clear page
uView.print("2011 PMR\n"); // display string
uView.print("Salsa\n");
uView.print("08/28/2019");
// first time configuration on startup
if(EEPROM.read(8) != ver){
uView.print("EEPROM P");
EEPROM.write(0, 100); // ROF
EEPROM.write(1, 30); // dwell
EEPROM.write(2, 100); // ramp ROF
EEPROM.write(3, 50); // ramp BPS trigger requirement to enter ramp (5bps)
EEPROM.write(4, 5); // trigger sensitivity
EEPROM.write(5, 0); // ABS (anti-bolt stick) - OFF
EEPROM.write(6, 1); // eyes on or off - ON
EEPROM.write(7, 0); // firing mode - Semi
EEPROM.write(8, ver); // value marking that the EEPROM is now configured with the default settings (value needs to be <255)
}
else{
uView.print("EEPROM OK");
}
// Read and populate variables from EEPROM
ROF = EEPROM.read(0);
dwell = EEPROM.read(1);
rampROF = EEPROM.read(2);
rampTriggerBPS = EEPROM.read(3);
triggerSensitivity = EEPROM.read(4);
ABS = EEPROM.read(5);
eyesOnOff = EEPROM.read(6);
firingMode = EEPROM.read(7);
//Section to electronically turn eyes off if moved to ouput pin instead of just ignoring them? saves battery
if(eyesOnOff == 0){
digitalWrite(eyePowerPin, LOW);
}
else{
digitalWrite(eyePowerPin, HIGH);
}
uView.display(); // prints what is in the cache to the display
delay(3000); // allows splash screen to be visible
mainDisplayUpdate(); //updates display to home screen
}
void loop() {
// read the state of the pushbutton values
triggerState = digitalRead(triggerPin);
upButtonState = digitalRead(buttonUpPin);
downButtonState = digitalRead(buttonDownPin);
// if the up and down buttons are held down for 3 seconds then enter configuration mode
if (upButtonState == 0 && downButtonState == 0){
if(buttonHoldTimer == 0){
buttonHoldTimer = millis();
}
else if(millis() - buttonHoldTimer >= 3000){
configuration();
buttonHoldTimer = 0;
mainDisplayUpdate();
}
}
// reset ball counter if down button and trigger are held at same time for 2 seconds
else if (downButtonState == 0 && triggerState == 0){
if(buttonHoldTimer == 0){
buttonHoldTimer = millis();
}
else if(millis() - buttonHoldTimer >= 2000){
shotsSincePower = 0;
gameTimer = 0;
buttonHoldTimer = 0;
mainDisplayUpdate();
while(digitalRead(triggerPin)==LOW){
delay(100);
}
}
}
// check if the trigger is pulled
else if (triggerState == LOW) {
// SEMI-AUTOMATIC
if (firingMode == 0 && solenoidReset == 0){ // if in semi-auto and the trigger has been released once
fire();
}
// BURST MODE
else if(firingMode == 1 && solenoidReset == 0){ // burst mode (maybe make burst mode not accessible while eyes are disabled?)
for(int i = 0; i < 3; i++){ // 3 shots
fire();
delay(100);
while(eyeStatus() == 0 && (millis()-timerStart) < 2000){ // times out after 2 seconds if ball isn't detected in eye (needed to maintain 3 shot burst if eyes are delayed)
}
}
}
// AUTOMATIC
else if(firingMode == 2){ // full auto mode
if((millis() - timerStart) >= (1000/(ROF/10))){ //ensure that BPS does not exceed ROF
fire();
}
}
// RAMP (speeds up into automatic fire after 3 pulls at a set ROF)
else if(firingMode == 3 && solenoidReset==0){ // ramp mode
if(rampCount == 0){ // if first new shot after ramp count expired then set the timer, increase count, and fire
rampTimer = millis();
rampCount++;
fire();
}
else if(rampCount < 3 && (millis()-rampTimer) < (1000/ (rampTriggerBPS/10) ) ){ // if count is less than 3 required to switch into full auto and the ROF is higher than required trigger then increase count, set time, and fire (semi-mode)
rampCount++;
rampTimer = millis();
if(solenoidReset = 0){
fire();
}
}
// perhaps need to move this section into else or outside of if sctructure and just set a flag
else if(rampCount == 3 && (millis()-rampTimer) < (1000/ (rampTriggerBPS/10) ) ){ // if trigger pulled 3 times at higher ROF than required then switch into full auro and ensure that BPS does not exceed ROF
if( (millis() - timerStart) >= ( 1000/(rampROF/10) ) ){
fire();
}
rampTimer = millis();
}
if((millis()-rampTimer) > (1000/ (rampTriggerBPS/10) )){ // if ROF is not within required BPS then reset the ramp count
rampCount = 0;
}
}
mainDisplayUpdate();
}
// If nothing, then just reset solenoid pin to let semi-auto know it is ok to fire on next trigger pull
else {
digitalWrite(solenoidPin, LOW); // turn solenoid off (not necessary but just insurance)
solenoidReset = 0; // mark that trigger has been let go for semi-auto mode
buttonHoldTimer = 0;
if(screenResetTimer == 0){ // resets the display if no action is taken in 0.5s
screenResetTimer = millis();
}
else if(millis() - screenResetTimer >= 500){
screenResetTimer = 0;
mainDisplayUpdate();
}
/*
If in ramp mode we need to set a flag and keep firing at the ROF for ramp
*/
// redundant section here needed outside of trigger pull to keep it firing until triggerBPS is not maintained
if(firingMode == 3){
if(rampCount == 3 && (millis()-rampTimer) < (1000/ (rampTriggerBPS/10) ) ){ // if trigger pulled 3 times at higher ROF than required then switch into full auro and ensure that BPS does not exceed ROF
if( (millis() - timerStart) >= ( 1000/(rampROF/10) ) ){
fire();
}
rampTimer = millis();
}
if((millis()-rampTimer) > (1000/ (rampTriggerBPS/10) )){ // if ROF is not within required BPS then reset the ramp count
rampCount = 0;
}
}
}
}
// Triggers the solenoid to fire the marker
void fire(){
if(eyeStatus() == 1){ // check if ball is detected by the eyes
int dwellTotal = dwell;
if(ABS == 1 && (millis()-timerStart) > 15000){ // apply ABS if gun hasn't fired in 15s
dwellTotal = dwell + ABStime;
}
digitalWrite(solenoidPin, HIGH); // turn on solenoid allowing air into spool
delay(dwellTotal); // keep solenoid open for dwell time period
digitalWrite(solenoidPin, LOW); // turn off solenoid
timerStart = millis(); // mark when trigger was pulled for ROF timing in auto mode
solenoidReset = 1; // note that gun has been fired for semi-auto mode
shotsSincePower++; // increment shots fired
if(gameTimer==0){ // sets game timer on first shot after shot count reset
gameTimer = millis();
}
}
}
// What is going on with the eyes? Is there a ball there or not? Returns 0 if empty, 1 if ball detected, and 2 if in error (future implementation)
int eyeStatus(){
int eyeState = digitalRead(eyePin); // checks if beam is broken or not - HIGH = ball in eye, LOW = no ball???
if(eyesOnOff == 0){ // if the eyes are set to off, return a 1
eyeState = 1;
}
return eyeState;
}
// Run to do a configuration of all of the parameters
void configuration(){
//Menu first time setup
int menuPosition = 5;
configureScreenReset(menuPosition);
menuPosition = 6; // first entry triggers down button, may move button detect delay before code
while(1){
triggerState = digitalRead(triggerPin);
upButtonState = digitalRead(buttonUpPin);
downButtonState = digitalRead(buttonDownPin);
if(downButtonState == 0){ // Check if down button pressed
if(menuPosition > 0){
menuPosition--; // Move menu cursor up (it's inverted on the screen. the higher the number the lower the position)
sliderWidgetMenu->setValue(menuPosition);
uView.display();
while(digitalRead(buttonUpPin)==LOW){ // wait for button to be unpressed
delay(100);
}
}
}
else if(upButtonState == 0){ // Check if up button is pressed
if(menuPosition < 5){
menuPosition++; // Move menu cursor down (it's inverted on the screen. the higher the number the lower the position)
sliderWidgetMenu->setValue(menuPosition);
uView.display();
while(digitalRead(buttonDownPin)==LOW){ // wait for button to be unpressed
delay(100);
}
}
}
else if(triggerState == 0){ // Check if trigger is pulled
while(digitalRead(triggerPin)==LOW){ // Wait for trigger to be unpulled
delay(100);
}
delete sliderWidgetMenu;
// Configure firing modes
if(menuPosition == 5){
firingMode = configureFiringMode(firingMode); // configure firing mode
EEPROM.update(7, firingMode); // write firing mode value to address 7
if(firingMode == 2){ // configure AUTO mode
ROF = configureNumericParameter("RoF (bps)", ROF, 90, 152, 1); // configured auto ROF
EEPROM.update(0, ROF); // write ROF value to address 0
}
else if(firingMode == 3){ // configure RAMP mode
rampTriggerBPS = configureNumericParameter("Ramp Trig", rampTriggerBPS, 50, 150, 1);
EEPROM.update(3, rampTriggerBPS); // write ramp bps trigger value to address 3
rampROF = configureNumericParameter("Ramp ROF", rampROF, 90, 152, 1);
EEPROM.update(2, rampROF); // write ramp speed value to address 2
}
}
// Configure Eyes
else if(menuPosition == 4){
eyesOnOff = configureBinaryParameter("Eyes", eyesOnOff); // configure eyes setting
EEPROM.update(6, eyesOnOff); // write eye mode value to address 6
}
// Configure Dwell
else if(menuPosition == 3){
dwell = configureNumericParameter("Dwell(ms)", dwell, 8, 34, 1); // configure dwell setting
EEPROM.update(1, dwell); // write dwell value to address 1
}
// Configure ABS
else if(menuPosition == 2){
ABS = configureBinaryParameter("ABS", ABS); // configure ABS setting
EEPROM.update(5, ABS); // write anti bolt stick mode value to address 5
}
// Configure Trigger Sensitivity
else if(menuPosition == 1){
triggerSensitivity = configureNumericParameter("Trigger", triggerSensitivity, 0, 500, 10); // configure trigger sensitivity setting
EEPROM.update(4, triggerSensitivity); // write trigger sensitivity value to address 4
}
// Exit Menu and return to home screen
else if(menuPosition == 0){
mainDisplayUpdate();
return;
}
configureScreenReset(menuPosition);
}
delay(150); // menu scroll responsiveness
}
buttonHoldTimer = 0; //why is this here? shouldn't be able to be reached
}
//Resets the main configuration screen after a parameter has been configured
void configureScreenReset(int menuPos){
uView.clear(PAGE);
uView.setCursor(10,0);
uView.print("Mode");
uView.setCursor(10,8);
uView.print("EyeState");
uView.setCursor(10,16);
uView.print("Dwell");
uView.setCursor(10,24);
uView.print("ABS");
uView.setCursor(10,32);
uView.print("Sensitiv");
uView.setCursor(10,40);
uView.print("EXIT");
sliderWidgetMenu = new MicroViewSlider(0, 3, 0, 5, WIDGETSTYLE3 + WIDGETNOVALUE); // 6 list slider for menu
sliderWidgetMenu->setValue(menuPos);
uView.display();
return;
}
// configures the firing mode
int configureFiringMode(int currentValue){
uView.clear(PAGE); // clear page
uView.setCursor(0,0);
uView.print("Configure:\n");
uView.print("Fire Mode");
uView.print("\nCurrently:\n");
if(currentValue == 0){
uView.print("Semi");
}
else if(currentValue == 1){
uView.print("Burst");
}
else if(currentValue == 2){
uView.print("Auto");
}
else if(currentValue == 3){
uView.print("Ramp");
}
uView.display();
while(1){
triggerState = digitalRead(triggerPin);
upButtonState = digitalRead(buttonUpPin);
downButtonState = digitalRead(buttonDownPin);
if(upButtonState == 0 || downButtonState == 0){
//change state of current value
if(upButtonState == 0 && currentValue < 3){
currentValue++;
}
else if(downButtonState == 0 && currentValue > 0){
currentValue--;
}
uView.clear(PAGE); // clear page
uView.setCursor(0,0);
uView.print("Configure:\n");
uView.print("Fire Mode");
uView.print("\nCurrently:\n");
if(currentValue == 0){
uView.print("Semi");
}
else if(currentValue == 1){
uView.print("Burst");
}
else if(currentValue == 2){
uView.print("Auto");
}
else if(currentValue == 3){
uView.print("Ramp");
}
uView.display();
while(digitalRead(buttonUpPin)==LOW || digitalRead(buttonDownPin)==LOW){
delay(100);
}
}
else if(triggerState == 0){
while(digitalRead(triggerPin)==LOW){
delay(100);
}
return currentValue;
}
}
}
// configures any binary parameter such as on/off
int configureBinaryParameter(String parameterStr, int currentValue){
uView.clear(PAGE); // clear page
uView.setCursor(0,0);
uView.print("Configure:\n");
uView.print(parameterStr);
uView.print("\nCurrently:\n");
if(currentValue == 0){
uView.print("OFF");
}
else if(currentValue == 1){
uView.print("ON");
}
uView.display();
while(1){
triggerState = digitalRead(triggerPin);
upButtonState = digitalRead(buttonUpPin);
downButtonState = digitalRead(buttonDownPin);
if(upButtonState == 0 || downButtonState == 0){
//change state of current value
if(currentValue == 0){
currentValue = 1;
}
else if(currentValue == 1){
currentValue = 0;
}
uView.clear(PAGE); // clear page
uView.setCursor(0,0);
uView.print("Configure:\n");
uView.print(parameterStr);
uView.print("\nCurrently:\n");
if(currentValue == 0){
uView.print("OFF");
}
else if(currentValue == 1){
uView.print("ON");
}
uView.display();
while(digitalRead(buttonUpPin)==LOW || digitalRead(buttonDownPin)==LOW){
delay(100);
}
}
else if(triggerState == 0){
while(digitalRead(triggerPin)==LOW){
delay(100);
}
return currentValue;
}
}
}
// call to update a numeric parameter
int configureNumericParameter(String parameterStr, int currentValue, int min, int max, int increment){
uView.clear(PAGE); // clear page
uView.setCursor(0,0);
uView.print("Configure:"); // display string
uView.print(parameterStr);
uView.print("\nCurrently:");
uView.print(currentValue);
sliderWidget = new MicroViewSlider(0,30,min,max, WIDGETSTYLE1);// draw Slider widget at x=0,y=20,min=9.8, max=15.2
sliderWidget->setValue(currentValue);
uView.display();
while(digitalRead(triggerPin) == HIGH){
if(digitalRead(buttonUpPin) == LOW && currentValue < max){
currentValue = currentValue + increment;
sliderWidget->setValue(currentValue);
uView.display();
}
else if(digitalRead(buttonDownPin) == LOW && currentValue > min){
currentValue = currentValue - increment;
sliderWidget->setValue(currentValue);
uView.display();
}
delay(250);
}
while(digitalRead(triggerPin)==LOW){ // wait for trigger to be released
delay(100);
}
delete sliderWidget;
return currentValue; // returns value to write to EEPROM
}
//Updates the main display with current values
void mainDisplayUpdate(){
uView.clear(PAGE); // clear page
uView.setCursor(0,0); // set cursor to 0,0
//uView.print("2011 PMR\n"); // display string
// Firing Mode
uView.print("Mode:");
if(firingMode == 0){
uView.print(" Semi");
}
else if(firingMode == 1){
uView.print("Burst");
}
else if(firingMode == 2){
uView.print("Auto-");
uView.print(String(ROF/10));
uView.print(" bps");
}
else if(firingMode == 3){
uView.print("Ramp-");
uView.print(String(rampTriggerBPS/10));
uView.print("/");
uView.print(String(rampROF/10));
}
//Battery Level
bat = analogRead(batteryLevel);
float battery = 2*bat*5/1024;
uView.print("Bat: ");
uView.print(String(bat));
if(battery / int(battery) > 0){
uView.print(".");
uView.print(String(10*(battery-int(battery))));
}
uView.print("V");
// Status of Eyes
uView.print("\n(");
if(eyesOnOff == 0){
uView.print("X");
}
else if(eyeStatus()==1){
uView.print("0");
}
else{
uView.print("_");
}
uView.print(")");
// Ball count
uView.print("\nShot: ");
uView.print(String(shotsSincePower));
// Game timer
uView.print("\nTime: ");
int timer = (millis()-gameTimer)/1000;
int minutes = timer / 60;
int seconds = timer % 60;
uView.print(String(minutes));
uView.print(":");
if(seconds < 10){
uView.print("0");
uView.print(String(seconds));
}
else{
uView.print(String(seconds));
}
uView.display(); // prints what is in the cache to the display
}
|
Java
|
UTF-8
| 1,480 | 2.078125 | 2 |
[] |
no_license
|
package com.yj.domain.user.service;
import com.yj.domain.user.model.RolePermission;
import com.yj.domain.user.model.RolePermissionDto;
import com.yj.domain.user.model.UserDetail;
import com.yj.domain.user.repository.RolePermissionRepository;
import com.yj.pojo.ReSult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RolePermissionServiceImpl implements RolePermissionService {
@Autowired
RolePermissionRepository rolePermissionRepository;
@Override
public ReSult addRolePermission(RolePermissionDto dto, UserDetail user) {
List<RolePermission> list= rolePermissionRepository.findByRoleIdAndClient(dto.getRoleId(),user.getClient());
if(list!=null && dto.getPermissions()!=null&&dto.getPermissions().size()>0){
rolePermissionRepository.deleteAll(list);
}
dto.getPermissions().stream().forEach(item->{
RolePermission rp = new RolePermission();
rp.setPermissionId(item);
rp.setRoleId(dto.getRoleId());
rp.setClient(user.getClient());
rolePermissionRepository.save(rp);
});
return ReSult.success();
}
@Override
public ReSult selectRolePermission(Long id, UserDetail user) {
List<RolePermission> list= rolePermissionRepository.findByRoleIdAndClient(id,user.getClient());
return ReSult.success(list);
}
}
|
SQL
|
UTF-8
| 1,448 | 4.28125 | 4 |
[
"Apache-2.0"
] |
permissive
|
#standardSQL
CREATE TEMPORARY FUNCTION getImportantProperties(css STRING)
RETURNS ARRAY<STRUCT<property STRING, freq INT64>>
LANGUAGE js
OPTIONS (library = "gs://httparchive/lib/css-utils.js")
AS '''
try {
var ast = JSON.parse(css);
let ret = {
total: 0,
important: 0,
properties: {}
};
walkDeclarations(ast, ({property, important}) => {
ret.total++;
if (important) {
ret.important++;
incrementByKey(ret.properties, property);
}
});
ret.properties = sortObject(ret.properties);
return Object.entries(ret.properties).map(([property, freq]) => {
return {property, freq};
});
} catch (e) {
return [];
}
''';
WITH totals AS (
SELECT
_TABLE_SUFFIX AS client,
COUNT(0) AS total_pages
FROM
`httparchive.summary_pages.2022_07_01_*` -- noqa: L062
GROUP BY
client
)
SELECT
client,
property,
COUNT(DISTINCT page) AS pages,
ANY_VALUE(total_pages) AS total_pages,
COUNT(DISTINCT page) / ANY_VALUE(total_pages) AS pct_pages,
SUM(freq) AS freq,
SUM(SUM(freq)) OVER (PARTITION BY client) AS total,
SUM(freq) / SUM(SUM(freq)) OVER (PARTITION BY client) AS pct
FROM (
SELECT
client,
page,
important.property,
important.freq
FROM
`httparchive.almanac.parsed_css`,
UNNEST(getImportantProperties(css)) AS important
WHERE
date = '2022-07-01')
JOIN
totals
USING
(client)
GROUP BY
client,
property
ORDER BY
pct DESC
LIMIT 500
|
Ruby
|
UTF-8
| 1,591 | 2.875 | 3 |
[] |
no_license
|
class Gear < ActiveRecord::Base
has_many :gearactivities
has_many :activities, through: :gearactivities
def self.essentials
essentials = self.select do |gear|
gear.essential == true
end
essentials.pluck(:name).map do |name|
puts name
end
end
def self.add(name:, weight:, quantity:, essential:)
found_gear = find_by_name(name)
quantity = quantity.to_i
if found_gear == nil
item = Gear.new(name: name, weight: weight, quantity_owned: quantity, essential: essential)
item.save
item
else
found_gear.quantity_owned += quantity
found_gear
end
end
def self.delete(name:, quantity:)
found_gear = find_by_name(name)
quantity = quantity.to_i
if found_gear == nil
puts "Item not found"
else
found_gear.quantity_owned -= quantity
name = found_gear.name
if found_gear.quantity_owned == 0
gear_activities = found_gear.find_gearactivities
gear_activities.map {|gear_activity| gear_activity.destroy}
found_gear.destroy
puts "#{name} Deleted"
else
puts "#{name} quantity updated to #{found_gear.quantity_owned}"
end
end
end
def self.find_by_name(name)
find_by(name: name)
end
def find_gearactivities
Gearactivity.select do |gearactivity|
self.id == gearactivity.gear_id
end
end
end
|
Java
|
UTF-8
| 546 | 3.546875 | 4 |
[] |
no_license
|
package com.arun.java8.module1;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class StrategyInjectionFour {
public static int totalValues(List<Integer> values, Predicate<Integer> strategy)
{
return values.stream()
.filter(strategy)
.reduce(0, Math::addExact);
}
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
System.out.println(totalValues(values, x-> true));
System.out.println(totalValues(values, x-> x%2 == 0));
}
}
|
Markdown
|
UTF-8
| 1,071 | 2.5625 | 3 |
[] |
no_license
|
---
author:
name: RachelR
body: "Hi all\r\n\r\nQuick question - Are there any problems associated with using
underscores in the name of font families? Are there any charcaters that shouldn't
be used in the name of fonts?\r\n\r\nEg.\r\n\r\nMy_Font "
comments:
- author:
name: Ramiro Espinoza
picture: 110426
body: Non ascii characters cause problems when running scripts, for example, when
generating UFO. Cheers.
created: '2008-12-18 08:44:18'
- author:
name: RachelR
body: Sorry I should explained I'm generating Opentype fonts with this naming.
created: '2008-12-18 09:07:20'
- author:
name: twardoch
picture: 110427
body: "http://www.typophile.com/node/51100\r\n\r\nAlso, underscores in font names
look ugly and to some users, confusing. Some users may not notice them and assume
that they are spaces or something of that kind. \r\n\r\nJust use spaces and plain
English letters, nothing else. \r\n\r\nA."
created: '2008-12-18 11:36:53'
date: '2008-12-18 08:30:07'
node_type: forum
title: Underscores '_' in Font Names
---
|
C++
|
GB18030
| 1,669 | 3.875 | 4 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//ҵķʱռڴѾѣDz
bool isPalindrome(string s)
{
int lenStr = s.size();
if (lenStr == 0)
return true;
char tmp;
int j = lenStr - 1;
for (int i = 0; i < lenStr;++i)
{
if (isalpha(s[i]) || isdigit(s[i]))
{
tmp = s[i];
while (j > 0)
{
if ((isalpha(s[j]) && tolower(s[j]) != s[i] && toupper(s[j]) != s[i])
|| (isdigit(s[j]) && s[j]!=s[i]))
return false;
else if (!isalpha(s[j]) && !isdigit(s[j]))
--j;
else
{
--j;
break;
}
}
}
if (i >= j)
return true;
}
return false;
}
/*
ѷ
I think this problem, if asked at an interview, is to test whether a candidate
is able to handle all edge cases systematically and write clean codes :-)
To avoid using if-else to handle lowercase and uppercase letters, I call tolower to
convert all of them to lower case ones before comparison. And tolower will not change a number.
bool isPalindrome(string s)
{
int n = s.size(), l = 0, r = n - 1;
while (l < r)
{
while (l < r && !isalnum(s[l]))
{
l++;
}
while (l < r && !isalnum(s[r]))
{
r--;
}
if (tolower(s[l++]) != tolower(s[r--]))
{
return false;
}
}
return true;
}
*/
int main()
{
//cout << isPalindrome(string("1b1")) << endl;
string myStr = "A man, a plan, a canal: Panama";
cout << isPalindrome(myStr) << endl;
//cout << isPalindrome(string("asdfdsb")) << endl;
//cout << isPalindrome(string("0P")) << endl;
return 0;
}
|
Markdown
|
UTF-8
| 2,584 | 3 | 3 |
[] |
no_license
|
# Google-Calendar-Tool
Lo scopo di questo di tool è quello di permette ad un utente di visualizzare, con la possibilità di stampare in formato pdf, l'elenco dei propri calendari presenti sulla piattaforma Google Calendar e del monte ore degli stessi.
Il tool è stato realizzato utilizzando le API di Google Calendar, reperibili al link: https://developers.google.com/calendar/v3/reference,
Si è reso necessario, al fine di poterle utilizzare, creare delle credenziali nella sezione "developer" offerta da Google Calendar.
# Requisiti
- *Python 2.4 o versioni successive (per fornire un server Web)*
- *Account Google con Google Calendar abilitato*
- *Account Google sviluppatore*
# Funzionamento
- *Al primo avvio del tool viene richiesta l'autenticazione al proprio account google;
cliccare il pulsante "Login", il quale aprirà una finestra pop-up per le opportune operazioni, ed infine autorizzare l'applicazione.
Effettuata l'autenticazione, l'utente può visualizzare tutti i calendari ad esso associato tramite apposito pulsante.
Selezionandone uno dall'elenco, viene visualizzata la lista degli eventi su esso registrati, la data di svolgimento e la durata degli stessi.
L'utente può, inoltre, inserire nuovi calendari e nuovi eventi.
Infine, cliccando il pulsante "stampa", all'utente viene chiesto di selezionare il mese e il calendario di cui effettuare la rendicontazione, eventualmente salvandola in formato pdf.*
- *Il tool nasce dall'esigenza di effettuare la rendicontazione delle ore per progetto.
A tal proposito, utilizzando Google Calendar, l'utente inserisce il proprio progetto come "calendario", a cui può attribuire un nome, e le ore svolte come "eventi", con un orario di inizio ed uno di fine.
Utilizzando il tool, potrà effettuare queste operazione su un'unica piattaforma e,in seguito, effettuare la rendicontazione.*
# Installazione
- Clonare la repository o scaricare la repository.
- Creare un nuovo progetto Cloud Platform e abilitare automaticamente l'API di Google Calendar; successivamente creare una chiave API nello stesso progetto e prendere nota del "client ID" e della chiave generati. I dati creati andranno poi inseriti nel file "script.js".
- Avviare un qualsiasi server web.
- Per testare il tool è stato utilizzato il python SimpleHTTPServer:
Eseguire "python -m SimpleHTTPServer 8000" (Python 2.x) oppure "python -m http.server 8000" (Python 3.x).
- Il tool è stato testato utilizzando Google Chrome.
# Author:
- Sabrina Beninati
- Email: sabry.beninati@gmail.com
- LinkedIn: https://www.linkedin.com/in/sabrina-beninati-26108618b
|
C++
|
UTF-8
| 2,043 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
//----------------------------------*-C++-*-----------------------------------//
/**
* @file PPMPlotter.cc
* @brief PPMPlotter member definitions
* @note Copyright (C) Jeremy Roberts 2013
*/
//----------------------------------------------------------------------------//
#include "ioutils/PPMPlotter.hh"
#include "utilities/MathUtilities.hh"
#include "utilities/Random.hh"
#include <fstream>
#include <cstdio>
namespace detran_ioutils
{
//----------------------------------------------------------------------------//
PPMPlotter::PPMPlotter()
: d_nx(0)
, d_ny(0)
, d_scheme(ColorMap::DEFAULT)
{
/* ... */
}
//----------------------------------------------------------------------------//
void PPMPlotter::
initialize(const size_t nx,
const size_t ny,
const std::string &name,
const size_t scheme)
{
Require(nx > 0);
Require(ny > 0);
Require(name.length() > 0);
Require(scheme < ColorMap::END_COLOR_MAPS);
d_nx = nx;
d_ny = ny;
d_name = name;
d_image.resize(nx * ny, -1.0);
d_scheme = scheme;
}
//----------------------------------------------------------------------------//
void PPMPlotter::set_pixel(const size_t i, const size_t j, const double v)
{
d_image[i + j * d_nx] = v;
}
//----------------------------------------------------------------------------//
bool PPMPlotter::write()
{
// open the file
std::ofstream file;
file.open(d_name.c_str(), std::ios::binary);
// write the header
file << "P6\n" << d_nx << " " << d_ny << "\n" << 255 << "\n";
// get the colors
ColorMap::vec_rgb colors = ColorMap::color(d_scheme, d_image);
// write each pixel
for (size_t i = 0; i < d_nx * d_ny; ++i)
{
file << colors[i].r << colors[i].g << colors[i].b;
}
file.close();
return true;
}
} // end namespace detran_ioutils
//----------------------------------------------------------------------------//
// end of file PPMPlotter.cc
//----------------------------------------------------------------------------//
|
Python
|
UTF-8
| 9,453 | 2.53125 | 3 |
[] |
no_license
|
import os
import cv2 as cv
import cv2
import numpy as np
import logging
import csv
import operator
import parameter
def get_images(path):
""" Returns a list of filenames for
all images in a directory. """
image_filenames = []
for f in os.listdir(path):
if f.endswith('bmp') or f.endswith('jpg') or f.endswith('png'):
image_filenames.append(os.path.join(path,f))
return image_filenames
def show_images(images):
""" Shows all images in a window"""
if images == None:
logging.error('Cannot Show Images (No image saved). Image-Type: %s (tools.py)' % str(type(images).__name__))
elif type(images).__name__=='list':
for i in range(len(images)):
print type(images[i])
if type(images[i]).__name__=='ndarray':
tmpimage = []
tmpimage[i] = array2cv(images[i])
cv.ShowImage("Image", tmpimage[i])
if cv.WaitKey() == 27:
cv.DestroyWindow("Image")
else:
cv.ShowImage("Image", images[i])
if cv.WaitKey() == 27:
cv.DestroyWindow("Image")
elif type(images).__name__=='cvmat':
cv.ShowImage("Image", images)
if cv.WaitKey() == 27:
cv.DestroyWindow("Image")
elif type(images).__name__=='iplimage':
cv.ShowImage("Image", images)
if cv.WaitKey() == 27:
cv.DestroyWindow("Image")
elif type(images).__name__=='ndarray':
images = array2cv(images)
cv.ShowImage("Image", images)
if cv.WaitKey() == 27:
cv.DestroyWindow("test")
elif type(images).__name__=='str':
logging.error('TypeError: Cannot Show Images (No image saved?). Image-Type: %s (tools.py)' % str(type(images).__name__))
else:
logging.error('TypeError: Cannot Show Images. Image-Type: %s (tools.py)' % str(type(images).__name__))
def show_keypoints(data):
""" paint and show images with keypoints"""
for i in range(len(data)):
try:
if data[i].facedata:
for j in range(len(data[i].facedata)):
nbr_keypoints = len(data[i].facedata[j].keypoints)
print('%d Features found in file %s' %(nbr_keypoints, data[i].filename))
tmpImage = cv.CloneMat(data[i].facedata[j].face)
for k in range (nbr_keypoints):
if parameter.description_method == 'sift':
size = int(data[i].facedata[j].keypoints[k].size)
elif parameter.description_method == 'surf':
size = int(data[i].facedata[j].keypoints[k].size)/2
cv.Circle(tmpImage, (int(data[i].facedata[j].keypoints[k].pt[0]), int(data[i].facedata[j].keypoints[k].pt[1])), size, 255)
show_images(tmpImage)
except:
logging.error('Error showing keypoints - Maybe no Face in File %s (tools.py)' % data[i].filename)
def topresults(match_data):
""" Show top matching results"""
with open('match-statistics.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(["Position", "Search-Image", "Train-Image", "Matching-Value", "Nbr-Matches"])
for i in range(len(match_data)):
if hasattr(match_data[i], 'matcheddata'):
nbr_images = len(match_data[i].matcheddata)
matchvalues = {}
if nbr_images == 0:
logging.warn('No MatchData available - Maybe no face in Search-File (tools.py)')
else:
# extract matchvalues into tmp dictionary
for j in range(nbr_images):
if not match_data[i].matcheddata[j].matchvalue:
logging.warn('No face found in file %s (tools.py)' % match_data[i].searchfilename)
else:
matchvalues[j] = match_data[i].matcheddata[j].matchvalue
# sort dictionary
sorted_matchvalues = sorted(matchvalues.iteritems(), key=operator.itemgetter(1), reverse=True)
nbr_matches = len(sorted_matchvalues)
for j in range(nbr_matches):
if (j+1) <= int(parameter.number_topresults): # only show given number of topresults
if not match_data[i].matcheddata[j].matchvalue:
logging.warn('No face found in file %s (tools.py)' % match_data[i].filename)
else:
print('Nr. %d with MatchingValue %.5f (left %s, right %s, %d matches) (tools.py)' %((j+1), float(sorted_matchvalues[j][1]),match_data[i].matcheddata[sorted_matchvalues[j][0]].filename, match_data[i].searchfilename, match_data[i].matcheddata[sorted_matchvalues[j][0]].nbr_matches))
#write data to file
writer.writerow([j+1, match_data[i].searchfilename, match_data[i].matcheddata[sorted_matchvalues[j][0]].filename, float(sorted_matchvalues[j][1]), match_data[i].matcheddata[sorted_matchvalues[j][0]].nbr_matches])
# show images
if parameter.save_images == 1:
show_images(match_data[i].matcheddata[sorted_matchvalues[j][0]].vis)
else:
print 'Only Top %s images are printed (tools.py)' % parameter.number_topresults
break
else:
logging.warn('No Match Data for Searchfile %s available' %match_data[i].searchfilename)
writer.writerow(['', match_data[i].searchfilename, 'No Match-Data available'])
def count_features(data):
""" prints and saves stats for the trained data"""
with open('train-statistics.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(["Image-Name", "Face-Nr", "number of Keypoints", "number of Descriptors", "rows", "cols"])
for i in range(len(data)):
try:
if hasattr(data[i], 'facedata'):
for j in range(len(data[i].facedata)):
nbr_keypoints = len(data[i].facedata[j].keypoints)
nbr_descriptors = len(data[i].facedata[j].descriptors)
writer.writerow([data[i].filename, j+1, len(data[i].facedata[j].keypoints), len(data[i].facedata[j].descriptors), data[i].facedata[j].facesize[0], data[i].facedata[j].facesize[1]])
else:
logging.info('No facedata available in File %s (Maybe no Face found or filtered?) (tools.py)' % data[i].filename)
writer.writerow([data[i].filename, "no data saved"])
except AttributeError:
logging.error('Error counting features for file %s (tools.py)' % data[i].filename)
def enlarge_image(image, factor):
""" Enlarge the image to the given size
Image must be of type cv.cvmat"""
if type(image).__name__=='cvmat':
new_image = cv.CreateMat(int(round(image.height * factor)), int(round(image.width * factor)), cv.GetElemType(image))
cv.Resize(image, new_image)
image = new_image
logging.debug('Image has been enlarged with factor %.3f (face-detector.py)' % (factor))
return image
else:
logging.error('Unkown Image Type (tools.py)')
def downsize_image(image):
""" Resize the image to the given size
Image must be of type cv.cvmat"""
height_factor = float(image.height/parameter.max_facesize[0])
width_factor = float(image.width/parameter.max_facesize[1])
if height_factor > width_factor:
new_face = cv.CreateMat(image.height/height_factor, image.width/height_factor, cv.GetElemType(image))
downsize_factor = height_factor
else:
new_face = cv.CreateMat(int(image.height/width_factor), int(image.width/width_factor), cv.GetElemType(image))
downsize_factor = width_factor
cv.Resize(image, new_face)
return new_face, downsize_factor
def cv2array(im):
""" convert from type cv into type array"""
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
arrdtype=im.depth
a = np.fromstring(
im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width*im.height*im.nChannels)
a.shape = (im.height,im.width,im.nChannels)
return a
def array2cv(a):
""" convert from type array into type cv"""
dtype2depth = {
'uint8': cv.IPL_DEPTH_8U,
'int8': cv.IPL_DEPTH_8S,
'uint16': cv.IPL_DEPTH_16U,
'int16': cv.IPL_DEPTH_16S,
'int32': cv.IPL_DEPTH_32S,
'float32': cv.IPL_DEPTH_32F,
'float64': cv.IPL_DEPTH_64F,
}
try:
nChannels = a.shape[2]
except:
nChannels = 1
cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels)
cv.SetData(cv_im, a.tostring(),a.dtype.itemsize*nChannels*a.shape[1])
return cv_im
def anorm2(a):
return (a*a).sum(-1)
def anorm(a):
return np.sqrt( anorm2(a) )
|
Markdown
|
UTF-8
| 3,580 | 2.71875 | 3 |
[] |
no_license
|
# Evoq Modules - Liquid Content Job List
This is a sample DNN module to access Liquid Content using Angular JS v1.6. A bearer token with read permission for Liquid Content is generated on the server side and passed to the front-end.

## View.ascx
Add a div with Angular controller using "ng-controller" directive (line #3 in the code in the following screenshot). ScopeWrapper.ClientId is a unique id generated by dnn on the server side. Use it to give unique name to the controller.
Add a div with unique id using ScopeWrapper.ClientId (line #4). It will be a container for Angular application.

To keep array of Module IDs use dnn.moduleIds global variable. Angular application will need the ids to know in what container to bootstrap.
Also there is a dnn.app variable that bundle Angular app to unique controller

Script tag to the path with the Angular bundle is included to the View.

## NPM and Webpack
Install node.js and npm if it's not installed.
Include all devDependecies into package.json file.

Install all node modules from the folder where your package.json is located
```
npm install
```
Configure webpack to load bundle in the path that is used in View.ascx
## Template
For this module only one template is used. It's included in app.html file.

ng-repeat directive iterates through each job in JobList and repeats the job-item element for each iteration
## app.js
Get moduleId first. It will be used to name Angular module and Angular controller to make it unique for each Evoq module

Create an empty object as a global variable. In this variable we will store Angular modules and controllers for each Evoq module

Create an Angular module using moduleId. One Angular module per Evoq module. Bind template and controller to it.

Create an Angular controller using moduleId. The controller is a JS class. Provide $scope, $htpp, $compile and $sce services to the constructor of the class.

Inject all the services into the controller.

Inside of the constructor of the controller Append template app.html to the Evoq module DOM. Compile the template using $compile service.

Liquid Content requires a bearer token for a client to access the APIs. Get the token from DOM element of the Evoq Module.

Get the Id of the "Job Posting" content type. We need this id to get content items only of the "Job Posting" content type.
Asynchronously call loadPage() function after getting the content type id.

Load content items using content type id. Store the result into the $scope.

Register the Angular module with the controller.

To be able to load multiple Angular modules on the same page, bootstrap all the modules. Bootstrap should happen only once for all modules. There is a delay with timeout that alows the next module to clear the timeout. This way only when the last module is loaded bootstrap will execute.

|
JavaScript
|
UTF-8
| 1,289 | 2.796875 | 3 |
[] |
no_license
|
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
//io.on('connection', function(socket){
// socket.on('chat message', function(msg){
// console.log('message: ' + msg);
// io.emit('chat message', msg);
// });
//});
var change = 0;
function intervalFunc(arg) {
//var rand = Math.random() * 200;
//rand = Math.floor(rand);
//io.emit('chat message', '{ "values": [ [' + rand + ',20], [30,40] ] }');
// Read Synchrously
var fs = require("fs");
if (change == 0) {
//var content = fs.readFileSync('data.json');
var content = fs.readFileSync('test3.json');
//console.log("Output Content : \n"+ content);
change = 1;
}
else if (change == 1) {
var content = fs.readFileSync('test.json');
change = 2;
}
else {
var content = fs.readFileSync('test2.json');
change = 0;
}
//io.emit('jpet', '{ "values": [ [100,20], [30,40] ] }');
content = content.toString('utf8')
io.emit('jpet', content);
}
setInterval(intervalFunc, 500);
http.listen(3000, function(){
console.log('listening on *:3000');
});
|
Markdown
|
UTF-8
| 2,252 | 2.78125 | 3 |
[] |
no_license
|
# [RetinaFace: Single-stage Dense Face Localisation in the Wild](https://arxiv.org/abs/1905.00641)
_September 2019_
tl;dr: Single stage face detection with landmark regression and dense face regression. Landmark regression helps object detection.
#### Overall impression
The paper is from the same authors of [ArcFace](arcface.md).
Joint face detection and alignment (landmark regression) has been widely used, such as [MT-CNN](mtcnn.md). This paper also adds a dense face regression branch by generating mesh and reproject to 2D image and calculating the photometric loss. This self-supervised branch (can be turned off during inference) helps boost the performance of object detection.
Face detection can be trained on GPU, but inference on CPU is still the most popular choice, for surveillance purpose, etc.
#### Key ideas
- Mask RCNN helps with object detection: Dense pixel annotation helps with object detection.
- Multiple loss:
- cls loss: face vs not face
- Face box regression: zero loss for negative anchors
- Facial landmark regression: zero loss for negative anchors, normalized according to same anchor as face box.
- Dense regression loss: renders a face mesh and reprojects for self-supervised learning.
- **Context module**: inspired by single stage headless detector (SSH) and PyramidBox, basically concats features from different levels together after **FPN**.
- input 256 --> 128 --> 64 --> 64
- 128 + 64 + 64 = 256 output
- all 3x3 conv replaced with **DCN** (deformable)
- Mesh decode is a pretrained model, and it extracts 128 points per face. Then an efficient 3D mesh renderer projects the 128 points to the 2D plane, and compares the photometric loss. Additional parameters in camera and illumination parameters (7+9) for each face.
#### Technical details
- Face detection features smaller ratio variations but much larger scale variation.
- Anchors: 75% of anchors are from P2, high resolution image.
- Accuracy evaluation normalized by face box size (√WxH)
#### Notes
- Both the retinaFace and the STN (supervised transformer network) from MSRA predicts landmark together from the first stage (RPN for STN, and FPN for retinaFace). Maybe regressing landmarks with bbox simultaneously works after all.
|
Java
|
UTF-8
| 2,199 | 2.25 | 2 |
[] |
no_license
|
package rcp.manticora.acciones;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.hibernate.Session;
import rcp.manticora.controllers.CommonController;
import rcp.manticora.dao.CommonDAO;
import rcp.manticora.dao.CommonDAO2;
import rcp.manticora.services.HibernateUtil;
import rcp.manticora.views.IRefreshView;
public class BorrarElementoAction implements IViewActionDelegate {
private Object seleccion;
private CommonDAO daoController;
private CommonDAO2 daoController2;
private CommonController daoController3;
private IRefreshView v;
private Shell shell;
public void init(IViewPart view) {
daoController = new CommonDAO();
daoController2 = new CommonDAO2();
daoController3 = new CommonController();
shell = view.getSite().getShell();
v = (IRefreshView) view;
}
public void run(IAction action) {
if (seleccion == null) {
MessageDialog.openInformation(shell, "Aviso", "No ha seleccionado ningún registro.");
} else {
boolean respuesta = MessageDialog.openConfirm(shell, "Confirmación", "Desea borrar el registro seleccionado?");
if (respuesta) {
System.out.println("Borrando elemento seleccionado..." + seleccion);
if (daoController != null) {
/*
Session s = HibernateUtil.currentSession();
s.beginTransaction();
daoController.setSession(s);
daoController.makeTransient(seleccion);
daoController.commit();
HibernateUtil.closeSession();
*/
//daoController.doDelete(seleccion);
//daoController2.doDelete(seleccion);
daoController3.doDelete(seleccion);
v.refrescar();
} else {
System.out.println("daoController es NULL, no se pudo borrar el registro");
}
} else {
MessageDialog.openInformation(shell, "Información", "La acción ha sido cancelada.");
}
}
}
public void selectionChanged(IAction action, ISelection selection) {
seleccion = ((StructuredSelection) selection).getFirstElement();
}
}
|
C++
|
UTF-8
| 589 | 2.71875 | 3 |
[] |
no_license
|
#pragma once
#include <string>
#include "Statistics.h";
using namespace std;
class Player
{
private:
string name;
char playing_mark;
Statistics stats;
public:
Player();
Player(string player_name, char mark_used);
int get_score();
string getPlayerName();
void setPlayerName(string playerName);
char getPlayingMark();
void setPlayingMark(char playingMark);
friend bool operator> (const Player &c1 , const Player &c2);
friend bool operator< (const Player &c1, const Player &c2);
friend bool operator== (const Player &c1, const Player &c2);
void printResult();
~Player();
};
|
JavaScript
|
UTF-8
| 1,345 | 2.59375 | 3 |
[] |
no_license
|
var
express = require("express"),
fs = require("fs"),
bodyParser = require("body-parser"),
cors = require("cors"),
config = {
name_str: "price",
port_int: 3000,
host_str: "0.0.0.0"
},
app = express();
app.use(bodyParser.json());
app.use(cors());
app.get("/", (req, res) => {
res.status(200).send("hello this is the root of the price api");
});
var
g_payload = {
price_arr: ["134.50", "455.99"]
};
var shared_file_path_str = "/my_amazing_shared_folder/price_data.json";
if(fs.existsSync(shared_file_path_str)) {
console.log("The price file exists, getting info");
var file_data = fs.readFileSync(shared_file_path_str);
g_payload = JSON.parse(file_data.toString());
}
//IF we are using the names volume overrider this again
shared_file_path_str = "/contains_your_price_data/price_data.json";
if(fs.existsSync(shared_file_path_str)) {
console.log("The named volume price file exists, getting info");
file_data = fs.readFileSync(shared_file_path_str);
g_payload = JSON.parse(file_data.toString());//replace
}
app.get("/get-prices", (req, res) => {
res.status(200).json(g_payload);
console.log("returning prices");
});
app.listen(config.port_int, config.host_str, (e)=> {
if(e) {
throw new Error("Internal Server Error");
}
console.log("Running the " + config.name_str + " app");
});
|
Markdown
|
UTF-8
| 891 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# JCL IT
**Created At:** 5/28/2018 11:12:03 AM
**Updated At:** 6/11/2018 4:15:27 AM
**Original Doc:** [318726-jcl-it](https://docs.jbase.com/45792-jcl/318726-jcl-it)
**Original ID:** 318726
**Internal:** No
## Description
The command reads a tape record into the primary input buffer. It takes the general form:
```
IT{C}{A}
```
where:
- C performs an EBCDIC to ASCII conversion before the data is put into the buffer.
- A masks 8-bit ASCII characters to 7 bits (resets the most significant bit to a 0).
## Note:
> The IT command will read a tape record into the primary input buffer. The new data will be placed at the beginning of the buffer and will replace all existing buffer data.
###### EXAMPLE
| Command | PIB Before<br> | PIB After<br> |
| --- | --- | --- |
| IT<br> | ABC<br> | tape data<br> |
Back to [JCL Commands](./../jcl-commands)
|
Python
|
UTF-8
| 2,383 | 2.890625 | 3 |
[] |
no_license
|
import os, sqlite3, hashlib, atexit
_DATABASE=sqlite3.connect('data.sqlite')
def hashfile(filecontents):
"""Save a string to a file and return the hash for lookup.
The string can then be retrieved by gethash().
TODO unit tests
"""
filehash=hashlib.sha256(filecontents).hexdigest() # pylint: disable-msg=E1101
# save filecontents
(hashfolder, hashfilename)=__hashpath(filehash)
if not os.path.exists(hashfilename):
if not os.path.exists(hashfolder): # Create parent directories, if needed
os.makedirs(hashfolder)
with open(hashfilename, 'w') as filehandle:
filehandle.write(filecontents)
return filehash
def gethash(filehash):
"""Given a hash, returns the string which was saved by hashfile()
TODO unit test
"""
with open(__hashpath(filehash)[1], 'r') as filehandle:
return filehandle.read()
def __hashpath(filehash):
"""Turn a hex digest into a folder and file path.
>>> __hashpath('954e65600cf9ab574449316106c8df9ef12d09f1e4b525132c0a13d4e9ff8899')
('data/95/4e/65/60', 'data/95/4e/65/60/954e65600cf9ab574449316106c8df9ef12d09f1e4b525132c0a13d4e9ff8899')
"""
hashfolder = "/".join([ 'data', filehash[0:2], filehash[2:4],
filehash[4:6], filehash[6:8] ])
return (hashfolder, hashfolder+"/"+filehash)
def getlatest(host, port, path):
"""Get the latest archived version of a file.
"""
cursor = _DATABASE.cursor()
cols=['host', 'port', 'dtype', 'path', 'state', 'timestamp', 'log', 'hash']
cursor.execute("SELECT "+", ".join(cols)+
" FROM latest WHERE host=? AND port=? AND path=?;",
(host, port, path))
data=cursor.fetchone()
if data is None:
return None
result={}
for i in range(len(cols)):
result[cols[i]] = data[i]
return result
def dbsave(host, port, dtype, path, state, timestamp, log, filehash,
autocommit =True):
"""Insert a row into the files table.
autocommit should be set to false if a lot of rows are to be inserted at once.
"""
_DATABASE.execute("INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?);",
(host, port, dtype, path, state, int(timestamp),log, filehash))
if autocommit :
dbcommit()
def dbcommit():
"""Commit the current database transaction.
Called by dbclose() when the program exits.
"""
_DATABASE.commit()
@atexit.register
def dbclose():
"""Commit changes to the database and close the connection.
Called automatically when the program exits.
"""
dbcommit()
_DATABASE.close()
|
JavaScript
|
UTF-8
| 1,025 | 2.953125 | 3 |
[] |
no_license
|
let $button, $img, imageCapture;
document.addEventListener('DOMContentLoaded', init, false);
function init() {
$button = document.querySelector('#takePictureButton');
$img = document.querySelector('#testImage');
navigator.mediaDevices.getUserMedia({video: true})
.then(setup)
.catch(error => console.error('getUserMedia() error:', error));
}
function setup(mediaStream) {
$button.addEventListener('click', takePic);
$img.addEventListener('load', getSwatches);
const mediaStreamTrack = mediaStream.getVideoTracks()[0];
imageCapture = new ImageCapture(mediaStreamTrack);
}
function takePic() {
imageCapture.takePhoto()
.then(res => {
$img.src = URL.createObjectURL(res);
});
}
function getSwatches() {
let colorThief = new ColorThief();
var colorArr = colorThief.getPalette($img, 5);
console.dir(colorArr);
for (var i = 0; i < Math.min(5, colorArr.length); i++) {
document.querySelector('#swatch'+i).style.backgroundColor = "rgb("+colorArr[i][0]+","+colorArr[i][1]+","+colorArr[i][2]+")";
}
}
|
C++
|
UTF-8
| 1,029 | 3.703125 | 4 |
[] |
no_license
|
/*
Palindrome.cpp
*/
#include <string>
#include <iostream>
#define STACKSIZE 80
#define TRUE 1
#define FALSE 0
using namespace std;
class Stack {
public:
void StackInit();
int IsStackEmpty();
int IsStackFull();
int StackPush(char c);
char StackPop();
char ViewStackTop();
private:
char myStack[80];
int top;
};
string pstring;
int main() {
// write your code here
cout << "This Is A Palindrome Check Programe" << endl;
cout << "Please Enter Anything For Palindrome Check" << endl;
cin >> pstring;
system("pause");
return 0;
}
void Stack::StackInit() {
top = -1;
}
int Stack::IsStackEmpty() {
if (top == -1)
return TRUE;
return FALSE;
}
int Stack::IsStackFull() {
if (top == (STACKSIZE - 1))
return TRUE;
return FALSE;
}
int Stack::StackPush(char c) {
if (top == (STACKSIZE - 1))
return FALSE;
myStack[++top] = c;
return TRUE;
}
char Stack::StackPop() {
if (top == -1)
return '\0';
return myStack[top--];
}
char Stack::ViewStackTop() {
if (top == -1)
return '\0';
return myStack[top];
}
|
Java
|
UTF-8
| 1,009 | 3.625 | 4 |
[] |
no_license
|
package interfacePractice_ComparatorGeometry;
import java.util.Arrays;
public class GeometryComparatorTest {
public static void main(String[] args) {
Circle[] circles = new Circle[2];
circles[0] = new Circle(20, "black", false);
circles[1] = new Circle(18, "black", false);
Rectangle[] r = new Rectangle[2];
r[0] = new Rectangle(20, 15, "red", true);
r[1] = new Rectangle(23, 10, "red", true);
Comparator circleComparator = new CircleComparator();
System.out.println(circleComparator.compare(circles[0], circles[1]));
Comparator rectComparator = new RectangleComparator();
System.out.println(rectComparator.compare(r[0], r[1]));
System.out.println("Thứ tự hình tròn");
for (Circle circle : circles){
System.out.println(circle);
}
System.out.println("Thứ tự hình vuông");
for (Rectangle rect : r){
System.out.println(rect);
}
}
}
|
Markdown
|
UTF-8
| 4,213 | 3.015625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
# Table of contents
- [What is gitlab-tester-tools](#what-is-gitlab-tester-tools)
- [Gitlab setup](#gitlab-setup)
- [Create tester user](#create-tester-user)
- [Add tester user to your project](#add-tester-user-to-your-project)
- [Setup testing secret token](#setup-testing-secret-token)
- [Setting up the .gitlab-ci.yml file](#setting-up-the-gitlab-ciyml-file)
- [Delete a branch from pipeline](#delete-a-branch-from-pipeline)
- [git-test plugin](#git-test-plugin)
- [How to use the plugin](#how-to-use-the-plugin)
- [How the plugin works](#how-the-plugin-works)
- [TODO](#todo)
# What is gitlab-tester-tools
Gitlab tester tools are a set of tools used to interact with Gitlab and
automatize the testing process during local development.
$ git add <files i want to test>
$ git test origin
Simple as that...Gitlab tester tools makes testers' lifes easier.
# Gitlab setup
## Create tester user
To create the `tester` user, go in the Admin Area, select `New user` and set
`Access Level` to `Regular`.
Once the creation process is finished, click on the `tester` user, in the Admin
Area and go to `Impersonation Tokens`, then set `Scopes` to `api`.
## Add tester user to your project
Go to the project page and under `Settings -> Members` add `tester` user
with Master role.
## Setup testing secret token
The token that is generated for `tester` user now can be used to send requests
to the Gitlab API. This can be done by exposing it to the pipeline environment
variables: go to `Settings -> CI / CD -> Secret variables` and create the
`CI_TESTER_TOKEN` variable with the token value of the `tester` user.
At this point, `tester` user is the access to our Gitlab API and its token is
exposed by `CI_TESTER_TOKEN`. All the times the project's pipeline will run,
`CI_TESTER_TOKEN` will be exposed in order to interact with Gitlab using the
HTTP protocol.
## Setting up the .gitlab-ci.yml file
The pipeline file `.gitlab-ci.yml`, in order to work with the ci tools has to
be configured properly.
### Delete testing branch from pipeline
An example on how to remove a branch from pipeline is the following:
stages:
- tests
- cleanup
mytests:
stage: tests
script:
- echo "hello world"
only:
refs:
- /^testing\/.*/
delete-testing-branch:
stage: cleanup
script:
- ci_tools/gitlab-pipeline.py -d
# the cleanup must be executed on testing "temporary" branches only
only:
refs:
- /^testing\/.*/
# always run this stage even if the previous stages are failing
when: always
In this example, the `delete-testing-branch` is always executed after any job
which fails or not. Its purpose is to remove the current branch with `testing/`
prefix.
With this setup, any branch starting with `testing/` prefix can be considered
as a "temporary branch" used to trigger `tests` stage.
# git-test plugin
## How to use the plugin
Git recognize plugins starting with `git-` prefix and inside the PATH, so, to
use the git-test plugin, PATH has to be initialized as following:
export PATH=$PATH:<my parent path>/ci_tools
## How the plugin works
Note that to use this plugin the CI system must be configured to run tests
when a commit has been received inside a branch with `testing/` name suffix.
A way to do so in gitlab is to setup `.gitlab-ci.yml` like following:
stages:
- test
tests:
stage: test
script:
- echo "this is a test"
only:
refs:
- /^testing\/.*/
- master
When user runs `git test origin`, the plugin will upload the current
modifications inside a branch named `testing/<username>/<random string>`
in the `origin` server.
In particular, git-test plugin simplifies the following procedure:
$ git stash --keep-index
$ git push stash:refs/heads/testing/<username>/<random string>
$ git stash pop
And it can be used in the following way:
$ git add <my testing files>
$ git test origin
# License
All the source code and documentation is released under the BSD license.
|
C++
|
UTF-8
| 1,309 | 2.640625 | 3 |
[] |
no_license
|
#ifndef TEST_RGBLEDJSONSERVICE_H
#define TEST_RGBLEDJSONSERVICE_H
#include <Arduino.h>
#include <ArduinoJson.h>
#include <domain/valoplus/rgbLed.h>
class RgbLedJsonService {
private:
public:
char* toJson(RgbLed obj) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root("name", obj.getName());
root("channelIdRed", obj.getChannelIdRed());
root("channelIdGreen", obj.getChannelIdGreen());
root("channelIdBlue", obj.getChannelIdBlue());
JsonObject& links = root.createNestedObject("_links");
JsonObject& self1 = links.createNestedObject("self");
self1.set("href", "/rgbLeds/" + obj.getId());
JsonObject& self2 = links.createNestedObject("rgbLed");
self2.set("href", "/rgbLeds/" + obj.getId());
char buffer[root.measureLength()];
root.printTo(buffer, sizeof(buffer));
return buffer;
}
RgbLed fromJson(String json) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
RgbLed result = RgbLed();
result.setName(root("name"));
result.setChannelIdRed(root("channelIdRed"));
result.setChannelIdGreen(root("channelIdGreen"));
result.setChannelIdBlue(root("channelIdBlue"));
return result;
}
};
#endif //TEST_RGBLEDJSONSERVICE_H
|
Markdown
|
UTF-8
| 2,261 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# Vendor Dependencies
When we use hardware from a third-party source, we need to place what are called "vendor dependency" files into our robot program.
A prime example of such hardware would be a motor controller (see [Motors](https://frc1257.github.io/robotics-training/#/frc/1-Basics/2-Motors) for more detail). Say we are using a SPARK MAX controller from REV Robotics--in order for the controller to actually function, we need to get the vendor dependency (a `.json` file) from REV Robotics' [website](http://www.revrobotics.com/sparkmax-software/).
## Installing
The following steps for managing vendor dependencies **online** can be found on that site:
1. Open your robot project in VSCode.
2. Click on the WPI icon in the corner to open the WPI Command Pallet.
3. Select **Manage Vendor Libraries**.
4. Select **Install new library (online)**.
5. Enter the following installation URL and press ENTER:
`http://www.revrobotics.com/content/sw/max/sdk/REVRobotics.json`
If you are managing vendor dependencies **offline**, you must:
1. Download and unzip the latest SPARK MAX Java API into the C:\Users\Public\wpilib\2020 directory on windows and ~/wpilib/2020 directory on Unix systems.
2. Follow the [Adding an offline-installed Library](https://docs.wpilib.org/en/latest/docs/software/wpilib-overview/3rd-party-libraries.html) instructions from WPI.
Similar steps can be followed with other devices, such as the [Talon SRX motor controller (or other motor controllers from CTRE)](https://phoenix-documentation.readthedocs.io/en/latest/ch05a_CppJava.html) and [navX-MXP gyroscope](https://pdocs.kauailabs.com/navx-mxp/software/roborio-libraries/java/).
## Updating
Over time, those third-party vendors will most likely release new updates, and will do so through a new vendor dependency file. Therefore, it's our job to check for updates regularly.
To update the vendor dependencies, the steps are similar to those above:
1. Open your robot project in VSCode.
2. Click on the WPI icon in the corner to open the WPI Command Pallet.
3. Select **Manage Vendor Libraries**.
4. Select **Check for updates (online)**. (Can also be **(offline)**).
5. If an update appears, click on it. Otherwise, you're all set.
|
Java
|
UTF-8
| 335 | 1.632813 | 2 |
[] |
no_license
|
package com.brtbeacon.map3d.demo.dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public interface DialogFragmentListener {
void onDialogCancel(DialogFragment fragment);
void onDialogDismiss(DialogFragment fragment);
void onDialogResult(DialogFragment fragment, Bundle result);
}
|
Java
|
UTF-8
| 19,641 | 1.664063 | 2 |
[] |
no_license
|
package com.bestweby.enewz.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;
import com.bestweby.enewz.R;
import com.bestweby.enewz.adapter.recycler.HomeCategoryAdapter;
import com.bestweby.enewz.adapter.recycler.StoryPostListAdapter;
import com.bestweby.enewz.adapter.viewpager.TemplateSliderAdapter;
import com.bestweby.enewz.app.BaseActivity;
import com.bestweby.enewz.cache.constant.AppConstants;
import com.bestweby.enewz.databinding.ActivityStoryTemplateLayoutBinding;
import com.bestweby.enewz.databinding.NavHeaderLayoutBinding;
import com.bestweby.enewz.helper.AppHelper;
import com.bestweby.enewz.listener.ItemClickListener;
import com.bestweby.enewz.listener.ItemViewClickListener;
import com.bestweby.enewz.listener.MenuItemClickListener;
import com.bestweby.enewz.model.Category.CategoryModel;
import com.bestweby.enewz.model.posts.post.PostModel;
import com.bestweby.enewz.network.ApiClient;
import com.bestweby.enewz.network.ApiRequests;
import com.bestweby.enewz.receiver.NetworkChangeReceiver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by Md Sahidul Islam on 04-Jun-19.
*/
public class StoryTemplateActivity extends BaseActivity {
private ActivityStoryTemplateLayoutBinding binding;
private NavHeaderLayoutBinding navHeaderbinding;
private TemplateSliderAdapter sliderAdapter;
private HomeCategoryAdapter categoryAdapter;
private StoryPostListAdapter postListAdapter;
private List<PostModel> featuredList, postList;
private List<CategoryModel> categoryList;
private int pageNumber = AppConstants.PAGE_NUMBER;
private Boolean isDataLoading = false;
private Boolean canLoadMore = false;
private boolean doubleBackToExitPressedOnce = false;
private int NUM_PAGES = 0, CURRENT_PAGE = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initVars();
initView();
initListener();
loadData();
}
@Override
protected void onResume() {
super.onResume();
updateToolbarNotificationCount(binding.homeToolbar.notificationCounter);
binding.mainNavView.getMenu().getItem(3).setChecked(true);
}
@Override
public void onBackPressed() {
if (this.binding.homeDrawerlayout.isDrawerOpen(GravityCompat.START)) {
this.binding.homeDrawerlayout.closeDrawer(GravityCompat.START);
} else {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
AppHelper.showShortToast(StoryTemplateActivity.this, "Please click BACK again to exit");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
}
private void initVars() {
featuredList = new ArrayList<>();
postList = new ArrayList<>();
categoryList = new ArrayList<>();
}
private void initView() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_story_template_layout);
initDrawerLayout(binding.homeDrawerlayout, binding.mainNavView, binding.homeToolbar.toolbar);
initializeDrawerHeader();
initSliderViewPager();
initRecyclerView();
}
private void initListener() {
binding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData();
}
});
binding.contentView.sliderViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
enableDisableSwipeRefresh(binding.swipeRefresh, state == ViewPager.SCROLL_STATE_IDLE);
}
});
binding.homeToolbar.toolbarMenuNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(StoryTemplateActivity.this, NotificationActivity.class));
}
});
binding.homeToolbar.toolbarMenuSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(StoryTemplateActivity.this, SearchPostActivity.class));
}
});
categoryAdapter.setItemClickListener(new ItemViewClickListener() {
@Override
public void onItemViewClickGetPosition(int position, View view) {
Bundle bundle = new Bundle();
bundle.putString(AppConstants.BUNDLE_PAGE_TITLE, categoryList.get(position).getName());
bundle.putInt(AppConstants.BUNDLE_CATEGORY_ID, categoryList.get(position).getId());
bundle.putSerializable(AppConstants.BUNDLE_LAYOUT_TYPE, AppConstants.ListLayoutType.GRID);
startActivity(new Intent(StoryTemplateActivity.this, CategoryPostsActivity.class).putExtras(bundle));
}
});
postListAdapter.setItemClickListener(new ItemViewClickListener() {
@Override
public void onItemViewClickGetPosition(int position, View view) {
switch (view.getId()) {
case R.id.parent_view:
Bundle bundle = new Bundle();
bundle.putInt(AppConstants.BUNDLE_POST_ID, postList.get(position).getId());
bundle.putString(AppConstants.BUNDLE_PAGE_TITLE, postList.get(position).getTitle().getRendered());
startActivity(new Intent(StoryTemplateActivity.this, PostDetailActivity.class).putExtras(bundle));
break;
}
}
});
postListAdapter.setMenuItemClickListener(new MenuItemClickListener() {
@Override
public void onMenuItemClick(int position, MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_share:
sharePost(postList.get(position));
break;
case R.id.menu_save:
checkAndSaveFavourite(postList.get(position));
break;
}
}
});
}
private void initializeDrawerHeader() {
navHeaderbinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.nav_header_layout, binding.mainNavView, false);
binding.mainNavView.addHeaderView(navHeaderbinding.getRoot());
}
private void initSliderViewPager() {
sliderAdapter = new TemplateSliderAdapter(this, featuredList, true);
binding.contentView.sliderViewpager.setAdapter(sliderAdapter);
sliderAdapter.setSliderItemClickListerner(new ItemClickListener() {
@Override
public void onItemClickGetPosition(int position) {
Bundle bundle = new Bundle();
bundle.putInt(AppConstants.BUNDLE_POST_ID, featuredList.get(position).getId());
bundle.putString(AppConstants.BUNDLE_PAGE_TITLE, featuredList.get(position).getTitle().getRendered());
startActivity(new Intent(StoryTemplateActivity.this, PostDetailActivity.class).putExtras(bundle));
}
});
}
private void initRecyclerView() {
categoryAdapter = new HomeCategoryAdapter(StoryTemplateActivity.this, categoryList);
binding.contentView.categoryRecycler.setLayoutManager(new LinearLayoutManager(StoryTemplateActivity.this, LinearLayoutManager.HORIZONTAL, false));
binding.contentView.categoryRecycler.setNestedScrollingEnabled(false);
binding.contentView.categoryRecycler.setAdapter(categoryAdapter);
postListAdapter = new StoryPostListAdapter(StoryTemplateActivity.this, postList);
binding.contentView.primaryRecycler.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
binding.contentView.primaryRecycler.setItemAnimator(new DefaultItemAnimator());
binding.contentView.primaryRecycler.setNestedScrollingEnabled(false);
binding.contentView.primaryRecycler.setAdapter(postListAdapter);
binding.nestedscrollView.setOnScrollChangeListener(onNestedScrollChange());
}
private void showSlider() {
sliderAdapter.notifyDataSetChanged();
binding.contentView.sliderShimmerView.shimmerView.setVisibility(View.GONE);
binding.contentView.sliderViewpager.setVisibility(View.VISIBLE);
/*Uncomment below codes for auto sliding effect*/
/* NUM_PAGES = featuredList.size();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(AppConstants.SLIDER_DURATION);
} catch (Exception e) {
e.printStackTrace();
}
CURRENT_PAGE = binding.contentView.sliderViewpager.getCurrentItem();
if (CURRENT_PAGE == (NUM_PAGES - 1)) {
CURRENT_PAGE = 0;
} else {
CURRENT_PAGE++;
}
(StoryTemplateActivity.this).runOnUiThread(new Runnable() {
@Override
public void run() {
binding.contentView.sliderViewpager.setCurrentItem(CURRENT_PAGE, true);
}
});
}
}
}).start();*/
}
private void loadData() {
loadFeaturedPosts();
loadCategories();
loadAllPosts(AppConstants.PAGE_NUMBER);
}
private void refreshData() {
loadFeaturedPosts();
loadCategories();
loadAllPosts(AppConstants.PAGE_NUMBER);
if (binding.swipeRefresh.isRefreshing()) {
binding.swipeRefresh.setRefreshing(false);
}
}
private void loadFeaturedPosts() {
if (NetworkChangeReceiver.isNetworkConnected()) {
binding.contentView.sliderViewpager.setVisibility(View.GONE);
binding.contentView.sliderShimmerView.shimmerView.setVisibility(View.VISIBLE);
HashMap<String, String> featuredPostsMap = ApiRequests.buildPostTaxonomy(true, AppConstants.PER_PAGE);
ApiClient.getInstance().getApiInterface().getPosts(featuredPostsMap).enqueue(new Callback<List<PostModel>>() {
@Override
public void onResponse(@NonNull Call<List<PostModel>> call, @NonNull Response<List<PostModel>> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
featuredList.clear();
featuredList.addAll(response.body());
if (featuredList != null && featuredList.size() > 0) {
showSlider();
}
binding.contentView.sliderShimmerView.shimmerView.setVisibility(View.GONE);
}
} else {
AppHelper.showShortToast(context, getString(R.string.failed_msg));
}
}
@Override
public void onFailure(@NonNull Call<List<PostModel>> call, @NonNull Throwable t) {
binding.contentView.sliderShimmerView.shimmerView.setVisibility(View.GONE);
AppHelper.showShortToast(context, getString(R.string.failed_msg));
}
});
}
AppHelper.noInternetWarning(context, binding.getRoot());
}
private void loadCategories() {
if (NetworkChangeReceiver.isNetworkConnected()) {
binding.contentView.categoryCardView.setVisibility(View.GONE);
binding.contentView.categoryShimmerView.shimmerView.setVisibility(View.VISIBLE);
HashMap<String, String> categoriesMap = ApiRequests.buildCategory(true, AppConstants.CATEGORY_PER_PAGE);
ApiClient.getInstance().getApiInterface().getCategories(categoriesMap).enqueue(new Callback<List<CategoryModel>>() {
@Override
public void onResponse(@NonNull Call<List<CategoryModel>> call, @NonNull Response<List<CategoryModel>> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
categoryList.clear();
/* Show only Main/Parent Categories*/
for (CategoryModel categoryModel : response.body()) {
if (categoryModel.getParent() == 0) {
categoryList.add(categoryModel);
}
}
/* Show All Categories*/
// categoryList.addAll(response.body());
if (categoryList != null && categoryList.size() > 0) {
categoryAdapter.notifyDataSetChanged();
binding.contentView.categoryCardView.setVisibility(View.VISIBLE);
}
binding.contentView.categoryShimmerView.shimmerView.setVisibility(View.GONE);
}
} else {
AppHelper.showShortToast(context, getString(R.string.failed_msg));
}
}
@Override
public void onFailure(@NonNull Call<List<CategoryModel>> call, @NonNull Throwable t) {
binding.contentView.categoryShimmerView.shimmerView.setVisibility(View.GONE);
AppHelper.showShortToast(context, getString(R.string.failed_msg));
}
});
}
AppHelper.noInternetWarning(context, binding.getRoot());
}
private void loadAllPosts(int pageNumber) {
if (NetworkChangeReceiver.isNetworkConnected()) {
if (pageNumber == AppConstants.PAGE_NUMBER) {
binding.contentView.primaryRecycler.setVisibility(View.GONE);
binding.contentView.emptyListLayout.setVisibility(View.GONE);
binding.contentView.storyShimmerView.shimmerView.setVisibility(View.VISIBLE);
}
HashMap<String, String> allPostsMap = ApiRequests.buildAllPosts(pageNumber);
ApiClient.getInstance().getApiInterface().getPosts(allPostsMap).enqueue(new Callback<List<PostModel>>() {
@Override
public void onResponse(@NonNull Call<List<PostModel>> call, @NonNull Response<List<PostModel>> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
if (response.body().size() > 0) {
canLoadMore = true;
postList.addAll(response.body());
postListAdapter.notifyDataSetChanged();
binding.contentView.primaryRecycler.setVisibility(View.VISIBLE);
binding.contentView.storyShimmerView.shimmerView.setVisibility(View.GONE);
} else {
if (postList.size() == 0) {
binding.contentView.emptyListLayout.removeAllViews();
binding.contentView.emptyListLayout.addView(setEmptyLayout(StoryTemplateActivity.this, getString(R.string.no_data)));
binding.contentView.emptyListLayout.setVisibility(View.VISIBLE);
binding.contentView.storyShimmerView.shimmerView.setVisibility(View.GONE);
binding.contentView.primaryRecycler.setVisibility(View.GONE);
}
canLoadMore = false;
}
isDataLoading = false;
binding.contentView.progressBar.setVisibility(View.GONE);
}
} else {
if (response.code() == AppConstants.EMPTY_RESULT) {
canLoadMore = false;
binding.contentView.progressBar.setVisibility(View.GONE);
} else {
AppHelper.showShortToast(context, getString(R.string.failed_msg));
}
}
}
@Override
public void onFailure(@NonNull Call<List<PostModel>> call, @NonNull Throwable t) {
binding.contentView.storyShimmerView.shimmerView.setVisibility(View.GONE);
AppHelper.showShortToast(context, getString(R.string.failed_msg));
}
});
}
AppHelper.noInternetWarning(context, binding.getRoot());
}
private NestedScrollView.OnScrollChangeListener onNestedScrollChange() {
return new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView scrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollY > 0) {
if (!scrollView.canScrollVertically(NestedScrollView.FOCUS_DOWN)) {
if (canLoadMore && !isDataLoading) {
isDataLoading = true;
binding.contentView.progressBar.setVisibility(View.VISIBLE);
pageNumber += 1;
loadAllPosts(pageNumber);
}
}
}
}
};
}
}
|
Markdown
|
UTF-8
| 914 | 2.8125 | 3 |
[] |
no_license
|
# DHI-clone
DHI was an app which my college used in my first year engineering . I was always curious to make like that of my own . Now I was studying Django, I thought of giving a shot.
In this application, people can normally signup and by default they will be logged in as student , if one needs to upgrade status to teacher it can done by opening a private link,
here I've kept '/upgrade' which can be changed later
Teacher can create class inside the app, and students to join, Once students have joined teachers gets to mark attendance and even edit pervious attendance details, and see attendance report of all the students at once which shows how much percentage of attendance they have.
Teachers can also Enter/Edit marks , for the student View, they get the option to join class or see their marks report , where it summarize their marks obtained in all the registered course.
Software Used:
Django 3.2
|
C#
|
UTF-8
| 1,139 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
using Domain.Entitties.Library;
using Domain.Interfaces;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Application.Services.LibraryService.EditionFeatures.Commands
{
public class CreateEdition
{
public record Command(Edition Edition) : IRequest<Response>;
public record Response(bool Successed, string Message);
public class Handler : IRequestHandler<Command, Response>
{
private readonly IRepository<Edition> _editionRepository;
public Handler(IRepository<Edition> editionRepository)
{
_editionRepository = editionRepository;
}
public async Task<Response> Handle(Command request, CancellationToken cancellationToken)
{
string id = Guid.NewGuid().ToString();
request.Edition.Id = id;
await _editionRepository.CreateAsync(request.Edition);
return new Response(true, $"Издание было добавлено, id - {id}");
}
}
}
}
|
C
|
UTF-8
| 487 | 2.78125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <door.h>
int
main(int argc, const char *argv)
{
int fd;
door_arg_t door_arg = {0};
fd = open(DOOR_FILE, O_RDONLY);
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
if (door_call(fd, &door_arg) == -1) {
perror("door_call");
close(fd);
return EXIT_FAILURE;
}
printf("door_arg.rsize is %d\n", door_arg.rsize);
if (door_arg.rsize != sizeof(int))
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
|
Python
|
UTF-8
| 540 | 3.453125 | 3 |
[] |
no_license
|
"""
This file just shows if we have to compare 2 objects based on their field values
how we could override the equals method for the Object within the class of the object.
here the method to override would be :
1) __eq__ for the equals method (==)
2) __ne__ for not equals (!=)
3) __lt__ for less than (<)
4) __gt__ for greater than (>)
5) __le__ for less than or equal to (<=)
6) __ge__ for greater than or equal to (>=)
** IMPORTANT ** Always use "isinstance(object,class)" method to verify if the object is same type of the class
"""
|
JavaScript
|
UTF-8
| 554 | 2.9375 | 3 |
[] |
no_license
|
/**
* Represents a user role
*/
class UserRole {
/**
* Creates a new instance of UserRole
* @param {number} id role identifier
* @param {string} label role label used for display
*/
constructor(id, label) {
this.id = id;
this.label = label;
}
}
/**
*
* Registers every role a user can be assigned to
*/
const UserRoles = Object.freeze({
SUPER_ADMIN: new UserRole(0, 'Super Admin'),
AGENT: new UserRole(1, 'Agent'),
USER: new UserRole(2, 'Utilisateur'),
});
module.exports = UserRoles;
|
Java
|
UTF-8
| 2,514 | 3.90625 | 4 |
[] |
no_license
|
package facebookCoding;
/**
* Write a function to tell if two line segments intersect or not
* @author shirleyyoung
*http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
*http://shirleyisnotageek.blogspot.com/2015/02/determine-if-two-line-segments-intersect.html
*/
public class IntersectionOfTwoLineSegments {
/**
* check if two line segments pq and rs intersect with each other
* @param p
* @param q
* @param r
* @param s
* @return
*/
public static boolean hasIntersection(Point p, Point q, Point r, Point s) {
if (p == null || q == null || r == null || s == null)
throw new NullPointerException("Null points!");
if (p.equals(q) || r.equals(s))
throw new IllegalArgumentException("Not a line!");
int ori1 = orientation(p, q, r);
int ori2 = orientation(p, q, s);
int ori3 = orientation(r, s, p);
int ori4 = orientation(r, s, q);
if (ori1 != ori2 && ori3 != ori4)
return true;
if (ori1 == 0 && isOnSegment(p, q, r))
return true;
if (ori2 == 0 && isOnSegment(p, q, s))
return true;
if (ori3 == 0 && isOnSegment(r, s, p))
return true;
if (ori4 == 0 && isOnSegment(r, s, q))
return true;
return false;
}
/**
* check if point r is on line segment pq
* @param p
* @param q
* @param r
*/
private static boolean isOnSegment(Point p, Point q, Point r) {
return r.x <= Math.max(p.x, q.x) && r.x >= Math.min(p.x, q.x)
&& r.y <= Math.max(p.y, q.y) && r.y >= Math.min(p.y, q.y);
}
/**
* return the orientation of the triplet
* 0: parallel
* 1: clockwise
* 2: counterclockwise
* cross product
* http://en.wikipedia.org/wiki/Cross_product
* pq & pr
* @param p
* @param q
* @param r
* @return
*/
private static int orientation(Point p, Point q, Point r) {
double orientation = (p.x - q.x) * (p.y - r.y) - (p.y - q.y) * (p.x - r.x);
if (orientation == 0)
return 0;
return orientation > 0 ? 1 : 2;
}
public static void main(String[] args) {
System.out.println(hasIntersection(new Point(1, 4), new Point(2, 3), new Point(0, 2), new Point(3, 1)));
System.out.println(hasIntersection(new Point(0, 0), new Point(1, 1), new Point(2, 1), new Point(3, 1)));
System.out.println(hasIntersection(new Point(-1, 4), new Point(-2, 3), new Point(2, 1), new Point(0, 0)));
System.out.println(hasIntersection(new Point(1, 2), new Point(8, 9), new Point(3, 1), new Point(4, 6)));
System.out.println(hasIntersection(new Point(0, 0), new Point(0, 5), new Point(0, 2), new Point(0, -1)));
}
}
|
Markdown
|
UTF-8
| 5,381 | 2.78125 | 3 |
[] |
no_license
|
iRobot Interview Project
========================
A command-line application that leverages the [Food2Fork API](https://www.food2fork.com/about/api) in order to find the most popular recipe based on ingredients the user specifies.
See the [Take Home Assignment](./docs/take-home-assignment.md) doc for the original assignment text.
**Table of Contents**
- [iRobot Interview Project](#irobot-interview-project)
- [What You'll Need](#what-youll-need)
- [Quick Start](#quick-start)
- [Obtain the Source Code](#obtain-the-source-code)
- [Using the application](#using-the-application)
- [Development](#development)
- [Testing](#testing)
- [Coverage](#coverage)
- [Sensitive Data](#sensitive-data)
- [Unaddressed Considerations / Known Problems](#unaddressed-considerations--known-problems)
# What You'll Need
* Python 2.7+
* Pipenv
* Pipenv can be easily installed using `pip` with this command:
```bash
pip install pipenv
```
* A [Food2Fork](https://www.food2fork.com) account, which gives you a free API Key
# Quick Start
## Obtain the Source Code
```bash
git clone https://github.com/ceosion/irobot-interview-project.git
cd ./irobot-interview-project/
```
## Using the application
This application is a command-line interface and so you will need to use it from one. Bash is recommended, and the instructions here are written with Bash in mind.
```bash
pipenv install
pipenv run food_finder --f2f_api_key "enter-your-API-key-here" "ingredient 1" "ingredient 2" ...
```
Display the built-in help using:
```bash
pipenv run food_finder --help
```
Your Food2Fork API Key may also be placed in a file so you don't have to specify it as an argument to the program. See the [Sensitive Data](#sensitive-data) section for more details.
## Development
This project was developed using [Visual Studio Code](https://code.visualstudio.com). `start-vscode` scripts have been provided which will launch Visual Studio Code (VS Code) in an isolated environment separate from any existing user installation(s). The first step is to ensure you have the needed software (see the [What You'll Need](#what-youll-need) section above). Then you can execute the following commands:
```bash
pipenv install --dev
./start-vscode.sh
```
When launching for the first time, you should proceed to install all of the workspace's recommended extensions, as they have been selected specifically for use with this project.
## Testing
Unit tests leverage the [pytest](https://docs.pytest.org/en/latest/) framework. They can be ran after the steps in [Development](##development) with the following:
```bash
pipenv run pytest -s
```
or with:
```bash
pipenv run test
```
## Coverage
Code coverage can be calculated using:
```bash
pipenv run pytest --cov=food_finder test/
```
See https://docs.pytest.org/en/latest/usage.html for additional information.
# Sensitive Data
The `./secrets` directory should be used to store local files containing any sensitive data. The entire `./secrets/` directory should be excluded from Git, so nothing in this directory should be committed to source control.
The `./secrets/f2f_api_key` file may be used to specify your Food2Fork API key. This file is *optional*, but may be used by the app in different circumstances, if provided.
# Unaddressed Considerations / Known Problems
The following is a list of problems or nuances that apply to this application, which may be fixed in the future if desired:
* The Free-tier of the Food2Fork API is limited to 50 requests per day, and the application has not been tested for when this happens.
* The code does nothing specific to handle this, and hasn't been tested when this case occurs. With that said, the code does check for a 200 (Success) HTTP status code and should enter a failure path assuming Food2Fork sets this code to something other than 200.
* Sensitive data is allowed in the `./secrets/` directory, which is excluded from Git via the `.gitignore` file. This works, but could still make some folks uncomfortable because a slip-up while modifying `.gitignore` or failure to keep sensitive files isolated within `./secrets/` could leak sensitive data.
* A trivial refactoring could be done to move all sensitive files out of the applciation's project directory entirely, thus increasing the degree of separation between sensitive and non-sensitive files. (e.g. move `./secrets/` to `../food_finder_secrets/`)
* The data in `./secrets/` is not shared with the team in an defined way, at the moment. There are many ways to accomplish this, but one possible way is to archive and encrypt the sensitive files and actually commit the encrypted archive to Git. This is especially useful when sharing things like SSL certs and other non-user-specific sensitive files (i.e. not just a single API key file, which is specific to a user anyway). Then, the only thing that needs to be shared with team members is the password used to encrypt the sensitive data archive. (`git-crypt` and other tools can also be used to accomplish similar results.)
* At least one of the tests requires a valid API key and access to the actual Food2Fork API in order to pass.
* This makes automated testing more difficult. The API could be mocked in order to provide an isolated/offline environment for the test to run without the need for a real API key or the real Food2Fork API.
|
Python
|
UTF-8
| 1,012 | 3.796875 | 4 |
[] |
no_license
|
#!/usr/bin/env python
# encoding: utf-8
"""
用list模拟堆栈
"""
from stack_interface import BaseStack
class Stack(BaseStack) :
def __init__(self) :
"""
init a stack with []
"""
self.stack = []
def push(self,item) :
"""
push an item into stack.
"""
self.stack.append(item)
def top(self) :
"""
visite the top elements of stack.
"""
index = len(self.stack)-1
item = self.stack[index]
return item
def pop(self) :
"""
pop the top elements of stack.
"""
index = len(self.stack)-1
item = self.stack[index]
self.stack = self.stack[:index]
return item
def empty(self) :
"""
if the stack is empty ,return True,else return False
"""
length = len(self.stack)
return length == 0
def size(self) :
"""
return the size of stack
"""
return len(self.stack)
|
C#
|
UTF-8
| 8,408 | 2.765625 | 3 |
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace TcBlackCLI
{
/// <summary>
/// Builds a TwinCAT project using the devenv.
/// </summary>
public class TcProjectBuilder
{
private readonly string projectPath;
private readonly string slnPath;
private readonly string devenvPath;
protected string BuildLogFile { get; set; } = "build.log";
public TcProjectBuilder(string projectOrTcPouPath)
{
projectPath = GetParentPath(projectOrTcPouPath, ".plcproj");
slnPath = GetParentPath(projectOrTcPouPath, ".sln");
string vsVersion = GetVsVersion(slnPath);
devenvPath = GetDevEnvPath(vsVersion);
}
/// <summary>
/// Searched through the current and its parent paths for the first occurence
/// of a file with given extension
/// </summary>
/// <param name="extension">The extension to look for.</param>
/// <returns>Path to the directory with given extension.</returns>
private static string GetParentPath(string startingPath, string extension)
{
string path = "";
string parentPath = Path.GetDirectoryName(startingPath);
string exceptionMessage = (
$"Unable to find a {extension} file in any of the "
+ $"parent folders of {startingPath}."
);
while (true)
{
try
{
IEnumerable<string> filesWithExtension = Directory.EnumerateFiles(
parentPath, $"*{extension}"
).Where(
x => x.Substring(x.Length - extension.Length) == extension
);
path = filesWithExtension.Single();
break;
}
catch (Exception ex) when (
ex is DirectoryNotFoundException || ex is ArgumentException
)
{
throw new FileNotFoundException(exceptionMessage);
}
catch (InvalidOperationException)
{
}
try
{
parentPath = Directory.GetParent(parentPath).ToString();
}
catch (NullReferenceException)
{
throw new FileNotFoundException(exceptionMessage);
}
}
return path;
}
/// <summary>
/// Return the Visual Studio version from the solution file.
/// </summary>
/// <param name="slnPath">Path the solution file.</param>
/// <returns>Major and minor version number of Visual Studio.</returns>
private static string GetVsVersion(string slnPath)
{
string file;
try
{
file = File.ReadAllText(slnPath);
}
catch (ArgumentException)
{
return "";
}
string pattern = @"^VisualStudioVersion\s+=\s+(?<version>\d+\.\d+)";
Match match = Regex.Match(
file, pattern, RegexOptions.Multiline
);
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return "";
}
}
/// <summary>
/// Return the path to devenv.com of the given Visual Studio version.
/// </summary>
/// <param name="vsVersion">
/// Visual Studio version to get the devenv.com path of.
/// </param>
/// <returns>
/// The path to devenv.com of the given Visual Studio version.
/// </returns>
private static string GetDevEnvPath(string vsVersion)
{
RegistryKey rkey = Registry.LocalMachine
.OpenSubKey(
@"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7", false
);
try
{
return Path.Combine(
rkey.GetValue(vsVersion).ToString(),
"Common7",
"IDE",
"devenv.com"
);
}
catch (NullReferenceException)
{
return "";
}
}
/// <summary>
/// Build the project file.
/// </summary>
public TcProjectBuilder Build(bool verbose)
{
string currentDirectory = Directory.GetCurrentDirectory();
string buildScript = Path.Combine(
currentDirectory, "BuildTwinCatProject.bat"
);
ExecuteCommand(
$"{buildScript} \"{devenvPath}\" \"{slnPath}\" \"{projectPath}\"",
verbose
);
string buildLog = File.ReadAllText(BuildLogFile);
if (BuildFailed(buildLog))
{
throw new ProjectBuildFailedException();
}
return this;
}
/// <summary>
/// Reads the last line from the build.log file to see if the build failed.
/// </summary>
/// <param name="buildLog">The </param>
public static bool BuildFailed(string buildLog)
{
string pattern =
@"(?:========== Build: )(\d+)(?:[a-z \-,]*)(\d+)(?:[a-z \-,]*)";
MatchCollection matches = Regex.Matches(buildLog, pattern);
if (matches.Count > 0)
{
var lastMatch = matches[matches.Count - 1];
int buildsFailed = Convert.ToInt16(lastMatch.Groups[2].Value);
return buildsFailed != 0;
}
return false;
}
/// <summary>
/// Get the hash of the compiled project. Hash doesn't change when whitespaces
/// are adjusted or comments are added/removed.
/// </summary>
public string Hash {
get
{
if (projectPath.Length == 0)
{
return "";
}
try
{
string projectDirectory = Path.GetDirectoryName(projectPath);
string compileDirectory = Path.Combine(
projectDirectory, "_CompileInfo"
);
string latestCompileInfo = new DirectoryInfo(compileDirectory)
.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.First()
.Name;
return Path.GetFileNameWithoutExtension(latestCompileInfo);
}
catch (DirectoryNotFoundException)
{
return "";
}
}
}
/// <summary>
/// Execute a command in the windown command prompt cmd.exe.
/// Source: https://stackoverflow.com/a/5519517/6329629
/// </summary>
/// <param name="command"></param>
protected virtual void ExecuteCommand(string command, bool verbose)
{
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command)
{
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
};
var process = Process.Start(processInfo);
if (verbose)
{
process.OutputDataReceived += (object sender, DataReceivedEventArgs e)
=> Console.WriteLine("output >> " + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e)
=> Console.WriteLine("error >> " + e.Data);
process.BeginErrorReadLine();
}
process.WaitForExit();
if (verbose)
{
Console.WriteLine("Exit code: {0}", process.ExitCode);
}
process.Close();
}
}
}
|
Java
|
UTF-8
| 2,832 | 1.8125 | 2 |
[] |
no_license
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package IFC2X3.impl;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import IFC2X3.IFC2X3Package;
import IFC2X3.IfcObjectTypeEnum;
import IFC2X3.IfcProxy;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ifc Proxy</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link IFC2X3.impl.IfcProxyImpl#getProxyType <em>Proxy Type</em>}</li>
* <li>{@link IFC2X3.impl.IfcProxyImpl#getTag <em>Tag</em>}</li>
* </ul>
* </p>
*
* @generated
*/
@XmlType(name = "IfcProxy")
@XmlRootElement(name = "IfcProxyElement")
public class IfcProxyImpl extends IfcProductImpl implements IfcProxy {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IfcProxyImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return IFC2X3Package.eINSTANCE.getIfcProxy();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getTag() {
return (String)eGet(IFC2X3Package.eINSTANCE.getIfcProxy_Tag(), true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTag(String newTag) {
eSet(IFC2X3Package.eINSTANCE.getIfcProxy_Tag(), newTag);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetTag() {
eUnset(IFC2X3Package.eINSTANCE.getIfcProxy_Tag());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetTag() {
return eIsSet(IFC2X3Package.eINSTANCE.getIfcProxy_Tag());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IfcObjectTypeEnum getProxyType() {
return (IfcObjectTypeEnum)eGet(IFC2X3Package.eINSTANCE.getIfcProxy_ProxyType(), true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setProxyType(IfcObjectTypeEnum newProxyType) {
eSet(IFC2X3Package.eINSTANCE.getIfcProxy_ProxyType(), newProxyType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetProxyType() {
eUnset(IFC2X3Package.eINSTANCE.getIfcProxy_ProxyType());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetProxyType() {
return eIsSet(IFC2X3Package.eINSTANCE.getIfcProxy_ProxyType());
}
} //IfcProxyImpl
|
Java
|
UTF-8
| 3,502 | 2.1875 | 2 |
[
"MIT"
] |
permissive
|
package me.calebjones.spacelaunchnow.astronauts.list;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.calebjones.spacelaunchnow.common.GlideApp;
import me.calebjones.spacelaunchnow.data.models.main.astronaut.Astronaut;
import me.spacelaunchnow.astronauts.R;
import me.spacelaunchnow.astronauts.R2;
import me.calebjones.spacelaunchnow.astronauts.detail.AstronautDetailsActivity;
public class AstronautRecyclerViewAdapter extends RecyclerView.Adapter<AstronautRecyclerViewAdapter.ViewHolder> {
private List<Astronaut> astronauts;
private Context context;
public AstronautRecyclerViewAdapter(Context context) {
astronauts = new ArrayList<>();
this.context = context;
}
public void addItems(List<Astronaut> astronauts) {
this.astronauts = astronauts;
this.notifyDataSetChanged();
}
public void clear() {
astronauts = new ArrayList<>();
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.astronaut_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = astronauts.get(position);
holder.astronautName.setText(holder.mItem.getName());
holder.astronautStatus.setText(holder.mItem.getStatus().getName());
String abbrev = "";
if (holder.mItem.getAgency() != null && holder.mItem.getAgency().getAbbrev() != null){
abbrev = holder.mItem.getAgency().getAbbrev();
}
holder.astronautNationality.setText(String.format("%s (%s)",
holder.mItem.getNationality(), abbrev));
GlideApp.with(context)
.load(holder.mItem.getProfileImageThumbnail())
.placeholder(R.drawable.placeholder)
.circleCrop()
.into(holder.astronautImage);
}
@Override
public int getItemCount() {
return astronauts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R2.id.astronaut_image)
ImageView astronautImage;
@BindView(R2.id.astronaut_name)
TextView astronautName;
@BindView(R2.id.astronaut_nationality)
TextView astronautNationality;
@BindView(R2.id.astronaut_status)
TextView astronautStatus;
@BindView(R2.id.rootview)
ConstraintLayout rootview;
public Astronaut mItem;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
@OnClick(R2.id.rootview)
void onClick(View v){
Astronaut astronaut = astronauts.get(getAdapterPosition());
Intent exploreIntent = new Intent(context, AstronautDetailsActivity.class);
exploreIntent.putExtra("astronautId", astronaut.getId());
context.startActivity(exploreIntent);
}
}
}
|
Java
|
UTF-8
| 1,344 | 4.34375 | 4 |
[] |
no_license
|
package com.company;
/*
CountDownLatch is described in section 5.5.1. The constructor initializes a counter to the
provided value. The countdown() method decrements the counter (by 1); the await()
method returns when the counter is no longer positive
*/
public class CountDownLatch {
//simple counting variable
private volatile int counter;
//basic constructor
public CountDownLatch (int counter){
this.counter = counter;
}
//when a thread calls countdown, this decrements counter,
//then if the counter has reach 0, it notifies all threads waiting
public synchronized void countdown()
{
counter--;
if (counter == 0)
{
System.out.println("Thread " + Thread.currentThread().getId() + " notifying other threads.");
notifyAll();
}
return;
}
//This is probably as basic as a synchronized waiting method can get.
//When a thread calls await, it just waits until the counter is at 0.
public synchronized void await()
{
while(counter > 0){
try {
System.out.println("Thread " + Thread.currentThread().getId() + " waiting.");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return;
}
}
|
JavaScript
|
UTF-8
| 406 | 3.546875 | 4 |
[] |
no_license
|
const binarySearch = (Arr, target) => {
const len = Arr.length;
let lo = 0;
let hi = len - 1;
while ( lo <= hi ) {
let mid = Math.floor((lo + hi) / 2);
if ( Arr[mid] === target ) {
return mid;
}
if ( target < Arr[mid] ) {
hi = mid - 1;
}
if ( target > Arr[mid] ) {
lo = mid + 1;
}
}
return -1;
};
console.log(binarySearch([-2, -1, 3, 4, 5], -1));
|
Java
|
UTF-8
| 1,820 | 3.484375 | 3 |
[] |
no_license
|
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FizzBuzzGameTest {
@Test
@DisplayName("Converter should return the same number when the number is not divisible by 5 or 10 or 15")
void test1(){
//given
FizzBuzzGame fizzBuzzGame = new FizzBuzzGame();
//when
String result1 = fizzBuzzGame.convert(1);
String result2 = fizzBuzzGame.convert(11);
//then
assertEquals("1", result1);
assertEquals("11", result2);
}
@Test
@DisplayName("Converter should return 'Fizz' word when the number is divisible by 3")
void test2(){
//given
FizzBuzzGame fizzBuzzGame = new FizzBuzzGame();
//when
String result1 = fizzBuzzGame.convert(3);
String string2 = fizzBuzzGame.convert(9);
//then
assertEquals("Fizz", result1);
assertEquals("Fizz", string2);
}
@Test
@DisplayName("Converter should return 'Buzz' word when the number is divisible by 5")
void test3(){
//given
FizzBuzzGame fizzBuzzGame = new FizzBuzzGame();
//when
String result1 = fizzBuzzGame.convert(5);
String string2 = fizzBuzzGame.convert(20);
//then
assertEquals("Buzz", result1);
assertEquals("Buzz", string2);
}
@Test
@DisplayName("Converter should return 'FizzBuzz' word when the number is divisible by 3 and 5")
void test4(){
//given
FizzBuzzGame fizzBuzzGame = new FizzBuzzGame();
//when
String result1 = fizzBuzzGame.convert(15);
String string2 = fizzBuzzGame.convert(30);
//then
assertEquals("FizzBuzz", result1);
assertEquals("FizzBuzz", string2);
}
}
|
C#
|
UTF-8
| 927 | 2.515625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace ThoughtWorks.CruiseControl.Remote.Messages
{
/// <summary>
/// A message for passing a message to the server.
/// </summary>
[XmlRoot("messageMessage")]
[Serializable]
public class MessageRequest
: ProjectRequest
{
private string message;
private Message.MessageKind kind ;
/// <summary>
/// The message being passed.
/// </summary>
[XmlElement("message")]
public string Message
{
get { return message; }
set { message = value; }
}
/// <summary>
/// The kind of message
/// </summary>
[XmlElement("kind")]
public Message.MessageKind Kind
{
get { return kind; }
set { kind = value; }
}
}
}
|
Java
|
UTF-8
| 3,814 | 2.15625 | 2 |
[
"MIT"
] |
permissive
|
/**
* Copyright 2017, 2018, 2019, 2020 Stephen Powis https://github.com/Crim/pardot-java-client
*
* 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.
*/
package com.darksci.pardot.api.parser.listmembership;
import com.darksci.pardot.api.parser.BaseResponseParserTest;
import com.darksci.pardot.api.response.list.ListMembership;
import com.darksci.pardot.api.response.listmembership.ListMembershipQueryResponse;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ListMembershipQueryResponseParserTest extends BaseResponseParserTest {
private static final Logger logger = LoggerFactory.getLogger(ListMembershipQueryResponseParserTest.class);
/**
* Validates we can parse a List query with multiple Lists response A-OK.
*/
@Test
public void testMultipleCampaigns() throws IOException {
final String input = readFile("listMembershipQuery.xml");
final ListMembershipQueryResponse.Result response = new ListMembershipQueryResponseParser().parseResponse(input);
logger.info("Result: {}", response);
assertNotNull("Should not be null", response);
assertEquals("Should have 2 results", 2, (int) response.getTotalResults());
assertEquals("Should have 2 results", 2, response.getListMemberships().size());
// Validate first list
ListMembership listMembership = response.getListMemberships().get(0);
assertEquals("Has correct id", 158902003L, (long) listMembership.getId());
assertEquals("Has correct listId", 33173L, (long) listMembership.getListId());
assertEquals("Has correct prospectId", 59135263L, (long) listMembership.getProspectId());
assertEquals("Has correct optedOut", false, listMembership.getOptedOut());
assertEquals("Has correct createdAt", "2017-08-11T22:03:37.000", listMembership.getCreatedAt().toString());
assertEquals("Has correct updatedAt", "2017-08-11T22:03:37.000", listMembership.getUpdatedAt().toString());
// Validate 2nd list
listMembership = response.getListMemberships().get(1);
assertEquals("Has correct id", 170293539L, (long) listMembership.getId());
assertEquals("Has correct listId", 33173L, (long) listMembership.getListId());
assertEquals("Has correct prospectId", 59156811L, (long) listMembership.getProspectId());
assertEquals("Has correct optedOut", true, listMembership.getOptedOut());
assertEquals("Has correct createdAt", "2017-11-11T07:40:44.000", listMembership.getCreatedAt().toString());
assertEquals("Has correct updatedAt", "2017-11-11T07:40:44.000", listMembership.getUpdatedAt().toString());
}
}
|
Java
|
UTF-8
| 1,962 | 2.4375 | 2 |
[] |
no_license
|
package cn.example.wang.slideslipedemo;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import cn.we.swipe.helper.WeSwipe;
import cn.we.swipe.helper.WeSwipeHelper;
/**
* 1.侧滑的距离可控。
* 2.统一CallBack里面的接口。
* 3.下拉刷新的问题。
* 4.侧滑打开下点击事件
* 5.没打开侧滑也能点击到下面的删除按钮。
* 6.一个阀值的管理。
*
*
*/
public class MainActivity extends AppCompatActivity implements RecAdapter.DeletedItemListener{
RecyclerView recyclerView;
private RecAdapter recAdapter;
public static void start(Context context){
Intent intent = new Intent(context,MainActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initData() {
List<String> list = new ArrayList<>();
for (int i = 0; i < 30; i++) {
list.add("Item " +i);
}
recAdapter.setList(list);
}
private void initView() {
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recAdapter = new RecAdapter(this);
recAdapter.setDelectedItemListener(this);
recyclerView.setAdapter(recAdapter);
//设置WeSwipe。
WeSwipe weSwipe = WeSwipe.attach(recyclerView).setType(WeSwipeHelper.SWIPE_ITEM_TYPE_FLOWING);
recAdapter.setWeSwipe(weSwipe);
}
@Override
public void deleted(int position) {
recAdapter.removeDataByPosition(position);
}
}
|
C++
|
UTF-8
| 641 | 3.828125 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
string &appendToString(string &OrigString, string PreString, string PostString)
{
/*
this doesn't work:
OrigString.insert(OrigString.begin(), PreString);
*/
/*
this works:
OrigString.insert(OrigString.begin(), PreString.begin(), PreString.end());
*/
OrigString.insert(0, PreString);
OrigString.append(PostString);
return OrigString;
}
int main()
{
string Name = "Peter";
string PreName = "Mr.";
string PostName = "Jr.";
string WholeName = appendToString(Name, PreName+" ", " "+PostName);
cout << WholeName << endl;
return 0;
}
|
Java
|
UTF-8
| 358 | 2.296875 | 2 |
[] |
no_license
|
public class Dummy {
void sendRequest(Connection conn) throws SQLException {
String sql = "Select T.tripId,T.customerId,T.driverId,P.totalFare From tripHistory T join payment P ON T.tripId>P.tripId where P.totalFare>="+Fare+" AND (T.date<="+CurrentDate") order by P.totalFare DESC";
Statement stmt = conn.createStatement();
stmt.executeQuery(sql);
}
}
|
Java
|
UTF-8
| 344 | 1.875 | 2 |
[] |
no_license
|
package com.example.turistickaagencija.repository;
import com.example.turistickaagencija.model.Destinacija;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface DestinacijaRepository extends JpaRepository<Destinacija,Long> {
List<Destinacija> findAllByDrzhavaContaining(String name);
}
|
Markdown
|
UTF-8
| 4,093 | 3.859375 | 4 |
[
"MIT"
] |
permissive
|
# 哈希表
面试中能用 hashMap 解答的题目往往会有更优的解法,但是 hashMap 是一种最容易想到也最容易实现的解法。
## [每日温度](https://leetcode-cn.com/problems/daily-temperatures/)
> 请根据每日 **气温** 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
>
> 例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
>
> 提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
>
```typescript
function dailyTemperatures(T: number[]): number[] {
const n = T.length;
if (!n) return [];
const res = Array(T.length).fill(0);
const stack: number[] = [];
for (let i = n - 1; i >= 0; i--) {
while (stack.length && T[i] >= T[stack[stack.length - 1]]) {
stack.pop();
}
if (stack.length) res[i] = stack[stack.length - 1] - i;
stack.push(i);
}
return res;
}
```
## [字母异位词分组](https://leetcode-cn.com/problems/group-anagrams/)
> 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
```typescript
function groupAnagrams(strs: string[]): string[][] {
const sortStrs = new Set<string>(
strs.map((value) => value.split("").sort().join(""))
);
const hashMap: { [key: string]: string[] } = {};
sortStrs.forEach((value) => {
hashMap[value] = [];
});
for (const str of strs) {
const sortStr = str.split("").sort().join("");
hashMap[sortStr].push(str);
}
return Object.values(hashMap);
}
```
## [和为 K 的子数组](https://leetcode-cn.com/problems/subarray-sum-equals-k/)
> 给定一个整数数组和一个整数 K,你需要找到该数组中和为 K 的连续子数组的个数
```typescript
function subarraySum(nums: number[], k: number): number {
const mp = new Map<number, number>();
mp.set(0, 1);
let count = 0,
pre = 0;
for (const x of nums) {
pre += x;
if (mp.has(pre - k)) count += mp.get(pre - k)!;
if (mp.has(pre)) mp.set(pre, mp.get(pre)! + 1);
else mp.set(pre, 1);
}
return count;
}
```
## [前 K 个高频元素](https://leetcode-cn.com/problems/top-k-frequent-elements/)
> 给定一个非空数组,返回其中出现频率前 K 高的元素。
```typescript
function topKFrequent(nums: number[], k: number): number[] {
const hashMap: { [key: number]: number } = {};
for (const num of nums) {
hashMap[num] = hashMap[num] ?? 0;
hashMap[num]++;
}
return Object.entries(hashMap)
.sort(([__, a], [_, b]) => b - a)
.map(([key]) => +key)
.slice(0, k);
}
```
## [计算质数](https://leetcode-cn.com/problems/count-primes/)
> 统计所有小于非负整数 n 的质数的数量
```typescript
function countPrimes(n: number): number {
const isPrimes = Array(n).fill(true)
for(let i = 2; i * i < n; i++) {
if(isPrimes[i]) {
for(let j = i * i; j < n; j += i) {
isPrimes[j] = false
}
}
}
let count = 0
for(let i = 2; i < n; i++) {
if(isPrimes[i]) count++
}
return count
}
```
## [无重复字符串的最长子串](https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/)
> 给定一个字符串,请你找出其中不含有重复字符的 **最长子串** 的长度。
```typescript
function lengthOfLongestSubstring(s: string): number {
const n = s.length;
let sub = "";
let res = "";
for (let i = 0; i < n; i++) {
if (!sub) {
sub += s[i];
if (i === n - 1 && res.length < sub.length) res = sub;
} else {
if (!sub.includes(s[i])) {
sub += s[i];
if (i === n - 1 && res.length < sub.length) res = sub;
} else {
if (sub.length > res.length) res = sub;
sub = sub.substr(sub.indexOf(s[i]) + 1) + s[i];
}
}
}
return res.length;
}
```
|
C#
|
UTF-8
| 943 | 3.140625 | 3 |
[] |
no_license
|
using System;
using App.Extensions;
using App.LSP.Good.Models;
namespace App.LSP.Good
{
public static class LspGoodExample
{
private static readonly Type BaseType = typeof(Fruit);
// We can replace Fruit BaseType with any SubType Apple or
// Orange without altering the correctness of the program
public static void Run()
{
ConsoleColor.Green.WriteLine(nameof(LspGoodExample));
// Call with SubType Apple which print green as color for an apple fruit
PrintColor(new Apple());
// Call with SubType Orange which print orange as color for an orange fruit
PrintColor(new Orange());
}
private static void PrintColor(Fruit fruit)
{
var typeName = BaseType.Name;
var typeColor = fruit.GetColor();
Console.WriteLine($"Color for {typeName} is {typeColor}");
}
}
}
|
Markdown
|
UTF-8
| 37,957 | 2.78125 | 3 |
[] |
no_license
|
# Interfaz Gráfica en Java
Curso propuesto por el grupo de trabajo Semana de Ingenio y Diseño (**SID**) de la Universidad Distrital Francisco Jose de Caldas.
## Monitor
**Cristian Felipe Patiño Cáceres** - Estudiante de Ingeniería de Sistemás de la Universidad Distrital Francisco Jose de Caldas
# Clase 7
## Objetivos
* Comprender el concepto de reutilización de componentes gráficos y las ventajas que provee al desarrollar interfaces gráficas de usuario.
* Reconocer los diferentes enfoques que existen para realizar reutilización de componentes gráficos y en que casos es mejor utilizar alguno de ellos.
* Identificar en que momento es necesario realizar la reutilización de componentes y que enfoque es acorde según la situación presentada.
# Antes de Comenzar
### **Actualización de Imágenes en recursos**
Para continuar con la lección deberá actualizar la carpeta **resources/images** ya que se han agregado nuevas imágenes. Estas las puede descargar en este mismo repositorio entrando a la carpeta **Clase7** seguido de **resources/images**. Es recomendable seguir la misma estructura que se realiza dentro de esta carpeta ya que se estarán creando subcarpetas:
<div align='center'>
<img src='https://i.imgur.com/ftFp3Gn.png'>
<p>Divisiones dentro de la carpeta Images de Resources</p>
</div>
### **Ajustes en el servicio Recursos Service**
En el servicio **RecursosService** se crea un nuevo objeto decorador **Border**:
**Declaración:**
```javascript
private Border borderGris;
```
**Ejemplificación:**
```javascript
// Dentro del método crearBordes
borderGris = BorderFactory.createLineBorder(Color.LIGHT_GRAY, 2, true);
```
**Método get:**
```javascript
public Border getBorderGris(){ return borderGris; }
```
Por ultimo se crea un objeto decorador tipo **Color**:
**Declaración:**
```javascript
// Al inicio del servicio
private Color colorGrisClaro;
```
**Ejemplificación:**
```javascript
// Dentro del método crearColores
colorGrisClaro = new Color(249, 246, 249);
```
**Método get:**
```javascript
public Color getColorGrisClaro(){ return colorGrisClaro; }
```
***Nota:** Recordar que estos objetos decoradores dentro del servicio **RecursosService** se crean pensando en que serán utilizados en varias partes del proyecto, si ese no es el caso entonces el objeto decorador debe ser creado unicamente en el componente gráfico donde se necesita.*
### **Ajustes en Vista Principal**
En esta sesión se va a construir el componente **inicio** y se quiere que una vez se abra la vista principal este sea visible. Para esto se realizan unas pequeñas modificaciones en la clase **VistaPrincipalComponent**:
* **Ejemplificación de componente dentro de constructor**
Anteriormente se había configurado la ejemplificación del componente **inicio** dentro del método **mostrarComponente** en su respectivo caso en el Switch, sin embargo ahora se realiza su ejemplificación dentro del constructor para que pueda ser visualizado una ez se abre la ventana principal:
```javascript
// Dentro del constructor
this.inicioComponent = new InicioComponent();
```
* **Incorporación de componente dentro de constructor**
Para que el componente sea visible inmediatamente al abrir la ventana principal se debe incorporar el componente al panel **pPrincipal** dentro del constructor:
```javascript
// Dentro del constructor
vistaPrincipalTemplate.getPPrincipal()
.add(inicioComponent.getInicioTemplate());
```
* **Ajuste en el caso de incorporación del componente inicio**
Como el componente **inicio** ya fue ejemplificado dentro del constructor ya se tiene la certeza de que este ya fue creado previamente por lo que tener el condicional preguntando esto es algo redundante, es por esto que en el caso de incorporación del componente **inicio** basta con indicar que se va a incorporar al panel **pPrincipal** solamente:
```javascript
case "Inicio":
vistaPrincipalTemplate.getPPrincipal()
.add(inicioComponent.getInicioTemplate());
break;
```
### **Recordatorio**
Recordando el recorrido, se tiene la vista principal con una integración de varios componentes gráficos, además existe un control de visibilidad mediante la navegación de componentes. También se reviso la importancia de controlar la creación de objetos de los componentes gráficos.
<div align='center'>
<img src='https://i.imgur.com/2F1rXG7.png'>
<p>Vista Principal y Single-Page App</p>
</div>
# Reutilización de componentes gráficos
En esta sesión se explicará un tema de gran importancia, la reutilización de componentes y en que casos realizar esta practica:
* Reutilizacion de componentes gráficos.
* Enfoque de reutilización por incorporación.
* Enfoque de reutilización por posicionamiento.
# Reutilización de componentes gráficos
En la sesión pasada se creo una serie de componentes que pueden ser visible una vez el usuario lo solicite oprimiendo los botones ubicados en el componente **navegacionUsuario**. Algunos de estos componentes gráficos son: **inicio**, **perfil**, **amigos**, **productos** y **configuraciones**. Sin embargo, estos componentes aun no tienen nada más que un color de fondo.
Esta lección esta enfocada en la construcción el componente gráfico **inicio** haciendo uso de la reutilizacion de otros componentes que se crearán para este propósito.
## Concepto de reutilización
Para entender mejor el concepto de reutilización se va a mostrar primero cual es el diseño deseado al crear el componente gráfico **inicio** a continuación:
<div align='center'>
<img src='https://i.imgur.com/6LcW9rb.png'>
<p>Resultado de construcción de componente gráfico Inicio</p>
</div>
Es posible notar con un pequeño grado de detalle que el componente gráfico **inicio** esta conformado por varios objetos gráficos, tiene algunos paneles, bastantes imágenes, títulos y párrafos. Sin embargo, aumentando el grado de detalle es posible notar que existen ciertas particularidades con los objetos gráficos que conforman al componente gráfico **inicio**.
Primero se observa la parte superior del componente, se puede ver que hay tres paneles y los tres contienen los mismos objetos gráficos, cada uno de ellos tiene una imágen en la parte superior, seguido de un título y un párrafo justificado en la parte inferior.
<div align='center'>
<img src='https://i.imgur.com/Ii5Dopv.png'>
<p>Paneles de la parte superior con un mismo patrón en sus objetos gráficos</p>
</div>
Ahora se observa la parte inferior, se puede notar que hay un panel principal que contiene un conjunto de paneles que están distribuidos uniformemente a lo largo del panel contenedor. Observe que cada uno de estos paneles cuentan con un patrón, todos tienen un borde gris que los separa unos de otros, un icono centrado, seguido de un título y un párrafo centrados de igual forma.
<div align='center'>
<img src='https://i.imgur.com/mZFvPJ4.png'>
<p>Paneles de la parte inferior con un mismo patrón en sus objetos gráficos</p>
</div>
Lo único que cambia en ambos casos es el contenido en cada panel, pero la estructura interna es idéntica. Otro factor importante es que dicha similitud en estructura está conformada por distintos objetos gráficos y aquí está la **clave para usar un componente reutilizable**, para crear un componente que se pueda reutilizar en varias partes este debe estar conformado por varios objetos gráficos que cumplen un patrón de estructura que se desea repetir en la interfaz gráfica.
No vale la pena construir un componente que repita el patrón de un simple objeto gráfico (piense en los botones del componente **navegacionUsuario**), aunque estos botones se conforman de varios elementos (Imágenes y texto) y cumplen con un patron de estructura que se repite, es solo un botón que puede ser construido con el servicio **ObjGraficosService**. Por otro lado si hay un patrón que se repite y vincula a varios objetos gráficos si vale la pena revisar si realizar la reutilización de componentes gráficos.
El componente **inicio** podría escribirse completamente en la clase **Template** sin depender de ningún otro componente para su construcción y no está mal, es una forma de hacerlo. Sin embargo, imagine todo el código repetido que va existir dentro de esta clase para mostrar 3 paneles que tienen una misma estructura y otros 6 paneles que tienen esta misma condición. Realmente es muy tedioso y llenará la clase **Template** de un extenso código que afectara en la forma en que se analiza, mantiene y se entiende el código.
Una alternativa a esto es la construcción de componentes gráficos que encapsulen el código de este patrón de estructura identificado y se pueda hacer uso de él, las veces que sean necesarias. A continuación se muestra a ver como hacer esto posible.
Cuando un componente depende de otros componentes para su construcción se crea una relación de **Componente Padre** Y **Componente Hijo** (No tiene que ver con el concepto de herencia) ya que el componente padre contiene al componente hijo. Es común encontrar este tipo de relaciónes, un ejemplo que ya se ha realizado es entre el componente **VistaPrincipal** y los componente **inicio**, **barraTitulo**, **navegacionUsuario** etc. Ahora el mismo componente **inicio** tendrá otros componentes para su construcción y estos serán los hijos de **inicio**, esta construcción estará basada en la reutilización de componentes que a su vez se basará en dos enfoques principales.
## Construcción base del componente inicio
Se va a construir a continuación la base del componente **inicio**, en su clase **Template** se va a crear unos paneles que sirven de soporte a los componentes a construir y además se crearán ciertos objetos más:
* Primero se obtienen los servicios **ObjGraficosService** y **RecursosService** que serán necesarios en la construcción de algunos objetos gráficos:
**Declaración:**
```javascript
private ObjGraficosService sObjGraficos;
private RecursosService sRecursos;
```
**Obtención de servicios:**
```javascript
// Dentro del Constructor
sObjGraficos = ObjGraficosService.getService();
sRecursos = RecursosService.getService();
```
* Se proporciona de otro color de fondo al componente:
```javascript
// Dentro del Constructor
this.setBackground(sRecursos.getColorGrisClaro());
```
* Se van a crear paneles base para contener los objetos gráficos que serán visibles en la ventana principal además de un Label que representará el título principal en el panel inferior (**pAcciones**):
**Declaración:**
```javascript
// Declaración Objetos Gráficos
private JPanel pMision, pVision, pNosotros, pAcciones;
private JLabel lAcciones;
```
**Método crearJPanels:**
```javascript
public void crearJPanels(){
this.pMision = sObjGraficos.construirJPanel(20, 15, 256, 230, Color.WHITE, null);
this.add(pMision);
this.pVision = sObjGraficos.construirJPanel(296, 15, 256, 230, Color.WHITE, null);
this.add(pVision);
this.pNosotros = sObjGraficos.construirJPanel(572, 15, 256, 230, Color.WHITE, null);
this.add(pNosotros);
this.pAcciones = sObjGraficos.construirJPanel(20, 260, 810, 330, Color.WHITE, null);
this.add(pAcciones);
}
```
**llamada del método dentro del constructor:**
```javascript
// Dentro del constructor
this.crearJPanels();
```
Cuando se ejecuta la aplicación y se oprime el botón que llama al componente **inicio**, la interfaz gráfica luce de la siguiente manera:
<div align='center'>
<img src='https://i.imgur.com/JsPvkP3.png'>
<p>Componente inicio con sus paneles base adicionados</p>
</div>
Para este componente se va a realizar la modularización un tanto distinta, esta vez no se va a separar la creación por tipo de objetos gráficos, **se va a separar la creación por el contenido en cada panel**, con una pequeña excepción en la creación de objetos decoradores, por ahora solo se declaran los métodos:
```javascript
public void crearObjetosDecoradores(){
}
```
```javascript
public void crearContenidoPMision(){
}
```
```javascript
public void crearContenidoPVision(){
}
```
```javascript
public void crearContenidoPNosotros(){
}
```
```javascript
public void crearContenidoPAcciones(){
}
```
# Enfoque de reutilización por incorporación.
Este enfoque se caracteriza por que cuando se crea el **componente hijo**, este va a ser incorporado a un panel que exista previamente en el **componente padre**, por ejemplo, ya fueron creados los paneles **pMision, pVision, pNosotros** en el componente padre. Esto quiere decir que no es necesario preocuparse con la locación del componente hijo, esta ya se configuro cuando se crearon los paneles de incorporación, lo que si se debe tener pendiente es que tanto el panel de incorporación como el componente hijo tengan el mismo tamaño y de esa forma no habrán problemás de posicionamiento. Este enfoque ya se ha realizado en sesiones anteriores, donde **navegaciónUsuario** y **barraTitulo** fueron incorporados a unos paneles creados previamente en **vistaPrincipal**.
Se crea un nuevo component que encapsule la estructura del contenido de los paneles superiores, este componente será llamado **tarjeta**, para esto se crea su respectivo paquete y clases dentro del directorio **components**:
<div align='center'>
<img src='https://i.imgur.com/KwTONrs.png'>
<p>Componente tarjeta creado dentro del paquete components</p>
</div>
* Se empieza con la clase **Component** y como de costumbre se realizan los siguientes pasos:
Como el componente no tiene botones no se va a necesitar la implementación de ninguna interfaz.
```javascript
public class TarjetaComponent{
}
```
Se crea un objeto de la clase **Template** y se realiza la inyección enviándose por argumento la referencia de si mismo con la palabra **this**:
**Declaración:**
```javascript
private TarjetaTemplate tarjetaTemplate;
```
**Ejemplificación:**
```javascript
// Dentro del constructor
tarjetaTemplate = new TarjetaTemplate(this);
```
Se crea el método **get** de su respectivo **Template**:
```javascript
public TarjetaTemplate getTarjetaTemplate(){
return tarjetaTemplate;
}
```
* Ahora se codifica la clase **Template**:
Esta al representar las características gráficas del componente debe heredar de un **JPanel**:
```javascript
public class TarjetaTemplate extends JPanel{
}
```
Como se ha realizado anteriormente, se va a obtener los servicios **ObjGraficosService** y **RecursosService** además de obtener por constructor la inyección de la clase **Component**:
**Ejemplificación**
```javascript
private TarjetaComponent tarjetaComponent;
private ObjGraficosService sObjGraficos;
private RecursosService sRecursos;
```
**Obtención de servicios e inyección:**
```javascript
public TarjetaTemplate(TarjetaComponent tarjetaComponent){
this.tarjetaComponent = tarjetaComponent;
sObjGraficos= ObjGraficosService.getService();
sRecursos =
RecursosService.getService();
}
```
Ahora se configuran las propiedades gráficas al componente:
```javascript
// Dentro del constructor
this.setSize(256, 230);
this.setBackground(Color.white);
this.setLayout(null);
this.setVisible(true);
```
Note que el tamaño del componente debe ser igual panel al cual será incorporado. En este caso en los paneles **pMision, pVision y pNosotros**.
<div align='center'>
<img src='https://i.imgur.com/hGLhBrc.png'>
<p>Mismo tamaño del componente con los paneles a reemplazar</p>
</div>
Este componente va a contener:
* Label que contiene la imagen.
* Label que contiene el título.
* Label que contiene el párrafo.
* Objeto decorador iDimAux para redimensionar imágenes.
**declaración:**
```javascript
// Declaración Objetos Gráficos
private JLabel lTitulo, lImagen, lParrafo;
// Declaración Objetos Decoradores
private ImageIcon iDimAux;
```
Como el contenido del título, el contenido del párrafo y la imagen van a ser las propiedades que serán dinámicas (que van a variar). Estas deben ser recibidas de alguno modo. Se podría tomar el enfoque de **setters y getters**, sin embargo, se opta por recibir estos parámetros desde el constructor:
<div align='center'>
<img src='https://i.imgur.com/NrO68Ne.png'>
<p>Parámetros recibidos en el constructor</p>
</div>
Se puede notar que ahora el constructor a parte de recibir la **inyección de dependencia** recibe también ahora:
* Un **String** que representa el título.
* Un **ImageIcon** que representa la imágen del componente.
* Un **String** que representa el párrafo.
***Nota:** Como el código de este componente es corto y para evitar la declaración de más atributos en la clase se van a crear los objetos gráficos dentro del constructor:*
**Imagen:**
```javascript
// Dentro del constructor
iDimAux = new ImageIcon(
iImagen.getImage()
.getScaledInstance(246, 110, Image.SCALE_AREA_AVERAGING)
);
lImagen = sObjGraficos.construirJLabel(
null,
5, 5, 246, 110,
sRecursos.getCMano(),
iDimAux,
null, null, null, null,
"c"
);
this.add(lImagen);
```
Se puede observar que la imágen que redimensiona la variable auxiliar **iDimAux** es la que fue recibida por parámetro el constructor.
**título:**
```javascript
// Dentro del constructor
this.lTitulo = sObjGraficos.construirJLabel(
titulo,
15, 120, 180, 30,
null, null,
sRecursos.getFontTitulo(),
null,
sRecursos.getColorPrincipal(),
null,
"l"
);
this.add(lTitulo);
```
Se puede observar que el texto que se envía para la construcción del Label es el String **título** recibido por parámetro desde el constructor.
**Párrafo:**
```javascript
// Dentro del constructor
lParrafo = sObjGraficos.construirJLabel(
"<html><div align='justify'>" + parrafo + "</div></html>",
20, 120, 206, 120,
null, null,
sRecursos.getFontLigera(),
null,
sRecursos.getColorGrisOscuro(),
null,
"c"
);
this.add(lParrafo);
```
Se puede observar que el texto que se envía para la construcción del Label es el String **parrafo** recibido por parámetro desde el constructor. También se puede observar que el párrafo está contenido dentro de etiquetas html. Esto se realiza para darle la estructura de texto justificado ya que es el componente quien se debe encargar de la estructura.
En teoría el componente esta listo, sin embargo, ahora el editor de texto indica que hay un error en la clase **Component** justamente en la ejemplificación de la clase **Template**, esto es debido a que ahora por constructor se están pidiendo más parámetros y como argumento solo se esta enviando la **inyección**.
<div align='center'>
<img src='https://i.imgur.com/P1JVTR5.png'>
<p>Error en clase Component ya que se piden más parámetros</p>
</div>
Para resolver esto se debe recibir por parámetro en el constructor de la clase **Component** los mismos parámetros (**título, Imagen, Párrafo**), para después pasarlos a su clase **Template**:
```javascript
public TarjetaComponent(String titulo, ImageIcon iImagen, String parrafo) {
tarjetaTemplate = new TarjetaTemplate(this, titulo, iImagen, parrafo);
}
```
El componente **Tarjeta** esta listo para ser incorporado, se debe hacer dicha incorporación en el componente **inicio**. En la clase **InicioTemplate** se van a declarar las imágenes necesarias para los componentes, luego se ejemplifican:
**Declaración:**
```javascript
private ImageIcon iTarjeta1, iTarjeta2, iTarjeta3;
```
**Ejemplificación:**
```javascript
// Dentro del método crearObjetosDecoradores
this.iTarjeta1 = new ImageIcon("clase7/resources/images/tarjetas/tarjeta1.jpg");
this.iTarjeta2 = new ImageIcon("clase7/resources/images/tarjetas/tarjeta2.jpg");
this.iTarjeta3 = new ImageIcon("clase7/resources/images/tarjetas/tarjeta3.jpg");
```
Note algo importante, aunque es el componente **tarjeta** el que va a mostrar las imágenes en pantalla estas van a ser creadas de su componente padre que es **inicio** en este caso. Ya que el componente **tarjeta** exige unas imágenes como parámetros y estas deben ser creadas previamente. Sin embargo el componente **Tarjeta** si se encarga de la redimensión en las imágenes.
Se va a realizar la incorporación de este componente primero en el método **crearContenidoPMision**, como este enfoque es **por medio de incorporación** lo que se debe realizar es adicionar el componente al panel que incorporará el componente gráfico:
* Se llama al panel en cuestión y se indica que se añadirá un objeto gráfico con el método **add**:
```javascript
public void crearContenidoPMision() {
this.pMision.add();
}
```
* Dentro de los paréntesis se puede crear una **Ejemplificación anónima** del componente:
```javascript
public void crearContenidoPMision() {
this.pMision.add(new TarjetaComponent());
}
```
* Sin embargo la clase **Component** pide por parámetros 3 cosas **(String título, ImageIcon imagen, String párrafo)** asi que se debe enviar por argumento lo que se pide:
```javascript
public void crearContenidoPMision() {
this.pMision.add(
new TarjetaComponent(
"Nuestra Misión",
iTarjeta1,
"Brindar cursos a la comunidad académica para" +
"complementar habilidades fuera del pensum común."
)
);
}
```
Hasta el momento la incorporación esta fallando y es que es necesario recordar que la clase **Component** no cuenta con características gráficas, es la clase **Template** la que las tiene asi que se debe obtener mediante el método **get** de la clase **Component**.
```javascript
public void crearContenidoPMision() {
this.pMision.add(
new TarjetaComponent(
"Nuestra Misión",
iTarjeta1,
"Brindar cursos a la comunidad académica para" +
"complementar habilidades fuera del pensum común."
).getTarjetaTemplate()
);
}
```
* Ahora el componente ha quedado incorporado, solo falta llamar al método **crearContenidoPMision** desde el constructor para que el contenido pueda ser visible:
```javascript
// Dentro del constructor
this.crearObjetosDecoradores();
this.crearContenidoPMision();
```
***Nota:** También faltaba llamar al método **crearObjetosDecoradores** dentro del constructor.*
Si se corre la aplicación y se oprime el botón que muestra el componente **inicio** la interfaz se ve asi:
<div align='center'>
<img src='https://i.imgur.com/CuhXYvJ.png'>
<p>Interfaz gráfica con la llamada del componente tarjeta 1 vez</p>
</div>
Ahora se realiza el mismo proceso con los otros 2 paneles, claramente el contenido será distinto asi que los argumentos enviados al componente también lo serán:
**Panel pVision:**
```javascript
public void crearContenidoPVision() {
this.pVision.add(
new TarjetaComponent(
"Nuestra Visión",
iTarjeta2,
"Brindar cursos académicos al 80% de los" +
"estudiantes de ingeniería de Sistemás."
).getTarjetaTemplate()
);
}
```
**Panel pNosotros:**
```javascript
public void crearContenidoPNosotros() {
this.pNosotros.add(
new TarjetaComponent(
"Sobre Nosotros",
iTarjeta3,
"Somos un grupo de trabajo de la Universidad" +
"distrital Francisco jose de Caldas."
).getTarjetaTemplate()
);
}
```
**llamada de métodos dentro del constructor**
```javascript
// Dentro del constructor
this.crearContenidoPVision();
this.crearContenidoPNosotros();
```
Ejecutando la aplicación nuevamente ahora la interfaz se ve asi:
<div align='center'>
<img src='https://i.imgur.com/0wADZUn.png'>
<p>Componente inicio con la reutilización del componente Tarjeta</p>
</div>
# Enfoque de reutilización por Posicionamiento.
A menudo existen casos donde se requiere un componente reutilizable una n cantidad de veces y no se tiene con certeza el numero de veces que se va a reutilizar, un ejemplo puede ser una lista de películas obtenidas externamente donde cada película va a ser un componente hijo, sin embargo podría ser un listado largo de películas que se va a mostrar y no se sabe cuantas sean exactamente. Por lo que crear paneles base para incorporar cada componente hijo es una mala idea, una buena opción es traer el componente gráfico hijo y posicionarlo dentro de un espacio dado.
Este enfoque se caracteriza por que cuando se cree el **componente hijo**, este no va se va incorporar a ningún objeto gráfico directamente sino que va a ocupar un espacio dentro del **componente padre**. Por lo que ahora se debe tener presente la locación del componente aunque por otro lado ya no es una preocupación que el componente hijo tenga el mismo tamaño de algún objeto gráfico previo ya que al no incorporar nada esta libre de tener un tamaño independiente.
Se crea un nuevo component que encapsule la creación del contenido de los paneles inferiores, este componente será llamado **accion**, para esto se crea su respectivo paquete y clases dentro del directorio **components**:
<div align='center'>
<img src='https://i.imgur.com/hiWKgTt.png'>
<p>Componente accion creado dentro del paquete components</p>
</div>
* Se empieza con la clase **Component** y como de costumbre se realizan los siguientes pasos:
Como el componente no tiene botones no va a necesitar la implementación de ninguna interfaz.
```javascript
public class AccionComponent {
}
```
Se crea un objeto de la clase **Template** y se realiza la inyección enviándose por argumento la referencia de si mismo con la palabra **this**:
**Declaración:**
```javascript
private AccionTemplate accionTemplate;
```
**Ejemplificación:**
```javascript
// Dentro del constructor
this.accionTemplate= new AccionTemplate(this);
```
Se crea su método **get** de su respectivo **Template**:
```javascript
public AccionTemplate getAccionTemplate(){
return accionTemplate;
}
```
* Ahora se va a codificar la clase **Template**:
Esta al representar las características gráficas del componente debe heredar de un **JPanel**:
```javascript
public class AccionTemplate extends JPanel {
}
```
Se obtienen los servicios **ObjGraficosService** y **RecursosService** además de obtener por constructor la inyección de la clase **Component**:
**Ejemplificación**
```javascript
private AccionComponent accionComponent;
private ObjGraficosService sObjGraficos;
private RecursosService sRecursos;
```
**Obtención de servicios e inyección:**
```javascript
public AccionTemplate(AccionComponent accionComponent){
this.accionComponent = accionComponent;
sObjGraficos= ObjGraficosService.getService();
sRecursos = RecursosService.getService();
}
```
Ahora se configuran las propiedades gráficas al componente:
```javascript
// Dentro del constructor
this.setSize(250, 125);
this.setBackground(Color.WHITE);
this.setBorder(sRecursos.getBorderGris());
this.setLayout(null);
this.setVisible(true);
```
Note que el componente tiene un borde que se llama del servicio **RecursosService** para poder diferenciarse. Además el tamaño del componente no tiene la restricción de ser igual a ningún objeto gráfico del componente padre ya que se usará un enfoque de **posicionamiento**.
Este componente va a contener:
* Label que contiene el título.
* Label que contiene el icono.
* Label que contiene el párrafo.
* Objeto decorador iDimAux para redimensionar imágenes.
**declaración:**
```javascript
// Declaración Objetos Gráficos
private JLabel lImagen, lTitulo, lParrafo;
// Declaración Objetos Decoradores
private ImageIcon iDimAux;
```
Como el contenido del título, el contenido del párrafo y el icono van a ser las propiedades que serán dinámicas (que van a variar). Estas deben ser recibidas de alguno modo. Nuevamente se opta por recibir estos parámetros desde el constructor:
<div align='center'>
<img src='https://i.imgur.com/f1oncLQ.png'>
<p>Parámetros recibidos en el constructor</p>
</div>
Se puede notar que ahora el constructor a parte de recibir la **inyección de dependencia** recibe también ahora:
* Un **ImageIcon** que representa el icono del componente.
* Un **String** que representa el título.
* Un **String** que representa el párrafo.
***Nota:** Como el código de este componente también es corto y para evitar la declaración de más atributos en la clase se crean los objetos gráficos dentro del constructor:*
**Imagen:**
```javascript
// Dentro del constructor
iDimAux = new ImageIcon(
imagen.getImage()
.getScaledInstance(45, 45, Image.SCALE_AREA_AVERAGING)
);
this.lImagen = sObjGraficos.construirJLabel(
null,
(250 - 60) / 2, 5, 45, 45,
null,
iDimAux,
null, null, null, null,
"c"
);
this.add(lImagen);
```
Se puede observar que la imagen que redimensiona la variable auxiliar **iDimAux** es la que fue recibida por parámetro en el constructor.
**título:**
```javascript
// Dentro del constructor
this.lTitulo = sObjGraficos.construirJLabel(
titulo,
(250 - 220) / 2, 50, 220, 30,
null, null,
sRecursos.getFontTitulo(),
null,
sRecursos.getColorGrisOscuro(),
null,
"c"
);
this.add(lTitulo);
```
Se puede observar que el texto que se envía para la construcción del Label es el String **título** recibido como parámetro desde el constructor.
**Párrafo:**
```javascript
// Dentro del constructor
this.lParrafo = sObjGraficos.construirJLabel(
"<html><div align='center'>" + parrafo + "</div></html>",
(250 - 230) / 2, 75, 230, 50,
null, null,
sRecursos.getFontLigera(),
null,
sRecursos.getColorGrisOscuro(),
null,
"c"
);
this.add(lParrafo);
```
Se puede observar que el texto que se envía para la construcción del Label es el String **parrafo** recibido como parámetro desde el constructor. Además el parrafo esta envuelto en etiquetas HTML que le proporcionan una estructura al texto de estar centrado. Recordar que este componente se debe encargar de encapsular aspectos de estructura como este.
Como se vio con el anterior componente **tarjeta** la clase **Component** ahora debe ser modificada ya que la clase **Template** exige nuevos parámetros que deben ser enviados como argumento.
Para resolver esto se debe recibir por parámetro en el constructor de la clase **Component** los mismos parámetros (**Imagen, titulo, Párrafo**), para después pasárselos a su clase **Template**:
```javascript
public AccionComponent(ImageIcon imagen, String titulo, String parrafo) {
this.accionTemplate= new AccionTemplate(this, imagen, titulo, parrafo);
}
```
El componente gráfico **Accion** esta listo para usarse ahora se explica de que manera se reutilizará desde su componente padre.
En la clase **InicioTemplate** primero se van a declarar las imágenes necesarias para los componentes, luego se ejemplifican:
**Declaración:**
```javascript
private ImageIcon iClase, iPantalla, iIdea, iCelular, iEstadistica, iDireccion;
```
**Ejemplificación:**
```javascript
// Dentro del método crearObjetosDecoradores
this.iClase = new ImageIcon("clase7/resources/images/acciones/clases.png");
this.iPantalla = new ImageIcon("clase7/resources/images/acciones/pantalla.png");
this.iCelular = new ImageIcon("clase7/resources/images/acciones/celular.png");
this.iIdea = new ImageIcon("clase7/resources/images/acciones/ideas.png");
this.iEstadistica = new ImageIcon("clase7/resources/images/acciones/estadisticas.png");
this.iDireccion = new ImageIcon("clase7/resources/images/acciones/direccion.png");
```
* Previo a la llamada del componente gráfico **Accion** se va crear un título al panel inferior **pAcciones**:
```javascript
public void crearContenidoPAcciones(){
this.lAcciones = sObjGraficos.construirJLabel(
"Nuestros Servicios",
10, 10, 160, 30,
null, null,
sRecursos.getFontTitulo(),
null,
sRecursos.getColorPrincipal(),
null,
"c"
);
this.pAcciones.add(lAcciones);
}
```
Como esta vez no se va a incorporar ningún componente no es posible crear la ejemplificación de forma anónima, es necesario crear variables de objeto para representar al componente hijo:
```javascript
// Dentro del método crearContenidoPAcciones
AccionTemplate p1= new AccionComponent();
```
Se debe recordar que:
* la clase **AccionComponent** exige el envío de algunos argumentos.
* Se debe obtener la clase **Template** del componente ya que el objeto que se debe agregar debe contener características gráficas y se declaro inicialmente como un **ActionTemplate**.
```javascript
// COMPONENTE ACCIÓN 1 ------------------------------------
AccionTemplate p1= new AccionComponent(
iClase,
"Clases",
"Clases a la comunidad que complementan el pensum."
).getAccionTemplate();
```
***Nota:** Puede observar que se crea un objeto tipo Template del Componente Accion pero se esta igualando a la ejemplificación de la clase Component, esto claramente generaría error pero esto se hace por que inmediatamente en la ejemplificación se va a traer la clase template a traves del método **getAccionTemplate()** y asi la igualdad será cierta.*
Ya se tiene un objeto del componente hijo dentro de **inicio** pero aun se debe indicar la posición y además realizar la agregación en el panel inferior **pAcciones**:
```javascript
p1.setLocation(15, 50);
this.pAcciones.add(p1);
```
Para probar el método se llama en el constructor:
```javascript
// Dentro del constructor
this.crearContenidoPAcciones();
```
Al ejecutar la aplicación, la interfaz luce asi:
<div align='center'>
<img src='https://i.imgur.com/2pxfy1H.png'>
<p>Componente inicio con la agregación de un componente accion</p>
</div>
este proceso se repite varias veces más:
```javascript
// COMPONENTE ACCIÓN 2 ------------------------------------
AccionTemplate p2 = new AccionComponent(
iPantalla,
"Clases Virtuales",
"Cursos virtuales como medio de enseñanza."
).getAccionTemplate();
p2.setLocation(30 + p2.getWidth(), 50);
this.pAcciones.add(p2);
// COMPONENTE ACCIÓN 3 ------------------------------------
AccionTemplate p3 = new AccionComponent(
iIdea,
"Generación de ideas",
"Desarrollo de ideas con tecnologías actuales."
).getAccionTemplate();
p3.setLocation(45 + p3.getWidth() * 2, 50);
this.pAcciones.add(p3);
// COMPONENTE ACCIÓN 4 ------------------------------------
AccionTemplate p4 = new AccionComponent(
iCelular,
"Notificaciones",
"Notificaión el estado de tus cursos y actividades."
).getAccionTemplate();
p4.setLocation(15, 65 + p4.getHeight());
this.pAcciones.add(p4);
// COMPONENTE ACCIÓN 5 ------------------------------------
AccionTemplate p5 = new AccionComponent(
iEstadistica,
"Estadisticas",
"Gestión de participación en nuestros cursos."
).getAccionTemplate();
p5.setLocation(30 + p5.getWidth(), 65 + p5.getHeight());
this.pAcciones.add(p5);
// COMPONENTE ACCIÓN 6 ------------------------------------
AccionTemplate p6 = new AccionComponent(
iDireccion,
"Dirección",
"Damos direcciónamiento a nuestros estudiantes."
).getAccionTemplate();
p6.setLocation(45 + p6.getWidth() * 2, 65 + p6.getHeight());
this.pAcciones.add(p6);
```
Corriendo la aplicación es posible ver el resultado propuesto desde el comienzo:
<div align='center'>
<img src='https://i.imgur.com/6LcW9rb.png'>
<p>Vista Principal con el panel inicio terminado</p>
</div>
El anterior enfoque queda un tanto desperdiciado debido a que se esta repitiendo el código las 6 veces que fue reutilizado el componente. Si existieran 10 acciones más se tendría que volver a repetir este código y no es para nada optimo hacer esto. Un enfoque apropiado es crear un arreglo de objetos donde cada objeto contenga la información necesaria (Imagen, titulo, Párrafo) y recorrerlo mediante un ciclo para que de esta forma el código solo sea escrito una sola vez y asi ahorrar lineas de código. Sin embargo este enfoque se discutirá en futuras clases cuando se hable acerca de **Servicios Lógicos**.
## Pequeña Reflexión de la reutilización
El concepto de reutilización es quizás el factor que más le da reconocimiento al uso de los componentes gráficos, de esta forma no solo se tiene un código mucho más entendible y organizado. También se esta encapsulado la estructura de una plantilla dentro de un componente lo cual dota del código de una estructuración y modularizacion alta. Incluso el concepto de reutilización puede ser tan util que si por ejemplo en algún otro componente como puede ser **Productos** se quiere usar uno de estos componentes reutilizables perfectamente se puede hacer haciendo de su función mucho más amplia para el proyecto.
Otro criterio que podría tomarse a favor es el dinamismo hacia el tamaño y posición de objetos gráficos dentro de la estructura de un componente altamente reutilizable, piense por un momento, que tal si se quiere usar de nuevo el componente **tarjeta** en otra parte del proyecto pero esta vez con más altura o menos ancho, podría entonces el componente pedir el ancho y alto por parámetros para incorporarlo o posicionarlo en la interfaz. Además se puede usar un posicionamiento y tamaño de los objetos gráficos internos basado en **porcentajes** para que no se pierda la estructura deseada.
Este posicionamiento basado en **porcentajes** es un enfoque que mejora el enfoque de posicionamiento en pixeles pero esta basado en el. En este curso no veremos dicho enfoque pero se menciona para motivar a la investigación al estudiante de este curso.
# Resultado
Si has llegado hasta aquí **!Felicidades!** se ha aprendido a realizar reutilización de componentes gráficos, cuando utilizarse y los diferentes enfoques de **incorporación y posicionamiento** para encapsular la estructura de una plantilla en un componente que se puede usar varias veces.
En la siguiente clase se revisará de nuevo el tema de **Eventos** y esta vez vamos a estudiar los eventos del **Mouse**.
# Actividad
Utilizar reutilización de componentes en sus proyectos para encapsular la lógica y estructura de una plantilla que pueda utilizarse varias veces.
|
SQL
|
UTF-8
| 2,266 | 4.5 | 4 |
[] |
no_license
|
-- List for each employee: employee number, last name, first name, gender, salary
SELECT e.emp_no, e.last_name, e.first_name, e.sex, s.salary
FROM employees as e
JOIN salaries as s ON e.emp_no = s.emp_no
ORDER BY e.emp_no;
-- List first name, last name, and hire date for employees who were hired in 1986
SELECT e.first_name, e.last_name, e.hire_date
FROM employees as e
WHERE DATE_PART('year', hire_date) = 1986
ORDER BY e.emp_no
-- List the manager of each department with the following information: department number,
-- department name, the manager's employee number, last name, first name
SELECT dm.dept_no, d.dept_name, e.emp_no, e.last_name, e.first_name
FROM dept_manager as dm
JOIN departments as d ON dm.dept_no = d.dept_no
JOIN employees as e on dm.emp_no = e.emp_no;
-- List the department of each employee with the following information: employee number,
-- last name, first name, and department name
SELECT e.emp_no, e.last_name, e.first_name, d.dept_name
FROM employees AS e
JOIN dept_emp as de ON e.emp_no = de.emp_no
JOIN departments as d ON de.dept_no = d.dept_no
-- List first name, last name, and sex for employees whose first name is "Hercules" and
-- last names begin with "B"
SELECT e.first_name, e.last_name, e.sex
FROM employees AS e
WHERE e.first_name = 'Hercules' AND e.last_name LIKE 'B%';
-- List all employees in the Sales department, including their employee number, last name,
-- first name, and department name
SELECT e.emp_no, e.last_name, e.first_name, d.dept_name
FROM employees AS e
JOIN dept_emp as de ON e.emp_no = de.emp_no
JOIN departments as d ON de.dept_no = d.dept_no
WHERE d.dept_name='Sales';
-- List all employees in the Sales and Development departments, including their
-- employee number, last name, first name, and department name
SELECT e.emp_no, e.last_name, e.first_name, d.dept_name
FROM employees AS e
JOIN dept_emp as de ON e.emp_no = de.emp_no
JOIN departments as d ON de.dept_no = d.dept_no
WHERE d.dept_name='Sales' OR d.dept_name='Development';
-- In descending order, list the frequency count of employee last names, i.e., how many
-- employees share each last name
SELECT e.last_name, COUNT(*) AS freq_count
FROM employees AS e
GROUP BY e.last_name
ORDER BY freq_count DESC;
|
Python
|
UTF-8
| 206 | 2.640625 | 3 |
[] |
no_license
|
# Link: https://edabit.com/challenge/YN9mNNc4mMPDxyhFf
def name_string(name):
return name+'Edabit'
print(name_string('Mubashir'))
print(name_string('Matt'))
print(name_string('python'))
|
JavaScript
|
UTF-8
| 874 | 2.90625 | 3 |
[] |
no_license
|
/**
* Advent of code solution
* @Andrew_Haine
*/
import fs from 'fs';
import chunk from 'chunk';
import { showAns, dump } from "../../utils/index.js";
const input = fs.readFileSync(new URL('input.txt', import.meta.url), "utf8");
const rucksacks = input.split("\n");
const groups = chunk(rucksacks, 3);
const letterToIndex = letter => {
let index = letter.toLowerCase().charCodeAt(0) - 96;
if (letter === letter.toUpperCase()) {
index += 26;
}
return index;
}
const groupBadges = groups.map(groupRucksacks => {
const commonItem = groupRucksacks[0].split('').filter(item => {
return groupRucksacks.every(groupRucksack => groupRucksack.includes(item));
});
return commonItem.at(0);
});
const totalPriorities = groupBadges.reduce((total, commonItem) => {
return total + letterToIndex(commonItem);
}, 0);
showAns(totalPriorities);
|
PHP
|
UTF-8
| 1,018 | 2.96875 | 3 |
[] |
no_license
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* This class define the main class for all db exceptions, support to put some data
* on the exception , for example a current value of a record.
* Esa clase define la excepcion base para errores en base de datos.
*
* @author Carlos Arana Reategui
* @version 1.00 , 15 JUL 2009
* @history Modificado 27 MAY 2011 , para TECHSOFT
*
*/
class TSLDbException extends TSLGenericException {
private $_data;
/**
* Constructor , soporte el tener alguna data
* que pueda servir para mayor informacion.
*
* @param string|null $message
* @param int $code
* @param mixed|null $data
*/
public function __construct($message = NULL, $code = 0,$data = NULL)
{
parent::__construct($message, $code);
$this->_data = $data;
}
/**
* Retorna la data contenida en la excepcion.
* @return Mixed
*/
public function getData() {
return $this->_data;
}
}
/**/
|
Java
|
UTF-8
| 2,723 | 2.3125 | 2 |
[] |
no_license
|
package com.sublimeprev.api.service;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sublimeprev.api.config.i18n.Messages;
import com.sublimeprev.api.config.i18n.ServiceException;
import com.sublimeprev.api.model.Mother;
import com.sublimeprev.api.model.ProcessMother;
import com.sublimeprev.api.repository.ProcessMotherRepository;
@Service
public class ProcessMotherService {
@Autowired
private ProcessMotherRepository repository;
@Autowired
private MotherService motherService;
public ProcessMother save(ProcessMother processMother, Long idMother) {
if(processMother.getId() == null) {
Mother mother = this.motherService.findById(idMother);
processMother.setMother(mother);
processMother.setDateStart(LocalDate.now());
}
return this.repository.save(processMother);
}
public ProcessMother findById(Long idAddresMother) {
return this.repository.findById(idAddresMother)
.orElseThrow(() -> new ServiceException("Mother not foud."));
}
public ProcessMother findByMother(Long idMother) {
Mother mother = this.motherService.findById(idMother);
return this.repository.findByMother(mother).orElseThrow(() -> new ServiceException("Mother not foud"));
}
public void logicalExclusion(Long id) {
if (!this.repository.findByIdAndNotDeleted(id).isPresent())
throw new ServiceException(Messages.record_not_found);
this.repository.softDelete(id);
}
public void restoreDeleted(Long id) {
if (!this.repository.findDeletedById(id).isPresent())
throw new ServiceException(Messages.record_not_found_at_recycle_bin);
this.repository.restoreDeleted(id);
}
public List<ProcessMother> findAllDeleted() {
return this.repository.findAllDeleted();
}
public List<ProcessMother> findByIds(Long[] ids) {
return this.repository.findAllById(Arrays.asList(ids));
}
public void permanentDestroy(Long id) {
if (!this.repository.findDeletedById(id).isPresent())
throw new ServiceException(Messages.record_not_found_at_recycle_bin);
this.repository.deleteById(id);
}
public boolean verifyAddresMother(Long idMother) {
Mother mother = this.motherService.findById(idMother);
Optional<ProcessMother> optionalMother = this.repository.findByMother(mother);
if (optionalMother.isPresent()) {
return true;
} else {
return false;
}
}
public ProcessMother findByCpfAndBirthdayMother(String cpf, String birthday) {
LocalDate birth = LocalDate.parse(birthday);
Mother mother = this.motherService.findByCpfAndBirthday(cpf, birth);
return this.findByMother(mother.getId());
}
}
|
C
|
UTF-8
| 1,945 | 2.640625 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_b.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfujimot <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/17 18:08:36 by lfujimot #+# #+# */
/* Updated: 2018/01/23 16:24:18 by lfujimot ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_checker.h"
static void ft_init(t_stack *stack, int *pivot)
{
*pivot = ft_find_pivot(&(stack)->b, stack->nb, stack);
ft_pushfront(&(stack)->p, *pivot);
}
static void ft_action(t_stack *stack, int action)
{
if (action == 1)
{
ft_pa(stack);
stack->naa++;
}
else if (action == 2)
ft_rb(stack);
else if (action == 3)
{
ft_pa(stack);
ft_ra(stack);
stack->sorted++;
}
}
static int ft_setaction(int tmpnb, int pivot, t_stk **stk)
{
if (ft_ismin(stk, tmpnb) == 1)
return (3);
else if (tmpnb > pivot)
return (1);
else
return (2);
}
void ft_b(t_stack *stack)
{
t_stk *tmp;
int pivot;
int action;
ft_init(stack, &pivot);
tmp = stack->b;
if (stack->nb == 4)
while (tmp && stack->nb > 3)
{
if (tmp->nb == ft_maxk(&(stack)->b))
{
ft_pa(stack);
return ;
}
tmp = tmp->next;
ft_rb(stack);
}
else
while (tmp && ft_haveabove(&(stack)->b, pivot) && stack->nb > 3)
{
action = ft_setaction(tmp->nb, pivot, &(stack)->b);
tmp = tmp->next;
ft_action(stack, action);
}
}
|
Markdown
|
UTF-8
| 13,075 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
---
title: "Enterprise Browser - Using the Android Headset as a Barcode Trigger"
summary: "What if... you want to use a Zebra's Android device mounted on an arm-wrist and you want to control the barcode scanner with a wired button? WT6000 is the obvious answer! But if your customer has already chosen the TC51 for other activities, we can help them using the headset connector."
date: 2018-07-12T18:00:48+02:00
draft: false
type: "post"
author: "Pietro F. Maggi"
tags: ["Android", "Enterprise Browser", "Zebra"]
---
What if...
you want to use a Zebra's Android device mounted on an arm-mount and you want to control the barcode scanner with a wired button?
WT6000 is the obvious answer!
But if your customer has already chosen the TC51 for other activities, we can help them using the headset connector.
## The Android headset connectors
Before Apple decided that we don't need anymore the 3.5mm headset connector on our phones, people started to look into it as a standard input interface for all the devices.
Android, being more open than its alternatives, published all the specification of this interface, explaining what can be done with it:
[Android Headset documentation](https://source.android.com/devices/accessories/headset/plug-headset-spec)

Here we're looking how we can intercept the `Button_A` in our application so that we can use it as a barcode trigger.
Looking through [some other documentation on the Android website](https://source.android.com/devices/accessories/headset/jack-headset-spec) we can see that the Android KeyCode we need to intercept is the `KEYCODE_MEDIA_PLAY_PAUSE`.
About the hardware, there're online some alternatives but we ended up building our own prototype:

## Enterprise Browser's KeyCapture API
As we wrote at the beginning, this particular customer was using a web application, so we decided to use Zebra's Enterprise Browser to integrate this headset based trigger with the existing web application.
Given that we've seen that the headset keys generate an Android KeyCode we can use [EB's KeyCapture API to intercept](https://techdocs.zebra.com/enterprise-browser/1-8/api/keycapture/) them.
### Building a POC demo with Enterprise Browser's KeyCapture API
First of all, we need to understand which KeyCode we get in EB to be able to intercept it. [As I wrote in a past post]({{ relref . "android_backbutton_and_eb.md" }}) we can use a very simple page to discover the right value we need.
Just create a new index.html file with the following content, and copy it to your device.
{{< highlight html "linenos=table" >}}
<!DOCTYPE html>
<html lang="en">
<META HTTP-Equiv="KeyCapture" Content="KeyValue:All; Dispatch:False; KeyEvent:url('JavaScript:console.log('Key Pressed: %s');')">
<head>
<meta charset="utf-8">
<title>Display KeyCode</title>
</head>
<body>
<H1>Press a key to see it's KeyCode</H1>
</body>
</html>
{{< / highlight >}}
We can then look into EB's logs or use Chrome's DevTools to see what our code is logging.
In my case, testing this on a TC56 running Android v7.1 Nougat. I get two different KeyCode: 228 and 79. We want both!

We can now build our PoC application, starting from the `index.html` page:
{{< highlight html "linenos=table" >}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Barcode scanning test</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Barcode scanning test</h1>
<input type="checkbox" id="scanner"/>
<label for="scanner" class="button" id="scannerLabel">Scanner Disabled</label>
<div id="barcode">
Barcode Data: <br>
Time:
</div>
<br>
<button class="quit">Exit</button>
<input type="text" value="type here">
<footer></footer>
<script src="ebapi-modules.js"></script>
<script src="app.js"></script>
</body>
</html>
{{< / highlight >}}
The accompanying style sheet is `style.css`:
{{< highlight css "linenos=table" >}}
* {
padding: 0;
margin: 0;
}
body {
text-align: center;
font-family: sans-serif;
}
h1 {
margin: .5em 0 1em;
}
#barcode {
margin: 1em auto 1em;
border-spacing: 0;
border-collapse: collapse;
}
button, .button {
padding: .8em 1.2em;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: .3em;
box-shadow: 0 1px 0 hsla(0, 0%, 100%, .7) inset, 0 .15em .1em -.1em rgba(0, 0, 0, .3);
background: linear-gradient(hsla(0, 0%, 100%, .3), hsla(0, 0%, 100%, 0)) hsl(80, 80%, 35%);
color: white;
text-shadow: 0 -.05em .05em rgba(0, 0, 0, .3);
font: inherit;
font-weight: bold;
outline: none;
cursor: pointer;
}
button:enabled:active,
.button:active,
input[type="checkbox"]:checked + label.button {
background-image: none;
box-shadow: 0 .1em .3em rgba(0, 0, 0, .5) inset;
}
button:disabled {
background-color: hsl(80, 20%, 40%);
cursor: not-allowed;
}
#scanner {
position: absolute;
clip: rect(0, 0, 0, 0);
}
{{< / highlight >}}
And we can then focus on the JavaScript code in the `app.js` file:
{{< highlight js "linenos=table" >}}
function $$(selector, container) {
return (container || document).querySelector(selector);
}
function fnScanReceived(params) {
if (params['data'] == "" || params['time'] == "") {
$$('#barcode').innerHTML = "Failed!";
return;
}
var displayStr = "Barcode Data: " + params['data'] + "<br>Time: " + params['time'];
$$("#barcode").innerHTML = displayStr + "<br>" + JSON.stringify(params);;
}
function keyCallback(params) {
console.log("this key has just been pressed!: " + params['keyValue']);
if (79 === params.keyValue) {
EB.Barcode.start();
}
}
(function() {
var buttons = {
quit: $$('button.quit'),
};
buttons.quit.addEventListener('click', function() {
EB.Application.quit();
});
EB.KeyCapture.captureKey(false, "228", keyCallback);
EB.KeyCapture.captureKey(false, "79", keyCallback);
$$('#scanner').addEventListener('change', function() {
if (this.checked) {
EB.Barcode.enable({ allDecoders: true }, fnScanReceived);
$$('#scannerLabel').innerHTML = "Scanner Enabled";
} else {
EB.Barcode.disable();
$$('#scannerLabel').innerHTML = "Scanner Disabled";
}
});
})();
{{< / highlight >}}
We can test this copying these files on the device. I usually prefer to work with EB's http server copying the files on the `/sdcard/www/` folder.
In EB's `Config.xml` I then use:
{{< highlight xml "linenos=table" >}}
<WebServer>
<Enabled VALUE="1"/>
<Port VALUE="8082"/>
<WebFolder VALUE="%PRIMARYDIR%/www/"/>
<Public VALUE="0"/>
</WebServer>
<General>
<Name value="HeadsetPoC"/>
<StartPage value="http://0.0.0.0:8082/demo1/index.html" name="HeadsetPoC"/>
</General>
{{< / highlight >}}
You can modify the following option to be able to debug the application using Chrome's DevTools [as explained in a previous post]({{ relref . "eb_modernization.md" }}).
{{< highlight xml "linenos=table" >}}
<DebugSetting>
<DebugModeEnable value="1"/>
</DebugSetting>
{{< / highlight >}}
[The full sample project is available as a ZIP archive](/assets/HeadsetPoC.zip).
## Working on an existing web application
As we wrote at the beginning, this customer wanted to have this headset trigger to work with an existing web application. Once we built the PoC and we knew that it was possible to use the headset connection as a barcode trigger we used [EB's DOM Injection](https://techdocs.zebra.com/enterprise-browser/1-8/guide/DOMinjection/) functionality to add these capabilities to the existing application.
This customization is really dependent on the existing application, what I can write here, is that you need to add to EB's `Config.xml` a `CustomDOMElements` element:
{{< highlight xml "linenos=table" >}}
<CustomDOMElements value="file://%INSTALLDIR%/mytags.txt"/>
{{< / highlight >}}
In this case we've the `mytags.txt` file in the same folder of the `Config.xml` file, usually `/sdcard/Android/data/com.symbol.enterprisebrowser/`, and we inject a single JavaScript in every page:
{{< highlight xml "linenos=table" >}}
<!--Sample tags file -->
<!--FILENAME: 'mytags.txt' -->
<!--DESC: 'tags' file for DOM Injection -->
<!--JavaScript section-->
<!--inject keycapture.js into all pages-->
<script type='text/javascript' src='file:///storage/emulated/0/Android/data/com.symbol.enterprisebrowser/keycapture.js' pages='*'/>
{{< / highlight >}}
The content of the `keycapture.js` file is:
{{< highlight js "linenos=table" >}}
console.log('KeyCapture Configured');
EB.KeyCapture.captureKey(false, "228", keyCallback);
EB.KeyCapture.captureKey(false, "79", keyCallback);
function keyCallback(params) {
console.log("this key has just been pressed!: " + params['keyValue']);
if (79 === params.keyValue) {
i = {
'intentType': 'broadcast',
'action': 'com.symbol.datawedge.api.ACTION_SOFTSCANTRIGGER',
'data': {
'com.symbol.datawedge.api.EXTRA_PARAMETER': 'START_SCANNING',
}
};
EB.Intent.send(i);
}
}
{{< / highlight >}}
Yes, you're right, in this case we're not using EB's Barcode API, but we're using EB's Intent API to use DataWedge together with Enterprise Browser.
There're some additional steps to be able to do this that you can find on [EB's documentation website](https://techdocs.zebra.com/enterprise-browser/1-8/guide/datawedge/) and in [this useful blog post on Zebra's developer portal](https://developer.zebra.com/community/home/blog/2018/04/05/get-simulscan-data-using-datawedge-inside-enterprise-browser-as-javascript-callback).
This is all for Enterprise Browser. I hope you enjoy this incredible tool!
## One more thing
If your customer want to use the same setup with a native application, one option is to have a small Android service that works with the Android media service to capture this particular event.
A very simple implementation of such a service could be:
{{< highlight java "linenos=table" >}}
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.media.session.MediaButtonReceiver;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import android.widget.Toast;
public class myService extends Service {
@Nullable
// DataWedge SoftTrigger intent's parameters
String softScanTrigger = "com.symbol.datawedge.api.ACTION_SOFTSCANTRIGGER";
String extraData = "com.symbol.datawedge.api.EXTRA_PARAMETER";
@Override
public IBinder onBind(Intent intent) {
return null;
}
private MediaSessionCompat.Callback mediaSessionCompatCallBack = new MediaSessionCompat.Callback()
{
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.d("MEDIAKEY", "Key Event");
return super.onMediaButtonEvent(mediaButtonEvent);
}
};
private MediaSessionCompat mediaSessionCompat;
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d("SERVICE", "onCreate");
mediaSessionCompat = new MediaSessionCompat(this, "MEDIA");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d("SERVICE", "onDestroy");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d("SERVICE_STARTUP", "onStart");
MediaButtonReceiver.handleIntent(mediaSessionCompat, intent);
mediaSessionCompat.setActive(true);
mediaSessionCompat.setFlags(
MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.d("MEDIA", "event");
Intent i = new Intent();
i.setAction(softScanTrigger);
i.putExtra(extraData, "START_SCANNING");
sendBroadcast(i);
return super.onMediaButtonEvent(mediaButtonEvent);
}
});
return START_STICKY;
}
}
{{< / highlight >}}
## Final note
Thanks to [Maurizio Raimondi and his team in Barware](http://www.barware.it/) to work with me to build this solution and to put together in a very short time some samples of the headset trigger!
|
Java
|
UTF-8
| 120 | 1.734375 | 2 |
[] |
no_license
|
package online.fireflower.easy_enchants.enchant_types;
public enum EnchantType {
ARMOR_ENCHANT,
ITEM_ENCHANT
}
|
SQL
|
UTF-8
| 245 | 3.75 | 4 |
[] |
no_license
|
SELECT e.FirstName + ' ' + e.LastName AS [Full Name], d.Name, e.HireDate
FROM Employees AS e
JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID
WHERE d.Name IN ('Sales', 'Finance')
AND e.HireDate >= '1995/1/1' AND e.HireDate <= '2005/1/1'
|
TypeScript
|
UTF-8
| 1,726 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
import { range } from '../range';
export function getPagersNumbers(
currentIndex: number,
lastIndex: number,
currentPageNeighboursCount: number,
ellipsisPrev: number,
ellipsisNext: number
): number[] {
// @see https://www.figma.com/file/SBNBQInDC8Ms3GyiqtEzm3/%F0%9F%95%B9-Vienna-RDS-Components?node-id=1253%3A734
// Обшее количество пэйджеров без учета стрелок вперед-назад берем равные 9
const totalBlocks = 9;
// Если текщий индекс страницы меньше leftPagesLimit или больше rightPagesLimit, то рендерим троеточия
const leftPagesLimit = totalBlocks - 2;
const rightPagesLimit = leftPagesLimit;
if (lastIndex < totalBlocks) {
return range(0, lastIndex);
}
// Начинать отображение следующих страниц, если стал активным 3 справа или слева элемент
const hasLeftSpill: boolean = currentIndex > leftPagesLimit - 3;
const hasRightSpill: boolean = currentIndex < lastIndex - rightPagesLimit + 3;
if (hasLeftSpill && !hasRightSpill) {
return [0, ellipsisPrev, ...range(lastIndex - rightPagesLimit + 1, lastIndex)];
}
if (!hasLeftSpill && hasRightSpill) {
return [...range(0, leftPagesLimit - 1), ellipsisNext, lastIndex];
}
if (hasLeftSpill && hasRightSpill) {
return [
0,
ellipsisPrev,
...range(currentIndex - currentPageNeighboursCount, currentIndex + currentPageNeighboursCount),
ellipsisNext,
lastIndex,
];
}
return range(0, lastIndex);
}
|
C
|
UTF-8
| 742 | 2.984375 | 3 |
[] |
no_license
|
#include "lorem.h"
int pushInList(t_data **pointer, char *word) {
t_data *elem;
if ((elem = malloc(sizeof(t_data))) == NULL)
return (-1);
elem->word = word;
elem->prec = *pointer;
*pointer = elem;
return (0);
}
char *popInList(t_data **pointer) {
char *word;
t_data *tmp;
if (!*pointer)
return (NULL);
tmp = (*pointer)->prec;
word = (*pointer)->word;
free(*pointer);
*pointer = tmp;
return (word);
}
void clearDaList(t_data **pointer) {
t_data *tmp;
while (*pointer) {
tmp = (*pointer)->prec;
free(*pointer);
*pointer = tmp;
}
}
int main(int ac, char *av) {
t_data *my_data = NULL;
pushInList(&my_data, "toto");
clearDaList(&my_data);
//printf("%s\n", popInList(&my_data));
return (0);
}
|
Java
|
UTF-8
| 1,430 | 2.09375 | 2 |
[] |
no_license
|
package com.geovanni.studioghibli.views.views.base;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.geovanni.studioghibli.views.bussiness.interfaces.IToolbarListener;
import butterknife.ButterKnife;
public abstract class BaseFragment extends Fragment {
private View rootView;
private Context context;
private IToolbarListener toolbarListener;
protected abstract int getLayoutResourceId();
protected abstract String getCustomTag();
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
try {
toolbarListener = (IToolbarListener) context;
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(getLayoutResourceId(), container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
protected void updateToolbar(String title, int imageResource) {
if (toolbarListener != null) {
toolbarListener.updateToolbar(title, imageResource);
}
}
}
|
Go
|
UTF-8
| 797 | 2.65625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
package shared
import "flag"
type Version int
type Server struct {
Address string
Https bool
Tls struct {
Address string
Domain string
HttpsKey string
HttpsCert string
}
}
type Recording struct {
Enabled bool
CompressLevel int
Name string
Folder string
Zip bool
}
func (s *Server) WithFlags() {
flag.StringVar(&s.Address, "address", s.Address, "HTTP server address (host:port)")
flag.StringVar(&s.Tls.Address, "httpsAddress", s.Tls.Address, "HTTPS server address (host:port)")
flag.StringVar(&s.Tls.HttpsKey, "httpsKey", s.Tls.HttpsKey, "HTTPS key")
flag.StringVar(&s.Tls.HttpsCert, "httpsCert", s.Tls.HttpsCert, "HTTPS chain")
}
func (s *Server) GetAddr() string {
if s.Https {
return s.Tls.Address
}
return s.Address
}
|
Java
|
UTF-8
| 16,035 | 1.773438 | 2 |
[] |
no_license
|
package br.ufjf.pgcc.eseco.app.controller;
import br.ufjf.pgcc.eseco.app.service.MendeleyService;
import br.ufjf.pgcc.eseco.app.validator.ResearcherFormValidator;
import br.ufjf.pgcc.eseco.domain.model.core.*;
import br.ufjf.pgcc.eseco.domain.service.core.*;
import br.ufjf.pgcc.eseco.common.controller.CommonController;
import br.ufjf.pgcc.eseco.domain.model.experiment.Experiment;
import br.ufjf.pgcc.eseco.domain.model.uac.User;
import br.ufjf.pgcc.eseco.domain.service.experiment.ExperimentService;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@SessionAttributes({"researcherForm"})
public class ResearchersController extends CommonController {
private static final Logger LOGGER = Logger.getLogger(ExperimentsController.class.getName());
private final ResearcherService researcherService;
private final InstitutionService institutionService;
private final AgentService agentService;
private final DisciplineService disciplineService;
private final InterestService interestService;
private final MendeleyService mendeleyService;
private final ResearcherKeywordService researcherKeywordService;
private final ExperimentService experimentService;
@Autowired
ResearcherFormValidator researcherFormValidator;
@InitBinder("researcherForm")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(researcherFormValidator);
}
@Autowired
public ResearchersController(ResearcherService researcherService, InstitutionService institutionService,
AgentService agentService, DisciplineService disciplineService, InterestService interestService,
MendeleyService mendeleyService, ResearcherKeywordService researcherKeywordService,
ExperimentService experimentService) {
this.researcherService = researcherService;
this.institutionService = institutionService;
this.agentService = agentService;
this.disciplineService = disciplineService;
this.interestService = interestService;
this.mendeleyService = mendeleyService;
this.researcherKeywordService = researcherKeywordService;
this.experimentService = experimentService;
}
@RequestMapping(value = "/researchers", method = RequestMethod.GET)
public String showAllResearchers(Model model) {
LOGGER.info("showAllResearchers()");
List<Researcher> allResearchers = researcherService.findAll();
model.addAttribute("researchers", allResearchers);
model.addAttribute("researchRelationsGraphJSON", getResearchRelationsGraph());
model.addAttribute("researchExperimentsChartJSON", getResearchExperimentsChart());
return "researchers/list";
}
@RequestMapping(value = "/researchers/add", method = RequestMethod.GET)
public String showAddResearcherForm(Model model, HttpSession session) {
LOGGER.info("showAddResearcherForm()");
User user = (User) session.getAttribute("logged_user");
if (user.getAgent() != null && user.getAgent().getResearcher() != null) {
return "redirect:/researchers/" + user.getAgent().getResearcher().getId();
} else {
Researcher researcher = new Researcher();
researcher.setAgent(user.getAgent());
model.addAttribute("researcherForm", researcher);
populateDefaultModel(model);
return "researchers/researcher-form";
}
}
@RequestMapping(value = "/researchers/{id}", method = RequestMethod.GET)
public String showResearcher(@PathVariable("id") int id, Model model, HttpSession session) {
LOGGER.log(Level.INFO, "showResearcher() : {0}", id);
Researcher researcher = researcherService.find(id);
if (researcher == null) {
model.addAttribute("css", "danger");
model.addAttribute("msg", "Researcher not found");
User user = (User) session.getAttribute("logged_user");
researcher = new Researcher();
researcher.setAgent(user.getAgent());
model.addAttribute("researcherForm", researcher);
return "researchers/researcher-form";
}
// Transform context info into JSON String
List<ResearcherKeyword> researcherKeywordList = new ArrayList<>();
for (ResearcherKeyword rk : researcher.getResearchKeywords()) {
ResearcherKeyword newRk = new ResearcherKeyword();
newRk.setName(rk.getName());
researcherKeywordList.add(newRk);
}
if (researcherKeywordList.isEmpty()) {
for (Interest i : researcher.getResearchInterests()) {
ResearcherKeyword newRk = new ResearcherKeyword();
newRk.setName(i.getName());
researcherKeywordList.add(newRk);
researcher.getResearchKeywords().add(newRk);
}
}
Gson gson = new GsonBuilder().create();
String researcherKeywordsJSON = gson.toJson(researcherKeywordList);
model.addAttribute("researcher", researcher);
model.addAttribute("researcherKeywordsJSON", researcherKeywordsJSON);
return "researchers/show";
}
@RequestMapping(value = "/researchers/{id}/update", method = RequestMethod.GET)
public String showUpdateResearcherForm(@PathVariable("id") int id, Model model) {
LOGGER.log(Level.INFO, "showUpdateResearcherForm() : {0}", id);
Researcher researcher = researcherService.find(id);
model.addAttribute("researcherForm", researcher);
populateDefaultModel(model);
return "researchers/researcher-form";
}
@RequestMapping(value = "/researchers", method = RequestMethod.POST)
public String saveOrUpdateResearcher(@ModelAttribute("researcherForm") @Validated Researcher researcher,
BindingResult result, Model model, final RedirectAttributes redirectAttributes, HttpSession session) {
LOGGER.log(Level.INFO, "saveOrUpdateResearcher() : {0}", researcher);
if (!result.hasErrors()) {
redirectAttributes.addFlashAttribute("css", "success");
if (researcher.isNew()) {
redirectAttributes.addFlashAttribute("msg", "Researcher added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "Researcher updated successfully!");
}
try {
researcher = researcherService.saveOrUpdate(researcher);
Agent agent = researcher.getAgent();
if (agent == null) {
agent = ((User) session.getAttribute("logged_user")).getAgent();
agent.setResearcher(researcher);
researcher.setAgent(agent);
researcher = researcherService.saveOrUpdate(researcher);
}
// Add Keywords List
List<String> keyList = new ArrayList<>();
List<ResearcherKeyword> keywordsList = new ArrayList<>();
if (researcher.getMendeleyId() != null && !researcher.getMendeleyId().isEmpty()) {
for (ResearcherKeyword rk : mendeleyService.searchKeywordsByProfileId(researcher.getMendeleyId())) {
String key = rk.getName().toLowerCase() + "-" + rk.getYear();
if (!keyList.contains(key)) {
keyList.add(key);
rk.setName(rk.getName().toLowerCase());
rk.setResearcher(researcher);
keywordsList.add(rk);
}
}
}
// Delete previous keywords
/*
for (ResearcherKeyword rk : researcher.getResearchKeywords()) {
researcherKeywordService.delete(rk);
}
*/
// Add new keywords
researcher.setResearchKeywords(keywordsList);
for (ResearcherKeyword rk : researcher.getResearchKeywords()) {
rk.setResearcher(researcher);
researcherKeywordService.saveOrUpdate(rk);
}
return "redirect:/researchers/" + researcher.getId();
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
model.addAttribute("css", "danger");
model.addAttribute("msg", ex);
}
}
// Agent agent = ((User) session.getAttribute("logged_user")).getAgent();
// researcher.setAgent(agent);
// model.addAttribute("researcherForm", researcher);
populateDefaultModel(model);
return "researchers/researcher-form";
}
@RequestMapping(value = "/researchers/mendeleySearch", method = RequestMethod.GET)
public String mendeleySearch(@ModelAttribute("researcherForm") Researcher researcher, Model model) {
User user = researcher.getAgent().getUser();
LOGGER.log(Level.INFO, "mendeleySearch() : {0}", user.getEmail());
try {
List<Researcher> lista = mendeleyService.searchByEmail(user.getEmail());
if (lista.size() == 1) {
Researcher res = lista.get(0);
res = saveNewObjects(res);
researcher.setAcademicStatus(res.getAcademicStatus());
researcher.setDisplayName(res.getDisplayName());
researcher.setMendeleyId(res.getMendeleyId());
researcher.setTitle(res.getTitle());
researcher.setPhoto(res.getPhoto());
researcher.setMendeleyId(res.getMendeleyId());
researcher.setInstitutions(res.getInstitutions());
researcher.setDisciplines(res.getDisciplines());
researcher.setResearchInterests(res.getResearchInterests());
} else {
model.addAttribute("css", "warning");
model.addAttribute("msg", "Researcher not found!");
}
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
model.addAttribute("css", "danger");
model.addAttribute("msg", ex.getMessage());
}
model.addAttribute("researcherForm", researcher);
populateDefaultModel(model);
return "researchers/researcher-form";
}
/**
* Saves the new objects related to Researcher
*
* @param r
*
* @throws Exception
*/
private Researcher saveNewObjects(Researcher r) {
try {
for (Institution i : r.getInstitutions()) {
Institution findByName = institutionService.findByName(i.getName());
if (findByName == null) {
i = institutionService.saveOrUpdate(i);
} else {
i.setId(findByName.getId());
}
}
for (Discipline d : r.getDisciplines()) {
Discipline findByName = disciplineService.findByName(d.getName());
if (findByName == null) {
d = disciplineService.saveOrUpdate(d);
} else {
d.setId(findByName.getId());
}
}
for (Interest i : r.getResearchInterests()) {
Interest findByName = interestService.findByName(i.getName());
if (findByName == null) {
i = interestService.saveOrUpdate(i);
} else {
i.setId(findByName.getId());
}
}
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
return r;
}
private void populateDefaultModel(Model model) {
model.addAttribute("institutionsList", institutionService.findAll());
model.addAttribute("interestsList", interestService.findAll());
model.addAttribute("disciplinesList", disciplineService.findAll());
}
private JSONObject getResearchRelationsGraph() {
List<Researcher> allResearchers = researcherService.findAll();
List<Experiment> allExperiments = experimentService.findAll();
JSONObject object = new JSONObject();
JSONObject researchers = new JSONObject();
JSONObject researchRelations = new JSONObject();
for (Researcher researcher : allResearchers) {
JSONObject node = new JSONObject();
node.put("name", researcher.getDisplayName());
node.put("img", researcher.getPhoto());
researchers.put(researcher.getId(), node);
}
for (Experiment experiment : allExperiments) {
JSONObject experimentJson = new JSONObject();
researchRelations.put("experiment_" + experiment.getId(), experimentJson);
for (Researcher researcher2 : experiment.getResearchers()) {
if (experiment.getAuthor().getId() != researcher2.getId()) {
JSONObject peer = new JSONObject();
peer.put("id_1", experiment.getAuthor().getDisplayName());
peer.put("id_2", researcher2.getDisplayName());
Integer.compare(experiment.getAuthor().getId(), researcher2.getId());
experimentJson.put(experiment.getAuthor().getId() + "_" + researcher2.getId(), peer);
}
}
}
object.put("nodes", researchers);
object.put("relations", researchRelations);
return object;
}
private JSONObject getResearchExperimentsChart() {
List<Researcher> allResearchers = researcherService.findAll();
JSONArray relations = new JSONArray();
for (Researcher researcher : allResearchers) {
JSONObject relation = new JSONObject();
relation.put("label", researcher.getDisplayName());
List<Experiment> experiments = experimentService.findByResearcherId(researcher.getId());
JSONArray array = new JSONArray();
for (Experiment experiment : experiments) {
JSONObject experimentObj = new JSONObject();
experimentObj.put("label", experiment.getName());
experimentObj.put("value", 1);
array.add(experimentObj);
}
relation.put("values", array);
if (experiments.size() > 0) {
relations.add(relation);
}
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("content", relations);
return jsonObject;
}
}
|
Java
|
UTF-8
| 6,470 | 2.28125 | 2 |
[] |
no_license
|
package cn.notemi.controller;
import cn.notemi.po.User;
import cn.notemi.po.UserCustom;
import cn.notemi.po.UserQueryVo;
import cn.notemi.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.UUID;
/**
* Title:UserCustom
* Description:用户controller
*
* @author Flicker
* @create 2017-01-17 下午 7:55
**/
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Resource
private UserService userService;
/*批量修改*/
//这里的值传到了UserQueryVo这个包装对象中
@RequestMapping("/updateUserList")
public String updateUserList(UserQueryVo userQueryVo) throws Exception{
return "redirect:editUserList";
}
@RequestMapping("/editUserList")
public ModelAndView editUserList(ModelAndView modelAndView,UserQueryVo userQueryVo) throws Exception{
List<UserCustom> userList = userService.selectChooseList(userQueryVo);
//填充数据
modelAndView.addObject("userList", userList);
//视图
modelAndView.setViewName("user/editList");
return modelAndView;
}
/*批量删除*/
//数组绑定
@RequestMapping(value = "/deletes")
public String deletes(Integer[] user_id) throws Exception{
for (int i=0;i<user_id.length-1;i++){
userService.deleteById(user_id[i]);
}
//删除操作
return "redirect:index";
}
/*添加操作*/
@RequestMapping(value = "/added",method = RequestMethod.POST)
public String added(Model model,
@Validated UserCustom userCustom,
BindingResult bindingResult,
MultipartFile photo_file) throws Exception{
//获取校验错误消息
if (bindingResult.hasErrors()){
//输出错误信息
List<ObjectError> allErros = bindingResult.getAllErrors();
for (ObjectError objectError:allErros){
//输出错误信息
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("error",allErros);
//数据回显
model.addAttribute("user",userCustom);
return "user/add";
}
//原始名称
String originalFilename = photo_file.getOriginalFilename();
//上传图片
if(photo_file!=null && originalFilename!=null && originalFilename.length()>0){
//存储图片的物理路径
String pic_path = "d:\\upload\\";
//新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//新图片
File newFile = new File(pic_path+newFileName);
//将内存中的数据写入磁盘
photo_file.transferTo(newFile);
//将新图片名称写到itemsCustom中
userCustom.setPhoto("/upload/"+newFileName);
System.out.println("图片上传地址:/upload/"+newFileName);
}
userService.add(userCustom);
return "redirect:index";
}
@RequestMapping(value = "/add")
public String add() throws Exception{
return "user/add";
}
/*删除用户*/
@RequestMapping(value = "/delete")
public String delete(@RequestParam("id") Integer id) throws Exception{
userService.deleteById(id);
return "redirect:index";
}
/*更新*/
@RequestMapping(value = "/update")
public String update(UserCustom userCustom,MultipartFile photo_file) throws Exception{
//原始名称
String originalFilename = photo_file.getOriginalFilename();
//上传图片
if(photo_file!=null && originalFilename!=null && originalFilename.length()>0){
//存储图片的物理路径
String pic_path = "d:\\upload\\";
//新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//新图片
File newFile = new File(pic_path+newFileName);
//将内存中的数据写入磁盘
photo_file.transferTo(newFile);
//将新图片名称写到itemsCustom中
userCustom.setPhoto("/upload/"+newFileName);
System.out.println("图片上传地址:/upload/"+newFileName);
}
userService.updateChoose(userCustom);
return "redirect:index";
}
/*编辑*/
@RequestMapping(value = "/edit")
public String edit(@RequestParam(value = "id",required = true) Integer id,
Model model) throws Exception {
User users = userService.selectById(id);
System.out.println(users.toString());
model.addAttribute("users",users);
return "user/edit";
}
/*搜索*/
@RequestMapping(value = "/search")
public String search(Model model, UserQueryVo userQueryVo) throws Exception{
List<UserCustom> userList = userService.selectChooseList(userQueryVo);
model.addAttribute("userList",userList);
return "user/index";
}
/*用户列表*/
@RequestMapping(value = "/index")
public ModelAndView index(ModelAndView modelAndView, UserQueryVo userQueryVo, HttpSession session) throws Exception {
User users = (User) session.getAttribute("users");
int id = users.getId();
User user = userService.selectById(id);
modelAndView.addObject("user",user);
List<UserCustom> userList = userService.selectChooseList(userQueryVo);
//填充数据
modelAndView.addObject("userList", userList);
//视图
modelAndView.setViewName("user/index");
return modelAndView;
}
}
|
PHP
|
UTF-8
| 3,522 | 3.078125 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* PHP Version: 7.4
*
* @category
* @author Oleh Boiko <developer@mackais.com>
* @copyright 2018-2020 @MackRais
* @link <https://mackrais.com>
* @date 2020-02-17
*/
declare(strict_types=1);
namespace TicTacToe\Board;
use TicTacToe\Exception\InvalidBoardUser;
use TicTacToe\Exception\InvalidValidation;
use TicTacToe\Game\ResultChecker;
use TicTacToe\Storage\PhpSessionStorage;
use TicTacToe\User\MiniMaxBot;
use TicTacToe\User\User;
class Board
{
public const SYMBOL_O = 'O';
public const SYMBOL_X = 'X';
public const ALLOWED_SYMBOLS = [self::SYMBOL_O, self::SYMBOL_X];
public const ROW_SIZE = 3;
public const COLUMN_SIZE = 3;
private const STORAGE_KEY = 'board';
protected PhpSessionStorage $storage;
protected ?User $user;
protected ResultChecker $resultChecker;
protected MiniMaxBot $miniMaxBot;
public function __construct()
{
$this->storage = new PhpSessionStorage();
$this->user = (new User())->get();
$this->resultChecker = new ResultChecker();
$this->miniMaxBot = new MiniMaxBot();
}
public function getBoard()
{
return $this->storage->get(self::STORAGE_KEY, $this->getDefaultBoard());
}
public function makeMove(?int $rowIndex, ?int $columnIndex)
{
$board = $this->getBoard();
$winner = null;
$this->resultChecker->getWinner($board, $winner);
if ($winner === null) {
$this->validate($rowIndex, $columnIndex);
$board[$rowIndex][$columnIndex] = $this->user->getSymbol();
$this->set($board);
}
$this->resultChecker->getWinner($board, $winner);
if (!$this->resultChecker->isGameOver() && $winner === null) {
$this->miniMaxBot->makeMove($this);
}
}
public function validate(?int $rowIndex, ?int $columnIndex)
{
if ($this->resultChecker->isGameOver()) {
throw new InvalidBoardUser('Game over.');
}
if (!($this->user instanceof User)) {
throw new InvalidBoardUser('Incorrect user.');
}
if (!Board::isValidSymbol($this->user->getSymbol())) {
throw new InvalidValidation(
sprintf('Please use one of the following symbols: "%s".', implode('", "', Board::ALLOWED_SYMBOLS))
);
}
if ($rowIndex === null || $columnIndex === null) {
throw new InvalidValidation('Incorrect coordinates');
}
$board = $this->getBoard();
if (!empty($board[$rowIndex][$columnIndex])) {
throw new InvalidValidation('Coordinates already taken');
}
}
public function set(array $board)
{
$this->storage->set(self::STORAGE_KEY, $board);
}
public function clear()
{
if ($this->storage->has(self::STORAGE_KEY)) {
$this->storage->delete(self::STORAGE_KEY);
}
}
public static function isValidSymbol(string $symbol): bool
{
return in_array($symbol, self::ALLOWED_SYMBOLS);
}
protected function getDefaultBoard()
{
$board = [];
for ($rowIndex = 0; $rowIndex < static::ROW_SIZE; $rowIndex++) {
for ($columnIndex = 0; $columnIndex < static::COLUMN_SIZE; $columnIndex++) {
$board[$rowIndex][$columnIndex] = null;
}
}
return $board;
}
public function setUser(User $user): void
{
$this->user = $user;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.