language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 3,054
| 2.25
| 2
|
[] |
no_license
|
package hdu.homework.chat.entity.bean.database;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import javax.persistence.*;
/**
* created by 钱曹宇@supercode on 3/8/2020
*/
@ToString
@ApiModel
@Entity
@Table()
public class GroupInfo {
public Integer getGId() {
return gId;
}
public void setgId(Integer gId) {
this.gId = gId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getAdminId() {
return adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
public String getProfileUrl() {
return profileUrl;
}
public void setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
}
public String getNotice() {
return notice;
}
public void setNotice(String notice) {
this.notice = notice;
}
public GroupInfo(Integer gId, String name, String createTime, String description, Integer adminId, String profileUrl, String notice) {
this.gId = gId;
this.name = name;
this.createTime = createTime;
this.description = description;
this.adminId = adminId;
this.profileUrl = profileUrl;
this.notice = notice;
}
@Id
@GeneratedValue
@ApiModelProperty(name = "群组id", dataType = "number")
@Column(name = "gId")
private Integer gId;
@ApiModelProperty(name = "群组名称", dataType = "string")
private String name;
@ApiModelProperty(name = "创建时间", dataType = "string", value = "2020-02-02 20:02")
private String createTime;
@ApiModelProperty(value = "群组介绍", dataType = "string")
private String description;
@ApiModelProperty(value = "群主id", dataType = "number")
private Integer adminId;
@ApiModelProperty(value = "群组头像", dataType = "string")
private String profileUrl;
@ApiModelProperty(value = "群消息", dataType = "string")
private String notice;
public GroupInfo(){}
public GroupInfo(Integer gId, String name, String description, Integer adminId, String profileUrl, String notice) {
this.gId = gId;
this.name = name;
this.description = description;
this.adminId = adminId;
this.profileUrl = profileUrl;
this.notice = notice;
}
public GroupInfo(String name, String description, String profileUrl) {
this.name = name;
this.description = description;
this.profileUrl = profileUrl;
}
}
|
Java
|
UTF-8
| 794
| 2.328125
| 2
|
[
"WTFPL"
] |
permissive
|
package ptrman.mltoolset.PIPE;
import ptrman.mltoolset.PIPE.program.Instruction;
import ptrman.mltoolset.PIPE.program.Program;
public interface ProblemspecificDescriptor {
int getNumberOfArgumentsOfInstruction(Instruction selectedInstruction);
ptrman.mltoolset.PIPE.program.Instruction createTerminalNode(float randomConstant);
ptrman.mltoolset.PIPE.program.Instruction getInstructionByIndex(int selectedInstruction);
float createTerminalNodeFromProblemdependSet();
// lower fitness is better
float getFitnessOfProgram(ptrman.mltoolset.PIPE.program.Program program);
float getNumberOfInstructions();
ptrman.mltoolset.PIPE.PropabilisticPrototypeTree.Node createPptNode();
String getDescriptionOfProgramAsString(Program elitist);
}
|
C#
|
UTF-8
| 2,435
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Linq;
using NGitLab.Mock.Clients;
namespace NGitLab.Mock
{
public class ReleaseCollection : Collection<ReleaseInfo>
{
private Project Project => (Project)Parent;
public ReleaseCollection(GitLabObject parent)
: base(parent)
{
}
public ReleaseInfo GetByTagName(string tagName)
{
return this.FirstOrDefault(r => string.Equals(r.TagName, tagName, StringComparison.Ordinal));
}
public override void Add(ReleaseInfo release)
{
if (release is null)
throw new ArgumentNullException(nameof(release));
if (release.TagName == default || Project.Repository.GetTags().FirstOrDefault(t => t.FriendlyName.Equals(release.TagName, StringComparison.Ordinal)) == null)
{
throw new ArgumentException($"Tag '{release.TagName}' invalid or not found", nameof(release));
}
if (release.Name == default)
{
release.Name = release.TagName;
}
if (GetByTagName(release.TagName) != null)
{
throw new GitLabException("Release already exists");
}
base.Add(release);
}
public ReleaseInfo Add(string tagName, string name, string description, User user)
{
return Add(tagName, name, reference: null, description, user);
}
public ReleaseInfo Add(string tagName, string name, string reference, string description, User user)
{
if (tagName is null)
throw new ArgumentNullException(nameof(tagName));
if (user is null)
throw new ArgumentNullException(nameof(user));
if (!Project.Repository.GetTags().Any(r => string.Equals(r.FriendlyName, tagName, StringComparison.Ordinal)))
{
if (string.IsNullOrEmpty(reference))
throw new GitLabBadRequestException("A reference must be set when the tag does not exist");
Project.Repository.CreateTag(tagName);
}
var release = new ReleaseInfo
{
TagName = tagName,
Name = name,
Description = description,
Author = user,
};
Add(release);
return release;
}
}
}
|
Java
|
UTF-8
| 4,536
| 2.515625
| 3
|
[] |
no_license
|
package web;
import java.net.URL;
import java.sql.Timestamp;
import java.text.ParseException;
import java.time.Instant;
import CurrencyHandler.CurrencyHAndler;
import DateHandler.DateHandler;
import downloader.CbrfDownloader;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public HelloController(NamedParameterJdbcTemplate namedParameterJdbcTemplate){
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@GetMapping("/hello/{name1}/{date1}")
public String helloName(
@PathVariable(name = "name1") String name,
@PathVariable String date1){
String return_string = "";
String request = name + "/" + date1;
int error = 0;
CurrencyHAndler currencyHAndler = new CurrencyHAndler();
String currency = currencyHAndler.getCss(name);
if (currency == "error1"){
return_string = "Вы ввели валюту '" + name +
"', формат валюты неверный, " +
"введите трехзначное название валюты с заглавной буквы например USD\n";
error ++;
}
DateHandler dateHandler = new DateHandler();
String date_web = "";
try {
date_web = dateHandler.getDate(date1);
}
catch (Error e){
String error2 = e.toString();
if (error2.equals("java.lang.Error: 1")){
return_string += "Проверьте существует ли такая дата " + date1;
}
else if (error2.equals("java.lang.Error: 2")){
return_string += "Вы ввели дату '" + date1 +
"', формат неверный, введите дату в формате dd.MM.YYYY например 01.10.1999";
}
else{
return_string +=
"Заглядываю в магический шар... будущий курс валюты туманен";
}
error++;
}
if (error >0) {
namedParameterJdbcTemplate.update(
" insert into requested_names(name , process_time, return_string) " +
" values (:name_ph, :process_time_ph, :return_ph)",
new MapSqlParameterSource()
.addValue("name_ph", request)
.addValue("process_time_ph", Timestamp.from(Instant.now()))
.addValue("return_ph",return_string)
);
return return_string;
}
CbrfDownloader downloader = new CbrfDownloader();
try {
URL url = new URIBuilder()
.setScheme("https")
.setHost("www.cbr.ru")
// .setPort(8080)
.setPath("/currency_base/daily/")
.addParameter("UniDbQuery.Posted", "True")
.addParameter("UniDbQuery.To", date_web)
.build()
.toURL();
try {
String actual = downloader.get(url, currency);
return_string += ("Курс " + name + " на " + date_web + " " + actual);
}
catch (Exception e) {
return_string += "\n downloader fail " + url.toString() + e.toString();
}
}
catch (Exception e) {
return_string += "\n url fail" + e.toString();
}
namedParameterJdbcTemplate.update(
" insert into requested_names(name , process_time, return_string) " +
" values (:name_ph, :process_time_ph, :return_ph)",
new MapSqlParameterSource()
.addValue("name_ph", request)
.addValue("process_time_ph", Timestamp.from(Instant.now()))
.addValue("return_ph",return_string)
);
return return_string;
}
}
|
Shell
|
UTF-8
| 44,907
| 3.5625
| 4
|
[] |
no_license
|
#
# Script @__AnyLabel__ from content/tutorials/setup.md
#
#----------------------------------------------------------------------# Start 1 of 1
echo "# @envVars (block #1 in __AnyLabel__) of content/tutorials/setup.md"
# If JIRI_ROOT or V23_RELEASE are not defined, set them to the default values
# from the installation instructions and hope for the best.
[ -z "$JIRI_ROOT" ] && export JIRI_ROOT=${HOME}/v23_root
[ -z "$V23_RELEASE" ] && export V23_RELEASE=${JIRI_ROOT}/release/go
# All files created by the tutorial will be placed in $V_TUT. It is a disposable
# workspace, easy to recreate.
export V_TUT=${V_TUT-$HOME/v23_tutorial}
# V_BIN is a convenience for running Vanadium binaries. It avoids the need to
# modify your PATH or to be 'in' a particular directory when doing the
# tutorials.
export V_BIN=${V23_RELEASE}/bin
# For the shell doing the tutorials, GOPATH must include both Vanadium and the
# code created as a result of doing the tutorials. To avoid trouble with
# accumulation, $GOPATH is intentionally omitted from the right hand side (any
# existing value is ignored).
if [ -z "$V23_GOPATH" ]; then
export V23_GOPATH=`${JIRI_ROOT}/devtools/bin/jiri go env GOPATH`
fi
export GOPATH=$V_TUT:${V23_GOPATH}
# HISTCONTROL set as follows excludes long file creation commands used in
# tutorials from your shell history.
HISTCONTROL=ignorespace
# A convenience for killing tutorial processes
function kill_tut_process() {
eval local pid=\$$1
if [ -n "$pid" ]; then
kill $pid || true
wait $pid || true
eval unset $1
fi
}
#----------------------------------------------------------------------# End 1 of 1
#
# Script @__AnyLabel__ from content/tutorials/checkup.md
#
#----------------------------------------------------------------------# Start 1 of 1
echo "# @checkTutorialAssets (block #1 in __AnyLabel__) of content/tutorials/checkup.md"
function bad_vanadium() {
echo '
Per https://vanadium.github.io/installation/, either
export JIRI_ROOT={your installation directory}
or do a fresh install.';
exit 1;
}
[ -z "$V23_RELEASE" ] && { echo 'The environment variable V23_RELEASE is not defined.'; bad_vanadium; }
[ -x "$V23_RELEASE/bin/principal" ] || { echo 'The file $V23_RELEASE/bin/principal does not exist or is not executable.'; bad_vanadium; }
#----------------------------------------------------------------------# End 1 of 1
#
# Script @__AnyLabel__ from content/tutorials/wipe-slate.md
#
#----------------------------------------------------------------------# Start 1 of 1
echo "# @deleteTutdirContent (block #1 in __AnyLabel__) of content/tutorials/wipe-slate.md"
if [ -z "${V_TUT}" ]; then
echo "V_TUT not defined, nothing to do."
else
if [ -d "${V_TUT}" ]; then
/bin/rm -rf $V_TUT/*
echo "Removed contents of $V_TUT"
else
echo "Not a directory: V_TUT=\"$V_TUT\""
fi
fi
#----------------------------------------------------------------------# End 1 of 1
#
# Script @__AnyLabel__ from content/tutorials/basics.md
#
#----------------------------------------------------------------------# Start 1 of 16
echo "# @defineService (block #1 in __AnyLabel__) of content/tutorials/basics.md"
mkdir -p $V_TUT/src/fortune/ifc
cat - <<EOF >$V_TUT/src/fortune/ifc/fortune.vdl
package ifc
type Fortune interface {
// Returns a random fortune.
Get() (wisdom string | error)
// Adds a fortune to the set used by Get().
Add(wisdom string) error
}
EOF
#----------------------------------------------------------------------# End 1 of 16
#----------------------------------------------------------------------# Start 2 of 16
echo "# @compileInterface (block #2 in __AnyLabel__) of content/tutorials/basics.md"
VDLROOT=$V23_RELEASE/src/v.io/v23/vdlroot \
VDLPATH=$V_TUT/src \
$V_BIN/vdl generate --lang go $V_TUT/src/fortune/ifc
go build fortune/ifc
#----------------------------------------------------------------------# End 2 of 16
#----------------------------------------------------------------------# Start 3 of 16
echo "# @serviceImpl (block #3 in __AnyLabel__) of content/tutorials/basics.md"
mkdir -p $V_TUT/src/fortune/service
cat - <<EOF >$V_TUT/src/fortune/service/service.go
package service
import (
"math/rand"
"fortune/ifc"
"sync"
"v.io/v23/context"
"v.io/v23/rpc"
)
type impl struct {
wisdom []string // All known fortunes.
random *rand.Rand // To pick a random index in 'wisdom'.
mu sync.RWMutex // To safely enable concurrent use.
}
// Makes an implementation.
func Make() ifc.FortuneServerMethods {
return &impl {
wisdom: []string{
"You will reach the heights of success.",
"Conquer your fears or they will conquer you.",
"Today is your lucky day!",
},
random: rand.New(rand.NewSource(99)),
}
}
func (f *impl) Get(_ *context.T, _ rpc.ServerCall) (blah string, err error) {
f.mu.RLock()
defer f.mu.RUnlock()
if len(f.wisdom) == 0 {
return "[empty]", nil
}
return f.wisdom[f.random.Intn(len(f.wisdom))], nil
}
func (f *impl) Add(_ *context.T, _ rpc.ServerCall, blah string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.wisdom = append(f.wisdom, blah)
return nil
}
EOF
go build fortune/service
#----------------------------------------------------------------------# End 3 of 16
#----------------------------------------------------------------------# Start 4 of 16
echo "# @authorizer (block #4 in __AnyLabel__) of content/tutorials/basics.md"
mkdir -p $V_TUT/src/fortune/server/util
cat - <<EOF >$V_TUT/src/fortune/server/util/authorizer.go
package util
import (
"v.io/v23/security"
)
// Returns Vanadium's default authorizer.
func MakeAuthorizer() security.Authorizer {
return security.DefaultAuthorizer()
}
EOF
go build fortune/server/util
#----------------------------------------------------------------------# End 4 of 16
#----------------------------------------------------------------------# Start 5 of 16
echo "# @dispatcher (block #5 in __AnyLabel__) of content/tutorials/basics.md"
mkdir -p $V_TUT/src/fortune/server/util
cat - <<EOF >$V_TUT/src/fortune/server/util/dispatcher.go
package util
import (
"v.io/v23/rpc"
)
// Returns nil to trigger use of the default dispatcher.
func MakeDispatcher() (d rpc.Dispatcher) {
return nil
}
EOF
go build fortune/server/util
#----------------------------------------------------------------------# End 5 of 16
#----------------------------------------------------------------------# Start 6 of 16
echo "# @intializer (block #6 in __AnyLabel__) of content/tutorials/basics.md"
mkdir -p $V_TUT/src/fortune/server/util
cat - <<EOF >$V_TUT/src/fortune/server/util/initializer.go
package util
import (
"flag"
"fmt"
"io/ioutil"
"log"
"v.io/v23/naming"
)
var (
fileName = flag.String(
"endpoint-file-name", "",
"Write endpoint address to given file.")
)
func SaveEndpointToFile(e naming.Endpoint) {
if *fileName == "" {
return
}
contents := []byte(
naming.JoinAddressName(e.String(), "") + "\n")
if ioutil.WriteFile(*fileName, contents, 0644) != nil {
log.Panic("Error writing ", *fileName)
}
fmt.Printf("Wrote endpoint name to %v.\n", *fileName)
}
EOF
go build fortune/server/util
#----------------------------------------------------------------------# End 6 of 16
#----------------------------------------------------------------------# Start 7 of 16
echo "# @server (block #7 in __AnyLabel__) of content/tutorials/basics.md"
mkdir -p $V_TUT/src/fortune/server
cat - <<EOF >$V_TUT/src/fortune/server/main.go
package main
import (
"flag"
"fmt"
"log"
"fortune/ifc"
"fortune/server/util"
"fortune/service"
"v.io/v23"
"v.io/v23/rpc"
"v.io/x/ref/lib/signals"
_ "v.io/x/ref/runtime/factories/generic"
)
var (
serviceName = flag.String(
"service-name", "",
"Name for service in default mount table.")
)
func main() {
ctx, shutdown := v23.Init()
defer shutdown()
// Attach the 'fortune service' implementation
// defined above to a queriable, textual description
// of the implementation used for service discovery.
fortune := ifc.FortuneServer(service.Make())
// If the dispatcher isn't nil, it's presumed to have
// obtained its authorizer from util.MakeAuthorizer().
dispatcher := util.MakeDispatcher()
// Start serving.
var err error
var server rpc.Server
if dispatcher == nil {
// Use the default dispatcher.
_, server, err = v23.WithNewServer(
ctx, *serviceName, fortune, util.MakeAuthorizer())
} else {
_, server, err = v23.WithNewDispatchingServer(
ctx, *serviceName, dispatcher)
}
if err != nil {
log.Panic("Error serving service: ", err)
}
endpoint := server.Status().Endpoints[0]
util.SaveEndpointToFile(endpoint)
fmt.Printf("Listening at: %v\n", endpoint)
// Wait forever.
<-signals.ShutdownOnSignals(ctx)
}
EOF
go install fortune/server
#----------------------------------------------------------------------# End 7 of 16
#----------------------------------------------------------------------# Start 8 of 16
echo "# @client (block #8 in __AnyLabel__) of content/tutorials/basics.md"
mkdir -p $V_TUT/src/fortune/client
cat - <<EOF >$V_TUT/src/fortune/client/main.go
package main
import (
"flag"
"fmt"
"time"
"fortune/ifc"
"v.io/v23"
"v.io/v23/context"
"v.io/x/lib/vlog"
_ "v.io/x/ref/runtime/factories/generic"
)
var (
server = flag.String(
"server", "", "Name of the server to connect to")
newFortune = flag.String(
"add", "", "A new fortune to add to the server's set")
)
func main() {
ctx, shutdown := v23.Init()
defer shutdown()
if *server == "" {
vlog.Error("--server must be specified")
return
}
f := ifc.FortuneClient(*server)
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
if *newFortune == "" { // --add flag not specified
fortune, err := f.Get(ctx)
if err != nil {
vlog.Errorf("error getting fortune: %v", err)
return
}
fmt.Println(fortune)
} else {
if err := f.Add(ctx, *newFortune); err != nil {
vlog.Errorf("error adding fortune: %v", err)
return
}
}
}
EOF
go install fortune/client
#----------------------------------------------------------------------# End 8 of 16
#----------------------------------------------------------------------# Start 9 of 16
echo "# @principalTutorial (block #9 in __AnyLabel__) of content/tutorials/basics.md"
$V_BIN/principal create \
--overwrite $V_TUT/cred/basics tutorial
#----------------------------------------------------------------------# End 9 of 16
#----------------------------------------------------------------------# Start 10 of 16
echo "# @runServerAsPrincipal (block #10 in __AnyLabel__) of content/tutorials/basics.md"
kill_tut_process TUT_PID_SERVER
$V_TUT/bin/server \
--v23.credentials $V_TUT/cred/basics \
--endpoint-file-name $V_TUT/server.txt &
TUT_PID_SERVER=$!
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 10 of 16
#----------------------------------------------------------------------# Start 11 of 16
echo "# @runClientAsPrincipal (block #11 in __AnyLabel__) of content/tutorials/basics.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/basics \
--server `cat $V_TUT/server.txt`
#----------------------------------------------------------------------# End 11 of 16
#----------------------------------------------------------------------# Start 12 of 16
echo "# @clientGet (block #12 in __AnyLabel__) of content/tutorials/basics.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/basics \
--server `cat $V_TUT/server.txt` \
--add 'Fortune favors the bold.'
#----------------------------------------------------------------------# End 12 of 16
#----------------------------------------------------------------------# Start 13 of 16
echo "# @checkMethods (block #13 in __AnyLabel__) of content/tutorials/basics.md"
$V_BIN/vrpc --v23.credentials $V_TUT/cred/basics \
call `cat $V_TUT/server.txt` Get
$V_BIN/vrpc --v23.credentials $V_TUT/cred/basics \
call `cat $V_TUT/server.txt` Add \"More cowbell.\"
#----------------------------------------------------------------------# End 13 of 16
#----------------------------------------------------------------------# Start 14 of 16
echo "# @checkTheSignature (block #14 in __AnyLabel__) of content/tutorials/basics.md"
$V_BIN/vrpc --v23.credentials $V_TUT/cred/basics \
signature `cat $V_TUT/server.txt`
#----------------------------------------------------------------------# End 14 of 16
#----------------------------------------------------------------------# Start 15 of 16
echo "# @checkMethods (block #15 in __AnyLabel__) of content/tutorials/basics.md"
$V_BIN/vrpc --v23.credentials $V_TUT/cred/basics \
signature `cat $V_TUT/server.txt` Add
$V_BIN/vrpc --v23.credentials $V_TUT/cred/basics \
signature `cat $V_TUT/server.txt` Get
#----------------------------------------------------------------------# End 15 of 16
#----------------------------------------------------------------------# Start 16 of 16
echo "# @killServer (block #16 in __AnyLabel__) of content/tutorials/basics.md"
kill_tut_process TUT_PID_SERVER
#----------------------------------------------------------------------# End 16 of 16
#
# Script @__AnyLabel__ from content/tutorials/security/principals-and-blessings.md
#
#----------------------------------------------------------------------# Start 1 of 21
echo "# @makeAliceAndBob (block #1 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal create --overwrite $V_TUT/cred/alice alice
$V_BIN/principal create --overwrite $V_TUT/cred/bob bob
#----------------------------------------------------------------------# End 1 of 21
#----------------------------------------------------------------------# Start 2 of 21
echo "# @runServerAsAlice (block #2 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
kill_tut_process TUT_PID_SERVER
$V_TUT/bin/server \
--v23.credentials $V_TUT/cred/alice \
--endpoint-file-name $V_TUT/server.txt &
TUT_PID_SERVER=$!
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 2 of 21
#----------------------------------------------------------------------# Start 3 of 21
echo "# @runClientAsAlice (block #3 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/alice \
--server `cat $V_TUT/server.txt`
#----------------------------------------------------------------------# End 3 of 21
#----------------------------------------------------------------------# Start 4 of 21
echo "# @aliceBlessBobAsFriend (block #4 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal bless \
--v23.credentials $V_TUT/cred/alice \
--for=24h $V_TUT/cred/bob friend:bob | \
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
set forpeer - alice
#----------------------------------------------------------------------# End 4 of 21
#----------------------------------------------------------------------# Start 5 of 21
echo "# @clientAsBob (block #5 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/bob \
--server `cat $V_TUT/server.txt`
#----------------------------------------------------------------------# End 5 of 21
#----------------------------------------------------------------------# Start 6 of 21
echo "# @killServer (block #6 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
kill_tut_process TUT_PID_SERVER
#----------------------------------------------------------------------# End 6 of 21
#----------------------------------------------------------------------# Start 7 of 21
echo "# @principalAliceDump (block #7 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/alice \
dump
#----------------------------------------------------------------------# End 7 of 21
#----------------------------------------------------------------------# Start 8 of 21
echo "# @principalAliceGetPublicKey (block #8 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/alice \
get publickey --pretty
#----------------------------------------------------------------------# End 8 of 21
#----------------------------------------------------------------------# Start 9 of 21
echo "# @principalAliceGetDefault (block #9 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/alice \
get default -names
#----------------------------------------------------------------------# End 9 of 21
#----------------------------------------------------------------------# Start 10 of 21
echo "# @principalAliceGetPeerMap (block #10 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/alice \
get peermap
#----------------------------------------------------------------------# End 10 of 21
#----------------------------------------------------------------------# Start 11 of 21
echo "# @principalAliceGetRoots (block #11 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/alice \
get recognizedroots
#----------------------------------------------------------------------# End 11 of 21
#----------------------------------------------------------------------# Start 12 of 21
echo "# @principalBobDump (block #12 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
dump
#----------------------------------------------------------------------# End 12 of 21
#----------------------------------------------------------------------# Start 13 of 21
echo "# @comparePublicKeys (block #13 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
keyAlice=`$V_BIN/principal \
--v23.credentials $V_TUT/cred/alice \
get publickey --pretty`
keyBob=`$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get publickey --pretty`
echo -e "alice $keyAlice\n bob $keyBob"
#----------------------------------------------------------------------# End 13 of 21
#----------------------------------------------------------------------# Start 14 of 21
echo "# @principalBobGetDefault (block #14 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get default -names
#----------------------------------------------------------------------# End 14 of 21
#----------------------------------------------------------------------# Start 15 of 21
echo "# @principalBobGetPeerMap (block #15 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get peermap
#----------------------------------------------------------------------# End 15 of 21
#----------------------------------------------------------------------# Start 16 of 21
echo "# @principalBobGetRoots (block #16 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get recognizedroots
#----------------------------------------------------------------------# End 16 of 21
#----------------------------------------------------------------------# Start 17 of 21
echo "# @principalBobDumpBlessings (block #17 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get forpeer alice | \
$V_BIN/principal dumpblessings -
#----------------------------------------------------------------------# End 17 of 21
#----------------------------------------------------------------------# Start 18 of 21
echo "# @principalBobGetForPeerName (block #18 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get forpeer -names alice
#----------------------------------------------------------------------# End 18 of 21
#----------------------------------------------------------------------# Start 19 of 21
echo "# @principalBobGetForPeerRoots (block #19 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get forpeer -rootkey=alice:friend:bob alice
#----------------------------------------------------------------------# End 19 of 21
#----------------------------------------------------------------------# Start 20 of 21
echo "# @echoAlicesKey (block #20 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
echo $keyAlice
#----------------------------------------------------------------------# End 20 of 21
#----------------------------------------------------------------------# Start 21 of 21
echo "# @principalBobGetForPeerCaveats (block #21 in __AnyLabel__) of content/tutorials/security/principals-and-blessings.md"
$V_BIN/principal \
--v23.credentials $V_TUT/cred/bob \
get forpeer -caveats=alice:friend:bob alice
#----------------------------------------------------------------------# End 21 of 21
#
# Script @__AnyLabel__ from content/tutorials/security/permissions-authorizer.md
#
#----------------------------------------------------------------------# Start 1 of 9
echo "# @fortuneInterfaceWithTags (block #1 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
cat - <<EOF >$V_TUT/src/fortune/ifc/fortune.vdl
package ifc
type MyTag string
const (
Reader = MyTag("R")
Writer = MyTag("W")
)
type Fortune interface {
// Returns a random fortune.
Get() (Fortune string | error) {Reader}
// Adds a fortune to the set used by Get().
Add(Fortune string) error {Writer}
}
EOF
VDLROOT=$V23_RELEASE/src/v.io/v23/vdlroot \
VDLPATH=$V_TUT/src \
$V_BIN/vdl generate --lang go $V_TUT/src/fortune/ifc
go build fortune/ifc
#----------------------------------------------------------------------# End 1 of 9
#----------------------------------------------------------------------# Start 2 of 9
echo "# @permissionsAuthorizer (block #2 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
cat - <<EOF >$V_TUT/src/fortune/server/util/authorizer.go
package util
import (
"bytes"
"flag"
"fortune/ifc"
"v.io/v23/security"
"v.io/v23/security/access"
"v.io/v23/vdl"
)
var (
perms = flag.String("perms", "",
"JSON-encoded access.Permissions.")
)
func MakeAuthorizer() (authorizer security.Authorizer) {
aMap, _ := access.ReadPermissions(
bytes.NewBufferString(*perms))
typ := vdl.TypeOf(ifc.Reader)
authorizer, _ = access.PermissionsAuthorizer(aMap, typ)
return
}
EOF
go install fortune/server
#----------------------------------------------------------------------# End 2 of 9
#----------------------------------------------------------------------# Start 3 of 9
echo "# @startServerWithPerms (block #3 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
kill_tut_process TUT_PID_SERVER
$V_TUT/bin/server \
--v23.credentials $V_TUT/cred/alice \
--endpoint-file-name $V_TUT/server.txt \
--perms '{"R": {"In": ["alice:family",
"alice:friend"]},
"W": {"In": ["alice:family"]}}' &
TUT_PID_SERVER=$!
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 3 of 9
#----------------------------------------------------------------------# Start 4 of 9
echo "# @bobCanRead (block #4 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/bob \
--server `cat $V_TUT/server.txt`
#----------------------------------------------------------------------# End 4 of 9
#----------------------------------------------------------------------# Start 5 of 9
echo "# @bobCannotWrite (block #5 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/bob \
--server `cat $V_TUT/server.txt` \
--add 'Bob is awesome.'
#----------------------------------------------------------------------# End 5 of 9
#----------------------------------------------------------------------# Start 6 of 9
echo "# @createCarol (block #6 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
$V_BIN/principal create --overwrite $V_TUT/cred/carol carol
#----------------------------------------------------------------------# End 6 of 9
#----------------------------------------------------------------------# Start 7 of 9
echo "# @aliceBlessCarolAsSister (block #7 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
$V_BIN/principal bless \
--v23.credentials $V_TUT/cred/alice \
--for=24h $V_TUT/cred/carol family:sister | \
$V_BIN/principal set \
--v23.credentials $V_TUT/cred/carol \
forpeer - alice
#----------------------------------------------------------------------# End 7 of 9
#----------------------------------------------------------------------# Start 8 of 9
echo "# @clientIsCarol (block #8 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/carol \
--server `cat $V_TUT/server.txt`
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/carol \
--server `cat $V_TUT/server.txt` \
--add 'Eat kale.'
#----------------------------------------------------------------------# End 8 of 9
#----------------------------------------------------------------------# Start 9 of 9
echo "# @killServer (block #9 in __AnyLabel__) of content/tutorials/security/permissions-authorizer.md"
kill_tut_process TUT_PID_SERVER
#----------------------------------------------------------------------# End 9 of 9
#
# Script @__AnyLabel__ from content/tutorials/naming/suffix-part1.md
#
#----------------------------------------------------------------------# Start 1 of 13
echo "# @newDispatcher (block #1 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
cat - <<EOF >$V_TUT/src/fortune/server/util/dispatcher.go
package util
import (
"errors"
"strings"
"sync"
"fortune/ifc"
"fortune/service"
"v.io/v23/context"
"v.io/v23/rpc"
"v.io/v23/security"
)
type myDispatcher struct {
mu sync.Mutex
registry map[string]interface{}
}
func (d *myDispatcher) Lookup(
_ *context.T, suffix string) (interface{}, security.Authorizer, error) {
if strings.Contains(suffix, "/") {
return nil, nil, errors.New("unsupported service name")
}
auth := MakeAuthorizer()
d.mu.Lock()
defer d.mu.Unlock()
if suffix == "" {
names := make([]string, 0, len(d.registry))
for name, _ := range d.registry {
names = append(names, name)
}
return rpc.ChildrenGlobberInvoker(names...), auth, nil
}
s, ok := d.registry[suffix]
if !ok {
// Make the service on first attempt to use.
s = ifc.FortuneServer(service.Make())
d.registry[suffix] = s
}
return s, auth, nil;
}
func MakeDispatcher() rpc.Dispatcher {
return &myDispatcher {
registry: make(map[string]interface{}),
}
}
EOF
#----------------------------------------------------------------------# End 1 of 13
#----------------------------------------------------------------------# Start 2 of 13
echo "# @buildServer (block #2 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
go install fortune/server
#----------------------------------------------------------------------# End 2 of 13
#----------------------------------------------------------------------# Start 3 of 13
echo "# @runServer (block #3 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
kill_tut_process TUT_PID_SERVER
$V_TUT/bin/server \
--v23.credentials $V_TUT/cred/basics \
--endpoint-file-name $V_TUT/server.txt &
TUT_PID_SERVER=$!
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 3 of 13
#----------------------------------------------------------------------# Start 4 of 13
echo "# @firstTry (block #4 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/basics \
--server `cat $V_TUT/server.txt`
#----------------------------------------------------------------------# End 4 of 13
#----------------------------------------------------------------------# Start 5 of 13
echo "# @secondTry (block #5 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/basics \
--server `cat $V_TUT/server.txt`/cassandra
#----------------------------------------------------------------------# End 5 of 13
#----------------------------------------------------------------------# Start 6 of 13
echo "# @writingWorksToo (block #6 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/basics \
--server `cat $V_TUT/server.txt`/cassandra \
--add 'Do not visit Sparta!'
#----------------------------------------------------------------------# End 6 of 13
#----------------------------------------------------------------------# Start 7 of 13
echo "# @globServer (block #7 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
$V_BIN/namespace \
--v23.credentials $V_TUT/cred/basics \
--v23.namespace.root `cat $V_TUT/server.txt` \
glob "*"
#----------------------------------------------------------------------# End 7 of 13
#----------------------------------------------------------------------# Start 8 of 13
echo "# @startMountTable (block #8 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
PORT_MT=23000 # Pick an unused port.
kill_tut_process TUT_PID_MT
$V_BIN/mounttabled \
--v23.credentials $V_TUT/cred/basics \
--v23.tcp.address :$PORT_MT &
TUT_PID_MT=$!
export V23_NAMESPACE=/localhost:$PORT_MT
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 8 of 13
#----------------------------------------------------------------------# Start 9 of 13
echo "# @runServer2 (block #9 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
kill_tut_process TUT_PID_SERVER
$V_TUT/bin/server \
--v23.credentials $V_TUT/cred/basics \
--service-name prophInc \
--endpoint-file-name $V_TUT/server.txt &
TUT_PID_SERVER=$!
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 9 of 13
#----------------------------------------------------------------------# Start 10 of 13
echo "# @writeViaTable (block #10 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/basics \
--server prophInc/cassandra \
--add 'Troy is doomed!'
#----------------------------------------------------------------------# End 10 of 13
#----------------------------------------------------------------------# Start 11 of 13
echo "# @globMounttable (block #11 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
$V_BIN/namespace \
--v23.credentials $V_TUT/cred/basics \
glob "prophInc/*"
#----------------------------------------------------------------------# End 11 of 13
#----------------------------------------------------------------------# Start 12 of 13
echo "# @createNostradamusService (block #12 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/basics \
--server prophInc/nostradamus
$V_BIN/namespace \
--v23.credentials $V_TUT/cred/basics \
glob "prophInc/*"
#----------------------------------------------------------------------# End 12 of 13
#----------------------------------------------------------------------# Start 13 of 13
echo "# @cleanup (block #13 in __AnyLabel__) of content/tutorials/naming/suffix-part1.md"
kill_tut_process TUT_PID_SERVER
kill_tut_process TUT_PID_MT
unset V23_NAMESPACE
#----------------------------------------------------------------------# End 13 of 13
#
# Script @__AnyLabel__ from content/tutorials/naming/suffix-part2.md
#
#----------------------------------------------------------------------# Start 1 of 25
echo "# @newAuthorizer (block #1 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
cat - <<EOF >$V_TUT/src/fortune/server/util/authorizer.go
package util
import (
"strings"
"fortune/ifc"
"errors"
"v.io/v23/context"
"v.io/v23/security"
"v.io/v23/security/access"
)
type myAuthorizer struct {}
// The method being called - is it tagged?
func isTagged(call security.Call, tag string) (bool) {
for _, mTag := range call.MethodTags() {
if tag == mTag.RawString() {
return true
}
}
return false
}
func join(args ...string) security.BlessingPattern {
return security.BlessingPattern(strings.Join(args, security.ChainSeparator))
}
func (my myAuthorizer) Authorize(ctx *context.T, call security.Call) error {
if call.Suffix() == "" {
return nil
}
var (
serverBlessings = security.LocalBlessingNames(ctx, call)
clientBlessings, _ = security.RemoteBlessingNames(ctx, call)
consultant = join(serverBlessings[0], "consultant", call.Suffix())
intern = join(string(consultant), "intern")
customer = join(string(consultant), "cust")
)
if consultant.MakeNonExtendable().MatchedBy(clientBlessings...) {
return nil
}
if intern.MatchedBy(clientBlessings...) {
return nil
}
if (isTagged(call, string(ifc.Reader)) ||
isTagged(call, string(access.Resolve))) && customer.MatchedBy(clientBlessings...) {
return nil
}
return errors.New("access denied.")
}
func MakeAuthorizer() security.Authorizer {
return &myAuthorizer {}
}
EOF
#----------------------------------------------------------------------# End 1 of 25
#----------------------------------------------------------------------# Start 2 of 25
echo "# @createProphIncPrincipal (block #2 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/principal create --overwrite \
$V_TUT/cred/prophInc prophInc
$V_BIN/principal create --overwrite \
$V_TUT/cred/cassandra cassandra
$V_BIN/principal create --overwrite \
$V_TUT/cred/nostradamus nostradamus
$V_BIN/principal create --overwrite \
$V_TUT/cred/alice alice
$V_BIN/principal create --overwrite \
$V_TUT/cred/bob bob
#----------------------------------------------------------------------# End 2 of 25
#----------------------------------------------------------------------# Start 3 of 25
echo "# @buildServer (block #3 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
go install fortune/server
#----------------------------------------------------------------------# End 3 of 25
#----------------------------------------------------------------------# Start 4 of 25
echo "# @runServer (block #4 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
kill_tut_process TUT_PID_SERVER
$V_TUT/bin/server \
--v23.credentials $V_TUT/cred/prophInc \
--endpoint-file-name $V_TUT/server.txt &
TUT_PID_SERVER=$!
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 4 of 25
#----------------------------------------------------------------------# Start 5 of 25
echo "# @startMountTable (block #5 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
PORT_MT=23000 # Pick an unused port.
kill_tut_process TUT_PID_MT
$V_BIN/mounttabled \
--v23.credentials $V_TUT/cred/prophInc \
--v23.tcp.address :$PORT_MT &
TUT_PID_MT=$!
export V23_NAMESPACE=/localhost:$PORT_MT
sleep 2s # Added by mdrip
#----------------------------------------------------------------------# End 5 of 25
#----------------------------------------------------------------------# Start 6 of 25
echo "# @mountFortune (block #6 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/namespace \
--v23.credentials $V_TUT/cred/prophInc \
mount prophInc `cat $V_TUT/server.txt` 2h
#----------------------------------------------------------------------# End 6 of 25
#----------------------------------------------------------------------# Start 7 of 25
echo "# @firstTryAsCassandra (block #7 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/cassandra \
--server prophInc/cassandra
#----------------------------------------------------------------------# End 7 of 25
#----------------------------------------------------------------------# Start 8 of 25
echo "# @blessCassandra (block #8 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/principal bless \
--v23.credentials $V_TUT/cred/prophInc \
--for=24h $V_TUT/cred/cassandra consultant:cassandra | \
$V_BIN/principal set \
--v23.credentials $V_TUT/cred/cassandra \
forpeer - prophInc
#----------------------------------------------------------------------# End 8 of 25
#----------------------------------------------------------------------# Start 9 of 25
echo "# @secondTryAsCassandra (block #9 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/cassandra \
--server prophInc/cassandra
#----------------------------------------------------------------------# End 9 of 25
#----------------------------------------------------------------------# Start 10 of 25
echo "# @writingFails (block #10 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/cassandra \
--server prophInc/cassandra \
--add 'Do not visit Sparta!'
#----------------------------------------------------------------------# End 10 of 25
#----------------------------------------------------------------------# Start 11 of 25
echo "# @blessNostradamus (block #11 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/principal bless \
--v23.credentials $V_TUT/cred/prophInc \
--for=24h $V_TUT/cred/nostradamus consultant:nostradamus |\
$V_BIN/principal set \
--v23.credentials $V_TUT/cred/nostradamus \
forpeer - prophInc
#----------------------------------------------------------------------# End 11 of 25
#----------------------------------------------------------------------# Start 12 of 25
echo "# @firstTryAsNostradamus (block #12 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/nostradamus \
--server prophInc/nostradamus
#----------------------------------------------------------------------# End 12 of 25
#----------------------------------------------------------------------# Start 13 of 25
echo "# @secondTryAsNostradamus (block #13 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/nostradamus \
--server prophInc/cassandra
#----------------------------------------------------------------------# End 13 of 25
#----------------------------------------------------------------------# Start 14 of 25
echo "# @globServer (block #14 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/namespace \
--v23.credentials $V_TUT/cred/nostradamus \
glob "prophInc/*"
#----------------------------------------------------------------------# End 14 of 25
#----------------------------------------------------------------------# Start 15 of 25
echo "# @cassandraDelegatesToAlice (block #15 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/principal get \
--v23.credentials $V_TUT/cred/cassandra \
forpeer prophInc | \
$V_BIN/principal bless \
--v23.credentials $V_TUT/cred/cassandra \
--with=- --for=24h $V_TUT/cred/alice intern:alice |\
$V_BIN/principal set \
--v23.credentials $V_TUT/cred/alice \
forpeer - prophInc
#----------------------------------------------------------------------# End 15 of 25
#----------------------------------------------------------------------# Start 16 of 25
echo "# @firstTryAsAlice (block #16 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/alice \
--server prophInc/cassandra
#----------------------------------------------------------------------# End 16 of 25
#----------------------------------------------------------------------# Start 17 of 25
echo "# @secondTryAsAlice (block #17 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/alice \
--server prophInc/nostradamus
#----------------------------------------------------------------------# End 17 of 25
#----------------------------------------------------------------------# Start 18 of 25
echo "# @globServer (block #18 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/namespace \
--v23.credentials $V_TUT/cred/alice \
glob "prophInc/*"
#----------------------------------------------------------------------# End 18 of 25
#----------------------------------------------------------------------# Start 19 of 25
echo "# @bobIsCustomerOfNostradamus (block #19 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/principal get \
--v23.credentials $V_TUT/cred/nostradamus \
forpeer prophInc | \
$V_BIN/principal bless \
--v23.credentials $V_TUT/cred/nostradamus \
--with=- --for=24h $V_TUT/cred/bob cust:bob | \
$V_BIN/principal set \
--v23.credentials $V_TUT/cred/bob \
forpeer - prophInc
#----------------------------------------------------------------------# End 19 of 25
#----------------------------------------------------------------------# Start 20 of 25
echo "# @bobCanRead (block #20 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/bob \
--server prophInc/nostradamus
#----------------------------------------------------------------------# End 20 of 25
#----------------------------------------------------------------------# Start 21 of 25
echo "# @bobCannotWrite (block #21 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/bob \
--server prophInc/nostradamus \
--add 'Bob is so Cool!'
#----------------------------------------------------------------------# End 21 of 25
#----------------------------------------------------------------------# Start 22 of 25
echo "# @bobCannotReadCassandra (block #22 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/bob \
--server prophInc/cassandra
#----------------------------------------------------------------------# End 22 of 25
#----------------------------------------------------------------------# Start 23 of 25
echo "# @bobOnlySeesNostradamus (block #23 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_BIN/namespace \
--v23.credentials $V_TUT/cred/bob \
glob "prophInc/*"
#----------------------------------------------------------------------# End 23 of 25
#----------------------------------------------------------------------# Start 24 of 25
echo "# @aliceReadsNostradamus (block #24 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
$V_TUT/bin/client \
--v23.credentials $V_TUT/cred/alice \
--server prophInc/nostradamus
#----------------------------------------------------------------------# End 24 of 25
#----------------------------------------------------------------------# Start 25 of 25
echo "# @cleanup (block #25 in __AnyLabel__) of content/tutorials/naming/suffix-part2.md"
kill_tut_process TUT_PID_SERVER
kill_tut_process TUT_PID_MT
unset V23_NAMESPACE
#----------------------------------------------------------------------# End 25 of 25
echo " "
echo "All done. No errors."
|
Python
|
UTF-8
| 610
| 3.5
| 4
|
[] |
no_license
|
class Solution:
def detectCapitalUse(self, word: str) -> bool:
variations = []
variations.append(word.upper())
variations.append(word.lower())
variations.append(word.capitalize())
if word in variations:
return True
else:
return False
''' count= 0
for char in word:
if char.isupper():
count += 1
return len(word) == count
This case passes most cases. It fails when the letter is a single alphabet "a" to "z".
'''
|
PHP
|
UTF-8
| 597
| 2.71875
| 3
|
[] |
no_license
|
<?php
namespace App\DataStructures;
class JsonBuilder
{
public static function data($data)
{
return [
'data' => $data
];
}
public static function success($message, $code)
{
return [
'message' => $message,
'code' => $code
];
}
public static function message($message)
{
return [
'message' => $message
];
}
public static function error($message, $code)
{
return [
'message' => $message,
'code' => $code
];
}
}
|
Python
|
UTF-8
| 1,490
| 2.84375
| 3
|
[] |
no_license
|
# Old code from the good old multithreaded days
'''
def playerthread(conn, player_number):
global current_player
global prev_pass
conn.send('Connected. You are player number ' + str(player_number) + '\n');
data = conn.recv(1024)
while data:
# print data
cmdlist = data.split()
cmd = cmdlist[0]
args = cmdlist[1:]
if cmd == 'PLAY':
if current_player != player_number:
conn.sendall('ERROR: It\'s not your turn\n')
elif len(args) != 2:
conn.sendall('ERROR: Wrong number of arguments for PLAY\n')
else:
try:
row = int(args[0])
col = int(args[1])
gb.play(player_number, row, col)
current_player = 2 if (player_number == 1) else 1
conn.sendall('SUCCESS: Play made at row '+str(row)+', column '+str(col)+'\n')
gb.dbg_print()
except goban.GobanError as e:
conn.sendall('ERROR: Goban error: '+str(e)+'\n')
except ValueError:
conn.sendall('ERROR: row/column argument for PLAY was not an int\n')
elif cmd == 'PASS':
current_player = 2 if (player_number == 1) else 1
conn.sendall('SUCCESS: You passed this turn')
else:
conn.sendall('ERROR: Unrecognized command '+cmd+'\n')
# receive new data
data = conn.recv(1024)
# conn.sendall('fdsfds\n')
print 'Connection 1 closed'
'''
|
JavaScript
|
UTF-8
| 1,365
| 2.578125
| 3
|
[] |
no_license
|
// import the packages from node_modules
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
const fs = require("fs"); // give access to the file system
require("dotenv").config();
// import routes
// const authRoutes = require("./routes/auth");
// create the app
const app = express();
// connect to MongoDB using Mongoose
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: true,
})
.then(() => console.log("DB CONNECTED"))
.catch((error) => console.log(`DB CONNECTION ERR ${error}`));
// middlewares: a function that runs inbetween
app.use(morgan("dev")); // use morgan to check how much time it takes to get /api
app.use(bodyParser.json({ limit: "2mb" }));
app.use(cors());
// route middlewares
// app.use("/api", authRoutes);
fs.readdirSync("./routes").map(
(r) => app.use("/api", require("./routes/" + r)) // autoload all the routes
);
// route (moved the following to auth.js)
// app.get("/api", (req, res) => {
// // send some hard coded data
// res.json({
// data: "hey you hit node API",
// });
// });
// port
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
|
Python
|
UTF-8
| 121
| 2.53125
| 3
|
[] |
no_license
|
def primeiras_ocorrencias(x):
dic = {}
for i in range(len(x)):
dic[x][i] = i
return dic
|
Python
|
UTF-8
| 168
| 2.953125
| 3
|
[] |
no_license
|
x = int(input())
if x <= 3:
print(1)
exit()
res = 0
for i in range(2, 33):
for j in range(2, 12):
a = i ** j
if a <= x:
res = max(res, a)
print(res)
|
Shell
|
UTF-8
| 426
| 2.96875
| 3
|
[] |
no_license
|
# Maintainer: Hatem Masmoudi <hatem.masmoudi@gmail.com>
pkgname=core-version
pkgver=2018.06.16
pkgrel=2
pkgdesc="Contains SyphaxOS Core version."
arch=('x86_64')
license=('GPL')
groups=('core')
depends=('rootfs')
prepare() {
mkdir -pv "$srcdir/$pkgname-$pkgver"
}
package() {
cd "$srcdir/$pkgname-$pkgver"
mkdir -p $pkgdir/etc
cp ../../lsb-release $pkgdir/etc/
cp ../../os-release $pkgdir/etc/
cp ../../issue $pkgdir/etc/
}
|
Java
|
UTF-8
| 1,165
| 2.859375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package no.kantega.search.api.search;
import java.util.Date;
public class DateRange {
private final String field;
private final String gap;
private final Date from;
private final Date to;
/**
* @param field to create date range from
* @param from the date to start
* @param to the date to end
* @param gap spacing between facets. As seen in DateMathParser. Example 1DAY.
* @see org.apache.solr.util.DateMathParser
*/
public DateRange(String field, Date from, Date to, String gap) {
this.field = field;
this.gap = gap;
this.from = from;
this.to = to;
}
/**
* @return the field this DateRange should apply to.
*/
public String getField() {
return field;
}
/**
* @return the spacing between each facet.
* @see org.apache.solr.util.DateMathParser
*/
public String getGap() {
return gap;
}
/**
* @return the start of this range.
*/
public Date getFrom() {
return from;
}
/**
* @return the end of this range.
*/
public Date getTo() {
return to;
}
}
|
JavaScript
|
UTF-8
| 308
| 3.25
| 3
|
[] |
no_license
|
const HOUR_IN_MS = 1000 * 60 * 60
const differenceInHours = (dateA, dateB) =>
Math.trunc((dateA - dateB) / HOUR_IN_MS)
// How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00?
module.exports = differenceInHours(
new Date(2014, 6, 2, 19, 0),
new Date(2014, 6, 2, 6, 50)
)
// => 12
|
C++
|
UTF-8
| 3,954
| 2.921875
| 3
|
[] |
no_license
|
#include "JSONObject.h"
int __jsoneq(const char *json, jsmntok_t *tok, const char *s)
{
if (tok->type == JSMN_STRING && (int)strlen(s) == tok->end - tok->start &&
strncmp(json + tok->start, s, tok->end - tok->start) == 0)
{
return 0;
}
return -1;
}
JSONObject *JSONObject_CreateObject(void)
{
JSONObject *returnObject = (JSONObject *)malloc(sizeof(JSONObject));
returnObject->tokens_counter = 0;
jsmn_init(&(returnObject->parser));
return returnObject;
}
JSONObject_OperationResultCode JSONObject_Parse(JSONObject *json_object, const char *json_string)
{
json_object->json_string = json_string;
json_object->tokens_counter = jsmn_parse(&(json_object->parser), json_string, strlen(json_string), (json_object->tokens), sizeof(json_object->tokens) / sizeof((json_object->tokens)[0]));
if (json_object->tokens_counter < 0)
{
return OPERATION_FAIL;
}
else if (json_object->tokens_counter < 1 || (json_object->tokens)[0].type != JSMN_OBJECT)
{
return OPERATION_FAIL;
}
else
{
return OPERATION_SUCCESS;
}
}
const char *JSONObject_GetOperationResultName(JSONObject_OperationResultCode code)
{
static const char *JSONObject_OperationResultCodeName[] = {
"OPERATION_FAIL",
"OPERATION_SUCCESS"};
return JSONObject_OperationResultCodeName[code];
}
JSONObject_OperationResultCode JSONObject_GetString(JSONObject *json_object, const char *key, char **returnValue)
{
int i = 1;
*returnValue = (char *)malloc(sizeof(char) * NUM_OF_MAX_STRING_BUFFER);
for (i = 1; i < json_object->tokens_counter; i++)
{
if (__jsoneq(json_object->json_string, &(json_object->tokens[i]), key) == 0)
{
sprintf(*returnValue, "%.*s", json_object->tokens[i + 1].end - json_object->tokens[i + 1].start, json_object->json_string + json_object->tokens[i + 1].start);
break;
}
}
if (i == json_object->tokens_counter)
{
return OPERATION_FAIL;
}
else
{
return OPERATION_SUCCESS;
}
}
JSONObject_OperationResultCode JSONObject_GetFloat(JSONObject *json_object, const char *key, float *returnValue)
{
char *strValue;
JSONObject_OperationResultCode res = JSONObject_GetString(json_object, key, &strValue);
if (res == OPERATION_SUCCESS)
{
*returnValue = atof(strValue);
return OPERATION_SUCCESS;
}
else
{
return OPERATION_FAIL;
}
}
JSONObject_OperationResultCode JSONObject_GetInt(JSONObject *json_object, const char *key, int *returnValue)
{
char *strValue;
JSONObject_OperationResultCode res = JSONObject_GetString(json_object, key, &strValue);
if (res == OPERATION_SUCCESS)
{
*returnValue = atoi(strValue);
return OPERATION_SUCCESS;
}
else
{
return OPERATION_FAIL;
}
}
JSONObject_OperationResultCode JSONObject_GetLong(JSONObject *json_object, const char *key, long *returnValue)
{
char *strValue;
JSONObject_OperationResultCode res = JSONObject_GetString(json_object, key, &strValue);
if (res == OPERATION_SUCCESS)
{
*returnValue = atol(strValue);
return OPERATION_SUCCESS;
}
else
{
return OPERATION_FAIL;
}
}
JSONObject_OperationResultCode JSONObject_GetBool(JSONObject *json_object, const char *key, __boolType *returnValue)
{
char *strValue;
JSONObject_OperationResultCode res = JSONObject_GetString(json_object, key, &strValue);
if (res == OPERATION_SUCCESS)
{
if (strcmp(strValue, "true") == 0)
{
*returnValue = __boolTrueValue;
}
else if (strcmp(strValue, "false") == 0)
{
*returnValue = __boolFalseValue;
}
else
{
return OPERATION_FAIL;
}
return OPERATION_SUCCESS;
}
else
{
return OPERATION_FAIL;
}
}
|
Java
|
UTF-8
| 381
| 1.851563
| 2
|
[] |
no_license
|
package yp.com.akki.ypreportadmin.network;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
/**
* Created by akshaybmsa96 on 13/02/18.
*/
public interface ApiClientSubmitAttendance {
@POST("attendance/")
@FormUrlEncoded
Call<String> submitAttendance(@Field("data") String data);
}
|
C#
|
UTF-8
| 7,706
| 3.625
| 4
|
[] |
no_license
|
using System;
using System.Collections;
namespace Hierarchy
{
[Serializable]
public class MyQueue<T> : IEnumerable
{
public int Capacity { get; private set; } //Вместимость
public int Count { get; private set; } //Кол-во элементов
internal QueueElement<T> QueueElement; //Элемент очереди
public bool Add(T person, int index) //Добавить элемент
{
if (index <= Count)
{
if (Count == index)
Enqueue(person);
else
{
QueueElement<T> nextElement = this[index];
this[index - 1].Next = new QueueElement<T>(person);
this[index].Next = nextElement;
}
if (++Count == Capacity)
Capacity *= 2;
return true;
}
else
return false;
}
public bool Remove(int index) //Удалить элемент
{
if (index <= Count)
{
if (index == Count)
this[index] = null;
if (index == 0)
{
for (int i = 0; i < Count - 1; i++)
this[i].Data = this[i + 1].Data;
this[Count] = null;
}
else
this[index - 1].Next = this[index].Next;
Count--;
return true;
}
return false;
}
public QueueElement<T> this[int index] //Индекс элемента
{
get
{
if (index < Count)
{
int count = 0;
foreach (var element in this)
{
if (count == index) return (QueueElement<T>)element;
count++;
}
}
else Console.WriteLine("Индекс неверен!");
return null;
}
set
{
if (index < Count)
{
QueueElement<T> root = QueueElement;
for (var count = 0; count <= Count; count++)
{
if (count == index)
{
root = value;
break;
}
else root = root.Next;
}
}
else Console.WriteLine("Индекс неверен!");
}
}
#region Constructors
//Пустой конструктор
public MyQueue()
{
Capacity = 10;
}
//С заданным разрешением(ёмкостью)
public MyQueue(int capacity)
{
Capacity = capacity;
}
//Элементы и емкости другой последовательность(not ready)
public MyQueue(MyQueue<T> queue)
{
Capacity = queue.Capacity;
Count = queue.Count;
QueueElement = queue.QueueElement;
}
#endregion
#region Methods
public bool Contains(object queueElement) //Проверить содержание
{
foreach (var queue in this)
if (queue.Equals(queueElement))
return true;
return false;
}
public void Clear() //Очистить
{
Count = 0;
QueueElement = null;
}
public T Dequeue() //Исключить из очереди
{
Count--;
T data = QueueElement.Data;
QueueElement = QueueElement.Next;
return data;
}
public void Enqueue(T addElement) //Включить в очередь
{
Count++;
Capacity *= Count == Capacity ? 2 : 1;
QueueElement<T> add = new QueueElement<T>(addElement);
QueueElement<T> beg = QueueElement;
if (beg != null)
{
while (beg.Next != null)
beg = beg.Next;
add.Next = beg.Next;
beg.Next = add;
}
else
QueueElement = add;
}
public T Peek() //Возвращает значение элемента
{
return QueueElement.Data;
}
public T[] ToArray() //Преобразование в массив
{
T[] array = new T[0];
foreach (T add in this)
{
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = add;
}
return array;
}
public MyQueue<T> Clone() //Клонирование
{
MyQueue<T> newQueue = new MyQueue<T>(Capacity);
foreach (QueueElement <T> cloneElement in this)
newQueue.Enqueue(cloneElement.Data);
return newQueue;
}
public void CopyTo(out T[] array, int arrayIndex) //Копирование
{
array = new T[arrayIndex];
int i = 0;
foreach (T addElement in this)
{
array[i] = addElement;
i++;
if (i == arrayIndex)
{
return;
}
}
}
#endregion
public IEnumerator GetEnumerator()
{
return new ClassEnumerator<T>(this);
}
}
[Serializable]
public class QueueElement<T> //Класс элемента
{
public T Data; //информационное поле
public QueueElement<T> Next; //адресное поле
public QueueElement() //конструктор без параметров
{
Data = default(T);
Next = null;
}
public QueueElement(T d) //конструктор с параметрами
{
Data = d;
Next = null;
}
public override bool Equals(object obj)
{
QueueElement<T> queue = (QueueElement<T>)obj;
return (Data.Equals(queue.Data));
}
public override string ToString()
{
return Data + " ";
}
}
public class ClassEnumerator<T> : IEnumerator
{
private int _position = -1; //Начальная позиция
private readonly MyQueue<T> _t; //Очередь
private QueueElement<T> currElement; //Текущий элемент
public ClassEnumerator(MyQueue<T> t) //Конструктор с параметрами
{
_t = t;
currElement = _t.QueueElement;
}
// Перемещение вперёд
public bool MoveNext()
{
if (_position == -1)
{
_position++;
return true;
}
if (currElement.Next != null)
{
_position++;
currElement = currElement.Next;
return true;
}
return false;
}
// Возврат в начало
public void Reset()
{
_position = -1;
}
// Текущий элемент
public object Current => currElement;
}
}
|
Java
|
UTF-8
| 585
| 3.421875
| 3
|
[] |
no_license
|
package ch18;
import java.util.*;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<String, Double> tm = new TreeMap<String, Double>(new RevLastNameComparator());
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Tod Hall", new Double(99.22));
tm.put("Ralph Zhen", new Double(-19.08));
Set<Map.Entry<String, Double>> set = tm.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
}
|
Markdown
|
UTF-8
| 3,098
| 2.875
| 3
|
[] |
no_license
|
---
layout: post
title: Maya - Keyframe Reduction
description: Keyframe reduction for Maya using least-squares method.
img: /img/tools/keyframe_reduction_thumbnail.png
date: 2019-02-10 15:30:00
category: [tools]
tag: [tool, python, maya, pyside, rigging, animation]
github: https://github.com/robertjoosten/maya-keyframe-reduction
github-docs: https://robertjoosten.github.io/maya-keyframe-reduction/
gumroad: https://gum.co/maya-keyframe-reduction
---
<p class="justify">Keyframe reduction for Maya using least-squares method.</p>
<p align="center"><iframe width="640" height="360" src="https://www.youtube.com/embed/9Zszvc_pxuw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>
<h4>Installation</h4>
* Extract the content of the .rar file anywhere on disk.
* Drag the keyframeReduction.mel file in Maya to permanently install the script.
<h4>Usage</h4>
<p class="justify">A button on the MiscTools shelf will be created that will allow easy access to the ui, this way the user doesn't need to worry about any of the code. If user wishes to not use the shelf button the following commands can be used.</p>
<p class="justify">The ui responds to the current selection where it finds all of the suitable animation curves for reduction. You will be able to filter the animation curves based on the plug it is connected to. This will make it easier to target exactly the curves you want to reduce.</p>
<p class="justify">After an animation curve is reduced the reduction percentage will be printed to the console. This can give you an idea if you would like to increase or decrease the error rate to get the desired results.</p>
<h4>UI</h4>
<p align="center"><img src="/img/tools/keyframe_reduction_ui.png"/></p>
Display the UI with the following code.
{% highlight python %}
import keyframeReduction.ui
keyframeReduction.ui.show()
{% endhighlight %}
<h4>Command Line</h4>
Use the KeyframeReduction class on individual animation curves.
{% highlight python %}
from keyframeReduction import KeyframeReduction
obj = KeyframeReduction(pathToAnimCurve)
obj.reduce(error=0.1)
{% endhighlight %}
<h4>Options</h4>
* **error**<br>The maximum amount the reduced curve is allowed to deviate from the sampled curve.
* **step**<br>The step size to sample the curve.
* **weightedTangents**<br>Reduce curve using weighted tangents, using weighted tangents will result in less keyframes but is a bit slower to calculate.
* **tangentSplitAuto**<br>Automatically split tangents based on the angles of the sampled curve and deviation of those angles from the mean.
* **tangentSplitExisting**<br>Use existing keyframes that have split tangents as a split tangent point.
* **tangentSplitAngleThreshold**<br>Split tangents based on an angle value threshold.
* **tangentSplitAngleThresholdValue**<br>Split tangent angle threshold value.
<h4>Note</h4>
The fitting algorithm is ported from <a href="http://paperjs.org/">Paper.js - The Swiss Army Knife of Vector Graphics Scripting</a>.
|
Java
|
UTF-8
| 9,382
| 2.375
| 2
|
[
"MIT"
] |
permissive
|
package odfgenerator;
import com.independentsoft.office.odf.TextDocument;
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class MainOverviewController {
private MainApp mainApp;
@FXML
private TextField templatePathField;
@FXML
private TextField saveDirField;
@FXML
private TextField docNameField;
@FXML
private ChoiceBox<String> indexBox;
@FXML
private TableView<List<String>> dataTable;
@FXML
private CheckBox firstRowTitlesBox;
private ObservableList<String> indexList;
private Map<String, Integer> indexMap;
public MainOverviewController() {
}
@FXML
private void initialize() {
dataTable.setPlaceholder(new Label("Данные не загружены"));
resetIndexList();
indexBox.setItems(indexList);
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
@FXML
private void searchTemplate() {
//Открывается системное окно выбора файла
//После выбора файла путь к нему записывается в соответствующее поле
//Также после следующего открытия диалогового окна будет открыта последняя папка
//Остальные методы с диалоговым окном работают так же
File templateODT = mainApp.templateChooser.showOpenDialog(mainApp.getPrimaryStage());
if (templateODT != null) {
templatePathField.setText(templateODT.getPath());
mainApp.templateChooser.setInitialDirectory(new File(templateODT.getParent()));
}
}
@FXML
private void searchSaveDir() {
File saveDir = mainApp.directoryChooser.showDialog(mainApp.getPrimaryStage());
if (saveDir != null) {
saveDirField.setText(saveDir.getPath());
mainApp.directoryChooser.setInitialDirectory(saveDir);
}
}
@FXML
private void readData() {
try {
File dataODS = mainApp.dataODSChooser.showOpenDialog(mainApp.getPrimaryStage());
if (dataODS != null) {
//Перед считыванием данных таблица данных очищается
dataTable.getColumns().clear();
boolean firstRowTitles = firstRowTitlesBox.selectedProperty().getValue();
resetIndexList();
mainApp.odfTemplateProcessor.readDataFromODS(dataODS.getPath(), firstRowTitles);
ObservableList<List<String>> observableData = FXCollections.observableArrayList(mainApp.odfTemplateProcessor.data);
//Если в первой строке таблицы ODS заголовки, они не должны заноситься в таблицу в окне приложения как данные
if (firstRowTitles) {
observableData.remove(0);
}
int colCount = observableData.get(0).size();
for (int i = 0; i < colCount; i++) {
String colTitle;
if (firstRowTitles) {
colTitle = mainApp.odfTemplateProcessor.data.get(0).get(i);
} else {
colTitle = "Колонка " + (i + 1);
}
TableColumn col = new TableColumn<>(colTitle);
final int colNo = i;
//Эта конструкция позволяет отображать данные из двухмерных списков в TableView
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<List<String>, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<List<String>, String> p) {
return new SimpleStringProperty(p.getValue().get(colNo));
}
});
col.setPrefWidth(90);
dataTable.getColumns().add(col);
indexList.add(colTitle);
indexMap.put(colTitle, i);
}
dataTable.setItems(observableData);
indexBox.setItems(indexList);
mainApp.dataODSChooser.setInitialDirectory(new File(dataODS.getParent()));
}
} catch (IndexOutOfBoundsException e) {
//При передаче некорректного файла пользователю выдается предупреждение
e.printStackTrace();
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Ошибка!");
alert.setHeaderText("Загрузка данных отменена");
alert.setContentText("Выбранный файл пуст или не является ODS");
alert.showAndWait();
}
}
@FXML
private void generateDocuments() {
Alert alert;
mainApp.odfTemplateProcessor.setTemplate(templatePathField.getText());
//Если поле директории для сохранения не указано, фалы будут сохранены в директорию шаблона
String dirPath;
if (saveDirField.getText().isBlank()) {
dirPath = new File(templatePathField.getText()).getParent();
} else {
dirPath = saveDirField.getText();
}
mainApp.odfTemplateProcessor.setSaveDirectory(dirPath);
//Если не указано имя для генерируемых шаблонов, будет использоваться имя файла шаблона
if (docNameField.getText().isBlank()) {
mainApp.odfTemplateProcessor.setSaveName(new File(templatePathField.getText()).getName().replace(".odt",""));
} else {
mainApp.odfTemplateProcessor.setSaveName(docNameField.getText());
}
//Выдать предупреждение пользователю в случае, если он не укажет способ индексации готовых документов
if (indexBox.getValue() == null) {
alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Ошибка");
alert.setHeaderText("Способ индексации не выбран");
alert.setContentText("Выберите нужный способ именования сгенерированных документов");
alert.showAndWait();
return;
}
try {
mainApp.odfTemplateProcessor.generateDocuments(indexMap.get(indexBox.getValue()));
//Уведомление пользователя в случае успешной генерации документов
alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Успех!");
alert.setHeaderText("Генерация документов завершена");
alert.setContentText("Сорхаренные документы сохранены в директории " + dirPath);
alert.showAndWait();
} catch (FileNotFoundException e) {
//Предупредение при передаче некорректного файла шаблона
alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Ошибка");
alert.setHeaderText("Генерация документов отменена");
alert.setContentText("Проверьте путь к шаблону");
alert.showAndWait();
} catch (NullPointerException e) {
//Предупреждение в случае, если данные для генерации не были загружены
alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Ошибка");
alert.setHeaderText("Генерация документов отменена");
alert.setContentText("Вы не загрузили данные");
alert.showAndWait();
}
}
//Метод для повторной генерации содержимого выпадающего списка
private void resetIndexList() {
indexList = FXCollections.observableArrayList();
indexMap = new HashMap<>();
indexList.add("Пронумеровать");
indexMap.put("Пронумеровать", -1);
}
}
|
Markdown
|
UTF-8
| 1,846
| 3.328125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
- Start Date: 2017-01-20
- RFC Issue: #30
- RFC PR:
- Implementation Issue:
# Summary
[summary]: #summary
Define the format for struct and union declarations.
# Details
[details]: #details
Struct names follow on the same line as the `struct` keyword, with the opening brace on
the same line when it fits within the right margin. All struct fields are indented once and
end with a trailing comma. The closing brace is not indented and appears on its own line.
```rust
struct Foo {
a: A,
b: B,
}
```
If and only if the type name does not fit within the right margin, it is pulled down to its
own line and indented again.
```rust
struct Foo {
a: A,
long_name:
LongName,
}
```
The same guidelines are used for untagged unions declarations.
```rust
union Foo {
a: A,
b: B,
}
```
# Implementation
[implementation]: #implementation
`rustfmt` currently formats structs correctly, except for the case where a long
type name needs to be indented onto its own line.
Unions are currently not supported by `rustfmt:`
[rust-lang-nursery/rustfmt#1157](https://github.com/rust-lang-nursery/rustfmt/issues/1157)
# Rationale
[rationale]: #rationale
Requiring a trailing comma on the last struct field has the following benefits:
- Follows the principle to use a trailing comma when it is followed by a newline:
[#42](https://github.com/rust-lang-nursery/fmt-rfcs/issues/42)
- Avoids the need to add a comma when adding another field
- Avoids the need to delete a comma with deleting a field
- Allows easier copying of fields between different structs
# Alternatives
[alternatives]: #alternatives
Some prefer to omit the trailing comma from the final struct field.
# Unresolved questions
[unresolved]: #unresolved-questions
Unions have not been stabilized yet, and thus the syntax could possibly change.
|
Python
|
UTF-8
| 9,766
| 2.9375
| 3
|
[] |
no_license
|
"""Hue Controller Module (main script)."""
import sys
import os
from hue_controller.hue_classes import HueBridge
from hue_controller.hue_util import get_next
def print_help():
"""Print Help Information."""
help_str = """Usage: hue_controller.py <command> [params]
Special Commands:
--init-bridge 'bridge name' 'ip'
Initializes new Hue Bridge at given ip.
Press hue sync button before executing.
--show-bridges
Shows all avaliable initialized bridges.
================================================================================
Bridge-Specific Commands (Specify bridge with -b 'bridge_name'):
--show-lights
Lists lights connected to a bridge.
--show-groups
Lists groups defined for a bridge.
--reset-lock
Removes lockfile for bridge.
-------------------------------------------------------------------------------
Grouping:
--create-group 'group_name|light1;light2;light3...'
Creates group of lights by light name.
--remove-group 'group_name'
Removes group by name.
-------------------------------------------------------------------------------
Light Control:
--on 'light_name'
Turns on light by name.
--off 'light_name'
Turns off light by name.
--toggle 'light_name1;light_name2;light_name3...'
Toggle on-status of (multiple) lights by name (separate lights by semicolon).
Lights will be toggled individually.
--group-on 'group_name'
Turns on all lights in group by name
--group-off 'group_name'
Turns off all lights in group by name
--toggle-group 'group_name'
Toggles all on-states of lights in group
Lights will be toggled individually
--set-bsh 'light_name|brightness;saturation;hue'
Sets brightness, saturation and hue for light by name.
Brightness and saturation values are percentages.
Hue value is between 0 and 65535.
--set-bsh-group 'group_name|brightness;saturation;hue'
Similar to --set-bsh.
Sets brightness, saturation and hue for a group.
--inc-bsh 'light_name|brightness;saturation;hue'
Increments brightness, saturation and hue of a light by name.
Brightness and Saturation increments in are percentages.
Hue increment is between 0 and 65535
--inc-bsh-group 'group_name|brightness;saturation;hue'
Similar to --inc-bsh.
Increments brightness, saturation and hue for a group.
"""
print(help_str)
def get_input_params():
"""Get input parameters and manage special commands.
Returns
-------
Tuple (str, str, str)
Information on input parameters
"""
bridge_name = None
action = None
params = None
# TODO: Make this more Elegant. Use Dict for actions
for element in sys.argv:
if element in ("--help", "-h"):
print_help()
return None, None, None
if element == "--show-bridges":
for bridge_file in os.scandir(HueBridge.HUE_FILE_LOCATION):
print(bridge_file.name.strip(".json"))
return None, None, None
if element == "--init-bridge":
bridge_name = get_next(sys.argv, element)
ip = get_next(sys.argv, bridge_name)
bridge = HueBridge(bridge_name, ip)
bridge.serialize()
print(f"Created Hue Bridge {bridge_name} at IP {ip}")
return None, None, None
if element == "-b":
bridge_name = get_next(sys.argv, element)
if element == "--show-lights":
action = "SHOWLIGHTS"
params = None
break
if element == "--show-groups":
action = "SHOWGROUPS"
params = None
break
if element == "--on":
action = "TURNON"
params = get_next(sys.argv, element).split(";")
break
if element == "--off":
action = "TURNOFF"
params = get_next(sys.argv, element).split(";")
break
if element == "--toggle":
action = "TOGGLE_LIGHTS"
params = get_next(sys.argv, element).split(";")
if element == "--create-group":
action = "CREATEGROUP"
group_name, lights = get_next(sys.argv, element).split("|")
params = [group_name, lights.split(";")]
break
if element == "--remove-group":
action = "REMOVEGROUP"
params = get_next(sys.argv, element)
break
if element == "--group-on":
action = "GROUPON"
params = get_next(sys.argv, element)
break
if element == "--group-off":
action = "GROUPOFF"
params = get_next(sys.argv, element)
break
if element == "--toggle-group":
action = "TOGGLE_GROUP"
params = get_next(sys.argv, element)
if element == "--set-bsh":
action = "SETBSH"
light_name, l_params = get_next(sys.argv, element).split("|")
params = [light_name, l_params.split(";")]
break
if element == "--set-bsh-group":
action = "SETBSHGROUP"
group_name, l_params = get_next(sys.argv, element).split("|")
params = [group_name, l_params.split(";")]
break
if element == "--inc-bsh":
action = "INCBSH"
light_name, inc_params = get_next(sys.argv, element).split("|")
params = [light_name, inc_params.split(";")]
break
if element == "--inc-bsh-group":
action = "INCBSHGROUP"
group_name, inc_params = get_next(sys.argv, element).split("|")
params = [group_name, inc_params.split(";")]
break
if element == "--reset-lock":
action = "RESETLOCK"
params = None
break
if not action:
print("No or unknown action."
"Try calling with parameter -h or --help for all avaliable options.")
return bridge_name, action, params
def main():
"""Manage command line input obtained through get_input_params.
Sanitizes values input values and calls hue bridge functions
to control lights and output information on hue bridge
"""
bridge_name, action, params = get_input_params()
if bridge_name:
bridge = HueBridge(bridge_name)
# Creating lockfile to prevent multiple simultateous actions on hue bridge
lockfile_path = f"{HueBridge.HUE_FILE_LOCATION}/{bridge_name}.lck"
# Lock reset
if action == "RESETLOCK":
try:
os.remove(lockfile_path)
except FileNotFoundError:
print(f"No lockfile found for bridge '{bridge_name}'.")
else:
print(f"Removed lockfile for bridge '{bridge_name}'.")
if not os.path.isfile(lockfile_path):
with open(lockfile_path, "w+") as lck_file:
lck_file.write(f"{bridge_name} is locked!")
if action == "TURNON":
bridge.set_light_on(params)
if action == "TURNOFF":
bridge.set_light_off(params)
if action == "TOGGLE_LIGHTS":
bridge.toggle_lights(params)
if action == "GROUPON":
bridge.set_group_on(params)
if action == "GROUPOFF":
bridge.set_group_off(params)
if action == "TOGGLE_GROUP":
bridge.toggle_group(params)
# removes "" values and replaces them with none, so nothing is changed
if "BSH" in action:
light_vals = params[1]
for index, val in enumerate(light_vals):
try:
light_vals[index] = int(val)
except ValueError:
light_vals[index] = None
# setting actions
if action == "SETBSH":
bridge.set_bri_sat_hue([params[0]], brightness=light_vals[0],
saturation=light_vals[1], hue=light_vals[2])
elif action == "SETBSHGROUP":
bridge.group_set_bri_sat_hue(params[0], brightness=light_vals[0],
saturation=light_vals[1], hue=light_vals[2])
# incrementing actions
elif action == "INCBSH":
bridge.increment_light([params[0]], brightness_inc=light_vals[0],
saturation_inc=light_vals[1], hue_inc=light_vals[2])
elif action == "INCBSHGROUP":
bridge.increment_group(params[0], brightness_inc=light_vals[0],
saturation_inc=light_vals[1], hue_inc=light_vals[2])
if action == "CREATEGROUP":
try:
bridge.create_group(*params)
except KeyError:
print("Correct Usage:"
" -b hue_bridge --create-group 'group_name|light_1;light_2;...")
if action == "REMOVEGROUP":
bridge.remove_group(params)
if action == "SHOWLIGHTS":
for light in bridge.lights:
print(light)
if action == "SHOWGROUPS":
for group in bridge.groups:
print(f"{group:>15}: {bridge.groups[group]}")
os.remove(lockfile_path)
if __name__ == "__main__":
main()
|
PHP
|
UTF-8
| 4,035
| 2.765625
| 3
|
[] |
no_license
|
<?php
/**
* @author IMobiGeeks
* @category Controller
* @desc This is a utility class
*
*/
class Utility
{
/**
* Function - urlEncode
*
* This function is used to encode a given URL
*
* @param $url - it contains a url
* @return- it returns encoded URL
*/
function urlEncode($url)
{
$decoded_url=urldecode($url);
$encoded_url= implode("/", array_map("rawurlencode", explode("/", $decoded_url)));
$encode_url=str_replace("%3A",":",$encoded_url);
$encode_url=str_replace("%23","#",$encode_url);
$encode_url=str_replace("%3F","?",$encode_url);
$encode_url=str_replace("%3D","=",$encode_url);
$encode_url=str_replace("%26","&",$encode_url);
$encode_url=str_replace("%2C",",",$encode_url);
return $encode_url;
}
/**
* Function - spacesEncode
*
* This function is used to encode spaces if exist in given url
*
* @param $url - it contains a url
* @return returns spaces encoded URL
*/
function spacesEncode($url)
{
$decoded_url=urldecode($url);
$encode_url=str_replace(" ","%20",$decoded_url);
return $encode_url;
}
/**
* Function - updateHTMLDescription
*
* This function is used to add font tags to the html content
*
* @param $description - it contains the description
* @return returns the html description by adding font tag to it
*/
function updateHTMLDescription($description)
{
$description1="<style type='text/css'>h1,h2,h3{color : #F1C40F;}h5{font-style:italic}blockquote{color:#747474;font-style:italic;}img {max-width: 100%;height: auto;}</style>";
$description=$description1."<font style='font-family: roboto,helvetica, arial;'>" .stripslashes ( html_entity_decode(str_replace(' ', ' ',stripslashes ($description)),ENT_QUOTES,"UTF-8") )."</font>";
return $description;
}
/**
* Function - getLatlang
*
* This function is used to get latitude and longitude values based on given address
*
* @param $addressline1 - It contains address line 1
* @param $addressline2 - It contains address line 2
* @param $city - It contains city
* @param $state - It contains state
* @param $zipcode - - It contains zipcode
* @return - returns latitude and longitude values on success,
* false on invalid address
*/
function getLatlang($addressline1, $addressline2, $city, $state, $zipcode)
{
global $config;
$address = $addressline1.",".$addressline2.",".$city.",".$state.",".$zipcode;
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$prepAddr.'&key='.$config['maps_api_key']);
$output= json_decode($geocode);
$maps_status=$output->status;
$maps_error_msg=$output->error_message;
if(!empty($output->results))
{
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
return $lat."$#@".$long;
} else if($maps_status){
if($maps_status=="REQUEST_DENIED"){
return "Google maps API key is invalid.";
}else if($maps_status=="ZERO_RESULTS"){
return "Invalid address,Please provide valid address!";
}else if($maps_status=="INVALID_REQUESTs"){
return "Invalid request. Missing the 'address' parameter";
}else if($maps_status=="OVER_QUERY_LIMIT"){
return "Google maps API QPS(query per second) limit was exceeded. please try again later";
}else if($maps_error_msg){
return $maps_error_msg;
}else{
return $maps_status;
}
}else if($maps_error_msg){
return $maps_error_msg;
}else{
return "404";
}
}
function format_phone($phone)
{
$phone = preg_replace("/[^0-9]/", "", $phone);
if(strlen($phone) == 7)
return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
elseif(strlen($phone) == 10)
return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
elseif (strlen($phone) == 11) {
return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
}
else
return $phone;
}
}
?>
|
Swift
|
UTF-8
| 1,168
| 2.640625
| 3
|
[] |
no_license
|
//
// MenuCalendar.swift
// ManageMoney
//
// Created by admin101 on 4/5/18.
// Copyright © 2018 demi. All rights reserved.
//
import UIKit
import FSCalendar
class MenuCalendar : UIViewController ,FSCalendarDelegate ,FSCalendarDataSource{
fileprivate weak var calendar: FSCalendar!
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = "Calendar"
if Language.currentLanguage() == "en" {
self.navigationController?.navigationBar.topItem?.title = "Calendar"
}else{
self.navigationController?.navigationBar.topItem?.title = "الاجندة"
self.hideKeyboardWhenTappedAround()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let calendar = FSCalendar(frame: CGRect(x: 0, y: (navigationController?.navigationBar.frame.size.height)! * 2, width: (navigationController?.navigationBar.frame.size.width)!, height: 350))
calendar.dataSource = self
calendar.delegate = self
view.addSubview(calendar)
self.calendar = calendar
}
}
|
C#
|
UTF-8
| 907
| 2.53125
| 3
|
[] |
no_license
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Application.Commons.Interfaces;
using Application.Commons.Models;
using Domain.Entities;
using MediatR;
namespace Application.Cars.Commands.CreateCarCommands
{
public class CreateCarCommand : IRequest<string>
{
public Car car { get; set; }
}
public class CreateCarCommandHandler : BaseCommand, IRequestHandler<CreateCarCommand, string>
{
public CreateCarCommandHandler(IAppDbContext appDbContext) : base(appDbContext)
{
}
public async Task<string> Handle(CreateCarCommand request, CancellationToken cancellationToken)
{
request.car.IdGuid = Guid.NewGuid();
await DbContext.Cars.AddAsync(request.car, cancellationToken);
await DbContext.SaveChangesAsync(true, cancellationToken);
return "Anjing";
}
}
}
|
C++
|
UTF-8
| 386
| 3.234375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include <iostream>
using namespace std;
int main()
{
int A, B, W;
cin >> A >> B >> W;
int min;
if((W*1000)%B == 0) {
min = (W*1000) / B;
} else {
min = (W*1000) / B + 1;
}
int max = (W*1000) / A;
if(min <= max) {
cout << min << " " << max << endl;
} else {
cout << "UNSATISFIABLE" << endl;
}
return 0;
}
|
C++
|
UTF-8
| 1,219
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
#ifndef _USERWORDITERATORCREATOR_H_
#define _USERWORDITERATORCREATOR_H_
#include "WordIterator.h"
#include "WordIteratorCreator.h"
#include "DiscreteWordIterator.h"
#include "EvaluateStrategy.h"
#include "UserInfo.h"
#include "IDictionary.h"
#include <random>
#include <memory>
// 使用用户数据创建迭代器
class UserWordIteratorCreator
: public WordIteratorCreator
{
protected:
/// 随机数生成器,用户,词典
std::default_random_engine &engine;
UserInfo &user;
IDictionary &dict;
public:
/// 构造
UserWordIteratorCreator(std::default_random_engine &engine, UserInfo &user, IDictionary &dict)
: engine(engine), user(user), dict(dict)
{
}
/// 迭代器创建接口
std::shared_ptr<WordIterator> Create() override = 0;
/// 按名称创建Creator
static std::shared_ptr<UserWordIteratorCreator> ByName(const std::string &name, std::default_random_engine &engine, UserInfo &user, IDictionary &dict);
/// 尝试按名称创建Creator
static std::shared_ptr<UserWordIteratorCreator> TryByName(const std::string &name, std::default_random_engine &engine, UserInfo &user, IDictionary &dict);
};
#endif // _USERWORDITERATORCREATOR_H_
|
Ruby
|
UTF-8
| 635
| 3.046875
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'pry'
require_relative "./lib/cat.rb"
require_relative "./lib/dog.rb"
require_relative "./lib/owner.rb"
ryan = Owner.new("ryan")
ryan.buy_dog("Fido")
ryan.walk_dogs
ryan.buy_dog("Tom")
ryan.buy_dog("Rachel")
paws = Cat.new("Paws", ryan, "nervous", rand(10))
betty = Cat.new("Betty", ryan, "happy", rand(10))
alice = Cat.new("Alice", ryan, "happy", rand(10))
bell = Cat.new("Bell", ryan, "nervous", rand(10))
bones = Dog.new("Bones", ryan, "nervous", rand(10))
bruno = Dog.new("Bruno", ryan, "happy", rand(10))
ben = Dog.new("Ben", ryan, "happy", rand(10))
cheese = Dog.new("Cheese", ryan, "nervous", rand(10))
binding.pry
|
Ruby
|
UTF-8
| 970
| 3.609375
| 4
|
[
"MIT"
] |
permissive
|
# Our CLI Controller
class PokedexList::CLI
def call
list_pokedex
menu
goodbye
end
def list_pokedex
puts "POKEDEX LIST "
@pokemon = PokedexList::List.pokemon
@pokemon.each.with_index(1) do |deal, i|
puts "#{i}. #{pokemon.name} - #{pokemon.type} - #{pokemon.weakness} - #{pokemon.category} - #{pokemon.ability} - #{pokemon.fatures} - #{pokemon.url}"
end
end
def menu
puts "Choose Pokemon to see features or type exit:"
input = nil
while input != "exit"
input = gets.strip.downcase
if input.to_i > 0
puts @pokemon[input.to_i-1]
elsif input == "list"
list_pokedex
else
puts "there is no more pokemon available."
end
end
end
def goodbye
puts "Sorry to see you leave, COMEEE BACK SOOOON TO SEE MORE POKEMOOOON AVAILABLES!!!"
end
end
|
PHP
|
UTF-8
| 529
| 3
| 3
|
[] |
no_license
|
<?php
declare(strict_types=1);
namespace Tests\Strategy;
use App\Strategy\RSortStrategy;
use PHPUnit\Framework\TestCase;
class SortStrategyTest extends TestCase
{
/**
* Teste algoritmo
*/
public function testFazAOrdenacaoDeFormAscendenteDeUmArray()
{
$rsort = new RSortStrategy();
$data = [3, 7, 9, 1, 6];
$ordenado = [9, 7, 6, 3, 1];
$this->assertInternalType("array", $rsort->algoritmo($data));
$this->assertSame($ordenado, $rsort->algoritmo($data));
}
}
|
Markdown
|
UTF-8
| 10,212
| 2.546875
| 3
|
[] |
no_license
|
---
layout: post
title: "Mind The Product 2020 - Recap Partie 1"
date: 2020-11-24 12:00:00 +0200
date-suffix: ", à 23h en faisant la cuisine et HHAAA mes gnoccis sont en train de cramer"
categories: conference
keywords: "CONFERENCE, MIND THE PRODUCT"
excerpt: "La semaine dernière j'ai assisté à la MindTheProduct, une des confs les plus connus sur le Product Management et j'ai envie de vous partager ce que j'en ai retenu ;)
D'un point de vue global sur la conf, je l'ai trouvé de la même qualité que..."
---
La semaine dernière j'ai assisté à la MindTheProduct, une des confs les plus connues sur le Product Management et j'ai envie de vous partager ce que j'en ai retenu ;)
D'un point de vue global sur la conf, je l'ai trouvé de la même qualité que celle de 2019 à laquelle j'avais assisté (en physique 😭RIP la vie). Là encore, et comme dans toutes les confs, tous les talks ne m'ont pas parlé, c'est donc une vision totalement biaisée de votre serviteur dont vous allez profiter ! Servez-vous un café/chocolat chaud/thé/larmes de chefs de projet et prenez le temps :)
*J'espère que vous prendrez autant de plaisir que moi à découvrir tous ces points de vue différents et nouveaux. Comme je sais que votre temps est précieux, j'ai divisé ce retour en 2 parties pour faciliter votre lecture et vous laisser un peu plus de temps pour digérer. Enjoy !*
#### Shaun Russel - How Successful Product People Develop
Dans ce talk, Shaun Russel nous a parlé d'un concept qu'il appelle Produktgëfuhl et comment le développer. Pour ceux qui ont fait 0 année d'allemand (ou 7 comme moi mais qui ont seulement retenu comment dire "Pouvez-vous répéter ?", "Je ne sais pas" et l'indétrônable "Salade de pommes de terre"), on pourrait traduire ça en "Product feel", ou ce qui fait qu'on développe "l'intuition" pour faire du produit.
Shaun est coach produit et nous partage donc les compétences qu'il a vu chez des PM qui progressent plus vite que d'autres.
Il résume cela en plusieurs points (ça enfonce un peu des portes ouvertes, attention):
- Apprendre en faisant
- Il avance l'importance de s'attaquer à des **challenges** de plus en plus grands pour progresser. Être PM d'un produit avec une petite équipe → Être PM d'un produit avec des attentes fortes → Être PM d'un produit avec une portée internationale et plus impactant → Etc
- Une phrase qu'il a entendu, et que j'aime beaucoup car elle capture une de nos valeurs chez BENEXT, l'Humilité : "Pourquoi s'embêter à avoir l'air intelligent, lorsqu'on peut devenir plus intelligent ?"
- Apprendre des autres
- Il souligne l'importance des feedbacks pour grandir. Demandez à vos collègues, vos supérieurs, votre équipe, on découvre toujours de nouveaux axes d'amélioration qui nous redonnent la pêche
- Et trouver des mentors en interne pour progresser.
- Apprendre de son environnement
- Pour progresser, il faut y aller par étape. D'abord observer et apprendre de son équipe, ensuite élargir son environnement (ou sa zone d'influence ?), faire évoluer sa pensée, pour apprendre de la stratégie de l'entreprise, et enfin de la politique de celle-ci.
- Shaun rappelle l'importance de trouver le juste milieu au fond de nous entre l'idéaliste et le nihiliste. C'est-à-dire entre celui qui souhaite tout changer et qui veut vivre un idéal, et celui qui ne croit pas pouvoir changer les choses. (Note: "Ne vous comportez pas en Héro)
En résumé, il rajoute quelques conseils pour progresser plus vite:
- Comprendre l'organigramme de son entreprise
- S'approprier le business model de l'entreprise en remplissant, par exemple, le Business Model Canvas pour vraiment le comprendre
- Mettre la main sur le budget et les prévisions de l'entreprise, cela peut donner beaucoup d'informations
- Identifier la réunion la plus importante de l'entreprise et essayer d'y assister. Au mieux y participer. Si ce n'est pas possible, essayer d'y assister en observateur, et enfin si ce n'est vraiment pas possible, essayer de découvrir ce qui s'y dit par d'autres moyens
#### Anthony Rindone - Stay Humble or Be Humbled
Anthony nous a partagé ses réflexions sur comment prendre de meilleures décisions.
J'en ai retenu un piège data: Lors de l'analyse de performances d'une fonctionnalité sur différents segments utilisateurs, il faut faire attention au "Simpson's Paradox" qui met en lumière un paradoxe, où dans certains cas, on peut trouver des résultats complètement opposés lors de 2 analyses différentes, qui sont (et c'est là le paradoxe) toutes les 2 justes. Je vous laisse creuser si ça vous intrigue ;)
#### Ibrahim Bashir - Bootstrapping a Product Team
Ibrahim nous a parlé création d’une Product Team et comment choisir le bon type de profil de PM selon l’avancement de son produit.
J'ai particulièrement aimé la division en 3 parties qu'il fait de la vie d'un produit.
- Il y a le Starter. Un PM qui n'a pas d'anxiété à propos du fait d'être le 1er PM, il va comprendre les besoins des pré-customers et travailler sur le Product Market Fit
- Ensuite vient le Scaler. Un PM qui va rapidement capturer des parts de marché, capturer de l'engagement. Il va être drivé par une ou plusieurs métriques.
- Enfin vient le Sustainer. Qui va maintenir le produit et va principalement interagir avec les clients
Bien sûr, selon lui, il est totalement possible de faire la transition entre ces différents profils, même si on trouvera certains PM plus à l'aise dans certains rôles que dans d'autres.
#### Cassidy Fein - Roundtable: Discovery & Research
Cassidy a une table ronde autour du Discovery et de la Research.
Voici, ce qui est ressorti de ce moment:
- À 2 reprises le framework Jobs To Be Done est ressorti (JTBD pour les intimes, rien à voir avec JBD qui sont mes initiales malheureusement) comme méthode pour aider au Discovery
- La mention d'un très bon article de Teresa Torres sur le Discovery en temps de COVID (malheureusement je n'ai pas réussi à le retrouver, si quelqu'un a un indice, qu'il n'hésite pas)
- Avec notamment l'importance d'être extra-emphatique avec ses utilisateurs
- Le temps de nos utilisateurs est encore plus précieux aujourd'hui qu'avant
- L'importance de diviser les rôles qui font du Design (au sens large) de ceux qui font de la Research
#### Mary Poppendieck - Lessons from a Product Champion
Keynote de la 1ère demi-journée. Excellent talk de Mary Poppendieck qui est plus ou moins (avec son mari Tom) la daronne du Lean dans le monde du développement logiciel. Et oui ça se pose là.
Mary nous a parlé de ses années chez 3M (qui nous apporte à tous une joie immense au quotidien avec les post-its de couleurs flashy) dans les années 80-90. Elle nous a notamment parlé du rôle de...Product Champion !
On parle parfois de Product Leader dans le Product Management pour essayer de donner plus de sens au métier de PM mais c'est la 1ère fois que j'entendais parler de ce rôle et c'est très intéressant.
- No Champion → No Product
- Sans champion, à 3M, ils considéraient qu'un produit ne pouvait pas marcher
- Un champion, c'est quelqu'un pour qui le produit est son bébé
- Quelqu'un qui fera tout ce qui est possible pour amener le produit **sur le marché**
- Un champion est un entrepreneur
- Il est responsable du succès marketing du produit
- Les champions qui arrivent à faire marcher un produit sont souvent ceux qui finissent par en gérer le business une fois que celui-ci a pris de l'ampleur
- Un champion est self-selected. Il se porte volontaire pour ce rôle
- Le champion doit trouver/attirer/composer une "leadership team" au sein de son équipe
- Un Product Champion ne peut pas réussir seul
- Il a besoin de former une équipe composée d'une personne Design, d'une personne tech, d'une personne Marketing-Vente et d'une personne Finance
- On parle ici d'une équipe au sein de l'équipe de développement produit
- Le Product Champion n'est pas un expert dans un de ces domaines
- Il doit profondément comprendre le problème que le produit veut résoudre
- Il établit un but commun à toute l'équipe, pour que tout le monde soit aligné sur l'objectif final
- Il va chercher les conflits (Note: Difficile à traduire "provide for conflicts)
- Mary avance que les excellents compromis font les excellents produits. C'est à la base une citation de Toyota "Great conflicts makes great cars"
- Il est impératif d'avoir des débats "fair", qui reposent toujours sur 3 piliers pour arriver à une réponse: tech, design et produit par exemple. Il est extrêmement important que le débat ne soit pas gagné parce que c'est le boss a tranché dans son propre sens
- Il évite les décisions (Note: mon préféré)
- Un champion ne décide pas, et il ne priorise pas
- Lorsque 2 personnes ne sont pas d'accord, il souligne les arguments valides des 2 parties et les oblige à trouver une solution ensemble
- Il compare cette situation au fait d'avoir des enfants: Si tu décides, alors tu as perdu
- (Note: On retrouve le même schéma chez les leaders de l'excellent livre *Tribal Leadership*)
- Toujours reporter la décision au dernier moment
- De cette manière, vous continuerez d'apprendre jusqu'au dernier moment où vous serez obligé de prendre la décision -> "Be lazy, don't decide"
- (Note: Si ce principe vous intéresse, je vous conseille les *Real Options* de Chris Matts et sa bd *Commitment* (oui oui une bd, c'est top))
- Apprendre en avançant
- Il ne devrait pas y avoir de proxy entre l'équipe et le résultat de son travail. Même le champion ne devrait pas faire proxy avec les utilisateurs
- C'est le travail du Champion de mettre son équipe en contact avec les clients
- Utiliser la data pour prendre la bonne décision
- L'équipe devrait prendre des décisions de manière collective
Et le mot de la fin de Mary: "Development is learning"
C'est fini pour cette première journée ;)
Pour lire la suite, 👉 <a href="/conference/mindtheproduct2020-part2/" class="link light-link">**c’est par ici.**</a>
|
PHP
|
UTF-8
| 1,253
| 2.921875
| 3
|
[] |
no_license
|
<?php
require "../config/Conexion.php";
class Hora
{
public function __construct()
{
}
public function insertar($nombre)
{
$sql="INSERT INTO hora (nombre,estado)VALUES
('$nombre','1')";
return ejecutarConsulta($sql);
}
public function editar($idhora,$nombre)
{
$sql="UPDATE hora SET nombre='$nombre' WHERE idhora='$idhora'";
return ejecutarConsulta($sql);
}
//Implementamos un método para desactivar categorías
public function desactivar($idhora)
{
$sql="UPDATE hora SET estado='0' WHERE idhora='$idhora'";
return ejecutarConsulta($sql);
}
//Implementamos un método para activar categorías
public function activar($idhora)
{
$sql="UPDATE hora SET estado='1' WHERE idhora='$idhora'";
return ejecutarConsulta($sql);
}
public function mostrar($idhora)
{
$sql="SELECT * FROM hora WHERE idhora='$idhora'";
return ejecutarConsultaSimpleFila($sql);
}
public function listar()
{
$sql="SELECT * FROM hora";
return ejecutarConsulta($sql);
}
public function select()
{
$sql="SELECT * FROM hora WHERE estado=1";
return ejecutarConsulta($sql);
}
}
?>
|
Java
|
UTF-8
| 4,913
| 2.015625
| 2
|
[] |
no_license
|
package com.zdsoft.finance.common.base;
import com.zdsoft.essential.dto.permission.DataOperPermDto;
import com.zdsoft.framework.core.common.domain.BaseEntity;
import com.zdsoft.framework.core.common.page.Page;
import com.zdsoft.framework.core.common.page.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* 自定义操作库
*
* @author LiaoGuoWei
* @create 2016-10-27 10:00
**/
@NoRepositoryBean
public interface CustomRepository<T extends BaseEntity, ID extends Serializable> extends JpaRepository<T, ID> {
/**
*
* @Title: findByHqlPage
* @Description: 分页查询
* @author dengyy
* @param pageable 分页信息
* @param hql 查询hql
* @param condition 查询条件
* @param dataOperPermDto 数据权限信息
* @return
*/
public Page<T> findByHqlPage(Pageable pageable, String hql, Map<String, Object> condition,DataOperPermDto dataOperPermDto);
/**
*
* @Title: findByHql
* @Description: 通过HQL查找
* @author dengyy
* @param hql HQL语句
* @param condition 查询条件
* @param dataOperPermDto 数据权限信息
* @return
*/
public List<T> findByHql(String hql, Map<String, Object> condition,DataOperPermDto dataOperPermDto);
/**
* 通过HQL查找
*
* @param hql
* HQL语句
* @param condition
* 查询条件
* @return
*/
public List<T> findByHql(String hql, Map<String, Object> condition);
/**
* 多条件hql分页查询
*
* @param pageable
* 分页参数
* @param hql
* 查询HQL
* @param condition
* 查询条件
* @return
*/
public Page<T> findByHqlPage(Pageable pageable, String hql, Map<String, Object> condition);
/**
* 多条件sql分页查询
* @param pageable 分页参数
* @param sql sql语句
* @param condition 查询条件
* @return
*/
public Page<Map<String,Object>> findBySqlMapPage(Pageable pageable, String sql, Map<String, Object> condition) throws Exception;
/**
* 多条件sql分页查询
* @param pageable 分页参数
* @param sql sql语句
* @param condition 查询条件
* @return
*/
public Page<T> findBySqlEntityPage(Pageable pageable, String sql, Map<String, Object> condition, Class<T> tClass) throws Exception;
/**
* 多条件sql查询
* @param sql
* @param condition
* @param tClass
* @return
* @throws Exception
*/
public List<T> findBySql(String sql,Map<String,Object> condition,Class<T> tClass) throws Exception;
/**
* 分页查询自动封装
* @param pageable
* @param li
* @return
*/
public Page<T> findByHqlConditions(Pageable pageable, List<QueryObj> li);
/**
*
* @Title: findByHqlConditions
* @Description: 分页查询自动封装
* @author dengyy
* @param pageable 分页信息
* @param li 查询条件
* @param dataOperPermDto 权限信息
* @return
*/
public Page<T> findByHqlConditions(Pageable pageable, List<QueryObj> li,DataOperPermDto dataOperPermDto);
/**
* 获取当前查询条件下总条数
*
* @param hql
* 查询HQL
* @param condition
* 查询条件
* @return
*/
public Long countAll(String hql, Map<String, Object> condition);
/**
* 获取当前查询条件下总条数
*
* @param sql
* 查询SQL
* @param condition
* 查询条件
* @return
*/
public Long countAllSql(String sql, Map<String, Object> condition);
/**
* 保存域对象
*
* @param t
* 域对象
* @return
*/
public T saveEntity(T t);
/**
* 更新实体
*
* @param t
* 需更新的实体
* @return
*/
public T updateEntity(T t);
/**
* 逻辑删除
*
* @param t
* 需要删除的域对象
* @return
*/
public T logicDelete(T t);
/**
* 列表查询SQL公共实现
* @param pageRequest 分页参数
* @param param 参数集合
* @param _sql 查询基础SQL
* @param _extendSql 查询扩展SQL
* @return SQL查询的列表数据page对象
*/
public Page<Map<String,Object>> getListObjectBySql(Pageable pageable, List<QueryObj> param, StringBuffer _sql, StringBuffer _extendSql);
/**
* 根据条件查询List<Map<>>
* @param sql
* @param condition
* @return
* @throws Exception
*/
public List<Map<String,Object>> findListMapByCondition(String sql, Map<String, Object> condition) throws Exception;
/**
* 批量保存
* @param list
* @return
*/
public List<T> batchSave(List<T> list);
/**
* 批量更新
* @param list
* @return
*/
public List<T> batchUpdate(List<T> list);
/**
* 批量逻辑删除
* @param list
* @return
*/
public List<T> batchLogicDelete(List<T> list);
}
|
Markdown
|
UTF-8
| 2,333
| 2.671875
| 3
|
[] |
no_license
|
---
title: Hive QL(HQL)でORDER BYするときの注意点
date: 2009/10/14 23:57:37
tags: hadoop
published: true
---
<p>HiveでのSQLことHQLの小ネタ。HQLでは基本的にSQLはほぼ完璧に利用できますが、たまにハマりポイントもあります。その1つが並び替えのORDER BY。</p>
<h3>ORDER BYとSORT BY</h3>
<p>HQLの文法的にORDER BYは有効ですが、実際は並び替えは行われません。(無視されているような感じ)Hiveでは代わりに<strong>「SORT BY [column]」</strong>を利用することになります。</p>
<p>ただし、ここでも罠があって、SORT BYは結果がreducerの数に依存します。(各reducerがsort処理をしたものがマージされるものになるので、全体としてはおかしな結果を得ることになります) 通常、reducerは複数走っているはずなので、結局SORT BYを利用してもORDER BYと同等の結果を得ることができません。</p>
<p>では、どうするか?と言うと明示的にreducerの数を1に指定してからSORT BYを実行すればOKです。</p>
<p><pre>
set mapred.reduce.tasks=1;
SELECT key, value FROM table_name SORT BY key;
</pre></p>
<p>また、Hiveシェルを使わない場合は1ライナーで。</p>
<p><pre>
hive -e 'set mapred.reduce.tasks=1;SELECT key, value FROM table_name SORT BY key;'
</pre></p>
<h3>HQL最適化</h3>
<p>ただ、これだとreducerの数がボトルネックになって、SORT BYと条件文などが組合わさると途端に処理が遅くなることがあります。</p>
<p>なので、このような条件文付きSORT BYを実行するときは、</p>
<p><ol>
<li>複数のreducerが条件文つきHQLでデータを整形し、中間テーブルAを作成</li>
<li>1つのreducerが、中間テーブルAを対象にSORT BYし、条件文は付けない</li>
</ol></p>
<p>な、方針でHQLを分割して実行すると、高速に動作できるかと思います。</p>
<p>ちなみに、このテーブルを分ける(カラムを厳選した中間テーブルを作成する)のはHQLの最適化でかなり有効で、SORT BY以外でもかなり有効なケースが多くあります。このあたりの最適化の話は、また別途まとめたいと思います。</p>
|
C++
|
UTF-8
| 525
| 3.25
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
void main()
{
int a, b;
double r;
cout << "introduceti a: ";
cin >> a;
cout << "introduceti b: ";
cin >> b;
if (a == 1 && b == 2 )
{r = a/b;
cout << "a/b = " << r << endl;
r = (double)a/b;
cout << "(double)a/b = " << r << endl;
r = 1. + a/b;
cout << "1. + a/b = " << r<< endl;
r = 1. + (a*1.)/b;
cout << "1. + (a*1.)/b = " << r << endl;
r = 1. + (double)a/b;
cout << "1. + (double)a/b = " << r << endl;
}
else
cout << "introduceti 1 si 2";
system ("pause");
}
|
Python
|
UTF-8
| 836
| 2.546875
| 3
|
[] |
no_license
|
"""CRUD operations."""
from model import db, Product, connect_to_db
import datetime
def create_product(channel_name,product_description, option, product_url, price, added_on, number_sold, margin, updated_on):
product = Product(channel_name=channel_name,
product_description=product_description,
option=option,
product_url=product_url,
price=price,
added_on=added_on,
number_sold=number_sold,
margin=margin,
updated_on=updated_on)
db.session.add(product)
db.session.commit()
return product
def get_products():
"""Return all rows of product data."""
return Product.query.all()
if __name__ == '__main__':
from server import app
connect_to_db(app)
|
SQL
|
UTF-8
| 206
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
SELECT v.id AS videoGameId,
v.name AS videoGameName,
v.levels AS videoGameLevels
FROM Videogames v
WHERE ARRAY_CONTAINS(v.levels,
{
"title": "Jungle Arena",
"towers": 2
})
|
Java
|
UTF-8
| 1,413
| 2.40625
| 2
|
[] |
no_license
|
package com.zql.validator.controller;
import com.zql.validator.common.Result;
import com.zql.validator.entity.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
/**
* @author lawliet.L
*/
@RestController
@RequestMapping("/validator")
@Validated // 如果类中的方法有单参数校验,则需要加此注解
public class ValidatorController {
@GetMapping("/login")
public User login(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
FieldError error = bindingResult.getFieldError();
System.out.println(error.getField() + " " + error.getDefaultMessage());
return null;
}
return user;
}
@GetMapping("/login2")
public Result<User> login2(@Valid User user) {
return Result.success(user);
}
@GetMapping("/username")
public Result<User> getByUsername(@NotNull(message = "用户名不能为空") String username) {
return Result.success(new User(1L, username, "123" ,"123@11.com"));
}
}
|
C#
|
UTF-8
| 859
| 3.578125
| 4
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ForLoop : MonoBehaviour
{
int numEnemies = 3;
void Start()
{
for (int i = 0; i < numEnemies; i++)
{
Debug.Log("Creating enemy number: " + i);
}
/* This is an example of a situation in which to use a forLoop
We want it to add all the numbers between one and 10 together*/
int total = 0; //we begin by creating a variable, the 'total'
//for (do this before loop; check this before running; do at end)
for (int count = 1; count <= 10; count++) // the ++ is just short for count = count + 1. If I want it to add more than one I say count += x
{
total = count + total;
}
Debug.Log("The answer is " +total);
}
}
|
Python
|
UTF-8
| 3,390
| 2.515625
| 3
|
[] |
no_license
|
import time
from tabulate import tabulate
import pandas as pd
import Logger
class TimeKeeper:
def __init__(self):
self.pretty_df = pd.DataFrame(columns=['Image','BLEU','Total_Time','Comm_Time'])
self.E_START_CLIENT_PROCESSING = 'E_START_CLIENT_PROCESSING'
self.E_STOP_CLIENT_PROCESSING = 'E_STOP_CLIENT_PROCESSING'
self.E_START_COMMUNICATION = 'E_START_COMMUNICATION'
self.E_STOP_COMMUNICATION = 'E_STOP_COMMUNICATION'
self.I_BUFFER_SIZE = 'I_BUFFER_SIZE'
self.I_BLEU = 'I_BLEU'
self.I_REAL_CAPTION = 'I_REAL_CAPTION'
self.I_PRED_CAPTION = 'I_PRED_CAPTION'
self.I_CLIENT_PROCESSING_TIME = 'I_CLIENT_PROCESSING_TIME'
self.I_COMMUNICATION_TIME = 'I_COMMUNICATION_TIME'
self.I_TAIL_MODEL_TIME = 'I_TAIL_MODEL_TIME'
self.records = {}
def startRecord(self, image):
self.records[image] = {}
def logTime(self, image, event):
self.records[image][event] = time.perf_counter()
def logInfo(self, image, info_key, info):
self.records[image][info_key] = info
def finishRecord(self, image):
# self.records[image] = {}
self.records[image][self.I_CLIENT_PROCESSING_TIME] = self.records[image][self.E_STOP_CLIENT_PROCESSING] - \
self.records[image][self.E_START_CLIENT_PROCESSING]
self.records[image][self.I_COMMUNICATION_TIME] = self.records[image][self.E_STOP_COMMUNICATION] - \
self.records[image][self.E_START_COMMUNICATION]
record = self.records[image]
pretty_record = {}
pretty_record['Image'] = image.rsplit('/', 1)[-1]
pretty_record['BLEU'] = "{:.02f}".format(self.records[image][self.I_BLEU])
pretty_record['Total_Time'] = "{:.02f}".format(self.records[image][self.I_CLIENT_PROCESSING_TIME])
pretty_record['Comm_Time'] = "{:.02f}".format(self.records[image][self.I_COMMUNICATION_TIME])
self.pretty_df = self.pretty_df.append(pretty_record,ignore_index=True)
pass
def printAll(self):
Logger.event_print(tabulate(self.pretty_df, headers='keys', tablefmt='psql'))
def summary(self):
df = pd.DataFrame(self.records)
df_t = df.T
# df_t.to_csv("TimeKeeper.csv")
average_bleu = df_t[self.I_BLEU].mean()
average_inference_time = df_t[self.I_CLIENT_PROCESSING_TIME].mean()
average_head_model_time = df_t[self.I_CLIENT_PROCESSING_TIME].mean() - df_t[self.I_COMMUNICATION_TIME].mean()
average_communication_time = df_t[self.I_COMMUNICATION_TIME].mean() - df_t[self.I_TAIL_MODEL_TIME].mean()
average_tail_model_time = df_t[self.I_TAIL_MODEL_TIME].mean()
average_communication_payload = int(df_t[self.I_BUFFER_SIZE].mean())
Logger.milestone_print("Average BLEU : %.2f" % (average_bleu))
Logger.milestone_print("Average inference time : %.2f s" % (average_inference_time))
Logger.milestone_print("Average head model time : %.2f s" % (average_head_model_time))
Logger.milestone_print("Average communication time : %.2f s" % (average_communication_time))
Logger.milestone_print("Average tail model time : %.2f s" % (average_tail_model_time))
Logger.milestone_print("Average communication payload : " + f"{int(average_communication_payload):,d}")
|
Java
|
UTF-8
| 806
| 2.03125
| 2
|
[] |
no_license
|
package pl.kul.todos.adapter.gui.edititem;
import pl.kul.todos.adapter.gui.mainwindow.MainWindowPresenter;
public class EditItemPresenter {
private final EditItemView editItemView;
private final MainWindowPresenter mainWindowPresenter;
private final ItemToEditDto itemToEditDto;
public EditItemPresenter(MainWindowPresenter mainWindowPresenter, ItemToEditDto itemToEditDto, EditItemView editItemView) {
this.mainWindowPresenter = mainWindowPresenter;
this.itemToEditDto = itemToEditDto;
this.editItemView = editItemView;
}
public void showEditItem() {
editItemView.showEditItem(itemToEditDto);
}
public void updateItem(UpdateItemDto updateItemDto) {
mainWindowPresenter.updateItem(itemToEditDto.getId(), updateItemDto);
}
}
|
Java
|
UTF-8
| 4,164
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
package com.special.test13;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Create by Special on 2018/4/5 16:27
*/
public class ProEImprove3 {
static int[] s = {-1, 1};
static final int MIN = -1000;
static final int MAX = 1000;
public static void main(String[] args){
FastScanner input = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
String c = input.next();
int n = input.nextInt();
int[][][] dp1 = new int[c.length() + 1][n + 1][2];
int[][][] dp2 = new int[c.length() + 1][n + 1][2];
for(int i = 0; i <= c.length(); i++){
for(int j = 0; j <= n; j++){
for(int d = 0; d < 2; d++){
dp1[i][j][d] = MIN;
dp2[i][j][d] = MAX;
}
}
}
dp1[0][0][1] = dp2[0][0][1] = 0;
dp1[0][0][0] = dp2[0][0][0] = 0;
for(int i = 1; i <= c.length(); i++){
for(int j = 0; j <= n; j++){
for(int e = 0; e <= j; e++){
int t = j - e;
if((t & 1) == 0){
if(c.charAt(i - 1) == 'F') {
dp1[i][j][0] = Math.max(dp1[i - 1][e][0] - 1, dp1[i][j][0]);
dp1[i][j][1] = Math.max(dp1[i - 1][e][1] + 1, dp1[i][j][1]);
dp2[i][j][0] = Math.min(dp2[i - 1][e][0] - 1, dp2[i][j][0]);
dp2[i][j][1] = Math.min(dp2[i - 1][e][1] + 1, dp2[i][j][1]);
}else {
dp1[i][j][0] = Math.max(dp1[i - 1][e][1], dp1[i][j][0]);
dp1[i][j][1] = Math.max(dp1[i - 1][e][0], dp1[i][j][1]);
dp2[i][j][0] = Math.min(dp2[i - 1][e][1], dp2[i][j][0]);
dp2[i][j][1] = Math.min(dp2[i - 1][e][0], dp2[i][j][1]);
}
}else{
if(c.charAt(i - 1) == 'F') {
dp1[i][j][0] = Math.max(dp1[i - 1][e][1], dp1[i][j][0]);
dp1[i][j][1] = Math.max(dp1[i - 1][e][0], dp1[i][j][1]);
dp2[i][j][0] = Math.min(dp2[i - 1][e][1], dp2[i][j][0]);
dp2[i][j][1] = Math.min(dp2[i - 1][e][0], dp2[i][j][1]);
}else {
dp1[i][j][0] = Math.max(dp1[i - 1][e][0] + 1, dp1[i][j][0]);
dp1[i][j][1] = Math.max(dp1[i - 1][e][1] - 1, dp1[i][j][1]);
dp2[i][j][0] = Math.min(dp2[i - 1][e][0] - 1, dp2[i][j][0]);
dp2[i][j][1] = Math.min(dp2[i - 1][e][1] + 1, dp2[i][j][1]);
}
}
}
}
}
int max = 0;
max = Math.max(Math.abs(dp1[c.length()][n][0]), max);
max = Math.max(Math.abs(dp1[c.length()][n][1]), max);
max = Math.max(Math.abs(dp2[c.length()][n][0]), max);
max = Math.max(Math.abs(dp2[c.length()][n][1]), max);
out.println(max);
out.close();
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
}
|
C++
|
UTF-8
| 726
| 2.703125
| 3
|
[] |
no_license
|
#ifndef LOGGER_H_INCLUDED
#define LOGGER_H_INCLUDED
#include <ostream>
#include <string>
#include <sstream>
#include <map>
#include <memory>
#include "windows.h"
class Logger
{
private:
// create logger which write to file
explicit Logger( std::ostream * ost );
Logger( const Logger & orig );
Logger & operator=( const Logger & orig );
public:
~Logger();
void println( const std::string & line );
void println( std::ostringstream & line );
static Logger & getInstance( const std::string & name );
private:
static void init( std::map<std::string, Logger *> & loggers );
HANDLE mux;
std::ostream * ost;
};
#endif // LOGGER_H_INCLUDED
|
TypeScript
|
UTF-8
| 1,424
| 2.515625
| 3
|
[] |
no_license
|
import * as mongoose from 'mongoose';
import {IReturnedRental} from './ReturnedRental';
import ReturnedRental from '../database/ReturnedRental';
export class ReturnedRentalRepository {
private static returnedRentalRepository: ReturnedRentalRepository;
public static create(): ReturnedRentalRepository {
if(!ReturnedRentalRepository.returnedRentalRepository) {
ReturnedRentalRepository.returnedRentalRepository = new ReturnedRentalRepository();
}
return ReturnedRentalRepository.returnedRentalRepository;
}
public async getAll(): Promise<IReturnedRental[]> {
return ReturnedRental.find();
}
public async find(rentalId: string): Promise<IReturnedRental> {
// @ts-ignore
return ReturnedRental.findById(rentalId);
}
public async add(rental: IReturnedRental): Promise<IReturnedRental> {
const rentalObject = new ReturnedRental(rental);
return rentalObject.save();
}
public async delete(rentalId: string): Promise<any> {
return ReturnedRental.findByIdAndDelete({_id: rentalId});
}
public async update(rental: any): Promise<IReturnedRental> {
// @ts-ignore
return ReturnedRental.findByIdAndUpdate(rental._id, {$set:rental},{new: true, runValidators: true});
}
public isValidId(unicornId: string) {
return mongoose.Types.ObjectId.isValid(unicornId);
}
}
|
JavaScript
|
UTF-8
| 1,260
| 3.0625
| 3
|
[] |
no_license
|
/*
* @lc app=leetcode.cn id=863 lang=javascript
*
* [863] 二叉树中所有距离为 K 的结点
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} target
* @param {number} K
* @return {number[]}
*/
var distanceK = function (root, target, K) {
let res = [];
let targetFound = false;
(function mapper(node, parent) {
if (!node) return
if (node === target) targetFound = true;
if (parent) {
node.parent = parent;
}
mapper(node.left, node);
mapper(node.right, node);
})(root, null);
if (!targetFound) return res;
(function mapper(node, dis, prevPath) {
if (!node) return
if (dis === K) {
res.push(node.val);
return
}
if (dis < K) {
let next = prevPath.concat(node);
node.left && !prevPath.includes(node.left) && mapper(node.left, dis + 1, next);
node.right && !prevPath.includes(node.right) && mapper(node.right, dis + 1, next);
node.parent && !prevPath.includes(node.parent) && mapper(node.parent, dis + 1, next);
}
if (dis > K) return
})(target, 0, []);
return res
};
// @lc code=end
|
PHP
|
UTF-8
| 1,068
| 3
| 3
|
[
"LicenseRef-scancode-996-icu-1.0",
"Apache-2.0",
"ICU"
] |
permissive
|
<?php
use \Go\Chan;
use \Go\Time;
use \Go\Scheduler;
$ch1 = new Chan(["capacity"=>1]);
$ch2 = new Chan(["capacity"=>1]);
$exit = new Chan(0);
go(function() use($ch1, $ch2, $exit){
$selector = select(
[
'case', $ch1, function($value){
echo "go 0: receive from ch1: " . $value . PHP_EOL;
}
],
[
'case', $ch2, function($value){
echo "go 0: receive from ch2: " . $value . PHP_EOL;
}
]
);
echo "go 0: after 1st select\n";
while( $exit->tryPop() !== NULL ) $selector->select();
});
go(function() use($ch1, $exit){
$i = 0;
while( $exit->tryPop() !== NULL ){ //===NULL: channel closed
echo "go 1: push $i\n";
$ch1->push($i++);
}
});
go(function() use($ch2, $exit){
$i = 0;
while( $exit->tryPop() !== NULL ){
echo "go 2: push $i\n";
$ch2->push($i++);
}
});
go(function() use($exit){
echo "main: now sleep 5ms\n";
Time::sleep(5*1000*1000);
echo "main: now close the exit channel\n";
$exit->close();
});
Scheduler::join();
|
PHP
|
UTF-8
| 1,255
| 2.515625
| 3
|
[] |
no_license
|
<?php
class pages_categoryModel extends commonModel
{
public function __construct()
{
parent::__construct();
}
//模型附加表信息
public function model_ini_data()
{
return array();
}
//模型文件或文件夹信息
public function model_ini_file()
{
return array();
}
//保存单页内容
public function page_save($data)
{
$data['content'] = html_in($data['content']);
return $this->model->table('category_page')->data($data)->insert();
}
//编辑单页内容
public function edit_save($data)
{
$cid = intval($data['cid']);
$data['content'] = html_in($data['content']);
return $this->model->table('category_page')->data($data)->where('cid=' . $cid)->update();
}
//获取页面内容
public function page_info($cid)
{
$data['content'] = html_in($data['content']);
return $this->model->table('category_page')->where('cid=' . $cid)->find();
}
//删除页面内容
//栏目删除
public function del($cid)
{
return $this->model->table('category_page')->where('cid=' . $cid)->delete();
}
}
?>
|
Markdown
|
UTF-8
| 1,125
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
# Get Unsubscribed Stats
This gets an XML document with the unsubscribed stats for a particular promotion and mail send.
## Unsubscribed Stats Options
[MadMimi's Statistics API Documentation](https://madmimi.com/developer/statistics-api-methods) should give you an idea
of what you need to send to the API. This options object makes some of the methods easier.
Please keep in mind - **both promotion ID and mailing ID must be set** for this class.
### Method Reference
`Unsubscribed::setPromotionId($promotionId)` - Sets the promotion ID that should be retrieved
`Unsubscribed::setMailingId($promotionId)` - Sets the mailing ID that should be retrieved
`Unsubscribed::setPage($pageNumber)` - Sets the page of records to view
`Unsubscribed::setRecordsPerPage($recordsPerPage)` - Sets the amount of records per page
## Exceptions
The following exceptions may be thrown throughout the duration of a options object.
- `MadMimi\Exception\InvalidOptionException` During options object creation, a value in the array of the constructor argument that's key was not defined as a protected property of this options class
|
Markdown
|
UTF-8
| 24,240
| 2.65625
| 3
|
[] |
no_license
|
---
title: ०२१
---
महातपा उवाच ।
पूर्वं प्रजापतिर्देवः सिसृक्षुर्विविधाः प्रजाः ।
चिन्तयामास धर्मात्मा यदा ता नाध्यगच्छत ।। २१.२ ।।
तदाऽस्य कोपात् संजज्ञे स च रुद्रः प्रतापवान् ।
रोदनात् तस्य रुद्रत्वं संजातं परमेष्ठिनः ।। २१.३ ।।
तस्य ब्रह्मा शुभां कन्यां भार्यार्थं मूर्त्तिसंभवाम् ।
गौरी नाम्ना स्वयं देवी भारती तां ददौ पिता ।। २१.४ ।।
रुद्रायामितदेहाय स्वयं ब्रह्मा प्रजापतिः ।
स तां लब्ध्वा वरारोहां मुदा परमया युतः ।। २१.५ ।।
सर्गकालेषु तं ब्रह्मा तपसा प्रत्युवाच ह ।
रुद्र प्रजाः सृजस्वेति पौनःपुन्येन चोदितः ।
असमर्थोऽहमिति जले निमज्जत महाबलः ।। २१.६ ।।
तपोर्थित्वं तपोहीनः स्त्रष्टुं शक्नोति न प्रजाः ।
एवं चिन्त्य जले मग्नस्ततो रुद्रः प्रतापवान् ।। २१.७ ।।
तस्मिन् निमग्ने देवेशे तां ब्रह्मा कन्यकां पुनः ।
अन्तःशरीरगां कृत्वा गौरीं परमशोभनाम् ।। २१.८ ।।
पुनः सिसृक्षुर्भगवानसृजत् सप्त मानसान् ।
दक्षं च तेषामारभ्य प्रजाः सम्यग् व्यवर्द्धिताः ।। २१.९ ।।
तत्र दाक्षायणीपुत्राः सर्वे देवाः सवासवाः ।
वसवोऽष्टौ च रुद्राश्च आदित्या मरुतस्तथा ।। २१.१० ।।
साऽपि दक्षाय सुश्रोणी गौरी दत्ताथ ब्रह्मणा ।
दुहितृत्वे पुरा या हि रुद्रेणोढा महात्मना ।। २१.११ ।।
सा च दाक्षायणी देवी पुनर्भूता नृपोत्तम ।
ततो दक्षः प्रहृष्टात्मा दौहित्रान् स्वान् स वृद्धिकृत् ।
दृष्ट्वा यज्ञमथारेभे प्रीणनाय प्रजापतिः ।। २१.१२ ।।
तत्र ब्रह्मसुताः सर्वे मरीच्यादय एव च ।
चक्रुरार्त्त्विज्यकं कर्म्म स्वे स्वे मार्गे व्यवस्थिताः ।। २१.१३ ।।
ब्रह्मा स्वयं मरीच्यस्तु बभूवाऽन्ये तथापरे ।
अत्रिस्तु यज्ञकर्मस्थ आग्नीध्रस्त्वङ्गिरा भवत् ।। २१.१४ ।।
होता पुलस्त्यस्त्वभवदुद्गाता पुलहोऽभवत् ।
क्रतौ क्रतुस्तु प्रस्तोता तदा यज्ञे महातपाः ।। २१.१५ ।।
प्रतिहर्ता प्रचेतास्तु तस्मिन् क्रतुवरे बभौ ।
सुब्रह्मण्यो वसिष्ठस्तु सनकाद्याः सभासदः ।
तत्र याज्यः स्वयं ब्रह्मा स च इज्यस्तु पूज्यते ।। २१.१६ ।।
पूज्या दक्षस्य दौहित्रा रुद्रादित्याङ्गिरादयः ।
प्रत्यक्षपितरस्ते हि तैः प्रीतैः प्रीयते जगत् ।। २१.१७ ।।
तत्र भागार्थिनो देवा आदित्या वसवस्तथा ।
विश्वेदेवाः सपितरो गन्धर्वाद्या मरुद्गणाः ।। २१.१८ ।।
जगृहुर्यज्ञभागान् स्वान् यावत् ते हविषोर्पितान् ।
तावत्कालं जलात् सद्य उत्तस्थौ ब्रह्मणः पुनः ।। २१.१९ ।।
रुद्रः कोपोद्भवो यस्तु पूर्वं मग्नो महाजले ।
स सहस्त्रार्कसंकाशो निश्चक्राम जलात् ततः ।। २१.२० ।।
सर्वज्ञानमयो देवः सर्वदेवमयोऽमलः ।
प्रत्यक्षदर्शी सर्वस्य जगतस्तपसा बभौ ।। २१.२१ ।।
तस्मिंस्तु काले पञ्चानां जातः सर्गो नरोत्तम ।
दिव्यानां पृथिवीस्थानां चतुर्णामरजातिनाम् ।। २१.२२ ।।
रौद्रसर्गस्य संभूतिस्तदा सद्योऽपि जायते ।
इदानीं रुद्रसर्गं त्वं श्रृणु पार्थिवसत्तम ।। २१.२३ ।।
दशवर्षसहस्त्राणि तपश्चीर्त्वा महज्जले ।
प्रतिबुद्धो यदा रुद्रस्तदा चोर्वों सकाननाम् ।
दृष्ट्वा सस्यवतीं रम्यां मनुष्यपशुसंकुलाम् ।। २१.२४ ।।
शुश्राव च तदा शब्दानृत्विजां दक्षसद्मनि ।
आश्रमे यज्ञिनां चोच्चैर्योगस्थैरिति कीर्त्तितम् ।। २१.२५ ।।
ततः श्रुत्वा महातेजाः सर्वज्ञः परमेश्वरः ।
चुकोप सुभृशं देवो वाक्यं चेदमुवाच ह ।। २१.२६ ।।
अहं पूर्वं तु कविना सृष्टः सर्वात्मना विभुः ।
प्रजाः सृजस्वेति तदा वाक्यमेतत् तथोक्तवान् ।। २१.२७ ।।
इदानीं केन तत्कर्म कृतं सृष्ट्यादिवर्णनम् ।
एवमुक्त्वा भृशं कोपान्ननाद परमेश्वरः ।। २१.२८ ।।
तस्य नानदतो ज्वालाः श्रोत्रेभ्यो निर्ययुस्तदा ।
तत्र भूतानि वेताला उच्छ्रुष्माः प्रेतपूतनाः ।। २१.२९ ।।
कूष्माण्डा यातुधानाश्च सर्वे प्रज्वलिताननाः ।
उत्तस्थुः कोटिशस्तत्र नानाप्रहरणावृताः ।। २१.३० ।।
ते दृष्ट्वा भूतसंघाता विविधायुधपाणयः ।
ससर्ज वेदविद्याङ्गं रथं परमशोभनम् ।। २१.३१ ।।
तस्मिन्नृगादयस्त्वश्वास्त्रितत्त्वं च त्रिवेणुकम् ।
त्रिपूजकं त्रिषवणं धर्माक्षं मारुतध्वनिम् ।। २१.३२ ।।
अहोरात्रे पताके द्वे धर्माधर्मे तु दण्डके ।
शकटं सर्वविद्याश्च स्वयं ब्रह्मादिसारथिः ।। २१.३३ ।।
गायत्री च धनुस्तस्य ओङ्कारो गुण एव च ।
स्वराः सप्त शरास्तस्य देवदेवस्य सुव्रत ।। २१.३४ ।।
एवं कृत्वा स सामग्रीं देवदेवः प्रतापवान् ।
जगाम दक्षयज्ञाय कोपाद् रुद्रः प्रतापवान् ।। २१.३५ ।।
गच्छतस्तस्य देवस्य अम्बराङ्गिरसं नयत् ।
ऋत्विजां मन्त्रनिचयो नष्टो रुद्रागमे तदा ।। २१.३६ ।।
विपरीतमिदं दृष्ट्वा तदा सर्वे च ऋत्विजः ।
ऊचुः संनह्यतां देवा महद् वो भयमागतम् ।। २१.३७ ।।
कश्चिदायाति बलवानसुरो ब्रह्मनिर्मितः ।
यज्ञभागार्थमेतस्मिन् क्रतौ परमदुर्लभम् ।। २१.३८ ।।
एवमुक्तास्ततो देवा ऊचुर्मातामहं तदा ।
दक्ष तात किमत्रास्मत्कार्यं ब्रूहि विवक्षितम् ।। २१.३९ ।।
दक्ष उवाच ।
गृह्यन्तां द्रुतमस्त्राणि संग्रामोऽत्र विधीयताम् ।
एवमुक्ते तदा देवैर्विविधायुधधारिभिः ।
रुद्रस्यानुचरैः सार्धं महद्युद्धं प्रवर्तितम् ।। २१.४० ।।
तत्र वेतालभूतानि कूष्माण्डा ग्रहपूतनाः ।
युयुधुर्लोकपालैश्च नानाशस्त्रधराणि च ।। २१.४१ ।।
देवा रौद्राणि भूतानि निरसन्तो यमालयम् ।
चिक्षिपुः सायकान् घोरानसींश्च सपरश्वधान् ।। २१.४२ ।।
भूतान्यपि मृधे धोराण्युल्मुकैरस्थिभिः शरैः ।
जग्मुर्देवान् मृधे रोषाद् रुद्रस्य पुरतो बलात् ।। २१.४३ ।।
ततस्तस्मिन् महारौद्रे संग्रामे भीमरूपिणि ।
रुद्रो भगस्य नेत्रे तु बिभेदैकेषुणा मृधे ।। २१.४४ ।।
रुद्रस्य शरपातेन नष्टनेत्रं भगं तदा ।
दृष्ट्वाऽस्य क्रोधात् तेजस्वी पूषा रुद्रमयोधयत् ।। २१.४५ ।।
सृजन्तमिषुजालानि पूषणं तु महामृधे ।
दृष्ट्वा रुद्रोऽस्य दन्तांस्तु चकर्षं परवीरहा ।। २१.४६ ।।
तस्य दन्तांस्तदा दृष्ट्वा पूष्णो रुद्रेण पातितान् ।
दुद्रुवुः वसवो दिक्षु रुद्रास्त्वेकादश द्रुतम् ।। २१.४७ ।।
तान् भग्नान् सहसा दिक्षु दृष्ट्वा विष्णुः प्रतापवान् ।
आदित्यावरजो वाक्यमुवाच स्वबलं तदा ।। २१.४८ ।।
क्व यात पौरुषं त्यक्त्वा दर्पं माहात्म्यमेव च ।
व्यवसायं कुलं भूतिं कथं न स्मर्यते द्रुतम् ।। २१.४९ ।।
परमेष्ठिगुणैर्युक्तो लघुवद्भीतितः पुरा ।
नमस्कं कुरुते मोघं पृथिव्यां पद्मजः स्वयम् ।। २१.५० ।।
एवमुक्त्वा गरुत्मन्तमारुरोह हरिस्तदा ।
शङ्खचक्रगदापाणिः पीतवासा जनार्दनः ।। २१.५१ ।।
ततो हरिहरं युद्धमभवल्लोमहर्षणम् ।
रुद्रः पाशुपतास्त्रेण विव्याध हरिमोजसा ।
हरिर्नारायणास्त्रेण रुद्रं विव्याध कोपवान् ।। २१.५२ ।।
नारायणं पाशुपतमुभेऽस्त्रे व्योम्नि रोषिते ।
युयुधाते भृशं दिव्यं परस्परजिघांसया ।
दिव्यं वर्षसहस्त्रं तु तयोर्युद्धमभूत् तदा ।। २१.५३ ।।
तत्रैकं मुकुटोद्बद्धं मूर्द्धन्यं जटजालकम् ।
एकं प्रध्मापयच्छङ्खमन्यडुमरुकं शुभम् ।। २१.५४ ।।
एकं खङ्गकरं तत्र तथाऽन्यं दण्डधारिणम् ।
एकं कौस्तुभदीप्ताङ्गमन्यं भूतिविभूषितम् ।। २१.५५ ।।
एकं गदां भ्रामयति द्वितीयं दण्डमेव च ।
एकं शोभति कण्ठस्थैर्मणिभिस्त्वस्थिभिः परम् ।
एकं पीताम्बरं तत्र द्वितीयं सर्पमेखलम् ।। २१.५६ ।।
एवं तौ स्पर्द्धिनावस्त्रौ रौद्रनारायणात्मकौ ।
अन्योऽन्यातिशयोपेतौ तदालोक्य पितामहः ।। २१.५७ ।।
उवाच शाम्यतामस्त्रौ स्वस्वभावेन सुव्रतौ ।
एवं ते ब्रह्मणा चोक्तौ शान्तभावं प्रजग्मतुः ।। २१.५८ ।।
तथा विष्णुहरौ ब्रह्मा वाक्यमेतदुवाच ह ।
उभौ हरिहरौ देवौ लोके ख्यातिं गमिष्यथः ।। २१.५९ ।।
अयं च यज्ञो विध्वस्तः संपूर्णत्वं गमिष्यति ।
दक्षस्य ख्यातिमाँल्लोकः संतत्याऽयं भविष्यति ।। २१.६० ।।
एवमुक्त्वा हरिहरौ तदा लोकपितामहः ।
ब्रह्मा लोकानुवाचेदं रुद्रभागोऽस्य दीयताम् ।। २१.६१ ।।
रुद्रभागो ज्येष्ठभाग इतीयं वैदिकी श्रुतिः ।
स्तुतिं च देवाः कुरुत रुद्रस्य परमेष्ठि नः ।। २१.६२ ।।
भगनेत्रहरं देवं पूष्णो दन्तविनाशनम् ।
स्तुतिं कुरुतमा शीघ्रं गीतैरेतैस्तु नामभिः ।
येनायं वः प्रसन्नात्मा वरदत्वं भजेत ह ।। २१.६३ ।।
एवमुक्तास्तु ते देवाः स्तोत्रं शंभोर्महात्मनः ।
चक्रुः परमया भक्त्या नमस्कृत्य स्वयंभुवे ।। २१.६४ ।।
देवा ऊचुः ।
नमो विषमनेत्राय नमस्ते त्र्यम्बकाय च ।
नमः सहस्त्रनेत्राय नमस्ते शूलपाणये ।। २१.६५ ।।
नमः खट्वाङ्गहस्ताय नमो दण्डभृते करे ।
त्वं देव हुतभुग्ज्वालाकोटिभानुसमप्रभः ।। २१.६६ ।।
अदर्शनेऽनयद् देव मूढविज्ञानतोऽधुना ।
कृतमस्माभिरेवेश तदत्र क्षम्यतां प्रभो ।। २१.६७ ।।
नमस्त्रिनेत्रार्त्तिहराय शंभो
त्रिशूलपाणे विकृतास्यरूप ।
समस्तदेवेश्वर शुद्धभाव
प्रसीद रुद्राच्युत सर्वभाव ।। २१.६८ ।।
पूष्णोऽस्य दन्तान्तक भीमरूप
प्रलम्बभोगीन्द्रलुलन्तकण्ठ ।
विशालदेहाच्युत नीलकण्ठ
प्रसीद विश्वेश्वर विश्वमूर्त्ते ।। २१.६९ ।।
भगाक्षिसंस्फोटनदक्षकर्मा
गृहाण भागं मखतः प्रधानम् ।
प्रसीद देवेश्वर नीलकण्ठ
प्रपाहि नः सर्वगुणोपपन्न ।। २१.७० ।।
सिताङ्गरागाप्रतिपन्नमूर्त्ते
कपालधारिंस्त्रिपुरघ्न देव ।
प्रपाहि नः सर्वभयेषु चैव
उमापते पुष्करनालजन्म ।। २१.७१ ।।
पश्याम ते देहगतान् सुरेश
सर्गादयो वेदवराननन्त ।
साङ्गान् सविद्यान् सपदक्रमांश्च
सर्वान् निलीनांस्त्वयि देवदेव ।। २१.७२ ।।
भव शर्व महादेव पिनाकिन् रुद्र ते हर ।
नताः स्म सर्वे विश्वेश त्राहि नः परमेश्वर ।। २१.७३ ।।
इत्थं स्तुतस्तदा देवैर्देवदेवो महेश्वरः ।
तुतोष सर्वदेवानां वाक्यं चेदमुवाच ह ।। २१.७४ ।।
रुद्र उवाच ।
भगस्य नेत्रं भवतु पूष्णो दन्तास्तथा मखः ।
दक्षस्याच्छिद्रतां यातु यज्ञश्चाप्यदितेः सुताः ।
पशुभावं तथा चापि अपनेष्यामि वो सुराः ।। २१.७५ ।।
मद्दर्शनेन यो जातः पशुभावो दिवौकसाम् ।
स मयाऽपहृतः सद्यः पतित्वं वो भविष्यति ।। २१.७६ ।।
अहं च सर्वविद्यानां पतिराद्यः सनातनः ।
अहं वै पतिभावेन पशुमध्ये व्यवस्थितः ।। २१.७७ ।।
अतः पशुपतिर्नाम मम लोके भविष्यति ।
ये मां यजन्ति तेषां स्याद् दीक्षा पाशुपती भवेत् ।। २१.७८ ।।
एवमुक्तेऽथ रुद्रेण ब्रह्मा लोकपितामहः ।
उवाच रुद्रं सस्नेहं स्मितपूर्वमिदं वचः ।। २१.७९ ।।
ध्रुवं पाशुपतिर्देव त्वं लोके ख्यातिमेस्यति ।
अयं च देवस्त्वन्नाम्ना लोके ख्यातिं गमिष्यति ।
आराध्यश्च समस्तानां देवादीनां गमिष्यसि ।। २१.८० ।।
एवमुक्त्वा तदा ब्रह्मा दक्षं प्रोवाच बुद्धिमान् ।
गौरीं प्रयच्छ रुद्राय पूर्वमेवोपपादिताम् ।। २१.८१ ।।
एवमुक्त्वा तदा दक्षस्तां कन्यां ब्रह्मसन्निधौ ।
ददौ रुद्राय महते गौरीं परमशोभनाम् ।। २१.८२ ।।
स तां जग्राह विधिवद् रुद्रः परमशोभनाम् ।
दक्षस्य च प्रियं कुर्वन् बहुमानपुरःसरम् ।। २१.८३ ।।
गृहीतायां तु कन्यायां दाक्षायण्यां पितामहः ।
ददौ रुद्रस्य निलयं कैलासं सुरसन्निधौ ।। २१.८४ ।।
रुद्रोऽपि प्रययौ भूतैः समं कैलासपर्वतम् ।
देवाश्चापि यथास्थानं स्वं स्वं जग्मुर्मुदान्विताः ।
ब्रह्माऽपि दक्षसहितः प्राजापत्यं पुरं ययौ ।। २१.८५ ।।
।। इति श्रीवराहपुराणे भगवच्छास्त्रे एकविंशोऽध्यायः ।। २१ ।।
|
Java
|
UTF-8
| 994
| 2.921875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Question3;
import java.util.ArrayList;
import java.util.Date;
/**
*
* @author Sai Satyanarayana Gullapalli
*/
public class MainDriver {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ArrayList<Object> arrayOfObjects = new ArrayList<>();
LoanTest loanData = new LoanTest("Car", 1000000, 7);
CircleTest circleData = new CircleTest("Satya", 2.5, true);
String stringData = "Exam";
Date dateData = new Date();
arrayOfObjects.add(loanData);
arrayOfObjects.add(circleData);
arrayOfObjects.add(stringData);
arrayOfObjects.add(dateData);
for (Object LCSD : arrayOfObjects) {
System.out.println(LCSD);
}
}
}
|
Swift
|
UTF-8
| 1,741
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
/// An abstract protocol that a GraphQL "`scalar`" type must conform to.
///
/// # See Also
/// [GraphQL Spec - Scalars](http://spec.graphql.org/October2021/#sec-Scalars)
public protocol AnyScalarType: JSONEncodable, AnyHashableConvertible {}
/// A protocol that represents any GraphQL "`scalar`" defined in the GraphQL Specification.
///
/// Conforming types are:
/// * `String`
/// * `Int`
/// * `Bool`
/// * `Float`
/// * `Double`
///
/// # See Also
/// [GraphQL Spec - Scalars](http://spec.graphql.org/October2021/#sec-Scalars)
public protocol ScalarType:
AnyScalarType,
JSONDecodable,
GraphQLOperationVariableValue {}
extension String: ScalarType {}
extension Int: ScalarType {}
extension Bool: ScalarType {}
extension Float: ScalarType {}
extension Double: ScalarType {}
/// A protocol a custom GraphQL "`scalar`" must conform to.
///
/// Custom scalars defined in a schema are generated to conform to the ``CustomScalarType``
/// protocol. By default, these are generated as typealiases to `String`. You can edit the
/// implementation of a custom scalar in the generated file. *Changes to generated custom scalar
/// types will not be overwritten when running code generation again.*
///
/// # See Also
/// [GraphQL Spec - Scalars](http://spec.graphql.org/October2021/#sec-Scalars)
public protocol CustomScalarType:
AnyScalarType,
JSONDecodable,
OutputTypeConvertible,
GraphQLOperationVariableValue
{}
extension CustomScalarType {
@inlinable public static var _asOutputType: Selection.Field.OutputType {
.nonNull(.customScalar(self))
}
}
extension Array: AnyScalarType where Array.Element: AnyScalarType & Hashable {}
extension Optional: AnyScalarType where Wrapped: AnyScalarType & Hashable {}
|
JavaScript
|
UTF-8
| 3,547
| 3.171875
| 3
|
[] |
no_license
|
//Array con el listado de canciones a mostrar en el reprodutor
const canciones = [
"music1.mp3",
"music2.mp3",
"music3.mp3"
]
var indiceActual = new Array(1)
function crearPlayList(){//Función para crear la playlist
const listado = document.createElement('ol')
listado.setAttribute("id", 'listadoMusica')
for (let i = 0; i<canciones.length; i++){
const item = document.createElement('li')
item.appendChild(document.createTextNode(canciones[i]))
item.setAttribute("id", canciones.indexOf(canciones[i]))
listado.appendChild(item)
}
return listado
}
document.getElementById('playList').appendChild(crearPlayList())
var listadoMusica= document.getElementById('listadoMusica')
listadoMusica.onclick = (e) =>{
const itemClick = e.target
removeActive()
itemClick.classList.add("active");
reproduccionActual("Reproduciendo: "+ itemClick.innerText)
loadMusic(itemClick.innerText)
player.play()
indiceActual[0]= e.target.id
}
function nextMusic(){ //Siguiente canción
const source = document.getElementById('source');
var musicaActual= Number(indiceActual[0]);
if (canciones.length == (musicaActual+1)){
var siguiente = 0
} else {
var siguiente = musicaActual + 1
}
removeActive()
var item=document.getElementById(siguiente)
item.classList.add("active");
loadMusic(canciones[siguiente]);
player.play()
indiceActual[0]= siguiente
reproduccionActual(canciones[siguiente])
}
function prevMusic(){ //Canción anterior
const source = document.getElementById('source');
var musicaActual= Number(indiceActual[0]);
if (musicaActual==0){
var anterior= canciones.length - 1
} else {
var anterior = musicaActual - 1
}
removeActive()
var item=document.getElementById(anterior)
item.classList.add("active");
loadMusic(canciones[anterior]);
player.play()
indiceActual[0]= anterior
reproduccionActual(canciones[anterior])
}
function removeActive(){//Parar la reproducción activa
var elems = document.querySelectorAll(".active");
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
return elems
}
function reproduccionActual(texto){//Muestra la canción que se esta reproduciendo
document.getElementById('currentPlay').innerText=texto
}
function loadMusic(ruta){//Carga las canciones en el reproductor
var source = document.getElementById('source')
var folder ="audio";
source.src= folder+"/"+ruta
var index= indiceActual[0]= canciones.indexOf(ruta)
removeActive()
var item=document.getElementById(index)
item.classList.add("active");
reproduccionActual("Reproduciendo: "+ ruta)
player.load()
}
window.onload = function(){//Funcion para pausar o darle play
var player = document.getElementById("player");
document.getElementById("play").onclick = function(){player.play()}
document.getElementById("pause").onclick = function(){player.pause()}
}
loadMusic(canciones[0])
|
C++
|
UTF-8
| 653
| 2.65625
| 3
|
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int n,x;
int s[111];
void input(){
scanf("%d %d",&n,&x);
for (int i=0;i<n;i++)
scanf("%d",&s[i]);
}
int binary_search(int so){
int l = 0;
int r = n-1;
int m;
while ( l <= r ){
m = ( l+r )/2;
if ( so == s[m] )
return m;
if ( so > s[m] )
l = m+1;
else
r = m-1;
}
return -1;
}
void solve(){
printf("%d\n",binary_search(x));
}
int main()
{
freopen("binarysearch.inp","r",stdin);
input();
solve();
return 0;
}
|
C
|
UTF-8
| 4,397
| 2.8125
| 3
|
[
"CC0-1.0"
] |
permissive
|
#include "copy.h"
#include <exec/types.h>
#include <proto/keymap.h>
#include <assert.h>
#include <string.h>
// 'Normal' kmEntries are copied as-is
void copyNormal(void* pContext, UBYTE rawKey, UBYTE kmType, ULONG kmEntry) {
CopyContext* pClone = pContext;
*(pClone->pKmEntry++) = kmEntry;
}
// 'KCF_NOP' kmEntries are copied as-is.
void copyNop(void* pContext, UBYTE rawKey, UBYTE kmType, ULONG kmEntry) {
CopyContext* pClone = pContext;
*(pClone->pKmEntry++) = kmEntry;
}
// 'KCF_STRING' entries append a copy of the referenced string table to 'pBuffer'
// and write the address to the kmEntry.
void copyString(void* pContext, UBYTE rawKey, int numEntries, const UBYTE* pSrcTable) {
CopyContext* pClone = pContext;
// Remember the start of the src/dest string tables. We'll need these for
// computing the string offsets.
const UBYTE* pSrcStart = pSrcTable;
UBYTE* pDestTable = pClone->pBuffer;
const UBYTE* pDestStart = pDestTable;
// Write the address of the string table to the kmEntry.
*(pClone->pKmEntry++) = (ULONG) pDestStart;
// Bump 'pBuffer' to point to the beginning of the char data. Entering the
// loop, our pointers are arranged as follows:
//
// pSrcStart,
// pSrcTable pBuffer
// | |
// v v
// +-----------------+------------------------------+
// | len/off | char data |
// | numEntries * 2B | (Σ lens B) |
// +-----------------+------------------------------+
//
// pSrcTable is advanced as we copy the string length and offsets. pSrcStart is
// a const pointer used when calculating offsets into the char data.
pClone->pBuffer += (numEntries << 1);
for (int n = 0; n < numEntries; n++) {
const UBYTE len = *(pDestTable++) = *(pSrcTable++); // Copy length
UBYTE off = *(pDestTable++) = pClone->pBuffer - pDestStart; // Compute offset
memcpy(pClone->pBuffer, pSrcStart + *(pSrcTable++), len); // Copy bytes
pClone->pBuffer += len;
}
}
// 'KCF_DEAD' entries append a copy of the referenced dead table to 'pBuffer'
// and write the address to the kmEntry.
void copyDead(void* pContext, UBYTE rawKey, int numEntries, const UBYTE* pSrcTable) {
CopyContext* pClone = pContext;
// Remember the start of the src/dest. We'll need these for computing the
// offsets to dead tables for DPF_MOD entries.
const UBYTE* pSrcStart = pSrcTable;
UBYTE* pDestTable = pClone->pBuffer;
const UBYTE* pDestStart = pDestTable;
// Write the address of the dead table to the kmEntry.
*(pClone->pKmEntry++) = (ULONG) pDestStart;
// Bump 'pBuffer' to point to the beginning of the char data. Entering the
// loop, our pointers are arranged as follows:
//
// pSrcStart,
// pSrcTable pBuffer
// | |
// v v
// +-----------------+------------------------------+
// | kind/value | dead tables |
// | numEntries * 2B | |
// +-----------------+------------------------------+
//
//
// pSrcTable is advanced as we copy the dead kind/value entries. pSrcStart is
// a const pointer used when calculating offsets into the data tables.
pClone->pBuffer += (numEntries << 1);
for (int n = 0; n < numEntries; n++) {
const UBYTE kind = *(pDestTable++) = *(pSrcTable++); // copy kind
switch (kind) {
case 0:
*(pDestTable++) = *(pSrcTable++); // copy char
break;
case DPF_DEAD:
*(pDestTable++) = *(pSrcTable++); // copy index
break;
default:
assert(kind == DPF_MOD);
UBYTE off = *(pDestTable++) = pClone->pBuffer - pDestStart; // Compute offset
const UBYTE len = pClone->deadCharTableBytes;
memcpy(pClone->pBuffer, pSrcStart + *(pSrcTable++), len); // Copy table
pClone->pBuffer += len;
break;
}
}
}
const Visitor CopyVisitor = {
copyNormal,
copyString,
copyDead,
copyNop,
};
|
Java
|
UTF-8
| 928
| 2.390625
| 2
|
[] |
no_license
|
package ua.com.golubov.algo.exam.test;
import org.junit.Test;
import ua.com.golubov.algo.exam.CodilityNokiaService;
import static org.junit.Assert.assertEquals;
public class CodilityNokiaServiceTest {
@Test
public void testCase() {
assertEquals(11, new CodilityNokiaService().solution(9736));
assertEquals(11, new CodilityNokiaService().solution(9736));
}
@Test
public void testCase2() {
}
@Test
public void testCase3() {
assertEquals(0, new CodilityNokiaService().solution(1_000_000_000, 1_000_000_000, 1_000_000_000));
assertEquals(0, new CodilityNokiaService().solution(0, 100, 1_000_000_000));
assertEquals(1, new CodilityNokiaService().solution(100, 0, 99));
assertEquals(1, new CodilityNokiaService().solution(1_000_000_001, 1_000_000_000, 1_000_000_000));
assertEquals(1, new CodilityNokiaService().solution(3, 4, 8));
}
}
|
Python
|
UTF-8
| 289
| 3.53125
| 4
|
[
"MIT"
] |
permissive
|
"""
A function that used to be buggy.
"""
def createabug(x):
"""
A function that created a bug by dividing by zero.
"""
y = x**4
# Stop the script and debug it.
#import pdb; pdb.set_trace()
# Set z to 1 rather than zero.
z = 1.
y = y/z
return y
print createabug(25)
|
Markdown
|
UTF-8
| 14,679
| 2.890625
| 3
|
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
---
---
title: 11统治阶层支配的历史
---
我们常用自己的眼光看待不熟悉的外国文化。北京政府所用的一些词句,使我们对它更难理解。中国的政治文章不光有道德性,还常掺杂进一些对历史人物的影射,如秦始皇(公元前221年,他建立起统一的帝国,被视为一个残酷的暴君,但也可把他看成是具有进步意义的人物),还有最近发明的马克思主义词汇,如“走资派”(指赞成用物质奖励促进生产的忠诚的党员;他本人并非资本家,但主张走物质发展的道路)。中国的民俗学与马克思主义对美国人来说都是异邦之物,我们在这两者间发现一些意义含混的词语,其威力显而易见,内容却令我们感到迷惑不解。既然中国的政治论争通常是间接和隐晦的,那么,这种迷惑也正说明了我们对中国政治的无知。
历史可以帮助我们。先来看看毛泽东和周恩来,他们是中国共产主义革命的主要领导者,扮演着两个典型的历史角色。1911年清王朝解体时,中国的独裁政治已演化了2000多年,当时毛还是一所小学的尖子生。遗憾的是,我们对中国的研究很不深人,以致像这样一个世界最古老的统治机构,在今天仍未用政治科学的术语加以分析、研究――无疑,对历史学家和政治学家来说,中国的史料记载太浩繁、太难懂了。我们知道,中国的君主政治和科举制度一样都出自同一个政治传统。科举最早出现于唐朝,比查里曼在西方建立中央政权还早200年。再提早ll00年,中国已发明了官僚政治,那时,中国就着手创立中央集权统治极为复杂的政府机构。这一古老传统一直延续到2O世纪,甚至仍控制着当今的中国政治。
任何一个伟大的革命家都想抛开历史,使一切从头开始。但中国人在世界各民族中最有历史感,毛语录中充满了历史的引喻。中国革命的特点是反帝、反封建。假设新的革命理想主导了人们的思想,而人类行为中有一半或2/3(或90%?)的行为是不自觉形成的,那么,这些行为如何适应环境的发展呢?毛对旧思想和旧习俗深恶痛绝,是可以理解的。
以执政期的长短为例,在1607年以后的历史进程中,中国有两个皇帝各自统治了60年(康熙皇帝,1662―1722年;乾隆皇帝,1736―1795年)。从1861到1908年,慈禧太后掌权也达4O多年。此后是毛泽东,他与慈禧太后在各个方面都截然对立,只是在执政时间之长这一点上一致。设想一下,如果罗斯福从1932年入主白宫一直呆到现在,会是什么情景。毛泽东从1935年――有人说是从1927年起就开始领导中国革命。这可以说明,中国人愿意接受一个至高无上的个人权威,而不是法律的至高无上。
毛比历史上的所有皇帝更具创造力,这成为智慧和政策的源泉,但他反官僚,神秘莫测,甚至在销声匿迹几个月之后,又闪电般地出现。中国政治能没有这样一个人物吗?只有具有天子性格的人才能两度罢免第二号人物(1967年,是刘少奇;1971年,是林彪),像皇帝撤换大臣一样,并把曾被撤职的第三号人物邓小平副总理官复原职,同时,自己总是稳坐头把交椅。
1911年以前,天子只处在一个占人口不足5%的由官员、上层学者和地主商人组成的贵族统治阶级之上。毛对旧的统治阶级发动了史无前例的攻击,成为历史上最伟大的解放者。他的独特地位并非凭空而来,而是有其历史根源。毛在北京的心脏天安门城楼上回顾了中国革命的历程,他所站立的位置和几百年前紫禁城内皇帝登基的太和殿处在同一个中轴线上。站在这里攻击中国陈腐的过去,最具有历史意义。
可以认为,作为1935年之后中国共产党和1949年以后中华人民共和国的最高领导人,毛泽东所显露的许多品质都是由中国传统精神和习惯做法而来的。我们不必从未做大量报道的毛对母亲的好感,或大肆渲染的他与父亲的对立中,寻求他行为的秘密。实际上,在他成为中国最高领袖之后,就被深埋在中国人思想和行为中的、几千年的传统观念支配了。
中国的皇帝是高于一切的天子,他只遵从先祖、政体和孔教的遗训,不易为任何人控制。皇帝是选任官员的最后决定者;选拔时,他必须权衡能力和忠诚,或根据手下官员的表现决定其命运。他的行为代表着王朝的利益,不受规则约束,因此,他就是法律。他变幻无常,高深莫测,冷酷无情,官员们莫名其妙地被免职(有时反因为干得太好,引起了皇帝的嫉妒)。越居高官显位,就越祸福难测,也许今天还在行使权力,明天就铐镣加身,发配充军。这种帝王宠幸的不定性,是使官员们尽职尽力的一种手段。
例如,管理学家们惊奇地发现,清朝皇帝(1616―1911)在18世纪初发明了一种绝密的“御览”情报系统。全国的官员向皇帝递交的奏折,只能由皇帝一人拆看;他写在折子上的批语,也只交给起奏者。因此,在西方官僚机构建立之先,清朝皇帝就已在其官员中安插了许多情报人员。
周恩来是个理想的大臣:1935年以来,他始终忠于毛,无私地忠于职守,管理灵活、务实,具有一种感染、影响中国人民大众和外国人的特殊魅力。只有具备周公那种才智的人(大约3000年前,周公全心全意扶植一个小皇帝治理国家),才能毫无争议地稳坐新中国总理宝座达1/4世纪之久。周恩来成功地避免了做第二号人物,并能自始至终地调和矛盾,达到妥协,脚踏实地,使政府的管理职能得以发挥。当然,做到这些的关键是他从不冒犯最高权威,并能把他从偏激中拯救过来。当毛的运动把政府机构搞得支离破碎时,他又能把它们重新组织起来。最后,周成为反对激进派的温和派领袖,这说明周也无法阻止毛领导机构的衰弱。毛、周都握有实权,两人组成了联合阵线。这段历史表明,周对毛、周联合阵线,做出了巨大贡献。
两位领导人都是致力于摧毁旧秩序、创造新制度的一代革命新人,这并不能使他们从中国旧传统的束缚中解脱出来。整个中国革命都是在与传统做斗争,但当革命者之间出现意见分歧时,又都以传统来反击对方。这种历史的延续不摒弃近期的新发明,例如,现在认为,人能在新的环境中得到完善,并信奉行为主义的浅显哲学――在很大程度上,传统似乎并没有支配现在――对美国人来说,这很难理解。正如句子结构比内容相对稳定一样,尽管观念、政策被彻底颠倒了,中国人政治生活的基本形式将得以延续。例如,孔教和谐的理想被毛从西方引进的斗争观念所取代,但这两种思想都成为官方的正统理论,是庞大的中国政府所必不可少的。在研究近十年来“两条路线斗争”时,我们首先在许多发展中国家及其革命中看到一种共有的现象。一方面,科学技术在工业化或更广泛地讲在运用科技解决现代问题的过程中得以稳步发展;另一方面,革命热情在不断高涨。人们把斗争看成一场反对邪恶的旧秩序的道德运动,新闻界喜欢将温和派称为“实用主义者”。对我们来说,这些人似乎比“激进分子”及其抽象的理论术语更易于接受。总之,我们能够理解那些发展技术的人,尽管他们有着社会主义者对自由联合企业的憎恶。邓小平主张不管黑猫白猫,抓住老鼠就是好猫,而那些激进分子则运用一种近乎疯狂的语言,只关心夺权,阻碍经济发展。
然而,我们有把丹麦王子置于革命的《哈姆雷特》之外的危险,因为中国进行的是社会的也是经济的革命,其社会目标是推翻旧的统治阶级。研究中国革命,必先回顾中国历史,尤其是中国在很早以前就成功地创造了一个儿乎垄断全国文化阶层、宫僚政权和巨大财富的统治阶级,而其人数不足全国人口的5%或10%。这个统治阶级成分之庞杂和从大众中选拔贤才、维持自身地位及传统的能力,在世界社会史中首屈一指。中国的统治阶级谱写了中国的历史,因此,只能透过中国统治阶级考察中国历史。所以,史料中很难见到有关中国庞大农业人口的记载,尽管他们辛勤耕耘,忍饥挨饿或揭竿而起,但他们总是受一小部分脑力劳动者的控制和引导。
到了20世纪,旧的统治阶级已逐渐瓦解,因此革命的一个基本目标是消除达官贵人的特权,把文化知识、能动性和参与政治的权利传播给普通百姓。从广义上看,这确实是一场民主革命。具有讽刺意味的是,在进行这场革命的过程中,新生的公民还是产生了传统的,要求提高地位、享受更多特权和跻身上流社会的欲望。事实上,旧的统治阶级的思想已渗人到大众的头脑中,跻身上流社会在人们心目中仍是奋斗目标。因此,今天的人很容易被地位和特权诱惑。毛在革命中所要消除的东西,在那些领导这场革命的领导人身上似乎又重现了。这也说明为什么毛认为必须发动一系列的革命,来消除传统的弊端。我们非常同情这位老人,他在6O年代发现在新的官僚机构中又出现了特权。我们也很欣赏他的政治手腕:发动那些十几岁的红卫兵,出奇不意地攻击派系总部,帮他清除异己――莫斯科至今仍对这场运动感到不可思议。
然而,我们必须记住,毛的革命理想在美国人看来并不民主,国家对人民的控制仍过于严格。毛泽东主义者很巧妙地利用宣传媒介,攻击“走资派”和其他牛鬼蛇神。但毛泽东主义者自身有何怨言呢?
在此,美国观察家又一次被中国的传统迷惑了。在中国,人们总是把不合时宜的政策与道德败坏等同起来。对中国政治的这一特征,从未有满意的解释。它似乎源于理论联系实际的原则:行为表现性格,言必表现于行。这种传统思想一经成立,人们就不能像西方人那样,把政策与道德区分开来,相反,政策是官员行为的组成部分。一旦其政策为人厌恶,其道德品质也就受人怀疑了。这种观点产生的结果是,不可能有“忠诚的反对意见”,因为一个人反对另一个人的政策,就是反对他本人。因此,他们不像英美人那样,把对元首的忠诚和对元首现行政策的不满区分开。
我们在当代中国看到一个更令人惊异的现象――揭发当权者的恶劣品行。这使人想起帝王时代的监察宫――很久以前,他们就有权弹勃、劝诫官员注意言行。这些监察官受传统道德经典的教育,认为孔夫子的伦理道德至高无上,对其他任何有悖于此的世俗或自私的言行加以批驳。直到19世纪七八十年代,沙文主义的官员们还在劝告皇帝反对与外国人接触,特别是不要同法国妥协,当时,中法正在印度支那边境上交战。中国政治学中把这种职能称为“清议”。它类似于我们政治舞台上喧嚣的崇尚美国或反共运动,并兼有古老福音传道的地狱之火。“清议”者把自己置于无可指摘的理论权威的地位,且不负任何责任。面对这类批评家,没有人能取胜。另一方面,皇帝又偏信谗言,并把这做为惩罚官吏或重新组阁的依据。
中国两条不同政治路线的斗争以及代表两种路线的阵营,是我们的民主党和共和党无法相比的。中国两派力量的对比极为鲜明,一方主张发展经济,一方主张改造社会;一方是要完成人类使命的管理人员,一方是追求意识形态中完美准则的理论家。管理人员总体上握有军政大权,而理论家们则操纵着宣传工具。因此,我们看不到权力的平衡;激进分子显然在宣传上占了上风,却很少付诸行动。
所有试图了解中国政治的努力,都因一基本过失而屡遭挫折:我们总是以自己的经验来看待中国的政治。我们必须牢记一点,中国行政管理人员和思想理论家所追求的目标,和我们美国人所追求的迥然不同。例如,我们不是一个以农业为主的国家,没有在农村过联系紧密的集体生活的传统。我们从来也没有把一个国家高层次的文化知识生活,交给一小部分人来管理。
在毛主席和周总理时代,主席为使社会变革,发动了周期性的运动,总理行使着管理的职能。这种工作上多年的合作一直很成功,结果,毛泽东主席及其周围的人摆脱了另一方的束缚和制约。以前,伟大领袖可以统帅两条不同路线的人,只是偶尔侧重于推行一条路线,但后来毛完全站到了激进、喧嚣的派系一边。这使中国的形势恶化易变,但在政策上终归存在着两条路线,因为中国革命的两重性,即通过经济现代化强化国家,同时通过发动有利于民众的社会变革改变中国人的生活,决定了两种路线、政策的存在。事实上,革命的盛衰荣枯并没有使他们放弃目标。
在中国,中央政权特别是官僚统治阶层,依赖正统的意识形态和道德观念,这使中国革命特别容易出现起伏不定的局面。对于一个德治而不是法治的国家来说,主要祸患是随之而来的道德败坏和贪污腐化。但革命理想不会泯灭,中国有悠久的儒家改革的传统,而且不断地与官僚主义和特权做着不懈的斗争。中国历史成为中国革命的基础,因此,美国人要想了解中国革命,必先了解中国历史。
此篇评论的是《毛主席与人民对话:1956―1971年》(纽约:众神出版社,1974年),斯图尔特・斯瑞姆编辑,约翰・辛那瑞、泰云译,部分发表于1975年5月1日的《纽约书评》,其余部分发表在1976年9月的《哈佛杂志》,题为《北京政治:一位西方向导》。
|
Markdown
|
UTF-8
| 1,195
| 2.703125
| 3
|
[
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
# LED Single
identifier: 0x1e3048f8
camel: ledSingle
group: light
tags: 8bit, padauk
status: deprecated
A controller for 1 or more monochrome or RGB LEDs connected in parallel.
## Commands
command animate @ 0x80 {
to_red: u8
to_green: u8
to_blue: u8
speed: u8
}
This has the same semantics as `set_status_light` in the control service.
## Registers
ro color @ 0x180 {
red: u8
green: u8
blue: u8
}
The current color of the LED.
rw max_power? = 100: u16 mA @ max_power
Limit the power drawn by the light-strip (and controller).
const led_count?: u16 @ 0x183
If known, specifies the number of LEDs in parallel on this device.
const wave_length?: u16 nm { typical_min=365, typical_max=885 } @ 0x181
If monochrome LED, specifies the wave length of the LED.
const luminous_intensity?: u16 mcd { typical_min=10, typical_max=5000 } @ 0x182
The luminous intensity of the LED, at full value, in micro candella.
enum Variant: u8 {
ThroughHole = 1
SMD = 2
Power = 3
Bead = 4
}
const variant?: Variant @ variant
The physical type of LED.
|
Java
|
UTF-8
| 1,167
| 2.71875
| 3
|
[] |
no_license
|
package com.example.root.metr.utils;
import android.support.v7.util.DiffUtil;
import java.util.List;
public class DiffCallback<T> extends DiffUtil.Callback{
private List<T> oldPersons;
private List<T> newPersons;
public DiffCallback(List<T> newPersons, List<T> oldPersons) {
this.newPersons = newPersons;
this.oldPersons = oldPersons;
}
@Override
public int getOldListSize() {
return oldPersons.size();
}
@Override
public int getNewListSize() {
return newPersons.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return oldPersons.get(oldItemPosition).equals(newPersons.get(newItemPosition));
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return oldPersons.get(oldItemPosition).equals(newPersons.get(newItemPosition));
}
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
//you can return particular field for changed item.
return super.getChangePayload(oldItemPosition, newItemPosition);
}
}
|
Markdown
|
UTF-8
| 740
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
# angular-auto-save
Code to auto save content of page in every 5 seconds(time could be changed)
My new solution uses the $watch method that Angular provides for watching for changes to scope variables. I don’t want to make requests to the server with every keystroke, so I’ll use a simple debounce function (using Angular’s $timeout service) to limit my requests to happening every few seconds.
To implement this solution, there is nothing to add to your view. But in the controller, you’ll need to inject $timeout and write a couple $watch statement. I added a watch statement for each individual attribute of the model, but you could also do a deep watch of the entire model. This is slightly more expensive performance-wise.
|
Java
|
UTF-8
| 3,426
| 2.171875
| 2
|
[] |
no_license
|
package com.ambition.epm.baseinfo.dao;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Repository;
import com.ambition.epm.entity.EpmOrtIndicator;
import com.ambition.epm.entity.EpmOrtItem;
import com.norteksoft.product.orm.Page;
import com.norteksoft.product.orm.hibernate.HibernateDao;
import com.norteksoft.product.util.ContextUtils;
import com.norteksoft.product.web.struts2.Struts2Utils;
@Repository
public class EpmOrtItemDao extends HibernateDao<EpmOrtItem,Long>{
public Page<EpmOrtItem> list(Page<EpmOrtItem> page,EpmOrtIndicator ortIndicator){
if(ortIndicator != null){
return searchPageByHql(page,"from EpmOrtItem d where d.companyId = ? and d.ortIndicator = ?",new Object[]{ContextUtils.getCompanyId(),ortIndicator});
}else{
return searchPageByHql(page,"from EpmOrtItem d where d.companyId = ?",new Object[]{ContextUtils.getCompanyId()});
}
}
public Page<EpmOrtItem> listByParent(Page<EpmOrtItem> page,Long parentId){
List<Object> params = new ArrayList<Object>();
StringBuffer hql = new StringBuffer("from EpmOrtItem d where d.companyId = ?");
params.add(ContextUtils.getCompanyId());
String customSearch = Struts2Utils.getParameter("customSearch");
if(customSearch != null){
hql.append(" and d.itemName like ");
params.add("%" + customSearch.trim() + "%");
}else if(parentId != null){
hql.append(" and d.ortIndicator.id = ?");
params.add(parentId);
}
hql.append(" order by d.itemName desc");
return searchPageByHql(page, hql.toString(), params.toArray());
}
public Page<EpmOrtItem> getCodeByParams(Page<EpmOrtItem> page,JSONObject params,EpmOrtIndicator ortIndicator){
StringBuffer hql = new StringBuffer("from EpmOrtItem d where d.companyId=?");
List<Object> searchParams = new ArrayList<Object>();
searchParams.add(ContextUtils.getCompanyId());
if(params != null){
for(Object pro : params.keySet()){
hql.append(" and d." + pro + " like ?");
searchParams.add("%" + params.getString(pro.toString()) + "%");
}
}
if(ortIndicator!=null){
hql.append(" and d.ortIndicator = ?");
searchParams.add(ortIndicator);
}
hql.append(" order by d.ortItemNo");
return searchPageByHql(page,hql.toString(),searchParams.toArray());
}
public Page<EpmOrtItem> list(Page<EpmOrtItem> page, String itemName){
if(itemName != null){
return searchPageByHql(page,"from EpmOrtItem d where d.companyId = ? and d.itemName like ?",new Object[]{ContextUtils.getCompanyId(),"%"+itemName+"%"});
}else{
return searchPageByHql(page,"from EpmOrtItem d where d.companyId = ?",new Object[]{ContextUtils.getCompanyId()});
}
}
public List<EpmOrtItem> getAllOrtItems(EpmOrtIndicator ortIndicator){
if(ortIndicator != null){
return find("from EpmOrtItem d where d.companyId = ? and d.ortIndicator = ?",new Object[]{ContextUtils.getCompanyId(),ortIndicator});
}else{
return find("from EpmOrtItem d where d.companyId = ?",new Object[]{ContextUtils.getCompanyId()});
}
}
public List<EpmOrtItem> getOrtItem(String itemName) {
return find("from EpmOrtItem d where d.itemName = ?",new Object[]{itemName});
}
public EpmOrtItem getOrtItemByItemName(String itemName) {
String hql = "from EpmOrtItem d where d.itemName = ?";
List<EpmOrtItem> ortItems = this.find(hql,itemName);
if(ortItems.size()>0){
return ortItems.get(0);
}else{
return null;
}
}
}
|
C++
|
UHC
| 1,279
| 2.515625
| 3
|
[] |
no_license
|
#include<stdio.h>
#define Max 21
typedef long long int ll;
ll fact[Max], K;
int N,op, ans[Max], visit[Max];
void init() {
for (int i = 0; i < Max; i++) {
ans[i] = 0;
visit[i] = 0;
}
fact[0] = 1;
for (int i = 1; i < Max; i++)
fact[i] = fact[i - 1] * i;
}
int main() {
init();
scanf("%d", &N);
scanf("%d", &op);
if (op == 1) {//k° Ž
scanf("%lld", &K);
int st = N - 1;
int now;
for (int i = 1; i <= N; i++) {
int cnt = 1;
for (int j = 1; j <= N; j++) {
if (visit[j] == 1)continue;
if (K <= fact[st] * cnt) {
ans[i] = j;
K -= (cnt - 1)*fact[st];
st--;
visit[j] = 1;
break;
}
else cnt++;
}
if (K == 0) {
if (ans[i] != 0)now = i + 1;
else now = i;
break;
}
}
for (int i = N; i >= 1; i--) {
if (visit[i] == 0)ans[now++] = i;
}
for (int i = 1; i <= N; i++)
printf("%d ",ans[i]);
}
else if (op == 2) {//־ ° ΰ
for (int i = 1; i <= N; i++) {
scanf("%d", &ans[i]);
}
K = 0;
for (int i = 1; i <= N; i++) {
int cnt = 0;
visit[ans[i]] = 1;
for (int j = 1; j <= N; j++) {
if (j == ans[i])break;
if (visit[j] == 1)continue;
cnt++;
}
K += ((ll)cnt)*fact[N - i];
}
K++;
printf("%lld", K);
}
}
|
Python
|
UTF-8
| 5,758
| 3.171875
| 3
|
[] |
no_license
|
from __future__ import division
import random
class Perceptron:
def __init__(self, learningRate, epoch, randomInit=True):
# There are 124 features in the test and training data.
self.FEATURE_COUNT = 124
random.seed(124)
# Should the weight vector and bias be randomly initalizied.
if randomInit:
self.bias = random.uniform(-1,1)
self.weightVector = [random.uniform(-1,1) for x in range(self.FEATURE_COUNT)]
else:
self.weightVector = [0 for x in range(self.FEATURE_COUNT)]
self.bias = 0
self.learningRate = learningRate
self.mistakes = 0
self.correctClassifications = 0
self.trainingSpace = 0
self.testSpace = 0
self.margin = 0
self.epoch = epoch
self.shuffle = True
def readFile(self, path):
'Takes in a file path and returns a list of examples'
examples = []
with open(path) as file:
for line in file:
line = line.strip().split(' ')
featureVector = [0 for x in range(self.FEATURE_COUNT)]
label = int(line[0])
for feature in line[1:]:
colonIndex = feature.index(':')
index = int(feature[:colonIndex])
value = int(feature[colonIndex + 1:])
featureVector[index] = value
examples.append((label, featureVector))
return examples
def sign(self, value):
'Returns 1 if value is positive and -1 otherwise.'
if value >= 0:
return 1
else:
return -1
def getTestAccuracy(self):
'Returns the percent of correctly classified examples when testing.'
if self.testSpace == 0:
return 0
return round(((self.correctClassifications/self.testSpace)*100),2)
def getTrainingAccuracy(self):
'Returns the percent of updates when training.'
if self.trainingSpace == 0:
return 0
return round(((self.mistakes/(self.trainingSpace * self.epoch))*100),2)
def test(self, path):
'Takes in a path and runs all the examples it contains through the current Perceptron.'
self.correctClassifications = 0
examples = self.readFile(path)
self.testSpace = len(examples)
for example in examples:
label, featureVector = example
vectorSum = self.bias
for index in range(self.FEATURE_COUNT):
vectorSum += self.weightVector[index] * featureVector[index]
if self.sign(vectorSum) == label:
self.correctClassifications += 1
def marginTrain(self, path):
'Trains a margin Perceptron. The weight vector is stored in self.weightVector.'
self.mistakes = 0
examples = self.readFile(path)
self.trainingSpace = len(examples)
for _ in range(self.epoch):
for example in examples:
label, featureVector = example
vectorSum = self.bias
for index in range(self.FEATURE_COUNT):
vectorSum += self.weightVector[index] * featureVector[index]
if label * (vectorSum) < self.margin:
self.mistakes += 1
for index in range(self.FEATURE_COUNT):
self.weightVector[index] += self.learningRate * (label * featureVector[index])
random.shuffle(examples)
def getAggressiveLearningRate(self, label, vectorSum, featureVector):
'Returns the learning rate for aggressive Perceptron with margin.'
learningRate = self.margin - (label * vectorSum)
denominator = 1
for index in range(self.FEATURE_COUNT):
denominator += featureVector[index] * featureVector[index]
learningRate = learningRate / denominator
return learningRate
def aggressiveMarginTrain(self, path):
'Trains a aggressive Perceptron with margin. The weight vector is stored in self.weightVector.'
self.mistakes = 0
examples = self.readFile(path)
self.trainingSpace = len(examples)
for _ in range(self.epoch):
for example in examples:
label, featureVector = example
vectorSum = self.bias
for index in range(self.FEATURE_COUNT):
vectorSum += self.weightVector[index] * featureVector[index]
if label * (vectorSum) < self.margin:
self.mistakes += 1
aggressiveLearningRate = self.getAggressiveLearningRate(label, vectorSum, featureVector)
for index in range(self.FEATURE_COUNT):
self.weightVector[index] += aggressiveLearningRate * (label * featureVector[index])
if self.shuffle:
random.shuffle(examples)
def classicTrain(self, path):
'Trains a classic Perceptron. The weight vector is stored in self.weightVector.'
self.mistakes = 0
examples = self.readFile(path)
self.trainingSpace = len(examples)
for _ in range(self.epoch):
for example in examples:
label, featureVector = example
vectorSum = self.bias
for index in range(self.FEATURE_COUNT):
vectorSum += self.weightVector[index] * featureVector[index]
if (label * vectorSum) <= 0:
self.mistakes += 1
for index in range(self.FEATURE_COUNT):
self.weightVector[index] += self.learningRate * (label * featureVector[index])
random.shuffle(examples)
|
Ruby
|
UTF-8
| 1,213
| 2.953125
| 3
|
[] |
no_license
|
class Assignment
extend ClassModule
include InstanceModule
attr_accessor :general_info, :github_link, :co_workers
attr_reader :id
def initialize(options={})
@id = options["id"]
@general_info = options["general_info"]
@github_link = options["github_link"]
@co_workers = options["co_workers"]
end
# - Updates the row new (or same) values
def save
CONNECTION.execute("UPDATE assignments SET general_info = '#{self.general_info}', github_link = '#{self.github_link}', co_workers = '#{self.co_workers}' WHERE id = #{self.id};")
end
# - Deletes row from table
def delete
CONNECTION.execute("DELETE FROM assignments WHERE id = #{self.id};")
end
# - Adds values for the object into a new row in the database
def add_to_database
CONNECTION.execute("INSERT INTO assignments (general_info, github_link, co_workers) VALUES ('#{self.general_info}', '#{self.github_link}', '#{self.co_workers}');")
@id = CONNECTION.last_insert_row_id
return self
end
def object_as_hash
hash = {"id" => self.id, "general_info" => self.general_info, "github_link" => self.github_link, "co_workers" => self.co_workers}
return hash
end
end
|
C++
|
UTF-8
| 1,840
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
/*
* Copyright © 2018 AperLambda <aperlambda@gmail.com>
*
* This file is part of kimiko++.
*
* Licensed under the MIT license. For more information,
* see the LICENSE file.
*/
#ifndef KIMIKO_MANAGER_H
#define KIMIKO_MANAGER_H
#include "command.h"
#include <optional>
namespace kimiko
{
/*!
* CommandManager.
*
* Manages command registration and detection.
* @tparam S The typename of the sender.
* @version 1.0.0
* @since 1.0.0
*/
template<class S>
class CommandManager
{
protected:
std::vector<std::shared_ptr<Command<S>>> commands;
public:
/*!
* Registers the specified command.
* @param command The command to register.
*/
virtual void register_command(std::shared_ptr<Command<S>> command)
{
if (has_command(command->get_identifier()))
return;
commands.push_back(command);
}
/*!
* Checks whether the command is registered or not.
* @param identifier The identifier of the command.
* @return True if the command is registered, else false.
*/
virtual bool has_command(const lambdacommon::ResourceName &identifier) const
{
for (const std::shared_ptr<Command<S>> &cmd : commands)
if (cmd->get_identifier() == identifier)
return true;
return false;
}
virtual std::optional<std::shared_ptr<Command<S>>>
get_command(const lambdacommon::ResourceName &identifier) const
{
for (const std::shared_ptr<Command<S>> &cmd : commands)
if (cmd->get_identifier() == identifier)
return {cmd};
return std::nullopt;
}
/*!
* Gets all of the registered commands.
* @return The registered commands.
*/
const std::vector<std::shared_ptr<Command<S>>> &get_commands() const
{
return commands;
}
/*!
* Removes all of the register commands.
*/
virtual void clear()
{
commands.clear();
}
};
}
#endif //KIMIKO_MANAGER_H
|
Markdown
|
UTF-8
| 2,668
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
---
pageClass: "rule-details"
sidebarDepth: 0
title: "yml/no-irregular-whitespace"
description: "disallow irregular whitespace"
since: "v0.1.0"
---
# yml/no-irregular-whitespace
> disallow irregular whitespace
- :gear: This rule is included in `"plugin:yml/recommended"` and `"plugin:yml/standard"`.
## :book: Rule Details
`yml/no-irregular-whitespace` rule is aimed at catching invalid whitespace that is not a normal tab and space. Some of these characters may cause issues in YAML parsers and others will be a debugging issue to spot.
`yml/no-irregular-whitespace` rule is the similar rule as core [no-irregular-whitespace] rule but it applies to the source code in YAML.
<eslint-code-block>
<!-- eslint-skip -->
```yaml
# eslint yml/no-irregular-whitespace: 'error'
# ✓ GOOD
a: b
# ✗ BAD
c: d
# ^ LINE TABULATION (U+000B)
```
</eslint-code-block>
## :wrench: Options
```yaml
yml/no-irregular-whitespace:
- error
- skipQuotedScalars: true
skipComments: false
```
- `skipQuotedScalars` ... if `true`, allows any whitespace characters in quoted scalars. default `true`
- `skipComments` ... if `true`, allows any whitespace characters in comments. default `false`
### `"skipQuotedScalars": true` (default)
<eslint-code-block>
<!-- eslint-skip -->
```yml
# eslint yml/no-irregular-whitespace: [error, {skipQuotedScalars: true}]
# ✓ GOOD
- 'foo'
# ^ LINE TABULATION (U+000B)
- "bar"
# ^ LINE TABULATION (U+000B)
```
</eslint-code-block>
### `"skipQuotedScalars": false`
<eslint-code-block>
<!-- eslint-skip -->
```yml
# eslint yml/no-irregular-whitespace: [error, {skipQuotedScalars: false}]
# ✗ BAD
- 'foo'
# ^ LINE TABULATION (U+000B)
- "bar"
# ^ LINE TABULATION (U+000B)
```
</eslint-code-block>
### `"skipComments": true`
<eslint-code-block>
<!-- eslint-skip -->
```yml
# eslint yml/no-irregular-whitespace: [error, {skipComments: true}]
# ✓ GOOD
# []< LINE TABULATION (U+000B)
```
</eslint-code-block>
## :couple: Related rules
- [no-irregular-whitespace]
[no-irregular-whitespace]: https://eslint.org/docs/rules/no-irregular-whitespace
## :rocket: Version
This rule was introduced in eslint-plugin-yml v0.1.0
## :mag: Implementation
- [Rule source](https://github.com/ota-meshi/eslint-plugin-yml/blob/master/src/rules/no-irregular-whitespace.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-yml/blob/master/tests/src/rules/no-irregular-whitespace.ts)
- [Test fixture sources](https://github.com/ota-meshi/eslint-plugin-yml/tree/master/tests/fixtures/rules/no-irregular-whitespace)
<sup>Taken with ❤️ [from ESLint core](https://eslint.org/docs/rules/no-irregular-whitespace)</sup>
|
Markdown
|
UTF-8
| 584
| 2.53125
| 3
|
[] |
no_license
|
# Pneumatic
I find myself trying to store links often that I want to share with others at a later time. This app easily stores the links for later retrieval.

## Tubes and Capsules
A tube is a queue that stores your individual links (capsules). Create a tube that is used to send to one person or for one purpose and fill it up with as many capsules as you need to. The capsules are stored in a FIFO queue (although you can copy and delete from anywhere).
## Todo
* Add user accounts
* Finish implementing clipboard.js
* Mobile friendly
* YouTube previews
|
Python
|
UTF-8
| 1,856
| 3.109375
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# Big Data Assignment 1 - Task5
# Jungwoo Han (jh5990@nyu.edu)
from operator import itemgetter
import sys
current_registration_state = None
registration_state = None
current_plate_id = None
plate_id = None
count = 0
max_count = 0
max_reg_state = None
max_plate_id = None
# input comes from STDIN
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
if not line:
continue
if '\t' not in line:
continue
# key = registration_state, plate_id
# value = count
# parse the input we got from mapper.py
key, value = line.split('\t', 1)
registration_state, plate_id = key.split(",")
registration_state = registration_state.upper()
plate_id = plate_id.upper()
# If we were previously working on this person...
if ((current_registration_state == registration_state) and \
(current_plate_id == plate_id)):
count = count + 1
# If this is a new registration_state...
else:
# But not a first one...
if current_registration_state:
# update the maximum violation data if applicable
if count > max_count:
max_count = count
max_reg_state = current_registration_state
max_plate_id = current_plate_id
# reset data to current ones
count = 1
current_registration_state = registration_state
current_plate_id = plate_id
# output for the last registration_state
if ((current_registration_state == registration_state) and \
(current_plate_id == plate_id)):
if count > max_count:
max_count = count
max_reg_state = current_registration_state
max_plate_id = current_plate_id
# print the key-value pair with maximum violation count
print('%s, %s\t%d'%(max_reg_state, max_plate_id, max_count))
|
C
|
UTF-8
| 5,994
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
#include "../include/penv.h"
#include "../include/pbound.h"
#include "../include/ptile.h"
#include <stdio.h>
int addsub_index(long long lhs_lattice, long long rhs_lattice){
//matrix points are generated by shifting away the ulp status.
int lpoint1 = (lhs_lattice >> 1);
int lpoint2 = (rhs_lattice >> 1);
//shift the left value index by the number of lattice bits.
return (lpoint1 << (PENV->latticebits - 1)) + lpoint2;
}
//addsub index when we have to consider moving between tables.
int table_addsub_index(int table, long long lhs_lattice, long long rhs_lattice){
int lpoint1 = (lhs_lattice >> 1);
int lpoint2 = (rhs_lattice >> 1);
int tablewidth = (1 << (PENV->latticebits - 1));
return table * tablewidth * tablewidth + (lpoint1 * tablewidth) + lpoint2;
}
static PTile exact_arithmetic_addition_crossed(__dc_tile *outer, __dc_tile *inner){
int table = outer->epoch + inner->epoch;
unsigned long long old_lattice = outer->lattice;
if (table < PENV->table_counts[__ADD_CROSSED_TABLE]){
outer->lattice = (PENV->tables[__ADD_CROSSED_TABLE])[table_addsub_index(table, outer->lattice, inner->lattice)];
outer->epoch += (outer->lattice < old_lattice) ? 1 : 0;
return tile_synth(outer);
} else {
return tile_synth(dc_lvup(outer));
}
}
static PTile exact_arithmetic_addition_inverted(__dc_tile *outer, __dc_tile *inner){
int table = inner->epoch - outer->epoch;
int index = table_addsub_index(table, outer->lattice, inner->lattice);
if (table < PENV->table_counts[__ADD_INVERTED_TABLE]) {
outer->lattice = (PENV->tables[__ADD_INVERTED_TABLE])[index];
outer->epoch -= (outer->lattice > inner->lattice) ? 1 : 0;
} else if (outer->lattice != 0) {
return tile_synth(dc_lvdn(outer));
} else {
outer->epoch -= 1;
outer->lattice = (1 << PENV->latticebits) - 1;
}
if (outer->epoch < 0){
outer->inverted = false;
outer->epoch = 0;
if (table < PENV->table_counts[__ADD_INVERTED_TABLE]) {
outer->lattice = (PENV->tables[__INVERTED_ADD_INVERTED_TABLE])[index];
} else {
outer->lattice = 1;
}
}
return tile_synth(outer);
}
static PTile exact_arithmetic_addition_uninverted(__dc_tile *outer, __dc_tile *inner){
int table = outer->epoch - inner->epoch;
if (table < PENV->table_counts[__ADD_TABLE]){
outer->lattice = (PENV->tables[__ADD_TABLE])[table_addsub_index(table, outer->lattice, inner->lattice)];
outer->epoch += (outer->lattice < inner->lattice) ? 1 : 0;
return tile_synth(outer);
} else {
return tile_synth(dc_lvup(outer));
}
}
PTile dc_arithmetic_addition(__dc_tile *outer, __dc_tile *inner){
//swap the order of the two terms to make sure that the outer float appears
//first.
if ((outer->inverted) ^ (inner->inverted)) {
return exact_arithmetic_addition_crossed(outer, inner);
} else if (outer->inverted) {
return exact_arithmetic_addition_inverted(outer, inner);
} else {
return exact_arithmetic_addition_uninverted(outer, inner);
}
}
static bool are_inverses(PTile lhs, PTile rhs){
return tile_additiveinverse(lhs) == rhs;
}
static PTile tile_exact_add(PTile lhs, PTile rhs){
//redo the checks on this in case we've been passed from inexact_add.
if (is_tile_inf(lhs)) {return __inf;}
if (is_tile_inf(rhs)) {return __inf;}
if (is_tile_zero(lhs)) {return rhs;}
if (is_tile_zero(rhs)) {return lhs;}
if (are_inverses(lhs, rhs)) {return __zero;}
//order lhs vs rhs into inner/outer.
bool orderswap = __s(tile_abs(lhs)) < __s(tile_abs(rhs));
DECOMPOSE(rhs)
DECOMPOSE(lhs)
__dc_tile *outer = orderswap ? &rhs_dc : &lhs_dc;
__dc_tile *inner = orderswap ? &lhs_dc : &rhs_dc;
if (outer->negative ^ inner->negative){
return dc_arithmetic_subtraction(outer, inner);
} else {
return dc_arithmetic_addition(outer, inner);
}
}
static PTile inexact_add(PTile lhs, PTile rhs, bool upper){
if (upper){
return lower_ulp(tile_exact_add(lub(lhs), lub(rhs)));
} else {
return upper_ulp(tile_exact_add(glb(lhs), glb(rhs)));
}
}
PTile tile_add(PTile lhs, PTile rhs, bool upper){
if (is_tile_inf(lhs)) {return __inf;}
if (is_tile_inf(rhs)) {return __inf;}
if (is_tile_zero(lhs)) {return rhs;}
if (is_tile_zero(rhs)) {return lhs;}
if (is_tile_exact(lhs) && is_tile_exact(rhs)) {
return tile_exact_add(lhs, rhs);
} else {
return inexact_add(lhs, rhs, upper);
}
}
void add(PBound *dest, const PBound *lhs, const PBound *rhs){
/*first handle all the corner cases*/
if (isempty(lhs) || isempty(rhs)) {set_empty(dest); return;}
if (isallpreals(lhs) || isallpreals(rhs)) {set_allreals(dest); return;}
if (issingle(lhs) && issingle(rhs)) {
//TODO: contemplate adding an exactitude check here.
dest->state = STDBOUND;
dest->lower = tile_add(lhs->lower, rhs->lower, false);
dest->upper = tile_add(lhs->lower, rhs->lower, true);
collapseifsingle(dest);
return;
}
//assign proxy values because "single" doesn't have a meaningful upper value.
PTile lhs_upper_proxy = issingle(lhs) ? lhs->lower : lhs->upper;
PTile rhs_upper_proxy = issingle(rhs) ? rhs->lower : rhs->upper;
//NB: consider going directly to "single_add" with a double single check.
//go ahead and do both sides of the bound calculation. Use a temporary variable.
dest->state = STDBOUND;
dest->lower = pf_add(lhs->lower, rhs->lower, false);
dest->upper = pf_add(lhs_upper_proxy, rhs_upper_proxy, true);
if (roundsinf(lhs) || roundsinf(rhs)){
// let's make sure our result still rounds inf, this is a property which is
// invariant under addition. Losing this property suggests that the answer
// should be recast as "allreals." While we're at it, check to see if the
// answer ends now "touch", which makes them "allreals".
if (__s(dest->lower) <= __s(dest->upper)) {
set_allreals(dest);
} else if (next(dest->upper) == dest->lower) {
set_allreals(dest);
}
}
collapseifsingle(dest);
}
|
PHP
|
UTF-8
| 728
| 2.625
| 3
|
[] |
no_license
|
<?php
if (!isset($_SESSION['id'])) {
if (isset($_COOKIE['user']) && isset($_COOKIE['hashPass'])) { // s'il y a des cookies de session, on vérifie qu'ils correspondent à un des users, et on ouvre la session
$req = $bdd->prepare('SELECT id FROM users WHERE user = :user AND hashPass = :hashPass');
$req->execute(array( // Vérification des cookies de connexion
'user' => $_COOKIE['user'],
'hashPass' => $_COOKIE['hashPass']));
$resultat = $req->fetch();
if ($resultat) {
$_SESSION['id'] = $resultat['id'];
$_SESSION['user']= $_COOKIE['user'];
}
$req->closeCursor();
}
else {
require_once 'define CONSTANT domain.php';
header ('Location: '. DOMAIN .'/Organiznotes/index.php');
exit;
}
}
?>
|
Markdown
|
UTF-8
| 10,885
| 3.484375
| 3
|
[] |
no_license
|
## stats包
`scipy`计算包提供了[scipy.stats](https://docs.scipy.org/doc/scipy/reference/stats.html#module-scipy.stats)子模块来支持与**分布**和**概率**相关的计算.
`stats`子包中包含了几乎所有可能见到的**连续分布**和**离散分布**类型. 而对于所有的连续分布有着同样的方法来进行操作, 离散部分同理, 只是部分函数与连续的有区别.
因此在使用时, 需要首先选择一种分布, 然后使用这个分布中的某些方法来达成目的.
首先了解**连续分布**和**离散分布**共有的一些方法.
## 分布的可用方法
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pyplot import rcParams
```
```python
rcParams["figure.figsize"] = 15, 6
```
这里借助连续的**[正态分布](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm)**, 离散的**[二项分布](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binom.html#scipy.stats.binom)**, 统计学三大分布其中的连续的**[卡方分布](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2.html#scipy.stats.chi2)**来进行说明.
```python
from scipy.stats import norm, binom, chi2
```
### 参数
对于每种分布, 都有其自己的参数, 不同的参数对应着不同的分布. 在`scipy.stats`中, 最常见的参数为**loc**和**scale**, 无论在连续还是离散分布中.
这两个参数顾名思义, 分别代表着:
- `loc`: 位置, 在很多分布中代表**均值**, **期望**.
- `scale`: 缩放, 在很多分布中代表**标准差**的意思.
如果分布是与均值和标准差有关, 即这个分布中的参数包含这两者, 就使用这两者定义即可. 例如, **正态分布**, 即`norm`, 就可以完全只用这两个参数定义. 我们定义一个标准正态分布:
```python
x = np.linspace(-0.99, 0.99, 100)
```
```python
t = plt.plot(norm.pdf(x, loc=0, scale=1))
```

有的分布, 例如**卡方分布**, 需要使用额外的参数, 对于卡方分布, 需要使用**自由度**参数.
**备注**, 与本章目的无关, 对于卡方分布, 往往使用其*标准*分布, 它也可以像正态分布一样, 有位置的平移和峰度的区别. 如果使用`loc`和`scale`, `chi.pdf(x, df, loc, scale)`等价于`chi.pdf(y, df) / scale`, 其中`y = (x - loc) / scale`.
```python
df = 7
x = np.linspace(chi2.ppf(0.01, df), chi2.ppf(0.99, df), 100)
t = plt.plot(norm.pdf(x, df))
```

有的分布, 完全与这两个参数无关, 例如常见的**二项分布**. 它需要的是`n`, `p`两个参数表示次数和单次概率. 这里我们模型投掷20次硬币的分布情况.
```python
n, p = 20, 0.5
x = np.arange(binom.ppf(0.01, n, p), binom.ppf(0.99, n, p))
t = plt.plot(binom.pmf(x, n, p))
```

### 统计函数
对于连续和离散分布, 有着共有的一些常用的方法.
#### stats
`stats(*args, moments="mv")`
给出分布的统计量. 可以给出的统计量有:
- `m`: 均值, mean
- `v`: 方差, variance
- `s`: 偏度, skew
- `k`: 峰度, kurtosis
使用`moments`函数指定.
```python
# 正态分布
norm.stats(loc=1, scale=3, moments="mvsk")
```
(array(1.), array(9.), array(0.), array(0.))
```python
# 卡方分布
chi2.stats(df=10, moments="mvsk")
```
(array(10.), array(20.), array(0.89442719), array(1.2))
#### cdf
- `cdf(x, *args)` 连续
- `cdf(k, *args)` 离散
**Cumulative distribution function**, **累积分布函数**. 返回给定的`x`(连续)或`k`离散坐标值对应的累计概率值.
```python
# 正态分布
x = np.linspace(norm.ppf(0.01), norm.ppf(0.99), 20)
x, norm.cdf(x)
```
(array([-2.32634787, -2.08146915, -1.83659043, -1.5917117 , -1.34683298,
-1.10195426, -0.85707553, -0.61219681, -0.36731809, -0.12243936,
0.12243936, 0.36731809, 0.61219681, 0.85707553, 1.10195426,
1.34683298, 1.5917117 , 1.83659043, 2.08146915, 2.32634787]),
array([0.01 , 0.01869549, 0.03313519, 0.05572475, 0.08901702,
0.13524078, 0.19570157, 0.27020378, 0.35669088, 0.45127553,
0.54872447, 0.64330912, 0.72979622, 0.80429843, 0.86475922,
0.91098298, 0.94427525, 0.96686481, 0.98130451, 0.99 ]))
```python
# 二项分布
n, p = 20, 0.5
x = np.arange(binom.ppf(0.01, n, p), binom.ppf(0.99, n, p))
x, binom.cdf(x, n, p)
```
(array([ 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.]),
array([0.02069473, 0.05765915, 0.13158798, 0.25172234, 0.41190147,
0.58809853, 0.74827766, 0.86841202, 0.94234085, 0.97930527]))
#### sf
- `cdf(x, *args)` 连续
- `cdf(k, *args)` 离散
**Survival function**, 剩余密度的累计, 也可以定义为`1 - cdf`
```python
# 正态分布
x = np.linspace(norm.ppf(0.01), norm.ppf(0.99), 20)
x, norm.sf(x)
```
(array([-2.32634787, -2.08146915, -1.83659043, -1.5917117 , -1.34683298,
-1.10195426, -0.85707553, -0.61219681, -0.36731809, -0.12243936,
0.12243936, 0.36731809, 0.61219681, 0.85707553, 1.10195426,
1.34683298, 1.5917117 , 1.83659043, 2.08146915, 2.32634787]),
array([0.99 , 0.98130451, 0.96686481, 0.94427525, 0.91098298,
0.86475922, 0.80429843, 0.72979622, 0.64330912, 0.54872447,
0.45127553, 0.35669088, 0.27020378, 0.19570157, 0.13524078,
0.08901702, 0.05572475, 0.03313519, 0.01869549, 0.01 ]))
```python
# 二项分布
n, p = 20, 0.5
x = np.arange(binom.ppf(0.01, n, p), binom.ppf(0.99, n, p))
x, binom.sf(x, n, p)
```
(array([ 5., 6., 7., 8., 9., 10., 11., 12., 13., 14.]),
array([0.97930527, 0.94234085, 0.86841202, 0.74827766, 0.58809853,
0.41190147, 0.25172234, 0.13158798, 0.05765915, 0.02069473]))
#### ppf
- `ppf(q, *args)`
**Percent point function**, **百分位函数**. 给定一个百分数, 返回这个分布累计密度为这个数时对应的随机变量的值(即**百分位**).
`cdf`的反函数.
```python
# 正态分布
x = np.linspace(0.01, 0.99, 20)
x, norm.ppf(x)
```
(array([0.01 , 0.06157895, 0.11315789, 0.16473684, 0.21631579,
0.26789474, 0.31947368, 0.37105263, 0.42263158, 0.47421053,
0.52578947, 0.57736842, 0.62894737, 0.68052632, 0.73210526,
0.78368421, 0.83526316, 0.88684211, 0.93842105, 0.99 ]),
array([-2.32634787, -1.54165318, -1.20990385, -0.97517455, -0.78469643,
-0.61919262, -0.46917106, -0.32906671, -0.19516579, -0.06468971,
0.06468971, 0.19516579, 0.32906671, 0.46917106, 0.61919262,
0.78469643, 0.97517455, 1.20990385, 1.54165318, 2.32634787]))
#### mean, median, var, std
- `mean(*args)`
- `median(*args)`
- `var(*args)`
- `std(*args)`
均值, 中位数, 方差, 标准差. 选定分布, 传入分布的参数, 得到对应的统计量.
```python
# 标准正态分布
norm.mean(), norm.median(), norm.var(10), norm.std(10)
```
(0.0, 0.0, 1.0, 1.0)
```python
# 二项分布
binom.mean(10, 0.5), binom.median(10, 0.5), binom.var(10, 0.5), binom.std(10, 0.5)
```
(5.0, 5.0, 2.5, 1.5811388300841898)
#### expect
- 正态分布
- `expect(func, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)`
- 二项分布
- `expect(func, args=(n, p), loc=0, lb=None, ub=None, conditional=False)`
求**函数的期望**. 函数是关于该**随机变量**的**单变量函数**. 求在自变量为指定的分布情况下, 对应函数的期望值.
其中**分布的参数**由`args`, `loc`, `scale`参数共同指定. 如果像正态分布一样, 只使用到`loc`和`scale`, `args`传空`tuple`即可.
```python
def x_plus_5(x):
return x + 5
```
```python
# 标准正态分布
norm.expect(x_plus_5, args=(), loc=0, scale=1)
```
4.999999999999998
```python
# 二项分布
binom.expect(x_plus_5, args=(10, 0.5))
```
10.00000000000001
### 统计推断方法
#### interval
- `interval(alpha, *args)`
给定**置信水平**$$\alpha$$, 求出对应的区间范围. 如对于$$\alpha=0.05$$的双向$$z$$检验, 使用的就是**标准正态分布**, 对应的区间为:
```python
alpha = 0.05
norm.interval((2 - alpha) / 2)
```
(-2.241402727604945, 2.241402727604947)
### 采样
#### rvs
- `rvs(*args, size=1, random_state=None)`
选定分布类型和分布参数, 就可以进行采样了. `size`参数指定采样样本的数量, `random_state`可以指定随机种子.
```python
# 标准正态分布
norm.rvs(size=20)
```
array([-0.07518554, 0.20304797, -1.14698151, 1.21465788, -0.26719107,
1.09448395, -0.75106881, -1.38107981, 0.97681162, 0.02723926,
0.03163507, 1.41163216, 0.35405607, 0.7989187 , 0.86508305,
-0.60533099, -0.7849912 , -0.73408228, 1.23046816, 0.4392824 ])
```python
# 二项分布
binom.rvs(20, 0.5, size=20)
```
array([11, 10, 10, 13, 7, 11, 9, 7, 13, 11, 7, 7, 8, 7, 13, 13, 14,
10, 11, 7])
### 拟合
#### fit
- `fit(data, *args)`
使用数据拟合得到分布的参数. 假设这些数据来自于这种类型分布的抽样, 现在要推算出分布对应的参数.
也可以指定参数, 这里指定的参数作为**先验分布**来使用.
推算参数的方法为: **Maximum Likelihood Estimation, MLE**, **最大似然法**.
只有部分分布支持拟合(原因: 参数的可导性). 以正态分布为例子进行说明.
首先使用标准正态分布, 抽样生成数据, 再对数据进行拟合.
```python
data = norm.rvs(size=100)
norm.fit(data)
```
(0.0022467502682304197, 0.9544937497006565)
使用更大的数据量, 拟合更准确.
```python
data = norm.rvs(size=100000)
norm.fit(data)
```
(0.0013160936919521882, 1.0035769090418196)
在大样本量的情况下, 先验参数的选择并不重要.
```python
data = norm.rvs(size=100000)
norm.fit(data, loc=2, scale=2)
```
(-0.006140183965886018, 0.9979153641748688)
## 连续分布和离散分布不同的方法
### pdf和pmf
- `pdf`: **Probability density function**, 连续随机变量的**概率密度函数**
- `pmf`: **Probability mass function**, 离散随机变量的**概率质量函数**
两者的意义是一样的, 只是对应连续和离散的问题.
- `pdf(x, *args)`
- `pmf(k, *args)`
即给定随机变量的一个值, 返回这个值对应的概率密度(连续)或概率(离散).
```python
# 标准正态分布
norm.pdf(0)
```
0.3989422804014327
```python
# 二项分布
binom.pmf(8, n=10, p=0.5)
```
0.04394531249999999
|
Java
|
UTF-8
| 7,714
| 2.625
| 3
|
[] |
no_license
|
package com.kaylerrenslow.mysqlDatabaseTool.fx.db;
import com.kaylerrenslow.mysqlDatabaseTool.database.lib.MysqlQueryResult;
import com.kaylerrenslow.mysqlDatabaseTool.fx.contextMenu.CM_DBTableView;
import com.kaylerrenslow.mysqlDatabaseTool.fx.control.factory.TableRowFactory;
import com.kaylerrenslow.mysqlDatabaseTool.fx.controllers.QueryFXController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
/**
* @author Kayler
* Class that holds a TableView for showing the database's information
* Created on 12/9/15.
*/
public class DBTable implements IDBTableData{
private final TableView<ObservableList> tv;
private final String tableName;
private final QueryFXController qc;
private ContextMenu cm;
/**The table row data that was edited before the last database synchronization*/
private ArrayList<DBTableEdit> rowsEdited = new ArrayList<>();
private String[] columnTypes, columnNames;
/** Creates a DBTable instance with the given Database table name.
* @param tableName name of a table in the database. If null, this DBTable instance won't have a context menu
* @param qc QueryFXController instance
*/
public DBTable(String tableName, QueryFXController qc) {
this.qc = qc;
this.tv = new TableView<>();
this.tableName = tableName;
if(this.tableName != null){
initializeContextMenu(qc);
}
}
public TableView getTableView(){
return this.tv;
}
private void initializeContextMenu(QueryFXController qc) {
cm = new CM_DBTableView(this, qc);
this.tv.setContextMenu(cm);
}
/**Clears all the entries from the table*/
public void clearTable(){
this.tv.getItems().clear();
}
/**
* Clears the table and then adds the query data to the table.
*/
public void addQueryDataToTable(MysqlQueryResult rs) throws SQLException {
tv.getColumns().clear();
if(rs == null){
return;
}
this.columnNames = rs.getColNames();
this.columnTypes = rs.getColumnTypes();
//add all the table columns
TableColumn tcol;
for (int col = 0; col < rs.getNumColumns(); col++){
tcol = new TableColumn<>(rs.getColNames()[col]);
tcol.setCellValueFactory(new TableRowFactory(col));
tv.getColumns().add(tcol);
}
//object that holds all the row data
ObservableList<ObservableList> allRows = FXCollections.observableArrayList();
addNewRows(rs, allRows);
tv.setItems(allRows);
}
private void addNewRows(MysqlQueryResult rs, ObservableList allRows) throws SQLException {
ObservableList<String> row;
//now add all of the row data
Iterator<String[]> iter = rs.rowIterator();
while(iter.hasNext()){
row = FXCollections.observableArrayList(iter.next());
allRows.add(row);
}
}
/**Get the current selected row index*/
public int getSelectedRowIndex(){
return this.tv.getSelectionModel().getSelectedIndex();
}
/**Get the current selected row data*/
public ObservableList getSelectedRowData(){
return this.tv.getSelectionModel().getSelectedItem();
}
/**Removes the currently selected row. This method will also add the removal to the edits list*/
public void removeSelectedRow() {
if(this.getSelectedRowIndex() > -1){
updateData(DBTableEdit.EditType.DELETION, this.getSelectedRowIndex(), null, getSelectedRowData());
}
}
/**Duplicates the row at index selectedRowIndex and appends it to the bottom of the table. This method will also add the duplicate row into the edits when the duplicate is saved,*/
public ObservableList<String> duplicateRow(int selectedRowIndex) {
if(this.getSelectedRowIndex() == -1){
return null;
}
ObservableList old = this.tv.getItems().get(selectedRowIndex);
ObservableList neww =FXCollections.observableArrayList(new String[old.size()]);
FXCollections.copy(neww, old);
return neww;
// updateData(DBTableEdit.EditType.ADDITION, this.tv.getItems().size(), neww, old);
}
/**Mark a table row's data at index as edited. When database synchronization happens, this edited data will be used to update the database.*/
private void markAsEdited(DBTableEdit.EditType type, int index, ObservableList newData, ObservableList oldData){
DBTableEdit edit = new DBTableEdit(type, index, newData, oldData);
this.rowsEdited.add(edit);
}
@Override
public void clearEdited(){
this.rowsEdited.clear();
}
@Override
public String getTableName() {
return this.tableName;
}
/**
* Creates and returns a new list of data
*/
public ObservableList<String> getNewRowData() {
if (!this.hasColumns()){
throw new IllegalStateException("Can't add an empty row when there isn't any data to add to");
}
String[] data = new String[this.tv.getColumns().size()];
for (int i = 0; i < this.tv.getColumns().size(); i++){
data[i] = "";
}
ObservableList<String> row = FXCollections.observableArrayList();
row.addAll(data);
return row;
}
@Override
public void updateData(DBTableEdit.EditType type, int rowIndex, ObservableList newData, ObservableList oldData) {
if(type == DBTableEdit.EditType.ADDITION){
this.tv.getItems().add(newData);
}else if (type == DBTableEdit.EditType.DELETION){
this.tv.getItems().remove(rowIndex);
}else{
this.tv.getItems().set(rowIndex, newData);
}
if(type == DBTableEdit.EditType.DELETION){
for(int i = 0; i < this.rowsEdited.size(); i++){
if(this.rowsEdited.get(i).rowIndex() > rowIndex){
this.rowsEdited.get(i).decrementRowIndex(1); //since an element is getting removed from the table, the indexes need to be shifted -1 to realign their indexes
}
}
}
this.markAsEdited(type, rowIndex, newData, oldData);
}
/**Undo the edit made to the table*/
public void undoLastEdit() {
if(this.rowsEdited.size() == 0){
return;
}
DBTableEdit edit = this.rowsEdited.get(this.rowsEdited.size() - 1);
if(edit.type() == DBTableEdit.EditType.DELETION){
this.tv.getItems().add(edit.rowIndex(), edit.oldRowData());
}else if(edit.type() == DBTableEdit.EditType.ADDITION){
this.tv.getItems().remove(edit.rowIndex());
}else{
this.tv.getItems().set(edit.rowIndex(), edit.oldRowData());
}
this.rowsEdited.remove(this.rowsEdited.size() - 1);
}
@Override
public ObservableList getData(int rowIndex) {
return this.tv.getItems().get(rowIndex);
}
@Override
public boolean hasColumns() {
return tv.getColumns().size() > 0;
}
@Override
public Iterator<DBTableEdit> iterator(boolean reversed) {
return new EditedDataIterator(this, reversed);
}
@Override
public String[] getColumnTypes(){
return this.columnTypes;
}
@Override
public String[] getColumnNames(){
return this.columnNames;
}
/**Get the number of rows in the table*/
public int getRowSize() {
return this.tv.getItems().size();
}
/**Synchronize this table to the table on the server's database*/
public void synchronizeToDatabase() {
this.qc.synchronizeToDatabase(this);
}
private class EditedDataIterator implements Iterator<DBTableEdit>{
private final DBTable table;
private int cursor = 0;
private final boolean reverse;
public EditedDataIterator(DBTable table, boolean reverse) {
this.table = table;
this.reverse = reverse;
if(reverse){
this.cursor = this.table.rowsEdited.size() - 1;
}
}
@Override
public boolean hasNext() {
if(reverse){
return cursor >= 0;
}
return cursor < table.rowsEdited.size();
}
@Override
public DBTableEdit next() {
if(reverse){
return this.table.rowsEdited.get(cursor--);
}
return this.table.rowsEdited.get(cursor++);
}
}
}
|
C++
|
UTF-8
| 971
| 3.71875
| 4
|
[] |
no_license
|
/*
* 04.cpp
*
* Created on: Dec 13, 2016
* Author: robertwinke
*/
#include <iostream>
#include <string>
#include <map>
using namespace std;
// write a function that takes a string and returns a map
// the map should have the letters of the string as keys and
// it should have integers as values that represents how many times the
// letter appeared int the string
int letterCount(string word, char letter) {
int sum = 0;
for (unsigned int i = 0; i < word.length(); i++) {
if (word[i] == letter) {
sum++;
}
}
return sum;
}
map<char,int> letterCountInString(string word) {
map<char,int> myMap;
for (unsigned int i = 0; i < word.length(); i++) {
myMap[word[i]] = letterCount(word, word[i]);
}
return myMap;
}
int main() {
map<char,int> m;
m = letterCountInString("almaaal");
for (map<char,int>::iterator it = m.begin(); it != m.end(); it++) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
|
C#
|
UTF-8
| 932
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
// Copyright (c) PdfToSvg.NET contributors.
// https://github.com/dmester/pdftosvg.net
// Licensed under the MIT License.
using System;
using System.IO;
using System.Threading.Tasks;
namespace PdfToSvg.Driver
{
internal static class Program
{
public static async Task Main()
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var input = @"M:\Repos\pdftosvg.net\tests\Test-files\rotated-page.pdf";
using (var doc = await PdfDocument.OpenAsync(input))
{
var pageIndex = 0;
foreach (var page in doc.Pages)
{
var svgFileName = Path.GetFileNameWithoutExtension(input) + "-" + pageIndex++ + ".svg";
await page.SaveAsSvgAsync("R:\\" + svgFileName);
}
}
Console.WriteLine("Done! {0}ms", sw.ElapsedMilliseconds);
}
}
}
|
C++
|
UTF-8
| 2,071
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
/*
* test_dispatch.cxx
*
* Created on: 29 Aug 2020
* Author: nirsancho
*/
#include "../dispatch/safe_queue.h"
#include "../dispatch/dispatch_queue.h"
#include <thread>
#include <chrono>
using namespace dispatch;
#define NITEMS 50000
#define TIMEOUT 10
struct Tiktok {
Tiktok(const std::string &label) :
_label(label), _s(std::chrono::steady_clock::now()) {
}
~Tiktok() {
auto ms = elapsed();
printf("%s: %fms\n", _label.c_str(), ms.count() * 1000);
}
//
std::chrono::duration<double> elapsed() {
return (std::chrono::steady_clock::now() - _s);
}
private:
const std::string _label;
const std::chrono::time_point<std::chrono::steady_clock> _s;
};
void test_safe_queue() {
SafeQueue<int> q;
std::thread t1([&q]() {
Tiktok t("t1");
for (int i = 0; i < 2 * NITEMS; i++) {
q.push(2 * i);
}
});
std::thread t2([&q]() {
Tiktok t("t2");
for (int i = 0; i < NITEMS; i++) {
q.push(2 * i + 1);
}
});
std::thread t3([&q]() {
Tiktok t("t3");
int items = 0;
int v;
while (true) {
if (!q.pop(v, TIMEOUT)) {
break;
}
items++;
}
printf("t3 read %d items\n", items);
});
// std::thread t4([&q]() {
// Tiktok t("t4");
// int items = 0;
// int v;
// while (true) {
// if (!q.pop(v, TIMEOUT)) {
// break;
// }
// items++;
// }
// printf("t4 read %d items\n", items);
// });
//
// std::thread t5([&q]() {
// Tiktok t("t5");
// int items = 0;
// int v;
// while (true) {
// if (!q.pop(v, TIMEOUT)) {
// break;
// }
// items++;
// }
// printf("t5 read %d items\n", items);
// });
t1.join();
t2.join();
t3.join();
// t4.join();
// t5.join();
}
void test_dispatch_queue() {
Poller mainpoller;
DisptchQueue bgq;
DisptchQueue mainq;
std::thread bg([&bgq]() {
Poller poller;
bgq.mainLoop(poller);
});
Poller poller;
mainq.dispatch([&bgq, &mainq]() {
int i = bgq.sync<int>([]() {
return 10;
});
bgq.dispatchClose();
mainq.dispatchClose();
});
mainq.mainLoop(poller);
bg.join();
}
int main() {
// test_safe_queue();
test_dispatch_queue();
return 0;
}
|
Python
|
UTF-8
| 5,905
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
from actualizar import *
from impresiones import limpiar, mostrarGanador
from movimientos import moverPzaEnTab, posiblesDestinos, reporMata
from busquedas import jugTienePza, validMov, posDePzaEnTab
def turno(tablero, jugs):
N = 0
hay_presi = False
siguiente = 0
anterior = -1
dblturn = False
first = True
turnos = 0
quitar = False
pza = ''
orig = 0
while True:
aux = N
if anterior == 3:
aux = 0
if hay_presi:
if anterior != presidente:
siguiente = aux
N = presidente
else:
if dblturn:
if not first:
if turnos < 1:
N = presidente
turnos += 1
else:
turnos = 0
first = False
if siguiente == presidente:
siguiente += 1
else:
N = siguiente
else:
dblturn = False
first = True
if siguiente == anterior:
siguiente += 1
N = siguiente
if N > 3:
N = 0
if siguiente > 3:
siguiente = 0
if not jugs[N].jefe or jugs[N].cerrado:
if N == siguiente:
siguiente += 1
N += 1
continue
if N == anterior and (not jugs[N].presi or not dblturn):
N += 1
continue
jug = jugs[N].num
limpiar(tablero,jug,jugs)
while True:
x = 0
y = 0
if not quitar:
pza = pedirPieza()
orig = 0
pza = pza.upper()
ficha = str(jug) + pza
tiene = jugTienePza(jugs[N].piezas, pza)
if not tiene:
print("\t\tUsted no tiene la pieza ",pza,".\n\t\tSolo letras de su color de jugador.\n", sep='')
continue
elif tiene > 1 and not quitar:
orig = especificar(1)
x = int(orig[0])
y = int(orig[1])
if len(tablero[x][y]) == 2:
if tablero[x][y][0] != str(jug):
print("\t\tNo puede mover piezas de otro jugador.\n")
continue
else:
print("\t\tEn la casilla",orig,"no se encuentra ninguna pieza",pza,"\b.\n")
continue
vector = posiblesDestinos(tablero, ficha, orig)
if not vector:
print("\t\tSu pieza",pza,"no tiene ningún movimiento válido.\n")
quitar = False
continue
else:
pos = pedirCasilla(1,ficha[1])
if not validMov(vector,pos):
print("\t\tLa casilla ",pos," no es un destino válido para la pieza ",pza,".\n", sep='')
continue
else:
break
obj = tablero[ int(pos[0]) ][ int(pos[1]) ]
letraObj = ''
if pza == 'R':
tablero = moverPzaEnTab(tablero, ficha, '', pos, orig)
limpiar(tablero,jug,jugs)
arreglo = reporMata(tablero,pos,jug)
if arreglo:
if len(arreglo) == 1:
dest = arreglo[0]
elif len(arreglo) > 1:
while True:
dest = especificar(0)
if not validMov(arreglo,dest):
print("\t\tEn la casilla",dest,"no se encuentra ninguna víctima válida.\n")
continue
else:
break
i = int(dest[0])
j = int(dest[1])
obj = tablero[i][j]
letraObj = obj[1]
tablero[i][j] = '0'
else:
if obj == '':
tablero = moverPzaEnTab(tablero, ficha, '', pos, orig)
elif obj == '0':
tablero = moverPzaEnTab(tablero, ficha, '', pos, orig)
limpiar(tablero,jug,jugs)
while True:
dest = pedirCasilla(0,letraObj)
if dest == '44':
print("\t\tLas fichas muertas no se pueden colocar en la casilla central (44).\n")
continue
elif tablero[int(dest[0])][int(dest[1])] == '':
break
else:
print("\t\tLa ficha muerta debe ser colocada en una casilla vacía.\n")
continue
tablero = moverPzaEnTab(tablero, '0', ficha, dest, pos)
else:
letraObj = obj[1]
if pza == 'D':
tablero = moverPzaEnTab(tablero, ficha, '', pos, orig)
limpiar(tablero,jug,jugs)
while True:
dest = pedirCasilla(1,letraObj)
if tablero[int(dest[0])][int(dest[1])] == '':
if dest == '44':
if letraObj == 'C':
break
else:
print("\t\tSolo las piezas C pueden colocarse en la casilla central (44).\n")
continue
else:
break
else:
print("\t\tLa pieza enemiga",letraObj,"debe ser colocada en una casilla vacía.\n")
continue
tablero = moverPzaEnTab(tablero, obj, ficha, dest, pos)
elif pza == 'A':
tablero = moverPzaEnTab(tablero, ficha, '0', pos, orig)
else:
tablero = moverPzaEnTab(tablero, ficha, '', pos, orig)
limpiar(tablero,jug,jugs)
while True:
dest = pedirCasilla(0,letraObj)
if dest == '44':
print("\t\tLas fichas muertas no se pueden colocar en la casilla central (44).\n")
continue
elif tablero[int(dest[0])][int(dest[1])] == '':
break
else:
print("\t\tLa ficha muerta debe ser colocada en una casilla vacía.\n")
continue
tablero = moverPzaEnTab(tablero, '0', ficha, dest, pos)
if letraObj == 'C' and pza != 'D':
tablero = pasarPiezas(tablero, str(jug), obj[0])
jugs = propiedades(jugs, tablero)
vivos = 0
for jug in jugs:
if jug.jefe:
if not jug.necro and posDePzaEnTab(tablero,str(jug.num) + 'C') != '44' and encerrado(tablero,jug.num):
jug.cerrado = True
else:
vivos += 1
ganador = jug.num
jug.cerrado = False
if vivos == 1:
limpiar(tablero,ganador,jugs)
mostrarGanador(ganador)
break
elif vivos == 2:
dblturn = True
central = tablero[4][4]
if central == '' or central == '0':
hay_presi = False
presidente = -1
elif central[1] == 'C':
for jug in jugs:
if int(central[0]) == jug.num:
hay_presi = True
jug.presi = True
presidente = jug.num -1
break
else:
jug.presi = False
else:
quitar = True
N = central[0]
pza = central[1]
orig = '44'
continue
pza = ''
orig = 0
quitar = False
if hay_presi:
for jug in jugs:
if jug.jefe and jug.cerrado:
pos = posDePzaEnTab(tablero,str(jug.num)+'C')
tablero[int(pos[0])][int(pos[1])] = '0'
tablero = pasarPiezas(tablero, str(presidente + 1), str(jug.num) )
jugs = propiedades(jugs, tablero)
anterior = N
N += 1
|
Java
|
UTF-8
| 3,877
| 3.0625
| 3
|
[] |
no_license
|
package correlationmatrix;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
public class CorrelationMatrix {
public static void main(String[] args) throws IOException {
//Get the data from file
try(FileInputStream inputStream = new FileInputStream("abalone.txt")) {
String data = IOUtils.toString(inputStream);
// Split each line of data and store into array
String[] tokens = data.split("\\R");
// Store each element into a 2d array
String[][] elementsAsString = new String[tokens.length][];
for (int i = 0; i < elementsAsString.length; i++) {
elementsAsString[i] = tokens[i].split(",");
for (int j = 0; j < 9; j++) {
}
}
// Make sure the array contains only numbers
for (int i = 0; i < elementsAsString.length; i++) {
if (elementsAsString[i][0].contentEquals("M")) {
elementsAsString[i][0] = "1.0";
}
else if (elementsAsString[i][0].contentEquals("F")) {
elementsAsString[i][0] = "2.0";
}
else if (elementsAsString[i][0].contentEquals("I")) {
elementsAsString[i][0] = "3.0";
}
}
// convert the strings into double values and store in a 2d array of double numbers
double[][] elements = new double[elementsAsString.length][elementsAsString[0].length];
for (int i = 0; i < elementsAsString.length; i++) {
for (int j = 0; j < elementsAsString[0].length; j++) {
elements[i][j] = Double.parseDouble(elementsAsString[i][j]);
}
}
// Compute and display the correlations matrix
DependenceSubsets ds = new DependenceSubsets(elements, 0.7);
System.out.println("Correlation Matrix:\n");
System.out.print(" x0 x1 x2 x3 x4 x5 x6 x7 x8");
double[][] correlationData = ds.getCorrelationTable();
for (int i = 0; i < correlationData.length; i++) {
System.out.print("\nx" + i + ": ");
for (int j = 0; j < correlationData[0].length; j++) {
if (correlationData[i][j] > 0) {
System.out.print(" " + String.format( "%.2f", Math.round(correlationData[i][j] * 100.0) / 100.0) + " ");
}
else {
System.out.print(String.format( "%.2f", Math.round(correlationData[i][j] * 100.0) / 100.0) + " ");
}
}
}
// Compute and display subsets
System.out.println("\n\nCorrelation subsets:");
int i = 1;
String subsetDisplay = "";
for (Set subset : ds.getSubsets()) {
subsetDisplay = subsetDisplay.concat("subset" + i + ": {");
for (Object o : subset) {
DataVariable x = (DataVariable)o;
subsetDisplay = subsetDisplay.concat("x" + x.getId() + ", ");
}
subsetDisplay = subsetDisplay.substring(0, subsetDisplay.length() - 2);
subsetDisplay += "}\n";
i++;
}
System.out.println(subsetDisplay);
}
catch (FileNotFoundException ex) {
Logger.getLogger(CorrelationMatrix.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
C++
|
UTF-8
| 465
| 3.015625
| 3
|
[] |
no_license
|
// xy.cpp: definisce il punto di ingresso dell'applicazione console.
//
#include "stdafx.h"
#include<stdio.h>
int main()
{
int fine;
int x;
int y;
int contatore=0;
int risultato=1;
printf("digita un numero e il suo esponenente\n");
scanf_s("%d%d", &x, &y);
while (contatore < y) {
risultato = risultato*x;
contatore = contatore + 1;
}
printf("x^y=%i",risultato);
printf("Digita un numero per finire");
scanf_s("%i", &fine);
return 0;
}
|
JavaScript
|
UTF-8
| 4,436
| 3.40625
| 3
|
[] |
no_license
|
const form = document.querySelector('form');
const firstNameEl = document.querySelector('#first-name')
const lastNameEl = document.querySelector('#last-name')
const emailEl = document.querySelector('#email')
const passwordEl = document.querySelector('#password')
const submit = document.querySelector('.submit')
submit.setAttribute('disabled', "")
// Base Functions
function isRequired(input) {
if (input === ''){
return false
}
else{
return true
}
}
function isInRange(input, min, max) {
if(input.length < min || input.length > max) {
return false
}
else{
return true
}
}
function validName(input) {
let regEx = /[A-Za-z]+/
return regEx.test(input)
}
function validEmail(input) {
let regEx = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
return regEx.test(input);
}
function strongPassword(input) {
let regEx = /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^A-Za-z0-9])(?=.{8,})/;
return regEx.test(input);
}
// Error functions
function createError(element, message) {
const formItem = element.parentElement;
const input = formItem.querySelector('input');
const icon = formItem.querySelector('img');
const errorText = formItem.querySelector('span');
input.classList.add('error');
icon.classList.add('error');
errorText.textContent = message;
}
function removeError(element) {
const formItem = element.parentElement;
const input = formItem.querySelector('input');
const icon = formItem.querySelector('img');
const errorText = formItem.querySelector('span');
input.classList.remove('error')
icon.classList.remove('error')
errorText.textContent = '';
}
// Check Functions
function checkFirstName(){
let valid = false;
const firstName = firstNameEl.value.trim()
if (!isRequired(firstName)){
createError(firstNameEl, 'A First Name is required')
}
else if (!isInRange(firstName, 2, 25)) {
createError(firstNameEl, 'First Name must be between 2 and 25 characters')
}
else if (!validName(firstName)) {
createError(firstNameEl, 'First Name must contain only letters with no whitespace')
}
else{
removeError(firstNameEl);
valid = true;
}
return valid;
}
function checkLastName(){
let valid = false;
const lastName = lastNameEl.value.trim()
if (!isRequired(lastName)) {
createError(lastNameEl, 'A Last Name is required')
}
else if(!isInRange(lastName, 2, 25)){
createError(lastNameEl, 'Last Name must be between 2 and 25 characters')
}
else if(!validName(lastName)){
createError*(lastNameEl, 'Last Name must only contain letters with no whitespace')
}
else{
removeError(lastNameEl);
valid = true;
}
return valid;
}
function checkEmail(){
let valid = false;
const email = emailEl.value.trim()
if(!isRequired(email)){
createError(emailEl, 'An Email Address is required')
}
else if(!validEmail(email)){
createError(emailEl, 'Email Address is not valid')
}
else{
removeError(emailEl);
valid = true;
}
return valid;
}
function checkPassword() {
let valid = false;
const password = passwordEl.value.trim()
if(!isRequired(password)){
createError(passwordEl, 'A Password is required')
}
else if(!strongPassword(password)) {
createError(passwordEl, 'The Password must contain at least one of the following: Uppercase letter, Lowercase letter, Number, and a Special character');
}
else{
removeError(passwordEl);
valid = true;
}
return valid
}
const debounce = (fn, delay = 500) => {
let timeoutId;
return (...args) => {
// cancel the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// setup a new timer
timeoutId = setTimeout(() => {
fn.apply(null, args)
}, delay);
};
};
form.addEventListener('input', debounce(function (e) {
let isFirstNameValid = checkFirstName()
let isLastNameValid = checkLastName()
let isEmailValid = checkEmail()
let isPasswordValid = checkPassword()
let isFormValid = isFirstNameValid & isLastNameValid & isEmailValid & isPasswordValid;
if (isFormValid) {
submit.removeAttribute('disabled')
}
}));
|
JavaScript
|
UTF-8
| 859
| 3.4375
| 3
|
[] |
no_license
|
'use strict';
const a = { name: 'a', discs: [] };
const b = { name: 'b', discs: [] };
const c = { name: 'c', discs: [] };
function newHanoi(num) {
let counter = 0;
for (let i = 0; i < num; i++) {
a.discs.push(num - i);
console.log(a.discs, b.discs, c.discs);
}
const solver = (disc, source, dest, aux) => {
if (disc === 1) {
makeMove(source, dest);
} else {
solver(disc - 1, source, aux, dest);
makeMove(source, dest);
solver(disc - 1, aux, dest, source);
}
};
const makeMove = (source, target) => {
counter++;
console.log(`I will now move from ${source.name} to ${target.name}`);
target.discs.push(source.discs.pop());
console.log('Number of moves:', counter);
};
solver(num, a, c, b);
}
newHanoi(7);
|
Java
|
UTF-8
| 3,587
| 2.796875
| 3
|
[] |
no_license
|
package hibernate.lesson4.dao;
import hibernate.lesson4.entity.Room;
import hibernate.lesson4.exceptions.BadRequestException;
import hibernate.lesson4.exceptions.DBException;
import hibernate.lesson4.utils.Filter;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import java.util.List;
public class RoomDAO extends GenericDAO<Room> {
private static final String ALL_ROOMS = "SELECT * FROM ROOM";
private static final String DELETE_ROOM_BY_ID = "DELETE * FROM ROOM WHERE ID = ?";
private static final String FIND_ROOM_BY_PARAMETERS = "SELECT ROOM.* FROM ROOM " +
"JOIN HOTEL ON ROOM.ID_HOTEL = HOTEL.ID WHERE ROOM.BREAKFAST_INCLUDED = ?" +
" AND ROOM.PETS_ALLOWED = ? ";
// AND ROOM.DATE_AVAILABLE_FROM = COALESCE(?,ROOM.DATE_AVAILABLE_FROM)
@Override
public Room save(Room room) throws DBException {
return super.save(room);
}
@Override
public Room update(Room room) {
return super.update(room);
}
@Override
public void delete(long id) throws BadRequestException {
try( Session session = createSessionFactory().openSession()) {
NativeQuery query = session.createNativeQuery(DELETE_ROOM_BY_ID);
query.addEntity(Room.class);
query.setParameter(1,id);
query.executeUpdate();
}catch (HibernateException e){
System.err.println(e.getMessage());
throw e;
}
}
@Override
public Room findById(Class<Room> c, long id) throws BadRequestException {
return super.findById(c, id);
}
public List<Room> findRoomsByParameters(Filter filter){
try (Session session = createSessionFactory().openSession()) {
String queryString = FIND_ROOM_BY_PARAMETERS;
if (filter.getName() != null) queryString +=" AND HOTEL.HOTEL_NAME = \'"+filter.getName()+"\'";
if (filter.getCountry() != null) queryString +=" AND HOTEL.COUNTRY = \'"+filter.getCountry()+"\'";
if (filter.getCity() != null) queryString +=" AND HOTEL.CITY = \'"+filter.getCity()+"\'";
if (filter.getStreet() != null) queryString +=" AND HOTEL.STREET = \'"+filter.getStreet()+"\'";
if (filter.getNumberOfGuests() != 0) queryString +=" AND ROOM.NUMBER_OF_GUESTS = "+filter.getNumberOfGuests();
if (filter.getPrice() != 0) queryString +=" AND ROOM.PRICE = "+filter.getPrice();
if (filter.getDateAvailableFrom() != null) queryString +=" AND ROOM.DATE_AVAILABLE_FROM= "+filter.getDateAvailableFrom();
NativeQuery query = session.createNativeQuery(queryString);
query.addEntity(Room.class);
query.setParameter(1,filter.getBreakfastIncluded());
query.setParameter(2,filter.getPetsAllowed());
List<Room> resultSet = query.getResultList();
return resultSet;
} catch (HibernateException e) {
System.err.println("No rooms.");
System.err.println(e.getMessage());
throw e;
}
}
public List<Room> getAll() {
try (Session session = createSessionFactory().openSession()) {
NativeQuery query = session.createNativeQuery(ALL_ROOMS);
query.addEntity(Room.class);
List<Room> objects = query.getResultList();
return objects;
} catch (HibernateException e) {
System.err.println("No rooms.");
System.err.println(e.getMessage());
throw e;
}
}
}
|
C#
|
UTF-8
| 1,811
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
using GameStore.Data.Models;
using GameStore.Models;
using System.Collections.Generic;
using System.Linq;
namespace GameStore.Test.Data
{
public static class Games
{
public static IEnumerable<Game> GetFiveGames()
{
return Enumerable.Range(0, 5).Select(x => new Game
{
});
}
public static Game GameWithId(int id)
{
return new Game()
{
Id = id,
ImageUrl = "lalallalaa",
Description = "sadsdasdsa",
Price = 20,
TrailerUrl = "sadasdasda",
Title = "sdasdasda",
Guide = "sdadasda",
Requirements = "sdasdas",
PlatformId = 1,
GenreId = 1,
Genre = new Genre
{
Id = 1,
Name = "Shooter"
},
Platform = new Platform
{
Id = 1,
Name = "Pc"
}
};
}
public static Game CreateGame()
{
return new Game
{
Id = 1,
Title = "Title",
Description = "Description",
Requirements = "Requirements",
Price = 20,
Guide = "Guide",
Platform = new Platform
{
Id = 1,
Name = "Pc"
},
ImageUrl = "ImageUrl",
TrailerUrl = "TrailerUrl",
Genre = new Genre
{
Id = 1,
Name = "Shooter"
}
};
}
}
}
|
Java
|
UTF-8
| 1,555
| 2.140625
| 2
|
[] |
no_license
|
package uz.cas.controllersestem.payload.request;
import javax.validation.constraints.NotBlank;
public class ReqUser {
@NotBlank(message = "malumot kiritilmagan")
private String firstName;
@NotBlank(message = "malumot kiritilmagan")
private String lastName;
@NotBlank(message = "malumot kiritilmagan")
private String username;
@NotBlank(message = "malumot kiritilmagan")
private String password;
@NotBlank(message = "malumot kiritilmagan")
private String job;
public ReqUser() {
}
public ReqUser(String firstName, String lastName, String username, String password, String job) {
this.firstName = firstName;
this.lastName = lastName;
this.username = username;
this.password = password;
this.job = job;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
|
C#
|
UTF-8
| 827
| 3.328125
| 3
|
[] |
no_license
|
namespace Utilities
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Permite adicionar linhas a uma tabela.
/// </summary>
/// <typeparam name="ElementType">O tipo de objetos que constituem as entradas da tabela.</typeparam>
public class TabularItemAdder<ElementType>
: IDataParseAdder<ITabularItem, ElementType>
{
/// <summary>
/// Adiciona um conjunto de elementos a um item tabular.
/// </summary>
/// <param name="addObj">O item tabular.</param>
/// <param name="elements">O conjunto de elementos.</param>
public void Add(
ITabularItem addObj,
IEnumerable<ElementType> elements)
{
addObj.Add(elements);
}
}
}
|
Python
|
UTF-8
| 720
| 3
| 3
|
[] |
no_license
|
import time
from typing import Union
import RPi.GPIO as GPIO
class SSR:
def __init__(self, pin: int) -> None:
self.__pin = pin
GPIO.setup(
self.__pin,
GPIO.OUT,
)
self.is_on = 0
GPIO.output(self.__pin, self.is_on)
def write(self, is_on: Union[bool, int]) -> None:
self.is_on = int(is_on)
GPIO.output(self.__pin, self.is_on)
if __name__ == "__main__":
try:
GPIO.setmode(GPIO.BCM)
ssr = SSR(pin=12)
is_on = False
while True:
is_on = not is_on
time.sleep(5)
ssr.write(is_on)
print(ssr.is_on)
except KeyboardInterrupt:
GPIO.cleanup()
|
Ruby
|
UTF-8
| 2,020
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
require 'shameless/errors'
module Shameless
class Index
PRIMARY = :primary
attr_reader :name
def initialize(name, model, &block)
@name = name || PRIMARY
@model = model
instance_eval(&block)
end
DataTypes = {integer: Integer, string: String}
DataTypes.each do |name, type|
define_method(name) do |column|
self.column(column, type)
end
end
def column(name, type)
@columns ||= {}
@columns[name] = type
end
def shard_on(shard_on)
@shard_on = shard_on
end
def put(values)
shardable_value = values.fetch(@shard_on).to_i
index_values = index_values(values, true)
@model.store.put(table_name, shardable_value, index_values)
end
def where(query, &block)
shardable_value = query.fetch(@shard_on).to_i
query = index_values(query, false)
@model.store.where(table_name, shardable_value, query, &block).map {|r| @model.new(r[:uuid]) }
end
def table_name
"#{@model.table_name}_#{full_name}"
end
def full_name
"#{@name}_index"
end
def index_values(values, all_required)
(@columns.keys + [:uuid]).each_with_object({}) do |column, o|
if all_required
o[column] = values.fetch(column)
else
o[column] = values[column] if values.key?(column)
end
end
end
def create_tables!
@model.store.create_table!(table_name) do |t, sharded_table_name|
@columns.each do |name, type|
t.column name, type, null: false
end
t.varchar :uuid, size: 36
t.index @columns.keys, name: "#{sharded_table_name}_index", unique: true
end
end
def column?(key)
@columns.keys.any? {|c| c.to_s == key.to_s }
end
def prevent_readonly_attribute_mutation!(key)
if column?(key)
raise ReadonlyAttributeMutation, "The attribute #{key} cannot be modified because it's part of the #{@name} index"
end
end
end
end
|
Python
|
UTF-8
| 6,470
| 4.25
| 4
|
[] |
no_license
|
"""
Hash Map :
A key-value store that uses an array and a hashing function to save and retrieve values.
Being a map means relating two pieces of information, but a map also has one further requirement.
Key: The identifier given to a value for later retrieval.
In order for a relationship to be a map, every key that is used can only be the key to a single value.
we don’t really care about the exact sequence of the data. We only care that a given input, when fed into the map, gives the accurate output.
An array uses indices to keep track of values in memory, so we’ll need a way of turning each key in our map to an index in our array.
Hash Function :
Hash function: A function that takes some input and returns a number.
Compression function: A function that transforms its inputs into some smaller range of possible outputs.
hash function takes a string as input and returns an array index as output.
The hash function will first compute a value using some scoring metric: this is the hash value, hash code, or just the hash. Our hash map implementation then takes that hash value mod the size of the array. This guarantees that the value returned by the hash function can be used as an index into the array we’re using.
hash functions are also known as compression functions.
The hashing is not a reversible process as it compresses the input into the hash value in range(array_index).
Hash value calculation:
=> for string input:
input = garnet
hashed_into(['g', 'a', 'r', 'n', 'e', 't'])
code point = ['103', '97', '114', '110', '101', '116']
Hash_value = 641 (adding code points)
=> for integers like 641
The storage location at the index given by a hash is called the hash bucket.
Hash map performs modulo arithmetic to turn the hash into an array index. lets say array_size = 10
array_index = 641 % 10
Collisions:
Hash function might produce the same hash for two different keys known as hash collision.
A hash collision is when a hash function returns the same index for two different keys.
Strategy to resolve collisions:
1. Separate Chaining:
The user wants to assign a value to a key in the map.
The hash map takes the key and transforms it into a hash code.
The hash code is then converted into an index to an array using the modulus operation.
If the value of the array at the hash function’s returned index is empty, a new linked list is created with the value as the first element of the linked list.
If a linked list already exists at the address, append the value to the linked list given.
But the retrieval becomes very time taking in O(n)
2. Saving Key:
In case of Separate chaining multiple keys can create confusion on retrieval.
we save both the key and the value, then we will be able to check against the saved key when we’re accessing data in a hash map. By saving the key with the value, we can avoid situations in which two keys have the same hash code where we might not be able to distinguish which value goes with a given key.
For each element, if the saved key is the same as our key, return the value. Otherwise, continue iterating through the list comparing the keys saved in that list with our key
3. Open Addressing:
Linear Probing:
In open addressing we stick to the array as our underlying data structure, but we continue looking for a new index to save our data if the first result of our hash function has a different key’s data
Probing means continuing to find new array indices in a fixed sequence until an empty index is found.
Linear probing systems, could jump by five steps instead of one step.
Quadratic probing
we add increasingly large numbers to the hash code. At the first collision we just add 1, but if the hash collides there too we add 4 ,and the third time we add 9. Having a probe sequence change over time like this avoids clustering.
Clustering : It happens when a single hash collision causes additional hash collisions.
All the output in form of Array index, key, value creates Hash Table.
"""
class HashMap:
def __init__(self, array_size):
self.array_size = array_size
self.array = [None for item in range(array_size)]
def hash(self, key, count_collisions=0):
key_bytes = key.encode()
hash_code = sum(key_bytes)
return hash_code + count_collisions
def compressor(self, hash_code):
return hash_code % self.array_size
def assign(self, key, value):
array_index = self.compressor(self.hash(key))
current_array_value = self.array[array_index]
if current_array_value is None:
self.array[array_index] = [key, value]
return
if current_array_value[0] == key:
self.array[array_index] = [key, value]
return
# Collision!
number_collisions = 1
while(current_array_value[0] != key):
new_hash_code = self.hash(key, number_collisions)
new_array_index = self.compressor(new_hash_code)
current_array_value = self.array[new_array_index]
if current_array_value is None:
self.array[new_array_index] = [key, value]
return
if current_array_value[0] == key:
self.array[new_array_index] = [key, value]
return
number_collisions += 1
return
def retrieve(self, key):
array_index = self.compressor(self.hash(key))
possible_return_value = self.array[array_index]
if possible_return_value is None:
return None
if possible_return_value[0] == key:
return possible_return_value[1]
retrieval_collisions = 1
while (possible_return_value != key):
new_hash_code = self.hash(key, retrieval_collisions)
retrieving_array_index = self.compressor(new_hash_code)
possible_return_value = self.array[retrieving_array_index]
if possible_return_value is None:
return None
if possible_return_value[0] == key:
return possible_return_value[1]
retrieval_collisions += 1
return
hash_map = HashMap(15)
hash_map.assign("gabbro","igneous")
hash_map.assign("sandstone","sedimentary")
hash_map.assign("gneiss","metamorphic")
print(hash_map.retrieve("gabbro"))
print(hash_map.retrieve("sandstone"))
print(hash_map.retrieve("gneiss"))
|
Markdown
|
UTF-8
| 1,047
| 3.328125
| 3
|
[] |
no_license
|
####初始化
```c++
//1.chushihua.cpp
#include <iostream>
#include <string>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
int a = 0;
int b(1);
int c = {3};
}
```
```c++
//大佬笔记
#include <iostream>
using namespace std;
struct test{
public:
string s;
int i;
};
int global_i; //全局内置类型初始化为0
test global_t;
int main()
{
int local_i; //局部内置类型不默认初始化,值未定义
static int static_i; //静态内置类型值初始化,为0
test local_t;
static test static_t;
cout << "global int:" << global_i << endl; //0
cout << "local int:" << local_i << endl; //未定义
cout << "static int:" << static_i << endl; //0
cout << "global test:" << global_t.s << "," << global_t.i << endl; // "",0
cout << "local test:" << local_t.s << "," << local_t.i << endl; // "",未定义
cout << "static test:" << static_t.s << "," << static_t.i << endl; // "",0
return EXIT_SUCCESS;
};
```
|
Java
|
UTF-8
| 85
| 1.664063
| 2
|
[] |
no_license
|
package com.example.demo.utils;
public enum RoleEnum {
CLIENT,
LIBRARIAN
}
|
C++
|
UTF-8
| 1,832
| 3.90625
| 4
|
[] |
no_license
|
/*
Short example of how to use the trig functions in C++
Code by Jason Lillard, 2018
*/
#include <cmath> //for trig function functions
#include <iostream> // for input and output
using namespace std;
//FUNCTION PROTOTYPE
//helper function to get float inputs w/0 breaking
float getFloat(const char * prompt, float min, float max);
//BEGIN MAIN
int main(){
//OUTPUT INTRO AND PROMPT
cout<<"Tangent thing.\n"
"Determine the height of a thing with your distance from its base\n"
"and the angle from the ground to the top of the thing."<<endl;
//GET INPUTS, DO MATH
float x = getFloat("How far away is the thing?: ", 0, 1e10);
float theta = getFloat("At the given distance away, what is the angle in degrees\n"
"from the ground to the top of the thing?: ", 0.01, 89.99 );
theta *= M_PI/180.0; //convert from degrees to radians for math functions
//OUTPUT RESULTS ( & DO THE LAST BIT OF MATH)
cout<<"The thing's height is " << x*tan(theta) <<" units tall"<<endl;
return 0;
}
//END OF MAIN
//HELPER FUNC DEF.
float getFloat(const char * prompt, float min, float max){
bool valid = false; //assume input failed
float result; //allocate some space to store result
do{
cout<<prompt; //output the prompt
cin>>result; //get in the input
//test the input
if (!cin.good()){ //check cin.good() to make sure no letters were input
cin.clear(); //clear all flags
cin.ignore(1028, '\n'); //ignore rest of input buffer
}
else if (result>=min&&result<=max){ //check range
valid = true; //if range is good, set valid to true
}
//after all that, if input isn't true, output an error message
if(!valid) cout<<"Invalid input!"<<endl;
}while(!valid); //repeat until input is deemed valid
return result; //return validated input
}
|
C#
|
UTF-8
| 1,917
| 2.71875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemonstrativoPagamento
{
public class FolhaPagamento : IFolhaPagamento
{
public Demonstrativo GerarDemonstrativo(int horasCategoria, double salarioBase, double horasExtras, double horasDescontadas)
{
var valorHoras = Math.Round(salarioBase / horasCategoria, 777); // valor hora funcionario
double valorTotalExtras = Math.Round(valorHoras * horasExtras, 2); // valor de horas extras
double valorTotalDescontos = Math.Round(valorHoras * horasDescontadas, 2); // valor de horas descontadas
HorasCalculadas HorasExtrasCalculadas = new HorasCalculadas(horasExtras, valorTotalExtras); // total de horas extras calculadas
HorasCalculadas HorasDescontadasCalculadas = new HorasCalculadas(horasDescontadas, valorTotalDescontos); // total de horas descontadas calculadas
double totalProventos = Math.Round(salarioBase + (HorasExtrasCalculadas.ValorTotalHoras - HorasDescontadasCalculadas.ValorTotalHoras), 2); // valor total de ganhos mensais do funcionario
Desconto INSS = new CalcularINSS().calcular(totalProventos);
double salarioComINSS = totalProventos - INSS.Valor;
Desconto IRRF = new CalcularINSS().calcular(salarioComINSS);
double totalDescontos = INSS.Valor + IRRF.Valor;
double TotalLiquido = Math.Round(totalProventos - totalDescontos, 2);
double valorFGTS = Math.Round(totalProventos * 0.11, 2);
Desconto FGTS = new Desconto(0.11, valorFGTS);
return new Demonstrativo(salarioBase, horasCategoria, HorasExtrasCalculadas,
HorasDescontadasCalculadas, totalProventos, INSS,
IRRF, totalDescontos, TotalLiquido,
FGTS);
}
}
}
|
Ruby
|
UTF-8
| 624
| 3.359375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Artist
attr_reader :name
@@all = []
def initialize(name)
@name = name
save
end
def name=(name)
@name = name
end
def self.all
@@all
end
def add_song(song_instance)
song_instance.artist = self
end
def songs
Song.all.select do |song|
song.artist == self
end
end
def print_songs
songs.each do |song|
puts song.name
end
end
def self.find_or_create_by_name(artist_name)
if !@@all.any?{|instance| instance.name == artist_name}
artist = Artist.new(artist_name)
end
end
def save
@@all << self
end
end
|
Python
|
UTF-8
| 1,384
| 2.640625
| 3
|
[] |
no_license
|
from struct import *;
from binascii import *;
from array import *;
from random import *;
from re import *;
from socket import *;
import sys;
from helper import *
serverName = "paris.cs.utexas.edu"
serverPort = 35604
serverIP = gethostbyname(serverName)
# creates a UDP socket #
sock = socket(AF_INET, SOCK_DGRAM)
cookie = 12 #randint(0, 100)
checksum = 0
result = 0
SSN = input("Provide SSN: ")
timeouts = 0
msg = bytearray()
# pack 356, lab1, version7, cookie, SSN, checksum, and result to bytearray in network byte order
msg.extend(pack("!HBBIIHH", 356, 1, 7, cookie, SSN, checksum, result))
# computes the new checksum
checksum = computeChecksum(msg)
# repack using new computed checksum
newMessage = bytearray()
newMessage.extend(pack("!HBBIIHH", 356, 1, 7, cookie, SSN, checksum, result))
while timeouts < 5:
try:
sock.settimeout(2)
sock.sendto(newMessage, (serverName, serverPort))
response = sock.recvfrom(2048)
packet = response[0]
recvMessage = unpack("!HBBIIHH", packet)
result = recvMessage[6]
if checkValidity(recvMessage, cookie, SSN, result):
print "P.O. Box number: ", result
break
except timeout:
# timeout expired, retransmit
if timeouts > 5:
print "max timeouts"
else:
print "timeout occured, retransmitting"
timeouts += 1
|
Markdown
|
UTF-8
| 1,534
| 3.109375
| 3
|
[] |
no_license
|
# monograph
This is a little web site generator, just for me, so I can publish journal
entries, if I want.
It uses [hemingway](https://github.com/griffinmyers/hemingway) to parse individual
journal entries and a hacky treetop parser I rigged together just to parse my
journal structure.
# generally, how it works.
I've got this big latex document right? It's my journal, I'd like to share
it online with people. But I want to restrict what certain people can see.
So I need some from of authentication. But that doesn't mean I should get
involved with a dynamic site on rails or whatever, I'm still just serving up
static files, ideally.
Because there are only a handful of people who will want access to this, I could
just generate an index page of the journal for each person and put it in
its own directory with a `.htaccess` file to permission them.
# syntax
I put my authentication in latex comments inline with the journal.
At the top of the file I'll say something like
% register: roymuntz password123
% register: griffinmyers qwerty
% whitelist: motherbear eastereggs
% public: resume
to register a user. If I register someone via the `whitelist` command then
it will opt them into seeing _every single post_. I must use that cautiously.
The `public` declaration will produce a user that is not required to authenticate.
Then in a post (all my posts use the `\section{}` tag) I can say something like
\section{March 24$^th$, 2013}
% show: roymuntz
Dear Journal, ....
......
....
..
.
whoop.
|
Java
|
UTF-8
| 1,089
| 2.46875
| 2
|
[] |
no_license
|
package com.dhrs.service.impl;
import com.dhrs.dao.UserDao;
import com.dhrs.domain.User;
import com.dhrs.service.UserService;
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Override
public User getUserByUsername(String username) {
User user = null;
try {
user = userDao.selectUserByName(username);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
@Override
public boolean addNewUser(User user) {
try {
userDao.insertNewUser(user);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public User getUserByID(String id) {
try {
return userDao.selectUserByID(id);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
|
Markdown
|
UTF-8
| 4,209
| 2.84375
| 3
|
[
"Apache-2.0"
] |
permissive
|
[](https://jitpack.io/#Yesferal/HornsApp-DI)
# HADI: Kotlin HornsApp Dependency Injection
Hadi is a whole Kotlin container, which you can use very simple on JVM or Android.
You can define all the instance that you will need in your app and manage them in a single place.
## Getting Started
In your app gradle, you should add the repository:
```kotlin
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```
and the dependency:
```kotlin
implementation 'com.github.Yesferal:HornsApp-DI:${version}'
```
Then, you should instance Hadi Container in your main class, so any class could access it without any problem.
```kotlin
val container: Container = Hadi()
```
### Android
In case of Android, you should create an instance of Hadi in your Application class.
```kotlin
class MyApp: Application() {
val container: Container = Hadi()
}
```
So, you can use it in any Activity:
```kotlin
val container = (application as MyApp).container
```
## How to use: Register a simple dependency
Some times the code is better than words, to register any dependency you just need:
```kotlin
container register Factory<String> { "Message: Hadi Container is our first option !" }
container register Singleton<MainRepository> {
MainRepository(message = container.resolve())
}
class MainRepository(private val message: String) {
fun getMessage() = message
}
```
## How to use: Resolve dependency without Tag
To resolve any dependency you just need:
```kotlin
private val mainRepository: MainRepository = container.resolve()
```
## How to use: Register dependency using Tag
To register a dependency using a Tag you just need to define the tag as a string. You can use this feature if you have dependencies that implement the same class, for example String:
```kotlin
container register Factory<String>(tag = "Title") { "Title: Hadi Container" }
container register Factory<String>(tag = "Description") { "Description: This is a demo app, which implement Hadi Container. This strings are injected by Hadi using a Tag, in order to Kadi know which one to use in each case." }
container register Singleton<MainRepository> {
MainRepository(
message = container.resolve(tag = "Title"),
description = container.resolve(tag = "Description")
)
}
container register Factory<MainContract.ActionListener> {
MainPresenter(mainRepository = container.resolve())
}
```
## How to use: Resolve dependency using Tag
To resolve a dependency using a Tag you just need to specify the tag that you used to register it:
```kotlin
val message: String = container.resolve(tag = "Title")
val description: String = container.resolve(tag = "Description")
```
## How to use: Register dependency with Parameters
To register a dependency with parameters you just need to define the parameter structure as `name: Type`.
You can use this feature if you have dependencies that need some parameters obtained at runtime:
```kotlin
container register Factory(tag = "Parameter") { (string: String) ->
string
}
```
## How to use: Resolve dependency with parameters
To resolve a dependency with parameters you just need to specify them inside the `Parameters`'s constructor:
```kotlin
val description: String = container.resolve(params = Parameters("Description: Inserting value as Parameter"))
```
Now you're ready to include & use Hadi library into your project!
## Demo Projects
In this Repository you have an Android Demo that explain how to use it.
## License
```
Copyright 2020 HornsApp Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
|
C++
|
UTF-8
| 3,519
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
// Explanation: https://www.youtube.com/watch?v=WMZp0XzkhyQ
/**********************************************************************************************************/
// Problem: E - Rotate and Flip
// Contest: AtCoder - AtCoder Beginner Contest 189
// URL: https://atcoder.jp/contests/abc189/tasks/abc189_e
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
// Parsed on: 26-01-2021 00:31:54 IST (UTC+05:30)
// Author: Kapil Choudhary
// ********************************************************************
// कर्मण्येवाधिकारस्ते मा फलेषु कदाचन |
// मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि || १.४७ ||
// ********************************************************************
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
class Point {
public:
ll x, y;
Point() { x = 0; y = 0; }
~Point() {}
};
class Coefficients {
public:
ll a, b, c;
Coefficients() { a = 0; b = 0; c = 0; }
Coefficients(ll i, ll j, ll k) { a = i; b = j; c = k; }
~Coefficients() {}
void negative() { a = -a; b = -b; c = -c; }
void add(ll k) { c += k; }
ll evaluate(Point p) { return (a * p.x) + (b * p.y) + c; }
};
void solve()
{
ll n, m, q;
cin >> n;
vector<Point> v(n);
for(ll i = 0; i < n; i++) {
cin >> v[i].x >> v[i].y;
}
cin >> m;
vll op(m), par(m);
for(ll i = 0; i < m; i++) {
cin >> op[i];
if(op[i] > 2) cin >> par[i];
}
vector<pair<Coefficients, Coefficients>> coeff(m + 1);
coeff[0] = {Coefficients(1, 0, 0), Coefficients(0, 1, 0)};
for(ll i = 1; i <= m; i++) {
switch(op[i-1]) {
case 1:
coeff[i] = { coeff[i-1].S, coeff[i-1].F };
coeff[i].S.negative();
break;
case 2:
coeff[i] = { coeff[i-1].S, coeff[i-1].F };
coeff[i].F.negative();
break;
case 3:
coeff[i] = coeff[i-1];
coeff[i].F.negative();
coeff[i].F.add(2 * par[i-1]);
break;
case 4:
coeff[i] = coeff[i-1];
coeff[i].S.negative();
coeff[i].S.add(2 * par[i-1]);
break;
}
}
cin >> q;
for(ll i = 0; i < q; i++) {
ll opr, pt;
cin >> opr >> pt;
cout << coeff[opr].F.evaluate(v[pt-1]) << " "
<< coeff[opr].S.evaluate(v[pt-1]) << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// cin >> t;
while(t--) {
solve();
}
return 0;
}
|
Markdown
|
UTF-8
| 2,462
| 2.6875
| 3
|
[] |
no_license
|
# Everything Proxy
More often than not I find myself behind a proxy server. And then, that one tool I need, just doesn't work. Well, this guide might help.
## APT (Debian's Advanced Package Tool)
```bash
# Configure the proxy in the proxy.conf file
cat /etc/apt/apt.conf.d/proxy.conf
Acquire::http::Proxy "http://proxy.domain.com:8080";
```
## Burp Suite
Configure an upstream proxy server:
1. Select tab "User options".
2. Select sub-tab "Connections".
3. Under "Upstream Proxy Servers" add/enable the upstream proxy server to use. Example:
* Destination host: `*`
* Proxy host: `proxy.domain.com`
* Proxy port: `8080`
* Authentication type: None
4. Click OK
## curl
```bash
# Set the proxy
export HTTP_PROXY=http://proxy.domain.com:8080
export HTTPS_PROXY=http://proxy.domain.com:8080
export ALL_PROXY=http://proxy.domain.com:8080
```
## Firefox
1. Select menu Preferences > Network Settings > Settings...
2. Select on of the following:
* Auto-detect proxy settings for this network
* Use system proxy settings
* Manual proxy configuration
## Git
```bash
# Set the proxy
git config --global http.proxy http://proxy.domain.com:8080
# Check the proxy value
git config --global --get http.proxy
# Unset the proxy
git config --global --unset http.proxy
```
## Homebrew
```bash
# Set the proxy
export HTTP_PROXY=http://proxy.domain.com:8080
export HTTPS_PROXY=http://proxy.domain.com:8080
export ALL_PROXY=http://proxy.domain.com:8080
```
## Hydra
Different types of proxies are possible:
```bash
export HYDRA_PROXY=connect://proxy.domain.com:8080
export HYDRA_PROXY=socks4://proxy.domain.com:8080
export HYDRA_PROXY=socks5://proxy.domain.com:8080
```
## OpenVPN
Edit the configuration (`.opvn` file) and add the proxy information. Some examples:
```console
# Simple HTTP proxy
http-proxy proxy.domain.com 8080
# HTTP proxy with Basic authentication
http-proxy proxy.domain.com 8080 stdin basic
# HTTP proxy with NTLM authentication
http-proxy proxy.domain.com 8080 stdin ntlm
```
## pip (Python's package management)
```bash
export HTTP_PROXY=http://proxy.domain.com:8080
export HTTPS_PROXY=http://proxy.domain.com:8080
```
## wget
```bash
export http_proxy=http://username:password@proxy.domain.com:8080
export https_proxy=http://username:password@proxy.domain.com:8080
export ftp_proxy=http://username:password@proxy.domain.com:8080
# No proxy for these
export no_proxy="domain1.com,domain2.com,domain3.com"
```
|
Java
|
UTF-8
| 2,211
| 3.09375
| 3
|
[] |
no_license
|
package main.converters;
import com.opencsv.bean.AbstractBeanField;
/*
* Converts given String into Java Double object.
* Works directly for phosphate, nitrate/nitrite.
*/
public class DoubleConverter extends AbstractBeanField<String> {
// uses SimpleDoubleConverter as base
private SimpleDoubleConverter converter = new SimpleDoubleConverter();
@Override
public Object convert(String s) {
try {
Double value = (Double) converter.convertToRead(s);
if (value == null) {
// extra characters/units at end
int index = -1;
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != '.') {
index = i;
break;
}
}
value = (Double) converter.convertToRead(s.substring(0, index));
}
if (value == null) {
// extra characters/units at beginning
int index = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != '.') {
index = i + 1;
break;
}
}
value = (Double) converter.convertToRead(s.substring(index));
}
if (value == null) {
// beginning and end
int beginIndex = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
beginIndex = i;
break;
}
}
int endIndex = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
if (Character.isDigit(s.charAt(i))) {
endIndex = i + 1;
break;
}
}
value = Double.parseDouble(s.substring(beginIndex, endIndex));
}
return value;
} catch (Exception ee) {
return null;
}
}
}
|
C#
|
UTF-8
| 4,870
| 2.703125
| 3
|
[] |
no_license
|
namespace SystemFrameWork.Error
{
using System;
using ExtendedMethords;
/// <summary>
/// This class is used for logging error
/// </summary>
public class Error : IError
{
#region Private Variable
#endregion
#region Properties
/// <summary>
/// Gets the error unique identifier.
/// </summary>
/// <value>
/// The error unique identifier.
/// </value>
public string ErrorUniqueId { get; }
/// <summary>
/// Gets the data.
/// </summary>
/// <value>
/// The data.
/// </value>
public System.Collections.IDictionary Data { get; }
/// <summary>
/// Gets the help link.
/// </summary>
/// <value>
/// The help link.
/// </value>
public string HelpLink { get; }
/// <summary>
/// Gets the error code.
/// </summary>
/// <value>
/// The error code.
/// </value>
public long ErrorCode { get; }
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
public string ErrorMessage { get; }
/// <summary>
/// Gets the exception message.
/// </summary>
/// <value>
/// The exception message.
/// </value>
public string ExceptionMessage { get; }
/// <summary>
/// Gets the inner exception.
/// </summary>
/// <value>
/// The inner exception.
/// </value>
public string InnerException { get; }
/// <summary>
/// Gets the stack trace.
/// </summary>
/// <value>
/// The stack trace.
/// </value>
public string StackTrace { get; }
/// <summary>
/// Gets the type of the error.
/// </summary>
/// <value>
/// The type of the error.
/// </value>
public ErrorType ErrorType { get; }
/// <summary>
/// Gets the target site.
/// </summary>
/// <value>
/// The target site.
/// </value>
public string TargetSite { get; }
/// <summary>
/// Gets the date time.
/// </summary>
/// <value>
/// The date time.
/// </value>
public DateTime DateTime { get; }
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="Error" /> class.
/// </summary>
/// <param name="errorMessage">The error message.</param>
/// <param name="errorCode">The error code.</param>
/// <param name="exceptionMessage">The exception message.</param>
/// <param name="innerException">The inner exception.</param>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="errorType">Type of the error.</param>
/// <param name="targetSite">Target from where it is generated</param>
/// <param name="data">The data.</param>
public Error(string errorMessage, long errorCode, string exceptionMessage, string innerException, string stackTrace, ErrorType errorType, string targetSite = "", System.Collections.IDictionary data = null)
{
ErrorUniqueId = Guid.NewGuid().ToString();
ErrorCode = errorCode;
ErrorMessage = errorMessage;
Data = data;
ExceptionMessage = exceptionMessage;
InnerException = innerException;
StackTrace = stackTrace;
ErrorType = errorType;
TargetSite = targetSite;
DateTime = DateTime.UtcNow;
}
/// <summary>
/// This constructor instantiate the error class
/// </summary>
/// <param name="exception">Object of System.Exception is passed as parameter.</param>
/// <param name="targetSite">Target from where it is generated</param>
public Error(Exception exception, string targetSite = "")
{
ErrorUniqueId = Guid.NewGuid().ToString();
Data = exception.Data;
HelpLink = exception.HelpLink;
ErrorCode = exception.HResult;
ErrorMessage = exception.Message;
ExceptionMessage = exception.InnerException.Message;
InnerException = (exception.InnerException != null)? exception.InnerException.GetJsonString() : string.Empty;
StackTrace = exception.StackTrace;
ErrorType = ErrorType.ServerSideRuntime;
TargetSite = targetSite;
DateTime = DateTime.UtcNow;
}
#endregion
#region private methods
#endregion
#region Public methods
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.