Search is not available for this dataset
content
stringlengths 60
399M
| max_stars_repo_name
stringlengths 6
110
|
---|---|
<|start_filename|>public/assets/js/get_comments.js<|end_filename|>
$(document).ready(() => {
// On click on .comment class...
$(".feed").on('click', '.comment', (event) => {
// Fetch the pid of the post
let pid = event.target.id.split("_")[1];
// Toggle the class
$(`#postid_${pid}.feed-comments`).toggleClass('hide-comment');
// If the selected feed comment has class of 'hide-content'...
if ($(`#postid_${pid}.feed-comments`).hasClass('hide-comment')) {
// ..then display the comment section and load comments
$(`#postid_${pid}.feed-comments`).show();
// ..and change the class to fas
$(`#postid_${pid}.comment`).removeClass('far').addClass('fas');
// Load into the appropriate post, the comments.
// Pass pid as POST argument via .load() method
$(`#postid_${pid}.feed-comments`).load('../../includes/get_comments.php', {pid:pid});
} else {
// Else.. just hide
$(`#postid_${pid}.feed-comments`).hide();
// ..and change the class to far
$(`#postid_${pid}.comment`).removeClass('fas').addClass('far');
}
});
$(".feed").on('keydown', '.post-comment', (event) => {
if (event.keyCode == 13) {
let pid = event.target.id.split("_")[1];
let comment_content = $(`#postid_${pid}.post-comment`).val();
$.ajax({
url: '../../includes/post_comment.php',
method: 'POST',
data: {pid:pid, comment_content:comment_content},
success: (data) => {
// On success, re-load the contents of the appropriate comment section
$(`#postid_${pid}.feed-comments`).load('../../includes/get_comments.php', {pid:pid});
}
});
}
});
});
<|start_filename|>public/assets/js/logout.js<|end_filename|>
$(() => {
let timer = 3;
var interval = setInterval(() => {
$(".countdown").text(timer);
timer--;
if (timer < 0) {
clearInterval(interval);
window.location.replace('/public');
}
}, 1000);
});
<|start_filename|>public/assets/js/upload_post.js<|end_filename|>
$(document).ready(() => {
$("#photo-input").on('click', (event) => {
// console.log(event.target.files);
});
$("#video-input").on('click', () => {
});
});
<|start_filename|>public/assets/js/auth.js<|end_filename|>
$(() => {
$("#login-form").validate({
rules: {
username: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 6
}
}
});
$("#signup-form").validate({
rules: {
username_signup: {
required: true,
minlength: 5
},
email_signup: {
required: true,
email: true
},
password_signup: {
required: true,
minlength: 6
},
password_signup_c: {
required: true,
minlength: 6,
equalTo: "#password_signup"
}
}
});
$("a[href*='#signup']").on('click', () => {
$("#login-form").toggle();
$("#signup-form").toggle();
});
$("a[href*='#login']").on('click', () => {
$("#login-form").toggle();
$("#signup-form").toggle();
});
if (window.location.hash == '#signup') {
$("#login-form").hide();
$("#signup-form").show();
} else if (window.location.hash == '#login') {
$("#login-form").show();
$("#signup-form").hide();
}
});
<|start_filename|>public/assets/css/custom.css<|end_filename|>
.h-100v {
min-height: 100vh; }
.auth-box {
padding: 2rem 2rem 1rem 2rem;
background: #fff;
text-align: center;
box-shadow: 0 0 5px 0;
color: #ccc; }
.auth-box .logo {
margin: 2rem auto; }
.auth-box h3 {
color: #34495e;
margin-bottom: 2rem; }
.auth-box h4 {
color: #34495e; }
.auth-box input {
border: 0;
border-bottom: 1px solid #ccc;
border-radius: 0;
background: #f8f8f8; }
.auth-box input:focus {
box-shadow: 0 0; }
.auth-box button {
width: 100%;
margin-top: 1rem; }
.auth-box a {
text-decoration: none; }
.auth-box a:hover {
font-weight: bold; }
.auth-box .helper {
margin-top: 1rem;
font-size: 15px;
color: #aaa; }
.auth-box label {
color: #e74c3c; }
.auth-box #signup-form {
display: none; }
#navbar {
background: #fff;
color: #ccc;
box-shadow: 0 0 5px 0; }
#navbar .fa-fw {
font-size: 1.8rem;
color: #ccc; }
#navbar .fa-fw:hover {
color: #aaa; }
.feed {
margin: 0 auto; }
.feed-row {
margin: 2rem auto;
background: #fff;
box-shadow: 0 0 5px 0;
border: 1px solid #ccc;
color: #ccc; }
.feed-row .feed-post {
padding: 0; }
.feed-row .feed-post h3 {
position: relative;
margin-left: 3.25rem;
top: 0.6rem;
font-size: 1rem;
text-transform: lowercase;
color: #34495e; }
.feed-row .feed-post h3 a {
color: inherit;
text-decoration: none; }
.feed-row .feed-post h3 a:hover {
font-weight: bold; }
.feed-row .feed-post .feed-user {
padding: 0.5rem 1rem;
margin-bottom: 0.75rem; }
.feed-row .feed-post .feed-user img.thumbnail {
position: absolute;
border-radius: 50%;
border: 1px solid #ccc; }
.feed-row .feed-post .feed-media img.feed-img {
max-width: 100%; }
.feed-row .feed-post .feed-media video {
max-width: 100%; }
.feed-row .feed-post .feed-reaction {
padding: 0.5rem 0;
text-align: center;
border-bottom: 1px solid #ccc; }
.feed-row .feed-post .feed-reaction span {
position: absolute;
top: 5px;
margin-left: 5px; }
.feed-row .feed-post .feed-reaction .far.fa-heart:hover {
cursor: pointer;
color: #e74c3c; }
.feed-row .feed-post .feed-reaction .far.fa-comment:hover {
cursor: pointer;
color: #3498db; }
.feed-row .feed-post .feed-reaction .fas {
cursor: pointer; }
.feed-row .feed-post .feed-reaction .fas.fa-heart {
color: #e74c3c; }
.feed-row .feed-post .feed-reaction .fas.fa-comment {
color: #3498db; }
.feed-row .feed-post .feed-comments .comment {
padding: 0.35rem 0.5rem; }
.feed-row .feed-post .feed-comments .comment a {
font-weight: bold; }
.feed-row .feed-post .feed-comments .comment .comment-user {
color: #34495e; }
.feed-row .feed-post .feed-comments .comment .comment-content {
color: #bbb; }
.feed-row .feed-post .feed-comments input {
width: 100%;
border: 0;
border-top: 1px solid #ccc;
padding: 0.25rem 0.5rem;
font-weight: 300; }
.upload {
margin: 0 auto;
text-align: center; }
.upload .upload-content {
margin: 2rem auto auto; }
.upload .upload-content .fas {
cursor: pointer;
color: #34495e; }
.upload .upload-content .fas:hover {
color: #444; }
.upload .upload-content input {
display: none; }
body {
background: #fafafa; }
/*# sourceMappingURL=custom.css.map */
<|start_filename|>public/assets/js/like_action.js<|end_filename|>
$(document).ready(() => {
$(".feed").load('../../includes/get_feed.php');
// Post Like Ajax request
$(".feed").on('click', '.like', (event) => {
let id = event.target.id;
let split_id = id.split("_");
let pid = split_id[1];
$.ajax({
url: '../../includes/like_action.php',
method: 'POST',
data: {pid:pid},
success: (data) => {
event.target.classList.remove('far');
event.target.classList.add('fas');
event.target.classList.remove('like');
event.target.classList.add('unlike');
}
});
});
$(".feed").on('click', '.unlike', (event) => {
let unlike_id = event.target.id;
let split_unlike_id = unlike_id.split("_");
let unlike_pid = split_unlike_id[1];
$.ajax({
url: '../../includes/unlike_action.php',
method: 'POST',
data: {unlike_pid:unlike_pid},
success: (data) => {
event.target.classList.remove('fas');
event.target.classList.add('far');
event.target.classList.remove('unlike');
event.target.classList.add('like');
}
});
});
}); | nikosgatzoulis/instagram-clone-php |
<|start_filename|>example/lib/sample_event.dart<|end_filename|>
import 'package:cell_calendar/cell_calendar.dart';
import 'package:flutter/material.dart';
List<CalendarEvent> sampleEvents() {
final today = DateTime.now();
final sampleEvents = [
CalendarEvent(
eventName: "New iPhone",
eventDate: today.add(Duration(days: -42)),
eventBackgroundColor: Colors.black),
CalendarEvent(
eventName: "Writing test",
eventDate: today.add(Duration(days: -30)),
eventBackgroundColor: Colors.deepOrange),
CalendarEvent(
eventName: "Play soccer",
eventDate: today.add(Duration(days: -7)),
eventBackgroundColor: Colors.greenAccent),
CalendarEvent(
eventName: "Learn about history",
eventDate: today.add(Duration(days: -7))),
CalendarEvent(
eventName: "Buy new keyboard",
eventDate: today.add(Duration(days: -7))),
CalendarEvent(
eventName: "Walk around the park",
eventDate: today.add(Duration(days: -7)),
eventBackgroundColor: Colors.deepOrange),
CalendarEvent(
eventName: "Buy a present for Rebecca",
eventDate: today.add(Duration(days: -7)),
eventBackgroundColor: Colors.pink),
CalendarEvent(
eventName: "Firebase", eventDate: today.add(Duration(days: -7))),
CalendarEvent(eventName: "Task Deadline", eventDate: today),
CalendarEvent(
eventName: "Jon's Birthday",
eventDate: today.add(Duration(days: 3)),
eventBackgroundColor: Colors.green),
CalendarEvent(
eventName: "Date with Rebecca",
eventDate: today.add(Duration(days: 7)),
eventBackgroundColor: Colors.pink),
CalendarEvent(
eventName: "Start to study Spanish",
eventDate: today.add(Duration(days: 13))),
CalendarEvent(
eventName: "Have lunch with Mike",
eventDate: today.add(Duration(days: 13)),
eventBackgroundColor: Colors.green),
CalendarEvent(
eventName: "Buy new Play Station software",
eventDate: today.add(Duration(days: 13)),
eventBackgroundColor: Colors.indigoAccent),
CalendarEvent(
eventName: "Update my flutter package",
eventDate: today.add(Duration(days: 13))),
CalendarEvent(
eventName: "Watch movies in my house",
eventDate: today.add(Duration(days: 21))),
CalendarEvent(
eventName: "Medical Checkup",
eventDate: today.add(Duration(days: 30)),
eventBackgroundColor: Colors.red),
CalendarEvent(
eventName: "Gym",
eventDate: today.add(Duration(days: 42)),
eventBackgroundColor: Colors.indigoAccent),
];
return sampleEvents;
}
| AndrewJEON/cell_calendar |
<|start_filename|>game.js<|end_filename|>
import Main from './js/main'
new Main()
| wqzwh/wx-game |
<|start_filename|>smoke-test/diagram-assertions-graphviz.test.js<|end_filename|>
const fs = require('fs')
const path = require('path')
const basePath = process.env.SMOKE_TEST_BASE_PATH
const diagramFileName = 'diagram.png';
console.info("Asserting expected diagram PNG at " + path.join(basePath, diagramFileName))
describe('Created diagram PNG file', ()=>{
it ('should exist', ()=>{
const dirFiles = fs.readdirSync(basePath)
expect(dirFiles).toContain(diagramFileName)
})
it ('should have a reasonable size', ()=>{
const fileProps = fs.statSync(path.join(basePath, diagramFileName))
// On my local setup and Graphviz impl. the diagram is 229KB. In other environmenrts it seems to differ.
expect(fileProps.size / 1024).toBeGreaterThan(160) //200KB
expect(fileProps.size / 1024).toBeLessThan(400) //200KB
})
})
<|start_filename|>testSetup.js<|end_filename|>
import fs from 'fs';
import rimraf from 'rimraf';
module.exports = async () => {
const basePath = `${process.cwd()}/test-generated`
rimraf.sync(basePath)
fs.mkdirSync(basePath)
};
<|start_filename|>jest.config.js<|end_filename|>
module.exports = {
testMatch: ['**/src/**/tests/**/*.test.ts'],
testPathIgnorePatterns: ["/node_modules/"],
reporters: ["default"],
globalSetup: "./testSetup.js"
}
<|start_filename|>smoke-test/diagram-assertions-cytoscape.test.js<|end_filename|>
const path = require('path')
const fs = require('fs')
const basePath = process.env.SMOKE_TEST_BASE_PATH
const diagramFolderName = 'diagram';
console.info("Asserting expected static website with Cytoscape at: " + path.join(basePath, diagramFolderName))
describe('Genretated static website', ()=>{
it ('should exist as expected', ()=>{
const index = new File(`${basePath}/${diagramFolderName}/index.html`)
expect(index.stats.size).toBeGreaterThanOrEqual(300)
expect(index.body).toContain("CDK-Dia")
const icons = new File(`${basePath}/${diagramFolderName}/icons`)
expect(icons.stats.isDirectory()).toBeTruthy()
const js = new File(`${basePath}/${diagramFolderName}/js`)
expect(js.stats.isDirectory()).toBeTruthy()
const elementsJson = new File(`${basePath}/${diagramFolderName}/cy-elements.json`)
expect(JSON.parse(elementsJson.body).length).toBeGreaterThanOrEqual(2)
const stylesJson = new File(`${basePath}/${diagramFolderName}/cy-styles.json`)
expect(JSON.parse(stylesJson.body).length).toBeGreaterThanOrEqual(15)
})
})
class File {
stats
body
constructor(path) {
this.stats = fs.statSync(path)
if (!this.stats.isDirectory()) {
this.body = fs.readFileSync(path).toString()
}
}
} | Flolight/cdk-dia |
<|start_filename|>skychanger-bukkit/src/main/java/com/dscalzi/skychanger/bukkit/internal/SkyChangeImpl.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.bukkit.internal;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.dscalzi.skychanger.bukkit.api.SkyChanger;
import com.dscalzi.skychanger.core.api.SkyAPI;
import com.dscalzi.skychanger.core.api.SkyPacket;
import com.dscalzi.skychanger.core.internal.wrap.IPlayer;
import com.dscalzi.skychanger.core.internal.manager.MessageManager;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
public class SkyChangeImpl implements SkyAPI {
public static final List<String> FREEZE_UNSUPPORTED = Stream.of("1.8", "1.13").collect(Collectors.toList());
/* API Methods */
@Override
public boolean changeSky(IPlayer p, float number) {
return changeSky(p, SkyPacket.RAIN_LEVEL_CHANGE, number);
}
@Override
public boolean changeSky(IPlayer p, SkyPacket packet, float number) {
try {
int major = ReflectionUtil.getMajor(), minor = ReflectionUtil.getMinor();
if(major > 1 || (major == 1 && minor >= 17)) {
MessageManager.getInstance().featureUnsupported(p, "1.17+");
}
Object payload = null;
if(major == 1) {
if(minor >= 17) {
payload = createPacket_117_plus(packet.getValue(), number);
} else if(minor >= 16) {
payload = createPacket_116(packet.getValue(), number);
} else {
payload = createPacket_18_to_115(packet.getValue(), number);
}
}
if(payload != null) {
if(minor >= 17) {
deliverPacket(payload, (Player)p.getOriginal());
} else {
deliverPacketLegacy(payload, (Player)p.getOriginal());
}
return true;
} else {
MessageManager.getInstance().logPacketError();
return false;
}
} catch(Throwable t) {
MessageManager.getInstance().logPacketError();
t.printStackTrace();
return false;
}
}
@Override
public boolean freeze(IPlayer p) {
return sendFreezePacket((Player)p.getOriginal());
}
@Override
public boolean unfreeze(IPlayer p) {
return p.teleport(p.getLocation());
}
/* NMS Utility */
protected Object getConnectionLegacy(Player player) throws InvocationTargetException, IllegalAccessException, NoSuchFieldException {
Class<?> ocbPlayer = ReflectionUtil.getOCBClass("entity.CraftPlayer");
Method getHandle = ReflectionUtil.getMethod(ocbPlayer, "getHandle");
Object nmsPlayer = Objects.requireNonNull(getHandle).invoke(player);
Field conField = nmsPlayer.getClass().getField("playerConnection");
return conField.get(nmsPlayer);
}
protected Object getConnection(Player player) throws InvocationTargetException, IllegalAccessException, NoSuchFieldException {
Class<?> ocbPlayer = ReflectionUtil.getOCBClass("entity.CraftPlayer");
Method getHandle = ReflectionUtil.getMethod(ocbPlayer, "getHandle");
Object nmsPlayer = Objects.requireNonNull(getHandle).invoke(player);
Field conField = nmsPlayer.getClass().getField("b");
return conField.get(nmsPlayer);
}
protected void deliverPacketLegacy(Object packet, Player player) throws NoSuchMethodException,
IllegalAccessException, NoSuchFieldException, InvocationTargetException {
Method sendPacket = ReflectionUtil.getNMSClassLegacy("PlayerConnection")
.getMethod( "sendPacket", ReflectionUtil.getNMSClassLegacy("Packet"));
sendPacket.invoke(this.getConnectionLegacy(player), packet);
}
protected void deliverPacket(Object packet, Player player) throws NoSuchMethodException,
IllegalAccessException, NoSuchFieldException, InvocationTargetException {
Method sendPacket = ReflectionUtil.getMCClass("server.network.PlayerConnection")
.getMethod( "sendPacket", ReflectionUtil.getMCClass("network.protocol.Packet"));
sendPacket.invoke(this.getConnection(player), packet);
}
/* Sky Change Packet Creation */
protected Object createPacket_18_to_115(int packetNum, float number) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> ClientboundGameEventPacket = ReflectionUtil.getNMSClassLegacy("PacketPlayOutGameStateChange");
Constructor<?> packetConstructor = ClientboundGameEventPacket.getConstructor(int.class, float.class);
return packetConstructor.newInstance(packetNum, number);
}
public Object createPacket_116(int packetNum, float number) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> ClientboundGameEventPacket = ReflectionUtil.getNMSClassLegacy("PacketPlayOutGameStateChange");
Class<?> packetTypeClass = ReflectionUtil.getDeclaredClass(ClientboundGameEventPacket, "a");
Constructor<?> packetConstructor = ClientboundGameEventPacket.getConstructor(packetTypeClass, float.class);
Constructor<?> packetTypeConstructor = Objects.requireNonNull(packetTypeClass).getConstructor(int.class);
Object packetType = packetTypeConstructor.newInstance(packetNum);
return packetConstructor.newInstance(packetType, number);
}
public Object createPacket_117_plus(int packetNum, float number) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> ClientboundGameEventPacket = ReflectionUtil.getMCClass("network.protocol.game.PacketPlayOutGameStateChange");
Class<?> packetTypeClass = ReflectionUtil.getDeclaredClass(ClientboundGameEventPacket, "a");
Constructor<?> packetConstructor = ClientboundGameEventPacket.getConstructor(packetTypeClass, float.class);
Constructor<?> packetTypeConstructor = Objects.requireNonNull(packetTypeClass).getConstructor(int.class);
Object packetType = packetTypeConstructor.newInstance(packetNum);
return packetConstructor.newInstance(packetType, number);
}
/* Freeze NMS Utility */
// 1.16+
private Object getTypeKey(Class<?> WorldClass, Object world) throws InvocationTargetException, IllegalAccessException {
Method getTypeKey = Objects.requireNonNull(ReflectionUtil.getMethod(WorldClass, "getTypeKey"));
return getTypeKey.invoke(world);
}
private Object getDimensionManager1162Plus(Class<?> WorldClass, Object world) throws InvocationTargetException, IllegalAccessException {
Method getDimensionManager = Objects.requireNonNull(ReflectionUtil.getMethod(WorldClass, "getDimensionManager"));
return getDimensionManager.invoke(world);
}
// 1.16+
private Object getDimensionKey(Class<?> WorldClass, Object world) throws InvocationTargetException, IllegalAccessException {
Method getDimensionKey = Objects.requireNonNull(ReflectionUtil.getMethod(WorldClass, "getDimensionKey"));
return getDimensionKey.invoke(world);
}
private Object getWorldServer(Player player) throws InvocationTargetException, IllegalAccessException {
Class<?> craftWorldClass = ReflectionUtil.getOCBClass("CraftWorld");
Method getHandle = Objects.requireNonNull(ReflectionUtil.getMethod(craftWorldClass, "getHandle"));
return getHandle.invoke(player.getWorld());
}
private Object getDimensionManager(Object worldServer) throws InvocationTargetException, IllegalAccessException, NoSuchFieldException {
Class<?> worldProviderClass = ReflectionUtil.getNMSClassLegacy("WorldProvider");
Class<?> worldClass = ReflectionUtil.getNMSClassLegacy("World");
Field worldProviderField = worldClass.getDeclaredField("worldProvider");
Object worldProvider = worldProviderField.get(worldServer);
Method getDimensionManager = Objects.requireNonNull(ReflectionUtil.getMethod(worldProviderClass, "getDimensionManager"));
return getDimensionManager.invoke(worldProvider);
}
// 1.13, 1.14, 1.15
private Object getWorldType(Object worldServer) throws InvocationTargetException, IllegalAccessException {
Class<?> WorldServerClass = ReflectionUtil.getNMSClassLegacy("WorldServer");
Method getWorldData = Objects.requireNonNull(ReflectionUtil.getMethod(WorldServerClass, "getWorldData"));
Object worldData = getWorldData.invoke(worldServer);
Class<?> worldDataClass = ReflectionUtil.getNMSClassLegacy("WorldData");
Method getType = Objects.requireNonNull(ReflectionUtil.getMethod(worldDataClass, "getType"));
return getType.invoke(worldData);
}
private int getWorldEnvironmentId(Player player) throws InvocationTargetException, IllegalAccessException {
Method getId = Objects.requireNonNull(ReflectionUtil.getMethod(World.Environment.class, "getId"));
return (int) getId.invoke(player.getWorld().getEnvironment());
}
private int getGameModeValue(Player player) throws InvocationTargetException, IllegalAccessException {
Method deprecatedGetValue = Objects.requireNonNull(ReflectionUtil.getMethod(GameMode.class, "getValue"));
return (int) deprecatedGetValue.invoke(player.getGameMode());
}
private Object getEnumGamemode(Class<?> EnumGamemodeClass, Player player) throws InvocationTargetException, IllegalAccessException {
Method gmGetById = Objects.requireNonNull(ReflectionUtil.getMethod(EnumGamemodeClass, "getById", int.class));
return gmGetById.invoke(null, getGameModeValue(player));
}
private Object getEnumDifficulty(Class<?> EnumDifficultyClass, Player player) throws InvocationTargetException, IllegalAccessException {
Method diffGetById = Objects.requireNonNull(ReflectionUtil.getMethod(EnumDifficultyClass, "getById", int.class));
Method deprecatedGetValue = Objects.requireNonNull(ReflectionUtil.getMethod(Difficulty.class, "getValue"));
return diffGetById.invoke(null, deprecatedGetValue.invoke(player.getWorld().getDifficulty()));
}
/* Freeze Packet Creation and Dispatch */
protected boolean sendFreezePacket(Player player) {
int major = ReflectionUtil.getMajor(), minor = ReflectionUtil.getMinor(), r = ReflectionUtil.getR();
if(FREEZE_UNSUPPORTED.contains(major + "." + minor)) {
MessageManager.getInstance().featureUnsupported(SkyChanger.wrapPlayer(player), FREEZE_UNSUPPORTED.toString());
} else if(major > 1 || (major == 1 && minor >= 17)) {
List<String> unsupportedList = new ArrayList<>(FREEZE_UNSUPPORTED);
unsupportedList.add("1.17+");
MessageManager.getInstance().featureUnsupported(SkyChanger.wrapPlayer(player), unsupportedList.toString());
}
try {
Object packet;
Class<?> ClientboundRespawnPacket = minor >= 17
? ReflectionUtil.getMCClass("network.protocol.game.PacketPlayOutRespawn")
: ReflectionUtil.getNMSClassLegacy("PacketPlayOutRespawn");
if (major == 1) {
if (minor >= 17) {
// 1.17
Class<?> EnumGamemodeClass = ReflectionUtil.getMCClass("world.level.EnumGamemode");
Object worldServer = getWorldServer(player);
Object gameMode = getEnumGamemode(EnumGamemodeClass, player);
Class<?> WorldClass = ReflectionUtil.getMCClass("world.level.World");
Class<?> ResourceKeyClass = ReflectionUtil.getMCClass("resources.ResourceKey");
Class<?> DimensionManagerClass = ReflectionUtil.getMCClass("world.level.dimension.DimensionManager");
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(
DimensionManagerClass, // DimensionManager
ResourceKeyClass, // DimensionKey
long.class, // Seed
EnumGamemodeClass, // gameType
EnumGamemodeClass, // previousGameType
boolean.class, // isDebug
boolean.class, // isFlat
boolean.class); // keepAllPlayerData
packet = packetConstructor.newInstance(
getDimensionManager1162Plus(WorldClass, worldServer),
getDimensionKey(WorldClass, worldServer),
player.getWorld().getSeed(),
gameMode,
gameMode,
false,
false,
true);
} else if (minor >= 16) {
// 1.16
// Works sometimes so let's just say it works.
Class<?> EnumGamemodeClass = ReflectionUtil.getNMSClassLegacy("EnumGamemode");
Object worldServer = getWorldServer(player);
Object gameMode = getEnumGamemode(EnumGamemodeClass, player);
Class<?> WorldClass = ReflectionUtil.getNMSClassLegacy("World");
Class<?> ResourceKeyClass = ReflectionUtil.getNMSClassLegacy("ResourceKey");
if(r >= 2) {
// 1.16.2+
Class<?> DimensionManagerClass = ReflectionUtil.getNMSClassLegacy("DimensionManager");
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(
DimensionManagerClass, // DimensionManager
ResourceKeyClass, // DimensionKey
long.class, // Seed
EnumGamemodeClass, // gameType
EnumGamemodeClass, // previousGameType
boolean.class, // isDebug
boolean.class, // isFlat
boolean.class); // keepAllPlayerData
packet = packetConstructor.newInstance(
getDimensionManager1162Plus(WorldClass, worldServer),
getDimensionKey(WorldClass, worldServer),
player.getWorld().getSeed(),
gameMode,
gameMode,
false,
false,
true);
} else {
// 1.16.1
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(
ResourceKeyClass, // DimensionType
ResourceKeyClass, // DimensionKey
long.class, // Seed
EnumGamemodeClass, // gameType
EnumGamemodeClass, // previousGameType
boolean.class, // isDebug
boolean.class, // isFlat
boolean.class); // keepAllPlayerData
packet = packetConstructor.newInstance(
getTypeKey(WorldClass, worldServer),
getDimensionKey(WorldClass, worldServer),
player.getWorld().getSeed(),
gameMode,
gameMode,
false,
false,
true);
}
} else if (minor >= 13) {
// 1.13, 1.14, 1.15
Class<?> EnumGamemodeClass = ReflectionUtil.getNMSClassLegacy("EnumGamemode");
Object worldServer = getWorldServer(player);
Class<?> DimensionManagerClass = ReflectionUtil.getNMSClassLegacy("DimensionManager");
Class<?> WorldTypeClass = ReflectionUtil.getNMSClassLegacy("WorldType");
if (minor == 15) {
// 1.15 Constructor
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(
DimensionManagerClass,
long.class,
WorldTypeClass,
EnumGamemodeClass);
packet = packetConstructor.newInstance(
getDimensionManager(worldServer),
player.getWorld().getSeed(),
getWorldType(worldServer),
getEnumGamemode(EnumGamemodeClass, player));
} else if (minor == 14) {
// 1.14 Constructor
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(
DimensionManagerClass,
WorldTypeClass,
EnumGamemodeClass);
packet = packetConstructor.newInstance(
getDimensionManager(worldServer),
getWorldType(worldServer),
getEnumGamemode(EnumGamemodeClass, player));
} else {
// 1.13 Constructor
// Does not produce desired effect on 1.13
Class<?> EnumDifficultyClass = ReflectionUtil.getNMSClassLegacy("EnumDifficulty");
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(
DimensionManagerClass,
EnumDifficultyClass,
WorldTypeClass,
EnumGamemodeClass);
packet = packetConstructor.newInstance(
getDimensionManager(worldServer),
getEnumDifficulty(EnumDifficultyClass, player),
getWorldType(worldServer),
getEnumGamemode(EnumGamemodeClass, player));
}
} else {
// 1.12 and Below
// 1.8, 1.9, 1.10, 1.11, 1.12
Class<?> EnumDifficultyClass = ReflectionUtil.getNMSClassLegacy("EnumDifficulty");
Class<?> WorldTypeClass = ReflectionUtil.getNMSClassLegacy("WorldType");
final Object WorldType_NORMAL = WorldTypeClass.getField("NORMAL").get(null);
if(minor >= 10) {
// 1.10 - 1.12 Constructor
Class<?> EnumGamemodeClass = ReflectionUtil.getNMSClassLegacy("EnumGamemode");
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(int.class, EnumDifficultyClass, WorldTypeClass, EnumGamemodeClass);
packet = packetConstructor.newInstance(
getWorldEnvironmentId(player),
getEnumDifficulty(EnumDifficultyClass, player),
WorldType_NORMAL,
getEnumGamemode(EnumGamemodeClass, player));
} else {
// 1.8 - 1.9 Constructor
Class<?> WorldSettingsClass = ReflectionUtil.getNMSClassLegacy("WorldSettings");
Class<?> EnumGamemodeClass_Declared = ReflectionUtil.getDeclaredClass(WorldSettingsClass, "EnumGamemode");
Method getById = Objects.requireNonNull(ReflectionUtil.getMethod(EnumGamemodeClass_Declared, "getById", int.class));
Constructor<?> packetConstructor = ClientboundRespawnPacket.getConstructor(int.class, EnumDifficultyClass, WorldTypeClass, EnumGamemodeClass_Declared);
packet = packetConstructor.newInstance(
getWorldEnvironmentId(player),
getEnumDifficulty(EnumDifficultyClass, player),
WorldType_NORMAL,
getById.invoke(null, getGameModeValue(player)));
}
}
} else {
// Minecraft 2? Wow
MessageManager.getInstance().logPacketError();
return false;
}
if(minor >= 17) {
deliverPacket(packet, player);
} else {
deliverPacketLegacy(packet, player);
}
player.updateInventory();
return true;
} catch(Throwable t) {
MessageManager.getInstance().logPacketError();
t.printStackTrace();
return false;
}
}
}
<|start_filename|>skychanger-sponge/src/main/java/com/dscalzi/skychanger/sponge/internal/SkyChangeImpl.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.sponge.internal;
import com.dscalzi.skychanger.core.api.SkyAPI;
import com.dscalzi.skychanger.core.api.SkyPacket;
import com.dscalzi.skychanger.core.internal.wrap.IPlayer;
import net.minecraft.core.NonNullList;
import net.minecraft.network.protocol.game.ClientboundContainerSetContentPacket;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.network.protocol.game.ClientboundGameEventPacket;
import net.minecraft.network.protocol.game.ClientboundRespawnPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
import org.spongepowered.api.entity.living.player.Player;
public class SkyChangeImpl implements SkyAPI {
@Override
public boolean changeSky(IPlayer p, float number) {
return changeSky(p, SkyPacket.RAIN_LEVEL_CHANGE, number);
}
@Override
public boolean changeSky(IPlayer p, SkyPacket packet, float number) {
return sendPacket((Player)p.getOriginal(), packet.getValue(), number);
}
@Override
public boolean freeze(IPlayer p) {
return sendFreezePacket((Player)p.getOriginal());
}
@Override
public boolean unfreeze(IPlayer p) {
return p.teleport(p.getLocation());
}
private boolean sendPacket(Player player, int stateIn, float number) {
ClientboundGameEventPacket packet = new ClientboundGameEventPacket(new ClientboundGameEventPacket.Type(stateIn), number);
((ServerPlayer)player).connection.send(packet);
return true;
}
private boolean sendFreezePacket(Player player) {
ServerPlayer sp = ((ServerPlayer)player);
ClientboundRespawnPacket packet = new ClientboundRespawnPacket(
sp.level.dimensionType(),
sp.level.dimension(),
player.world().seed(),
sp.gameMode.getGameModeForPlayer(),
sp.gameMode.getPreviousGameModeForPlayer(),
false,
false,
true
);
NonNullList<ItemStack> nonNullList = NonNullList.create();
for(int i = 0; i < sp.inventoryMenu.slots.size(); ++i) {
nonNullList.add(sp.inventoryMenu.slots.get(i).getItem());
}
sp.connection.send(packet);
sp.connection.send(new ClientboundContainerSetContentPacket(sp.inventoryMenu.containerId, nonNullList));
sp.connection.send(new ClientboundContainerSetSlotPacket(-1, -1, sp.inventory.getCarried()));
return true;
}
}
<|start_filename|>skychanger-sponge/src/main/java/com/dscalzi/skychanger/sponge/internal/WildcardPermissionUtil.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.sponge.internal;
import com.dscalzi.skychanger.core.internal.util.IWildcardPermissionUtil;
import com.dscalzi.skychanger.core.internal.wrap.IPermissible;
import com.dscalzi.skychanger.core.internal.wrap.IWorld;
import org.spongepowered.api.SystemSubject;
import org.spongepowered.api.service.permission.Subject;
import java.util.Map;
import java.util.function.Predicate;
public class WildcardPermissionUtil extends IWildcardPermissionUtil {
@Override
public boolean hasGeneralChangeskyWorldPerm(IPermissible p) {
return hasGeneralPerm(p, CWORLDPERM);
}
@Override
public boolean hasGeneralFreezeWorldPerm(IPermissible p) {
return hasGeneralPerm(p, FWORLDPERM);
}
@Override
public boolean hasGeneralChangeskyRadiusPerm(IPermissible p) {
return hasGeneralPerm(p, CRADIUSPERM);
}
@Override
public boolean hasGeneralFreezeRadiusPerm(IPermissible p) {
return hasGeneralPerm(p, FRADIUSPERM);
}
private static boolean hasGeneralPerm(IPermissible ip, String perm) {
Subject p = (Subject)ip.getOriginal();
if(p instanceof SystemSubject) {
return true;
}
for (Map<String, Boolean> d : p.subjectData().allPermissions().values()) {
for(Map.Entry<String, Boolean> s : d.entrySet()) {
if(s.getKey().toLowerCase().startsWith(perm)) {
if(s.getValue()) {
return true;
}
}
}
}
return p.hasPermission(perm);
}
@Override
public boolean hasChangeskyWorldPerm(IPermissible p, IWorld w) {
return hasWorldPerm(p, w, CWORLDPERM);
}
@Override
public boolean hasFreezeWorldPerm(IPermissible p, IWorld w) {
return hasWorldPerm(p, w, FWORLDPERM);
}
private static boolean hasWorldPerm(IPermissible p, IWorld w, String perm) {
return hasPerm(p, (s) -> s.getKey().substring(perm.length() + 1).equals(w.getName()), perm)
|| p.hasPermission(perm);
}
@Override
public boolean hasChangeskyRadiusPerm(IPermissible p, double radius) {
return hasRadiusPerm(p, radius, CRADIUSPERM);
}
@Override
public boolean hasFreezeRadiusPerm(IPermissible p, double radius) {
return hasRadiusPerm(p, radius, FRADIUSPERM);
}
public static boolean hasRadiusPerm(IPermissible p, double radius, String perm) {
return hasPerm(p, (s) -> {
try {
double radiusLimit = Double.parseDouble(s.getKey().substring(perm.length() + 1));
return radius <= radiusLimit;
} catch (NumberFormatException e) {
// Malformed permission.
return false;
}
}, perm) || p.hasPermission(perm);
}
private static boolean hasPerm(IPermissible ip, Predicate<Map.Entry<String, Boolean>> hasSpecificPermissionTest, String perm) {
Subject p = (Subject)ip.getOriginal();
if(p instanceof SystemSubject) {
return true;
}
boolean canByRight = false;
for (Map<String, Boolean> d : p.subjectData().allPermissions().values()) {
for(Map.Entry<String, Boolean> s : d.entrySet()) {
final String effective = s.getKey().toLowerCase();
if (effective.equals(perm)) {
canByRight = s.getValue();
} else if (effective.contains(perm) && hasSpecificPermissionTest.test(s)) {
return s.getValue();
}
}
}
return canByRight;
}
public static String changeskyBasePerm() {
return CWORLDPERM;
}
public static String freezeBasePerm() {
return FWORLDPERM;
}
}
<|start_filename|>skychanger-bukkit/src/main/java/com/dscalzi/skychanger/bukkit/api/SkyChanger.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.bukkit.api;
import com.dscalzi.skychanger.bukkit.SkyChangerPlugin;
import com.dscalzi.skychanger.bukkit.internal.SkyChangeImpl;
import com.dscalzi.skychanger.bukkit.internal.wrap.BukkitPlayer;
import com.dscalzi.skychanger.core.api.SkyAPI;
import com.dscalzi.skychanger.core.internal.wrap.IPlayer;
import org.bukkit.entity.Player;
/**
* Utility class to obtain references to components of SkyChanger.
*/
public class SkyChanger {
private static final SkyAPI api = new SkyChangeImpl();
/**
* Get the SkyChanger plugin. If SkyChanger is not loaded yet, then this will
* return null.
* <p>
* If you are depending on SkyChanger in your plugin, you should place
* <code>softdepend: [SkyChanger]</code> or <code>depend: [SkyChanger]</code> in
* your plugin.yml so that this won't return null for you.
*
* @return the SkyChanger plugin if it is loaded, otherwise null.
*/
@SuppressWarnings("unused")
public static SkyChangerPlugin getPlugin() {
return SkyChangerPlugin.inst();
}
/**
* Get an instance of the SkyChanger API.
*
* @return An instance of the SkyChanger API.
*/
public static SkyAPI getAPI() {
return api;
}
/**
* Wrap a player instance to be sent to the API.
*
* @param p The player to be wrapped.
*
* @return A wrapped IPlayer instance of the provided player.
*/
@SuppressWarnings("unused")
public static IPlayer wrapPlayer(Player p) {
return BukkitPlayer.of(p);
}
}
<|start_filename|>skychanger-core/src/main/java/com/dscalzi/skychanger/core/internal/command/CommandAdapter.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.core.internal.command;
import com.dscalzi.skychanger.core.api.SkyAPI;
import com.dscalzi.skychanger.core.api.SkyPacket;
import com.dscalzi.skychanger.core.internal.wrap.ICommandSender;
import com.dscalzi.skychanger.core.internal.wrap.IOfflinePlayer;
import com.dscalzi.skychanger.core.internal.wrap.IPlayer;
import com.dscalzi.skychanger.core.internal.manager.MessageManager;
import com.dscalzi.skychanger.core.internal.util.IWildcardPermissionUtil;
import com.dscalzi.skychanger.core.internal.wrap.ICommandBlock;
import com.dscalzi.skychanger.core.internal.wrap.ILocation;
import com.dscalzi.skychanger.core.internal.wrap.IPlugin;
import com.dscalzi.skychanger.core.internal.wrap.IWorld;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class CommandAdapter {
private static final Pattern packetNum = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?");
private MessageManager mm;
private final IPlugin plugin;
public CommandAdapter(IPlugin plugin) {
this.plugin = plugin;
}
public boolean resolve(ICommandSender sender, String[] args) {
this.mm = MessageManager.getInstance();
if (args.length > 0) {
if (packetNum.matcher(args[0]).matches()) {
this.cmdChangeSky(sender, args);
return true;
}
if (args[0].equalsIgnoreCase("help")) {
mm.helpMessage(sender);
return true;
}
if (args[0].equalsIgnoreCase("freeze")) {
this.cmdFreeze(sender, false, args);
return true;
}
if (args[0].equalsIgnoreCase("unfreeze")) {
this.cmdFreeze(sender, true, args);
return true;
}
if (args[0].equalsIgnoreCase("version")) {
this.cmdVersion(sender);
return true;
}
if (args[0].equalsIgnoreCase("reload")) {
this.cmdReload(sender);
return true;
}
}
mm.helpMessage(sender);
return false;
}
private void cmdChangeSky(ICommandSender sender, String[] args) {
final IWildcardPermissionUtil wpu = plugin.getWildcardPermissionUtil();
final String basePerm = "skychanger.changesky";
boolean s = sender.hasPermission(basePerm + ".self");
boolean o = sender.hasPermission(basePerm + ".others");
boolean a = sender.hasPermission(basePerm + ".all");
boolean w = wpu.hasGeneralChangeskyWorldPerm(sender);
boolean r = wpu.hasGeneralChangeskyRadiusPerm(sender);
if (!s && !o && !a && !w && !r) {
mm.noPermission(sender);
return;
}
float rainLevel;
Float thunderLevel = null;
try {
rainLevel = Float.parseFloat(args[0]);
} catch (NumberFormatException e) {
mm.floatingPointOverflow(sender, args[0]);
return;
}
if(args.length > 1) {
try {
thunderLevel = Float.valueOf(args[1]);
} catch (NumberFormatException ignored) {
// Not specified
}
}
// shifted right when thunderLevel is present
int flagPos = thunderLevel == null ? 1 : 2;
int valPos = flagPos+1;
if (!sender.hasPermission("skychanger.bypasslimit")) {
float upper = plugin.getConfigManager().getUpperLimit();
float lower = plugin.getConfigManager().getLowerLimit();
if (rainLevel > upper || (thunderLevel != null && thunderLevel > upper)) {
mm.outOfBoundsUpper(sender, upper);
return;
}
if (lower > rainLevel || (thunderLevel != null && lower > thunderLevel)) {
mm.outOfBoundsLower(sender, lower);
return;
}
}
final SkyAPI api = plugin.getAPI();
if (args.length > flagPos) {
// Check if requested for all
if (args[flagPos].equalsIgnoreCase("-a")) {
if (!a) {
mm.noPermission(sender);
return;
}
for (IPlayer p : plugin.getOnlinePlayers()) {
api.changeSky(p, SkyPacket.RAIN_LEVEL_CHANGE, rainLevel);
if(thunderLevel != null) {
api.changeSky(p, SkyPacket.THUNDER_LEVEL_CHANGE, thunderLevel);
}
}
mm.packetSent(sender, "-a (" + mm.getString("message.everyone") + ")");
return;
}
// Check if requested for world
if (args[flagPos].equalsIgnoreCase("-w")) {
IWorld t;
if (args.length > valPos) {
t = plugin.getWorld(args[valPos]);
if (t == null) {
mm.worldDoesntExist(sender, args[valPos]);
return;
}
} else {
if (!(sender.isPlayer())) {
mm.mustSpecifyWorld(sender);
return;
}
t = ((IPlayer) sender).getWorld();
}
if (!wpu.hasChangeskyWorldPerm(sender, t)) {
mm.noPermission(sender);
return;
}
for (IPlayer p : t.getPlayers()) {
api.changeSky(p, SkyPacket.RAIN_LEVEL_CHANGE, rainLevel);
if(thunderLevel != null) {
api.changeSky(p, SkyPacket.THUNDER_LEVEL_CHANGE, thunderLevel);
}
}
mm.packetSent(sender, mm.getString("message.allPlayersIn") + " " + t.getName());
return;
}
// Check if requested for radius
if (args[flagPos].equalsIgnoreCase("-r")) {
if (sender.isConsole()) {
MessageManager.getInstance().denyNonPlayer(sender);
return;
}
if(args.length > valPos) {
double radius;
double radiusSq;
try {
radius = Double.parseDouble(args[valPos]);
if (!wpu.hasChangeskyRadiusPerm(sender, radius)) {
mm.noPermission(sender);
return;
}
radiusSq = Math.pow(radius, valPos);
} catch (NumberFormatException e) {
MessageManager.getInstance().radiusFormatError(sender);
return;
}
ILocation origin;
if (sender.isPlayer()) {
origin = ((IPlayer)sender).getLocation();
} else if (sender.isCommandBlock()) {
origin = ((ICommandBlock)sender).getLocation();
} else {
MessageManager.getInstance().denyNonPlayer(sender);
return;
}
for(IPlayer p : origin.getWorld().getPlayers()) {
if(Math.abs(origin.distanceSquared(p.getLocation())) <= radiusSq) {
api.changeSky(p, SkyPacket.RAIN_LEVEL_CHANGE, rainLevel);
if(thunderLevel != null) {
api.changeSky(p, SkyPacket.THUNDER_LEVEL_CHANGE, thunderLevel);
}
}
}
mm.packetSent(sender, mm.getString("message.allPlayersInRadius") + " " + args[2]);
return;
} else {
mm.mustSpecifyRadius(sender);
return;
}
}
// Check if param is a player
if (!o) {
mm.noPermission(sender);
return;
}
IOfflinePlayer target;
try {
target = plugin.getOfflinePlayer(MessageManager.formatFromInput(args[flagPos]));
} catch (IllegalArgumentException e) {
target = plugin.getOfflinePlayer(args[flagPos]);
}
if (target == null || !target.isOnline()) {
mm.playerNotFound(sender, target == null || target.getName() == null ? args[flagPos] : target.getName());
return;
}
// If a player specified their own name, we run the command as if the player
// param was not
// given. The others permission therefore includes the self.
if (!(sender.isPlayer()) || !target.getUniqueId().equals(((IPlayer) sender).getUniqueId())) {
boolean res = api.changeSky(target.getPlayer(), SkyPacket.RAIN_LEVEL_CHANGE, rainLevel);
if(thunderLevel != null) {
res = res && api.changeSky(target.getPlayer(), SkyPacket.THUNDER_LEVEL_CHANGE, thunderLevel);
}
if (res)
mm.packetSent(sender, target.getName());
else
mm.packetError(sender, target.getName());
return;
}
}
if (!(sender.isPlayer())) {
MessageManager.getInstance().denyNonPlayer(sender);
return;
}
boolean res = api.changeSky((IPlayer) sender, SkyPacket.RAIN_LEVEL_CHANGE, rainLevel);
if(thunderLevel != null) {
res = res && api.changeSky((IPlayer) sender, SkyPacket.THUNDER_LEVEL_CHANGE, thunderLevel);
}
if (res)
mm.packetSent(sender);
else
mm.packetError(sender);
}
private void cmdFreeze(ICommandSender sender, boolean unfreeze, String[] args) {
final IWildcardPermissionUtil wpu = plugin.getWildcardPermissionUtil();
final String basePerm = "skychanger.freeze";
boolean s = sender.hasPermission(basePerm + ".self");
boolean o = sender.hasPermission(basePerm + ".others");
boolean a = sender.hasPermission(basePerm + ".all");
boolean w = wpu.hasGeneralFreezeWorldPerm(sender);
boolean r = wpu.hasGeneralFreezeRadiusPerm(sender);
if (!s && !o && !a && !w && !r) {
mm.noPermission(sender);
return;
}
final SkyAPI api = plugin.getAPI();
if (args.length > 1) {
// Check if requested for all
if (args[1].equalsIgnoreCase("-a")) {
if (!a) {
mm.noPermission(sender);
return;
}
for (IPlayer p : plugin.getOnlinePlayers()) {
if (unfreeze)
api.unfreeze(p);
else
api.freeze(p);
}
if (unfreeze)
mm.packetUnfreeze(sender, "-a (" + mm.getString("message.everyone") + ")");
else
mm.packetSent(sender, "@a (" + mm.getString("message.everyone") + ")");
return;
}
// Check if requested for world
if (args[1].equalsIgnoreCase("-w")) {
IWorld t;
if (args.length > 2) {
t = plugin.getWorld(args[2]);
if (t == null) {
mm.worldDoesntExist(sender, args[2]);
return;
}
} else {
if (!(sender.isPlayer())) {
mm.mustSpecifyWorld(sender);
return;
}
t = ((IPlayer) sender).getWorld();
}
if (!wpu.hasFreezeWorldPerm(sender, t)) {
mm.noPermission(sender);
return;
}
for (IPlayer p : t.getPlayers()) {
if (unfreeze)
api.unfreeze(p);
else
api.freeze(p);
}
if (unfreeze)
mm.packetUnfreeze(sender, mm.getString("message.allPlayersIn") + " " + t.getName());
else
mm.packetSent(sender, mm.getString("message.allPlayersIn") + " " + t.getName());
return;
}
// Check if requested for radius
if (args[1].equalsIgnoreCase("-r")) {
if (sender.isConsole()) {
MessageManager.getInstance().denyNonPlayer(sender);
return;
}
if(args.length > 2) {
double radius;
double radiusSq;
try {
radius = Double.parseDouble(args[2]);
if (!wpu.hasFreezeRadiusPerm(sender, radius)) {
mm.noPermission(sender);
return;
}
radiusSq = Math.pow(radius, 2);
} catch (NumberFormatException e) {
MessageManager.getInstance().radiusFormatError(sender);
return;
}
ILocation origin;
if (sender.isPlayer()) {
origin = ((IPlayer)sender).getLocation();
} else if (sender.isCommandBlock()) {
origin = ((ICommandBlock)sender).getLocation();
} else {
MessageManager.getInstance().denyNonPlayer(sender);
return;
}
for(IPlayer p : origin.getWorld().getPlayers()) {
if(Math.abs(origin.distanceSquared(p.getLocation())) <= radiusSq) {
if (unfreeze)
api.unfreeze(p);
else
api.freeze(p);
}
}
if (unfreeze)
mm.packetUnfreeze(sender, mm.getString("message.allPlayersInRadius") + " " + args[2]);
else
mm.packetSent(sender, mm.getString("message.allPlayersInRadius") + " " + args[2]);
return;
} else {
mm.mustSpecifyRadius(sender);
return;
}
}
// Check if param is a player
if (!o) {
mm.noPermission(sender);
return;
}
IOfflinePlayer target;
try {
target = plugin.getOfflinePlayer(MessageManager.formatFromInput(args[1]));
} catch (IllegalArgumentException e) {
target = plugin.getOfflinePlayer(args[1]);
}
if (target == null || !target.isOnline()) {
mm.playerNotFound(sender, target == null || target.getName() == null ? args[1] : target.getName());
return;
}
// If a player specified their own name, we run the command as if the player
// param was not
// given. The others permission therefore includes the self.
if (!(sender.isPlayer()) || !target.getUniqueId().equals(((IPlayer) sender).getUniqueId())) {
if ((!unfreeze && api.freeze(target.getPlayer()))
|| (unfreeze && target.getPlayer().teleport(target.getPlayer().getLocation())))
if (unfreeze)
mm.packetUnfreeze(sender, target.getName());
else
mm.packetSent(sender, target.getName());
else
mm.packetError(sender, target.getName());
return;
}
}
if (!(sender.isPlayer())) {
MessageManager.getInstance().denyNonPlayer(sender);
return;
}
IPlayer p = (IPlayer) sender;
if ((!unfreeze && api.freeze(p)) || (unfreeze && api.unfreeze(p)))
if (unfreeze)
mm.packetUnfreeze(sender);
else
mm.packetSent(sender);
else
mm.packetError(sender);
}
private void cmdReload(ICommandSender sender) {
if (!sender.hasPermission("skychanger.reload")) {
mm.noPermission(sender);
return;
}
if (plugin.getConfigManager().reload()) {
MessageManager.reload();
mm.reloadSuccessful(sender);
} else
mm.reloadFailed(sender);
}
private void cmdVersion(ICommandSender sender) {
mm.versionMessage(sender);
}
public List<String> tabComplete(ICommandSender sender, String[] args) {
final IWildcardPermissionUtil wpu = plugin.getWildcardPermissionUtil();
List<String> ret = new ArrayList<>();
boolean b = sender.hasPermission("skychanger.freeze.self") || sender.hasPermission("skychanger.freeze.others")
|| sender.hasPermission("skychanger.freeze.all") || wpu.hasGeneralFreezeWorldPerm(sender)
|| wpu.hasGeneralFreezeRadiusPerm(sender);
if (args.length == 1) {
if ("help".startsWith(args[0].toLowerCase()))
ret.add("help");
if (b && "freeze".startsWith(args[0].toLowerCase()))
ret.add("freeze");
if (b && "unfreeze".startsWith(args[0].toLowerCase()))
ret.add("unfreeze");
if ("version".startsWith(args[0].toLowerCase()))
ret.add("version");
if (sender.hasPermission("skychanger.reload") && "reload".startsWith(args[0].toLowerCase()))
ret.add("reload");
}
// isTweak = command is /skychanger # #
// args are shifted right.
final boolean isTweak = args.length >= 3 && packetNum.matcher(args[1]).matches();
final boolean isChangeSkyOrFreeze = !isTweak && args.length >= 2 && (packetNum.matcher(args[0]).matches() || args[0].equalsIgnoreCase("freeze")
|| args[0].equalsIgnoreCase("unfreeze"));
final int flagPos = isTweak ? 2 : 1;
if ((args.length == 3 && isTweak) || (args.length == 2 && isChangeSkyOrFreeze)) {
// Players
if (sender.hasPermission("skychanger.changesky.others") || sender.hasPermission("skychanger.freeze.others"))
plugin.getOnlinePlayers().forEach(player -> {
if (player.getName().toLowerCase().startsWith(args[flagPos].toLowerCase())) {
ret.add(player.getName());
}
});
// All flag
if ((sender.hasPermission("skychanger.changesky.all") || sender.hasPermission("skychanger.freeze.all"))
&& "-a".startsWith(args[flagPos].toLowerCase())) {
ret.add("-a");
}
// World flag
if (args[0].equalsIgnoreCase("freeze") || args[0].equalsIgnoreCase("unfreeze")) {
if ("-w".startsWith(args[flagPos].toLowerCase()) && wpu.hasGeneralFreezeWorldPerm(sender)) {
ret.add("-w");
}
} else {
if ("-w".startsWith(args[flagPos].toLowerCase()) && wpu.hasGeneralChangeskyWorldPerm(sender)) {
ret.add("-w");
}
}
// Radius flag
if (args[0].equalsIgnoreCase("freeze") || args[0].equalsIgnoreCase("unfreeze")) {
if ("-r".startsWith(args[flagPos].toLowerCase()) && wpu.hasGeneralFreezeRadiusPerm(sender)) {
ret.add("-r");
}
} else {
if ("-r".startsWith(args[flagPos].toLowerCase()) && wpu.hasGeneralChangeskyRadiusPerm(sender)) {
ret.add("-r");
}
}
}
// World names
if ((isChangeSkyOrFreeze && args.length == 3) || (isTweak && args.length == 4)) {
if(args[flagPos].equalsIgnoreCase("-w")) {
if (isTweak || packetNum.matcher(args[0]).matches()) {
for (IWorld w : plugin.getWorlds()) {
if (w.getName().toLowerCase().startsWith(args[flagPos + 1].toLowerCase())
&& wpu.hasChangeskyWorldPerm(sender, w)) {
ret.add(w.getName());
}
}
} else if (args[0].equalsIgnoreCase("freeze") || args[0].equalsIgnoreCase("unfreeze")) {
for (IWorld w : plugin.getWorlds()) {
if (w.getName().toLowerCase().startsWith(args[flagPos + 1].toLowerCase())
&& wpu.hasFreezeWorldPerm(sender, w)) {
ret.add(w.getName());
}
}
}
}
}
return ret;
}
}
<|start_filename|>skychanger-bukkit/src/main/java/com/dscalzi/skychanger/bukkit/internal/wrap/BukkitPlayer.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.bukkit.internal.wrap;
import com.dscalzi.skychanger.core.internal.wrap.ILocation;
import com.dscalzi.skychanger.core.internal.wrap.IPlayer;
import com.dscalzi.skychanger.core.internal.wrap.IWorld;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.util.UUID;
public class BukkitPlayer extends BukkitCommandSender implements IPlayer {
private final Player p;
private BukkitPlayer(Player player) {
super(player);
this.p = player;
}
public static BukkitPlayer of(Player player) {
return player == null ? null : new BukkitPlayer(player);
}
@Override
public Object getOriginal() {
return p;
}
@Override
public IWorld getWorld() {
return BukkitWorld.of(p.getWorld());
}
@Override
public ILocation getLocation() {
return BukkitLocation.of(p.getLocation());
}
@Override
public boolean teleport(ILocation loc) {
return p.teleport((Location)loc.getOriginal());
}
@Override
public UUID getUniqueId() {
return p.getUniqueId();
}
@Override
public boolean isOnline() {
return p.isOnline();
}
@Override
public IPlayer getPlayer() {
return this;
}
@Override
public String getName() {
return p.getName();
}
}
<|start_filename|>skychanger-sponge/src/main/java/com/dscalzi/skychanger/sponge/internal/MainExecutor.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.sponge.internal;
import com.dscalzi.skychanger.core.internal.command.CommandAdapter;
import com.dscalzi.skychanger.sponge.SkyChangerPlugin;
import com.dscalzi.skychanger.sponge.internal.wrap.SpongeCommandSender;
import net.kyori.adventure.text.Component;
import org.spongepowered.api.command.*;
import org.spongepowered.api.command.parameter.ArgumentReader;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class MainExecutor implements Command.Raw {
private final CommandAdapter adapter;
public MainExecutor(SkyChangerPlugin plugin) {
this.adapter = new CommandAdapter(plugin);
}
@Override
public CommandResult process(CommandCause cause, ArgumentReader.Mutable arguments) {
String argStr = arguments.remaining();
final String[] args = argStr.isEmpty() ? new String[0] : argStr.replaceAll("\\s{2,}", " ").split(" ");
adapter.resolve(SpongeCommandSender.of(cause), args);
return CommandResult.success();
}
@Override
public List<CommandCompletion> complete(CommandCause cause, ArgumentReader.Mutable arguments) {
String argStr = arguments.remaining();
String[] argsDirty = argStr.replaceAll("\\s{2,}", " ").split(" ");
String[] args = argStr.endsWith(" ") ? new String[argsDirty.length + 1] : argsDirty;
if(args != argsDirty) {
System.arraycopy(argsDirty, 0, args, 0, argsDirty.length);
args[args.length-1] = "";
}
return adapter.tabComplete(SpongeCommandSender.of(cause), args).stream().map(CommandCompletion::of).collect(Collectors.toList());
}
@Override
public boolean canExecute(CommandCause cause) {
return true;
}
@Override
public Optional<Component> shortDescription(CommandCause cause) {
return Optional.of(Component.text("Change the color of the sky."));
}
@Override
public Optional<Component> extendedDescription(CommandCause cause) {
return Optional.of(Component.text("Change the color of the sky."));
}
@Override
public Optional<Component> help(@SuppressWarnings("NullableProblems") CommandCause cause) {
Component t = Component.text("Run /SkyChanger to view usage.");
return Optional.of(t);
}
@Override
public Component usage(CommandCause cause) {
return Component.text("/SkyChanger <args>");
}
}
<|start_filename|>skychanger-sponge/src/main/java/com/dscalzi/skychanger/sponge/internal/managers/ConfigManager.java<|end_filename|>
/*
* This file is part of SkyChanger, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2021 <NAME> <https://github.com/dscalzi/SkyChanger>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.dscalzi.skychanger.sponge.internal.managers;
import com.dscalzi.skychanger.core.internal.manager.IConfigManager;
import com.dscalzi.skychanger.sponge.SkyChangerPlugin;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.asset.Asset;
import org.spongepowered.configurate.CommentedConfigurationNode;
import java.io.File;
import java.io.IOException;
public class ConfigManager implements IConfigManager {
private static boolean initialized;
private static ConfigManager instance;
// TODO Will be implemented in a later version
private final double configVersion = 1.0;
private SkyChangerPlugin plugin;
private CommentedConfigurationNode config;
private ConfigManager(SkyChangerPlugin plugin) {
this.plugin = plugin;
loadConfig();
}
public void loadConfig() {
boolean res = verifyFile();
if(res) {
try {
this.config = this.plugin.getConfigLoader().load();
} catch (IOException e) {
plugin.severe("Failed to load config.");
e.printStackTrace();
}
} else {
this.config = null;
}
}
public boolean verifyFile() {
Asset asset = Sponge.assetManager().asset(plugin.getPlugin(), "skychanger.conf").orElse(null);
File file = plugin.getConfigDir().resolve("skychanger.conf").toFile();
if (!file.exists()) {
if(asset != null) {
try {
asset.copyToFile(file.toPath());
return true;
} catch (IOException e) {
plugin.severe("Failed to save default config.");
e.printStackTrace();
return false;
}
} else {
plugin.severe("Failed to locate default config.");
return false;
}
}
return true;
}
public static void initialize(SkyChangerPlugin plugin) {
if (!initialized) {
instance = new ConfigManager(plugin);
initialized = true;
}
}
public static boolean reloadStatic() {
if (!initialized)
return false;
return getInstance().reload();
}
@Override
public boolean reload() {
try {
loadConfig();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static ConfigManager getInstance() {
return ConfigManager.instance;
}
/* Configuration Accessors */
@Override
public float getUpperLimit() {
if(config == null) {
return 50.0F;
} else {
return Float.parseFloat(config.node("general_settings", "upper_limit").getString("50.0"));
}
}
@Override
public float getLowerLimit() {
if(config == null) {
return -50.0F;
} else {
return Float.parseFloat(config.node("general_settings", "lower_limit").getString("-50.0"));
}
}
@Override
public String getLanguage() {
if(config == null) {
return "en_US";
} else {
return config.node("general_settings", "language").getString("en_US");
}
}
@Override
public double getSystemConfigVersion() {
return this.configVersion;
}
@Override
public double getConfigVersion() {
if(config == null) {
return getSystemConfigVersion();
} else {
return config.node("ConfigVersion").getDouble(getSystemConfigVersion());
}
}
}
| dscalzi/SkyChanger |
<|start_filename|>composer.json<|end_filename|>
{
"name": "components/mathjs",
"description": "Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices.",
"type": "component",
"homepage": "http://mathjs.org",
"license": "Apache-2.0",
"support": {
"issues": "https://github.com/josdejong/mathjs/issues",
"source": "https://github.com/josdejong/mathjs/",
"docs": "http://mathjs.org/docs"
},
"authors": [
{
"name": "<NAME>",
"email": "<EMAIL>"
}
],
"extra": {
"component": {
"scripts": [
"./dist/math.js"
],
"files": [
"./dist/math.min.js",
"./dist/math.map"
]
}
}
} | bnlcas/mathjs |
<|start_filename|>include/graphics.h<|end_filename|>
#pragma once
// Extracts the upper 16 bits of a 32-bit number
#define HIHALF(n) (((n) & 0xFFFF0000) >> 16)
// Extracts the lower 16 bits of a 32-bit number
#define LOHALF(n) ((n) & 0xFFFF)
struct MonCoords
{
// This would use a bitfield, but some function
// uses it as a u8 and casting won't match.
u8 size; // u8 width:4, height:4;
u8 y_offset;
u16 unused;
};
struct CompressedSpriteSheet
{
const u8* data; // LZ77 compressed pixel data
u16 size; // Uncompressed size of pixel data
u16 tag;
};
struct CompressedSpritePalette
{
const u8* data; // LZ77 compressed palette data
u16 tag;
u16 unused;
};
void __attribute__((long_call)) LZ77UnCompWram(const void *src, void *dest);
void __attribute__((long_call)) DrawSpindaSpots(u16, u32, u8*, u8);
<|start_filename|>include/base_stats.h<|end_filename|>
#pragma once
struct BaseStats
{
/* 0x00 */ u8 baseHP;
/* 0x01 */ u8 baseAttack;
/* 0x02 */ u8 baseDefense;
/* 0x03 */ u8 baseSpeed;
/* 0x04 */ u8 baseSpAttack;
/* 0x05 */ u8 baseSpDefense;
/* 0x06 */ u8 type1;
/* 0x07 */ u8 type2;
/* 0x08 */ u8 catchRate;
/* 0x09 */ u8 expYield;
/* 0x0A */ u16 evYield_HP:2;
/* 0x0A */ u16 evYield_Attack:2;
/* 0x0A */ u16 evYield_Defense:2;
/* 0x0A */ u16 evYield_Speed:2;
/* 0x0B */ u16 evYield_SpAttack:2;
/* 0x0B */ u16 evYield_SpDefense:2;
/* 0x0C */ u16 item1;
/* 0x0E */ u16 item2;
/* 0x10 */ u8 genderRatio;
/* 0x11 */ u8 eggCycles;
/* 0x12 */ u8 friendship;
/* 0x13 */ u8 growthRate;
/* 0x14 */ u8 eggGroup1;
/* 0x15 */ u8 eggGroup2;
/* 0x16 */ u8 ability1;
/* 0x17 */ u8 ability2;
/* 0x18 */ u8 safariZoneFleeRate;
/* 0x19 */ u8 bodyColor : 7;
u8 noFlip : 1;
/* 0x1A */ u8 hiddenAbility;
};
enum
{
EGG_GROUP_NONE,
EGG_GROUP_MONSTER,
EGG_GROUP_WATER_1,
EGG_GROUP_BUG,
EGG_GROUP_FLYING,
EGG_GROUP_FIELD,
EGG_GROUP_FAIRY,
EGG_GROUP_GRASS,
EGG_GROUP_HUMAN_LIKE,
EGG_GROUP_WATER_3,
EGG_GROUP_MINERAL,
EGG_GROUP_AMORPHOUS,
EGG_GROUP_WATER_2,
EGG_GROUP_DITTO,
EGG_GROUP_DRAGON,
EGG_GROUP_UNDISCOVERED
};
enum
{
GROWTH_MEDIUM_FAST,
GROWTH_ERRATIC,
GROWTH_FLUCTUATING,
GROWTH_MEDIUM_SLOW,
GROWTH_FAST,
GROWTH_SLOW
};
enum
{
BODY_COLOR_RED,
BODY_COLOR_BLUE,
BODY_COLOR_YELLOW,
BODY_COLOR_GREEN,
BODY_COLOR_BLACK,
BODY_COLOR_BROWN,
BODY_COLOR_PURPLE,
BODY_COLOR_GRAY,
BODY_COLOR_WHITE,
BODY_COLOR_PINK
};
#define TYPE_NORMAL 0x00
#define TYPE_FIGHTING 0x01
#define TYPE_FLYING 0x02
#define TYPE_POISON 0x03
#define TYPE_GROUND 0x04
#define TYPE_ROCK 0x05
#define TYPE_BUG 0x06
#define TYPE_GHOST 0x07
#define TYPE_STEEL 0x08
#define TYPE_MYSTERY 0x09
#define TYPE_FIRE 0x0a
#define TYPE_WATER 0x0b
#define TYPE_GRASS 0x0c
#define TYPE_ELECTRIC 0x0d
#define TYPE_PSYCHIC 0x0e
#define TYPE_ICE 0x0f
#define TYPE_DRAGON 0x10
#define TYPE_DARK 0x11
#define TYPE_ROOSTLESS 0x13
#define TYPE_BLANK 0x14
#define TYPE_FAIRY 0x17
#define MON_MALE 0x00
#define MON_FEMALE 0xFE
#define MON_GENDERLESS 0xFF
<|start_filename|>src/defines.h<|end_filename|>
#pragma once
#include "../include/types.h"
#include "../include/species.h"
#define EVOS_PER_MON 16
#define FALSE 0
#define TRUE 1
#define ARRAY_COUNT(array) (sizeof(array) / sizeof((array)[0]))
#define SPECIES_TABLES_TERMIN 0xFEFE
//CHANGE THESE IF YOU WANT
#define EXPAND_LEARNSETS //If you're using this feature, make sure you insert the Complete Fire Red Upgrade
// afterwards or the game will crash when selecting certain Pokemon. Comment out this
// line if you're using the CFRU to expand movesets.
//#define INCLUDE_FOOTPRINTS //If you uncomment this line, make sure to uncomment gMonFootprintTable in "repoints", and remove the footprint remover in "bytereplacement"
#define NUM_TMSHMS 128
#define NUM_MOVE_TUTOR_MOVES 128
<|start_filename|>src/updated_code.c<|end_filename|>
#include "defines.h"
#include "../include/evolution.h"
#include "../include/graphics.h"
#include "../include/main.h"
#include "../include/pokedex.h"
//Backsprite battle start
extern const u8 gSpeciesNames[][POKEMON_NAME_LENGTH + 1];
extern const u16 gSpeciesIdToCryId[];
extern const u16 gSpeciesToNationalPokedexNum[];
extern const u16 gPokedexOrder_Regional[];
extern const u16 gRegionalDexCount;
extern const u16 gPokedexOrder_Alphabetical[];
extern const u16 gPokedexOrderAlphabeticalCount;
extern const u16 gPokedexOrder_Weight[];
extern const u16 gPokedexOrderWeightCount;
extern const u16 gPokedexOrder_Height[];
extern const u16 gPokedexOrderHeightCount;
extern const u16 gPokedexOrder_Type[];
extern const u16 gPokedexOrderTypeCount;
extern const struct AlternateDexEntries gAlternateDexEntries[];
extern const struct CompressedSpriteSheet gMonBackPicTable[];
extern const struct CompressedSpriteSheet gMonFrontPicTable[];
extern const struct CompressedSpritePalette gMonPaletteTable[];
extern const struct CompressedSpritePalette gMonShinyPaletteTable[];
const u16 gNumSpecies = NUM_SPECIES;
const u16 gNumDexEntries = FINAL_DEX_ENTRY;
u8 __attribute__((long_call)) GetGenderFromSpeciesAndPersonality(u16 species, u32 personality);
u8 __attribute__((long_call)) GetUnownLetterFromPersonality(u32 personality);
bool8 __attribute__((long_call)) GetSetPokedexFlag(u16 nationalNum, u8 caseID);
s8 __attribute__((long_call)) DexFlagCheck(u16 nationalDexNo, u8 caseId, bool8 indexIsSpecies);
u16 __attribute__((long_call)) SpeciesToNationalPokedexNum(u16 species);
void __attribute__((long_call)) break_func();
//This file's functions
u16 TryGetFemaleGenderedSpecies(u16 species, u32 personality);
static u16 LoadNationalPokedexView(void);
u16 SpeciesToCryId(u16 species)
{
return species + 1;
}
struct PivotalDexSpecies
{
u16 species;
u16 dexNum;
};
static const struct PivotalDexSpecies sPivotalDexSpecies[] =
{
//These species have Pokemon grouped in order after them
{SPECIES_ROWLET, NATIONAL_DEX_ROWLET},
{SPECIES_CHESPIN, NATIONAL_DEX_CHESPIN},
{SPECIES_TURTWIG, NATIONAL_DEX_TURTWIG},
{SPECIES_TREECKO, NATIONAL_DEX_TREECKO},
{SPECIES_BULBASAUR, NATIONAL_DEX_BULBASAUR},
};
u16 NationalPokedexNumToSpecies(u16 nationalNum)
{
u16 species, i;
if (nationalNum == 0)
return 0;
species = 0;
//Optimization
if (nationalNum <= SPECIES_SHIFTRY || nationalNum >= SPECIES_TURTWIG) //Hoenn Mons are too out of order for this to work
{
for (i = 0; i < ARRAY_COUNT(sPivotalDexSpecies); ++i)
{
if (nationalNum > sPivotalDexSpecies[i].dexNum)
{
u16 difference = nationalNum - sPivotalDexSpecies[i].dexNum;
if (gSpeciesToNationalPokedexNum[sPivotalDexSpecies[i].species + difference - 1] == nationalNum)
return sPivotalDexSpecies[i].species + difference;
break;
}
}
}
while (species < (NUM_SPECIES - 1) && gSpeciesToNationalPokedexNum[species] != nationalNum)
species++;
if (species == NUM_SPECIES - 1)
return 0;
return species + 1;
}
const u8* TryLoadAlternateDexEntry(u16 species)
{
for (int i = 0; gAlternateDexEntries[i].species != SPECIES_TABLES_TERMIN; ++i)
{
if (gAlternateDexEntries[i].species == species)
return gAlternateDexEntries[i].description;
}
return 0;
}
void LoadSpecialPokePic(const struct CompressedSpriteSheet* src, void* dest, u16 species, u32 personality, bool8 isFrontPic)
{
u16 oldSpecies = species;
const struct CompressedSpriteSheet* table = isFrontPic ? gMonFrontPicTable : gMonBackPicTable;
species = TryGetFemaleGenderedSpecies(species, personality);
if (species != oldSpecies) //Updated sprite
src = &table[species];
if (species == SPECIES_UNOWN)
{
u16 i = GetUnownLetterFromPersonality(personality);
// The other Unowns are separate from Unown A.
if (i == 0)
i = SPECIES_UNOWN;
else
i += SPECIES_UNOWN_B - 1;
if (!isFrontPic)
LZ77UnCompWram((void*) gMonBackPicTable[i].data, dest);
else
LZ77UnCompWram((void*) gMonFrontPicTable[i].data, dest);
}
else if (species > NUM_SPECIES) // is species unknown? draw the ? icon
LZ77UnCompWram((void*) gMonFrontPicTable[0].data, dest);
else
LZ77UnCompWram((void*) src->data, dest);
DrawSpindaSpots(species, personality, dest, isFrontPic);
}
const u32* GetFrontSpritePalFromSpeciesAndPersonality(u16 species, u32 otId, u32 personality)
{
u32 shinyValue;
species = TryGetFemaleGenderedSpecies(species, personality);
if (species > NUM_SPECIES)
return (u32*) gMonPaletteTable[0].data;
shinyValue = HIHALF(otId) ^ LOHALF(otId) ^ HIHALF(personality) ^ LOHALF(personality);
if (shinyValue < 8)
return (u32*) gMonShinyPaletteTable[species].data;
else
return (u32*) gMonPaletteTable[species].data;
}
const struct CompressedSpritePalette* GetMonSpritePalStructFromOtIdPersonality(u16 species, u32 otId , u32 personality)
{
u32 shinyValue;
species = TryGetFemaleGenderedSpecies(species, personality);
shinyValue = HIHALF(otId) ^ LOHALF(otId) ^ HIHALF(personality) ^ LOHALF(personality);
if (shinyValue < 8)
return &gMonShinyPaletteTable[species];
else
return &gMonPaletteTable[species];
}
u16 TryGetFemaleGenderedSpecies(u16 species, u32 personality)
{
if (GetGenderFromSpeciesAndPersonality(species, personality) == MON_FEMALE)
{
switch (species) {
case SPECIES_HIPPOPOTAS:
species = SPECIES_HIPPOPOTAS_F;
break;
case SPECIES_HIPPOWDON:
species = SPECIES_HIPPOWDON_F;
break;
case SPECIES_UNFEZANT:
species = SPECIES_UNFEZANT_F;
break;
case SPECIES_FRILLISH:
species = SPECIES_FRILLISH_F;
break;
case SPECIES_JELLICENT:
species = SPECIES_JELLICENT_F;
break;
case SPECIES_PYROAR:
species = SPECIES_PYROAR_FEMALE;
break;
}
}
else if (species == SPECIES_XERNEAS && !gMain.inBattle)
species = SPECIES_XERNEAS_NATURAL;
return species;
}
u16 GetIconSpecies(u16 species, u32 personality)
{
u16 result;
if (species == SPECIES_UNOWN)
{
u16 letter = GetUnownLetterFromPersonality(personality);
if (letter == 0)
letter = SPECIES_UNOWN;
else
letter += (SPECIES_UNOWN_B - 1);
result = letter;
}
else
{
if (species > NUM_SPECIES)
result = 0;
else
result = TryGetFemaleGenderedSpecies(species, personality);
}
return result;
}
bool8 IsInBattle(void)
{
return gMain.inBattle;
}
u16 CountSpeciesInDex(u8 caseId, bool8 whichDex)
{
u16 count = 0;
u16 i;
switch (whichDex) {
case 0: //Regional
for (i = 0; i < gRegionalDexCount; ++i)
{
if (DexFlagCheck(SpeciesToNationalPokedexNum(gPokedexOrder_Regional[i]), caseId, FALSE))
count++;
}
break;
case 1: //National
for (i = 1; i <= FINAL_DEX_ENTRY; ++i)
{
if (DexFlagCheck(i, caseId, FALSE))
count++;
}
break;
}
return count;
}
u16 GetRegionalPokedexCount(u8 caseId)
{
u16 i, count;
for (i = 0, count = 0; i < gRegionalDexCount; ++i)
{
if (GetSetPokedexFlag(SpeciesToNationalPokedexNum(gPokedexOrder_Regional[i]), caseId))
count++;
}
return count;
}
bool16 HasAllRegionalMons(void)
{
u16 i;
for (i = 0; i < gRegionalDexCount; ++i)
{
if (!GetSetPokedexFlag(SpeciesToNationalPokedexNum(gPokedexOrder_Regional[i]), FLAG_GET_CAUGHT))
return FALSE;
}
return TRUE;
}
bool16 sp1B9_SeenAllRegionalMons(void)
{
u16 i;
for (i = 0; i < gRegionalDexCount; ++i)
{
if (!GetSetPokedexFlag(SpeciesToNationalPokedexNum(gPokedexOrder_Regional[i]), FLAG_GET_SEEN))
return FALSE;
}
return TRUE;
}
bool16 HasAllMons(void)
{
u16 i;
for (i = 1; i <= FINAL_DEX_ENTRY; ++i)
{
if (!GetSetPokedexFlag(i, FLAG_GET_CAUGHT))
return FALSE;
}
return TRUE;
}
u16 SpeciesToRegionalDexNum(u16 species)
{
u16 i;
for (i = 0; i < gRegionalDexCount; ++i)
{
if (gPokedexOrder_Regional[i] == species)
return i + 1;
}
return 0;
}
extern const u16 gPokedexOrder_Regional[];
extern const u16 gRegionalDexCount;
extern const u16 gPokedexOrder_Alphabetical[];
extern const u16 gPokedexOrderAlphabeticalCount;
extern const u16 gPokedexOrder_Weight[];
extern const u16 gPokedexOrderWeightCount;
extern const u16 gPokedexOrder_Height[];
extern const u16 gPokedexOrderHeightCount;
extern const u16 gPokedexOrder_Type[];
extern const u16 gPokedexOrderTypeCount;
u16 LoadPokedexViews(u8 type)
{
u16 i, counter, count, lastMeaningfulIndex;
const u16* dexList;
bool8 showUnseenSpecies = FALSE;
bool8 showUncaughtSpecies = FALSE;
switch (type) {
case 0:
dexList = gPokedexOrder_Regional;
count = gRegionalDexCount;
showUnseenSpecies = TRUE;
showUncaughtSpecies = TRUE;
break;
case 1:
dexList = gPokedexOrder_Alphabetical;
count = gPokedexOrderAlphabeticalCount;
showUncaughtSpecies = TRUE;
break;
case 2:
dexList = gPokedexOrder_Type;
count = gPokedexOrderTypeCount;
break;
case 3:
dexList = gPokedexOrder_Weight;
count = gPokedexOrderWeightCount;
break;
case 4:
dexList = gPokedexOrder_Height;
count = gPokedexOrderHeightCount;
break;
case 5:
default:
return LoadNationalPokedexView();
}
for (i = 0, counter = 0, lastMeaningfulIndex = 0; i < count; ++i)
{
u16 species = dexList[i];
bool8 seen = DexFlagCheck(species, FLAG_GET_SEEN, TRUE);
bool8 caught = DexFlagCheck(species, FLAG_GET_CAUGHT, TRUE);
if (!seen)
{
if (showUnseenSpecies)
{
gPokedexScreenDataPtr->listItem[counter].name = (void*) 0x8415F66; //-----
gPokedexScreenDataPtr->listItem[counter++].id = species | (0 << 16); //Unseen
}
}
else if (caught || showUncaughtSpecies)
{
lastMeaningfulIndex = counter + 1;
gPokedexScreenDataPtr->listItem[counter].name = gSpeciesNames[species];
if (caught)
gPokedexScreenDataPtr->listItem[counter++].id = species | (3 << 16); //Caught
else
gPokedexScreenDataPtr->listItem[counter++].id = species | (1 << 16); //Seen
}
}
if (lastMeaningfulIndex == 0)
{
//Fix empty list
lastMeaningfulIndex = 1;
gPokedexScreenDataPtr->listItem[0].name = (void*) 0x8415F66; //-----
gPokedexScreenDataPtr->listItem[0].id = gPokedexOrder_Regional[0] | (0 << 16); //Unseen
}
return lastMeaningfulIndex;
}
static u16 LoadNationalPokedexView(void)
{
u16 i, lastMeaningfulIndex;
for (i = 1, lastMeaningfulIndex = 0; i < NATIONAL_DEX_COUNT; ++i)
{
bool8 seen = DexFlagCheck(i, FLAG_GET_SEEN, FALSE);
bool8 caught = DexFlagCheck(i, FLAG_GET_CAUGHT, FALSE);
u16 species = NationalPokedexNumToSpecies(i);
u16 listIndex = i - 1;
if (!seen)
{
gPokedexScreenDataPtr->listItem[listIndex].name = (void*) 0x8415F66; //-----
gPokedexScreenDataPtr->listItem[listIndex].id = species | (0 << 16); //Unseen
}
else
{
lastMeaningfulIndex = i;
gPokedexScreenDataPtr->listItem[listIndex].name = gSpeciesNames[species];
if (caught)
gPokedexScreenDataPtr->listItem[listIndex].id = species | (3 << 16); //Caught
else
gPokedexScreenDataPtr->listItem[listIndex].id = species | (1 << 16); //Seen
}
}
return lastMeaningfulIndex;
}
<|start_filename|>include/cries.h<|end_filename|>
#pragma once
struct ToneData
{
u8 type;
u8 key;
u8 length; // sound length (compatible sound)
u8 pan_sweep; // pan or sweep (compatible sound ch. 1)
u8* wav; //struct WaveData *wav;
u8 attack;
u8 decay;
u8 sustain;
u8 release;
}; | GarfieldTheLightning/Dynamic-Pokemon-Expansion |
"<|start_filename|>src/libzoo/io/FastOFStream.cpp<|end_filename|>\n/**\n ** Copyright (c) 2011-2014 (...TRUNCATED) | ndaniel/BEETL |
"<|start_filename|>ouster_viz/include/ouster/lidar_scan.h<|end_filename|>\n/**\n * @file\n * @brief (...TRUNCATED) | wonjin/ouster_example |
"<|start_filename|>utils.c<|end_filename|>\n#include \"utils.h\"\n\nvoid\nshuffle(int *array, size_t(...TRUNCATED) | cgvwzq/evsets |
End of preview. Expand
in Dataset Viewer.
Combines the data from starcoderdata and removes any repos with <= 10 stars.
- Downloads last month
- 91