qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,307,760 | <p>I'm trying to make a button that has a linear gradient only in the text, but when I make the button it loses the backgroud, can anyone help me?</p>
<p><a href="https://codepen.io/caiohaffs/pen/wvXWBOZ" rel="nofollow noreferrer">https://codepen.io/caiohaffs/pen/wvXWBOZ</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.default {
width: 154px;
height: 72px;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 24px;
object-fit: contain;
border-style: solid;
border-width: 1px;
border-image-source: linear-gradient(65deg, #ff8d4d 0%, #6d37ff 100%);
border-image-slice: 1;
background-color: #000;
text-transform: uppercase;
color: #fff;
font-size: 16px;
line-height: 1.75;
letter-spacing: 1.28px;
font-weight: 500;
font-family: 'Roboto Condensed';
}
button.default:hover {
background: #FF8D4D;
background: linear-gradient(to right, #FF8D4D 0%, #6d37ff 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="default">Saiba Mais</button></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74307829,
"author": "Rodolfo BocaneGra",
"author_id": 7623144,
"author_profile": "https://Stackoverflow.com/users/7623144",
"pm_score": 0,
"selected": false,
"text": "console.log()"
},
{
"answer_id": 74324580,
"author": "musca999",
"author_id": 4403891,
"author_profile": "https://Stackoverflow.com/users/4403891",
"pm_score": -1,
"selected": false,
"text": "var xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function() {\n if (xhr.readyState == XMLHttpRequest.DONE) {\n console.log(xhr.responseText);\n }\n}\nxhr.open(\"GET\", \"https://<ip of host...not localhost>:2121\");\nxhr.send() \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410609/"
] |
74,307,809 | <p>I am building the site which seems fairly simple show data on page from database.</p>
<p>I want it to be as fast as possible. It already works/partially works in 3 ways:</p>
<p>#Approach 1</p>
<p>+page.server.js -> gets data from Supabase</p>
<p>+page.svelte -> gets data and creates a website</p>
<p>Advantages:</p>
<p>- works</p>
<p>- pre-fetch (hovering over links) works</p>
<p>Disadvantages:</p>
<p>- wasting a lot of time (100-600ms) waiting for document. I don't know what is the reason for waiting. Just render site (logo, menu, header etc.) and when data is retrieved show it on page. Don't make user wait with blank site for document to get downloaded. As stated in here: <a href="https://kit.svelte.dev/docs/load" rel="nofollow noreferrer">https://kit.svelte.dev/docs/load</a> "Once all load functions have returned, the page is rendered." As said, it seems to be a waste of time to wait</p>
<p>#Approach 2</p>
<p>As stated in here: <a href="https://languageimperfect.com/2021/02/17/data-fetching-in-svelte.html" rel="nofollow noreferrer">https://languageimperfect.com/2021/02/17/data-fetching-in-svelte.html</a></p>
<p>I only use +page.svelte with onMount</p>
<p>Advantages:</p>
<p>- works</p>
<p>- there is no wasted time waiting for document to retrieve data</p>
<p>Disadvantages:</p>
<p>- pre-fetch does not work</p>
<p>So in general this approach is faster for 1-st time user, however is much slower for desktop users (as there is no pre-fetch on hover)</p>
<p>#Approach 3</p>
<p>Only use +page.svelte, in <script context="module"> import data from Supabase and show it as:</p>
<pre><code>{#await getDataFromSupabase}
<p>Loading ...</p>
{:then data}
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
</code></pre>
<p>Advantages:</p>
<p>- there is no wasted time waiting for document to retrieve data</p>
<p>- pre-fetch works</p>
<p>Disadvantages:</p>
<p>- does not work with any additional parameters. For example I am not able to user page path to retrieve only selected data based on my URL</p>
<p>So those are my 3 ways already tested.</p>
<p>How to improve it?</p>
<p>My goal seems fairly simple:</p>
<p>1)Load data as soon as possible, without waiting for document (Approach #1 does not do it)</p>
<p>2)Pre-fetch should work, so if user hoover over link on desktop it should already start building webpage (Approach #2 does not do it)</p>
<p>3)I should be able to use parameters from URL (Approach #3 does not do it)</p>
<p>Any idea how to achieve it?</p>
<p>I've tried 3 methods described above. All 3 have some disadvantages.</p>
<p>I am looking for creating blazing fast webpage</p>
| [
{
"answer_id": 74318426,
"author": "Ryszard Kozłowski",
"author_id": 13058897,
"author_profile": "https://Stackoverflow.com/users/13058897",
"pm_score": 0,
"selected": false,
"text": "prerender: {\n entries: [\n '/product/1',\n '/product/2',\n '/product/3'\n ],\n},\n"
},
{
"answer_id": 74355928,
"author": "Andrew Perkins",
"author_id": 20446151,
"author_profile": "https://Stackoverflow.com/users/20446151",
"pm_score": 2,
"selected": true,
"text": " return {\n user: session.user,\n tableData\n };\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13058897/"
] |
74,307,820 | <p>I don't know why my minecraft clone destroys blocks of the ground, where I don't want. Here's my code:</p>
<pre class="lang-py prettyprint-override"><code>from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
from random import *
from perlin_noise import *
app = Ursina()
player = FirstPersonController()
Sky(color=color.azure,texture=None)
amp = 6
freq = 24
shells = []
shellWidth = 12
noise = PerlinNoise(octaves=2,seed=randrange(1, 100000000000000000000000000000000000))
for i in range(shellWidth*shellWidth):
ent = Entity(model='cube', texture='ursina-tutorials-main/assets/grass', collider='box')
shells.append(ent)
def respawn():
player.y=5
player.gravity=0
Entity1=None
def destruction(position: Vec3):
try:
collider_entity = Entity(
model="cube",
collider="box",
visible=False,
scale=Vec3(0.5, 0.5, 0.5),
position=position
)
collider_entity.intersects(ignore=[collider_entity]).entity.color=color.clear
collider_entity.intersects(ignore=[collider_entity]).entity.collider = None
return collider_entity.position
except:pass
destructionPos=None
TextureList=["ursina-tutorials-main/assets/grass","ursina-tutorials-main/assets/sandMinecraft.jfif"]
textureNumber=0
x1=0
z1=0
def input(key):
global TextureList,textureNumber
global Entity1, destructionPos, x1,z1
x1=0
z1=0
amp = 6
freq = 24
position_x = player.x
position_z = player.z
if key == "w" or key == "w hold" or key == "s" or key == "s hold" or key == "a" or key == "a hold" or key == "d" or key == "d hold":
x1 = abs(position_x - abs(player.x)) if player.x > position_x else -abs(position_x - abs(player.x))
z1 = abs(position_z - abs(player.z)) if player.z > position_z else -abs(position_x - abs(player.x))
for i in range(len(shells)):
x = shells[i].x = floor((i / shellWidth) + player.x - 0.5 * shellWidth)
z = shells[i].z = floor((i % shellWidth) + player.z - 0.5 * shellWidth)
y = shells[i].y = floor(noise([x / freq, z / freq]) * amp)
if key=="left mouse down" and shells[i].hovered and mouse.world_point:
Entity1=(round(mouse.world_point.x), ceil(mouse.world_point.y)-1, round(mouse.world_point.z))
if key=="right mouse down" and mouse.world_point:
PlacedBlock = Entity(model='cube', texture=TextureList[textureNumber%2], color=color.white, collider='box', scale=(1, 1, 1),
position=(round(mouse.world_point.x), ceil(mouse.world_point.y), round(mouse.world_point.z)),on_click=lambda:destroy(PlacedBlock))
if key=="g":
textureNumber+=1
if Entity1!=None:
if destructionPos!=None:
if distance(Entity(position=(destructionPos)),Entity(position=(Entity1)))>=1:
""
myDestructionList=[]
def update():
global Entity1,x1,z1,destructionPos
if player.y<-100:
respawn()
try:
x000,y000,z000=Entity1
myDestructionList.append(destructionPos)
if player.x != x1 or player.z != z1:
if (myDestructionList.__len__()+1)>3:
destructionPos = destruction(position=(x1,y000,z1))
destructionPos=destruction(destructionPos)
else:
""
print(destructionPos)
except:pass
app.run()
</code></pre>
<p>When I clicked on the blocks, they destroyed behind me. And when I was on the place, where the block should get destroyed, I fell down.</p>
| [
{
"answer_id": 74318426,
"author": "Ryszard Kozłowski",
"author_id": 13058897,
"author_profile": "https://Stackoverflow.com/users/13058897",
"pm_score": 0,
"selected": false,
"text": "prerender: {\n entries: [\n '/product/1',\n '/product/2',\n '/product/3'\n ],\n},\n"
},
{
"answer_id": 74355928,
"author": "Andrew Perkins",
"author_id": 20446151,
"author_profile": "https://Stackoverflow.com/users/20446151",
"pm_score": 2,
"selected": true,
"text": " return {\n user: session.user,\n tableData\n };\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410627/"
] |
74,307,822 | <p>I have a table with Contract_Id, Site_Name, and Hours columns… and now my requirement is to generate the comma seperated values by performing <strong>Group By</strong> on Contract_Id column.</p>
<pre><code>Contract_Id Site_Name Hours
1 X 20
1 Y 20
2 X 20
</code></pre>
<p>Required Output in the Below Format</p>
<pre><code>Contract_Id Site_Name Hours
1 X,Y 40
2 X 20
</code></pre>
<p>I have tried with the below XML Path by doing group by... but it didn't work!!...</p>
<pre><code>SELECT STUFF((SELECT ',' + Name,Contract_Id
FROM #Tbl_Practice
GROUP BY Name,Contract_Id
FOR XML PATH('')) ,1,1,'') AS Txt
</code></pre>
<p>Can anyone provide me the SQL solution to handle this in a dynamic way….</p>
| [
{
"answer_id": 74307880,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 1,
"selected": false,
"text": "FOR XML PATH"
},
{
"answer_id": 74309192,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (Contract_ID INT, Site_Name NVARCHAR(20), Hours INT)\nINSERT INTO @table (Contract_ID, Site_Name, Hours) VALUES \n(1, 'X',20),\n(1, 'Y',20),\n(2, 'X',20);\n\n;WITH base AS (\nSELECT Contract_ID, Site_Name, Hours, ROW_NUMBER() OVER (PARTITION BY Contract_ID ORDER BY Site_Name) AS rn\n FROM @table\n), rCTE AS (\nSELECT Contract_ID, CAST(Site_Name AS NVARCHAR(MAX)) AS Site_Name, Hours, rn\n FROM base\n WHERE rn = 1\nUNION ALL\nSELECT a.Contract_ID, a.Site_Name+','+r.Site_Name, a.Hours+r.Hours, r.rn\n FROM rCTE a\n INNER JOIN base r\n ON a.Contract_ID = r.Contract_ID\n AND a.rn + 1 = r.rn\n)\n\nSELECT r.Contract_ID, r.Site_Name, r.Hours\n FROM rCTE r\n INNER JOIN (SELECT Contract_ID, MAX(rn) AS rn FROM rCTE GROUP BY rCTE.Contract_ID) a\n ON r.Contract_ID = a.Contract_ID\n AND r.rn = a.rn\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19198516/"
] |
74,307,824 | <p>I have a datafile that looks something like this.</p>
<pre><code>id <- c(1001, 1002, 1003, 1004, 1005, 1006)
var1 <- c(1, 0, 1, 0, 1, 1)
var2 <- c(1, 1, 1, 1, 1, 0)
var3 <- c(0, 0, 1, 1, 1, 0)
file <- data.frame (id, var1, var2, var3)
file
</code></pre>
<p>We have several different variables that are all scored in the same way, in this case 0 and 1. I want to count up all the responses of 1 and percentages for each variable and export that as a dataframe.</p>
<p>Here is what I want the final product to look like</p>
<pre><code>variable response count percent
var1 1 4 66.67
var2 1 5 83.33
var3 1 3 50.00
</code></pre>
<p>I could generate table and probability tables for each individual variable and manually copy over the information by hand like this.</p>
<pre><code>table (file$var1, exclude = FALSE)
table (file$var2, exclude = FALSE)
table (file$var3, exclude = FALSE)
</code></pre>
<p>Unfortunately, I have a lot of variables that I need to count up this way so this would not work. Is there a function or a way to set up a for loop.</p>
| [
{
"answer_id": 74307855,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "table"
},
{
"answer_id": 74308114,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "colSums"
},
{
"answer_id": 74308946,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 0,
"selected": false,
"text": "tidyverse"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15488033/"
] |
74,307,839 | <p>I have this problem, I would like to convert each character to a binary number according to an if the condition or another easier way. All numbers greater than or equal to 5 must convert to 1 and numbers less than or equal to 4 convert to 0.</p>
<p>Whole code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>n = [
'0110100000', '1001011111',
'1110001010', '0111010101',
'0011100110', '1010011001',
'1101100100', '1011010100',
'1001100111', '1000011000'
] // array of binary
let bin = [] // converting to numbers
length = n.length;
for (var i = 0; i < length; i++)
bin.push(parseInt(n[i]));
var sum = 0; // sum of all binaries
for (var i = 0; i < bin.length; i++) {
sum += bin[i];
}
console.log(sum); // 7466454644
// ...
// code converting each character
// ...
// console.log(sumConverted) // 1011010100</code></pre>
</div>
</div>
</p>
<p>How do I convert each character >= 5 to 1, and the <5 to 0?</p>
<p>ex:</p>
<pre><code>7466454644
7=1, 4=0, 6=1, 6=1, 4=0, 5=1, 4=0, 6=1, 4=0, 4=0
return 1011010100
</code></pre>
| [
{
"answer_id": 74307855,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "table"
},
{
"answer_id": 74308114,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "colSums"
},
{
"answer_id": 74308946,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 0,
"selected": false,
"text": "tidyverse"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410595/"
] |
74,307,862 | <p>I have created class File:</p>
<pre><code>@dataclass
class Match:
length: int
pos_A: int
pos_B: int
f_index: int
class File:
__name = ""
__pos_in_list = 0
__statements = []
__matches = []
def __init__(self, name: str, pos: int, statements: [Statement]):
self.__name = name
self.__pos_in_list = pos
self.__statements = statements
def set_matches(self, matches: [Match]):
self.__matches.append(matches)
</code></pre>
<p>After putting 3 objects of class File, so i have a list A = [File, File, File] and calling:</p>
<pre><code>A[0].set_matches[Match(1,2,3,4)]
</code></pre>
<p>all files in list A are updated, so it looks like:</p>
<pre><code>pos_in_list: 0 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]
pos_in_list: 1 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]
pos_in_list: 2 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]
</code></pre>
<p>,but I would like to have it like:</p>
<pre><code>pos_in_list: 0 matches: [[Match(length=1, pos_A=2, pos_B=3, f_index=4)]]
pos_in_list: 1 matches: []
pos_in_list: 2 matches: []
</code></pre>
<p>List is filled like:</p>
<pre><code> files = []
for i in range(len(parsed_text)):
statements = []
for func in parsed_text[i]:
statements.extend(parse_text_into_tokens(func + ";"))
f = File(filenames[i], i, statements)
files.append(f)
</code></pre>
<p>Where is the problem?</p>
| [
{
"answer_id": 74308094,
"author": "drx",
"author_id": 20353137,
"author_profile": "https://Stackoverflow.com/users/20353137",
"pm_score": 2,
"selected": true,
"text": "__name"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14091997/"
] |
74,307,890 | <p>Hi I am trying to import python file in my robot code using library function like this.</p>
<pre><code>Library /Users/test/Desktop/bb/src/json.py
Library /Users/test/Desktop/bb/src/csv.py
</code></pre>
<p>I have another python file in same directory that is working. I imported like this.</p>
<pre><code>Library ./API.py
</code></pre>
<p>But those two files not getting imported. I am using Pycharm and mac os. I tried setting python path changing interpreter. nothing works for me.</p>
<p>Python path in pycharm</p>
<pre><code> ["/Users/test/Desktop/bb/src/"]
</code></pre>
<p>Any help will be much appreciated.</p>
| [
{
"answer_id": 74308094,
"author": "drx",
"author_id": 20353137,
"author_profile": "https://Stackoverflow.com/users/20353137",
"pm_score": 2,
"selected": true,
"text": "__name"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3354840/"
] |
74,307,903 | <p>How would I write a python code for this using split function?
Example of input file (.txt) :</p>
<pre><code>3
Day 1
Option A, 30
Option B, 60
Option C, 90
Day 2
Option A, 16
Option B, 24
Option C, 30
Day 3
Option A, 64
Option B, 49
Option C, 39
</code></pre>
<p>This should be the output:</p>
<pre><code>List A = [3] #total options available
List B = [110, 133, 159] #sums of each individual option
List C = [1, 2, 3] #number of days
Option A = 110
Option B = 133
Option C = 159
</code></pre>
<p>I tried utilising the split function but I don't get the above output</p>
<pre><code>option_num_list = []
total_list =[]
input_file = open(userfile, "r")
for next_line in input_file:
x = next_line.strip().split(",")
option_number = x[0]
option_num_list.append(option_number)
total = x[-1]
total_list.append(total)
print(sum(total_list))
</code></pre>
| [
{
"answer_id": 74308094,
"author": "drx",
"author_id": 20353137,
"author_profile": "https://Stackoverflow.com/users/20353137",
"pm_score": 2,
"selected": true,
"text": "__name"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,307,904 | <p>I have coded a function that check if brackets in a certain string are valid and returns true if it is and false if it isn't.</p>
<p>For example:</p>
<p>str1: { [ a + b ] - ] ( c - d } ] = false.</p>
<p>str2: { [ a + b ] - ( c - d ) } = true.</p>
<p>When I run the program it doesn't give any output, just a blank output.</p>
<p>What do I need to change?</p>
<pre class="lang-cs prettyprint-override"><code>public static Boolean BracketCheck(string str)
{
Stack<char> stk = new Stack<char>();
Stack<char> aid = new Stack<char>();
Stack<char> temp = new Stack<char>();
while (str != "")
{
char ch = str[0];
if(ch == '(' || ch == '{' || ch == '[' || ch == ')' || ch == '}' || ch == ']')
{
stk.Push(ch);
}
if(str.Length != 1)
str = str.Substring(1, str.Length - 1);
}
stk = Opposite(stk);
char first = stk.Pop();
char last;
while (!stk.IsEmpty() && !aid.IsEmpty())
{
while (!stk.IsEmpty())
{
aid.Push(stk.Top());
last = stk.Pop();
if (stk.IsEmpty())
if (int.Parse(first + "") + 1 != int.Parse(last + "") || int.Parse(first + "") + 2 != int.Parse(last + ""))
{
return false;
}
}
first = aid.Pop();
while (!aid.IsEmpty())
{
aid.Push(aid.Top());
last = aid.Pop();
if (aid.IsEmpty())
if (int.Parse(first + "") + 1 != int.Parse(last + "") || int.Parse(first + "") + 2 != int.Parse(last + ""))
{
return false;
}
}
first = stk.Pop();
}
return true;
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>public static Stack<char> Opposite(Stack<char> stk)
{
Stack<char> temp = new Stack<char>();
while (stk.IsEmpty())
{
temp.Push(stk.Pop());
}
return temp;
}
</code></pre>
| [
{
"answer_id": 74308049,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 0,
"selected": false,
"text": "aid"
},
{
"answer_id": 74308105,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 2,
"selected": false,
"text": "Stack"
},
{
"answer_id": 74308892,
"author": "schnitzel_prog",
"author_id": 19212648,
"author_profile": "https://Stackoverflow.com/users/19212648",
"pm_score": 1,
"selected": true,
"text": "public static Boolean BracketCheck(string str)\n {\n Stack<char> stk = new Stack<char>();\n foreach(char c in str)\n {\n if (c == '(' || c == '[' || c == '{')\n {\n stk.Push(c);\n }\n else if (c == ')' || c == ']' || c == '}')\n {\n if (stk.Top() == (int)c - 1 || stk.Top() == (int)c - 2)\n {\n stk.Pop();\n }\n }\n \n }\n return stk.IsEmpty();\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212648/"
] |
74,307,941 | <p>I am using Ag-grid library for grid view in React app. Following is my Ag-Grid component:</p>
<pre><code>const handleChanged = (gridOptions) => {
const selectedNodes = gridOptions.api.getSelectedNodes()
//TODO
}
<AgGridReact
data-testid="details-data"
columnDefs={DetailsColDef}
rowData={formatDetailsData(
data?.Response,
false
)}
rowSelection="single"
reactNext={true}
defaultColDef={defaultColDef}
onSelectionChanged={handleSelected}
suppressPaginationPanel={true}
domLayout="autoHeight"
suppressMaxRenderedRowRestriction={true}
rowBuffer={5}
suppressColumnVirtualisation={false}
debounceVerticalScrollbar={true}
alwaysShowVerticalScroll={true}
></AgGridReact>
</code></pre>
<p><strong>Current Scenario:</strong> handleChanged is getting called when we click on Grid row.<br />
<strong>Requirement:</strong> Need to call handleChanged event every time on multiple click at same time. Currently event is getting called first time only. If we click again on same row, it need's to be called.</p>
| [
{
"answer_id": 74312910,
"author": "Usama",
"author_id": 13405106,
"author_profile": "https://Stackoverflow.com/users/13405106",
"pm_score": 1,
"selected": false,
"text": "gridOptions.api.getSelectedNodes()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10473540/"
] |
74,307,950 | <p>I extended the ASP.NET CheckBoxList web control to create a Bootstrap 5 layout version.</p>
<p>The control works fine, but on postback, it loses the checked state. Also, the control's SelectedItem property is null.</p>
<p>I created the same control for the RadioButtonList and it works perfectly. Using DotPeek, I see that both of those inherit the same controls and interfaces, so I can't figure out why the custom RadioButtonList maintains state but the CheckboxList doesn't.</p>
<p>Any ideas? The internet has no useable examples to speak of.</p>
<p>C#</p>
<pre><code>public class Bootstrap5CheckBoxList : CheckBoxList {
protected override void Render(HtmlTextWriter writer) {
try {
var selected = false;
//var webControl = new WebControl(HtmlTextWriterTag.Div);
//webControl.ID = ClientID;
//webControl.RenderBeginTag(writer);
for (int index = 0; index < Items.Count; index++) {
var item = this.Items[index];
//div
writer.Indent++;
writer.WriteBeginTag($"div class='form-check {base.CssClass}'");
writer.Write('>');
writer.WriteLine();
//input
writer.Indent++;
writer.WriteBeginTag("input");
writer.WriteAttribute("id", $"{this.ID}_{index}");
writer.WriteAttribute("type", "checkbox");
writer.WriteAttribute("name", $"{this.UniqueID}_{index}");
var cssClass = "";
if (item.Attributes["class"] != null) {
cssClass = item.Attributes["class"];
}
writer.WriteAttribute("class", $"form-check-input {cssClass}");
writer.WriteAttribute("value", item.Value);
var clientID = this.ClientID;
if (item.Selected) {
if (selected) {
this.VerifyMultiSelect();
}
selected = true;
writer.WriteAttribute("checked", "checked");
}
if (item.Attributes.Count > 0) {
foreach (string key in item.Attributes.Keys) {
if (!"class".Equals(key)) {
writer.WriteAttribute(key, item.Attributes[key]);
}
}
}
if (!item.Enabled)
writer.WriteAttribute("disabled", "disabled");
if (this.Page != null) {
this.Page.ClientScript.RegisterForEventValidation(
this.UniqueID,
item.Value);
}
writer.Write('>');
writer.WriteEndTag("input");
writer.WriteLine();
//label
writer.WriteBeginTag("label");
writer.WriteAttribute("class", "form-check-label");
writer.WriteAttribute("for", $"{this.ID}_{index}");
writer.Write('>');
HttpUtility.HtmlEncode(item.Text, writer);
writer.WriteEndTag("label");
writer.Indent--;
writer.WriteLine();
//Close Div
writer.WriteEndTag("div");
writer.WriteLine();
writer.Indent--;
}
//webControl.RenderEndTag(writer);
} catch (Exception ex) {
throw new Exception(string.Format("{0}.{1}:{2} {3}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex.StackTrace));
}
}
}
</code></pre>
<p>HTML</p>
<pre><code><%@ Register TagPrefix="BSControls" Namespace="My.App.classes.custom_controls" Assembly="My.App" %>
<BSControls:Bootstrap5CheckBoxList ID="customCheckList" runat="server">
<asp:ListItem Value="1">Check 1</asp:ListItem>
<asp:ListItem Value="2">Check 2</asp:ListItem>
</BSControls:Bootstrap5CheckBoxList>
</code></pre>
| [
{
"answer_id": 74312910,
"author": "Usama",
"author_id": 13405106,
"author_profile": "https://Stackoverflow.com/users/13405106",
"pm_score": 1,
"selected": false,
"text": "gridOptions.api.getSelectedNodes()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74307950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815362/"
] |
74,308,012 | <p>I was under the impression that <a href="https://docs.python.org/3/library/typing.html" rel="nofollow noreferrer"><code>typing</code></a> module in Python is mostly for increasing code readability and for code documentation purposes.</p>
<p>After playing around with it and reading about the module, I've managed to confuse myself with it.</p>
<p>Code below works even though those two variables are not initialized (as you would normally initialize them e.g. <code>a = "test"</code>).</p>
<p>I've only put a type hint on it and everything seems ok. That is, I did not get a <code>NameError</code> as I would get if I just had <code>a</code> in my code <code>NameError: name 'a' is not defined</code></p>
<p>Is declaring variables in this manner (with type hints) an OK practice? Why does this work?</p>
<pre class="lang-py prettyprint-override"><code>from typing import Any
test_var: int
a: Any
print('hi')
</code></pre>
<p>I expected <code>test_var: int</code> to return an error saying that <code>test_var</code> is not initiated and that I would have to do something like <code>test_var: int = 0</code> (or any value at all). Does this get set to a default value because I added type hint to it?</p>
| [
{
"answer_id": 74308315,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": 1,
"selected": false,
"text": "a: int"
},
{
"answer_id": 74310375,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "NameError"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19557946/"
] |
74,308,028 | <p>Question.
Write a PL/SQL program to check whether a date falls on weekend i.e.
‘SATURDAY’ or ‘SUNDAY’.</p>
<p>I tried running the code on livesql.oracle.com</p>
<p>My Code:
<a href="https://i.stack.imgur.com/loPAX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/loPAX.png" alt="enter image description here" /></a></p>
<p>I am very new to sql and don't really know why i am getting this error.
It is saying that all variables are not bound.
Please help.</p>
<p>The output which I was expecting is:
<a href="https://i.stack.imgur.com/Bcr2B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bcr2B.png" alt="enter image description here" /></a></p>
<p>I tried changing single quotes to double but that didn't work.</p>
| [
{
"answer_id": 74308315,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": 1,
"selected": false,
"text": "a: int"
},
{
"answer_id": 74310375,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "NameError"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410463/"
] |
74,308,043 | <p>i have two tables professor and department. professor table has dept_id as foreign key and department table has prof_id as forgin key. how i have created professor table without adding dept_id column then i created department table with prof_id as foreign key. now i added data in both table(professor table do not have column dept_id). now i altered table professor and added dept_id as foreign key and now i want to add data in this column what sql query should i use?</p>
<pre><code>create table PROFESSOR( Prof_id varchar2(5) primary key check(length(Prof_id)=5),
Prof_name varchar2(40),
Email varchar2(40) check(Email like '%@%') unique,
Mobile varchar2(40) check(length(Mobile)=10) unique,
Speciality varchar2(40));
create table DEPARTMENT(Dept_id varchar2(40) primary key,
Dname varchar2(40),
Prof_id varchar2(5) check(length(Prof_id)=5) references PROFESSOR(Prof_id) on delete cascade);
insert into PROFESSOR values('prof1','prof.raj','raj@gmail.com','9992214587','blockchain');
insert into PROFESSOR values('prof2','prof.ravi','ravi@gmail.com','9292514787','database');
insert into DEPARTMENT values('11','mca','prof1');
insert into DEPARTMENT values('12','btech','prof2');
alter table PROFESSOR add Dept_id varchar2(40) references PROFESSOR(Prof_id)on delete cascade;
</code></pre>
<p>now i want to add data into column Dept_id of table professor
i tried</p>
<pre><code>update PROFESSOR set Dept_id='11' where Prof_id='prof1';
</code></pre>
<p>command but it is showing</p>
<p>ORA-02291: integrity constraint (SQL_TRUVEWTCOSJUGCBEMBVYVITBK.SYS_C00101381949) violated - parent key not found ORA-06512: at "SYS.DBMS_SQL", line 1721</p>
| [
{
"answer_id": 74308315,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": 1,
"selected": false,
"text": "a: int"
},
{
"answer_id": 74310375,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "NameError"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12775094/"
] |
74,308,055 | <p>Currently trying to build a small website using socket.io and express.
Writing in Typescript, because I like actually getting proper type errors, and transpiling the frontend code to Javascript so it actually runs in the browser.</p>
<p>Frontend code:</p>
<pre><code>import { io, Socket } from 'socket.io-client';
// plus some relative module imports; these work just fine
// and later...
const socket = io();
// even later...
socket.emit("a message", /*some message content*/);
</code></pre>
<p>This script is included in index.html with <code><script type="module" src="${the file}"></script></code>. (with the actual file, of course, not a placeholder)</p>
<p>As far as I'm aware, this should just import the module and then do things with it.</p>
<p>However, when I try to view the webpage, I get an error:</p>
<pre><code>Uncaught TypeError: Failed to resolve module specifier "socket.io-client". Relative references must start with either "/", "./", or "../".
</code></pre>
<p>Fair enough, imports work differently in the browser.</p>
<p>So I try using a bundler (webpack) to avoid anything getting imported at all, but get a different error:</p>
<pre><code>main.js:1 Uncaught TypeError: Cannot read properties of undefined (reading 'emit')
// plus a bunch of traceback)
</code></pre>
<p>(main.js is the bundled code produced by webpack)</p>
<p>How am I supposed to import socket.io-client?</p>
<p>socket.io's official docs say to put
<code><script src="/socket.io/socket.io.js"></script></code>
in the html, but that just doesn't work for me, possibly because I'm using ES6 and the example in the docs uses CommonJS and puts all the frontend code in the HTML (which I don't want to have to do).</p>
<p>When I try the method from the docs, I just don't have access to <code>io()</code>.</p>
| [
{
"answer_id": 74308315,
"author": "Devin Sag",
"author_id": 20388932,
"author_profile": "https://Stackoverflow.com/users/20388932",
"pm_score": 1,
"selected": false,
"text": "a: int"
},
{
"answer_id": 74310375,
"author": "Daniil Fajnberg",
"author_id": 19770795,
"author_profile": "https://Stackoverflow.com/users/19770795",
"pm_score": 3,
"selected": true,
"text": "NameError"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410602/"
] |
74,308,059 | <h2>Context</h2>
<p>To prevent circular imports in Python when using type-hints, one can use <a href="https://adamj.eu/tech/2021/05/13/python-type-hints-how-to-fix-circular-imports/" rel="nofollow noreferrer">the following</a> construct:</p>
<pre class="lang-py prettyprint-override"><code># controllers.py
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models import Book
class BookController:
def __init__(self, book: "Book") -> None:
self.book = book
</code></pre>
<p>Where the <code>if TYPE_CHECKING:</code> is only executed during type checking, and not during execution of the code.</p>
<h2>Issue</h2>
<p>When one applies active function argument type verification, (based on the type hints of the arguments), <code>typeguard</code> throws the error:</p>
<blockquote>
<p>NameError: name 'Supported_experiment_settings' is not defined</p>
</blockquote>
<h2>MWE I</h2>
<pre class="lang-py prettyprint-override"><code># models.py
from controllers import BookController
from typeguard import typechecked
class Book:
@typechecked
def get_controller(self, some_bookcontroller:BookController):
return some_bookcontroller
some_book=Book()
BookController("somestring")
</code></pre>
<p>And:</p>
<pre class="lang-py prettyprint-override"><code># controllers.py
from __future__ import annotations
from typing import TYPE_CHECKING
from typeguard import typechecked
#from models import Book
if TYPE_CHECKING:
from models import Book
class BookController:
@typechecked
def __init__(self, book: Book) -> None:
self.book = book
</code></pre>
<p>Note the <code>#from models import Book</code> is commented out. Now if one runs:</p>
<pre><code>python models.py
</code></pre>
<p>It throws the error:</p>
<blockquote>
<p>File "/home/name/Documents/eg/models.py", line 13, in
BookController("somestring")
...
NameError: name 'Book' is not defined. Did you mean: 'bool'?
because the typechecking for <code>def __init__(self, book: Book) -> None:</code> does not know what the class Book is.</p>
</blockquote>
<h2>MWE II</h2>
<p>Then if one disables <code>@typechecked</code> in <code>controllers.py</code> with:</p>
<pre><code># controllers.py
from __future__ import annotations
from typing import TYPE_CHECKING
from typeguard import typechecked
if TYPE_CHECKING:
from models import Book
class BookController:
#@typechecked
def __init__(self, book: Book) -> None:
self.book = book
</code></pre>
<p>it works. (But no typechecking).</p>
<h2>MWE III</h2>
<p>Then if one re-enables typechecking, <strong>and</strong> includes the import of book, (with <code>from models import Book</code>) like:</p>
<pre class="lang-py prettyprint-override"><code># controllers.py
from __future__ import annotations
from typing import TYPE_CHECKING
from typeguard import typechecked
from models import Book
if TYPE_CHECKING:
from models import Book
class BookController:
@typechecked
def __init__(self, book: Book) -> None:
self.book = book
</code></pre>
<p>It throws the circular import error:</p>
<pre><code>Traceback (most recent call last):
File "/home/name/Documents/eg/models.py", line 2, in <module>
from controllers import BookController
File "/home/name/Documents/eg/controllers.py", line 5, in <module>
from models import Book
File "/home/name/Documents/eg/models.py", line 2, in <module>
from controllers import BookController
ImportError: cannot import name 'BookController' from partially initialized module 'controllers' (most likely due to a circular import) (/home/name/Documents/eg/controllers.py)
</code></pre>
<h2>Question</h2>
<p>How can one evade this circular import whilst still allowing the <code>@typechecked</code> decorator to verify/access the <code>Book</code> import?</p>
<p>Is there an equivalent <code>TYPE_CHECKING</code> boolean for <code>typeguard</code>?</p>
| [
{
"answer_id": 74376222,
"author": "a.t.",
"author_id": 7437143,
"author_profile": "https://Stackoverflow.com/users/7437143",
"pm_score": 0,
"selected": false,
"text": "python controllers.py"
},
{
"answer_id": 74376396,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 3,
"selected": true,
"text": "from x import y"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437143/"
] |
74,308,102 | <p><strong>This was solved in my answer below</strong></p>
<p>I have a website in 2 languages.</p>
<p>German version: website/index.html<br />
English version: website/english/index.html</p>
<p>The site loads Google fonts locally. Font file location: website/assets/fonts</p>
<p>This works for the german version, but not for the English one.</p>
<p>German main CSS file: website/assets/mbr/mbr-additional.css<br />
English main CSS file: website/english/assets/mbr/mbr-additional.css</p>
<p>website/index.html loads this stylesheet:</p>
<pre><code><link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">
</code></pre>
<p>website/english/index.html also loads:</p>
<pre><code> <link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">
</code></pre>
<p>I import the font-face settings from the tangerine.css file. The fonts are located in the same folder as the tangerine.css file.</p>
<p>I import the tangerine.css file with this line:</p>
<pre><code>@import url(https://websitename/assets/fonts/tangerine.css);
</code></pre>
<p>In the tangerine.css file, I have the following code (just one example for one browser):</p>
<pre><code>@font-face {
font-family: 'Tangerine';
font-style: normal;
font-weight: 400;
src: url('../fonts/tangerine-v17-latin-regular.eot'); /* IE9 Compat Modes */
</code></pre>
<p>Whenever I try and add the same code for the tangerine.css in the English mbr-additional.css the whole website changes the font to default and ignores everything else.</p>
<p>I tried renaming the fonts files, even duplicating the whole fonts folder in the English directory, and changing the @import code but it don't work.</p>
<p>I also tried <code>url('../../fonts/tangerine-v17-latin-regular.eot');</code> for the font, so the English mbr-additional.css uses the same files as the German one.</p>
<p><strong>Edit 1</strong>: the devtools error shows a CORS error and is not allowing the fonts to load.</p>
<p>This is the htaccess file:</p>
<pre><code><IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine on
</IfModule>
# Require all granted
Satisfy Any
Order Deny,Allow
Allow from all
<FilesMatch "^\.">
# Require all denied
Order Allow,Deny
Deny from all
</FilesMatch>
</code></pre>
<p>I added the <code><FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch></code> but it still denies the request.</p>
<p><strong>Edit 2:</strong>
I added this to the htaccess:</p>
<pre><code>AddType application/vnd.ms-fontobject .eot
AddType application/x-font-opentype .otf
AddType image/svg+xml .svg
AddType application/x-font-ttf .ttf
AddType application/font-woff .woff
AddType application/font-woff2 .woff2
</code></pre>
<p><strong>Edit 3:</strong></p>
<p>mbr-additional.css:</p>
<pre><code>@import url(websitename/assets/fonts/roboto.css);
@import url(websitename/assets/fonts/roboto-condensed.css);
@import url(websitename/assets/fonts/tangerine.css);
@import url(websitename/assets/fonts/titillium.css);
body {
font-style: normal;
line-height: 1.5;
}
*and more css*
</code></pre>
<p>roboto font file (named roboto.css located in https://websitename/assets/fonts/):</p>
<pre><code>/* roboto-100 - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 100;
src: url('../fonts/roboto-v30-latin-100.eot'); /* IE9 Compat Modes */
src: local(''),
url('../fonts/roboto-v30-latin-100.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/roboto-v30-latin-100.woff2') format('woff2'), /* Super Modern Browsers */
url('../fonts/roboto-v30-latin-100.woff') format('woff'), /* Modern Browsers */
url('../fonts/roboto-v30-latin-100.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/roboto-v30-latin-100.svg#Roboto') format('svg'); /* Legacy iOS */
}
</code></pre>
<p>The index.html(main page) calls the mbr-additional.css with :
<code> <link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css"></code></p>
| [
{
"answer_id": 74376222,
"author": "a.t.",
"author_id": 7437143,
"author_profile": "https://Stackoverflow.com/users/7437143",
"pm_score": 0,
"selected": false,
"text": "python controllers.py"
},
{
"answer_id": 74376396,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 3,
"selected": true,
"text": "from x import y"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410722/"
] |
74,308,141 | <p>I have been searching and I have not seen an example like this.</p>
<p>I want to query a Model table to retrieve all Models from German manufacturers.</p>
<p>My data structure is Model Table has a Navigation Property called "Manufacturer" and an FK called "IdManufacturer"</p>
<p>A Manufacturer Has a Navigation Property called "Origin" and an FK called IdOrigin.</p>
<p>I would like to have a query that includes a where clause something like this:</p>
<pre class="lang-cs prettyprint-override"><code>(m => m.Manufacturer.Origin.Name == "German");
</code></pre>
<p>I would like this to be dynamically created at run time. Not only the lookup value might change, but the next time even the fields may change to, for example:
<code>(m.Type.Name == "SUV")</code>;</p>
<p>Finally, there will not necessarily be a UI associated with this request, it may be generated in code.</p>
<p>Please don't get too hung up on the business of it, I am hoping this made up example will be simple to understand.</p>
<p>Any suggestions on how to handle this would be greatly appreciated. Any general thoughts on performance would be created.</p>
| [
{
"answer_id": 74315237,
"author": "Svyatoslav Danyliv",
"author_id": 10646316,
"author_profile": "https://Stackoverflow.com/users/10646316",
"pm_score": 0,
"selected": false,
"text": "query = query.Where(\"Manufacturer.Origin.Name\", \"German\");\n"
},
{
"answer_id": 74315798,
"author": "Winteriscoming",
"author_id": 6405199,
"author_profile": "https://Stackoverflow.com/users/6405199",
"pm_score": 1,
"selected": false,
"text": "RouteList"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17825056/"
] |
74,308,159 | <p>How can I write a regex in a shell script that would target only the targeted substring between two given values? Give the example</p>
<pre><code>https://www.stackoverflow.com
</code></pre>
<p>How can I match only the ":" in between "https" and "//".
If possible please also explain the approach.</p>
<p>The context is that I need to prepare a file that would fetch a config from the server and append it to the .env file. The response comes as JSON</p>
<pre><code>{
"GRAPHQL_URL": "https://someurl/xyz",
"PUBLIC_TOKEN": "skml2JdJyOcrVdfEJ3Bj1bs472wY8aSyprO2DsZbHIiBRqEIPBNg9S7yXBbYkndX2Lk8UuHoZ9JPdJEWaiqlIyGdwU6O5",
"SUPER_SECRET": "MY_SUPER_SECRET"
}
</code></pre>
<p>so I need to adjust it to the <code>.env</code> syntax. What I managed to do this far is</p>
<pre><code>#!/bin/bash
CURL_RESPONSE="$(curl -s url)"
cat <<< ${CURL_RESPONSE} | jq -r '.property.source' | sed -r 's/:/=/g;s/[^a-zA-Z0-9=:_/-]//g' > .env.test
</code></pre>
<p>so basically I fetch the data, then extract the key I am after with <code>jq</code>, and then I use <code>sed</code> to first replace all ":" to "=" and after that I remove all the quotations and semicolons and white spaces that comes from JSON and leave some characters that are necessary.</p>
<p>I am almost there but the problem is that now my graphql url (and only other) would look like so</p>
<pre><code>https=//someurl/xyz
</code></pre>
<p>so I need to replace this = that is in between https and // back with the colon.</p>
<p>Thank you very much @Nic3500 for the response, not sure why but I get error saying that</p>
<pre><code>sed: 1: "s/:/=/g;s#https\(.*\)// ...": \1 not defined in the RE
</code></pre>
<p>I searched SO and it seems that it should work since the brackets are escaped and I use <code>-r</code> flag (tried <code>-E</code> but no difference) and I don't know how to apply it. To be honest I assume that the replacement block is this part</p>
<pre><code>#\1#
</code></pre>
<p>so how can I let this know to what character should it be replaced?</p>
<p>This is how I tried to use it</p>
<pre><code>#!/bin/bash
CURL_RESPONSE="$(curl -s url)"
cat <<< ${CURL_RESPONSE} | jq -r '.property.source' | sed -r 's/:/=/g;s#https\(.*\)//.*#\1#;s/[^a-zA-Z0-9=:_/-]//g' > .env.test
</code></pre>
<p>Hope with this context you would be able to help me.</p>
| [
{
"answer_id": 74315237,
"author": "Svyatoslav Danyliv",
"author_id": 10646316,
"author_profile": "https://Stackoverflow.com/users/10646316",
"pm_score": 0,
"selected": false,
"text": "query = query.Where(\"Manufacturer.Origin.Name\", \"German\");\n"
},
{
"answer_id": 74315798,
"author": "Winteriscoming",
"author_id": 6405199,
"author_profile": "https://Stackoverflow.com/users/6405199",
"pm_score": 1,
"selected": false,
"text": "RouteList"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13969419/"
] |
74,308,160 | <p>I have a couple of strings I'd like to remove unclosed brackets such as <code>(</code> or <code>[</code></p>
<pre><code>"A Pro Webcam ((Good text) [[Good Text] more texts"
"Text (Example (Good text) [Good Text] more texts"
</code></pre>
<p>I have tried using this with php with no luck</p>
<pre><code>\((?:[^)(]*(?R)?)*+\)
</code></pre>
| [
{
"answer_id": 74308441,
"author": "nice_dev",
"author_id": 4964822,
"author_profile": "https://Stackoverflow.com/users/4964822",
"pm_score": 2,
"selected": false,
"text": "("
},
{
"answer_id": 74308499,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "(?:(\\((?:[^()]++|(?1))*\\))|(\\[(?:[^][]++|(?2))*]))(*SKIP)(*F)|[][()]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309558/"
] |
74,308,161 | <p>Using q’s <code>like</code> function, how can we achieve the following match using a single regex string <code>regstr</code>?</p>
<pre><code>q) ("foo7"; "foo8"; "foo9"; "foo10"; "foo11"; "foo12"; "foo13") like regstr
>>> 0111110b
</code></pre>
<p>That is, <code>like regstr</code> matches the foo-strings which end in the numbers 8,9,10,11,12.</p>
<p>Using <code>regstr:"foo[8-12]"</code> confuses the square brackets (how does it interpret this?) since 12 is not a single digit, while <code>regstr:"foo[1[0-2]|[1-9]]"</code> returns a type error, even without the foo-string complication.</p>
| [
{
"answer_id": 74310442,
"author": "Thomas Smyth - Treliant",
"author_id": 5620913,
"author_profile": "https://Stackoverflow.com/users/5620913",
"pm_score": 2,
"selected": false,
"text": "q)str:(\"foo7\"; \"foo8\"; \"foo9\"; \"foo10\"; \"foo11\"; \"foo12\"; \"foo13\"; \"foo3x\"; \"foo123\")\nq)any str like/:(\"foo[0-9]\";\"foo[0-9][0-9]\")\n111111100b\n"
},
{
"answer_id": 74312425,
"author": "cillianreilly",
"author_id": 12838568,
"author_profile": "https://Stackoverflow.com/users/12838568",
"pm_score": 2,
"selected": false,
"text": "q)str:(\"foo7\";\"foo8\";\"foo9\";\"foo10\";\"foo11\";\"foo12\";\"foo13\")\nq)match:{x in y,/:string z[0]+til 1+neg(-/)z}\nq)match[str;\"foo\";8 12]\n0111110b\n"
},
{
"answer_id": 74315259,
"author": "Sean O'Hagan",
"author_id": 4578955,
"author_profile": "https://Stackoverflow.com/users/4578955",
"pm_score": 2,
"selected": false,
"text": "(\".\"^5$(\"foo7\";\"foo8\";\"foo9\";\"foo10\";\"foo11\";\"foo12\";\"foo13\")) like \"foo[1|8-9][.|0-2]\"\n"
},
{
"answer_id": 74320213,
"author": "SJT",
"author_id": 3540194,
"author_profile": "https://Stackoverflow.com/users/3540194",
"pm_score": 3,
"selected": true,
"text": "q)range:{x+til 1+y-x}.\nq)s:\"foo\",/:string 82,range 7 13 / include \"foo82\" in tests\nq)match:{min(x~/:;in[;string range y]')@'flip count[x]cut'z}\nq)match[\"foo\";8 12;] s\n00111110b\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13442590/"
] |
74,308,176 | <p>I have 50,000+ json objects buried in nested arrays. I want to pull them out so that they can be in single array. Also these nested arrays are quite random having no pattern.
E.g</p>
<p>[ [ [ [ [ {"a":1 } ], [ {"b":2 } ] ], [[{"c":3 }]] ] ], [{"d":4 }] ]</p>
<p>has to be converted to</p>
<p>[{"a":1},{"b":2},{"c":3},{"d":4}]</p>
<p>using Dataweave 2.0</p>
<p>Used flatten but doesn't look like its the right function.</p>
| [
{
"answer_id": 74308255,
"author": "Shoki",
"author_id": 4551844,
"author_profile": "https://Stackoverflow.com/users/4551844",
"pm_score": 4,
"selected": true,
"text": "%dw 2.0\noutput application/json\nfun flattenAllLevels(arr: Array) = do {\n arr reduce ((item, acc = []) -> \n item match {\n case x is Array -> acc ++ flattenAllLevels(x)\n else -> acc << item\n }\n )\n}\n---\nflattenAllLevels(payload)\n"
},
{
"answer_id": 74317441,
"author": "Harshank Bansal",
"author_id": 10946202,
"author_profile": "https://Stackoverflow.com/users/10946202",
"pm_score": 1,
"selected": false,
"text": "%dw 2.0\nimport some from dw::core::Arrays\noutput application/json\n\n@TailRec()\nfun flattenAllLevels(arr: Array) = do {\n var flattenedLevel1 = flatten(arr)\n ---\n if(flattenedLevel1 some ($ is Array)) flattenAllLevels(flattenedLevel1)\n else flattenedLevel1\n}\n\n// Helper function to create deeply nested array. \n// for example, calling getDeepArray(5) will create [5,[4,[3,[2,[1,[0]]]]]]\nfun getDeepArray(level) = \n 1 to level\n reduce ((item, acc=[0]) -> ( [item] << acc ))\n---\nflattenAllLevels(getDeepArray(500))\n\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410989/"
] |
74,308,206 | <p>I have an R dataframe containing pairs of SNPs (with chromosome number and base pair location in separate columns) and p-values for each pair. The data looks like this:</p>
<pre><code>chr_snp1 loc_snp1 chr_snp2 loc_snp2 pval
1 278474050 2 57386477 7.43e-08
1 275620856 2 57386662 1.08e-07
1 144075771 3 109909704 1.02e-06
1 144075771 3 111344453 2.06e-06
2 103701229 7 56369738 3.83e-08
2 102990566 7 56407691 1.07e-07
</code></pre>
<p>I want to remove redundancies in pairs. However, redundancy being defined as a similar pair that is close to another determined by the values in the <code>loc_snp1</code> and <code>loc_snp2</code> columns as well as <code>chr_snp1</code> and <code>chr_snp2</code>. The numeric limit I want to impose for values in <code>loc_snp1</code> and <code>loc_snp2</code> is 10,000,000 for pairs on the same combination of chromosomes. This data is sorted by chromosome (<code>chr_snp1</code> and <code>chr_snp2</code>), then base pair location (<code>loc_snp1</code> and <code>loc_snp2</code>), then by p-value (<code>pval</code>).</p>
<p>Basically I want the script to check if the value in <code>loc_snp1</code> is within 10,000,000 of the value in <code>loc_snp1</code> in the row above and if they both have the same value in <code>chr_snp1</code>. Then, also check if the value in <code>loc_snp2</code> is within 10,000,000 of the value in <code>loc_snp2</code> in the row above and if they both have the same value in <code>chr_snp2</code>. If all four conditions are true, only keep the row with the lowest pval and discard the other.</p>
<p>In order words, only keep the best pair and remove all the others that are close (have the same chromosome combination and within 10,000,000 base pairs of other pairs on their respective chromosomes).</p>
<p>This would result in the dataframe looking like:</p>
<pre><code>chr_snp1 loc_snp1 chr_snp2 loc_snp2 pval
1 278474050 2 57386477 7.43e-08
1 144075771 3 109909704 1.02e-06
2 103701229 7 56369738 3.83e-08
</code></pre>
<p>Of course, the script doesn't have to actually check the row above. I assume there are more elegant ways to approach the problem.</p>
| [
{
"answer_id": 74308400,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "df <- textConnection('\nchr_snp1, loc_snp1, chr_snp2, loc_snp2, pval\n1, 278474050, 2, 57386477, 7.43e-08\n1, 275620856, 2, 57386662, 1.08e-07\n1, 194406449, 2, 182907442, 2.22e-06\n1, 144075771, 3, 109909704, 1.02e-06\n1, 144075771, 3, 111344453, 1.02e-06\n2, 103701229, 7, 56369738, 1.02e-06\n2, 102990566, 7, 56407691, 1.02e-06\n') |> read.csv(header = TRUE)\n\n# filter based on first 4 criteria\nthreshold <- 1e7\nidx <- (\n ((diff(df$loc_snp1) |> abs()) <= threshold) &\n (diff(df$chr_snp1) == 0) &\n ((diff(df$loc_snp2) |> abs()) <= threshold) &\n (diff(df$chr_snp2) == 0)\n) |> which()\ndf <- df[ idx, ]\n\n# now retain only the pair with lowest p-value\ndf <- split(df, paste0(df$chr_snp1, df$chr_snp2)) |>\n lapply(function(x) {\n idx <- which.min(x$pval)\n x[ idx, ]\n }) |> \n data.table::rbindlist() |> \n as.data.frame()\n\n# now retain only the pair with lowest p-value (mirror redundancies)\ndf <- split(df, paste0(df$chr_snp2, df$chr_snp1)) |>\n lapply(function(x) {\n idx <- which.min(x$pval)\n x[ idx, ]\n }) |> \n data.table::rbindlist() |> \n as.data.frame()\n\nprint(df)\n"
},
{
"answer_id": 74308736,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": true,
"text": "library(tidyverse)\n\ndf |>\n group_by(chr_snp1, chr_snp2) |>\n mutate(grp = (abs(loc_snp1 - lag(loc_snp1, default = first(loc_snp1))) < 10e6) &\n (abs(loc_snp2 - lag(loc_snp2, default = first(loc_snp2))) < 10e6)) |>\n group_by(grp, .add=TRUE) |>\n filter(pval == min(pval)) |>\n ungroup()|>\n select(-grp)\n#> # A tibble: 3 x 5\n#> chr_snp1 loc_snp1 chr_snp2 loc_snp2 pval\n#> <dbl> <dbl> <dbl> <dbl> <dbl>\n#> 1 1 278474050 2 57386477 0.0000000743\n#> 2 1 144075771 3 109909704 0.00000102 \n#> 3 2 103701229 7 56369738 0.0000000383\n"
},
{
"answer_id": 74310501,
"author": "Melderon",
"author_id": 6836719,
"author_profile": "https://Stackoverflow.com/users/6836719",
"pm_score": 0,
"selected": false,
"text": "Cart_Inter_Pruned$skip = FALSE\ndf = NULL\nthreshold = 10e7\nfor(i in 1:nrow(Cart_Inter_Pruned)){\n if(Cart_Inter_Pruned[i,]$skip) next\n ordered_key1 = sort(array(unlist(Cart_Inter_Pruned[i,c(1,3)])))\n \n for(j in (i+1):nrow(Cart_Inter_Pruned)){\n if(Cart_Inter_Pruned[j,]$skip) next\n ordered_key2 = sort(array(unlist(Cart_Inter_Pruned[j,c(1,3)])))\n if(paste(ordered_key1,collapse=\",\") == paste(ordered_key2,collapse = \",\")){\n if_switch = ordered_key1[1] == ordered_key2[2]\n print(paste(i,j,ordered_key1))\n if(if_switch){\n if(abs(Cart_Inter_Pruned[i,2]- Cart_Inter_Pruned[j,4]) <= threshold && abs(Cart_Inter_Pruned[i,4] - Cart_Inter_Pruned[j,2]) <= threshold){\n Cart_Inter_Pruned[j,]$skip = TRUE\n Cart_Inter_Pruned[i,5] = min(as.numeric(Cart_Inter_Pruned[i,5] ,as.numeric(Cart_Inter_Pruned[j,5])))\n }\n }else{\n if(abs(Cart_Inter_Pruned[i,2]- Cart_Inter_Pruned[j,2]) <= threshold && abs(Cart_Inter_Pruned[i,4] - Cart_Inter_Pruned[j,4]) <= threshold){\n Cart_Inter_Pruned[j,]$skip = TRUE\n Cart_Inter_Pruned[i,5] = min(as.numeric(Cart_Inter_Pruned[i,5] ,as.numeric(Cart_Inter_Pruned[j,5])))\n }\n }\n }\n }\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6836719/"
] |
74,308,229 | <p>If I have an array of objects like so:</p>
<pre><code>const array = [
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26},
{name: "Bob", attributes: "lazy, small, thin", age: 32}
]
</code></pre>
<p>Is there a way to use <code>_.filter(array)</code> to create a new array with objects whereby a property contains a value.
Something like _.filter(array, attributes.contains("tall")) would return desired result of:</p>
<pre><code>[
{name: "Jim", attributes: "strong, handsome, tall", age: 28},
{name: "Alice", attributes: "blonde, thin, tall", age: 26}
]
</code></pre>
| [
{
"answer_id": 74308302,
"author": "Ax0n",
"author_id": 13078911,
"author_profile": "https://Stackoverflow.com/users/13078911",
"pm_score": 1,
"selected": true,
"text": "array.filter(el => el.attributes.includes('tall'))\n"
},
{
"answer_id": 74308316,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": false,
"text": "filter"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18472704/"
] |
74,308,261 | <p>I have a table like below,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>Sample1</td>
</tr>
<tr>
<td>A</td>
<td>Sample2</td>
</tr>
<tr>
<td>A</td>
<td>Sample3</td>
</tr>
<tr>
<td>B</td>
<td>Sample3</td>
</tr>
<tr>
<td>B</td>
<td>Sample1</td>
</tr>
<tr>
<td>C</td>
<td>Sample2</td>
</tr>
<tr>
<td>C</td>
<td>Sample3</td>
</tr>
<tr>
<td>D</td>
<td>Sample1</td>
</tr>
</tbody>
</table>
</div>
<p>If I group the table by Name to get the count,</p>
<pre><code>Select Name, Count(*) as count from table group by Name;
</code></pre>
<p>I will get the following result,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>count</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>3</td>
</tr>
<tr>
<td>B</td>
<td>2</td>
</tr>
<tr>
<td>C</td>
<td>2</td>
</tr>
<tr>
<td>D</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I need to get the number of repetitions of each count. Means desired outcome below,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>count</th>
<th>numberOfTimes</th>
</tr>
</thead>
<tbody>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74308302,
"author": "Ax0n",
"author_id": 13078911,
"author_profile": "https://Stackoverflow.com/users/13078911",
"pm_score": 1,
"selected": true,
"text": "array.filter(el => el.attributes.includes('tall'))\n"
},
{
"answer_id": 74308316,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": false,
"text": "filter"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3675978/"
] |
74,308,267 | <p>Given I have the following function:</p>
<pre><code>add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))
</code></pre>
<p>This function is supposed to convert values <strong>('GOOG', 130.00)</strong> into a dictionary in the format <strong>'GOOG':130.00</strong>. On top, it is meant to append the already existing dictionaries with values that are not already included.</p>
<p>Upon trying the code I stumble upon the issue that I cannot transform the list into a dictionary:</p>
<pre><code>def add_to_list(x,y):
output=list(y)
dict.output
return output
add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))
</code></pre>
| [
{
"answer_id": 74308537,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 0,
"selected": false,
"text": "def add_to_list(x,y):\n d={y[0]:y[1]}\n return d\nadd_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))\n{'GOOG': 130.0}\n"
},
{
"answer_id": 74308626,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "def add_to_list(x, y):\n assert isinstance(x, dict)\n assert isinstance(y, tuple)\n k, v = y\n x.setdefault(k, []).append(v)\n return x\nprint(add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00)))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18072226/"
] |
74,308,279 | <p>Some background: I am creating a POS system and have a MySQL Database. The design of my database is one table "tblProducts" is keeping track of product UPC, description, price, etc. The other table "tblStock" is keeping track of quantity, min and max. There is a FK connecting UPC's between tblStock and tblProducts. When I scan a product into my program, it adds the UPC to tblStock.</p>
<p>Problem: I need to SELECT from my database all products that are:</p>
<ol>
<li>"Quantity" < "Max"</li>
<li>"Ordered_Flag" = 0</li>
</ol>
<p>I have this working, however the tricky part I need help with is that if 1) is true, I need all products that have the exact same description to also show, even if those products are not below the Max value and if those UPC's are not even in tblStock</p>
<p>The reason for needing products with the same description is my workaround to suppliers having different codes for the same product</p>
<p>Let me know if you need a better explanation... I had a hard time trying to put this in words</p>
<p>Here is what I have so far</p>
<pre><code>SELECT p.id, p.upc, p.description, p.purchasePrice, p.salePrice, p.supplier, p.supplierSku, p.moveCode,
s.quantity, s.min, s.max, s.orderedFlag
FROM tblProducts p
INNER JOIN tblStock s ON p.upc = s.upc
WHERE s.orderedFlag = 0 AND s.quantity < s.max
ORDER BY p.description, p.purchasePrice;
</code></pre>
<p>DBFIDDLE: <a href="https://www.db-fiddle.com/f/ctM5CK5myvor7PhFYPqEDq/6" rel="nofollow noreferrer">https://www.db-fiddle.com/f/ctM5CK5myvor7PhFYPqEDq/6</a></p>
<p>When I run my query below, it excludes ID 5 because it is not in the tblStock</p>
| [
{
"answer_id": 74308537,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 0,
"selected": false,
"text": "def add_to_list(x,y):\n d={y[0]:y[1]}\n return d\nadd_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))\n{'GOOG': 130.0}\n"
},
{
"answer_id": 74308626,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "def add_to_list(x, y):\n assert isinstance(x, dict)\n assert isinstance(y, tuple)\n k, v = y\n x.setdefault(k, []).append(v)\n return x\nprint(add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00)))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19659745/"
] |
74,308,283 | <p>I have two tables: TableA and TableB.</p>
<p>Table A :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Id</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>0021</td>
<td>Cell 2</td>
</tr>
<tr>
<td>0033</td>
<td>Cell 4</td>
</tr>
<tr>
<td>0021</td>
<td>Cell 1</td>
</tr>
<tr>
<td>0036</td>
<td>Cell 6</td>
</tr>
</tbody>
</table>
</div>
<p>Table B</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>0021</td>
<td>Cell 8</td>
</tr>
<tr>
<td>0033</td>
<td>Unknown</td>
</tr>
</tbody>
</table>
</div>
<p>I want to update the Value of ID in Table A based on the results of Table B :
If TableB.Value like '%Cell%', Update the first record with ID (0021 in the exemple) of Table A</p>
<p>After searching, I have written this (But it does not take the condition correctly, and update all rows with the ID found) :</p>
<pre><code>UPDATE TableA
SET TableA.Value = (SELECT TableB.Value
FROM TableB
Where Value like '%Cell%'
AND TableA.ID = TableB.ID) ;
</code></pre>
| [
{
"answer_id": 74308537,
"author": "Talha Tayyab",
"author_id": 13086128,
"author_profile": "https://Stackoverflow.com/users/13086128",
"pm_score": 0,
"selected": false,
"text": "def add_to_list(x,y):\n d={y[0]:y[1]}\n return d\nadd_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00))\n{'GOOG': 130.0}\n"
},
{
"answer_id": 74308626,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 3,
"selected": true,
"text": "def add_to_list(x, y):\n assert isinstance(x, dict)\n assert isinstance(y, tuple)\n k, v = y\n x.setdefault(k, []).append(v)\n return x\nprint(add_to_list({ 'GOOG': [100.21] }, ('GOOG', 130.00)))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19830366/"
] |
74,308,301 | <p>Im trying to write a function complex_decode( string str) in c sharp that takes a non-simple repeated encoded string, and returns the original un-encoded string.
for example, "t11h12e14" would return "ttttttttttthhhhhhhhhhhheeeeeeeeeeeeee". I have been successful in decoding strings where the length is less than 10, but unable to work with length for than 10. I am not allowed to use regex, libraries or loops. Only recursions.
This is my code for simple decode which decodes when length less than 10.</p>
<pre><code>public string decode(string str)
{
if (str.Length < 1)
return "";
if(str.Length==2)
return repeat_char(str[0], char_to_int(str[1]));
else
return repeat_char(str[0], char_to_int(str[1]))+decode(str.Substring(2));
}
</code></pre>
<pre><code>public int char_to_int(char c)
{
return (int)(c-48);
}
</code></pre>
<pre><code> public string repeat_char(char c, int n)
{
if (n < 1)
return "";
if (n == 1)
return ""+c;
else
return c + repeat_char(c, n - 1);
}
</code></pre>
<p>This works as intended, for example input "a5" returns "aaaaa", "t1h1e1" returns "the"</p>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 74309195,
"author": "cemahseri",
"author_id": 10189024,
"author_profile": "https://Stackoverflow.com/users/10189024",
"pm_score": 0,
"selected": false,
"text": "public static string Decode(string input)\n{\n // If the string is empty or has only 1 character, return the string itself to not proceed.\n if (input.Length <= 1)\n {\n return input;\n }\n \n // Convert string into character list.\n var characters = new List<char>();\n characters.AddRange(input);\n \n var firstDigitIndex = characters.FindIndex(c => char.IsDigit(c)); // Get first digit\n var nextLetterIndex = characters.FindIndex(firstDigitIndex, c => char.IsLetter(c)); // Get the next letter after that digit\n if (nextLetterIndex == -1)\n {\n // This has only one reason. Let's say you are in the last recursion and you have c2\n // There is no letter after the digit, so the index will -1, which means \"not found\"\n // So, it will raise an exception, since we try to use the -1 in slicing part\n // Instead, if it's not found, we set the next letter index to length of the string\n // With doing that, you either get repeatCount correctly (since remaining part is only digits)\n // or you will get empty string in the next recursion, which will stop the recursion.\n nextLetterIndex = input.Length;\n }\n \n // Let's say first digit's index is 1 and the next letter's index is 2\n // str[2..3] will start to slice the string from index 2 and will stop in index 3\n // So, it will basically return us the repeat count.\n var repeatCount = int.Parse(input[firstDigitIndex..nextLetterIndex]);\n \n // string(character, repeatCount) constructor will repeat the \"character\" you passed to it for \"repeatCount\" times\n return new string(input[0], repeatCount) + Decode(input[nextLetterIndex..]);\n}\n"
},
{
"answer_id": 74309268,
"author": "Bruno Canettieri",
"author_id": 5170189,
"author_profile": "https://Stackoverflow.com/users/5170189",
"pm_score": 0,
"selected": false,
"text": "public static string repeat_char(char c, int resultLength)\n{\n if(resultLength < 1) throw new ArgumentOutOfRangeException(\"resultLength\"); \n if(resultLength == 1) return c.ToString();\n return c + repeat_char(c, resultLength - 1);\n}\n"
},
{
"answer_id": 74309723,
"author": "JuanR",
"author_id": 4190402,
"author_profile": "https://Stackoverflow.com/users/4190402",
"pm_score": 1,
"selected": false,
"text": "StringBuilder"
},
{
"answer_id": 74310443,
"author": "Flydog57",
"author_id": 4739488,
"author_profile": "https://Stackoverflow.com/users/4739488",
"pm_score": 0,
"selected": false,
"text": "State"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16279466/"
] |
74,308,334 | <p>I have read several times before that the length of the data type in C depends on the architecture on the PC.</p>
<p>But recently I have read documentation of a compiler and this documentation specifies the data types that you can access and the length of this data type.</p>
<p>So my question is, the data type length depends on the compiler your using, the architecture of the computer or both?</p>
| [
{
"answer_id": 74308423,
"author": "Jeremy Friesner",
"author_id": 131930,
"author_profile": "https://Stackoverflow.com/users/131930",
"pm_score": 2,
"selected": false,
"text": "sizeof(int)==2"
},
{
"answer_id": 74308456,
"author": "Eric Postpischil",
"author_id": 298225,
"author_profile": "https://Stackoverflow.com/users/298225",
"pm_score": 3,
"selected": false,
"text": "char"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384406/"
] |
74,308,368 | <p>Lately I have been trying to make my own operating system. To do this I need to learn assembly. It's going well, but I have stumbled upon a problem: what registers can I use for function arguments? And is it a good practice?</p>
| [
{
"answer_id": 74309197,
"author": "Sep Roland",
"author_id": 3144770,
"author_profile": "https://Stackoverflow.com/users/3144770",
"pm_score": 3,
"selected": true,
"text": "bx Handle\ncx Count\nds:dx Far pointer\nes:bx Far pointer\n...\n"
},
{
"answer_id": 74309434,
"author": "Brendan",
"author_id": 559737,
"author_profile": "https://Stackoverflow.com/users/559737",
"pm_score": 1,
"selected": false,
"text": "; Routine to juggle the wobbly things\n;\n;Input\n; ax First thing\n; bx Second thing\n;\n;Output\n; cx First result\n; dx Second result\n;\n;Trashed\n; ax, bx, bp\n\njuggleTheWobblies:\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16835604/"
] |
74,308,369 | <p>Consider the following (nonsensical, but working) plot:</p>
<pre><code>ggplot(mtcars,
aes(x = as.factor(cyl), y = hp)) +
geom_boxplot() +
facet_wrap( ~ am) +
geom_text(label = "test")
</code></pre>
<p><a href="https://i.stack.imgur.com/gY3rl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gY3rl.png" alt="Nonsensical graph" /></a></p>
<p>I'd like to pass the value of <code>am</code> within each facet to the <code>label</code> argument of <code>geom_text</code>. So all the labels within the left facet would read "0", all the labels within the right facet would read "1".</p>
<p>How could I achieve this? Simply passing <code>am</code> doesn't work, and neither does <code>.$am</code>.</p>
| [
{
"answer_id": 74308414,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 1,
"selected": false,
"text": "mapping"
},
{
"answer_id": 74308422,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 0,
"selected": false,
"text": "library(ggplot2)\nggplot(mtcars, aes(x = as.factor(cyl), y = hp)) + \n geom_boxplot() + \n facet_wrap( ~ am) +\n geom_text(label = mtcars$am) \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239765/"
] |
74,308,370 | <p>There you go. When I try to retrieve when loading the page, all the tables of users who liked the posts, that I make the comparisons, that I change the state, it is the states of all the posts that change, without difference. If only one post is liked by the user, all posts are marked as liked. And if I post a new post, all the others are marked as unliked. If I like it, all the others mark liked. I searched, searched, searched, I don't know how to do it.</p>
<pre class="lang-js prettyprint-override"><code> const [liked, setLiked] = useState(false)
let newArray = []
useEffect(() => {
if (!isDataLoading) {
for (let arrayOfLikes of dataResultPosts) {
newArray.push(arrayOfLikes.usersLiked)
}
for (let element of newArray) {
let userId = element.find((id) => id === dataResult.infos._id)
if (userId) {
setLiked(true)
console.log('yes')
} else if (!userId) {
setLiked(false)
console.log('no')
}
}
}
}, [])
</code></pre>
<pre><code>function DisplayPosts(props, index) {
return (
<div className="allPostsAndModals" key={Date.now}>
<div className="blockAuthor">
<div className="divAuthor">
<div className="pictureUserPost">
<img
id={props.id}
src=""
className="imageUser"
></img>
</div>
<div className="nameAuthor">
{props.firstname} {props.lastname}
</div>
<div className="divIconOptions">
<div className="blockIconOptions">
<p className="iconOption">
<FontAwesomeIcon
icon={faEllipsis}
fontSize="36px"
/>
</p>
</div>
</div>
</div>
</div>
<div className="blockContentPost">
<div className="paragraphContentPost">
{props.postContent} {props.id}
</div>
{liked ? <p>Liked ! </p> : <p>Not liked</p>}
</div>
<div className="separator"></div>
<div className="blockImagePost">
<img
className="imagePost"
src={props.imageUrlPostPicture || ' '}
alt="photo profil utilisateur"
></img>
</div>
<div className="separator"></div>
<div className="ContenairOptions">
<div className="iconLikeOn">
<button
id={props.id}
className="buttonLike"
onClick={likeSystem}
>
<FontAwesomeIcon id={props.id} icon={farThumbsUp} />
</button>
</div>
<div>{props.id}</div>
<input
className="inputLike"
defaultValue={props.likes + likeUser}
></input>
</div>
</div>
)
}
const postsDisplay = dataResultPosts.map((post) => (
<DisplayPosts
firstname={post.firstname}
lastname={post.lastname}
postContent={post.postContent}
imageUrlPostPicture={post.imageUrlPostPicture}
likes={post.likes}
key={post._id}
id={post._id}
></DisplayPosts>
))
</code></pre>
<pre><code> const likeSystem = async (e) => {
console.log(e.target.id)
// let inputLike = document.querySelector('#likeInput')
// inputLike.value = parseInt(inputLike.value) + 1
// let iconLikeOn = document.querySelector('#iconLikeOn')
// iconLikeOn.classList.add('iconLikeOn')
// if (likeUser === 0) {
// setLikeUser(1)
// }
// // if (likeUser === 1) {
// // setLikeUser(0)
// // }
let idUrl = e.target.id
if (likeUser === 0) {
try {
const response = await fetch(
'http://localhost:4200/api/ficheUser/post/like/' + idUrl,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authContext.token}`,
},
body: JSON.stringify({
userId: authContext.userId,
likes: 1,
}),
}
)
const dataResponse = await response.json()
if (response.ok) {
setLikeUser(1)
}
} catch (err) {
console.log(err)
}
}
if (likeUser === 1) {
try {
const response = await fetch(
'http://localhost:4200/api/ficheUser/post/like/' + idUrl,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authContext.token}`,
},
body: JSON.stringify({
userId: authContext.userId,
likes: 0,
}),
}
)
const dataResponse = await response.json()
if (response.ok) {
setLikeUser(0)
}
} catch (err) {
console.log(err)
}
}
}
</code></pre>
| [
{
"answer_id": 74308414,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 1,
"selected": false,
"text": "mapping"
},
{
"answer_id": 74308422,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 0,
"selected": false,
"text": "library(ggplot2)\nggplot(mtcars, aes(x = as.factor(cyl), y = hp)) + \n geom_boxplot() + \n facet_wrap( ~ am) +\n geom_text(label = mtcars$am) \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20390168/"
] |
74,308,390 | <p>I am trying to clean up my code a lot. I have a form that I realise I use multiple times in my app. So I wanted to turn the form into its own stateful widget so I could easily re-use it. Unfortunately this is proving more difficult than I thought.</p>
<p>The form is first used in the app to add items. I then want to re-use that same form to edit items and change values in those text fields.</p>
<p>I call the new widget that I created:</p>
<pre><code> body: const GearForm(
onSaveFunctionType: 'add',
itemID: 'none',
itemManufacturer: 'hi',
itemName: '',
itemType: 'test',
itemVolume: '',
itemWeight: '',
packCategory: '',
tempRating: '',
),
</code></pre>
<p>If I am passing arguments into the widget though they do not show up in the form when I am testing:</p>
<pre><code>class GearForm extends StatefulWidget {
const GearForm(
{Key? key,
required this.onSaveFunctionType,
required this.itemID,
required this.itemName,
required this.itemManufacturer,
required this.itemType,
required this.packCategory,
required this.itemWeight,
required this.tempRating,
required this.itemVolume})
: super(key: key);
final String onSaveFunctionType;
final String itemID;
final String itemName;
final String itemManufacturer;
final String itemType;
final String packCategory;
final String itemWeight;
final String tempRating;
final String itemVolume;
@override
State<GearForm> createState() => _GearFormState();
}
//define category stream stream
Stream<DocumentSnapshot<Map<String, dynamic>>> streamUserCategories() {
FirebaseFirestore db = FirebaseFirestore.instance;
String userID = FirebaseAuth.instance.currentUser!.uid;
return db.collection('UserPackCategoryList').doc(userID).snapshots();
}
class _GearFormState extends State<GearForm> {
FirebaseAnalytics analytics = FirebaseAnalytics.instance;
FirebaseFirestore db = FirebaseFirestore.instance;
String userID = FirebaseAuth.instance.currentUser!.uid;
//text editing controllers
TextEditingController itemNameController = TextEditingController();
TextEditingController manufacturerController = TextEditingController();
TextEditingController itemTypeController = TextEditingController();
TextEditingController packCategoryController = TextEditingController();
TextEditingController itemWeightController = TextEditingController();
TextEditingController temperatureRatingController = TextEditingController();
TextEditingController volumeController = TextEditingController();
@override
Widget build(BuildContext context) {
//get entitlements from revenue cat
final Entitlement entitlement =
Provider.of<RevenueCatProvider>(context).entitlement;
print(widget.itemManufacturer);
//set initial controller values
itemNameController.text = widget.itemName;
manufacturerController.text = widget.itemManufacturer;
itemTypeController.text = widget.itemType;
packCategoryController.text = widget.packCategory;
itemWeightController.text = widget.itemWeight;
temperatureRatingController.text = widget.tempRating;
volumeController.text = widget.itemVolume;
</code></pre>
<p>The odd part is if I did a cmd+s in visual studio code then all the value would magically appear. Since the Cmd+s worked I thought it was showing the values on rebuild so I tried wrappign everythign in setState:</p>
<pre><code> @override
Widget build(BuildContext context) {
//get entitlements from revenue cat
final Entitlement entitlement =
Provider.of<RevenueCatProvider>(context).entitlement;
print(widget.itemManufacturer);
setState(() {
//set initial controller values
itemNameController.text = widget.itemName;
manufacturerController.text = widget.itemManufacturer;
itemTypeController.text = widget.itemType;
packCategoryController.text = widget.packCategory;
itemWeightController.text = widget.itemWeight;
temperatureRatingController.text = widget.tempRating;
volumeController.text = widget.itemVolume;
});
</code></pre>
<p>but that didnt fix the issue either...</p>
<p><strong>Update:</strong></p>
<p>I did soem further troubleshooting and tried initState:</p>
<pre><code> @override
void initState() {
super.initState();
print(widget.itemManufacturer);
itemNameController.text = widget.itemName;
manufacturerController.text = widget.itemManufacturer;
itemTypeController.text = widget.itemType;
packCategoryController.text = widget.packCategory;
itemWeightController.text = widget.itemWeight;
temperatureRatingController.text = widget.tempRating;
volumeController.text = widget.itemVolume;
//set initial controller values
}
</code></pre>
<p>What is super odd here is that my <code>print(widget.itemManufacturer);</code> works fine and I see the correct value. But it is not being assigned to the <code>manufacturerController.text = widget.itemManufacturer;</code> a few lines down.</p>
| [
{
"answer_id": 74308414,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 1,
"selected": false,
"text": "mapping"
},
{
"answer_id": 74308422,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 0,
"selected": false,
"text": "library(ggplot2)\nggplot(mtcars, aes(x = as.factor(cyl), y = hp)) + \n geom_boxplot() + \n facet_wrap( ~ am) +\n geom_text(label = mtcars$am) \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522607/"
] |
74,308,397 | <p>I am making a website for a school project, and in it, there is a login page. Right now, there is only 1 login username and password. How can I have TWO username and TWO passwords? I have tried the else if, but it didn't work. Any ideas? The code for the login is below.
Thanks</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function check(form) {
if (form.userid.value == "admin" && form.pwd.value == "noahgrocery") {
return true;
} else {
alert("Incorrect Password or Username")
return false;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Login to Noah Grocery</title>
</head>
<body>
<a href="index.html" class="a">Home</a>
<a href="contactus.html" class="a">Contact Us!</a>
<a href="products.html" class="a">Products</a>
<a href="cart.html">
<img src="https://codehs.com/uploads/d1091610e3a63fb99a6d5608b94a0fa8" width="50px" height="50px" style="float:right; margin-right: 15px">
</a>
<a href="userlogin.html">
<img src="https://codehs.com/uploads/a4a800a1e73c30e0f37382731c3b1234" width="50px" height="50px" style="float:right; margin-right: 15px; background-color: white;">
</a>
<center><img src="https://drive.google.com/uc?export=view&id=1NKWr5CjLNa7tYtO8a49xQ_mcWzMoWGg_" style="width:300px;height:300px;"></center>
<form name="loginForm" method="post" action="admin.html">
<table width="20%" align="center">
<tr>
<td colspan=2>
<center>
<font size=4><b>Login to Noah Grocery</b></font>
</center>
</td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" size=25 name="userid"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="Password" size=25 name="pwd"></td>
</tr>
<tr>
<td><input type="Reset"></td>
<td><input type="submit" onclick="return check(this.form)" value="Login"></td>
</tr>
</table>
</form>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74308414,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 1,
"selected": false,
"text": "mapping"
},
{
"answer_id": 74308422,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 0,
"selected": false,
"text": "library(ggplot2)\nggplot(mtcars, aes(x = as.factor(cyl), y = hp)) + \n geom_boxplot() + \n facet_wrap( ~ am) +\n geom_text(label = mtcars$am) \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20267650/"
] |
74,308,420 | <p>I am trying to navigate from welcomepage to screen tab but unable to do so because of the above error.</p>
<p><strong>Part of welcome screen.dart</strong></p>
<pre><code>class WelcomePage extends StatelessWidget {
static const routeName = '/welcome-screen';
const WelcomePage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.black,
child: Stack(
children: [
Positioned.fill(
child: Opacity(
opacity: 0.3,
child: Image.asset('assets/images/of_main_bg.png', fit: BoxFit.cover),
),
),
ThemeButton(
label: "Get Started!",
labelColor: AppColors.MAIN_COLOR,
color: Colors.transparent,
highlight: AppColors.MAIN_COLOR.withOpacity(0.5),
borderColor: AppColors.MAIN_COLOR,
borderWidth: 4,
onPressed: () {Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return TabsScreen(**ERROR**#What should I write here);
},
),
</code></pre>
<p><strong>Routes in main.dart</strong></p>
<pre><code>initialRoute: '/', // default is '/'
routes: {
'/': (ctx) => WelcomePage(),
CategoryMealsScreen.routeName: (ctx) => CategoryMealsScreen(_availableMeals),
MealDetailScreen.routeName: (ctx) => MealDetailScreen(_toggleFavorite, _isMealFavorite),
FiltersScreen.routeName: (ctx) => FiltersScreen(_filters, _setFilters),
TabsScreen.routeName: (ctx) => TabsScreen(_favoriteMeals),
WelcomePage.routeName: (ctx) => WelcomePage(),
},
</code></pre>
<p><strong>class code in tabscreen.dart</strong></p>
<pre><code> class TabsScreen extends StatefulWidget {
static const routeName = '/tabs-screen';
final List<Meal> favoriteMeals;
TabsScreen(this.favoriteMeals);
</code></pre>
<p>How should i navigate from welcomepage to tabs_screen page?In order to navigate for the same what should I write in that <strong>ERROR</strong> place in welcome_screen.dart.
If there's another method for navigation please do tell.</p>
| [
{
"answer_id": 74308414,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 1,
"selected": false,
"text": "mapping"
},
{
"answer_id": 74308422,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 0,
"selected": false,
"text": "library(ggplot2)\nggplot(mtcars, aes(x = as.factor(cyl), y = hp)) + \n geom_boxplot() + \n facet_wrap( ~ am) +\n geom_text(label = mtcars$am) \n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19017043/"
] |
74,308,449 | <p>Here is a sample dataset:</p>
<pre><code>
data <- data.frame(x=c(4,3,4,4,99),
y=c(4,NA,3,2,4),
z = c(88,NA,4,4,5),
w = c(4,5,2,3,4))
</code></pre>
<p>I would like to create a new column for means using rowMeans. I would like to keep na.rm=F because if its truly NA I do not want to include that into my means calculation.
But if its either 88/99 I would like R to ignore it while calculating the mean and still use the remaining valid values. So far I have the below.</p>
<pre><code>data$mean <- rowMeans(subset(data, select = c(`x`,`y`,`z`,`w`)), na.rm = T)
</code></pre>
<p>But I am not sure how to add in a function where it would just ignore the 88 and 99 from calculations.</p>
<p>This is what I am hoping to get</p>
<pre><code>data <- data.frame(x=c(4,3,4,4,99),
y=c(4,NA,3,2,4),
z = c(88,NA,4,4,5),
w = c(4,5,2,3,4),
mean=c(4,NA,3.25,3.25,4.3))
</code></pre>
<p>Any help is appreciated - thank you!</p>
| [
{
"answer_id": 74308578,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "data <- data.frame(x=c(4,3,4,4,99),\n y=c(4,NA,3,2,4),\n z = c(88,NA,4,4,5),\n w = c(4,5,2,3,4))\n\ndf$mean <- apply(data, 1, function(x) {\n idx <- which((x %in% c(88, 89)) == FALSE)\n mean(x[ idx ], na.rm = TRUE)\n})\n\n"
},
{
"answer_id": 74308580,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 3,
"selected": true,
"text": "rowMeans"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17491547/"
] |
74,308,457 | <p>I am trying to show the list of food types whereas I need to display the first 5 values in the html. While using slice I am getting this error Property 'slice' does not exist on type '{ categories: Category[]; }</p>
<pre><code> loadcategoriesfood(): Observable<{ categories: Category[] }> {
return this.http.get<{ categories: Category[] }>(
this.recipies.listofcategories + 'categories.php',
{}
).pipe(map((food) => food.slice(0, 5)));
}
</code></pre>
| [
{
"answer_id": 74308578,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "data <- data.frame(x=c(4,3,4,4,99),\n y=c(4,NA,3,2,4),\n z = c(88,NA,4,4,5),\n w = c(4,5,2,3,4))\n\ndf$mean <- apply(data, 1, function(x) {\n idx <- which((x %in% c(88, 89)) == FALSE)\n mean(x[ idx ], na.rm = TRUE)\n})\n\n"
},
{
"answer_id": 74308580,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 3,
"selected": true,
"text": "rowMeans"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20328106/"
] |
74,308,483 | <p>I have a table ANC_PER_ABS_ENTRIES that has the following detail -</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>PER_AB_ENTRY_ID</th>
<th>person_number</th>
<th>action_type</th>
<th>duration</th>
<th>START_dATE</th>
<th>END_DATE</th>
<th>LAST_UPD_DT</th>
</tr>
</thead>
<tbody>
<tr>
<td>15</td>
<td>101</td>
<td>INSERT</td>
<td>3</td>
<td>01/10/2022</td>
<td>03/10/2022</td>
<td>2022-11-01T04:59:43</td>
</tr>
<tr>
<td>15</td>
<td>101</td>
<td>UPDATE</td>
<td>1</td>
<td>01/10/2022</td>
<td>01/10/2022</td>
<td>2022-11-02T10:59:43</td>
</tr>
</tbody>
</table>
</div>
<p>This table is a history table and the action like - insert update and delete are tracked in this table.</p>
<ol>
<li>Insert means when the entry in the table was added</li>
<li>Update means some sort of changes were made in the table</li>
<li>Delete means the record was deleted.</li>
</ol>
<p>I want to create a query that picks up the changes in this table by comparing the <code>last_update_date</code> and the run_date (parameter)</p>
<p>Eg- for <code>person_number</code> 101 with <code>per_ab_entry_id</code> -- > 15 , the <code>action_type</code> is insert first that means the record was created on first, then it is updated and the <code>end_date</code> , duration is changed.</p>
<p>so if i run the below query on the 1st after 4:59, then the 1st row will be picked.
When I run it on 2nd , only the 2nd row is getting picked.</p>
<p>But how i want is that in case sthe same per_ab_entry_id was updated and if the last_upd_dt of the update >= run_Date then , the insert row should also be extracted -</p>
<p>The output should look like this in the latest run-</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>PER_AB_ENTRY_ID</th>
<th>person_number</th>
<th>flag</th>
<th>duration</th>
<th>START_dATE</th>
<th>END_DATE</th>
<th>LAST_UPD_DT</th>
</tr>
</thead>
<tbody>
<tr>
<td>15</td>
<td>101</td>
<td>O</td>
<td>3</td>
<td>01/10/2022</td>
<td>03/10/2022</td>
<td>2022-11-01T04:59:43</td>
</tr>
<tr>
<td>15</td>
<td>101</td>
<td>u</td>
<td>1</td>
<td>01/10/2022</td>
<td>01/10/2022</td>
<td>2022-11-02T10:59:43</td>
</tr>
</tbody>
</table>
</div>
<p>I have to run the below query such that the last_update_date >= :process_date.
Its working for the delete condition and evrything except this case. How can it be tweaked that when the last_upd_dt of the latest recorrd of one per_ab_entry_id >=process_date then its previous row is also sent.</p>
<p>The below query is not working because the last_upd_dt of the 1st row <= process_date</p>
<pre><code> with anc as
(
select person_number,
absence_type,
ABSENCE_STATUS,
approval_status_cd,
start_date,
end_date,
duration,
PER_AB_ENTRY_ID,
AUDIT_ACTION_TYPE_,
row_number() over (order by PER_AB_ENTRY_ID, LAST_UPD_DT) rn
from ANC_PER_ABS_ENTRIES
)
SELECT * FROM ANC
where RN = 1
or RN = 2 and UPPER(flag) = 'D'
and APPROVAL_STATUS_CD = 'Approved'
and last_update_date >=:process_date
ORder by PER_AB_ENTRY_ID, LAST_UPD_DT
</code></pre>
| [
{
"answer_id": 74308578,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "data <- data.frame(x=c(4,3,4,4,99),\n y=c(4,NA,3,2,4),\n z = c(88,NA,4,4,5),\n w = c(4,5,2,3,4))\n\ndf$mean <- apply(data, 1, function(x) {\n idx <- which((x %in% c(88, 89)) == FALSE)\n mean(x[ idx ], na.rm = TRUE)\n})\n\n"
},
{
"answer_id": 74308580,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 3,
"selected": true,
"text": "rowMeans"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490556/"
] |
74,308,534 | <p>I have piece of a code that I don't entirely understand why it acts like that.</p>
<p><code>const handleLoadMore = () => { setPageNumber(pageNumber+1); fetchData(pageNumber); };</code></p>
<p>State <code>pageNumber </code>remains same as I didn't change the state. Outside of the <code>handleLoadMore </code>function increments. I kind of understand that it won't increment function body. So, is there anyway to tell <code>fetchData(pageNumber)</code> to wait for state to update.</p>
<p>I tried to find on google how to solve this kind of a problem. I tried setTimeout function but it didn't help.</p>
| [
{
"answer_id": 74308578,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "data <- data.frame(x=c(4,3,4,4,99),\n y=c(4,NA,3,2,4),\n z = c(88,NA,4,4,5),\n w = c(4,5,2,3,4))\n\ndf$mean <- apply(data, 1, function(x) {\n idx <- which((x %in% c(88, 89)) == FALSE)\n mean(x[ idx ], na.rm = TRUE)\n})\n\n"
},
{
"answer_id": 74308580,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 3,
"selected": true,
"text": "rowMeans"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15587166/"
] |
74,308,535 | <p>I've been told that <code>Rigidbody.MoveRotation</code> is the best way in Unity 3D to rotate the player between fixed positions while still detecting hits. However, while I can move smoothly from fixed position to position with:</p>
<pre><code>if (Vector3.Distance(player.position, targetPos) > 0.0455f) //FIXES JITTER
{
var direction = targetPos - rb.transform.position;
rb.MovePosition(transform.position + direction.normalized * playerSpeed * Time.fixedDeltaTime);
}
</code></pre>
<p>I can't find out how to rotate smoothly between fixed positions. I can rotate to the angle I want instantly using <code>Rigidbody.MoveRotation(Vector3 target);</code>, but I can't seem to find a way to do the above as a rotation.</p>
<p>Note: <code>Vector3.Distance</code> is the only thing stopping jitter. Has anyone got any ideas?</p>
| [
{
"answer_id": 74308740,
"author": "Pavlos Mavris",
"author_id": 16523060,
"author_profile": "https://Stackoverflow.com/users/16523060",
"pm_score": -1,
"selected": false,
"text": "private bool rotating = true;\npublic void Update()\n{\n if (rotating)\n {\n Vector3 to = new Vector3(20, 20, 20);\n if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)\n {\n transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);\n }\n else\n {\n transform.eulerAngles = to;\n rotating = false;\n }\n }\n \n}\n"
},
{
"answer_id": 74309502,
"author": "Horothenic",
"author_id": 9855648,
"author_profile": "https://Stackoverflow.com/users/9855648",
"pm_score": 0,
"selected": false,
"text": "rigidbody.DoRotate(target, 1f)"
},
{
"answer_id": 74315977,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 0,
"selected": false,
"text": "MoveRotation"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14849988/"
] |
74,308,593 | <p>Hello everyone I am new to Python and I wanted to see if someone can help. I am trying to automate text input on a website. I am trying to run a code that says if the input box is empty to type 4.00 if not to press the down key. An image is provided to help understand the issue.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import pyautogui
driver = webdriver.Chrome()
driver.maximize_window()
login = driver.get("somesite")
sleep = time.sleep(10)
sleep
select_applications = driver.find_element(By.XPATH,"/html/body/div[3]/div[2]/div[1]/div[1]/div[1]/div/div/div/div/header/div[3]/div[3]/div[1]/button").click()
time.sleep(3)
select_app = driver.find_element(By.XPATH,"/html/body/div[3]/div[2]/div[1]/div[1]/div[1]/div/div/div/div/header/div[3]/div[3]/div[2]/div/div[2]/div/div/div[5]/div/div[33]/div/div/div[1]/span/a/img").click()
time.sleep(10)
py = pyautogui
py.moveTo('Wed.PNG')
py.move(0,35)
send_click = py.click()
if send_click = " ":
py.hotkey("4.00)
else:
py.hotkey("down")
</code></pre>
<p>I try running the If statement but I got no results.</p>
<p><a href="https://i.stack.imgur.com/dpI9v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dpI9v.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74308740,
"author": "Pavlos Mavris",
"author_id": 16523060,
"author_profile": "https://Stackoverflow.com/users/16523060",
"pm_score": -1,
"selected": false,
"text": "private bool rotating = true;\npublic void Update()\n{\n if (rotating)\n {\n Vector3 to = new Vector3(20, 20, 20);\n if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)\n {\n transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);\n }\n else\n {\n transform.eulerAngles = to;\n rotating = false;\n }\n }\n \n}\n"
},
{
"answer_id": 74309502,
"author": "Horothenic",
"author_id": 9855648,
"author_profile": "https://Stackoverflow.com/users/9855648",
"pm_score": 0,
"selected": false,
"text": "rigidbody.DoRotate(target, 1f)"
},
{
"answer_id": 74315977,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 0,
"selected": false,
"text": "MoveRotation"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411196/"
] |
74,308,612 | <p>I am trying to create a time series of the sea surface temperature data over the whole year for six consecutive years and plot them using the subplots. I want to mark the x-ticks as the months. I tried using the <code>matplotlib.dates</code> option. However the years doesn't change on the subsequent subplots.</p>
<pre><code>import numpy as np
import sys
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import set_epoch
arrays14 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2014.ascii')] #loading the data
arrays15 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2015.ascii')]
arrays16 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2016.ascii')]
arrays17 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2017.ascii')]
arrays18 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2018.ascii')]
arrays19 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2019.ascii')]
arrays14 = np.delete(arrays14,[0,1,2,3,4],0) #deleting the headers
arrays15 = np.delete(arrays15,[0,1,2,3,4],0)
arrays16 = np.delete(arrays16,[0,1,2,3,4],0)
arrays17 = np.delete(arrays17,[0,1,2,3,4],0)
arrays18 = np.delete(arrays18,[0,1,2,3,4],0)
arrays19 = np.delete(arrays19,[0,1,2,3,4,215,216,217],0)
sst14 = []
for i in arrays14:
d1 = i[0]
d2 = i[2]
sst1 = i[2]
sst14.append(sst1)
datetime1.append(d1)
datetime2.append(d2)
sst14 = np.array(sst14,dtype = np.float64)
sst_14_m = np.ma.masked_equal(sst14,-9.99) #masking the fillvalues
sst15 = []
for i in arrays15:
sst2 = i[2]
sst15.append(sst2)
sst15 = np.array(sst15,dtype = np.float64)
sst_15_m = np.ma.masked_equal(sst15,-9.99)
sst16 = []
for i in arrays16:
sst3 = i[2]
sst16.append(sst3)
sst16 = np.array(sst16,dtype = np.float64)
sst_16_m = np.ma.masked_equal(sst16,-9.99)
sst17 = []
for i in arrays17:
sst4 = i[2]
sst17.append(sst4)
sst17 = np.array(sst17,dtype = np.float64)
sst_17_m = np.ma.masked_equal(sst17,-9.99)
sst18 = []
for i in arrays18:
sst5 = i[2]
sst18.append(sst5)
sst18 = np.array(sst18,dtype = np.float64)
sst_18_m = np.ma.masked_equal(sst18,-9.99)
np.shape(sst18)
sst19 = []
for i in arrays19:
sst6 = i[2]
sst19.append(sst6)
sst19 = np.array(sst19,dtype = np.float64)
sst19_u = np.zeros(len(sst14), dtype = np.float64)
sst19_fill = np.full([118],-9.99,dtype=np.float64)
sst19_u[0:211] = sst19[0:211]
sst19_u[211:329] = sst19_fill
sst19_u[329:365] = sst19[211:247]
sst_19_m = np.ma.masked_equal(sst19_u,-9.99)
##########Plotting
new_epoch = '2016-01-01T00:00:00'
mdates.set_epoch(new_epoch)
fig, axs=plt.subplots(3, 2, figsize=(12, 8),constrained_layout=True)
axs = axs.ravel()
axs[0].plot(sst_14_m)
axs[1].plot(sst_15_m)
axs[2].plot(sst_16_m)
axs[3].plot(sst_17_m)
axs[4].plot(sst_18_m)
axs[5].plot(sst_19_m)
for i in range(6):
axs[i].xaxis.set_major_locator(mdates.MonthLocator())
axs[i].xaxis.set_minor_locator(mdates.MonthLocator())
axs[i].xaxis.set_major_formatter(mdates.ConciseDateFormatter(axs[i].xaxis.get_major_locator()))
#axs[i].grid(True)
axs[i].set_ylim(bottom=25, top=32)
axs[i].set_ylabel('SST')
plt.show()
</code></pre>
<p>I got an output like the following:
<a href="https://i.stack.imgur.com/y3Gqq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y3Gqq.png" alt="enter image description here" /></a></p>
<p>I would like to change the xlabels as 2016,2017,2018,2019 etc.</p>
<p>The data can be found in the folder - <a href="https://drive.google.com/drive/folders/1bETa7PjWKIUNS13xg3RgIMa5L7bpYn5W?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/drive/folders/1bETa7PjWKIUNS13xg3RgIMa5L7bpYn5W?usp=sharing</a></p>
| [
{
"answer_id": 74310227,
"author": "The Emerging Star",
"author_id": 17581930,
"author_profile": "https://Stackoverflow.com/users/17581930",
"pm_score": 0,
"selected": false,
"text": "from pickletools import float8\nimport os\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import set_epoch\nfrom datetime import datetime\n# for files in os.listdir('/home/swadhin/project/sst/daily'):\n# path = (files)\n# print(path)\n# arrays = [np.asarray(list(map(str, line.split()))) for line in open(files)]\n\narrays14 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2014.ascii')] #loading the data\narrays15 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2015.ascii')]\narrays16 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2016.ascii')]\narrays17 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2017.ascii')]\narrays18 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2018.ascii')]\narrays08 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2008.ascii')]\n\narrays14 = np.delete(arrays14,[0,1,2,3,4],0) #deleting the headers\narrays15 = np.delete(arrays15,[0,1,2,3,4],0)\narrays16 = np.delete(arrays16,[0,1,2,3,4],0)\narrays17 = np.delete(arrays17,[0,1,2,3,4],0)\narrays18 = np.delete(arrays18,[0,1,2,3,4],0)\narrays08 = np.delete(arrays08,[0,1,2,3,4,215,216,217],0)\nsst14 = []\ndatetime1 = [] #year, month,date\n#datetime2 = [] #hour,min,second\nfor i in arrays14:\n d1 = i[0]\n #d2 = i[2]\n sst1 = i[2]\n sst14.append(sst1)\n datetime1.append(d1)\n #datetime2.append(d2)\n#reading the data\n# datetime1 = np.array(datetime1,dtype = np.float64)\n# datetime2 = np.array(datetime2,dtype = np.float64)\nsst14 = np.array(sst14,dtype = np.float64)\nsst_14_m = np.ma.masked_equal(sst14,-9.99) #masking the fillvalues\n\nsst15 = []\ndatetime2 = [] \nfor i in arrays15:\n d2 = i[0]\n sst2 = i[2]\n sst15.append(sst2)\n datetime2.append(d2)\nsst15 = np.array(sst15,dtype = np.float64)\nsst_15_m = np.ma.masked_equal(sst15,-9.99)\n\nsst16 = []\ndatetime3 = [] \nfor i in arrays16:\n d3 = i[0]\n sst3 = i[2]\n sst16.append(sst3)\n datetime3.append(d3)\nsst16 = np.array(sst16,dtype = np.float64)\nsst_16_m = np.ma.masked_equal(sst16,-9.99)\n\nsst17 = []\ndatetime4 = [] \nfor i in arrays17:\n d4 = i[0]\n sst4 = i[2]\n sst17.append(sst4)\n datetime4.append(d4)\nsst17 = np.array(sst17,dtype = np.float64)\nsst_17_m = np.ma.masked_equal(sst17,-9.99)\n\nsst18 = []\ndatetime5 = [] \nfor i in arrays18:\n d5 = i[0]\n sst5 = i[2]\n sst18.append(sst5)\n datetime5.append(d5)\nsst18 = np.array(sst18,dtype = np.float64)\nsst_18_m = np.ma.masked_equal(sst18,-9.99)\n\nsst08 = []\ndatetime6 = [] \nfor i in arrays08:\n d6 = i[0]\n sst6 = i[2]\n sst08.append(sst6)\n datetime6.append(d6)\nsst08 = np.array(sst08,dtype = np.float64)\n# sst08_u = np.zeros(len(sst14), dtype = np.float64)\n# sst08_fill = np.full([118],-9.99,dtype=np.float64)\n# sst08_u[0:211] = sst08[0:211]\n# sst08_u[211:329] = sst08_fill\n# sst08_u[329:365] = sst08[211:247]\nsst_08_m = np.ma.masked_equal(sst08,-9.99)\n\ndt = np.asarray([datetime1,datetime2,datetime3,datetime4,datetime5,datetime6])\n\ndt_m = []\nfor i in dt:\n dt_m1= []\n for j in i:\n datetime_object = datetime.strptime(j,'%Y%m%d')\n dt_m1.append(datetime_object)\n dt_m.append(dt_m1)\n\n##########Plotting\n# new_epoch = '2016-01-01T00:00:00'\n# mdates.set_epoch(new_epoch)\nfig, axs=plt.subplots(3, 2, figsize=(12, 8),constrained_layout=True)\naxs = axs.ravel()\naxs[0].plot_date(dt_m[5],sst_08_m,'-')\naxs[1].plot_date(dt_m[0],sst_14_m,'-')\naxs[2].plot_date(dt_m[1],sst_15_m,'-')\naxs[3].plot_date(dt_m[2],sst_16_m,'-')\naxs[4].plot_date(dt_m[3],sst_17_m,'-')\naxs[5].plot_date(dt_m[4],sst_18_m,'-')\nfor i in range(6):\n axs[i].xaxis.set_major_locator(mdates.MonthLocator())\n axs[i].xaxis.set_minor_locator(mdates.MonthLocator())\n axs[i].xaxis.set_major_formatter(mdates.ConciseDateFormatter(axs[i].xaxis.get_major_locator()))\n axs[i].grid(True)\n axs[i].set_ylim(bottom=25, top=32)\n axs[i].set_ylabel('SST')\n\n\nplt.show()\n"
},
{
"answer_id": 74320826,
"author": "kwinkunks",
"author_id": 3381305,
"author_profile": "https://Stackoverflow.com/users/3381305",
"pm_score": 2,
"selected": true,
"text": "pandas"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17581930/"
] |
74,308,623 | <p>I have a pandas dataframe where I want to replace the value in the Prediction column with the value in the column referred to by the prediction column.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Prediction</th>
</tr>
</thead>
<tbody>
<tr>
<td>stipulation</td>
<td>interrelation</td>
<td>jurisdiction</td>
<td>interpretation</td>
<td>D</td>
</tr>
<tr>
<td>typically</td>
<td>conceivably</td>
<td>tentatively</td>
<td>desperately</td>
<td>C</td>
</tr>
<tr>
<td>familiar</td>
<td>imaginative</td>
<td>apparent</td>
<td>logical</td>
<td>A</td>
</tr>
<tr>
<td>plan</td>
<td>explain</td>
<td>study</td>
<td>discard</td>
<td>B</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried a few methods using df.apply() and map() but they haven't worked. The resulting dataframe would look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Prediction</th>
</tr>
</thead>
<tbody>
<tr>
<td>stipulation</td>
<td>interrelation</td>
<td>jurisdiction</td>
<td>interpretation</td>
<td>interpretation</td>
</tr>
<tr>
<td>typically</td>
<td>conceivably</td>
<td>tentatively</td>
<td>desperately</td>
<td>tentatively</td>
</tr>
<tr>
<td>familiar</td>
<td>imaginative</td>
<td>apparent</td>
<td>logical</td>
<td>familiar</td>
</tr>
<tr>
<td>plan</td>
<td>explain</td>
<td>study</td>
<td>discard</td>
<td>explain</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74310227,
"author": "The Emerging Star",
"author_id": 17581930,
"author_profile": "https://Stackoverflow.com/users/17581930",
"pm_score": 0,
"selected": false,
"text": "from pickletools import float8\nimport os\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import set_epoch\nfrom datetime import datetime\n# for files in os.listdir('/home/swadhin/project/sst/daily'):\n# path = (files)\n# print(path)\n# arrays = [np.asarray(list(map(str, line.split()))) for line in open(files)]\n\narrays14 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2014.ascii')] #loading the data\narrays15 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2015.ascii')]\narrays16 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2016.ascii')]\narrays17 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2017.ascii')]\narrays18 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2018.ascii')]\narrays08 = [np.asarray(list(map(str, line.split()))) for line in open('/home/swadhin/project/sst/daily/sst15n90e_dy_2008.ascii')]\n\narrays14 = np.delete(arrays14,[0,1,2,3,4],0) #deleting the headers\narrays15 = np.delete(arrays15,[0,1,2,3,4],0)\narrays16 = np.delete(arrays16,[0,1,2,3,4],0)\narrays17 = np.delete(arrays17,[0,1,2,3,4],0)\narrays18 = np.delete(arrays18,[0,1,2,3,4],0)\narrays08 = np.delete(arrays08,[0,1,2,3,4,215,216,217],0)\nsst14 = []\ndatetime1 = [] #year, month,date\n#datetime2 = [] #hour,min,second\nfor i in arrays14:\n d1 = i[0]\n #d2 = i[2]\n sst1 = i[2]\n sst14.append(sst1)\n datetime1.append(d1)\n #datetime2.append(d2)\n#reading the data\n# datetime1 = np.array(datetime1,dtype = np.float64)\n# datetime2 = np.array(datetime2,dtype = np.float64)\nsst14 = np.array(sst14,dtype = np.float64)\nsst_14_m = np.ma.masked_equal(sst14,-9.99) #masking the fillvalues\n\nsst15 = []\ndatetime2 = [] \nfor i in arrays15:\n d2 = i[0]\n sst2 = i[2]\n sst15.append(sst2)\n datetime2.append(d2)\nsst15 = np.array(sst15,dtype = np.float64)\nsst_15_m = np.ma.masked_equal(sst15,-9.99)\n\nsst16 = []\ndatetime3 = [] \nfor i in arrays16:\n d3 = i[0]\n sst3 = i[2]\n sst16.append(sst3)\n datetime3.append(d3)\nsst16 = np.array(sst16,dtype = np.float64)\nsst_16_m = np.ma.masked_equal(sst16,-9.99)\n\nsst17 = []\ndatetime4 = [] \nfor i in arrays17:\n d4 = i[0]\n sst4 = i[2]\n sst17.append(sst4)\n datetime4.append(d4)\nsst17 = np.array(sst17,dtype = np.float64)\nsst_17_m = np.ma.masked_equal(sst17,-9.99)\n\nsst18 = []\ndatetime5 = [] \nfor i in arrays18:\n d5 = i[0]\n sst5 = i[2]\n sst18.append(sst5)\n datetime5.append(d5)\nsst18 = np.array(sst18,dtype = np.float64)\nsst_18_m = np.ma.masked_equal(sst18,-9.99)\n\nsst08 = []\ndatetime6 = [] \nfor i in arrays08:\n d6 = i[0]\n sst6 = i[2]\n sst08.append(sst6)\n datetime6.append(d6)\nsst08 = np.array(sst08,dtype = np.float64)\n# sst08_u = np.zeros(len(sst14), dtype = np.float64)\n# sst08_fill = np.full([118],-9.99,dtype=np.float64)\n# sst08_u[0:211] = sst08[0:211]\n# sst08_u[211:329] = sst08_fill\n# sst08_u[329:365] = sst08[211:247]\nsst_08_m = np.ma.masked_equal(sst08,-9.99)\n\ndt = np.asarray([datetime1,datetime2,datetime3,datetime4,datetime5,datetime6])\n\ndt_m = []\nfor i in dt:\n dt_m1= []\n for j in i:\n datetime_object = datetime.strptime(j,'%Y%m%d')\n dt_m1.append(datetime_object)\n dt_m.append(dt_m1)\n\n##########Plotting\n# new_epoch = '2016-01-01T00:00:00'\n# mdates.set_epoch(new_epoch)\nfig, axs=plt.subplots(3, 2, figsize=(12, 8),constrained_layout=True)\naxs = axs.ravel()\naxs[0].plot_date(dt_m[5],sst_08_m,'-')\naxs[1].plot_date(dt_m[0],sst_14_m,'-')\naxs[2].plot_date(dt_m[1],sst_15_m,'-')\naxs[3].plot_date(dt_m[2],sst_16_m,'-')\naxs[4].plot_date(dt_m[3],sst_17_m,'-')\naxs[5].plot_date(dt_m[4],sst_18_m,'-')\nfor i in range(6):\n axs[i].xaxis.set_major_locator(mdates.MonthLocator())\n axs[i].xaxis.set_minor_locator(mdates.MonthLocator())\n axs[i].xaxis.set_major_formatter(mdates.ConciseDateFormatter(axs[i].xaxis.get_major_locator()))\n axs[i].grid(True)\n axs[i].set_ylim(bottom=25, top=32)\n axs[i].set_ylabel('SST')\n\n\nplt.show()\n"
},
{
"answer_id": 74320826,
"author": "kwinkunks",
"author_id": 3381305,
"author_profile": "https://Stackoverflow.com/users/3381305",
"pm_score": 2,
"selected": true,
"text": "pandas"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20222924/"
] |
74,308,652 | <p>I would like to create two new columns based on a third one. These two columns should have incrementing values of two different kinds.</p>
<p>Let´s take the following dataset as an example:</p>
<pre><code>events <- data.frame(Frame = seq(from = 1001, to = 1033, by = 1),
Value = c(2.05, 0, 2.26, 2.38, 0, 0, 2.88, 0.32, 0.85, 2.85, 2.09, 0, 0, 0, 1.11, 0, 0,
0, 2.46, 2.85, 0, 0, 0.38, 1.91, 0, 0, 0, 2.23, 0, 0.48, 1.83, 0.23, 1.49))
</code></pre>
<p>I would like to create:</p>
<ul>
<li>a column called "Number" incrementing everytime there is a sequence starting with 0 in the column "Value", and</li>
<li>a column called "Duration" starting from 1 everytime a new sequence of 0s is present in the column "Value" and incrementing with 1 as long as the sequence of 0s continues.</li>
</ul>
<p>Ideally, the final data frame would be this one:</p>
<pre><code>events_final <- data.frame(Frame = seq(from = 1001, to = 1033, by = 1),
Value = c(2.05, 0, 2.26, 2.38, 0, 0, 2.88, 0.32, 0.85, 2.85, 2.09, 0, 0, 0, 1.11, 0, 0,
0, 2.46, 2.85, 0, 0, 0.38, 1.91, 0, 0, 0, 2.23, 0, 0.48, 1.83, 0.23, 1.49),
Number = c(0, 1, 0, 0, 2, 2, 0, 0, 0, 0, 0, 3, 3, 3, 0, 4, 4,
4, 0, 0, 5, 5, 0, 0, 6, 6, 6, 0, 7, 0, 0, 0, 0),
Duration = c(0, 1, 0, 0, 1, 2, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2,
3, 0, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 0, 0, 0, 0))
</code></pre>
<p>I tried to use the <code>tidyverse</code> to do so, but I do not manage to get what I need [I am even very far from it]:</p>
<pre><code>events %>%
mutate(Number = ifelse(Value > 0, NA, 1),
Duration = case_when(Value == 0 & lag(Value, n = 1) != 0 ~ 1,
Value == 0 & lag(Value, n = 1) == 0 ~ 2))
</code></pre>
<p>By looking for related questions, I found that this was feasible in SQL [https://stackoverflow.com/questions/42971752/increment-value-based-on-another-column]. I also know that this is quite easy to be done in Excel [the first Value is in the cell B2]:</p>
<ul>
<li>Number column [Column C]: =IF(B2>0,0,IF(B1=0,C1,MAX(C$1:C1)+1))</li>
<li>Duration column [Column D]: =IF(B2>0,0,IF(B1=0,D1+1,1))</li>
</ul>
<p>But I need to have it work in R ;-)</p>
<p>Any help is welcome :-)</p>
| [
{
"answer_id": 74308909,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 3,
"selected": false,
"text": "data.table::rleid()"
},
{
"answer_id": 74308956,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 0,
"selected": false,
"text": "events <- data.frame(Frame = seq(from = 1001, to = 1033, by = 1),\n Value = c(2.05, 0, 2.26, 2.38, 0, 0, 2.88, 0.32, 0.85, 2.85, 2.09, 0, 0, 0, 1.11, 0, 0,\n 0, 2.46, 2.85, 0, 0, 0.38, 1.91, 0, 0, 0, 2.23, 0, 0.48, 1.83, 0.23, 1.49))\n\nevents_final <- data.frame(Frame = seq(from = 1001, to = 1033, by = 1),\n Value = c(2.05, 0, 2.26, 2.38, 0, 0, 2.88, 0.32, 0.85, 2.85, 2.09, 0, 0, 0, 1.11, 0, 0,\n 0, 2.46, 2.85, 0, 0, 0.38, 1.91, 0, 0, 0, 2.23, 0, 0.48, 1.83, 0.23, 1.49),\n Number = c(0, 1, 0, 0, 2, 2, 0, 0, 0, 0, 0, 3, 3, 3, 0, 4, 4,\n 4, 0, 0, 5, 5, 0, 0, 6, 6, 6, 0, 7, 0, 0, 0, 0),\n Duration = c(0, 1, 0, 0, 1, 2, 0, 0, 0, 0, 0, 1, 2, 3, 0, 1, 2,\n 3, 0, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 0, 0, 0, 0))\nlibrary(stringr)\nevents$Number <- events$Value == 0\nevents$tmp <- NA\ni <- 0\nlapply(2:nrow(events), function(x) {\n if ((events[ x, 'Number' ] == TRUE) & \n (events[ x - 1, 'Number' ] == FALSE)) { \n i <<- i + 1\n events[ x, 'tmp' ] <<- i\n } else if ((events[ x, 'Number' ] == TRUE) & \n (events[ x - 1, 'Number' ] == TRUE)) {\n events[ x, 'tmp' ] <<- i\n }\n}) |> \n invisible()\nidx <- which(is.na(events$tmp))\nevents[ idx, 'tmp' ] <- 0\nevents <- split(events, events$tmp) |> \n lapply(function(x) {\n if (unique(x$tmp) > 0) { \n x$duration <- 1:nrow(x)\n } else {\n x$duration <- 0\n }\n x\n}) |> \n data.table::rbindlist(fill = TRUE) |>\n as.data.frame()\n\nidx <- order(events$Frame)\nevents <- events[ idx, ]\nevents$Number <- NULL\ncolnames(events) <- c('Frame', 'Value', 'Number', 'Duration')\nrownames(events) <- NULL\nprint(events)\n\nidentical(events, events_final)\n\n"
},
{
"answer_id": 74309055,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": false,
"text": "tidyverse"
},
{
"answer_id": 74309059,
"author": "Gregor Thomas",
"author_id": 903061,
"author_profile": "https://Stackoverflow.com/users/903061",
"pm_score": 3,
"selected": true,
"text": "dplyr"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3829013/"
] |
74,308,683 | <p>In React I'm using utility functions to handle the api calls. When the Arrow function is no longer anonymous it returns a pending promise, which is what I would like. However when the arrow function is anonymous it returns the function.</p>
<p>Is there any way to return a pending promise in one line?</p>
<p>Here is what the function looks like when not anonymous:</p>
<pre class="lang-js prettyprint-override"><code>const list = () => {
let res = async () => await api.get("list");
return res();
}
</code></pre>
<p>Here is what it looks like anonymous:</p>
<pre class="lang-js prettyprint-override"><code>const list = () => {
return async () => await api.get("list")
}
</code></pre>
| [
{
"answer_id": 74308710,
"author": "Finbar",
"author_id": 17525834,
"author_profile": "https://Stackoverflow.com/users/17525834",
"pm_score": 0,
"selected": false,
"text": "const list = () => {\n return (async () => await api.get(\"list\"))();\n}\n"
},
{
"answer_id": 74308713,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": true,
"text": "res();\n"
},
{
"answer_id": 74308716,
"author": "Dr. Vortex",
"author_id": 17637456,
"author_profile": "https://Stackoverflow.com/users/17637456",
"pm_score": 0,
"selected": false,
"text": "const list = () => {\n return api.get(\"list\")\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14402975/"
] |
74,308,698 | <p>I am a beginner in SQL and I want to do something on my table 'User'.</p>
<p>I would like to make a constraint on my 'Password' column. The constraint is "Passwords only can be made of letters and digits, the only symbol allowed is "_" "</p>
<p>I don't know how to allowed only one symbol with a check() constraint.</p>
<p>I searched a lot on google and didn't find the solution.</p>
<p>I was thinking something like this :</p>
<p>CONSTRAINT TABLE_PASSWORD check ( password ........ )</p>
| [
{
"answer_id": 74308985,
"author": "EdmCoff",
"author_id": 5504922,
"author_profile": "https://Stackoverflow.com/users/5504922",
"pm_score": 1,
"selected": false,
"text": "CHECK"
},
{
"answer_id": 74308999,
"author": "Ergest Basha",
"author_id": 16461952,
"author_profile": "https://Stackoverflow.com/users/16461952",
"pm_score": 1,
"selected": true,
"text": "_"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411301/"
] |
74,308,703 | <p>I have a data frame with integers, like so:</p>
<pre><code># generate data frame
df = cbind(c(0,102,0,40,0,0), c(22,0,0,0,12,4), c(23,101,55,0,0,0),
c(0,0,0,414,0,0), c(0,0,61,0,0,112), c(0,0,0,0,20,0))
colnames(df) = c('A', 'T', 'C', 'G', 'N', 'Del')
rownames(df) = c('Pos1', 'Pos2', 'Pos3', 'Pos4', 'Pos5', 'Pos6')
df
</code></pre>
<blockquote>
<pre><code> A T C G N Del
Pos1 0 22 23 0 0 0
Pos2 102 0 101 0 0 0
Pos3 0 0 55 0 61 0
Pos4 40 0 0 414 0 0
Pos5 0 12 0 0 0 20
Pos6 0 4 0 0 112 0
</code></pre>
</blockquote>
<p>I also have a vector with integers (which correspond to column indices of df):</p>
<pre><code># generate vector
cols = c(2,3,5,4,6,5)
</code></pre>
<p>Now, I want to reset all integers in df to zero that are present in columns with column indices that are listed in the vector, <strong>row-by-row</strong>. For example, for the first row I want to reset column 2 to zero, for the second row I want to reset column 3 to zero, etc.</p>
<p>I solved this with the following piece of code:</p>
<pre><code>for (i in c(1:nrow(df))) {
ncol = cols[[i]]
df[[i, ncol]] = 0
df
}
df
</code></pre>
<blockquote>
<pre><code> A T C G N Del
Pos1 0 0 23 0 0 0
Pos2 102 0 0 0 0 0
Pos3 0 0 55 0 0 0
Pos4 40 0 0 0 0 0
Pos5 0 12 0 0 0 0
Pos6 0 4 0 0 0 0
</code></pre>
</blockquote>
<p>As you can see, my code behaves as intended. However, it turns out to be very inefficient on large datasets. I therefore wondered whether there is an alternative that will be considerably faster than using a for-loop.</p>
<p><strong>Note</strong> that it looks like I am resetting the maximum value in each row, but this is not the case as in some instances, it is the smaller of the two values that I am resetting to zero. So I cannot simply reset the min or max in each row to zero.</p>
| [
{
"answer_id": 74308783,
"author": "markus",
"author_id": 8583393,
"author_profile": "https://Stackoverflow.com/users/8583393",
"pm_score": 3,
"selected": true,
"text": "cbind"
},
{
"answer_id": 74309353,
"author": "tmfmnk",
"author_id": 5964557,
"author_profile": "https://Stackoverflow.com/users/5964557",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6584775/"
] |
74,308,711 | <p>I'm pretty new to Swift. I have a DB connection to my app and all of the query results are stored in an Array of type Any as I've created one function to pass any queries.</p>
<p>I am now looking to search into this array for a specific string (here for example the email).</p>
<pre class="lang-swift prettyprint-override"><code>let Array = [1, Doe, John, john_doe@gmail.com, jdoe, t, 03/11/2022 15:00:00, nil, 1]
let stringToSearch:String = "John_doe@gmail.com"
if contains(itemsArray, stringToSearch) {
NSLog("Term Exists")
}
else {
NSLog("Can't find term")
}
</code></pre>
<p>I've looked at several options, but my main issue is how to move out from <code>Array<Any></code> to <code>String</code>.</p>
| [
{
"answer_id": 74308783,
"author": "markus",
"author_id": 8583393,
"author_profile": "https://Stackoverflow.com/users/8583393",
"pm_score": 3,
"selected": true,
"text": "cbind"
},
{
"answer_id": 74309353,
"author": "tmfmnk",
"author_id": 5964557,
"author_profile": "https://Stackoverflow.com/users/5964557",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411324/"
] |
74,308,712 | <p><strong>Question Explanation</strong> (<a href="https://open.kattis.com/problems/zamka" rel="nofollow noreferrer">Zamka</a>):<br />
<---------------------------------------------------------------------------------------------------------->
<em>Input Example:</em></p>
<pre><code>100
500
12
</code></pre>
<p><strong>1st Line:</strong> left bound <strong>(L)</strong><br />
<strong>2nd Line:</strong> right bound <strong>(D)</strong><br />
<strong>3rd Line:</strong> sum of digits within <strong>N/M (X)</strong><br />
<----------------------------------------------------------------------------------------------------------><br />
<em>Output Example:</em></p>
<pre><code>129 //focusing on this first
480
</code></pre>
<p><strong>1st Line:</strong> minimal integer that = <strong>X (N)</strong><br />
<strong>2nd Line:</strong> maximal integer that = <strong>X (M)</strong><br />
<----------------------------------------------------------------------------------------------------------><br />
<em>Thought process:</em><br />
<strong>1.</strong> declare input values with an array:</p>
<pre class="lang-js prettyprint-override"><code>input = ['100','500','12'];
</code></pre>
<p><strong>2.</strong> create loop between left (100) and right (500) bound:</p>
<pre class="lang-js prettyprint-override"><code>for (let i = input[0]; i <= input[1]; i++)
</code></pre>
<p><strong>3.</strong> declare a sum variable = 0 within the loop:</p>
<pre class="lang-js prettyprint-override"><code>let sumMIN = 0;
</code></pre>
<p><strong>4.</strong> create nested loop between 0 (first digit within <code>i</code>) and the length of <code>i</code> (<code>i.length</code>):</p>
<pre class="lang-js prettyprint-override"><code>for (let j = 0; j < i.length; j++) //problem => stops at i = 100
</code></pre>
<p><strong>5.</strong> for every digit within <code>i</code> sum up to <code>sumMIN</code>:</p>
<pre class="lang-js prettyprint-override"><code>sumMIN += parseInt(i[j]);
</code></pre>
<p><strong>6.</strong> if the sum of <code>i</code>'s digits = X then return true:</p>
<pre class="lang-js prettyprint-override"><code>if (sumMIN == input[2]) {
console.log("true");
}
</code></pre>
<p><----------------------------------------------------------------------------------------------------------><br />
<em>Problem:</em><br />
<strong>1.</strong> the nested loop only iterates <code>i = 100</code><br />
<strong>2.</strong> I think there is a problem lying within declaration of variables (<strong>string</strong> vs. <strong>integer</strong>)</p>
<p><strong>My Code so far:</strong></p>
<pre class="lang-js prettyprint-override"><code>var input = ['100', '500', '12'];
function decipher() {
for (let i = input[0]; i <= input[1]; i++) { //loops executes correctly
let sumMIN = 0;
for (let j = 0; j < i.length; j++) { //loop stops at i = 100
sumMIN += parseInt(i[j]);
console.log(sumMIN);
if (sumMIN == input[2]) {
console.log("true");
} else {
console.log("false");
}
}
}
}
return decipher(input);
</code></pre>
<p><strong>Current Output:</strong></p>
<pre class="lang-js prettyprint-override"><code>1
false
1
false
1
false
</code></pre>
<p><em>(let me know if you need more information!)</em></p>
| [
{
"answer_id": 74308783,
"author": "markus",
"author_id": 8583393,
"author_profile": "https://Stackoverflow.com/users/8583393",
"pm_score": 3,
"selected": true,
"text": "cbind"
},
{
"answer_id": 74309353,
"author": "tmfmnk",
"author_id": 5964557,
"author_profile": "https://Stackoverflow.com/users/5964557",
"pm_score": 1,
"selected": false,
"text": "dplyr"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411243/"
] |
74,308,719 | <p><code>console.log(result);</code>
In code here is being logged in the console every time there is an onChange in the input.
looking for a way to stop component re-render on input value change.</p>
<pre><code>import "./home.css";
const Home = () => {
const [city, setCity] = useState("kampala");
const [result, setResult] = useState(null);
const fetchApi = async (city) => {
const data = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=`api
key_here``
).then((res) => res.json())
.then((data) => setResult(data));
};
useEffect(() => {
fetchApi(city);
console.log("heyy");
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
await fetchApi(city);
};
if(result === null) {
return <p>Loading</p>
}
console.log(result);//this is logged in the console on every character change in the input. need to stop the re-render
return (
<div className="home__container">
<div className="home__img">
<div className="home__hero__info">
<div>
<h1>26 C</h1>
</div>
<div>
<h3>Kampala</h3>
<p>31 - October - 2022</p>
</div>
<div>
<p>Suuny</p>
</div>
</div>
</div>
<div className="home__details">
<div className="weather__div">
<form onSubmit={handleSubmit}>
<input
type="text"
className="home__input"
onChange={(e) => setCity(e.target.value)}
/>
<button type="submit" className="weather__button">
Search
</button>
</form>
<div className="weather__ul">
<ul>
<li>Kampala</li>
<li>Nairobi</li>
<li>Dodoma</li>
</ul>
</div>
<hr />
</div>
<div className="weather__div">
<h4 className="h4">Weather Conditions</h4>
<div>
<span className="weather__details">
<h4>Cloudy</h4>
<h3>{result.clouds.all}%</h3>
</span>
<span className="weather__details">
<h4>Humidity</h4>
{/* <h3>{result.main.humidity}%</h3> */}
</span>
<span className="weather__details">
<h4>Wind</h4>
{/* <h3>{wind.speed}</h3> */}
</span>
<span className="weather__details">
<h4>Rain</h4>
<h3>23%</h3>
</span>
</div>
<hr />
</div>
</div>
</div>
);
};
export default Home;
</code></pre>
| [
{
"answer_id": 74308840,
"author": "rocambille",
"author_id": 6612932,
"author_profile": "https://Stackoverflow.com/users/6612932",
"pm_score": 1,
"selected": false,
"text": "const initialValue = \"kampala\";\n\nconst Home = () => {\n const city = useRef();\n const [result, setResult] = useState(null);\n\n ...\n\n useEffect(() => {\n fetchApi(initialValue);\n console.log(\"heyy\");\n }, []);\n\n const handleSubmit = async (e) => {\n e.preventDefault();\n await fetchApi(city.current.value);\n };\n\n ...\n\n return (\n <div className=\"home__container\">\n ...\n <form onSubmit={handleSubmit}>\n <input\n type=\"text\"\n ref={city}\n className=\"home__input\"\n value={initialValue} \n />\n <button type=\"submit\" className=\"weather__button\">\n Search\n </button>\n </form>\n ...\n </div>\n );\n};\n"
},
{
"answer_id": 74308855,
"author": "Dmitriy",
"author_id": 9613899,
"author_profile": "https://Stackoverflow.com/users/9613899",
"pm_score": 0,
"selected": false,
"text": "const city = useRef(\"kampala\");\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14131746/"
] |
74,308,737 | <p>I use the following code to create a table if it does not exist yet:</p>
<pre><code>
PGconn* conn;
PGnotify* notify;
PGresult* createTableRes;
createTableRes = PQexec(conn, "CREATE TABLE IF NOT EXISTS t_xyz (xyzId SERIAL PRIMARY KEY NOT NULL, xyz VARCHAR(100) UNIQUE NOT NULL)");
notify = PQnotifies(conn);
if (notify != NULL)
{
char* extraStr = notify->extra;
}
errorDescribed = PQerrorMessage(conn);
if (PQresultStatus(createTableRes) != PGRES_COMMAND_OK)
{
errorDescribed = PQerrorMessage(conn);
my_logger.error("could not create table t_xyz, errorMessage:{}", errorDescribed);
PQclear(createTableRes);
exit_nicely(conn);
}
else
{
my_logger.info("created table t_xyz successfully.");
</code></pre>
<p>I would have expected to get a notify when the table exists since the console logs "relation already exists skipping" but notify is always NULL.
I would like to catch that notification so that I could log something like "table t_xyz existed already" instead of "created table t_xyz successfully".
How could I do that?</p>
<p>I've searched for solutions but only found hints to use "set client_min_messages=NOTICE" and I tried to do that using</p>
<pre><code>setRes = PQexec(conn, "set client_min_messages=INFO");
</code></pre>
<p>before creating the table but it did not change anything.</p>
| [
{
"answer_id": 74314040,
"author": "Laurenz Albe",
"author_id": 6464308,
"author_profile": "https://Stackoverflow.com/users/6464308",
"pm_score": 2,
"selected": true,
"text": "PQnotifies()"
},
{
"answer_id": 74320652,
"author": "Quiensabe",
"author_id": 14906583,
"author_profile": "https://Stackoverflow.com/users/14906583",
"pm_score": 0,
"selected": false,
"text": "PGconn* conn;\nPGnotify* notify;\nPGresult* createTableRes;\nstd::string notifyStr = \"\";\n\nstatic void\nmyrecv(void *arg, const PGresult *res)\n{\n notifyStr = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);\n printf(\"Received NOTICE: \\\"%s\\\"\\n\", notifyStr.c_str()); \n}\n\n PQsetNoticeReceiver(conn, myrecv, NULL);\n\n createTableRes = PQexec(conn, \"CREATE TABLE IF NOT EXISTS t_xyz (xyzId SERIAL PRIMARY KEY NOT NULL, xyz VARCHAR(100) UNIQUE NOT NULL)\");\n notify = PQnotifies(conn);\n if (notify != NULL)\n {\n char* extraStr = notify->extra;\n }\n errorDescribed = PQerrorMessage(conn);\n\n if (PQresultStatus(createTableRes) != PGRES_COMMAND_OK)\n {\n errorDescribed = PQerrorMessage(conn);\n my_logger.error(\"could not create table t_xyz, errorMessage:{}\", errorDescribed);\n PQclear(createTableRes);\n exit_nicely(conn);\n }\n else\n {\n if (notifyStr.find(\"already exists\") != std::string::npos)\n {\n my_logger.info(\"table t_xyz existed already.\");\n }\n else\n {\n my_logger.info(\"created table t_xyz successfully.\");\n }\n notifyStr = \"\";\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14906583/"
] |
74,308,748 | <p>I want to cover the folowing code usingjest:</p>
<pre><code> @Debounce(100)
private checkDataToPositionInStep(): void {
const proposalConsultData = this.proposalConsultResponseStore.get();
if(proposalConsultData?.documentProposalData?.length > 1) {
this.fullScreenLoaderService.hideLoader();
this.router.navigate(['proposta-enviada']);
return;
}
if(proposalConsultData?.warrantyData?.plateUf) {
this.fullScreenLoaderService.hideLoader();
this.router.navigate(['upload']);
}
if(proposalConsultData?.bankData?.branchCode) {
this.fullScreenLoaderService.hideLoader();
this.scrollService.next(STEP_ACCORDION.DADOS_GARANTIA.STEP);
this.stepperService.next(STEP_ACCORDION.DADOS_GARANTIA.ID);
return;
}
this.fullScreenLoaderService.hideLoader();
this.scrollService.next(STEP_ACCORDION.DADOS_BANCARIOS.STEP);
this.stepperService.next(STEP_ACCORDION.DADOS_BANCARIOS.ID);
return;
}
</code></pre>
<p>And de debounce decorator is like this:</p>
<pre><code>export function Debounce(timeout: number): Function {
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function debounce(...args) {
setTimeout(() => {
original.apply(this, args);
}, timeout);
}
return descriptor;
}
}
</code></pre>
<p>When i run <code>npm run:coverage</code> all lines that are below decorators are not covering. Is there anyway to cover this lines ?</p>
<p>I just tried to call the checkDataToPositionStep method like this:</p>
<pre><code>it('Should call checkDataToPositionInStep with only bankData', () => {ons
const = proposalConsultMock = <any> {
bankData: {
branchCode: '01901'
}
};
(facade as any).checkDataToPositionInStep(proposalConsultMock );
});
</code></pre>
<p>And i thought that jest should cover the checkDataToPositionStep method.</p>
| [
{
"answer_id": 74309799,
"author": "Facundo Gallardo",
"author_id": 20375146,
"author_profile": "https://Stackoverflow.com/users/20375146",
"pm_score": 0,
"selected": false,
"text": "import { Debounce } from './Debouncefile';\n\ndescribe('Debounce', () => {\n it('should do something', () => {\n // Arrange\n const debounceFunction = Debounce(60);\n\n // Act\n const result = debounceFunction(params...);\n\n // Assert\n expect(result).toBe(something);\n });\n});\n"
},
{
"answer_id": 74309971,
"author": "Sebastien H.",
"author_id": 1667822,
"author_profile": "https://Stackoverflow.com/users/1667822",
"pm_score": 1,
"selected": false,
"text": "expect(...)"
},
{
"answer_id": 74318317,
"author": "Felipe Ken",
"author_id": 20411169,
"author_profile": "https://Stackoverflow.com/users/20411169",
"pm_score": 2,
"selected": true,
"text": "jest.useFakeTimers()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411169/"
] |
74,308,764 | <p>I have a loop which runs through a list of files then uploads them a Google Drive folder. There is a client_secrets.json file in the folder on my computer.</p>
<p>I am able to create new files in the Google Drive folder but I wish to overwrite the existing files, without changing the Google Drive file IDs. Is this possible to do this adapting my code below?</p>
<pre><code>from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
upload_file_list ["a.xlsx", "b.xlsx"]
for upload_file in upload_file_list:
gfile = drive.CreateFile({'parents': [{'id': [FOLDER ID}]})
gfile.SetContentFile(upload_file)
gfile.Upload()
gfile.content.close()
</code></pre>
| [
{
"answer_id": 74309433,
"author": "Captain Caveman",
"author_id": 2325014,
"author_profile": "https://Stackoverflow.com/users/2325014",
"pm_score": 1,
"selected": false,
"text": "service.files().update()\n"
},
{
"answer_id": 74309529,
"author": "Daniel",
"author_id": 12306687,
"author_profile": "https://Stackoverflow.com/users/12306687",
"pm_score": 1,
"selected": false,
"text": "files.update"
},
{
"answer_id": 74311107,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 3,
"selected": true,
"text": "file_id"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12525250/"
] |
74,308,768 | <p>I was looking for a way to find the mean of numerical values based on a certain column. I looked to this <a href="https://stackoverflow.com/questions/70824278/pandas-how-to-find-mean-of-a-column-based-on-duplicate-rows-in-another-column">link</a> for advice but it requires all values of one column to be the same and I'm sure there's a Pythonic way that would do that for all values that are duplicates.</p>
<p>Here's an example.</p>
<pre><code>data = {
"Name": ["John", "John", "Robert", "Robert", "Cindy", "Cindy", "Sarah", "Sarah"],
"Score": [84, 45, 67, 87, 88, 100, 76, 91]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
df
</code></pre>
<p><a href="https://i.stack.imgur.com/oJ1f0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oJ1f0.png" alt="enter image description here" /></a></p>
<p>I'd like it so there's one row of John with whatever the mean of John is. Same with Robert, Cindy and Sarah.</p>
<p>Thanks!</p>
| [
{
"answer_id": 74309433,
"author": "Captain Caveman",
"author_id": 2325014,
"author_profile": "https://Stackoverflow.com/users/2325014",
"pm_score": 1,
"selected": false,
"text": "service.files().update()\n"
},
{
"answer_id": 74309529,
"author": "Daniel",
"author_id": 12306687,
"author_profile": "https://Stackoverflow.com/users/12306687",
"pm_score": 1,
"selected": false,
"text": "files.update"
},
{
"answer_id": 74311107,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 3,
"selected": true,
"text": "file_id"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16370131/"
] |
74,308,777 | <p>I'm trying to write a program which task is to get rid of extra whitespace in a text stream.</p>
<pre><code>#include <stdio.h>
int main()
{
int c;
while( (c = getchar()) != EOF)
{
if(c == ' ')
{
putchar(c);
while( (c = getchar()) == ' ' );
if(c == EOF) break;
}
putchar(c);
}
}
</code></pre>
<p>I know that <code>getchar()</code> function returns a new character each iteration and we store the character in the <code>c</code> variable, but I can't figure out why do we need to assign <code>c</code> variable to <code>getchar()</code> in the second while loop again.</p>
| [
{
"answer_id": 74309433,
"author": "Captain Caveman",
"author_id": 2325014,
"author_profile": "https://Stackoverflow.com/users/2325014",
"pm_score": 1,
"selected": false,
"text": "service.files().update()\n"
},
{
"answer_id": 74309529,
"author": "Daniel",
"author_id": 12306687,
"author_profile": "https://Stackoverflow.com/users/12306687",
"pm_score": 1,
"selected": false,
"text": "files.update"
},
{
"answer_id": 74311107,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 3,
"selected": true,
"text": "file_id"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17481360/"
] |
74,308,792 | <p>In creating a python thread with name, we can do it by</p>
<pre><code>t = threading.Thread(target=func,name="my_thread")
</code></pre>
<p>In flask, each request spawns its own thread holding the context until the process is completed. How do i assign dynamic name to these threads being created by flask?</p>
| [
{
"answer_id": 74309433,
"author": "Captain Caveman",
"author_id": 2325014,
"author_profile": "https://Stackoverflow.com/users/2325014",
"pm_score": 1,
"selected": false,
"text": "service.files().update()\n"
},
{
"answer_id": 74309529,
"author": "Daniel",
"author_id": 12306687,
"author_profile": "https://Stackoverflow.com/users/12306687",
"pm_score": 1,
"selected": false,
"text": "files.update"
},
{
"answer_id": 74311107,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 3,
"selected": true,
"text": "file_id"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11784080/"
] |
74,308,795 | <p>I'm not super familiar with mocking, but I have to write unit tests for an endpoint for a flask app. So I'm using flask's unittest tools. We use blueprints, so the endpoints are located in a different file than the flask app. I have a function (call it function A). That function uses a helper function (call it function B). Function A always uses function B, and function B is only ever used by function A. I understand that in a unit test, its best to test one function at a time, but for all intent and purposes, these 2 functions are 2 halves of the same action. They probably should just be one function but it was split for readability.</p>
<p>Function B makes a call to a webservice using the requests library.</p>
<p>I would like to mock the call to this webservice. For some reason, this is giving me trouble. The webservice call isn't being properly captured and mocked. Instead, the actual webservice is being called. However, in my testing earlier when I created a dummy endpoint that made a similar webservice call, the mocking worked properly. This leads me to believe that the problem stems from the webservice call happening in funciton B not function A. Here is the code for the endpoint.</p>
<pre><code>@app.route('/myendpoint', methods=\['POST'\])
def functionA():
<some code>
functionB():
return something
def functionB():
resp = requests.get(url, headers=header)
</code></pre>
<p>and here is my test function in another file.</p>
<pre><code> @patch.object(requests, 'get')
def test_functionA(self, mock_requests):
mock_requests.json().returnvalue = json.dumps('"some": "value"')
mock_requests.status_code = 201
data = {'some': 'data'}
headers = {'Authorization': 'Bearer somekey'}
result = self.app.post('/myendpoint', data=data, follow_redirects=True, content_type='multipart/form-data', headers=headers)
mock_requests.assert_called()
self.assertEqual(result.status_code, 201)
</code></pre>
<p>In addition to my theory that it is failing because function B is making the request rather than function A, I have a theory that involves imports. In all of the documentation I've read for python unittests, unit testing with flask, and mocking, typically in the examples, the test script is in the same directory as the script being tested. The test script will then import whatever object is being mocked from the script being tested. So if the script being tested has a class CoolObject() and you wanted to mock it, you'd import CoolObject from the script being tested into the testing script. In my case, the file structure is not so straight-forward. Here is the file structure:</p>
<pre><code>myproject
⊢---src
| ⊢---routes
| ⊢---CRUD
| ⊢---myscript.py
⊢---test_scripts
⊢---test_script.py
</code></pre>
<p>So imports are a little complicated. So rather than importing requests.get FROM the script being tested, I just imported it like normal as part of the standard library. I fear this may give me undesired results. HOWEVER, I still think it is more likely that the problem is my original theory about the helper function. If the import was really the cause of the problem, the testing I did earlier with a dummy endpoint wouldn't have worked but it did.</p>
<p>I'm at a loss. Can anybody give me some help?</p>
| [
{
"answer_id": 74314463,
"author": "frankfalse",
"author_id": 18108367,
"author_profile": "https://Stackoverflow.com/users/18108367",
"pm_score": 1,
"selected": false,
"text": "src/routes/CRUD/myscript.py"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17091823/"
] |
74,308,834 | <p>I understand that this is not the best optimized code for leetcode problem 202 Happy Number, but I am trying to figure out what the Big O of this because of the conditional while loop. Ofc if n starts out as 0-4, it would be O(1).</p>
<pre><code>/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
/* pseudocode
- n is input
- while loop if num is greater than 1
- turn number to string
- split the string
- map to an array
- add all numbers' squares
- if num is 1, break and return true
- if not loop
*/
// check for definite false cases
if (n === 1) {
return true;
}
else if (n === 0|| n === 2 || n === 3 || n === 4) {
return false;
}
while (n > 1) {
// split and turn to string
n = n.toString().split("");
console.log(n);
// map to arr
//let tempArr = n.map(n);
console.log("n: " + n);
// add all nums squares
let tempNum = 0;
n.forEach(e => {
tempNum += (e**2);
console.log("adding ", e**2);
});
// change n to sum and reset tempNum
n = tempNum;
tempNum = 0;
// check conditions for true/false
if (n === 1) {
return true;
}
else if (n === 0|| n === 2 || n === 3 || n === 4) {
return false;
}
}
};
</code></pre>
| [
{
"answer_id": 74308927,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "n > 4"
},
{
"answer_id": 74309550,
"author": "Jared A Sutton",
"author_id": 4667746,
"author_profile": "https://Stackoverflow.com/users/4667746",
"pm_score": 2,
"selected": false,
"text": "n > 1"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18445495/"
] |
74,308,847 | <p>I have created a GitHub App for GitHub users to install on their personal accounts. I want it to use the GitHub API to create a new repository on their user account.</p>
<p>I've spent a couple days trying to follow the instructions in the official GitHub API Documentation, specifically how to <a href="https://docs.github.com/en/rest/repos/repos#create-a-repository-for-the-authenticated-user" rel="nofollow noreferrer">create a repository for the authenticated user</a>. I haven't had much success.</p>
<p>I can generate a JWT using my GitHub App's private key, and then use that to generate an access token on behalf of a GitHub App installation (an installation refers to any user or organization account that has installed the app).</p>
<p><strong>Request:</strong></p>
<pre><code>curl -i -X POST -H "Authorization: Bearer <<<JWT>>>" -H "Accept: application/vnd.github+json" https://api.github.com/app/installations/<<<Installation ID>>>/access_tokens
</code></pre>
<p><strong>Response:</strong></p>
<pre class="lang-json prettyprint-override"><code>{
"token": "ghs_zdhWvuGrhoi4UJsd1tX4Ggtae5f84jdu8tH3",
"expires_at": "2022-11-01T12:00:00Z",
"permissions": {
"administration": "write",
"metadata": "read"
},
"repository_selection": "all"
}
</code></pre>
<p>Based off the response, it appears that the scope of that access token should be able to create a new repository, since it says <code>administration: write</code> in the permissions body response JSON, but I could be mistaken on that assumption.</p>
<p>Can anyone help me with formatting my request to the GitHub API for creating the new repository for an installation of my GitHub App? According to the documentation I linked above, it should look something like this. Should I add the new access token that I generate?</p>
<pre><code>curl \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ghs_zdhWvuGrhoi4UJsd1tX4Ggtae5f84jdu8tH3" \
https://api.github.com/user/repos \
-d '{"name":"Repo-Created-From-GitHub-API"}'
</code></pre>
| [
{
"answer_id": 74308927,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "n > 4"
},
{
"answer_id": 74309550,
"author": "Jared A Sutton",
"author_id": 4667746,
"author_profile": "https://Stackoverflow.com/users/4667746",
"pm_score": 2,
"selected": false,
"text": "n > 1"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6105256/"
] |
74,308,861 | <p>I need to retrieve first and second post ID of current taxonomy page.</p>
<p>So for example when I'm on page mywebsite.com/tag/Gaming-laptop I have lists of laptops with tag "gaming laptop" i do need to get post ID of first and second laptop that was displayed by current taxonomy.</p>
<p>I was looking in wordpress documentation but I can't find related function</p>
| [
{
"answer_id": 74308927,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "n > 4"
},
{
"answer_id": 74309550,
"author": "Jared A Sutton",
"author_id": 4667746,
"author_profile": "https://Stackoverflow.com/users/4667746",
"pm_score": 2,
"selected": false,
"text": "n > 1"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6179361/"
] |
74,308,897 | <p>Given 3 int's "start", "end", and "factor", using a loop, count how many multiples of "factor" occur between start and end (inclusive).</p>
<p>I was given this question on a lab for my first programming class. I've been stuck on it for a few days now, and whenever I reach out for help with what I could be doing wrong, I'm given really vague "yep somethings definitely not right there" responses and I get stuck in an endless loop of trying to figure out what's wrong so I can google it.</p>
<p>I've tried a few different iterations of code, some have come close but still not right.</p>
<pre><code>public static int Test1(int start, int end, int factor)
{
for(int i = start; i <= end; i++)
{
int result = i % factor;
{
return i;
}
}
return 0;
}
</code></pre>
<pre><code>public static int Test1(int start, int end, int factor)
{
for(int i = 0; start <= end; i++)
{
if(start + factor <= end)
{
factor++;
continue;
}
else
{
return i;
}
}
return 0;
}
</code></pre>
<pre><code> public static int Test1(int start, int end, int factor)
{
for (int i = 0; start <= end; i++)
{
if (start + factor < end)
{
start+=factor;
}
else
{
return i;
}
}
return 0;
}
</code></pre>
<p>Expected result:
if (for example) start = 14; end = 35; factor = 3;
result should equal 7 multiples of 3, outputting 7.</p>
| [
{
"answer_id": 74308927,
"author": "Zach J.",
"author_id": 20276330,
"author_profile": "https://Stackoverflow.com/users/20276330",
"pm_score": 1,
"selected": false,
"text": "n > 4"
},
{
"answer_id": 74309550,
"author": "Jared A Sutton",
"author_id": 4667746,
"author_profile": "https://Stackoverflow.com/users/4667746",
"pm_score": 2,
"selected": false,
"text": "n > 1"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411373/"
] |
74,308,898 | <p>I have multiple rectangles on a x-y plane which are not rotated. How do I check if these rectangles intersect with a n-sized polygon?</p>
<p>I drew a picture here for clarity.
<a href="https://i.stack.imgur.com/76xQf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/76xQf.png" alt="enter image description here" /></a></p>
<p>In the image above, the purple shape is the polygon and I have a bunch of black rectangles.</p>
<p>I've looked at the line-sweeping methods however from what I understand that would only work if my polygon was also a non-rotated rectangle. So I'm kinda stumped as to what type of algorithm I could use here.
Thanks</p>
| [
{
"answer_id": 74314959,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "PIL Image"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12293384/"
] |
74,308,911 | <p>I am trying to create tuples from 2 input. For example, my program will ask how many people is there. Let's say I write 3. The program will ask profession of each one and his salary. After that, I want the program to display a tuple containing (profession, salary) is ascending order of salary.
What im trying to achieve:</p>
<p>#1-Number of person = Input:(Please write the number of person you want to analyze) (Lets say 3)</p>
<p>#2-Profession1:Doctor
Salary1:350000
Profession2:Teacher
Salary 2:60000
Profession3:CEO
Salary3:1000000</p>
<p>#3-Then I want my programm to display this in the console :
('Teacher',60000)
('Doctor',350000)
('CEO',1000000)</p>
<pre><code>number_person=input("Write the number of person: ")
for i in range(int(number_person)):
profession=input("Write profession")
salary=input("Write salary")
</code></pre>
| [
{
"answer_id": 74314959,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 0,
"selected": false,
"text": "PIL Image"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20402809/"
] |
74,308,950 | <p>I have the following 3 <em>MySQL</em> tables.<br>
I am storing bookings in the <code>bookings</code> table & the event dates and times in separate MySQL tables.</p>
<p>I want to have a MySQL query to list available times for a specific date.</p>
<p>So if I enter date of value <code>1</code> it'll show no times available but if I enter <code>2</code> it'll output <code>1 | 9:00</code>.</p>
<pre><code>INSERT INTO `bookings` (`id`, `email`, `date_requested`, `time_requested`) VALUES
(1, 'test@test.com', '1', '1'),
(2, 'test2@test.com', '1', '2'),
(3, 'test3@test.com', '2', '2');
INSERT INTO `bookings_dates` (`id`, `date`) VALUES
(1, '2022-11-05'),
(2, '2022-11-06'),
(3, '2022-11-07');
INSERT INTO `bookings_times` (`id`, `time`) VALUES
(1, '9:00'),
(2, '9:15');
</code></pre>
| [
{
"answer_id": 74309181,
"author": "Barmar",
"author_id": 1491895,
"author_profile": "https://Stackoverflow.com/users/1491895",
"pm_score": 2,
"selected": true,
"text": "NOT IN"
},
{
"answer_id": 74309293,
"author": "Ehab",
"author_id": 20342736,
"author_profile": "https://Stackoverflow.com/users/20342736",
"pm_score": -1,
"selected": false,
"text": "SELECT \n t.`id`, t.`time`\nFROM \n bookings_times AS t\n INNER JOIN bookings AS b ON b.time_requested = t.id\nWHERE\n b.date_requested = 1\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644978/"
] |
74,308,951 | <p>I am trying to create a function to parse a string based on multiple delimiters, but in a hierarchical format: i.e., try the first delimiter, then the second, then the third, etc.</p>
<p><a href="https://stackoverflow.com/questions/67574893/python-split-string-by-multiple-delimiters-following-a-hierarchy">This question</a> seemingly provides a solution, specifically linking <a href="https://tio.run/##XY5NCsIwEIX3nmLATQtVEHcFD@AZRKQ2ExOaJiEzpXr6OE0Lgm81fLyfiR82wZ8PxF0/OCTKWaEGis7yw@NcWR8bUOjsSHW7A5EOCRRYv9EVLrJ65RL5wUUJeUqFH0txpRoYu3e5L6e6eNERtgB7cCFE6MMYHTISzFYenBieCbth99d4k8q7ZK4afGBj/Ut6uTcoA5uFDS7DE@f8BQ" rel="nofollow noreferrer">this comment</a>.</p>
<pre><code># Split the team names, with a hierarchical delimiter
def split_new(inp, delims=['VS', '/ ' ,'/']):
# https://stackoverflow.com/questions/67574893/python-split-string-by-multiple-delimiters-following-a-hierarchy
for d in delims:
result = inp.split(d, maxsplit=1)
if len(result) == 2:
return result
else:
return [inp] # If nothing worked, return the input
test_strs = ['STACK/ OVERFLOW', 'STACK #11/00 VS OVERFLOW', 'STACK/OVERFLOW' ]
for ts in test_strs:
res = split_new(ts)
print(res)
"""
Output:
['STACK/ OVERFLOW']
['STACK #11/00 ', ' OVERFLOW']
['STACK/OVERFLOW']
Expected:
['STACK',' OVERFLOW']
['STACK #11/00 ', ' OVERFLOW']
['STACK', 'OVERFLOW']
"""
</code></pre>
<p>However, my results are not as expected. What am I missing?</p>
| [
{
"answer_id": 74309019,
"author": "VPfB",
"author_id": 5378816,
"author_profile": "https://Stackoverflow.com/users/5378816",
"pm_score": 3,
"selected": true,
"text": "for d in delims:\n result = inp.split(d, maxsplit=1)\n if len(result) == 2: \n return result\nreturn [inp] # If nothing worked, return the input \n"
},
{
"answer_id": 74309041,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "|"
},
{
"answer_id": 74309073,
"author": "sameer aggarwal",
"author_id": 20390437,
"author_profile": "https://Stackoverflow.com/users/20390437",
"pm_score": 0,
"selected": false,
"text": "def split_new(inp, delims=['VS', '/ ' ,'/']):\n for d in delims:\n result = inp.split(d, maxsplit=1)\n if len(result) == 2: \n return result\n \n return [inp] # If nothing worked, return the input \n\ntest_strs = ['STACK/ OVERFLOW', 'STACK #11/00 VS OVERFLOW', 'STACK/OVERFLOW' ]\n\nfor ts in test_strs:\n res = split_new(ts)\n print(res)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4876561/"
] |
74,308,962 | <p>I have a dataframe looking like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>user</th>
<th>user</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-08-01</td>
<td>Andy</td>
</tr>
<tr>
<td>2022-08-04</td>
<td>Mary</td>
</tr>
<tr>
<td>2022-08-05</td>
<td>Marc</td>
</tr>
<tr>
<td>2022-08-01</td>
<td>Frank</td>
</tr>
</tbody>
</table>
</div>
<p>Now I want to pick up that rows where Andy an Frank are Users at the same date. The date is the unknown part. It can be many more rows and many more dates where that two users are both in the result with different dates.
How can I do that with dataframe query?</p>
<p>I am new at python. Can anybody help me out?</p>
| [
{
"answer_id": 74309148,
"author": "Behzad Aslani Avilaq",
"author_id": 15083206,
"author_profile": "https://Stackoverflow.com/users/15083206",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({'date':['2022-08-01','2022-08-04','2022-08-05','2022-08-01'],\n 'user':['Andy','Mary','Marc','Frank']})\n"
},
{
"answer_id": 74309466,
"author": "Arne",
"author_id": 13014172,
"author_profile": "https://Stackoverflow.com/users/13014172",
"pm_score": 0,
"selected": false,
"text": "dates = set(df.date[df.user == 'Andy']).intersection(df.date[df.user == 'Frank'])\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74308962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19023397/"
] |
74,309,034 | <p>I am trying to further my VBA skillset by automating some reporting I am responsible for, but I am getting a little stuck and after a couple of weeks of trying and asking co-workers, I haven't been able to find a way to move forward. I've tried to sterilize the JSON as little as possible, but enough so i don't get fired, haha. Please let me know if any additional information is needed.</p>
<p>I am getting a JSON response from an API endpoint, and would like to extract the values sections of the responses into a string variable.</p>
<p>This is the JSON response (stored in variable <code>strResult</code>):
<code>{"totalCount":3,"nextPageKey":null,"resolution":"4h","result":[{"metricId":"builtin:service.keyRequest.count.total:names","dataPointCountRatio":3.6E-6,"dimensionCountRatio":3.0E-5,"data":[{"dimensions":["IMPORTANT_ARL_#1","SERVICE_METHOD-HEX#1"],"dimensionMap":{"dt.entity.service_method":"SERVICE_METHOD-HEX#1","dt.entity.service_method.name":"IMPORTANT_ARL_#1"},"timestamps":[1667289600000,1667304000000,1667318400000,1667332800000,1667347200000,1667361600000],"values":[null,1,30,26,null,null]},{"dimensions":["IMPORTANT_ARL_#2","SERVICE_METHOD-HEX#2"],"dimensionMap":{"dt.entity.service_method":"SERVICE_METHOD-HEX#2","dt.entity.service_method.name":"IMPORTANT_ARL_#2"},"timestamps":[1667289600000,1667304000000,1667318400000,1667332800000,1667347200000,1667361600000],"values":[60,371,1764,1964,1707,1036]},{"dimensions":["IMPORTANT_ARL_#3","SERVICE_METHOD-HEX#3"],"dimensionMap":{"dt.entity.service_method":"SERVICE_METHOD-HEX#3","dt.entity.service_method.name":"IMPORTANT_ARL_#3"},"timestamps":[1667289600000,1667304000000,1667318400000,1667332800000,1667347200000,1667361600000],"values":[9,6,1077,1171,462,null]}]}]}</code></p>
<p>Here's the RegEx I wrote using regex101.com
<code>(?<=values\"\:\[)(.+?)(?=\])</code></p>
<p>I realize the double-quote is a problem, so I have a string variable (JSON3) set to this string with Chr(34) replacing the double quote</p>
<p><code>JSON3 = "(?<=values\" & Chr(34) & "\:\[)(.+?)(?=\])"</code></p>
<p>debug.print json3 will show the correct string needed.</p>
<p>I've tried using some other <a href="https://stackoverflow.com/questions/8146485/returning-a-regex-match-in-vba-excel">solutions I've found here</a>, but whenever I pass <code>strResult</code> as the string, and <code>JSON3</code> as the pattern, the functions return an empty set.</p>
<p>I have also tried using <a href="https://github.com/VBA-tools/VBA-JSON" rel="nofollow noreferrer">VBA-JSON</a> to parse the JSON into an object that I could extract the data from, but I am getting zero values from that no matter what I try there either. I followed the ReadMe, but am not sure how to pull the JSON from a variable, as the readme example pulls it from a file.</p>
<p>In a perfect world, I would like to be able to store all of the keys/values in an object that I can extract the data from. This JSON is just one of many queries I am submitting to the API, so it would be ideal to have something that could be scaled for other uses as well.</p>
<p>Thanks for reading through my long-winded explanation. I apologize if this is a lot to ask, I feel like I'm close to where I want to be, but I could be very wrong too. Again, if any additional information is needed, I'll try my best to share it as soon as I can if possible. Thanks in advance.</p>
| [
{
"answer_id": 74309148,
"author": "Behzad Aslani Avilaq",
"author_id": 15083206,
"author_profile": "https://Stackoverflow.com/users/15083206",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({'date':['2022-08-01','2022-08-04','2022-08-05','2022-08-01'],\n 'user':['Andy','Mary','Marc','Frank']})\n"
},
{
"answer_id": 74309466,
"author": "Arne",
"author_id": 13014172,
"author_profile": "https://Stackoverflow.com/users/13014172",
"pm_score": 0,
"selected": false,
"text": "dates = set(df.date[df.user == 'Andy']).intersection(df.date[df.user == 'Frank'])\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19582239/"
] |
74,309,079 | <p>I'm currently doing self project inventory app and trying to implement filter and search.</p>
<p>what I've done</p>
<p>#views.py</p>
<pre><code>from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
class ListInventories(generics.ListAPIView):
serializer_class = Inventory
filter_backends = [filters.SearchFilter]
search_fields = ['name']
filter_backends = [DjangoFilterBackend]
filterset_fields = ['name', 'stock']
def get(self, request):
inventories = Inventory.objects.all()
serializer = InventorySerializers(inventories, many=True)
return Response({'inventories': serializer.data})
class InventoryDetails(APIView):
def get(self, request, pk):
inventories = Inventory.objects.get(id=pk)
serializer = InventorySerializers(inventories)
return Response({'inventory': serializer.data})
</code></pre>
<p>in settings.py</p>
<pre><code>INSTALLED_APPS = [
...
'django_filters',
...
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
</code></pre>
<p>in url:</p>
<pre><code>http://127.0.0.1:8000/api/inventory?name=para
</code></pre>
<p>I tried <code>?search=para</code> and <code>?search=anynonsense</code> . and the DRF would always return everything.</p>
<p>just for the sake of clarification here is the screenshot(the total of item is just 3 for now, but even then filter/search should work):</p>
<p><a href="https://i.stack.imgur.com/Qy6WH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qy6WH.png" alt="DRF" /></a></p>
<p>I expect the filter/search to function at least on a minimal level. What do I do to make this right?</p>
| [
{
"answer_id": 74309148,
"author": "Behzad Aslani Avilaq",
"author_id": 15083206,
"author_profile": "https://Stackoverflow.com/users/15083206",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({'date':['2022-08-01','2022-08-04','2022-08-05','2022-08-01'],\n 'user':['Andy','Mary','Marc','Frank']})\n"
},
{
"answer_id": 74309466,
"author": "Arne",
"author_id": 13014172,
"author_profile": "https://Stackoverflow.com/users/13014172",
"pm_score": 0,
"selected": false,
"text": "dates = set(df.date[df.user == 'Andy']).intersection(df.date[df.user == 'Frank'])\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18489452/"
] |
74,309,088 | <p>I believe the following is a relatively common pattern (the exact types used are not important, they're just for example):</p>
<pre><code>std::vector<std::string> manufactureVector(int param1, const std::string& param2) {
std::vector<std::string> returnValue;
// do some calculation with param1 and param2 to fill in the vector
return returnValue;
}
</code></pre>
<p>However, the return type of manufactureVector is mentioned twice, with all of the drawbacks of that sort of redundancy, e.g. any future change has to be made identically in two places, etc. What's the best way to remove this redundancy? I am aware of:</p>
<ol>
<li>Use a typedef. This seems cumbersome if the return type is a one-off, so that the typedef would not be used anywhere else; at the very least, such a typedef adds a line of code.</li>
<li>I believe C++20 (and possibly earlier) allows you to change the <em>first</em> occurrence of the type (in the function declaration) to <code>auto</code> and it will be inferred from what is actually returned. But that doesn't seem to work for declaring the function in a header (where there is no body to infer from) and then defining it in another source file. (Perhaps this is among the reasons to switch to modules?) Moreover, to my eyes at least it's harder to see what the return type of <code>manufactureVector</code> actually is if you use <code>auto</code> as its return type: I have to find the return statement, and then figure out what the type of that expression is.</li>
</ol>
<p>Are there other possibly better alternatives to consider? In particular is there any reasonably brief "Incantation" such that</p>
<pre><code>MyComplicatedType foo(int p, double q) {
Incantation returnValue;
// Here returnValue is a variable of type MyComplicatedType, whatever that type was
...
}
</code></pre>
<p>Ideally, such an Incantation wouldn't have to explicitly use the function name "foo" either, as that would substitute a different (small) bit of redundancy.</p>
<p>(Quite) a while back, GCC had named return values like</p>
<pre><code>MyComplicatedType foo(int* ptr, char c) return returnValue {
// here returnValue is a newly default-constructed variable
// of type MyComplicatedType
...
// And in fact having declared the return variable this way,
// you didn't even need to have the return statement at the end.
}
</code></pre>
<p>which was exactly the ticket here, in my view, but unfortunately that has been left behind in the dustbin of C++ history. Is there a modern equivalent or substitute? (I am perfectly happy with C++20-only solutions.)</p>
| [
{
"answer_id": 74309999,
"author": "apple apple",
"author_id": 5980430,
"author_profile": "https://Stackoverflow.com/users/5980430",
"pm_score": 2,
"selected": false,
"text": "template <auto F>\nusing return_type_of = decltype(std::function{F})::result_type;\n\nint foo(int p){\n return_type_of<foo> x;\n return x;\n}\n"
},
{
"answer_id": 74310074,
"author": "Sam Varshavchik",
"author_id": 3943312,
"author_profile": "https://Stackoverflow.com/users/3943312",
"pm_score": 0,
"selected": false,
"text": "std::vector<std::string>::iterator b, e;\n\nfor (b=returnValue.begin(), e=returnValue.end(); b != e; ++b)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5583443/"
] |
74,309,097 | <p>In the following case, I just want to count films of each category with a length plus 5 or minus 5 minutes (respective the current length LEN)?
How can I add this condition to the statement after PARTITION BY?</p>
<pre><code>SELECT film_id, title, category_name, length AS LEN,
Count(film_id) OVER (PARTITION BY category_name)
FROM film INNER JOIN film_category USING (film_id)
INNER JOIN category USING (category_id)
ORDER BY name, length;
</code></pre>
<p>I've tried with RANGE but it does not have the effect I want.</p>
<pre><code>SELECT film_id, title, category_name, length AS LEN,
Count(film_id) OVER (PARTITION BY category_name)
FROM film INNER JOIN film_category USING (film_id)
INNER JOIN category USING (category_id)
ORDER BY name, length;
</code></pre>
| [
{
"answer_id": 74310249,
"author": "Chris Maurer",
"author_id": 5440883,
"author_profile": "https://Stackoverflow.com/users/5440883",
"pm_score": 0,
"selected": false,
"text": "With basequery AS (\n SELECT film_id, title, category_name, length AS LEN, \n FROM film INNER JOIN film_category USING (film_id) \n INNER JOIN category USING (category_id)\n)\nSelect film_id, title, category_name, count(*) as nbr_similar\nFrom basequery A Inner Join basequery B\n On A.category_name=B.category_name\n AND B.LEN between A.LEN-5 and A.LEN+5\nGroup By film_id, title, category_name\nOrder By A.category_name, A.Len\n"
},
{
"answer_id": 74310459,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "RANGE"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20197912/"
] |
74,309,107 | <p>I am modifying the sample at <a href="https://github.com/cdk-patterns/serverless/tree/main/the-eventbridge-etl/typescript" rel="nofollow noreferrer">https://github.com/cdk-patterns/serverless/tree/main/the-eventbridge-etl/typescript</a> as I want to add a dashboard widget to my CloudFormation Stack that shows the Fargate vCPU usage. I have been able to upgrade the app to use CDK v2, and deployment/functionality has been confirmed. However, I cannot get the vCPU widget in the dashboard to show any data.</p>
<p>If I configure the widget manually, from within AWS CloudWatch's Source field, the query looks as follows:</p>
<pre><code>{
"metrics": [
[ { "expression": "SELECT COUNT(ResourceCount) FROM SCHEMA(\"AWS/Usage\", Class,Resource,Service,Type) WHERE Service = 'Fargate' AND Resource = 'vCPU'", "label": "Query1", "id": "q1" } ],
[ "AWS/Usage", "ResourceCount", "Service", "Fargate", "Type", "Resource", { "id": "m1" } ]
],
"view": "timeSeries",
"title": "ExtractECSJob",
"region": "us-west-2",
"timezone": "Local",
"stat": "Sum",
"period": 300
}
</code></pre>
<p>However, when I attempt to use CDK, with the following TypeScript code:</p>
<pre><code> const extractECSWidget = new GraphWidget({
title: "ExtractECSJob",
left: [
new Metric({
namespace: "AWS/Usage",
metricName: "ResourceCount",
statistic: "Sum",
period: Duration.seconds(300),
dimensionsMap: {
"Service": "Fargate",
"Type": "Resource",
"Resource": "vCPU"
}
})
]
});
</code></pre>
<p>This does not translate to the above, and no information is shown in this widget. The new source looks as follows:</p>
<pre><code>{
"view": "timeSeries",
"title": "ExtractECSJob",
"region": "us-west-2",
"metrics": [
[ "AWS/Usage", "ResourceCount", "Resource", "vCPU", "Service", "Fargate", "Type", "Resource", { "stat": "Sum" } ]
],
"period": 300
}
</code></pre>
<p>How do I map the above metrics source definition to the CDK source construct?</p>
<p>I tried using MathExpression but with the following:</p>
<pre><code> let metrics = new MathExpression({
expression: "SELECT COUNT('metricName') FROM SCHEMA('\"AWS/Usage\"', 'Class','Resource','Service','Type') WHERE Service = 'Fargate' AND Resource = 'vCPU'",
usingMetrics: {}
})
const extractECSWidget = new GraphWidget({
title: "ExtractECSJob",
left: [
metrics
]
});
</code></pre>
<p>I get the warning during <code>cdk diff</code>:</p>
<pre><code>[Warning at /EventbridgeEtlStack/EventBridgeETLDashboard] Math expression 'SELECT COUNT(metricName) FROM SCHEMA($namespace, Class,Resource,Service,Type) WHERE Service = 'Fargate' AND Resource = 'vCPU'' references unknown identifiers: metricName, namespace, lass, esource, ervice, ype, ervice, argate, esource, vCPU. Please add them to the 'usingMetrics' map.
</code></pre>
<p>What should I put in the usingMetrics map? Any help is appreciated.</p>
| [
{
"answer_id": 74310249,
"author": "Chris Maurer",
"author_id": 5440883,
"author_profile": "https://Stackoverflow.com/users/5440883",
"pm_score": 0,
"selected": false,
"text": "With basequery AS (\n SELECT film_id, title, category_name, length AS LEN, \n FROM film INNER JOIN film_category USING (film_id) \n INNER JOIN category USING (category_id)\n)\nSelect film_id, title, category_name, count(*) as nbr_similar\nFrom basequery A Inner Join basequery B\n On A.category_name=B.category_name\n AND B.LEN between A.LEN-5 and A.LEN+5\nGroup By film_id, title, category_name\nOrder By A.category_name, A.Len\n"
},
{
"answer_id": 74310459,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "RANGE"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4332644/"
] |
74,309,110 | <p>I created a repository, on Artifactory, which includes a zip containing 2 folders.
<a href="https://artifactory.healthcareit.net:443/artifactory/pi-generic-local/paymentintegrity-airflow-lib-plugins/paymentintegrity-airflow-libs-plugins-202211031330.zip" rel="nofollow noreferrer">https://artifactory.healthcareit.net:443/artifactory/pi-generic-local/paymentintegrity-airflow-lib-plugins/paymentintegrity-airflow-libs-plugins-202211031330.zip</a></p>
<p>Is there a way to download that zip and extract the directories during a pip install? Basically, the developer just runs a pip install and gets the directories where needed.</p>
<p>I'm not looking for something in the [scripts] section since installing these directories would be the only thing currently needed in the Pipfile (its a weird project). Is this possible?</p>
| [
{
"answer_id": 74310249,
"author": "Chris Maurer",
"author_id": 5440883,
"author_profile": "https://Stackoverflow.com/users/5440883",
"pm_score": 0,
"selected": false,
"text": "With basequery AS (\n SELECT film_id, title, category_name, length AS LEN, \n FROM film INNER JOIN film_category USING (film_id) \n INNER JOIN category USING (category_id)\n)\nSelect film_id, title, category_name, count(*) as nbr_similar\nFrom basequery A Inner Join basequery B\n On A.category_name=B.category_name\n AND B.LEN between A.LEN-5 and A.LEN+5\nGroup By film_id, title, category_name\nOrder By A.category_name, A.Len\n"
},
{
"answer_id": 74310459,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 2,
"selected": true,
"text": "RANGE"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16262955/"
] |
74,309,167 | <p>I have been browsing through similar questions but have found nothing that would fit the bill. I have three input / select fields and a working JS function to calculate the number. All I need now is to display it automatically upon the selection and number input.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Calculate() {
var f1 = document.getElementById("item");
var field1 = parseInt(f1.options[f1.selectedIndex].value);
var f2 = document.getElementById("level");
var field2 = parseInt(f2.options[f2.selectedIndex].value);
var f3 = document.getElementById("number");
var field3 = parseInt(f3.value);
(field1 * field2 * field3) / 100;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="item">Choose item:</label>
<select id="item" name="item" form="qForm" required>
<option value="empty"></option>
<option value="250">item1</option>
<option value="250">item2</option>
<option value="300">item3</option>
</select>
</br>
<label for="level">Choose level:</label>
<select id="level" name="level" form="qForm" required>
<option value="empty"></option>
<option value="100">lvl1</option>
<option value="120">lvl2</option>
<option value="140">lvl3</option>
</select>
</br>
<label for="number">Duration (hours):</label>
<input id="number" type="number" name="number" min="10" required>
</br>
<label for="price">Preliminary price (EUR):</label>
<input type="number" id="price" name="price" form="qForm" readonly value="Calculate()"></code></pre>
</div>
</div>
</p>
<p>Can you help me, please, to find a way to display the JS function in the "number" input field automatically?
Thanks.</p>
<p>I tried the JS function with a button and <code>alert()</code> and it works just fine. However, I cannot make it appear in the input field as I hoped I would by assigning its value to the function.</p>
| [
{
"answer_id": 74309272,
"author": "Yannick Durden",
"author_id": 9509765,
"author_profile": "https://Stackoverflow.com/users/9509765",
"pm_score": 0,
"selected": false,
"text": "let foo = document.getElementById(\"price\");\nlet price = Calculate();\nfoo.value = price;\n"
},
{
"answer_id": 74309338,
"author": "Evgeni Dikerman",
"author_id": 1761692,
"author_profile": "https://Stackoverflow.com/users/1761692",
"pm_score": 2,
"selected": true,
"text": "change"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19887229/"
] |
74,309,179 | <p>The following code is intended to update an emp record. However, if Zip is null, the data does not get updated.</p>
<p>I did not write this code, and I am not sure of the original intention behind using this type of syntax and I don't see a benefit to it.</p>
<p>Example: <code>zip = iif(zip<>@zip,@zip,zip)</code></p>
<p>I would just write this: <code>zip = @zip</code></p>
<p>Am I missing anything?</p>
<p>The intention is to update the zip field as long as the @zip parameter is not null. The problem is that it does not get updated with the zip field currently is null.</p>
<pre><code>UPDATE emp
SET first_name = iif(first_name <> @first_name,@first_name,first_name)
,last_name = iif(last_name <> @last_name, @last_name, last_name)
,dob = iif(dob <> @dob,@dob,dob)
,social_security_num = iif(social_security_num<>@social_security_num,@social_security_num,social_security_num)
,dl_num = iif(dl_num<>@dl_num,@dl_num,dl_num)
,dl_state = iif(dl_state<>@dl_state,@dl_state,dl_state)
,gender = iif(gender<>@gender,@gender,gender)
,address1 = iif(address1<>@address1,@address1,address1)
,address2 = iif(address2<>@address2,@address2,address2)
,city = iif(city<>@city,@city,city)
,zip = iif(zip<>@zip,@zip,zip)
,STATE = iif(state<>@state,@state,state)
,primary_phone = iif(primary_phone<>@primary_phone,@primary_phone,primary_phone)
,emergency_contact = iif(emergency_contact<>@emergency_contact,@emergency_contact,emergency_contact)
,secondary_phone = iif(secondary_phone<>@secondary_phone,@secondary_phone,secondary_phone)
,emergency_contact_phone = iif(emergency_contact_phone<>@emergency_contact_phone,@emergency_contact_phone,emergency_contact_phone)
,emp_pay_type_id = @emp_pay_type_id
WHERE emp_id = @emp_id
</code></pre>
| [
{
"answer_id": 74309234,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (zip NVARCHAR(10))\nINSERT INTO @table (zip) VALUES ('90210-1234')\n\nDECLARE @zip NVARCHAR(10)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = IIF(@zip<>zip,@zip,zip)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n\nSET @zip = '90210-1234'\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n"
},
{
"answer_id": 74309238,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 2,
"selected": true,
"text": "null"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/425823/"
] |
74,309,185 | <p>I'm trying to create a neon-effect w/ a source image. I have included three images, the source, my current attempt & a target. The program takes the image, finds the white-edges, & calculates the distance from each pixel to the nearest white-edge (these parts both work fine); from there, I am struggling to find the right saturation and value parameters to create the neon-glow.</p>
<p>From the target image, what I need to happen is basically for the saturation to be 0 on a white-edge, then to dramatically increase the further away it gets from an edge; for value, I need it to be 1 on a white-edge, then to dramatically decrease. I can't figure out the best way to manipulate distance_image (which holds each pixel's distance from the nearest white-edge) such as to achieve these two results with saturation and value.</p>
<pre><code>from PIL import Image
import cv2
import numpy as np
from scipy.ndimage import binary_erosion
from scipy.spatial import KDTree
def find_closest_distance(img):
white_pixel_points = np.array(np.where(img))
tree = KDTree(white_pixel_points.T)
img_meshgrid = np.array(np.meshgrid(np.arange(img.shape[0]),
np.arange(img.shape[1]))).T
distances, _ = tree.query(img_meshgrid)
return distances
def find_edges(img):
img_np = np.array(img)
kernel = np.ones((3,3))
return img_np - binary_erosion(img_np, kernel)*255
img = Image.open('a.png').convert('L')
edge_image = find_edges(img)
distance_image = find_closest_distance(edge_image)
max_dist = np.max(distance_image)
distance_image = distance_image / max_dist
hue = np.full(distance_image.shape, 0.44*180)
saturation = distance_image * 255
value = np.power(distance_image, 0.2)
value = 255 * (1 - value**2)
new_tups = np.dstack((hue, saturation, value)).astype('uint8')
new_tups = cv2.cvtColor(new_tups, cv2.COLOR_HSV2BGR)
new_img = Image.fromarray(new_tups, 'RGB').save('out.png')
</code></pre>
<p>The following images show the source data (left), the current result (middle), and the desired result (right).</p>
<p><a href="https://i.stack.imgur.com/MhUQZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MhUQZ.png" alt="source" /></a>
<a href="https://i.stack.imgur.com/Kenzn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kenzn.png" alt="current" /></a>
<a href="https://i.stack.imgur.com/9PLoS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9PLoS.png" alt="target" /></a></p>
| [
{
"answer_id": 74309234,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (zip NVARCHAR(10))\nINSERT INTO @table (zip) VALUES ('90210-1234')\n\nDECLARE @zip NVARCHAR(10)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = IIF(@zip<>zip,@zip,zip)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n\nSET @zip = '90210-1234'\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n"
},
{
"answer_id": 74309238,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 2,
"selected": true,
"text": "null"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18615293/"
] |
74,309,188 | <p>I am writing a program where I need to check if an object matches a certain type. The way it's written so far, you need to compare the character-array of the object with the character-array of the category you are looking for.</p>
<p>I am using <strong>strcmp</strong> to do this, for the following code let's say that Object->Name returns a character-array equal to "TypeA" ...</p>
<pre><code>char type[] = "TypeA";
if (0 == strcmp (Object->Name, type))
{
printf("Match!");
}
</code></pre>
<p>^This has worked well so far...</p>
<p>The only problem is that sometimes the character-array from Object->Name will have a 9 letter name in front of it. So Object->Name could be: "Chocolate_TypeA" or "FireTruck_TypeA"</p>
<p>I need to compare the last five characters with the value of <strong>type</strong>. I'm not sure how to do it.</p>
<p>My first idea was to use <strong>strncmp</strong> and specifying an index</p>
<pre><code>char type[] = "TypeA";
if (0 == strncmp (type, Object->Name + 10))
{
printf("Match!");
}
</code></pre>
<p>This works if the program only receives 15 character character-arrays (such as "Firetruck_TypeA"), but it doesn't... if Object->Name gives "TypeA" then I get a segmentation fault.</p>
<p>What is an easy way to grab the last 5 characters of any character-array and compare them to <strong>type</strong>?</p>
| [
{
"answer_id": 74309234,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (zip NVARCHAR(10))\nINSERT INTO @table (zip) VALUES ('90210-1234')\n\nDECLARE @zip NVARCHAR(10)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = IIF(@zip<>zip,@zip,zip)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n\nSET @zip = '90210-1234'\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n"
},
{
"answer_id": 74309238,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 2,
"selected": true,
"text": "null"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6454589/"
] |
74,309,212 | <p>Please, Can somebody help me. I need to do cross-platform app based on flutter as frontend, and there is problem with backend. I know python very well and I want use it for my app as backend. Is it possible to use python(backend) for flutter(frontend)?</p>
<p>And I just started to learn flutter and don't knowing the Dart language.</p>
| [
{
"answer_id": 74309234,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @table TABLE (zip NVARCHAR(10))\nINSERT INTO @table (zip) VALUES ('90210-1234')\n\nDECLARE @zip NVARCHAR(10)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = IIF(@zip<>zip,@zip,zip)\n\nSELECT * \n FROM @table\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n\nSET @zip = '90210-1234'\n\nUPDATE @table\n SET zip = @zip\n\nSELECT * \n FROM @table\n"
},
{
"answer_id": 74309238,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 2,
"selected": true,
"text": "null"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411120/"
] |
74,309,308 | <p>I have a table that contains an item ID, the date and the price. All items show their price for each day, but I want only to select the items that have not had their price change, and to show the days without change.</p>
<p>An example of the table is</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>Price</th>
<th>Day</th>
<th>Month</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr>
<td>asdf</td>
<td>10</td>
<td>03</td>
<td>11</td>
<td>2022</td>
</tr>
<tr>
<td>asdr1</td>
<td>8</td>
<td>03</td>
<td>11</td>
<td>2022</td>
</tr>
<tr>
<td>asdf</td>
<td>10</td>
<td>02</td>
<td>11</td>
<td>2022</td>
</tr>
<tr>
<td>asdr1</td>
<td>8</td>
<td>02</td>
<td>11</td>
<td>2022</td>
</tr>
<tr>
<td>asdf</td>
<td>10</td>
<td>01</td>
<td>11</td>
<td>2022</td>
</tr>
<tr>
<td>asdr1</td>
<td>7</td>
<td>01</td>
<td>11</td>
<td>2022</td>
</tr>
<tr>
<td>asdf</td>
<td>9</td>
<td>31</td>
<td>10</td>
<td>2022</td>
</tr>
<tr>
<td>asdr1</td>
<td>8</td>
<td>31</td>
<td>10</td>
<td>2022</td>
</tr>
<tr>
<td>asdf</td>
<td>8</td>
<td>31</td>
<td>10</td>
<td>2022</td>
</tr>
<tr>
<td>asdr1</td>
<td>8</td>
<td>31</td>
<td>10</td>
<td>2022</td>
</tr>
</tbody>
</table>
</div>
<p>The output I want is:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Date</th>
<th>id</th>
<th>Last_Price</th>
<th>First_Price_Appearance</th>
<th>DaysWOchange</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-11-03</td>
<td>asdf</td>
<td>10</td>
<td>2022-11-01</td>
<td>2</td>
</tr>
<tr>
<td>2022-11-03</td>
<td>asdr1</td>
<td>8</td>
<td>2022-11-02</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>The solutions needs to run quickly, so how are some efficency intensive ways to solve this, considering that the table has millions of rows, and there are items that have not changed their price in years.</p>
<p>The issue for efficiency comes because for each id, I would need to loop the entire table, looking for the first match in which the price has changed, and repeat this for thousands of items.</p>
<p>I am attempting to calculate the difference between the current last price, and all the history, but these becomes slow to process, and may take several minutes to calculate for all of history.
The main concern for this problem is efficiency.</p>
| [
{
"answer_id": 74309452,
"author": "HKTE",
"author_id": 12412262,
"author_profile": "https://Stackoverflow.com/users/12412262",
"pm_score": 0,
"selected": false,
"text": "select id, date, price\nfrom (select t.*,\n max(case when price <> lag_price then date end) over (partition by id) as price_change_date\n from (select t.*, lag(price) over (partition by id order by date) as lag_price\n from t\n ) t\n ) t\nwhere price_change_date is null;\n"
},
{
"answer_id": 74309491,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 1,
"selected": false,
"text": "DECLARE @table TABLE (id NVARCHAR(5), Price INT, Date DATE)\nINSERT INTO @table (id, Price, Date) VALUES\n('asdf', 10, '2022-10-20'), \n('asdr1', 8, '2022-10-15'),\n('asdf', 10, '2022-11-03'), \n('asdr1', 8, '2022-11-02'), \n('asdf', 10, '2022-11-02'), \n('asdr1', 8, '2022-11-02'), \n('asdf', 10, '2022-11-01'), \n('asdr1', 7, '2022-11-01'), \n('asdf', 9, '2022-10-31'), \n('asdr1', 8, '2022-10-31'), \n('asdf', 8, '2022-10-31'), \n('asdr1', 8, '2022-10-31')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411505/"
] |
74,309,314 | <p>I am not sure where to apply the count to my Badge Component. The displayValue should have the count but I am not sure how to apply it.</p>
<p><strong>EDITED :</strong>
Counter is applied now but when I decrement the counter , after 0 , it should disappear. I have the logic for this and it works only when I apply badgeContent ="0" in App.tsx and not when the badge is 0 by clicking the decrement button.</p>
<p>I tried it on codesandbox. Here is the link. Please help. Thanks!</p>
<p><a href="https://codesandbox.io/s/badgecomponent-ljdq25?file=/src/components/Badge.tsx:468-480" rel="nofollow noreferrer">https://codesandbox.io/s/badgecomponent-ljdq25?file=/src/components/Badge.tsx:468-480</a></p>
| [
{
"answer_id": 74309452,
"author": "HKTE",
"author_id": 12412262,
"author_profile": "https://Stackoverflow.com/users/12412262",
"pm_score": 0,
"selected": false,
"text": "select id, date, price\nfrom (select t.*,\n max(case when price <> lag_price then date end) over (partition by id) as price_change_date\n from (select t.*, lag(price) over (partition by id order by date) as lag_price\n from t\n ) t\n ) t\nwhere price_change_date is null;\n"
},
{
"answer_id": 74309491,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 1,
"selected": false,
"text": "DECLARE @table TABLE (id NVARCHAR(5), Price INT, Date DATE)\nINSERT INTO @table (id, Price, Date) VALUES\n('asdf', 10, '2022-10-20'), \n('asdr1', 8, '2022-10-15'),\n('asdf', 10, '2022-11-03'), \n('asdr1', 8, '2022-11-02'), \n('asdf', 10, '2022-11-02'), \n('asdr1', 8, '2022-11-02'), \n('asdf', 10, '2022-11-01'), \n('asdr1', 7, '2022-11-01'), \n('asdf', 9, '2022-10-31'), \n('asdr1', 8, '2022-10-31'), \n('asdf', 8, '2022-10-31'), \n('asdr1', 8, '2022-10-31')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14410605/"
] |
74,309,331 | <p>When performing a curl with --ntlm, what is happening between the WWW-Authenticate header being sent back, and then then the second NTLM Authorization header being sent to finally return a 200?</p>
<blockquote>
<p>Authorization: NTLM xxxxxxxx</p>
</blockquote>
<p>< HTTP/1.1 401 Unauthorized
< WWW-Authenticate: NTLM xxxxxxxx</p>
<blockquote>
<p>Authorization: NTLM xxxxxxxxxx</p>
</blockquote>
<p>< HTTP/1.1 200 OK</p>
<p>I want to be able to take the first NTLM header (this stays constant with the username/password I believe), and build it into a script, take the returned header, and send the second NTLM one back to authenticate. What I don't understand is how the challenge (WWW-Authenticate header?) is taken in, and then sent back as another NTLM header.</p>
<p>I have tried using the WWW-Auth header as the second NTLM-Auth header, I didnt expect it to work but tried.</p>
| [
{
"answer_id": 74310522,
"author": "Iridium",
"author_id": 381588,
"author_profile": "https://Stackoverflow.com/users/381588",
"pm_score": 2,
"selected": false,
"text": "WWW-Authenticate: NTLM"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384109/"
] |
74,309,367 | <p>In my project I need to update member's user attribute if it's empty.</p>
<p>I have this code in the model:</p>
<pre class="lang-php prettyprint-override"><code>class Member extends Model
{
public static function boot()
{
parent::boot();
self::saving(function ($model) {
if (empty($model->user)) {
$model->user = $model->email;
}
});
}
protected $fillable = [
'name',
'email',
'user',
'password',
// ...
];
// ...
}
</code></pre>
<p>This is the migration for the model:</p>
<pre class="lang-php prettyprint-override"><code>Schema::create('members', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('user');
$table->string('password');
// ...
});
</code></pre>
<p>And I try to test it like this:</p>
<pre class="lang-php prettyprint-override"><code> /** @test */
public function shouldSetUserToEmailIfUserNotSet()
{
$instance = $this->model::factory([
'user' => null
])->create();
$model = $this->model::all()->first();
$this->assertEquals($model->user, $model->email);
}
</code></pre>
<p>So the user field is required in the database. And this is the test result:</p>
<pre><code>Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 19
NOT NULL constraint failed: members.user (SQL: insert into "members" ("password", "name",
"email", "user", ...
</code></pre>
<p>And this error comes from the <code>->create();</code> line in the test.</p>
<p>So how should I set the <code>user</code> attribute on the model before save if it's not set?</p>
| [
{
"answer_id": 74309525,
"author": "Ramil Huseynov",
"author_id": 6711823,
"author_profile": "https://Stackoverflow.com/users/6711823",
"pm_score": 1,
"selected": false,
"text": "static::saving(function (self $model) {\n if (empty($model->user)) {\n $model->forceFill(['user' => $model->email]);\n }\n});\n"
},
{
"answer_id": 74311579,
"author": "Ali Raza",
"author_id": 6873407,
"author_profile": "https://Stackoverflow.com/users/6873407",
"pm_score": 0,
"selected": false,
"text": "public function setUserAttribute($value)\n{\n if(empty($value){\n $this->attributes['user'] = $this->attributes['email'];\n }\n}\n\n\n [1]: https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator\n"
},
{
"answer_id": 74312960,
"author": "Ismoil Shifoev",
"author_id": 2801588,
"author_profile": "https://Stackoverflow.com/users/2801588",
"pm_score": 0,
"selected": false,
"text": "updating"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972828/"
] |
74,309,412 | <p>For example, I have a string <code>/something an-arg=some-value another-arg=another-value</code>.</p>
<p>What would be the most straightforward way to extract <code>an-arg</code>'s value to a variable and <code>another-arg</code>'s value to another variable?</p>
<p>To better exemplify, this is what I need to happen:</p>
<pre><code>STRING="/something an-arg=some-value another-arg=another-value"
AN_ARG=... # <-- do some magic here to extract an-arg's value
ANOTHER_ARG=... # <-- do some magic here to extract another-arg's value
echo $AN_ARG # should print `some-value`
echo $ANOTHER_ARG # should print `another-value`
</code></pre>
<p>So I was looking for a simple/straightforward way to do this, I tried:</p>
<pre><code>ARG_NAME="an-arg="
AN_ARG=${STRING#*$ARG_NAME}
</code></pre>
<p>But the problem with this solution is that it will print everything that comes after <code>an-arg</code>, including the second argument's name and its value, eg <code>some-value another-arg=another-value</code>.</p>
| [
{
"answer_id": 74309535,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 3,
"selected": true,
"text": "#!/usr/bin/env bash\n# ^^^^- specifically, bash 4.0 or newer; NOT /bin/sh\n\ndeclare -A vars=( )\n\nre='^([^=]* )?([[:alpha:]_-][[:alnum:]_-]+)=([^[:space:]]+)( (.*))?$'\nstring=\"/something an-arg=some-value another-arg=another-value third-arg=three\"\nwhile [[ $string =~ $re ]]; do : \"${BASH_REMATCH[@]}\"\n string=${BASH_REMATCH[5]}\n vars[${BASH_REMATCH[2]}]=${BASH_REMATCH[3]}\ndone\n\ndeclare -p vars # print the variables we extracted\n"
},
{
"answer_id": 74309866,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "-"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4734782/"
] |
74,309,446 | <p>I'm currently using Vue, nuxt3, and javascript for a front project.<br />
My goal right now is to create a function that gets the distance between to city given in the parameters. So I wanted to use the google matrix API.</p>
<p>This is what I've tried to do :</p>
<pre class="lang-js prettyprint-override"><code>const getDistance = async (town, center) => {
const response = await fetch(
`https://maps.googleapis.com/maps/api/distancematrix/json?destinations=${town}&origins=${center}&units=imperial&key=API_KEY`
);
const data = await response.json();
console.log(data);
return data.rows[0].elements[0].distance.value;
};
</code></pre>
<p>But I keep receiving this error on the console:</p>
<pre><code>(reason: cors header ‘access-control-allow-origin’ missing). status code: 200
</code></pre>
<p>I've already tried the HTTPS link request on google and that's working, seems like the error doesn't come from my API_KEY or something. Could someone help me?</p>
| [
{
"answer_id": 74309535,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 3,
"selected": true,
"text": "#!/usr/bin/env bash\n# ^^^^- specifically, bash 4.0 or newer; NOT /bin/sh\n\ndeclare -A vars=( )\n\nre='^([^=]* )?([[:alpha:]_-][[:alnum:]_-]+)=([^[:space:]]+)( (.*))?$'\nstring=\"/something an-arg=some-value another-arg=another-value third-arg=three\"\nwhile [[ $string =~ $re ]]; do : \"${BASH_REMATCH[@]}\"\n string=${BASH_REMATCH[5]}\n vars[${BASH_REMATCH[2]}]=${BASH_REMATCH[3]}\ndone\n\ndeclare -p vars # print the variables we extracted\n"
},
{
"answer_id": 74309866,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "-"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20410210/"
] |
74,309,458 | <p>I am trying to do pd.wide_to_long and I want to separate based off of what is inside a parenthesis. I looked up the pandas manual <a href="https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html#pandas-wide-to-long" rel="nofollow noreferrer">here</a> and the closes example is below. I changed the column names to match something to what I have.</p>
<pre><code>np.random.seed(0)
df = pd.DataFrame({'A(weekly_2010)': np.random.rand(3),
'A(weekly_2011)': np.random.rand(3),
'B(weekly_2010)': np.random.rand(3),
'B(weekly_2011)': np.random.rand(3),
'X' : np.random.randint(3, size=3)})
df['id'] = df.index
</code></pre>
<p>I would do</p>
<pre><code>df1=pd.wide_to_long(df, stubnames=['A', 'B'], i=['id'], j='year', sep='()', suffix='\w+')
</code></pre>
<p>This returns an empty dataframe. I looked at this <a href="https://stackoverflow.com/questions/72137046/what-is-the-stubname-for-fields-with-multiple-separators">example</a> and switched the i and J but it returns a KeyError: "None of [Index(['year'], dtype='object')] are in the [columns]"
I have tried the following for sep= and still no luck. Does someone have an idea of how to get the following dataframe.</p>
<pre><code>df1=pd.wide_to_long(df, stubnames=['A', 'B'], i=['id'], j='year', sep='(*)', suffix='\w+')
df1=pd.wide_to_long(df, stubnames=['A', 'B'], i=['id'], j='year', sep='\\()', suffix='\w+')
df1=pd.wide_to_long(df, stubnames=['A', 'B'], i=['id'], j='year', sep=r'\\()', suffix='\w+')
df1=pd.wide_to_long(df11, stubnames=['A', 'B'], i=['id'], j='year', sep=r'\(*\)', suffix='\w+')
</code></pre>
<p>The desired dataframe would be</p>
<pre><code>desiredDF= pd.DataFrame({'year':["(weekly_2010)","(weekly_2010)","(weekly_2010)","(weekly_2011)","(weekly_2011)","(weekly_2011)"],
'A': np.random.rand(6),
'B': np.random.rand(6),
'X' : np.random.randint(6, size=6),
'id':np.random.randint(6, size=6)})
</code></pre>
<p>obviously with the same numbers, I just wanted to show the column that matters which is the year column. I need to do pivot because my dataframe is more complicated and doing other formats, messes up the numbers. If anyone knows how to write in the sep, I would greatly appreciate it!</p>
| [
{
"answer_id": 74309790,
"author": "Scott Boston",
"author_id": 6361531,
"author_profile": "https://Stackoverflow.com/users/6361531",
"pm_score": 2,
"selected": true,
"text": "df.columns = df.columns.str.replace(')','', regex=False)\npd.wide_to_long(df, stubnames=['A', 'B'], i=['id'], j='year', sep='(', suffix='\\w+')\n"
},
{
"answer_id": 74310026,
"author": "sammywemmy",
"author_id": 7175713,
"author_profile": "https://Stackoverflow.com/users/7175713",
"pm_score": 0,
"selected": false,
"text": "pd.wide_to_long"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14146065/"
] |
74,309,471 | <p>I've data as follows</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>AreaId</th>
<th>AreaName</th>
<th>Module</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AAA</td>
<td>Square</td>
</tr>
<tr>
<td>2</td>
<td>AAA</td>
<td>Circle</td>
</tr>
<tr>
<td>3</td>
<td>BBB</td>
<td>Square</td>
</tr>
<tr>
<td>4</td>
<td>CCC</td>
<td>Square</td>
</tr>
<tr>
<td>5</td>
<td>CCC</td>
<td>Circle</td>
</tr>
<tr>
<td>6</td>
<td>DDD</td>
<td>Circle</td>
</tr>
</tbody>
</table>
</div>
<p>I'm looking for some help in SQL to get the data as follows</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>AreaName</th>
<th>SquareArea</th>
<th>CircleArea</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>BBB</td>
<td>3</td>
<td>Null</td>
</tr>
<tr>
<td>CCC</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>DDD</td>
<td>Null</td>
<td>6</td>
</tr>
</tbody>
</table>
</div>
<p>I've tried with Distinct. But I'm unable to prepare the SQL for the data result that I'm looking for</p>
| [
{
"answer_id": 74309579,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 1,
"selected": true,
"text": "SELECT AreaName, SquareArea = [Square], CircleArea = [Circle]\n FROM dbo.YourTableName\n PIVOT (MAX(AreaID) FOR Module IN ([Square],[Circle])) AS p;\n"
},
{
"answer_id": 74309681,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 1,
"selected": false,
"text": "DECLARE @table TABLE (AreaID INT IDENTITY, AreaName NVARCHAR(3), Module NVARCHAR(10))\nINSERT INTO @table (AreaName, Module) VALUES\n('AAA','Square'),('AAA','Circle'),('BBB','Square'),\n('CCC','Square'),('CCC','Circle'),('DDD','Circle')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411821/"
] |
74,309,560 | <p>sorry for the basic question, new to terraform. I am running through some sample examples in terraform where lots of example show declaration of local variable, i.e. locals, by name it sounds like the scope of it, is local to the file. instead of locals, we should be able to pass this list as variable right? such as .also, the examples use for_each construct or locals.names[count.index] , where count.index = length(locals.names) , what is the best way to pass and iterate such list in terraform?</p>
<pre><code>variable "name_list"{
names = ["luke", "Tom", ...]
type = ...
}
</code></pre>
<p>file - main.tf</p>
<pre><code>locals{
names = ["luke", "Tom", "Jerry"]
}
resource "aws..." "example..."{
foreach
}
</code></pre>
<p>I have tried it as locals but want to pass the list as variable.</p>
| [
{
"answer_id": 74309579,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 1,
"selected": true,
"text": "SELECT AreaName, SquareArea = [Square], CircleArea = [Circle]\n FROM dbo.YourTableName\n PIVOT (MAX(AreaID) FOR Module IN ([Square],[Circle])) AS p;\n"
},
{
"answer_id": 74309681,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 1,
"selected": false,
"text": "DECLARE @table TABLE (AreaID INT IDENTITY, AreaName NVARCHAR(3), Module NVARCHAR(10))\nINSERT INTO @table (AreaName, Module) VALUES\n('AAA','Square'),('AAA','Circle'),('BBB','Square'),\n('CCC','Square'),('CCC','Circle'),('DDD','Circle')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12696928/"
] |
74,309,570 | <p>I'm trying to implement a priority queue in Python using heapq as a base. It works fine when inputting values directly, and then popping them, but when values are updated or removed in between, the values begin to pop in the wrong order.</p>
<p>Since changing values directly (I have already tested this) does not maintain the heap invariant, I instead empty the original value list, and then insert the updated version. When popping values from the heap, if an empty list is popped, it will pop again until it returns a proper value.</p>
<p>I thought that the invariant must have been disrupted somehow, despite my efforts, so I used heapq.nsmallest(len(heap), heap) to check the ordering of the values. To my surprise, it always returned the correct ordering. Nonetheless, when removing the values with heapq.heappop(heap), they were <em>not</em> returned in that order. How can that be possible? My code is below:</p>
<pre><code>import heapq
class IndexedPriorityQueue:
def __init__(self, start: list | tuple):
self.added = 0
self.heap = []
self.key_values = {}
for index, item in enumerate(start):
self._add(item[0], index, item[1])
def add(self, item: str, priority: int):
if item in self.key_values:
return False
self._add(item, self.added, priority)
self.added += 1
def _add(self, item: str, index: int, priority: int):
next = [-priority, index, item]
self.key_values[item] = next
heapq.heappush(self.heap, next)
def pop(self):
if not self.heap:
return
value = heapq.heappop(self.heap)
while not value:
value = heapq.heappop(self.heap)
return value[2]
def remove(self, item: str):
if self.key_values[item] is self.heap[0]:
heapq.heappop(self.heap)
else:
self.key_values[item].pop()
self.key_values[item].pop()
self.key_values[item].pop()
del self.key_values[item]
def update(self, item: str, new_priority: int):
if self.key_values[item] is self.heap[0]:
new = [-new_priority, self.key_values[item][1], item]
heapq.heapreplace(self.heap, new)
self.key_values[item] = new
else:
self.key_values[item].pop()
index = self.key_values[item].pop()
self.key_values[item].pop()
self._add(item, index, new_priority)
ipq = IndexedPriorityQueue((["First", 1], ["Third", 10], ["Second", 0], ["Fifth", 7], ["Fourth", 6], ["None", 9999]))
print("Actual: ", heapq.nsmallest(len(ipq.heap), ipq.heap))
return_list = []
while (next_val := ipq.pop()) is not None:
return_list.append(next_val)
print("Returned: ", return_list)
ipq = IndexedPriorityQueue((["First", 1], ["Third", 10], ["Second", 0], ["Fifth", 7], ["Fourth", 6], ["None", 9999]))
ipq.add("Sixth", 0)
ipq.update("First", 9999)
ipq.remove("None")
ipq.update("Second", 999)
ipq.update("Fourth", 8)
print("Actual: ", heapq.nsmallest(len(ipq.heap), ipq.heap))
return_list = []
while (next_val := ipq.pop()) is not None:
return_list.append(next_val)
print("Returned: ", return_list)
</code></pre>
<p>The printed values are:</p>
<pre><code>Actual: [[-9999, 5, 'None'], [-10, 1, 'Third'], [-7, 3, 'Fifth'], [-6, 4, 'Fourth'], [-1, 0, 'First'], [0, 2, 'Second']]
Returned: ['None', 'Third', 'Fifth', 'Fourth', 'First', 'Second']
Actual: [[], [], [], [-9999, 0, 'First'], [-999, 2, 'Second'], [-10, 1, 'Third'], [-8, 4, 'Fourth'], [-7, 3, 'Fifth'], [0, 0, 'Sixth']]
Returned: ['First', 'Third', 'Second', 'Fourth', 'Fifth', 'Sixth']
</code></pre>
<p>The empty lists are also not all popped at the beginning.</p>
| [
{
"answer_id": 74309768,
"author": "Tim Roberts",
"author_id": 1883316,
"author_profile": "https://Stackoverflow.com/users/1883316",
"pm_score": 0,
"selected": false,
"text": "remove"
},
{
"answer_id": 74310164,
"author": "trincot",
"author_id": 5459839,
"author_profile": "https://Stackoverflow.com/users/5459839",
"pm_score": 2,
"selected": true,
"text": " def remove(self, item: str):\n if self.key_values[item] is self.heap[0]:\n heapq.heappop(self.heap)\n else:\n # Perform only one pop so to leave 2 members in the list\n self.key_values[item].pop()\n del self.key_values[item]\n\n def update(self, item: str, new_priority: int):\n if self.key_values[item] is self.heap[0]:\n new = [-new_priority, self.key_values[item][1], item]\n heapq.heapreplace(self.heap, new)\n self.key_values[item] = new\n else:\n self.key_values[item].pop() # Only pop the last member\n index = self.key_values[item][-1] # Don't pop this one -- just read\n self._add(item, index, new_priority)\n\n def pop(self):\n if not self.heap:\n return\n value = heapq.heappop(self.heap)\n while len(value) < 3: # Changed test for delete-mark\n if not self.heap: # Protection needed!\n return\n value = heapq.heappop(self.heap)\n return value[2]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17750765/"
] |
74,309,576 | <p>Trying to access components via findByViewId and get null
The problem is in this line:</p>
<p>(I cannot connect my viewxml to the class)</p>
<pre><code>// HERE I GET NULL
**_addButton = context.findViewById(R.id.buttonAdd);**
</code></pre>
<p>I have an activity:
with this OnCreate:</p>
<p>MainActivity class</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
</code></pre>
<p>I have a custom view I call in my MainActivity
MainActivity xml</p>
<pre><code> <com.example.myemptyapplication.PlayersFragment
android:id="@+id/fragment_container_view_players"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10px"/>
</code></pre>
<p>In 'PlayersFragment' I' trying to access</p>
<pre><code>PlayersFragment extends View
</code></pre>
<pre><code>@RequiresApi(api = Build.VERSION_CODES.O)
public PlayersFragment(Context context, AttributeSet attSet) {
super(context, attSet);
</code></pre>
<pre><code> protected void onFinishInflate() {
super.onFinishInflate();
// HERE I GET NULL
**_addButton = context.findViewById(R.id.buttonAdd);**
}
</code></pre>
<p>Tried to get components in a custom view</p>
| [
{
"answer_id": 74326420,
"author": "Tammy Roytvarf",
"author_id": 20411760,
"author_profile": "https://Stackoverflow.com/users/20411760",
"pm_score": 0,
"selected": false,
"text": "ayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n inflater.inflate(R.layout.fragment_players, null, false);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411760/"
] |
74,309,584 | <p>I have an example df:</p>
<pre><code>df <- data.frame(
group = c("a", "a", "a", "a", "b", "b", "c", "c", "c", "c", "d", "d", "d"),
col1 = c(-36,10,-5,1, 0, 5,10, 5, 20, 2, -1, 1, 2 )
)
group col1
1 a -36
2 a 10
3 a -5
4 a 1
5 b 0
6 b 5
7 c 10
8 c 5
9 c 20
10 c 2
11 d -1
12 d 1
13 d 2
</code></pre>
<p>and I want to derive flag such that grouped by 'group', if there is a value of 1 in col1, set flag = Y. If there is not a value of 1 in col1, then set the highest col1 value to flag = Y.</p>
<p>I tried this logic but I don't know how to make it so that if it meets the first condition to not fulfill the second condition in the group:</p>
<pre><code>df <- df %>%
group_by(group) %>%
mutate(flag = case_when(
col1 == 1 ~ "Y",
col1 == max(col1) ~ "Y",
TRUE ~ "")
)
</code></pre>
<p>expected output:</p>
<pre><code> group col1 flag
1 a -36
2 a 10
3 a -5
4 a 1 Y
5 b 0
6 b 5 Y
7 c 10
8 c 5
9 c 20 Y
10 c 2
11 d -1
12 d 1 Y
13 d 2
</code></pre>
| [
{
"answer_id": 74326420,
"author": "Tammy Roytvarf",
"author_id": 20411760,
"author_profile": "https://Stackoverflow.com/users/20411760",
"pm_score": 0,
"selected": false,
"text": "ayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n inflater.inflate(R.layout.fragment_players, null, false);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8864308/"
] |
74,309,587 | <p>i am trying to built a little game with random. In this game you have the choice to answer a question with "a1" and "a2" for "Answer 1" and "Answer 2". At the End it should print, if you chose the right Answer. To make it a little more dynamic i want that the Option for "a1" and "a2" is not always the same. Like the Answer, if the sky ist Blue shouldn't be always "a1". If would be nice if somebody helps me with my code.
Thanks</p>
<pre><code>import random
from random import randint
list = ["a1", "a2"]
op1 = random.choice(list)
op2 = ""
if op1 == "a1":
op2 = "a2"
else:
op1 = "a2"
print("Is the Sky Blue ? If Yes type")
print("a1")
print("If NO type")
print("a2")
test = "a1" # user input
if test == op1:
print("Yeah thats right")
elif test == op2:
print("thats the wrong answer")
</code></pre>
| [
{
"answer_id": 74326420,
"author": "Tammy Roytvarf",
"author_id": 20411760,
"author_profile": "https://Stackoverflow.com/users/20411760",
"pm_score": 0,
"selected": false,
"text": "ayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n inflater.inflate(R.layout.fragment_players, null, false);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20411850/"
] |
74,309,671 | <p>If anyone has any experience with the BinanceUS api please let me know if you have had this problem.
I have read the docs thoroughly and can not come up with an adequate solution. Yes I have read the docs for both BinanceUS and node-binance-us-api. This is a test of a STOP_LOSS data object to be sent with credentials/apikeys/secrets. It is not working and I can not find an answer anywhere as this appears to be the correct method. But when I do regular buy and sell orders they work. I am at a loss, thanks for anyone's’ help!
The <code>object</code></p>
<p>{</p>
<p>“symbol”:“SHIBUSDT”,</p>
<p>“side”:“SELL”,</p>
<p>“type”:“STOP_LOSS”,</p>
<p>“quantity”:“1200000”,</p>
<p>“stopPrice”:“0.00001150”,</p>
<p>“timestamp”:1667507603276,</p>
<p>“recvWindow”:5000</p>
<p>}</p>
<p>As stated I have read both API docs and I am in need of someone with more experience with binanceUS API than I.</p>
| [
{
"answer_id": 74326420,
"author": "Tammy Roytvarf",
"author_id": 20411760,
"author_profile": "https://Stackoverflow.com/users/20411760",
"pm_score": 0,
"selected": false,
"text": "ayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n inflater.inflate(R.layout.fragment_players, null, false);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12835213/"
] |
74,309,708 | <p>I have a scenario to update 'NULL' string if column has no value that means null. So, i ran multiple update query to set the 'NULL' string.</p>
<pre><code>update codesets set system_name='NULL' where system_name is null
update codesets set column_name='NULL' where column_name is null
update codesets set table_name='NULL' where table_name is null
update codesets set schema_name='NULL' where schema_name is null
</code></pre>
<p>How to merge multiple update query as a single update query ?</p>
| [
{
"answer_id": 74309794,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": false,
"text": "update codesets\nset system_name=coalesce(system_name, 'NULL'),\n column_name=coalesce(column_name, 'NULL'),\n table_name=coalesce(table_name, 'NULL'),\n schema_name=coalesce(schema_name, 'NULL')\nwhere system_name is null\nor column_name is null\nor table_name is null\nor schema_name is null\n"
},
{
"answer_id": 74309824,
"author": "aLittleSalty",
"author_id": 12723936,
"author_profile": "https://Stackoverflow.com/users/12723936",
"pm_score": 2,
"selected": false,
"text": "coalesce"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848031/"
] |
74,309,719 | <ul>
<li>Created a new "WPF Application" .NET 6.0 project
There creating classical Application Settings was easy in project->properties->Settings->"Create or open application settings"</li>
<li>Observed: the project gets a new folder "Properties" which has a yellow Folder icon with an additional black wrench symbol, okay</li>
<li>It contains a new item <code>Settings.settings</code> that can get edited via classical Settings Designer looking like it used to look in .Net 4.8, and a new App.config XML file is getting created automatically in the project's root folder which also looks like it used to in .Net 4.8, okay</li>
</ul>
<p>Now the same procedure can apparently only be done manually in</p>
<ul>
<li>a new "Class Library" project being added in the same solution where I would want to use that Properties.Settings / app.config feature pack for storing a DB connection string configurably:</li>
<li>the new sub-project does not seem to have a "Settings" option in the project Properties dialog (as opposed to a .Net4.x would have had)</li>
<li>the new Properties folder and new Settings file can be created successfully there too manually as described in <a href="https://stackoverflow.com/questions/56847571/equivalent-to-usersettings-applicationsettings-in-wpf-net-5-net-6-or-net-c">Equivalent to UserSettings / ApplicationSettings in WPF .NET 5, .NET 6 or .Net Core</a></li>
<li>but doing a "Rebuild solution" gives an</li>
</ul>
<blockquote>
<p>Error CS1069 The type name 'ApplicationSettingsBase' could not be found in the namespace 'System.Configuration'. This type has been forwarded to assembly 'System.Configuration.ConfigurationManager, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' Consider adding a reference to that assembly. ClassLibrary1 C:\Users\Stefan\source\repos\WpfCorePropertiesSettings\ClassLibrary1\Properties\Settings.Designer.cs 16 Active</p>
</blockquote>
<ul>
<li>as a next step adding NuGet package "System.Configuration.Abstractions" to the Class Library project cures the symptom, "rebuild solution" makes the error disappear.</li>
</ul>
<p>TLDNR, <strong>actual question</strong>: is that sequence an acceptable solution or a kludge to avoid?</p>
<p>To me the NuGet package description does not sound as if the package was made for that purpose, and I have not heard the maintainers' names before (which might or might not matter?)
<a href="https://github.com/davidwhitney/System.Configuration.Abstractions" rel="nofollow noreferrer">https://github.com/davidwhitney/System.Configuration.Abstractions</a></p>
<p>TIA</p>
<p>PS: <a href="https://i.stack.imgur.com/KMo1C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KMo1C.png" alt=""Class Library" Project Template" /></a></p>
<p><a href="https://i.stack.imgur.com/J2Cjn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J2Cjn.png" alt=""Class Library" Project properties" /></a></p>
| [
{
"answer_id": 74309794,
"author": "Alex Poole",
"author_id": 266304,
"author_profile": "https://Stackoverflow.com/users/266304",
"pm_score": 2,
"selected": false,
"text": "update codesets\nset system_name=coalesce(system_name, 'NULL'),\n column_name=coalesce(column_name, 'NULL'),\n table_name=coalesce(table_name, 'NULL'),\n schema_name=coalesce(schema_name, 'NULL')\nwhere system_name is null\nor column_name is null\nor table_name is null\nor schema_name is null\n"
},
{
"answer_id": 74309824,
"author": "aLittleSalty",
"author_id": 12723936,
"author_profile": "https://Stackoverflow.com/users/12723936",
"pm_score": 2,
"selected": false,
"text": "coalesce"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489263/"
] |
74,309,733 | <p>I am trying to make a design where there are two columns in a box. One column contains an image and takes up 1/4 of the width under normal circumstances, and 1/2 of the width when hovered over. The other column contains a decent amount of text and takes up whatever space is left.</p>
<p>I am running into an issue where the CSS that tells the first column's width to be either 50% or 25% is not being respected. The first column is less than 1/8 of the width when it is supposed to be 1/4 and less than 1/4 when it is supposed to be 1/2. I have managed to create a minimal example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
height: 100%;
width: 100%;
min-width: 100%;
}
.container {
height: 50%;
width: 100%;
display: flex;
flex-direction: row;
border-radius: 0.25rem;
margin: 1rem;
overflow: hidden;
border-width: 1px;
border-style: solid;
}
.left {
margin: auto;
width: 25%;
height: 100%;
border-width: 1px;
border-style: solid;
transition-property: width;
transition-duration: 300ms;
padding: 1rem;
}
.left:hover {
width: 50%;
}
.right {
width: auto;
margin: auto;
font-size: 1.5rem;
line-height: 2rem;
padding: 1rem 4rem;
border-width: 1px;
border-style: solid;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="left">
Placeholder
</div>
<p class="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus ligula purus, lobortis luctus malesuada vitae, egestas quis lorem. Mauris ultrices mauris et enim dictum fermentum. Nam nibh nulla, posuere ut egestas a, fringilla ac augue. Vivamus sed
eros eget purus maximus iaculis. </p>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/mnw6x29o/27/" rel="nofollow noreferrer">JSFiddle link</a></p>
<p>I have looked up previous questions like this and they all seem to state that somehow the parent <code>div</code>'s dimensions are not defined. However, in this case they are defined! <code>html</code> and <code>body</code> have defined dimensions, and so does the container div.</p>
<p>Why isn't the width doing what I think it should do in this case?</p>
| [
{
"answer_id": 74309812,
"author": "Johannes",
"author_id": 5641669,
"author_profile": "https://Stackoverflow.com/users/5641669",
"pm_score": 2,
"selected": true,
"text": "flex-shrink: 0;"
},
{
"answer_id": 74309875,
"author": "DCR",
"author_id": 4398966,
"author_profile": "https://Stackoverflow.com/users/4398966",
"pm_score": 0,
"selected": false,
"text": ".left {\n width: 25%;\n display: inline-block;\n border: 1px solid red;\n}\n\n.right {\n float: right;\n width: 50%;\n}\n\n.left:hover {\n width: calc(50% - 2px);\n}"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5667338/"
] |
74,309,738 | <p>Let's say I have this array</p>
<pre><code>const testData = [
{ properties: { number: 1, name: 'haha' } , second: 'this type'},
['one', 'two', 'three'],
];
</code></pre>
<p>I want to get the value of 'second' which is 'this type' like this:</p>
<pre><code>
const wantToGet = testData[0].second;
</code></pre>
<p>But the typescript generates an error saying</p>
<pre><code>
Property 'second' does not exist on type 'string[] | { properties: { number: number; name: string; }; second: string; }'.
Property 'second' does not exist on type 'string[]'
</code></pre>
<p>testData[0] is always an object, not an array. Why is that?</p>
| [
{
"answer_id": 74309836,
"author": "Federkun",
"author_id": 711206,
"author_profile": "https://Stackoverflow.com/users/711206",
"pm_score": 2,
"selected": false,
"text": "testData"
},
{
"answer_id": 74309884,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 1,
"selected": true,
"text": "testData"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13401991/"
] |
74,309,754 | <p>This is the problem. The <code>print</code> statement in the <code>populateProviders</code> function is not getting run.</p>
<pre><code>class _MyHomePageState extends State<MyHomePage> {
Future<void> loadData = Future(
() => null,
);
bool hostBottomNavigationBar = true;
void toggleHostBottomNavigationBar() {
setState(() {
hostBottomNavigationBar = !hostBottomNavigationBar;
});
}
@override
void initState() {
super.initState();
loadData = populateProviders();
}
Future<void> populateProviders() async {
await Provider.of<ExploreData>(context, listen: false).populate();
await Provider.of<HostEvents>(context, listen: false).populate();
print('This line never runs');
return;
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: loadData,
builder: (context, snapshot) => snapshot.connectionState !=
ConnectionState.done
? Scaffold(
appBar: AppBar(title: Text('House')),
body: Center(
child: CircularProgressIndicator(),
),
)
: hostBottomNavigationBar
? HostScaffold(widget.title, toggleHostBottomNavigationBar)
: PartierScaffold(widget.title, toggleHostBottomNavigationBar));
}
}
</code></pre>
| [
{
"answer_id": 74309861,
"author": "hasan karaman",
"author_id": 11544943,
"author_profile": "https://Stackoverflow.com/users/11544943",
"pm_score": 1,
"selected": false,
"text": " @override\nWidget build(BuildContext context) {\n return \n Consumer2<ExploreData, HostEvents>(\n builder: (\n final BuildContext context,\n final ExploreData exploreData,\n final HostEvents hostEvents,\n final Widget? child,\n ) {\n return \nFutureBuilder(\n future: Future.wait([exploreData.populate(),hostEvents.populate()]),\n builder: (context, snapshot) => snapshot.connectionState !=\n ConnectionState.done\n"
},
{
"answer_id": 74330930,
"author": "Joel Castro",
"author_id": 8386132,
"author_profile": "https://Stackoverflow.com/users/8386132",
"pm_score": 1,
"selected": true,
"text": "Future<void> populate() async {\n print('This executes');\n var snapshot = await db\n .collection(\"parties\")\n .where(FieldPath.documentId, whereNotIn:)\n .get();\n print('This does not execute');\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8386132/"
] |
74,309,755 | <p>I've seen a lot of post on removing duplicates but those don't apply to my case.
The idea is I only care about whether the dataset contain IDs associate with more than one industries, if an ID has more than one industry, completely remove that ID and rows associate with it from the dataset. Can this be done with SQL? Python?</p>
<p>For example:</p>
<pre><code> ID | Date | Industry |
S000123 | oct/1/22 | Media |
S000123 | oct/1/22 | Education |
S000456 | oct/4/22 | Auto |
S000789 | oct/4/22 | Beverage |
</code></pre>
<p>becomes</p>
<pre><code> ID | Date | Industry |
S000456 | oct/4/22 | Auto |
S000789 | oct/4/22 | Beverage |
</code></pre>
| [
{
"answer_id": 74309861,
"author": "hasan karaman",
"author_id": 11544943,
"author_profile": "https://Stackoverflow.com/users/11544943",
"pm_score": 1,
"selected": false,
"text": " @override\nWidget build(BuildContext context) {\n return \n Consumer2<ExploreData, HostEvents>(\n builder: (\n final BuildContext context,\n final ExploreData exploreData,\n final HostEvents hostEvents,\n final Widget? child,\n ) {\n return \nFutureBuilder(\n future: Future.wait([exploreData.populate(),hostEvents.populate()]),\n builder: (context, snapshot) => snapshot.connectionState !=\n ConnectionState.done\n"
},
{
"answer_id": 74330930,
"author": "Joel Castro",
"author_id": 8386132,
"author_profile": "https://Stackoverflow.com/users/8386132",
"pm_score": 1,
"selected": true,
"text": "Future<void> populate() async {\n print('This executes');\n var snapshot = await db\n .collection(\"parties\")\n .where(FieldPath.documentId, whereNotIn:)\n .get();\n print('This does not execute');\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6846071/"
] |
74,309,756 | <p>I want to store structs in HashMap but also reference to same structs inside another struct vector field.</p>
<p>Let's say I have a tree build of two types of structs Item and Relation.</p>
<p>I am storing all the relations in HashMap by their id,
but I also want to fill each item.out_relations vector with mutable references to same Relation structs which are owned by HashMap.</p>
<p>Here is my Item:</p>
<pre><code>pub struct Item<'a> {
pub id: oid::ObjectId,
pub out_relations: Vec<&'a mut Relation>, // <-- want to fill this
}
</code></pre>
<p>And when I am iterating over my relations got from DB
I am trying to do smth like this:</p>
<pre><code>let from_id = relation.from_id; //to find related item
item_map // my items loaded here already
.entry(from_id)
.and_modify(|item| {
(*item)
.out_relations.push(
relation_map.try_insert(relation.id, relation).unwrap() // mut ref to relation expected here
)
}
);
</code></pre>
<p>For now compiler warns try_insert is unstable feature and points me to this <a href="https://github.com/rust-lang/rust/issues/82766" rel="nofollow noreferrer">bug</a>
But let's imagine I have this mutable ref to relation owned already by HashMap- is it going to work?</p>
<p>Or this will be again some ref lives not long enough error? What are my options then? Or I better will store just relation id in item out_relations vector rather then refs? And when needed I will take my relation from the hashmap?</p>
| [
{
"answer_id": 74309861,
"author": "hasan karaman",
"author_id": 11544943,
"author_profile": "https://Stackoverflow.com/users/11544943",
"pm_score": 1,
"selected": false,
"text": " @override\nWidget build(BuildContext context) {\n return \n Consumer2<ExploreData, HostEvents>(\n builder: (\n final BuildContext context,\n final ExploreData exploreData,\n final HostEvents hostEvents,\n final Widget? child,\n ) {\n return \nFutureBuilder(\n future: Future.wait([exploreData.populate(),hostEvents.populate()]),\n builder: (context, snapshot) => snapshot.connectionState !=\n ConnectionState.done\n"
},
{
"answer_id": 74330930,
"author": "Joel Castro",
"author_id": 8386132,
"author_profile": "https://Stackoverflow.com/users/8386132",
"pm_score": 1,
"selected": true,
"text": "Future<void> populate() async {\n print('This executes');\n var snapshot = await db\n .collection(\"parties\")\n .where(FieldPath.documentId, whereNotIn:)\n .get();\n print('This does not execute');\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043073/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.