By continuing you indicate that you have read and agree to our Terms of service and Privacy policy
by hupfdule Java Version: 2.1.1 License: Apache-2.0
by hupfdule Java Version: 2.1.1 License: Apache-2.0
Support
Quality
Security
License
Reuse
kandi has reviewed apron and discovered the below as its top functions. This is intended to give you an instant insight into apron implemented functionality, and help decide if they suit your requirements.
Get all kandi verified functions for this library.
Get all kandi verified functions for this library.
Advanced Properties — Read and write Java .properties files in a more sane manner.
QUESTION
How do I pivot columns?
Asked 2021-Aug-04 at 17:08I have found this dataframe in an Excel file, very disorganized. This is just a sample of a bigger dataset, with many jobs.
df <- data.frame(
Job = c("Frequency", "Driver", "Operator"),
Gloves = c("Daily", 1,2),
Aprons = c("Weekly", 2,0),
)
df <- data.frame(
Job = c("Driver", "Driver", "Operator", "Operator"),
Frequency= c("Daily", "Weekly", "Daily", "Weekly"),
Item= c("Gloves", "Aprons", "Gloves", "Aprons"),
Quantity= c(1,2,2,0)
)
ANSWER
Answered 2021-Aug-04 at 17:03We could use tidyverse
methods by doing this in three steps
slice(-1)
, reshape to 'long' format (pivot_longer
)slice(1)
, reshape to 'long' format (pivot_longer
)library(dplyr)
library(tidyr)
df %>%
slice(-1) %>%
pivot_longer(cols = -Job, names_to = 'Item',
values_to = 'Quantity') %>%
left_join(df %>%
slice(1) %>%
pivot_longer(cols= -Job, values_to = 'Frequency',
names_to = 'Item') %>%
select(-Job) )
-output
# A tibble: 4 x 4
Job Item Quantity Frequency
<chr> <chr> <chr> <chr>
1 Driver Gloves 1 Daily
2 Driver Aprons 2 Weekly
3 Operator Gloves 2 Daily
4 Operator Aprons 0 Weekly
df <- data.frame(
Job = c("Frequency", "Driver", "Operator"),
Gloves = c("Daily", 1,2),
Aprons = c("Weekly", 2,0))
QUESTION
how to filter array from the letters found within a word game?
Asked 2021-Aug-04 at 10:12I have a word game here made with javascript,
I play against a robot that guesses a word from a directory of words it has. If the guessed word have a matching letter and matching index it turns blue and gets displayed.
If any letter only exist in the guess word but not at correct index it turns orange.
The robot now randomly guesses the words and doesn't do anything with the blue or orange letters. I want the robot to filter the word directory it guesses from with the letters that are correct or exist in the guess word.
I can store those letters in two variable but I'm having scope problems to filter the word directory from the scope these variable
let wordDirectory = ["ABOUT", "ABOVE", "ACTOR", "ACUTE", "ADEPT", "ADMIT", "ADOPT", "ADORE", "ADULT", "AFTER", "AGILE", "AGREE", "AISLE", "ALBUM", "ALERT", "ALIEN", "ALIKE", "ALIVE", "ALLOW", "ALONG", "ALOUD", "ALTER", "AMBER", "AMEND", "AMPLE", "AMPLY", "AMUSE", "ANGEL", "ANGLE", "ANKLE", "APPLE", "APPLY", "APRON", "ARROW", "ASSET", "AVERT", "AVOID", "BACON", "BAKER", "BASIC", "BASIL", "BASIN", "BATHE", "BEACH", "BEARD", "BEAST", "BEATS", "BEGIN", "BEGUN", "BEING", "BELOW", "BIRCH", "BIRTH", "BLACK", "BLANK", "BLINK", "BLOWN", "BLUSH", "BOARD", "BOAST", "BONUS", "BOOST", "BOUND", "BOWEL", "BRAID", "BRAIN", "BRAKE", "BRAND", "BRAVE", "BREAD", "BREAK", "BRIDE", "BRIEF", "BRING", "BRISK", "BROKE", "BROOM", "BROWN", "BULKY", "BUNCH", "BUYER", "CABIN", "CABLE", "CAMEL", "CANDY", "CATER", "CHAIN", "CHAIR", "CHALK", "CHARM", "CHART", "CHASM", "CHEAP", "CHIEF", "CHINA", "CHIPS", "CHOKE", "CHOPS", "CIGAR", "CLAIM", "CLAMP", "CLASP", "CLASS", "CLEAN", "CLEAR", "CLIMB", "CLOAK", "CLONE", "CLOSE", "CLOTH", "CLOUD", "CLOVE", "CLOWN", "COAST", "CORAL", "COUNT", "CRAFT", "CRANE", "CRANK", "CRAWL", "CRISP", "CROSS", "CROWD", "CROWN", "CRUSH", "CRUST", "CURVE", "DAILY", "DAIRY", "DANCE", "DATUM", "DECAY", "DECOR", "DELAY", "DEVIL", "DIARY", "DINER", "DIRTY", "DISCO", "DIVER", "DOUBT", "DOUGH", "DRAFT", "DRAIN", "DRAWN", "DREAM", "DRESS", "DRINK", "DRIVE", "EARLY", "EARTH", "EIGHT", "ELBOW", "EMAIL", "EMPTY", "ENJOY", "EQUAL", "EQUIP", "ETHIC", "EXACT", "EXIST", "EXTRA", "FACET", "FAIRY", "FAITH", "FALSE", "FANCY", "FAULT", "FAVOR", "FEAST", "FETCH", "FIBER", "FIELD", "FINAL", "FIRST", "FLAIR", "FLAKE", "FLASK", "FLICK", "FLOAT", "FLOCK", "FLOWN", "FLUSH", "FLUTE", "FOCAL", "FOCUS", "FORCE", "FORUM", "FOUND", "FRAME", "FRANK", "FRAUD", "FRESH", "FRONT", "FROST", "FROZE", "FRUIT", "FUNGI", "FUNNY", "GHOST", "GIVEN", "GLASS", "GLAZE", "GLOBE", "GLORY", "GLOVE", "GRACE", "GRADE", "GRAIN", "GRAND", "GRAPE", "GRAPH", "GRASP", "GRASS", "GRAVY", "GREAT", "GREET", "GRILL", "GROUP", "GROWN", "GUARD", "GUESS", "GUEST", "GUIDE", "HABIT", "HAIRY", "HAPPY", "HARDY", "HASTE", "HAUNT", "HEART", "HEAVY", "HEFTY", "HONEY", "HORSE", "HOTEL", "HOUSE", "HUMAN", "HUMID", "HUMOR", "HUSKY", "IDEAL", "IMAGE", "IMPLY", "INCUR", "INDEX", "INFER", "INFRA", "INLET", "INNER", "INPUT", "INSET", "IVORY", "JEANS", "JOINT", "JUICE", "LABOR", "LADEN", "LAPSE", "LARGE", "LATEX", "LAUGH", "LAYER", "LEAFY", "LEANS", "LEARN", "LEMON", "LIGHT", "LINER", "LIVER", "LIVES", "LODGE", "LOFTY", "LOGIC", "LOVER", "LOWER", "LUCID", "LUCKY", "LUNCH", "LYMPH", "MACRO", "MAGIC", "MAIZE", "MAJOR", "MAKER", "MANGO", "MAPLE", "MARCH", "MATCH", "MEDAL", "MEDIA", "MERCY", "MERIT", "METAL", "MICRO", "MIDST", "MIGHT", "MINOR", "MINUS", "MIXER", "MODEL", "MOIST", "MONEY", "MONTH", "MORAL", "MOUNT", "MOUSE", "MOUTH", "MOVER", "MOVIE", "MULTI", "MUSIC", "NAIVE", "NEWLY", "NEXUS", "NICHE", "NIGHT", "NINJA", "NOBLE", "NODAL", "NOISE", "NOISY", "NORTH", "NOTCH", "NOTED", "NOVEL", "NURSE", "OCEAN", "OFTEN", "OLIVE", "ONSET", "OPERA", "OPTIC", "ORBIT", "ORGAN", "OTHER", "OUGHT", "OUNCE", "OUTER", "OVERT", "OWING", "OWNED", "OWNER", "OXIDE", "PACED", "PAINT", "PANIC", "PANTS", "PARTY", "PASTE", "PATCH", "PATIO", "PAUSE", "PAVED", "PAYER", "PEACH", "PEARL", "PEDAL", "PHASE", "PHONE", "PIANO", "PILOT", "PINCH", "PIVOT", "PIZZA", "PLACE", "PLAIN", "PLANE", "PLANK", "PLANT", "PLATE", "PLEAD", "PLUCK", "POINT", "POKER", "POLAR", "PORCH", "POUCH", "POUND", "POWER", "PRESS", "PRICE", "PRIDE", "PRIME", "PRINT", "PRIZE", "PRONE", "PROUD", "PROVE", "PUNCH", "PUPPY", "PURGE", "PURSE", "QUAIL", "QUEEN", "QUERY", "QUEST", "QUICK", "QUIET", "QUILT", "QUITE", "QUOTA", "QUOTE", "RADIO", "RAINY", "RAISE", "RANCH", "RANGE", "RAPID", "RATIO", "REACH", "REACT", "READY", "REALM", "REGAL", "REIGN", "RELAX", "RELAY", "RELIC", "REMIT", "REPAY", "REPLY", "RESIN", "RIDGE", "RIGHT", "RINSE", "RISKY", "RIVAL", "ROAST", "ROCKY", "ROMAN", "ROUGH", "ROUND", "ROYAL", "RUSTY", "SADLY", "SAINT", "SALON", "SALTY", "SANDY", "SATIN", "SAUCE", "SCALE", "SCARE", "SCARF", "SCARY", "SCENT", "SCORE", "SCOUT", "SCREW", "SERUM", "SETUP", "SHADE", "SHADY", "SHAKE", "SHAKY", "SHAME", "SHAPE", "SHARE", "SHARK", "SHARP", "SHAVE", "SHEAR", "SHELF", "SHELL", "SHIFT", "SHINE", "SHIRT", "SHOCK", "SHORE", "SHORT", "SHOUT", "SHOVE", "SHOWN", "SHRUB", "SHRUG", "SIGHT", "SIGMA", "SILKY", "SINCE", "SIXTY", "SKATE", "SKILL", "SKIRT", "SLACK", "SLATE", "SLEEP", "SLEPT", "SLICE", "SLICK", "SLIDE", "SLING", "SLUMP", "SMALL", "SMART", "SMILE", "SMOKE", "SMOKY", "SNACK", "SNAIL", "SNAKE", "SNEAK", "SOBER", "SOLAR", "SOLVE", "SOUND", "SOUTH", "SPACE", "SPADE", "SPARE", "SPARK", "SPEAK", "SPEAR", "SPELL", "SPICE", "SPICY", "SPIKE", "SPILL", "SPINE", "SPLIT", "SPOIL", "SPOKE", "SPORT", "SPRAY", "SQUAD", "SQUAT", "SQUID", "STACK", "STAFF", "STAGE", "STAIN", "STAIR", "STAKE", "STALE", "STAMP", "STAND", "STARE", "STEAD", "STEAK", "STEAL", "STEAM", "STEEL", "STERN", "STICK", "STILL", "STING", "STOCK", "STONE", "STORE", "STORM", "STORY", "STOVE", "STRAP", "STRAW", "STRAY", "STUCK", "STUDY", "STUFF", "STUMP", "STYLE", "SUGAR", "SUITE", "SUNNY", "SUPER", "SWAMP", "SWEAT", "SWEPT", "SWIFT", "SWINE", "SWING", "SWIRL", "SYRUP", "TABLE", "TAKEN", "TEACH", "TEMPO", "THANK", "THEIR", "THICK", "THING", "THINK", "THIRD", "THORN", "THOSE", "THREE", "THROW", "THUMB", "THYME", "TIDAL", "TIGER", "TIMER", "TODAY", "TOKEN", "TONIC", "TOUCH", "TOUGH", "TOWEL", "TOWER", "TOXIC", "TOXIN", "TRACE", "TRACK", "TRADE", "TRAIL", "TRAIN", "TRASH", "TREAD", "TREND", "TRIAD", "TRIAL", "TRIBE", "TRICK", "TWICE", "TWINS", "ULCER", "ULTRA", "UNCLE", "UNDER", "UNIFY", "UNITE", "UNITY", "UPSET", "URBAN", "USAGE", "VAGUE", "VALID", "VALUE", "VIDEO", "VIRAL", "VITAL", "VOCAL", "VODKA", "VOICE", "VOWEL", "WAFER", "WAGED", "WAGER", "WAGON", "WAIST", "WAIVE", "WASTE", "WATCH", "WATER", "WEARY", "WEIGH", "WEIRD", "WHALE", "WHARF", "WHEAT", "WHILE", "WHITE", "WHOLE", "WHOSE", "WIDEN", "WIDTH", "WINDY", "WOMAN", "WOMEN", "WORLD", "WORSE", "WORST", "WORTH", "WOULD", "WOUND", "WOVEN", "WRECK", "WRITE", "WRONG", "YEAST", "YIELD", "YOUNG", "YOUTH"];
// generate random word for user and robot to guess
const randomWord = function(array) {
return array[Math.floor(Math.random() * array.length)];
}
let pickedWord = randomWord(wordDirectory);
//recieve user input and show it on screen.
const btn = document.getElementById("btn");
console.log(pickedWord);
btn.addEventListener("click", function(e) {
e.preventDefault();
const li = document.createElement("li");
const list = document.getElementById("list");
const list2 = document.getElementById("list2");
const userGuess = document.getElementById("userInput").value;
/*USER---------*/
const guessResult = document.createElement('p')
if (userGuess === pickedWord) {
li.style.color = 'green';
guessResult.appendChild(document.createTextNode(userGuess));
alert("user wins");
window.location.reload(false);
} else {
userGuess.split('').forEach((char, i) => {
const span = document.createElement('span');
if (pickedWord.charAt(i) === char) {
span.style.color = 'dodgerblue';
} else if (pickedWord.includes(char)) {
span.style.color = 'orange';
}
span.appendChild(document.createTextNode(char));
guessResult.appendChild(span);
});
}
li.appendChild(guessResult);
list.appendChild(li);
setTimeout(function() {
startRobot();
}, 2000);
});
/*ROBOT----------------------------------- */
function startRobot() {
const randomWord = function(array) {
return array[Math.floor(Math.random() * array.length)];
}
let robotGuess = randomWord(wordDirectory);
const li = document.createElement("li");
const robotResult = document.createElement('p')
if (robotGuess === pickedWord) {
li.style.color = 'green';
guessResult.appendChild(document.createTextNode(robotGuess));
alert("robot wins");
window.location.reload(false);
} else {
robotGuess.split('').forEach((char, i) => {
const span = document.createElement('span');
if (pickedWord.charAt(i) === char) {
span.style.color = 'dodgerblue';
} else if (pickedWord.includes(char)) {
span.style.color = 'orange';
}
span.appendChild(document.createTextNode(char));
robotResult.appendChild(span);
});
}
li.appendChild(robotResult);
list2.appendChild(li);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.rules {
font-size: 1.5rem;
}
#green {
color: green;
}
#blue {
color: dodgerblue;
}
#orange {
color: orange;
}
form input {
width: 200px;
height: 50px;
}
form button {
height: 50px;
}
form {
margin-top: 40px;
}
.lists {
width: 100%;
height: 100%;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
margin-top: 10px;
}
.lists ul {
margin: 10px 20px;
list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Robot</title>
</head>
<body>
<div class="container">
<div class="rules">
<p><span id="green">If</span> the whole word is correct</p>
<p><span id="blue">If</span> the letter guessed and its position is correct</p>
<p><span id="orange">If</span> the letter is corect but its position is not</p>
<p>Robot will start guessing 2 seconds after user guessed</p>
</div>
<form>
<input onkeyup="this.value = this.value.toUpperCase();" id="userInput" type="text" placeholder="Text">
<button id="btn">Submit</button>
</form>
<div class="lists">
<ul id="list">
<h3>user</h3>
</ul>
<ul id="list2">
<h3>robot</h3>
</ul>
</div>
</div>
. how can i filter array from where my variable are?
ANSWER
Answered 2021-Aug-04 at 09:42You have too much code too see where the problem is happening. Is this the filter you are looking for?
let words = ['HOUSE', 'DOG', 'MOON', 'MAN'];
let letter = 'M';
let filtered = words.filter((w) => w.indexOf(letter) > -1);
console.log(filtered)
EDIT: I know notice you know how to filter but having scope problems. However, I don't know what variables giving you troubles
QUESTION
how to compare arrays and find if a letter is in the array at the same index and if it is in the array even if its not at the same index?
Asked 2021-Aug-03 at 11:09Hi i am writing a javascript guessing game which on start of the page a random word is generated, then the user tries to guess the word, if the user guess the whole word correctly the word is turned to green and pushed to page. i have made this part. now here if the user guess doesn't match the random word I'm trying to compare the two words and if any letters in user guess matches the random words letters and both letters are at the same index the letter in the use guess becomes yellow and then pushed to the screen. but if the letters is in the wrong index but still exist in the other word i want that letter to be blue.i have tried to make them into arrays and compare them but i cant find the logic to do so.
const wordDirectory = ["ABOUT", "ABOVE", "ACTOR", "ACUTE", "ADEPT", "ADMIT", "ADOPT", "ADORE", "ADULT", "AFTER", "AGILE", "AGREE", "AISLE", "ALBUM", "ALERT", "ALIEN", "ALIKE", "ALIVE", "ALLOW", "ALONG", "ALOUD", "ALTER", "AMBER", "AMEND", "AMPLE", "AMPLY", "AMUSE", "ANGEL", "ANGLE", "ANKLE", "APPLE", "APPLY", "APRON", "ARROW", "ASSET", "AVERT", "AVOID", "BACON", "BAKER", "BASIC", "BASIL", "BASIN", "BATHE", "BEACH", "BEARD", "BEAST", "BEATS", "BEGIN", "BEGUN", "BEING", "BELOW", "BIRCH", "BIRTH", "BLACK", "BLANK", "BLINK", "BLOWN", "BLUSH", "BOARD", "BOAST", "BONUS", "BOOST", "BOUND", "BOWEL", "BRAID", "BRAIN", "BRAKE", "BRAND", "BRAVE", "BREAD", "BREAK", "BRIDE", "BRIEF", "BRING", "BRISK", "BROKE", "BROOM", "BROWN", "BULKY", "BUNCH", "BUYER", "CABIN", "CABLE", "CAMEL", "CANDY", "CATER", "CHAIN", "CHAIR", "CHALK", "CHARM", "CHART", "CHASM", "CHEAP", "CHIEF", "CHINA", "CHIPS", "CHOKE", "CHOPS", "CIGAR", "CLAIM", "CLAMP", "CLASP", "CLASS", "CLEAN", "CLEAR", "CLIMB", "CLOAK", "CLONE", "CLOSE", "CLOTH", "CLOUD", "CLOVE", "CLOWN", "COAST", "CORAL", "COUNT", "CRAFT", "CRANE", "CRANK", "CRAWL", "CRISP", "CROSS", "CROWD", "CROWN", "CRUSH", "CRUST", "CURVE", "DAILY", "DAIRY", "DANCE", "DATUM", "DECAY", "DECOR", "DELAY", "DEVIL", "DIARY", "DINER", "DIRTY", "DISCO", "DIVER", "DOUBT", "DOUGH", "DRAFT", "DRAIN", "DRAWN", "DREAM", "DRESS", "DRINK", "DRIVE", "EARLY", "EARTH", "EIGHT", "ELBOW", "EMAIL", "EMPTY", "ENJOY", "EQUAL", "EQUIP", "ETHIC", "EXACT", "EXIST", "EXTRA", "FACET", "FAIRY", "FAITH", "FALSE", "FANCY", "FAULT", "FAVOR", "FEAST", "FETCH", "FIBER", "FIELD", "FINAL", "FIRST", "FLAIR", "FLAKE", "FLASK", "FLICK", "FLOAT", "FLOCK", "FLOWN", "FLUSH", "FLUTE", "FOCAL", "FOCUS", "FORCE", "FORUM", "FOUND", "FRAME", "FRANK", "FRAUD", "FRESH", "FRONT", "FROST", "FROZE", "FRUIT", "FUNGI", "FUNNY", "GHOST", "GIVEN", "GLASS", "GLAZE", "GLOBE", "GLORY", "GLOVE", "GRACE", "GRADE", "GRAIN", "GRAND", "GRAPE", "GRAPH", "GRASP", "GRASS", "GRAVY", "GREAT", "GREET", "GRILL", "GROUP", "GROWN", "GUARD", "GUESS", "GUEST", "GUIDE", "HABIT", "HAIRY", "HAPPY", "HARDY", "HASTE", "HAUNT", "HEART", "HEAVY", "HEFTY", "HONEY", "HORSE", "HOTEL", "HOUSE", "HUMAN", "HUMID", "HUMOR", "HUSKY", "IDEAL", "IMAGE", "IMPLY", "INCUR", "INDEX", "INFER", "INFRA", "INLET", "INNER", "INPUT", "INSET", "IVORY", "JEANS", "JOINT", "JUICE", "LABOR", "LADEN", "LAPSE", "LARGE", "LATEX", "LAUGH", "LAYER", "LEAFY", "LEANS", "LEARN", "LEMON", "LIGHT", "LINER", "LIVER", "LIVES", "LODGE", "LOFTY", "LOGIC", "LOVER", "LOWER", "LUCID", "LUCKY", "LUNCH", "LYMPH", "MACRO", "MAGIC", "MAIZE", "MAJOR", "MAKER", "MANGO", "MAPLE", "MARCH", "MATCH", "MEDAL", "MEDIA", "MERCY", "MERIT", "METAL", "MICRO", "MIDST", "MIGHT", "MINOR", "MINUS", "MIXER", "MODEL", "MOIST", "MONEY", "MONTH", "MORAL", "MOUNT", "MOUSE", "MOUTH", "MOVER", "MOVIE", "MULTI", "MUSIC", "NAIVE", "NEWLY", "NEXUS", "NICHE", "NIGHT", "NINJA", "NOBLE", "NODAL", "NOISE", "NOISY", "NORTH", "NOTCH", "NOTED", "NOVEL", "NURSE", "OCEAN", "OFTEN", "OLIVE", "ONSET", "OPERA", "OPTIC", "ORBIT", "ORGAN", "OTHER", "OUGHT", "OUNCE", "OUTER", "OVERT", "OWING", "OWNED", "OWNER", "OXIDE", "PACED", "PAINT", "PANIC", "PANTS", "PARTY", "PASTE", "PATCH", "PATIO", "PAUSE", "PAVED", "PAYER", "PEACH", "PEARL", "PEDAL", "PHASE", "PHONE", "PIANO", "PILOT", "PINCH", "PIVOT", "PIZZA", "PLACE", "PLAIN", "PLANE", "PLANK", "PLANT", "PLATE", "PLEAD", "PLUCK", "POINT", "POKER", "POLAR", "PORCH", "POUCH", "POUND", "POWER", "PRESS", "PRICE", "PRIDE", "PRIME", "PRINT", "PRIZE", "PRONE", "PROUD", "PROVE", "PUNCH", "PUPPY", "PURGE", "PURSE", "QUAIL", "QUEEN", "QUERY", "QUEST", "QUICK", "QUIET", "QUILT", "QUITE", "QUOTA", "QUOTE", "RADIO", "RAINY", "RAISE", "RANCH", "RANGE", "RAPID", "RATIO", "REACH", "REACT", "READY", "REALM", "REGAL", "REIGN", "RELAX", "RELAY", "RELIC", "REMIT", "REPAY", "REPLY", "RESIN", "RIDGE", "RIGHT", "RINSE", "RISKY", "RIVAL", "ROAST", "ROCKY", "ROMAN", "ROUGH", "ROUND", "ROYAL", "RUSTY", "SADLY", "SAINT", "SALON", "SALTY", "SANDY", "SATIN", "SAUCE", "SCALE", "SCARE", "SCARF", "SCARY", "SCENT", "SCORE", "SCOUT", "SCREW", "SERUM", "SETUP", "SHADE", "SHADY", "SHAKE", "SHAKY", "SHAME", "SHAPE", "SHARE", "SHARK", "SHARP", "SHAVE", "SHEAR", "SHELF", "SHELL", "SHIFT", "SHINE", "SHIRT", "SHOCK", "SHORE", "SHORT", "SHOUT", "SHOVE", "SHOWN", "SHRUB", "SHRUG", "SIGHT", "SIGMA", "SILKY", "SINCE", "SIXTY", "SKATE", "SKILL", "SKIRT", "SLACK", "SLATE", "SLEEP", "SLEPT", "SLICE", "SLICK", "SLIDE", "SLING", "SLUMP", "SMALL", "SMART", "SMILE", "SMOKE", "SMOKY", "SNACK", "SNAIL", "SNAKE", "SNEAK", "SOBER", "SOLAR", "SOLVE", "SOUND", "SOUTH", "SPACE", "SPADE", "SPARE", "SPARK", "SPEAK", "SPEAR", "SPELL", "SPICE", "SPICY", "SPIKE", "SPILL", "SPINE", "SPLIT", "SPOIL", "SPOKE", "SPORT", "SPRAY", "SQUAD", "SQUAT", "SQUID", "STACK", "STAFF", "STAGE", "STAIN", "STAIR", "STAKE", "STALE", "STAMP", "STAND", "STARE", "STEAD", "STEAK", "STEAL", "STEAM", "STEEL", "STERN", "STICK", "STILL", "STING", "STOCK", "STONE", "STORE", "STORM", "STORY", "STOVE", "STRAP", "STRAW", "STRAY", "STUCK", "STUDY", "STUFF", "STUMP", "STYLE", "SUGAR", "SUITE", "SUNNY", "SUPER", "SWAMP", "SWEAT", "SWEPT", "SWIFT", "SWINE", "SWING", "SWIRL", "SYRUP", "TABLE", "TAKEN", "TEACH", "TEMPO", "THANK", "THEIR", "THICK", "THING", "THINK", "THIRD", "THORN", "THOSE", "THREE", "THROW", "THUMB", "THYME", "TIDAL", "TIGER", "TIMER", "TODAY", "TOKEN", "TONIC", "TOUCH", "TOUGH", "TOWEL", "TOWER", "TOXIC", "TOXIN", "TRACE", "TRACK", "TRADE", "TRAIL", "TRAIN", "TRASH", "TREAD", "TREND", "TRIAD", "TRIAL", "TRIBE", "TRICK", "TWICE", "TWINS", "ULCER", "ULTRA", "UNCLE", "UNDER", "UNIFY", "UNITE", "UNITY", "UPSET", "URBAN", "USAGE", "VAGUE", "VALID", "VALUE", "VIDEO", "VIRAL", "VITAL", "VOCAL", "VODKA", "VOICE", "VOWEL", "WAFER", "WAGED", "WAGER", "WAGON", "WAIST", "WAIVE", "WASTE", "WATCH", "WATER", "WEARY", "WEIGH", "WEIRD", "WHALE", "WHARF", "WHEAT", "WHILE", "WHITE", "WHOLE", "WHOSE", "WIDEN", "WIDTH", "WINDY", "WOMAN", "WOMEN", "WORLD", "WORSE", "WORST", "WORTH", "WOULD", "WOUND", "WOVEN", "WRECK", "WRITE", "WRONG", "YEAST", "YIELD", "YOUNG", "YOUTH"];
// generate random word for user and robot to guess
const randomWord = function(array) {
return array[Math.floor(Math.random() * array.length)];
}
let pickedWord = randomWord(wordDirectory);
//recieve user input and show it on screen.
const btn = document.getElementById("btn");
console.log(pickedWord);
btn.addEventListener("click", function(e) {
e.preventDefault();
const li = document.createElement("li");
const list = document.getElementById("list");
const userGuess = document.getElementById("userInput").value;
/*Compare---------*/
if (userGuess === pickedWord) {
li.style.color = 'green';
} else {
let comp1 = userGuess.split('');
let comp2 = pickedWord.split('');
console.log(comp1);
}
const word = document.createTextNode(userGuess);
li.appendChild(word);
list.appendChild(li);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#list li {
list-style: none;
margin-top: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Robot</title>
</head>
<body>
<form>
<input onkeyup="this.value = this.value.toUpperCase();" id="userInput" type="text" placeholder="Text">
<button id="btn">Submit</button>
<ul id="list"></ul>
</form>
ANSWER
Answered 2021-Aug-03 at 11:09You can make use of String#includes()
and String#charAt()
to check each character in the userGuess
against the pickedWord
.
The snippet below uses the results to wrap each character in a span
of the appropriate color. You can refactor the HTML generated as needed.
/*Compare---------*/
const guessResult = document.createElement('p')
if (userGuess === pickedWord) {
li.style.color = 'mediumseagreen';
guessResult.appendChild(document.createTextNode(userGuess));
} else {
userGuess.split('').forEach((char, i) => {
const span = document.createElement('span');
if (pickedWord.charAt(i) === char) {
span.style.color = 'dodgerblue';
} else if (pickedWord.includes(char)) {
span.style.color = 'tomato';
}
span.appendChild(document.createTextNode(char));
guessResult.appendChild(span);
});
}
Show working snippet:
const wordDirectory = ["ABOUT", "ABOVE", "ACTOR", "ACUTE", "ADEPT", "ADMIT", "ADOPT", "ADORE", "ADULT", "AFTER", "AGILE", "AGREE", "AISLE", "ALBUM", "ALERT", "ALIEN", "ALIKE", "ALIVE", "ALLOW", "ALONG", "ALOUD", "ALTER", "AMBER", "AMEND", "AMPLE", "AMPLY", "AMUSE", "ANGEL", "ANGLE", "ANKLE", "APPLE", "APPLY", "APRON", "ARROW", "ASSET", "AVERT", "AVOID", "BACON", "BAKER", "BASIC", "BASIL", "BASIN", "BATHE", "BEACH", "BEARD", "BEAST", "BEATS", "BEGIN", "BEGUN", "BEING", "BELOW", "BIRCH", "BIRTH", "BLACK", "BLANK", "BLINK", "BLOWN", "BLUSH", "BOARD", "BOAST", "BONUS", "BOOST", "BOUND", "BOWEL", "BRAID", "BRAIN", "BRAKE", "BRAND", "BRAVE", "BREAD", "BREAK", "BRIDE", "BRIEF", "BRING", "BRISK", "BROKE", "BROOM", "BROWN", "BULKY", "BUNCH", "BUYER", "CABIN", "CABLE", "CAMEL", "CANDY", "CATER", "CHAIN", "CHAIR", "CHALK", "CHARM", "CHART", "CHASM", "CHEAP", "CHIEF", "CHINA", "CHIPS", "CHOKE", "CHOPS", "CIGAR", "CLAIM", "CLAMP", "CLASP", "CLASS", "CLEAN", "CLEAR", "CLIMB", "CLOAK", "CLONE", "CLOSE", "CLOTH", "CLOUD", "CLOVE", "CLOWN", "COAST", "CORAL", "COUNT", "CRAFT", "CRANE", "CRANK", "CRAWL", "CRISP", "CROSS", "CROWD", "CROWN", "CRUSH", "CRUST", "CURVE", "DAILY", "DAIRY", "DANCE", "DATUM", "DECAY", "DECOR", "DELAY", "DEVIL", "DIARY", "DINER", "DIRTY", "DISCO", "DIVER", "DOUBT", "DOUGH", "DRAFT", "DRAIN", "DRAWN", "DREAM", "DRESS", "DRINK", "DRIVE", "EARLY", "EARTH", "EIGHT", "ELBOW", "EMAIL", "EMPTY", "ENJOY", "EQUAL", "EQUIP", "ETHIC", "EXACT", "EXIST", "EXTRA", "FACET", "FAIRY", "FAITH", "FALSE", "FANCY", "FAULT", "FAVOR", "FEAST", "FETCH", "FIBER", "FIELD", "FINAL", "FIRST", "FLAIR", "FLAKE", "FLASK", "FLICK", "FLOAT", "FLOCK", "FLOWN", "FLUSH", "FLUTE", "FOCAL", "FOCUS", "FORCE", "FORUM", "FOUND", "FRAME", "FRANK", "FRAUD", "FRESH", "FRONT", "FROST", "FROZE", "FRUIT", "FUNGI", "FUNNY", "GHOST", "GIVEN", "GLASS", "GLAZE", "GLOBE", "GLORY", "GLOVE", "GRACE", "GRADE", "GRAIN", "GRAND", "GRAPE", "GRAPH", "GRASP", "GRASS", "GRAVY", "GREAT", "GREET", "GRILL", "GROUP", "GROWN", "GUARD", "GUESS", "GUEST", "GUIDE", "HABIT", "HAIRY", "HAPPY", "HARDY", "HASTE", "HAUNT", "HEART", "HEAVY", "HEFTY", "HONEY", "HORSE", "HOTEL", "HOUSE", "HUMAN", "HUMID", "HUMOR", "HUSKY", "IDEAL", "IMAGE", "IMPLY", "INCUR", "INDEX", "INFER", "INFRA", "INLET", "INNER", "INPUT", "INSET", "IVORY", "JEANS", "JOINT", "JUICE", "LABOR", "LADEN", "LAPSE", "LARGE", "LATEX", "LAUGH", "LAYER", "LEAFY", "LEANS", "LEARN", "LEMON", "LIGHT", "LINER", "LIVER", "LIVES", "LODGE", "LOFTY", "LOGIC", "LOVER", "LOWER", "LUCID", "LUCKY", "LUNCH", "LYMPH", "MACRO", "MAGIC", "MAIZE", "MAJOR", "MAKER", "MANGO", "MAPLE", "MARCH", "MATCH", "MEDAL", "MEDIA", "MERCY", "MERIT", "METAL", "MICRO", "MIDST", "MIGHT", "MINOR", "MINUS", "MIXER", "MODEL", "MOIST", "MONEY", "MONTH", "MORAL", "MOUNT", "MOUSE", "MOUTH", "MOVER", "MOVIE", "MULTI", "MUSIC", "NAIVE", "NEWLY", "NEXUS", "NICHE", "NIGHT", "NINJA", "NOBLE", "NODAL", "NOISE", "NOISY", "NORTH", "NOTCH", "NOTED", "NOVEL", "NURSE", "OCEAN", "OFTEN", "OLIVE", "ONSET", "OPERA", "OPTIC", "ORBIT", "ORGAN", "OTHER", "OUGHT", "OUNCE", "OUTER", "OVERT", "OWING", "OWNED", "OWNER", "OXIDE", "PACED", "PAINT", "PANIC", "PANTS", "PARTY", "PASTE", "PATCH", "PATIO", "PAUSE", "PAVED", "PAYER", "PEACH", "PEARL", "PEDAL", "PHASE", "PHONE", "PIANO", "PILOT", "PINCH", "PIVOT", "PIZZA", "PLACE", "PLAIN", "PLANE", "PLANK", "PLANT", "PLATE", "PLEAD", "PLUCK", "POINT", "POKER", "POLAR", "PORCH", "POUCH", "POUND", "POWER", "PRESS", "PRICE", "PRIDE", "PRIME", "PRINT", "PRIZE", "PRONE", "PROUD", "PROVE", "PUNCH", "PUPPY", "PURGE", "PURSE", "QUAIL", "QUEEN", "QUERY", "QUEST", "QUICK", "QUIET", "QUILT", "QUITE", "QUOTA", "QUOTE", "RADIO", "RAINY", "RAISE", "RANCH", "RANGE", "RAPID", "RATIO", "REACH", "REACT", "READY", "REALM", "REGAL", "REIGN", "RELAX", "RELAY", "RELIC", "REMIT", "REPAY", "REPLY", "RESIN", "RIDGE", "RIGHT", "RINSE", "RISKY", "RIVAL", "ROAST", "ROCKY", "ROMAN", "ROUGH", "ROUND", "ROYAL", "RUSTY", "SADLY", "SAINT", "SALON", "SALTY", "SANDY", "SATIN", "SAUCE", "SCALE", "SCARE", "SCARF", "SCARY", "SCENT", "SCORE", "SCOUT", "SCREW", "SERUM", "SETUP", "SHADE", "SHADY", "SHAKE", "SHAKY", "SHAME", "SHAPE", "SHARE", "SHARK", "SHARP", "SHAVE", "SHEAR", "SHELF", "SHELL", "SHIFT", "SHINE", "SHIRT", "SHOCK", "SHORE", "SHORT", "SHOUT", "SHOVE", "SHOWN", "SHRUB", "SHRUG", "SIGHT", "SIGMA", "SILKY", "SINCE", "SIXTY", "SKATE", "SKILL", "SKIRT", "SLACK", "SLATE", "SLEEP", "SLEPT", "SLICE", "SLICK", "SLIDE", "SLING", "SLUMP", "SMALL", "SMART", "SMILE", "SMOKE", "SMOKY", "SNACK", "SNAIL", "SNAKE", "SNEAK", "SOBER", "SOLAR", "SOLVE", "SOUND", "SOUTH", "SPACE", "SPADE", "SPARE", "SPARK", "SPEAK", "SPEAR", "SPELL", "SPICE", "SPICY", "SPIKE", "SPILL", "SPINE", "SPLIT", "SPOIL", "SPOKE", "SPORT", "SPRAY", "SQUAD", "SQUAT", "SQUID", "STACK", "STAFF", "STAGE", "STAIN", "STAIR", "STAKE", "STALE", "STAMP", "STAND", "STARE", "STEAD", "STEAK", "STEAL", "STEAM", "STEEL", "STERN", "STICK", "STILL", "STING", "STOCK", "STONE", "STORE", "STORM", "STORY", "STOVE", "STRAP", "STRAW", "STRAY", "STUCK", "STUDY", "STUFF", "STUMP", "STYLE", "SUGAR", "SUITE", "SUNNY", "SUPER", "SWAMP", "SWEAT", "SWEPT", "SWIFT", "SWINE", "SWING", "SWIRL", "SYRUP", "TABLE", "TAKEN", "TEACH", "TEMPO", "THANK", "THEIR", "THICK", "THING", "THINK", "THIRD", "THORN", "THOSE", "THREE", "THROW", "THUMB", "THYME", "TIDAL", "TIGER", "TIMER", "TODAY", "TOKEN", "TONIC", "TOUCH", "TOUGH", "TOWEL", "TOWER", "TOXIC", "TOXIN", "TRACE", "TRACK", "TRADE", "TRAIL", "TRAIN", "TRASH", "TREAD", "TREND", "TRIAD", "TRIAL", "TRIBE", "TRICK", "TWICE", "TWINS", "ULCER", "ULTRA", "UNCLE", "UNDER", "UNIFY", "UNITE", "UNITY", "UPSET", "URBAN", "USAGE", "VAGUE", "VALID", "VALUE", "VIDEO", "VIRAL", "VITAL", "VOCAL", "VODKA", "VOICE", "VOWEL", "WAFER", "WAGED", "WAGER", "WAGON", "WAIST", "WAIVE", "WASTE", "WATCH", "WATER", "WEARY", "WEIGH", "WEIRD", "WHALE", "WHARF", "WHEAT", "WHILE", "WHITE", "WHOLE", "WHOSE", "WIDEN", "WIDTH", "WINDY", "WOMAN", "WOMEN", "WORLD", "WORSE", "WORST", "WORTH", "WOULD", "WOUND", "WOVEN", "WRECK", "WRITE", "WRONG", "YEAST", "YIELD", "YOUNG", "YOUTH"];
// generate random word for user and robot to guess
const randomWord = function (array) {
return array[Math.floor(Math.random() * array.length)];
}
let pickedWord = randomWord(wordDirectory);
//recieve user input and show it on screen.
const btn = document.getElementById("btn");
console.log(pickedWord);
btn.addEventListener("click", function (e) {
e.preventDefault();
const li = document.createElement("li");
const list = document.getElementById("list");
const userGuess = document.getElementById("userInput").value;
/*Compare---------*/
const guessResult = document.createElement('p')
if (userGuess === pickedWord) {
li.style.color = 'mediumseagreen';
guessResult.appendChild(document.createTextNode(userGuess));
} else {
userGuess.split('').forEach((char, i) => {
const span = document.createElement('span');
if (pickedWord.charAt(i) === char) {
span.style.color = 'dodgerblue';
} else if (pickedWord.includes(char)) {
span.style.color = 'tomato';
}
span.appendChild(document.createTextNode(char));
guessResult.appendChild(span);
});
}
li.appendChild(guessResult);
list.appendChild(li);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#list li {
list-style: none;
margin-top: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Robot</title>
</head>
<body>
<form>
<input onkeyup="this.value = this.value.toUpperCase();" id="userInput" type="text" placeholder="Text">
<button id="btn">Submit</button>
<ul id="list"></ul>
</form>
QUESTION
Find the table entry with the largest number, only if it matches a condition
Asked 2021-Jun-13 at 19:56I have a table like below and I want to return the name of the item with the greatest effect of a particular type. For example, I want the name of the ring with the best 'Shield' enchantment, in this case 'Brusef Amelion's Ring'.
Description | Apparel slot | Effect Type | Effect Value |
---|---|---|---|
Apron of Adroitness | Chest | Fortify Agility | 5 pts |
Brusef Amelion's Ring | Ring | Shield | 18% |
Cuirass of the Herald | Chest | Fortify Health | 15 pts |
Fortify Magicka Pants | Legs | Fortify Magicka | 20 pts |
Grand ring of Aegis | Ring | Shield | 6% |
I've tried using a MAXIFS statement:
=maxifs(Effect Value, Apparel Slot, "=Ring", Effect Type, "=Shield")
and that returns 0.18, as I'd expect. But I want it to return the name of this item, 'Brusef Amelion's Ring'. So I then tried using a vlookup on this value, but there doesn't seem to be the option to only lookup a value if ('Apparel Slot'='Ring' && 'Effect Type'='Shield'), for example.
I feel like there must be a way of nesting some specific functions here, but I can't quite figure it out.
Is there any way to do this while avoiding manually sorting and filtering my data before running each query?
ANSWER
Answered 2021-Jun-13 at 19:56Is this what you are looking for?
=DGET(A1:D6,"Description",{"Apparel slot","Effect Value";"Ring",MAXIFS(D2:D6,B2:B6,"Ring",C2:C6,"Shield")})
DGET function needs column headers to work with as you can see. So we want the value from the column Description. "Originally" this is a DGET function:
DGET(A2:F20,"price",{"Ticker";"Google"})
This is saying: Find price where ticker = google.
We can enhance this a bit by entering two criteria's this is done , or \ separated (depends on your country settings) like this:
DGET(A2:F20,"price",{"Ticker","Year;"Google",2020})
DGET(A2:F20;"price";{"Ticker"\"Year;"Google"\2020})
Find price where ticker = google and year = 2020.
Ofcource you can replace "Google" with a cell reference. Hope this helps.
QUESTION
Why is sklearn's TfidfVectorizer returning an empty matrix when I pass an argument for vocabulary, but not when I don't?
Asked 2021-May-28 at 14:41I'm trying to get the tf-idf for a set of documents using the following code:
documents = ['iADV díltudNOUN iADV gaibidVERB gabálNOUN', 'iADV díthNOUN dérnumNOUN iADP foileNOUN', ...]
vocab = ['aADP', 'aDET', 'aPRON', 'achtSCONJ', 'amalSCONJ', 'arADP', 'arPRON', ...]
vectorizer = TfidfVectorizer(analyzer='word', token_pattern=r"(?u)\b[\wáéíóúↄḟṁṅæǽ⁊ɫ֊̃]+\b", vocabulary=vocab)
vectors = vectorizer.fit_transform(documents)
print(vectors)
When I do this the matrix is empty. If I try to print([vectors])
instead, I can see the shape of the matrix, but there is no data in it.
[<42x79 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>]
Weirdly, when I remove the vocabulary=vocab
argument, I can get the tf-idf for all of the words in the documents, though, I really don't want it for all words:
vectorizer = TfidfVectorizer(analyzer='word', token_pattern=r"(?u)\b[\wáéíóúↄḟṁṅæǽ⁊ɫ֊̃]+\b")
vectors = vectorizer.fit_transform(documents)
print(vectors)
(0, 564) 0.09058331497564333
(0, 313) 0.09058331497564333
(0, 93) 0.08155482537999634
(0, 165) 0.06268804803234075
(0, 169) 0.09058331497564333
...
What is causing my matrix to be empty when I pass the vocabulary
argument? Is there something wrong with my token_pattern
?
ANSWER
Answered 2021-May-28 at 14:41The problem comes from the default parameter lowercase
which is equal to True
. So, all your text is tranformed in lowercase. If you change your vocabulary to lowercase, it will work :
vocab=[v.lower() for v in vocab]
You can also change the paramater lowercase
to False
QUESTION
jq - Parsing fields with hyphen - Invalid Numeric Literal
Asked 2020-Aug-24 at 09:24I'm trying to pull a list of product categories from an API using jq and some nested for-loops. I have to pull the category ID first, then I'm able to pull product details. Some of the category IDs have hypens and jq seems to be treating them like math instead of a string, and I've tried every manner of quoting but I'm still running into this error. In Powershell, I'm able to pull the list just fine, but I really need this to work in bash.
Here's the expected list:
aprons
backpacks
beanies
bracelet
coaster
cutting-board
dress-shirts
duffel-bags
earring
full-brim-hats
generic-dropoff
hats
etc...
And trying to recreate the same script in Bash, here's the output:
aprons
backpacks
beanies
bracelet
coaster
parse error: Invalid numeric literal at line 1, column 6
parse error: Invalid numeric literal at line 1, column 7
parse error: Invalid numeric literal at line 1, column 5
earring
parse error: Invalid numeric literal at line 2, column 0
parse error: Invalid numeric literal at line 1, column 5
parse error: Invalid numeric literal at line 1, column 8
hats
etc...
You can see that it's running into this error with all values that contain hyphens. Here's my current script:
#!/bin/bash
CATEGORIES=$(curl -s https://api.scalablepress.com/v2/categories)
IFS=$' \t\n'
for CATEGORY in $(echo $CATEGORIES | jq -rc '.[]')
do
CATEGORY_IDS=$(echo $CATEGORY | jq -rc '."categoryId"')
for CATEGORY_ID in $(echo $CATEGORY_IDS)
do
echo $CATEGORY_ID
PRODUCT_IDS=$(curl -s https://api.scalablepress.com/v2/categories/$CATEGORY_ID | jq -rc '.products[].id')
#for PRODUCT_ID in $(echo $PRODUCT_IDS)
#do
#echo $PRODUCT_ID
#done
done
done
This is a publicly available API so you should be able to copy this script and produce the same results. All of the guides I've seen have said to put double quotes around the field you're trying to parse if it contains hyphens, but I'm having no luck trying that.
ANSWER
Answered 2020-Aug-24 at 09:24You can select the key categoryId
for each object in the array by applying the selector: curl -s https://api.scalablepress.com/v2/categories | jq 'map(.categoryId)'
This will give you a JSON array with only the values you're interested in. Then you can use the antislurp filter .[]
to turn the array into individual results. jq
can then output raw strings with the -r
switch.
Combining everything, you can achieve what you're looking for with a one-liner:
curl -s https://api.scalablepress.com/v2/categories | jq -r 'map(.categoryId) | .[]'
Even better, you can antislurp first, and then select the key you're looking for: curl -s https://api.scalablepress.com/v2/categories | jq -r '.[] | .categoryId'
QUESTION
Search Form refreshes the page instead of searching for a value
Asked 2020-Jul-02 at 08:01So my code is below. Every time I try to search using the feature, it just refreshes the page. I have searched topics on here and still not been able to figure out how to stop it. I would really appreciate some help with this.
<link rel="stylesheet" href="searchstands.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<script type="text/javascript" src="searchstands.js"></script>
<script type="text/javascript">
$(document).ready(function() {
prepareSearch($('#searchBox'), {
'searchLine' : '.searchTarget div.product',
'searchSightPoint' : 'div.stand, span.apron, div.aircraft',
'fade' : true, //true or false
'contrastString' : false //true or false
});
});
</script>
<div class="row" id="standsearch">
<form class="form-search" action="#standsearch">
<div class="input-append">
<input type="text" id="searchBox" class="span2 search-query" placeholder="Search">
<button type="button" class="btnsearch">Find
</button>
</div>
</form>
</div>
<center><div class="row">
<div class="searchTarget">
<div class="product span3">
<div class="stand">
Stand 100
</div>
<span class="apron">West Apron</span>
<div class="aircraft">
B748
</div>
<div>
<img src="dhl.png" class="image">
</div>
</div>
<div class="product span3">
<div class="stand">
Stand 101
</div>
<span class="apron">West Apron</span>
<div class="aircraft">
B748
</div>
<div>
<img src="dhl.png" class="image">
</div>
</div>```
ANSWER
Answered 2020-Jul-02 at 08:01When clicking on the button, the <form>
will submit itself. You should capture and prevent that event.
Inside the $(document).ready()
function, add:
$('#standsearch').submit(function(e) {
e.preventDefault();
});
This will prevent the <form>
from ever being submitted.
QUESTION
Explode Array into Multidimensional Arrays (parent->child->sub-child)
Asked 2020-Jun-07 at 23:52I've got an array ($categories_final), looks similar to this:
Array
(
[0] => Accessories/Apron
[1] => Accessories/Banners
[2] => Accessories/Belts
[3] => Brand/Brand1
[4] => Brand/Brand2
[5] => Apparel/Men/Belts
[6] => Apparel/Men/Socks
[7] => Apparel/Women/Leggings
)
I'm trying to get it to look like this so I can add it to a database as my store's category structure:
Array
(
[Accessories] => Array
(
[0] => Apron
[1] => Banners
[2] => Belts
)
[Apparel] => Array
(
[0] => Men => Array
(
[0] => Belts
[1] => Socks
)
[1] => Women => Array
(
[0] => Leggings
)
)
...etc
Here's what I've got so far, but I am under able to figure out how to add the children under Men/ & Women/:
$categories = array();
foreach ($categories_final as $cat) {
$levels = explode('/', $cat);
if (isset($categories[$levels[0]])) {
if (!in_array($levels[1], $categories[$levels[0]])) {
$categories[$levels[0]][]= $levels[1];
}
}
else {
$categories[$levels[0]][]= $levels[1];
}
}
print_r($categories);
Again, I'm stuck on how to add the /Belts, /Socks & /Leggings under their respective parents.
Any helps is appreciated, thanks!
ANSWER
Answered 2020-Jun-07 at 22:25Since there can be an unlimited amount of branching, you should probably have a recursive solution. I tried my best and got this code:
$arr = ['Accessories/Apron', 'Accessories/Banners', 'Accessories/Belts','Brand/Brand1','Brand/Brand2',
'Apparel/Men/Belts', 'Apparel/Men/Socks', 'Apparel/Women/Leggings'];
$final = [];
foreach ($arr as $branch) {
$temp = branchRecursive($branch);
$final = array_merge_recursive($final, $temp);
}
function branchRecursive($branch) {
// explode only first
$newBranch = explode('/', $branch, 2);
// A leaf, no more branches
if(count($newBranch) != 2) {
return $newBranch[0];
}
$array [ $newBranch[0] ]= branchRecursive($newBranch[1]);
return $array;
}
it returns this:
Array
(
[Accessories] => Array
(
[0] => Apron
[1] => Banners
[2] => Belts
)
[Brand] => Array
(
[0] => Brand1
[1] => Brand2
)
[Apparel] => Array
(
[Men] => Array
(
[0] => Belts
[1] => Socks
)
[Women] => Leggings
)
)
The only thing different from your code is
[Women] => Leggings
instead of
[0] => Leggings
But I want to sleep and my head is not working, so if anyone can point out what to change, I would be thankful. I hope it will not be much of an issue:)
QUESTION
Use a specific part of code (img src) that I generated using a foreach loop in the page I open using asp-route-id and asp-page
Asked 2020-Apr-24 at 13:04This is probably really simple and I'm looking in completely the worng place when looking for answers online, so apologies for the noobyness of the question. Here goes...
I am developing a ASP.NET Core Web Application (using Razor Pages) and utilising Entity Framework Core in Visual Studio 2019. I have created a page that generates a bunch of different images and buttons in an OWL2 carousel using foreach based on my model:
<div class="owl_@bandModel.BandId owl-carousel owl-theme owl-drag">
@foreach (var jobTitleModel in bandModel.JobTitles)
{
@if (jobTitleModel.ImageType.ImageTypeOption != null)
{
switch (jobTitleModel.ImageType.ImageTypeOption)
{
case "Apron":
<div class="item">
@{int randomImg = random.Next(1, Apron);}
<img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
</div>
break;
case "Casual":
<div class="item">
@{randomImg = random.Next(1, Casual);}
<img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
</div>
break;
etc...
This is all working fine. However, when the user clicks on the button i.e.
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
I would like to be able to take the exact image that was randomly generated and use that on the page that opens.
it would look something like this:
<img src="~/content/images/map/Apron/img5.svg" type="image/svg+xml" />
So my question is, can this be done? I've explored the asp-all-route-data helper, but I can figure it out. I want it to work in the same way that the asp-route-ID helper does, but I think that this would be wrong because it will add it to the URL.
It's worth pointing out that there isn't any database association with the images, I am having to add them in randomly from the wwwroot/contents folder (using the img#) as a random number, to esure they don't look that same every time.
Thnaks in advance.
(Thanks for the explaination and the confidence boost Fei Han, sometimes it just helps having someone say that you can do something the way you thought)
EDIT TO SHOW HOW I IMPLEMENTED @FeiHan's SUGGESTION:
Fei Han suggested that I use:
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
The main point being the addition of the asp-route-ImgId="@randomImg" helper, however, this wasn't all I needed, as I needed to pass the ImageType into the img src as well. So I followed the logic and also included an asp-helper-tag for that too i.e. asp-route-ImgType="@jobTitleModel.ImageType.ImageTypeOption".
So my link structure looked like this:
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgType="@jobTitleModel.ImageType.ImageTypeOption" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
Then I moved over to the Requirements/Index Page as reference in the link and edited the Index.cshtml.cs to include:
namespace ProjectName.Pages.UIMain.Requirments
{
public class IndexModel : PageModel
{
public string RndmImgSrc { get; set; }
public async Task OnGetAsync(int? id, int? ImgId, string ImgType)
{
RndmImgSrc = string.Format("/content/images/map/{0}/img{1}.svg", ImgType, ImgId);
//If you are a proper noob like me, a little heads-up here. You need to remove the "~" symbol from the begining of the URL (~/content/) as the Routing will add the current page route and wont refer to the wwwroot.
}
}
}
Then in the Index.cshtml I added:
@page "{ImgType?}/{ImgID?}/{ID?}" //This was just to tidy up the URL
@model ProjectName.Pages.UIMain.Requirments.IndexModel
<img src="@Model.RndmImgSrc" type="image/svg+xml" width="300"/>
And hey presto!!! it worked.
ANSWER
Answered 2020-Apr-24 at 09:34I want it to work in the same way that the asp-route-ID helper does, but I think that this would be wrong because it will add it to the URL.
You are using tag to navigate to another page, passing data through URL is ok. You can pass generated Img Id randomImg
, like below.
<div class="item">
@{int randomImg = random.Next(1, Apron);}
<img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
</div>
Besides, if you don't want to pass data randomImg
as query string or route parameter in URL, you can post generated Id of img via a hidden form, like below.
switch (jobTitleModel.ImageType.ImageTypeOption)
{
case "Apron":
<div class="item">
@{int randomImg = random.Next(1, Apron);}
<img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
<form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
<input type="hidden" name="ImgId" value="@randomImg" />
<input type="submit" class="btnhidden" />
</form>
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
</div>
break;
case "Casual":
<div class="item">
@{randomImg = random.Next(1, Casual);}
<img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
<form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
<input type="hidden" name="ImgId" value="@randomImg" />
<input type="submit" class="btnhidden" />
</form>
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
</div>
break;
}
Handler method ShowImg
public IActionResult OnPostShowImg()
{
//code logic here
return Page();
}
Trigger form submission while clicking <a>
tag
function myfunc(el) {
$(el).prev().find("input[type='submit']").click();
return false;
}
QUESTION
MongoDB query on two collections to add/subtract a field in first collection with matched field from second collection
Asked 2020-Feb-20 at 06:32I've been stuck on this for a couple days and can't seem to figure it out.
Here's a couple example collections in my MongoDB database: (just an example. sorry if they're not formatted correctly)
Products :
{
"_id": {
"$oid": "5e4633eaa7095f26d44a43c3"
},
"name": "Acrylic Frame Magnetic",
"units: "50",
"fbasku": "AFM-CL-0507-FBA",
"upc": "642709233954"
},
{
"_id": {
"$oid": "5e4633eaa7095f26d44a43c4"
},
"name": "Apron Polka Dot",
"units: "488",
"fbasku": "APD-RD-03PC-FBA",
"upc": "642709233961"
},
{
"_id": {
"$oid": "5e4633eaa7095f26d44a43c5"
},
"name": "Acrylic Sign Holder - 5x7",
"units: "632",
"fbasku": "ASH-GD-0507-FBA",
"upc": "642709233978"
}
Transactions :
{
"_id": {
"$oid": "5e44e8ed8f4cd40bd09d5ce8"
},
"type": "adjust",
"fbasku": "AFM-CL-0507-FBA",
"units": {
"$numberInt": "25"
},
"comment": "example transaction"
},
{
"_id": {
"$oid": "5e4c9ab642c5a232042f4b67"
},
"type": "send",
"fbasku": "AFM-CL-0507-FBA",
"units": {
"$numberInt": "75"
},
"comment": ""
},
{
"_id": {
"$oid": "5e4c9ab642c5a232042f4b69"
},
"type": "send",
"fbasku": "AFM-CL-0507-FBA",
"units": {
"$numberInt": "5"
},
"comment": ""
}
This is for a REST api I'm trying to build, so when I send a request to get all products, I want to:
I got stuck when it came to all the async/await and Promise stuff, don't really understand it
ANSWER
Answered 2020-Feb-20 at 06:28You can try below code - it is a sample of how to do your requirement using native nodejs-mongodb driver and node.js :
const MongoClient = require('mongodb').MongoClient;
const dbConnection = async function () {
/** Connection URL */
const url = 'mongodb://localhost:27017/test'; // Check whether you're passing correct DB name & full formed connection string
let client;
try {
/** Use connect method to connect to the Server */
client = await MongoClient.connect(url);
const db = client.db(); // MongoDB would return client and you need to call DB on it.
let dbResp = await db.collection('Products').aggregate([
{
$lookup:
{
from: "Transactions",
let: { fbasku: "$fbasku" },
pipeline: [
{
$match:
{
$expr:
{ $eq: ["$fbasku", "$$fbasku"] }
}
},
{ $project: { units: 1, _id: 0 } }
],
as: "transaction_docs"
}
}, {
$project: {
_id: 0, fbasku: 1,
units: {
$add: [{ $toInt: '$units' }, {
$reduce: {
input: '$transaction_docs',
initialValue: 0,
in: { $add: ["$$value", "$$this.units"] }
}
}]
}
}
}
]).toArray();
client.close();
return dbResp;
} catch (err) {
(client) && client.close();
console.log(err);
throw err
}
};
/** In general dbConnection() has to be in one config file & it needs to be imported where ever db transactions are done like below */
dbConnection().then(res => console.log('Printing at calling ::', res)).catch(err => console.log('Err at Calling ::', err));
Note : This code has query which assumes units in products is a string, So we're converting it into int & adding that values to (sum of units of transactions => intOf(units of a products) + (sum of units of all matched transactions)
).
Test Query : MongoDB-Playground
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
HTTPS
https://github.com/hupfdule/apron.git
CLI
gh repo clone hupfdule/apron
SSH
git@github.com:hupfdule/apron.git
Share this Page
See Similar Libraries in
by hupfdule Java
by hupfdule Java
by hupfdule Java
by hupfdule Java
by hupfdule Java
See all Libraries by this author
by alibaba
by google
by rjsf-team
by nlohmann
by JamesNK
See all JSON Processing Libraries
by reinert
by qatools
by sromku
by AtomGraph
by FasterXML
See all JSON Processing Libraries
by reinert
by KyleBanks
by java-json-tools
by qatools
by sromku
See all JSON Processing Libraries
by qatools
by SmartBear
by ndimiduk
by AtomGraph
by hertzsprung
See all JSON Processing Libraries
by owlike
by mmastrac
by hupfdule
by prcaen
by FasterXML
See all JSON Processing Libraries
Save this library and start creating your kit
Open Weaver – Develop Applications Faster with Open Source