text:
package com.gmail.st3venau.plugins.armorstandtools;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.CommandBlock;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.util.EulerAngle;
import org.bukkit.util.Vector;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

class Utils {

    private static DecimalFormat twoDec;

    static boolean hasDisabledSlots(ArmorStand as) {
        for(EquipmentSlot slot : EquipmentSlot.values()) {
            for(ArmorStand.LockType lockType : ArmorStand.LockType.values()) {
                if(!as.hasEquipmentLock(slot, lockType)) {
                    return false;
                }
            }
        }
        return true;
    }

    static void setSlotsDisabled(ArmorStand as, boolean slotsDisabled) {
        for(EquipmentSlot slot : EquipmentSlot.values()) {
            for(ArmorStand.LockType lockType : ArmorStand.LockType.values()) {
                if(slotsDisabled) {
                    as.addEquipmentLock(slot, lockType);
                } else {
                    as.removeEquipmentLock(slot, lockType);
                }
            }
        }
    }

    static int disabledSlotsAsInteger(ArmorStand as) {
        return    (as.hasEquipmentLock(EquipmentSlot.HAND,     ArmorStand.LockType.ADDING_OR_CHANGING) ? 1 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.FEET,     ArmorStand.LockType.ADDING_OR_CHANGING) ? 2 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.LEGS,     ArmorStand.LockType.ADDING_OR_CHANGING) ? 4 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.CHEST,    ArmorStand.LockType.ADDING_OR_CHANGING) ? 8 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.HEAD,     ArmorStand.LockType.ADDING_OR_CHANGING) ? 16 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.OFF_HAND, ArmorStand.LockType.ADDING_OR_CHANGING) ? 32 : 0)

                + (as.hasEquipmentLock(EquipmentSlot.HAND,     ArmorStand.LockType.REMOVING_OR_CHANGING) ? 256 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.FEET,     ArmorStand.LockType.REMOVING_OR_CHANGING) ? 512 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.LEGS,     ArmorStand.LockType.REMOVING_OR_CHANGING) ? 1024 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.CHEST,    ArmorStand.LockType.REMOVING_OR_CHANGING) ? 2048 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.HEAD,     ArmorStand.LockType.REMOVING_OR_CHANGING) ? 4096 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.OFF_HAND, ArmorStand.LockType.REMOVING_OR_CHANGING) ? 8192 : 0)

                + (as.hasEquipmentLock(EquipmentSlot.HAND,     ArmorStand.LockType.ADDING) ? 65536 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.FEET,     ArmorStand.LockType.ADDING) ? 131072 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.LEGS,     ArmorStand.LockType.ADDING) ? 262144 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.CHEST,    ArmorStand.LockType.ADDING) ? 524288 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.HEAD,     ArmorStand.LockType.ADDING) ? 1048576 : 0)
                + (as.hasEquipmentLock(EquipmentSlot.OFF_HAND, ArmorStand.LockType.ADDING) ? 2097152 : 0);
    }

    static boolean toggleSlotsDisabled(ArmorStand as) {
        boolean slotsDisabled = !hasDisabledSlots(as);
        setSlotsDisabled(as, slotsDisabled);
        return slotsDisabled;
    }

    static boolean hasPermissionNode(Player p, String perm) {
        if ((p == null) || p.isOp()) {
            return true;
        }
        if (p.hasPermission(perm)) {
            return true;
        }
        final String[] nodes = perm.split("\\.");
        final StringBuilder n = new StringBuilder();
        for (int i = 0; i < (nodes.length - 1); i++) {
            n.append(nodes[i]).append(".");
            if (p.hasPermission(n + "*")) {
                return true;
            }
        }
        return false;
    }

    static void title(Player p, String msg) {
        p.sendTitle(" ", msg, 0, 70, 0);
    }

    static Location getLocationFacing(Location loc) {
        Location l = loc.clone();
        Vector v = l.getDirection();
        v.setY(0);
        v.multiply(3);
        l.add(v);
        l.setYaw(l.getYaw() + 180);
        int n;
        boolean ok = false;
        for (n = 0; n < 5; n++) {
            if (l.getBlock().getType().isSolid()) {
                l.add(0, 1, 0);
            } else {
                ok = true;
                break;
            }
        }
        if (!ok) {
            l.subtract(0, 5, 0);
        }
        return l;
    }

    static boolean containsItems(Collection<ItemStack> items) {
        for(ItemStack i : items) {
            if(ArmorStandTool.get(i) != null) {
                return true;
            }
        }
        return false;
    }

    static private String getItemStackTags(ItemStack is) {
        if(is == null) {
            return "";
        }
        StringBuilder tags = new StringBuilder();
        if(is.getItemMeta() != null && is.getItemMeta() instanceof LeatherArmorMeta armorMeta) {
            tags.append("display:{color:");
            tags.append(armorMeta.getColor().asRGB());
            tags.append("}");
        }
        Map<Enchantment, Integer> enchants = is.getEnchantments();
        if(enchants.size() > 0) {
            if(tags.length() > 0) {
                tags.append(",");
            }
            tags.append("Enchantments:[");

            for(Enchantment e : enchants.keySet()) {
                tags.append("{id:");
                tags.append(e.getKey().getKey());
                tags.append(",lvl:");
                tags.append(enchants.get(e));
                tags.append("},");
            }

            tags.setCharAt(tags.length() - 1, ']');
        }
        return tags.length() == 0 ? "" : tags.toString();
    }

    static private int getItemCustomModelData(ItemStack is) {
        if(is == null || is.getItemMeta() == null || is.getItemMeta().getCustomModelData() == null) return 0;
        return is.getItemMeta().getCustomModelData();
    }

    static private String skullOwner(ItemStack is) {
        if(is == null || is.getItemMeta() == null || !(is.getItemMeta() instanceof SkullMeta skull)) return "";
        return skull.getOwningPlayer() == null ? "" : "SkullOwner:\"" + skull.getOwner() + "\"";
    }

    static private boolean isEmpty(ItemStack is) {
        return is == null || is.getType() == Material.AIR;
    }

    static private String itemInfo(ItemStack is) {
        if(isEmpty(is)) return "{}";
        StringBuilder sb = new StringBuilder("{id:");
        sb.append(is.getType().getKey().getKey());
        if(is.getAmount() > 0) {
            sb.append(",Count:").append(is.getAmount());
        }
        String itemStackTags = getItemStackTags(is);
        @SuppressWarnings("deprecation")
        short durability = is.getDurability();
        String skullOwner = skullOwner(is);
        int customModelData = getItemCustomModelData(is);
        int n = 0;
        if(itemStackTags.length() > 0 || durability > 0 || skullOwner.length() > 0) {
            sb.append(",tag:{");
            if(durability > 0) {
                sb.append("Damage:").append(durability);
                n++;
            }
            if(customModelData > 0) {
                if(n > 0) sb.append(",");
                sb.append("CustomModelData:").append(customModelData);
                n++;
            }
            if(itemStackTags.length() > 0) {
                if(n > 0) sb.append(",");
                sb.append(itemStackTags);
                n++;
            }
            if(skullOwner.length() > 0) {
                if(n > 0) sb.append(",");
                sb.append(skullOwner);
            }
            sb.append("}");
        }
        sb.append("}");
        return sb.toString();
    }

    static private String armorItems(EntityEquipment e) {
        if(e == null || (isEmpty(e.getBoots()) && isEmpty(e.getLeggings()) && isEmpty(e.getChestplate()) && isEmpty(e.getHelmet()))) {
            return "";
        }
        return "ArmorItems:["
                + itemInfo(e.getBoots()) + ","
                + itemInfo(e.getLeggings()) + ","
                + itemInfo(e.getChestplate()) + ","
                + itemInfo(e.getHelmet())
                + "],";
    }

    static private String handItems(EntityEquipment e) {
        if(e == null || (isEmpty(e.getItemInMainHand()) && isEmpty(e.getItemInOffHand()))) {
            return "";
        }
        return "HandItems:["
                + itemInfo(e.getItemInMainHand()) + ","
                + itemInfo(e.getItemInOffHand())
                + "],";
    }

    static private String angleInfo(EulerAngle ea) {
        return "[" + degrees(ea.getX()) + "f," + degrees(ea.getY()) + "f," + degrees(ea.getZ()) + "f]";
    }

    static private String pose(ArmorStand as) {
        return "Pose:{"
                + "Body:"     + angleInfo(as.getBodyPose())     + ","
                + "Head:"     + angleInfo(as.getHeadPose())     + ","
                + "LeftLeg:"  + angleInfo(as.getLeftLegPose())  + ","
                + "RightLeg:" + angleInfo(as.getRightLegPose()) + ","
                + "LeftArm:"  + angleInfo(as.getLeftArmPose())  + ","
                + "RightArm:" + angleInfo(as.getRightArmPose())
                + "}";
    }

    static String createSummonCommand(ArmorStand as) {
        Location asLocation = as.getLocation();
        return  "summon minecraft:armor_stand " +
                twoDec(asLocation.getX()) + " " +
                twoDec(asLocation.getY()) + " " +
                twoDec(asLocation.getZ()) + " " +
                createEntityTag(as);
    }

    static String quote(String s) {
        return "\"\\\"" + s + "\\\"\"";
    }

    static String createGiveCommand(ArmorStand as, Player p) {
        StringBuilder sb = new StringBuilder("give ");
        sb.append(p.getName()).append(" minecraft:armor_stand{Enchantments:[{id:unbreaking,lvl:1}],HideFlags:1,display:{Name:");
        sb.append(quote(Config.configuredArmorStand));
        sb.append(",Lore:[");
        boolean comma = false;
        for(String s : createItemLore(as)) {
            if(comma) sb.append(",");
            comma = true;
            sb.append(quote(s));
        }
        sb.append("]},EntityTag:").append(createEntityTag(as)).append("}");
        return sb.toString();
    }

    static String createEntityTag(ArmorStand as) {
        EntityEquipment e = as.getEquipment();
        StringBuilder sb = new StringBuilder("{");
        if(!as.isVisible())                 sb.append("Invisible:1,");
        if(!as.hasBasePlate())              sb.append("NoBasePlate:1,");
        if(!as.hasGravity())                sb.append("NoGravity:1,");
        if(as.hasArms())                    sb.append("ShowArms:1,");
        if(as.isSmall())                    sb.append("Small:1,");
        if(as.isInvulnerable())             sb.append("Invulnerable:1,");
        if(as.isGlowing())                  sb.append("Glowing:1,");
        if(hasDisabledSlots(as))            sb.append("DisabledSlots:").append(disabledSlotsAsInteger(as)).append(",");
        if(as.isCustomNameVisible())        sb.append("CustomNameVisible:1,");
        if(as.getCustomName() != null)      sb.append("CustomName:").append(quote(as.getCustomName())).append(",");
        if(as.getLocation().getYaw() != 0F) sb.append("Rotation:[").append(twoDec(as.getLocation().getYaw())).append("f],");
        sb.append(armorItems(e));
        sb.append(handItems(e));
        sb.append(pose(as));
        sb.append("}");
        return sb.toString();
    }

    static List<String> createItemLore(ArmorStand as) {
        EntityEquipment e = as.getEquipment();
        List<String> lore = new ArrayList<>();
        String name = as.getCustomName();
        if(name != null && name.length() > 0) {
            lore.add(Config.name + ": " + name);
        }
        if (e != null) {
            int stacks = 0;
            int items = 0;
            if(e.getHelmet() != null)                           { stacks++; items += e.getHelmet().getAmount();         }
            if(e.getChestplate() != null)                       { stacks++; items += e.getChestplate().getAmount();     }
            if(e.getLeggings() != null)                         { stacks++; items += e.getLeggings().getAmount();       }
            if(e.getBoots() != null)                            { stacks++; items += e.getBoots().getAmount();          }
            if(Material.AIR != e.getItemInMainHand().getType()) { stacks++; items += e.getItemInMainHand().getAmount(); }
            if(Material.AIR != e.getItemInOffHand().getType())  { stacks++; items += e.getItemInOffHand().getAmount();  }
            if(stacks > 0) {
                lore.add(Config.inventory + ": " + items + " " + Config.items + " (" + stacks + " " + Config.stacks + ")");
            }
        }
        List<String> attribs = new ArrayList<>();
        if(hasDisabledSlots(as))    attribs.add(Config.equip + " " + Config.locked);
        if(!as.hasGravity())        attribs.add(Config.gravity + " " + Config.isOff);
        if(!as.isVisible())         attribs.add(Config.invisible);
        if(as.hasArms())            attribs.add(Config.arms);
        if(as.isSmall())            attribs.add(Config.small);
        if(as.isInvulnerable())     attribs.add(Config.invuln);
        if(as.isGlowing())          attribs.add(Config.glowing);
        if(attribs.size() > 0) {
            StringBuilder sb = new StringBuilder(Config.attributes + ": ");
            for (String attrib : attribs) {
                sb.append(attrib).append(", ");
                if (sb.length() >= 40) {
                    lore.add(sb.toString());
                    sb = new StringBuilder();
                }
            }
            if (sb.length() > 1) {
                lore.add(sb.substring(0, sb.length() - 2));
            } else {
                String last = lore.get(lore.size() - 1);
                lore.remove(lore.size() - 1);
                lore.add(last.substring(0, last.length() - 2));
            }
        }
        return lore;
    }

    static void generateCmdBlock(Location l, String command) {
        Block b = l.getBlock();
        b.setType(Material.COMMAND_BLOCK);
        CommandBlock cb = (CommandBlock) b.getState();
        cb.setCommand(command);
        cb.update();
    }

    static String twoDec(double d) {
        if(twoDec == null) {
            twoDec = new DecimalFormat("0.0#");
            DecimalFormatSymbols symbols = new DecimalFormatSymbols();
            symbols.setDecimalSeparator('.');
            twoDec.setDecimalFormatSymbols(symbols);
        }
        return twoDec.format(d);
    }

    private static String degrees(double d) {
        return twoDec(d * 180.0 / Math.PI);
    }

    static boolean hasAnyTools(Player p) {
        for(ItemStack i : p.getInventory()) {
            if(ArmorStandTool.isTool(i)) {
                return true;
            }
        }
        return false;
    }

    private static boolean onCooldown(Entity e) {
        for(MetadataValue meta : e.getMetadata("lastEvent")) {
            if(AST.plugin.equals(meta.getOwningPlugin())) {
                return System.currentTimeMillis() - meta.asLong() < 100;
            }
        }
        return false;
    }

    static void cycleInventory(Player p) {
        if(onCooldown(p)) return;
        Inventory i = p.getInventory();
        ItemStack temp;
        for (int n = 0; n < 9; n++) {
            temp = i.getItem(n);
            i.setItem(n, i.getItem(27 + n));
            i.setItem(27 + n, i.getItem(18 + n));
            i.setItem(18 + n, i.getItem(9 + n));
            i.setItem(9 + n, temp);
        }
        p.updateInventory();
        p.setMetadata("lastEvent", new FixedMetadataValue(AST.plugin, System.currentTimeMillis()));
    }

    static ArmorStand cloneArmorStand(ArmorStand as) {
        ArmorStand clone = (ArmorStand) as.getWorld().spawnEntity(as.getLocation().add(1, 0, 0), EntityType.ARMOR_STAND);
        EntityEquipment asEquipment = as.getEquipment();
        EntityEquipment cloneEquipment = clone.getEquipment();
        if(asEquipment != null && cloneEquipment != null) {
            cloneEquipment.setHelmet(asEquipment.getHelmet());
            cloneEquipment.setChestplate(asEquipment.getChestplate());
            cloneEquipment.setLeggings(asEquipment.getLeggings());
            cloneEquipment.setBoots(asEquipment.getBoots());
            cloneEquipment.setItemInMainHand(asEquipment.getItemInMainHand());
            cloneEquipment.setItemInOffHand(asEquipment.getItemInOffHand());
        }
        clone.setHeadPose(as.getHeadPose());
        clone.setBodyPose(as.getBodyPose());
        clone.setLeftArmPose(as.getLeftArmPose());
        clone.setRightArmPose(as.getRightArmPose());
        clone.setLeftLegPose(as.getLeftLegPose());
        clone.setRightLegPose(as.getRightLegPose());
        clone.setGravity(as.hasGravity());
        clone.setVisible(as.isVisible());
        clone.setBasePlate(as.hasBasePlate());
        clone.setArms(as.hasArms());
        clone.setCustomName(as.getCustomName());
        clone.setCustomNameVisible(as.isCustomNameVisible());
        clone.setSmall(as.isSmall());
        clone.setInvulnerable(as.isInvulnerable());
        clone.setGlowing(as.isGlowing());
        for(EquipmentSlot slot : EquipmentSlot.values()) {
            for(ArmorStand.LockType lockType : ArmorStand.LockType.values()) {
                if(as.hasEquipmentLock(slot, lockType)) {
                    clone.addEquipmentLock(slot, lockType);
                }
            }
        }
        ArmorStandCmdManager cmdMgrAs = new ArmorStandCmdManager(as);
        ArmorStandCmdManager cmdMgrClone = new ArmorStandCmdManager(clone);
        for(ArmorStandCmd asCmd : cmdMgrAs.getCommands()) {
            cmdMgrClone.addCommand(asCmd, true);
        }
        int cooldown = cmdMgrAs.getCooldownTime();
        if(cooldown > 0) {
            cmdMgrClone.setCooldownTime(cooldown);
        }
        clone.setMetadata("clone", new FixedMetadataValue(AST.plugin, true));
        return clone;
    }

}


text:
<query-mapping package='AWA.Questions.Models'>
    <description>
      The list of questions.
    </description>

    <class name="AWA.Questions.Models.Question_Info" bean="yes">
        <comment>The list of questions.</comment>
        <property type='Identifier' name="id">
            <comment>the question identifier.</comment>
        </property>
        <property type='String' name="title">
            <comment>the question title.</comment>
        </property>
        <property type='Date' name="create_date">
            <comment>the question creation date.</comment>
        </property>
        <property type='String' name="description">
            <comment>the question short description.</comment>
        </property>
        <property type='Integer' name="rating">
            <comment>the question rating.</comment>
        </property>
        <property type='Integer' name="answer_count">
            <comment>the number of answers.</comment>
        </property>
        <property type='Identifier' name="author_id">
            <comment>the author's identifier.</comment>
        </property>
        <property type='String' name="author_name">
            <comment>the author's name.</comment>
        </property>
        <property type='String' name="author_email">
            <comment>the author's email.</comment>
        </property>
    </class>

    <query name='question-list'>
       <comment>Get a list of questions.</comment>
       <sql>
    SELECT
      q.id,
      q.title,
      q.create_date,
      q.short_description,
      coalesce(r.rating,0),
      (select count(*) from awa_answer AS a WHERE q.id = a.question_id),
      q.author_id,
      u.name,
      email.email
    FROM awa_question AS q
    INNER JOIN awa_user AS u ON q.author_id = u.id
    INNER JOIN awa_email AS email ON q.author_id = email.user_id
    LEFT JOIN awa_rating AS r ON r.for_entity_id = q.id AND r.for_entity_type = $entity_type[awa_question]
    ORDER BY q.create_date DESC
       </sql>
    </query>

    <query name='question-tag-list'>
       <comment>Get a list of questions filtered by a tag.</comment>
       <sql>
    SELECT
      q.id,
      q.title,
      q.create_date,
      q.short_description,
      coalesce(r.rating,0),
      (select count(*) from awa_answer AS a WHERE q.id = a.question_id),
      q.author_id,
      u.name,
      email.email
    FROM awa_question AS q
    INNER JOIN awa_user AS u ON q.author_id = u.id
    INNER JOIN awa_email AS email ON q.author_id = email.user_id
    INNER JOIN awa_tagged_entity AS e ON e.for_entity_id = q.id AND e.entity_type = $entity_type[awa_question] AND e.tag_id = :tag
    LEFT JOIN awa_rating AS r ON r.for_entity_id = q.id AND r.for_entity_type = $entity_type[awa_question]
    ORDER BY q.create_date DESC
       </sql>
    </query>

</query-mapping>

redpajama_set_name: RedPajamaGithub


text:
{{currentVideo.title}}

Comments:{{currentVideo.comments}}

        <button class="btn" ng-click="comments=true"> Add Comments</button>

            <input type="text" class="form-control" placeholder="Place your comments here" ng-model="currentVideo.comments" />
            <button class="btn" ng-click="runVideoEdit(currentVideo)">Submit</button>
            <button class="btn" ng-click="fool=true">Act A Fool</button>

            <video autoplay="true" id="videoElement">
            </video>


text:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
#if UNITY_2021_2_OR_NEWER
using PrefabStage = UnityEditor.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.SceneManagement.PrefabStageUtility;
#elif UNITY_2018_3_OR_NEWER
using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage;
using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility;
#endif

namespace AssetUsageDetectorNamespace
{
	public enum Phase { Setup, Processing, Complete };

	public class AssetUsageDetectorWindow : EditorWindow, IHasCustomMenu
	{
		private enum WindowFilter { AlwaysReturnActive, ReturnActiveIfNotLocked, AlwaysReturnNew };

		private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch";
		private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch";
		private const string PREFS_SEARCH_PROJECT_SETTINGS = "AUD_ProjectSettingsSearch";
		private const string PREFS_DONT_SEARCH_SOURCE_ASSETS = "AUD_AssetsExcludeSrc";
		private const string PREFS_SEARCH_DEPTH_LIMIT = "AUD_Depth";
		private const string PREFS_SEARCH_FIELDS = "AUD_Fields";
		private const string PREFS_SEARCH_PROPERTIES = "AUD_Properties";
		private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables";
		private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps";
		private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch";
		private const string PREFS_ADDRESSABLES_SUPPORT = "AUD_AddressablesSupport";
		private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs";
		private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates";
		private const string PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS = "AUD_HideRedundantPVariantLinks";
		private const string PREFS_SHOW_PROGRESS = "AUD_Progress";

		private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" );
		private static readonly Vector2 windowMinSize = new Vector2( 325f, 220f );

		private readonly GUILayoutOption GL_WIDTH_12 = GUILayout.Width( 12f );

		private GUIStyle lockButtonStyle;

		private readonly AssetUsageDetector core = new AssetUsageDetector();
		private SearchResult searchResult; // Overall search results

		// This isn't readonly so that it can be serialized
		private List<ObjectToSearch> objectsToSearch = new List<ObjectToSearch>() { new ObjectToSearch( null ) };

#pragma warning disable 0649
		[SerializeField] // Since titleContent persists between Editor sessions, so should the IsLocked property because otherwise, "[L]" in title becomes confusing when the EditorWindow isn't actually locked
		private bool m_isLocked;
		private bool IsLocked
		{
			get { return m_isLocked; }
			set
			{
				if( m_isLocked != value )
				{
					m_isLocked = value;
					titleContent = value ? new GUIContent( "[L] " + windowTitle.text, EditorGUIUtility.IconContent( "InspectorLock" ).image ) : windowTitle;
				}
			}
		}
#pragma warning restore 0649

		private Phase currentPhase = Phase.Setup;

		private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view
		private bool searchInScenesInBuild = true; // Scenes in build
		private bool searchInScenesInBuildTickedOnly = true; // Scenes in build (ticked only or not)
		private bool searchInAllScenes = true; // All scenes (including scenes that are not in build)
		private bool searchInAssetsFolder = true; // Assets in Project window
		private bool dontSearchInSourceAssets = true; // objectsToSearch won't be searched for internal references
		private bool searchInProjectSettings = true; // Player Settings, Graphics Settings etc.

		private List<Object> searchInAssetsSubset = new List<Object>() { null }; // If not empty, only these assets are searched for references
		private List<Object> excludedAssets = new List<Object>() { null }; // These assets won't be searched for references
		private List<Object> excludedScenes = new List<Object>() { null }; // These scenes won't be searched for references

		private int searchDepthLimit = 4; // Depth limit for recursively searching variables of objects

		private bool lazySceneSearch = true;
#if ASSET_USAGE_ADDRESSABLES
		private bool addressablesSupport = false;
#endif
		private bool searchNonSerializableVariables = true;
		private bool searchUnusedMaterialProperties = true;
		private bool calculateUnusedObjects = false;
		private bool hideDuplicateRows = true;
		private bool hideReduntantPrefabVariantLinks = true;
		private bool noAssetDatabaseChanges = false;
		private bool showDetailedProgressBar = true;

		private BindingFlags fieldModifiers, propertyModifiers;

		private SearchRefactoring searchRefactoring = null; // Its value can be assigned via ShowAndSearch

		private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer();
		private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false );
		private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false );
		private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false );

		private bool drawObjectsToSearchSection = true;

		private Vector2 scrollPosition = Vector2.zero;

		private bool shouldRepositionSelf;
		private Rect windowTargetPosition;

		void IHasCustomMenu.AddItemsToMenu( GenericMenu contextMenu )
		{
			contextMenu.AddItem( new GUIContent( "Lock" ), IsLocked, () => IsLocked = !IsLocked );
			contextMenu.AddSeparator( "" );

#if UNITY_2018_3_OR_NEWER
			contextMenu.AddItem( new GUIContent( "Settings" ), false, () => SettingsService.OpenProjectSettings( "Project/yasirkula/Asset Usage Detector" ) );
#else
			contextMenu.AddItem( new GUIContent( "Settings" ), false, () =>
			{
				System.Type preferencesWindowType = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.PreferencesWindow" );
				preferencesWindowType.GetMethod( "ShowPreferencesWindow", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).Invoke( null, null );

				EditorWindow preferencesWindow = GetWindow( preferencesWindowType );
				if( (bool) preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow ) )
				{
					preferencesWindowType.GetMethod( "AddCustomSections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).Invoke( preferencesWindow, null );
					preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, false );
				}

				int targetSectionIndex = -1;
				System.Collections.IList sections = (System.Collections.IList) preferencesWindowType.GetField( "m_Sections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow );
				for( int i = 0; i < sections.Count; i++ )
				{
					if( ( (GUIContent) sections[i].GetType().GetField( "content", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( sections[i] ) ).text == "Asset Usage Detector" )
					{
						targetSectionIndex = i;
						break;
					}
				}

				if( targetSectionIndex >= 0 )
					preferencesWindowType.GetProperty( "selectedSectionIndex", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, targetSectionIndex, null );
			} );
#endif

			if( currentPhase == Phase.Setup )
			{
				contextMenu.AddSeparator( "" );
				contextMenu.AddItem( new GUIContent( "Refresh Sub-Assets of Searched Objects" ), false, () =>
				{
					for( int i = objectsToSearch.Count - 1; i >= 0; i-- )
						objectsToSearch[i].RefreshSubAssets();
				} );
			}
			else if( currentPhase == Phase.Complete )
			{
				if( searchResult != null && searchResult.NumberOfGroups > 0 )
				{
					contextMenu.AddSeparator( "" );
					contextMenu.AddItem( new GUIContent( "Collapse All" ), false, searchResult.CollapseAllSearchResultGroups );
				}
			}
		}

		// Shows lock button at the top-right corner
		// Credit: http://leahayes.co.uk/2013/04/30/adding-the-little-padlock-button-to-your-editorwindow.html
		private void ShowButton( Rect position )
		{
			if( lockButtonStyle == null )
				lockButtonStyle = "IN LockButton";

			IsLocked = GUI.Toggle( position, IsLocked, GUIContent.none, lockButtonStyle );
		}

		private static AssetUsageDetectorWindow GetWindow( WindowFilter filter )
		{
			AssetUsageDetectorWindow[] windows = Resources.FindObjectsOfTypeAll<AssetUsageDetectorWindow>();
			AssetUsageDetectorWindow window = System.Array.Find( windows, ( w ) => w && !w.IsLocked );
			if( !window )
				window = System.Array.Find( windows, ( w ) => w );

			if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) )
			{
				window.Show();
				window.Focus();

				return window;
			}

			Rect? windowTargetPosition = null;
			if( window )
			{
				Rect position = window.position;
				position.position += new Vector2( 50f, 50f );
				windowTargetPosition = position;
			}

			window = CreateInstance<AssetUsageDetectorWindow>();
			window.titleContent = windowTitle;
			window.minSize = windowMinSize;

			if( windowTargetPosition.HasValue )
			{
				window.shouldRepositionSelf = true;
				window.windowTargetPosition = windowTargetPosition.Value;
			}

			window.Show( true );
			window.Focus();

			return window;
		}

		[MenuItem( "Window/Asset Usage Detector/Active Window" )]
		private static void OpenActiveWindow()
		{
			GetWindow( WindowFilter.AlwaysReturnActive );
		}

		[MenuItem( "Window/Asset Usage Detector/New Window" )]
		private static void OpenNewWindow()
		{
			GetWindow( WindowFilter.AlwaysReturnNew );
		}

		// Quickly initiate search for the selected assets
		[MenuItem( "GameObject/Search for References/This Object Only", priority = 49 )]
		[MenuItem( "Assets/Search for References", priority = 1000 )]
		private static void SearchSelectedAssetReferences( MenuCommand command )
		{
			// This happens when this button is clicked via hierarchy's right click context menu
			// and is called once for each object in the selection. We don't want that, we want
			// the function to be called only once
			if( command.context )
			{
				EditorApplication.update -= CallSearchSelectedAssetReferencesOnce;
				EditorApplication.update += CallSearchSelectedAssetReferencesOnce;
			}
			else
				ShowAndSearch( Selection.objects );
		}

		[MenuItem( "GameObject/Search for References/Include Children", priority = 49 )]
		private static void SearchSelectedAssetReferencesWithChildren( MenuCommand command )
		{
			if( command.context )
			{
				EditorApplication.update -= CallSearchSelectedAssetReferencesWithChildrenOnce;
				EditorApplication.update += CallSearchSelectedAssetReferencesWithChildrenOnce;
			}
			else
				ShowAndSearch( Selection.objects, true );
		}

		// Show the menu item only if there is a selection in the Editor
		[MenuItem( "GameObject/Search for References/This Object Only", validate = true )]
		[MenuItem( "GameObject/Search for References/Include Children", validate = true )]
		[MenuItem( "Assets/Search for References", validate = true )]
		private static bool SearchSelectedAssetReferencesValidate( MenuCommand command )
		{
			return Selection.objects.Length > 0;
		}

		// Quickly show the AssetUsageDetector window and initiate a search
		public static void ShowAndSearch( IEnumerable<Object> searchObjects, bool? shouldSearchChildren = null )
		{
			GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchObjects, null, shouldSearchChildren );
		}

		// Quickly show the AssetUsageDetector window and initiate a search
		public static void ShowAndSearch( AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren = null )
		{
			if( searchParameters == null )
			{
				Debug.LogError( "searchParameters can't be null!" );
				return;
			}

			GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchParameters.objectsToSearch, searchParameters, shouldSearchChildren );
		}

		private static void CallSearchSelectedAssetReferencesOnce()
		{
			EditorApplication.update -= CallSearchSelectedAssetReferencesOnce;
			SearchSelectedAssetReferences( new MenuCommand( null ) );
		}

		private static void CallSearchSelectedAssetReferencesWithChildrenOnce()
		{
			EditorApplication.update -= CallSearchSelectedAssetReferencesWithChildrenOnce;
			SearchSelectedAssetReferencesWithChildren( new MenuCommand( null ) );
		}

		private void ShowAndSearchInternal( IEnumerable<Object> searchObjects, AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren )
		{
			if( !ReturnToSetupPhase() )
			{
				Debug.LogError( "Need to reset the previous search first!" );
				return;
			}

			objectsToSearch.Clear();
			if( searchObjects != null )
			{
				foreach( Object obj in searchObjects )
					objectsToSearch.Add( new ObjectToSearch( obj, shouldSearchChildren ) );
			}

			if( searchParameters != null )
			{
				ParseSceneSearchMode( searchParameters.searchInScenes );
				searchInAssetsFolder = searchParameters.searchInAssetsFolder;
				dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets;
				searchInProjectSettings = searchParameters.searchInProjectSettings;
				searchDepthLimit = searchParameters.searchDepthLimit;
				fieldModifiers = searchParameters.fieldModifiers;
				propertyModifiers = searchParameters.propertyModifiers;
				searchNonSerializableVariables = searchParameters.searchNonSerializableVariables;
				searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties;
				searchRefactoring = searchParameters.searchRefactoring;
				lazySceneSearch = searchParameters.lazySceneSearch;
#if ASSET_USAGE_ADDRESSABLES
				addressablesSupport = searchParameters.addressablesSupport;
#endif
				calculateUnusedObjects = searchParameters.calculateUnusedObjects;
				hideDuplicateRows = searchParameters.hideDuplicateRows;
				hideReduntantPrefabVariantLinks = searchParameters.hideReduntantPrefabVariantLinks;
				noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges;
				showDetailedProgressBar = searchParameters.showDetailedProgressBar;

				searchInAssetsSubset.Clear();
				if( searchParameters.searchInAssetsSubset != null )
				{
					foreach( Object obj in searchParameters.searchInAssetsSubset )
						searchInAssetsSubset.Add( obj );
				}

				excludedAssets.Clear();
				if( searchParameters.excludedAssetsFromSearch != null )
				{
					foreach( Object obj in searchParameters.excludedAssetsFromSearch )
						excludedAssets.Add( obj );
				}

				excludedScenes.Clear();
				if( searchParameters.excludedScenesFromSearch != null )
				{
					foreach( Object obj in searchParameters.excludedScenesFromSearch )
						excludedScenes.Add( obj );
				}
			}

			InitiateSearch();
			Repaint();
		}

		private void Awake()
		{
			LoadPrefs();
		}

		private void OnEnable()
		{
			if( currentPhase == Phase.Complete && AssetUsageDetectorSettings.ShowCustomTooltip )
				wantsMouseMove = wantsMouseEnterLeaveWindow = true; // These values aren't preserved during domain reload on Unity 2020.3.0f1

#if UNITY_2018_3_OR_NEWER
			PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
			PrefabStage.prefabStageClosing += ReplacePrefabStageObjectsWithAssets;
#endif
		}

		private void OnDisable()
		{
#if UNITY_2018_3_OR_NEWER
			PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets;
#endif
			SearchResultTooltip.Hide();
		}

		private void OnDestroy()
		{
			if( core != null )
				core.SaveCache();

			SavePrefs();

			if( searchResult != null && currentPhase == Phase.Complete )
				searchResult.RestoreInitialSceneSetup();
		}

		private void SavePrefs()
		{
			EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) );
			EditorPrefs.SetBool( PREFS_SEARCH_ASSETS, searchInAssetsFolder );
			EditorPrefs.SetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, dontSearchInSourceAssets );
			EditorPrefs.SetBool( PREFS_SEARCH_PROJECT_SETTINGS, searchInProjectSettings );
			EditorPrefs.SetInt( PREFS_SEARCH_DEPTH_LIMIT, searchDepthLimit );
			EditorPrefs.SetInt( PREFS_SEARCH_FIELDS, (int) fieldModifiers );
			EditorPrefs.SetInt( PREFS_SEARCH_PROPERTIES, (int) propertyModifiers );
			EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables );
			EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties );
			EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES
			EditorPrefs.SetBool( PREFS_ADDRESSABLES_SUPPORT, addressablesSupport );
#endif
			EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects );
			EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows );
			EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, hideReduntantPrefabVariantLinks );
			EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar );
		}

		private void LoadPrefs()
		{
			ParseSceneSearchMode( (SceneSearchMode) EditorPrefs.GetInt( PREFS_SEARCH_SCENES, (int) ( SceneSearchMode.OpenScenes | SceneSearchMode.ScenesInBuildSettingsTickedOnly | SceneSearchMode.AllScenes ) ) );

			searchInAssetsFolder = EditorPrefs.GetBool( PREFS_SEARCH_ASSETS, true );
			dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true );
			searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true );
			searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 );
			fieldModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_FIELDS, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
			propertyModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_PROPERTIES, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) );
			searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true );
			searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true );
			lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true );
#if ASSET_USAGE_ADDRESSABLES
			addressablesSupport = EditorPrefs.GetBool( PREFS_ADDRESSABLES_SUPPORT, false );
#endif
			calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false );
			hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true );
			hideReduntantPrefabVariantLinks = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, true );
			showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true );
		}

		private SceneSearchMode GetSceneSearchMode( bool hideOptionsInPlayMode )
		{
			SceneSearchMode sceneSearchMode = SceneSearchMode.None;
			if( searchInOpenScenes )
				sceneSearchMode |= SceneSearchMode.OpenScenes;
			if( !hideOptionsInPlayMode || !EditorApplication.isPlaying )
			{
				if( searchInScenesInBuild )
					sceneSearchMode |= searchInScenesInBuildTickedOnly ? SceneSearchMode.ScenesInBuildSettingsTickedOnly : SceneSearchMode.ScenesInBuildSettingsAll;
				if( searchInAllScenes )
					sceneSearchMode |= SceneSearchMode.AllScenes;
			}

			return sceneSearchMode;
		}

		private void ParseSceneSearchMode( SceneSearchMode sceneSearchMode )
		{
			searchInOpenScenes = ( sceneSearchMode & SceneSearchMode.OpenScenes ) == SceneSearchMode.OpenScenes;
			searchInScenesInBuild = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) == SceneSearchMode.ScenesInBuildSettingsAll || ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsTickedOnly ) == SceneSearchMode.ScenesInBuildSettingsTickedOnly;
			searchInScenesInBuildTickedOnly = ( sceneSearchMode & SceneSearchMode.ScenesInBuildSettingsAll ) != SceneSearchMode.ScenesInBuildSettingsAll;
			searchInAllScenes = ( sceneSearchMode & SceneSearchMode.AllScenes ) == SceneSearchMode.AllScenes;
		}

		private void Update()
		{
			if( shouldRepositionSelf )
			{
				shouldRepositionSelf = false;
				position = windowTargetPosition;
			}
		}

		private void OnGUI()
		{
			// Make the window scrollable
			scrollPosition = EditorGUILayout.BeginScrollView( scrollPosition, Utilities.GL_EXPAND_WIDTH, Utilities.GL_EXPAND_HEIGHT );

			GUILayout.BeginVertical();

			if( currentPhase == Phase.Processing )
			{
				// If we are stuck at this phase, then we have encountered an exception
				GUILayout.Label( ". . . Search in progress or something went wrong (check console) . . ." );

				if( GUILayout.Button( "RETURN", Utilities.GL_HEIGHT_30 ) )
				{
					ReturnToSetupPhase();
					GUIUtility.ExitGUI();
				}
			}
			else if( currentPhase == Phase.Setup )
			{
				DrawObjectsToSearchSection();

				GUILayout.Space( 10f );

				Color c = GUI.backgroundColor;
				GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
				GUILayout.Box( "<b>SEARCH IN</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
				GUI.backgroundColor = c;

				searchInAssetsFolder = WordWrappingToggleLeft( "Project window (Assets folder)", searchInAssetsFolder );

				if( searchInAssetsFolder )
				{
					GUILayout.BeginHorizontal();
					GUILayout.Space( 35f );
					GUILayout.BeginVertical();

					searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset );
					excludedAssetsDrawer.Draw( excludedAssets );

					GUILayout.EndVertical();
					GUILayout.EndHorizontal();
				}

				GUILayout.Space( 5f );

				dontSearchInSourceAssets = WordWrappingToggleLeft( "Don't search \"SEARCHED OBJECTS\" themselves for references", dontSearchInSourceAssets );
				searchUnusedMaterialProperties = WordWrappingToggleLeft( "Search unused material properties (e.g. normal map of a material that no longer uses normal mapping)", searchUnusedMaterialProperties );

				Utilities.DrawSeparatorLine();

				if( searchInAllScenes && !EditorApplication.isPlaying )
					GUI.enabled = false;

				searchInOpenScenes = WordWrappingToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes );

				if( !EditorApplication.isPlaying )
				{
					searchInScenesInBuild = WordWrappingToggleLeft( "Scenes in Build Settings", searchInScenesInBuild );

					if( searchInScenesInBuild )
					{
						GUILayout.BeginHorizontal();
						GUILayout.Space( 35f );

						searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );
						searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 );

						GUILayout.EndHorizontal();
					}

					GUI.enabled = true;

					searchInAllScenes = WordWrappingToggleLeft( "All scenes in the project", searchInAllScenes );
				}

				GUILayout.BeginHorizontal();
				GUILayout.Space( 35f );
				GUILayout.BeginVertical();

				excludedScenesDrawer.Draw( excludedScenes );

				GUILayout.EndVertical();
				GUILayout.EndHorizontal();

				Utilities.DrawSeparatorLine();

				searchInProjectSettings = WordWrappingToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings );

				GUILayout.Space( 10f );

				GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
				GUILayout.Box( "<b>SETTINGS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
				GUI.backgroundColor = c;

#if ASSET_USAGE_ADDRESSABLES
				EditorGUI.BeginDisabledGroup( addressablesSupport );
#endif
				lazySceneSearch = WordWrappingToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch );
#if ASSET_USAGE_ADDRESSABLES
				EditorGUI.EndDisabledGroup();
				addressablesSupport = WordWrappingToggleLeft( "Addressables support (WARNING: 'Lazy scene search' will be disabled) (slower search)", addressablesSupport );
#endif
				calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects );
				hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows );
#if UNITY_2018_3_OR_NEWER
				hideReduntantPrefabVariantLinks = WordWrappingToggleLeft( "Hide redundant prefab variant links (when the same value is assigned to the same Component of a prefab and its variant(s))", hideReduntantPrefabVariantLinks );
#endif
				noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges );
				showDetailedProgressBar = WordWrappingToggleLeft( "Update search progress bar more often (cancelable search) (slower search)", showDetailedProgressBar );

				GUILayout.Space( 10f );

				// Don't let the user press the GO button without any valid search location
				if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder && !searchInProjectSettings )
					GUI.enabled = false;

				if( GUILayout.Button( "GO!", Utilities.GL_HEIGHT_30 ) )
				{
					InitiateSearch();
					GUIUtility.ExitGUI();
				}

				GUILayout.Space( 5f );
			}
			else if( currentPhase == Phase.Complete )
			{
				// Draw the results of the search
				GUI.enabled = false;

				DrawObjectsToSearchSection();

				if( drawObjectsToSearchSection )
					GUILayout.Space( 10f );

				GUI.enabled = true;

				if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) )
				{
					ReturnToSetupPhase();
					GUIUtility.ExitGUI();
				}

				if( searchResult == null )
				{
					EditorGUILayout.HelpBox( "ERROR: searchResult is null", MessageType.Error );
					return;
				}
				else if( !searchResult.SearchCompletedSuccessfully )
					EditorGUILayout.HelpBox( "ERROR: search was interrupted, check the logs for more info", MessageType.Error );

				if( searchResult.NumberOfGroups == 0 )
				{
					GUILayout.Space( 10f );
					GUILayout.Box( "No references found...", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
				}
				else
				{
					noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges );

					EditorGUILayout.Space();

					scrollPosition.y = searchResult.DrawOnGUI( this, scrollPosition.y, noAssetDatabaseChanges );
				}
			}

			if( Event.current.type == EventType.MouseLeaveWindow )
			{
				SearchResultTooltip.Hide();

				if( searchResult != null )
					searchResult.CancelDelayedTreeViewTooltip();
			}

			GUILayout.EndVertical();

			EditorGUILayout.EndScrollView();
		}

		private void DrawObjectsToSearchSection()
		{
			Color c = GUI.backgroundColor;
			GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor;
			GUILayout.Box( "<b>SEARCHED OBJECTS</b>", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH );
			GUI.backgroundColor = c;

			Rect searchedObjectsHeaderRect = GUILayoutUtility.GetLastRect();
			searchedObjectsHeaderRect.x += 5f;
			searchedObjectsHeaderRect.yMin += ( searchedObjectsHeaderRect.height - EditorGUIUtility.singleLineHeight ) * 0.5f;
			searchedObjectsHeaderRect.height = EditorGUIUtility.singleLineHeight;

			drawObjectsToSearchSection = EditorGUI.Foldout( searchedObjectsHeaderRect, drawObjectsToSearchSection, GUIContent.none, true );

			if( drawObjectsToSearchSection )
				objectsToSearchDrawer.Draw( objectsToSearch );
		}

		private bool WordWrappingToggleLeft( string label, bool value )
		{
			GUILayout.BeginHorizontal();
			bool result = EditorGUILayout.ToggleLeft( GUIContent.none, value, GL_WIDTH_12 );
			if( GUILayout.Button( label, EditorStyles.wordWrappedLabel ) )
			{
				GUI.FocusControl( null );
				result = !value;
			}
			GUILayout.EndHorizontal();

			return result;
		}

		private void InitiateSearch()
		{
			currentPhase = Phase.Processing;

			SavePrefs();

#if UNITY_2018_3_OR_NEWER
			ReplacePrefabStageObjectsWithAssets( PrefabStageUtility.GetCurrentPrefabStage() );
#endif

			// Start searching
			searchResult = core.Run( new AssetUsageDetector.Parameters()
			{
				objectsToSearch = !objectsToSearch.IsEmpty() ? new ObjectToSearchEnumerator( objectsToSearch ).ToArray() : null,
				searchInScenes = GetSceneSearchMode( true ),
				searchInAssetsFolder = searchInAssetsFolder,
				searchInAssetsSubset = !searchInAssetsSubset.IsEmpty() ? searchInAssetsSubset.ToArray() : null,
				excludedAssetsFromSearch = !excludedAssets.IsEmpty() ? excludedAssets.ToArray() : null,
				dontSearchInSourceAssets = dontSearchInSourceAssets,
				excludedScenesFromSearch = !excludedScenes.IsEmpty() ? excludedScenes.ToArray() : null,
				searchInProjectSettings = searchInProjectSettings,
				//fieldModifiers = fieldModifiers,
				//propertyModifiers = propertyModifiers,
				//searchDepthLimit = searchDepthLimit,
				//searchNonSerializableVariables = searchNonSerializableVariables,
				searchUnusedMaterialProperties = searchUnusedMaterialProperties,
				searchRefactoring = searchRefactoring,
#if ASSET_USAGE_ADDRESSABLES
				lazySceneSearch = lazySceneSearch && !addressablesSupport,
				addressablesSupport = addressablesSupport,
#else
				lazySceneSearch = lazySceneSearch,
#endif
				calculateUnusedObjects = calculateUnusedObjects,
				hideDuplicateRows = hideDuplicateRows,
				hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks,
				noAssetDatabaseChanges = noAssetDatabaseChanges,
				showDetailedProgressBar = showDetailedProgressBar
			} );

			currentPhase = Phase.Complete;

			// We really don't want SearchRefactoring to affect next searches unless the search is initiated via ShowAndSearch again
			searchRefactoring = null;

			if( AssetUsageDetectorSettings.ShowCustomTooltip )
				wantsMouseMove = wantsMouseEnterLeaveWindow = true;
		}

#if UNITY_2018_3_OR_NEWER
		// Try replacing searched objects who are part of currently open prefab stage with their corresponding prefab assets
		public void ReplacePrefabStageObjectsWithAssets( PrefabStage prefabStage )
		{
			if( prefabStage == null || !prefabStage.stageHandle.IsValid() )
				return;

#if UNITY_2020_1_OR_NEWER
			GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.assetPath );
#else
			GameObject prefabAsset = AssetDatabase.LoadAssetAtPath<GameObject>( prefabStage.prefabAssetPath );
#endif
			if( prefabAsset == null || prefabAsset.Equals( null ) )
				return;

			for( int i = 0; i < objectsToSearch.Count; i++ )
			{
				Object obj = objectsToSearch[i].obj;
				if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
				{
					GameObject prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabStage.prefabContentsRoot, prefabAsset );
					if( prefabStageObjectSource != null )
						objectsToSearch[i].obj = prefabStageObjectSource;

					List<ObjectToSearch.SubAsset> subAssets = objectsToSearch[i].subAssets;
					for( int j = 0; j < subAssets.Count; j++ )
					{
						obj = subAssets[j].subAsset;
						if( obj != null && !obj.Equals( null ) && obj is GameObject && prefabStage.IsPartOfPrefabContents( (GameObject) obj ) )
						{
							prefabStageObjectSource = ( (GameObject) obj ).FollowSymmetricHierarchy( prefabStage.prefabContentsRoot, prefabAsset );
							if( prefabStageObjectSource != null )
								subAssets[j].subAsset = prefabStageObjectSource;
						}
					}
				}
			}
		}
#endif

		private bool ReturnToSetupPhase()
		{
			if( searchResult != null && !EditorApplication.isPlaying && !searchResult.RestoreInitialSceneSetup() )
				return false;

			searchResult = null;
			currentPhase = Phase.Setup;
			wantsMouseMove = wantsMouseEnterLeaveWindow = false;

			SearchResultTooltip.Hide();

			return true;
		}

		internal void OnSettingsChanged( bool highlightedSearchTextColorChanged = false, bool tooltipDescriptionsColorChanged = false )
		{
			if( searchResult == null )
				return;

			wantsMouseMove = wantsMouseEnterLeaveWindow = AssetUsageDetectorSettings.ShowCustomTooltip;

			for( int i = searchResult.NumberOfGroups - 1; i >= 0; i-- )
			{
				if( searchResult[i].treeView != null )
				{
					searchResult[i].treeView.rowHeight = EditorGUIUtility.singleLineHeight + AssetUsageDetectorSettings.ExtraRowHeight;
					searchResult[i].treeView.OnSettingsChanged( highlightedSearchTextColorChanged, tooltipDescriptionsColorChanged );
				}
			}
		}
	}
}


text:
import requests
import os
import bs4

# open url
proxies = {
    'https': 'https://127.0.0.1:1080',
    'http': 'http://127.0.0.1:1080'
}
url = 'https://xkcd.com/'
os.makedirs('xkcd', exist_ok=True)
downloadCount = 5
while downloadCount > 0:
    print('Downloading page %s ...' % url)
    res = requests.get(url, proxies=proxies)
    res.raise_for_status()
    soup = bs4.BeautifulSoup(res.text, 'html.parser')
    # find img
    img = soup.select('#comic img')
    if img == []:
        print('Could not find comic image')
    else:
        comicUrl = 'https:' + img[0].get('src')
        print('downloading image %s ...' % comicUrl)
        res = requests.get(comicUrl, proxies=proxies)
        res.raise_for_status()
        imgFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
        # save img
        for chunk in res.iter_content(100000):
            imgFile.write(chunk)
        imgFile.close()
    # find prev
    prev = soup.select('a[rel="prev"]')[0]
    url = 'https://xkcd.com/' + prev.get('href')
    downloadCount -= 1


text:
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
var _excluded = ["children", "onRemove", "removePlaceholder", "align"];
import { createScopedElement } from "../../lib/jsxRuntime";
import * as React from 'react';
import { classNames } from "../../lib/classNames";
import { getTitleFromChildren } from "../../lib/utils";
import { usePlatform } from "../../hooks/usePlatform";
import { getClassName } from "../../helpers/getClassName";
import { useAdaptivity } from "../../hooks/useAdaptivity";
import { useDOM } from "../../lib/dom";
import { ANDROID, IOS, VKCOM } from "../../lib/platform";
import { Icon24Cancel } from '@vkontakte/icons';
import IconButton from "../IconButton/IconButton";
import { useGlobalEventListener } from "../../hooks/useGlobalEventListener";
import Tappable from "../Tappable/Tappable";
import "./Removable.css";

var RemovableIos = function RemovableIos(_ref) {
  var onRemoveClick = _ref.onRemoveClick,
      removePlaceholder = _ref.removePlaceholder,
      removePlaceholderString = _ref.removePlaceholderString,
      children = _ref.children;

  var _useDOM = useDOM(),
      document = _useDOM.document;

  var removeButtonRef = React.useRef(null);

  var _React$useState = React.useState(0),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      removeOffset = _React$useState2[0],
      updateRemoveOffset = _React$useState2[1];

  useGlobalEventListener(document, 'click', removeOffset > 0 && function () {
    updateRemoveOffset(0);
  });

  var onRemoveTransitionEnd = function onRemoveTransitionEnd() {
    if (removeOffset > 0) {
      var _removeButtonRef$curr;

      removeButtonRef === null || removeButtonRef === void 0 ? void 0 : (_removeButtonRef$curr = removeButtonRef.current) === null || _removeButtonRef$curr === void 0 ? void 0 : _removeButtonRef$curr.focus();
    }
  };

  var onRemoveActivateClick = function onRemoveActivateClick() {
    var _removeButtonRef$curr2 = removeButtonRef === null || removeButtonRef === void 0 ? void 0 : removeButtonRef.current,
        _removeButtonRef$curr3 = _removeButtonRef$curr2.offsetWidth,
        offsetWidth = _removeButtonRef$curr3 === void 0 ? 0 : _removeButtonRef$curr3;

    updateRemoveOffset(offsetWidth);
  };

  return createScopedElement("div", {
    vkuiClass: "Removable__content",
    style: {
      transform: "translateX(-".concat(removeOffset !== null && removeOffset !== void 0 ? removeOffset : 0, "px)")
    },
    onTransitionEnd: onRemoveTransitionEnd
  }, createScopedElement(IconButton, {
    hasActive: false,
    hasHover: false,
    "aria-label": removePlaceholderString,
    vkuiClass: "Removable__action Removable__toggle",
    onClick: onRemoveActivateClick,
    disabled: removeOffset > 0
  }, createScopedElement("i", {
    vkuiClass: "Removable__toggle-in",
    role: "presentation"
  })), children, createScopedElement("span", {
    vkuiClass: "Removable__offset",
    "aria-hidden": "true"
  }), createScopedElement(Tappable, {
    Component: "button",
    hasActive: false,
    hasHover: false,
    disabled: removeOffset === 0,
    getRootRef: removeButtonRef,
    vkuiClass: "Removable__remove",
    onClick: onRemoveClick,
    onTransitionEnd: onRemoveTransitionEnd
  }, createScopedElement("span", {
    vkuiClass: "Removable__remove-in"
  }, removePlaceholder)));
};

export var Removable = function Removable(_ref2) {
  var children = _ref2.children,
      onRemove = _ref2.onRemove,
      _ref2$removePlacehold = _ref2.removePlaceholder,
      removePlaceholder = _ref2$removePlacehold === void 0 ? 'Удалить' : _ref2$removePlacehold,
      _ref2$align = _ref2.align,
      align = _ref2$align === void 0 ? 'center' : _ref2$align,
      restProps = _objectWithoutProperties(_ref2, _excluded);

  var platform = usePlatform();

  var _useAdaptivity = useAdaptivity(),
      sizeY = _useAdaptivity.sizeY;

  var onRemoveClick = function onRemoveClick(e) {
    e.preventDefault();
    onRemove && onRemove(e);
  };

  var removePlaceholderString = getTitleFromChildren(removePlaceholder);
  return createScopedElement("div", _extends({}, restProps, {
    vkuiClass: classNames(getClassName('Removable', platform), "Removable--".concat(align), "Removable--sizeY-".concat(sizeY))
  }), (platform === ANDROID || platform === VKCOM) && createScopedElement("div", {
    vkuiClass: "Removable__content"
  }, children, createScopedElement(IconButton, {
    activeMode: "opacity",
    hoverMode: "opacity",
    vkuiClass: "Removable__action",
    onClick: onRemoveClick,
    "aria-label": removePlaceholderString
  }, createScopedElement(Icon24Cancel, {
    role: "presentation"
  }))), platform === IOS && createScopedElement(RemovableIos, {
    onRemoveClick: onRemoveClick,
    removePlaceholder: removePlaceholder,
    removePlaceholderString: removePlaceholderString
  }, children));
};
//# sourceMappingURL=Removable.js.map


text:
package dataflux.persister.hbase;

import dataflux.common.type.WebTxnData;
import dataflux.persister.schema.TColumnFamily;
import dataflux.persister.schema.TWebTxnData;
import dataflux.persister.util.PersistenceUtil;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

public class BatchReader implements Callable<List<WebTxnData>> {

    String tblName = null;

    long startDate = 0;
    long stopDate = 0;
    int txnUId = 0;

    public BatchReader(String tblName, int txnUId, long startDate,
                       long stopDate) {
        this.tblName = tblName;
        this.startDate = startDate;
        this.stopDate = stopDate;
        this.txnUId = txnUId;
    }

    public static void main(String args[]) {
        try {
            BatchReader abr = new BatchReader("TranLoad1", 9895, (new Date("2014-01-23 11:00:00")).getTime(),
                    (new Date("2014-01-23 13:00:00")).getTime());
            List<WebTxnData> ab = abr.call();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public List<WebTxnData> call() throws Exception {

        List<WebTxnData> txnAudit = new ArrayList<WebTxnData>();
        double timeTaken = 0;

        HBaseResourceFactory.HTablePool htp = HBaseResourceFactory.getHBaseTablePool();
        try (HTableInterface table = htp.getTable(tblName);) {
            Scan scan = new Scan();
            String startRow = txnUId + PersistenceUtil.reverseTimeStamp(startDate);
            String stopRow = txnUId + PersistenceUtil.reverseTimeStamp(stopDate);
            System.out.println("startRow : " + startRow + ", stopRow : " + stopRow);
            scan.setStartRow(startRow.getBytes());
            scan.setStopRow(stopRow.getBytes());
            scan.addFamily(TColumnFamily.TXNAUD_CF_BA);
            scan.setBatch(10000);
            String strVal = null;
            try (ResultScanner rs = table.getScanner(scan);) {
                double startTime = System.currentTimeMillis();
                for (Result rslt : rs) {
                    WebTxnData txnData = new WebTxnData();
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_ID_BA));
                    txnData.setTxnId(PersistenceUtil.getIntValue(strVal, 0));
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_URL_BA));
                    txnData.setUrl(strVal);
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_TIMESTAMP_BA));
                    txnData.setTimestamp(PersistenceUtil.getLongValue(strVal, 0));
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_OPERATION_BA));
                    txnData.setOperation(strVal);
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_USERID_BA));
                    txnData.setUserId(PersistenceUtil.getIntValue(strVal, 0));
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_HTTPCODE_BA));
                    txnData.setHttpCode(PersistenceUtil.getIntValue(strVal, 0));
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_RTIME_BA));
                    txnData.setResponseTime(PersistenceUtil.getIntValue(strVal, 0));
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_BYTES_BA));
                    txnData.setBytesTransferred(PersistenceUtil.getIntValue(strVal, 0));
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_SERVERIP_BA));
                    txnData.setServerIp(strVal);
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_CLIENTIP_BA));
                    txnData.setClientIp(strVal);
                    strVal = new String(rslt.getValue(TColumnFamily.TXNAUD_CF_BA, TWebTxnData.TXN_CLIENTAGENT_BA));
                    txnData.setClientAgent(strVal);
                }
                timeTaken = System.currentTimeMillis() - startTime;
                System.out.println("No. of records : " + txnAudit.size() + " in : " + timeTaken + " ms @ " + (txnAudit.size() / timeTaken) * 1000 + " rps");
            }
            //System.out.println("After close");
        } catch (Exception exp) {
            System.out.println("No. of records : " + txnAudit.size() + " time : " + timeTaken + " ms");
            exp.printStackTrace();
        }
        return txnAudit;
    }
}


text:
{% load static %}
<!DOCTYPE html>

        <meta charset="utf-8"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

        <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css">
        <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-iconic-font/2.2.0/css/material-design-iconic-font.min.css">

        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

Home

Now

What is planned

Demo Django-Shopy

Django-Shopy

Django-based E-comerce platform
with friendly admin interface.

                        Django-Shopy has been developed as a free open-source alternative of well-know SaaS e-comerce platfrom shopify.com.

                        It allows you to build your shop based on popular python framework Django and use multiple ready e-comerce themes.
                        In compare with other Django shops Shopifies has nice UI for staff user which is based on Andgular 2.

Now

Project is in deep pre-alpha version for the moment, so already supported:

Admin interface for staff users, products and customers.

What is planned:

full support of liquid template engine

Import and export with shopify.com

Support of localization and internalization

and many othersemail

Demo Django-Shopy:

                        <video class="col s10 offset-s1" width="100%" height="100%" src="/media/shopifier.mp4" autoplay loop></video>

                        username: staff@django-shopy.com

                        password: 123456

                    Go to the demo admin django-shopy

Django-Shopy

Django-based E-comerce platform with friendly admin interface.

                    © 2017 Vladimir Kuryachenko


text:
        {{error.message}}

    <form ab-elem="form" name="form" role="form">

                {{eText('Users:changePassword_oldPassword_Label')}}

            <input ab-elem="oldPassword"
                    type="password" name="login" id="login" required=""
                    placeholder="{{eText('Users:changePassword_oldPassword_Placeholder')}}"
                    class="form-control" />

                {{oldPassword.error.message}}

                {{eText('Users:changePassword_newPassword_Label')}}

            <input ab-elem="newPassword"
                    type="password" name="password" id="password" required=""
                    placeholder="{{eText('Users:changePassword_newPassword_Placeholder')}}"
                    class="form-control" />

            <input ab-elem="newPasswordConfirmation"
                    type="password" name="password" id="password" required=""
                    placeholder="{{eText('Users:changePassword_newPasswordConfirmation_Placeholder')}}"
                    class="form-control" />

                {{newPassword.error.message}}

            <button
                type="submit" class="btn btn-danger">
                {{eText('Users:changePassword_Submit')}}
            </button>

    </form>


text:
namespace GVis {

class Light : public SceneNode
{
	friend class ShadowProjector;

public:
	Light();

	const ShadowProjector* getShadowProjector() const {return m_shadowProjector;}

private:
	ShadowProjector* m_shadowProjector;
};

} // namespace GVis


text:
module GraphDB.Util.Prelude.TH
(
  module Exports,

  purify,
  tryToReify,
  isInstance',
  isProperInstance',
)
where

import GraphDB.Util.Prelude hiding (Fixity)
import Language.Haskell.TH as Exports
import Language.Haskell.TH.Syntax as Exports
import THInstanceReification as Exports

purify :: Q a -> a
purify = unsafePerformIO . runQ

tryToReify :: Name -> Q (Maybe Info)
tryToReify n = recover (return Nothing) (fmap Just $ reify n)

isInstance' :: Name -> [Type] -> Q Bool
isInstance' name types = recover (return False) (isInstance name types)

isProperInstance' :: Name -> [Type] -> Q Bool
isProperInstance' name types = recover (return False) (isProperInstance name types)


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Architecture du GCsystem — documentation Documentation GCsystem 1</title>

    <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="../_static/style.css" type="text/css" />

    <link rel="top" title="documentation Documentation GCsystem 1" href="../index.html"/>
        <link rel="up" title="Pour commencer" href="index.html"/>
        <link rel="next" title="Installation" href="install.html"/>
        <link rel="prev" title="Pour commencer" href="index.html"/>

           Documentation GCsystem

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Pour commencer

Architecture du GCsystem

Organisation du Framework

Cheminement d’une requête

Installation

Installation avec Composer

Installation avec Github et Composer

Configuration

Connexion à la base de données

Parefeu

Antispam

Encodage

Répertoire racine

Langue par défaut

Choix de l’environnement

Maintenance

Profiler

Échappement des variables superglobales

Constantes utilisateur

Cache

Logs

Affichage des erreurs

Minifier sortie html

Asset manager

Chemins vers les ressources web

L’anti spam

Configuration

Page d’erreur

Exceptions

Le parefeu

Les rôles

Les redirections

Page de connexion

Page par défaut

Les pages d’erreur

La faille CSRF

Le routing

Introduction

Création de routes

Création d’une route simple

Gestion des routes à paramètres variables

Gestion des groupes de routes

Restreindre l’accès à une url

Connexion de l’utilisateur

Statut de l’utilisateur

Les objets Request et Response

Les contrôleurs

Les modèles

Les vues

L’Orm

Notions avancées

Tutoriaux

Création d’un blog

Helpers

Pagination

Mails

Autre

        Documentation GCsystem

Docs »

Pour commencer »

Architecture du GCsystem

             View page source

Architecture du GCsystem¶

Avant de commencer à développer votre application, il est important que vous preniez connaissance de l’architecture du GCsystem.

Organisation du Framework¶

La struture du dossier du framework est similaire à celle-ci :

app/
    cache/
    log/
    resource/
src/
    gcs/
        controller/
        model/
        resource/
vendor/
web/

Le dossier app contient les fichiers de cache et de log. Il comprend également toutes les ressources qui seront communes à tous les modules de votre application (configuration, entités, évènements, fichiers de langues, validation de formulaire, template).

Le dossier src est le coeur de votre application, c’est là que vous placerez tous vos modules (contrôleurs, modèles, templates etc.), ainsi que les ressources propres à chaque module (configuration, entités, évènements, fichiers de langues, validation de formulaire).

Le dossier vendor est lié à l’intégration de Composer. C’est dans ce dossier que se trouve le framework en tant que tel. Vous n’aurez jamais à modifier vous-même ce dossier.

Cheminement d’une requête¶

Le premier fichier appelé avant le routing  est index.php. Il s’agit du contrôleur principal de l’application qui va se charger de lancer le moteur. Son appel est paramétré dans le .htaccess situé à la racine du projet :

php_flag short_open_tag off
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

php_flag zlib.output_compression on

Attention

Si vous utilisez un autre logiciel qu’Apache, il vous faudra configurer l’équivalent du .htaccess par vous-même.

Une fois le moteur lancé, celui-ci va se charger d’analyser l’URL soumise afin d’en retirer les informations qui permettront d’appeler les bons contrôleurs des bonnes rubriques.

Parallèlement à l’appel des contrôleurs, le moteur se charge également des processus tels que l’antispam, le parefeu, les crons, la connexion à la base de données, le cache des pages, la création des constantes personnalisées etc.

Comme un bon croquis vaut mieux qu’un long discours, voici un résumé du fonctionnement interne du framework :

        Next

         Previous

        © Copyright 2015, fabsgc.

  Built with Sphinx using a theme provided by Read the Docs.


text:
using System.Linq;
using System.Text.RegularExpressions;

namespace InsurgenceServerCore.Utilities
{
    public static class NicknameChecker
    {
        private static Regex[] ForbiddenWords = {
            new Regex(@".*fuck.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*retard.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*shit.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*damn.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*dick.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*cunt.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*ass.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*cock.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*pussy.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*bitch.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*fag.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*slut.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*nigg.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*gamer.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*penis.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*owo.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*uwu.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*coon.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
            new Regex(@".*jew.*", RegexOptions.IgnoreCase | RegexOptions.Compiled),
        };

        public static bool IsForbiddenWord(string s)
        {
            return ForbiddenWords.Any(forbiddenWord => forbiddenWord.IsMatch(s));
        }
    }
}


text:
"""
Standard implementations of Twisted protocol-related interfaces.

Start here if you are looking to write a new protocol implementation for
Twisted.  The Protocol class contains some introductory material.
"""

#from __future__ import division, absolute_import

#import random
from zope.interface import implementer

#from twisted.python import log, failure, components
#from twisted.internet import interfaces, error, defer

from . import internet_interfaces as interfaces

@implementer(interfaces.IProtocolFactory, interfaces.ILoggingContext)
class Factory:
    """
    This is a factory which produces protocols.

    By default, buildProtocol will create a protocol of the class given in
    self.protocol.
    """

    # put a subclass of Protocol here:
    protocol = None

    numPorts = 0
    noisy = True

    @classmethod
    def forProtocol(cls, protocol, *args, **kwargs):
        """
        Create a factory for the given protocol.

        It sets the C{protocol} attribute and returns the constructed factory
        instance.

        @param protocol: A L{Protocol} subclass

        @param args: Positional arguments for the factory.

        @param kwargs: Keyword arguments for the factory.

        @return: A L{Factory} instance wired up to C{protocol}.
        """
        factory = cls(*args, **kwargs)
        factory.protocol = protocol
        return factory

    def logPrefix(self):
        """
        Describe this factory for log messages.
        """
        return self.__class__.__name__

    def doStart(self):
        """Make sure startFactory is called.

        Users should not call this function themselves!
        """
        if not self.numPorts:
            if self.noisy:
                log.msg("Starting factory %r" % self)
            self.startFactory()
        self.numPorts = self.numPorts + 1

    def doStop(self):
        """Make sure stopFactory is called.

        Users should not call this function themselves!
        """
        if self.numPorts == 0:
            # this shouldn't happen, but does sometimes and this is better
            # than blowing up in assert as we did previously.
            return
        self.numPorts = self.numPorts - 1
        if not self.numPorts:
            if self.noisy:
                log.msg("Stopping factory %r" % self)
            self.stopFactory()

    def startFactory(self):
        """This will be called before I begin listening on a Port or Connector.

        It will only be called once, even if the factory is connected
        to multiple ports.

        This can be used to perform 'unserialization' tasks that
        are best put off until things are actually running, such
        as connecting to a database, opening files, etcetera.
        """

    def stopFactory(self):
        """This will be called before I stop listening on all Ports/Connectors.

        This can be overridden to perform 'shutdown' tasks such as disconnecting
        database connections, closing files, etc.

        It will be called, for example, before an application shuts down,
        if it was connected to a port. User code should not call this function
        directly.
        """

    def buildProtocol(self, addr):
        """Create an instance of a subclass of Protocol.

        The returned instance will handle input on an incoming server
        connection, and an attribute \"factory\" pointing to the creating
        factory.

        Override this method to alter how Protocol instances get created.

        @param addr: an object implementing L{twisted.internet.interfaces.IAddress}
        """
        p = self.protocol()
        p.factory = self
        return p

class BaseProtocol:
    """
    This is the abstract superclass of all protocols.

    Some methods have helpful default implementations here so that they can
    easily be shared, but otherwise the direct subclasses of this class are more
    interesting, L{Protocol} and L{ProcessProtocol}.
    """
    connected = 0
    transport = None

    def makeConnection(self, transport):
        """Make a connection to a transport and a server.

        This sets the 'transport' attribute of this Protocol, and calls the
        connectionMade() callback.
        """
        self.connected = 1
        self.transport = transport
        self.connectionMade()

    def connectionMade(self):
        """Called when a connection is made.

        This may be considered the initializer of the protocol, because
        it is called when the connection is completed.  For clients,
        this is called once the connection to the server has been
        established; for servers, this is called after an accept() call
        stops blocking and a socket has been received.  If you need to
        send any greeting or initial message, do it here.
        """

#connectionDone=failure.Failure(error.ConnectionDone())
#connectionDone.cleanFailure()
connectionDone = None

@implementer(interfaces.IProtocol, interfaces.ILoggingContext)
class Protocol(BaseProtocol):
    """
    This is the base class for streaming connection-oriented protocols.

    If you are going to write a new connection-oriented protocol for Twisted,
    start here.  Any protocol implementation, either client or server, should
    be a subclass of this class.

    The API is quite simple.  Implement L{dataReceived} to handle both
    event-based and synchronous input; output can be sent through the
    'transport' attribute, which is to be an instance that implements
    L{twisted.internet.interfaces.ITransport}.  Override C{connectionLost} to be
    notified when the connection ends.

    Some subclasses exist already to help you write common types of protocols:
    see the L{twisted.protocols.basic} module for a few of them.
    """

    def logPrefix(self):
        """
        Return a prefix matching the class name, to identify log messages
        related to this protocol instance.
        """
        return self.__class__.__name__

    def dataReceived(self, data):
        """Called whenever data is received.

        Use this method to translate to a higher-level message.  Usually, some
        callback will be made upon the receipt of each complete protocol
        message.

        @param data: a string of indeterminate length.  Please keep in mind
            that you will probably need to buffer some data, as partial
            (or multiple) protocol messages may be received!  I recommend
            that unit tests for protocols call through to this method with
            differing chunk sizes, down to one byte at a time.
        """

    def connectionLost(self, reason=connectionDone):
        """Called when the connection is shut down.

        Clear any circular references here, and any external references
        to this Protocol.  The connection has been closed.

        @type reason: L{twisted.python.failure.Failure}
        """


text:
NSString * const TI_APPLICATION_DEPLOYTYPE = @"development";
NSString * const TI_APPLICATION_ID = @"com.projet.db";
NSString * const TI_APPLICATION_PUBLISHER = @"skytoa";
NSString * const TI_APPLICATION_URL = @"http://";
NSString * const TI_APPLICATION_NAME = @"projet";
NSString * const TI_APPLICATION_VERSION = @"1.0";
NSString * const TI_APPLICATION_DESCRIPTION = @"undefined";
NSString * const TI_APPLICATION_COPYRIGHT = @"2015 by skytoa";
NSString * const TI_APPLICATION_GUID = @"67cd1272-421d-44ad-b25c-ab5fda442416";
BOOL const TI_APPLICATION_ANALYTICS = true;
NSString * const TI_APPLICATION_BUILD_TYPE = @"";

#ifdef TARGET_IPHONE_SIMULATOR
NSString * const TI_APPLICATION_RESOURCE_DIR = @"";
#endif

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

#ifdef __LOG__ID__
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *logPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%s.log",STRING(__LOG__ID__)]];
	freopen([logPath cStringUsingEncoding:NSUTF8StringEncoding],"w+",stderr);
	fprintf(stderr,"[INFO] Application started\n");
#endif

	int retVal = UIApplicationMain(argc, argv, nil, @"TiApp");
    [pool release];
    return retVal;
}