text stringlengths 1 1.05M |
|---|
if [ -z "$DISABLE_VALGRIND" ]; then
VALGRIND=valgrind
VALGRIND_OPTS="-q --error-exitcode=1 --leak-check=full --show-reachable=yes"
fi
|
"""
Use a machine learning algorithm to classify the name of a sports team into the type of sport it plays
"""
# imports
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
# create dataframe
df = pd.DataFrame(
{'team_name': ['Manchester United', 'Orlando Magic', 'Los Angeles Dodgers'],
'label': ['soccer', 'basketball', 'baseball']})
# encode labels
encoder = LabelEncoder()
encoder.fit(df['label'])
df['label_encoded'] = encoder.transform(df['label'])
# train model
model = DecisionTreeClassifier()
model.fit(df[['team_name']], df['label_encoded'])
# predict labels
model.predict(['Manchester United', 'Orlando Magic', 'Los Angeles Dodgers']) |
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
product_name TEXT NOT NULL,
product_price INTEGER NOT NULL;
);
CREATE TABLE sales (
sale_id SERIAL PRIMARY KEY,
product_id INTEGER REFERENCES products (product_id),
quantity INTEGER NOT NULL,
sale_date DATE NOT NULL;
); |
#!/bin/bash
curl -v "http://127.0.0.1/threshold/set?threshold=0.8" |
#include <Godunov.H>
#include <PLM.H>
#include <PPM.H>
using namespace amrex;
extern void
trace_ppm(const Box& bx,
const int idir,
Array4<Real const> const& q_arr,
Array4<Real const> const& srcQ,
Array4<Real> const& qm,
Array4<Real> const& qp,
const Box& vbx,
const Real dt, const Real* del,
const Real gamma,
const Real small_dens, const Real small_pres,
const Real small,
const int FirstSpec, const int NumSpec,
const Real a_old);
// Host function to call gpu hydro functions
void
pc_umeth_3D(
Box const& bx,
Array4<const Real> const& q,
Array4<const Real> const& srcQ,
Array4<Real> const& flx1,
Array4<Real> const& flx2,
Array4<Real> const& flx3,
Array4<Real> const& q1,
Array4<Real> const& q2,
Array4<Real> const& q3,
Array4<Real> const& pdivu,
const Real* del,
const Real dt,
const Real a_old,
const Real a_new,
const int NumSpec,
const Real gamma, const Real gamma_minus_1,
const Real small_dens, const Real small_pres,
const Real small,
const int ppm_type)
{
const int FirstSpec_loc = FirstSpec;
const int NumSpec_loc = NumSpec;
const Real a_half = 0.5 * (a_old + a_new);
Real const dx = del[0];
Real const dy = del[1];
Real const dz = del[2];
Real const hdtdx = 0.5 * dt / dx / a_half;
Real const hdtdy = 0.5 * dt / dy / a_half;
Real const hdtdz = 0.5 * dt / dz / a_half;
Real const cdtdx = 1.0 / 3.0 * dt / dx / a_half;
Real const cdtdy = 1.0 / 3.0 * dt / dy / a_half;
Real const cdtdz = 1.0 / 3.0 * dt / dz / a_half;
const amrex::Box& bxg1 = grow(bx, 1);
const amrex::Box& bxg2 = grow(bx, 2);
// X data
int cdir = 0;
const amrex::Box& xmbx = growHi(bxg2, cdir, 1);
const amrex::Box& xflxbx = surroundingNodes(grow(bxg2, cdir, -1), cdir);
amrex::FArrayBox qxm(xmbx, QVAR);
amrex::FArrayBox qxp(bxg2, QVAR);
amrex::Elixir qxmeli = qxm.elixir();
amrex::Elixir qxpeli = qxp.elixir();
auto const& qxmarr = qxm.array();
auto const& qxparr = qxp.array();
// Y data
cdir = 1;
const amrex::Box& yflxbx = surroundingNodes(grow(bxg2, cdir, -1), cdir);
const amrex::Box& ymbx = growHi(bxg2, cdir, 1);
amrex::FArrayBox qym(ymbx, QVAR);
amrex::FArrayBox qyp(bxg2, QVAR);
amrex::Elixir qymeli = qym.elixir();
amrex::Elixir qypeli = qyp.elixir();
auto const& qymarr = qym.array();
auto const& qyparr = qyp.array();
// Z data
cdir = 2;
const amrex::Box& zmbx = growHi(bxg2, cdir, 1);
const amrex::Box& zflxbx = surroundingNodes(grow(bxg2, cdir, -1), cdir);
amrex::FArrayBox qzm(zmbx, QVAR);
amrex::FArrayBox qzp(bxg2, QVAR);
amrex::Elixir qzmeli = qzm.elixir();
amrex::Elixir qzpeli = qzp.elixir();
auto const& qzmarr = qzm.array();
auto const& qzparr = qzp.array();
// Put the PLM and slopes in the same kernel launch to avoid unnecessary
// launch overhead Pelec_Slope_* are SIMD as well as PeleC_plm_* which loop
// over the same box
if(ppm_type == 0 )
{
amrex::ParallelFor(bxg2, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
amrex::Real slope[8];
const amrex::Real c = std::sqrt((gamma_minus_1+1.0) * q(i,j,k,QPRES)/q(i,j,k,QRHO));
// X slopes and interp
for (int n = 0; n < QVAR; ++n)
slope[n] = plm_slope(i, j, k, n, 0, q, small_pres);
pc_plm_x(i, j, k, qxmarr, qxparr, srcQ, slope, q, c, a_old, dx, dt, NumSpec,
gamma_minus_1, small_dens, small_pres);
// Y slopes and interp
for (int n = 0; n < QVAR; n++)
slope[n] = plm_slope(i, j, k, n, 1, q, small_pres);
pc_plm_y(i, j, k, qymarr, qyparr, srcQ, slope, q, c, a_old, dy, dt, NumSpec,
gamma_minus_1, small_dens, small_pres);
// Z slopes and interp
for (int n = 0; n < QVAR; ++n)
slope[n] = plm_slope(i, j, k, n, 2, q, small_pres);
pc_plm_z(i, j, k, qzmarr, qzparr, srcQ, slope, q, c, a_old, dz, dt, NumSpec,
gamma_minus_1, small_dens, small_pres);
});
} else {
// Compute the normal interface states by reconstructing
// the primitive variables using the piecewise parabolic method
// and doing characteristic tracing. We do not apply the
// transverse terms here.
int idir = 0;
trace_ppm(bxg2,
idir,
q, srcQ,
qxmarr, qxparr,
bxg2, dt, del, gamma,
small_dens, small_pres,
small,
FirstSpec, NumSpec,
a_old);
idir = 1;
trace_ppm(bxg2,
idir,
q, srcQ,
qymarr, qyparr,
bxg2, dt, del, gamma,
small_dens, small_pres,
small,
FirstSpec, NumSpec,
a_old);
idir = 2;
trace_ppm(bxg2,
idir,
q, srcQ,
qzmarr, qzparr,
bxg2, dt, del, gamma,
small_dens, small_pres,
small,
FirstSpec, NumSpec,
a_old);
}
// These are the first flux estimates as per the corner-transport-upwind
// method X initial fluxes
cdir = 0;
amrex::FArrayBox fx(xflxbx, flx1.nComp());
amrex::Elixir fxeli = fx.elixir();
auto const& fxarr = fx.array();
amrex::FArrayBox qgdx(xflxbx, NGDNV);
amrex::Elixir qgdxeli = qgdx.elixir();
auto const& gdtempx = qgdx.array();
amrex::ParallelFor(
xflxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_cmpflx(
i, j, k, qxmarr, qxparr, fxarr, gdtempx,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
// Y initial fluxes
cdir = 1;
amrex::FArrayBox fy(yflxbx, flx2.nComp());
amrex::Elixir fyeli = fy.elixir();
auto const& fyarr = fy.array();
amrex::FArrayBox qgdy(yflxbx, NGDNV);
amrex::Elixir qgdyeli = qgdy.elixir();
auto const& gdtempy = qgdy.array();
amrex::ParallelFor(
yflxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_cmpflx(
i, j, k, qymarr, qyparr, fyarr, gdtempy,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
// Z initial fluxes
cdir = 2;
amrex::FArrayBox fz(zflxbx, flx3.nComp());
amrex::Elixir fzeli = fz.elixir();
auto const& fzarr = fz.array();
amrex::FArrayBox qgdz(zflxbx, NGDNV);
amrex::Elixir qgdzeli = qgdz.elixir();
auto const& gdtempz = qgdz.array();
amrex::ParallelFor(
zflxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_cmpflx(
i, j, k, qzmarr, qzparr, fzarr, gdtempz,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
// X interface corrections
cdir = 0;
const amrex::Box& txbx = grow(bxg1, cdir, 1);
const amrex::Box& txbxm = growHi(txbx, cdir, 1);
amrex::FArrayBox qxym(txbxm, QVAR);
amrex::Elixir qxymeli = qxym.elixir();
amrex::FArrayBox qxyp(txbx, QVAR);
amrex::Elixir qxypeli = qxyp.elixir();
auto const& qmxy = qxym.array();
auto const& qpxy = qxyp.array();
amrex::FArrayBox qxzm(txbxm, QVAR);
amrex::Elixir qxzmeli = qxzm.elixir();
amrex::FArrayBox qxzp(txbx, QVAR);
amrex::Elixir qxzpeli = qxzp.elixir();
auto const& qmxz = qxzm.array();
auto const& qpxz = qxzp.array();
amrex::ParallelFor(txbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
// X|Y
pc_transy1(
i, j, k, qmxy, qpxy, qxmarr, qxparr, fyarr, gdtempy, cdtdy, NumSpec, gamma, small_pres);
// X|Z
pc_transz1(
i, j, k, qmxz, qpxz, qxmarr, qxparr, fzarr, gdtempz, cdtdz, NumSpec, gamma, small_pres);
});
const amrex::Box& txfxbx = surroundingNodes(bxg1, cdir);
amrex::FArrayBox fluxxy(txfxbx, flx1.nComp());
amrex::FArrayBox fluxxz(txfxbx, flx1.nComp());
amrex::FArrayBox gdvxyfab(txfxbx, NGDNV);
amrex::FArrayBox gdvxzfab(txfxbx, NGDNV);
amrex::Elixir fluxxyeli = fluxxy.elixir(), gdvxyeli = gdvxyfab.elixir();
amrex::Elixir fluxxzeli = fluxxz.elixir(), gdvxzeli = gdvxzfab.elixir();
auto const& flxy = fluxxy.array();
auto const& flxz = fluxxz.array();
auto const& qxy = gdvxyfab.array();
auto const& qxz = gdvxzfab.array();
// Riemann problem X|Y X|Z
amrex::ParallelFor(
txfxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
// X|Y
pc_cmpflx(
i, j, k, qmxy, qpxy, flxy, qxy,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
// X|Z
pc_cmpflx(
i, j, k, qmxz, qpxz, flxz, qxz,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
qxymeli.clear();
qxypeli.clear();
qxzmeli.clear();
qxzpeli.clear();
// Y interface corrections
cdir = 1;
const amrex::Box& tybx = grow(bxg1, cdir, 1);
const amrex::Box& tybxm = growHi(tybx, cdir, 1);
amrex::FArrayBox qyxm(tybxm, QVAR);
amrex::FArrayBox qyxp(tybx, QVAR);
amrex::FArrayBox qyzm(tybxm, QVAR);
amrex::FArrayBox qyzp(tybx, QVAR);
amrex::Elixir qyxmeli = qyxm.elixir(), qyxpeli = qyxp.elixir();
amrex::Elixir qyzmeli = qyzm.elixir(), qyzpeli = qyzp.elixir();
auto const& qmyx = qyxm.array();
auto const& qpyx = qyxp.array();
auto const& qmyz = qyzm.array();
auto const& qpyz = qyzp.array();
amrex::ParallelFor(tybx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
// Y|X
pc_transx1(
i, j, k, qmyx, qpyx, qymarr, qyparr, fxarr, gdtempx, cdtdx, NumSpec, gamma, small_pres);
// Y|Z
pc_transz2(
i, j, k, qmyz, qpyz, qymarr, qyparr, fzarr, gdtempz, cdtdz, NumSpec, gamma, small_pres);
});
fzeli.clear();
qgdzeli.clear();
// Riemann problem Y|X Y|Z
const amrex::Box& tyfxbx = surroundingNodes(bxg1, cdir);
amrex::FArrayBox fluxyx(tyfxbx, flx1.nComp());
amrex::FArrayBox fluxyz(tyfxbx, flx1.nComp());
amrex::FArrayBox gdvyxfab(tyfxbx, NGDNV);
amrex::FArrayBox gdvyzfab(tyfxbx, NGDNV);
amrex::Elixir fluxyxeli = fluxyx.elixir(), gdvyxeli = gdvyxfab.elixir();
amrex::Elixir fluxyzeli = fluxyz.elixir(), gdvyzeli = gdvyzfab.elixir();
auto const& flyx = fluxyx.array();
auto const& flyz = fluxyz.array();
auto const& qyx = gdvyxfab.array();
auto const& qyz = gdvyzfab.array();
amrex::ParallelFor(
tyfxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
// Y|X
pc_cmpflx(
i, j, k, qmyx, qpyx, flyx, qyx,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
// Y|Z
pc_cmpflx(
i, j, k, qmyz, qpyz, flyz, qyz,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
qyxmeli.clear();
qyxpeli.clear();
qyzmeli.clear();
qyzpeli.clear();
// Z interface corrections
cdir = 2;
const amrex::Box& tzbx = grow(bxg1, cdir, 1);
const amrex::Box& tzbxm = growHi(tzbx, cdir, 1);
amrex::FArrayBox qzxm(tzbxm, QVAR);
amrex::FArrayBox qzxp(tzbx, QVAR);
amrex::FArrayBox qzym(tzbxm, QVAR);
amrex::FArrayBox qzyp(tzbx, QVAR);
amrex::Elixir qzxmeli = qzxm.elixir(), qzxpeli = qzxp.elixir();
amrex::Elixir qzymeli = qzym.elixir(), qzypeli = qzyp.elixir();
auto const& qmzx = qzxm.array();
auto const& qpzx = qzxp.array();
auto const& qmzy = qzym.array();
auto const& qpzy = qzyp.array();
amrex::ParallelFor(tzbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
// Z|X
pc_transx2(
i, j, k, qmzx, qpzx, qzmarr, qzparr, fxarr, gdtempx, cdtdx, NumSpec, gamma, small_pres);
// Z|Y
pc_transy2(
i, j, k, qmzy, qpzy, qzmarr, qzparr, fyarr, gdtempy, cdtdy, NumSpec, gamma, small_pres);
});
fxeli.clear();
fyeli.clear();
qgdxeli.clear();
qgdyeli.clear();
// Riemann problem Z|X Z|Y
const amrex::Box& tzfxbx = surroundingNodes(bxg1, cdir);
amrex::FArrayBox fluxzx(tzfxbx, flx1.nComp());
amrex::FArrayBox fluxzy(tzfxbx, flx1.nComp());
amrex::FArrayBox gdvzxfab(tzfxbx, NGDNV);
amrex::FArrayBox gdvzyfab(tzfxbx, NGDNV);
amrex::Elixir fluxzxeli = fluxzx.elixir(), gdvzxeli = gdvzxfab.elixir();
amrex::Elixir fluxzyeli = fluxzy.elixir(), gdvzyeli = gdvzyfab.elixir();
auto const& flzx = fluxzx.array();
auto const& flzy = fluxzy.array();
auto const& qzx = gdvzxfab.array();
auto const& qzy = gdvzyfab.array();
amrex::ParallelFor(
tzfxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
// Z|X
pc_cmpflx(
i, j, k, qmzx, qpzx, flzx, qzx,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
// Z|Y
pc_cmpflx(
i, j, k, qmzy, qpzy, flzy, qzy,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
qzxmeli.clear();
qzxpeli.clear();
qzymeli.clear();
qzypeli.clear();
// Temp Fabs for Final Fluxes
amrex::FArrayBox qmfab(bxg2, QVAR);
amrex::FArrayBox qpfab(bxg1, QVAR);
amrex::Elixir qmeli = qmfab.elixir();
amrex::Elixir qpeli = qpfab.elixir();
auto const& qm = qmfab.array();
auto const& qp = qpfab.array();
// X | Y&Z
cdir = 0;
const amrex::Box& xfxbx = surroundingNodes(bx, cdir);
const amrex::Box& tyzbx = grow(bx, cdir, 1);
amrex::ParallelFor(tyzbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_transyz(
i, j, k, qm, qp, qxmarr, qxparr, flyz, flzy, qyz, qzy,
hdtdy, hdtdz, NumSpec, gamma, small_pres);
});
fluxzyeli.clear();
gdvzyeli.clear();
gdvyzeli.clear();
fluxyzeli.clear();
qxmeli.clear();
qxpeli.clear();
// Final X flux
amrex::ParallelFor(xfxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_cmpflx(i, j, k, qm, qp, flx1, q1,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
// Y | X&Z
cdir = 1;
const amrex::Box& yfxbx = surroundingNodes(bx, cdir);
const amrex::Box& txzbx = grow(bx, cdir, 1);
amrex::ParallelFor(txzbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_transxz(
i, j, k, qm, qp, qymarr, qyparr, flxz, flzx, qxz, qzx,
hdtdx, hdtdz, NumSpec, gamma, small_pres);
});
fluxzxeli.clear();
gdvzxeli.clear();
gdvxzeli.clear();
fluxxzeli.clear();
qymeli.clear();
qypeli.clear();
// Final Y flux
amrex::ParallelFor(yfxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_cmpflx(i, j, k, qm, qp, flx2, q2,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
// Z | X&Y
cdir = 2;
const amrex::Box& zfxbx = surroundingNodes(bx, cdir);
const amrex::Box& txybx = grow(bx, cdir, 1);
amrex::ParallelFor(txybx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_transxy(
i, j, k, qm, qp, qzmarr, qzparr, flxy, flyx, qxy, qyx,
hdtdx, hdtdy, NumSpec, gamma, small_pres);
});
gdvyxeli.clear();
fluxyxeli.clear();
gdvxyeli.clear();
fluxxyeli.clear();
qzmeli.clear();
qzpeli.clear();
// Final Z flux
amrex::ParallelFor(zfxbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_cmpflx(i, j, k, qm, qp, flx3, q3,
q, small_dens, small_pres, small, gamma,
FirstSpec_loc, NumSpec_loc, cdir);
});
qmeli.clear();
qpeli.clear();
// Construct p div{U}
amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
pc_pdivu(i, j, k, pdivu, q1, q2, q3, dx, dy, dz);
});
}
|
#!/bin/bash
set -e
STACKNAME=$(npx @cdk-turnkey/stackname@1.2.0 --suffix webapp)
TABLE_NAME=$(aws cloudformation describe-stacks \
--stack-name ${STACKNAME} | \
jq '.Stacks[0].Outputs | map(select(.OutputKey == "TableName"))[0].OutputValue' | \
tr -d \")
BUCKET_NAME=$(aws cloudformation describe-stacks \
--stack-name ${STACKNAME} | \
jq '.Stacks[0].Outputs | map(select(.OutputKey == "ScriptsBucketName"))[0].OutputValue' | \
tr -d \")
CONTENT_FILE_PATH='./content.json'
./bin/content2dynamo.js \
--table-name ${TABLE_NAME} \
--bucket-name ${BUCKET_NAME} \
--content-file-path ${CONTENT_FILE_PATH}
echo $?
mkdir -p deploy
for f in scripts/*
do
g=$(echo ${f} | sed 's/^scripts/deploy/' | sed 's/[.]md$/.json/')
./bin/txt2json.js ${f} > ${g}
done
aws s3 sync \
--content-type "application/json" \
--delete \
deploy/ \
s3://${BUCKET_NAME}
|
<reponame>LuChangliCN/medas-iot
package com.foxconn.iot.sso.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class User implements UserDetails {
private static final long serialVersionUID = 1L;
private long id;
private String username;
private String password;
private List<String> roles;
private int status;
private int modify;
private long companyId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getModify() {
return modify;
}
public void setModify(int modify) {
this.modify = modify;
}
public long getCompanyId() {
return companyId;
}
public void setCompanyId(long companyId) {
this.companyId = companyId;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>(roles.size());
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return modify > 0;
}
@Override
public boolean isEnabled() {
return this.status == 0;
}
}
|
#!/bin/bash
set -eo pipefail
bash <(curl -s -L https://detect.synopsys.com/detect.sh) \
--detect.source.path="${WORKSPACE}/cactus/modules/$1" \
--detect.yarn.prod.only=true \
--detect.project.name="github.com/repaygithub/cactus" \
--detect.project.version.name="master" \
--detect.code.location.name="cactus" \
--detect.project.version.phase="RELEASED" \
--blackduck.url="https://repay.blackducksoftware.com" \
--blackduck.api.token=${BLACKDUCK_TOKEN} \
--detect.project.version.distribution=SAAS \
--detect.cleanup=true \
--detect.tools.excluded=SIGNATURE_SCAN \
--detect.excluded.detector.types=MAVEN |
<gh_stars>0
let origin = location.origin;
let URLWord = 'https://localhost:8080';
// let URLWord = '';
let ejecution = false;
const avanzar = 'forward';
const retroceder = 'backward';
const giro_derecha = 'turn-right';
const giro_izquierda = 'turn-left';
var params = new URLSearchParams(location.search);
// const moves = JSON.parse(params.get('moves')) || [];
const program = JSON.parse(params.get('programLI'));
const moves = program.moves || [];
const wordDefault = "word1";
// let nameWord = String(params.get('mundo')) || wordDefault;
let nameWord = program?.mundo || wordDefault;
// URL del mundo a ejecutar
const URLMundo = () => (`./word/${nameWord}.json`);
const imgFondo = (newF) => (`./assets/fondo/fondo_${newF}.png`);
let word;
let fondo = imgFondo(wordDefault);
// imgFondo(nameWord);
function loadJSON() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', URLMundo());
xobj.onreadystatechange = function () { // si el mundo no se encuentra se precarga el mundo por defecto
if (xobj.readyState == 4 && xobj.status == "404" && nameWord !== wordDefault) { // evita recursividad infinita
nameWord = wordDefault;
loadJSON();
}
if (xobj.readyState == 4 && xobj.status == "200") {
word = JSON.parse(xobj.responseText);
}
};
xobj.send(null);
}
// function loadFondo() {
// var xobj = new XMLHttpRequest();
// xobj.overrideMimeType("application/json");
// xobj.open('GET', fondo);
// xobj.onreadystatechange = function () { // si la imagen del fondo no se encuentra se precarga el fondo por defecto
// if (xobj.readyState == 4 && xobj.status == "404" && nameWord !== wordDefault) { // evita recursividad infinita
// console.log(xobj);
// fondo = imgFondo(wordDefault);
// console.log(fondo);
// }
// if (xobj.readyState == 4 && xobj.status == "200") {
// fondo = imgFondo(nameWord);
// }
// };
// // console.log(xobj);
// xobj.send(null);
// }
loadJSON();
//loadFondo();
let contMoves = 0; //contamos la cantidad de movimientos realizados
const velX = 97;
const velY = 97;
const config = {
type: Phaser.AUTO, //intenta utilizar WebGL automáticamente
width: 1155,
height: 575,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 },
debug: false
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
let timedEvent;
let game = new Phaser.Game(config);
let player;
const mov_down = 'rana_mov_down';
const mov_left = 'rana_mov_left';
const mov_up = 'rana_mov_up';
const mov_right = 'rana_mov_right';
const turn_down_left = 'rana_turn_down_left';
const turn_up_right = 'rana_turn_up_right';
const turn_down_right = 'rana_turn_down_right';
const turn_up_left = 'rana_turn_up_left';
let dirAgente = {
orientacion: '',
velX: 0,
velY: 0
};
let contStart = 0;
let scoreText;
function preload() {
this.load.setBaseURL(URLWord);
// cargamos fondo y demás imágenes de objetos estáticos del mundo
this.load.image('fondo', fondo);
// cargamos los elementos coleccionables
this.load.image('star', './assets/elementos/star.png');
// cargamos sprite rana para giros
this.load.spritesheet(turn_down_left, './assets/spritesheets/rana/giro_abajo_izquierda.png', { frameWidth: 85, frameHeight: 79 });
this.load.spritesheet(turn_up_right, './assets/spritesheets/rana/giro_arriba_derecha.png', { frameWidth: 85, frameHeight: 79 });
this.load.spritesheet(turn_down_right, './assets/spritesheets/rana/giro_abajo_derecha.png', { frameWidth: 85, frameHeight: 79 });
this.load.spritesheet(turn_up_left, './assets/spritesheets/rana/giro_arriba_izquierda.png', { frameWidth: 85, frameHeight: 79 });
// cargamos sprite rana para movimientos de avanzar
this.load.spritesheet(mov_up, './assets/spritesheets/rana/mov_arriba.png', { frameWidth: 85, frameHeight: 79 });
this.load.spritesheet(mov_down, './assets/spritesheets/rana/mov_abajo.png', { frameWidth: 85, frameHeight: 79 });
this.load.spritesheet(mov_right, './assets/spritesheets/rana/mov_derecha.png', { frameWidth: 85, frameHeight: 79 });
this.load.spritesheet(mov_left, './assets/spritesheets/rana/mov_izquierda.png', { frameWidth: 85, frameHeight: 79 });
}
const framesCyclic = async (start, medium) => {
let frames = [];
for (let i = start; i < medium; i++) { frames.push(i) }
for (let i = medium; start <= i; i--) { frames.push(i) }
return frames;
}
const setDireccion = async function (x = 0, y = 0, mov = '') {
if (mov) {
// si no viene direccion se usa la que tenía, si no tenía alguna se asigna una
dirAgente.orientacion = mov || dirAgente.orientacion || mov_left;
dirAgente.velX = x;
dirAgente.velY = y;
}
}
const setOrientacion = async function (newMov) {
// seteamos la direccion a la que apunta el sprite en base a su nueva orientacion
(newMov === mov_right) ? setDireccion(velX, 0, mov_right) :
(newMov === mov_left) ? setDireccion(-velX, 0, mov_left) :
(newMov === mov_down) ? setDireccion(0, velY, mov_down) :
(newMov === mov_up) ? setDireccion(0, -velY, mov_up) :
setDireccion(0, 0, '');
}
const randomPos = (initObj, step, initR, finR) => initObj + step * (Phaser.Math.Between(initR, finR));
// se generan estrellas en posiciones aleatorias (ya no se usa, eliminar)
// async function posXYGenerate(arrayObj, initObj) {
// let x = randomPos(initObj.x, velX, 1, 11); // ver!!! 11 podria ser el div de ancho mundo
// let y = randomPos(initObj.y, velY, 1, 5);
// let pos = { x, y };
// let posFound;
// console.log(arrayObj, pos);
// // let array = arrayObj.map(async obj => {
// // // console.log(obj, x, y);
// // if ((obj.x === x && obj.y === y)) {
// // console.log("objeto encontrado repetido!!!")
// // posFound = obj; //await posXYGenerate(arrayObj, initObj);
// // pos = await posXYGenerate(arrayObj, initObj);
// // }
// // return obj;
// // });
// // Promise.all(array);
// posFound = await arrayObj.find(p => p.x === x && p.y === y);
// // console.log(posFound);
// if (posFound) {
// console.log("genera pos nueva => (", x, ", ", y, ")");
// return await posXYGenerate(arrayObj, initObj);
// }
// return pos;
// }
function collectStar(player, star) {
contStart++;
// console.log("contStart => ", contStart);
star.disableBody(true, true);
scoreText.setText('Puntos: ' + contStart);
}
async function create() {
this.add.image(600, 275, 'fondo');
// create player
player = this.physics.add.sprite(50, 560, mov_up);
player.setBounce(0.2);
player.setCollideWorldBounds(true);
await setOrientacion(mov_up);
// ------------ Creamos objetos estáticos del mundo --------------
// creamos estrellas
const initObj = { x: 50, y: 50 };
const posiciones = await word.posiciones;
// console.log(" ------- posiciones => ", posiciones.length);
// definimos cantidad de estrellas, de acuerdo a la cantidad definida en el array del mundo elegido
let stars = this.physics.add.group({
key: 'star',
repeat: posiciones.length - 1,
setXY: {
x: initObj.x,
y: initObj.y
}
});
let arrayPos = posiciones.map(pos => ({ x: initObj.x + velX * pos.x, y: initObj.y + velY * pos.y }));
// this.physics.add.collider(stars, stars);
stars.getChildren().forEach((star, index) => {
star.setCollideWorldBounds(true);
// let pos = { x: star.x + velX, y: star.y + velY };// await posXYGenerate(arrayPos, initObj);
// arrayPos.push(pos);
star.x = arrayPos[index].x;
star.y = arrayPos[index].y;
console.log(star.x, star.y);
});
this.physics.add.overlap(player, stars, collectStar, null, this);
// creamos el objeto que muestra el puntaje
scoreText = this.add.text(16, 16, 'Puntos: 0', { fontSize: '28px', fill: '#000' });
// player.direccion = direccion;
// cantidad de imagenes en lineSprite para movimiento 'walk'
const duration = 1000;
// CREAMOS ANIMACIONES
const repeat = -1;
let frames = [0, 1, 2, 3, 4, 5, 6];
//console.log(frames);
// ANIMACIONES DE MOVIMIENTOS AVANZAR
this.anims.create({
key: mov_up,
frames: this.anims.generateFrameNumbers(mov_up, { frames }),
duration,
repeat
});
this.anims.create({
key: mov_left,
frames: this.anims.generateFrameNumbers(mov_left, { frames }),
duration,
repeat
});
this.anims.create({
key: mov_down,
frames: this.anims.generateFrameNumbers(mov_down, { frames }),
duration,
repeat
});
this.anims.create({
key: mov_right,
frames: this.anims.generateFrameNumbers(mov_right, { frames }),
duration,
repeat
});
// ANIMACIONES DE MOVIMIENTOS CON GIRO
this.anims.create({
key: turn_down_left,
frames: this.anims.generateFrameNumbers(turn_down_left, { frames }),
duration,
repeat
});
this.anims.create({
key: turn_up_right,
frames: this.anims.generateFrameNumbers(turn_up_right, { frames }),
duration,
repeat
});
this.anims.create({
key: turn_down_right,
frames: this.anims.generateFrameNumbers(turn_down_right, { frames }),
duration,
repeat
});
this.anims.create({
key: turn_up_left,
frames: this.anims.generateFrameNumbers(turn_up_left, { frames }),
duration,
repeat
});
// ANIMACIONES DE MOVIMIENTOS CON GIRO INVERTIDO
frames = [6, 5, 4, 3, 2, 1, 0];
this.anims.create({
key: 'invert_' + turn_down_left,
frames: this.anims.generateFrameNumbers(turn_down_left, { frames }),
duration,
repeat
});
this.anims.create({
key: 'invert_' + turn_up_right,
frames: this.anims.generateFrameNumbers(turn_up_right, { frames }),
duration,
repeat
});
this.anims.create({
key: 'invert_' + turn_down_right,
frames: this.anims.generateFrameNumbers(turn_down_right, { frames }),
duration,
repeat
});
this.anims.create({
key: 'invert_' + turn_up_left,
frames: this.anims.generateFrameNumbers(turn_up_left, { frames }),
duration,
repeat
});
// ANIMACIONES DE MOVIMIENTOS RETROCEDER
this.anims.create({
key: 'back_' + mov_up,
frames: this.anims.generateFrameNumbers(mov_up, { frames }),
duration,
repeat
});
this.anims.create({
key: 'back_' + mov_left,
frames: this.anims.generateFrameNumbers(mov_left, { frames }),
duration,
repeat
});
this.anims.create({
key: 'back_' + mov_down,
frames: this.anims.generateFrameNumbers(mov_down, { frames }),
duration,
repeat
});
this.anims.create({
key: 'back_' + mov_right,
frames: this.anims.generateFrameNumbers(mov_right, { frames }),
duration,
repeat
});
timedEvent = this.time.addEvent({ delay: 1000, callback: moveExecution, callbackScope: this, loop: true });
}
function update() {
const cursors = this.input.keyboard.createCursorKeys();
const enter = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER);
const mouseDown = game.input.mousePointer.isDown || (game.input.touch && game.input.touch.isDown)
|| (game.input.touch && game.input.touch.down) || (game.input.touching && game.input.touching.down)
|| (game.input.activePointer.isDown);
const teclaDown = enter.isDown || cursors.space.isDown || cursors.left.isDown
|| cursors.right.isDown || cursors.down.isDown || cursors.up.isDown;
if (teclaDown || mouseDown) {
playWord();
}
}
function playWord() {
ejecution = true;
}
async function selectMove(moves, contMoves) {
let newMove;
let anims = '';
// solo al girar cambia la orientacion del agente
// console.log("EJECUTANDO: ", moves[contMoves]['move']);
switch (moves[contMoves]['move']) {
case retroceder: {
let dirX = dirAgente.velX ? -dirAgente.velX : 0;
let dirY = dirAgente.velY ? -dirAgente.velY : 0;
newMove = await setAnimsMove(dirX, dirY, 'back_' + dirAgente.orientacion);
}
break;
case avanzar:
newMove = await setAnimsMove(dirAgente.velX, dirAgente.velY, dirAgente.orientacion);
break;
case giro_izquierda:
// sentido inverso a las agujas del reloj
if (dirAgente.orientacion === mov_left) {
anims = 'invert_' + turn_down_left;
//direccion.orientacion = mov_down;
await setOrientacion(mov_down);
} else if (dirAgente.orientacion === mov_down) {
anims = turn_down_right;
await setOrientacion(mov_right);
} else if (dirAgente.orientacion === mov_right) {
anims = 'invert_' + turn_up_right;
await setOrientacion(mov_up);
} else if (dirAgente.orientacion === mov_up) {
anims = turn_up_left;
await setOrientacion(mov_left);
}
console.log(dirAgente);
console.log("anims:", anims);
newMove = await setAnimsMove(0, 0, anims);
break;
case giro_derecha:
// sentido de las agujas del reloj
if (dirAgente.orientacion === mov_left) {
anims = 'invert_' + turn_up_left;
await setOrientacion(mov_up);
} else if (dirAgente.orientacion === mov_up) {
anims = turn_up_right;
await setOrientacion(mov_right);
} else if (dirAgente.orientacion === mov_right) {
anims = 'invert_' + turn_down_right;
await setOrientacion(mov_down);
} else if (dirAgente.orientacion === mov_down) {
await setOrientacion(mov_left);
anims = turn_down_left;
}
newMove = await setAnimsMove(0, 0, anims);
break;
default:
newMove = await setAnimsMove(0, 0, '');
};
// console.log("sprite: ", dirAgente, 'newMove: ', newMove);
return newMove;
}
async function setAnimsMove(dirX = 0, dirY = 0, anims = '') {
const animsMove = {
dirX,
dirY,
anims
};
return animsMove;
}
async function moveExecution() {
if (ejecution) {
const moveUpdated = await selectMove(moves, contMoves); // corregir se podría enviar moves[contMoves]['move'] (1 param)
// console.log("move => ", moveUpdated.dirX, moveUpdated.dirY, moveUpdated.anims);
if (moves[contMoves] && !moves[contMoves]['ejecuted']) {
player.setVelocityX(moveUpdated.dirX);
player.setVelocityY(moveUpdated.dirY);
player.anims.play(moveUpdated.anims, true);
moves[contMoves]['ejecuted'] = true;
contMoves++;
}
ejecution = (contMoves < moves.length);
} else {
// si se ejecutaron todos los movimientos, se detiene el agente
if (contMoves >= moves.length) {
// console.log("JUEGO TERMINADO!!!", contMoves, moves.length);
player.setVelocityX(0);
player.setVelocityY(0);
player.anims.stop();
ejecution = false;
timedEvent.remove(false);
}
}
}
|
module Capistrano
VERSION = "3.8.2".freeze
end
|
# TED-Talks Dataset Setting
SRC=${1?Error: no source language given}
TGT=${2?Error: no target langauge given}
AFFIX=${3?Error: Affix}
gpu=${4}
bpe=${5}
# Download and prepare the data
cd examples/translation/
bash prepare-tedtalks.sh $SRC $TGT $bpe
cd ../..
# Preprocess/binarize the data --> later, will make it language specific
DIR=tedtalks.tokenized.$bpe.$SRC-$TGT
TEXT=examples/translation/$DIR
fairseq-preprocess --source-lang $SRC --target-lang $TGT \
--joined-dictionary \
--trainpref $TEXT/train --validpref $TEXT/valid --testpref $TEXT/test \
--destdir data-bin/$DIR \
--workers 20
# Train on the data
SAVE_DIR=checkpoints/$SRC.$TGT.$AFFIX
mkdir -p $SAVE_DIR
tempdir=$(mktemp -d /tmp/XXXXX)
cp -r data-bin/$DIR $tempdir
CUDA_VISIBLE_DEVICES=$gpu fairseq-train $tempdir/$DIR \
-a transformer_iwslt_de_en --optimizer adam --lr 0.0005 -s $SRC -t $TGT \
--dropout 0.3 --max-tokens 4000 \
--min-lr '1e-09' --lr-scheduler inverse_sqrt --weight-decay 0.0001 \
--criterion cross_entropy --max-update 20000 \
--warmup-updates 4000 --warmup-init-lr '1e-07' \
--adam-betas '(0.9, 0.98)' --save-dir $SAVE_DIR \
--fp16 \
--save-interval-updates 2000 --keep-interval-updates 10 --keep-last-epochs 10
# 40K is now reduced to 10K
#CUDA_VISIBLE_DEVICES=0 fairseq-train \
# data-bin/$DIR \
# --arch transformer_tedtalks --share-decoder-input-output-embed \
# --reset-optimizer \
# --optimizer adam --adam-betas '(0.9, 0.98)' --clip-norm 0.0 \
# --lr 5e-4 --lr-scheduler inverse_sqrt --warmup-updates 4000 \
# --dropout 0.4 --weight-decay 0.0001 \
# --criterion focal_loss \
# --max-tokens 4096 \
# --eval-bleu \
# --eval-bleu-args '{"beam": 5, "max_len_a": 1.2, "max_len_b": 10}' \
# --eval-bleu-detok moses \
# --eval-bleu-remove-bpe \
# --eval-bleu-print-samples \
# --save-dir $SAVE_DIR \
# --best-checkpoint-metric bleu --maximize-best-checkpoint-metric \
# --fp16
# Evaluate the best model
#fairseq-generate data-bin/$DIR \
# --path $SAVE_DIR/checkpoint_best.pt \
# --batch-size 128 --beam 5 --remove-bpe
|
from django.contrib.auth import authenticate, login
from django.shortcuts import render, HttpResponseRedirect, reverse
def login_view(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("dashboard")) # Redirect to the dashboard upon successful login
else:
# Handle invalid login credentials
return render(request, "imageais/login.html", {'error_message': 'Invalid username or password'})
else:
return render(request, "imageais/login.html")
def logout_view(request):
if request.method == "GET":
logout(request)
return HttpResponseRedirect(reverse("index")) |
<reponame>PrincetonUniversity/PMagnet
materials = {
# material => (k_i, alpha, beta)
'3C90': (0.042177, 1.5424, 2.6152),
'3C94': (0.012263, 1.6159, 2.4982),
'3E6': (0.00015324, 1.9098, 2.0903),
'3F4': (0.75798, 1.4146, 3.1455),
'77': (0.053696, 1.5269, 2.519),
'78': (0.016878, 1.609, 2.5432),
'N27': (0.066924, 1.5158, 2.5254),
'N30': (0.0001319, 1.9629, 2.3541),
'N49': (0.13263, 1.4987, 3.2337),
'N87': (0.15178, 1.4722, 2.6147),
}
materials_extra = {
# material => (mu_r_0, f_min, f_max)
'3C90': (2_300, 25_000, 200_000),
'3C94': (2_300, 25_000, 300_000),
'3E6': (10_000, float('nan'), float('nan')),
'3F4': (900, 25_000, 2_000_000),
'77': (2_000, 10_000, 100_000),
'78': (2_300, 25_000, 500_000),
'N27': (2_000, 25_000, 150_000),
'N30': (4_300, 10_000, 400_000),
'N49': (1_500, 300_000, 1_000_000),
'N87': (2_200, 25_000, 500_000),
}
material_manufacturers = {
'3C90': 'Ferroxcube',
'3C94': 'Ferroxcube',
'3E6': 'Ferroxcube',
'3F4': 'Ferroxcube',
'77': 'Fair-Rite',
'78': 'Fair-Rite',
'N27': 'TDK',
'N30': 'TDK',
'N49': 'TDK',
'N87': 'TDK',
}
material_applications = {
'3C90': 'Power and general purpose transformers',
'3C94': 'Power and general purpose transformers',
'3E6': 'Wideband transformers and EMI-suppression filters',
'3F4': 'Power and general purpose transformers',
'77': 'High and low flux density inductive designs',
'78': 'Power applications and low loss inductive applications',
'N27': 'Power transformers',
'N30': 'Broadband transformers',
'N49': 'Power transformers',
'N87': 'Power transformers',
}
material_core_tested = {
'3C90': 'TX-25-15-10',
'3C94': 'TX-20-10-7',
'3E6': 'TX-22-14-6.4',
'3F4': 'E-32-6-20-R',
'77': '5977001401',
'78': '5978007601',
'N27': 'R20.0X10.0X7.0',
'N30': 'R22.1X13.7X6.35',
'N49': 'R16.0X9.6X6.3',
'N87': 'R22.1X13.7X7.9',
}
material_names = list(materials.keys())
excitations_db = ('Datasheet', 'Sinusoidal', 'Triangular', 'Trapezoidal')
excitations_download = ('Sinusoidal', 'Triangular', 'Trapezoidal')
excitations_predict = ('Sinusoidal', 'Triangular', 'Trapezoidal', 'Arbitrary')
|
package org.rudogma.bytownite.decoders
import java.nio.charset.Charset
import org.rudogma.bytownite.Nullable
class StringDecoder(charset: Charset) extends Decoder[String] with HeaderBasedDecoder[String] with Nullable {
override def decodeBody(bytes: Array[Byte]) = new String(bytes, charset)
}
object StringDecoder {
implicit val UTF8:Decoder[String] = new StringDecoder(Charset.forName("UTF-8"))
}
|
import { __extends } from "tslib";
import { registerPlotType } from '../../base/global';
import { getGeom } from '../../geoms/factory';
import TinyLayer from '../tiny-layer';
import * as EventParser from './event';
var GEOM_MAP = {
line: 'line',
};
var TinyLineLayer = /** @class */ (function (_super) {
__extends(TinyLineLayer, _super);
function TinyLineLayer() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = 'tinyLine';
return _this;
}
TinyLineLayer.prototype.geometryParser = function (dim, type) {
return GEOM_MAP[type];
};
TinyLineLayer.prototype.addGeometry = function () {
this.line = getGeom('line', 'mini', {
plot: this,
});
this.setConfig('geometry', this.line);
};
TinyLineLayer.prototype.parseEvents = function () {
_super.prototype.parseEvents.call(this, EventParser);
};
return TinyLineLayer;
}(TinyLayer));
export default TinyLineLayer;
registerPlotType('tinyLine', TinyLineLayer);
//# sourceMappingURL=layer.js.map |
<reponame>vharsh/cattle2
package io.cattle.platform.allocator.constraint;
import io.cattle.platform.allocator.port.PortManager;
import io.cattle.platform.allocator.service.AllocationCandidate;
import io.cattle.platform.core.util.PortSpec;
import java.util.List;
public class PortsConstraint extends HardConstraint implements Constraint {
List<PortSpec> ports;
PortManager portManager;
long instanceId;
public PortsConstraint(long instanceId, List<PortSpec> ports, PortManager portManager) {
this.ports = ports;
this.instanceId = instanceId;
this.portManager = portManager;
}
@Override
public boolean matches(AllocationCandidate candidate) {
if (candidate.getHost() == null) {
return false;
}
return portManager.portsFree(candidate.getClusterId(), candidate.getHost(), ports);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (PortSpec port: ports) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(port.getPublicPort());
sb.append("/");
sb.append(port.getProtocol());
}
return String.format("host needs ports %s available", sb.toString());
}
}
|
# This shell script executes Slurm jobs for thresholding
# predictions of NTT-like convolutional
# neural network on BirdVox-70k full audio
# with logmelspec input.
# Augmentation kind: none.
# Test unit: unit05.
# Trial ID: 5.
sbatch 042_aug-none_test-unit05_predict-unit05_trial-5.sbatch
sbatch 042_aug-none_test-unit05_predict-unit02_trial-5.sbatch
sbatch 042_aug-none_test-unit05_predict-unit03_trial-5.sbatch
|
#!/bin/tcsh
source ${PULP_PATH}/vsim/vcompile/colors.csh
##############################################################################
# Settings
##############################################################################
set IP=pulpino
set IP_NAME="PULPino"
##############################################################################
# Check settings
##############################################################################
# check if environment variables are defined
if (! $?MSIM_LIBS_PATH ) then
echo "${Red} MSIM_LIBS_PATH is not defined ${NC}"
exit 1
endif
if (! $?RTL_PATH ) then
echo "${Red} RTL_PATH is not defined ${NC}"
exit 1
endif
set LIB_NAME="${IP}_lib"
set LIB_PATH="${MSIM_LIBS_PATH}/${LIB_NAME}"
##############################################################################
# Preparing library
##############################################################################
echo "${Green}--> Compiling ${IP_NAME}... ${NC}"
rm -rf $LIB_PATH
vlib $LIB_PATH
vmap $LIB_NAME $LIB_PATH
echo "${Green}Compiling component: ${Brown} ${IP_NAME} ${NC}"
echo "${Red}"
##############################################################################
# Compiling RTL
##############################################################################
# decide if we want to build for riscv or or1k
if ( ! $?PULP_CORE) then
set PULP_CORE="riscv"
endif
if ( $PULP_CORE == "riscv" ) then
set CORE_DEFINES=+define+RISCV
echo "${Yellow} Compiling for RISCV core ${NC}"
else
set CORE_DEFINES=+define+OR10N
echo "${Yellow} Compiling for OR10N core ${NC}"
endif
# decide if we want to build for riscv or or1k
if ( ! $?ASIC_DEFINES) then
set ASIC_DEFINES=""
endif
# components
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/cluster_clock_gating.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/pulp_clock_gating.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/cluster_clock_inverter.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/cluster_clock_mux2.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/pulp_clock_inverter.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/pulp_clock_mux2.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/generic_fifo.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/rstgen.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} ${RTL_PATH}/components/sp_ram.sv || goto error
# files depending on RISCV vs. OR1K
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/core_region.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/random_stalls.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/boot_rom_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/boot_code.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/instr_ram_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/sp_ram_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/ram_mux.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/axi_node_intf_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/pulpino_top.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/peripherals.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/periph_bus_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/axi2apb_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/axi_spi_slave_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/axi_mem_if_SP_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/clk_rst_gen.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/axi_slice_wrap.sv || goto error
vlog -quiet -sv -work ${LIB_PATH} +incdir+${RTL_PATH}/includes ${ASIC_DEFINES} ${CORE_DEFINES} ${RTL_PATH}/core2axi_wrap.sv || goto error
echo "${Cyan}--> ${IP_NAME} compilation complete! ${NC}"
exit 0
##############################################################################
# Error handler
##############################################################################
error:
echo "${NC}"
exit 1
|
<html>
<head>
<title>URL Validator</title>
</head>
<body>
<form action="validateUrl.php" method="POST">
<input type="text" name="url" placeholder="Enter URL" />
<input type="submit" value="Validate" />
</form>
<div id="output"></div>
</body>
</html>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const inputUrl = form.querySelector('input[name="url"]').value;
const xhr = new XMLHttpRequest();
xhr.open('POST', form.getAttribute('action'));
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function () {
document.querySelector('#output').innerText = xhr.responseText;
}
xhr.send('url=' + inputUrl);
});
</script> |
//PARAMETROS ADICIONAIS NO N1 IMPEDEM DE CASO NAO POR UM DOS PARAMETROS RETORNAR O VALOR
function soma (n1=0,n2=0) {
return n1 + n2
}
//EXEMPLO DE APENAS UM PARAMETRO INFORMADO
console.log(soma(2)) |
#!/bin/bash
browserify --insert-globals -t brfs fontkit-browserify.js -o fontkit.js
browserify --insert-globals jspdf-browserify.js -o jspdf.js
|
#!/usr/bin/env python
#
# -*- coding: utf-8 -*-
#
# file: hos_utils.py
# created: 2014/10/10 <NAME> <<EMAIL>'at'<EMAIL>>
# Copyright (C) 2014 <NAME>
# See LICENSE for details
#
# purpose: Plotting accuracy analyses of different Central Difference
# advection schemes implemented in a NWP and RCM model
# usage: "python schemes.py" from shell or via
# "./hosanalytics.py" after making this script executable
##
# Attributes: hosFunctions
# (a) Phase errors:
# omegaSeond =>Symmetric Second order (QCHOS)
# omegaSecondTrad =>Traditional Second order (HOS)
# omegaFourth =>Symmetric Fourth order (QCHOS)
# omegaFourthTrad =>Traditional Fourth order (HOS)
# omegaSixth =>Symmetric Sixth order (QCHOS)
# omegaSixthTrad =>Traditional Sixth order (HOS)
# (b) Group velocities
# groupVSeond =>Symmetric Second order (QCHOS)
# groupVSecondTrad =>Traditional Second order (HOS)
# groupVFourth =>Symmetric Fourth order (QCHOS)
# groupVFourthTrad =>Traditional Fourth order (HOS)
# groupVSixth =>Symmetric Sixth order (QCHOS)
# groupVSixthTrad =>Traditional Sixth order (HOS)
#--------------------------------------------------------------#
# >> modules
from __future__ import absolute_import
import numpy as np
import math as mt
#--- The following can be bundled into a config file ---#
import os, sys, inspect
libPath = os.path.abspath('hosUtilities')
sys.path.append(libPath)
#------------------------#
import hosFunctions as hf
import hosGraphics as hg
#----------------------------------------------------------------------------80
# >> defintions
#---- Wavenumber ----#
c=10.
dx=2.
k=np.linspace(0.00095,np.pi/dx,50)
#--alias Error settings---#
#m=np.pi/dx
#m=8.*np.pi/9./dx
#m=3.*np.pi/4./dx
m=np.pi/2./dx
#m=np.pi/20./dx
k2=np.linspace(-np.pi/dx,np.pi/dx,100)
k1=np.linspace(-np.pi/dx,np.pi/dx,100)
#+++k1=m-k2
k3=k1+k2
kmax=np.pi/dx
if m >= 0.0:
b=k1-kmax
#b=m-kmax
else:
b=k1+kmax
b=m+kmax
print(' K3[4] = {0}, K3[83] = {1}'.format(k3[4],k3[83]))
kt=[]
for i in range(len(k3)):
if k3[i] > kmax:
kt.append(-2.0*kmax + k3[i])
if k3[i] < -kmax:
kt.append(2.0*kmax + k3[i])
print('LEN(KT) = {0}'.format(len(kt)))
print(kt)
#--------------------------#
#+============================+#
# Error objects and instances +#
#+============================+#
hos = hf.hosSymbolic()
hos.dx = dx
hos.c = c
hos1 = hos.PhaseError(k)
hos2 = hos.GroupVelocity(k)
hos3 = hos.aliasError(k1,k2)
#+--------------+#
(oSec,oSecTrad,oFourth,oFourthTrad,oSixth,oSixthTrad) = hos1
(vSec,vSecTrad,vFourth,vFourthTrad,vSixth,vSixthTrad) = hos2
(aSec,aSecTrad,aThird,aFou,aFouTrad,aFifth,aSix,aSixTrad)\
=[abs(scheme) for scheme in hos3]
#hos4\
# = [hos.aliasError(k1[i],k2)
# for i in range(len(k1))]
#(aSec2d,aSecTrad2d,aThird2d,aFou2d,aFouTrad2d,
# aFifth2d,aSix2d,aSixTrad2d)\
# =[[hos4[m][n] for m in range(len(k1))]
# for n in range(len(hos4[0]))]
hos4\
= [hos.aliasError(kt[i],k2)
for i in range(len(kt))]
(aSec2d,aSecTrad2d,aThird2d,aFou2d,aFouTrad2d,
aFifth2d,aSix2d,aSixTrad2d)\
=[[hos4[m][n] for m in range(len(kt))]
for n in range(len(hos4[0]))]
bp=[[b[i][j] for i in range(len(kt))] for j in range(len(k2))]
#+=================================+#
#+ Plots of the analytic functions +#
#+=================================+#
#-- Plot settings/Attributes---#
plt = hg.hosPlot() # call the plot utility
plt.title='Test plot'
plt.styles = ['b-.','r--','k+'] #['b-.','r--','k+','kx','g-','k:']
#plt.lwidth=[2,2,2,2,2]
plt.labels = ['2nd order']
plt.savePlot= True
plt.plotName= 'MyPlot'
plt.plotDir = 'Dietz' # Folder in the cwd
#plt.legLoc = 'lower center' # Legend location
plt.lblsize = 14
plt.ttlsize = 16
plt.minorticks=True
plt.lgframe=True
plt.lgFontSize=12
#plt.ymax=0.14
#plt.xmax=0.14
plt.ylabel='Effecitve wavenumber $k_{eff}$'
plt.xlabel='wave number $k$'
#plt.vline=True
#plt.hline=True
#plt.plotLine(k,oSec,oFourth,oFourthTrad,oSixth,oSixthTrad,refLine=(k,'Toto'))
plt2=plt
plt2.title='You Know'
#plt2.ymax=13.
#plt2.ymin=-23.
plt2.plotName='MyPlot2'
plt2.lwidth=[2,2,2,2,2]
#plt2.plotLine(k,vSec,vFourth,vFourthTrad,vSixth,vSixthTrad,hLine=(c,'Babe'))
plt3=plt
plt3.savePlot=False
plt3.lwidth=[]
#plt3.xmin=-np.pi/dx
#plt3.xmax=np.pi/dx
#plt3.plotLine(k2,aSec,aSecTrad,aThird,aFou,aFouTrad,aFifth,
# aSix,aSixTrad,hLine=0.0,refLine=(abs(k2),'refline'))
#print(aSec2d)
#print(aThird2d)
plt4=plt
plt4.plotContour(k2,kt,aSec2d)
plt4.plotContour(k2,kt,bp)
#==== Some test =====
#plt5=plt
#plt5.testContour()
|
<filename>isomorfeus-data/lib/data_uri/uri.rb
module URI
class Data < Generic
COMPONENT = [:scheme, :opaque].freeze
MIME_TYPE_RE = %r{^([-\w.+]+/[-\w.+]*)}.freeze
MIME_PARAM_RE = /^;([-\w.+]+)=([^;,]+)/.freeze
attr_reader :content_type, :data
def initialize(*args)
if args.length == 1
uri = args.first.to_s
unless uri.match(/^data:/)
raise URI::InvalidURIError.new('Invalid Data URI: ' + args.first.inspect)
end
@scheme = 'data'
@opaque = uri[5 .. -1]
else
super(*args)
end
@data = @opaque
if md = MIME_TYPE_RE.match(@data)
@content_type = md[1]
@data = @data[@content_type.length .. -1]
end
@content_type ||= 'text/plain'
@mime_params = {}
while md = MIME_PARAM_RE.match(@data)
@mime_params[md[1]] = md[2]
@data = @data[md[0].length .. -1]
end
if base64 = /^;base64/.match(@data)
@data = @data[7 .. -1]
end
unless /^,/.match(@data)
raise URI::InvalidURIError.new('Invalid data URI')
end
@data = @data[1 .. -1]
@data = base64 ? Base64.decode64(@data) : URI.decode(@data)
if @data.respond_to?(:force_encoding) && charset = @mime_params['charset']
@data.force_encoding(charset)
end
end
def self.build(arg)
data = nil
content_type = nil
case arg
when IO
data = arg
when Hash
data = arg[:data]
content_type = arg[:content_type]
end
raise 'Invalid build argument: ' + arg.inspect unless data
if !content_type && data.respond_to?(:content_type)
content_type = data.content_type
end
new('data', nil, nil, nil, nil, nil, "#{content_type};base64,#{Base64.encode64(data.read).chop}", nil, nil)
end
end
end
|
<filename>src/Screens/Invoices.js
import React, { useState, useEffect, useContext } from "react";
import { getPaymentRequestByCompanyId } from "../API/Plans";
import { useSelector } from "react-redux";
import { balanceSvg } from "Assets";
import UserContext from "Context/UserContext";
import { CustomError } from "./Toasts";
import NoData from "Components/NoData";
import {
Head,
PaymentDetailsEntry,
PaymentDetailsHeader,
DashboardHeading,
} from "Components";
export default function Invoices({ setIsInvoiceOpen }) {
const user = useContext(UserContext);
const { company } = useSelector((state) => state.company);
const [isLoading, setIsLoading] = useState(true);
const [isPaymentHistoryShown, setIsPaymentHistoryShown] = useState(true);
const [paymentHistoryData, setPaymentHistoryData] = useState([]);
useEffect(() => {
getPaymentRequest();
}, []);
const getPaymentRequest = () => {
setIsLoading(true);
getPaymentRequestByCompanyId(user.CompanyId)
.then(({ data }) => {
console.log("data", data);
if (data.success) setPaymentHistoryData(data.result);
else CustomError("Some error occured.");
setIsLoading(false);
})
.catch((err) => {
console.log("err", err);
CustomError("Some error occured.");
setIsLoading(false);
});
};
return (
<>
<Head title="AIDApro | Balance" description="Balance" />
<section className="plans__container">
<DashboardHeading heading="Invoices" svg={balanceSvg} />
{isPaymentHistoryShown ? (
<div className="payment__details__container__entry__wrapper animate__animated animate__fadeIn">
<div className="payment__details__container__entry__content">
<PaymentDetailsHeader />
{paymentHistoryData.length === 0 ? (
<NoData />
) : (
paymentHistoryData.map((paymentHistoryDataEntry, i) => (
<PaymentDetailsEntry
key={i}
ReceiptsList={paymentHistoryDataEntry.TransactionId}
Status={paymentHistoryDataEntry.Status}
Total={paymentHistoryDataEntry.Description}
CreatedAt={paymentHistoryDataEntry.CreatedOn}
PaidAt={paymentHistoryDataEntry.CreatedOn}
setIsInvoiceOpen={setIsInvoiceOpen}
/>
))
)}
</div>
</div>
) : null}
</section>
</>
);
}
|
package com.misakiga.husky.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication(scanBasePackageClasses = ProviderAdminLoginLogBootstrap.class)
@MapperScan(basePackages = "com.misakiga.husky.provider.mapper")
public class ProviderAdminLoginLogBootstrap {
public static void main(String[] args) {
SpringApplication.run(ProviderAdminLoginLogBootstrap.class,args);
}
}
|
package com.github.chen0040.leetcode.day16.medium;
import java.util.HashMap;
/**
* Created by xschen on 11/8/2017.
*
* link: https://leetcode.com/problems/fraction-to-recurring-decimal/description/
*/
public class FractionToRecurring {
public class Solution {
public String fractionToDecimal(int num, int denom) {
long numerator = num;
long denominator = denom;
boolean diffSign = numerator * denominator < 0;
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
long whole_part = numerator / denominator;
long dec_part = numerator % denominator;
StringBuilder sb = new StringBuilder();
sb.append(whole_part);
long prev = -1;
HashMap<Long, Integer> dec_pat = new HashMap<Long, Integer>();
dec_pat.put(dec_part, 0);
int d = 0;
int duplicate_count = 0;
while(dec_part > 0) {
long digit = (dec_part * 10) / denominator;
if(prev == -1) {
sb.append(".");
} else {
sb.append(prev);
}
long new_dec_part = (dec_part * 10) % denominator;
prev = digit;
d++;
if(dec_pat.containsKey(new_dec_part)) {
duplicate_count = d - dec_pat.get(new_dec_part);
break;
} else {
dec_part = new_dec_part;
dec_pat.put(dec_part, d);
}
}
if(prev != -1) {
sb.append(prev);
}
String s = sb.toString();
if(duplicate_count > 0) {
s = s.substring(0, s.length()-duplicate_count) + "(" + s.substring(s.length()-duplicate_count) + ")";
}
if(diffSign) {
return "-" + s;
}
return s;
}
}
}
|
#!/bin/sh
umask 0002
# Copy settings.py (settings.py copied to allow for legacy installs and customizations)
cd /app
TARGET_SETTINGS_FILE=dojo/settings/settings.py
if [ ! -f ${TARGET_SETTINGS_FILE} ]; then
echo "Creating settings.py"
cp dojo/settings/settings.dist.py dojo/settings/settings.py
fi
while ping -c1 initializer 1>/dev/null 2>/dev/null
do {
echo "Waiting for initializer to complete"
sleep 3
}
done;
echo "Starting DefectDojo: http://localhost:8000"
python manage.py runserver 0.0.0.0:8000 |
#!/bin/bash
set -eu
# @description Install item assets
#
# @example
# assets-install
#
# @arg $1 Task: "brief", "help" or "exec"
#
# @exitcode The result of the assets installation
#
# @stdout "Not implemented" message if the requested task is not implemented
#
function assets-install() {
# Init
local briefMessage
local helpMessage
briefMessage="Install assets"
helpMessage=$(cat <<EOF
Install nginx product assets:
* Create the "data/passbolt/config/gpg" and "data/var/www/passbolt/webroot/img/public" directories with all permissions (777)
* Create the network "platform_services"
EOF
)
# Task choosing
case $1 in
brief)
showBriefMessage "${FUNCNAME[0]}" "$briefMessage"
;;
help)
showHelpMessage "${FUNCNAME[0]}" "$helpMessage"
;;
exec)
# Create network
if [ "$(docker network ls -f name='platform_services' -q)" == "" ]; then
echo -n "- Creating docker network 'platform_services' ..."
docker network create platform_services
echo "[OK]"
else
echo "The 'platform_services' docker network already exists, skipping"
fi
# Create directories
for directory in data \
data/passbolt data/passbolt/config data/passbolt/config data/passbolt/config/gpg \
data/var data/var/www data/var/www/passbolt data/var/www/passbolt/webroot data/var/www/passbolt/webroot/img data/var/www/passbolt/webroot/img/public
do
if [ ! -d ${directory} ]; then
echo -n "- Creating '${directory}' directory..."
mkdir ${directory}
echo "[OK]"
echo -n "- Setting '${directory}' permissions..."
chmod 777 ${directory}
echo "[OK]"
else
echo "The '${directory}' directory already exists, skipping"
fi
done
;;
*)
showNotImplemtedMessage "$1" "${FUNCNAME[0]}"
return 1
esac
}
# Main
assets-install "$@"
|
<reponame>sraashis/coinstac
const { populate } = require('./populate');
populate();
|
/*******************************************************************************
Copyright (c) 2017, Honda Research Institute Europe GmbH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <Rcs_macros.h>
#include <Rcs_cmdLine.h>
#include <Rcs_resourcePath.h>
#include <Rcs_timer.h>
#include <Rcs_typedef.h>
#include <Rcs_math.h>
#include <IkSolverRMR.h>
#include <PhysicsNode.h>
#include <HUD.h>
#include <KeyCatcher.h>
#include <RcsViewer.h>
#include <Rcs_guiFactory.h>
#include <ControllerWidgetBase.h>
#include <SegFaultHandler.h>
#include <pthread.h>
#include <csignal>
RCS_INSTALL_ERRORHANDLERS
bool runLoop = true;
/*******************************************************************************
* Ctrl-C destructor. Tries to quit gracefully with the first Ctrl-C
* press, then just exits.
******************************************************************************/
void quit(int /*sig*/)
{
static int kHit = 0;
runLoop = false;
fprintf(stderr, "Trying to exit gracefully - %dst attempt\n", kHit + 1);
kHit++;
if (kHit == 2)
{
fprintf(stderr, "Exiting without cleanup\n");
exit(0);
}
}
/*******************************************************************************
*
******************************************************************************/
static inline double computeBlendingPolynomial(double s)
{
s = Math_clip(s, 0.0, 1.0);
return 6.0*pow(s,5) - 15.0*pow(s, 4) + 10.0*pow(s, 3);
}
/*******************************************************************************
*
******************************************************************************/
static void testBlendingLeftInverse(int argc, char** argv)
{
// Parse command line arguments
size_t nSteps = 600;
double alpha = 0.05, lambda = 1.0e-8, dt = 0.01;
std::string blending = "Binary";
std::string xmlFileName = "cPlanarArm7D.xml";
std::string directory = "config/xml/Examples";
Rcs::CmdLineParser argP(argc, argv);
argP.getArgument("-f", &xmlFileName, "Configuration file name");
argP.getArgument("-dir", &directory, "Configuration file directory");
argP.getArgument("-blending", &blending, "Blending mode (default is %s)",
blending.c_str());
argP.getArgument("-alpha", &alpha,
"Null space scaling factor (default is %f)", alpha);
argP.getArgument("-lambda", &lambda, "Regularization (default is %f)",
lambda);
argP.getArgument("-nSteps", &nSteps, "Number of computation steps (default"
" is %d)", nSteps);
bool randomizeQ0 = argP.hasArgument("-randomize");
Rcs_addResourcePath("config");
Rcs_addResourcePath(directory.c_str());
// Initialize mutex that takes care that Gui, viewer and control loop can
// run concurrently.
pthread_mutex_t mtx;
pthread_mutex_init(&mtx, NULL);
// Create controller and Inverse Kinematics solver
Rcs::ControllerBase controller(xmlFileName);
if (randomizeQ0)
{
MatNd_setRandom(controller.getGraph()->q, -M_PI, M_PI);
RcsGraph_setState(controller.getGraph(), NULL, NULL);
}
Rcs::IkSolverRMR ikSolver(&controller);
bool success = ikSolver.setActivationBlending(blending);
RCHECK(success);
MatNd* dq_des = MatNd_create(controller.getGraph()->dof, 1);
MatNd* a_des = MatNd_create(controller.getNumberOfTasks(), 1);
MatNd* a_blend = MatNd_create(controller.getNumberOfTasks(), 1);
MatNd* x_curr = MatNd_create(controller.getTaskDim(), 1);
MatNd* x_des = MatNd_create(controller.getTaskDim(), 1);
MatNd* dx_des = MatNd_create(controller.getTaskDim(), 1);
MatNd* dH = MatNd_create(1, controller.getGraph()->nJ);
MatNd_setElementsTo(dx_des, 1.0);
MatNd* plotMat = MatNd_create(nSteps, 3+7+2);
plotMat->m = 0;
// We assign the values from the xml file to the activation vector. If a
// task is tagged with active="true", the activation is 1, otherwise 0.
controller.readActivationsFromXML(a_des);
MatNd_setZero(a_des);
MatNd_setZero(a_blend);
// Computes the task kinematics for the current configuration of the model.
// We initialize it before the Gui is created, so that the sliders will be
// initialized with the actual values of our model.
controller.computeX(x_curr);
MatNd_copy(x_des, x_curr);
// Launch the task widget in its own thread. The Gui will
// only write to the arrays if it can grab the mutex.
// Rcs::ControllerWidgetBase::create(&controller, a_des, x_des, x_curr, &mtx);
// while (runLoop == true)
for (size_t i=0; i<nSteps; ++i)
{
//pthread_mutex_lock(&mtx);
//controller.computeDX(dx_des, x_des);
// controller.computeJointlimitGradient(dH);
// MatNd_constMulSelf(dH, alpha);
ikSolver.solveLeftInverse(dq_des, dx_des, dH, a_blend, lambda);
// MatNd_addSelf(controller.getGraph()->q, dq_des);
// RcsGraph_setState(controller.getGraph(), NULL, NULL);
// controller.computeX(x_curr);
//pthread_mutex_unlock(&mtx);
// MatNd_printCommentDigits("dq", dq_des, 6);
// This outputs some information text in the HUD.
// sprintf(hudText, "dof: %d nJ: %d nx: %zu lambda:%g alpha: %g\n"
// "Control is %s",
// controller.getGraph()->dof, controller.getGraph()->nJ,
// controller.getActiveTaskDim(a_des), lambda, alpha,
// ffwd ? "feed-forward" : "feed-back");
// hud->setText(hudText);
if (i<100)
{
a_des->ele[0] = Math_clip(a_des->ele[0]+dt, 0.0, 1.0);
}
if (i>=200 && i<300)
{
a_des->ele[0] = Math_clip(a_des->ele[0]-dt, 0.0, 1.0);
a_des->ele[1] = Math_clip(a_des->ele[1]+dt, 0.0, 1.0);
}
if (i>=400 && i<500)
{
a_des->ele[0] = Math_clip(a_des->ele[0]+dt, 0.0, 1.0);
a_des->ele[1] = Math_clip(a_des->ele[1]-dt, 0.0, 1.0);
}
a_blend->ele[0] = computeBlendingPolynomial(a_des->ele[0]);
a_blend->ele[1] = computeBlendingPolynomial(a_des->ele[1]);
plotMat->m++;
double* row = MatNd_getRowPtr(plotMat, plotMat->m-1);
row[0] = i*dt;
row[1] = a_blend->ele[0];
row[2] = a_blend->ele[1];
VecNd_copy(&row[3], dq_des->ele, 7);
row[10] = VecNd_mean(ikSolver.getCurrentActivation()->ele, 3);
row[11] = VecNd_mean(&ikSolver.getCurrentActivation()->ele[3], 7);
}
MatNd_toFile(plotMat, "blending.dat");
const char* gpCmd = "plot \"blending.dat\" u 1:2 w l title \"a1\", \"blending.dat\" u 1:3 w l title \"a2\", \"blending.dat\" u 1:4 w lp title \"qp1\", \"blending.dat\" u 1:5 w lp title \"qp2\", \"blending.dat\" u 1:6 w lp title \"qp3\", \"blending.dat\" u 1:7 w lp title \"qp4\", \"blending.dat\" u 1:8 w lp title \"qp5\", \"blending.dat\" u 1:9 w lp title \"qp6\", \"blending.dat\" u 1:10 w lp title \"qp7\"";
RLOG(0, "Gnuplot command 1:\n\n%s", gpCmd);
gpCmd = "plot \"blending.dat\" u 1:2 w l title \"a1\", \"blending.dat\" u 1:3 w l title \"a2\", \"blending.dat\" u 1:11 w lp title \"a_{1,curr}\", \"blending.dat\" u 1:12 w lp title \"a_{2,curr}\"";
RLOG(0, "Gnuplot command 2:\n\n%s", gpCmd);
// Clean up
MatNd_destroy(dq_des);
MatNd_destroy(a_des);
MatNd_destroy(a_blend);
MatNd_destroy(x_des);
MatNd_destroy(dx_des);
MatNd_destroy(dH);
MatNd_destroy(plotMat);
RcsGuiFactory_shutdown();
xmlCleanupParser();
pthread_mutex_destroy(&mtx);
}
/*******************************************************************************
*
******************************************************************************/
int main(int argc, char** argv)
{
RMSG("Starting Rcs...");
int mode = 0;
// Ctrl-C callback handler
signal(SIGINT, quit);
// This initialize the xml library and check potential mismatches between
// the version it was compiled for and the actual shared library used.
LIBXML_TEST_VERSION;
// Parse command line arguments
Rcs::CmdLineParser argP(argc, argv);
argP.getArgument("-dl", &RcsLogLevel, "Debug level (default is 0)");
argP.getArgument("-m", &mode, "Test mode");
Rcs_addResourcePath("config");
switch (mode)
{
// ==============================================================
// Just print out some global information
// ==============================================================
case 0:
{
argP.print();
printf("\nHere's some useful testing modes:\n\n");
printf("\t-m");
printf("\t0 Print this message\n");
printf("\t\t1 Test blending with left inverse\n");
break;
}
case 1:
{
testBlendingLeftInverse(argc, argv);
break;
}
// ==============================================================
// That's it.
// ==============================================================
default:
{
RMSG("there is no mode %d", mode);
}
} // switch(mode)
if ((mode!=0) && argP.hasArgument("-h", "Show help message"))
{
Rcs::KeyCatcherBase::printRegisteredKeys();
argP.print();
Rcs_printResourcePath();
}
xmlCleanupParser();
fprintf(stderr, "Thanks for using the TestTasks program\n");
return 0;
}
|
package chylex.hee.world.structure.island.biome.feature.forest.ravageddungeon;
// TODO update stuff
public final class RavagedDungeonPlacer/* implements ITileEntityGenerator*/{
//private static final byte radEntrance = 2, radHallway = 2, radRoom = 7;
/*private final byte hallHeight;
private byte level;
public RavagedDungeonPlacer(int hallHeight){
this.hallHeight = (byte)hallHeight;
}
public void setDungeonLevel(int level){
this.level = (byte)level;
}*/
/*
* ENTRANCE
*/
/*public void generateEntrance(LargeStructureWorld world, Random rand, int x, int y, int z, int maxEntranceHeight, DungeonElement entrance){
int surfaceY = y-maxEntranceHeight-1;
while(++surfaceY <= y){
if (world.getBlock(x, surfaceY, z) == IslandBiomeBase.getTopBlock())break;
}
for(int yy = surfaceY+5; yy >= y-maxEntranceHeight; yy--){
for(int xx = x-radEntrance; xx <= x+radEntrance; xx++){
for(int zz = z-radEntrance; zz <= z+radEntrance; zz++){
if (yy > surfaceY || (Math.abs(xx-x) <= radEntrance-1 && Math.abs(zz-z) <= radEntrance-1 && yy != y-maxEntranceHeight))world.setBlock(xx, yy, zz, Blocks.air);
else world.setBlock(xx, yy, zz, BlockList.ravaged_brick, getBrickMeta(rand));
}
}
}
}*/
/*
* DESCEND
*/
/*private enum EnumDescendDesign{
PILLARS_WITH_SPAWNER, GOO_CORNERS, FENCE_LIGHTS, CORNER_LIGHTS
}
private static final WeightedMap<EnumDescendDesign> descendDesignList = new WeightedMap<>(EnumDescendDesign.values().length, map -> {
map.add(EnumDescendDesign.PILLARS_WITH_SPAWNER, 50);
map.add(EnumDescendDesign.FENCE_LIGHTS, 42);
map.add(EnumDescendDesign.GOO_CORNERS, 35);
map.add(EnumDescendDesign.CORNER_LIGHTS, 25);
});*/
/*public void generateDescend(LargeStructureWorld world, Random rand, int x, int y, int z, DungeonElement descend){
generateRoomLayout(world, rand, x, y, z);
Block coverBlock = rand.nextInt(3) == 0 ? Blocks.glass : Blocks.air;
for(int yy = y; yy >= y-hallHeight-2; yy--){
for(int xx = x-radEntrance; xx <= x+radEntrance; xx++){
for(int zz = z-radEntrance; zz <= z+radEntrance; zz++){
if (Math.abs(xx-x) <= 1 && Math.abs(zz-z) <= radEntrance-1 && yy != y-hallHeight-2)world.setBlock(xx, yy, zz, yy == y ? coverBlock : Blocks.air);
else world.setBlock(xx, yy, zz, BlockList.ravaged_brick, getBrickMeta(rand));
}
}
}
boolean hasGenerated = false;
while(!hasGenerated){
hasGenerated = true;
EnumDescendDesign design = descendDesignList.getRandomItem(rand).getObject();
switch(design){
case PILLARS_WITH_SPAWNER:
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
for(int py = 0; py < hallHeight-1; py++){
world.setBlock(x-4+8*a, y+1+py, z-4+8*b, py == 2 ? BlockList.ravaged_brick_glow : BlockList.ravaged_brick);
}
}
}
world.setBlock(x, y+hallHeight, z, BlockList.ravaged_brick);
world.setBlock(x, y+hallHeight-1, z, BlockList.custom_spawner, 2);
world.setTileEntityGenerator(x, y+hallHeight-1, z, "louseSpawner", this);
break;
case GOO_CORNERS:
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
world.setBlock(x-6+12*a, y+1, z-6+12*b, BlockList.ender_goo);
world.setBlock(x-5+10*a, y+1, z-6+12*b, BlockList.ender_goo);
world.setBlock(x-4+8*a, y+1, z-6+12*b, BlockList.ender_goo);
world.setBlock(x-6+12*a, y+1, z-5+10*b, BlockList.ender_goo);
world.setBlock(x-6+12*a, y+1, z-4+8*b, BlockList.ender_goo);
world.setBlock(x-6+12*a, y+1, z-3+6*b, BlockList.ravaged_brick);
world.setBlock(x-6+12*a, y+2, z-3+6*b, BlockList.ravaged_brick);
world.setBlock(x-6+12*a, y+3, z-3+6*b, BlockList.ravaged_brick_glow);
world.setBlock(x-6+12*a, y+4, z-3+6*b, BlockList.ravaged_brick);
world.setBlock(x-3+6*a, y+1, z-6+12*b, BlockList.ravaged_brick);
world.setBlock(x-3+6*a, y+2, z-6+12*b, BlockList.ravaged_brick);
world.setBlock(x-3+6*a, y+3, z-6+12*b, BlockList.ravaged_brick_glow);
world.setBlock(x-3+6*a, y+4, z-6+12*b, BlockList.ravaged_brick);
world.setBlock(x-5+10*a, y+1, z-5+10*b, BlockList.ravaged_brick);
world.setBlock(x-4+8*a, y+1, z-5+10*b, BlockList.ravaged_brick);
world.setBlock(x-3+6*a, y+1, z-5+10*b, BlockList.ravaged_brick);
world.setBlock(x-5+10*a, y+1, z-4+8*b, BlockList.ravaged_brick);
world.setBlock(x-5+10*a, y+1, z-3+6*b, BlockList.ravaged_brick);
world.setBlock(x-4+8*a, y+1, z-4+8*b, BlockList.ravaged_brick_slab);
world.setBlock(x-3+6*a, y+1, z-4+8*b, BlockList.ravaged_brick_slab);
world.setBlock(x-2+4*a, y+1, z-4+8*b, BlockList.ravaged_brick_slab);
world.setBlock(x-4+8*a, y+1, z-3+6*b, BlockList.ravaged_brick_slab);
world.setBlock(x-4+8*a, y+1, z-2+4*b, BlockList.ravaged_brick_slab);
world.setBlock(x-2+4*a, y+1, z-5+10*b, BlockList.ravaged_brick_slab);
world.setBlock(x-2+4*a, y+1, z-6+12*b, BlockList.ravaged_brick_slab);
world.setBlock(x-5+10*a, y+1, z-2+4*b, BlockList.ravaged_brick_slab);
world.setBlock(x-6+12*a, y+1, z-2+4*b, BlockList.ravaged_brick_slab);
}
}
break;
case FENCE_LIGHTS:
int xx, zz;
xx = x-5+rand.nextInt(4);
zz = z-5+rand.nextInt(4);
world.setBlock(xx, y+hallHeight, zz, BlockList.ravaged_brick_fence);
world.setBlock(xx, y+hallHeight-1, zz, BlockList.ravaged_brick_glow);
xx = x+5-rand.nextInt(4);
zz = z-5+rand.nextInt(4);
world.setBlock(xx, y+hallHeight, zz, BlockList.ravaged_brick_fence);
world.setBlock(xx, y+hallHeight-1, zz, BlockList.ravaged_brick_glow);
xx = x-5+rand.nextInt(4);
zz = z+5-rand.nextInt(4);
world.setBlock(xx, y+hallHeight, zz, BlockList.ravaged_brick_fence);
world.setBlock(xx, y+hallHeight-1, zz, BlockList.ravaged_brick_glow);
xx = x+5-rand.nextInt(4);
zz = z+5-rand.nextInt(4);
world.setBlock(xx, y+hallHeight, zz, BlockList.ravaged_brick_fence);
world.setBlock(xx, y+hallHeight-1, zz, BlockList.ravaged_brick_glow);
xx = x-1+rand.nextInt(3);
zz = z-1+rand.nextInt(3);
world.setBlock(xx, y+hallHeight, zz, BlockList.ravaged_brick_fence);
world.setBlock(xx, y+hallHeight-1, zz, BlockList.ravaged_brick_glow);
break;
case CORNER_LIGHTS:
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
world.setBlock(x-5+10*a, y+1, z-5+10*b, BlockList.ravaged_brick_glow);
world.setBlock(x-5+10*a, y+2, z-5+10*b, BlockList.ravaged_brick_slab);
}
}
break;
default:
}
}
}*/
/*
* HALLWAY
*/
/*private enum EnumHallwayDesign{
NONE, DESTROYED_WALLS, STAIR_PATTERN, EMBEDDED_CHEST, COBWEBS, FLOOR_CEILING_SLABS, LAPIS_BLOCK, WALL_MOUNTED_SPAWNERS, DEAD_END_CHEST, FLOWER_POT,
SPAWNERS_IN_WALLS
}
private static final WeightedMap<EnumHallwayDesign> hallwayDesignList = new WeightedMap<>(EnumHallwayDesign.values().length, map -> {
map.add(EnumHallwayDesign.NONE, 88);
map.add(EnumHallwayDesign.DEAD_END_CHEST, 45);
map.add(EnumHallwayDesign.DESTROYED_WALLS, 44);
map.add(EnumHallwayDesign.EMBEDDED_CHEST, 33);
map.add(EnumHallwayDesign.STAIR_PATTERN, 32);
map.add(EnumHallwayDesign.COBWEBS, 24);
map.add(EnumHallwayDesign.SPAWNERS_IN_WALLS, 24);
map.add(EnumHallwayDesign.FLOOR_CEILING_SLABS, 21);
map.add(EnumHallwayDesign.WALL_MOUNTED_SPAWNERS, 19);
map.add(EnumHallwayDesign.FLOWER_POT, 16);
map.add(EnumHallwayDesign.LAPIS_BLOCK, 4);
});*/
/*public void generateHallway(LargeStructureWorld world, Random rand, int x, int y, int z, DungeonElement hallway){
for(int yy = y; yy <= y+hallHeight+1; yy++){
for(int xx = x-radHallway; xx <= x+radHallway; xx++){
for(int zz = z-radHallway; zz <= z+radHallway; zz++){
if (yy == y || yy == y+hallHeight+1 || xx == x-radHallway || xx == x+radHallway || zz == z-radHallway || zz == z+radHallway){
world.setBlock(xx, yy, zz, BlockList.ravaged_brick, getBrickMeta(rand));
}
else world.setBlock(xx, yy, zz, Blocks.air);
}
}
}
EnumHallwayDesign design = hallwayDesignList.getRandomItem(rand).getObject();
if (design == EnumHallwayDesign.NONE)return;
int connections = ((hallway.checkConnection(DungeonDir.UP) ? 1 : 0) + (hallway.checkConnection(DungeonDir.DOWN) ? 1 : 0) + (hallway.checkConnection(DungeonDir.LEFT) ? 1 : 0) + (hallway.checkConnection(DungeonDir.RIGHT) ? 1 : 0));
boolean isStraight = (hallway.checkConnection(DungeonDir.UP) && hallway.checkConnection(DungeonDir.DOWN) && !hallway.checkConnection(DungeonDir.LEFT) && !hallway.checkConnection(DungeonDir.RIGHT)) ||
(hallway.checkConnection(DungeonDir.LEFT) && hallway.checkConnection(DungeonDir.RIGHT) && !hallway.checkConnection(DungeonDir.UP) && !hallway.checkConnection(DungeonDir.DOWN));
boolean isFullyOpen = hallway.checkConnection(DungeonDir.UP) && hallway.checkConnection(DungeonDir.LEFT) && hallway.checkConnection(DungeonDir.DOWN) && hallway.checkConnection(DungeonDir.RIGHT);
boolean isDeadEnd = connections == 1;
DungeonDir off;
Facing offFacing;
boolean isLR;
switch(design){
case DESTROYED_WALLS:
for(int attempt = 0, attempts = 80+rand.nextInt(40+rand.nextInt(30)), xx, yy, zz; attempt < attempts; attempt++){
xx = x+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
zz = z+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
yy = y+1+rand.nextInt(hallHeight);
if (world.getBlock(xx, yy, zz) == BlockList.ravaged_brick){
world.setBlock(xx, yy, zz, BlockList.ravaged_brick, BlockRavagedBrick.metaDamaged1+rand.nextInt(1+BlockRavagedBrick.metaDamaged4-BlockRavagedBrick.metaDamaged1));
}
}
break;
case STAIR_PATTERN:
if (isFullyOpen)break;
off = DungeonDir.values[rand.nextInt(DungeonDir.values.length)];
while(hallway.checkConnection(off))off = DungeonDir.values[rand.nextInt(DungeonDir.values.length)];
offFacing = dirToFacing(off);
isLR = off == DungeonDir.LEFT || off == DungeonDir.RIGHT;
int metaStairsLeft = (isLR ? offFacing.getRotatedRight() : offFacing.getRotatedLeft()).getStairs()+(rand.nextBoolean() ? 0 : 4),
metaStairsRight = (isLR ? offFacing.getRotatedLeft() : offFacing.getRotatedRight()).getStairs()+(rand.nextBoolean() ? 0 : 4);
for(int yy = y+1; yy <= y+hallHeight; yy++){
for(int ax1 = -1; ax1 <= 1; ax1++){
for(int ax2 = 2; ax2 <= 3; ax2++){
if (ax2 == 2 && (ax1 == -1 || ax1 == 1)){
world.setBlock(x+rotX(off, ax1, 2), yy, z+rotZ(off, ax1, 2), BlockList.ravaged_brick_stairs, ax1 == -1 ? metaStairsLeft : metaStairsRight);
continue;
}
if (ax2 == 3 && !canReplaceBlock(world.getBlock(x+rotX(off, ax1, ax2), yy, z+rotZ(off, ax1, ax2))))continue;
world.setBlock(x+rotX(off, ax1, ax2), yy, z+rotZ(off, ax1, ax2), ax2 == 2 ? Blocks.air : BlockList.ravaged_brick, ax2 == 2 ? 0 : getBrickMeta(rand));
}
}
}
break;
case EMBEDDED_CHEST:
if (!isStraight && !isDeadEnd)break;
off = hallway.checkConnection(DungeonDir.UP) || hallway.checkConnection(DungeonDir.DOWN) ? DungeonDir.LEFT : DungeonDir.UP;
if (rand.nextBoolean())off = off.reversed();
isLR = off == DungeonDir.LEFT || off == DungeonDir.RIGHT;
offFacing = dirToFacing(off);
int sz = isDeadEnd ? 1 : 2;
boolean canGenerate = true;
for(int yy = y+1; yy <= y+hallHeight && canGenerate; yy++){
for(int ax1 = -sz; ax1 <= sz && canGenerate; ax1++){
for(int ax2 = 2; ax2 <= 3 && canGenerate; ax2++){
if (ax2 == 3 && !canReplaceBlock(world.getBlock(x+rotX(off, ax1, ax2), yy, z+rotZ(off, ax1, ax2)))){
if (world.getBlock(x+rotX(off, ax1, ax2), yy, z+rotZ(off, ax1, ax2)) == Blocks.chest){
canGenerate = false;
}
continue;
}
world.setBlock(x+rotX(off, ax1, ax2), yy, z+rotZ(off, ax1, ax2), ax2 == 2 ? Blocks.air : BlockList.ravaged_brick, ax2 == 2 ? 0 : getBrickMeta(rand));
}
world.setBlock(x+rotX(off, ax1, 2), y+hallHeight, z+rotZ(off, ax1, 2), BlockList.ravaged_brick_stairs, 4+offFacing.getStairs());
}
}
if (!canGenerate)break;
if (sz == 2){
world.setBlock(x+rotX(off, -2, 2), y+1, z+rotZ(off, -2, 2), BlockList.ravaged_brick_stairs, 4+(isLR ? offFacing.getRotatedRight() : offFacing.getRotatedLeft()).getStairs());
world.setBlock(x+rotX(off, 2, 2), y+1, z+rotZ(off, 2, 2), BlockList.ravaged_brick_stairs, 4+(isLR ? offFacing.getRotatedLeft() : offFacing.getRotatedRight()).getStairs());
}
for(int a = 0; a < 2; a++)world.setBlock(x+rotX(off, -1+2*a, 2), y+1, z+rotZ(off, -1+2*a, 2), BlockList.ravaged_brick_stairs, 4+offFacing.getStairs());
world.setBlock(x+rotX(off, 0, 2), y+1, z+rotZ(off, 0, 2), BlockList.ravaged_brick);
world.setBlock(x+rotX(off, 0, 2), y+2, z+rotZ(off, 0, 2), Blocks.chest, offFacing.getReversed().get6Directional());
world.setTileEntityGenerator(x+rotX(off, 0, 2), y+2, z+rotZ(off, 0, 2), "hallwayEmbeddedChest", this);
break;
case DEAD_END_CHEST:
if (!isDeadEnd)break;
off = DungeonDir.DOWN;
for(DungeonDir dir:DungeonDir.values){
if (hallway.checkConnection(dir)){
off = dir;
break;
}
}
offFacing = dirToFacing(off);
for(int ax1 = -1; ax1 <= 1; ax1++){
world.setBlock(x+rotX(off, ax1, 1), y+hallHeight, z+rotZ(off, ax1, 1), BlockList.ravaged_brick_stairs, 4+offFacing.getStairs());
if (ax1 != 0)world.setBlock(x+rotX(off, ax1, 1), y+1, z+rotZ(off, ax1, 1), BlockList.ravaged_brick_stairs, offFacing.getStairs());
}
world.setBlock(x+rotX(off, 0, 1), y+1, z+rotZ(off, 0, 1), BlockList.ravaged_brick, offFacing.getStairs());
world.setBlock(x+rotX(off, 0, 1), y+2, z+rotZ(off, 0, 1), Blocks.chest, offFacing.getReversed().get6Directional());
world.setTileEntityGenerator(x+rotX(off, 0, 1), y+2, z+rotZ(off, 0, 1), "hallwayDeadEndChest", this);
break;
case COBWEBS:
for(int attempt = 0, attempts = 2+rand.nextInt(6*(1+rand.nextInt(2))), xx, yy, zz; attempt < attempts; attempt++){
xx = x+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
zz = z+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
yy = y+1+rand.nextInt(hallHeight);
if (world.isAir(xx, yy, zz))world.setBlock(xx, yy, zz, Blocks.web);
}
break;
case FLOOR_CEILING_SLABS:
for(int attempt = 0, attempts = 6+rand.nextInt(7), xx, yy, zz; attempt < attempts; attempt++){
xx = x+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
zz = z+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
yy = rand.nextBoolean() ? y+1 : y+hallHeight;
if (world.isAir(xx, yy, zz))world.setBlock(xx, yy, zz, BlockList.ravaged_brick_slab, yy == y+1 ? 0 : 8);
}
break;
case LAPIS_BLOCK:
world.setBlock(x, y, z, Blocks.lapis_block);
world.setBlock(x, y-1, z, BlockList.ravaged_brick);
break;
case WALL_MOUNTED_SPAWNERS:
List<DungeonDir> availableDirs = CollectionUtil.newList(DungeonDir.values);
for(int attempt = 0, placed = 0; attempt < 1+rand.nextInt(3) && !availableDirs.isEmpty(); attempt++){
off = availableDirs.remove(rand.nextInt(availableDirs.size()));
if (hallway.checkConnection(off)){
if (placed == 0)--attempt;
continue;
}
world.setBlock(x+rotX(off, 0, -1), y+2, z+rotZ(off, 0, -1), BlockList.ravaged_brick_slab, 8);
world.setBlock(x+rotX(off, 0, -1), y+3, z+rotZ(off, 0, -1), BlockList.custom_spawner, 2);
world.setTileEntityGenerator(x+rotX(off, 0, -1), y+3, z+rotZ(off, 0, -1), "louseSpawner", this);
world.setBlock(x+rotX(off, 0, -1), y+4, z+rotZ(off, 0, -1), BlockList.ravaged_brick_slab, 0);
}
break;
case SPAWNERS_IN_WALLS:
int spawnerMeta = rand.nextBoolean() ? 3 : 2;
for(int attempt = 0, placed = 0, maxPlaced = 2+level+rand.nextInt(3+level), xx, yy, zz; attempt < 22 && placed < maxPlaced; attempt++){
xx = x+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
zz = z+rand.nextInt(radHallway+1)-rand.nextInt(radHallway+1);
yy = rand.nextBoolean() ? y+1 : y+hallHeight;
if (world.getBlock(xx, yy, zz) == BlockList.ravaged_brick){
world.setBlock(xx, yy, zz, BlockList.custom_spawner, spawnerMeta);
if (spawnerMeta == 2)world.setTileEntityGenerator(xx, yy, zz, "louseSpawner", this);
++placed;
}
}
for(DungeonDir dir:DungeonDir.values){
if (!hallway.checkConnection(dir)){
for(int a = -1; a <= 1; a++){
for(int yy = y+1; yy <= y+hallHeight; yy++){
if (canReplaceBlock(world.getBlock(x+rotX(dir, a, 3), yy, z+rotZ(dir, a, 3))))world.setBlock(x+rotX(dir, a, 3), yy, z+rotZ(dir, a, 3), BlockList.ravaged_brick, getBrickMeta(rand));
}
}
}
}
break;
case FLOWER_POT:
int type = rand.nextInt(6);
if (type == 0){ // embedded in wall
if (!isStraight)break;
off = hallway.checkConnection(DungeonDir.UP) || hallway.checkConnection(DungeonDir.DOWN) ? DungeonDir.LEFT : DungeonDir.UP;
if (rand.nextBoolean())off = off.reversed();
for(int ax1 = -1; ax1 <= 1; ax1++){
if (canReplaceBlock(world.getBlock(x+rotX(off, ax1, 3), y+2, z+rotZ(off, ax1, 3))))world.setBlock(x+rotX(off, ax1, 3), y+2, z+rotZ(off, ax1, 3), BlockList.ravaged_brick, getBrickMeta(rand));
world.setBlock(x+rotX(off, ax1, 2), y+2, z+rotZ(off, ax1, 2), Blocks.flower_pot);
world.setTileEntityGenerator(x+rotX(off, ax1, 2), y+2, z+rotZ(off, ax1, 2), "flowerPot", this);
}
}
else if (type == 1 || type == 2){ // floor
int xx = x+rand.nextInt(3)-1, zz = z+rand.nextInt(3)-1;
world.setBlock(xx, y+1, zz, Blocks.flower_pot);
world.setTileEntityGenerator(xx, y+1, zz, "flowerPot", this);
}
else if (type == 3 || type == 4){ // slab on wall
if (isFullyOpen)break;
off = DungeonDir.values[rand.nextInt(DungeonDir.values.length)];
while(hallway.checkConnection(off))off = DungeonDir.values[rand.nextInt(DungeonDir.values.length)];
world.setBlock(x+rotX(off, 0, -1), y+2, z+rotZ(off, 0, -1), BlockList.ravaged_brick_slab, 8);
world.setBlock(x+rotX(off, 0, -1), y+3, z+rotZ(off, 0, -1), Blocks.flower_pot);
world.setTileEntityGenerator(x+rotX(off, 0, -1), y+3, z+rotZ(off, 0, -1), "flowerPot", this);
}
break;
case NONE:
default:
}
if (connections >= 3 && rand.nextInt(10) == 0)world.setBlock(x, y+hallHeight, z, BlockList.ravaged_brick_glow);
}*/
/*
* ROOM
*/
/*private enum EnumRoomDesign{
GOO_FOUNTAINS, BOWLS, CARPET_TARGET, SCATTERED_SPAWNERS_WITH_COAL, GLOWING_ROOM, FOUR_SPAWNERS, ENCASED_CUBICLE, TERRARIUM, RUINS
}
private static final WeightedMap<EnumRoomDesign> roomDesignList = new WeightedMap<>(EnumRoomDesign.values().length, map -> {
map.add(EnumRoomDesign.GOO_FOUNTAINS, 56);
map.add(EnumRoomDesign.RUINS, 56);
map.add(EnumRoomDesign.BOWLS, 54);
map.add(EnumRoomDesign.FOUR_SPAWNERS, 51);
map.add(EnumRoomDesign.SCATTERED_SPAWNERS_WITH_COAL, 44);
map.add(EnumRoomDesign.GLOWING_ROOM, 35);
map.add(EnumRoomDesign.CARPET_TARGET, 26);
map.add(EnumRoomDesign.ENCASED_CUBICLE, 20);
map.add(EnumRoomDesign.TERRARIUM, 17);
});*/
/*private void generateRoomLayout(LargeStructureWorld world, Random rand, int x, int y, int z){
for(int yy = y; yy <= y+hallHeight+1; yy++){
for(int xx = x-radRoom; xx <= x+radRoom; xx++){
for(int zz = z-radRoom; zz <= z+radRoom; zz++){
if (yy == y || yy == y+hallHeight+1 || xx == x-radRoom || xx == x+radRoom || zz == z-radRoom || zz == z+radRoom){
world.setBlock(xx, yy, zz, BlockList.ravaged_brick, getBrickMeta(rand));
}
else world.setBlock(xx, yy, zz, Blocks.air);
}
}
}
}
public void generateRoom(LargeStructureWorld world, Random rand, int x, int y, int z, DungeonElement room){
generateRoomLayout(world, rand, x, y, z);
boolean isStraight = (room.checkConnection(DungeonDir.UP) && room.checkConnection(DungeonDir.DOWN) && !room.checkConnection(DungeonDir.LEFT) && !room.checkConnection(DungeonDir.RIGHT)) ||
(room.checkConnection(DungeonDir.LEFT) && room.checkConnection(DungeonDir.RIGHT) && !room.checkConnection(DungeonDir.UP) && !room.checkConnection(DungeonDir.DOWN));
boolean hasGenerated = false;
while(!hasGenerated){
hasGenerated = true;
EnumRoomDesign design = roomDesignList.getRandomItem(rand).getObject();
switch(design){
case GOO_FOUNTAINS:
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
world.setBlock(x-6+12*a, y+hallHeight, z-6+12*b, BlockList.ender_goo);
world.setBlock(x-6+12*a, y+1, z-2+4*b, BlockList.ravaged_brick_slab);
world.setBlock(x-5+10*a, y+1, z-3+6*b, BlockList.ravaged_brick_slab);
world.setBlock(x-4+8*a, y+1, z-4+8*b, BlockList.ravaged_brick_slab);
world.setBlock(x-3+6*a, y+1, z-5+10*b, BlockList.ravaged_brick_slab);
world.setBlock(x-2+4*a, y+1, z-6+12*b, BlockList.ravaged_brick_slab);
}
}
world.setBlock(x, y+hallHeight, z, BlockList.ender_goo);
world.setBlock(x, y+1, z, BlockList.custom_spawner, 3);
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
world.setBlock(x-2+4*a, y+1, z-2+4*b, BlockList.ravaged_brick_slab);
world.setBlock(x-3+6*a, y+1, z-1+2*b, BlockList.ravaged_brick_slab);
world.setBlock(x-1+2*a, y+1, z-3+6*b, BlockList.ravaged_brick_slab);
}
world.setBlock(x-3+6*a, y+1, z, BlockList.ravaged_brick_slab);
world.setBlock(x, y+1, z-3+6*a, BlockList.ravaged_brick_slab);
}
break;
case CARPET_TARGET:
int color;
switch(rand.nextInt(4)){
case 0: color = 10; break; // purple
case 1: color = 14; break; // red
case 2: color = 15; break; // black
default: color = 0; break; // white
}
for(int a = -6; a <= 6; a++){
world.setBlock(x+a, y+1, z-6, Blocks.carpet, color);
world.setBlock(x+a, y+1, z+6, Blocks.carpet, color);
}
for(int a = -4; a <= 4; a++){
world.setBlock(x+a, y+1, z-4, Blocks.carpet, color);
world.setBlock(x+a, y+1, z+4, Blocks.carpet, color);
}
for(int a = -2; a <= 2; a++){
world.setBlock(x+a, y+1, z-2, Blocks.carpet, color);
world.setBlock(x+a, y+1, z+2, Blocks.carpet, color);
}
for(int a = -5; a <= 5; a++){
world.setBlock(x-6, y+1, z+a, Blocks.carpet, color);
world.setBlock(x+6, y+1, z+a, Blocks.carpet, color);
}
for(int a = -3; a <= 3; a++){
world.setBlock(x-4, y+1, z+a, Blocks.carpet, color);
world.setBlock(x+4, y+1, z+a, Blocks.carpet, color);
}
for(int a = -1; a <= 1; a++){
world.setBlock(x-2, y+1, z+a, Blocks.carpet, color);
world.setBlock(x+2, y+1, z+a, Blocks.carpet, color);
}
for(DungeonDir dir:DungeonDir.values){
if (room.checkConnection(dir)){
for(int ax1 = -1; ax1 <= 1; ax1++){
for(int ax2 = 2; ax2 <= 6; ax2++){
world.setBlock(x+rotX(dir, ax1, ax2), y+1, z+rotZ(dir, ax1, ax2), Blocks.air);
}
}
}
}
break;
case SCATTERED_SPAWNERS_WITH_COAL:
for(int attempt = 0, attemptAmount = rand.nextInt(3)+4+level*2, xx, zz, spawnerMeta = rand.nextBoolean() ? 2 : 3; attempt < attemptAmount; attempt++){
xx = x+rand.nextInt(5)-rand.nextInt(5);
zz = z+rand.nextInt(5)-rand.nextInt(5);
world.setBlock(xx, y+1, zz, BlockList.custom_spawner, spawnerMeta);
if (spawnerMeta == 2)world.setTileEntityGenerator(xx, y+1, zz, "louseSpawner", this);
world.setBlock(xx, y+2, zz, Blocks.coal_block);
}
break;
case ENCASED_CUBICLE:
if (level == 0){
hasGenerated = false;
break;
}
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
world.setBlock(x-6+12*a, y+hallHeight, z-6+12*b, BlockList.ravaged_brick_glow);
world.setBlock(x-6+12*a, y+hallHeight-1, z-6+12*b, BlockList.ravaged_brick_slab, 8);
}
}
for(int yy = y+1; yy <= y+hallHeight; yy++){
for(int xx = x-2; xx <= x+2; xx++){
world.setBlock(xx, yy, z+2, BlockList.ravaged_brick, getBrickMeta(rand));
world.setBlock(xx, yy, z-2, BlockList.ravaged_brick, getBrickMeta(rand));
}
for(int zz = z-1; zz <= z+1; zz++){
world.setBlock(x+2, yy, zz, BlockList.ravaged_brick, getBrickMeta(rand));
world.setBlock(x-2, yy, zz, BlockList.ravaged_brick, getBrickMeta(rand));
}
}
world.setBlock(x, y+1, z, Blocks.chest);
world.setTileEntityGenerator(x, y+1, z, "encasedCubicleChest", this);
int[] spawnerX = new int[]{ -1, -1, -1, 0, 0, 1, 1, 1 }, spawnerZ = new int[]{ -1, 0, 1, -1, 1, -1, 0, 1 };
for(int a = 0, spawnerMeta; a < spawnerX.length; a++){
spawnerMeta = rand.nextInt(3) == 0 ? 2 : 3;
world.setBlock(x+spawnerX[a], y+1, z+spawnerZ[a], BlockList.custom_spawner, spawnerMeta);
if (spawnerMeta == 2)world.setTileEntityGenerator(x+spawnerX[a], y+1, z+spawnerZ[a], "louseSpawner", this);
}
break;
case TERRARIUM:
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
for(int c = 6; c >= 2; c--){
world.setBlock(x-c+2*c*a, y+1, z-6+12*b, Blocks.dirt, 2);
world.setBlock(x-c+2*c*a, y+1, z-5+10*b, Blocks.dirt, 2);
world.setBlock(x-c+2*c*a, y+1, z-4+8*b, Blocks.dirt, 2);
}
world.setBlock(x-6+12*a, y+1, z-3+6*b, Blocks.dirt, 2);
world.setBlock(x-5+10*a, y+1, z-3+6*b, Blocks.dirt, 2);
world.setBlock(x-4+8*a, y+1, z-3+6*b, Blocks.dirt, 2);
world.setBlock(x-6+12*a, y+1, z-2+4*b, BlockList.ravaged_brick_glow);
world.setBlock(x-5+10*a, y+1, z-2+4*b, BlockList.ravaged_brick);
world.setBlock(x-4+8*a, y+1, z-2+4*b, BlockList.ravaged_brick_glow);
world.setBlock(x-3+6*a, y+1, z-2+4*b, BlockList.ravaged_brick);
world.setBlock(x-3+6*a, y+1, z-3+6*b, BlockList.ravaged_brick_glow);
world.setBlock(x-2+4*a, y+1, z-3+6*b, BlockList.ravaged_brick);
world.setBlock(x-2+4*a, y+1, z-4+8*b, BlockList.ravaged_brick_glow);
world.setBlock(x-2+4*a, y+1, z-5+10*b, BlockList.ravaged_brick);
world.setBlock(x-2+4*a, y+1, z-6+12*b, BlockList.ravaged_brick_glow);
for(int yy = y+2; yy <= y+hallHeight; yy++){
for(int c = 3; c <= 6; c++){
world.setBlock(x-c+2*c*a, yy, z-2+4*b, Blocks.stained_glass, 14);
world.setBlock(x-2+4*a, yy, z-c+2*c*b, Blocks.stained_glass, 14);
}
}
int plants = 5+rand.nextInt(9);
for(int plant = 0, xx, zz; plant < plants; plant++){
xx = x-6+9*a+rand.nextInt(4);
zz = z-6+9*b+rand.nextInt(4);
if (world.getBlock(xx, y+1, zz) == Blocks.dirt){
Block plantBlock = Blocks.air;
int plantMeta = 0;
switch(rand.nextInt(11)){
case 0:
case 1:
plantBlock = Blocks.sapling;
plantMeta = rand.nextBoolean() ? 2 : 0; // birch & oak sapling
break;
case 2:
plantBlock = Blocks.yellow_flower; // dandelion
break;
case 3:
case 4:
plantBlock = Blocks.tallgrass;
plantMeta = rand.nextBoolean() ? 1 : 2; // tall grass & fern
break;
case 5:
plantBlock = rand.nextBoolean() ? Blocks.brown_mushroom : Blocks.red_mushroom; // mushrooms are a little more rare
break;
default: // 6, 7, 8, 9, 10
plantBlock = Blocks.red_flower;
plantMeta = rand.nextInt(5); // poppy, blue orchid, allium, azure bluet
if (plantMeta == 4)plantMeta = 8; // oxeye daisy
break;
}
world.setBlock(xx, y+2, zz, plantBlock, plantMeta);
}
}
}
}
break;
case RUINS:
for(int attempt = 0, attemptAmount = 28+rand.nextInt(12), placedChests = 0, xx, zz; attempt < attemptAmount; attempt++){
xx = x+rand.nextInt(radRoom)-rand.nextInt(radRoom);
zz = z+rand.nextInt(radRoom)-rand.nextInt(radRoom);
if (!world.isAir(xx, y+1, zz))continue;
int height = rand.nextInt(3);
for(int yy = y+1; yy <= y+1+height; yy++){
if (rand.nextInt(8-level) == 0)world.setBlock(xx, yy, zz, BlockList.custom_spawner, 3);
else world.setBlock(xx, yy, zz, BlockList.ravaged_brick);
}
if (rand.nextInt(3) == 0)world.setBlock(xx, y+2+height, zz, BlockList.ravaged_brick_slab);
else if (rand.nextInt(4) == 0)world.setBlock(xx, y+2+height, zz, BlockList.ravaged_brick_stairs, rand.nextInt(4));
else if (placedChests < 2 && height < 2 && rand.nextInt(4+placedChests*2) == 0){
world.setBlock(xx, y+2+height, zz, Blocks.chest);
world.setTileEntityGenerator(xx, y+2+height, zz, "ruinChest", this);
++placedChests;
}
}
break;
case FOUR_SPAWNERS:
if (!isStraight){
hasGenerated = false;
break;
}
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
world.setBlock(x-2+4*a, y+1, z-2+4*b, BlockList.custom_spawner, 2);
world.setTileEntityGenerator(x-2+4*a, y+1, z-2+4*b, "louseSpawner", this);
world.setBlock(x-2+4*a, y+2, z-2+4*b, BlockList.ravaged_brick_slab);
}
}
DungeonDir dir = room.checkConnection(DungeonDir.UP) ? DungeonDir.UP : DungeonDir.LEFT;
int[] zValues = new int[]{ -5, 0, 5 };
for(int a = 0; a < zValues.length; a++){
world.setBlock(x+rotX(dir, 6, zValues[a]), y+2, z+rotZ(dir, 6, zValues[a]), BlockList.ravaged_brick_fence);
world.setBlock(x+rotX(dir, 6, zValues[a]), y+3, z+rotZ(dir, 6, zValues[a]), BlockList.ravaged_brick_glow);
world.setBlock(x+rotX(dir, -6, zValues[a]), y+2, z+rotZ(dir, -6, zValues[a]), BlockList.ravaged_brick_fence);
world.setBlock(x+rotX(dir, -6, zValues[a]), y+3, z+rotZ(dir, -6, zValues[a]), BlockList.ravaged_brick_glow);
}
break;
case GLOWING_ROOM:
int[] pillarX = new int[]{ -6, -2, 2, 6, -6, 6, -6, 6, -6, -2, 2, 6 }, pillarZ = new int[]{ -6, -6, -6, -6, -2, -2, 2, 2, 6, 6, 6, 6 };
for(int a = 0; a < pillarX.length; a++){
for(int yy = y+1; yy <= y+hallHeight; yy++){
world.setBlock(x+pillarX[a], yy, z+pillarZ[a], BlockList.ravaged_brick_glow);
}
}
if (rand.nextBoolean()){ // fences
for(int yy = y+1; yy <= y+hallHeight; yy++){
for(int xx = x-5; xx <= x+5; xx++){
if (world.isAir(xx, yy, z-6))world.setBlock(xx, yy, z-6, BlockList.ravaged_brick_fence);
if (world.isAir(xx, yy, z+6))world.setBlock(xx, yy, z+6, BlockList.ravaged_brick_fence);
}
for(int zz = z-5; zz <= z+5; zz++){
if (world.isAir(x-6, yy, zz))world.setBlock(x-6, yy, zz, BlockList.ravaged_brick_fence);
if (world.isAir(x+6, yy, zz))world.setBlock(x+6, yy, zz, BlockList.ravaged_brick_fence);
}
for(DungeonDir checkDir:DungeonDir.values){
if (room.checkConnection(checkDir)){
for(int ax1 = -1; ax1 <= 1; ax1++){
world.setBlock(x+rotX(checkDir, ax1, -6), yy, z+rotZ(checkDir, ax1, -6), Blocks.air);
}
}
}
}
}
break;
case BOWLS:
int bowlFill = rand.nextInt(4);
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
world.setBlock(x-5+7*a, y+1, z-5+7*b, BlockList.ravaged_brick_glow);
world.setBlock(x-4+7*a, y+1, z-5+7*b, BlockList.ravaged_brick);
world.setBlock(x-3+7*a, y+1, z-5+7*b, BlockList.ravaged_brick);
world.setBlock(x-2+7*a, y+1, z-5+7*b, BlockList.ravaged_brick_glow);
world.setBlock(x-5+7*a, y+1, z-4+7*b, BlockList.ravaged_brick);
world.setBlock(x-5+7*a, y+1, z-3+7*b, BlockList.ravaged_brick);
world.setBlock(x-5+7*a, y+1, z-2+7*b, BlockList.ravaged_brick_glow);
world.setBlock(x-3+7*a, y+1, z-2+7*b, BlockList.ravaged_brick);
world.setBlock(x-4+7*a, y+1, z-2+7*b, BlockList.ravaged_brick);
world.setBlock(x-2+7*a, y+1, z-2+7*b, BlockList.ravaged_brick_glow);
world.setBlock(x-2+7*a, y+1, z-3+7*b, BlockList.ravaged_brick);
world.setBlock(x-2+7*a, y+1, z-4+7*b, BlockList.ravaged_brick);
switch(bowlFill){
case 0:
case 1:
case 2:
world.setBlock(x-4+7*a, y+1, z-4+7*b, bowlFill == 0 ? BlockList.ender_goo : bowlFill == 1 ? BlockList.ravaged_brick_slab : Blocks.obsidian);
world.setBlock(x-3+7*a, y+1, z-4+7*b, bowlFill == 0 ? BlockList.ender_goo : bowlFill == 1 ? BlockList.ravaged_brick_slab : Blocks.obsidian);
world.setBlock(x-3+7*a, y+1, z-3+7*b, bowlFill == 0 ? BlockList.ender_goo : bowlFill == 1 ? BlockList.ravaged_brick_slab : Blocks.obsidian);
world.setBlock(x-4+7*a, y+1, z-3+7*b, bowlFill == 0 ? BlockList.ender_goo : bowlFill == 1 ? BlockList.ravaged_brick_slab : Blocks.obsidian);
break;
case 3:
world.setBlock(x-4+7*a, y+1, z-4+7*b, (a^b) == 1 ? BlockList.custom_spawner : Blocks.coal_block, (a^b) == 1 ? 3 : 0);
world.setBlock(x-3+7*a, y+1, z-4+7*b, (a^b) == 0 ? BlockList.custom_spawner : Blocks.coal_block, (a^b) == 0 ? 3 : 0);
world.setBlock(x-3+7*a, y+1, z-3+7*b, (a^b) == 1 ? BlockList.custom_spawner : Blocks.coal_block, (a^b) == 1 ? 3 : 0);
world.setBlock(x-4+7*a, y+1, z-3+7*b, (a^b) == 0 ? BlockList.custom_spawner : Blocks.coal_block, (a^b) == 0 ? 3 : 0);
break;
}
}
}
break;
default:
}
}
}*/
/*
* END
*/
/*public void generateEndLayout(LargeStructureWorld world, Random rand, int[] x, int y, int[] z, List<DungeonElement> end){
int minX = x[0], maxX = x[0], minZ = z[0], maxZ = z[0];
for(int a = 1; a < x.length; a++){
if (x[a] < minX)minX = x[a];
if (x[a] > maxX)maxX = x[a];
if (z[a] < minZ)minZ = z[a];
if (z[a] > maxZ)maxZ = z[a];
}
for(int yy = y; yy <= y+hallHeight+1; yy++){
for(int xx = minX-radRoom; xx <= maxX+radRoom; xx++){
for(int zz = minZ-radRoom; zz <= maxZ+radRoom; zz++){
if (yy == y || yy == y+hallHeight+1 || xx == minX-radRoom || xx == maxX+radRoom || zz == minZ-radRoom || zz == maxZ+radRoom){
world.setBlock(xx, yy, zz, BlockList.ravaged_brick, getBrickMeta(rand));
}
else world.setBlock(xx, yy, zz, Blocks.air);
}
}
}
}
public void generateEndContent(LargeStructureWorld world, Random rand, int[] x, int y, int[] z, List<DungeonElement> end){
int minX = x[0], minZ = z[0];
for(int a = 1; a < x.length; a++){
if (x[a] < minX)minX = x[a];
if (z[a] < minZ)minZ = z[a];
}
int topLeftAirX = minX-radRoom+1, topLeftAirZ = minZ-radRoom+1;
int[] gooX = new int[]{ 2, 12, 22, 2, 22, 2, 12, 22 }, gooZ = new int[]{ 2, 2, 2, 12, 12, 22, 22, 22 };
for(int a = 0; a < gooX.length; a++){
for(int px = 0; px < 2; px++){
for(int pz = 0; pz < 2; pz++){
world.setBlock(topLeftAirX+gooX[a]+1+px, y+hallHeight, topLeftAirZ+gooZ[a]+1+pz, BlockList.ender_goo);
world.setBlock(topLeftAirX+gooX[a]+1+px, y+hallHeight+1, topLeftAirZ+gooZ[a]+1+pz, BlockList.ravaged_brick_glow);
}
}
for(int py = 0; py < 2; py++){
for(int px = 0; px < 4; px++){
world.setBlock(topLeftAirX+gooX[a]+px, y+2+py, topLeftAirZ+gooZ[a], Blocks.air);
world.setBlock(topLeftAirX+gooX[a]+px, y+1+py*(hallHeight-1), topLeftAirZ+gooZ[a], BlockList.ravaged_brick, getBrickMeta(rand));
world.setBlock(topLeftAirX+gooX[a]+px, y+2+py, topLeftAirZ+gooZ[a]+3, Blocks.air);
world.setBlock(topLeftAirX+gooX[a]+px, y+1+py*(hallHeight-1), topLeftAirZ+gooZ[a]+3, BlockList.ravaged_brick, getBrickMeta(rand));
}
for(int pz = 0; pz < 2; pz++){
world.setBlock(topLeftAirX+gooX[a], y+2+py, topLeftAirZ+gooZ[a]+1+pz, Blocks.air);
world.setBlock(topLeftAirX+gooX[a], y+1+py*(hallHeight-1), topLeftAirZ+gooZ[a]+1+pz, BlockList.ravaged_brick, getBrickMeta(rand));
world.setBlock(topLeftAirX+gooX[a]+3, y+2+py, topLeftAirZ+gooZ[a]+1+pz, Blocks.air);
world.setBlock(topLeftAirX+gooX[a]+3, y+1+py*(hallHeight-1), topLeftAirZ+gooZ[a]+1+pz, BlockList.ravaged_brick, getBrickMeta(rand));
}
}
for(int attempt = 0, xx, yy, zz; attempt < 3+rand.nextInt(4); attempt++){
xx = topLeftAirX+gooX[a]+rand.nextInt(4);
zz = topLeftAirZ+gooZ[a]+rand.nextInt(4);
yy = rand.nextBoolean() ? y+1 : y+hallHeight;
if (world.getBlock(xx, yy, zz) == BlockList.ravaged_brick){
world.setBlock(xx, yy, zz, BlockList.custom_spawner, 2);
world.setTileEntityGenerator(xx, yy, zz, "louseSpawner", this);
}
}
}
for(int a = 0; a < 2; a++){
for(int b = 0; b < 2; b++){
for(int py = 0; py < 4; py++){
world.setBlock(topLeftAirX+12+3*a, y+1+py, topLeftAirZ+12+3*b, py == 0 || py == 3 ? BlockList.ravaged_brick_glow : BlockList.ravaged_brick);
if (py > 0){
world.setBlock(topLeftAirX+13+a, y+1+py, topLeftAirZ+13+b, BlockList.custom_spawner, 2);
world.setTileEntityGenerator(topLeftAirX+13+a, y+1+py, topLeftAirZ+13+b, "louseSpawner", this);
}
else world.setBlock(topLeftAirX+13+a, y+1, topLeftAirZ+13+b, BlockList.ravaged_brick);
}
}
}
int[] chestX = new int[]{ 13, 14, 13, 14, 12, 12, 15, 15 }, chestZ = new int[]{ 12, 12, 15, 15, 13, 14, 13, 14 };
for(int a = 0; a < chestX.length; a++){
world.setBlock(topLeftAirX+chestX[a], y+1, topLeftAirZ+chestZ[a], Blocks.chest);
world.setTileEntityGenerator(topLeftAirX+chestX[a], y+1, topLeftAirZ+chestZ[a], "endRoomChest", this);
}
}*/
/*
* TILE ENTITIES
*/
/*@Override
public void onTileEntityRequested(String key, TileEntity tile, Random rand){
// TODO
if (key.equals("hallwayEmbeddedChest")){
TileEntityChest chest = (TileEntityChest)tile;
for(int attempt = 0, attemptAmount = 4+rand.nextInt(5)+rand.nextInt(4+level); attempt < attemptAmount; attempt++){
chest.setInventorySlotContents(rand.nextInt(chest.getSizeInventory()), (rand.nextInt(3) == 0 ? RavagedDungeonLoot.lootUncommon : RavagedDungeonLoot.lootGeneral).generateIS(rand));
}
}
else if (key.equals("hallwayDeadEndChest")){
TileEntityChest chest = (TileEntityChest)tile;
for(int attempt = 0, attemptAmount = 7+rand.nextInt(8+level*2); attempt < attemptAmount; attempt++){
chest.setInventorySlotContents(rand.nextInt(chest.getSizeInventory()), (rand.nextInt(3) != 0 ? RavagedDungeonLoot.lootRare : RavagedDungeonLoot.lootGeneral).generateIS(rand));
}
}
else if (key.equals("ruinChest")){
TileEntityChest chest = (TileEntityChest)tile;
for(int attempt = 0, attemptAmount = 5+rand.nextInt(5+level*2); attempt < attemptAmount; attempt++){
chest.setInventorySlotContents(rand.nextInt(chest.getSizeInventory()), RavagedDungeonLoot.lootGeneral.generateIS(rand));
}
}
else if (key.equals("encasedCubicleChest")){
TileEntityChest chest = (TileEntityChest)tile;
for(int attempt = 0, attemptAmount = 10+level+rand.nextInt(10+level); attempt < attemptAmount; attempt++){
chest.setInventorySlotContents(rand.nextInt(chest.getSizeInventory()), RavagedDungeonLoot.lootRare.generateIS(rand));
}
}
else if (key.equals("endRoomChest")){
TileEntityChest chest = (TileEntityChest)tile;
for(int attempt = 0, attemptAmount = 3+rand.nextInt(2+rand.nextInt(2)); attempt < attemptAmount; attempt++){
chest.setInventorySlotContents(rand.nextInt(chest.getSizeInventory()), RavagedDungeonLoot.lootEnd.generateIS(rand));
}
}
else if (key.equals("louseSpawner")){
LouseRavagedSpawnerLogic logic = (LouseRavagedSpawnerLogic)((TileEntityCustomSpawner)tile).getSpawnerLogic();
logic.setLouseSpawnData(new LouseSpawnData(level, rand));
}
else if (key.equals("flowerPot")){
ItemStack is = RavagedDungeonLoot.flowerPotItems[rand.nextInt(RavagedDungeonLoot.flowerPotItems.length)].copy();
if (is.getItem() == Item.getItemFromBlock(BlockList.death_flower)){
tile.getWorldObj().setBlock(tile.xCoord, tile.yCoord, tile.zCoord, BlockList.death_flower_pot, is.getItemDamage(), 3);
}
else{
TileEntityFlowerPot flowerPot = (TileEntityFlowerPot)tile;
flowerPot.func_145964_a(is.getItem(), is.getItemDamage());
flowerPot.markDirty();
if (!flowerPot.getWorldObj().setBlockMetadataWithNotify(flowerPot.xCoord, flowerPot.yCoord, flowerPot.zCoord, is.getItemDamage(), 2)){
flowerPot.getWorldObj().markBlockForUpdate(flowerPot.xCoord, flowerPot.yCoord, flowerPot.zCoord);
}
}
}
}*/
/*
* UTILITIES
*/
/*private static boolean canReplaceBlock(Block block){
return block == Blocks.end_stone || block == BlockList.end_terrain || block == Blocks.air || block == BlockList.crossed_decoration || block == BlockList.stardust_ore || block == BlockList.end_powder_ore;
}
private static int getBrickMeta(Random rand){
return rand.nextInt(8) != 0 ? 0 : rand.nextInt(12) == 0 ? BlockRavagedBrick.metaCracked : BlockRavagedBrick.metaDamaged1+rand.nextInt(1+BlockRavagedBrick.metaDamaged4-BlockRavagedBrick.metaDamaged1);
}
private static int rotX(DungeonDir dir, int x, int z){
switch(dir){
case UP: return x;
case DOWN: return -x;
case LEFT: return z;
case RIGHT: return -z;
default: return 0;
}
}
private static int rotZ(DungeonDir dir, int x, int z){
switch(dir){
case UP: return z;
case DOWN: return -z;
case LEFT: return x;
case RIGHT: return -x;
default: return 0;
}
}
private static Facing4 dirToFacing(DungeonDir dir){
switch(dir){
case UP: return Facing4.SOUTH_POSZ;
case DOWN: return Facing4.NORTH_NEGZ;
case LEFT: return Facing4.EAST_POSX;
case RIGHT: return Facing4.WEST_NEGX;
default: return null;
}
}*/
}
|
<gh_stars>0
#include "Common.hpp"
// returns maximal entropy score for random sequences which is log2|A| where A is the alphabet
// returns something close to 0 for highly repetitive sequences
double getEntropy(const char* s, const size_t len){
double counts[4] = {0, 0, 0, 0};
double logs[4];
for (size_t i = 0; i != len; ++i){
const char c = s[i] & 0xDF;
if (isDNA(c)){
const size_t x = (c & 4) >> 1;
++counts[x + ((x ^ (c & 2)) >> 1)];
}
}
counts[0] /= len;
counts[1] /= len;
counts[2] /= len;
counts[3] /= len;
logs[0] = (counts[0] == 0) ? 0 : log2(counts[0]);
logs[1] = (counts[1] == 0) ? 0 : log2(counts[1]);
logs[2] = (counts[2] == 0) ? 0 : log2(counts[2]);
logs[3] = (counts[3] == 0) ? 0 : log2(counts[3]);
return 0 - ((counts[0] * logs[0]) + (counts[1] * logs[1]) + (counts[2] * logs[2]) + (counts[3] * logs[3]));
}
size_t getMaxPaths(const double seq_entropy, const size_t max_len_path, const size_t k){
const double entropy_factor = 3. - seq_entropy;
const size_t v = rndup(max_len_path);
return static_cast<double>(v * (__builtin_ctzll(v) + k)) * entropy_factor;
}
size_t getMaxBranch(const double seq_entropy, const size_t max_len_path, const size_t k){
const double entropy_factor = 3. - seq_entropy;
const double base_nb_nodes = static_cast<double>(__builtin_ctzll(rndup(max_len_path - k + 1)));
return (base_nb_nodes + 1) * entropy_factor;
}
bool hasEnoughSharedPairID(const PairID& a, const PairID& b, const size_t min_shared_ids) {
size_t nb_shared = 0;
const size_t a_card = a.cardinality();
const size_t b_card = b.cardinality();
if ((a_card >= min_shared_ids) && (b_card >= min_shared_ids)) {
const size_t log2_a = b_card * approximate_log2(a_card);
const size_t log2_b = a_card * approximate_log2(b_card);
const size_t min_a_b = min(a_card + b_card, min(log2_a, log2_b));
if (min_a_b == (a_card + b_card)) {
PairID::const_iterator a_it_s = a.begin(), a_it_e = a.end();
PairID::const_iterator b_it_s = b.begin(), b_it_e = b.end();
while ((a_it_s != a_it_e) && (b_it_s != b_it_e) && (nb_shared < min_shared_ids)){
const uint32_t val_a = *a_it_s;
const uint32_t val_b = *b_it_s;
if (val_a == val_b){
++nb_shared;
++a_it_s;
++b_it_s;
}
else if (val_a < val_b) ++a_it_s;
else ++b_it_s;
}
}
else if (min_a_b == log2_a){
PairID::const_iterator b_it_s = b.begin(), b_it_e = b.end();
while ((b_it_s != b_it_e) && (nb_shared < min_shared_ids)){
nb_shared += static_cast<size_t>(a.contains(*b_it_s));
++b_it_s;
}
}
else {
PairID::const_iterator a_it_s = a.begin(), a_it_e = a.end();
while ((a_it_s != a_it_e) && (nb_shared < min_shared_ids)){
nb_shared += static_cast<size_t>(b.contains(*a_it_s));
++a_it_s;
}
}
}
return (nb_shared == min_shared_ids);
}
bool hasEnoughSharedPairID(const TinyBloomFilter<uint32_t>& tbf_a, const PairID& a, const PairID& b, const size_t min_shared_ids) {
size_t nb_shared = 0;
const size_t a_card = a.cardinality();
const size_t b_card = b.cardinality();
if ((a_card >= min_shared_ids) && (b_card >= min_shared_ids)) {
const size_t log2_a = b_card * (approximate_log2(a_card) + tbf_a.getNumberHashFunctions());
const size_t log2_b = a_card * approximate_log2(b_card);
const size_t min_a_b = min(a_card + b_card, min(log2_a, log2_b));
if (min_a_b == log2_a) {
PairID::const_iterator b_it_s = b.begin(), b_it_e = b.end();
while ((b_it_s != b_it_e) && (nb_shared < min_shared_ids)){
const uint32_t val_b = *b_it_s;
nb_shared += static_cast<size_t>(tbf_a.query(val_b) && a.contains(val_b));
++b_it_s;
}
}
else return hasEnoughSharedPairID(a, b, min_shared_ids);
}
return (nb_shared == min_shared_ids);
}
size_t getNumberSharedPairID(const PairID& a, const PairID& b) {
if (a.isEmpty() || b.isEmpty()) return 0;
size_t nb_shared = 0;
const size_t a_card = a.cardinality();
const size_t b_card = b.cardinality();
const size_t log2_a = b_card * approximate_log2(a_card);
const size_t log2_b = a_card * approximate_log2(b_card);
const size_t min_a_b = min(a_card + b_card, min(log2_a, log2_b));
if (min_a_b == (a_card + b_card)) {
PairID::const_iterator a_it_s = a.begin(), a_it_e = a.end();
PairID::const_iterator b_it_s = b.begin(), b_it_e = b.end();
while ((a_it_s != a_it_e) && (b_it_s != b_it_e)){
const uint32_t val_a = *a_it_s;
const uint32_t val_b = *b_it_s;
if (val_a == val_b){
++nb_shared;
++a_it_s;
++b_it_s;
}
else if (val_a < val_b) ++a_it_s;
else ++b_it_s;
}
}
else if (min_a_b == log2_a){
PairID::const_iterator b_it_s = b.begin(), b_it_e = b.end();
while (b_it_s != b_it_e){
nb_shared += static_cast<size_t>(a.contains(*b_it_s));
++b_it_s;
}
}
else {
PairID::const_iterator a_it_s = a.begin(), a_it_e = a.end();
while (a_it_s != a_it_e){
nb_shared += static_cast<size_t>(b.contains(*a_it_s));
++a_it_s;
}
}
return nb_shared;
}
size_t getNumberSharedPairID(const TinyBloomFilter<uint32_t>& tbf_a, const PairID& a, const PairID& b) {
if (a.isEmpty() || b.isEmpty()) return 0;
size_t nb_shared = 0;
const size_t a_card = a.cardinality();
const size_t b_card = b.cardinality();
const size_t log2_a = b_card * (approximate_log2(a_card) + tbf_a.getNumberHashFunctions());
const size_t log2_b = a_card * approximate_log2(b_card);
const size_t min_a_b = min(a_card + b_card, min(log2_a, log2_b));
if (min_a_b == log2_a) {
PairID::const_iterator b_it_s = b.begin(), b_it_e = b.end();
while (b_it_s != b_it_e){
const uint32_t val_b = *b_it_s;
nb_shared += static_cast<size_t>(tbf_a.query(val_b) && a.contains(val_b));
++b_it_s;
}
}
else return getNumberSharedPairID(a, b);
return nb_shared;
}
size_t approximate_log2(size_t v) {
static const uint8_t tab64[64] = {
63, 0, 58, 1, 59, 47, 53, 2,
60, 39, 48, 27, 54, 33, 42, 3,
61, 51, 37, 40, 49, 18, 28, 20,
55, 30, 34, 11, 43, 14, 22, 4,
62, 57, 46, 52, 38, 26, 32, 41,
50, 36, 17, 19, 29, 10, 13, 21,
56, 45, 25, 31, 35, 16, 9, 12,
44, 24, 15, 8, 23, 7, 6, 5
};
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
return tab64[(static_cast<size_t>((v - (v >> 1))*0x07EDD5E59A4E28C2)) >> 58];
} |
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JAction2 extends JFrame implements ActionListener
{
JLabel label = new JLabel("Name?");
JTextField field = new JTextField(12);
JButton button = new JButton("OK");
boolean readyToQuit = false;
public JAction2()
{
super("Action");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(label);
add(field);
add(button);
button.addActionListener(this);
field.addActionListener(this);
}
public static void main(String[] args)
{
JAction2 aFrame = new JAction2();
final int WIDTH = 250;
final int HEIGHT = 150;
aFrame.setSize(WIDTH, HEIGHT);
aFrame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == button)
label.setText("You clicked the button");
else
label.setText("You pressed Enter");
if(readyToQuit)
System.exit(0);
button.setText("Application done");
readyToQuit = true;
}
} |
# Shows user's password aging information
chage -l USERNAME
# To enforce pasword change every 30 days we modify the file:
nano /etc/login.defs
"
# Maximum days before password change
PASS_MAX_DAYS 30
# Minimum days before password change
PASS_MIN_DAYS 2
# Warn user 7 days before expiration
PASS_WARN_AGE 7
# Enforce minimum password length of 10
PASS_MIN_LEN 10
"
# These configs will only apply to new user.
# We can force them onold users with chage:
chage -M 30 USERNAME
chage -m 2 USERNAME
chage -W 7 USERNAME
chage -l USERNAME
# Install password quality security module for PAM
sudo apt-get install libpam-pwquality
# Set password policy for all users by modifying
# PAM's (Pluggable Authentication Modules) common-password config file.
nano /etc/security/pwquality.conf
"
# Require at least one uppercase character
ucredit = -1
# Require at least one digit
dcredit = -1
# No more than 3 consecutive identical characters
maxrepeat = 3
# Check if it contains the username
usercheck = 1
# The number of characters in the new password that must not have been present in the old password.
difok = 7
# Enforce pasword policy for root user
enforce_for_root
# OPTIONAL
# Minimum password length of 10
minlen = 10
# Require at least one lowercase character
lcredit = -1
"
# Change currenr user's password
passwd
# Change password of any user, bypasses rules
chpasswd <<<"USERNAME:NEWPASSWORD"
|
function processPixelData(imageData, color, amp) {
for (let j = 0; j < imageData.length; j += 3) {
const pixelIdx = j;
if (j < amp) {
imageData[pixelIdx + 0] = color.r;
imageData[pixelIdx + 1] = color.g;
imageData[pixelIdx + 2] = color.b;
} else {
imageData[pixelIdx + 0] = imageData[pixelIdx + 1] = imageData[pixelIdx + 2] = 0;
}
}
} |
// Copyright 2017 The TIE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A service for managing the keys used in localStorage. All
* localStorage key management should be done here in order to reduce the
* likelihood of collisions.
*/
tie.factory('LocalStorageKeyManagerService', [
function() {
// TIE uses local storage with the following key structure:
//
// - tie:1:lastSavedCode:{{questionId}}:{{language}} -- the last saved
// code (a string)
// - tie:1:sessionHistory:{{questionId}}:{{submissionNumber}} -- the
// session history (a list of transcript paragraph dicts)
//
// The second number in each key is for version control. If this schema
// changes, that number should be updated to prevent collision.
return {
/**
* Returns the local storage key for the last saved code for a given
* question.
*
* @param {string} tieId
* @param {string} questionId
* @param {string} language
* @returns {string}
*/
getLastSavedCodeKey: function(tieId, questionId, language) {
return 'tie:' + tieId + ':lastSavedCode:' + questionId + ':' + language;
},
/**
* Returns the local storage key for the session history.
*
* @param {string} tieId
* @param {string} questionId
* @param {number} snapshotIndex
* @returns {string}
*/
getSessionHistoryKey: function(tieId, questionId, snapshotIndex) {
return 'tie:' + tieId + ':sessionHistory:' + questionId + ':' +
snapshotIndex.toString();
}
};
}
]);
|
<filename>trees-and-graphs/bst-sequences.py
import sys
from queue import Queue
def problem():
"""
BST Sequences: A binary search tree was created by traversing through an array from left to right
and inserting each element. Given a binary search tree with distinct elements, print all possible
arrays that could have led to this tree.
EXAMPLE
Input:
Root: 2
Left: 1
Right: 3
Output: {2, 1, 3}, {2, 3, 1}
"""
pass
class Tree:
def __init__(self):
self.root = None
self.count = 0
def add(self, item):
self.root = self.__add(self.root, item)
self.count += 1
def __add(self, current, item):
if current is None:
return self.TreeNode(item)
if current.value >= item:
current.left = self.__add(current.left, item)
else:
current.right = self.__add(current.right, item)
return current
def find_addition_sequences(self):
if self.root is None:
return []
sequences = []
self.__find_addition_sequences(self.root, sequences, [])
self.__find_addition_sequences_inverse(self.root, sequences, [])
self.__find_addition_sequences_bfs(sequences)
self.__find_addition_sequences_bfs_reverse(sequences)
return sequences
def __find_addition_sequences_bfs(self, sequences):
q = Queue()
q.enqueue(self.root)
current_sequence = []
while not q.empty():
current = q.dequeue()
current_sequence.append(current.value)
if current.left is not None:
q.enqueue(current.left)
if current.right is not None:
q.enqueue(current.right)
sequences.append(current_sequence)
def __find_addition_sequences_bfs_reverse(self, sequences):
q = Queue()
q.enqueue(self.root)
current_sequence = []
while not q.empty():
current = q.dequeue()
current_sequence.append(current.value)
if current.right is not None:
q.enqueue(current.right)
if current.left is not None:
q.enqueue(current.left)
sequences.append(current_sequence)
def __find_addition_sequences(self, node, current, current_sequence):
if node is None:
return
current_sequence.append(node.value)
self.__find_addition_sequences(node.left, current, current_sequence)
self.__find_addition_sequences(node.right, current, current_sequence)
if node.left is None and node.right is None:
current.append(current_sequence)
def __find_addition_sequences_inverse(self, node, current, current_sequence):
if node is None:
return
current_sequence.append(node.value)
self.__find_addition_sequences(node.right, current, current_sequence)
self.__find_addition_sequences(node.left, current, current_sequence)
if node.left is None and node.right is None:
current.append(current_sequence)
def dump(self):
self.__dump(self.root)
def __dump(self, current, indent = 0):
if current is None:
return
print("{0}{1}".format(indent * " ", current.value))
self.__dump(current.left, indent + 2)
self.__dump(current.right, indent + 2)
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __repr__(self):
return "Node({0})".format(self.value)
class TreeTester:
@staticmethod
def test_creation(tree, TreeClass, sequences):
for sequence in sequences:
current_tree = TreeClass()
[current_tree.add(x) for x in sequence]
if not TreeTester.compare_trees(tree, current_tree):
return False
return True
@staticmethod
def compare_trees(left, right):
return TreeTester.__DFS_compare(left.root, right.root)
@staticmethod
def __DFS_compare(left_current, right_current):
if left_current is None and right_current is None:
return True
if left_current is None:
return False
if right_current is None:
return False
res = left_current.value == right_current.value
return res and TreeTester.__DFS_compare(left_current.left, right_current.left) \
and TreeTester.__DFS_compare(left_current.right, right_current.right)
if __name__ == '__main__':
args = sys.argv[1:]
tree = Tree()
tree.add(2)
tree.add(1)
tree.add(3)
tree.add(-5)
tree.add(6)
tree.dump()
tester = TreeTester()
sequences = tree.find_addition_sequences()
print(tester.test_creation(tree, Tree, sequences))
print(sequences)
|
<gh_stars>0
package com.dmitrybrant.response.sessionResponse;
public class DeleteSessionRes {
}
|
#!/bin/bash
#
# Copyright (c) 2020, Arm Limited and affiliates.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
python3 -m venv venv
. venv/bin/activate
pip install --upgrade pip
pip install --upgrade wheel
pip install --upgrade setuptools
pip install pyyaml
pip install gitpython
pip install -e scripts
|
<filename>node_modules/react-icons-kit/metrize/arrowCycle.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrowCycle = void 0;
var arrowCycle = {
"viewBox": "0 0 512 512",
"children": [{
"name": "g",
"attribs": {},
"children": [{
"name": "path",
"attribs": {
"d": "M256,0C114.609,0,0,114.609,0,256s114.609,256,256,256s256-114.609,256-256S397.391,0,256,0z M256,472\r\n\t\tc-119.297,0-216-96.703-216-216S136.703,40,256,40s216,96.703,216,216S375.297,472,256,472z"
},
"children": [{
"name": "path",
"attribs": {
"d": "M256,0C114.609,0,0,114.609,0,256s114.609,256,256,256s256-114.609,256-256S397.391,0,256,0z M256,472\r\n\t\tc-119.297,0-216-96.703-216-216S136.703,40,256,40s216,96.703,216,216S375.297,472,256,472z"
},
"children": []
}]
}, {
"name": "path",
"attribs": {
"d": "M188.117,188.125c37.5-37.5,98.273-37.5,135.758,0l-11.312,11.312l50.922,16.969L346.5,165.484l-11.312,11.328\r\n\t\tc-43.75-43.75-114.641-43.75-158.383,0c-27.984,27.984-37.977,67.078-30.141,103.078l18.211,6.078\r\n\t\tC153.953,252.656,161.648,214.594,188.117,188.125z"
},
"children": [{
"name": "path",
"attribs": {
"d": "M188.117,188.125c37.5-37.5,98.273-37.5,135.758,0l-11.312,11.312l50.922,16.969L346.5,165.484l-11.312,11.328\r\n\t\tc-43.75-43.75-114.641-43.75-158.383,0c-27.984,27.984-37.977,67.078-30.141,103.078l18.211,6.078\r\n\t\tC153.953,252.656,161.648,214.594,188.117,188.125z"
},
"children": []
}]
}, {
"name": "path",
"attribs": {
"d": "M347.125,226.031c10.922,33.312,3.234,71.375-23.25,97.844c-37.5,37.5-98.258,37.5-135.758,0l11.312-11.312l-50.906-16.969\r\n\t\tl16.969,50.922l16.969-16.984l-5.656,5.672c43.742,43.734,114.648,43.734,158.383,0c28-28,37.984-67.078,30.156-103.094\r\n\t\tL347.125,226.031z"
},
"children": [{
"name": "path",
"attribs": {
"d": "M347.125,226.031c10.922,33.312,3.234,71.375-23.25,97.844c-37.5,37.5-98.258,37.5-135.758,0l11.312-11.312l-50.906-16.969\r\n\t\tl16.969,50.922l16.969-16.984l-5.656,5.672c43.742,43.734,114.648,43.734,158.383,0c28-28,37.984-67.078,30.156-103.094\r\n\t\tL347.125,226.031z"
},
"children": []
}]
}]
}]
};
exports.arrowCycle = arrowCycle; |
<!DOCTYPE html>
<html>
<head>
<title>My Bootstrap Page</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">My Page</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<h1>Hello World!</h1>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html> |
import React from "react";
import { LightningBoltIcon } from "@heroicons/react/solid";
import LoadingIcon from "../assets/icons/spinner-2.svg";
export default function Button(props) {
return (
<button
className={`items-center gap-2 ${
props.dark
? "bg-slate-900 text-white hover:ring-gray-300"
: "text-slate-900 bg-gray-100 hover:ring-gray-200"
} ${props.hoverOpacity && "opacity-50 hover:opacity-100"} ${
props.premium && "bg-slate-900 !text-white hover:ring-gray-300"
} py-2 px-3 rounded-lg hover:ring-4 transition flex`}
onClick={() => props.action()}
>
{props.loading ? (
<img src={LoadingIcon} className="w-4 animate-spin" alt="Loading" />
) : props.icon ? (
<props.icon className="w-4" />
) : null}
{props.premium && <LightningBoltIcon className="w-4 text-yellow-300" />}
{props.text && <span className="font-medium text-sm">{props.text}</span>}
</button>
);
}
|
import React from 'react';
import LottieView from 'lottie-react-native';
import { LoadingAnimation } from '@assets/animations';
import * as Atoms from '@components/atoms';
import { useLottieAnimation } from '@hooks/useLottieAnimation';
function Loading() {
const animation = useLottieAnimation();
return (
<Atoms.Center sx={{ flex: 1 }}>
<LottieView
ref={animation}
source={LoadingAnimation}
autoPlay
style={{ width: 50 }}
/>
</Atoms.Center>
);
}
export { Loading };
|
#ifndef _z2c2_ErrorReporter_h_
#define _z2c2_ErrorReporter_h_
#include <Core/Core.h>
namespace Z2 {
using namespace Upp;
class Assembly;
class ZClass;
class Method;
class Node;
class Overload;
class ZSyntaxError: Moveable<ZSyntaxError> {
public:
String Path;
String Error;
Point ErrorPoint;
Overload* Context = nullptr;
ZSyntaxError(const String& path, const Point& p, const String& error): Path(path), ErrorPoint(p), Error(error) {
}
void PrettyPrint(Stream& stream);
};
class ErrorReporter {
public:
static void SyntaxError(const String& path, const Point& p, const String& text);
static void InvalidNumericLiteral(const String& path, const Point& p);
static void InvalidCharLiteral(const String& path, const Point& p);
static void IntegerConstantTooBig(const String& path, const Point& p);
static void IntegerConstantTooBig(const String& path, const String& cls, const Point& p);
static void FloatConstantTooBig(const String& path, const Point& p);
static void QWordWrongSufix(const String& path, const Point& p);
static void LongWrongSufix(const String& path, const Point& p);
static void UnsignedLeadingMinus(const String& path, const Point& p);
static void ExpectedNotFound(const String& path, const Point& p, const String& expected, const String& found);
static void ExpectCT(const String& path, const Point& p);
static void EosExpected(const String& path, const Point& p, const String& found);
static void IdentifierExpected(const String& path, const Point& p, const String& found);
static void IdentifierExpected(const String& path, const Point& p, const String& id, const String& found);
static void UndeclaredIdentifier(const String& path, const Point& p, const String& id);
static void UndeclaredIdentifier(const String& path, const Point& p, const String& c1, const String& c2);
static void UndeclaredClass(const String& path, const Point& p, const String& id);
static void UnreachableCode(const String& path, const Point& p);
static void ClassMustBeInstanciated(const String& path, const Point& p, const String& c);
static void CantAssign(const String& path, const Point& p, const String& c1, const String& c2);
static void AssignNotLValue(const String& path, const Point& p);
static void NotLValue(const String& path, const Point& p);
static void AssignConst(const String& path, const Point& p, const String& c);
static void CantCreateClassVar(const String& path, const Point& p, const String& c);
static void CondNotBool(const String& path, const Point& p, const String& c);
static void NotStatic(const String& path, const Point& p, const String& c);
static void CantCall(const String& path, const Point& p, Assembly& ass, ZClass* ci, Method* def, Vector<Node*>& params, int limit, bool cons = false);
static void AmbigError(const String& path, const Point& p, Assembly& ass, ZClass* ci, Method* def, Vector<Node*>& params, int score);
static void SomeOverloadsBad(const String& path, const Point& p, const String& f);
static void DivisionByZero(const String& path, const Point& p);
static void IncompatOperands(const String& path, const Point& p, const String& op, const String& text, const String& text2);
static void IncompatUnary(const String& path, const Point& p, const String& text, const String& text2);
static void Error(const String& path, const Point& p, const String& text);
static void Dup(const String& path, const Point& p, const Point& p2, const String& text, const String& text2 = "");
static ZSyntaxError DupObject(const String& path, const Point& p, const Point& p2, const String& text, const String& text2 = "");
static void Warning(const String& path, const Point& p, const String& text);
};
}
#endif
|
<gh_stars>1-10
const {wait} = require("./utils");
const {error} = require("./utils");
module.exports = {
uuidv4: function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
},
verifAd: function (client,uuid,message) {
let tmp = true;
const de = message.content.replace(/\n/g, ' ').split(/ +/g);
for (let f = 0; f < de.length; f++) {
let arr = ""
if (de[f].match('https://discord.gg/') !== null ) {
arr = de[f].replace('https://discord.gg/','');
} else if(de[f].match('discord.gg') !== null) {
arr = de[f].replace('discord.gg/','');
}
if (arr !== "") {
client.getInvite(arr).then(() => {
}).catch(() => {
tmp = false;
})
}
}
setTimeout(function() {
if (tmp) {
const rt = Math.floor(Math.random() * (client.config.staffChannel.length - 0)- (0));
const channel = client.guilds.find(g => g.id === client.config.staffGuild).channels.find(c => c.id === client.config.staffChannel[rt]);
channel.createMessage({
embed: {
title: "<:btl_attention:770286642979274774> Nouvelle pub à verifier!",
description: client.ads.get(uuid).content,
fields: [
{
name: "🆔 ID de la Pub:",
value: uuid
},
{
name: "👤 Utilisateur:",
value: `${client.ads.get(uuid).author.tag} | ${client.ads.get(uuid).author.id}`
},
{
name: "💬 Serveur:",
value: `${client.ads.get(uuid).guild.name} | ${client.ads.get(uuid).guild.id}`
},
{
name: "🔌 Lien:",
value: client.ads.get(uuid).link
}
],
color: client.maincolor
}
}).then(async (msg) => {
client.adsVerif.set(msg.id, {
id: msg.id,
uuid: uuid
});
await msg.addReaction("btl_positif2:734141545711927296");
await msg.addReaction("⛔");
await msg.addReaction("🔌");
await msg.addReaction("🧯");
})
} else {
const {notApproved} = require('./utils');
notApproved(client, uuid, "Votre lien d'invitation est invalide.",`${client.user.username}#${client.user.discriminator} | ${client.user.id}`);
}
}, 500)
},
sendWarn: function(client, user, reason, completeuuid) {
client.users.find(u => u.id === user.id).getDMChannel().then(channel => {
channel.createMessage({
title: "Vous avez été avertis!",
description: reason,
fields: [
{
name: "ID de l'avertissement:",
value: `\`${completeuuid}\``
}
],
color: client.maincolor,
footer: {
text: client.footer
}
})
})
}
} |
package ru.job4j.tracker;
public class Item {
private String id;
private String name;
private String desc;
private long time;
public Item(String name, String desc, long time) {
this.name = name;
this.desc = desc;
this.time = time;
}
public Item(String name) {
this.name = name;
}
public Item(String name, String id) {
this.name = name;
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return String.format("%s %s", getId(), getName());
}
} |
<gh_stars>0
import React from 'react';
import Sidebar from '../../components/Sidebar';
import './styles.css';
import ContribExtra from '../../assets/images/contribextra.png';
import ContribBas from '../../assets/images/contribbas.png';
function Dashboard() {
return (
<>
<Sidebar />
<div id="dashboard">
<h1>Dashboard</h1>
<div id="cards">
<div className="card-hello">
<h2>Olá, <NAME></h2>
<h2>Seja Bem Vinda!</h2>
</div>
<div className="card">
<h1 className="value">R$ 10.987</h1>
<h4 className="title">Contribuição Básica</h4>
<p className="description">nos últimos 30 dias</p>
</div>
<div className="card">
<h1 className="value">R$ 10.987</h1>
<h4 className="title">Contribuição da Empresa</h4>
<p className="description">nos últimos 30 dias</p>
</div>
</div>
<div id="charts">
<img src={ContribExtra} alt="Contribuição Extra" />
<img src={ContribBas} alt="Contribuição Básica" />
</div>
</div>
</>
);
}
export default Dashboard;
|
#!/bin/bash
if [[ $# -ne 1 ]]; then
echo "Usage: ./umulov1 <num-bits>"
exit 1
fi
if [[ $1 -lt 1 ]]; then
echo "Number of bits must be greater than 0"
exit 1
fi
numbits=$1
((numbits2 = numbits * 2))
echo "1 var $numbits"
echo "2 var $numbits"
echo "3 zero $numbits"
echo "4 concat $numbits2 3 1"
echo "5 concat $numbits2 3 2"
echo "6 mul $numbits2 4 5"
echo "7 slice $numbits 6 $((numbits2 - 1)) $numbits"
echo "8 redor 1 7"
echo "9 umulo 1 1 2"
echo "10 eq 1 8 9"
echo "11 root 1 -10"
|
<filename>extras/apidoc/html/search/all_11.js
var searchData=
[
['waitinterrupr_472',['waitInterrupr',['../class_s_i4735.html#ad2e95c88de0dfa58ff7aa36988071421',1,'SI4735']]],
['waittosend_473',['waitToSend',['../group__group06.html#ga7b45c1b22c3c1a3f2326bee913d1e1e0',1,'SI4735']]],
['word_474',['word',['../group__group01.html#aff89664deed303ec065bbad68b2053ae',1,'si47x_frontend_agc_control']]]
];
|
package io.cattle.platform.process.volume;
import io.cattle.platform.core.constants.StoragePoolConstants;
import io.cattle.platform.core.constants.VolumeConstants;
import io.cattle.platform.core.dao.StoragePoolDao;
import io.cattle.platform.core.dao.VolumeDao;
import io.cattle.platform.core.model.Mount;
import io.cattle.platform.core.model.StorageDriver;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.core.model.Volume;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.object.util.DataAccessor;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.cattle.platform.core.model.tables.StorageDriverTable.*;
import static io.cattle.platform.core.model.tables.VolumeTable.*;
public class VolumeProcessManager {
ObjectManager objectManager;
ObjectProcessManager processManager;
StoragePoolDao storagePoolDao;
VolumeDao volumeDao;
public VolumeProcessManager(ObjectManager objectManager, ObjectProcessManager processManager, StoragePoolDao storagePoolDao, VolumeDao volumeDao) {
super();
this.objectManager = objectManager;
this.processManager = processManager;
this.storagePoolDao = storagePoolDao;
this.volumeDao = volumeDao;
}
private void preCreate(Volume v, Map<Object, Object> data) {
String driver = DataAccessor.fieldString(v, VolumeConstants.FIELD_VOLUME_DRIVER);
if (StringUtils.isEmpty(driver) || VolumeConstants.LOCAL_DRIVER.equals(driver)) {
return;
}
List<? extends StoragePool> pools = storagePoolDao.findStoragePoolByDriverName(v.getClusterId(), driver);
if (pools.size() == 0) {
return;
}
StoragePool sp = pools.get(0);
List<String> volumeCap = DataAccessor.fieldStringList(sp, StoragePoolConstants.FIELD_VOLUME_CAPABILITIES);
if (volumeCap != null && volumeCap.size() > 0) {
data.put(ObjectMetaDataManager.CAPABILITIES_FIELD, volumeCap);
}
}
public HandlerResult create(ProcessState state, ProcessInstance process) {
Map<Object, Object> data = new HashMap<>();
Volume volume = (Volume) state.getResource();
preCreate(volume, data);
String driver = DataAccessor.fieldString(volume, VolumeConstants.FIELD_VOLUME_DRIVER);
Long driverId = volume.getStorageDriverId();
StorageDriver storageDriver = objectManager.loadResource(StorageDriver.class, driverId);
if (storageDriver == null && StringUtils.isNotBlank(driver)) {
storageDriver = objectManager.findAny(StorageDriver.class,
STORAGE_DRIVER.CLUSTER_ID, volume.getClusterId(),
STORAGE_DRIVER.REMOVED, null,
STORAGE_DRIVER.NAME, driver);
}
if (storageDriver != null) {
driver = storageDriver.getName();
driverId = storageDriver.getId();
}
data.put(VolumeConstants.FIELD_VOLUME_DRIVER, driver);
data.put(VOLUME.STORAGE_DRIVER_ID, driverId);
HandlerResult result = new HandlerResult(data);
Long hostId = volume.getHostId();
if (storageDriver != null && hostId != null) {
if (storagePoolDao.associateVolumeToPool(volume.getId(), storageDriver.getId(), hostId) != null) {
result.withChainProcessName(processManager.getStandardProcessName(StandardProcess.DEACTIVATE, volume));
}
}
return result;
}
public HandlerResult update(ProcessState state, ProcessInstance process) {
return create(state, process);
}
public HandlerResult remove(ProcessState state, ProcessInstance process) {
Volume volume = (Volume)state.getResource();
for (Mount mount : volumeDao.findMountsToRemove(volume.getId())) {
processManager.executeDeactivateThenRemove(mount, null);
}
return null;
}
}
|
package com.touch.air.mall.ssoserver.controller;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
/**
* @author: bin.wang
* @date: 2021/1/28 11:17
*/
@Controller
public class LoginController {
@Resource
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/login.html")
public String loginPage(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {
if (StrUtil.isNotEmpty(sso_token)) {
//说明之前有人登陆过,给浏览器留下了痕迹
return "redirect:" + url + "?token=" + sso_token;
} else {
//如果没有,就展示登录
model.addAttribute("url", url);
return "login";
}
}
@PostMapping("/doLogin")
public String doLogin(String username, String password, String url, HttpServletResponse response) {
if (StrUtil.isNotEmpty(username) && StrUtil.isNotEmpty(password)) {
//登录成功,调回之前的页面
//假设把登录成功的用户存起来
String uuid = UUID.randomUUID().toString().replace("-", "");
stringRedisTemplate.opsForValue().set(uuid, username);
Cookie sso_token = new Cookie("sso_token", uuid);
response.addCookie(sso_token);
return "redirect:" + url + "?token=" + uuid;
} else {
//失败,展示登录页
return "login";
}
}
}
|
package xredis
import (
"encoding/json"
"github.com/gogf/gf/g/util/gconv"
"time"
)
// 设置值
func Set(key string, v interface{}, expiration ...time.Duration) (bool, error) {
redis := Client().DB()
n := 0 * time.Second
if len(expiration) > 0 {
n = expiration[0]
}
data := gconv.String(v)
err := redis.Set(key, data, n).Err()
if err != nil {
return false, err
}
return true, nil
}
// 获取键值
func Get(key string, out ...interface{}) (string, error) {
redis := Client().DB()
s, err := redis.Get(key).Result()
if err != nil {
return "", nil
}
if len(out) > 0 {
err := json.Unmarshal([]byte(s), out[0])
if err != nil {
return "", err
}
return s, nil
}
return s, nil
}
// 设置超时时间
func SetExpire(key string, expiration time.Duration) bool {
redis := Client().DB()
err := redis.Expire(key, expiration).Err()
return err == nil
}
func Remove(key string) bool {
redis := Client().DB()
err := redis.Del(key).Err()
return err == nil
}
|
<reponame>octavioturra/simple-worker<gh_stars>0
//simple-worker
|
public class ArraySum {
public static void main(String[] args)
{
// Array of size 5
int arr[] = { 1, 2, 3,4,5 };
// Variable to store the sum
int sum = 0;
// Iterate through the array
for (int i = 0; i < arr.length; i++)
// Add each element to the sum
sum += arr[i];
System.out.println("Sum of array elements: " + sum);
}
} |
import java.util.concurrent.Callable;
public class CallableTask implements Callable<String> {
public String call() throws Exception { // Just like run() of Thread or Runnable
Thread.sleep(10000);
System.out.println("Executing call() !!!");
/*
* if(1==1) throw new java.lang.Exception("Thrown from call()");
*/
return "success";
}
}
|
import { useState } from "react"
type UseStageManagerProps = {
initialStage : STAGE | null,
}
export type STAGE = "SIGNIN" | "SIGNUP" | "VERIFY" | "REQUEST_NEW_PASSWORD" | "NEW_PASSWORD"
| "ENTRANCE" | "CREATE_MEETING_ROOM" | "WAITING_ROOM" | "MEETING_ROOM"
| "MEETING_MANAGER_SIGNIN" | "MEETING_MANAGER"
| "HEADLESS_MEETING_MANAGER" | "HEADLESS_MEETING_MANAGER2"
| "MEETING_MANAGER_SIGNIN3" | "MEETING_MANAGER3"
export const useStageManager = (props:UseStageManagerProps) =>{
const [stage, setStage] = useState<STAGE>(props.initialStage||"SIGNIN")
return {stage, setStage}
}
|
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const state = () => ({
access_token: '', // token
hasLogin: false, // 是否已登录
userInfo: { // 用户信息
_id: 'ObjectId',
username: '',
avatar: '',
introduce: '',
createTime: '',
updateTime: ''
},
currentArticle: null,
routeInfo: {} // 当前激活的路由信息
})
export const mutations = {
// 设置登录状态
hasLogin(state, hasLogin) {
state.hasLogin = hasLogin
},
// 设置用户信息
userInfo(state, userInfo) {
state.userInfo = userInfo
localStorage.setItem('userInfo', state.userInfo)
},
// 保存路由信息
routeInfo(state, routeInfo) {
state.routeInfo = routeInfo
},
// 登录成功
login(state, data) {
// 重置vuex相关数据
state.access_token = data.token
state.hasLogin = true
state.userInfo = data.user
localStorage.setItem('access_token', state.access_token)
},
// 退出登录
logout(state) {
// 重置vuex相关数据
state.access_token = ''
state.hasLogin = false
state.userInfo = {
_id: 'ObjectId',
username: '',
avatar: '',
introduce: '',
createTime: '',
updateTime: ''
}
localStorage.setItem('access_token', state.access_token)
},
// 设置当前文章
SET_CURRENT_ARTICLE(state, article) {
state.currentArticle = article
}
}
export const actions = {
// 重新登录
reLogin({ commit }) {
Vue.prototype.$message({ type: 'error', message: '登录过期 请重新登录!' })
// 退出登录
commit('logout')
router.push({
path: '/login',
// 将当前路由携带过去,方便登录成功后跳转回去
query: { redirect: router.currentRoute.fullPath }
})
}
}
|
package io.opensphere.xyztile.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for {@link XYZDataTypeInfo}.
*/
public class XYZDataTypeInfoTest
{
/**
* Test.
*/
@Test
public void test()
{
XYZTileLayerInfo layerInfo = new XYZTileLayerInfo("name", "displayName", Projection.EPSG_4326, 1, false, 0,
new XYZServerInfo("serverName", "http://somehost"));
XYZDataTypeInfo dataType = new XYZDataTypeInfo(null, layerInfo);
assertEquals("name", dataType.getTypeName());
assertEquals("displayName", dataType.getDisplayName());
assertEquals("http://somehost", dataType.getUrl());
assertEquals("http://somehostname", dataType.getTypeKey());
assertEquals(layerInfo, dataType.getLayerInfo());
assertTrue(dataType.isVisible());
}
/**
* Test.
*/
@Test
public void testInvisible()
{
XYZTileLayerInfo layerInfo = new XYZTileLayerInfo("name", "displayName", Projection.EPSG_4326, 1, false, 0,
new XYZServerInfo("serverName", "http://somehost"));
layerInfo.setVisible(false);
XYZDataTypeInfo dataType = new XYZDataTypeInfo(null, layerInfo);
assertEquals("name", dataType.getTypeName());
assertEquals("displayName", dataType.getDisplayName());
assertEquals("http://somehost", dataType.getUrl());
assertEquals("http://somehostname", dataType.getTypeKey());
assertEquals(layerInfo, dataType.getLayerInfo());
assertFalse(dataType.isVisible());
}
}
|
import {
GET_PLAN_REQUEST,
GET_PLAN_SUCCESS,
GET_PLAN_FAILURE,
GET_PLAN_MSG_REQUEST,
GET_PLAN_MSG_SUCCESS,
GET_PLAN_MSG_FAILURE,
POST_PLAN_MSG_REQUEST,
POST_PLAN_MSG_SUCCESS,
POST_PLAN_MSG_FAILURE,
PATCH_PLAN_MSG_REQUEST,
PATCH_PLAN_MSG_SUCCESS,
PATCH_PLAN_MSG_FAILURE,
DELETE_PLAN_MSG_REQUEST,
DELETE_PLAN_MSG_SUCCESS,
DELETE_PLAN_MSG_FAILURE,
} from '../constants/PlanMessage';
import {
UNDEFINED_ERROR,
} from '../constants/Default';
const initialState = {
requesting: false,
message: '',
success_message: '',
error_code: '',
plan_msg_list: '',
plan: {},
refreshPlanMsg: false,
};
export default function plan(state = initialState, action) {
switch (action.type) {
case UNDEFINED_ERROR:
return {
...state,
requesting: false,
};
case GET_PLAN_REQUEST:
return {
...state,
requesting: action.payload.requesting,
};
case GET_PLAN_SUCCESS:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
plan: action.payload.data,
};
case GET_PLAN_FAILURE:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
error_code: action.payload.error_code,
};
case GET_PLAN_MSG_REQUEST:
return {
...state,
requesting: action.payload.requesting,
refreshPlanMsg: false,
message: '',
success_message: '',
};
case GET_PLAN_MSG_SUCCESS:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
plan_msg_list: action.payload.data,
};
case GET_PLAN_MSG_FAILURE:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
error_code: action.payload.error_code,
};
case POST_PLAN_MSG_REQUEST:
return {
...state,
requesting: action.payload.requesting,
};
case POST_PLAN_MSG_SUCCESS:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
success_message: 'New Plan Message Created Successfully',
refreshPlanMsg: true,
};
case POST_PLAN_MSG_FAILURE:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
error_code: action.payload.error_code,
};
case PATCH_PLAN_MSG_REQUEST:
return {
...state,
requesting: action.payload.requesting,
};
case PATCH_PLAN_MSG_SUCCESS:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
success_message: 'Plan Message Updated Successfully',
refreshPlanMsg: true,
};
case PATCH_PLAN_MSG_FAILURE:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
error_code: action.payload.error_code,
};
case DELETE_PLAN_MSG_REQUEST:
return {
...state,
requesting: action.payload.requesting,
};
case DELETE_PLAN_MSG_SUCCESS:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
success_message: 'Plan Message Deleted Successfully',
refreshPlanMsg: true,
};
case DELETE_PLAN_MSG_FAILURE:
return {
...state,
requesting: action.payload.requesting,
message: action.payload.message,
error_code: action.payload.error_code,
};
default:
return state;
}
}
|
package bnetp;
public enum BNetProtocolPacketId implements _PacketId {
SID_NULL,
SID_UNKNOWN_0x01,
SID_STOPADV,
SID_UNKNOWN_0x03,
SID_UNKNOWN_0x04,
SID_CLIENTID,
SID_STARTVERSIONING,
SID_REPORTVERSION,
SID_STARTADVEX,
SID_GETADVLISTEX,
SID_ENTERCHAT,
SID_GETCHANNELLIST,
SID_JOINCHANNEL,
SID_UNKNOWN_0x0D,
SID_CHATCOMMAND,
SID_CHATEVENT,
SID_LEAVECHAT,
SID_UNKNOWN_0x11,
SID_LOCALEINFO,
SID_FLOODDETECTED,
SID_UDPPINGRESPONSE,
SID_CHECKAD,
SID_CLICKAD,
SID_UNKNOWN_0x17,
SID_UNKNOWN_0x18,
SID_MESSAGEBOX,
SID_UNKNOWN_0x1A,
SID_UNKNOWN_0x1B,
SID_STARTADVEX3,
SID_LOGONCHALLENGEEX,
SID_CLIENTID2,
SID_LEAVEGAME,
SID_UNKNOWN_0x20,
SID_DISPLAYAD,
SID_NOTIFYJOIN,
SID_UNKNOWN_0x23,
SID_UNKNOWN_0x24,
SID_PING,
SID_READUSERDATA,
SID_WRITEUSERDATA,
SID_LOGONCHALLENGE,
SID_LOGONRESPONSE,
SID_CREATEACCOUNT,
SID_UNKNOWN_0x2B,
SID_GAMERESULT,
SID_GETICONDATA,
SID_GETLADDERDATA,
SID_FINDLADDERUSER,
SID_CDKEY,
SID_CHANGEPASSWORD,
SID_CHECKDATAFILE,
SID_GETFILETIME,
SID_QUERYREALMS,
SID_PROFILE,
SID_CDKEY2,
SID_UNKNOWN_0x37,
SID_UNKNOWN_0x38,
SID_UNKNOWN_0x39,
SID_LOGONRESPONSE2,
SID_UNKNOWN_0x3B,
SID_CHECKDATAFILE2,
SID_CREATEACCOUNT2,
SID_LOGONREALMEX,
SID_STARTVERSIONING2,
SID_QUERYREALMS2,
SID_QUERYADURL,
SID_UNKNOWN_0x42,
SID_UNKNOWN_0x43,
SID_WARCRAFTGENERAL,
SID_NETGAMEPORT,
SID_NEWS_INFO,
SID_UNKNOWN_0x47,
SID_UNKNOWN_0x48,
SID_UNKNOWN_0x49,
SID_OPTIONALWORK,
SID_EXTRAWORK,
SID_REQUIREDWORK,
SID_UNKNOWN_0x4D,
SID_UNKNOWN_0x4E,
SID_UNKNOWN_0x4F,
SID_AUTH_INFO,
SID_AUTH_CHECK,
SID_AUTH_ACCOUNTCREATE,
SID_AUTH_ACCOUNTLOGON,
SID_AUTH_ACCOUNTLOGONPROOF,
SID_AUTH_ACCOUNTCHANGE,
SID_AUTH_ACCOUNTCHANGEPROOF,
SID_AUTH_ACCOUNTUPGRADE,
SID_AUTH_ACCOUNTUPGRADEPROOF,
SID_SETEMAIL,
SID_RESETPASSWORD,
SID_CHANGEEMAIL,
SID_SWITCHPRODUCT,
SID_UNKNOWN_0x5D,
SID_WARDEN,
SID_UNKNOWN_0x5F,
SID_GAMEPLAYERSEARCH,
SID_UNKNOWN_0x61,
SID_UNKNOWN_0x62,
SID_UNKNOWN_0x63,
SID_UNKNOWN_0x64,
SID_FRIENDSLIST,
SID_FRIENDSUPDATE,
SID_FRIENDSADD,
SID_FRIENDSREMOVE,
SID_FRIENDSPOSITION,
SID_UNKNOWN_0x6A,
SID_UNKNOWN_0x6B,
SID_UNKNOWN_0x6C,
SID_UNKNOWN_0x6D,
SID_UNKNOWN_0x6E,
SID_UNKNOWN_0x6F,
SID_CLANFINDCANDIDATES,
SID_CLANINVITEMULTIPLE,
SID_CLANCREATIONINVITATION,
SID_CLANDISBAND,
SID_CLANMAKECHIEFTAIN,
SID_CLANINFO,
SID_CLANQUITNOTIFY,
SID_CLANINVITATION,
SID_CLANREMOVEMEMBER,
SID_CLANINVITATIONRESPONSE,
SID_CLANRANKCHANGE,
SID_CLANSETMOTD,
SID_CLANMOTD,
SID_CLANMEMBERLIST,
SID_CLANMEMBERREMOVED,
SID_CLANMEMBERSTATUSCHANGE,
SID_UNKNOWN_0x80,
SID_CLANMEMBERRANKCHANGE,
SID_CLANMEMBERINFORMATION,
} |
<filename>test/hash_function/main.cc
/*
* Copyright 2013 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* - Neither the name of the copyright holders nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* A test for hash function.
*
* Author: <NAME> <<EMAIL>>
*/
#include <boost/functional/hash.hpp>
#include <iostream> // NOLINT
#include <sstream> // NOLINT
#include <string>
#include <map>
#include "shared/nimbus.h"
#include "shared/log.h"
#define CAL_NUM 1000000
using namespace nimbus; // NOLINT
using boost::hash;
int main(int argc, const char *argv[]) {
if (argc < 2) {
std::cout << "ERROR: provide an input!" << std::endl;
exit(-1);
}
std::string input(argv[1]);
nimbus_initialize();
Log log;
hash<std::string> hash_function;
std:: cout << "Hash value: " << hash_function(input) << std::endl;
size_t result = 0;
log.StartTimer();
for (int i = 0; i < CAL_NUM; ++i) {
result += hash_function(input);
}
log.StopTimer();
std::cout << "result: " << result << std::endl;
std::cout << "Time elapsed for " << CAL_NUM << " hash calculations: " << log.timer() << std::endl;
}
|
<gh_stars>1-10
package breadth_first_search;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
/**
*
* @author minchoba
* 백준 13565번: 침투
*
* @see https://www.acmicpc.net/problem/13565/
*
*/
public class Boj13565 {
private static final int[][] DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
private static final int ROW = 0;
private static final int COL = 1;
private static final int CURRENT = 0;
private static final int FIBER = 2;
private static int[][] map = null;
private static Point[] finish = null;
public static void main(String[] args) throws Exception{
// 버퍼를 통한 값 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
Point[] start = new Point[M];
finish = new Point[M];
int sidx = 0, fidx = 0;
map = new int[N][M];
for(int i = 0; i < N; i++) {
String line = br.readLine();
for(int j = 0; j < M; j++) {
map[i][j] = line.charAt(j) - '0';
if(i == 0 && map[i][j] == CURRENT) { // 시작 지점 저장
start[sidx++] = new Point(i, j);
}
if(i == N - 1 && map[i][j] == CURRENT) { // 종료 지점 저장
finish[fidx++] = new Point(i, j);
}
}
}
System.out.println(bfs(N, M, start)); // 너비 우선 탐색 메소드를 통한 결과 출력
}
/**
* 정점 이너 클래스
* @author minchoba
*
*/
private static class Point{
int row;
int col;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
}
/**
* 너비 우선 탐색 메소드
*
*/
private static String bfs(int n, int m, Point[] start) {
boolean[][] isVisited = new boolean[n][m];
for(Point s: start) {
if(s == null) continue;
if(isVisited[s.row][s.col]) continue;
Queue<Point> q = new LinkedList<>();
q.offer(new Point(s.row, s.col));
isVisited[s.row][s.col] = true;
map[s.row][s.col] = FIBER;
while(!q.isEmpty()) {
Point current = q.poll();
for(final int[] DIRECTION: DIRECTIONS) {
int nextRow = DIRECTION[ROW] + current.row;
int nextCol = DIRECTION[COL] + current.col;
if(nextRow >= 0 && nextRow < n && nextCol >= 0 && nextCol < m) {
if(!isVisited[nextRow][nextCol] && map[nextRow][nextCol] == CURRENT) {
isVisited[nextRow][nextCol] = true; // 섬유 물질이 흐를 수 있는 곳은 섬유 물질로 채워줌
map[nextRow][nextCol] = FIBER;
q.offer(new Point(nextRow, nextCol));
}
}
}
}
}
return isPercolate(n, m) ? "YES" : "NO"; // 침투가 완료되었으면 YES, 아니면 NO를 반환
}
/**
* 침투 결과 메소드
*
*/
private static boolean isPercolate(int n, int m) {
for(Point f: finish) {
if(f == null) continue;
if(map[f.row][f.col] == FIBER) return true; // 끝 점에 섬유 물질이 존재 할 경우 참
}
return false; // 끝 점을 모두 방문 했는데도 물질이 없는 경우 거짓
}
}
|
#!/usr/bin/env bash
set -e
set -x
export GH_USERNAME="jenkins-x-versions-bot-test"
export GH_EMAIL="jenkins-x@googlegroups.com"
export GH_OWNER="jenkins-x-versions-bot-test"
# fix broken `BUILD_NUMBER` env var
export BUILD_NUMBER="$BUILD_ID"
JX_HOME="/tmp/jxhome"
KUBECONFIG="/tmp/jxhome/config"
# lets avoid the git/credentials causing confusion during the test
export XDG_CONFIG_HOME=$JX_HOME
mkdir -p $JX_HOME/git
# TODO hack until we fix boot to do this too!
helm init --client-only --stable-repo-url https://charts.helm.sh/stable
helm repo add jenkins-x https://jenkins-x-charts.github.io/repo
jx install dependencies --all
jx version --short
# replace the credentials file with a single user entry
echo "https://$GH_USERNAME:$GH_ACCESS_TOKEN@github.com" > $JX_HOME/git/credentials
gcloud auth activate-service-account --key-file $GKE_SA
# lets setup git
git config --global --add user.name JenkinsXBot
git config --global --add user.email jenkins-x@googlegroups.com
echo "running the BDD tests with JX_HOME = $JX_HOME"
# setup jx boot parameters
export JX_VALUE_ADMINUSER_PASSWORD="$JENKINS_PASSWORD"
export JX_VALUE_PIPELINEUSER_USERNAME="$GH_USERNAME"
export JX_VALUE_PIPELINEUSER_EMAIL="$GH_EMAIL"
export JX_VALUE_PIPELINEUSER_TOKEN="$GH_ACCESS_TOKEN"
export JX_VALUE_PROW_HMACTOKEN="$GH_ACCESS_TOKEN"
# TODO temporary hack until the batch mode in jx is fixed...
export JX_BATCH_MODE="true"
export BOOT_CONFIG_VERSION=$(jx step get dependency-version --host=github.com --owner=jenkins-x --repo=jenkins-x-boot-config --dir . | sed 's/.*: \(.*\)/\1/')
git clone https://github.com/jenkins-x/jenkins-x-boot-config.git boot-source
cd boot-source
git checkout tags/v${BOOT_CONFIG_VERSION} -b latest-boot-config
cp ../jx/bdd/boot-local/jx-requirements.yml .
cp ../jx/bdd/boot-local/parameters.yaml env
# Just run the spring-boot-rest-prometheus import test here
export BDD_TEST_SINGLE_IMPORT="spring-boot-rest-prometheus"
jx step bdd \
--use-revision \
--version-repo-pr \
--versions-repo https://github.com/jenkins-x/jenkins-x-versions.git \
--config ../jx/bdd/boot-local/cluster.yaml \
--gopath /tmp \
--git-provider=github \
--git-username $GH_USERNAME \
--git-owner $GH_OWNER \
--git-api-token $GH_ACCESS_TOKEN \
--default-admin-password $JENKINS_PASSWORD \
--no-delete-app \
--no-delete-repo \
--tests install \
--tests test-create-spring \
--tests test-single-import \
--tests test-app-lifecycle
|
<reponame>alterem/smartCityService
package com.zhcs.entity;
import java.io.Serializable;
import java.util.Date;
//*****************************************************************************
/**
* <p>Title:PartyEntity</p>
* <p>Description: 甲方</p>
* <p>Copyright: Copyright (c) 2017</p>
* <p>Company: 深圳市智慧城市管家信息科技有限公司 </p>
* @author 刘晓东 - Alter
* @version v1.0 2017年2月23日
*/
//*****************************************************************************
public class PartyEntity implements Serializable {
private static final long serialVersionUID = 1L;
//id
private Long id;
//名称
private String nm;
//联系人
private String contperson;
//备注
private String rmk;
//电话
private String phone;
//地址
private String addr;
//状态
private String status;
//创建人员
private Long crtid;
//创建时间
private Date crttm;
//修改人员
private Long updid;
//修改时间
private Date updtm;
/**
* 设置:id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取:id
*/
public Long getId() {
return id;
}
/**
* 设置:名称
*/
public void setNm(String nm) {
this.nm = nm;
}
/**
* 获取:名称
*/
public String getNm() {
return nm;
}
/**
* 设置:联系人
*/
public void setContperson(String contperson) {
this.contperson = contperson;
}
/**
* 获取:联系人
*/
public String getContperson() {
return contperson;
}
/**
* 设置:备注
*/
public void setRmk(String rmk) {
this.rmk = rmk;
}
/**
* 获取:备注
*/
public String getRmk() {
return rmk;
}
/**
* 设置:电话
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* 获取:电话
*/
public String getPhone() {
return phone;
}
/**
* 设置:地址
*/
public void setAddr(String addr) {
this.addr = addr;
}
/**
* 获取:地址
*/
public String getAddr() {
return addr;
}
/**
* 设置:状态
*/
public void setStatus(String status) {
this.status = status;
}
/**
* 获取:状态
*/
public String getStatus() {
return status;
}
/**
* 设置:创建人员
*/
public void setCrtid(Long crtid) {
this.crtid = crtid;
}
/**
* 获取:创建人员
*/
public Long getCrtid() {
return crtid;
}
/**
* 设置:创建时间
*/
public void setCrttm(Date crttm) {
this.crttm = crttm;
}
/**
* 获取:创建时间
*/
public Date getCrttm() {
return crttm;
}
/**
* 设置:修改人员
*/
public void setUpdid(Long updid) {
this.updid = updid;
}
/**
* 获取:修改人员
*/
public Long getUpdid() {
return updid;
}
/**
* 设置:修改时间
*/
public void setUpdtm(Date updtm) {
this.updtm = updtm;
}
/**
* 获取:修改时间
*/
public Date getUpdtm() {
return updtm;
}
}
|
#!/bin/bash
if [ "${APACHE_VERSION}" = "2.4.x" ]; then
default=/etc/apache2/sites-enabled/000-default.conf
conf=${TRAVIS_BUILD_DIR}/tests/conf/test.2.4.conf
else
default=/etc/apache2/sites-enabled/000-default
conf=${TRAVIS_BUILD_DIR}/tests/conf/test.2.2.conf
fi
sudo cp -f ${conf} ${default}
sudo mkdir -p /var/www/html/
sudo cp -R ${TRAVIS_BUILD_DIR}/tests/html/* /var/www/html/
printf '.%.0s' {1..65537} | sudo tee -a /var/www/html/br1/test01.txt
printf '.%.0s' {1..65537} | sudo tee -a /var/www/html/br1/test02.html
printf '.%.0s' {1..65537} | sudo tee -a /var/www/html/br2/test03.txt
printf '.%.0s' {1..65537} | sudo tee -a /var/www/html/br2/test04.html
printf '.%.0s' {1..65537} | sudo tee -a /var/www/html/br2/test05.htm
sudo service apache2 restart
curl -sI localhost
|
#!/bin/sh -e
: ${S3_BUCKET:=my-bucket}
: ${S3_ENDPOINT:=https://s3.amazonaws.com}
: ${AWS_ACCESS_KEY_ID=}
: ${AWS_SECRET_ACCESS_KEY=}
echo "bucket:$S3_BUCKET on $S3_ENDPOINT"
exec /usr/bin/s3fs -f "$S3_BUCKET" /srv -ourl="$S3_ENDPOINT" &
echo "> $@" && exec "$@"
|
<filename>src/index.js
const { cronsFromConfig, loadConfigFromPath } = require('./lib/services/MediaClerkService');
const moment = require('moment-timezone');
const { flatten } = require('./lib/util/ArrayUtils');
const cronOpts = {
timeZone: moment.tz.guess(),
};
const loadConfigs = paths => flatten(paths.map(loadConfigFromPath));
const [one, two, ...configPaths] = process.argv; // eslint-disable-line no-unused-vars
try {
const configs = loadConfigs(configPaths);
const jobs = cronsFromConfig(configs, cronOpts);
jobs.forEach(j => j.start());
} catch (err) {
// eslint-disable-next-line
console.error(err);
process.exit(1);
}
|
package helm
import (
"github.com/caos/orbos/pkg/kubernetes/k8s"
)
type Values struct {
ReplicaCount int `yaml:"replicaCount"`
Image Image `yaml:"image"`
ImagePullSecrets []string `yaml:"imagePullSecrets"`
NameOverride string `yaml:"nameOverride"`
FullnameOverride string `yaml:"fullnameOverride"`
Resources *k8s.Resources `yaml:"resources"`
NodeSelector map[string]string `yaml:"nodeSelector"`
Tolerations k8s.Tolerations `yaml:"tolerations"`
HTTP HTTP `yaml:"http"`
RBAC RBAC `yaml:"rbac"`
}
type Image struct {
Repository string `yaml:"repository"`
Tag string `yaml:"tag"`
PullPolicy string `yaml:"pullPolicy"`
}
type HTTP struct {
Port int `yaml:"port"`
Service Service `yaml:"service"`
}
type Service struct {
Type string `yaml:"type"`
Annotations struct{} `yaml:"annotations"`
Labels struct{} `yaml:"labels"`
}
type RBAC struct {
Enabled bool `yaml:"enabled"`
PSP PSP `yaml:"psp"`
}
type PSP struct {
Enabled bool `yaml:"enabled"`
}
|
<reponame>paulopinheiro1234/hasneto-loader<filename>src/org/hadatac/hasneto/loader/ValueCellProcessing.java<gh_stars>0
package org.hadatac.hasneto.loader;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.poi.ss.usermodel.Cell;
public class ValueCellProcessing {
boolean isFullURI(String str) {
return str.startsWith("http");
}
boolean isAbbreviatedURI(String str) {
if (!str.contains(":") || str.contains("//"))
return false;
if (str.substring(0,str.indexOf(':')).contains(" "))
return false;
return true;
}
/*
* the method verifies if cellContent contains a set of URIs, which we call an object set. Returns true if
* the content is regarded to be an object set.
*/
boolean isObjectSet (String cellContent) {
// we need to tokanize the string and verify that the first token is an URI
StringTokenizer st = new StringTokenizer(cellContent,",");
// the string needs to have at least two tokens
String firstToken, secondToken;
if (!st.hasMoreTokens()) {
return false;
}
firstToken = st.nextToken().trim();
if (!st.hasMoreTokens()) {
return false;
}
secondToken = st.nextToken().trim();
// the first token (we could also test the second) needs to be an URI
return (isFullURI(firstToken) || isAbbreviatedURI(firstToken));
}
/*
* if the argument str starts with the URI of one of the name spaces registered in NameSpaces.table, the
* URI gets replaced by the name space's abbreviation. Otherwise, the string is returned wrapper
* around angular brackets.
*/
private String replaceNameSpace(String str) {
String resp = str;
for (Map.Entry<String, NameSpace> entry : NameSpaces.table.entrySet()) {
String abbrev = entry.getKey().toString();
String nsString = entry.getValue().getName();
if (str.startsWith(nsString)) {
//System.out.println("REPLACE: " + resp + " / " + abbrev);
resp = str.replace(nsString, abbrev + ":");
return resp;
}
}
return "<" + str + ">";
}
/*
* check if the namespace in str is in the namamespace list (NameSpaces.table).
* If not, it issues a warning message. A warning message is issue if the name
* space used in the argument str is not registered in NameSpaces.table.
*/
public void validateNameSpace(String str) {
//System.out.println("Validating namespace <" + str + ">");
if (str.indexOf(':') <= 0)
return;
String abbrev = "";
String nsName = str.substring(0,(str.indexOf(':') + 1));
for (Map.Entry<String, NameSpace> entry : NameSpaces.table.entrySet()) {
abbrev = entry.getKey().toString() + ":";
if (abbrev.equals(nsName)) {
return;
}
}
System.out.println("# WARNING: NAMESPACE NOT DEFINED <" + nsName + ">");
System.out.println(abbrev);
return;
}
private String processSubjectValue(String subject) {
if (isAbbreviatedURI(subject))
validateNameSpace(subject);
// no indentation or semicolon at the end of the string
return (replaceNameSpace(subject) + "\n");
}
private String processObjectValue(String object) {
// if abbreviated URI, just print it
if (isAbbreviatedURI(object)) {
validateNameSpace(object);
//System.out.print(object);
return object;
}
// if full URI, either abbreviated it or print it between angled brackets
if (isFullURI(object)) {
// either replace namespace with acronym or add angled brackets
//System.out.print(replaceNameSpace(object));
return replaceNameSpace(object);
}
// if not URI, print the object between quotes
object = object.replace("\n", " ").replace("\r", " ").replace("\"", "''");
//System.out.println("\"" + object + "\"");
return "\"" + object + "\"";
}
public String exec(Cell cell, Vector<String> predicates) {
String clttl = "";
String cellValue = cell.getStringCellValue();
String predicate = predicates.get(cell.getColumnIndex());
// cell has subject value
if (predicate.equals("hasURI")) {
clttl = clttl + processSubjectValue(cell.getStringCellValue());
return clttl;
}
// cell has object value
clttl = clttl + " " + predicate + " ";
if (isObjectSet(cellValue)) {
StringTokenizer st = new StringTokenizer(cellValue,",");
while (st.hasMoreTokens()) {
clttl = clttl + processObjectValue(st.nextToken().trim());
if (st.hasMoreTokens()) {
clttl = clttl + ", ";
}
}
} else {
clttl = clttl + processObjectValue(cellValue);
}
clttl = clttl + ";\n";
return clttl;
}
}
|
weather () {
(curl -s wttr.in/$([ -z "$1" ] && echo $LOCATION || echo "$1")?0 || (echo && ([ $(tput cols) -gt 43 ] && cowsay -f bud-frogs 'Could not get info about current weather' || cowsay -f tux 'No weather info') | lolcat -ftS -26)) | tail -n +2
}
|
package mvedua.msu.com.spartansafety;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import mvedua.msu.com.spartansafety.Fragments.ReportFragment;
import mvedua.msu.com.spartansafety.Fragments.ResourcesFragment;
import mvedua.msu.com.spartansafety.Fragments.TwitterFragment;
public class MainActivity extends AppCompatActivity {
ResourcesFragment resourcesFragment = new ResourcesFragment();
ReportFragment reportFragment = new ReportFragment();
TwitterFragment twitterFragment = new TwitterFragment();
private void doFragmentTransaction(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (item.getItemId()) {
case R.id.navigation_resources:
doFragmentTransaction(resourcesFragment);
return true;
case R.id.navigation_report:
doFragmentTransaction(reportFragment);
return true;
case R.id.navigation_twitter:
doFragmentTransaction(twitterFragment);
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doFragmentTransaction(resourcesFragment);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
|
#!/usr/bin/env bash
get_git_revision() {
local branch shorthash revcount latesttag
branch=$(git -C "$BASEDIR" rev-parse --abbrev-ref HEAD)
shorthash=$(git -C "$BASEDIR" log --pretty=format:'%h' -n 1)
revcount=$(git -C "$BASEDIR" log --oneline | wc -l)
latesttag=$(git -C "$BASEDIR" describe --tags --abbrev=0)
echo "[$branch]$latesttag-$revcount($shorthash)"
}
openhabian_console_check() {
if [ "$(tput cols)" -lt 120 ]; then
warningtext="We detected that you use a console which is less than 120 columns wide. This tool is designed for a minimum of 120 columns and therefore some menus may not be presented correctly. Please increase the width of your console and rerun this tool.
\\nEither resize the window or consult the preferences of your console application."
whiptail --title "Compatibility Warning" --msgbox "$warningtext" 15 76
fi
}
openhabian_update_check() {
FAILED=0
echo "$(timestamp) [openHABian] openHABian configuration tool version: $(get_git_revision)"
echo -n "$(timestamp) [openHABian] Checking for changes in origin... "
git -C "$BASEDIR" config user.email 'openhabian@openHABian'
git -C "$BASEDIR" config user.name 'openhabian'
git -C "$BASEDIR" fetch --quiet origin || FAILED=1
# shellcheck disable=SC2046
if [ $(git -C "$BASEDIR" rev-parse HEAD) == $(git -C "$BASEDIR" rev-parse @\{u\}) ]; then
echo "OK"
else
echo -n "Updates available... "
introtext="Additions, improvements or fixes were added to the openHABian configuration tool. Would you like to update now and benefit from them? The update will not automatically apply changes to your system.\\n\\nUpdating is recommended."
if ! (whiptail --title "openHABian Update Available" --yes-button "Continue" --no-button "Skip" --yesno "$introtext" 15 80) then echo "SKIP"; return 0; fi
echo ""
openhabian_update
fi
}
openhabian_update() {
FAILED=0
echo -n "$(timestamp) [openHABian] Updating myself... "
read -r -t 1 -n 1 key
if [ "$key" != "" ]; then
echo -e "\\nRemote git branches available:"
git -C "$BASEDIR" branch -r
read -r -e -p "Please enter the branch to checkout: " branch
branch="${branch#origin/}"
if ! git -C "$BASEDIR" branch -r | grep -q "origin/$branch"; then
echo "FAILED - The custom branch does not exist."
return 1
fi
else
branch="master"
fi
shorthash_before=$(git -C "$BASEDIR" log --pretty=format:'%h' -n 1)
git -C "$BASEDIR" fetch --quiet origin || FAILED=1
git -C "$BASEDIR" reset --quiet --hard "origin/$branch" || FAILED=1
git -C "$BASEDIR" clean --quiet --force -x -d || FAILED=1
git -C "$BASEDIR" checkout --quiet "$branch" || FAILED=1
if [ $FAILED -eq 1 ]; then
echo "FAILED - There was a problem fetching the latest changes for the openHABian configuration tool. Please check your internet connection and try again later..."
return 1
fi
shorthash_after=$(git -C "$BASEDIR" log --pretty=format:'%h' -n 1)
if [ "$shorthash_before" == "$shorthash_after" ]; then
echo "OK - No remote changes detected. You are up to date!"
return 0
else
echo "OK - Commit history (oldest to newest):"
echo -e "\\n"
git -C "$BASEDIR" --no-pager log --pretty=format:'%Cred%h%Creset - %s %Cgreen(%ar) %C(bold blue)<%an>%Creset %C(dim yellow)%G?' --reverse --abbrev-commit --stat "$shorthash_before..$shorthash_after"
echo -e "\\n"
echo "openHABian configuration tool successfully updated."
# shellcheck disable=SC2154
echo "Visit the development repository for more details: $repositoryurl"
echo "The tool will now restart to load the updates... "
echo -e "\\n"
exec "$BASEDIR/$SCRIPTNAME"
exit 1
fi
}
system_check_default_password() {
introtext="The default password was detected on your system! That's a serious security concern. Others or malicious programs in your subnet are able to gain root access!
\\nPlease set a strong password by typing the command 'passwd'!"
echo -n "$(timestamp) [openHABian] Checking for default openHABian username:password combination... "
if is_pi && id -u pi &>/dev/null; then
USERNAME="pi"
PASSWORD="raspberry"
elif is_pi || is_pine64; then
USERNAME="openhabian"
PASSWORD="openhabian"
else
echo "SKIPPED (method not implemented)"
return 0
fi
if ! id -u $USERNAME &>/dev/null; then echo "OK (unknown user)"; return 0; fi
ORIGPASS=$(grep -w "$USERNAME" /etc/shadow | cut -d: -f2)
ALGO=$(echo "$ORIGPASS" | cut -d'$' -f2)
SALT=$(echo "$ORIGPASS" | cut -d'$' -f3)
export PASSWORD ALGO SALT
GENPASS=$(perl -le 'print crypt("$ENV{PASSWORD}","\$$ENV{ALGO}\$$ENV{SALT}\$")')
if [ "$GENPASS" == "$ORIGPASS" ]; then
if [ -n "$INTERACTIVE" ]; then
whiptail --title "Default Password Detected!" --msgbox "$introtext" 12 70
fi
echo "FAILED"
else
echo "OK"
fi
}
ua-netinst_check() {
if [ -f "/boot/config-reinstall.txt" ]; then
introtext="Attention: It was brought to our attention that the old openHABian ua-netinst based image has a problem with a lately updated Linux package.\\nIf you upgrade(d) the package 'raspberrypi-bootloader-nokernel' your Raspberry Pi will run into a Kernel Panic upon reboot!\\nDo not upgrade, do not reboot!\\nA preliminary solution is to not upgrade the system (via the Upgrade menu entry or 'apt-get upgrade') or to modify a configuration file. In the long run we would recommend to switch over to the new openHABian Raspbian based system image! This error message will keep reapearing even after you fixed the issue at hand.\\nPlease find all details regarding the issue and the resolution of it at: https://github.com/openhab/openhabian/issues/147"
if ! (whiptail --title "openHABian Raspberry Pi ua-netinst image detected" --yes-button "Continue" --no-button "Cancel" --yesno "$introtext" 20 80) then return 0; fi
fi
}
|
#!/usr/bin/env bash
#-------------------------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
#-------------------------------------------------------------------------------------------------------------
#
# Docs: https://github.com/microsoft/vscode-dev-containers/blob/main/script-library/docs/common.md
# Maintainer: The VS Code and Codespaces Teams
#
# Syntax: ./common-debian.sh [install zsh flag] [username] [user UID] [user GID] [upgrade packages flag] [install Oh My Zsh! flag] [Add non-free packages]
set -e
INSTALL_ZSH=${1:-"true"}
USERNAME=${2:-"automatic"}
USER_UID=${3:-"automatic"}
USER_GID=${4:-"automatic"}
UPGRADE_PACKAGES=${5:-"true"}
INSTALL_OH_MYS=${6:-"true"}
ADD_NON_FREE_PACKAGES=${7:-"false"}
SCRIPT_DIR="$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)"
if [ "$(id -u)" -ne 0 ]; then
echo -e 'Script must be run as root. Use sudo, su, or add "USER root" to your Dockerfile before running this script.'
exit 1
fi
# Ensure that login shells get the correct path if the user updated the PATH using ENV.
rm -f /etc/profile.d/00-restore-env.sh
echo "export PATH=${PATH//$(sh -lc 'echo $PATH')/\$PATH}" > /etc/profile.d/00-restore-env.sh
chmod +x /etc/profile.d/00-restore-env.sh
# If in automatic mode, determine if a user already exists, if not use vscode
if [ "${USERNAME}" = "auto" ] || [ "${USERNAME}" = "automatic" ]; then
USERNAME=""
POSSIBLE_USERS=("vscode" "node" "codespace" "$(awk -v val=1000 -F ":" '$3==val{print $1}' /etc/passwd)")
for CURRENT_USER in ${POSSIBLE_USERS[@]}; do
if id -u ${CURRENT_USER} > /dev/null 2>&1; then
USERNAME=${CURRENT_USER}
break
fi
done
if [ "${USERNAME}" = "" ]; then
USERNAME=vscode
fi
elif [ "${USERNAME}" = "none" ]; then
USERNAME=root
USER_UID=0
USER_GID=0
fi
# Load markers to see which steps have already run
MARKER_FILE="/usr/local/etc/vscode-dev-containers/common"
if [ -f "${MARKER_FILE}" ]; then
echo "Marker file found:"
cat "${MARKER_FILE}"
source "${MARKER_FILE}"
fi
# Ensure apt is in non-interactive to avoid prompts
export DEBIAN_FRONTEND=noninteractive
# Function to call apt-get if needed
apt-get-update-if-needed()
{
if [ ! -d "/var/lib/apt/lists" ] || [ "$(ls /var/lib/apt/lists/ | wc -l)" = "0" ]; then
echo "Running apt-get update..."
apt-get update
else
echo "Skipping apt-get update."
fi
}
# Run install apt-utils to avoid debconf warning then verify presence of other common developer tools and dependencies
if [ "${PACKAGES_ALREADY_INSTALLED}" != "true" ]; then
PACKAGE_LIST="apt-utils \
git \
openssh-client \
gnupg2 \
iproute2 \
procps \
lsof \
htop \
net-tools \
psmisc \
curl \
wget \
rsync \
ca-certificates \
unzip \
zip \
nano \
vim-tiny \
less \
jq \
lsb-release \
apt-transport-https \
dialog \
libc6 \
libgcc1 \
libkrb5-3 \
libgssapi-krb5-2 \
libicu[0-9][0-9] \
liblttng-ust0 \
libstdc++6 \
zlib1g \
locales \
sudo \
ncdu \
man-db \
strace \
manpages \
manpages-dev \
init-system-helpers"
# Needed for adding manpages-posix and manpages-posix-dev which are non-free packages in Debian
if [ "${ADD_NON_FREE_PACKAGES}" = "true" ]; then
CODENAME="$(cat /etc/os-release | grep -oE '^VERSION_CODENAME=.+$' | cut -d'=' -f2)"
sed -i -E "s/deb http:\/\/(deb|httpredir)\.debian\.org\/debian ${CODENAME} main/deb http:\/\/\1\.debian\.org\/debian ${CODENAME} main contrib non-free/" /etc/apt/sources.list
sed -i -E "s/deb-src http:\/\/(deb|httredir)\.debian\.org\/debian ${CODENAME} main/deb http:\/\/\1\.debian\.org\/debian ${CODENAME} main contrib non-free/" /etc/apt/sources.list
sed -i -E "s/deb http:\/\/(deb|httpredir)\.debian\.org\/debian ${CODENAME}-updates main/deb http:\/\/\1\.debian\.org\/debian ${CODENAME}-updates main contrib non-free/" /etc/apt/sources.list
sed -i -E "s/deb-src http:\/\/(deb|httpredir)\.debian\.org\/debian ${CODENAME}-updates main/deb http:\/\/\1\.debian\.org\/debian ${CODENAME}-updates main contrib non-free/" /etc/apt/sources.list
sed -i "s/deb http:\/\/security\.debian\.org\/debian-security ${CODENAME}\/updates main/deb http:\/\/security\.debian\.org\/debian-security ${CODENAME}\/updates main contrib non-free/" /etc/apt/sources.list
sed -i "s/deb-src http:\/\/security\.debian\.org\/debian-security ${CODENAME}\/updates main/deb http:\/\/security\.debian\.org\/debian-security ${CODENAME}\/updates main contrib non-free/" /etc/apt/sources.list
sed -i "s/deb http:\/\/deb\.debian\.org\/debian ${CODENAME}-backports main/deb http:\/\/deb\.debian\.org\/debian ${CODENAME}-backports main contrib non-free/" /etc/apt/sources.list
sed -i "s/deb-src http:\/\/deb\.debian\.org\/debian ${CODENAME}-backports main/deb http:\/\/deb\.debian\.org\/debian ${CODENAME}-backports main contrib non-free/" /etc/apt/sources.list
echo "Running apt-get update..."
apt-get update
PACKAGE_LIST="${PACKAGE_LIST} manpages-posix manpages-posix-dev"
else
apt-get-update-if-needed
fi
# Install libssl1.1 if available
if [[ ! -z $(apt-cache --names-only search ^libssl1.1$) ]]; then
PACKAGE_LIST="${PACKAGE_LIST} libssl1.1"
fi
# Install appropriate version of libssl1.0.x if available
LIBSSL=$(dpkg-query -f '${db:Status-Abbrev}\t${binary:Package}\n' -W 'libssl1\.0\.?' 2>&1 || echo '')
if [ "$(echo "$LIBSSL" | grep -o 'libssl1\.0\.[0-9]:' | uniq | sort | wc -l)" -eq 0 ]; then
if [[ ! -z $(apt-cache --names-only search ^libssl1.0.2$) ]]; then
# Debian 9
PACKAGE_LIST="${PACKAGE_LIST} libssl1.0.2"
elif [[ ! -z $(apt-cache --names-only search ^libssl1.0.0$) ]]; then
# Ubuntu 18.04, 16.04, earlier
PACKAGE_LIST="${PACKAGE_LIST} libssl1.0.0"
fi
fi
echo "Packages to verify are installed: ${PACKAGE_LIST}"
apt-get -y install --no-install-recommends ${PACKAGE_LIST} 2> >( grep -v 'debconf: delaying package configuration, since apt-utils is not installed' >&2 )
PACKAGES_ALREADY_INSTALLED="true"
fi
# Get to latest versions of all packages
if [ "${UPGRADE_PACKAGES}" = "true" ]; then
apt-get-update-if-needed
apt-get -y upgrade --no-install-recommends
apt-get autoremove -y
fi
# Ensure at least the en_US.UTF-8 UTF-8 locale is available.
# Common need for both applications and things like the agnoster ZSH theme.
if [ "${LOCALE_ALREADY_SET}" != "true" ] && ! grep -o -E '^\s*en_US.UTF-8\s+UTF-8' /etc/locale.gen > /dev/null; then
echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen
locale-gen
LOCALE_ALREADY_SET="true"
fi
# Create or update a non-root user to match UID/GID.
if id -u ${USERNAME} > /dev/null 2>&1; then
# User exists, update if needed
if [ "${USER_GID}" != "automatic" ] && [ "$USER_GID" != "$(id -G $USERNAME)" ]; then
groupmod --gid $USER_GID $USERNAME
usermod --gid $USER_GID $USERNAME
fi
if [ "${USER_UID}" != "automatic" ] && [ "$USER_UID" != "$(id -u $USERNAME)" ]; then
usermod --uid $USER_UID $USERNAME
fi
else
# Create user
if [ "${USER_GID}" = "automatic" ]; then
groupadd $USERNAME
else
groupadd --gid $USER_GID $USERNAME
fi
if [ "${USER_UID}" = "automatic" ]; then
useradd -s /bin/bash --gid $USERNAME -m $USERNAME
else
useradd -s /bin/bash --uid $USER_UID --gid $USERNAME -m $USERNAME
fi
fi
# Add add sudo support for non-root user
if [ "${USERNAME}" != "root" ] && [ "${EXISTING_NON_ROOT_USER}" != "${USERNAME}" ]; then
echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME
chmod 0440 /etc/sudoers.d/$USERNAME
EXISTING_NON_ROOT_USER="${USERNAME}"
fi
# ** Shell customization section **
if [ "${USERNAME}" = "root" ]; then
USER_RC_PATH="/root"
else
USER_RC_PATH="/home/${USERNAME}"
fi
# Restore user .bashrc defaults from skeleton file if it doesn't exist or is empty
if [ ! -f "${USER_RC_PATH}/.bashrc" ] || [ ! -s "${USER_RC_PATH}/.bashrc" ] ; then
cp /etc/skel/.bashrc "${USER_RC_PATH}/.bashrc"
fi
# Restore user .profile defaults from skeleton file if it doesn't exist or is empty
if [ ! -f "${USER_RC_PATH}/.profile" ] || [ ! -s "${USER_RC_PATH}/.profile" ] ; then
cp /etc/skel/.profile "${USER_RC_PATH}/.profile"
fi
# .bashrc/.zshrc snippet
RC_SNIPPET="$(cat << 'EOF'
if [ -z "${USER}" ]; then export USER=$(whoami); fi
if [[ "${PATH}" != *"$HOME/.local/bin"* ]]; then export PATH="${PATH}:$HOME/.local/bin"; fi
# Display optional first run image specific notice if configured and terminal is interactive
if [ -t 1 ] && [[ "${TERM_PROGRAM}" = "vscode" || "${TERM_PROGRAM}" = "codespaces" ]] && [ ! -f "$HOME/.config/vscode-dev-containers/first-run-notice-already-displayed" ]; then
if [ -f "/usr/local/etc/vscode-dev-containers/first-run-notice.txt" ]; then
cat "/usr/local/etc/vscode-dev-containers/first-run-notice.txt"
elif [ -f "/workspaces/.codespaces/shared/first-run-notice.txt" ]; then
cat "/workspaces/.codespaces/shared/first-run-notice.txt"
fi
mkdir -p "$HOME/.config/vscode-dev-containers"
# Mark first run notice as displayed after 10s to avoid problems with fast terminal refreshes hiding it
((sleep 10s; touch "$HOME/.config/vscode-dev-containers/first-run-notice-already-displayed") &)
fi
# Set the default git editor
if [ "${TERM_PROGRAM}" = "vscode" ]; then
if [[ -n $(command -v code-insiders) && -z $(command -v code) ]]; then
export GIT_EDITOR="code-insiders --wait"
else
export GIT_EDITOR="code --wait"
fi
fi
EOF
)"
# code shim, it fallbacks to code-insiders if code is not available
cat << 'EOF' > /usr/local/bin/code
#!/bin/sh
get_in_path_except_current() {
which -a "$1" | grep -A1 "$0" | grep -v "$0"
}
code="$(get_in_path_except_current code)"
if [ -n "$code" ]; then
exec "$code" "$@"
elif [ "$(command -v code-insiders)" ]; then
exec code-insiders "$@"
else
echo "code or code-insiders is not installed" >&2
exit 127
fi
EOF
chmod +x /usr/local/bin/code
# systemctl shim - tells people to use 'service' if systemd is not running
cat << 'EOF' > /usr/local/bin/systemctl
#!/bin/sh
set -e
if [ -d "/run/systemd/system" ]; then
exec /bin/systemctl/systemctl "$@"
else
echo '\n"systemd" is not running in this container due to its overhead.\nUse the "service" command to start services intead. e.g.: \n\nservice --status-all'
fi
EOF
chmod +x /usr/local/bin/systemctl
# Codespaces bash and OMZ themes - partly inspired by https://github.com/ohmyzsh/ohmyzsh/blob/master/themes/robbyrussell.zsh-theme
CODESPACES_BASH="$(cat \
<<'EOF'
# Codespaces bash prompt theme
__bash_prompt() {
local userpart='`export XIT=$? \
&& [ ! -z "${GITHUB_USER}" ] && echo -n "\[\033[0;32m\]@${GITHUB_USER} " || echo -n "\[\033[0;32m\]\u " \
&& [ "$XIT" -ne "0" ] && echo -n "\[\033[1;31m\]➜" || echo -n "\[\033[0m\]➜"`'
local gitbranch='`\
export BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null); \
if [ "${BRANCH}" = "HEAD" ]; then \
export BRANCH=$(git describe --contains --all HEAD 2>/dev/null); \
fi; \
if [ "${BRANCH}" != "" ]; then \
echo -n "\[\033[0;36m\](\[\033[1;31m\]${BRANCH}" \
&& if git ls-files --error-unmatch -m --directory --no-empty-directory -o --exclude-standard ":/*" > /dev/null 2>&1; then \
echo -n " \[\033[1;33m\]✗"; \
fi \
&& echo -n "\[\033[0;36m\]) "; \
fi`'
local lightblue='\[\033[1;34m\]'
local removecolor='\[\033[0m\]'
PS1="${userpart} ${lightblue}\w ${gitbranch}${removecolor}\$ "
unset -f __bash_prompt
}
__bash_prompt
EOF
)"
CODESPACES_ZSH="$(cat \
<<'EOF'
# Codespaces zsh prompt theme
__zsh_prompt() {
local prompt_username
if [ ! -z "${GITHUB_USER}" ]; then
prompt_username="@${GITHUB_USER}"
else
prompt_username="%n"
fi
PROMPT="%{$fg[green]%}${prompt_username} %(?:%{$reset_color%}➜ :%{$fg_bold[red]%}➜ )" # User/exit code arrow
PROMPT+='%{$fg_bold[blue]%}%(5~|%-1~/…/%3~|%4~)%{$reset_color%} ' # cwd
PROMPT+='$(git_prompt_info)%{$fg[white]%}$ %{$reset_color%}' # Git status
unset -f __zsh_prompt
}
ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg_bold[cyan]%}(%{$fg_bold[red]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%} "
ZSH_THEME_GIT_PROMPT_DIRTY=" %{$fg_bold[yellow]%}✗%{$fg_bold[cyan]%})"
ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg_bold[cyan]%})"
__zsh_prompt
EOF
)"
# Add notice that Oh My Bash! has been removed from images and how to provide information on how to install manually
OMB_README="$(cat \
<<'EOF'
"Oh My Bash!" has been removed from this image in favor of a simple shell prompt. If you
still wish to use it, remove "~/.oh-my-bash" and install it from: https://github.com/ohmybash/oh-my-bash
You may also want to consider "Bash-it" as an alternative: https://github.com/bash-it/bash-it
See here for infomation on adding it to your image or dotfiles: https://aka.ms/codespaces/omb-remove
EOF
)"
OMB_STUB="$(cat \
<<'EOF'
#!/usr/bin/env bash
if [ -t 1 ]; then
cat $HOME/.oh-my-bash/README.md
fi
EOF
)"
# Add RC snippet and custom bash prompt
if [ "${RC_SNIPPET_ALREADY_ADDED}" != "true" ]; then
echo "${RC_SNIPPET}" >> /etc/bash.bashrc
echo "${CODESPACES_BASH}" >> "${USER_RC_PATH}/.bashrc"
echo 'export PROMPT_DIRTRIM=4' >> "${USER_RC_PATH}/.bashrc"
if [ "${USERNAME}" != "root" ]; then
echo "${CODESPACES_BASH}" >> "/root/.bashrc"
echo 'export PROMPT_DIRTRIM=4' >> "/root/.bashrc"
fi
chown ${USERNAME}:${USERNAME} "${USER_RC_PATH}/.bashrc"
RC_SNIPPET_ALREADY_ADDED="true"
fi
# Add stub for Oh My Bash!
if [ ! -d "${USER_RC_PATH}/.oh-my-bash}" ] && [ "${INSTALL_OH_MYS}" = "true" ]; then
mkdir -p "${USER_RC_PATH}/.oh-my-bash" "/root/.oh-my-bash"
echo "${OMB_README}" >> "${USER_RC_PATH}/.oh-my-bash/README.md"
echo "${OMB_STUB}" >> "${USER_RC_PATH}/.oh-my-bash/oh-my-bash.sh"
chmod +x "${USER_RC_PATH}/.oh-my-bash/oh-my-bash.sh"
if [ "${USERNAME}" != "root" ]; then
echo "${OMB_README}" >> "/root/.oh-my-bash/README.md"
echo "${OMB_STUB}" >> "/root/.oh-my-bash/oh-my-bash.sh"
chmod +x "/root/.oh-my-bash/oh-my-bash.sh"
fi
chown -R "${USERNAME}:${USERNAME}" "${USER_RC_PATH}/.oh-my-bash"
fi
# Optionally install and configure zsh and Oh My Zsh!
if [ "${INSTALL_ZSH}" = "true" ]; then
if ! type zsh > /dev/null 2>&1; then
apt-get-update-if-needed
apt-get install -y zsh
fi
if [ "${ZSH_ALREADY_INSTALLED}" != "true" ]; then
echo "${RC_SNIPPET}" >> /etc/zsh/zshrc
ZSH_ALREADY_INSTALLED="true"
fi
# Adapted, simplified inline Oh My Zsh! install steps that adds, defaults to a codespaces theme.
# See https://github.com/ohmyzsh/ohmyzsh/blob/master/tools/install.sh for official script.
OH_MY_INSTALL_DIR="${USER_RC_PATH}/.oh-my-zsh"
if [ ! -d "${OH_MY_INSTALL_DIR}" ] && [ "${INSTALL_OH_MYS}" = "true" ]; then
TEMPLATE_PATH="${OH_MY_INSTALL_DIR}/templates/zshrc.zsh-template"
USER_RC_FILE="${USER_RC_PATH}/.zshrc"
umask g-w,o-w
mkdir -p ${OH_MY_INSTALL_DIR}
git clone --depth=1 \
-c core.eol=lf \
-c core.autocrlf=false \
-c fsck.zeroPaddedFilemode=ignore \
-c fetch.fsck.zeroPaddedFilemode=ignore \
-c receive.fsck.zeroPaddedFilemode=ignore \
"https://github.com/ohmyzsh/ohmyzsh" "${OH_MY_INSTALL_DIR}" 2>&1
echo -e "$(cat "${TEMPLATE_PATH}")\nDISABLE_AUTO_UPDATE=true\nDISABLE_UPDATE_PROMPT=true" > ${USER_RC_FILE}
sed -i -e 's/ZSH_THEME=.*/ZSH_THEME="codespaces"/g' ${USER_RC_FILE}
mkdir -p ${OH_MY_INSTALL_DIR}/custom/themes
echo "${CODESPACES_ZSH}" > "${OH_MY_INSTALL_DIR}/custom/themes/codespaces.zsh-theme"
# Shrink git while still enabling updates
cd "${OH_MY_INSTALL_DIR}"
git repack -a -d -f --depth=1 --window=1
# Copy to non-root user if one is specified
if [ "${USERNAME}" != "root" ]; then
cp -rf "${USER_RC_FILE}" "${OH_MY_INSTALL_DIR}" /root
chown -R ${USERNAME}:${USERNAME} "${USER_RC_PATH}"
fi
fi
fi
# Persist image metadata info, script if meta.env found in same directory
META_INFO_SCRIPT="$(cat << 'EOF'
#!/bin/sh
. /usr/local/etc/vscode-dev-containers/meta.env
# Minimal output
if [ "$1" = "version" ] || [ "$1" = "image-version" ]; then
echo "${VERSION}"
exit 0
elif [ "$1" = "release" ]; then
echo "${GIT_REPOSITORY_RELEASE}"
exit 0
elif [ "$1" = "content" ] || [ "$1" = "content-url" ] || [ "$1" = "contents" ] || [ "$1" = "contents-url" ]; then
echo "${CONTENTS_URL}"
exit 0
fi
#Full output
echo
echo "Development container image information"
echo
if [ ! -z "${VERSION}" ]; then echo "- Image version: ${VERSION}"; fi
if [ ! -z "${DEFINITION_ID}" ]; then echo "- Definition ID: ${DEFINITION_ID}"; fi
if [ ! -z "${VARIANT}" ]; then echo "- Variant: ${VARIANT}"; fi
if [ ! -z "${GIT_REPOSITORY}" ]; then echo "- Source code repository: ${GIT_REPOSITORY}"; fi
if [ ! -z "${GIT_REPOSITORY_RELEASE}" ]; then echo "- Source code release/branch: ${GIT_REPOSITORY_RELEASE}"; fi
if [ ! -z "${BUILD_TIMESTAMP}" ]; then echo "- Timestamp: ${BUILD_TIMESTAMP}"; fi
if [ ! -z "${CONTENTS_URL}" ]; then echo && echo "More info: ${CONTENTS_URL}"; fi
echo
EOF
)"
if [ -f "${SCRIPT_DIR}/meta.env" ]; then
mkdir -p /usr/local/etc/vscode-dev-containers/
cp -f "${SCRIPT_DIR}/meta.env" /usr/local/etc/vscode-dev-containers/meta.env
echo "${META_INFO_SCRIPT}" > /usr/local/bin/devcontainer-info
chmod +x /usr/local/bin/devcontainer-info
fi
# Write marker file
mkdir -p "$(dirname "${MARKER_FILE}")"
echo -e "\
PACKAGES_ALREADY_INSTALLED=${PACKAGES_ALREADY_INSTALLED}\n\
LOCALE_ALREADY_SET=${LOCALE_ALREADY_SET}\n\
EXISTING_NON_ROOT_USER=${EXISTING_NON_ROOT_USER}\n\
RC_SNIPPET_ALREADY_ADDED=${RC_SNIPPET_ALREADY_ADDED}\n\
ZSH_ALREADY_INSTALLED=${ZSH_ALREADY_INSTALLED}" > "${MARKER_FILE}"
echo "Done!"
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React from 'react';
import { render } from 'enzyme';
import { requiredProps } from '../../../test/required_props';
import { EuiSplitPanel } from './split_panel';
describe('EuiSplitPanel', () => {
test('is rendered', () => {
const component = render(<EuiSplitPanel.Outer {...requiredProps} />);
expect(component).toMatchSnapshot();
});
describe('inner children', () => {
test('are rendered', () => {
const component = render(
<EuiSplitPanel.Outer>
<EuiSplitPanel.Inner />
</EuiSplitPanel.Outer>
);
expect(component).toMatchSnapshot();
});
});
test('accepts panel props', () => {
const component = render(
<EuiSplitPanel.Outer color="primary">
<EuiSplitPanel.Inner color="success" {...requiredProps} />
</EuiSplitPanel.Outer>
);
expect(component).toMatchSnapshot();
});
test('renders as row', () => {
const component = render(<EuiSplitPanel.Outer direction="row" />);
expect(component).toMatchSnapshot();
});
describe('responsive', () => {
// @ts-ignore innerWidth might be read only but we can still override it for the sake of testing
beforeAll(() => (window.innerWidth = 520));
afterAll(() => 1024); // reset to jsdom's default
test('is rendered at small screens', () => {
const component = render(<EuiSplitPanel.Outer />);
expect(component).toMatchSnapshot();
});
test('can be false', () => {
const component = render(<EuiSplitPanel.Outer responsive={false} />);
expect(component).toMatchSnapshot();
});
});
describe('responsive', () => {
// @ts-ignore innerWidth might be read only but we can still override it for the sake of testing
beforeAll(() => (window.innerWidth = 1000));
afterAll(() => 1024); // reset to jsdom's default
test('can be changed to different breakpoints', () => {
const component = render(<EuiSplitPanel.Outer responsive={['m', 'l']} />);
expect(component).toMatchSnapshot();
});
});
});
|
<filename>Lib/site-packages/PyQt5/examples/sql/querymodel.py
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
## the names of its contributors may be used to endorse or promote
## products derived from this software without specific prior written
## permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication, QTableView
from PyQt5.QtSql import QSqlQuery, QSqlQueryModel
import connection
class CustomSqlModel(QSqlQueryModel):
def data(self, index, role):
value = super(CustomSqlModel, self).data(index, role)
if value is not None and role == Qt.DisplayRole:
if index.column() == 0:
return '#%d' % value
elif index.column() == 2:
return value.upper()
if role == Qt.TextColorRole and index.column() == 1:
return QColor(Qt.blue)
return value
class EditableSqlModel(QSqlQueryModel):
def flags(self, index):
flags = super(EditableSqlModel, self).flags(index)
if index.column() in (1, 2):
flags |= Qt.ItemIsEditable
return flags
def setData(self, index, value, role):
if index.column() not in (1, 2):
return False
primaryKeyIndex = self.index(index.row(), 0)
id = self.data(primaryKeyIndex)
self.clear()
if index.column() == 1:
ok = self.setFirstName(id, value)
else:
ok = self.setLastName(id, value)
self.refresh()
return ok
def refresh(self):
self.setQuery('select * from person')
self.setHeaderData(0, Qt.Horizontal, "ID")
self.setHeaderData(1, Qt.Horizontal, "First name")
self.setHeaderData(2, Qt.Horizontal, "Last name")
def setFirstName(self, personId, firstName):
query = QSqlQuery()
query.prepare('update person set firstname = ? where id = ?')
query.addBindValue(firstName)
query.addBindValue(personId)
return query.exec_()
def setLastName(self, personId, lastName):
query = QSqlQuery()
query.prepare('update person set lastname = ? where id = ?')
query.addBindValue(lastName)
query.addBindValue(personId)
return query.exec_()
def initializeModel(model):
model.setQuery('select * from person')
model.setHeaderData(0, Qt.Horizontal, "ID")
model.setHeaderData(1, Qt.Horizontal, "First name")
model.setHeaderData(2, Qt.Horizontal, "<NAME>")
offset = 0
views = []
def createView(title, model):
global offset, views
view = QTableView()
views.append(view)
view.setModel(model)
view.setWindowTitle(title)
view.move(100 + offset, 100 + offset)
offset += 20
view.show()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
if not connection.createConnection():
sys.exit(1)
plainModel = QSqlQueryModel()
editableModel = EditableSqlModel()
customModel = CustomSqlModel()
initializeModel(plainModel)
initializeModel(editableModel)
initializeModel(customModel)
createView("Plain Query Model", plainModel)
createView("Editable Query Model", editableModel)
createView("Custom Query Model", customModel)
sys.exit(app.exec_())
|
package com.frewing.dump.core;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.OpenableColumns;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Provider used to read dump files created by {@link DataExporter}.
*
* We send content: URI to sender apps (such as gmail). This provider implement the URI.
*/
public class DumpFileProvider extends ContentProvider {
public static final String AUTHORITY = "com.android.contacts.dumpfile";
public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY);
@Override
public boolean onCreate() {
return true;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// Not needed.
throw new UnsupportedOperationException();
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Not needed.
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// Not needed.
throw new UnsupportedOperationException();
}
@Override
public String getType(Uri uri) {
return DataExporter.ZIP_MIME_TYPE;
}
/** @return the path part of a URI, without the beginning "/". */
private static String extractFileName(Uri uri) {
final String path = uri.getPath();
return path.startsWith("/") ? path.substring(1) : path;
}
/** @return file content */
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
if (!"r".equals(mode)) {
throw new UnsupportedOperationException();
}
final String fileName = extractFileName(uri);
DataExporter.ensureValidFileName(fileName);
final File file = DataExporter.getOutputFile(getContext(), fileName);
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
/**
* Used to provide {@link OpenableColumns#DISPLAY_NAME} and {@link OpenableColumns#SIZE}
* for a URI.
*/
@Override
public Cursor query(Uri uri, String[] inProjection, String selection, String[] selectionArgs,
String sortOrder) {
final String fileName = extractFileName(uri);
DataExporter.ensureValidFileName(fileName);
final String[] projection = (inProjection != null) ? inProjection
: new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};
final MatrixCursor c = new MatrixCursor(projection);
// Result will always have one row.
final MatrixCursor.RowBuilder b = c.newRow();
for (int i = 0; i < c.getColumnCount(); i++) {
final String column = projection[i];
if (OpenableColumns.DISPLAY_NAME.equals(column)) {
// Just return the requested path as the display name. We don't care if the file
// really exists.
b.add(fileName);
} else if (OpenableColumns.SIZE.equals(column)) {
final File file = DataExporter.getOutputFile(getContext(), fileName);
if (file.exists()) {
b.add(file.length());
} else {
// File doesn't exist -- return null for "unknown".
b.add(null);
}
} else {
throw new IllegalArgumentException("Unknown column " + column);
}
}
return c;
}
}
|
#!/bin/bash
set -e
ganache-cli --gasLimit 47000000000 2> /dev/null 1> /dev/null &
sleep 5 # to make sure ganache-cli is up and running before compiling
rm -rf build
truffle compile
truffle migrate --reset --network development
truffle test
kill -9 $(lsof -t -i:8545) |
<gh_stars>0
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
# License: BSD 3 clause
"""
Detect centrosomes spots in the GFP images.
"""
import os
import argparse
from utils import check_directories, initialize_script, end_script
from loader import get_fov_names
import bigfish.stack as stack
import bigfish.detection as detection
import bigfish.plot as plot
import numpy as np
if __name__ == "__main__":
print()
# parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("input_directory",
help="Path of the input directory.",
type=str)
parser.add_argument("output_directory",
help="Path of the output directory.",
type=str)
parser.add_argument("experiment",
help="Name of the experiment.",
type=str)
parser.add_argument("--log_directory",
help="Path of the log directory.",
type=str,
default="/Users/arthur/output/2020_adham/log")
parser.add_argument("--threshold",
help="Threshold to discriminate centrosomes.",
type=int,
default=-1)
# initialize parameters
args = parser.parse_args()
input_directory = args.input_directory
output_directory = args.output_directory
centrosome_directory = os.path.join(output_directory,
"detected_centrosomes")
plot_directory = os.path.join(output_directory, "plot",
"centrosome_detection")
experiment = args.experiment
log_directory = args.log_directory
threshold = args.threshold
# check directories exists
check_directories([input_directory, output_directory, centrosome_directory,
plot_directory, log_directory])
# initialize script
start_time = initialize_script(log_directory, experiment)
nb_images = 0
print("Images are saved with the pattern plate_well_gene_drug_fov")
print()
# parameters
plate = experiment.split("_")[0]
if plate in ["4", "5", "6"]:
voxel_size_z = None
voxel_size_yx = 206
else:
voxel_size_z = None
voxel_size_yx = 103
psf_z_gfp = None
psf_yx_gfp = 300
print("Spot detection...", "\n")
# read gfp images
images = []
filenames = []
fov_names_generator = get_fov_names(experiment)
for i, fov_name in enumerate(fov_names_generator):
filename = "{0}".format(fov_name)
filenames.append(filename)
print("\r", filename)
# read image
plate = fov_name.split("_")[0]
if plate in ["4", "5", "6"]:
path = os.path.join(input_directory,
"{0}_640.tif".format(fov_name))
else:
path = os.path.join(input_directory,
"{0}_488.tif".format(fov_name))
gfp = stack.read_image(path)
images.append(gfp)
nb_images += 1
# detect spots
if threshold != -1:
spots = detection.detect_spots(
images,
threshold=threshold,
voxel_size_z=voxel_size_z,
voxel_size_yx=voxel_size_yx,
psf_z=psf_z_gfp,
psf_yx=psf_yx_gfp)
else:
spots, threshold = detection.detect_spots(
images,
return_threshold=True,
voxel_size_z=voxel_size_z,
voxel_size_yx=voxel_size_yx,
psf_z=psf_z_gfp,
psf_yx=psf_yx_gfp)
print()
print("\r threshold: {0}".format(threshold), "\n")
print("Clustering and postprocessing...", "\n")
# process all images from the experiment
for i in range(nb_images):
image = images[i]
spots_ = spots[i]
filename = filenames[i]
print("\r", filename)
# decompose clusters
spots_post_decomposition, _, _ = detection.decompose_cluster(
image, spots_,
voxel_size_z=voxel_size_z,
voxel_size_yx=voxel_size_yx,
psf_z=psf_z_gfp,
psf_yx=psf_yx_gfp,
alpha=0.7, # alpha impacts the number of spots per cluster
beta=1) # beta impacts the number of detected clusters
# detect centrosomes
centrosomes_post_clustering, foci_centrosome = detection.detect_foci(
spots_post_decomposition,
voxel_size_z=voxel_size_z,
voxel_size_yx=voxel_size_yx,
radius=1000,
nb_min_spots=2)
centrosomes = np.concatenate(
(centrosomes_post_clustering[
centrosomes_post_clustering[:, 2] == -1, :2],
foci_centrosome[:, :2]),
axis=0)
# save centrosomes
path = os.path.join(centrosome_directory, "{0}.npy".format(filename))
stack.save_array(centrosomes, path)
# plot
image_contrasted = stack.rescale(image, channel_to_stretch=0)
path = os.path.join(plot_directory, "{0}.png".format(filename))
plot.plot_detection(image_contrasted,
spots=centrosomes,
shape="polygon",
radius=15,
color="orange",
linewidth=2,
framesize=(15, 15),
title="threshold: {0} | centrosomes: {1}".format(
threshold, len(centrosomes)),
path_output=path,
show=False)
print()
print("Number of images: {0}".format(nb_images))
end_script(start_time)
|
<gh_stars>0
package cmd
import (
"github.com/spf13/cobra"
)
// fmtCmd represents the fmt command
var fmtCmd = &cobra.Command{
Use: "fmt",
Short: "fmt formats graphql document files to std out",
}
func init() {
rootCmd.AddCommand(fmtCmd)
}
|
<gh_stars>1-10
/*
* hdhomerun_os_windows.c
*
* Copyright © 2006-2010 Silicondust USA Inc. <www.silicondust.com>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "hdhomerun_os.h"
static DWORD random_get32_context_tls = TlsAlloc();
uint32_t random_get32(void)
{
HCRYPTPROV *phProv = (HCRYPTPROV *)TlsGetValue(random_get32_context_tls);
if (!phProv) {
phProv = (HCRYPTPROV *)calloc(1, sizeof(HCRYPTPROV));
CryptAcquireContext(phProv, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
TlsSetValue(random_get32_context_tls, phProv);
}
uint32_t Result;
if (!CryptGenRandom(*phProv, sizeof(Result), (BYTE *)&Result)) {
return (uint32_t)getcurrenttime();
}
return Result;
}
uint64_t getcurrenttime(void)
{
return GetTickCount64();
}
void msleep_approx(uint64_t ms)
{
Sleep((DWORD)ms);
}
void msleep_minimum(uint64_t ms)
{
uint64_t stop_time = getcurrenttime() + ms;
while (1) {
uint64_t current_time = getcurrenttime();
if (current_time >= stop_time) {
return;
}
msleep_approx(stop_time - current_time);
}
}
int pthread_create(pthread_t *tid, void *attr, LPTHREAD_START_ROUTINE start, void *arg)
{
*tid = CreateThread(NULL, 0, start, arg, 0, NULL);
if (!*tid) {
return (int)GetLastError();
}
return 0;
}
int pthread_join(pthread_t tid, void **value_ptr)
{
while (1) {
DWORD ExitCode = 0;
if (!GetExitCodeThread(tid, &ExitCode)) {
return (int)GetLastError();
}
if (ExitCode != STILL_ACTIVE) {
return 0;
}
}
}
void pthread_mutex_init(pthread_mutex_t *mutex, void *attr)
{
*mutex = CreateMutex(NULL, FALSE, NULL);
}
void pthread_mutex_lock(pthread_mutex_t *mutex)
{
WaitForSingleObject(*mutex, INFINITE);
}
void pthread_mutex_unlock(pthread_mutex_t *mutex)
{
ReleaseMutex(*mutex);
}
bool_t hdhomerun_vsprintf(char *buffer, char *end, const char *fmt, va_list ap)
{
if (buffer >= end) {
return FALSE;
}
int length = _vsnprintf(buffer, end - buffer - 1, fmt, ap);
if (length < 0) {
*buffer = 0;
return FALSE;
}
if (buffer + length + 1 > end) {
*(end - 1) = 0;
return FALSE;
}
return TRUE;
}
bool_t hdhomerun_sprintf(char *buffer, char *end, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
bool_t result = hdhomerun_vsprintf(buffer, end, fmt, ap);
va_end(ap);
return result;
}
/*
* The console output format should be set to UTF-8, however in XP and Vista this breaks batch file processing.
* Attempting to restore on exit fails to restore if the program is terminated by the user.
* Solution - set the output format each printf.
*/
void console_vprintf(const char *fmt, va_list ap)
{
UINT cp = GetConsoleOutputCP();
SetConsoleOutputCP(CP_UTF8);
vprintf(fmt, ap);
SetConsoleOutputCP(cp);
}
void console_printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
console_vprintf(fmt, ap);
va_end(ap);
}
|
import sys
import numpy as np
from sklearn import svm
def angle(x, y):
"""Compute angle in degrees for points x,y on unit circle"""
if x < 0:
return 180 - np.arcsin(y) * 360 / (2 * np.pi)
else:
return (0 if y >= 0 else 360) + np.arcsin(y) * 360 / (2 * np.pi)
def compute_loss(inputfile, outputfile):
"""
Train an SVM based on points given in `inputfile`
Writes a loss based based on true decision boundary of y = 0 to `outputfile`
"""
# Read the teaching set in comma-delimited format
data = np.loadtxt(inputfile, delimiter=', ')
# If teaching set contains only one label, classify all points with that
# label, so true loss is 0.5.
if np.ndim(data) == 1 or len(np.unique(data[:, 0])) == 1:
loss = 0.5
else:
# Assumes the label is in the first column
train_y = data[:, 0]
# Assume the remaining columns are features
train_x = data[:, 1:]
# Train an SVM
clf = svm.SVC(kernel="linear")
clf.fit(train_x, train_y)
# Extract vector normal to decision boundary
ww = clf.coef_[0]
# Normalize
ww = ww / np.sqrt(sum(np.square(ww)))
# Return a true loss based on angle with [1,0]
an = angle(ww[0], ww[1])
loss = min(an / 180, 2 - an / 180)
with open(outputfile, 'w') as f:
f.write(str(loss))
if __name__ == "__main__":
compute_loss(sys.argv[1], sys.argv[2])
|
<reponame>LightDestory/Personal-Portfolio
import {Howl, Howler} from 'howler';
import {utilsInstance} from "./utils";
import {DataSound} from "./dataset";
interface soundFile {
readonly file: string,
readonly name: string,
readonly loop: boolean,
readonly autoplay: boolean,
readonly volume: number
}
class soundSystem {
/* Settings */
private soundSystemData: soundFile[];
private loadedSounds: { [name: string] : Howl } = {};
private muteDelay: ReturnType<typeof setTimeout> = null;
private soundOn: boolean = false;
constructor() {
this.soundSystemData = DataSound;
}
/* init system */
init(mutedCookie: string, isMobile: boolean): void {
console.log("init sound system");
Howler.mute(true);
this.loadSounds();
if (mutedCookie === "0") {
this.soundOn = true;
this.unMuteAll();
}
this.enableSoundControls();
if (!isMobile) {
this.enableMouseOverAnimation();
}
}
/* load sounds */
private loadSounds(): void {
this.soundSystemData.forEach(s => {
this.loadedSounds[s.name] = new Howl({
src: s.file,
loop: s.loop,
volume: s.volume,
name: s.name,
autoplay: s.autoplay
});
});
}
/* mute control */
muteAll(): void{
console.log("mute all");
this.toggleAnimation();
this.loadedSounds['ambient'].fade(1, 0, 1000);
this.muteDelay = setTimeout(function () {
Howler.mute(true);
}, 1500);
}
/* unmute control */
unMuteAll(): void {
console.log("unMute all");
this.toggleAnimation();
clearTimeout(this.muteDelay);
Howler.mute(false);
this.loadedSounds['ambient'].fade(0, 1, 1000);
}
/* toggle the sound-bars animation */
private toggleAnimation(): void {
document.querySelectorAll(".sbar").forEach(element => element.classList.toggle("noAnim"));
const icon = document.querySelector("#sound-icon").classList;
if (this.soundOn) {
icon.add("fa-volume-up");
icon.remove("fa-volume-mute");
} else {
icon.remove("fa-volume-up");
icon.add("fa-volume-mute");
}
}
isSoundOn(): boolean {
return this.soundOn;
}
/* enable Mouse on Over animation on the controls icon*/
private enableMouseOverAnimation(): void {
document.querySelector(".sound-controls").addEventListener("mouseover", () => {
const icon = document.querySelector("#sound-icon").classList;
if (this.soundOn) {
icon.remove("fa-volume-up");
icon.add("fa-volume-mute");
} else {
icon.add("fa-volume-up");
icon.remove("fa-volume-mute");
}
});
document.querySelector(".sound-controls").addEventListener("mouseout", () => {
const icon = document.querySelector("#sound-icon").classList;
if (!this.soundOn) {
icon.remove("fa-volume-up");
icon.add("fa-volume-mute");
} else {
icon.add("fa-volume-up");
icon.remove("fa-volume-mute");
}
});
}
/* enable sound controls such as mute and unmute */
private enableSoundControls(): void {
document.querySelector(".sound-controls").addEventListener("click", () => {
this.playClick();
if (this.soundOn) {
this.soundOn = false;
this.muteAll();
utilsInstance.setCookie("muted", 1, 1);
} else {
this.soundOn = true;
this.unMuteAll();
utilsInstance.setCookie("muted", 0, 1);
}
});
}
public playClick(): void {
this.loadedSounds['click'].play();
}
}
const soundSystemInstance: soundSystem = new soundSystem();
export {soundFile, soundSystemInstance} |
#!/usr/bin/env bash
rm db.sqlite3
rm report/migrations/ -fr
./manage.py makemigrations report
./manage.py migrate
echo "enter new password for admin"
./manage.py createsuperuser --username admin --email "" |
<filename>client/components/yearlySpend.js
import React, {Component} from 'react'
import {Bar} from 'react-chartjs-2'
import {connect} from 'react-redux'
import {yearly} from '../store/yearly'
const moment = require('moment')
class YearlySpend extends Component {
async componentDidMount() {
await this.props.yearlyTransaction()
}
render() {
const data = {
labels: [
moment()
.subtract(11, 'months')
.format('MMM'),
moment()
.subtract(10, 'months')
.format('MMM'),
moment()
.subtract(9, 'months')
.format('MMM'),
moment()
.subtract(8, 'months')
.format('MMM'),
moment()
.subtract(7, 'months')
.format('MMM'),
moment()
.subtract(6, 'months')
.format('MMM'),
moment()
.subtract(5, 'months')
.format('MMM'),
moment()
.subtract(4, 'months')
.format('MMM'),
moment()
.subtract(3, 'months')
.format('MMM'),
moment()
.subtract(2, 'months')
.format('MMM'),
moment()
.subtract(1, 'months')
.format('MMM'),
moment()
.subtract(0, 'months')
.format('MMM')
],
datasets: [
{
data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
label: 'USD',
backgroundColor: [
'rgba(255, 99, 132, 0.1)',
'rgba(54, 162, 235, 0.1)',
'rgba(255, 206, 86, 0.1)',
'rgba(83, 109, 254, 0.1)',
'rgba(195, 0, 255, 0.1)',
'rgba(0, 128, 0, 0.1)',
'rgba(128, 0, 0, 0.1)',
'rgba(0, 0, 128, 0.1)',
'rgba(45, 242, 132, 0.1)',
'rgba(64, 189, 34, 0.1)',
'rgba(242, 22, 132, 0.1)',
'rgba(64, 150, 242, 0.1)'
],
borderColor: [
'rgba(255, 99, 132)',
'rgba(54, 162, 235)',
'rgba(255, 206, 86)',
'rgba(83, 109, 254)',
'rgba(195, 0, 255)',
'rgba(0, 128, 0)',
'rgba(128, 0, 0)',
'rgba(0, 0, 128)',
'rgba(45, 242, 132)',
'rgba(64, 189, 34)',
'rgba(242, 22, 132)',
'rgba(64, 150, 242)'
],
hoverBackgroundColor: [
'rgba(255, 99, 132, 0.5)',
'rgba(0, 0, 255, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(83, 109, 254, 0.5)',
'rgba(195, 0, 255, 0.5)',
'rgba(0, 128, 0, 0.5)',
'rgba(128, 0, 0, 0.5)',
'rgba(0, 0, 128, 0.5)',
'rgba(45, 242, 132, 0.5)',
'rgba(64, 189, 34, 0.5)',
'rgba(242, 22, 132, 0.5)',
'rgba(64, 150, 242, 0.5)'
],
borderWidth: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
}
]
}
let transactions = this.props.transactions
if (transactions.length) {
data.datasets[0].data.forEach((_, index) => {
const currIdx = moment()
.subtract(11 - index, 'months')
.month()
let currentMonth = currIdx
let total = 0
for (let i = 0; i < transactions[0].transactions.length; i++) {
if (
Number(transactions[0].transactions[i].date.slice(5, 7)) ===
currentMonth + 1
) {
if (
currentMonth ===
moment()
.subtract(0, 'months')
.month() &&
Number(transactions[0].transactions[i].date.slice(0, 4)) !==
moment().year()
) {
continue
}
total += transactions[0].transactions[i].amount
}
}
data.datasets[0].data[index] = total
})
}
return (
<div>
{transactions.length ? (
<div className="yearlyContainer">
<h2>Annual Spending</h2>
<Bar data={data} />
</div>
) : (
<div>
<h5>Loading...</h5>
</div>
)}
</div>
)
}
}
const mapState = state => {
return {
transactions: state.yearly
}
}
const mapDispatch = dispatch => {
return {
yearlyTransaction: () => dispatch(yearly())
}
}
export default connect(mapState, mapDispatch)(YearlySpend)
|
<filename>javascript/util.js
/*
Title: Genetic Algorithm to calculate the shortest route
Autor: <NAME>
Data: 31/05/2018
License: The MIT License (MIT)
*/
/*************************************************************************************************/
/*Utilitarian Functions*/
function orderByProperty(prop)
{
var args = Array.prototype.slice.call(arguments, 1);
return function (a, b)
{
var equality = a[prop] - b[prop];
if (equality === 0 && arguments.length > 1) {
return orderByProperty.apply(null, args)(a, b);
}
return equality;
};
}
function sleep(milliseconds)
{
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
|
<reponame>Itzbenz/Atomic-Library
package Atom.Utility;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Meth {
public static long max(Long[] arr) {
List<Long> b = Arrays.asList(arr);
return Collections.max(b);
}
public static long min(Long[] arr) {
List<Long> b = Arrays.asList(arr);
return Collections.min(b);
}
public static double avg(Iterable<Long> arr) {
long sum = 0;
int length = 0;
for (long l : arr) {
sum += l;
length++;
}
return (double) sum / length;
}
public static int positive(int i) {
if (i < 0) return -i;
return i;
}
public static int negative(int i) {
if (i > 0) return -i;
return i;
}
public static float positive(float i) {
if (i < 0) return -i;
return i;
}
public static float negative(float i) {
if (i > 0) return -i;
return i;
}
public static long positive(long i) {
if (i < 0) return -i;
return i;
}
public static long negative(long i) {
if (i > 0) return -i;
return i;
}
public static double positive(double i) {
if (i < 0) return -i;
return i;
}
public static double negative(double i) {
if (i > 0) return -i;
return i;
}
}
|
class BufferWriter:
def __init__(self):
self.buffer = []
def _buffer_write(self, text):
# Append the given text to the internal buffer
self.buffer.append(text)
def flush(self):
# Return the contents of the buffer and clear it
content = ''.join(self.buffer)
self.buffer.clear()
return content
# Test the implementation
bw = BufferWriter()
bw._buffer_write('<table>')
bw._buffer_write('<tr><td>Row 1</td></tr>')
bw._buffer_write('<tr><td>Row 2</td></tr>')
result = bw.flush()
print(result) # Expected output: '<table><tr><td>Row 1</td></tr><tr><td>Row 2</td></tr>' |
def validate_expression(expression: str) -> bool:
stack = []
opening_brackets = "({["
closing_brackets = ")}]"
bracket_pairs = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in opening_brackets:
stack.append(char)
elif char in closing_brackets:
if not stack or stack.pop() != bracket_pairs[char]:
return False
if stack:
return False # Unbalanced parentheses
try:
eval(expression) # Using eval to check for valid arithmetic expression
except SyntaxError:
return False # Invalid expression
return True |
<gh_stars>0
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { tap } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { IDinoDetails } from '../../data/dino.interface';
import { ApiService } from './../../data/api.service';
import { AuthService } from 'src/app/auth/auth.service';
@Component({
selector: 'app-dinosaur-details',
templateUrl: './dinosaur-details.component.html',
styles: []
})
export class DinosaurDetailsComponent implements OnInit, OnDestroy {
name: string;
params$ = this.route.params.pipe(
tap(
params => this.dinoSetup(params['name']),
err => this.handleErr('No dinosaur found.')
)
);
loading = true;
error: boolean;
errorMsg: string;
dinoSub: Subscription;
dino: IDinoDetails;
toggleFavSub: Subscription;
savingFav: boolean;
constructor(
private title: Title,
private route: ActivatedRoute,
private api: ApiService,
public auth: AuthService
) { }
ngOnInit() {
}
private dinoSetup(nameParam: string) {
this.dinoSub = this.api.getDinoByName$(nameParam).subscribe(
dino => {
if (dino) {
this.title.setTitle(dino.name);
this.loading = false;
this.dino = dino;
} else {
this.handleErr('The dinosaur you requested could not be found.');
}
},
err => this.handleErr()
);
}
private handleErr(msg?: string) {
this.error = true;
this.loading = false;
if (msg) {
this.errorMsg = msg;
}
}
toggleFav() {
this.savingFav = true;
this.toggleFavSub = this.api.favDino$(this.dino.name).subscribe(
dino => {
this.dino = dino;
this.savingFav = false;
}
);
}
get getFavBtnText() {
if (this.savingFav) {
return 'Saving...';
}
return !this.dino.favorite ? 'Favorite' : 'Un-favorite';
}
ngOnDestroy() {
if (this.toggleFavSub) {
this.toggleFavSub.unsubscribe();
}
this.dinoSub.unsubscribe();
}
}
|
<reponame>g-k/rust-libs<filename>lib/database.rb
require 'json'
require 'active_support'
require 'active_support/core_ext/date/calculations'
require 'active_support/core_ext/time/calculations'
require 'lib/core_extensions'
require 'lib/path_helper'
require 'lib/mash'
require 'lib/category'
require 'lib/entry'
class Database
VERSION = 1
include PathHelper
attr_reader :db
class << self
include PathHelper
def github_token
@github_token ||= config.github_token
end
def config
@config ||= Mash.new(TOML.load_file(tmp_path.join("config.toml")))
end
def load
@@instance ||= new
end
end
def initialize
unless File.exist? db_path
init_db
else
@db = Mash.new JSON.load db_path
end
ensure_current_version!
end
def save
File.write(db_path, @db.to_json)
end
def init_db
FileUtils.mkdir_p File.dirname(db_path)
@db = Mash.new(version: VERSION)
end
def ensure_current_version!
VERSION == @db.version || init_db
end
def prepare
Category.all.each do |cat|
cat.unsorted_entries.each do |entry|
if cache_expired?(cat, entry)
write_cache(cat, entry, entry.fetch_from_origin)
else
log_info "Skipping cache generation for #{entry.id_with_cat} (last run was at #{Time.at read_cache(cat, entry).fetch_timestamp})"
end
end
end
return self
end
def read_cache cat, entry
@db.cache!.fetch!(cat.id).fetch!(entry.id)
end
def write_cache cat, entry, payload
@db.cache!.fetch!(cat.id)[entry.id] = payload.merge(fetch_timestamp: Time.now.tv_sec)
end
def expire_cache cat, entry
read_cache(cat, entry).fetch_timestamp = 0
end
def cache_expired? cat, entry
read_cache(cat, entry).fetch_timestamp.to_i < Time.now.yesterday.tv_sec
end
end
|
import random
def generate_password(at_least_one_letter, at_least_one_number, at_least_one_punctuation, letters, numbers, punctuation):
valid_characters = ""
if at_least_one_letter:
valid_characters += letters
if at_least_one_number:
valid_characters += numbers
if at_least_one_punctuation:
valid_characters += punctuation
password_length = 10 # Define the length of the password as 10 characters
password = ''.join(random.choice(valid_characters) for _ in range(password_length))
return password |
<reponame>ItsYoungDaddy/Templar-Cosmetics-Beta
package tae.cosmetics.guiscreen;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
import tae.cosmetics.Globals;
public abstract class AbstractTAEGuiScreen extends GuiScreen {
protected static final AbstractTAEGuiScreen DEFAULT = new AbstractTAEGuiScreen(new GuiHome()) {
@Override
public void onGuiClosed() {
}
@Override
protected void drawScreen0(int mouseX, int mouseY, float partialTicks) {
}
@Override
protected void updateButtonPositions(int x, int y) {
}
};
private GuiScreen parent;
public AbstractTAEGuiScreen settingsScreen = DEFAULT;
protected GuiButton back = new GuiButton(0, 0, 0, 70, 20, "Back");
protected ArrayList<GuiMessage> messagesToDraw = new ArrayList<>();
protected ResourceLocation BACKGROUND = new ResourceLocation("taecosmetics","textures/gui/playeroptions.png");
protected int guiwidth = 290;
protected int guiheight = 200;
protected boolean override = false;
protected AbstractTAEGuiScreen(GuiScreen parent) {
this.parent = parent;
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
int i = width / 2;
int j = height / 2;
updateButtonPositions(i, j);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.disableLighting();
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
mc.getTextureManager().bindTexture(BACKGROUND);
if(!override) {
Gui.drawScaledCustomSizeModalRect(i - guiwidth / 2, j - guiheight / 2, 0, 0, 242, 192, guiwidth, guiheight, 256, 256);
}
drawScreen0(mouseX, mouseY, partialTicks);
messagesToDraw.forEach(x -> x.draw());
super.drawScreen(mouseX, mouseY, partialTicks);
}
@Override
protected void actionPerformed(GuiButton button) throws IOException {
if(button == back) {
displayScreen(parent);
}
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
public static void displayScreen(GuiScreen screenIn) {
Minecraft.getMinecraft().addScheduledTask(() -> {
Minecraft.getMinecraft().displayGuiScreen(screenIn);
});
}
protected void addMessage(String message, int x, int y, int ticks, int color) {
messagesToDraw.add(new GuiMessage(message, x, y, ticks, color));
}
protected void addMessage(String message, int x, int y, int ticks, Color color) {
messagesToDraw.add(new GuiMessage(message, x, y, ticks, color.getRGB()));
}
@Override
public void initGui() {
buttonList.add(back);
}
@Override
public abstract void onGuiClosed();
protected abstract void drawScreen0(int mouseX, int mouseY, float partialTicks);
public static void drawHoveringTextGlobal(String text, int x, int y) {
DEFAULT.drawHoveringText(text, x, y);
}
@Override
public void drawHoveringText(String text, int x, int y) {
drawHoveringText(Arrays.asList(text), x, y, Minecraft.getMinecraft().fontRenderer);
}
@Override
protected void drawHoveringText(List<String> textLines, int x, int y, FontRenderer font) {
if (!textLines.isEmpty()) {
int i = 0;
for (String s : textLines)
{
int j = font.getStringWidth(s);
if (j > i)
{
i = j;
}
}
int l1 = x + 12;
int i2 = y - 12;
int k = 8;
if (textLines.size() > 1)
{
k += 2 + (textLines.size() - 1) * 10;
}
this.drawGradientRect(l1 - 3, i2 - 4, l1 + i + 3, i2 - 3, -267386864, -267386864);
this.drawGradientRect(l1 - 3, i2 + k + 3, l1 + i + 3, i2 + k + 4, -267386864, -267386864);
this.drawGradientRect(l1 - 3, i2 - 3, l1 + i + 3, i2 + k + 3, -267386864, -267386864);
this.drawGradientRect(l1 - 4, i2 - 3, l1 - 3, i2 + k + 3, -267386864, -267386864);
this.drawGradientRect(l1 + i + 3, i2 - 3, l1 + i + 4, i2 + k + 3, -267386864, -267386864);
this.drawGradientRect(l1 - 3, i2 - 3 + 1, l1 - 3 + 1, i2 + k + 3 - 1, 1347420415, 1344798847);
this.drawGradientRect(l1 + i + 2, i2 - 3 + 1, l1 + i + 3, i2 + k + 3 - 1, 1347420415, 1344798847);
this.drawGradientRect(l1 - 3, i2 - 3, l1 + i + 3, i2 - 3 + 1, 1347420415, 1347420415);
this.drawGradientRect(l1 - 3, i2 + k + 2, l1 + i + 3, i2 + k + 3, 1344798847, 1344798847);
for (int k1 = 0; k1 < textLines.size(); ++k1)
{
String s1 = textLines.get(k1);
font.drawStringWithShadow(s1, (float)l1, (float)i2, -1);
if (k1 == 0)
{
i2 += 2;
}
i2 += 10;
}
}
}
protected abstract void updateButtonPositions(int x, int y);
static class GuiMessage extends Gui implements Globals {
private String message;
private int x;
private int y;
private int ticks;
private int color;
public GuiMessage(String message, int x, int y, int ticks, int color) {
this.message = message;
this.x = x;
this.y = y;
this.ticks = ticks;
this.color = color;
}
public void draw() {
if(ticks > 0) {
ticks--;
mc.fontRenderer.drawString(message, x, y, color);
}
}
}
}
|
<reponame>dereekb/dbcomponents<gh_stars>0
export * from './model';
export * from './model.copy';
export * from './model.conversion';
export * from './model.conversion.field';
export * from './model.modify';
export * from './id.batch';
|
#!/usr/bin/env bash
b5:module_load docker
DOCKER_COMPOSER_SERVICE="php"
DOCKER_COMPOSER_USER="www-data"
DOCKER_COMPOSER_PATH="/app/build"
DOCKER_COMPOSER_VENDOR_DIR="/app/vendor"
DOCKER_COMPOSER_RUNBIN_SCRIPT="/opt/composer_runbin.sh"
docker_composer:docker_container_run() {
docker:container_run \
-e DOCKER_COMPOSER_PATH="${DOCKER_COMPOSER_PATH}" \
-e DOCKER_COMPOSER_VENDOR_DIR="${DOCKER_COMPOSER_VENDOR_DIR}" \
-w "${DOCKER_COMPOSER_PATH}" \
"${DOCKER_COMPOSER_SERVICE}" "$@"
}
docker_composer:run() {
docker_composer:docker_container_run composer "$@"
}
docker_composer:install() {
docker_composer:run install
}
docker_composer:update() {
docker_composer:run update
}
docker_composer:runbin() {
docker_composer:docker_container_run "${DOCKER_COMPOSER_RUNBIN_SCRIPT}" "$@"
}
task:composer() {
docker_composer:run "$@"
}
|
/******************************************************************************
*
*
* Program: MoveLabel
*
* Programmer: <NAME>
* Date: 05/25/2018
* School: Northwest Guilford High School
*
*
* Description: This class creates a MoveLabel object by extending HBox. it is basically
* a specific creation of an HBox that serves as the bottom toolbar for the
* game, displaying whose move it is or who has won the game and allowing
* the user to start a new game
*
* Learned: I learned how to extend the HBox class to create objects that fit my specific needs
*
*
* Difficulties: I had a lot of difficulties with getting the HBox to display the correct colors
* luckily, I was able to use some online resources to teach myself
* CSS and Pane-specific methods related to the Color class
*
*********************************************************************************/
import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.text.*;
import javafx.scene.shape.Circle;
import javafx.geometry.*;
import javafx.scene.control.Button;
public class MoveLabel extends HBox
{
/*
* Instance variables
*/
private int moveColor;
private Label moveLabel;
private Circle myCircle;
/*
* constructor of an HBox. basically the same as a regular HBox except sets a width and by default will
* make it fill with the gameplay setup
*/
public MoveLabel()
{
super();
//setAlignment(Pos.CENTER);
setPrefWidth(1000);
playSetup();
}
/*
* gameplay setup: makes the HBox appear as it should during a game by displaying whose move it is
*/
public void playSetup()
{
getChildren().clear(); // clear any prior nodes in the HBox
moveColor = 1;
/*
* create a Red circle since red moves first
*/
myCircle= new Circle();
myCircle.setStroke(Color.BLACK);
myCircle.setRadius(50);
/*
* create two labels that say it is red's turn
*/
moveLabel = new Label("RED");
moveLabel.setFont(Font.font("Times New Roman",FontWeight.BOLD, 50));
moveLabel.setTextAlignment(TextAlignment.RIGHT);
moveLabel.setPrefWidth(450);
setColor();
getChildren().removeAll();
Label generic = new Label("To Move: ");
generic.setPrefWidth(450);
generic.setFont(Font.font("Times New Roman",50));
/*
* add all three nodes to the HBox
*/
generic.setAlignment(Pos.CENTER_RIGHT);
getChildren().addAll(generic, myCircle, moveLabel);
setPrefWidth(800);
setPrefHeight(100);
}
/*
* set color method. changes the information during gameplay by switching between
* displaying that it is red's turn to move and it is blue turn's to move
*/
public void setColor()
{
if(moveColor % 4 == 1)
{
myCircle.setFill(Color.RED);
moveLabel.setText("RED");
moveLabel.setTextFill(Color.RED);
}
else
{
myCircle.setFill(Color.BLUE);
moveLabel.setText("BLUE ");
moveLabel.setTextFill(Color.BLUE);
}
}
/*
* setWinner method: display's the winner by removing the gameplay commentary and showing a winner
* statement. also adds a button that, when clicked, starts a new game
*/
public void setWinner(Button returnButton, int t)
{
getChildren().clear(); // clear out the gameplay nodes
/*
* show who has won
*/
Label winnerLabel = new Label();
if(t % 4 == 1) // BLUE wins
{
winnerLabel.setText("Red Wins");
winnerLabel.setTextFill(Color.RED);
}
else if (t % 4 == 3) // RED wins
{
winnerLabel.setText("Blue Wins");
winnerLabel.setTextFill(Color.BLUE);
}
else // its a tie
{
winnerLabel.setText("It's a Tie");
}
winnerLabel.setPrefWidth(500);
winnerLabel.setPrefHeight(200);
winnerLabel.setFont(Font.font("Times New Roman", 40));
winnerLabel.setAlignment(Pos.CENTER);
/*
* edit the play again button and add both nodes to the HBox
*/
returnButton.setText("PLAY AGAIN");
returnButton.setStyle("-fx-background-color: green");
getChildren().addAll(winnerLabel, returnButton);
}
/*
* switch the color by adding 4 and taking a mod2. called after each valid move
*/
public void switchColor()
{
moveColor += 2;
moveColor %= 4;
setColor();
}
}
|
#!/bin/sh -e
set -o errexit
###
# Copyright (c) 2015-2019, Antoine "vv221/vv222" Le Gonidec
# Copyright (c) 2016-2019, Solène "Mopi" Huault
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# This software is provided by the copyright holders and contributors "as is"
# and any express or implied warranties, including, but not limited to, the
# implied warranties of merchantability and fitness for a particular purpose
# are disclaimed. In no event shall the copyright holder or contributors be
# liable for any direct, indirect, incidental, special, exemplary, or
# consequential damages (including, but not limited to, procurement of
# substitute goods or services; loss of use, data, or profits; or business
# interruption) however caused and on any theory of liability, whether in
# contract, strict liability, or tort (including negligence or otherwise)
# arising in any way out of the use of this software, even if advised of the
# possibility of such damage.
###
###
# Battle Chef Brigade
# build native packages from the original installers
# send your bug reports to mopi@dotslashplay.it
###
script_version=20181216.1
# Set game-specific variables
GAME_ID='battle-chef-brigade'
GAME_NAME='Battle Chef Brigade'
ARCHIVE_GOG='battle_chef_brigade_14725_624_23675.sh'
ARCHIVE_GOG_URL='https://www.gog.com/game/battle_chef_brigade'
ARCHIVE_GOG_MD5='d35140bf757e387a2e47198f96356d00'
ARCHIVE_GOG_SIZE='1300000'
ARCHIVE_GOG_VERSION='14725.624-gog23675'
ARCHIVE_GOG_TYPE='mojosetup'
ARCHIVE_DOC_DATA_PATH='data/noarch/docs'
ARCHIVE_DOC_DATA_FILES='*'
ARCHIVE_GAME_BIN_PATH='data/noarch/game'
ARCHIVE_GAME_BIN_FILES='BattleChefBrigade.x86_64 BattleChefBrigade_Data/*/x86_64'
ARCHIVE_GAME_DATA_PATH='data/noarch/game'
ARCHIVE_GAME_DATA_FILES='BattleChefBrigade_Data'
DATA_DIRS='./logs'
APP_MAIN_TYPE='native'
# shellcheck disable=SC2016
APP_MAIN_PRERUN='if ! command -v pulseaudio >/dev/null 2>&1; then
mkdir --parents libs
ln --force --symbolic /dev/null libs/libpulse-simple.so.0
export LD_LIBRARY_PATH="libs:$LD_LIBRARY_PATH"
else
if [ -e "libs/libpulse-simple.so.0" ]; then
rm libs/libpulse-simple.so.0
rmdir --ignore-fail-on-non-empty libs
fi
pulseaudio --start
fi
export LANG=C'
APP_MAIN_EXE='BattleChefBrigade.x86_64'
# shellcheck disable=SC2016
APP_MAIN_OPTIONS='-logFile ./logs/$(date +%F-%R).log'
APP_MAIN_ICON='BattleChefBrigade_Data/Resources/UnityPlayer.png'
PACKAGES_LIST='PKG_BIN PKG_DATA'
PKG_DATA_ID="${GAME_ID}-data"
PKG_DATA_DESCRIPTION='data'
PKG_BIN_ARCH='64'
PKG_BIN_DEPS="$PKG_DATA_ID glibc libstdc++"
# Load common functions
target_version='2.10'
if [ -z "$PLAYIT_LIB2" ]; then
: "${XDG_DATA_HOME:="$HOME/.local/share"}"
for path in\
"$PWD"\
"$XDG_DATA_HOME/play.it"\
'/usr/local/share/games/play.it'\
'/usr/local/share/play.it'\
'/usr/share/games/play.it'\
'/usr/share/play.it'
do
if [ -e "$path/libplayit2.sh" ]; then
PLAYIT_LIB2="$path/libplayit2.sh"
break
fi
done
fi
if [ -z "$PLAYIT_LIB2" ]; then
printf '\n\033[1;31mError:\033[0m\n'
printf 'libplayit2.sh not found.\n'
exit 1
fi
# shellcheck source=play.it-2/lib/libplayit2.sh
. "$PLAYIT_LIB2"
# Extract game data
extract_data_from "$SOURCE_ARCHIVE"
prepare_package_layout
rm --recursive "$PLAYIT_WORKDIR/gamedata"
# Write launchers
PKG='PKG_BIN'
write_launcher 'APP_MAIN'
# Build package
PKG='PKG_DATA'
icons_linking_postinst 'APP_MAIN'
write_metadata 'PKG_DATA'
write_metadata 'PKG_BIN'
build_pkg
# Clean up
rm --recursive "$PLAYIT_WORKDIR"
# Print instructions
print_instructions
exit 0
|
#!/usr/bin/env bash
# Terminate already running bar instances
killall -q polybar
# Wait until the processes have been shut down
while pgrep -u $UID -x polybar >/dev/null; do sleep 1; done
# Launch the bar
polybar -q main -c "$HOME"/.config/polybar/nordic/config.ini &
|
const revisions = require('puppeteer/lib/cjs/puppeteer/revisions.js');
const args = process.argv.slice(2);
console.log(revisions['PUPPETEER_REVISIONS'][args[0]]);
|
#import the necessary libraries
import math
from collections import Counter
#function to calculate the inverse document frequency
def inverse_document_frequency(term, documents):
num_documents_containing_term = 0
for document in documents:
if term in document:
num_documents_containing_term += 1
return math.log(float(len(documents)) / num_documents_containing_term)
#function to calculate the tf*idf score
def tf_idf_score(term, document, documents):
tf = float(document.count(term)) / sum(document.count(word) for word in document)
idf = inverse_document_frequency(term, documents)
return tf * idf
#function to find the relevant documents
def search(query, documents):
query_terms = query.split(' ')
scores = {document_index: 0 for document_index in range(len(documents))}
for term in query_terms:
for document_index, document in enumerate(documents):
scores[document_index] += tf_idf_score(term, document, documents)
return scores
#test data
documents = ["this is a sentence", "this is another sentence", "this sentence is irrelevant"]
#search for a sentence
query = "this sentence"
result = search(query, documents)
#print the relevent documents
print(result) # {0: 0.6931471805599453, 1: 0.6931471805599453, 2: 0.0} |
<reponame>wejs/we-core
/**
* Session store loader file
* only load session store modules if session are enabled
*/
module.exports = function sessionStoreLoader(we, weExpress) {
if (we.config.session) {
const session = require('express-session');
// - default session storage
// To change the session store change the we.config.session.store
// To disable session set we.config.session to null
if (we.config.session && !we.config.session.store && we.db.activeConnectionConfig.dialect == 'mysql') {
const c = we.db.defaultConnection.connectionManager.config;
let SessionStore = require('express-mysql-session');
we.config.session.store = new SessionStore({
host: c.host || 'localhost',
port: c.port || 3306,
user: c.username,
password: <PASSWORD>,
database: c.database
});
we.config.session.resave = true;
we.config.session.saveUninitialized = true;
}
if (we.config.session) {
// save the instance for reuse in plugins
we.sessionStore = we.config.session.store;
we.session = session(we.config.session);
weExpress.use(we.session);
}
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.