qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,300,367 | <p>I have a text field on my PostgreSQL database that I want to store only capital alphabetic letters not but not special characters in a column.</p>
<p>I have already used <code>CHECK (location_id ~* '[A-Z]')</code> I am able to insert both alphabetic and special characters that doesn't not solve my requirement.</p>
| [
{
"answer_id": 74300684,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 3,
"selected": true,
"text": "~*"
},
{
"answer_id": 74300686,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "CHECK (location_id ~ '^[A-Z]+$')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5106065/"
] |
74,300,375 | <pre><code>function RequestDetail({match}) {
const [request, setRequests] = useState({});
const [data, setData]= useState([]);
useEffect(() => {
fetchRequest();
}, []);
const fetchRequest = () => {
axios
.get(
`${baseUrl}/${match.params.id}`
)
.then((res) => {
setRequests(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
};
</code></pre>
<pre><code> <Card key={request.id}>
<Card.Header>{request.user.email}</Card.Header>
<Card.Body>
<Card.Title>{request.address}</Card.Title>
<Card.Text>
{request.description}<br/>
{request.kind}
</Card.Text>
</Card.Body>
</Card>
</code></pre>
<p>`</p>
<p>in the console I have this
<a href="https://i.stack.imgur.com/qV9s3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qV9s3.png" alt="enter image description here" /></a></p>
<p>any suggestions?</p>
<p>I just want to map the user included in the json, I have tried <code>.map()</code> but it throughs .map() is not a function</p>
| [
{
"answer_id": 74300445,
"author": "Vardhan",
"author_id": 18725205,
"author_profile": "https://Stackoverflow.com/users/18725205",
"pm_score": 1,
"selected": false,
"text": "const [request, setRequest] = useState();\n// do this when rendering\n{request && \n <Card key={request.id}>\n <Card.Header>{request.user.email}</Card.Header>\n <Card.Body>\n <Card.Title>{request.address}</Card.Title>\n <Card.Text>\n {request.description}<br/>\n {request.kind}\n </Card.Text>\n </Card.Body>\n </Card>\n}\n"
},
{
"answer_id": 74300454,
"author": "Apostolos",
"author_id": 1121008,
"author_profile": "https://Stackoverflow.com/users/1121008",
"pm_score": 3,
"selected": true,
"text": "reuest"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16811972/"
] |
74,300,385 | <p>Im geting error</p>
<p>ErrorException</p>
<p>PHP 8.1.1</p>
<p>9.37.0</p>
<p>Undefined variable $optionsForModels</p>
<p> </p>
<p>What am i doing wrong?</p>
<p>Models</p>
<pre><code>class Employee extends Model
{
public function numbers() {
return $this->morphMany(PhoneNumber::class, 'numberable');
}
}
class Place extends Model
{
public function numbers() {
return $this->morphMany(PhoneNumber::class, 'numberable');
}
}
class PhoneNumber extends Model
{
public function numberable() {
return $this->morphTo();
}
}
</code></pre>
<p>Contorller</p>
<pre><code>CRUD::field('numberable')
->addMorphOption('App\Models\Employee')
->addMorphOption('App\Models\Place');
</code></pre>
| [
{
"answer_id": 74300445,
"author": "Vardhan",
"author_id": 18725205,
"author_profile": "https://Stackoverflow.com/users/18725205",
"pm_score": 1,
"selected": false,
"text": "const [request, setRequest] = useState();\n// do this when rendering\n{request && \n <Card key={request.id}>\n <Card.Header>{request.user.email}</Card.Header>\n <Card.Body>\n <Card.Title>{request.address}</Card.Title>\n <Card.Text>\n {request.description}<br/>\n {request.kind}\n </Card.Text>\n </Card.Body>\n </Card>\n}\n"
},
{
"answer_id": 74300454,
"author": "Apostolos",
"author_id": 1121008,
"author_profile": "https://Stackoverflow.com/users/1121008",
"pm_score": 3,
"selected": true,
"text": "reuest"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405777/"
] |
74,300,441 | <p>I hope you are doing well!</p>
<p>I am trying to catch the window close or tab close or refresh event in my project and I tried all possible solutions but haven't succeeded.</p>
<p>I tried using:</p>
<pre><code> useEffect(() => {
return () => {
window.alert("Alert");
};
});
</code></pre>
<p>and I tried:</p>
<pre><code> useEffect(() => {
window.onbeforeunload = () => {
window.alert("alert");
};
return () => {
window.onbeforeunload = null;
};
});
</code></pre>
<p>which seems to only trigger if I have my window in the background for a while.</p>
<p>and I tried:</p>
<pre><code> window.addEventListener("onbeforeunload", () => {
window.alert("alert");
});
</code></pre>
<p>but haven't been able to capture it.</p>
<p>I will use this functionality to send data to a specific API whenever the user closes the window or tab or refreshes (and possibly turns off the PC while on the page if that is event possible). But all these methods weren't working for me.</p>
<p>Is there any other way or is there a reason they aren't working?</p>
<p>Thank you for your time!</p>
| [
{
"answer_id": 74300477,
"author": "Fralle",
"author_id": 3155183,
"author_profile": "https://Stackoverflow.com/users/3155183",
"pm_score": 2,
"selected": true,
"text": "preventDefault"
},
{
"answer_id": 74301082,
"author": "Vladimir Vladimirov",
"author_id": 6450052,
"author_profile": "https://Stackoverflow.com/users/6450052",
"pm_score": 0,
"selected": false,
"text": "const setEnabledBeforeUnload = useBeforeUnload({\n initEnable: false, // do you need to be enabled by default\n onRefresh: () => {\n // the page has been refreshed (the user has clicked Reload)\n },\n onCancel: () => {\n // the user has clicked Cancel\n }\n});\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17496055/"
] |
74,300,448 | <p>I have installed a bunch of CO2 loggers in water that log CO2 every hour for the open water season. I have characterized the loggers at 3 different concentrations of CO2 before and after installing them.</p>
<ul>
<li>I assume that the seasonal drift in error will be linear</li>
<li>I assume that the error between my characterization points will be linear</li>
</ul>
<p>My script is based on a for loop that goes through each timestamp and corrects the value, this works but is unfortuneately not fast enough. I know that this can be done within a second but I am not sure how. I seek some advice and I would be grateful if someone could show me how.</p>
<p>Reproduceable example based on basic R:</p>
<pre><code>start <- as.POSIXct("2022-08-01 00:00:00")#time when logger is installed
stop <- as.POSIXct("2022-09-01 00:00:00")#time when retrieved
dt <- seq.POSIXt(start,stop,by=3600)#generate datetime column, measured hourly
#generate a bunch of values within my measured range
co2 <- round(rnorm(length(dt),mean=600,sd=100))
#generate dummy dataframe
dummy <- data.frame(dt,co2)
#actual values used in characterization
actual <- c(0,400,1000)
#measured in the container by the instruments being characterized
measured.pre <- c(105,520,1150)
measured.post <- c(115,585,1250)
diff.pre <- measured.pre-actual#diff at precharacterization
diff.post <- measured.post-actual#diff at post
#linear interpolation of how deviance from actual values change throughout the season
#I assume that the temporal drift is linear
diff.0 <- seq(diff.pre[1],diff.post[1],length.out=length(dummy$dt))
diff.400 <- seq(diff.pre[2],diff.post[2],length.out = length(dummy$dt))
diff.1000 <- seq(diff.pre[3],diff.post[3],length.out = length(dummy$dt))
#creates a data frame with the assumed drift at each increment throughout the season
dummy <- data.frame(dummy,diff.0,diff.400,diff.1000)
#this loop makes a 3-point calibration at each day in the dummy data set
co2.corrected <- vector()
for(i in 1:nrow(dummy)){
print(paste0("row: ",i))#to show the progress of the loop
diff.0 <- dummy$diff.0[i]#get the differences at characterization increments
diff.400 <- dummy$diff.400[i]
diff.1000 <- dummy$diff.1000[i]
#values below are only used for encompassing the range of measured values in the characterization
#this is based on the interpolated difference at the given time point and the known concentrations used
measured.0 <- diff.0+0
measured.400 <- diff.400+400
measured.1000 <- diff.1000+1000
#linear difference between calibration at 0 and 400
seg1 <- seq(diff.0,diff.400,length.out=measured.400-measured.0)
#linear difference between calibration at 400 and 1000
seg2 <- seq(diff.400,diff.1000,length.out=measured.1000-measured.400)
#bind them together to get one vector
correction.ppm <- c(seg1,seg2)
#the complete range of measured co2 in the characterization.
#in reality it can not be below 0 and thus it can not be below the minimum measured in the range
measured.co2.range <- round(seq(measured.0,measured.1000,length.out=length(correction.ppm)))
#generate a table from which we can characterize the measured values from
correction.table <- data.frame(measured.co2.range,correction.ppm)
co2 <- dummy$co2[i] #measured co2 at the current row
#find the measured value in the table and extract the difference
diff <- correction.table$correction.ppm[match(co2,correction.table$measured.co2.range)]
#correct the value and save it to vector
co2.corrected[i] <- co2-diff
}
#generate column with calibrated values
dummy$co2.corrected <- co2.corrected
</code></pre>
| [
{
"answer_id": 74300477,
"author": "Fralle",
"author_id": 3155183,
"author_profile": "https://Stackoverflow.com/users/3155183",
"pm_score": 2,
"selected": true,
"text": "preventDefault"
},
{
"answer_id": 74301082,
"author": "Vladimir Vladimirov",
"author_id": 6450052,
"author_profile": "https://Stackoverflow.com/users/6450052",
"pm_score": 0,
"selected": false,
"text": "const setEnabledBeforeUnload = useBeforeUnload({\n initEnable: false, // do you need to be enabled by default\n onRefresh: () => {\n // the page has been refreshed (the user has clicked Reload)\n },\n onCancel: () => {\n // the user has clicked Cancel\n }\n});\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107742/"
] |
74,300,451 | <p><strong>Schema Details</strong></p>
<p>We are maintaining collections data in a project. Main columns of Collections table are <code>id(INT)</code>, <code>collectionId(String UUID)</code>, <code>versionNo(INT)</code>, <code>status(PUBLISHED/NEW/PURCHASED/DELETED/ARCHIVED)</code>. Each collection can have several versions. For each different version, <code>versionNo</code>, <code>id</code>, <code>status</code> column will have different values but <code>collectionId</code> will be same.</p>
<p><strong>Sample Data</strong></p>
<pre><code>id collectionId versionNo status
5 17af2c88-888d-4d9a-b7f0-dfcbac376434 1 PUBLISHED
80 17af2c88-888d-4d9a-b7f0-dfcbac376434 2 PUBLISHED
109 17af2c88-888d-4d9a-b7f0-dfcbac376434 3 NEW
6 d8451652-6b9e-426b-b883-dc8a96ec0010 1 PUBLISHED
</code></pre>
<p><strong>Problem Statement</strong></p>
<p>We want to fetch details of highest published version of collections. For example: for above dataset desired output is</p>
<pre><code>id collectionId versionNo status
80 17af2c88-888d-4d9a-b7f0-dfcbac376434 2 PUBLISHED
6 d8451652-6b9e-426b-b883-dc8a96ec0010 1 PUBLISHED
</code></pre>
<p>We tried following queries but either getting duplicate entries or not getting collections with single version only:</p>
<ol>
<li><p><code>select * from Collections where status="PUBLISHED" group by collectionId having versionNo=max(versionNo);</code></p>
</li>
<li><p><code>select T1.* from Collections T1 inner join Collections T2 on T1.collectionId = T2.collectionId AND T1.id <> T2.id where T1.status="PUBLISHED" AND T1.versionNo > T2.versionNo;</code></p>
</li>
</ol>
<p><strong>UPDATE</strong>: I am using MYSQL version 5.7.12.</p>
| [
{
"answer_id": 74300501,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "ROW_NUMBER()"
},
{
"answer_id": 74307849,
"author": "Vishal",
"author_id": 20184021,
"author_profile": "https://Stackoverflow.com/users/20184021",
"pm_score": 2,
"selected": true,
"text": "select C1.* from Collections C1 \n left join Collections C2 on C1.collectionId = C2.collectionId \n AND C1.status=\"PUBLISHED\" AND C2.status=\"PUBLISHED\" \n AND C1.versionNo < C2.versionNo \n WHERE C2.versionNo IS NULL \n AND C1.status=\"PUBLISHED\"\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357203/"
] |
74,300,461 | <p>sorry I am new to Prolog and logic programming. I was wondering if the following is possible in Prolog:</p>
<p>Given <code>j</code> lists of size <code>n = k*j</code>, how do I rearrange them into <code>m</code> lists, each containing the first <code>k</code> elements of each of the <code>j</code> lists?</p>
<p>For example, given a list of lists of 12 elements, such as</p>
<pre><code>[
[ 1, 2, 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ],
[ 13, 14, 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 ],
[ 25, 26, 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 ]
]
</code></pre>
<p>How do I transform it to</p>
<pre><code>[
[ 1, 2, 3, 4, 13, 14, 15, 16, 25, 26, 27, 28 ],
[ 5, 6, 7, 8, 17, 18, 19, 20, 29, 30, 31, 32 ],
[ 9, 10, 11, 12, 21, 22, 23, 24, 33, 34, 35, 36 ]
]
</code></pre>
<p>???</p>
<p>I can extract the first k elements of each list in the list.</p>
<pre><code>getFirstK(List, K, FirstK, Remainder) :-
length(FirstK, K),
append(FirstK, Remainder, List).
</code></pre>
<p>And I thought I could get at least [1,2,3,4,13,14,15,16,25,26,27,28] with the following,</p>
<pre><code>GetLists([], K, []).
GetLists([FirstList|RestOfLists], K, Result) :-
getFirstK(FirstList, K, FirstK, Remainder),
GetLists(RestOfLists, K, [FirstK|Result]).
</code></pre>
<p>However, when I run getLists to get Result, I get false instead. Is there a way to get the list of lists?</p>
| [
{
"answer_id": 74304168,
"author": "gusbro",
"author_id": 463243,
"author_profile": "https://Stackoverflow.com/users/463243",
"pm_score": 1,
"selected": false,
"text": "get_lists(LL, _, []):-\n maplist(=([]), LL).\nget_lists(LL, K, [R|LR]):-\n maplist(split(K), LL, LChunks, LRest),\n append(LChunks, R),\n get_lists(LRest, K, LR).\n\nsplit(K, L, Chunk, Rest):-\n length(Chunk, K),\n append(Chunk, Rest, L).\n"
},
{
"answer_id": 74327960,
"author": "brebs",
"author_id": 17628336,
"author_profile": "https://Stackoverflow.com/users/17628336",
"pm_score": 0,
"selected": false,
"text": "rearrange_lists([H|T], BiteLen, RLs) :-\n % Populate the heads, leaving the tails\n spread_list(H, BiteLen, RLs, Tails),\n % Loop through populating the tails\n rearrange_lists_(T, BiteLen, Tails).\n\nrearrange_lists_([], _, Tails) :-\n % Close the tails\n maplist(=([]), Tails).\nrearrange_lists_([H|T], BiteLen, Heads) :-\n spread_list(H, BiteLen, Heads, Tails),\n rearrange_lists_(T, BiteLen, Tails).\n\nspread_list([], _BL, [], []).\nspread_list([H|T], BiteLen, [BiteH|BiteHs], [BiteT|BiteTs]) :-\n copy_list_to_dl_len(BiteLen, [H|T], _HS, HR, BiteH, BiteT),\n spread_list(HR, BiteLen, BiteHs, BiteTs).\n\n% Generic, reusable predicate\ncopy_list_to_dl_len(Len, Lst, LstH, LstT, SubLstH, SubLstT) :-\n ( nonvar(Len)\n -> integer(Len),\n Len @>= 0,\n % Only once\n copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT), !\n ; copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT)\n ).\n \ncopy_list_to_dl_len_inc_(Lst, Lst, Lst, Len, Len, SubLst, SubLst).\ncopy_list_to_dl_len_inc_([H|T], [H|HT], LT, Len, FLen, [H|ST], SLT) :-\n Len1 is Len + 1,\n copy_list_to_dl_len_inc_(T, HT, LT, Len1, FLen, ST, SLT).\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405645/"
] |
74,300,464 | <p>I want to limit N processes ( introduced as parameters ) at the same time, but there is always more than N files to process. One process per file. Only N processes are being processes at one time. I know what the program must do but don't know how to make it happen.</p>
<p>I am sorry if I don't explain too well, I will answer all details needed.
Using C code in FreeBSD</p>
<pre><code>for (int i = 3; i < argc; i++) {
fflush(NULL);
if((pid_son = fork()) < 0){
printf("Error");
exit(-1);
}
else if(pid_son == 0){
}
}
</code></pre>
| [
{
"answer_id": 74304168,
"author": "gusbro",
"author_id": 463243,
"author_profile": "https://Stackoverflow.com/users/463243",
"pm_score": 1,
"selected": false,
"text": "get_lists(LL, _, []):-\n maplist(=([]), LL).\nget_lists(LL, K, [R|LR]):-\n maplist(split(K), LL, LChunks, LRest),\n append(LChunks, R),\n get_lists(LRest, K, LR).\n\nsplit(K, L, Chunk, Rest):-\n length(Chunk, K),\n append(Chunk, Rest, L).\n"
},
{
"answer_id": 74327960,
"author": "brebs",
"author_id": 17628336,
"author_profile": "https://Stackoverflow.com/users/17628336",
"pm_score": 0,
"selected": false,
"text": "rearrange_lists([H|T], BiteLen, RLs) :-\n % Populate the heads, leaving the tails\n spread_list(H, BiteLen, RLs, Tails),\n % Loop through populating the tails\n rearrange_lists_(T, BiteLen, Tails).\n\nrearrange_lists_([], _, Tails) :-\n % Close the tails\n maplist(=([]), Tails).\nrearrange_lists_([H|T], BiteLen, Heads) :-\n spread_list(H, BiteLen, Heads, Tails),\n rearrange_lists_(T, BiteLen, Tails).\n\nspread_list([], _BL, [], []).\nspread_list([H|T], BiteLen, [BiteH|BiteHs], [BiteT|BiteTs]) :-\n copy_list_to_dl_len(BiteLen, [H|T], _HS, HR, BiteH, BiteT),\n spread_list(HR, BiteLen, BiteHs, BiteTs).\n\n% Generic, reusable predicate\ncopy_list_to_dl_len(Len, Lst, LstH, LstT, SubLstH, SubLstT) :-\n ( nonvar(Len)\n -> integer(Len),\n Len @>= 0,\n % Only once\n copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT), !\n ; copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT)\n ).\n \ncopy_list_to_dl_len_inc_(Lst, Lst, Lst, Len, Len, SubLst, SubLst).\ncopy_list_to_dl_len_inc_([H|T], [H|HT], LT, Len, FLen, [H|ST], SLT) :-\n Len1 is Len + 1,\n copy_list_to_dl_len_inc_(T, HT, LT, Len1, FLen, ST, SLT).\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14611526/"
] |
74,300,476 | <p>Is the database used by netbox PostgreSQL?</p>
<p>Our virtual machine base information is stored inside netbox. We need Java to go to netbox to create VM information and to get VM information. But this does not guarantee transactivity. So we want to use Java to connect to netbox's database for transactional operations.</p>
<p>Our virtual machine base information is stored inside netbox. We need Java to go to netbox to create VM information and to get VM information. But this does not guarantee transactivity. So we want to use Java to connect to netbox's database for transactional operations.</p>
| [
{
"answer_id": 74304168,
"author": "gusbro",
"author_id": 463243,
"author_profile": "https://Stackoverflow.com/users/463243",
"pm_score": 1,
"selected": false,
"text": "get_lists(LL, _, []):-\n maplist(=([]), LL).\nget_lists(LL, K, [R|LR]):-\n maplist(split(K), LL, LChunks, LRest),\n append(LChunks, R),\n get_lists(LRest, K, LR).\n\nsplit(K, L, Chunk, Rest):-\n length(Chunk, K),\n append(Chunk, Rest, L).\n"
},
{
"answer_id": 74327960,
"author": "brebs",
"author_id": 17628336,
"author_profile": "https://Stackoverflow.com/users/17628336",
"pm_score": 0,
"selected": false,
"text": "rearrange_lists([H|T], BiteLen, RLs) :-\n % Populate the heads, leaving the tails\n spread_list(H, BiteLen, RLs, Tails),\n % Loop through populating the tails\n rearrange_lists_(T, BiteLen, Tails).\n\nrearrange_lists_([], _, Tails) :-\n % Close the tails\n maplist(=([]), Tails).\nrearrange_lists_([H|T], BiteLen, Heads) :-\n spread_list(H, BiteLen, Heads, Tails),\n rearrange_lists_(T, BiteLen, Tails).\n\nspread_list([], _BL, [], []).\nspread_list([H|T], BiteLen, [BiteH|BiteHs], [BiteT|BiteTs]) :-\n copy_list_to_dl_len(BiteLen, [H|T], _HS, HR, BiteH, BiteT),\n spread_list(HR, BiteLen, BiteHs, BiteTs).\n\n% Generic, reusable predicate\ncopy_list_to_dl_len(Len, Lst, LstH, LstT, SubLstH, SubLstT) :-\n ( nonvar(Len)\n -> integer(Len),\n Len @>= 0,\n % Only once\n copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT), !\n ; copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT)\n ).\n \ncopy_list_to_dl_len_inc_(Lst, Lst, Lst, Len, Len, SubLst, SubLst).\ncopy_list_to_dl_len_inc_([H|T], [H|HT], LT, Len, FLen, [H|ST], SLT) :-\n Len1 is Len + 1,\n copy_list_to_dl_len_inc_(T, HT, LT, Len1, FLen, ST, SLT).\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19774005/"
] |
74,300,488 | <p>I want to know if there is a function in python that can pretty print a file path with a maximum number of characters</p>
<pre><code>pretty_print("C:\Program Files\Common Files\Adobe\Keyfiles\dynamiclink\7.0\ConflictingP.xml",max_length=35)
</code></pre>
<p>output</p>
<pre><code>C:\Program Files\...\ConflictingP.xml
</code></pre>
<p>conditions:</p>
<ol>
<li>keep the file name</li>
<li>keep the drive letter</li>
<li>truncate the leading folders to keep the string length less than or equal to the maximum length</li>
</ol>
| [
{
"answer_id": 74304168,
"author": "gusbro",
"author_id": 463243,
"author_profile": "https://Stackoverflow.com/users/463243",
"pm_score": 1,
"selected": false,
"text": "get_lists(LL, _, []):-\n maplist(=([]), LL).\nget_lists(LL, K, [R|LR]):-\n maplist(split(K), LL, LChunks, LRest),\n append(LChunks, R),\n get_lists(LRest, K, LR).\n\nsplit(K, L, Chunk, Rest):-\n length(Chunk, K),\n append(Chunk, Rest, L).\n"
},
{
"answer_id": 74327960,
"author": "brebs",
"author_id": 17628336,
"author_profile": "https://Stackoverflow.com/users/17628336",
"pm_score": 0,
"selected": false,
"text": "rearrange_lists([H|T], BiteLen, RLs) :-\n % Populate the heads, leaving the tails\n spread_list(H, BiteLen, RLs, Tails),\n % Loop through populating the tails\n rearrange_lists_(T, BiteLen, Tails).\n\nrearrange_lists_([], _, Tails) :-\n % Close the tails\n maplist(=([]), Tails).\nrearrange_lists_([H|T], BiteLen, Heads) :-\n spread_list(H, BiteLen, Heads, Tails),\n rearrange_lists_(T, BiteLen, Tails).\n\nspread_list([], _BL, [], []).\nspread_list([H|T], BiteLen, [BiteH|BiteHs], [BiteT|BiteTs]) :-\n copy_list_to_dl_len(BiteLen, [H|T], _HS, HR, BiteH, BiteT),\n spread_list(HR, BiteLen, BiteHs, BiteTs).\n\n% Generic, reusable predicate\ncopy_list_to_dl_len(Len, Lst, LstH, LstT, SubLstH, SubLstT) :-\n ( nonvar(Len)\n -> integer(Len),\n Len @>= 0,\n % Only once\n copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT), !\n ; copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT)\n ).\n \ncopy_list_to_dl_len_inc_(Lst, Lst, Lst, Len, Len, SubLst, SubLst).\ncopy_list_to_dl_len_inc_([H|T], [H|HT], LT, Len, FLen, [H|ST], SLT) :-\n Len1 is Len + 1,\n copy_list_to_dl_len_inc_(T, HT, LT, Len1, FLen, ST, SLT).\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611156/"
] |
74,300,500 | <p>Basically I'm trying to implement three regular expressions as specified below -</p>
<ol>
<li><p>First regular expression should match at the least the literal string 10.1 or any string like 10.1.0.0 or 10.1.1.0 or 10.2.1.0 or 10.2.1.1 and so on but it should at the least match 10.1 or any higher versions. I tried the following regular expression
<code>\d+\.\d+(\.\d+\.\d+)*</code>
but this matches even lower versions such as 9.1.1.0 or 9.1 and so on.</p>
</li>
<li><p>Second regular expression should match anything higher than the string literal 10.1 but not 10.1 but it should match any other string like 10.2 or 10.3 or 10.1.0.0 or 10.1.1.0 or 10.2.1.0 or 10.2.1.1 or 10.2 or 10.3 or 11.1.1.0 or 11.1 and so on. Tried the following but did not match the expectation <code>(\\d+)\\.(\\d+)(.*)</code></p>
</li>
<li><p>Third regular expression should match anything lower than the string literal 10.1 but not 10.1 but it should match any other string like 10.0 or 9.1 or 9.2 or 9.1.1.0 or 9.1 or 9.1.2.0.</p>
</li>
</ol>
<p>Basically how do I match the literal string like 10.1 followed by any optional numbers separated by a dot and how do I match anything higher or lower than the literal string like in my 1st, 2nd and 3rd points?</p>
<p>I'm still trying to modify my regular expression to match my requirement, any help/guidance will be very helpful.</p>
| [
{
"answer_id": 74304168,
"author": "gusbro",
"author_id": 463243,
"author_profile": "https://Stackoverflow.com/users/463243",
"pm_score": 1,
"selected": false,
"text": "get_lists(LL, _, []):-\n maplist(=([]), LL).\nget_lists(LL, K, [R|LR]):-\n maplist(split(K), LL, LChunks, LRest),\n append(LChunks, R),\n get_lists(LRest, K, LR).\n\nsplit(K, L, Chunk, Rest):-\n length(Chunk, K),\n append(Chunk, Rest, L).\n"
},
{
"answer_id": 74327960,
"author": "brebs",
"author_id": 17628336,
"author_profile": "https://Stackoverflow.com/users/17628336",
"pm_score": 0,
"selected": false,
"text": "rearrange_lists([H|T], BiteLen, RLs) :-\n % Populate the heads, leaving the tails\n spread_list(H, BiteLen, RLs, Tails),\n % Loop through populating the tails\n rearrange_lists_(T, BiteLen, Tails).\n\nrearrange_lists_([], _, Tails) :-\n % Close the tails\n maplist(=([]), Tails).\nrearrange_lists_([H|T], BiteLen, Heads) :-\n spread_list(H, BiteLen, Heads, Tails),\n rearrange_lists_(T, BiteLen, Tails).\n\nspread_list([], _BL, [], []).\nspread_list([H|T], BiteLen, [BiteH|BiteHs], [BiteT|BiteTs]) :-\n copy_list_to_dl_len(BiteLen, [H|T], _HS, HR, BiteH, BiteT),\n spread_list(HR, BiteLen, BiteHs, BiteTs).\n\n% Generic, reusable predicate\ncopy_list_to_dl_len(Len, Lst, LstH, LstT, SubLstH, SubLstT) :-\n ( nonvar(Len)\n -> integer(Len),\n Len @>= 0,\n % Only once\n copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT), !\n ; copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT)\n ).\n \ncopy_list_to_dl_len_inc_(Lst, Lst, Lst, Len, Len, SubLst, SubLst).\ncopy_list_to_dl_len_inc_([H|T], [H|HT], LT, Len, FLen, [H|ST], SLT) :-\n Len1 is Len + 1,\n copy_list_to_dl_len_inc_(T, HT, LT, Len1, FLen, ST, SLT).\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3354299/"
] |
74,300,512 | <p>I have daily <code>weather</code> data:</p>
<pre><code> rain (mm)
date
01/01/2022 0.0
02/01/2022 0.5
03/01/2022 2.0
...
</code></pre>
<p>And I have another table (<code>df</code>) broken down by hour</p>
<pre><code> value
datetime
01/01/2022 01:00 x
01/01/2022 02:00 x
01/01/2022 03:00 x
...
</code></pre>
<p>And I want to join them like this:</p>
<pre><code> value rain
datetime
01/01/2022 01:00 x 0.0
01/01/2022 02:00 x 0.0
01/01/2022 03:00 x 0.0
...
02/01/2022 01:00 x 0.5
02/01/2022 02:00 x 0.5
02/01/2022 03:00 x 0.5
...
03/01/2022 01:00 x 2.0
03/01/2022 02:00 x 2.0
03/01/2022 03:00 x 2.0
...
</code></pre>
<p>(nb: all dates are in d%/m%/Y% format, and all dates are the index of their respective df)</p>
<p>I'm sure there is a straight-forward solution, but I can't find it...
Thanks in advance for any help!</p>
| [
{
"answer_id": 74304168,
"author": "gusbro",
"author_id": 463243,
"author_profile": "https://Stackoverflow.com/users/463243",
"pm_score": 1,
"selected": false,
"text": "get_lists(LL, _, []):-\n maplist(=([]), LL).\nget_lists(LL, K, [R|LR]):-\n maplist(split(K), LL, LChunks, LRest),\n append(LChunks, R),\n get_lists(LRest, K, LR).\n\nsplit(K, L, Chunk, Rest):-\n length(Chunk, K),\n append(Chunk, Rest, L).\n"
},
{
"answer_id": 74327960,
"author": "brebs",
"author_id": 17628336,
"author_profile": "https://Stackoverflow.com/users/17628336",
"pm_score": 0,
"selected": false,
"text": "rearrange_lists([H|T], BiteLen, RLs) :-\n % Populate the heads, leaving the tails\n spread_list(H, BiteLen, RLs, Tails),\n % Loop through populating the tails\n rearrange_lists_(T, BiteLen, Tails).\n\nrearrange_lists_([], _, Tails) :-\n % Close the tails\n maplist(=([]), Tails).\nrearrange_lists_([H|T], BiteLen, Heads) :-\n spread_list(H, BiteLen, Heads, Tails),\n rearrange_lists_(T, BiteLen, Tails).\n\nspread_list([], _BL, [], []).\nspread_list([H|T], BiteLen, [BiteH|BiteHs], [BiteT|BiteTs]) :-\n copy_list_to_dl_len(BiteLen, [H|T], _HS, HR, BiteH, BiteT),\n spread_list(HR, BiteLen, BiteHs, BiteTs).\n\n% Generic, reusable predicate\ncopy_list_to_dl_len(Len, Lst, LstH, LstT, SubLstH, SubLstT) :-\n ( nonvar(Len)\n -> integer(Len),\n Len @>= 0,\n % Only once\n copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT), !\n ; copy_list_to_dl_len_inc_(Lst, LstH, LstT, 0, Len, SubLstH, SubLstT)\n ).\n \ncopy_list_to_dl_len_inc_(Lst, Lst, Lst, Len, Len, SubLst, SubLst).\ncopy_list_to_dl_len_inc_([H|T], [H|HT], LT, Len, FLen, [H|ST], SLT) :-\n Len1 is Len + 1,\n copy_list_to_dl_len_inc_(T, HT, LT, Len1, FLen, ST, SLT).\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17767334/"
] |
74,300,536 | <p>I have about 95,000,000 permutations to check.
I have 8 lists of varying length, each string identifies properties (a-k) defined in an excel sheet.
e.g</p>
<pre><code>bcdgj
</code></pre>
<p>has properties b, c, d, g and j</p>
<p>I need to find just one permutation that contains at least 3 of every property and then match those properties to the data in the spreadsheet</p>
<p>I have made this script (my first attempt at using python)</p>
<pre class="lang-py prettyprint-override"><code>import numpy
import itertools
for x in itertools.product(['abfhj','bcdgj','fghij','abcj','bdgk','abgi','cdei','cdgi','dgik','aghi','abgh','bfhk'],['cdei','bcdgj','abcgi','abcj','abfj','bdfj','cdgi','bhjk','bdgk','dgik'],['afhk','cdgik','cegik','bdgi','cgij','cdei','bcgi','abgh'],['fhjk','bdgij','cgij','abk','ajk','bdk','cik','cdk','cei','fgj'],['abe','abcf','afh','cdi','afj','cdg','abi','cei','cgk','ceg','cgi'],['cdgi','bcgj','bcgi','bcdg','abfh','bdhi','bdgi','bdk','fhk','bei','beg','fgi','abf','abc','egi'],['bcdgik','cegik','chik','afhj','abcj','abfj'],['ceg','bcfg','cgi','bdg','afj','cgj','fhk','cfk','dgk','bcj']):
gear = ''.join(x)
count_a = gear.count('a')
count_b = gear.count('b')
count_c = gear.count('c')
count_d = gear.count('d')
count_e = gear.count('e')
count_f = gear.count('f')
count_g = gear.count('g')
count_h = gear.count('h')
count_i = gear.count('i')
count_j = gear.count('j')
count_k = gear.count('k')
score_a = numpy.clip(count_a, 0, 3)
score_b = numpy.clip(count_b, 0, 3)
score_c = numpy.clip(count_c, 0, 3)
score_d = numpy.clip(count_d, 0, 3)
score_e = numpy.clip(count_e, 0, 3)
score_f = numpy.clip(count_f, 0, 3)
score_g = numpy.clip(count_g, 0, 3)
score_h = numpy.clip(count_h, 0, 3)
score_i = numpy.clip(count_i, 0, 3)
score_j = numpy.clip(count_j, 0, 3)
score_k = numpy.clip(count_k, 0, 3)
rating = score_a + score_b + score_c + score_d + score_e + score_f + score_g + score_h + score_i + score_j + score_k
if rating == 33:
print(x)
print(rating)
</code></pre>
<p>I've adjusted the rating requirement to test that it's working, it is but it's going to take a while to crunch through 95,000,000 permutations. Anyone have any advice for getting it to run faster?
I think I've already reduced the number of values in each list as much as I can, the excel sheet the data comes from has several hundred entries per list and I've managed to reduce it to 6-12 per list.</p>
| [
{
"answer_id": 74301567,
"author": "LurkerZ",
"author_id": 11957401,
"author_profile": "https://Stackoverflow.com/users/11957401",
"pm_score": 1,
"selected": true,
"text": "from itertools import groupby, product\n\ndata = (\n ['abfhj','bcdgj','fghij','abcj','bdgk','abgi','cdei','cdgi','dgik','aghi','abgh','bfhk'],\n ['cdei','bcdgj','abcgi','abcj','abfj','bdfj','cdgi','bhjk','bdgk','dgik'],\n ['afhk','cdgik','cegik','bdgi','cgij','cdei','bcgi','abgh'],\n ['fhjk','bdgij','cgij','abk','ajk','bdk','cik','cdk','cei','fgj'],\n ['abe','abcf','afh','cdi','afj','cdg','abi','cei','cgk','ceg','cgi'],\n ['cdgi','bcgj','bcgi','bcdg','abfh','bdhi','bdgi','bdk','fhk','bei','beg','fgi','abf','abc ','egi'],\n ['bcdgik','cegik','chik','afhj','abcj','abfj'],\n ['ceg','bcfg','cgi','bdg','afj','cgj','fhk','cfk','dgk','bcj'],\n)\n\nREQ_PROPS = set(\"abcdefghijk\")\n\nfor x in product(*data):\n permu = ''.join(x)\n # if the permutation does not contain all letters from a-k, skip it.\n if REQ_PROPS.difference(permu):\n continue\n\n prop_map = dict.fromkeys(permu)\n for prop, group in groupby(sorted(permu)):\n group_rating = len(tuple(group))\n # dont bother searching more props of this permutation if the current\n # property has a rating less than 3\n if group_rating < 3:\n break\n prop_map[prop] = group_rating\n # check if this permutation satisfies the requirement and exit if it does.\n if all(v is not None for v in prop_map.values()):\n print(x)\n print(prop_map) # total rating of each property\n break\n"
},
{
"answer_id": 74302849,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "gear.count"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20402953/"
] |
74,300,556 | <p>I encountered a problem within my research for my internship. I made a script that gathered specific data from the instagram API. Is it possible to reproduce this script in a loop weekly via an option in Azure? I can't quite find it.</p>
<p>Thanks in advance!</p>
<p>I hard coded it within the python script option in Azure but I want to automate it.</p>
| [
{
"answer_id": 74301567,
"author": "LurkerZ",
"author_id": 11957401,
"author_profile": "https://Stackoverflow.com/users/11957401",
"pm_score": 1,
"selected": true,
"text": "from itertools import groupby, product\n\ndata = (\n ['abfhj','bcdgj','fghij','abcj','bdgk','abgi','cdei','cdgi','dgik','aghi','abgh','bfhk'],\n ['cdei','bcdgj','abcgi','abcj','abfj','bdfj','cdgi','bhjk','bdgk','dgik'],\n ['afhk','cdgik','cegik','bdgi','cgij','cdei','bcgi','abgh'],\n ['fhjk','bdgij','cgij','abk','ajk','bdk','cik','cdk','cei','fgj'],\n ['abe','abcf','afh','cdi','afj','cdg','abi','cei','cgk','ceg','cgi'],\n ['cdgi','bcgj','bcgi','bcdg','abfh','bdhi','bdgi','bdk','fhk','bei','beg','fgi','abf','abc ','egi'],\n ['bcdgik','cegik','chik','afhj','abcj','abfj'],\n ['ceg','bcfg','cgi','bdg','afj','cgj','fhk','cfk','dgk','bcj'],\n)\n\nREQ_PROPS = set(\"abcdefghijk\")\n\nfor x in product(*data):\n permu = ''.join(x)\n # if the permutation does not contain all letters from a-k, skip it.\n if REQ_PROPS.difference(permu):\n continue\n\n prop_map = dict.fromkeys(permu)\n for prop, group in groupby(sorted(permu)):\n group_rating = len(tuple(group))\n # dont bother searching more props of this permutation if the current\n # property has a rating less than 3\n if group_rating < 3:\n break\n prop_map[prop] = group_rating\n # check if this permutation satisfies the requirement and exit if it does.\n if all(v is not None for v in prop_map.values()):\n print(x)\n print(prop_map) # total rating of each property\n break\n"
},
{
"answer_id": 74302849,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "gear.count"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7188924/"
] |
74,300,597 | <p>I have a .NET Framework 4.8 application (Windows service) which sends and receives data over UDP.
Sometimes, randomly, on one of the ports, when calling socket.BeginReceiveFrom, the exception with error code 10054 is thrown</p>
<p>The code:<br />
NOTE: This code is just snippet. This is not fully functional solution equipped with error handling</p>
<pre><code>
private Socket serverSocket = null;
private byte[] byteData = new byte[1024];
private void DoReceiveFrom(IAsyncResult iar)
{
EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
int dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
if (dataLen > 0)
{
// Do something with the data
}
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
// This is the part which throws an exception randomly
this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
}
</code></pre>
<p>The error:</p>
<pre><code>"System.Net.Sockets.SocketException (0x80004005): The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress
at System.Net.Sockets.Socket.DoBeginReceiveFrom(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint endPointSnapshot, SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
at System.Net.Sockets.Socket.BeginReceiveFrom(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint& remoteEP, AsyncCallback callback, Object state)"
</code></pre>
<ul>
<li><p>There are about 10,000 simultaneously "connected" clients (remote controllers connected via cellular network)</p>
</li>
<li><p>The program listens on approximately 30 UDP ports, and controllers are distributed roughly evenly across the ports</p>
</li>
<li><p>Each controller sends/receives about 10 small data packets per minute</p>
</li>
</ul>
<p>I can't just "ignore" this error (as recommended on some internet posts), because after BeginReceiveFrom fails with an exception, the socket cannot receive other data</p>
<p>The only practical way I've found is to close current socket and create the new one, binded to the same port. This doesn't seem like the right thing because:<br />
First, I lose packets that were already received at the time of the exception, but not yet "handled" by the application<br />
Second, during the time between closing the current socket and creating a new one, the current port is not available to clients<br />
And third, and most importantly (to my mind), such solution does not look "correct" and "elegant"</p>
<p>So, what the "best", "By the Book" solution you can suggest me for this case?</p>
| [
{
"answer_id": 74301567,
"author": "LurkerZ",
"author_id": 11957401,
"author_profile": "https://Stackoverflow.com/users/11957401",
"pm_score": 1,
"selected": true,
"text": "from itertools import groupby, product\n\ndata = (\n ['abfhj','bcdgj','fghij','abcj','bdgk','abgi','cdei','cdgi','dgik','aghi','abgh','bfhk'],\n ['cdei','bcdgj','abcgi','abcj','abfj','bdfj','cdgi','bhjk','bdgk','dgik'],\n ['afhk','cdgik','cegik','bdgi','cgij','cdei','bcgi','abgh'],\n ['fhjk','bdgij','cgij','abk','ajk','bdk','cik','cdk','cei','fgj'],\n ['abe','abcf','afh','cdi','afj','cdg','abi','cei','cgk','ceg','cgi'],\n ['cdgi','bcgj','bcgi','bcdg','abfh','bdhi','bdgi','bdk','fhk','bei','beg','fgi','abf','abc ','egi'],\n ['bcdgik','cegik','chik','afhj','abcj','abfj'],\n ['ceg','bcfg','cgi','bdg','afj','cgj','fhk','cfk','dgk','bcj'],\n)\n\nREQ_PROPS = set(\"abcdefghijk\")\n\nfor x in product(*data):\n permu = ''.join(x)\n # if the permutation does not contain all letters from a-k, skip it.\n if REQ_PROPS.difference(permu):\n continue\n\n prop_map = dict.fromkeys(permu)\n for prop, group in groupby(sorted(permu)):\n group_rating = len(tuple(group))\n # dont bother searching more props of this permutation if the current\n # property has a rating less than 3\n if group_rating < 3:\n break\n prop_map[prop] = group_rating\n # check if this permutation satisfies the requirement and exit if it does.\n if all(v is not None for v in prop_map.values()):\n print(x)\n print(prop_map) # total rating of each property\n break\n"
},
{
"answer_id": 74302849,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "gear.count"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2134809/"
] |
74,300,638 | <p>I have one VStack and another HStack with buttons inside. I faced problem with shrinking buttons based on their content even though I tried to set fixed width and height of Buttons.</p>
<p>Here is the main screen:</p>
<pre><code>import Foundation
import SwiftUI
import SwiftUINavigator
struct SurveyScreenView: View, IItemView {
var listener: INavigationContainer?
@State var survey: Survey
@State var isUp = false
@State var isDown = false
@State var widthButton: CGFloat = 100
@State var heightButton: CGFloat = 50
var body: some View {
NavigationView {
VStack(alignment: .leading, spacing: 32) {
Text(survey.title)
.font(.title)
Text(survey.description)
VoteView( survey: $survey, isUp: $isUp, isDown: $isDown)
Spacer()
}
.navigationBarItems(leading:
Button(action: {
listener?.pop()
}, label: {
Text("Feed")
})
)
.navigationBarTitle(Text("Survey"))
.navigationBarTitleDisplayMode(.inline)
.padding()
}
}
}
</code></pre>
<p>View with Buttons in HStack</p>
<pre><code>struct VoteView: View {
@Binding var survey: Survey
@Binding var isUp: Bool
@Binding var isDown: Bool
var body: some View {
HStack(alignment: .center, spacing: 64) {
VoteButton (
isVoted: $isUp,
counter: survey.upVotes,
text: "YES"
) {
self.isUp.toggle()
if isUp == isDown {
self.isDown.toggle()
}
}
VoteButton (
isVoted: $isDown,
counter: survey.downVotes,
text: "NO"
) {
self.isDown.toggle()
if isUp == isDown {
self.isUp.toggle()
}
}
}
}
}
</code></pre>
<p>Cutom button view</p>
<pre><code>struct VoteButton: View {
@Binding var isVoted: Bool
var counter: Int = 0
var text: String = ""
var clicked: (() -> Void)
var body: some View {
if isVoted {
Button(action: clicked) {
VStack(alignment: .center, spacing: 5) {
Text(text)
.font(.headline)
Text("\(counter)")
.font(.subheadline)
}
.foregroundColor(.white)
.background(.blue)
.cornerRadius(8)
.frame(maxWidth: .infinity, minHeight: 40)
}
} else {
Button(action: clicked) {
VStack(alignment: .center, spacing: 5) {
Text(text)
.font(.headline)
Text("\(counter)")
.font(.subheadline)
}
.foregroundColor(.blue)
.background(.white)
.overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.blue, lineWidth: 2))
.frame(maxWidth: .infinity, minHeight: 40)
}
}
}
}
</code></pre>
<p>I tried several tutorials, for <a href="https://betterprogramming.pub/swiftui-tutorial-working-with-stacks-vstack-hstack-and-zstack-2b0070be18d7" rel="nofollow noreferrer">example</a>. Also tried this <a href="https://stackoverflow.com/questions/65607172/swiftui-hstack-elements-with-equal-height">solution</a>.</p>
<p>I got the same result everywhere, like this one:
<a href="https://i.stack.imgur.com/88Dbs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/88Dbs.png" alt="bad" /></a></p>
<p>But I am actually expecting this result:
<a href="https://i.stack.imgur.com/yR2Ar.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yR2Ar.png" alt="good" /></a></p>
| [
{
"answer_id": 74301567,
"author": "LurkerZ",
"author_id": 11957401,
"author_profile": "https://Stackoverflow.com/users/11957401",
"pm_score": 1,
"selected": true,
"text": "from itertools import groupby, product\n\ndata = (\n ['abfhj','bcdgj','fghij','abcj','bdgk','abgi','cdei','cdgi','dgik','aghi','abgh','bfhk'],\n ['cdei','bcdgj','abcgi','abcj','abfj','bdfj','cdgi','bhjk','bdgk','dgik'],\n ['afhk','cdgik','cegik','bdgi','cgij','cdei','bcgi','abgh'],\n ['fhjk','bdgij','cgij','abk','ajk','bdk','cik','cdk','cei','fgj'],\n ['abe','abcf','afh','cdi','afj','cdg','abi','cei','cgk','ceg','cgi'],\n ['cdgi','bcgj','bcgi','bcdg','abfh','bdhi','bdgi','bdk','fhk','bei','beg','fgi','abf','abc ','egi'],\n ['bcdgik','cegik','chik','afhj','abcj','abfj'],\n ['ceg','bcfg','cgi','bdg','afj','cgj','fhk','cfk','dgk','bcj'],\n)\n\nREQ_PROPS = set(\"abcdefghijk\")\n\nfor x in product(*data):\n permu = ''.join(x)\n # if the permutation does not contain all letters from a-k, skip it.\n if REQ_PROPS.difference(permu):\n continue\n\n prop_map = dict.fromkeys(permu)\n for prop, group in groupby(sorted(permu)):\n group_rating = len(tuple(group))\n # dont bother searching more props of this permutation if the current\n # property has a rating less than 3\n if group_rating < 3:\n break\n prop_map[prop] = group_rating\n # check if this permutation satisfies the requirement and exit if it does.\n if all(v is not None for v in prop_map.values()):\n print(x)\n print(prop_map) # total rating of each property\n break\n"
},
{
"answer_id": 74302849,
"author": "Jérôme Richard",
"author_id": 12939557,
"author_profile": "https://Stackoverflow.com/users/12939557",
"pm_score": 1,
"selected": false,
"text": "gear.count"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19561698/"
] |
74,300,639 | <p>I am getting linting errors as follows. Why is this occurring even when I destruct?</p>
<blockquote>
<p>error Must use destructuring props assignment
react/destructuring-assignment</p>
</blockquote>
<p>The lines with issues.</p>
<pre><code>const { imageName, header, description } = props.cardContentData || {};
const { description, content = [] } = props.cardData || {};
</code></pre>
| [
{
"answer_id": 74300723,
"author": "kar",
"author_id": 2840178,
"author_profile": "https://Stackoverflow.com/users/2840178",
"pm_score": 1,
"selected": false,
"text": "props.cardData"
},
{
"answer_id": 74301036,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 0,
"selected": false,
"text": "const { cardContentData: { imageName, header, description } = {} } = props;\nconst { cardData: { description, content = [] } = {} } = props;\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9401029/"
] |
74,300,646 | <p>I'm trying to do a mass-update of an enum column's value in my Laravel 9 project through tinker, my model is called <code>Domain</code> and I have an enum column called <code>status</code> with different values.</p>
<p>I'd like to select all entries where <code>status</code> is <strong>expired</strong> and set them to a different value.</p>
<p>I've tried running this in Tinker but it throws an error:</p>
<blockquote>
<p>PHP Deprecated: Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically in /Users/ryanholton/Sites/fudge-apieval()'d code on line 1</p>
</blockquote>
<pre class="lang-php prettyprint-override"><code>Domain::where('status', 'expired')->update(['status' => 'pending']);
</code></pre>
<p>What am I missing?</p>
| [
{
"answer_id": 74301128,
"author": "NIKUNJ KOTHIYA",
"author_id": 14870617,
"author_profile": "https://Stackoverflow.com/users/14870617",
"pm_score": 1,
"selected": false,
"text": "Domain::query()->where('status', 'expired')->update(['status' => 'pending']);\n"
},
{
"answer_id": 74301164,
"author": "Ramil Huseynov",
"author_id": 6711823,
"author_profile": "https://Stackoverflow.com/users/6711823",
"pm_score": 3,
"selected": true,
"text": "\nDomain::query()->where('status', 'expired')->update(['status' => 'pending']);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9982090/"
] |
74,300,664 | <p>I have a data where the key <code>count</code> appears 6 times and it is nested. I'm trying count the number of times it appears with below logic but somewhat I'm close to it not got the exact result.</p>
<p>The problem is child values I'm getting as 7 which I have consoled. but the final count is always 1 seriously I don't know why I'm getting 1. Any help!</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>let data = [{
"id": "1",
"child": [
{
"id": "12",
"child": [
{
"id": "123",
"child": [
{
"id": "1234"
}
]
}
]
},
{
"id": "2",
"child": [
{
"id": "22"
}
]
},
{
"id": "3"
},
{
"id": "4",
"child": [
{
"id": "42",
"child": [
{
"id": "43"
}
]
}
]
}
]
}]
const countChild = (arr,cnt = 0) => {
for (const {child} of arr) {
cnt = cnt + 1
console.log("child",cnt)
if(child) countChild(child, cnt)
}
return cnt;
};
console.log("Final count",countChild(data))</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74300737,
"author": "JStw",
"author_id": 8597732,
"author_profile": "https://Stackoverflow.com/users/8597732",
"pm_score": 3,
"selected": true,
"text": "reduce"
},
{
"answer_id": 74300868,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 2,
"selected": false,
"text": "let data = [{\n \"id\": \"1\",\n \"child\": [\n {\n \"id\": \"12\",\n \"child\": [\n {\n \"id\": \"123\",\n \"child\": [\n {\n \"id\": \"1234\"\n }\n ]\n }\n ]\n },\n {\n \"id\": \"2\",\n \"child\": [\n {\n \"id\": \"22\"\n }\n ]\n },\n {\n \"id\": \"3\"\n },\n {\n \"id\": \"4\",\n \"child\": [\n {\n\n \"id\": \"42\",\n \"child\": [\n {\n\n \"id\": \"43\"\n }\n ]\n }\n ]\n }\n ]\n}]\n\nconst flatChild = (arr) => \n arr.flatMap(({id, child}) => [id, ...flatChild(child || [])] ) \n\nconst countChild = arr => flatChild(arr).length\n\n\n\nconsole.log(\"Final count\", countChild(data))"
},
{
"answer_id": 74300909,
"author": "shubham patil",
"author_id": 4580405,
"author_profile": "https://Stackoverflow.com/users/4580405",
"pm_score": 0,
"selected": false,
"text": "let data = [{\n \"id\": \"1\",\n \"child\": [\n {\n \"id\": \"12\",\n \"child\": [\n {\n \"id\": \"123\",\n \"child\": [\n {\n \"id\": \"1234\"\n }\n ]\n }\n ]\n },\n {\n \"id\": \"2\",\n \"child\": [\n {\n \"id\": \"22\"\n }\n ]\n },\n {\n \"id\": \"3\"\n },\n {\n \"id\": \"4\",\n \"child\": [\n {\n\n \"id\": \"42\",\n \"child\": [\n {\n\n \"id\": \"43\"\n }\n ]\n }\n ]\n }\n ]\n}];\n\nlet cnt = 0;\n\nconst countChild = (arr) => {\n for (const {child} of arr) {\n cnt = cnt + 1;\n console.log(\"child\",cnt);\n if(child) countChild(child);\n }\n return cnt;\n};\nconsole.log(\"Final count\",countChild(data));"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8750174/"
] |
74,300,669 | <p>I have translated Bengali phonetics into English. But after parsing, I got some trash characters, which I want to remove. My data frame looks like this.</p>
<pre><code>col1
utto্tor
dokkho্shin
muuns্si
</code></pre>
<p>So I want to remove the trash character along with its previous and following character as well. For example: In the first row, I want to remove <strong>্</strong> - this character and also the character <strong>o</strong> and <strong>t</strong>, which is the adjacent of <strong>্</strong> (this) character.</p>
<p>My desired output is looks like the following-</p>
<pre><code>col1 col2
utto্tor uttor
dokkho্shin dokkhhin
muuns্si muuni
</code></pre>
<p><em><strong>P.S.</strong></em> I have got these kind of character by using <em>Avro parser</em> which looks like below:</p>
<pre><code>reversed_text = avro.reverse("উত্তর")
print(reversed_text)
output: utto্tor
</code></pre>
<pre><code>col0 col1
উত্তর utto্tor
দক্ষিণ dokkho্shin
মুন্সী muuns্si
</code></pre>
| [
{
"answer_id": 74300885,
"author": "Marcel Flygare",
"author_id": 5816681,
"author_profile": "https://Stackoverflow.com/users/5816681",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\n\ndf = pd.DataFrame({'Col1': ['Text1', 'Text2']})\ndf['Col1'] = df['Col1'].str.replace(\"Text\", \"newText\")\ndf\n"
},
{
"answer_id": 74300948,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "str.replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13019735/"
] |
74,300,692 | <p>I have created a asp.net core 6 mvc web application. I did not add user authorization from start but added ASP.NET Core Identity afterwards instead. My question is how do I make all pages password protected except the actual login page that the users shoud be redirected to if they havent logged in yet? Is that something I configure in program.cs or how do i do that?</p>
<p>here is my <strong>program.cs</strong> file...</p>
<pre><code> var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
// Add services to the container.
builder.Services.AddControllersWithViews();
var connectionString = builder.Configuration.GetConnectionString("AppDb");
builder.Services.AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString));
builder.Services.AddIdentityCore<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthenticationCheck();
//app.UseAuthentication();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
</code></pre>
<p>Update I added this middleware to check if user is authenticated, if not he need to login on the login page. But it does not work beacuse I get a error telling me "localhost redirected you too many times."</p>
<p>Here is my middleware..</p>
<pre><code> public class AuthenticationCheck
{
private readonly RequestDelegate _next;
public AuthenticationCheck(RequestDelegate next, ILoggerFactory logFactory)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.User.Identity != null || !httpContext.User.Identity.IsAuthenticated)
{
httpContext.Response.Redirect("Login");
}
else
{
await _next(httpContext);
}
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class AuthenticationCheckExtensions
{
public static IApplicationBuilder UseAuthenticationCheck(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AuthenticationCheck>();
}
}
</code></pre>
<p>What am I missing here...?</p>
| [
{
"answer_id": 74308331,
"author": "Milad Karimifard",
"author_id": 17797258,
"author_profile": "https://Stackoverflow.com/users/17797258",
"pm_score": 3,
"selected": true,
"text": "Authorized"
},
{
"answer_id": 74311643,
"author": "Md Farid Uddin Kiron",
"author_id": 9663070,
"author_profile": "https://Stackoverflow.com/users/9663070",
"pm_score": 0,
"selected": false,
"text": "infinite loop"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2153383/"
] |
74,300,711 | <p>I made an api query which returns a json as response. I am trying to extract the temperature_2m for the first time in the list (2022-11-03T00:00) which is 5.7, not sure how to get it with python</p>
<pre><code>api_query ={
"latitude": 52.52,
"longitude": 13.419998,
"generationtime_ms": 0.36203861236572266,
"utc_offset_seconds": 0,
"timezone": "GMT",
"timezone_abbreviation": "GMT",
"elevation": 38.0,
"hourly_units": {
"time": "iso8601",
"temperature_2m": "°C"
},
"hourly": {
"time": [
"2022-11-03T00:00",
"2022-11-03T01:00"
],
"temperature_2m": [
5.7,
5.2
]
}
}
for key in api_query:
temperature = api_query['hourly']['time'][0]['temperature_2m']
print(temperature)
</code></pre>
| [
{
"answer_id": 74308331,
"author": "Milad Karimifard",
"author_id": 17797258,
"author_profile": "https://Stackoverflow.com/users/17797258",
"pm_score": 3,
"selected": true,
"text": "Authorized"
},
{
"answer_id": 74311643,
"author": "Md Farid Uddin Kiron",
"author_id": 9663070,
"author_profile": "https://Stackoverflow.com/users/9663070",
"pm_score": 0,
"selected": false,
"text": "infinite loop"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6768849/"
] |
74,300,725 | <p>I was following the <a href="https://www.stackoverflow.com/">doc</a> and wanted to access filename and content when reading text files. I have the text files in GCP storage, (in compressed format - gzip) while trying to read the files it gives me the error as below:</p>
<pre><code>Error message from worker: Traceback (most recent call last):
File "apache_beam/runners/common.py", line 1417, in apache_beam.runners.common.DoFnRunner.process
File "apache_beam/runners/common.py", line 624, in apache_beam.runners.common.SimpleInvoker.invoke_process
File "/home/dc/.virtualenvs/bots/lib/python3.8/site-packages/apache_beam/transforms/core.py", line 1845, in <lambda>
wrapper = lambda x: [fn(x)]
File "/home/dc/office_projects/BI-pipelines/bots_dataflows/templates/adjust_events_dataflow.py", line 94, in <lambda>
File "/usr/local/lib/python3.8/site-packages/apache_beam/io/fileio.py", line 232, in read_utf8
return self.open().read().decode('utf-8')
File "/usr/local/lib/python3.8/site-packages/apache_beam/io/filesystem.py", line 264, in read
self._fetch_to_internal_buffer(num_bytes)
File "/usr/local/lib/python3.8/site-packages/apache_beam/io/filesystem.py", line 218, in _fetch_to_internal_buffer
while not self._read_eof and (self._read_buffer.tell() -
TypeError: '<' not supported between instances of 'int' and 'NoneType'
</code></pre>
<p>Following the same code available in doc (below), with the my file location.</p>
<pre><code>with beam.Pipeline() as pipeline:
readable_files = (
pipeline
| fileio.MatchFiles('<*filname.patterns>')
| fileio.ReadMatches()
| beam.Reshuffle())
files_and_contents = (
readable_files
| beam.Map(lambda x: (x.metadata.path, x.read_utf8())))
</code></pre>
<p>I tried logging the details, and I've got path name correctly but only the <code>read_utf8()</code> gives me this error, what I am missing here?</p>
| [
{
"answer_id": 74308331,
"author": "Milad Karimifard",
"author_id": 17797258,
"author_profile": "https://Stackoverflow.com/users/17797258",
"pm_score": 3,
"selected": true,
"text": "Authorized"
},
{
"answer_id": 74311643,
"author": "Md Farid Uddin Kiron",
"author_id": 9663070,
"author_profile": "https://Stackoverflow.com/users/9663070",
"pm_score": 0,
"selected": false,
"text": "infinite loop"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11483935/"
] |
74,300,730 | <p>I am making a todo list and in the following <code>Tasks</code> component I have an <code>li</code> component with mapped data.
I want to conditionally add a strikethrough on the task for which I used a <code>useState</code> hook with initial property as <code>null</code>.</p>
<p>I then added <code>onClick</code> functions to change state to <code>true</code> and <code>false</code> respectively but my style is not being applied :(</p>
<p>Below is the code for the same</p>
<pre><code>import React, {useState} from 'react';
import "./Tasks.css";
import DoneIcon from '@mui/icons-material/Done';
import CloseIcon from '@mui/icons-material/Close';
function Tasks(props) {
const [done, setDone] = useState(null);
return (
<div className="tasks">
{props.items.map(item => (
<li key={item.id} onClick={() => setDone(false)} style={{textDecorationLine: done && 'line-through'}}>{item.text}
<div>
<button onClick={() => setDone(true)} style={{color: "green"}}><DoneIcon/></button>
<button style={{color: "red"}}><CloseIcon/></button>
</div>
</li>
))}
</div>
)
}
export default Tasks;
</code></pre>
| [
{
"answer_id": 74300812,
"author": "Tuan",
"author_id": 8850735,
"author_profile": "https://Stackoverflow.com/users/8850735",
"pm_score": -1,
"selected": false,
"text": "item.id"
},
{
"answer_id": 74301860,
"author": "Fernando SA",
"author_id": 1077412,
"author_profile": "https://Stackoverflow.com/users/1077412",
"pm_score": 0,
"selected": false,
"text": "onClick"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19710733/"
] |
74,300,732 | <p>I have configured minikube and am trying to run kubenetes on my local ubuntu machine.
When I build the MongoDB docker image on my local, I can pass the env variables this way and it works well with the backend API:</p>
<pre><code>mongo_db:
image: mongo:latest
container_name: db_container
environment:
- MONGODB_INITDB_DATABASE=contacts
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=password
ports:
- 27017:27017
volumes:
- ./mongodb_data_container:/data/db
</code></pre>
<p>But when I try to run the entire application(frontend, backend, and MongoDB) in Kubernetes, how do I initiate the MongoDB with the env variables so the backend API can connect to the database pod instance? I'm pulling latest mongodb instance, here's the mongo-deployment yaml file:</p>
<pre><code># MongoDB Deployment - Database
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongo
spec:
selector:
matchLabels:
app: mern-stack
replicas: 1
template:
metadata:
labels:
app: mern-stack
spec:
containers:
- name: mern-stack
image: mongo:latest
ports:
- containerPort: 27017
volumeMounts:
- name: db-data
mountPath: /data
readOnly: false
volumes:
- name: db-data
persistentVolumeClaim:
claimName: mern-stack-data
</code></pre>
<p>I have tried to pass the env variables this way, but it doesn't seem to work:</p>
<pre><code>...
volumeMounts:
- name: db-data
mountPath: /data
readOnly: false
env:
- name: MONGODB_INITDB_DATABASE
value: "contacts"
- name: MONGO_INITDB_ROOT_USERNAME
value: "root"
- name: MONGO_INITDB_ROOT_PASSWORD
value: "password"
...
</code></pre>
<p>What's the quick solution? Should I try config map and secret eventually?</p>
| [
{
"answer_id": 74300812,
"author": "Tuan",
"author_id": 8850735,
"author_profile": "https://Stackoverflow.com/users/8850735",
"pm_score": -1,
"selected": false,
"text": "item.id"
},
{
"answer_id": 74301860,
"author": "Fernando SA",
"author_id": 1077412,
"author_profile": "https://Stackoverflow.com/users/1077412",
"pm_score": 0,
"selected": false,
"text": "onClick"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12743692/"
] |
74,300,733 | <p>We are using two libraries WireMock.Net & WireMock.Net.RestClient which are reporting vulnerabilities in our dependency checker (NVD). Both of those libs are version 1.5.9.</p>
<p><a href="https://i.stack.imgur.com/3eJzI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3eJzI.png" alt="Summary" /></a></p>
<p>The following are listed as published vulnerabilities with most set at Medium some two or three are rated high & at least one is rated critical.</p>
<ul>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2018-8909" rel="nofollow noreferrer">CVE-2018-8909</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2018-9116" rel="nofollow noreferrer">CVE-2018-9116</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2018-9117" rel="nofollow noreferrer">CVE-2018-9117</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-15258" rel="nofollow noreferrer">CVE-2020-15258</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2020-27853" rel="nofollow noreferrer">CVE-2020-27853</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-21301" rel="nofollow noreferrer">CVE-2021-21301</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-32665" rel="nofollow noreferrer">CVE-2021-32665</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-32666" rel="nofollow noreferrer">CVE-2021-32666</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-32755" rel="nofollow noreferrer">CVE-2021-32755</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2021-41093" rel="nofollow noreferrer">CVE-2021-41093</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2022-23625" rel="nofollow noreferrer">CVE-2022-23625</a>,</li>
<li><a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2022-31009" rel="nofollow noreferrer">CVE-2022-31009</a></li>
</ul>
<p>I have already upgraded from an earlier version which only had one vulnerability (relating to wire IOS). Upgrading has pulled in the RestClient &, apparently, a new bunch of vulnerabilities. There is no further option to upgrade as WireMock.net 1.5.9 is the latest stable even though some of the vulnerabilities list versions before 2.16 as the problem. I suspect that is mixed up with Java or other versions of WireMock.</p>
<p>So,</p>
<ol>
<li><p>Do I need to move away from from this library or are these
vulnerabilities false positive?</p>
</li>
<li><p>how do I move away from this library?</p>
</li>
<li><p>Which library would be best to replace this one?</p>
</li>
</ol>
<p><a href="https://ossindex.sonatype.org/component/pkg:nuget/WireMock.Net.RestClient@1.5.9?utm_source=dependency-check&utm_medium=integration&utm_content=6.1.5" rel="nofollow noreferrer">RestClient</a>
<a href="https://ossindex.sonatype.org/component/pkg:nuget/WireMock.Net@1.5.9?utm_source=dependency-check&utm_medium=integration&utm_content=6.1.5" rel="nofollow noreferrer">wiremock.net</a></p>
<p>Thanks for any help in advance.</p>
| [
{
"answer_id": 74419965,
"author": "Stef Heyenrath",
"author_id": 255966,
"author_profile": "https://Stackoverflow.com/users/255966",
"pm_score": 0,
"selected": false,
"text": "ossindex.sonatype.org"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535658/"
] |
74,300,756 | <p>It is a bit too hard to find a fitting title for the problem. So if you have an object:</p>
<pre class="lang-js prettyprint-override"><code>const primary = {
green: {
dark: '#dark' <-- hex code
light: '#light'
...: '#...'
}
}
</code></pre>
<p>I would like the following functionality.</p>
<ol>
<li><p>If I do <code>console.log(primary.green)</code> this should return a default hex string: <code>#def</code> and not the object <code>{ dark: ..., light: ... }</code></p>
</li>
<li><p>If I do <code>console.log(primary.green.dark)</code> this should return the hex string <code>#dark</code></p>
</li>
</ol>
<p>A clear option would be to add <code>default</code> attribute inside the <code>primary.green</code> object. So it would be <code>primary.green.default</code>. However I would like to avoid this.</p>
<p>I have tried to do thinks with getter, but was unsuccessful.</p>
| [
{
"answer_id": 74300955,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "x"
},
{
"answer_id": 74301025,
"author": "DulacreMi",
"author_id": 20381696,
"author_profile": "https://Stackoverflow.com/users/20381696",
"pm_score": 1,
"selected": false,
"text": "const primary = {\n green: {\n dark: '#dark',\n light: '#light'\n }\n}\n\nconst handler = {\n get: (obj, prop, receiver) => {\n return (key) => obj[prop][key] || obj[prop].dark\n }\n}\n\nconst proxyPrimary = new Proxy(primary, handler)\nconsole.log(proxyPrimary.green())\nconsole.log(proxyPrimary.green('light'))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7791653/"
] |
74,300,783 | <p>I currently have the following HTML tree:</p>
<pre><code><!-- App.vue -->
<main>
<!-- Header.vue -->
<header>
<!-- Nav.vue -->
<nav>
<button type="button">Click here should focus on the <a> link</button>
</nav>
</header>
<a ref="link" tabindex="0">External link</a>
</main>
</code></pre>
<p>When clicking on the <code>button</code>, I need to focus on the <code><a></code>. How can I get the reference to this link in my Nav.vue file ?</p>
<p>I can do something like <code>this.$parent.$parent.refs.link.focus()</code> but that is not very maintainable and I would rather not.</p>
| [
{
"answer_id": 74300955,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "x"
},
{
"answer_id": 74301025,
"author": "DulacreMi",
"author_id": 20381696,
"author_profile": "https://Stackoverflow.com/users/20381696",
"pm_score": 1,
"selected": false,
"text": "const primary = {\n green: {\n dark: '#dark',\n light: '#light'\n }\n}\n\nconst handler = {\n get: (obj, prop, receiver) => {\n return (key) => obj[prop][key] || obj[prop].dark\n }\n}\n\nconst proxyPrimary = new Proxy(primary, handler)\nconsole.log(proxyPrimary.green())\nconsole.log(proxyPrimary.green('light'))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058398/"
] |
74,300,795 | <p>I have these five tables and have an expected outcome for JOIN them.</p>
<p><strong>Example</strong></p>
<p>Table <em>JobShipment</em></p>
<p><a href="https://i.stack.imgur.com/FZvC6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FZvC6.png" alt="enter image description here" /></a></p>
<p>Table <em>Jobheader</em></p>
<p><a href="https://i.stack.imgur.com/JCYzL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JCYzL.png" alt="enter image description here" /></a></p>
<p>Table <em>Branch</em></p>
<p><a href="https://i.stack.imgur.com/bC9cM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bC9cM.png" alt="enter image description here" /></a></p>
<p>Table <em>Company</em></p>
<p><a href="https://i.stack.imgur.com/sXO2v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sXO2v.png" alt="enter image description here" /></a></p>
<p>Table <em>Notetext</em></p>
<p><a href="https://i.stack.imgur.com/9sHRD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9sHRD.png" alt="enter image description here" /></a></p>
<p><strong>My Expected outcome</strong></p>
<p><a href="https://i.stack.imgur.com/8qaLz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8qaLz.png" alt="enter image description here" /></a></p>
<p>The outcome is not what I expected.</p>
<p><strong>My query and result</strong></p>
<pre><code>SELECT JS.JS_JobNumber as 'JobNumber', gbb.GB_Code AS 'Branch' , gb.GB_Code as 'Company' ,jh.jh_Dept as 'Dept', ST.ST_NoteText AS 'Note Text'
FROM notetext st (NOLOCK)
LEFT JOIN Company gc (NOLOCK) on st.st_gc_relatedCompany = gc.gc_pk
LEFT JOIN jobshipment js (NOLOCK) ON st.ST_ParentID = js.JS_PK
LEFT JOIN jobheader jh (NOLOCK) on jh.jh_parentID = js.js_pk
left JOIN Branch gbb (NOLOCK) on jh.jh_ge = gbb.GB_PK
left JOIN Branch gb (NOLOCK) ON GB.gb_company = gc.gc_pk AND gbb.gb_pk = gb.gb_pk
where JS.JS_JobNumber = 'S0154'
</code></pre>
<p><a href="https://i.stack.imgur.com/AFTtT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AFTtT.png" alt="enter image description here" /></a></p>
<p>Why does notetext appear in branch 'CLE'?</p>
| [
{
"answer_id": 74300955,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 3,
"selected": true,
"text": "x"
},
{
"answer_id": 74301025,
"author": "DulacreMi",
"author_id": 20381696,
"author_profile": "https://Stackoverflow.com/users/20381696",
"pm_score": 1,
"selected": false,
"text": "const primary = {\n green: {\n dark: '#dark',\n light: '#light'\n }\n}\n\nconst handler = {\n get: (obj, prop, receiver) => {\n return (key) => obj[prop][key] || obj[prop].dark\n }\n}\n\nconst proxyPrimary = new Proxy(primary, handler)\nconsole.log(proxyPrimary.green())\nconsole.log(proxyPrimary.green('light'))\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15011107/"
] |
74,300,815 | <p>How do i find what the last row of of a column that is highlighted?
Currently I only know how to find last row that is used.</p>
<pre><code>LastRow = Cells(Rows.Count, 1).End(xlUp).Row
</code></pre>
| [
{
"answer_id": 74300946,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 2,
"selected": false,
"text": "1"
},
{
"answer_id": 74301268,
"author": "shrivallabha.redij",
"author_id": 8759927,
"author_profile": "https://Stackoverflow.com/users/8759927",
"pm_score": 0,
"selected": false,
"text": "lngLastRow = Selection.Cells(Selection.Cells.Count, 1).Row"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20257020/"
] |
74,300,816 | <p>Im using symfony 6 and easyadmin 4.
Im trying to figure out how to block a user account on my website but
i can't find a solution.</p>
<p>I tried to create a role named: ROLE_BLOCKED and then use a function like IsDenied in the controllers to block the access but it seems like they are no such function in symfony 6.</p>
<p>update:
here is my LoginAuthenticator</p>
<pre><code>
class LoginAuthenticator extends AbstractLoginFormAuthenticator
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_login';
public function __construct(private UrlGeneratorInterface $urlGenerator)
{
}
public function authenticate(Request $request): Passport
{
$email = $request->request->get('email', '');
$request->getSession()->set(Security::LAST_USERNAME, $email);
return new Passport(
new UserBadge($email),
new PasswordCredentials($request->request->get('password', '')),
[
new CsrfTokenBadge('authenticate', $request->request->get('_csrf_token')),
]
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
return new RedirectResponse($targetPath);
}
// For example:
// return new RedirectResponse($this->urlGenerator->generate('some_route'));
throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl(Request $request): string
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
</code></pre>
<p>and my security.yaml:</p>
<pre><code> # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
# used to reload user from session & other features (e.g. switch_user)
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
custom_authenticator: App\Security\RegisterAuthenticator
logout:
path: app_logout
# where to redirect after logout
# target: app_any_route
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_ARTIST: ROLE_USER
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/profile, roles: ROLE_USER }
when@test:
security:
password_hashers:
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon
</code></pre>
<p><strong>FINAL UPDATE: I solved the problem by using a userChecker CLass</strong></p>
| [
{
"answer_id": 74300946,
"author": "FunThomas",
"author_id": 7599798,
"author_profile": "https://Stackoverflow.com/users/7599798",
"pm_score": 2,
"selected": false,
"text": "1"
},
{
"answer_id": 74301268,
"author": "shrivallabha.redij",
"author_id": 8759927,
"author_profile": "https://Stackoverflow.com/users/8759927",
"pm_score": 0,
"selected": false,
"text": "lngLastRow = Selection.Cells(Selection.Cells.Count, 1).Row"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11428552/"
] |
74,300,857 | <p>I want to format the fraction part of double values with 5 digits by ignoring the leading zeros, for example:</p>
<p>0.123456 -> 0.12345</p>
<p>0.00001234567 -> 0.000012345</p>
<p>0.0001234567 -> 0.00012345</p>
<p>how can I do that?</p>
<p>I tried to set the maximum and minimum fraction digits with the number formatter but it didn't give me the result I wanted.</p>
| [
{
"answer_id": 74302230,
"author": "fbitterlich",
"author_id": 1262979,
"author_profile": "https://Stackoverflow.com/users/1262979",
"pm_score": 1,
"selected": false,
"text": "^\\d+\\.(0*)\\d{1,5}\n"
},
{
"answer_id": 74302664,
"author": "Antanas",
"author_id": 2386193,
"author_profile": "https://Stackoverflow.com/users/2386193",
"pm_score": 3,
"selected": true,
"text": "let nf = NSNumberFormatter()\nnf.usesSignificantDigits = true\nnf.maximumSignificantDigits = 5\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11972066/"
] |
74,300,889 | <p>I'm using kcat to check the content of kafka topics when working locally but, when messages are serialized with protobuf, the result I get is an unreadable stream of encoded characters. I'm aware of the existence of some other kafka-consumers tools (<a href="https://github.com/obsidiandynamics/kafdrop" rel="nofollow noreferrer">Kafdrop</a>, <a href="https://github.com/tchiotludo/akhq" rel="nofollow noreferrer">AKHQ</a>, <a href="https://github.com/cloudhut/kowl" rel="nofollow noreferrer">Kowl</a>, <a href="https://www.kadeck.com/" rel="nofollow noreferrer">Kadek</a>...) but I'm looking for the simplest option which fits my needs.</p>
<p><strong>Does kcat support protobuf key/value deserialization from protofile?</strong><br />
Is there any simple terminal-based tool which allows this?</p>
| [
{
"answer_id": 74302230,
"author": "fbitterlich",
"author_id": 1262979,
"author_profile": "https://Stackoverflow.com/users/1262979",
"pm_score": 1,
"selected": false,
"text": "^\\d+\\.(0*)\\d{1,5}\n"
},
{
"answer_id": 74302664,
"author": "Antanas",
"author_id": 2386193,
"author_profile": "https://Stackoverflow.com/users/2386193",
"pm_score": 3,
"selected": true,
"text": "let nf = NSNumberFormatter()\nnf.usesSignificantDigits = true\nnf.maximumSignificantDigits = 5\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15208738/"
] |
74,300,919 | <p>Using python/numpy, I have the following <code>np.einsum</code>:</p>
<pre><code>np.einsum('abde,abc->bcde', X, Y)
</code></pre>
<p><code>Y</code> is sparse: for each <code>[a,b]</code>, only one <code>c == 1</code>; all others := 0.
For an example of relative size of the axes, <code>X.shape</code> is on the order of <code>(1000, 5, 30, 30)</code>, and <code>Y.shape</code> is equivalently <code>(1000, 5, 300)</code>.</p>
<p>This operation is extremely costly; I want to make this more performant. For one thing, einsum is not parallelized. For another, beecause <code>Y</code> is sparse, I'm effectively computing 300x the number of multiplication operations I <em>should</em> be doing. In fact, when I wrote the equivalent of this einsum using a loop over n, I got a speed-up of around 3x. But that's clearly not very good.</p>
<p>How should I approach making this more performant? I've tried using np.tensordot, but I could not figure out how to get what I want from it (and I still run into the sparse/dense problem).</p>
| [
{
"answer_id": 74302230,
"author": "fbitterlich",
"author_id": 1262979,
"author_profile": "https://Stackoverflow.com/users/1262979",
"pm_score": 1,
"selected": false,
"text": "^\\d+\\.(0*)\\d{1,5}\n"
},
{
"answer_id": 74302664,
"author": "Antanas",
"author_id": 2386193,
"author_profile": "https://Stackoverflow.com/users/2386193",
"pm_score": 3,
"selected": true,
"text": "let nf = NSNumberFormatter()\nnf.usesSignificantDigits = true\nnf.maximumSignificantDigits = 5\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2341986/"
] |
74,300,944 | <p>My App does connect with a device which spans an own Wifi network. Before connection to this Wifi iOS does display the typical confirmation dialogue:</p>
<p>"App name" wants to join Wi-Fi network "Network name"</p>
<p>My app is now rejected during App Store submission with following reason:</p>
<p>"We noticed that your app requests the user’s consent to access the local network information, but doesn’t sufficiently explain the use of the local network information in the purpose string. To help users make informed decisions about how their data is used, permission request alerts need to explain and include an example of how your app will use the requested information. Next Steps Please revise the purpose string in your app’s Info.plist file for the local network information to explain why your app needs access and include an example of how the user's data will be used."</p>
<p>I have already added NSLocalNetworkUsageDescription to Info.plist, but this is not displayed in this dialogue. For connection to Wi-Fi I do use NEHotspotConfigurationManager.</p>
<p>Has anybody an idea how to meet the requested requirement?</p>
<p>Thank you very much!</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>MinimumOSVersion</key>
<string>10.0</string>
<key>CFBundleDisplayName</key>
<string>BRUNNER EAS3</string>
<key>CFBundleIdentifier</key>
<string>de.brunner.apps.eas3</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>CFBundleName</key>
<string>Brunner.Apps.EAS3</string>
<key>XSAppIconAssets</key>
<string>Assets.xcassets/AppIcon.appiconset</string>
<key>NSAllowsLocalNetworking</key>
<true/>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>192.168.4.1</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>192.168.4.1</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
<key>UILaunchImageFile</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>LaunchScreen</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>The enables the app to find your EAS3 control automatically in WLAN.</string>
<key>NSLocalNetworkUsageDescription</key>
<string>The enables the app to find your EAS3 control in WLAN and maintain a communication with it so that you can monitor and control the device (only when the app is used).</string>
<key>CFBundleVersion</key>
<string>1.19</string>
<key>CFBundleShortVersionString</key>
<string>20</string>
</dict>
</plist>
</code></pre>
| [
{
"answer_id": 74302230,
"author": "fbitterlich",
"author_id": 1262979,
"author_profile": "https://Stackoverflow.com/users/1262979",
"pm_score": 1,
"selected": false,
"text": "^\\d+\\.(0*)\\d{1,5}\n"
},
{
"answer_id": 74302664,
"author": "Antanas",
"author_id": 2386193,
"author_profile": "https://Stackoverflow.com/users/2386193",
"pm_score": 3,
"selected": true,
"text": "let nf = NSNumberFormatter()\nnf.usesSignificantDigits = true\nnf.maximumSignificantDigits = 5\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331650/"
] |
74,300,978 | <p>so i'm trying to implement a register and login mechanism using JWT. But somehow despite using permitAll() in security configuration. It still return 401 when unauthenticated user trying to access "/user/register"</p>
<p>Here is UserServiceImpl.java</p>
<pre><code>package com.kelompok7.bukuku.user;
import com.kelompok7.bukuku.user.role.ERole;
import com.kelompok7.bukuku.user.role.Role;
import com.kelompok7.bukuku.user.verificationToken.VerificationToken;
import com.kelompok7.bukuku.user.verificationToken.VerificationTokenRepo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service @RequiredArgsConstructor @Transactional @Slf4j
public class UserServiceImpl implements UserService, UserDetailsService {
@Autowired
private final UserRepo userRepo;
@Autowired
private final VerificationTokenRepo verificationTokenRepo;
@Autowired
private JavaMailSender mailSender;
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByUsername(username);
if(user == null){
log.error("{}", SecurityContextHolder.getContext().toString());
log.error("User not found in the database");
throw new UsernameNotFoundException("User not found in the database");
}
else{
log.info("User found in the database: {}", username);
}
Collection<SimpleGrantedAuthority> authorities = user.getAuthorities();
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
@Override
public User register(User user) throws MessagingException, UnsupportedEncodingException {
log.info("Saving new user {} to the database", user.getName());
user.setPassword(encoder().encode(user.getPassword()));
Set<Role> role = new HashSet<>();
role.add(new Role(ERole.ROLE_USER));
user.setRoles(role);
user.setEnabled(false);
userRepo.save(user);
return user;
}
}
</code></pre>
<p>Here is UserController.java</p>
<pre><code>package com.kelompok7.bukuku.user;
import lombok.RequiredArgsConstructor;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.\*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@PostMapping("/register")
public ResponseEntity<User> register(@RequestBody User user) throws MessagingException, UnsupportedEncodingException {
URI uri = URI.create(ServletUriComponentsBuilder.fromCurrentContextPath().path("user/register").toUriString());
return ResponseEntity.created(uri).body(userService.register(user));
}
}
</code></pre>
<p>Here is SecurityConfiguration.java</p>
<pre><code>package com.kelompok7.bukuku.security;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {
@Autowired
private final RsaKeyProperties rsaKeys;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.cors(cors -> cors.disable())
.authorizeRequests(auth -> auth
.antMatchers("/**").permitAll()
.anyRequest().permitAll()
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.build();
}
// @Bean
// public WebSecurityCustomizer webSecurityCustomizer() {
// return (web) -\> web.ignoring()
// .antMatchers("/\*\*");
// }
@Bean
JwtDecoder jwtDecoder(){
return NimbusJwtDecoder.withPublicKey(rsaKeys.publicKey()).build();
}
@Bean
JwtEncoder jwtEncoder(){
JWK jwk = new RSAKey.Builder(rsaKeys.publicKey()).privateKey(rsaKeys.privateKey()).build();
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
}
</code></pre>
<p>And finally the log</p>
<pre><code>2022-11-03 16:15:29.525 ERROR 19358 --- [nio-8081-exec-2] c.kelompok7.bukuku.user.UserServiceImpl : SecurityContextImpl [Null authentication]
2022-11-03 16:15:29.525 ERROR 19358 --- [nio-8081-exec-2] c.kelompok7.bukuku.user.UserServiceImpl : User not found in the database
</code></pre>
<p>I'm expecting that the request will go through and be processed, instead it seems it get caught in the SecurityFilterChain and get 401 Unauthorized instead. I've tried disabling CSRF and CORS but still failed. I've even just set permitAll() to anyRequest but somehow still getting 401.</p>
<p><strong>The only thing to be working seems to be using webSecurityCustomizer and use web.ignoring(), but i've read that it will skip the securityFilterChain entirely so i'm not sure if it's safe. Is it safe? is it how it normally be done? Is there any better way?</strong></p>
<p>Also, even if web.ignoring() work, i also wanted to know why the permitAll() doesn't work. Is it normal?</p>
<p>Thank you for your answer</p>
| [
{
"answer_id": 74302230,
"author": "fbitterlich",
"author_id": 1262979,
"author_profile": "https://Stackoverflow.com/users/1262979",
"pm_score": 1,
"selected": false,
"text": "^\\d+\\.(0*)\\d{1,5}\n"
},
{
"answer_id": 74302664,
"author": "Antanas",
"author_id": 2386193,
"author_profile": "https://Stackoverflow.com/users/2386193",
"pm_score": 3,
"selected": true,
"text": "let nf = NSNumberFormatter()\nnf.usesSignificantDigits = true\nnf.maximumSignificantDigits = 5\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405964/"
] |
74,300,983 | <p>I'm trying to implement the "save" feature from the answer in post <a href="https://stackoverflow.com/questions/68371723/how-to-use-the-localstorage-option-for-dt-in-r-shiny">How to use the localStorage option for DT in R Shiny?</a> into my table rendered with rhandsontable but it's not working. That post involves table package DT, whereas I'm using rhandsontable and need to stick with rhandsontable. By "save", I mean preserving the table with all its cumulative inputs/outputs from one session to the next, which the referred-to post does for DT table. I will need to implement the "clear" function from that post later, but first I want to see how "save" works, and what I'm doing wrong in my below attempt, before moving on to adapting the "clear" function.</p>
<p>Below code has comments <code># add...</code> for functions I pulled in from the reference post.</p>
<p>How would I enable the save feature in this rhandsontable example?</p>
<p>I get the following error message: <em>Error : Can't access reactive value 'hottable' outside of reactive consumer. Do you need to wrap inside reactive() or observer()?</em></p>
<p>Code:</p>
<pre><code># If not installed already, un-comment and run the below 3 lines to install shinyStore package:
# install.packages("devtools")
# library(devtools)
# install_github("trestletech/shinyStore")
library(rhandsontable)
library(shiny)
library(shinyStore)
myDF <- data.frame(x = c(1, 2, 3))
ui <- fluidPage(
initStore("store", "shinyStore-ex1"), # add
br(),
fluidRow(
column(6,
actionButton('addCol','Add column'),
actionButton("save", "Save", icon("save")), # add
actionButton("clear", "Clear", icon("stop")) # add
)
),
br(),rHandsontableOutput('hottable')
)
server <- function(input, output, session) {
EmptyTbl <- reactiveVal(myDF)
rv <- reactiveValues(uiTable = hot_to_r(input$hottable)) # add
observeEvent(input$hottable, {
EmptyTbl(hot_to_r(input$hottable))
})
output$hottable <- renderRHandsontable({
rhandsontable(EmptyTbl(),useTypes = FALSE)
})
observeEvent(input$addCol, {
newCol <- data.frame(c(1, 2, 3))
names(newCol) <- paste("Col", ncol(hot_to_r(input$hottable)) + 1)
EmptyTbl(cbind(EmptyTbl(), newCol))
})
# add observeEvent() below:
observeEvent(input$save,{
updateStore(session,name = "uiTable",rv$uiTable)
},ignoreInit = TRUE)
}
shinyApp(ui, server)
</code></pre>
| [
{
"answer_id": 74301247,
"author": "ismirsehregal",
"author_id": 9841389,
"author_profile": "https://Stackoverflow.com/users/9841389",
"pm_score": 3,
"selected": true,
"text": "# If not installed already, un-comment and run the below 3 lines to install shinyStore package:\n# install.packages(\"devtools\")\n# library(devtools)\n# install_github(\"trestletech/shinyStore\")\n\nlibrary(rhandsontable)\nlibrary(shiny)\nlibrary(shinyStore)\n\nmyDF <- data.frame(x = c(1, 2, 3))\n\nui <- fluidPage(\n initStore(\"store\", \"shinyStore-ex1\"),\n br(),\n fluidRow(column(\n 6,\n actionButton('addCol', 'Add column'),\n actionButton(\"save\", \"Save\", icon(\"save\")),\n actionButton(\"clear\", \"Clear\", icon(\"stop\")) # add\n )),\n br(),\n rHandsontableOutput('hottable')\n)\n\nserver <- function(input, output, session) {\n uiTable <- reactiveVal(myDF)\n \n output$hottable <- renderRHandsontable({\n rhandsontable(uiTable(), useTypes = FALSE)\n })\n\n observeEvent(input$hottable, {\n uiTable(hot_to_r(input$hottable))\n })\n \n observeEvent(input$addCol, {\n newCol <- data.frame(c(1, 2, 3))\n names(newCol) <-\n paste(\"Col\", ncol(hot_to_r(input$hottable)) + 1)\n uiTable(cbind(uiTable(), newCol))\n })\n \n observeEvent(input$save, {\n updateStore(session, name = \"uiTable\", uiTable())\n }, ignoreInit = TRUE)\n \n observeEvent(input$clear, {\n # clear tracking table:\n uiTable(myDF)\n \n # clear shinyStore:\n updateStore(session, name = \"uiTable\", myDF)\n }, ignoreInit = TRUE)\n \n observeEvent(input$store$uiTable, {\n uiTable(as.data.frame(input$store$uiTable))\n })\n}\n\nshinyApp(ui, server)\n"
},
{
"answer_id": 74314268,
"author": "Curious Jorge - user9788072",
"author_id": 9788072,
"author_profile": "https://Stackoverflow.com/users/9788072",
"pm_score": 0,
"selected": false,
"text": "myDF <- data.frame(x = c(1, 2, 3))\n\nui <- fluidPage(\n initStore(\"store\", \"shinyStore-ex1\"), # add\n br(),\n fluidRow(\n column(6,\n actionButton('addCol','Add column'),\n actionButton(\"save\", \"Save\", icon(\"save\")), # add\n actionButton(\"clear\", \"Clear\", icon(\"stop\")) # add\n )\n ),\n br(),rHandsontableOutput('hottable')\n)\n\nserver <- function(input, output, session) {\n EmptyTbl <- reactiveVal(myDF)\n \n observeEvent(input$hottable, {\n EmptyTbl(hot_to_r(input$hottable))\n })\n \n output$hottable <- renderRHandsontable({\n rhandsontable(EmptyTbl(),useTypes = FALSE)\n })\n \n observeEvent(input$addCol, {\n newCol <- data.frame(c(1, 2, 3))\n names(newCol) <- paste(\"Col\", ncol(hot_to_r(input$hottable)) + 1)\n EmptyTbl(cbind(EmptyTbl(), newCol))\n })\n \n observeEvent(input$save,{\n updateStore(session,name = \"EmptyTbl\",EmptyTbl())\n },ignoreInit = TRUE)\n \n observeEvent(input$store$EmptyTbl,{\n EmptyTbl(as.data.frame(input$store$EmptyTbl))\n })\n \n}\n\nshinyApp(ui, server)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74300983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9788072/"
] |
74,301,017 | <pre><code> Col-1 Col-2
0 Erin Tanya
1 Cathy Tom
2 Ross Wes
</code></pre>
<p>This is my dataset</p>
<p>I need the result to look like this:</p>
<pre><code> New_column
0 Erin
1 Cathy
2 Ross
3 Tanya
4 Tom
5 Wes
</code></pre>
<p>I tried using .map, append, concat and .ravel but no luck. Any help would be appreciated :)</p>
| [
{
"answer_id": 74301247,
"author": "ismirsehregal",
"author_id": 9841389,
"author_profile": "https://Stackoverflow.com/users/9841389",
"pm_score": 3,
"selected": true,
"text": "# If not installed already, un-comment and run the below 3 lines to install shinyStore package:\n# install.packages(\"devtools\")\n# library(devtools)\n# install_github(\"trestletech/shinyStore\")\n\nlibrary(rhandsontable)\nlibrary(shiny)\nlibrary(shinyStore)\n\nmyDF <- data.frame(x = c(1, 2, 3))\n\nui <- fluidPage(\n initStore(\"store\", \"shinyStore-ex1\"),\n br(),\n fluidRow(column(\n 6,\n actionButton('addCol', 'Add column'),\n actionButton(\"save\", \"Save\", icon(\"save\")),\n actionButton(\"clear\", \"Clear\", icon(\"stop\")) # add\n )),\n br(),\n rHandsontableOutput('hottable')\n)\n\nserver <- function(input, output, session) {\n uiTable <- reactiveVal(myDF)\n \n output$hottable <- renderRHandsontable({\n rhandsontable(uiTable(), useTypes = FALSE)\n })\n\n observeEvent(input$hottable, {\n uiTable(hot_to_r(input$hottable))\n })\n \n observeEvent(input$addCol, {\n newCol <- data.frame(c(1, 2, 3))\n names(newCol) <-\n paste(\"Col\", ncol(hot_to_r(input$hottable)) + 1)\n uiTable(cbind(uiTable(), newCol))\n })\n \n observeEvent(input$save, {\n updateStore(session, name = \"uiTable\", uiTable())\n }, ignoreInit = TRUE)\n \n observeEvent(input$clear, {\n # clear tracking table:\n uiTable(myDF)\n \n # clear shinyStore:\n updateStore(session, name = \"uiTable\", myDF)\n }, ignoreInit = TRUE)\n \n observeEvent(input$store$uiTable, {\n uiTable(as.data.frame(input$store$uiTable))\n })\n}\n\nshinyApp(ui, server)\n"
},
{
"answer_id": 74314268,
"author": "Curious Jorge - user9788072",
"author_id": 9788072,
"author_profile": "https://Stackoverflow.com/users/9788072",
"pm_score": 0,
"selected": false,
"text": "myDF <- data.frame(x = c(1, 2, 3))\n\nui <- fluidPage(\n initStore(\"store\", \"shinyStore-ex1\"), # add\n br(),\n fluidRow(\n column(6,\n actionButton('addCol','Add column'),\n actionButton(\"save\", \"Save\", icon(\"save\")), # add\n actionButton(\"clear\", \"Clear\", icon(\"stop\")) # add\n )\n ),\n br(),rHandsontableOutput('hottable')\n)\n\nserver <- function(input, output, session) {\n EmptyTbl <- reactiveVal(myDF)\n \n observeEvent(input$hottable, {\n EmptyTbl(hot_to_r(input$hottable))\n })\n \n output$hottable <- renderRHandsontable({\n rhandsontable(EmptyTbl(),useTypes = FALSE)\n })\n \n observeEvent(input$addCol, {\n newCol <- data.frame(c(1, 2, 3))\n names(newCol) <- paste(\"Col\", ncol(hot_to_r(input$hottable)) + 1)\n EmptyTbl(cbind(EmptyTbl(), newCol))\n })\n \n observeEvent(input$save,{\n updateStore(session,name = \"EmptyTbl\",EmptyTbl())\n },ignoreInit = TRUE)\n \n observeEvent(input$store$EmptyTbl,{\n EmptyTbl(as.data.frame(input$store$EmptyTbl))\n })\n \n}\n\nshinyApp(ui, server)\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406129/"
] |
74,301,032 | <p>I implement a lockfree ringbuffer, and then i test for debug is ok, but in release mode it can't work allways.</p>
<pre><code>use std::path::Display;
use std::sync::Arc;
#[derive(Debug)]
pub struct RingBuffer<T, const m_size: usize> {
idx_head: usize,
idx_tail: usize,
m_data: [T; m_size],
}
pub trait Queue<T> {
fn new_empty() -> Self;
fn push(&mut self, value: T) -> bool;
fn pop(&mut self) -> Option<&T>;
fn is_full(&self) -> bool;
fn is_empty(&self) -> bool;
}
impl<T, const Size: usize> Queue<T> for RingBuffer<T, Size>
{
fn new_empty() -> Self {
RingBuffer::<T, Size> {
idx_head: 0,
idx_tail: 0,
m_data: array_init::array_init(|_| {
unsafe {
std::mem::zeroed()
}
}),
}
}
fn push(&mut self, value: T) -> bool {
let mut head = self.idx_head + 1;
if head == Size {
head = 0;
}
if head == self.idx_tail {
return false;
}
self.m_data[self.idx_head] = value;
self.idx_head = head;
return true;
}
fn pop(&mut self) -> Option<&T> {
let mut tail = self.idx_tail;
if self.idx_head == tail {
return None;
}
let res = &self.m_data[tail];
tail += 1;
if tail == Size {
tail = 0;
}
self.idx_tail = tail;
return Some(res);
}
fn is_full(&self) -> bool {
self.idx_tail == (self.idx_head + 1) % Size
}
fn is_empty(&self) -> bool {
self.idx_head == self.idx_tail
}
}
pub struct SharedRingBuffer<T, const m_size: usize> {
pub ringbuffer: Arc<RingBuffer<T, m_size>>,
}
impl<T, const Size: usize> Clone for SharedRingBuffer<T, Size> {
fn clone(&self) -> Self {
Self {
ringbuffer: self.ringbuffer.clone(),
}
}
}
impl<T, const Size: usize, > Queue<T> for SharedRingBuffer<T, Size> {
fn new_empty() -> Self {
Self {
ringbuffer: Arc::new(RingBuffer::<T, Size>::new_empty()),
}
}
fn push(&mut self, value: T) -> bool {
unsafe {
(*Arc::get_mut_unchecked(&mut self.ringbuffer)).push(value)
}
}
fn pop(&mut self) -> Option<&T> {
unsafe {
(*Arc::get_mut_unchecked(&mut self.ringbuffer)).pop()
}
}
fn is_full(&self) -> bool {
self.ringbuffer.is_full()
}
fn is_empty(&self) -> bool {
self.ringbuffer.is_empty()
}
}
////////////////////// for test//////////////////////////
fn test_speed1() {
let mut q: SharedRingBuffer<i32, 8> = SharedRingBuffer::new_empty();
let mut t0 = std::time::SystemTime::now();
let t = {
let mut q = q.clone();
std::thread::spawn(move || {
loop {
let t = match q.pop() {
None => {
// std::thread::sleep(Duration::from_millis(10));
continue;
}
Some(res) => res
};
if *t == -1 {
break;
}
std::thread::sleep(Duration::from_millis(1));
}
let now = std::time::SystemTime::now();
println!("res: {}", now.duration_since(t0).unwrap().as_millis());
})
};
for i in 0..99 {
loop {
if q.push(i) {
// std::thread::sleep(Duration::from_millis(10));
break;
}
}
}
q.push(-1);
t.join().unwrap();
}
</code></pre>
<p>When i addition <code>std::thread::sleep(Duration::from_millis(10))</code> for q.push and q.pop method it is work well.</p>
<pre><code>rustc 1.67.0-nightly (95a3a7277 2022-10-31)
binary: rustc
commit-hash: 95a3a7277b44bbd2dd3485703d9a05f64652b60e
commit-date: 2022-10-31
host: x86_64-pc-windows-msvc
release: 1.67.0-nightly
LLVM version: 15.0.4
</code></pre>
<p>I expect the RingBuffer can work well.
The equivalent code is:</p>
<pre><code>fn test_speed2() {
let (send, recv) = channel::<i32>();
let mut is_run = SharedValue::new(true);
let mut t0 = std::time::SystemTime::now();
let t = {
let is_run = is_run.clone();
std::thread::spawn(move || {
loop {
let t = match recv.recv() {
Err(e) => {
break;
}
Ok(res) => res
};
if t == -1 {
break;
}
std::thread::sleep(Duration::from_millis(1));
}
let now = std::time::SystemTime::now();
// println!("res: {}", now.duration_since(t0).unwrap().as_millis());
})
};
for i in 0..99 {
send.send(i).unwrap();
}
send.send(-1).unwrap();
t.join().unwrap();
}
</code></pre>
<p>I hope ringbuffer can replace channel to communicate between two threads,Because ringbuffer is lockfree and faster.</p>
| [
{
"answer_id": 74305963,
"author": "wengang yang",
"author_id": 12958578,
"author_profile": "https://Stackoverflow.com/users/12958578",
"pm_score": -1,
"selected": false,
"text": "fn push(&mut self, value: T) -> bool {\n let mut head = unsafe {\n std::ptr::read_volatile(&self.idx_head) + 1\n };\n let tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n if head == Size {\n head = 0;\n }\n if head == tail {\n return false;\n }\n self.m_data[self.idx_head] = value;\n unsafe {\n std::ptr::write_volatile(&mut self.idx_head, head);\n }\n return true;\n}\n\nfn pop(&mut self) -> Option<&T> {\n let mut tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n let head = unsafe {\n std::ptr::read_volatile(&self.idx_head)\n };\n if head == tail {\n return None;\n }\n let res = &self.m_data[tail];\n tail += 1;\n if tail == Size {\n tail = 0;\n }\n unsafe {\n std::ptr::write_volatile(&mut self.idx_tail, tail);\n }\n return Some(res);\n}\n"
},
{
"answer_id": 74306646,
"author": "kmdreko",
"author_id": 2189130,
"author_profile": "https://Stackoverflow.com/users/2189130",
"pm_score": 1,
"selected": true,
"text": "Arc::get_mut_unchecked()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12958578/"
] |
74,301,041 | <p>I have just created a demo for better understanding future builder</p>
<p>scaffold body showing all users from api and appear should be shown with number of users</p>
<p>appear's title showing 0 when loaded but does not change...what to do to rebuild it</p>
<p>here is my code</p>
<pre><code>
class _withmodelState extends State<withmodel> {
List<UserModel> userlist=[];
Future<List<UserModel>> getdata() async {
final resp =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
if (resp.statusCode == 200) {
print('i ma called');
List<dynamic> dlist = json.decode(resp.body);
await Future.delayed(Duration(seconds: 2));
userlist= dlist.map((e) => UserModel.fromJson(e)).toList();
return userlist;
}
return userlist;
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(title: Text("Total users="+userlist.length.toString()),),
body: MyBody(
//MyBody returning FutureBuilder for showing userlist array;
),
));
}
</code></pre>
| [
{
"answer_id": 74305963,
"author": "wengang yang",
"author_id": 12958578,
"author_profile": "https://Stackoverflow.com/users/12958578",
"pm_score": -1,
"selected": false,
"text": "fn push(&mut self, value: T) -> bool {\n let mut head = unsafe {\n std::ptr::read_volatile(&self.idx_head) + 1\n };\n let tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n if head == Size {\n head = 0;\n }\n if head == tail {\n return false;\n }\n self.m_data[self.idx_head] = value;\n unsafe {\n std::ptr::write_volatile(&mut self.idx_head, head);\n }\n return true;\n}\n\nfn pop(&mut self) -> Option<&T> {\n let mut tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n let head = unsafe {\n std::ptr::read_volatile(&self.idx_head)\n };\n if head == tail {\n return None;\n }\n let res = &self.m_data[tail];\n tail += 1;\n if tail == Size {\n tail = 0;\n }\n unsafe {\n std::ptr::write_volatile(&mut self.idx_tail, tail);\n }\n return Some(res);\n}\n"
},
{
"answer_id": 74306646,
"author": "kmdreko",
"author_id": 2189130,
"author_profile": "https://Stackoverflow.com/users/2189130",
"pm_score": 1,
"selected": true,
"text": "Arc::get_mut_unchecked()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18817235/"
] |
74,301,064 | <p>I have a Polars <code>DataFrame</code> with a list column. I want to control how many elements of a <code>pl.List</code> column are printed.</p>
<p>I've tried <code>pl.pl.Config.set_fmt_str_lengths()</code> but this only restricts the number of elements if set to a small value, it doesn't show more elements for a large value.</p>
<p>I'm working in Jupyterlab but I think it's a general issue.</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
N = 5
df = (
pl.DataFrame(
{
'id': range(N)
}
)
.with_row_count("value")
.groupby_rolling(
"id",period=f"{N}i"
)
.agg(
pl.col("value")
)
)
df
shape: (5, 2)
┌─────┬───────────────┐
│ id ┆ value │
│ --- ┆ --- │
│ i64 ┆ list[u32] │
╞═════╪═══════════════╡
│ 0 ┆ [0] │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1 ┆ [0, 1] │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ [0, 1, 2] │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ [0, 1, ... 3] │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ [0, 1, ... 4] │
└─────┴───────────────┘
</code></pre>
| [
{
"answer_id": 74305963,
"author": "wengang yang",
"author_id": 12958578,
"author_profile": "https://Stackoverflow.com/users/12958578",
"pm_score": -1,
"selected": false,
"text": "fn push(&mut self, value: T) -> bool {\n let mut head = unsafe {\n std::ptr::read_volatile(&self.idx_head) + 1\n };\n let tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n if head == Size {\n head = 0;\n }\n if head == tail {\n return false;\n }\n self.m_data[self.idx_head] = value;\n unsafe {\n std::ptr::write_volatile(&mut self.idx_head, head);\n }\n return true;\n}\n\nfn pop(&mut self) -> Option<&T> {\n let mut tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n let head = unsafe {\n std::ptr::read_volatile(&self.idx_head)\n };\n if head == tail {\n return None;\n }\n let res = &self.m_data[tail];\n tail += 1;\n if tail == Size {\n tail = 0;\n }\n unsafe {\n std::ptr::write_volatile(&mut self.idx_tail, tail);\n }\n return Some(res);\n}\n"
},
{
"answer_id": 74306646,
"author": "kmdreko",
"author_id": 2189130,
"author_profile": "https://Stackoverflow.com/users/2189130",
"pm_score": 1,
"selected": true,
"text": "Arc::get_mut_unchecked()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5387991/"
] |
74,301,081 | <p>I need an unique ID for consecutive dates</p>
<p>source table</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>SNAPSHOT_DATE</th>
<th>CHANNEL</th>
<th>CASE_ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-10-18</td>
<td>web</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-19</td>
<td>web</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-20</td>
<td>web</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-23</td>
<td>web</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-24</td>
<td>web</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-25</td>
<td>web</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-18</td>
<td>phone</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-19</td>
<td>phone</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-21</td>
<td>phone</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-22</td>
<td>phone</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-18</td>
<td>phone</td>
<td>52LnlJQAS</td>
</tr>
<tr>
<td>2022-10-26</td>
<td>phone</td>
<td>52LnlJQAS</td>
</tr>
<tr>
<td>2022-10-20</td>
<td>phone</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-24</td>
<td>phone</td>
<td>521nzT3HQA</td>
</tr>
<tr>
<td>2022-10-25</td>
<td>phone</td>
<td>521nzT3HQA</td>
</tr>
</tbody>
</table>
</div>
<p>I tried this query</p>
<pre><code>Select snapshot_date, channel,case_id
,case_id||channel||Dateadd('day', -(row_number() over (partition by case_id, channel order by snapshot_date)), snapshot_date+1) as ID
From test
</code></pre>
<p>got output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>SNAPSHOT_DATE</th>
<th>CHANNEL</th>
<th>CASE_ID</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-10-18</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-19</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-20</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-21</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-22</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-24</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-19</td>
</tr>
<tr>
<td>2022-10-25</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-19</td>
</tr>
<tr>
<td>2022-10-18</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-18</td>
</tr>
<tr>
<td>2022-10-19</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-18</td>
</tr>
<tr>
<td>2022-10-20</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-18</td>
</tr>
<tr>
<td>2022-10-23</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-20</td>
</tr>
<tr>
<td>2022-10-24</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-20</td>
</tr>
<tr>
<td>2022-10-25</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-20</td>
</tr>
<tr>
<td>2022-10-18</td>
<td>phone</td>
<td>52LnlJQAS</td>
<td>52LnlJQASphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-26</td>
<td>phone</td>
<td>52LnlJQAS</td>
<td>52LnlJQASphone2022-10-25</td>
</tr>
</tbody>
</table>
</div>
<p>expected output</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>SNAPSHOT_DATE</th>
<th>CHANNEL</th>
<th>CASE_ID</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>2022-10-18</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-19</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-20</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-21</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-22</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-24</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-24</td>
</tr>
<tr>
<td>2022-10-25</td>
<td>phone</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAphone2022-10-24</td>
</tr>
<tr>
<td>2022-10-18</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-18</td>
</tr>
<tr>
<td>2022-10-19</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-18</td>
</tr>
<tr>
<td>2022-10-20</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-18</td>
</tr>
<tr>
<td>2022-10-23</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-23</td>
</tr>
<tr>
<td>2022-10-24</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-23</td>
</tr>
<tr>
<td>2022-10-25</td>
<td>web</td>
<td>521nzT3HQA</td>
<td>521nzT3HQAweb2022-10-23</td>
</tr>
<tr>
<td>2022-10-18</td>
<td>phone</td>
<td>52LnlJQAS</td>
<td>52LnlJQASphone2022-10-18</td>
</tr>
<tr>
<td>2022-10-26</td>
<td>phone</td>
<td>52LnlJQAS</td>
<td>52LnlJQASphone2022-10-26</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74305963,
"author": "wengang yang",
"author_id": 12958578,
"author_profile": "https://Stackoverflow.com/users/12958578",
"pm_score": -1,
"selected": false,
"text": "fn push(&mut self, value: T) -> bool {\n let mut head = unsafe {\n std::ptr::read_volatile(&self.idx_head) + 1\n };\n let tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n if head == Size {\n head = 0;\n }\n if head == tail {\n return false;\n }\n self.m_data[self.idx_head] = value;\n unsafe {\n std::ptr::write_volatile(&mut self.idx_head, head);\n }\n return true;\n}\n\nfn pop(&mut self) -> Option<&T> {\n let mut tail = unsafe {\n std::ptr::read_volatile(&self.idx_tail)\n };\n let head = unsafe {\n std::ptr::read_volatile(&self.idx_head)\n };\n if head == tail {\n return None;\n }\n let res = &self.m_data[tail];\n tail += 1;\n if tail == Size {\n tail = 0;\n }\n unsafe {\n std::ptr::write_volatile(&mut self.idx_tail, tail);\n }\n return Some(res);\n}\n"
},
{
"answer_id": 74306646,
"author": "kmdreko",
"author_id": 2189130,
"author_profile": "https://Stackoverflow.com/users/2189130",
"pm_score": 1,
"selected": true,
"text": "Arc::get_mut_unchecked()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281128/"
] |
74,301,089 | <p>I'm using Next JS. I've created a sidebar and added custom accordions (I've named the accordion component as SideAccord.js) in it. I'm looping the data through array. I've assigned the key but I'm still getting this error:</p>
<pre><code>Warning: Each child in a list should have a unique "key" prop.
Check the render method of SideAccord. See https://reactjs.org/link/warning-keys for more information.
at SideAccord (webpack-internal:///./components/SideAccord/index.js:25:19)
at ul
at div
at div
at nav
at div
at O (webpack-internal:///./node_modules/styled-components/dist/styled-components.browser.esm.js:31:19750)
at Sidebar (webpack-internal:///./components/Sidebar/index.js:28:66)
at div
at Home
at MyApp (webpack-internal:///./pages/_app.js:18:24)
</code></pre>
<p>You can check the files here - - <a href="https://codesandbox.io/s/festive-turing-59uo4v?file=/src/Sidebar.js" rel="nofollow noreferrer">https://codesandbox.io/s/festive-turing-59uo4v?file=/src/Sidebar.js</a></p>
<p>I have 3 component files</p>
<pre><code>Sidebar.js
SideAccord.js
SidebarData.js (which has all the data in the form of objects & arrays).
</code></pre>
<p>Here's the screenshot of the error - <a href="https://i.stack.imgur.com/Y96VO.png" rel="nofollow noreferrer">screenshot of the error</a></p>
| [
{
"answer_id": 74301165,
"author": "Nightcrawler",
"author_id": 13362831,
"author_profile": "https://Stackoverflow.com/users/13362831",
"pm_score": 2,
"selected": true,
"text": "<></>"
},
{
"answer_id": 74301241,
"author": "JBallin",
"author_id": 4722345,
"author_profile": "https://Stackoverflow.com/users/4722345",
"pm_score": 1,
"selected": false,
"text": "<>"
},
{
"answer_id": 74301390,
"author": "udoyhasan",
"author_id": 14359374,
"author_profile": "https://Stackoverflow.com/users/14359374",
"pm_score": 0,
"selected": false,
"text": "key"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19519558/"
] |
74,301,095 | <p>My SQL server database :</p>
<pre><code>CREATE TABLE Unit (
id INT primary key,
UnitName nvarchar(10)
);
INSERT INTO Unit (id,UnitName) VALUES (1,'Ton');
INSERT INTO Unit (id,UnitName) VALUES (2,'Kg');
INSERT INTO Unit (id,UnitName) VALUES (3,'g');
CREATE TABLE UnitGroup (
id INT primary key,
UnitGroupName nvarchar(50)
);
INSERT INTO UnitGroup (id,UnitGroupName) VALUES (1,'1Ton = 1000kg = 1000000g');
CREATE TABLE UnitGroupDetail (
id INT primary key,
UnitGroupId int,
UnitId int,
ConversionRate decimal(19,5),
FOREIGN KEY (UnitGroupId) REFERENCES UnitGroup(id),
FOREIGN KEY (UnitId) REFERENCES Unit(id),
);
CREATE TABLE Item (
id INT primary key,
ItemName nvarchar(50) ,
UnitGroupId int
FOREIGN KEY (UnitGroupId) REFERENCES UnitGroup(id),
);
INSERT INTO Item (id,ItemName,UnitGroupId) VALUES (1,'Item 1',1);
INSERT INTO UnitGroupDetail (id,UnitGroupId,UnitId,ConversionRate) VALUES (1,1,1,1.0);
INSERT INTO UnitGroupDetail (id,UnitGroupId,UnitId,ConversionRate) VALUES (2,1,2,1000.0);
INSERT INTO UnitGroupDetail (id,UnitGroupId,UnitId,ConversionRate) VALUES (3,1,3,1000000.0);
</code></pre>
<p>I want to create a function where I can pass the quantity in the base unit which its conversion is equal to 1.</p>
<pre><code>DECLARE @ItemId int =1
DECLARE @Quantity decimal(19,5)=105.82349 -- Assuming Passed quantity is in base unit which it's conversions equal to 1
DECLARE @UnitDetailId smallint = null
-- This is what I tried
SELECT *,
@Quantity / conversionrate,
@Quantity - ( @Quantity / conversionrate )
FROM unitgroupdetail
INNER JOIN item ON ( item.unitgroupid = unitgroupdetail.unitgroupid )
INNER JOIN unit ON ( unitgroupdetail.unitid = unit.id )
WHERE item.id = @ItemId
ORDER BY unitgroupdetail.conversionrate
-- Expected output should be in one row 105Ton , 823kg , 490g
</code></pre>
<p>I'm trying to get an output in one row this way :</p>
<blockquote>
<p>105Ton, 823kg, 490g</p>
</blockquote>
| [
{
"answer_id": 74303501,
"author": "Tamanna Pitroda",
"author_id": 13108134,
"author_profile": "https://Stackoverflow.com/users/13108134",
"pm_score": 2,
"selected": false,
"text": "DECLARE @ItemId int =1\nDECLARE @Quantity decimal(19,5)=105.82349 -- Assuming Passed quantity is in base unit which it's conversions equal to 1\nDECLARE @UnitDetailId smallint = null\n\nDECLARE @TableUnit table (Val decimal(19,5),Unit nvarchar(20),Rate decimal(19,5),Num int)\n\n\ninsert into @TableUnit (Val,Unit,Rate,Num)\nSELECT \n @Quantity * ugd.conversionrate,U.UnitName,ugd.conversionrate,ROW_NUMBER() OVER (\n ORDER BY ugd.conversionrate \n ) \n \nFROM unitgroupdetail ugd\n INNER JOIN item i ON ( i.unitgroupid = ugd.unitgroupid )\n INNER JOIN unit u ON ( ugd.unitid = u.id )\nWHERE i.id = @ItemId\nORDER BY ugd.conversionrate \n\n\n\nDECLARE @Cnt int = 1,@maxCnt int = 0,@NumString nvarchar(500) = '',@CurrentVal decimal(19,0),@CurrentRate decimal(19,5),\n@CurrentUnit nvarchar(20),@UpdatedVal decimal(19,2),@PreviousValDec decimal(19,5),@PreviousVal int = cast(@Quantity as int),\n@PreviousRate decimal(19,5);\n\nselect @maxCnt = max(Num) from @TableUnit tr\nwhile @Cnt <= @maxCnt\nbegin\n\n select @CurrentVal = cast(Val as int),@CurrentRate = Rate,@CurrentUnit = Unit from @TableUnit where Num = @Cnt;\n\n set @UpdatedVal= @CurrentVal;\n\n if @cnt = 1\n begin\n set @PreviousValDec = @Quantity;\n set @PreviousRate = @CurrentRate;\n end\n if(@cnt > 1)\n begin\n select @UpdatedVal = ((@PreviousValDec * (@CurrentRate/@PreviousRate))-(@PreviousVal * (@CurrentRate/@PreviousRate)));\n\n select @PreviousValDec = @UpdatedVal;\n\n set @UpdatedVal = cast (@UpdatedVal as int);\n\n set @PreviousVal = cast (@PreviousValDec as int)\n\n end\n\n select @NumString = @NumString + IIF (@Cnt = 1,'',', ') + cast (@UpdatedVal as nvarchar(20)) + ' ' + @CurrentUnit\n set @Cnt = @Cnt + 1\n select @PreviousRate = Rate from @TableUnit where Num = (@Cnt - 1)\nend\n\nselect @NumString as FinalResult;\n"
},
{
"answer_id": 74306138,
"author": "Patrick Hurst",
"author_id": 18522514,
"author_profile": "https://Stackoverflow.com/users/18522514",
"pm_score": 0,
"selected": false,
"text": "DECLARE @Unit TABLE (id INT PRIMARY KEY, UnitName NVARCHAR(10));\nINSERT INTO @Unit (id, UnitName) VALUES \n(1,'Ton'),(2,'Kg'),(3,'g');\nDECLARE @UnitGroupDetail TABLE (id INT PRIMARY KEY, UnitGroupId INT, MajorUnitID INT, SubUnitID INT, MinorUnitID INT, MajorUnitRate DECIMAL(10,2), SubUnitRate DECIMAL(10,2), MinorUnitRate DECIMAL(10,2));\nINSERT INTO @UnitGroupDetail (id, UnitGroupId, MajorUnitID, SubUnitID, MinorUnitID, MajorUnitRate, SubUnitRate, MinorUnitRate) VALUES \n(1, 1, 1, 2, 3, 1000000, 1000, 1);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5412814/"
] |
74,301,106 | <p>I have two dataframes <code>df_1</code> and <code>df_2</code>:</p>
<pre class="lang-py prettyprint-override"><code>rdd = spark.sparkContext.parallelize([
(1, '', '5647-0394'),
(2, '', '6748-9384'),
(3, '', '9485-9484')])
df_1 = spark.createDataFrame(rdd, schema=['ID', 'UPDATED_MESSAGE', 'ZIP_CODE'])
# +---+---------------+---------+
# | ID|UPDATED_MESSAGE| ZIP_CODE|
# +---+---------------+---------+
# | 1| |5647-0394|
# | 2| |6748-9384|
# | 3| |9485-9484|
# +---+---------------+---------+
rdd = spark.sparkContext.parallelize([
('JAMES', 'INDIA_WON', '6748-9384')])
df_2 = spark.createDataFrame(rdd, schema=['NAME', 'CODE', 'ADDRESS_CODE'])
# +-----+---------+------------+
# | NAME| CODE|ADDRESS_CODE|
# +-----+---------+------------+
# |JAMES|INDIA_WON| 6748-9384|
# +-----+---------+------------+
</code></pre>
<p>I need to update <code>df_1</code> column 'UPDATED MESSAGE' with value 'INDIA_WON' from df_2 column 'CODE'. Currently the column "UPDATED_MESSAGE" is Null. I need to update every row with value as 'INDIA_WON', How can we do it in PySpark?
The condition here is if we find 'ADDRESS_CODE" value in <code>df_1</code> column "ZIP_CODE", we need to populate all the values in 'UPDATED_MESSAGE' = 'INDIA_WON'.</p>
| [
{
"answer_id": 74308228,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "from pyspark.sql import functions as F\n\ndf_2 = df_2.groupBy('ADDRESS_CODE').agg(F.first('CODE').alias('CODE'))\n\ndf_joined = df_1.join(df_2, df_1.ZIP_CODE == df_2.ADDRESS_CODE, 'left')\ndf_filtered = df_joined.filter(~F.isnull('ADDRESS_CODE'))\nif bool(df_filtered.head(1)):\n df_1 = df_1.withColumn('UPDATED_MESSAGE', F.lit(df_filtered.head()['CODE']))\n\ndf_1.show()\n# +---+---------------+---------+\n# | ID|UPDATED_MESSAGE| ZIP_CODE|\n# +---+---------------+---------+\n# | 1| INDIA_WON|5647-0394|\n# | 2| INDIA_WON|6748-9384|\n# | 3| INDIA_WON|9485-9484|\n# +---+---------------+---------+\n"
},
{
"answer_id": 74308287,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 1,
"selected": false,
"text": "df_1"
},
{
"answer_id": 74308805,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": -1,
"selected": false,
"text": "%python\ndf_1.createOrReplaceTempView(\"tmp_zipcodes\")\ndf_2.createOrReplaceTempView(\"tmp_person\")\n"
},
{
"answer_id": 74312808,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "new=(df_1.drop('UPDATED_MESSAGE').join(broadcast(df_2.drop('NAME')),how='left', on=df_1.ZIP_CODE==df_2.ADDRESS_CODE)#Drop the null column and join\n .drop('ADDRESS_CODE')#Drop column no longer neede\n .toDF('ID', 'ZIP_CODE', 'UPDATED_MESSAGE')#rename new df\n ).show()\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20216373/"
] |
74,301,121 | <p>I have a function for detecting the window width and height on changing the layout.</p>
<p>The function for detecting width and height work fine but the problem is using them on stylesheet file.</p>
<p>The error is: Invalid hook call. Hooks can only be called inside the body of a function component.</p>
<p>My Function:</p>
<pre><code>import { useEffect, useCallback, useState } from 'react';
import { Dimensions } from 'react-native';
export function useDimensions () {
const [windowWidth, setWindowWidth] = useState(Dimensions.get('window').width);
const [windowHeight, setWindowHeight] = useState(Dimensions.get('window').height);
useEffect(() => {
const callback = () => {
setWindowWidth(Dimensions.get('window').width);
setWindowHeight(Dimensions.get('window').height);
}
Dimensions.addEventListener('change', callback);
}, []);
return {windowWidth, windowHeight};
};
</code></pre>
<p>Here is what I have tried in stylesheet (custom global stylesheet file) :</p>
<pre><code>import { StyleSheet } from "react-native";
import Colors from "./Colors";
import { windowHeight, windowWidth } from '../App/Components/Dimensions';
import { useDimensions } from '../App/Components/TestDimesions';
// Here is the problem : Invalid hook call...
const orientation = useDimensions();
const Global = StyleSheet.create({
test:{
width: windowWidht
}
});
export default Global
</code></pre>
| [
{
"answer_id": 74308228,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "from pyspark.sql import functions as F\n\ndf_2 = df_2.groupBy('ADDRESS_CODE').agg(F.first('CODE').alias('CODE'))\n\ndf_joined = df_1.join(df_2, df_1.ZIP_CODE == df_2.ADDRESS_CODE, 'left')\ndf_filtered = df_joined.filter(~F.isnull('ADDRESS_CODE'))\nif bool(df_filtered.head(1)):\n df_1 = df_1.withColumn('UPDATED_MESSAGE', F.lit(df_filtered.head()['CODE']))\n\ndf_1.show()\n# +---+---------------+---------+\n# | ID|UPDATED_MESSAGE| ZIP_CODE|\n# +---+---------------+---------+\n# | 1| INDIA_WON|5647-0394|\n# | 2| INDIA_WON|6748-9384|\n# | 3| INDIA_WON|9485-9484|\n# +---+---------------+---------+\n"
},
{
"answer_id": 74308287,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 1,
"selected": false,
"text": "df_1"
},
{
"answer_id": 74308805,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": -1,
"selected": false,
"text": "%python\ndf_1.createOrReplaceTempView(\"tmp_zipcodes\")\ndf_2.createOrReplaceTempView(\"tmp_person\")\n"
},
{
"answer_id": 74312808,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "new=(df_1.drop('UPDATED_MESSAGE').join(broadcast(df_2.drop('NAME')),how='left', on=df_1.ZIP_CODE==df_2.ADDRESS_CODE)#Drop the null column and join\n .drop('ADDRESS_CODE')#Drop column no longer neede\n .toDF('ID', 'ZIP_CODE', 'UPDATED_MESSAGE')#rename new df\n ).show()\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11848001/"
] |
74,301,148 | <p>I have a "<code>pandas.MultiIndex.from_product</code>" data-frame from which I want to slice some data.
For these slices I know the (multi-) index.</p>
<p>The known index does not necessarily exist in the data-frame, it might be lower for the start-index (<strong>b1</strong>) or higher for the end-index (<strong>b2</strong>), see code <code>slice1</code>.</p>
<p>Here is a <strong>minimal example</strong> of my problem.</p>
<pre><code>import pandas as pd
ind = pd.MultiIndex.from_product([range(3), range(3)], names=["a", "b"])
df = pd.DataFrame(range(0,9999,1111), columns=["values"], index=ind)
idx = pd.IndexSlice
slice1 = df.loc[idx[0:1, 1:3],:]
slice2 = df.loc[idx[0:2, 1:0],:]
</code></pre>
<p>In the pictures you see the data-frame <code>df</code>, <code>slice1</code> and the expected <code>slice2</code>. As long as <strong>b1<b2</strong> my code works perfectly fine but when <strong>b1>b2</strong> as it is in <code>slice2</code> it returns an empty data-frame.</p>
<p><a href="https://i.stack.imgur.com/5LKN1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5LKN1.png" alt="Data-Frame" /></a>
<a href="https://i.stack.imgur.com/pBfpX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pBfpX.png" alt="Slice1" /></a>
<a href="https://i.stack.imgur.com/tSqRc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tSqRc.png" alt="Slice2" /></a></p>
<p>Is there a way to make this working? BTW, I saw this post here: <a href="https://stackoverflow.com/questions/53927460/select-rows-in-pandas-multiindex-dataframe">Select rows in pandas MultiIndex DataFrame</a> but I don't think it answers this question.</p>
| [
{
"answer_id": 74308228,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "from pyspark.sql import functions as F\n\ndf_2 = df_2.groupBy('ADDRESS_CODE').agg(F.first('CODE').alias('CODE'))\n\ndf_joined = df_1.join(df_2, df_1.ZIP_CODE == df_2.ADDRESS_CODE, 'left')\ndf_filtered = df_joined.filter(~F.isnull('ADDRESS_CODE'))\nif bool(df_filtered.head(1)):\n df_1 = df_1.withColumn('UPDATED_MESSAGE', F.lit(df_filtered.head()['CODE']))\n\ndf_1.show()\n# +---+---------------+---------+\n# | ID|UPDATED_MESSAGE| ZIP_CODE|\n# +---+---------------+---------+\n# | 1| INDIA_WON|5647-0394|\n# | 2| INDIA_WON|6748-9384|\n# | 3| INDIA_WON|9485-9484|\n# +---+---------------+---------+\n"
},
{
"answer_id": 74308287,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 1,
"selected": false,
"text": "df_1"
},
{
"answer_id": 74308805,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": -1,
"selected": false,
"text": "%python\ndf_1.createOrReplaceTempView(\"tmp_zipcodes\")\ndf_2.createOrReplaceTempView(\"tmp_person\")\n"
},
{
"answer_id": 74312808,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "new=(df_1.drop('UPDATED_MESSAGE').join(broadcast(df_2.drop('NAME')),how='left', on=df_1.ZIP_CODE==df_2.ADDRESS_CODE)#Drop the null column and join\n .drop('ADDRESS_CODE')#Drop column no longer neede\n .toDF('ID', 'ZIP_CODE', 'UPDATED_MESSAGE')#rename new df\n ).show()\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14691491/"
] |
74,301,181 | <p>I have created a directive in Angular that can go back if there is a history or go to a default route.
We can not test in JS if there is previous history.
So I make a redirection to the default route and call the history.back() function.</p>
<ul>
<li><p>Case 1 :
there is not history, the history.back() function does nothing and the redirection to the default route is done.</p>
</li>
<li><p>Case 2 :
there is a history, the redirection to the default route starts but is canceled by the history.back() and the user is redirected to the previous page.</p>
</li>
</ul>
<pre><code>goBack() {
if(this.routerCommand) {
this.router.navigate(this.routerCommand);
}
window.history.back();
}
</code></pre>
<p>It works in all browsers except Safari.
I don't understand why ?</p>
<p>If someone can help me.
Thank's in advance.</p>
| [
{
"answer_id": 74308228,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "from pyspark.sql import functions as F\n\ndf_2 = df_2.groupBy('ADDRESS_CODE').agg(F.first('CODE').alias('CODE'))\n\ndf_joined = df_1.join(df_2, df_1.ZIP_CODE == df_2.ADDRESS_CODE, 'left')\ndf_filtered = df_joined.filter(~F.isnull('ADDRESS_CODE'))\nif bool(df_filtered.head(1)):\n df_1 = df_1.withColumn('UPDATED_MESSAGE', F.lit(df_filtered.head()['CODE']))\n\ndf_1.show()\n# +---+---------------+---------+\n# | ID|UPDATED_MESSAGE| ZIP_CODE|\n# +---+---------------+---------+\n# | 1| INDIA_WON|5647-0394|\n# | 2| INDIA_WON|6748-9384|\n# | 3| INDIA_WON|9485-9484|\n# +---+---------------+---------+\n"
},
{
"answer_id": 74308287,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 1,
"selected": false,
"text": "df_1"
},
{
"answer_id": 74308805,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": -1,
"selected": false,
"text": "%python\ndf_1.createOrReplaceTempView(\"tmp_zipcodes\")\ndf_2.createOrReplaceTempView(\"tmp_person\")\n"
},
{
"answer_id": 74312808,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "new=(df_1.drop('UPDATED_MESSAGE').join(broadcast(df_2.drop('NAME')),how='left', on=df_1.ZIP_CODE==df_2.ADDRESS_CODE)#Drop the null column and join\n .drop('ADDRESS_CODE')#Drop column no longer neede\n .toDF('ID', 'ZIP_CODE', 'UPDATED_MESSAGE')#rename new df\n ).show()\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406283/"
] |
74,301,185 | <p>I need to calculate frequency of float elements in list. Convert them to int I can't, because I need to manipulate then float values, not int.</p>
<p>My try in the code below:</p>
<pre><code> values = [21.963, 23.4131, 23.7639, 24.3934, 24.5237, 25.2829, 25.394]
df = pd.Series(values).value_counts().sort_index().reset_index().reset_index(drop=True)
df.columns = ['Element', 'Frequency']
frequency = (df['Frequency'].values).tolist()
</code></pre>
<h3>hovewer I want to have two separate lists(not dataframe):</h3>
<ol>
<li>List of float elements</li>
<li>List of frequencies of float elements given</li>
</ol>
<h3>Expected output:</h3>
<p>values = [21.963, 23.4131, 23.7639, 24.3934, 24.5237, 25.2829, 25.394]</p>
<p>frequency = [1, 1, 1, 1, 1, 1, 1]</p>
| [
{
"answer_id": 74308228,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "from pyspark.sql import functions as F\n\ndf_2 = df_2.groupBy('ADDRESS_CODE').agg(F.first('CODE').alias('CODE'))\n\ndf_joined = df_1.join(df_2, df_1.ZIP_CODE == df_2.ADDRESS_CODE, 'left')\ndf_filtered = df_joined.filter(~F.isnull('ADDRESS_CODE'))\nif bool(df_filtered.head(1)):\n df_1 = df_1.withColumn('UPDATED_MESSAGE', F.lit(df_filtered.head()['CODE']))\n\ndf_1.show()\n# +---+---------------+---------+\n# | ID|UPDATED_MESSAGE| ZIP_CODE|\n# +---+---------------+---------+\n# | 1| INDIA_WON|5647-0394|\n# | 2| INDIA_WON|6748-9384|\n# | 3| INDIA_WON|9485-9484|\n# +---+---------------+---------+\n"
},
{
"answer_id": 74308287,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 1,
"selected": false,
"text": "df_1"
},
{
"answer_id": 74308805,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": -1,
"selected": false,
"text": "%python\ndf_1.createOrReplaceTempView(\"tmp_zipcodes\")\ndf_2.createOrReplaceTempView(\"tmp_person\")\n"
},
{
"answer_id": 74312808,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "new=(df_1.drop('UPDATED_MESSAGE').join(broadcast(df_2.drop('NAME')),how='left', on=df_1.ZIP_CODE==df_2.ADDRESS_CODE)#Drop the null column and join\n .drop('ADDRESS_CODE')#Drop column no longer neede\n .toDF('ID', 'ZIP_CODE', 'UPDATED_MESSAGE')#rename new df\n ).show()\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15576385/"
] |
74,301,219 | <p>I want a certain text to be displayed to me depending on the button pressed. In the array I have set the text that needs to be assigned to the buttons. I know that can do this by passing a parameter (a++) to the type Text function when you click on the button, but for some reason it doesn't work. And it gives the error "Assignment to constant variable" If I don't add this parameter, then it outputs only the first word in the array to all buttons</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>const a = [];
a[0] = "На концерты";
a[1] = "На мероприятия";
a[2] = "На фестиваль";
a[3] = "На шоу";
a[4] = "На онлайн-событие";
const typewriter = document.querySelector('.typewriter')
// печать
function typeText() {
let line = 0; // номер строки
let count = 0; // счетчик позиции
let out = ''; // то что мы делаем
function typeLine() {
// рисует строки
let timeout = setInterval(function() {
out += a[0][line][count];
typewriter.innerHTML = out;
count++;
if (count >= a[0][line].length) {
count = 0;
line++;
}
if (line == a[0].length) {
clearTimeout(timeout)
return true;
}
}, 70);
}
typeLine();
}
typeText();
const buttons = document.querySelectorAll('#buttonsId')
Array.from(buttons).map((item, index) => item.addEventListener('click', (e) => {
typeText(a++)
}))</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header_text">
<div class="content">
<div class="header_text__block">
<h1>Сервис <br> продажи билетов</h1>
<p class="typewriter"></p>
</div>
<div class="header__button">
<button class="buttons" id="buttonsId" data-action="0"><a href="#">Конференция</a></button>
<button class="buttons" id="buttonsId" data-action="1"><a href="#">Выставка</a></button>
<button class="buttons" id="buttonsId" data-action="2"><a href="#">Шоу</a></button>
<button class="buttons" id="buttonsId" data-action="3"><a href="#">Онлайн</a></button>
<button class="buttons" id="buttonsId" data-action="4"><a href="#">Театр</a></button>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74308228,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "from pyspark.sql import functions as F\n\ndf_2 = df_2.groupBy('ADDRESS_CODE').agg(F.first('CODE').alias('CODE'))\n\ndf_joined = df_1.join(df_2, df_1.ZIP_CODE == df_2.ADDRESS_CODE, 'left')\ndf_filtered = df_joined.filter(~F.isnull('ADDRESS_CODE'))\nif bool(df_filtered.head(1)):\n df_1 = df_1.withColumn('UPDATED_MESSAGE', F.lit(df_filtered.head()['CODE']))\n\ndf_1.show()\n# +---+---------------+---------+\n# | ID|UPDATED_MESSAGE| ZIP_CODE|\n# +---+---------------+---------+\n# | 1| INDIA_WON|5647-0394|\n# | 2| INDIA_WON|6748-9384|\n# | 3| INDIA_WON|9485-9484|\n# +---+---------------+---------+\n"
},
{
"answer_id": 74308287,
"author": "Bartosz Gajda",
"author_id": 6870955,
"author_profile": "https://Stackoverflow.com/users/6870955",
"pm_score": 1,
"selected": false,
"text": "df_1"
},
{
"answer_id": 74308805,
"author": "CRAFTY DBA",
"author_id": 2577687,
"author_profile": "https://Stackoverflow.com/users/2577687",
"pm_score": -1,
"selected": false,
"text": "%python\ndf_1.createOrReplaceTempView(\"tmp_zipcodes\")\ndf_2.createOrReplaceTempView(\"tmp_person\")\n"
},
{
"answer_id": 74312808,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 0,
"selected": false,
"text": "new=(df_1.drop('UPDATED_MESSAGE').join(broadcast(df_2.drop('NAME')),how='left', on=df_1.ZIP_CODE==df_2.ADDRESS_CODE)#Drop the null column and join\n .drop('ADDRESS_CODE')#Drop column no longer neede\n .toDF('ID', 'ZIP_CODE', 'UPDATED_MESSAGE')#rename new df\n ).show()\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20324239/"
] |
74,301,235 | <p>I'm trying to run several functions in a useEffect after the internet connection state resolves to true. But at the start, the status will be null and then it will resolve to true. As a result the rest of the functions will not be invoked. How to resolve this conflict?</p>
<p>I want to run the functions only once</p>
<pre><code>const Component = () => {
const {isConnected} = useNetInfo();
useEffect(() => {
runFunctionOne();
runFunctionTwo();
}, []);
const runFunctionOne = () = {
if (!isConnected) return;
// rest
}
const runFunctionTwo = () = {
if (!isConnected) return;
// rest
}
}
</code></pre>
| [
{
"answer_id": 74301369,
"author": "E. Dn",
"author_id": 7976987,
"author_profile": "https://Stackoverflow.com/users/7976987",
"pm_score": 1,
"selected": false,
"text": "const wasConnectedRef = useRef(false);\n\nuseEffect(() => {\n if (isConnected && !wasConnectedRef.current) {\n runFunctionOne();\n runFunctionTwo();\n wasConnectedRef.current = true;\n }\n}, [isConnected]);\n"
},
{
"answer_id": 74301499,
"author": "Elbashir Saror",
"author_id": 20033482,
"author_profile": "https://Stackoverflow.com/users/20033482",
"pm_score": 0,
"selected": false,
"text": " useEffect(() => {\n // functions will not be called until 6s have passed, hopefully you will be connected by then.\n setTimeout(() => {\n runFunctionOne();\n runFunctionTwo(); \n }, 6000);\n }, []);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19574244/"
] |
74,301,259 | <p>I'm trying to make a call from within R to execute BASH commands, to get my feet wet:</p>
<ul>
<li>I wanted to simply capture a listing of my current files located in a specific directory through use of the "ls -al" command. The output would be sent to text file called a01_test.txt.</li>
<li>The directory I would like to capture the contents of is "C:\Users\user00\a01_TEST" which is referenced as "/mnt/c/Users/user00/a01_TEST/" from a WSL Ubuntu 20.04.5 LTS perspective.</li>
<li>The directory contains five (5) files: file_01.txt, file_02.txt ,..., file_05.txt.</li>
<li>FYI, I am running R (R version 4.2.0 (2022-04-22 ucrt)) via RStudio (2022.07.1 Build 554) on Windows 11 (Version 10.0.22000 Build 22000).</li>
</ul>
<p>I tried:</p>
<pre><code>PATH_UNIX <- "/mnt/c/Users/user00/a01_TEST/"
FILENAME_TEST <-"a01_test.txt"
paste0("system(\"bash -c \'ls -al ",PATH_UNIX," >",PATH_UNIX,FILENAME_TEST,"\'\")")
</code></pre>
<p>However that only returned a command prompt -- nothing else:</p>
<pre><code>> paste0("system(\"bash -c \'ls -al ",PATH_UNIX," >",PATH_UNIX,FILENAME_TEST,"\'\")")
[1] "system(\"bash -c 'ls -al /mnt/c/Users/user00/a01_TEST/ >/mnt/c/Users/user00/a01_TEST/a01_test.txt'\")"
>
</code></pre>
<p>I thought one could test the code using:</p>
<pre><code>cat(print(paste0("system(\"bash -c \'ls -al ",PATH_UNIX," >",PATH_UNIX,FILENAME_TEST,"\'\")")))
</code></pre>
<p>which resulted in:</p>
<pre><code>> cat(print(paste0("system(\"bash -c \'ls -al ",PATH_UNIX," >",PATH_UNIX,FILENAME_TEST,"\'\")")))
[1] "system(\"bash -c 'ls -al /mnt/c/Users/user00/a01_TEST/ >/mnt/c/Users/user00/a01_TEST/a01_test.txt'\")"
system("bash -c 'ls -al /mnt/c/Users/user00/a01_TEST/ >/mnt/c/Users/user00/a01_TEST/a01_test.txt'")
</code></pre>
<p>If I do not use variables, such as, PATH_UNIX and FILENAME_TEST and code the entire path manually, I can create a text file (a01_test.txt) giving me the desired listing of the directory's contents:</p>
<pre><code>system("bash -c 'ls -al /mnt/c/Users/user00/a01_TEST > /mnt/c/Users/user00/a01_TEST/a01_test.txt'")
</code></pre>
<p>which results in:</p>
<pre><code>> system("bash -c 'ls -al /mnt/c/Users/user00/a01_TEST > /mnt/c/Users/user00/a01_TEST/a01_test.txt'")
[1] 0
>
</code></pre>
<p>giving me the file called "a01_test.txt" containing the directory's contents:</p>
<pre><code>total 0
drwxrwxrwx 1 user00 user00 4096 Nov 3 2022 .
drwxrwxrwx 1 user00 user00 4096 Nov 3 05:07 ..
-rwxrwxrwx 1 user00 user00 0 Nov 3 2022 a01_test.txt
-rwxrwxrwx 1 user00 user00 0 Nov 3 05:26 file_01.txt
-rwxrwxrwx 1 user00 user00 0 Nov 3 05:26 file_02.txt
-rwxrwxrwx 1 user00 user00 0 Nov 3 05:26 file_03.txt
-rwxrwxrwx 1 user00 user00 0 Nov 3 05:26 file_04.txt
-rwxrwxrwx 1 user00 user00 0 Nov 3 05:26 file_05.txt
</code></pre>
<p>Any assistance to make use of the variables PATH_UNIX & FILENAME_TEST to make a call to Linux/Unix to obtain a directory listing would be appreciated.</p>
| [
{
"answer_id": 74301369,
"author": "E. Dn",
"author_id": 7976987,
"author_profile": "https://Stackoverflow.com/users/7976987",
"pm_score": 1,
"selected": false,
"text": "const wasConnectedRef = useRef(false);\n\nuseEffect(() => {\n if (isConnected && !wasConnectedRef.current) {\n runFunctionOne();\n runFunctionTwo();\n wasConnectedRef.current = true;\n }\n}, [isConnected]);\n"
},
{
"answer_id": 74301499,
"author": "Elbashir Saror",
"author_id": 20033482,
"author_profile": "https://Stackoverflow.com/users/20033482",
"pm_score": 0,
"selected": false,
"text": " useEffect(() => {\n // functions will not be called until 6s have passed, hopefully you will be connected by then.\n setTimeout(() => {\n runFunctionOne();\n runFunctionTwo(); \n }, 6000);\n }, []);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18414176/"
] |
74,301,260 | <ul>
<li>I have an array of 9 strings.</li>
<li>I also created 9 UI buttons.</li>
</ul>
<p>Task:</p>
<ul>
<li>when pressing the button <code>[0]</code> the line <code>[0]</code> appears.</li>
<li>when button <code>[1]</code> is pressed, line <code>[1]</code> appears</li>
</ul>
<p>and so on.</p>
<pre><code>using Assembly_CSharp;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;
public class WorldMapScr : MonoBehaviour
{
public GameObject RoomMap;
public TMP_Text txtHeader;
public TMP_Text txtDescription;
public TMP_Text txtNameRoom_1;
public TMP_Text txtNameRoom_2;
public TMP_Text txtNameRoom_3;
public TMP_Text txtNameRoom_4;
public Button[] buttons;
allTxtRoomMap txtRoom = new();
private void Update()
{
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].onClick.AddListener(OpenWindow);
txtHeader.text = txtRoom.headerAndDestcriptionlvl[i];
txtDescription.text = txtRoom.headerAndDestcriptionlvl[i];
txtNameRoom_1.text = txtRoom.roomLvlName[i];
txtNameRoom_2.text = txtRoom.roomLvlName[i];
txtNameRoom_3.text = txtRoom.roomLvlName[i];
txtNameRoom_4.text = txtRoom.roomLvlName[i];
break;
}
}
void OpenWindow()
{
RoomMap.SetActive(true);
}
}
</code></pre>
<p>I understand that the operations in the for loop don't matter because there is a "break". I sent this code only for an example, so that you understand what I want to achieve. I also want to clarify. The easiest way would be to just create a few separate methods for each button, but that's completely unprofessional in my opinion. Please tell me how this can be done with an array of buttons. Thanks for any replies.</p>
<p><a href="https://i.stack.imgur.com/SoRv0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SoRv0.png" alt="Buttons" /></a></p>
<p>Added:
Thank you very much for the explanation and code example. Of course, with your help, I managed to run the code, but as you rightly pointed out, because of the for loop, listening and reacting occurs many times. This significantly affected the speed. In the end I have this:</p>
<pre><code> private void Update()
{
for (int i = 0; i < buttons.Length; i++)
{
int index = i;
buttons[i].onClick.AddListener(() => OpenWindow(index));
}
}
void OpenWindow(int i)
{
RoomMap.SetActive(true);
Debug.Log(i);
txtHeader.text = txtRoom.headerAndDestcriptionlvl[0, i];
txtDescription.text = txtRoom.headerAndDestcriptionlvl[1, i];
txtNameRoom_1.text = txtRoom.roomLvlName[i, 0];
txtNameRoom_2.text = txtRoom.roomLvlName[i, 1];
txtNameRoom_3.text = txtRoom.roomLvlName[i, 2];
txtNameRoom_4.text = txtRoom.roomLvlName[i, 3];
}
</code></pre>
<p>To be honest, I don't have any idea how I can implement the same without using "for". If you have any ideas let me know. Thank you again. I just put the listener in the Start method and it worked. But I'm still confused: did I do the right thing?
P.S:Delegation is a topic I haven't gotten to yet, but will soon!</p>
| [
{
"answer_id": 74301369,
"author": "E. Dn",
"author_id": 7976987,
"author_profile": "https://Stackoverflow.com/users/7976987",
"pm_score": 1,
"selected": false,
"text": "const wasConnectedRef = useRef(false);\n\nuseEffect(() => {\n if (isConnected && !wasConnectedRef.current) {\n runFunctionOne();\n runFunctionTwo();\n wasConnectedRef.current = true;\n }\n}, [isConnected]);\n"
},
{
"answer_id": 74301499,
"author": "Elbashir Saror",
"author_id": 20033482,
"author_profile": "https://Stackoverflow.com/users/20033482",
"pm_score": 0,
"selected": false,
"text": " useEffect(() => {\n // functions will not be called until 6s have passed, hopefully you will be connected by then.\n setTimeout(() => {\n runFunctionOne();\n runFunctionTwo(); \n }, 6000);\n }, []);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406251/"
] |
74,301,263 | <p>I'm trying to import a table from a SQL Sever DB to Bigquery. This table has a Datetime column that I've mapped with Bigquery DATETIME. I'm using Dataflow to ingest the table with default template (JDBC to Bigquery).<br />
This is the connection string:<br />
<code>jdbc:sqlserver://<hostIP>:1433;instanceName=SQLSERVER;databaseName=<dbName>;encrypt=true;trustServerCertificate=true;</code><br />
I've also added user and pwd (my credentials) in the job's parameters.<br />
But Dataflow gives me the following error:</p>
<pre><code>Error message from worker: java.lang.ClassCastException: class java.sql.Timestamp cannot be cast to class java.time.temporal.TemporalAccessor (java.sql.Timestamp is in module java.sql of loader 'platform'; java.time.temporal.TemporalAccessor is in module java.base of loader 'bootstrap')
com.google.cloud.teleport.templates.common.JdbcConverters$ResultSetToTableRow.mapRow(JdbcConverters.java:157)
com.google.cloud.teleport.templates.common.JdbcConverters$ResultSetToTableRow.mapRow(JdbcConverters.java:115)
com.google.cloud.teleport.io.DynamicJdbcIO$DynamicReadFn.processElement(DynamicJdbcIO.java:388)
</code></pre>
<p>I've also tried to map the datetime column with the Bigquery TIMESTAMP datatype, but I've got the same error.<br />
It's not a connection problem, because I've tried to read other columns (except the datetime column) and the dataflow job works.</p>
<p>What do I have to do? What's the problem?</p>
<p>I'm using <code>com.microsoft.sqlserver.jdbc.SQLServerDriver</code> as JDBC Driver name and I've downloaded from Maven the jar version <code>mssql-jdbc-11.2.1.jre8.jar</code>.</p>
| [
{
"answer_id": 74334228,
"author": "Rathish Kumar B",
"author_id": 2156784,
"author_profile": "https://Stackoverflow.com/users/2156784",
"pm_score": 0,
"selected": false,
"text": "import pyodbc \nimport sqlalchemy\nfrom sqlalchemy.engine import URL\nimport datetime\nfrom google.cloud import bigquery\nfrom google.oauth2 import service_account\n\nprint(\"Sync job started at :\", datetime.datetime.now())\n\ncredentials = service_account.Credentials.from_service_account_file('sa-key.json')\nprojectid = \"myproject\"\ntableid = \"projectid.dataset.table\"\nclient = bigquery.Client(credentials= credentials,project=projectid)\n\nserver = 'cloudsql-proxyip' \ndatabase = 'db' \nusername = 'user' \npassword = 'pwd' \ndriver = \"{ODBC Driver 18 for SQL Server}\"\nport = 1433\n\ncnxn = pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';TrustServerCertificate=YES;')\ncursor = cnxn.cursor()\n\ndef HandleHierarchyId(v):\n return str(v)\n\nconnection_string = f\"DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};TrustServerCertificate=YES;\"\nconnection_url = URL.create(\"mssql+pyodbc\", query={\"odbc_connect\": connection_string})\nsql_engine = sqlalchemy.create_engine(connection_url)\n\nselect_stmt = (\"SELECT * FROM [db].[schema].[view]\")\n\nprint(\"Creating connetion\")\ndb = sql_engine.connect().connection\ndb.add_output_converter(-151, HandleHierarchyId)\n \nprint(\"Fetching data\")\ndata = db.execute(select_stmt).fetchall()\nmd = sqlalchemy.MetaData()\ntable = sqlalchemy.Table('view', md, autoload=True, autoload_with=sql_engine)\ncolumns = table.c\n\ncolumn_list = []\nfor column in columns:\n column_list.append(column.name)\n\n\ndef split(a, n):\n k, m = divmod(len(a), n)\n return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))\n\n\ndef to_json(row, columns):\n newlist = list(row)\n newdicts = dict(zip(columns, newlist))\n return newdicts\n\ndef ingestdata(tableid, data):\n table = bigquery.Table.from_string(tableid)\n print(\"Data ingestion started\")\n errors = client.insert_rows_json(table, data) # Make an API request.\n if errors == []:\n print(\"New rows have been added.\")\n else:\n print(\"Encountered errors while inserting rows: {}\".format(errors))\n\ninsertdata = []\nfor row in data:\n newdict = to_json(row, column_list)\n insertdata.append(newdict)\n\nprint(\"Total record count :\", len(insertdata))\n\n# BigQuery POST API limitations - split the list into multiple smaller chunks\nrecords = split(insertdata, 10)\n\n\nfor r in records:\n print(\"Batch record count :\", len(r))\n ingestdata(tableid=tableid, data=r)\n\n\nprint(\"Total records inserted : \", len(insertdata))\nprint(\"Sync job ended at :\", datetime.datetime.now())\n"
},
{
"answer_id": 74347960,
"author": "alex-mont",
"author_id": 20173273,
"author_profile": "https://Stackoverflow.com/users/20173273",
"pm_score": 3,
"selected": true,
"text": "CONVERT"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20173273/"
] |
74,301,277 | <p>I'm doing a very simple 2D platform game project, you can see here how it is so far: <a href="https://master.d3kjckivyd1c76.amplifyapp.com/src/Games/PlatformGame2D101/index.html" rel="nofollow noreferrer">https://master.d3kjckivyd1c76.amplifyapp.com/src/Games/PlatformGame2D101/index.html</a></p>
<p>But I can't detect the collision between the enemy (the chainsaw) and the player.</p>
<p>I have this code to detect if the two bodies are colliding, but it only prints the <code>Enemy</code> when the player is moving:</p>
<pre class="lang-py prettyprint-override"><code>func _physics_process(delta: float) -> void:
velocity = move_and_slide(velocity, Vector2.UP)
for i in get_slide_count():
var collision = get_slide_collision(i)
if collision.collider.is_in_group("Enemy"): print("Enemy")
</code></pre>
<ul>
<li><a href="https://bitbucket.org/201flaviosilva-labs/platform-game-2d-101-godot/src/697335074bca6ddc08a7712b1d7963de271398b9/Project/Scripts/Player.gd#lines-34" rel="nofollow noreferrer">original file</a></li>
<li><a href="https://bitbucket.org/201flaviosilva-labs/platform-game-2d-101-godot/src/master/" rel="nofollow noreferrer">I uploaded the project to the Bitbucket</a></li>
</ul>
<p>Thanks any help : )</p>
| [
{
"answer_id": 74334228,
"author": "Rathish Kumar B",
"author_id": 2156784,
"author_profile": "https://Stackoverflow.com/users/2156784",
"pm_score": 0,
"selected": false,
"text": "import pyodbc \nimport sqlalchemy\nfrom sqlalchemy.engine import URL\nimport datetime\nfrom google.cloud import bigquery\nfrom google.oauth2 import service_account\n\nprint(\"Sync job started at :\", datetime.datetime.now())\n\ncredentials = service_account.Credentials.from_service_account_file('sa-key.json')\nprojectid = \"myproject\"\ntableid = \"projectid.dataset.table\"\nclient = bigquery.Client(credentials= credentials,project=projectid)\n\nserver = 'cloudsql-proxyip' \ndatabase = 'db' \nusername = 'user' \npassword = 'pwd' \ndriver = \"{ODBC Driver 18 for SQL Server}\"\nport = 1433\n\ncnxn = pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';TrustServerCertificate=YES;')\ncursor = cnxn.cursor()\n\ndef HandleHierarchyId(v):\n return str(v)\n\nconnection_string = f\"DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};TrustServerCertificate=YES;\"\nconnection_url = URL.create(\"mssql+pyodbc\", query={\"odbc_connect\": connection_string})\nsql_engine = sqlalchemy.create_engine(connection_url)\n\nselect_stmt = (\"SELECT * FROM [db].[schema].[view]\")\n\nprint(\"Creating connetion\")\ndb = sql_engine.connect().connection\ndb.add_output_converter(-151, HandleHierarchyId)\n \nprint(\"Fetching data\")\ndata = db.execute(select_stmt).fetchall()\nmd = sqlalchemy.MetaData()\ntable = sqlalchemy.Table('view', md, autoload=True, autoload_with=sql_engine)\ncolumns = table.c\n\ncolumn_list = []\nfor column in columns:\n column_list.append(column.name)\n\n\ndef split(a, n):\n k, m = divmod(len(a), n)\n return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))\n\n\ndef to_json(row, columns):\n newlist = list(row)\n newdicts = dict(zip(columns, newlist))\n return newdicts\n\ndef ingestdata(tableid, data):\n table = bigquery.Table.from_string(tableid)\n print(\"Data ingestion started\")\n errors = client.insert_rows_json(table, data) # Make an API request.\n if errors == []:\n print(\"New rows have been added.\")\n else:\n print(\"Encountered errors while inserting rows: {}\".format(errors))\n\ninsertdata = []\nfor row in data:\n newdict = to_json(row, column_list)\n insertdata.append(newdict)\n\nprint(\"Total record count :\", len(insertdata))\n\n# BigQuery POST API limitations - split the list into multiple smaller chunks\nrecords = split(insertdata, 10)\n\n\nfor r in records:\n print(\"Batch record count :\", len(r))\n ingestdata(tableid=tableid, data=r)\n\n\nprint(\"Total records inserted : \", len(insertdata))\nprint(\"Sync job ended at :\", datetime.datetime.now())\n"
},
{
"answer_id": 74347960,
"author": "alex-mont",
"author_id": 20173273,
"author_profile": "https://Stackoverflow.com/users/20173273",
"pm_score": 3,
"selected": true,
"text": "CONVERT"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13356573/"
] |
74,301,299 | <p>Hi all I need to rotate two dimensional array as shown in the given picture. and if we rotate one set of array it should reflect for all the problems if you find out please do help me to solve the issue</p>
<p>input:</p>
<p><a href="https://i.stack.imgur.com/EkE9C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EkE9C.png" alt="enter image description here" /></a></p>
<p>output:</p>
<p><a href="https://i.stack.imgur.com/qc0kO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qc0kO.png" alt="enter image description here" /></a></p>
<p>Thankyou</p>
<p>I have tried slicing method to rotate the values but it doesn't give the correct values</p>
<pre><code>import pandas as pd
df = pd.read_csv("/content/pipe2.csv")
df1= df.iloc[6:10]+df.iloc[13:20]
df1
</code></pre>
| [
{
"answer_id": 74334228,
"author": "Rathish Kumar B",
"author_id": 2156784,
"author_profile": "https://Stackoverflow.com/users/2156784",
"pm_score": 0,
"selected": false,
"text": "import pyodbc \nimport sqlalchemy\nfrom sqlalchemy.engine import URL\nimport datetime\nfrom google.cloud import bigquery\nfrom google.oauth2 import service_account\n\nprint(\"Sync job started at :\", datetime.datetime.now())\n\ncredentials = service_account.Credentials.from_service_account_file('sa-key.json')\nprojectid = \"myproject\"\ntableid = \"projectid.dataset.table\"\nclient = bigquery.Client(credentials= credentials,project=projectid)\n\nserver = 'cloudsql-proxyip' \ndatabase = 'db' \nusername = 'user' \npassword = 'pwd' \ndriver = \"{ODBC Driver 18 for SQL Server}\"\nport = 1433\n\ncnxn = pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';TrustServerCertificate=YES;')\ncursor = cnxn.cursor()\n\ndef HandleHierarchyId(v):\n return str(v)\n\nconnection_string = f\"DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};TrustServerCertificate=YES;\"\nconnection_url = URL.create(\"mssql+pyodbc\", query={\"odbc_connect\": connection_string})\nsql_engine = sqlalchemy.create_engine(connection_url)\n\nselect_stmt = (\"SELECT * FROM [db].[schema].[view]\")\n\nprint(\"Creating connetion\")\ndb = sql_engine.connect().connection\ndb.add_output_converter(-151, HandleHierarchyId)\n \nprint(\"Fetching data\")\ndata = db.execute(select_stmt).fetchall()\nmd = sqlalchemy.MetaData()\ntable = sqlalchemy.Table('view', md, autoload=True, autoload_with=sql_engine)\ncolumns = table.c\n\ncolumn_list = []\nfor column in columns:\n column_list.append(column.name)\n\n\ndef split(a, n):\n k, m = divmod(len(a), n)\n return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))\n\n\ndef to_json(row, columns):\n newlist = list(row)\n newdicts = dict(zip(columns, newlist))\n return newdicts\n\ndef ingestdata(tableid, data):\n table = bigquery.Table.from_string(tableid)\n print(\"Data ingestion started\")\n errors = client.insert_rows_json(table, data) # Make an API request.\n if errors == []:\n print(\"New rows have been added.\")\n else:\n print(\"Encountered errors while inserting rows: {}\".format(errors))\n\ninsertdata = []\nfor row in data:\n newdict = to_json(row, column_list)\n insertdata.append(newdict)\n\nprint(\"Total record count :\", len(insertdata))\n\n# BigQuery POST API limitations - split the list into multiple smaller chunks\nrecords = split(insertdata, 10)\n\n\nfor r in records:\n print(\"Batch record count :\", len(r))\n ingestdata(tableid=tableid, data=r)\n\n\nprint(\"Total records inserted : \", len(insertdata))\nprint(\"Sync job ended at :\", datetime.datetime.now())\n"
},
{
"answer_id": 74347960,
"author": "alex-mont",
"author_id": 20173273,
"author_profile": "https://Stackoverflow.com/users/20173273",
"pm_score": 3,
"selected": true,
"text": "CONVERT"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15234905/"
] |
74,301,341 | <p>We are working on an S60 version and this platform has a nice PHP API..</p>
<p>However, there is nothing official about Php on Android, but since Jython exists, is there a way to let the snake and the robot work together??</p>
| [
{
"answer_id": 74334228,
"author": "Rathish Kumar B",
"author_id": 2156784,
"author_profile": "https://Stackoverflow.com/users/2156784",
"pm_score": 0,
"selected": false,
"text": "import pyodbc \nimport sqlalchemy\nfrom sqlalchemy.engine import URL\nimport datetime\nfrom google.cloud import bigquery\nfrom google.oauth2 import service_account\n\nprint(\"Sync job started at :\", datetime.datetime.now())\n\ncredentials = service_account.Credentials.from_service_account_file('sa-key.json')\nprojectid = \"myproject\"\ntableid = \"projectid.dataset.table\"\nclient = bigquery.Client(credentials= credentials,project=projectid)\n\nserver = 'cloudsql-proxyip' \ndatabase = 'db' \nusername = 'user' \npassword = 'pwd' \ndriver = \"{ODBC Driver 18 for SQL Server}\"\nport = 1433\n\ncnxn = pyodbc.connect('DRIVER={ODBC Driver 18 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';TrustServerCertificate=YES;')\ncursor = cnxn.cursor()\n\ndef HandleHierarchyId(v):\n return str(v)\n\nconnection_string = f\"DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password};TrustServerCertificate=YES;\"\nconnection_url = URL.create(\"mssql+pyodbc\", query={\"odbc_connect\": connection_string})\nsql_engine = sqlalchemy.create_engine(connection_url)\n\nselect_stmt = (\"SELECT * FROM [db].[schema].[view]\")\n\nprint(\"Creating connetion\")\ndb = sql_engine.connect().connection\ndb.add_output_converter(-151, HandleHierarchyId)\n \nprint(\"Fetching data\")\ndata = db.execute(select_stmt).fetchall()\nmd = sqlalchemy.MetaData()\ntable = sqlalchemy.Table('view', md, autoload=True, autoload_with=sql_engine)\ncolumns = table.c\n\ncolumn_list = []\nfor column in columns:\n column_list.append(column.name)\n\n\ndef split(a, n):\n k, m = divmod(len(a), n)\n return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))\n\n\ndef to_json(row, columns):\n newlist = list(row)\n newdicts = dict(zip(columns, newlist))\n return newdicts\n\ndef ingestdata(tableid, data):\n table = bigquery.Table.from_string(tableid)\n print(\"Data ingestion started\")\n errors = client.insert_rows_json(table, data) # Make an API request.\n if errors == []:\n print(\"New rows have been added.\")\n else:\n print(\"Encountered errors while inserting rows: {}\".format(errors))\n\ninsertdata = []\nfor row in data:\n newdict = to_json(row, column_list)\n insertdata.append(newdict)\n\nprint(\"Total record count :\", len(insertdata))\n\n# BigQuery POST API limitations - split the list into multiple smaller chunks\nrecords = split(insertdata, 10)\n\n\nfor r in records:\n print(\"Batch record count :\", len(r))\n ingestdata(tableid=tableid, data=r)\n\n\nprint(\"Total records inserted : \", len(insertdata))\nprint(\"Sync job ended at :\", datetime.datetime.now())\n"
},
{
"answer_id": 74347960,
"author": "alex-mont",
"author_id": 20173273,
"author_profile": "https://Stackoverflow.com/users/20173273",
"pm_score": 3,
"selected": true,
"text": "CONVERT"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20405408/"
] |
74,301,343 | <p>Am trying to create a poll results aggregation</p>
<p>I have two collections</p>
<p><strong>poll</strong> - here is one document</p>
<pre><code>{
"_id": {
"$oid": "636027704f7a15587ef74f26"
},
"question": "question 1",
"ended": false,
"options": [
{
"id": "1",
"option": "option 1"
},
{
"id": "2",
"option": "option 2"
},
{
"id": "3",
"option": "option 3"
}
]
}
</code></pre>
<p><strong>Vote</strong> - here is one document</p>
<pre><code>{
"_id": {
"$oid": "635ed3210acbf9fd14af8fd1"
},
"poll_id": "636027704f7a15587ef74f26",
"poll_option_id": "1",
"user_id": "1"
}
</code></pre>
<p>and i want to perform an aggregate query to get poll results</p>
<p>so am doing the following query</p>
<pre><code>
db.vote.aggregate(
[
{
$addFields: {
poll_id: { "$toObjectId": "$poll_id" }
},
},
{
$lookup: {
from: "poll",
localField: "poll_id",
foreignField: "_id",
as: "details"
}
},
{
$group:
{
_id: { poll_id: "$poll_id", poll_option_id: "$poll_option_id" },
details: { $first: "$details" },
count: { $sum: 1 }
}
},
{
$addFields: {
question: { $arrayElemAt: ["$details.question", 0] }
}
},
{
$addFields: {
options: { $arrayElemAt: ["$details.options", 0] }
}
},
{
$group: {
_id: "$_id.poll_id",
poll_id: { $first: "$_id.poll_id" },
question: { $first: "$question" },
options: { $first: "$options" },
optionsGrouped: {
$push: {
id: "$_id.poll_option_id",
count: "$count"
}
},
count: { $sum: "$count" }
}
}
]
)
</code></pre>
<p>That is giving me this form of results</p>
<pre><code>{ _id: ObjectId("636027704f7a15587ef74f26"),
poll_id: ObjectId("636027704f7a15587ef74f26"),
question: 'question 1',
options:
[ { id: '1', option: 'option 1' },
{ id: '2', option: 'option 2' },
{ id: '3', option: 'option 3' } ],
optionsGrouped:
[ { id: '1', count: 2 },
{ id: '2', count: 1 } ],
count: 3 }
</code></pre>
<p><strong>So</strong> what am interested in i want to have the results looking like ( like merging both options & options Group)</p>
<pre><code>{ _id: ObjectId("636027704f7a15587ef74f26"),
poll_id: ObjectId("636027704f7a15587ef74f26"),
question: 'question 1',
optionsGrouped:
[ { id: '1', option: 'option 1', count: 2 },
{ id: '2', option: 'option 2', count: 1 },
{ id: '3', option: 'option 3', count: 0 } ],
count: 4 }
</code></pre>
<hr />
<p><strong>Another question</strong> is the DB structure acceptable overall or i can represent that in a better way ?</p>
| [
{
"answer_id": 74301991,
"author": "nimrod serok",
"author_id": 18482310,
"author_profile": "https://Stackoverflow.com/users/18482310",
"pm_score": 2,
"selected": true,
"text": "$lookup"
},
{
"answer_id": 74487458,
"author": "Sherif Mo Shalaby",
"author_id": 2307340,
"author_profile": "https://Stackoverflow.com/users/2307340",
"pm_score": 0,
"selected": false,
"text": "db.poll.aggregate([\n {\n $addFields: {\n _id: {\n $toString: \"$_id\"\n }\n }\n },\n {\n $lookup: {\n from: \"poll_vote\",\n localField: \"_id\",\n foreignField: \"poll_id\",\n as: \"votes\"\n }\n },\n {\n $replaceRoot: {\n newRoot: {\n $let: {\n vars: {\n count: {\n $size: \"$votes\"\n },\n options: {\n $map: {\n input: \"$options\",\n as: \"option\",\n in: {\n $mergeObjects: [\n \"$$option\",\n {\n count: {\n $size: {\n $slice: [\n {\n $filter: {\n input: \"$votes\",\n as: \"v\",\n cond: {\n $and: [\n {\n $eq: [\n \"$$v.poll_option_id\",\n \"$$option._id\"\n ]\n }\n ]\n }\n }\n },\n 0,\n 100\n ]\n }\n }\n },\n {\n checked: {\n $toBool: {\n $size: {\n $slice: [\n {\n $filter: {\n input: \"$votes\",\n as: \"v\",\n cond: {\n $and: [\n {\n $eq: [\n \"$$v.user_id\",\n 2\n ]\n },\n {\n $eq: [\n \"$$v.poll_option_id\",\n \"$$option._id\"\n ]\n }\n ]\n }\n }\n },\n 0,\n 100\n ]\n }\n }\n }\n }\n ]\n }\n }\n }\n },\n \"in\": {\n _id: \"$_id\",\n question: \"$question\",\n count: \"$$count\",\n ended: \"$ended\",\n options: \"$$options\"\n }\n }\n }\n }\n },\n {\n $addFields: {\n answered: {\n $reduce: {\n input: \"$options\",\n initialValue: false,\n in: {\n $cond: [\n {\n $eq: [\n \"$$this.checked\",\n true\n ]\n },\n true,\n \"$$value\"\n ]\n }\n }\n }\n }\n }\n])\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2307340/"
] |
74,301,378 | <p>I have a library that provides implementation for processing some data and an abstract class that must be extended by the program that is using it to use the data processing stuff.</p>
<p>There is also another library, that depends on the first one and also implements the abstract class. I would like to make <em>both</em> of the libraries available to the program depending on the second one.</p>
<p>Example:</p>
<pre><code>libA/ (no deps)
DataProcessor.java
AbstractDataSource.java
libB/ (depends on libA)
FilesystemDataSource.java
app/ (depends on libB)
[here I want to access both DataProcessor and FilesystemDataSource]
</code></pre>
<p>I know that I can add both of the libraries as dependencies to the app, but it would be probably easier to maintain when there is not so many items in <code>build.gradle</code> files.</p>
| [
{
"answer_id": 74301606,
"author": "jiwopene",
"author_id": 4529168,
"author_profile": "https://Stackoverflow.com/users/4529168",
"pm_score": 1,
"selected": false,
"text": "api"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529168/"
] |
74,301,414 | <p>I'm currently trying to set up a new teams bot but can't really get it to work.</p>
<p>I have created a new Azure Bot service in azure, set it to UserAssignedMSI and I have managed to add it to teams. If I send something to the bot I can also see that the methods like <code>OnTurnAsync</code> and <code>OnMessageActivityAsync</code> are triggered so everything looks good so far.</p>
<p>But the moment I try to send something back, like for example:</p>
<pre><code> protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
await turnContext.SendActivityAsync(MessageFactory.Text("hello"), cancellationToken);
await base.OnMessageActivityAsync(turnContext, cancellationToken);
}
</code></pre>
<p>It crash with the following:</p>
<pre><code>System.ArgumentNullException: Value cannot be null. (Parameter 'clientSecret')
at Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential..ctor(String clientId, String clientSecret)
at Microsoft.Bot.Connector.Authentication.MicrosoftAppCredentials.<BuildAuthenticator>b__16_0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at System.Lazy`1.get_Value()
at Microsoft.Bot.Connector.Authentication.AppCredentials.<BuildIAuthenticator>b__36_0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at System.Lazy`1.get_Value()
at Microsoft.Bot.Connector.Authentication.AppCredentials.GetTokenAsync(Boolean forceRefresh)
at Microsoft.Bot.Connector.Authentication.AppCredentials.ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Bot.Connector.Conversations.ReplyToActivityWithHttpMessagesAsync(String conversationId, String activityId, Activity activity, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Bot.Connector.ConversationsExtensions.ReplyToActivityAsync(IConversations operations, String conversationId, String activityId, Activity activity, CancellationToken cancellationToken)
at Microsoft.Bot.Builder.BotFrameworkAdapter.SendActivitiesAsync(ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken)
at Microsoft.Bot.Builder.TurnContext.<>c__DisplayClass31_0.<<SendActivitiesAsync>g__SendActivitiesThroughAdapter|1>d.MoveNext()
--- End of stack trace from previous location ---
at Microsoft.Bot.Builder.TurnContext.SendActivityAsync(IActivity activity, CancellationToken cancellationToken)
at iPMC.Autotest.DevOps.Bots.Bots.AutotestBot.OnMessageActivityAsync(ITurnContext`1 turnContext, CancellationToken cancellationToken)
</code></pre>
<p>And I'm note sure why. According to the documentation this should be enough in my appsettings.json when using user assigned identity (AVALUE is of course my real values):</p>
<pre><code> "MicrosoftAppType": "UserAssignedMSI",
"MicrosoftAppId": "AVALUE",
"MicrosoftAppTenantId": "AVALUE",
"MicrosoftAppPassword": "",
"ConnectionName": "AVALUE"
</code></pre>
<p>It's seems like most examples use password as well so I can't really find anyone else that have used this.</p>
<p>I have also tried to both do it locally and deployed but I get the same exception on both places so I'm running out of ideas what I should test next.</p>
<p>Anyone else that have used UserAssignedMSI with teams bots and got it to work?</p>
| [
{
"answer_id": 74301606,
"author": "jiwopene",
"author_id": 4529168,
"author_profile": "https://Stackoverflow.com/users/4529168",
"pm_score": 1,
"selected": false,
"text": "api"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1776562/"
] |
74,301,422 | <p>I am using <code>length</code> because I need the length of state, but there is an error called <em>Uncaught TypeError: Cannot read properties of undefined (reading 'length')</em>. <code>SetName</code> and <code>name</code> are declared by the parent component, but they change every time they receive letters as input. I want to get a true value if there are more than one letter in the input, but what's wrong? I'd appreciate if you let me know</p>
<p><strong>File:</strong></p>
<pre><code>import React, { useState } from 'react'
import styled from 'styled-components';
import geryO from '../../resources/images/img/greyO.png'
const InputWrap = styled.div`
align-items: center;
-webkit-appearance: none;
background: rgb(250, 250, 250);
border: 1px solid rgb(219, 219, 219);
border-radius: 3px;
.inputInput {
font-size: 16px;
background: rgb(250, 250, 250);
border: 0;
flex: 1 0 auto;
margin: 0;
outline: none;
overflow: hidden;
padding: 9px 0 7px 8px;
text-overflow: ellipsis;
color: rgb(38, 38, 38);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}
.userIdCheckGreyO {
display: ${props=>props.isFocus===true&&props.isString?'flex':'none'};
align-items: center;
border: 0;
box-sizing: border-box;
flex: 0 0 auto;
flex-direction: row;
font: inherit;
font-size: 100%;
height: 100%;
margin: 0;
padding: 0;
padding-right: 8px;
position: relative;
vertical-align: middle;
}
`
function SignUpNameInpu({name, setName}) {
//isfocused?
const [isFocus, setIsFocus] = useState(false);
//change true/false if input is focused
const inputFocus = () => {
setIsFocus(false)
}
const inputNotFocus = () => {
setIsFocus(true)
}
//check length of string
const [isString, setIsString] = useState(false)
//(maybe this function is wrong)
const stringLengthCheck = (name) => {
if(name.length>0) {
setIsString(true)
}
}
console.log('stringLength :', isString)
return (
<InputWrap isFocus={isFocus} isString={isString}>
<label>
<span>
<input
onFocus={()=>{inputFocus(); stringLengthCheck();}}
onBlur={inputNotFocus}
className='inputInput'
value={name}
onChange={(e)=>{setName(e.target.value)}}>
</input>
</span>
</label>
<div className='userIdCheckGreyO'>
<span>
<img src={geryO} alt='greyO' />
</span>
</div>
</InputWrap>
)
}
export default SignUpNameInpu;
</code></pre>
| [
{
"answer_id": 74301606,
"author": "jiwopene",
"author_id": 4529168,
"author_profile": "https://Stackoverflow.com/users/4529168",
"pm_score": 1,
"selected": false,
"text": "api"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20108310/"
] |
74,301,447 | <p>I have an array that is made of multiple objects (9 to be exact). I'm looping through the array using .map() and then use axios.post() to post each single object with its corresponding name to a MySQL database.</p>
<p>However, when I run the code it gives me the error message:
"Too many re-renders. React limits the number of renders to prevent an infinite loop" which is being caused by the "parsedData.map()" function.</p>
<p>How can I avoid that, so that I can get each objects data and send it to the API?</p>
<pre><code> const [parsedData, setParsedData] = useState([]);
const [addInputData, SetAddInputData] = useState([]);
const handleSubmit = (event) => {
Papa.parse(event.target.files[0], {
header: true,
skipEmptyLines: true,
complete: function (results) {
setParsedData(results.data);
},
});
};
parsedData.map((person) => {
SetAddInputData({
status: person.status,
first_name: person.first_name,
last_name: person.last_name,
position: person.position,
email: person.email,
phone: person.phone,
image_url: person.image_url,
linked_in: person.linked_in,
business_name: person.business_name,
postcode: person.postcode,
icebreaker: person.icebreaker,
paragraph_one: person.paragraph_one,
paragraph_two: person.paragraph_two,
paragraph_three: person.paragraph_three,
call_to_action: person.call_to_action,
});
addNewLead({ addInputData }); // axios.post(`${base_url}/leads`, addInputData) in a different file
});
</code></pre>
| [
{
"answer_id": 74301606,
"author": "jiwopene",
"author_id": 4529168,
"author_profile": "https://Stackoverflow.com/users/4529168",
"pm_score": 1,
"selected": false,
"text": "api"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19389593/"
] |
74,301,453 | <p>Hi I need a help in redirecting users in my Wordpress website .I want to redirect users to different pages of the website based on their roles. Suppose for a vendor , after login I want to him to redirected to vendor dashboard or for a user like customer I want them to get redirected to custom page, admin will get redirected to admin dashboard , etc. I have tried Peter's login plugin and lots of other plugins to do this but these plugins has lots of limitation plus may lower the speed of the website. Is there anyway we can redirect users to different pages by adding code in the backend</p>
| [
{
"answer_id": 74301791,
"author": "Krishan Kaushik",
"author_id": 11901990,
"author_profile": "https://Stackoverflow.com/users/11901990",
"pm_score": 0,
"selected": false,
"text": "add_filter('login_redirect', 'login_redirect', 10, 3);\n\nfunction login_redirect($redirect_to, $requested_redirect_to, $user){\n \n if(!is_wp_error($user) ){\n\n $user_roles = $user->roles;\n if(in_array('vendor', $user_roles) ){\n\n $redirect_to = site_url('vendor/dashboard'); //vendor/dashboard update with your dashboard url\n }\n if(in_array('customer', $user_roles) ){\n\n $redirect_to = site_url('shop'); //any custom page url\n }\n }\n \n\n return $redirect_to;\n}\n"
},
{
"answer_id": 74301972,
"author": "Krunal Bhimajiyani",
"author_id": 19587288,
"author_profile": "https://Stackoverflow.com/users/19587288",
"pm_score": 2,
"selected": false,
"text": " function my_login_redirect( $redirect_to, $request, $user ) {\n global $user;\n if ( isset( $user->roles ) && is_array( $user->roles ) ) {\n $user_roles = $user->roles;\n if ( in_array( 'administrator', $user_roles ) ) {\n\n $redirect_to = admin_url(); // Admin redirect to admin dashboard.\n }\n if ( in_array( 'vendor', $user_roles ) ) {\n\n $redirect_to = site_url( 'vendor/dashboard' ); // Custom user redirect accordingly.\n }\n }\n return $redirect_to;\n }\n\n add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15692756/"
] |
74,301,470 | <p>I am wondering if it is possible to have a four stage media query what I mean by this is to have a max and min width as well as a max and min height in a media query an exmaple for what I am meaning is the following.</p>
<pre><code>@media only screen and (max-width: 400px)
and (min-width: 300px) and (max-height: 500px)
and (min-height: 600px){ .this-is-a-test-class{
padding-bottom: 100px ;
}
}
</code></pre>
<p>Above is what I think it would be if this is possible but I could not get it to work so any advice would be great or if there is a way to do this in 2 separate media query but only run if the other objective is met.</p>
| [
{
"answer_id": 74301788,
"author": "Ryan1827",
"author_id": 18440788,
"author_profile": "https://Stackoverflow.com/users/18440788",
"pm_score": 0,
"selected": false,
"text": "@media only screen and (max-width: 900px) and (min-width: 778px) and (max-height: 840px) {\n .slider-orange-text{\n padding-bottom: 200px ;\n } \n}\n"
},
{
"answer_id": 74301865,
"author": "Cornel Raiu",
"author_id": 3741900,
"author_profile": "https://Stackoverflow.com/users/3741900",
"pm_score": 2,
"selected": true,
"text": "min-height"
},
{
"answer_id": 74301901,
"author": "possum",
"author_id": 12050506,
"author_profile": "https://Stackoverflow.com/users/12050506",
"pm_score": 0,
"selected": false,
"text": "@media only screen and (max-width: 400px)\nand (min-width: 300px) and (max-height: 400px)\nand (min-height: 300px) {\n .this-is-a-test-class {\n background-color: hotpink;\n }\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18440788/"
] |
74,301,475 | <p>How to rewrite such code:</p>
<pre><code>Sub sierotkiTXT_zero()
'szukaj sierotek w tekście
Dim NumLines As Long
Selection.EndKey Unit:=wdStory, Extend:=wdExtend
NumLines = Selection.Range.ComputeStatistics(wdStatisticLines)
MsgBox "Lines to check " & (NumLines)
Selection.Collapse
For i = 1 To NumLines
Selection.EndKey Unit:=wdLine
Selection.MoveLeft Unit:=wdCharacter, Count:=3, Extend:=wdExtend
If Selection.Text Like "* [aAwWzZiIoOuUVQ] *" Or Selection.Text Like "*[A-Z]. *" _
Or Selection.Text Like "* [a-z]. *" Or Selection.Text Like "*z. *" Or Selection.Text Like "*:] *" Or Selection.Text Like "*([a-z] *" Then
Result = MsgBox("Akceptujesz?", vbYesNoCancel + vbQuestion)
If Result = vbYes Then
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.Delete
Selection.InsertAfter Text:=ChrW(8205) & " "
End If
If Result = vbCancel Then
Exit Sub
End If
End If
Selection.MoveRight Unit:=wdCharacter, Count:=3
Next
End Sub
</code></pre>
<p>So that it skips checking the text in the tables?
Unfortunately, my way counts each table cell as a line and adds it to the final loop counter.
Also, I don't want to check the text in the tables.</p>
<p>For now, I only know how to stop checking if I come across a table.</p>
<pre><code> If Selection.Information(wdWithInTable) = True Then
Exit Sub
End If
</code></pre>
<p>[EDIT1]
I can seemingly skip the table by adding:</p>
<pre><code> If Selection.Information(wdWithInTable) = True Then
Selection.EndKey Unit:=wdRow
Selection.EndKey Unit:=wdColumn
Selection.EndKey Unit:=wdRow
Selection.MoveRight Unit:=wdCharacter, Count:=10
</code></pre>
<p>But this is not a universal solution for every table and document (I manage to skip only a certain type of tables) and does not solve the loop counter problem.
The whole code needs a change.</p>
<p>[EDIT2]
I change script to:</p>
<pre><code>If Selection.Information(wdWithInTable) = True Then
Selection.EndKey unit:=wdRow
Selection.EndKey unit:=wdColumn
Selection.MoveDown unit:=wdLine, Count:=2
</code></pre>
<p>work ok on every table. (skip). The only problem is the end counter loop. Because I miscalculate the final number of loops (I skip the table, and count their cells as lines)</p>
<p>[EDIT3]
Change:</p>
<pre><code> Dim NumLines1 As Long
Dim NumLines2 As Long
Dim NumLines3 As Long
Dim mytable As Table
Selection.EndKey unit:=wdStory, Extend:=wdExtend
NumLines1 = Selection.Range.ComputeStatistics(wdStatisticLines)
Selection.Collapse
For Each mytable In ActiveDocument.Tables
mytable.Range.Editors.Add wdEditorEveryone
Next
ActiveDocument.SelectAllEditableRanges (wdEditorEveryone)
ActiveDocument.DeleteAllEditableRanges (wdEditorEveryone)
NumLines2 = Selection.Range.ComputeStatistics(wdStatisticLines)
Selection.Collapse
NumLines3 = NumLines1 - NumLines2
For i = 1 To NumLines3
</code></pre>
<p>I have something wrong here, because for 1 table it counts fine, with more tables it counts wrong.</p>
| [
{
"answer_id": 74303407,
"author": "Timothy Rylatt",
"author_id": 5211752,
"author_profile": "https://Stackoverflow.com/users/5211752",
"pm_score": 1,
"selected": false,
"text": "For i = 1 To NumLines\n Selection.EndKey Unit:=wdLine\n If Not Selection.Information(wdWithInTable) Then\n 'do your processing here\n End If\n Selection.MoveRight Unit:=wdCharacter, Count:=3 \nNext\n"
},
{
"answer_id": 74309137,
"author": "Piotr B",
"author_id": 20342355,
"author_profile": "https://Stackoverflow.com/users/20342355",
"pm_score": 0,
"selected": false,
"text": " Sub sierotkiTXT_zero()\n 'szukaj sierotek w przypisach\n Dim j As Integer\n Dim t As Table\n\n Selection.EndKey unit:=wdStory, Extend:=wdExtend\n\n j = Selection.Range.ComputeStatistics(wdStatisticLines)\n For Each t In Selection.Range.Tables\n j = j - t.Range.ComputeStatistics(wdStatisticLines)\n Next\n Selection.Collapse\nMsgBox \"Lines to check \" & (j) \n For i = 1 To j\n \n If Selection.Information(wdWithInTable) = True Then\n Selection.EndKey unit:=wdRow\n Selection.EndKey unit:=wdColumn\n Selection.MoveDown unit:=wdLine, Count:=2\n \n End If\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20342355/"
] |
74,301,487 | <p>I'm trying to fetch JSON data using okhttp3, but I'm getting and error in this code as e: Unresolved reference: url.</p>
<pre><code>private fun fetchJson() {
println("Attempting to fetch JSON")
val url = "https://lordvarun.github.io/back/data.json"
val request = Request.Builder.url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: Response) {
val body = response.body?.string()
println(body)
val gson = GsonBuilder().create()
val homeFeed = gson.fromJson<>(body, HomeFeed::class.java)
}
override fun onFailure(call: Call, e: IOException) {
println("Failed to execute request")
}
})
}
</code></pre>
<p>I rechecked all the dependeicies and imports. Why is url of all things an unresolved reference?</p>
| [
{
"answer_id": 74301590,
"author": "z.y",
"author_id": 19023745,
"author_profile": "https://Stackoverflow.com/users/19023745",
"pm_score": 1,
"selected": false,
"text": "Builder"
},
{
"answer_id": 74301602,
"author": "Mochamad Taufik Hidayat",
"author_id": 4168314,
"author_profile": "https://Stackoverflow.com/users/4168314",
"pm_score": 3,
"selected": true,
"text": "val request = Request.Builder.url(url).build()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17090545/"
] |
74,301,497 | <p>Consider the following <code>DataFrames</code> <code>df</code> :</p>
<pre><code>df =
kind A B
names u1 u2 u3 y1 y2
Time
0.0 0.5083 0.1007 0.8001 0.7373 0.1387
0.1 0.6748 0.0354 0.0076 0.8421 0.2670
0.2 0.1753 0.1013 0.5231 0.8060 0.0040
0.3 0.5953 0.6505 0.7127 0.0771 0.1023
0.4 0.4409 0.0193 0.6765 0.9800 0.0715
</code></pre>
<p>and <code>df1</code>:</p>
<pre><code>df1 =
kind A
names potato
Time
0.0 0.4043
0.1 0.9801
0.2 0.1298
0.3 0.9564
0.4 0.4409
</code></pre>
<p>I want to concatenate the two <code>DataFrames</code> such that the resulting <code>DataFrame</code> is:</p>
<pre><code>df2 =
kind A B
names u1 u2 u3 potato y1 y2
Time
0.0 0.5083 0.1007 0.8001 0.5083 0.7373 0.1387
0.1 0.6748 0.0354 0.0076 0.6748 0.8421 0.2670
0.2 0.1753 0.1013 0.5231 0.1753 0.8060 0.0040
0.3 0.5953 0.6505 0.7127 0.5953 0.0771 0.1023
0.4 0.4409 0.0193 0.6765 0.4409 0.9800 0.0715
</code></pre>
<p>What I run is <code>pandas.concat([df1, df2, axis=1).sort_index(level="kind", axis=1)</code> but that results in</p>
<pre><code>kind A B
names potato u1 u2 u3 y1 y2
Time
0.0 0.4043 0.5083 0.1007 0.8001 0.7373 0.1387
0.1 0.9801 0.6748 0.0354 0.0076 0.8421 0.2670
0.2 0.1298 0.1753 0.1013 0.5231 0.8060 0.0040
0.3 0.9564 0.5953 0.6505 0.7127 0.0771 0.1023
0.4 0.4409 0.4409 0.0193 0.6765 0.9800 0.0715
</code></pre>
<p>i.e. the column <code>potato</code> is appended at the beginning of <code>df["A"]</code> whereas I want it appended to the end.</p>
| [
{
"answer_id": 74301560,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "sort_remaining=False"
},
{
"answer_id": 74302110,
"author": "Leonardo ",
"author_id": 11509190,
"author_profile": "https://Stackoverflow.com/users/11509190",
"pm_score": 1,
"selected": false,
"text": "df.insert"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2562058/"
] |
74,301,529 | <p>For example, let's consider the following numpy array:</p>
<pre class="lang-py prettyprint-override"><code>[1, 5, 0, 5, 4, 6, 1, -1, 5, 10]
</code></pre>
<p>Also, let's suppose that the threshold is equal to <code>3</code>.
That is to say that we are looking for sequences of <strong>at least two consecutive</strong> values that are all above the threshold.</p>
<p>The output would be the <strong>indices</strong> of those values, which in our case is:</p>
<pre class="lang-py prettyprint-override"><code>[[3, 4, 5], [8, 9]]
</code></pre>
<p>If the output array was flattened that would work as well!</p>
<pre class="lang-py prettyprint-override"><code>[3, 4, 5, 8, 9]
</code></pre>
<hr>
<h3>Output Explanation</h3>
<p>In our initial array we can see that for <code>index = 1</code> we have the value <code>5</code>, which is greater than the threshold, but is not part of a sequence (of at least two values) where every value is greater than the threshold. That's why this index would <strong>not</strong> make it to our output.</p>
<p>On the other hand, for indices <code>[3, 4, 5]</code> we have a sequence of (at least two) neighboring values <code>[5, 4, 6]</code> where each and every of them are above the threshold and that's the reason that their indices are included in the final output!</p>
<hr>
<h3>My Code so far</h3>
<p>I have approached the issue with something like this:</p>
<pre class="lang-py prettyprint-override"><code>(arr > 3).nonzero()
</code></pre>
<p>The above command gathers the indices of all the items that are above the threshold. However, I cannot determine if they are consecutive or not. I have thought of trying a <code>diff</code> on the outcome of the above snippet and then may be locating ones (that is to say that indices are one after the other). Which would give us:</p>
<pre class="lang-py prettyprint-override"><code>np.diff((arr > 3).nonzero())
</code></pre>
<p>But I'd still be missing something here.</p>
| [
{
"answer_id": 74302095,
"author": "Abhi",
"author_id": 7430727,
"author_profile": "https://Stackoverflow.com/users/7430727",
"pm_score": 0,
"selected": false,
"text": "O(n)"
},
{
"answer_id": 74302198,
"author": "paime",
"author_id": 13636407,
"author_profile": "https://Stackoverflow.com/users/13636407",
"pm_score": 3,
"selected": true,
"text": "1"
},
{
"answer_id": 74302281,
"author": "Alex P",
"author_id": 11554968,
"author_profile": "https://Stackoverflow.com/users/11554968",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\n\narr = np.array([1, 5, 0, 5, 4, 6, 1, -1, 5, 10])\n\narr_padded = np.concatenate(([0], arr, [0]))\na = np.where(arr_padded > 3, 1, 0)\n\nda = np.diff(a)\n\nidx_start = (da == 1).nonzero()[0]\nidx_stop = (da == -1).nonzero()[0]\n\nvalid = (idx_stop - idx_start >= 2).nonzero()[0]\n\nresult = [list(range(idx_start[i], idx_stop[i])) for i in valid]\nprint(result)\n"
},
{
"answer_id": 74302338,
"author": "SirLoort",
"author_id": 20406619,
"author_profile": "https://Stackoverflow.com/users/20406619",
"pm_score": 0,
"selected": false,
"text": "values = [1, 5, 0, 5, 4, 6, 1, -1, 5, 10]\nres=[]\nthreshold= 3\n\ni=0\nj=0\nfor _ in values:\n j=i+1\n lista=[]\n try:\n print(f\"i: {i} j:{j}\")\n # check if condition is met\n if(values[i] > threshold and values[j] > threshold):\n lista.append(i)\n # add sequence \n while values[j] > threshold:\n lista.append(j)\n print(f\"j while: {j}\")\n j+=1\n if(j>=len(values)):\n break\n res.append(lista)\n \n i=j\n if(j>=len(values)): \n break\n except:\n print(\"ex\")\n"
},
{
"answer_id": 74302482,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 1,
"selected": false,
"text": "diff2"
},
{
"answer_id": 74302723,
"author": "Khaled DELLAL",
"author_id": 15852600,
"author_profile": "https://Stackoverflow.com/users/15852600",
"pm_score": 0,
"selected": false,
"text": "# Simple is better than complex\n# Complex is better than complicated\n\narr = [1, 5, 0, 5, 4, 6, 1, -1, 5, 10]\n\narr_3=[i if arr[i]>3 else 'a' for i in range(len(arr))]\n\narr_4=''.join(str(x) for x in arr_3)\n\ni=0\n\nwhile i<len(arr_5):\n if len(arr_5[i]) <=1:\n del arr_5[i]\n else:\n i+=1\n \narr_6=[list(map(lambda x: int(x), list(x))) for x in arr_5]\n\nprint(arr_6)\n"
},
{
"answer_id": 74303113,
"author": "Nathan Furnal",
"author_id": 9479128,
"author_profile": "https://Stackoverflow.com/users/9479128",
"pm_score": 1,
"selected": false,
"text": "import numpy as np\nfrom numpy.lib.stride_tricks import sliding_window_view as window\n\n\ndef consec_thresh(arr, thresh):\n win = window(np.argwhere(arr > thresh), (2, 1))\n return np.unique(win[np.diff(win, axis=2).ravel() == 1, :,:].ravel())\n"
},
{
"answer_id": 74327927,
"author": "ttsak",
"author_id": 14594208,
"author_profile": "https://Stackoverflow.com/users/14594208",
"pm_score": 0,
"selected": false,
"text": "Series"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14594208/"
] |
74,301,532 | <p>In my <code>useEffect</code> I try to get a user id token and when I have this token, I <code>fetch</code> data from my server with the token as <code>authorization</code> <code>header</code>.
With the data I fill some <code>highcharts</code> options and render a chart.</p>
<p>The problem is that I'm not able to access the <code>[[PromiseResult]]</code>, it returns the complete <code>Promise</code>.</p>
<p>I use <code>firebase</code> as a user database and wrap the user authentification in a <code>context</code>.</p>
<p>Edit: id I use <code>.then()</code> I would have to repeat a bunch of my code twice as my <code>header</code> constant depends on the outcome and the fetching of data depends on the <code>header</code> like so:</p>
<pre><code>if(currentUser) {
await currentUser.getIdToken(/* forceRefresh */ true).then(
// ... defining the header with idToken
// ... continue with the rest
)
} else {
// ... defining the header as "unauthorized"
// ... continue with the rest
}
</code></pre>
<p>So what would be the solution for it?</p>
<p>Here is my complete component:</p>
<pre><code>import React, {useState, useEffect } from "react";
import Highcharts from "highcharts/highstock";
import HighchartsReact from "highcharts-react-official";
import { useAuth } from "../../../contexts/AuthContext"
import ChartLoadingScreen from '../ChartLoadingScreen'
export default function MyChart(){
const [isMounted, setMounted] = useState(false)
const [options, setOptions] = useState(HighchartsTheme)
const { currentUser } = useAuth();
const HighchartsTheme = {
title: {
text: undefined,
},
series: [ ],
accessibility: {
enabled: false
},
yAxis: [{
opposite: true,
type: 'linear',
labels: {
align:'right',
},
},
{
opposite: false,
type: 'logarithmic',
}]
};
useEffect(() => {
const getIdToken = async () => {
const idToken = await currentUser.getIdToken(/* forceRefresh */ true);
return(idToken);
}
setMounted(false);
console.log(currentUser)
const idToken = currentUser ? getIdToken() : "unauthorized";
console.log(idToken)
let headers = new Headers();
headers.append('authorization', idToken);
Promise.all([
fetch("https://my-server-side/data1"),
fetch("https://my-server-side/data2", { headers: headers })
]).then(responses =>
Promise.all(responses.map(response => response.json()))
).then(data => {
console.log(data);
setSeriesData(data[1]);
options.series = [{ data: data[0], yAxis: 1}];
options.series.push({ data: data[1], yAxis: 0})
updateChart();
setMounted(true);
}
).catch(err =>
console.log(err)
);
return () => {
setMounted(false);
setOptions({});
};
}, [chartDataEndpoint]);
const updateChart = () => {
setOptions(prevState => ({ ...prevState}));
};
return (
<>
{isMounted ?
<>
<div>
<HighchartsReact
highcharts={Highcharts}
constructorType={"stockChart"}
options={options}
/>
</div>
</>
:
<ChartLoadingScreen isDefault={true}/>
}
</>
);
}
</code></pre>
| [
{
"answer_id": 74302088,
"author": "Keith",
"author_id": 6870228,
"author_profile": "https://Stackoverflow.com/users/6870228",
"pm_score": 3,
"selected": true,
"text": "useEffect"
},
{
"answer_id": 74302251,
"author": "mndcdk",
"author_id": 20406811,
"author_profile": "https://Stackoverflow.com/users/20406811",
"pm_score": 0,
"selected": false,
"text": " useEffect(async() => {\n let x = await fetch(URL);\n x = await x.json();\n setData(x);}, []);\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3352254/"
] |
74,301,583 | <p>I have a list in python, which contains alphanumeric elements. I would like to convert all elements to lowercase.</p>
<p>Is it the only way to create a Dataframe using the list and use the <code>lower</code> function?</p>
<p>Here is the example:</p>
<pre class="lang-py prettyprint-override"><code>l = ['abc123']
l.lower()
</code></pre>
<p>Error:</p>
<pre class="lang-none prettyprint-override"><code>AttributeError: 'list' object has not attribute 'lower'
</code></pre>
| [
{
"answer_id": 74301837,
"author": "Lochyj",
"author_id": 16113187,
"author_profile": "https://Stackoverflow.com/users/16113187",
"pm_score": 0,
"selected": false,
"text": "l = ['abc123']\nlower = []\nfor i in l:\n lower.append(i.lower())\n"
},
{
"answer_id": 74302054,
"author": "VdGR",
"author_id": 13473392,
"author_profile": "https://Stackoverflow.com/users/13473392",
"pm_score": -1,
"selected": false,
"text": "l = [char.lower() for char in l ]\nprint(l)\n"
},
{
"answer_id": 74302081,
"author": "Александр Слабкин",
"author_id": 12273990,
"author_profile": "https://Stackoverflow.com/users/12273990",
"pm_score": 0,
"selected": false,
"text": "L = ['ABS123']\nl = [i.lower() for i in L]\n"
},
{
"answer_id": 74302342,
"author": "Filip Hanes",
"author_id": 7948776,
"author_profile": "https://Stackoverflow.com/users/7948776",
"pm_score": 1,
"selected": false,
"text": ".lower()"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6187792/"
] |
74,301,587 | <pre><code>Products::whereIn('category_id', ['223', '15', '20'])
->where('active', 1)
->get();
</code></pre>
<p>How can I fix this example so that it finds the exact occurrence of <code>category_id = 223</code> and <code>15</code> and <code>20</code> and also necessarily <code>active = 1</code>?</p>
| [
{
"answer_id": 74301671,
"author": "matiaslauriti",
"author_id": 1998801,
"author_profile": "https://Stackoverflow.com/users/1998801",
"pm_score": 0,
"selected": false,
"text": "category_id = 15, 20 and 223"
},
{
"answer_id": 74302367,
"author": "Ramil Huseynov",
"author_id": 6711823,
"author_profile": "https://Stackoverflow.com/users/6711823",
"pm_score": -1,
"selected": false,
"text": "OR"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19845684/"
] |
74,301,607 | <p>This site and the internet are filled with answers to 'how to capitalize every word' but that isn't what I want to do. I couldn't find any answers anywhere to this question. Though it does seem like something that should have been answered well.</p>
<p>Using the previous three sentences as an example, say I had written them as:</p>
<blockquote>
<p><strong>this</strong> site and the internet are filled with answers to 'how to
capitalize every word' but that isn't what I want to do. <strong>and</strong> I couldn't
find any answers anywhere to this question. <strong>though</strong> it does seem like
something that should have been answered well.</p>
</blockquote>
<p>I'd like a JS function that will capitalize the three bolded words. Taking into account sentences can end after: '.' '?' or '!'.</p>
<p>I'm using Vue for this project so something that uses Vue would be great but Vanilla JS would be fine as well.</p>
| [
{
"answer_id": 74301816,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 0,
"selected": false,
"text": "regex"
},
{
"answer_id": 74301823,
"author": "Estus Flask",
"author_id": 3731501,
"author_profile": "https://Stackoverflow.com/users/3731501",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74302043,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 1,
"selected": false,
"text": "replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13493837/"
] |
74,301,621 | <pre><code>var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/mydb'
MongoClient.connect(url, function(err,db) {
if (err) {
console.log("err")
} else {
console.log("Database Connected")
}
})
</code></pre>
<p>.connect is striked off in VS Code</p>
<p>err is displayed in the VS Code terminal</p>
<p>Node.js node-v18.12.0-x64
Mongodb version 4.2
windows 8.1 Pro</p>
| [
{
"answer_id": 74301816,
"author": "Maniraj Murugan",
"author_id": 7785337,
"author_profile": "https://Stackoverflow.com/users/7785337",
"pm_score": 0,
"selected": false,
"text": "regex"
},
{
"answer_id": 74301823,
"author": "Estus Flask",
"author_id": 3731501,
"author_profile": "https://Stackoverflow.com/users/3731501",
"pm_score": 3,
"selected": true,
"text": "split"
},
{
"answer_id": 74302043,
"author": "Peter Seliger",
"author_id": 2627243,
"author_profile": "https://Stackoverflow.com/users/2627243",
"pm_score": 1,
"selected": false,
"text": "replace"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19645769/"
] |
74,301,652 | <p>I'm trying to remove the first 0 from the third column in my CSV file</p>
<p>tel.csv -</p>
<pre><code> test,01test,01234567890
test,01test,09876054321
</code></pre>
<p>I have been trying to use the following with no luck -</p>
<pre><code>cat tel.csv | sed 's/^0*//'
</code></pre>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18485470/"
] |
74,301,657 | <p>I'm looking for any ways to restrict the props' value of child elements by the type of parent element's props in React with typescript.</p>
<pre><code>type User = { name: string; age: number; };
const Parent = (props: User) => {
return (
<div>
<Child field="name" /> // ok
<Child field="age" /> // ok
<Child field="firstName" /> // not ok
</div>
);
};
</code></pre>
<p>I am look for something like above</p>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406554/"
] |
74,301,673 | <p>we have two snowflakes environments with different user login, one is for Development and one is for Testing. both are having same schemas and tables. i want to compare COUNT of all tables from both DEV and TEST. please help with the viable options!!</p>
<p>I could list the COUNT from one environment by referring information_schema.tables. But need help on connect both environment and list the COUNT ...Like DBlink in Oracle</p>
<p>select TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,TABLE_TYPE,ROW_COUNT,CREATED,LAST_ALTERED from information_schema.tables;</p>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20250071/"
] |
74,301,675 | <p>I am using <code>context()</code> in my <code>GlanceAppWidget()</code> for tasks like retrieving glanceId and updating app widget state. I am having issue with how I inject the <code>context</code> object.</p>
<p>I would like to use the dagger/hilt framework to inject the context into my <code>GlanceAppWidget()</code> constructor. See <code>MyWidget()</code> below.</p>
<p>However by injecting the context into <code>MyWidget</code>, I then need to pass the context as constructor parameter in <code>MyWidgetReceiver()</code> for <code>val glanceAppWidget</code>. Broadcast receivers are not meant to have constructor arguments so this gives me an Instantiation Exception.</p>
<p>How can I inject context into my GlanceAppWidget? Any help will be much appreciated.</p>
<p>Note: I have also tried using default arguments in <code>MyWidget()</code> to avoid providing context in MyWidgetReceiver but this throws <a href="https://stackoverflow.com/a/55240752/15597975">"Type may only contain one injected constructor"</a>.</p>
<pre><code>@Singleton
class MyWidget @Inject constructor(
@ApplicationContext val context: Context
) : GlanceAppWidget()
</code></pre>
<pre><code>@AndroidEntryPoint
@Singleton
class MyWidgetReceiver @Inject constructor(
@ApplicationContext val context: Context /*<-java.lang.InstantiationException when trying to inject into BroadcastReceiver*/
) : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget
get() = MyWidget(context)
}
</code></pre>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15597975/"
] |
74,301,677 | <p>We are given a CSV file containing names and birthdays, we have to output who's birthday is next in function.</p>
<p>kept getting a local unbound error, not sure how to fix it, basically trying to read the file, check the dates, find which date is next, then return the name connected with that date</p>
<pre><code>birthdates.csv:
Draven Brock,01/21/1952
Easton Mclean,09/02/1954
Destiny Pacheco,10/10/1958
Ariella Wood,12/20/1961
Keely Sanders,08/03/1985
Bryan Sloan,04/06/1986
Shannon Brewer,05/11/1986
Julianne Farrell,01/29/2000
Makhi Weeks,03/20/2000
Lucian Fields,08/02/2010
Function Call:
nextBirthdate("birthdates.csv", "01/01/2022")
Output:
Draven Brock
</code></pre>
<pre><code>def nextBirthdate(filename, date):
f = open(filename, 'r')
lines = f.readlines()
f.close()
for i in range(len(lines)):
lines[i] = lines[i].strip()
# split for the target date
date = line.split('/')
month = date[0]
day = date[1]
diff = 365
diffDays = 0
bName = None
bDays = []
for line in lines:
items = line.split(",")
names = items[0]
# split the date apart between month, day, and year
bDay = items[1].split("/")
bDays.append(bDay)
for d in bDays:
if bDay[0] == month:
if bDay[1] > day:
diffDays = int(bDay[0]) - int(day)
if diffdays < diff:
diff = diffDays
bName = name
elif bDay[0] > month:
diffDays = ((int(bDay[0]) - 1) * 31) + int(day)
if diffDays < diff:
diff = diffDays
bName = name
if bName == None:
return nextBirthdate(filename, "01/01/2022")
return bName
if __name__ == "__main__":
filename = "birthdates.csv"
date = "12/31/2022"
print(nextBirthdate(filename, date))
</code></pre>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20118471/"
] |
74,301,679 | <p>I have this dataset (let's imagine it with 900 variables ) and the list l2 as follows :</p>
<pre><code>df = data.frame(x = c(1,0,0,0,1,1,1), y = c(2,2,2,2,3,3,2) )
l1 = lapply(df,table)
l2 = lapply(l1,as.data.frame)
</code></pre>
<p>I wish to add a percentage column to each of these dataframes based on the <code>Freq</code> column of each dataframe. Appreciate the help.</p>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19720935/"
] |
74,301,708 | <p>I have the following data frame in R out of which I'd like to create a new column containing the Nut for each municipal (See second table). "Nut" refers simply to a higher hirachy level of municipalities in portugal. For later analysis I need to group the data by Nuts. The entire dataframe consists of 308 municipalities and 25 Nuts.</p>
<p>Does someone have a suggestion on how to approach this task? Since the number of municipals in each Nut differes I have difficulties on where to begin.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>geo-group</th>
<th>nuts_municipal</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nut III</td>
<td>Alto Minho</td>
</tr>
<tr>
<td>Municipal</td>
<td>Arcos de Valdevez</td>
</tr>
<tr>
<td>Municipal</td>
<td>Caminha</td>
</tr>
<tr>
<td>Municipal</td>
<td>Monção</td>
</tr>
<tr>
<td>Municipal</td>
<td>Ponte da Barca</td>
</tr>
<tr>
<td>Nuts III</td>
<td>Ponte da Barca</td>
</tr>
<tr>
<td>Municipal</td>
<td>Amares</td>
</tr>
<tr>
<td>Municipal</td>
<td>Barcelos</td>
</tr>
<tr>
<td>Municipal</td>
<td>Braga</td>
</tr>
<tr>
<td>Nuts III</td>
<td>Fafe</td>
</tr>
<tr>
<td>Municipal</td>
<td>Ave</td>
</tr>
</tbody>
</table>
</div>
<p>This is what I'd like to have as a final result.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>geo-group</th>
<th>nuts_municipal</th>
<th>Nut</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nut III</td>
<td>Alto Minho</td>
<td></td>
</tr>
<tr>
<td>Municipal</td>
<td>Arcos de Valdevez</td>
<td>Alto Minho</td>
</tr>
<tr>
<td>Municipal</td>
<td>Caminha</td>
<td>Alto Minho</td>
</tr>
<tr>
<td>Municipal</td>
<td>Monção</td>
<td>Alto Minho</td>
</tr>
<tr>
<td>Municipal</td>
<td>Ponte da Barca</td>
<td>Alto Minho</td>
</tr>
<tr>
<td>Nut III</td>
<td>Cávado</td>
<td></td>
</tr>
<tr>
<td>Municipal</td>
<td>Amares</td>
<td>Cávado</td>
</tr>
<tr>
<td>Municipal</td>
<td>Barcelos</td>
<td>Cávado</td>
</tr>
<tr>
<td>Municipal</td>
<td>Braga</td>
<td>Cávado</td>
</tr>
<tr>
<td>Nut III</td>
<td>Ave</td>
<td></td>
</tr>
<tr>
<td>Municipal</td>
<td>Fafe</td>
<td>Ave</td>
</tr>
<tr>
<td>Municipal</td>
<td>Mondim de Basto</td>
<td>Ave</td>
</tr>
</tbody>
</table>
</div>
<p>I have difficulties on where to begin and so far haven't found any appreach.</p>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20279856/"
] |
74,301,712 | <p>Im trying to create an impersonate operation within my user controller, I have been following this guide..</p>
<p><a href="https://backpackforlaravel.com/articles/tutorials/how-to-add-impersonate-functionality-to-your-admin-panel" rel="nofollow noreferrer">impersonate for backpack</a></p>
<p>The setupImpersonateDefaults function gets called ok but i get a 404 error, after some testing i figured out the setupImpersonateRoutes is not getting triggered</p>
<p>Any ideas on why?</p>
<blockquote>
</blockquote>
<pre><code><?php
namespace App\Http\Controllers\Admin\Operations;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use Illuminate\Support\Facades\Route;
use Session;
use Alert;
trait ImpersonateOperation
{
/**
* Define which routes are needed for this operation.
*
* @param string $segment Name of the current entity (singular). Used as first URL segment.
* @param string $routeName Prefix of the route name.
* @param string $controller Name of the current CrudController.
*/
protected function setupImpersonateRoutes($segment, $routeName, $controller)
{
Route::get($segment.'/{id}/impersonate', [
'as' => $routeName.'.impersonate',
'uses' => $controller.'@impersonate',
'operation' => 'impersonate',
]);
}
/**
* Add the default settings, buttons, etc that this operation needs.
*/
protected function setupImpersonateDefaults()
{
CRUD::allowAccess('impersonate');
CRUD::operation('impersonate', function () {
CRUD::loadDefaultOperationSettingsFromConfig();
});
CRUD::operation('list', function () {
// CRUD::addButton('top', 'impersonate', 'view', 'crud::buttons.impersonate');
CRUD::addButton('line', 'impersonate', 'view', 'crud::buttons.impersonate');
});
}
/**
* Show the view for performing the operation.
*
* @return Response
*/
public function impersonate()
{
CRUD::hasAccessOrFail('impersonate');
// prepare the fields you need to show
$this->data['crud'] = $this->crud;
$this->data['title'] = CRUD::getTitle() ?? 'Impersonate '.$this->crud->entity_name;
$entry = $this->crud->getCurrentEntry();
backpack_user()->setImpersonating($entry->id);
Alert::success('Impersonating '.$entry->name.' (id '.$entry->id.').')->flash();
// load the view
return redirect('dashboard');
// load the view
//return view('crud::operations.impersonate', $this->data);
}
}
</code></pre>
<p>Have tried following the guides and the routes are not getting added.</p>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20318498/"
] |
74,301,733 | <p>`I got this response from the api call and I need to extract specific values from the response. Also, I want to use it as a pre request script in another api call.</p>
<ol>
<li>How can I extract values of the ids from the Json object?
2)Is it possible to extract particular value of the id key where key from equals "rahul.sharma@gmail.com"?</li>
</ol>
<pre><code>{
"content": [
{
"id": "e7ab9f7d-c9f4-47e3-8d53-6febcfb914",
"from": "raulsdirect@gmail.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-2c2965dc5ca34@mailslurp.mx"
],
"subject": "id and sid",
"inboxId": "af09331a-d681-48c4-9075-2c2965dc34221",
"bcc": [],
"cc": [],
"createdAt": "2022-11-01T15:43:02.357Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\">id 23543253534<div>sid 34645656452342342343424</div></div>\r\n",
"teamAccess": true,
"bodyMD5Hash": "F2956A8791EB5E6F6F6E259C112BB13B"
},
{
"id": "8d547247-32d2-4553-b1fe-33b4ca00221d2",
"from": "rahul.sharma@adtraction.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-243d965dc5ba8@mailslurp.mx"
],
"subject": "Re: saas",
"inboxId": "af09331a-d681-48c4-9075-2c263f2dc5ba8",
"bcc": [],
"cc": [],
"createdAt": "2022-11-01T22:20:23.301Z",
"read": true,
"bodyExcerpt": "<div dir=\"auto\"><div dir=\"auto\"></div><p style=\"font-size:12.8px\">sid 325sd-df435-3fdgvd435-gdfv43</",
"teamAccess": true,
"bodyMD5Hash": "948B78E301880858EB66ABDE6698450B"
},
{
"id": "446760be-e261-441a-bffe-fa31aa935239",
"from": "rahul.sharma@gmail.com",
"domainId": null,
"attachments": [],
"to": [
"10ea0b7b-b5eb-4c0f-908d-39437f2214a71@mailslurp.com"
],
"subject": "Complete your registration",
"inboxId": "10ea0b7b-b5eb-4c0f-908d-394354324a71",
"bcc": [],
"cc": [],
"createdAt": "2022-11-02T07:41:41.685Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\"><span style=\"color:unset;font:unset;font-feature-settings:unset;font-kerning:unset;fo",
"teamAccess": true,
"bodyMD5Hash": "3A7619478AB69B1F63C99B9716896B1B"
},
{
"id": "79a2c183-5b72-4bc1-98aa-63bf5d52c2e6",
"from": "raulsdirect@gmail.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-2532165dc5ba8@mailslurp.mx"
],
"subject": "Re: id and sid",
"inboxId": "af09331a-d681-48c4-9075-2c2965dbdf5328",
"bcc": [],
"cc": [],
"createdAt": "2022-11-02T19:20:44.655Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\"><span style=\"color:unset;font:unset;font-feature-settings:unset;font-kerning:unset;fo",
"teamAccess": true,
"bodyMD5Hash": "1ED8849F70CBCBBA6CF3CFEA0ACA66C4"
}
],
"pageable": {
"sort": {
"empty": false,
"sorted": true,
"unsorted": false
},
"offset": 0,
"pageNumber": 0,
"pageSize": 20,
"paged": true,
"unpaged": false
},
"last": true,
"totalElements": 4,
"totalPages": 1,
"size": 20,
"number": 0,
"sort": {
"empty": false,
"sorted": true,
"unsorted": false
},
"first": true,
"numberOfElements": 4,
"empty": false
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406510/"
] |
74,301,743 | <p>I have the following live table</p>
<p><a href="https://i.stack.imgur.com/1Apvn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Apvn.png" alt="enter image description here" /></a></p>
<p>And i'm looking to write that into a stream to be written back into my kafka source.</p>
<p>I've seen in the apache spark docs that I can use writeStream ( I've used readStream to get it out of my kafka stream already ). But how do I transform the table into the medium it needs so it can use this?</p>
<p>I'm fairly new to both kafka and the data world so any further explanation's are welcome here.</p>
<pre><code>writeStream
.format("kafka")
.option("kafka.bootstrap.servers", "host1:port1,host2:port2")
.option("topic", "updates")
.start()
</code></pre>
<p>Thanks in Advance,</p>
<p>Ben</p>
<p>I've seen in the apache spark docs that I can use writeStream ( I've used readStream to get it out of my kafka stream already ). But how do I transform the table into the medium it needs so it can use this?I'm fairly new to both kafka and the data world so any further explanation's are welcome here.</p>
<pre><code>writeStream
.format("kafka")
.option("kafka.bootstrap.servers", "host1:port1,host2:port2")
.option("topic", "updates")
.start()
</code></pre>
| [
{
"answer_id": 74301776,
"author": "Jetchisel",
"author_id": 4452265,
"author_profile": "https://Stackoverflow.com/users/4452265",
"pm_score": 2,
"selected": true,
"text": "sed 's/^\\([^,]*\\),\\([^,]*\\),0\\(.*\\)$/\\1,\\2,\\3/' file.csv\n"
},
{
"answer_id": 74305035,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "0-9"
},
{
"answer_id": 74305250,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "sed 's/,0\\([^,]*\\)$/,\\1/' file\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406665/"
] |
74,301,768 | <p>Im looping over two lists and want to add the objects to a custom object. So Im getting an <code>Employee</code> a list of <code>Projects</code> and a list of <code>Doubles</code> from Thymeleaf and save them to a database. I want to save them to the object <code>EmployeeProject</code> which takes an Employee, a Project and a double (employeeBookedMonths). My problem is I either get the multiple projects saved to the EmployeeProject but all the project months are the same (the last double value one in the list) or I save the multiple projects to the employeeProject with correct employeeBookedMonths but there is dupicates, for example if I save 3 projects with 3 employeeBookedMonths, I get 3 times each saved (so 9 saved). I've tried moving the <code>employeeProjectService.saveEmployeeProject</code> but can't make it work plus many other variations but I need some help.</p>
<p>Question: how can I loop through the 2 lists and add and them to the EmployeeProject object? Without getting multiples or only getting the last employeeBookedMonths.</p>
<p>Thanks in advance.</p>
<p>Also the <code>System.println</code> prints the wanted values, they just don't save.</p>
<pre><code> public String saveEmployee(@ModelAttribute("employee") Employee employee,
@RequestParam("projectId") List<Project> projectIds,
@RequestParam("employeeProjectMonths") List<Double> months) {
List<Double> monthList = new ArrayList<>();
for (Double month : months) {
if (month != null) {
monthList.add(month);
System.out.println("Month:" + month);
}
}
employeeService.saveEmployee(employee);
if (projectIds != null) {
EmployeeProject employeeProject = new EmployeeProject(employee);
for (Project ids : projectIds) {
for (Double month : monthList) {
employeeProject.setEmployeeBookedMonths(month);
System.out.println("Months: " + employeeProject.getEmployeeBookedMonths());
employeeProjectService.saveEmployeeProject(employee, ids, month);
}
}
}
return "redirect:/ines/employees";
}
</code></pre>
<p>New Employee form</p>
<pre><code><form action="#" th:action="@{/ines/saveEmployeeMeeting}" th:object="${employee}"
method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Email:</label>
<input type="text" th:field="*{name}"
placeholder="Employee Name" class="form-control mb-4 col-4">
</div>
<th:block th:object="${meetingInfo}">
<div class="form-group">
<label>Start Time:</label>
<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input"
th:field="*{meetingStartDateTime}" id="meetingStartDateTime"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>End Time:</label>
<div class="input-group date" id="datetimepicker2" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1"
th:field="*{meetingEndDateTime}" id="meetingEndDateTime" placeholder="Date"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<input type="text" th:field="*{message}"
placeholder="Message" class="form-control mb-4 col-4">
</div>
</th:block>
<button type="submit" class="btn btn-info col-2">Save Employee/Meeting</button>
</form>
</code></pre>
<p>Employee</p>
<pre><code>@Entity
@Table(name = "employees")
public class Employee {
@Id
@Column(name = "employee_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
@Column(name = "contracted_from")
private String contractedFrom;
@JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
@Column(name = "contracted_to")
private String contractedTo;
@OneToMany(mappedBy = "employee",
cascade = CascadeType.ALL
// fetch=FetchType.EAGER
)
private Set<EmployeeProject> employeeProjects = new HashSet<>();
// constructores getters and setters
</code></pre>
<p>Project</p>
<pre><code>@Entity
@Table(name = "projects")
public class Project implements Serializable {
@Id
@Column(name = "project_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long projectNumber;
@Column(nullable = false, length = 45)
private String name;
@JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
@Column(name = "start_date", nullable = false)
private String startDate;
@JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
@Column(name = "end_date", nullable = false)
private String endDate;
@Column(name = "project_length_months")
private double projectLengthInMonths;
@Column(name = "project_booked_months")
private double currentBookedMonths;
@Column(name = "remaining_booked_months")
private double remainingBookedMonths;
private int numberOfEmployees;
@OneToMany(mappedBy = "project", cascade = CascadeType.ALL)
private Set<EmployeeProject> employeeProjects = new HashSet<>();
// constructores getters and setters
</code></pre>
<p>EmployeeProject</p>
<pre><code>@Entity
@Table(name = "employee_projects")
public class EmployeeProject implements Serializable {
@Id
@Column(name = "employee_project_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "employee_id")
private Employee employee;
@ManyToOne
@JoinColumn(name = "project_id")
private Project project;
@Column(name = "employee_booked_months")
private double employeeBookedMonths;
// constructores getters and setters
</code></pre>
| [
{
"answer_id": 74311230,
"author": "Lucas Favaro Borsatto",
"author_id": 12369894,
"author_profile": "https://Stackoverflow.com/users/12369894",
"pm_score": 0,
"selected": false,
"text": "employeeProjectService.saveEmployeeProject(employee, ids, month);\n"
},
{
"answer_id": 74324661,
"author": "Lucas Favaro Borsatto",
"author_id": 12369894,
"author_profile": "https://Stackoverflow.com/users/12369894",
"pm_score": 0,
"selected": false,
"text": " EmployeeProject employeeProject = new EmployeeProject(employee);"
},
{
"answer_id": 74374561,
"author": "Kayd Anderson",
"author_id": 19263679,
"author_profile": "https://Stackoverflow.com/users/19263679",
"pm_score": 2,
"selected": true,
"text": "@PostMapping(\"/saveEmployee\")\n public String saveEmployee(@ModelAttribute(\"employee\") Employee employee,\n @RequestParam(\"projectId\") List<Project> projectIds,\n @RequestParam(\"employeeProjectMonths\") List<Double> months) {\n\n List<Double> monthList = new ArrayList<>();\n for (Double month : months) {\n if (month != null) {\n monthList.add(month);\n System.out.println(\"Month:\" + month);\n }\n }\n\n List<Project> projectList = new ArrayList<>();\n for (Project project : projectIds) {\n if (project != null) {\n projectList.add(project);\n System.out.println(\"Project:\" + project);\n }\n }\n\n employeeService.saveEmployee(employee);\n for (int i=0; i<= monthList.size(); i++) {\n EmployeeProject employeeProject = new EmployeeProject(employee);\n employeeProject.setEmployeeBookedMonths(monthList.get(i));\n employeeProject.setProject(new Project(projectList.get(i).getId()));\n employeeProjectService.saveEmployeeProjectEmployeeOnly(employeeProject);\n }\n return \"redirect:/ines/employees\";\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19263679/"
] |
74,301,783 | <p>I want to add a function where when I press a button, text shows up somewhere on a screen.
<a href="https://i.stack.imgur.com/yiMeh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yiMeh.png" alt="enter image description here" /></a></p>
<pre><code>import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'App';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget(),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextButton(
style: TextButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {},
child: const Text('Text Button'),
),
const SizedBox(height: 30),
OutlinedButton(
style: OutlinedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {},
child: const Text('Outlined Button'),
),
const SizedBox(height: 30),
ElevatedButton(
style: ElevatedButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {},
child: const Text('Contained Button'),
),
const SizedBox(height: 30),
],
),
);
}
}
</code></pre>
<p>Thank you if you are able to help.</p>
| [
{
"answer_id": 74311230,
"author": "Lucas Favaro Borsatto",
"author_id": 12369894,
"author_profile": "https://Stackoverflow.com/users/12369894",
"pm_score": 0,
"selected": false,
"text": "employeeProjectService.saveEmployeeProject(employee, ids, month);\n"
},
{
"answer_id": 74324661,
"author": "Lucas Favaro Borsatto",
"author_id": 12369894,
"author_profile": "https://Stackoverflow.com/users/12369894",
"pm_score": 0,
"selected": false,
"text": " EmployeeProject employeeProject = new EmployeeProject(employee);"
},
{
"answer_id": 74374561,
"author": "Kayd Anderson",
"author_id": 19263679,
"author_profile": "https://Stackoverflow.com/users/19263679",
"pm_score": 2,
"selected": true,
"text": "@PostMapping(\"/saveEmployee\")\n public String saveEmployee(@ModelAttribute(\"employee\") Employee employee,\n @RequestParam(\"projectId\") List<Project> projectIds,\n @RequestParam(\"employeeProjectMonths\") List<Double> months) {\n\n List<Double> monthList = new ArrayList<>();\n for (Double month : months) {\n if (month != null) {\n monthList.add(month);\n System.out.println(\"Month:\" + month);\n }\n }\n\n List<Project> projectList = new ArrayList<>();\n for (Project project : projectIds) {\n if (project != null) {\n projectList.add(project);\n System.out.println(\"Project:\" + project);\n }\n }\n\n employeeService.saveEmployee(employee);\n for (int i=0; i<= monthList.size(); i++) {\n EmployeeProject employeeProject = new EmployeeProject(employee);\n employeeProject.setEmployeeBookedMonths(monthList.get(i));\n employeeProject.setProject(new Project(projectList.get(i).getId()));\n employeeProjectService.saveEmployeeProjectEmployeeOnly(employeeProject);\n }\n return \"redirect:/ines/employees\";\n }\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406730/"
] |
74,301,821 | <p>I want to change the default directory for creating migration i.e. If I do <code>php artisan make:migration create_users_table</code>, it should create users table in <code>/database/migrations/child_database</code>. I do not want to use --path every time I create a migration for child_database. I want to change the default directory for <code>php artisan make:migration</code>.</p>
| [
{
"answer_id": 74303792,
"author": "Ramil Huseynov",
"author_id": 6711823,
"author_profile": "https://Stackoverflow.com/users/6711823",
"pm_score": 1,
"selected": false,
"text": "\n/**\n * Register Custom Migration Paths\n */\n$this->loadMigrationsFrom([\n database_path().DIRECTORY_SEPARATOR.'migrations'.DIRECTORY_SEPARATOR.'folder1',\n database_path().DIRECTORY_SEPARATOR.'migrations'.DIRECTORY_SEPARATOR.'folder2',\n]);/\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9833118/"
] |
74,301,836 | <p>I have a simple program that has to delete some values that are between 2 given "days". For example, I have this list of dicts:</p>
<pre><code>lst=[{"day": 1, "sum": 25, "type": 'in'}, {"day": 2, "sum": 55, "type": 'in'}, {"day": 3, "sum": 154, "type": 'out'}, {"day": 4, "sum": 99, "type": 'in'}]
</code></pre>
<p>and I wanna delete the values with "day" values between 1 and 3 and the output should be:</p>
<pre><code>[{"day": 4, "sum": 99, "type": 'in'}]
</code></pre>
<p>Now I am using this program:</p>
<pre><code>def delete_transaction_interval(all_transactions, dayStart, dayEnd):
for element in enumerate(all_transactions):
if get_transaction_day(all_transactions[element])>=dayStart and get_transaction_day(all_transactions[element])<=dayEnd:
new_list_transactions=all_transactions[:]
return new_list_transactions
</code></pre>
<p>but I want to use a getter function instead of <code>all_transactions[i]["day"]</code>. I already created the function:</p>
<pre><code>def get_transaction_day(all_transactions):
return all_transactions["day"]
</code></pre>
<p>but I am using it I got this error:</p>
<pre><code>list indices must be integers or slices, not tuple
</code></pre>
<p>and I don't know how to handle it because I do not see any tuple in my code TBH.</p>
<p>My version is:</p>
<pre><code>def delete_transaction_interval(all_transactions, dayStart, dayEnd):
i=0
while i<=len(all_transactions)-1:
if get_transaction_day(all_transactions[i])>=dayStart and get_transaction_day(all_transactions[i])<=dayEnd:
new_transactions_list=all_transactions[:]
else:
i+=1
return new_transactions_list
</code></pre>
<p>Traceback:</p>
<pre><code> Exception has occurred: TypeError
list indices must be integers or slices, not tuple
File "<String>", line 81, in delete_transaction_interval
if get_transaction_day(all_transactions[element])>=dayStart and get_transaction_day(all_transactions[element])<=dayEnd:
File "<String>", line 229, in test_delete_interval
delete_transaction_interval(all_transactions,1,3)
File "<String>", line 276, in test_all
test_delete_interval()
File "<String>", line 281, in <module>
test_all()
</code></pre>
<p>Can somebody help me with this, please?</p>
| [
{
"answer_id": 74302040,
"author": "Tajinder Singh",
"author_id": 8440629,
"author_profile": "https://Stackoverflow.com/users/8440629",
"pm_score": 1,
"selected": false,
"text": "new_transactions_list = []\nfor elem in lst:\n if not 1 <= elem[\"day\"] <= 3 :\n new_transactions_list.append(elem)\n \nprint(new_transactions_list)\n"
},
{
"answer_id": 74304156,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 0,
"selected": false,
"text": "def get_transaction_day(all_transactions):\n return all_transactions[\"day\"]\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18164390/"
] |
74,301,844 | <p>I'm trying to make a message that appears when exiting the program. What I want it to look like is like this:</p>
<ol>
1. print the word "Quitting"
</ol>
<ol>
2. repeat 3 times:
<ul>
- halt for 0.5 seconds
</ul>
<ul>
- print a dot in the same line with the word "Quitting"
</ul>
3. show the prompt in a new line
</ol>
I wrote the code for it, But the problem is: either it shows the dots each 0.5 sec but vertically, or it waits for (0.5*3) sec to show everything (even the word "Quitting").
<p>The code:</p>
<pre><code> print("Quitting", end='')
for i in range(3):
print('.', end='')
time.sleep(0.5)
print('\n')
</code></pre>
| [
{
"answer_id": 74302033,
"author": "José Rodrigues",
"author_id": 10571074,
"author_profile": "https://Stackoverflow.com/users/10571074",
"pm_score": 0,
"selected": false,
"text": "import time\n\nprint(\"Quitting\", end='')\nfor i in range(3):\n print('.', end='', flush=True)\n time.sleep(0.5)\nprint('\\n')\n"
},
{
"answer_id": 74306244,
"author": "Abderrahmane",
"author_id": 12282746,
"author_profile": "https://Stackoverflow.com/users/12282746",
"pm_score": 1,
"selected": false,
"text": "import time\n\nprint(\"Quitting\", end='', flush=True)\nfor i in range(3):\n print('.', end='', flush=True)\n time.sleep(0.5)\nprint('\\n')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12282746/"
] |
74,301,859 | <pre><code>{
"data": [
{
"country": "China",
"color" : "Red",
"pet" : "Cat",
"name" : "Mark",
"height_unit_name" : "cm"
},
{
"country": "China",
"color" : "black",
"pet" : "dog",
"name" : "Jane",
"height_unit_name" : "cm"
}
]
}
</code></pre>
<p>I would like to move the duplicate data outside each array and show it once like this...
Like "country" and "height_unit_name", both are same in each array.</p>
<pre><code>{
"country": "China",
"height_unit_name": "cm",
"data": [
{
"color": "Red",
"pet": "Cat",
"name": "Mark"
},
{
"color": "black",
"pet": "dog",
"name": "Jane"
}
]
}
</code></pre>
<p>Thankyou for your helping</p>
| [
{
"answer_id": 74302223,
"author": "Mat",
"author_id": 968671,
"author_profile": "https://Stackoverflow.com/users/968671",
"pm_score": 0,
"selected": false,
"text": "object"
},
{
"answer_id": 74302397,
"author": "Serge",
"author_id": 11392290,
"author_profile": "https://Stackoverflow.com/users/11392290",
"pm_score": 1,
"selected": false,
"text": "var jsonArr = (JArray)JObject.Parse(json)[\"data\"];\n\nList<CountryPets> pets = jsonArr\n .GroupBy(a => new { c = (string)a[\"country\"], h = (string)a[\"height_unit_name\"], })\n .Select(b => new CountryPets\n {\n Country = b.Key.c,\n HeightUnitName = b.Key.h,\n Pets = b.Select(a => a.ToObject<Pet>()).ToList()\n }).ToList();\n\npublic partial class CountryPets\n{\n public string Country { get; set; }\n public string HeightUnitName { get; set; }\n public List<Pet> Pets { get; set; }\n}\n\npublic partial class Pet\n{\n [JsonProperty(\"color\")]\n public string Color { get; set; }\n\n [JsonProperty(\"pet\")]\n public string PetType { get; set; }\n\n [JsonProperty(\"name\")]\n public string Name { get; set; }\n}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406716/"
] |
74,301,905 | <p>I need your help.</p>
<p>I working with Oracle SQL and I need to remove everything that it outside the brackets.
For example:</p>
<pre><code> - Stabilization loans, mortgage lending (StabL ML) => StabL ML
- Refinanced loans and restructured loans (RefL RL) => RefL RL
- Individual reserve (IR) => IR
</code></pre>
<p>I'm trying to use something like this but it doen't work</p>
<pre><code>select regexp_replace(example, '\([A-Za-z ]\)', '') from dual;
</code></pre>
<p>I will be grateful for any help!</p>
| [
{
"answer_id": 74302034,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": ".*\\(|\\).*"
},
{
"answer_id": 74312789,
"author": "Griffin",
"author_id": 18280576,
"author_profile": "https://Stackoverflow.com/users/18280576",
"pm_score": 0,
"selected": false,
"text": "SELECT REGEXP_SUBSTR ( 'Stabilization loans, mortgage lending (StabL ML)', '\\( *([^)]*) *\\)', 1, 1, NULL, 1) FROM dual;\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20260589/"
] |
74,301,916 | <p>I am working through the Automate the Boring Stuff with Python course, and one of the lessons has me stumped, regarding the use of the try: and except: clauses.</p>
<p>When I run the code as described in the course below, using if/else statements it works, as the except clause is executed and python prints ' you did not enter a number' when entering text such as 'one'</p>
<pre><code>print('how many cats do you have?')
numcats=input()
try:
if int(numcats)>=4:
print('that is a lot of cats')
else:
print('that is not many cats')
except ValueError:
print('you did not enter a number')
</code></pre>
<p>however, when I use elif statements as per this example, the except clause is not executed, and I get an error. To me they both look like they should produce the same result.</p>
<p>What am I missing?</p>
<pre><code>print('how many cats do you own?')
numcats=int(input())
try:
if numcats<=5 and numcats>0:
print('that is not alot of cats')
elif numcats >5 and numcats<=10:
print('that is alot of cats! more than five and less than 10!')
elif numcats <0:
print('you cant have less than zero cats!')
elif numcats>10:
print('more than 10 cats! thats crazy!')
except ValueError:
print('you did not enter a numerical value, try again')
</code></pre>
<p>I compared the structure of the two sets of code, and looks like they should produce the same result, not sure why the elif statements cause the except: clause to not be executed? I thought it would be the same as an if, else statement</p>
| [
{
"answer_id": 74301942,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
"author_profile": "https://Stackoverflow.com/users/4727702",
"pm_score": 3,
"selected": true,
"text": "ValueError"
},
{
"answer_id": 74301996,
"author": "OmarFatahiDev",
"author_id": 18610613,
"author_profile": "https://Stackoverflow.com/users/18610613",
"pm_score": 0,
"selected": false,
"text": "print('how many cats do you own?')\nnumcats=input()\ntry: \n if int(numcats)<=5 and int(numcats)>0:\n print('that is not alot of cats')\n elif int(numcats) >5 and int(numcats)<=10:\n print('that is alot of cats! more than five and less than 10!')\n elif int(numcats) <0:\n print('you cant have less than zero cats!')\n elif int(numcats)>10:\n print('more than 10 cats! thats crazy!')\nexcept ValueError:\n print('you did not enter a numerical value, try again')\n"
},
{
"answer_id": 74302020,
"author": "Filip Hanes",
"author_id": 7948776,
"author_profile": "https://Stackoverflow.com/users/7948776",
"pm_score": 1,
"selected": false,
"text": "int()"
},
{
"answer_id": 74302030,
"author": "Stink",
"author_id": 19408629,
"author_profile": "https://Stackoverflow.com/users/19408629",
"pm_score": 0,
"selected": false,
"text": "user_input = input(\"enter a number\")\n\ntry : \n numcats= int(user_input)\nexcept ValueError:\n print (\"enter a number\")\nelse:\n if numcats<=5 and numcats>0:\n print('that is not alot of cats')\n elif numcats >5 and numcats<=10:\n print('that is alot of cats! more than five and less than 10!')\n elif numcats <0:\n print('you cant have less than zero cats!')\n elif numcats>10:\n print('more than 10 cats')\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406790/"
] |
74,301,929 | <p>I have a dataset like:</p>
<pre><code>a
c
c
d
b
a
a
d
d
c
c
b
a
b
</code></pre>
<p>I want to add a column that looks like the one below. When 'c' is reached, the new column will be zero and then be increased by one. Is there a way we can do this using python?</p>
<pre><code>a 1
c 0
c 0
d 2
b 2
a 2
a 2
d 2
d 2
c 0
c 0
b 3
a 3
b 3
</code></pre>
| [
{
"answer_id": 74301984,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": false,
"text": "s = df['col'].eq('c')\ndf['new'] = s.ne(s.shift())[~s].cumsum().reindex(df.index, fill_value=0)\n"
},
{
"answer_id": 74312727,
"author": "G.G",
"author_id": 20284103,
"author_profile": "https://Stackoverflow.com/users/20284103",
"pm_score": 0,
"selected": false,
"text": " df1.assign(col2=df1.col1.ne('c').astype(int))\\\n .assign(col3=lambda dd:(dd.col2.diff()==1).cumsum())\\\n .assign(col4=lambda dd:dd.col2*(dd.col2+dd.col3))\n \n \n col1 col2 col3 col4\n 0 a 1 0 1\n 1 c 0 0 0\n 2 c 0 0 0\n 3 d 1 1 2\n 4 b 1 1 2\n 5 a 1 1 2\n 6 a 1 1 2\n 7 d 1 1 2\n 8 d 1 1 2\n 9 c 0 1 0\n 10 c 0 1 0\n 11 b 1 2 3\n 12 a 1 2 3\n 13 b 1 2 3\n\n\nor \n\ndf1=df1.assign(col2=(df1.eq('c')&df1.shift().ne('c')).cumsum()+1)\ndf1.loc[df1.col1=='c']=0\ndf1\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20203862/"
] |
74,301,952 | <p>I have the following array</p>
<pre><code>[
'192.168.1.1 - 192.168.2.2',
'192.168.2.2 - 192.168.1.1',
'192.168.8.8 - 192.168.9.9',
'192.168.9.9 - 192.168.8.8'
]
</code></pre>
<p>It is basically in this format</p>
<pre><code>[
'A - B',
'B - A',
'X - Y',
'Y - X'
]
</code></pre>
<p>so I want the resultant string in the following format, i.e want only one string from 'A - B' and 'B - A', see the required string of above arrays below</p>
<pre><code>[
'192.168.1.1 - 192.168.2.2',
'192.168.8.8 - 192.168.9.9'
]
[
'A - B',
'X - Y'
]
</code></pre>
<p>Any Idea how to achieve this?</p>
| [
{
"answer_id": 74302062,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 3,
"selected": true,
"text": "const data = [\n 'A - B', \n 'B - A', \n 'X - Y', \n 'Y - X'\n]\n\nconst data2 = [\n '192.168.1.1 - 192.168.2.2', \n '192.168.2.2 - 192.168.1.1', \n '192.168.8.8 - 192.168.9.9', \n '192.168.9.9 - 192.168.8.8'\n]\n\n\nconst result = data => [...new Set(data.map(d => JSON.stringify(d.split(' - ').sort())))].map(s => JSON.parse(s).join(' - '))\n\nconsole.log(result(data))\n\n\nconsole.log(result(data2))"
},
{
"answer_id": 74302068,
"author": "BeSter Development",
"author_id": 20356148,
"author_profile": "https://Stackoverflow.com/users/20356148",
"pm_score": 0,
"selected": false,
"text": "const arr = [\n '192.168.1.1 - 192.168.2.2',\n '192.168.2.2 - 192.168.1.1',\n '192.168.8.8 - 192.168.9.9',\n '192.168.9.9 - 192.168.8.8'\n ]\n\n var a = arr.filter( x => arr.indexOf(x) % 2 == 0);\n console.log(a);"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10611485/"
] |
74,301,962 | <p>I'm trying to annotate the following code.</p>
<p>The function designed to work when both <code>zone</code> and <code>zones</code> defined, or when <code>file</code> is defined (but not both):</p>
<pre class="lang-py prettyprint-override"><code>def get_file(zone: str, zones: dict[str, str]) -> pathlib.Path:
pass
def connect(
zone: str | None = None,
zones: dict[str, str] | None = None,
file: pathlib.Path | None = None,
) -> bool:
file = file or get_file(zone, zones)
</code></pre>
<p>But it makes <code>mypy</code> angry -</p>
<pre><code>1. Argument of type "str | None" cannot be assigned to parameter "zone" of type "str" in function "_get_vpn_file"
Type "str | None" cannot be assigned to type "str"
Type "None" cannot be assigned to type "str"
2. Argument of type "dict[str, str] | None" cannot be assigned to parameter "zones" of type "dict[str, str]" in function "_get_vpn_file"
Type "dict[str, str] | None" cannot be assigned to type "dict[str, str]"
Type "None" cannot be assigned to type "dict[str, str]"
</code></pre>
<p>Then I tried to make some aggressive type narrowing:</p>
<pre class="lang-py prettyprint-override"><code>def _check_params_are_ok(
zone: str | None, zones: dict[str, str] | None, file: pathlib.Path | None,
) -> tuple[str, dict[str, str], None] | tuple[None, None, pathlib.Path]:
if zone is not None and file is not None:
raise ValueError("Pass `file` or `zone`, but not both.")
if zone is not None and zones is None:
raise ValueError("connect: Must define `zones` when `zone` is defined.")
if zone is None and file is None:
raise ValueError("connect: Must define `zone` or `file`.")
assert file is not None or (zone is not None and zones is not None)
# Type narrowing
if zone is not None and zones is not None and file is None:
return zone, zones, file
if zone is None and zones is None and file is not None:
return zone, zones, file
raise NotImplementedError("This error from _check_params_ok shouldn't happen.")
def connect(
zone: str | None = None,
zones: dict[str, str] | None = None,
file: pathlib.Path | None = None,
) -> bool:
zone, zones, file = _check_params_are_ok(zone, zones, file)
file = file or get_file(zone, zones)
</code></pre>
<p>And mypy still shows the same errors.</p>
<p>Mypy still shows the same errors even when adding very clear assertions:</p>
<pre class="lang-py prettyprint-override"><code> zone, zones, file = _check_params_are_ok(zone, zones, file)
if file is None:
assert zone is not None and zones is not None
file = file or get_file(zone, zones)
</code></pre>
<p>The best solution I found so far is to cast the types inline, but it effects the code readability and make the line hard to read:</p>
<pre class="lang-py prettyprint-override"><code> file = file or get_file(cast(str, zone), cast(dict[str, str], zones))
</code></pre>
<p>Is there any good way to narrow the types?</p>
| [
{
"answer_id": 74302062,
"author": "R4ncid",
"author_id": 14326899,
"author_profile": "https://Stackoverflow.com/users/14326899",
"pm_score": 3,
"selected": true,
"text": "const data = [\n 'A - B', \n 'B - A', \n 'X - Y', \n 'Y - X'\n]\n\nconst data2 = [\n '192.168.1.1 - 192.168.2.2', \n '192.168.2.2 - 192.168.1.1', \n '192.168.8.8 - 192.168.9.9', \n '192.168.9.9 - 192.168.8.8'\n]\n\n\nconst result = data => [...new Set(data.map(d => JSON.stringify(d.split(' - ').sort())))].map(s => JSON.parse(s).join(' - '))\n\nconsole.log(result(data))\n\n\nconsole.log(result(data2))"
},
{
"answer_id": 74302068,
"author": "BeSter Development",
"author_id": 20356148,
"author_profile": "https://Stackoverflow.com/users/20356148",
"pm_score": 0,
"selected": false,
"text": "const arr = [\n '192.168.1.1 - 192.168.2.2',\n '192.168.2.2 - 192.168.1.1',\n '192.168.8.8 - 192.168.9.9',\n '192.168.9.9 - 192.168.8.8'\n ]\n\n var a = arr.filter( x => arr.indexOf(x) % 2 == 0);\n console.log(a);"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058671/"
] |
74,301,968 | <p>I'm using python 3 and I have a dictionary containing some scheduler data. Now I want to set that if a day name repeats in the data list.</p>
<p>here is the case and code :</p>
<pre><code>data = [
{'day': 'Monday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},
{'day': 'Tuesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},
{'day': 'Wednesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},
{'day': 'Thursday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},
{'day': 'Friday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},
{'day': 'Saturday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},
{'day': 'Saturday', 'full_day': False, 'close_day': True, 'start_time': None, 'close_time': None},
{'day': 'Sunday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}
]
</code></pre>
<p>as you can see Saturday is 2 times in the data list. the second one is full-day false and close-day true. Now I want that to stay there and the first Saturday object removes from the list.
And this thing with all days which come in the list multiple times.</p>
| [
{
"answer_id": 74302328,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
"author_profile": "https://Stackoverflow.com/users/4727702",
"pm_score": 3,
"selected": true,
"text": "day"
},
{
"answer_id": 74302365,
"author": "Dmitriy Neledva",
"author_id": 16786350,
"author_profile": "https://Stackoverflow.com/users/16786350",
"pm_score": 0,
"selected": false,
"text": "data = [\n{ 'day': 'Monday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Tuesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Wednesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Thursday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Friday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{'day': 'Saturday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Saturday', 'full_day': False, 'close_day': True, 'start_time': None, 'close_time': None},\n{'day': 'Sunday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None} \n]\n\nfor e,i in enumerate(data):\n if i['day'] == 'Saturday' and i['full_day']:\n data.pop(e)\n\nfor i in data:\n print(i)\n\n# {'day': 'Monday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Tuesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Wednesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Thursday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Friday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Saturday', 'full_day': False, 'close_day': True, 'start_time': None, 'close_time': None}\n# {'day': 'Sunday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20286415/"
] |
74,301,981 | <p>Is there any tool or script available that creates millions of files directories, sub-directories and sub-sub-directories randomly in Linux and Windows.</p>
| [
{
"answer_id": 74302328,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
"author_profile": "https://Stackoverflow.com/users/4727702",
"pm_score": 3,
"selected": true,
"text": "day"
},
{
"answer_id": 74302365,
"author": "Dmitriy Neledva",
"author_id": 16786350,
"author_profile": "https://Stackoverflow.com/users/16786350",
"pm_score": 0,
"selected": false,
"text": "data = [\n{ 'day': 'Monday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Tuesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Wednesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Thursday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Friday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{'day': 'Saturday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None},\n{ 'day': 'Saturday', 'full_day': False, 'close_day': True, 'start_time': None, 'close_time': None},\n{'day': 'Sunday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None} \n]\n\nfor e,i in enumerate(data):\n if i['day'] == 'Saturday' and i['full_day']:\n data.pop(e)\n\nfor i in data:\n print(i)\n\n# {'day': 'Monday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Tuesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Wednesday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Thursday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Friday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n# {'day': 'Saturday', 'full_day': False, 'close_day': True, 'start_time': None, 'close_time': None}\n# {'day': 'Sunday', 'full_day': True, 'close_day': False, 'start_time': None, 'close_time': None}\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74301981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4306541/"
] |
74,302,059 | <p>I am trying to update a particular session variable in an array.</p>
<p>How i set up the session</p>
<pre><code> $_SESSION['cart_items'][] = [
'size' => $size,
'color' => $color,
'qty' => $quantity,
'price' => $price,
'productId' => $productId,
'image' => $image,
'name' => $name,
];
</code></pre>
<p>I want to update the 'qty' when i press update in the form.</p>
<pre><code> foreach ($_SESSION["cart_items"] as $key => $item) {
$item_price = $item["qty"] * $item["price"];
$total_quantity += $item["qty"];
$item_total = $item_price * $total_quantity;
$total_price += ($item["price"] * $item["qty"]);
$_SESSION['totalprice'] = $total_price;
//html code
echo '
<div class="cartitem">
<div id="cartimage">
<img src=' . $item['image'] . '>
</div>
<div id="cartdesc">
<form method="get" action="cart.php">
<p id="cartitemname"> ' . $item["name"] . ' </p>
<p>Quantity: <input id="updateprice" name="updateprice" type="number" step="1" min="1" value="' . $item["qty"] . '"> </p>
<p>Size: ' . $item["size"] . ' </p>
<p>Price:$ ' . $item["price"] . ' </p>
<p>Item total price $ ' . number_format($item["qty"] * $item["price"], 2) . ' </p>
<button type="submit" name="update">Update</button>
<a href="cart.php?action=remove&code=' . $key . '" class="btnRemoveAction"><img id="deletebtn" src="res/istockphoto-928418914-170667a.jpg" alt="Remove Item" /></a>
</form>
</div>
</div>
';
}
</code></pre>
<p>the get method called when i press update :</p>
<pre><code> if (isset($_GET['update'])) {
//print_r($_SESSION["cart_items"]);
// what i have tried :
// $_SESSION['cart_items']['qty'] = $_GET['updateprice']
//$item["qty"] = $_GET['updateprice'];
header('location:cart.php');
}
</code></pre>
<p>Both of these don't work! any help or nudge in the right direction would be greatly appreciated!</p>
| [
{
"answer_id": 74302499,
"author": "M. Eriksson",
"author_id": 2453432,
"author_profile": "https://Stackoverflow.com/users/2453432",
"pm_score": 3,
"selected": true,
"text": "// Equal to how you add the cart items\n$array[] = [\n 'id' => 1,\n 'qty' => 1\n];\n\n $array[] = [\n 'id' => 2,\n 'qty' => 1\n];\n\n// Results in an indexed array like this:\n[\n 0 => [\n 'id' => 1,\n 'qty' => 1\n ],\n 1 => [\n 'id' => 1,\n 'qty' => 1\n ]\n]\n"
},
{
"answer_id": 74303080,
"author": "Dugong98",
"author_id": 8703649,
"author_profile": "https://Stackoverflow.com/users/8703649",
"pm_score": 0,
"selected": false,
"text": "<input type=\"hidden\" name=\"uniquekey\" id=\"uniquekey\">\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74302059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8703649/"
] |
74,302,071 | <p>I need to migrate some table's data into another table in the same database;</p>
<p>for example table1:</p>
<pre><code>PersonID LastName FirstName Address City
1 Foo Bar xxx boh
2 Foo Bar xxx boh
3 Foo Bar xxx boh
</code></pre>
<p>and table2</p>
<pre><code> PersonID field2 field3 field4 field5
1 boh xxx Foo Bar
2 boh xxx Foo Bar
3 boh xxx Foo Bar
</code></pre>
<p>I've tried with this sample code:</p>
<pre><code>ResultSet table1 = s.executeQuery("Select * from table1");
ResultSet table2 = s.executeQuery("Select * from table2");
while(table1.next()) {
table2.insertRow();
}
</code></pre>
<p>But with just that instruction I got "The result set is closed." error.
Can I insert in table2 the same amount of rows of table1?
Then I tought about adding information by reading informations from table1 and adding them to table2 with the resultset updateRow method.</p>
<p>EDIT: Table2 in the beginning should be empty, with just the structure created.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74302499,
"author": "M. Eriksson",
"author_id": 2453432,
"author_profile": "https://Stackoverflow.com/users/2453432",
"pm_score": 3,
"selected": true,
"text": "// Equal to how you add the cart items\n$array[] = [\n 'id' => 1,\n 'qty' => 1\n];\n\n $array[] = [\n 'id' => 2,\n 'qty' => 1\n];\n\n// Results in an indexed array like this:\n[\n 0 => [\n 'id' => 1,\n 'qty' => 1\n ],\n 1 => [\n 'id' => 1,\n 'qty' => 1\n ]\n]\n"
},
{
"answer_id": 74303080,
"author": "Dugong98",
"author_id": 8703649,
"author_profile": "https://Stackoverflow.com/users/8703649",
"pm_score": 0,
"selected": false,
"text": "<input type=\"hidden\" name=\"uniquekey\" id=\"uniquekey\">\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74302071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8641624/"
] |
74,302,163 | <p>In SQL Server, the transaction log file was needed to be shrunk, therefore the DBCC SHRINKFILE was executed (we forgot to note down the file-size before execution). Now how can we check if the file shrinking process was succeeded, especially we don't know the initial file size before the shrinking was done.</p>
<p>For clarity: Shrinking process is currently <strong>not</strong> running, (this is not about checking the on-going progress of shrinking).</p>
<p>Also is there a way to get historical stats on shrinking events?</p>
<p>TIA.</p>
| [
{
"answer_id": 74302832,
"author": "SQLpro",
"author_id": 12659872,
"author_profile": "https://Stackoverflow.com/users/12659872",
"pm_score": 2,
"selected": false,
"text": "CREATE EVENT SESSION ES_TRACK_DB_FILE_CHANGE \n ON SERVER \n ADD EVENT sqlserver.database_file_size_change\n (ACTION(sqlserver.client_app_name,\n sqlserver.client_hostname,\n sqlserver.database_name,\n sqlserver.nt_username,\n sqlserver.server_principal_name,\n sqlserver.session_nt_username,\n sqlserver.sql_text,\n sqlserver.username))\n ADD TARGET package0.event_file\n (SET filename=N'C:\\XE_EVENTS\\TRACK_DB_FILE_CHANGE.xel')\n WITH (MAX_MEMORY=2048 KB,\n EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,\n MAX_DISPATCH_LATENCY=60 SECONDS,\n STARTUP_STATE=ON)\nGO\n"
},
{
"answer_id": 74302899,
"author": "Stuck at 1337",
"author_id": 20091109,
"author_profile": "https://Stackoverflow.com/users/20091109",
"pm_score": 1,
"selected": false,
"text": "DECLARE @path nvarchar(260);\n\nSELECT\n @path = REVERSE(SUBSTRING(REVERSE([path]),\n CHARINDEX(CHAR(92), REVERSE([path])), 260)) + N'log.trc'\nFROM sys.traces\nWHERE is_default = 1;\n\nSELECT TextData, [Database] = DB_NAME(DatabaseID), LoginName\nFROM sys.fn_trace_gettable(@path, DEFAULT)\nWHERE EventClass = 116\n AND UPPER(CONVERT(nvarchar(max), TextData)) LIKE N'%SHRINK%'; \n -- could be SHRINKDATABASE\n"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74302163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5571827/"
] |
74,302,170 | <p>Is it possible to show the actually code coverage with Istanbul, ignoring the <em>"ignore"</em> annotations?</p>
<p>e.g. Don't actually ignore next:</p>
<p><code>/* istanbul ignore next */</code></p>
<p>Our coverage reports 100% coverage but has ignores in the code.</p>
| [
{
"answer_id": 74334488,
"author": "Dennis van de Hoef - Xiotin",
"author_id": 5600652,
"author_profile": "https://Stackoverflow.com/users/5600652",
"pm_score": 2,
"selected": false,
"text": "for file in *.js\ndo\n sed '/istanbul ignore/d' \"$file\" > \"$file\".new_file.js\n mv \"$file\".new_file.js \"$file\".js\ndone\n"
},
{
"answer_id": 74392935,
"author": "Mario Varchmin",
"author_id": 7821823,
"author_profile": "https://Stackoverflow.com/users/7821823",
"pm_score": 2,
"selected": true,
"text": "/* istanbul ignore ... */"
}
] | 2022/11/03 | [
"https://Stackoverflow.com/questions/74302170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198040/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.