qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,192,052 | <p>I receive files (json) from time to time from AWS sns. Some of them contain only 1 object, some other have several objects.</p>
<p>I am trying to run a python script to extract a couple of columns as example but I get multiple errors due to this several objects or the format of the file. Ideally I want to get all the data into columns, specially the ones contained inside the "Message" section. (I.e. eventType, from, to, bcc, messageId, timestamp, etc.</p>
<p>Can anybody help?
Thanks</p>
<p><strong>script:</strong></p>
<pre><code>data = []
for line in open(folder + file, 'r', encoding='utf-8'):
data.append(json.loads(line))
pd.json_normalize(data)
#df = pd.DataFrame(((d['Message']) for d in data), columns=['Message'])
df = pd.DataFrame([(
data[0]['Timestamp'],
data[0]['Subject'],
data[0]['Message']['eventType'])
], columns=['Timestamp', 'Subject', 'eventType'])
df.to_csv(folder + 'testOutput.csv', index=False, encoding='utf-8')
print(df)
</code></pre>
<p><strong>Example file with multiple objects:</strong></p>
<pre><code>{"Type":"Notification","MessageId":"0579da9d-671f-547f-879a-8151d6048","TopicArn":"arn:aws:sns:region:123456789:SES-notification-s","Subject":"Event Notification","Message":"{\"eventType\":\"Click\",\"mail\":{\"timestamp\":\"2022-10-21T14:39:47.003Z\",\"source\":\"tester <fromemail@email.com>\",\"sendingAccountId\":\"123456789\",\"messageId\":\"01000183fafc5f3b-4f5f3dc2-281a-472a-85-915f85289858-000000\",\"destination\":[\"toemail@email.com\",\"bccemail@email.com\"],\"headersTruncated\":false,\"headers\":[{\"name\":\"Content-Type\",\"value\":\"multipart/mixed; boundary=\\\"===============4453571503606487627==\\\"\"},{\"name\":\"MIME-Version\",\"value\":\"1.0\"},{\"name\":\"Subject\",\"value\":\"Email tracking test\"},{\"name\":\"From\",\"value\":\"tester <fromemail@email.com>\"},{\"name\":\"To\",\"value\":\"toemail@email.com\"},{\"name\":\"Bcc\",\"value\":\"bccemail@email.com\"},{\"name\":\"Message-ID\",\"value\":\"null\"}],\"commonHeaders\":{\"from\":[\"tester <fromemail@email.com>\"],\"to\":[\"toemail@email.com\"],\"bcc\":[\"bccemail@email.com\"],\"messageId\":\"010001fafc5f33b-4f53dc2-281a-472a-8f65-915f889858-000000\",\"subject\":\"Email tracking test\"},\"tags\":{\"ses:operation\":[\"SendRawEmail\"],\"ses:configuration-set\":[\"ses-email-tracking\"],\"ses:source-ip\":[\"12.12.123.123\"],\"ses:from-domain\":[\"domain.dev\"],\"ses:caller-identity\":[\"caller_identity\"]}},\"click\":{\"timestamp\":\"2022-10-21T14:40:55.000Z\",\"ipAddress\":\"66.66.666.666\",\"userAgent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36\",\"link\":\"https://website.com\",\"linkTags\":null}}\n","Timestamp":"2022-10-21T14:40:55.066Z","UnsubscribeURL":"unsubscribeLink"}
{"Type":"Notification","MessageId":"03758739-75a9-5462-8361-dcf5c410e015","TopicArn":"arn:aws:sns:region:123456789:SES-notification-s","Subject":"Event Notification","Message":"{\"eventType\":\"ClickNum2\",\"mail\":{\"timestamp\":\"2022-10-21T14:39:47.003Z\",\"source\":\"tester <fromemail@email.com>\",\"sendingAccountId\":\"123456789\",\"messageId\":\"01000183fafc5f3b-4f5f3dc2-281a-472a-85-915f85289858-000000\",\"destination\":[\"toemail2@email.com\",\"bccemail2@email.com\"],\"headersTruncated\":false,\"headers\":[{\"name\":\"Content-Type\",\"value\":\"multipart/mixed; boundary=\\\"===============4453571503606487627==\\\"\"},{\"name\":\"MIME-Version\",\"value\":\"1.0\"},{\"name\":\"Subject\",\"value\":\"Email tracking test\"},{\"name\":\"From\",\"value\":\"tester <fromemail@email.com>\"},{\"name\":\"To\",\"value\":\"toemail2@email.com\"},{\"name\":\"Bcc\",\"value\":\"bccemail2@email.com\"},{\"name\":\"Message-ID\",\"value\":\"null\"}],\"commonHeaders\":{\"from\":[\"tester <fromemail@email.com>\"],\"to\":[\"toemail2@email.com\"],\"bcc\":[\"bccemail2@email.com\"],\"messageId\":\"010001fafc5f33b-4f53dc2-281a-472a-8f65-915f889858-000000\",\"subject\":\"Email tracking test\"},\"tags\":{\"ses:operation\":[\"SendRawEmail\"],\"ses:configuration-set\":[\"ses-email-tracking\"],\"ses:source-ip\":[\"12.12.123.123\"],\"ses:from-domain\":[\"domain.dev\"],\"ses:caller-identity\":[\"caller_identity\"]}},\"click2\":{\"timestamp\":\"2022-10-21T15:45:50.000Z\",\"ipAddress\":\"55.55.555.555\",\"userAgent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36\",\"link\":\"https://website.com\",\"linkTags\":null}}\n","Timestamp":"2022-10-21T15:50:50.066Z","UnsubscribeURL":"unsubscribeLink"}
{"Type":"Notification","MessageId":"03758739-75a9-5462-8361-dcf5c410e015","TopicArn":"arn:aws:sns:region:123456789:SES-notification-s","Subject":"Event Notification","Message":"{\"eventType\":\"ClickNum3\",\"mail\":{\"timestamp\":\"2022-10-21T14:39:47.003Z\",\"source\":\"tester <fromemail@email.com>\",\"sendingAccountId\":\"123456789\",\"messageId\":\"01000183fafc5f3b-4f5f3dc2-281a-472a-85-915f85289858-000000\",\"destination\":[\"toemail3@email.com\",\"bccemail3@email.com\"],\"headersTruncated\":false,\"headers\":[{\"name\":\"Content-Type\",\"value\":\"multipart/mixed; boundary=\\\"===============4453571503606487627==\\\"\"},{\"name\":\"MIME-Version\",\"value\":\"1.0\"},{\"name\":\"Subject\",\"value\":\"Email tracking test\"},{\"name\":\"From\",\"value\":\"tester <fromemail@email.com>\"},{\"name\":\"To\",\"value\":\"toemail3@email.com\"},{\"name\":\"Bcc\",\"value\":\"bccemail3@email.com\"},{\"name\":\"Message-ID\",\"value\":\"null\"}],\"commonHeaders\":{\"from\":[\"tester <fromemail@email.com>\"],\"to\":[\"toemail3@email.com\"],\"bcc\":[\"bccemail3@email.com\"],\"messageId\":\"010001fafc5f33b-4f53dc2-281a-472a-8f65-915f889858-000000\",\"subject\":\"Email tracking test\"},\"tags\":{\"ses:operation\":[\"SendRawEmail\"],\"ses:configuration-set\":[\"ses-email-tracking\"],\"ses:source-ip\":[\"12.12.123.123\"],\"ses:from-domain\":[\"domain.dev\"],\"ses:caller-identity\":[\"caller_identity\"]}},\"click3\":{\"timestamp\":\"2022-10-21T16:50:50.000Z\",\"ipAddress\":\"44.44.444.444\",\"userAgent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36\",\"link\":\"https://website.com\",\"linkTags\":null}}\n","Timestamp":"2022-10-21T16:50:50.066Z","UnsubscribeURL":"unsubscribeLink"}
</code></pre>
| [
{
"answer_id": 74193249,
"author": "Leon",
"author_id": 18737438,
"author_profile": "https://Stackoverflow.com/users/18737438",
"pm_score": -1,
"selected": false,
"text": "has_many"
},
{
"answer_id": 74195850,
"author": "BenFenner",
"author_id": 14837782,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20033563/"
] |
74,192,054 | <p>I've been recently trying to do the following in awk -
we have two files (F1.txt F2.txt.gz). While streaming from the second one, I want to replace all occurrences of entries from f1.txt with its substrings. I came to this point:</p>
<pre><code>zcat F2.txt.gz |
awk 'NR==FNR {a[$1]; next}
{for (i in a)
$0=gsub(i, substr(i, 0, 2), $0) #this does not work of course
}
{print $0}
' F1.txt -
</code></pre>
<p>Was wondering how to do this properly in Awk. Thanks!</p>
| [
{
"answer_id": 74193249,
"author": "Leon",
"author_id": 18737438,
"author_profile": "https://Stackoverflow.com/users/18737438",
"pm_score": -1,
"selected": false,
"text": "has_many"
},
{
"answer_id": 74195850,
"author": "BenFenner",
"author_id": 14837782,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3523464/"
] |
74,192,068 | <p>I have some VBA code that I would like to set the format (forecolour) of all cells in a given workbook that match some criteria (essentially this is to auto-mark use of a particular UDF). If the user has protected sheets in their workbook, they may have (sensibly) protected them in such a way that formatting is still permitted.
How do I check (from the VBA Range object representing the cell) whether a cell on any given worksheet is good to make format edits to?</p>
<p>I am aware the route-one answer to this will be an error handler to try it and handle the cases that fail - but as this has to run on every cell in the UsedRange of every sheet, I want it to be fast. I also realise that this is VBA, so there may not be a faster or more elegant way - but there is a lot of collected wisdom on here, hence my asking!</p>
| [
{
"answer_id": 74193249,
"author": "Leon",
"author_id": 18737438,
"author_profile": "https://Stackoverflow.com/users/18737438",
"pm_score": -1,
"selected": false,
"text": "has_many"
},
{
"answer_id": 74195850,
"author": "BenFenner",
"author_id": 14837782,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10462011/"
] |
74,192,124 | <p>I am trying to enable multiple uploads on the PrimeNG component for angular. And based on their documentation <a href="https://www.primefaces.org/primeng/fileupload" rel="nofollow noreferrer">Upload Component Documentation</a> I can see that we have to use a property "Multiple" to enable the multiple upload functionality. However, when I use the property given, I get an error below :</p>
<p>""</p>
<p>Below is my code :</p>
<pre><code><div class="card">
<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple" accept=".zip, .fap">
</p-fileUpload>
</code></pre>
<p>I also tried setting the multiple variable to true in the component.ts file but it didn't work for me.</p>
<pre><code>export class UploadComponent implements OnInit {
multiple: boolean ;
constructor() { }
ngOnInit(): void {
this.multiple = true;
}
}
</code></pre>
<p>Can I know what is my mistake?</p>
| [
{
"answer_id": 74193249,
"author": "Leon",
"author_id": 18737438,
"author_profile": "https://Stackoverflow.com/users/18737438",
"pm_score": -1,
"selected": false,
"text": "has_many"
},
{
"answer_id": 74195850,
"author": "BenFenner",
"author_id": 14837782,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20328812/"
] |
74,192,136 | <p>I have a question from php and I'm not expert in php.</p>
<p>1.I have html page with one form include a text box and submit button .</p>
<p>2.I have a static target url like this : <a href="https://example.com/invoice/XXXXXXXXXXXXXX" rel="nofollow noreferrer">https://example.com/invoice/XXXXXXXXXXXXXX</a></p>
<p>XXXXXXXXXXXXXX is just numbers and has 14 characters.</p>
<p>*** What I need is that my customer enter its 14 characters number in input text form and when it submit , goes to target url.I want to check input form for entry numbers too.</p>
<p>I make a sample form like this but not work:</p>
<pre><code> <form action="https://example.com/invoice" class="pey-form" method="get">
<input type="text" id="peyid" name="peyid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="14" ><br><br>
<input type="submit" value="submit">
</form>
</code></pre>
<p>What can I do?</p>
| [
{
"answer_id": 74193249,
"author": "Leon",
"author_id": 18737438,
"author_profile": "https://Stackoverflow.com/users/18737438",
"pm_score": -1,
"selected": false,
"text": "has_many"
},
{
"answer_id": 74195850,
"author": "BenFenner",
"author_id": 14837782,
"author_prof... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1135195/"
] |
74,192,142 | <p>In my example the result should be 3 but it shows me 0.
Count, if in</p>
<p>A:A = 1 AND B:B = (3 or 4 or 5).</p>
<p>I was trying something like that but it doesnt work:</p>
<p>=COUNTIFS(A:A; 1; B:B; OR(B=3;B=4;B=5))</p>
<p><a href="https://i.stack.imgur.com/8dR9K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8dR9K.png" alt="enter image description here" /></a></p>
<p>------------------------ EDIT:</p>
<p>Let's say I have one more colum with characters:</p>
<p><a href="https://i.stack.imgur.com/crH0M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/crH0M.png" alt="enter image description here" /></a></p>
<p>And I want to count only the character with "a".</p>
| [
{
"answer_id": 74192244,
"author": "Ike",
"author_id": 16578424,
"author_profile": "https://Stackoverflow.com/users/16578424",
"pm_score": 1,
"selected": false,
"text": "=SUM(COUNTIFS(A2:A10,1,B2:B10,{3,4,5}))"
},
{
"answer_id": 74192256,
"author": "Mayukh Bhattacharya",
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17217064/"
] |
74,192,153 | <p>I am trying to generate url based on the <code>params</code> data</p>
<p>Here is the code:</p>
<pre><code>const Feeds = () => {
const [url, setUrl] = useState("");
useEffect(() => {
switch (params.category) {
case "news_National":
setUrl("http://localhost:8090/newsOnAir/national");
break;
case "news_International":
setUrl("http://localhost:8090/newsOnAir/international");
break;
case "XYZ":
navigate("/home");
break;
...........
...........}
axios.get(url)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
},[params.category])
return (........)
}
</code></pre>
<p>But the problem occurs when the <code>get request</code> is made to the previous URL state data. When a <code>get request</code> is made at that time the old data persists then the state is changed.</p>
<p>I cannot eliminate the use of <code>useEffect</code> since the switch case has <code>navigate</code> logic for some cases.</p>
<p>Please guide me on how to overcome this issue.</p>
| [
{
"answer_id": 74192230,
"author": "A.Vinuela",
"author_id": 9095818,
"author_profile": "https://Stackoverflow.com/users/9095818",
"pm_score": -1,
"selected": false,
"text": "setUrl(url, () => {\n //url is now updated with the right value\n});\n"
},
{
"answer_id": 74192246,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17348251/"
] |
74,192,163 | <p>Windows 10 is consuming all free memory when <code>docker desktop</code> is installed and <code>hyper-v</code> is on. I don't have any container running right now but memory usage is around 99%. I have 24GB of RAM on the system.</p>
<p>If I reboot the system, memory usage eventually gets to 99% after sometime (no containers are running).</p>
<p>If I disable Hyper-V then the memory usage always below 50%. But I need it enabled so I can use Docker desktop.</p>
<p>Is there anything that can be done to reduce the memory usage when docker desktop isn't running? I've already tried <code>.wslconfig</code> and <code>wsl --shutdown</code> but still memory usages is 99%.</p>
<p>Task Manager:</p>
<p>The process tab doesn't show anything that's consuming memory.</p>
<p><a href="https://i.stack.imgur.com/12jKu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/12jKu.png" alt="enter image description here" /></a></p>
<p>RamMap:</p>
<p><a href="https://i.stack.imgur.com/x1Li2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x1Li2.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74192230,
"author": "A.Vinuela",
"author_id": 9095818,
"author_profile": "https://Stackoverflow.com/users/9095818",
"pm_score": -1,
"selected": false,
"text": "setUrl(url, () => {\n //url is now updated with the right value\n});\n"
},
{
"answer_id": 74192246,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19844993/"
] |
74,192,197 | <p>I want to calculate the monthly change of this serie which is already on a monthly basis. So my question is how I could calculate the change for each row (starting from the second row).</p>
<p><a href="https://i.stack.imgur.com/8mmMw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8mmMw.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74192418,
"author": "woshishui",
"author_id": 5442972,
"author_profile": "https://Stackoverflow.com/users/5442972",
"pm_score": 0,
"selected": false,
"text": " Calendar_Table = \n var startyear = year(min(datatable[Datum]))\n var endyear = year(max(datatable[Datum... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18196726/"
] |
74,192,199 | <p>I am trying to simulate an auction bid from a bidder which I know bids between 1250 and 2200, and most often bid 1700.</p>
<p>Is there any way to use the <code>randbetween()</code> for this type of problem with a most common value?</p>
| [
{
"answer_id": 74192324,
"author": "Dominique",
"author_id": 4279155,
"author_profile": "https://Stackoverflow.com/users/4279155",
"pm_score": 2,
"selected": false,
"text": "values_array=[1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 10] // value \"5\" is three times more probable to be picked.\nvalu... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329034/"
] |
74,192,209 | <p>I have a csv file with errors. Some rows have 4 separators (;), while most part of the rows have 5 separators (;). The reason why I have sometimes 4 separators is because sometimes the 2nd column is missing.</p>
<p>Example:</p>
<pre><code>var1;var2;var3;var4;var5
1;10;john;40;56
2;mary;34;78
3;90.0;smith;52;45
</code></pre>
<p>If I import the csv file:</p>
<pre><code>import pandas as pd
df=pd.read_csv('myfile.csv', sep=";")
</code></pre>
<p>I obtain the dataframe:</p>
<pre><code>var1 var2 var3 var4 var5
1 10 john 40 56
2 mary 34 78
3 90.0 smith 52 45
</code></pre>
<p>and I want:</p>
<pre><code>var1 var2 var3 var4 var5
1 10 john 40 56
2 NaN mary 34 78
3 90.0 smith 52 45
</code></pre>
<p>Maybe I could split the dataframe into two parts (one with 5 ";", another with 4 ";") and append in the end.
I started with the code:</p>
<pre><code>import csv
with open('myfile.csv',newline='') as fin, open('output.csv','w',newline='') as fout:
reader = csv.reader(fin)
writer = csv.writer(fout)
for row in reader:
if len(row) > 4:
writer.writerow(row)
</code></pre>
<p>but I obtain the error: "line contains NUL".</p>
| [
{
"answer_id": 74192277,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "shift"
},
{
"answer_id": 74192416,
"author": "Daweo",
"author_id": 10785975,
"author_profile": ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16384503/"
] |
74,192,226 | <p>from <strong>just two dicts(a, c)</strong>, I need to find term_wMca that just gives:
<strong>xA * xB * xc * W_ABC</strong>. In fact I need to leave repeated ones like W_AAC, W_BBC, just ternary ones without repeat.when bigger dicts are entered by user just ternary should be calculated in term_wMca .
Is there any way to do that??</p>
<pre><code>import sympy as sp
a = {'A': 1}
c = {'B': 1, 'C': 1}
term_wMca = 0
for k in a:
for j in c:
for l in c:
term_wMca += sp.symbols(f'x{str(k)}') * sp.symbols(f'x{str(j)}') *
sp.symbols(f'x{str(l)}') *sp.symbols(f'W_{str(l)}{str(j)}{str(k)}')
print(term_wMca)
</code></pre>
| [
{
"answer_id": 74192437,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
"author_profile": "https://Stackoverflow.com/users/4727702",
"pm_score": 1,
"selected": false,
"text": "for-loop"
},
{
"answer_id": 74223530,
"author": "user19396094",
"author_id": 19396094,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19396094/"
] |
74,192,238 | <p>If the system theme is light and the app theme is dark, the actionbar items are dark when the app startup. (left picture)
When I reload the dark theme again from the in-app settings, the actionbar items are light (as I want) (right picture). This problem only happens in MainActivity.
How can fix this problem?</p>
<p><a href="https://i.stack.imgur.com/wS728.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wS728.png" alt="enter image description here" /></a></p>
<p>MainActivity.java</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
PreferenceUtils.setTheme(this);
setContentView(R.layout.activity_main);
if (getSupportActionBar() != null) {
this.getSupportActionBar().setElevation(0);
}
setTitle("Sample App");
MobileAds.initialize(this, initializationStatus -> {});
FrameLayout adContainerView = findViewById(R.id.ad_view);
AdsUtils.loadBannerAd(this, adContainerView);
drawerLayout = findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_drawer_open, R.string.nav_drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
drawerToggle.syncState();
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
.
.
.
</code></pre>
<p>PreferenceUtils.java</p>
<pre><code>public class PreferenceUtils {
public static final String LIGHT_MODE = "light";
public static final String DARK_MODE = "dark";
public static void setTheme(Activity activity) {
switch (PreferenceManager.getDefaultSharedPreferences(activity).getString("pref_key_theme"), "")) {
case LIGHT_MODE: {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
} case DARK_MODE: {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
} default: {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
break;
}
}
}
}
</code></pre>
<p>activity_main.xml</p>
<pre><code><androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false"
tools:context=".MainActivity"
tools:openDrawer="start">
<RelativeLayout
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="?attr/colorAccent"
app:tabSelectedTextColor="?android:textColorPrimary"
app:tabTextColor="?android:textColorSecondary"
app:tabMode="fixed" />
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
</code></pre>
<p>themes.xml</p>
<pre><code><resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.SampleApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/red_800</item>
<item name="colorPrimaryVariant">@color/red_900</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/red_700</item>
<item name="colorSecondaryVariant">@color/red_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
</style>
</resources>
</code></pre>
<p>themes-night.xml</p>
<pre><code><resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.SampleApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/dark_grey_900</item>
<item name="colorPrimaryVariant">@color/black</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/blue_200</item>
<item name="colorSecondaryVariant">@color/blue_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
</style>
</resources>
</code></pre>
<p>manifest</p>
<pre><code><application
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:theme="@style/Theme.SampleApp">
<activity android:name=".MainActivity" android:configChanges="locale|orientation|screenSize|keyboardHidden|uiMode" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</code></pre>
<p><strong>EDIT - 30.10.2022</strong></p>
<p>The problem was fixed when I moved the "MobileAds.initialize(this, initializationStatus -> {});"" line to the top.</p>
<pre><code>protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MobileAds.initialize(this, initializationStatus -> {});
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
PreferenceUtils.setTheme(this);
setContentView(R.layout.activity_main);
if (getSupportActionBar() != null) {
this.getSupportActionBar().setElevation(0);
}
setTitle("Sample App");
</code></pre>
| [
{
"answer_id": 74192437,
"author": "Yevhen Kuzmovych",
"author_id": 4727702,
"author_profile": "https://Stackoverflow.com/users/4727702",
"pm_score": 1,
"selected": false,
"text": "for-loop"
},
{
"answer_id": 74223530,
"author": "user19396094",
"author_id": 19396094,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8523394/"
] |
74,192,240 | <p>I have a class with a public attribute created_at, that will stored the date of a current time, but when I check what type of object it is i says it is a string:</p>
<pre><code>def __init__(self, *args, **kwargs):
"""Instantiation Method"""
if not kwargs:
self.id = uuid4()
self.created_at = datetime.now().isoformat()
self.updated_at = datetime.now().isoformat()
</code></pre>
<p>When I check what type of object it i I get the following:</p>
<pre><code>t = Model()
print(type(t.created_at))
</code></pre>
<p>Output:</p>
<pre><code><class 'str'>
</code></pre>
<p>It should be a datetime object but it says it is a string, is it because of the <code>isoformat()</code> ?</p>
| [
{
"answer_id": 74192343,
"author": "imburningbabe",
"author_id": 17781468,
"author_profile": "https://Stackoverflow.com/users/17781468",
"pm_score": 0,
"selected": false,
"text": ".isoformat()"
},
{
"answer_id": 74192348,
"author": "Niviral",
"author_id": 8784383,
"au... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19214678/"
] |
74,192,272 | <p>In C when you define a string using a char pointer (technically you are defining a pointer variable), it creates an array of the characters in a read-only segment of memory, then returns a pointer to it. That means you should not be able to modify it since it is a constant. If you wanted to modify it you should use a char array instead or use malloc.</p>
<p>But for some reason I am actually able to change the string, how is this even possible?</p>
<pre><code>#include <stdio.h>
int main() {
// The string "Hello" is a read-only literal (formally its type is const char[5])
char * msg = "Hello";
msg = "New string"; // why / how does this work?
printf("%s \n", msg); // New string
}
</code></pre>
<p>But at the same time this does not work (which makes sense)</p>
<pre><code>#include <stdio.h>
int main() {
char * msg = "Hello";
*(msg + 1) = 'a'; // Error: segmentation fault
*(msg + 1) = "a"; // Error: segmentation fault
printf("%s \n", msg);
}
</code></pre>
| [
{
"answer_id": 74192620,
"author": "0___________",
"author_id": 6110094,
"author_profile": "https://Stackoverflow.com/users/6110094",
"pm_score": 0,
"selected": false,
"text": "\"Hello\""
},
{
"answer_id": 74192898,
"author": "chrslg",
"author_id": 20037042,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9008233/"
] |
74,192,296 | <p>I wrote this code to calculate the integral in time of:
Q = (Q_max*(1 - (time/t_0 - 1)**2))
which I derived analytically.</p>
<pre><code>import numpy as np
Q_max = 400 # W m-2
t_0 = 6*3600 # seconds
dt = 60 # seconds
time = np.arange(0,2*t_0,dt)
Q_integral_A = Q_max*((time)**2/(t_0) - (time)**3/(3*(t_0)**2))
</code></pre>
<p>However, I found that Q_integral_A gives the wrong solution. After trying a lot of stuff, I found out that doing the following leads to the right solution (dividing the second "time" by 1):</p>
<pre><code>Q_integral_B = Q_max*((time)**2/(t_0) - (time/1)**3/(3*(t_0)**2))
</code></pre>
<p>What is happening here? Why is there a difference between Q_integral_A and Q_integral_B?</p>
<p><a href="https://i.stack.imgur.com/vDsS9.png" rel="nofollow noreferrer">screenshot of output</a></p>
<p>Versions used:
Python 3.8.5
Numpy 1.20.3
Spyder 4.2.5</p>
| [
{
"answer_id": 74192515,
"author": "JosephThePatrician",
"author_id": 14768111,
"author_profile": "https://Stackoverflow.com/users/14768111",
"pm_score": 3,
"selected": true,
"text": "time"
},
{
"answer_id": 74192596,
"author": "juanpa.arrivillaga",
"author_id": 5014455,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13404616/"
] |
74,192,304 | <p>Does anyone know how secure user spaces *USRSPC are in the event of a power outage?</p>
<p>I use user spaces to provide last number issued on a per-file basis. I use so-called machine-code API to prevent the same number being issue twice. I have found duplicates caused by the user space not being saved to disc prior to re-IPL.</p>
<p>It would not appear that user spaces are eligible for journaling. Or does anyone know of a way that I could journal each time the last number issued is incremented?</p>
<p>Regards,
Frank Marshall</p>
| [
{
"answer_id": 74197989,
"author": "RockBoro",
"author_id": 5484737,
"author_profile": "https://Stackoverflow.com/users/5484737",
"pm_score": 1,
"selected": true,
"text": " PGM\n\n DCL VAR(&USRSPC) TYPE(*CHAR) LEN(20)\n dcl &start *int\n ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20166354/"
] |
74,192,309 | <p>I know that this MariaDB version 5.5.68 is really out of date, but I have to stay with this old version for a while.</p>
<p>Is there a way to prevent toxic selects, possibly blocking MyISAM tables for a longer time (minutes)? The thing is that the select creates a READ BLOCK on the whole MyISAM table and further inserts wait until they're all gone. So the long running select starts to block the system.</p>
<p>Take this example table:</p>
<pre><code>CREATE TABLE `tbllog` (
`LOGID` bigint unsigned NOT NULL auto_increment,
`LOGSOURCE` smallint unsigned default NULL,
`USERID` int unsigned default NULL,
`LOGDATE` datetime default NULL,
`SUBPROVIDERID` int unsigned default NULL,
`ACTIONID` smallint unsigned default NULL,
`COMMENT` varchar(255) default NULL,
PRIMARY KEY (`LOGID`),
KEY `idx_LogDate` (`LOGDATE`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code></pre>
<p>The following select works fine until less than 1 Mio entries in the table (the customers set the date range):</p>
<pre><code>SELECT *
FROM tbllog
WHERE logdate BETWEEN '2021-01-01 00:00:00' AND '2022-10-25 00:00:00'
AND subproviderid=1
ORDER BY logid
LIMIT 500;
</code></pre>
<p>But it becomes toxic if there are 10 Mio entries or more in the table. Then it starts to run for minutes, consumes a lot of memory and starts blocking the app.</p>
<p>This is the query plan with ~600.000 entries in the table:</p>
<pre><code>+------+-------------+--------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+-------------+--------+-------+---------------+---------+---------+------+------+-------------+
| 1 | SIMPLE | tbllog | index | idx_LogDate | PRIMARY | 8 | NULL | 624 | Using where |
+------+-------------+--------+-------+---------------+---------+---------+------+------+-------------+
</code></pre>
<p>The thing is, that I need to know if this becomes toxic or not before execution. So maybe I can warn the user that this might block the system for a while or even deny execution.</p>
<p>I know that InnoDB might not have this issue, but I don't know the drawbacks of a switch yet and I think it might be best to stay for the moment.</p>
<p>I tried to do a simple <code>SELECT COUNT(*) FROM tbllog WHERE logdate BETWEEN '2021-01-01 00:00:00' AND '2022-10-25 00:00:00' AND subproviderid=1</code> before (removing LIMIT and ORDER BY), but it is not really much faster than the real query and produces double the load in the worst case.</p>
<p>I also considered a worker thread (<a href="https://stackoverflow.com/a/13726326/6613909">like mentioned here</a>). But this is a relevant change to the whole system, too. InnoDB would be less impact I think.</p>
<p>Any ideas about this issue?</p>
| [
{
"answer_id": 74193657,
"author": "O. Jones",
"author_id": 205608,
"author_profile": "https://Stackoverflow.com/users/205608",
"pm_score": 0,
"selected": false,
"text": "CREATE INDEX sub_date_logid ON tbllog (subproviderid, logdate, logid);\n"
},
{
"answer_id": 74196333,
"au... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613909/"
] |
74,192,346 | <p>I tried to look up the answer on the Internet and did not find it, maybe I typed my query wrong on the Internet.</p>
<p>Can you tell me how to crop a 3:4 photo? I can't find the function to crop it. Please share?</p>
| [
{
"answer_id": 74192591,
"author": "udi",
"author_id": 11905533,
"author_profile": "https://Stackoverflow.com/users/11905533",
"pm_score": 1,
"selected": false,
"text": "func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage? \n... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19726662/"
] |
74,192,396 | <p>I'm trying to create a trigger for updating some columns of a record after creating or updating the record.</p>
<p>There my code:</p>
<pre><code>CREATE OR REPLACE TRIGGER "TRIGGER_UPDATE_CONTRACTOR_LOT"
AFTER INSERT OR UPDATE ON "CONTRACTOR_LOT"
FOR EACH ROW
DECLARE
CONTRACT_LOT_LABEL VARCHAR2(255 BYTE);
CONTRACTOR_LABEL VARCHAR2(200 BYTE);
BEGIN
SELECT LABEL INTO CONTRACT_LOT_LABEL FROM LOT_T WHERE ID = :NEW.LOT_ID;
SELECT CONTRACTOR INTO CONTRACTOR_LABEL FROM CONTRACTOR_T WHERE ID = :NEW.CONTRACTOR_ID;
UPDATE CONTRACTOR_LOT
SET LABEL = CONTRACT_LOT_LABEL || ':' || CONTRACTOR_LABEL,
FRAMEWORK_CONTRACT_NUMBER_LABEL = :NEW.ORDER || ':' || CONTRACT_LOT_LABEL || :NEW.FRAMEWORK_CONTRACT_NUMBER
WHERE ID = :NEW.ID;
END;
</code></pre>
<p>I get an error ORA-04091 (mutation)
I tried to add <code>PRAGMA AUTONOMOUS_TRANSACTION;</code> and I get the error ORA-00060 (deadlock detected while waiting for resource)
So I add <code>COMMIT;</code> after the update, but it's still the same issue.</p>
<p>Could you help me please with that?</p>
| [
{
"answer_id": 74192591,
"author": "udi",
"author_id": 11905533,
"author_profile": "https://Stackoverflow.com/users/11905533",
"pm_score": 1,
"selected": false,
"text": "func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage? \n... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4098175/"
] |
74,192,400 | <p>I have installed Ventura, the latest version of macOS(13), and would like to have a stable version of Xcode (e.g. 13.4.1) running, but it says "The version of Xcode installed on this Mac is not compatible with macOS Ventura"</p>
<p>Is there any way to run Xcode on Ventura?</p>
<p><a href="https://i.stack.imgur.com/3okME.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3okME.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74192401,
"author": "Hassan",
"author_id": 19500804,
"author_profile": "https://Stackoverflow.com/users/19500804",
"pm_score": 6,
"selected": true,
"text": "Applications Folder"
},
{
"answer_id": 74500488,
"author": "fredpi",
"author_id": 4355141,
"auth... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19500804/"
] |
74,192,424 | <p>I am new to JNI and trying to muddle my way through. Please can someone point me in the direction to do the following in JNI. I am a bit out of my depth here, Can JNI handle Byte Arrays. Also were is the best places to find JNI examples.</p>
<p>This is the JAVA code I want to convert</p>
<pre><code>ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(key1);
outputStream.write(key2);
byte[] key3 = outputStream.toByteArray();
</code></pre>
<p>Thank you in advance</p>
<p>Rob</p>
| [
{
"answer_id": 74200773,
"author": "Botje",
"author_id": 1548468,
"author_profile": "https://Stackoverflow.com/users/1548468",
"pm_score": 1,
"selected": false,
"text": "jclass cls_BAOS = env->FindClass(\"java/io/ByteArrayOutputStream\");\njmethodID ctr_BAOS = env->GetMethodID(cls_BAOS, ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5826242/"
] |
74,192,428 | <p>I am working on nextjs/reactjs project. I'd like to push it to GitHub and then deploy it on Vercel but when I run the command <em><strong>" git push -f origin master"</strong></em>, I get the following error:</p>
<pre><code>remote: warning: File .next/cache/webpack/client-development/1.pack is 51.79 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File .next/cache/webpack/client-development/10.pack is 85.61 MB; this is larger
than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File .next/cache/webpack/client-development/4.pack is 68.47 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File build/cache/webpack/client-development/6.pack is 58.71 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File .next/cache/webpack/client-development/33.pack is 58.47 MB; this is larger
than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File .next/cache/webpack/client-development/18.pack is 68.53 MB; this is larger
than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File .next/cache/webpack/client-production/11.pack is 57.80 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File .next/cache/webpack/client-development/36.pack is 70.37 MB; this is larger
than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File .next/cache/webpack/client-development/16.pack is 51.49 MB; this is larger
than GitHub's recommended maximum file size of 50.00 MB
remote: error: Trace: 03b58dddd7287425c8208146b851869685188308516370c77e3e662c5153ba87
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File build/cache/webpack/client-development/10.pack is 139.61 MB; this exceeds GitHub's file size limit of 100.00 MB
</code></pre>
<p>I've done some research, but I didn't find any solutions. Is there any solutions to Ignore Webpack in a way to not impact the website deployment ?</p>
| [
{
"answer_id": 74200773,
"author": "Botje",
"author_id": 1548468,
"author_profile": "https://Stackoverflow.com/users/1548468",
"pm_score": 1,
"selected": false,
"text": "jclass cls_BAOS = env->FindClass(\"java/io/ByteArrayOutputStream\");\njmethodID ctr_BAOS = env->GetMethodID(cls_BAOS, ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15023228/"
] |
74,192,433 | <p>I have this code.</p>
<pre class="lang-cs prettyprint-override"><code>DisplayTimeStamp = PredictionTableList
.Where(x => x.ContextTimestamp != null)
.Select(x => x.ContextTimestamp)
.FirstOrDefault();
</code></pre>
<p>It returns the first data of the table.
Sometimes <code>PredictionTableList</code> is null, how do I check for this and return the null value as "-"?</p>
| [
{
"answer_id": 74192466,
"author": "EduBic",
"author_id": 10529476,
"author_profile": "https://Stackoverflow.com/users/10529476",
"pm_score": 1,
"selected": false,
"text": "?"
},
{
"answer_id": 74192491,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20002160/"
] |
74,192,436 | <p>I am currently trying to mock jakarta.ws.rs.core.Response.</p>
<pre><code>@Mock
private Response response;
</code></pre>
<p>which is used in my test as</p>
<pre><code>when(response.getStatusInfo()).thenReturn(Response.Status.OK);
</code></pre>
<p>However, upon executing I get the following error message: <code>Mockito cannot mock this class: cla...</code></p>
<p>Upon further research, I came across an article from <a href="https://www.baeldung.com/junit-test-abstract-class" rel="nofollow noreferrer">Baeldung</a>. However, the article does not cover my use case where both the class and the method are abstract. How would I proceed? Do I need to create an implementation of the to-be-tested method?</p>
| [
{
"answer_id": 74192466,
"author": "EduBic",
"author_id": 10529476,
"author_profile": "https://Stackoverflow.com/users/10529476",
"pm_score": 1,
"selected": false,
"text": "?"
},
{
"answer_id": 74192491,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16317812/"
] |
74,192,461 | <p>I think I am repeating the same piece of code each time. Is there any way to shorten this code so that I do not have to rewrite it?</p>
<pre><code>router.get('/reports', async (req, res) => {
let filters = {};
if (req.query.y) filters['end_year'] = req.query.y.split(',');
if (req.query.t) filters['topic'] = req.query.t.split(',');
if (req.query.s) filters['sector'] = req.query.s.split(',');
if (req.query.r) filters['region'] = req.query.r.split(',');
if (req.query.src) filters['source'] = req.query.src.split(',');
const reports = await Report.find(filters);
});
</code></pre>
| [
{
"answer_id": 74192466,
"author": "EduBic",
"author_id": 10529476,
"author_profile": "https://Stackoverflow.com/users/10529476",
"pm_score": 1,
"selected": false,
"text": "?"
},
{
"answer_id": 74192491,
"author": "Yong Shun",
"author_id": 8017690,
"author_profile": "... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15046110/"
] |
74,192,472 | <p>I need to override the <code>shouldInterceptRequest</code> method of <code>WebViewClient</code> to <a href="https://developer.android.com/develop/ui/views/layout/webapps/load-local-content" rel="nofollow noreferrer">load in-app HTML content</a> following that guide.</p>
<p>Here's the repo with the reproducible code: <a href="https://github.com/datvm/DemoMauiWvClient" rel="nofollow noreferrer">GitHub</a>. I took a sample code from <a href="https://learn.microsoft.com/en-us/answers/questions/967507/how-to-set-custom-webviewclient-on-android-handler.html" rel="nofollow noreferrer">MS Q&A</a> as well:</p>
<pre class="lang-cs prettyprint-override"><code>// ...
.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<Microsoft.Maui.Controls.WebView, ProblemHandler2>();
});
// ...
internal class ProblemHandler2 : WebViewHandler
{
protected override Android.Webkit.WebView CreatePlatformView()
{
var wv = new Android.Webkit.WebView(Android.App.Application.Context);
wv.SetWebViewClient(new CustomWebClient());
return wv;
}
}
</code></pre>
<p>In the repo, I included 2 custom handlers:</p>
<ul>
<li><code>ProblemHandler2</code> is the exact snippet by the MSFT. I realized a problem: Setting MAUI <code>WebView</code>'s <code>Source</code> property no longer navigates the real Android WebView:</li>
</ul>
<pre class="lang-cs prettyprint-override"><code> WebViewHandler.Mapper.AppendToMapping("MyHandler", (handler, view) =>
{
#if ANDROID
var xWv = handler.PlatformView;
// For ProblemHandler2, this is needed to actually navigate:
xWv.LoadUrl("https://www.google.com/");
#endif
});
this.wv.Source = "https://www.google.com/";
</code></pre>
<ul>
<li><code>ProblemHandler1</code> uses the default result and adds a custom handler. This fixes the navigation problem, <strong>but</strong>, both problem have the same issue:</li>
</ul>
<p><strong><code>ShouldInterceptRequest</code> is never called</strong>. It is never called on anything even when I manually click a link to navigate. What am I missing? I am sure the <code>CustomWebClient</code> is correctly created and set.</p>
<p>I noticed none of the other callbacks works as well, for example:</p>
<pre class="lang-cs prettyprint-override"><code> public override void OnPageStarted(Android.Webkit.WebView view, string url, Bitmap favicon)
{
Debugger.Break();
Debug.WriteLine(url);
base.OnPageStarted(view, url, favicon);
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
Debugger.Break();
Debug.WriteLine(url);
base.OnPageFinished(view, url);
}
</code></pre>
<p>I also tried using <code>WebViewHandler.Mapping</code> but it also does not work:</p>
<pre class="lang-cs prettyprint-override"><code> WebViewHandler.Mapper.AppendToMapping("MyHandler", (handler, _) =>
{
#if ANDROID
handler.PlatformView.SetWebViewClient(new CustomWebClient());
#endif
});
</code></pre>
| [
{
"answer_id": 74233521,
"author": "FreakyAli",
"author_id": 7462031,
"author_profile": "https://Stackoverflow.com/users/7462031",
"pm_score": 2,
"selected": false,
"text": "CreatePlatform"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/653457/"
] |
74,192,495 | <p>I want to delete users that haven't activated their accounts when the activation token have expired, activation token expires after 30 minutes.</p>
<pre class="lang-py prettyprint-override"><code>from django.db.models.functions import Now
def delete_unactivated_users():
User = get_user_model()
expiry = User.date_joined + timedelta(seconds=1800)
unactivated_users = User.objects.filter(Q(Now()__gt=expiry) & (Q(is_active = False)))
for user in unactivated_users:
user.delete()
print('<<<User Deleted>>>')
user.save
</code></pre>
<p>I am getting a syntax error on line 5 of the code, I tried using</p>
<pre><code>unactivated_users = User.objects.filter(Q(expiry__lt=Now()) & (Q(is_active=False)))
</code></pre>
<p>but it didn't result in the same meaning. The problem seems to be the placing of <code>Now()</code> and <code>expiry</code> on line 5</p>
| [
{
"answer_id": 74192589,
"author": "AshSmith88",
"author_id": 20281564,
"author_profile": "https://Stackoverflow.com/users/20281564",
"pm_score": 0,
"selected": false,
"text": "Q"
},
{
"answer_id": 74192628,
"author": "Davit Tovmasyan",
"author_id": 5840704,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9342045/"
] |
74,192,526 | <p>We are moving from standalone docker containers architecture to K3s architecture. The current architecture uses a Nginx container to expose multiple uwsgi and websocket services (for django) that are running in different containers. I'm reading conflicting opinions on the internet over what approach should be used.</p>
<p>The options are:</p>
<ol>
<li>Nginx service of type LoadBalancer (Most conf from existing architecture can be reused)</li>
<li>Nginx-ingress (All conf from existing architecture will have to be converted to ingress annotations and ConfigMap)</li>
<li>Nginx-ingress + nginx service of type ClusterIP (Most conf from existing architecture can be reused, traffic coming into ingress will simply be routed to nginx service)</li>
</ol>
| [
{
"answer_id": 74192589,
"author": "AshSmith88",
"author_id": 20281564,
"author_profile": "https://Stackoverflow.com/users/20281564",
"pm_score": 0,
"selected": false,
"text": "Q"
},
{
"answer_id": 74192628,
"author": "Davit Tovmasyan",
"author_id": 5840704,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11721258/"
] |
74,192,536 | <p>I'm making a simple login with a checkbox. My sharedpreferences xml file does not contain the boolean statement at the very first login so the checkbox goes through as unchecked. For all users' first login, the checkbox value does not correctly reflect. I have to interact with the checkbox (click to check/uncheck) for it to work but after that, the succeeding tries work fine. What have I missed?</p>
<p><strong>MainActivity.java</strong></p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText lUsername = (EditText) findViewById(R.id.lUsername);
EditText lPassword = (EditText) findViewById(R.id.lPassword);
Button btnSignin = (Button) findViewById(R.id.btnSignin);
CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
btnSignin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
String username = lUsername.getText().toString();
String password = lPassword.getText().toString();
SharedPreferences preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);
String details = preferences.getString(username + password + "data", "invalid");
SharedPreferences.Editor editor = preferences.edit();
if (details == "invalid") {
Toast.makeText(MainActivity.this, "Invalid credentials", Toast.LENGTH_SHORT).show();
} else {
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(checkBox.isChecked()) {
editor.putBoolean("checked", true);
}else{
editor.putBoolean("checked", false);
}
editor.commit();
}
});
Intent displayScreen = new Intent(MainActivity.this, activity2.class);
startActivity(displayScreen);
}
}
});
</code></pre>
<p><strong>DisplayScreen.java</strong></p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.DisplayScreen);
SharedPreferences preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);
String username = preferences.getString("username", "invalid");
if(preferences.contains("checked") && preferences.getBoolean("checked",false) == true) {
String data = preferences.getString("data", "Hello senior " + username + "!");
TextView displayInfo = (TextView) findViewById(R.id.helloDisplay);
displayInfo.setText(data);
}else {
String data = preferences.getString("data", "Hello " + username + "!");
TextView displayInfo = (TextView) findViewById(R.id.helloDisplay);
displayInfo.setText(data);
}
}
</code></pre>
| [
{
"answer_id": 74192589,
"author": "AshSmith88",
"author_id": 20281564,
"author_profile": "https://Stackoverflow.com/users/20281564",
"pm_score": 0,
"selected": false,
"text": "Q"
},
{
"answer_id": 74192628,
"author": "Davit Tovmasyan",
"author_id": 5840704,
"author_p... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16839640/"
] |
74,192,550 | <p>I am getting an error as object cannot be cast from DBNull to other types when i add pic1 in this code. The pic1 is from img table in database.</p>
<pre class="lang-cs prettyprint-override"><code>public List<RentModel>GetData()
{
List<RentModel> dataList = new List<RentModel>();
SqlCommand command = new SqlCommand("SELECT * FROM rent FULL OUTER JOIN img ON rent.id= img.r_id",con);
SqlDataAdapter sqlda = new SqlDataAdapter(command);
DataTable dtdata= new DataTable();
con.Open();
sqlda.Fill(dtdata);
con.Close();
foreach(DataRow dr in dtdata.Rows)
{
dataList.Add(new RentModel
{
id = Convert.ToInt32(dr["ID"]),
tittle = dr["tittle"].ToString(),
descrip = dr["descrip"].ToString(),
area = Convert.ToInt32(dr["area"]),
areaUnit = dr["areaUnit"].ToString(),
bathroom = dr["bathroom"].ToString(),
bedroom = dr["bedroom"].ToString(),
province= dr["province"].ToString(),
city= dr["city"].ToString(),
stadress = dr["stadress"].ToString(),
furnished = dr["furnished"].ToString(),
p_type = dr["p_type"].ToString(),
price = dr["price"].ToString(),
pic1 = dr["pic1"].ToString(),
});
}
</code></pre>
| [
{
"answer_id": 74192797,
"author": "Can Bilgin",
"author_id": 5592556,
"author_profile": "https://Stackoverflow.com/users/5592556",
"pm_score": 0,
"selected": false,
"text": "dataList.Add(new RentModel\n{\n ....,\n pic1 = (dr[\"pic1\"] == DBNull.Value)? string.Empty : dr[\"pic1\"].... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12243242/"
] |
74,192,571 | <p>I am encrypting a file and it encrypts to a folder named mark but I want the file to encrypt and be placed in a sub folder named Kevin. Code is below:</p>
<pre class="lang-py prettyprint-override"><code>with open("encrypted_" + filename + '.txt', "wb") as ef:
ef.write(encrypted_file)
</code></pre>
<p>That encrypts the file but places it in the same folder. How can i edit this so it moves to the Kevin folder after encryption. I am using Python.</p>
<p>Thanks</p>
| [
{
"answer_id": 74192797,
"author": "Can Bilgin",
"author_id": 5592556,
"author_profile": "https://Stackoverflow.com/users/5592556",
"pm_score": 0,
"selected": false,
"text": "dataList.Add(new RentModel\n{\n ....,\n pic1 = (dr[\"pic1\"] == DBNull.Value)? string.Empty : dr[\"pic1\"].... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10691516/"
] |
74,192,582 | <p>I've got to tables merged in SQL. Now i want the output to just show me all rows with the same ID's when a cell contains a certain text.
This probably is peanuts, but I just can't seem to find the correct syntax using SQL Express 2013.</p>
<p>Example :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">ID</th>
<th style="text-align: left;">ARTICLE</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">Coke</td>
</tr>
<tr>
<td style="text-align: left;">1</td>
<td style="text-align: left;">Coke Light</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">Coke</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">Coke Light</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">Fanta</td>
</tr>
</tbody>
</table>
</div>
<p>The result should only show all the ID rows where one of them contains a Fanta. So in this case :</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">ID</th>
<th style="text-align: left;">ARTICLE</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">Coke</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">Coke Light</td>
</tr>
<tr>
<td style="text-align: left;">2</td>
<td style="text-align: left;">Fanta</td>
</tr>
</tbody>
</table>
</div>
<p>The example is a simplified version of the original table. And the query needs to be kept as simple as possible, due to limitations of the external program that needs to run the query.</p>
| [
{
"answer_id": 74192710,
"author": "ahmed",
"author_id": 12705912,
"author_profile": "https://Stackoverflow.com/users/12705912",
"pm_score": 2,
"selected": true,
"text": "SELECT T.ID, T.ARTICLE\nFROM table_name T\nJOIN\n (SELECT ID FROM table_name WHERE ARTICLE ='Fanta') D\nON T.ID=D.ID... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329157/"
] |
74,192,587 | <p>How can I access the content inside the highlighted class (image bellow)? I am trying to print all comments from a TikTok video (<a href="https://www.tiktok.com/@adhdvision/video/7156974534078385413?is_from_webapp=v1&item_id=7156974534078385413" rel="nofollow noreferrer">url here</a>), but I haven't manage to do it. I have tried several different approaches (listed bellow), but they always retrieved empty variables. I tested:</p>
<p>With bs4:</p>
<pre><code>url_ = urllib.request.urlopen(url)
content = url_.read()
soup = BeautifulSoup(content, 'lxml')
# 1.
containers = soup.find_all('p',{'data-e2e':'comment-level-1'})
# or 2. (to access the container and then somehow access the sub-container)
containers = soup.findAll('div',attrs={"class":"content-tiktok-1mf23fd-DivContentContainer e1g2efjf1"})
</code></pre>
<p>With Selenium:</p>
<pre><code>browser = webdriver.Chrome(executable_path=path, options=options)
browser.get(url)
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
comm = browser.find_elements_by_class_name("tiktok-q9aj5z-PCommentText e1g2efjf6")
</code></pre>
<p>I managed to make it work with Selenium using Xpath, but this thing changes among container to container, so it does not work because a have a lot of this "boxes".</p>
<p>This works with Selenium for only one comment box:</p>
<pre><code>browser = webdriver.Chrome(executable_path=path, options=options)
browser.get(url)
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
element = browser.find_element_by_xpath('//*[@id="7156976296152449797"]/div[1]/p[1]')
print(element.text)
</code></pre>
<p><a href="https://i.stack.imgur.com/OCGRM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OCGRM.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74192710,
"author": "ahmed",
"author_id": 12705912,
"author_profile": "https://Stackoverflow.com/users/12705912",
"pm_score": 2,
"selected": true,
"text": "SELECT T.ID, T.ARTICLE\nFROM table_name T\nJOIN\n (SELECT ID FROM table_name WHERE ARTICLE ='Fanta') D\nON T.ID=D.ID... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18333558/"
] |
74,192,590 | <p>I have two scripts, let's say "reading" and "calculation".
Script "reading" has inside of it several functions, and reads data from csv files and creates pandas dataframes. Let's say it defines variable "dataframe_1".
Script "calculation" makes some calculation with dataframes, which were defined in script "reading".</p>
<p>I want to run script "calculation" after I ran script "reading", and use its results somehow. How can I access that variable (dataframe_1) inside script "calculation", after it was defined in script "reading"?</p>
<p>I assume during execution of script "reading", dataframe_1 is stored in operating memory, how can I access it?</p>
<p>If I do it like that, it reads dataframe_1 again, instead of just accessing the result of reading, which are stored in memory?</p>
<pre><code>from reading import dataframe_1
</code></pre>
| [
{
"answer_id": 74192710,
"author": "ahmed",
"author_id": 12705912,
"author_profile": "https://Stackoverflow.com/users/12705912",
"pm_score": 2,
"selected": true,
"text": "SELECT T.ID, T.ARTICLE\nFROM table_name T\nJOIN\n (SELECT ID FROM table_name WHERE ARTICLE ='Fanta') D\nON T.ID=D.ID... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329165/"
] |
74,192,603 | <p>I have developed an Angular/.Net Core 6 where authorized users can insert new products.</p>
<p>When an authorized user creates a new product, he's the only user with the "Editor" role to be able to change it and in that case an "Edit" button is visible.
For the time being, each product contains the ID of the user who created it.</p>
<p>First question, it is the best option or should I use claims to link Product and User?</p>
<p>Second question, regarding the display in Angular, I have 2 options</p>
<ol>
<li>My back end is returning all the products with a flag to indicate if each product can be edited by this user</li>
<li>My back end is returning all the products and I use an <code>*ngIf</code> in my Angular template to display the Edit button if the user associated with each product is the same as the user currently logged</li>
</ol>
<p>What is the best practice? I don't want to overcomplicate everything. Should it be handled backend or frontend?</p>
<p>Thank you</p>
| [
{
"answer_id": 74192710,
"author": "ahmed",
"author_id": 12705912,
"author_profile": "https://Stackoverflow.com/users/12705912",
"pm_score": 2,
"selected": true,
"text": "SELECT T.ID, T.ARTICLE\nFROM table_name T\nJOIN\n (SELECT ID FROM table_name WHERE ARTICLE ='Fanta') D\nON T.ID=D.ID... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3439959/"
] |
74,192,605 | <p>I am trying to get rid of AttributeError using mutiprocessing in python.
I found out that multiprocessing does not allow local target functions and a possible solution
would be to declare the local function I want to execute as a process with the global statement.
I found the solution in this site: <a href="https://www.pythonpool.com/cant-pickle-local-object/" rel="nofollow noreferrer">https://www.pythonpool.com/cant-pickle-local-object/</a>.
Unfortunately the solution provided by the website does not work and i still get the same error.
I understand that a working solution would be to directly declare the function i want to process
in the global scope, but the way I structured the code in my prject does not make this solution
affordable, are there ways to target the local function directly?</p>
<pre><code>import multiprocessing as mp
def main() -> None:
global func
def func() -> None:
print("Hello World")
process = mp.Process(target=func)
process.start()
if __name__ == "__main__":
main()
</code></pre>
| [
{
"answer_id": 74192710,
"author": "ahmed",
"author_id": 12705912,
"author_profile": "https://Stackoverflow.com/users/12705912",
"pm_score": 2,
"selected": true,
"text": "SELECT T.ID, T.ARTICLE\nFROM table_name T\nJOIN\n (SELECT ID FROM table_name WHERE ARTICLE ='Fanta') D\nON T.ID=D.ID... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329094/"
] |
74,192,616 | <p>So I have this example of a LINQ Query:</p>
<pre><code>var productsPerSupplier = from s in suppliers
join p in products
on s.Id equals p.SupplierId
into sp
select new
{
SupplierId = s.Id,
SupplierName = s.Name,
ProductCount = sp.Count()
};
</code></pre>
<p>How does the count function know to count the number of products for each supplier? What is the structure of sp table? Isn't it supposed to count all the rows in the table?</p>
<p>This is the result:
<a href="https://i.stack.imgur.com/OpLpD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OpLpD.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74192706,
"author": "dotNET",
"author_id": 1137199,
"author_profile": "https://Stackoverflow.com/users/1137199",
"pm_score": 2,
"selected": false,
"text": "into"
},
{
"answer_id": 74192783,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "ht... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17966645/"
] |
74,192,630 | <p>I want to show a count of a related table to the one building the query builder. The working native query is the following one:</p>
<pre><code>select id, name, (select count(*) from houses where status = 1 and street_id = s.id) as total from streets s;
</code></pre>
<p>In the former query I want to show the street info and also how many houses there are in each street.</p>
<p>I started the query builder like this</p>
<pre><code>$queryBuilder = $this->createQueryBuilder('s');
$queryBuilder
->select('
s.id as street_id, s.name as name')
</code></pre>
<p>But I don't know how to add this count. On another hand I tested this query natively with joins and it is very slow, so I would need to avoid them.</p>
<p>House and Street are both ORM Entities</p>
| [
{
"answer_id": 74192706,
"author": "dotNET",
"author_id": 1137199,
"author_profile": "https://Stackoverflow.com/users/1137199",
"pm_score": 2,
"selected": false,
"text": "into"
},
{
"answer_id": 74192783,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "ht... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4594263/"
] |
74,192,644 | <p>I have this piece of code:</p>
<pre><code> foreach (var customer in customers)
{
foreach (var notifier in this.notifiers)
{
notifyCustomer(notifier, customer);
}
}
</code></pre>
<p>Is it possible to do the same action using one foreach or Linq, or even in a more elegant way?</p>
| [
{
"answer_id": 74192706,
"author": "dotNET",
"author_id": 1137199,
"author_profile": "https://Stackoverflow.com/users/1137199",
"pm_score": 2,
"selected": false,
"text": "into"
},
{
"answer_id": 74192783,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "ht... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19486477/"
] |
74,192,655 | <p>Having the following dataframe:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">name</th>
<th style="text-align: center;">aaa</th>
<th style="text-align: center;">bbb</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">Mick</td>
<td style="text-align: center;">None</td>
<td style="text-align: center;">None</td>
</tr>
<tr>
<td style="text-align: center;">Ivan</td>
<td style="text-align: center;">A</td>
<td style="text-align: center;">C</td>
</tr>
<tr>
<td style="text-align: center;">Ivan-Peter</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">None</td>
</tr>
<tr>
<td style="text-align: center;">Juli</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">P</td>
</tr>
</tbody>
</table>
</div>
<p>I want to get two dataframes.</p>
<ul>
<li>One with values, where we have <strong>None</strong> in columns <code>aaa</code> and/or <code>bbb</code>, named <code>filter_nulls</code> in my code</li>
<li>One where we do not have <strong>None</strong> at all. <code>df_out</code> in my code.</li>
</ul>
<p>This is what I have tried and it does not produce the required dataframes.</p>
<pre><code>import pandas as pd
df_out = {
'name': [ 'Mick', 'Ivan', 'Ivan-Peter', 'Juli'],
'aaa': [None, 'A', '1', '1'],
'bbb': [None, 'C', None, 'P'],
}
print(df_out)
filter_nulls = df_out[df_out['aaa'].isnull()|(df_out['bbb'] is None)]
print(filter_nulls)
df_out = df_out.loc[filter_nulls].reset_index(level=0, drop=True)
print(df_out)
</code></pre>
| [
{
"answer_id": 74192706,
"author": "dotNET",
"author_id": 1137199,
"author_profile": "https://Stackoverflow.com/users/1137199",
"pm_score": 2,
"selected": false,
"text": "into"
},
{
"answer_id": 74192783,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "ht... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5448626/"
] |
74,192,665 | <p>I have an enum, <code>Angle</code>, which has two variants, <code>Degrees</code> and <code>Radians</code>. I wanted to implement <code>From</code> for these, but it doesn't let me:</p>
<pre><code>enum Angle {
Degrees(f64),
Radians(f64)
}
impl From<Angle> for Angle {
fn from(value: Angle) -> Self {
match value {
Angle::Degrees(deg) => Angle::Radians(deg / 180.0 * PI),
Angle::Radians(rad) => Angle::Degrees(rad / PI * 180.0)
}
}
}
</code></pre>
<p>which throws</p>
<pre><code>error[E0119]: conflicting implementations of trait `std::convert::From<Angle>` for type `Angle`
--> src\lib.rs:45:1
|
45 | impl From<Angle> for Angle {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `core`:
- impl<T> From<T> for T;
Some errors have detailed explanations: E0119, E0412, E0425.
For more information about an error, try `rustc --explain E0119`.
</code></pre>
<p>From what I can see there are three options for this:</p>
<ol>
<li>I clarify this to the compiler in some way</li>
<li>I add two separate functions <code>to_degrees</code> and <code>to_radians</code></li>
<li>I separate <code>Angle::Degrees</code> and <code>Angle::Radians</code> into two separate structs</li>
</ol>
<p>If 1 is not possible, which is preferred of 2 and 3?</p>
| [
{
"answer_id": 74192791,
"author": "Aleksander Krauze",
"author_id": 13078067,
"author_profile": "https://Stackoverflow.com/users/13078067",
"pm_score": 0,
"selected": false,
"text": "impl<T> From<T> for T"
},
{
"answer_id": 74192801,
"author": "E_net4 the comment flagger",
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19666101/"
] |
74,192,687 | <p>I am trying to <code>setState</code> to <code>q.content</code>. However, it logs as undefined and I'm not sure how I'm using e.target incorrectly. It logs <code>q.name</code> fine.</p>
<p>I have a button that onClick calls a function that sets the constants.</p>
<p>In the function I have:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> function handleDelete(e) {
e.preventDefault();
setDeleteItem(e.target.value);
setConfirmModal(true);
setDeleteContent(e.target.content);
setDeleteName(e.target.name);
console.log(e.target.content);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button
onClick={handleDelete}
value={q.id}
name={q.name}
content={q.content}
></code></pre>
</div>
</div>
</p>
<p>But it just doesn't seem to work.</p>
| [
{
"answer_id": 74192738,
"author": "Sampson",
"author_id": 54680,
"author_profile": "https://Stackoverflow.com/users/54680",
"pm_score": 2,
"selected": false,
"text": "e.target.value"
},
{
"answer_id": 74192937,
"author": "shurikation",
"author_id": 19407265,
"author_... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18472704/"
] |
74,192,733 | <p>I have the following dictionary and list:</p>
<pre><code>dict_ = {'one':['a','b','c','d','e','f'],
'two':['g','h','l','m'],
'three':['x','y','z'],
'four':['xx','yy']}
ls = ['a','x','c','h','l']
</code></pre>
<p>I need to loop through the dict values and check if the items in ls exist in dict values, if so I would like to return a new dict with key/pair values, as follows:</p>
<pre><code>new_dict = {'one':['a','c'],'two':['h','l'], 'three':['x']}
</code></pre>
| [
{
"answer_id": 74192777,
"author": "Mortz",
"author_id": 4248842,
"author_profile": "https://Stackoverflow.com/users/4248842",
"pm_score": 3,
"selected": true,
"text": "new_dict = {k: list(set(v) & set(ls)) for k, v in dct.items() if (set(v) & set(ls))}\n"
},
{
"answer_id": 74192... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16196618/"
] |
74,192,742 | <p>I have the following code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>err = {
"content-type": null,
phone: null,
firstName: null,
lastName: null,
email: null,
website: null,
supplier: null
}
console.log(Object.keys(err).some(key => key !== null))</code></pre>
</div>
</div>
</p>
<p>I learnt about the <code>.some</code> function from stackoverflow, but this is returning true. All the values are null, so I would expect it to return false.</p>
<p>I just need a way to check if any of the values are not null, then I know there are errors in the form.</p>
| [
{
"answer_id": 74192808,
"author": "Robin Hood",
"author_id": 16561638,
"author_profile": "https://Stackoverflow.com/users/16561638",
"pm_score": 3,
"selected": true,
"text": "Object.values()"
},
{
"answer_id": 74193359,
"author": "Ben Aston",
"author_id": 38522,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17699392/"
] |
74,192,779 | <p>Suppose I have this dataset and it had 2 NAN values in columns 'alcohol' and 3 NAN values in column 'magnesium'. They do not have NAN values, but suppose they did.</p>
<p>What lines of code might I use to get not only the mean of the appropriate column (alcohol mean for alcohol), but also fill/replace alcohol NAN values with this mean? The same for magnesium.</p>
<p>There are questions on stackoverflow regarding a mean that is a mean of the entire dataframe as opposed to the column in particular.</p>
<p>I know this may be possible with sklearn.impute and sklearn.preprocessing</p>
<pre><code>data = load_wine()
df = pd.DataFrame(data.data, columns=data.feature_names)
df['target'] = pd.Series(data.target)
</code></pre>
| [
{
"answer_id": 74192808,
"author": "Robin Hood",
"author_id": 16561638,
"author_profile": "https://Stackoverflow.com/users/16561638",
"pm_score": 3,
"selected": true,
"text": "Object.values()"
},
{
"answer_id": 74193359,
"author": "Ben Aston",
"author_id": 38522,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20317654/"
] |
74,192,806 | <p>I have Realtime database for android app, there were some data , multiple records , but I checked it today and no data is showing up and it shows just <strong>null</strong>, what is wrong and how can I fix this ?</p>
| [
{
"answer_id": 74192808,
"author": "Robin Hood",
"author_id": 16561638,
"author_profile": "https://Stackoverflow.com/users/16561638",
"pm_score": 3,
"selected": true,
"text": "Object.values()"
},
{
"answer_id": 74193359,
"author": "Ben Aston",
"author_id": 38522,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9542356/"
] |
74,192,807 | <p>this is an excerpt of what works</p>
<pre><code><xsl:output method="json" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="dsl" as="element()">
<epg lastBuildDate="10/4/2019 9:46:00 AM">
</epg>
</xsl:variable>
<xsl:variable name="output" as="map(*)*">
<xsl:apply-templates select="$dsl" mode="interpret"/>
</xsl:variable>
<xsl:sequence select="$output"/>
</xsl:template>
</code></pre>
<p>based on</p>
<p><a href="https://stackoverflow.com/questions/56446836/how-to-dynamically-change-xsloutput-method-attribute-value">How to dynamically change xsl:output method attribute value?</a></p>
<p>I want to dynamically select the output format, so I've tried (as a starting point), removing the top level output instruction and then using result-document</p>
<pre><code><xsl:template match="/">
<xsl:variable name="dsl" as="element()">
<epg lastBuildDate="10/4/2019 9:46:00 AM">
</epg>
</xsl:variable>
<xsl:variable name="output" as="map(*)*">
<xsl:apply-templates select="$dsl" mode="interpret"/>
</xsl:variable>
<xsl:result-document method="json" encoding="UTF-8" indent="yes">
<xsl:sequence select="$output"/>
</xsl:result-document>
</xsl:template>
</code></pre>
<p>this gives me (in java saxon 10.6),</p>
<pre><code>cannot serialise a map using this method
</code></pre>
<p>(let me create a complete example as suggested)</p>
<p>I've subsequently edited my example and it works, so I'm not too sure how this didnt work</p>
| [
{
"answer_id": 74192808,
"author": "Robin Hood",
"author_id": 16561638,
"author_profile": "https://Stackoverflow.com/users/16561638",
"pm_score": 3,
"selected": true,
"text": "Object.values()"
},
{
"answer_id": 74193359,
"author": "Ben Aston",
"author_id": 38522,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2088029/"
] |
74,192,813 | <p>Before anyone asks, I have read all of these questions and none of them fixed my issue: <a href="https://stackoverflow.com/questions/66952098/the-use-of-safeargs-in-android-studio-is-causing-an-error-and-i-cannot-build-the">1</a>, <a href="https://stackoverflow.com/questions/70937015/android-studio-bumblebee-unable-to-use-safeargs">2</a>, <a href="https://stackoverflow.com/questions/70376213/new-build-gradle-in-android-studio-bumblebee-2021-1-1-beta-5-error-adding-depe">3</a>, <a href="https://stackoverflow.com/questions/67602765/i-was-learning-build-your-first-android-app-see-below-link-and-using-android-s">4</a>, <a href="https://stackoverflow.com/questions/74054576/after-update-my-android-studio-dolphin-2021-3-1-xml-layout-preview-cant-sh">5</a>, <a href="https://stackoverflow.com/questions/71181410/gradle-applying-a-plugin-in-android-studio-safeargs-for-navigationbar">6</a>.</p>
<p>I am currently learning Android app development and I have been following through the <a href="https://developer.android.com/codelabs/build-your-first-android-app-kotlin#8" rel="nofollow noreferrer">first tutorial on the Android Developer site</a>.
I created my project using the "Basic Activity" template (as instructed).<br />
In step 5 on the page linked above, it says to enable safe args by doing the following:</p>
<blockquote>
<p>Open <strong>Gradle Scripts > build.gradle (Module: My First App)</strong>
Find the <code>dependencies</code> section in the <code>buildscript</code> section, and add the following lines after the other classpath entries:<br />
<code>def nav_version = "2.3.0-alpha02"</code><br />
<code>classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"</code></p>
<p>Open <strong>Gradle Scripts > build.gradle (Module: app)</strong>
Just below the other lines that begin with apply plugin add a line to enable SafeArgs:<br />
<code>apply plugin: 'androidx.navigation.safeargs.kotlin'</code></p>
<p>Android Studio should display a message about the Gradle files being changed. Click Sync Now on the right hand side.
After a few moments, Android Studio should display a message in the Sync tab that it was successful.</p>
<p>Choose Build > Make Project. This should rebuild everything so that Android Studio can find FirstFragmentDirections.</p>
</blockquote>
<p>Unfortunately, the "Basic Activity" template in my version of Android Studio (see below) doesn't seem to be structured in a way that supports the changes in the instructions.</p>
<pre><code>Android Studio Dolphin | 2021.3.1 Patch 1
Build #AI-213.7172.25.2113.9123335, built on September 30, 2022
Runtime version: 11.0.13+0-b1751.21-8125866 amd64
</code></pre>
<p>Firstly, it says to "find the dependencies section in the buildscript section".
In my <code>build.gradle (:app)</code> file (I'm not even sure if this is the right file), there is just a top-level dependencies section containing <code>implementation</code> entry. Adding a <code>classpath</code> entry doesn't seem correct.</p>
<p>Next, it says to add the <code>apply plugin</code> entry to my <code>(Module: app)</code> file "just below the other lines that begin with <code>apply plugin</code>". No such lines exist, which makes be suspect the tutorial is out of date.</p>
<hr />
<p>After a bit of searching, I came to the conclusion that I needed to add safeargs in a different way. In my <code>build.gradle</code> project file, I've made it look like so (this is the full file):</p>
<pre><code>plugins {
id 'com.android.application' version '7.3.1' apply false
id 'com.android.library' version '7.3.1' apply false
id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
id 'androidx.navigation.safeargs.kotlin' version '2.5.3' apply false // I added this
}
</code></pre>
<p>And the <strong>top</strong> of my <code>build.gradle</code> module file looks like this:</p>
<pre><code>plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id "androidx.navigation.safeargs.kotlin" // I added this
}
</code></pre>
<p>There are no other changes to the files.</p>
<p>Syncing works fine, but I run into issues when I try to rebuild (even if I clean first).
I find that I always get the error below, after the checkDebugDuplicateClasses check fails:</p>
<pre><code>Duplicate class javax.activation.ActivationDataFlavor found in modules jakarta.activation-api-1.2.1 (jakarta.activation:jakarta.activation-api:1.2.1) and javax.activation-1.2.0 (com.sun.activation:javax.activation:1.2.0)
Duplicate class javax.activation.CommandInfo found in modules jakarta.activation-api-1.2.1 (jakarta.activation:jakarta.activation-api:1.2.1) and javax.activation-1.2.0 (com.sun.activation:javax.activation:1.2.0)
Duplicate class javax.activation.CommandInfo$Beans found in modules jakarta.activation-api-1.2.1 (jakarta.activation:jakarta.activation-api:1.2.1) and javax.activation-1.2.0 (com.sun.activation:javax.activation:1.2.0)
[...]
Duplicate class org.xmlpull.v1.XmlPullParser found in the following modules: kxml2-2.3.0 (net.sf.kxml:kxml2:2.3.0), xmlpull-1.1.3.1 (xmlpull:xmlpull:1.1.3.1) and xpp3-1.1.4c (xpp3:xpp3:1.1.4c)
Duplicate class org.xmlpull.v1.XmlPullParserException found in the following modules: kxml2-2.3.0 (net.sf.kxml:kxml2:2.3.0), xmlpull-1.1.3.1 (xmlpull:xmlpull:1.1.3.1) and xpp3-1.1.4c (xpp3:xpp3:1.1.4c)
Duplicate class org.xmlpull.v1.XmlPullParserFactory found in the following modules: kxml2-2.3.0 (net.sf.kxml:kxml2:2.3.0), xmlpull-1.1.3.1 (xmlpull:xmlpull:1.1.3.1) and xpp3-1.1.4c (xpp3:xpp3:1.1.4c)
Duplicate class org.xmlpull.v1.XmlSerializer found in the following modules: kxml2-2.3.0 (net.sf.kxml:kxml2:2.3.0), xmlpull-1.1.3.1 (xmlpull:xmlpull:1.1.3.1) and xpp3-1.1.4c (xpp3:xpp3:1.1.4c)
Go to the documentation to learn how to Fix dependency resolution errors.
</code></pre>
<p>It is unclear what needs to be done from here. I am unable to run the app in the emulator at all because the build completely fails. Any suggestions would be appreciated.</p>
| [
{
"answer_id": 74192808,
"author": "Robin Hood",
"author_id": 16561638,
"author_profile": "https://Stackoverflow.com/users/16561638",
"pm_score": 3,
"selected": true,
"text": "Object.values()"
},
{
"answer_id": 74193359,
"author": "Ben Aston",
"author_id": 38522,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6366927/"
] |
74,192,833 | <p>After reading the Design Patterns book and looking at Builder pattern examples online, I have noticed that there are two different ways of returning the object in the final "build()" method. I was wondering what is the difference between:</p>
<p>Simply returning the <code>maze</code> we have been building</p>
<pre><code>public class MazeBuilderImpl implements MazeBuilder {
private Maze maze;
@Override
public MazeBuilder builder() {
maze = new Maze();
return this;
}
// adding rooms, doors etc.
@Override
public Maze build() {
return maze;
}
}
</code></pre>
<p>Passing the <code>maze</code> as a parameter in a constructor and returning that</p>
<pre><code>public class MazeBuilderImpl implements MazeBuilder {
private Maze maze;
@Override
public MazeBuilder builder() {
maze = new Maze();
return this;
}
// adding rooms, doors etc.
@Override
public Maze build() {
return new Maze(maze);
}
}
</code></pre>
| [
{
"answer_id": 74192996,
"author": "Michael",
"author_id": 1898563,
"author_profile": "https://Stackoverflow.com/users/1898563",
"pm_score": 3,
"selected": true,
"text": "MazeBuilder builder = new MazeBuilderImpl();\nMaze maze = builder.rooms(1).build();\nbuilder.rooms(2); // modifies th... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13426164/"
] |
74,192,860 | <p>I can't access functions of the <code>wrapper.vm</code> in the unit tests once my component become async on the top-level (needed to use <code><suspense></code> feature).</p>
<pre class="lang-html prettyprint-override"><code><script setup lang="ts">
const state = reactive({ text: '' });
// -------
// How it was before
const addition = '3'; // <-- This works
// This is what I want!!!!!
const addition = await Promise.resolve('3'); // <-- This "await" doesn't let me access `wrapper.vm.getText()` in unit tests (undefined)
// -------
function getText(): string {
return '12' + addition;
}
</script>
<template>
<section class="foo">
<button @click="getText()">{{ state.text }}</button>
</section>
</template>
</code></pre>
<p>This is how I'm trying to test <code>getText()</code>:</p>
<pre class="lang-js prettyprint-override"><code>describe('some', () => {
describe('getText', () => {
it('should return "123"', async () => {
const wrapper = mount(Some);
await flushPromises();
const result = wrapper.vm.getText(); // <--- "getText()" is udnefined!!!
expect(result).toBe('123');
});
});
});
</code></pre>
<p>So, how to access <code>getText()</code> in unit-tests? I use vitest btw.</p>
<p>I know <a href="https://stackoverflow.com/a/65666315/16280429">some solutions to test the html</a>, but they aren't letting me to access functions either.</p>
<p>For sure I can test via "click". But what if I need to mock a function?</p>
| [
{
"answer_id": 74192996,
"author": "Michael",
"author_id": 1898563,
"author_profile": "https://Stackoverflow.com/users/1898563",
"pm_score": 3,
"selected": true,
"text": "MazeBuilder builder = new MazeBuilderImpl();\nMaze maze = builder.rooms(1).build();\nbuilder.rooms(2); // modifies th... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16280429/"
] |
74,192,873 | <p>I try to add Model Relation on Laravel. I know how we can make this but I don't understand, I can link all Model I need.</p>
<p>So this is my problem :</p>
<p>I build a exam system and it's work like this :</p>
<p>Evaluation -> Examid -> QuestionCategory -> Question -> Response.</p>
<p>So in Evaluation session, We choose a Examen which has question categories, which has questions, which has response.</p>
<p>So I wrote this :</p>
<pre><code>public function testtheorique($session){
$eval = Evaluation::find($session);
$caces = $eval->caces_cat;
$theorique = $eval->theorique;
$questioncat = $theorique->examcategory;
$question = $questioncat->categoryQuestions;
}
</code></pre>
<p>And this is my Models :</p>
<pre><code>//Evaluation Model
public function theorique(){
return $this->belongsTo(TestTheorique::class);
}
//TestThorique Model
public function examcategory(){
return $this->hasMany(QuestionCategorie::class, 'exam_id');
}
//QuestionCategory Model
public function categoryQuestions(){
return $this->hasMany(Question::class, 'category_id', 'id');
}
//Question Model
public function qcategory(){
return $this->belongsTo(QuestionCategorie::class);
}
</code></pre>
<p>So when I make this dd($eval) I have all the data displayed with the relationships but only up to the examcategory. I can't display the Question because I don't have relation.</p>
<p>So I don't know how I can have the question relation. I can't see where I made an error.</p>
<p>Thanks for your help.</p>
| [
{
"answer_id": 74193110,
"author": "Sumit kumar",
"author_id": 11545457,
"author_profile": "https://Stackoverflow.com/users/11545457",
"pm_score": 1,
"selected": true,
"text": "composer require staudenmeir/eloquent-has-many-deep:\"^1.13\""
},
{
"answer_id": 74194820,
"author"... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19618321/"
] |
74,192,874 | <p>The application is written for the data collection terminal (android). It has a physical keyboard. Can you tell me how to intercept keyboard clicks if there is no text field on the form?</p>
| [
{
"answer_id": 74202999,
"author": "Liyun Zhang - MSFT",
"author_id": 17455524,
"author_profile": "https://Stackoverflow.com/users/17455524",
"pm_score": 1,
"selected": false,
"text": "OnKeyListener"
},
{
"answer_id": 74446479,
"author": "rentoulis",
"author_id": 19958403... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16027043/"
] |
74,192,903 | <p><strong>Context</strong></p>
<p>I have a <code>Pandas</code> <code>DataFrame</code> and a <code>Use Case</code>, where I need to store a <code>Collection</code> (<code>Dictionary</code>) in of the <code>Columns</code>. I do know, that a <code>DataFrame</code> is probably not designed for this, however, I am looking for a simple solution without <code>Relationships</code> between multiple <code>DataFrames</code>, <code>Series</code>, etc.</p>
<p>I am currently getting the following Error:</p>
<blockquote>
<p>ValueError: Length of values (3) does not match length of index (5)</p>
</blockquote>
<hr />
<p><strong>Code</strong></p>
<pre class="lang-py prettyprint-override"><code>procedures = {'A': 'Procedure A', 'B': 'Procedure B', 'C': 'Procedure C'}
# I would like to create a new Column 'Procedures' and assign the Dictionary above to it for every Row.
data['Procedures'] = procedures
</code></pre>
<hr />
<p><strong>Question</strong></p>
<ul>
<li>Is this possible with <code>Pandas</code> and how can I achieve it?</li>
</ul>
| [
{
"answer_id": 74192925,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "data['Procedures'] = [procedures] * len(data)\n"
},
{
"answer_id": 74193408,
"author": "jaswanth",
"a... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13345744/"
] |
74,192,964 | <p>Let's say a branch has commits</p>
<pre><code>X
B
A
</code></pre>
<p>And say master has commits</p>
<pre><code>D
C
B
A
</code></pre>
<p>When I hit merge, does Gitlab automatically rebase and merge the branch into master?</p>
<p>After merging does it look like this?</p>
<pre><code>X
D
C
B
A
</code></pre>
| [
{
"answer_id": 74193018,
"author": "matt",
"author_id": 341994,
"author_profile": "https://Stackoverflow.com/users/341994",
"pm_score": 0,
"selected": false,
"text": "X'"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14996394/"
] |
74,192,981 | <p>I have this dataframe that I applied <code>multinom</code> function</p>
<pre><code>df = data.frame(x = c('a','a','b','b','c','c','d','d','d','e','e','f','f',
'f','f','g','g','g','h','h','h','h','i','i','j','j'),
y = c(1,2,1,3,1,2,1,4,5,1,2,2,3,4,5,1,1,2,1,2,2,3,2,2,3,4) )
df$y = factor(df$y,ordered = TRUE)
nnet::multinom(y~x, data = df)
</code></pre>
<p>when checking the output, I have all the variables with their coefficients (meaning everything is fine)</p>
<pre><code>Coefficients:
(Intercept) xb xc xd xe xf
2 -6.045294e-05 -31.83512 3.800915e-05 -36.67053 3.800915e-05 25.00515
3 -1.613311e+01 16.13310 -1.725649e+01 -21.06832 -1.725649e+01 41.13825
4 -1.692352e+01 -14.71119 -1.428100e+01 16.92351 -1.428100e+01 41.92865
5 -2.129358e+01 -10.49359 -1.002518e+01 21.29353 -1.002518e+01 46.29867
xg xh xi xj
2 -0.6931261 0.6932295 40.499799 -25.311410
3 -24.0387863 16.1332150 -8.876562 45.191730
4 -20.2673490 -16.0884760 -6.394423 45.982129
5 -15.1755064 -11.8589447 -4.563793 -6.953942
</code></pre>
<p>but my original dataframe (will share only the output) that is coded as the dependent and independent variables from the df dataframe (meaning as ordinal factors) and all the analysis is well done but when it comes to interpretation I have this output :</p>
<pre><code>Coefficients:
(Intercept) FIES_R.L FIES_R.Q FIES_R.C FIES_R^4 FIES_R^5
2 -0.09594409 -1.303256 0.03325169 -0.1753022 -0.46026668 -0.282463422
3 -0.18587599 -1.469957 0.42005569 -0.2977628 0.00508412 0.003068678
4 -0.58189239 -2.875183 0.33128994 -0.6787992 0.11145099 0.239368520
5 -2.68727952 -10.178604 -5.12515249 -5.8454920 -3.13775961 -1.820629143
FIES_R^6 FIES_R^7 FIES_R^8
2 -0.2179067 -0.1000471 -0.1489342
3 0.1915476 -0.5483707 -0.2565626
4 0.2585801 0.3821566 -0.2679774
5 -0.5562958 -0.6335412 -0.7205215
</code></pre>
<p>I don't want FIES_R.L,FIES_R.Q and FIES_R.C. I want them as : FIES_R_1, FIES_R_2, FIES_R_3, FIES_R_4, FIES_R_5, FIES_R_6, FIES_R_7, FIES_R_8,
why I have such an output ? knowing that the two dataframes include ordinal categorical variables and the x variable and the FIES variable include many categories in both dataframes. Thanks</p>
| [
{
"answer_id": 74193018,
"author": "matt",
"author_id": 341994,
"author_profile": "https://Stackoverflow.com/users/341994",
"pm_score": 0,
"selected": false,
"text": "X'"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19720935/"
] |
74,192,994 | <p>So I have a TextBox and I want to limit the input to a numerical value from 0 - 50, is this possible? I've looked at some Regex examples using the <code>PreviewTextInput</code> but that only validates one number at a time.</p>
<p>I've also tried utilizing the <code>MaxLength</code> property, but that didn't seem to do much.</p>
| [
{
"answer_id": 74193190,
"author": "Leandro Toloza",
"author_id": 14322498,
"author_profile": "https://Stackoverflow.com/users/14322498",
"pm_score": 1,
"selected": false,
"text": "<TextBox Name=\"NumberTextBoxLimited\" PreviewTextInput=\"NumberValidationTextBox\"/>\n"
},
{
"answ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5500630/"
] |
74,192,999 | <p>I'm having a problem with calling method
<strong>Files.write(Path.of(fileForDocumentContent.getAbsolutePath()), htmlDocument.getContent());</strong> It throws <strong>java.nio.file.NoSuchFileException.</strong> even if file really exists.</p>
<p>I want to point that on my local machine it works perfect but it doesn't work on DEV machine which is located on linux.</p>
<p>My code is:</p>
<pre><code>@Override
public Document convert(Document document, DocumentFormat documentFormat) {
Document htmlDocument = htmlDocumentConverter.convert(document, documentFormat);
File fileForDocumentContent = null;
File fileForConvertedContent = null;
try {
log.info("Converting document from {} to {}", getSourceFormat().toString(), getTargetFormat().toString());
CalibreConfigData calibreData = calibreConfig.getConfigurationData(CalibreConversion.HTML_TO_DOCX);
fileForDocumentContent = new File(calibreData.getSourceFilePath());
fileForConvertedContent = new File(calibreData.getConvertedFilePath());
// \/ doesn't work \/
Files.write(fileForDocumentContent.toPath(), htmlDocument.getContent());
Runtime.getRuntime().exec(calibreData.getCalibreCommand()).waitFor();
byte[] convertedFileAsBytes = Files.readAllBytes(fileForConvertedContent.toPath());
return new Document(convertedFileAsBytes);
} catch (InterruptedException | IOException e) {
log.error("Conversion failed due to problem: " + e);
throw new MetanormaConversionException("Conversion failed due to problem: " + e);
} finally {
deleteFilesIfPresent(fileForDocumentContent, fileForConvertedContent);
}
}
</code></pre>
<blockquote>
<p>fileForDocumentContent = new File(calibreData.getSourceFilePath());</p>
</blockquote>
<p>creates file under path: <strong>ile:/usr/src/pok-document-service.jar!/BOOT-INF/classes!/5b1138f8-1805-4db8-a5ed-acab8509adc4.html</strong></p>
<p>and exact error looks:</p>
<blockquote>
<p>"Conversion failed due to problem: java.nio.file.NoSuchFileException: <strong>ile:/usr/src/pok-document-service.jar!/BOOT-INF/classes!/5b1138f8-1805-4db8-a5ed-acab8509adc4.html"</strong></p>
</blockquote>
<p>As you can see both paths to the file looks the same and yet it throws an exception.
I've tried to change from <strong>.toPath()</strong> to <strong>.getAbsolutePath()</strong> but still the same problem appears.</p>
| [
{
"answer_id": 74193190,
"author": "Leandro Toloza",
"author_id": 14322498,
"author_profile": "https://Stackoverflow.com/users/14322498",
"pm_score": 1,
"selected": false,
"text": "<TextBox Name=\"NumberTextBoxLimited\" PreviewTextInput=\"NumberValidationTextBox\"/>\n"
},
{
"answ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74192999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329316/"
] |
74,193,029 | <p>I'm fetching data from an API and displaying it on the front end of my website</p>
<pre><code>{/*fetching the the data from an API*/}
function searchArtistes() {
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": "86f453f970msh48154777add2da0p1e185cjsn969596f1a317",
"X-RapidAPI-Host": "spotify81.p.rapidapi.com",
},
};
fetch(
`https://spotify81.p.rapidapi.com/search?q=${searchInput}&type=multi&offset=0&limit=10&numberOfTopResults=5`,
options
)
.then((response) => response.json())
.then((response) =>
setArtisteData(
response.artists.items.map((artist) => artist.data.profile.name)
)
)
.catch((err) => console.error(err));
}
</code></pre>
<pre><code>{/* function fetching the data is called by an onChange event listener in the input */}
<form className="search-input flex justify-between md:items-center">
<div className="flex md:flex-row-reverse">
<input
placeholder="search artists"
onChange={() => {
handleChange(event);
searchArtistes();
}}
className="search ml-6 "
/>
<img
src={search}
className="search-icon md:ml-12 lg:ml-14 2xl:ml-18"
/>
</div>
</form>
{/*Displaying it on the interface*/}
<div>
<ul className="flex flex-col items-center text-white">
{artisteData.map((name) => (
<li className="cursor-pointer pt-1">{name}</li>
))}
</ul>
</div>
</code></pre>
<p>But the problem is even when the query is empty the api still returns data as seen in the image below:</p>
<p><a href="https://i.stack.imgur.com/Iqf7M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Iqf7M.png" alt="enter image description here" /></a></p>
<p><strong>What can i do about this?</strong></p>
| [
{
"answer_id": 74193162,
"author": "Dirk jnr Odendaal",
"author_id": 9816682,
"author_profile": "https://Stackoverflow.com/users/9816682",
"pm_score": 1,
"selected": false,
"text": "const [artisteData, setArtisteData] = useState(null);\n"
},
{
"answer_id": 74193206,
"author":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17492736/"
] |
74,193,063 | <p>As the title states I am looking for ways to create and be able to interact with bool conditions.</p>
<p>I have tried predicates but they don't work. <code> public static Predicate<(decimal?,decimal?)> Create(Predicate<(decimal?,decimal?)> predicate) => predicate;</code></p>
<p>this only works as a filter for when I do <code>Condition.Create(c => c.IsSomeCalc(list1, list2))</code></p>
<p>then the use case is <code>var res=Condition(SomeValList)</code></p>
<p>there are many overloads for the creation of a condition and not just 1.</p>
<p>what I am trying to do is create a condition that returns true or false if the condition is met</p>
<p>i.e <code>Condition IsLower= Condition.Create(c=>c.IsLower(decimal,decimal)</code></p>
<p>Then to use</p>
<pre><code>IsLower(5,10)//=true
</code></pre>
<p>edit:
Say I have a <code>Condition</code>Class that has the field <code>ConditionOperator</code>
and <code>ConditionOperator</code> Is an interface that Implements Classes Like <code>IsGreaterThan</code> and in <code>IsGreaterThan</code> I have the field <code>IsTrue</code> which is <code>boolean</code> and in that class I can have multiple overloads for updating <code>IsTrue</code></p>
<p>i.e <code> public IsGreaterThan(decimal itm, decimal itm2) { isTrue = itm > itm2; }</code></p>
<p>and then use case would be another class that use the condition like</p>
<pre><code>Test Test= new Test();
Test.Condition.ConditionOperator= new IsGreaterThanCondition(1,2);
Console.WriteLine($"{Test.Condition.ConditionOperator.IsTrue}";
</code></pre>
<p>This is all redundant and less versatile than the extension methods for what I am trying to do.</p>
| [
{
"answer_id": 74193162,
"author": "Dirk jnr Odendaal",
"author_id": 9816682,
"author_profile": "https://Stackoverflow.com/users/9816682",
"pm_score": 1,
"selected": false,
"text": "const [artisteData, setArtisteData] = useState(null);\n"
},
{
"answer_id": 74193206,
"author":... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5743183/"
] |
74,193,091 | <p>I want to check if a command exists on my machine (RedHat) inside a perl script.</p>
<p>Im trying to check if <code>compgen -c</code> contains the desired command, but running it from inside a script just gives me an empty output. Other commands work fine.</p>
<p>example.pl:</p>
<pre><code>my $x = `compgen -c`;
print $x;
# empty output
my $y = `ls -a`;
print $y;
# .
# ..
# example.pl
</code></pre>
<p>Are there possible solutions for this? Or is there a better way to check for commands on my machine?</p>
| [
{
"answer_id": 74194343,
"author": "Dave Cross",
"author_id": 7231,
"author_profile": "https://Stackoverflow.com/users/7231",
"pm_score": 2,
"selected": false,
"text": "compgen"
},
{
"answer_id": 74197346,
"author": "zdim",
"author_id": 4653379,
"author_profile": "htt... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19745277/"
] |
74,193,096 | <p>I have 4466 .tsv files with this structure:
<a href="https://i.stack.imgur.com/94zzm.png" rel="nofollow noreferrer">file_structure</a></p>
<p>I want to compare the 4466 files to see how many IDs (the first column) matches.
I only found bash commands with two files with "comm". Could you tell me how I could do that?</p>
<p>Thank you</p>
| [
{
"answer_id": 74193751,
"author": "Andrej Podzimek",
"author_id": 8584929,
"author_profile": "https://Stackoverflow.com/users/8584929",
"pm_score": 0,
"selected": false,
"text": "*.tsv"
},
{
"answer_id": 74199580,
"author": "Zach Young",
"author_id": 246801,
"author_... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329392/"
] |
74,193,103 | <p>I'm having an issue <a href="https://social.msdn.microsoft.com/Forums/en-US/cc25d70a-eb6d-4bca-bcae-33c05380e61e/outlook-macro-sentonbehalfofname?forum=outlookdev" rel="nofollow noreferrer">like this one</a></p>
<pre><code> outlook = win32com.client.Dispatch('outlook.application')
accounts = win32com.client.Dispatch("outlook.Application").Session.Accounts
print(accounts[1])
mail = outlook.CreateItem(0)
mail.SentOnBehalfOfName = accounts[1]
mail.SendUsingAccount = accounts[1]
mail.To = to
mail.Subject = 'Subject TEST'
mail.HTMLBody = emailBody
mail.display()
mail.Send()
</code></pre>
<p>if I comment <code>mail.Send()</code> the window that shows up will show everything correctly but if I send it, i'll get reply <code>This message could not be sent. You do not have the permission to send the message on behalf of the specified user.</code> which is obviously not true since if instead of sending directly and choose the exact same email from the dropdown menu in From, and then click SEND, it will send the email with no issues.</p>
| [
{
"answer_id": 74195997,
"author": "Eugene Astafiev",
"author_id": 1603351,
"author_profile": "https://Stackoverflow.com/users/1603351",
"pm_score": 0,
"selected": false,
"text": "mail.SentOnBehalfOfName = accounts[1]\nmail.SendUsingAccount = accounts[1]\n"
},
{
"answer_id": ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10747598/"
] |
74,193,107 | <p>Im trying to achieve the following layout <strong>inside a row</strong> (please see attached image):</p>
<ol>
<li>A TextField, with 3 lines</li>
<li>A square image container (aspect ratio of 1:1), where the image has a cover fit</li>
</ol>
<p><a href="https://i.stack.imgur.com/bC6iB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bC6iB.jpg" alt="enter image description here" /></a></p>
<p>Constraints:
I want the TextField to set the height of the row, so no matter how big or small the font size, the image will always be square, and its height the same as the TextField height.<br />
So I <strong>don't want to use any pixel sizes</strong></p>
<p>This is my initial code, but of course the image is not constrained...<br />
Any ideas on how to fix that?</p>
<pre><code>IntrinsicHeight(
child: Row(
children: [
Flexible(
child: TextField(
controller: _controller,
maxLines: 3,
),
),
Image.file(File(imagePath), fit: BoxFit.cover)
],
),
)
</code></pre>
| [
{
"answer_id": 74195997,
"author": "Eugene Astafiev",
"author_id": 1603351,
"author_profile": "https://Stackoverflow.com/users/1603351",
"pm_score": 0,
"selected": false,
"text": "mail.SentOnBehalfOfName = accounts[1]\nmail.SendUsingAccount = accounts[1]\n"
},
{
"answer_id": ... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6097845/"
] |
74,193,164 | <p>I have made a program which outputs the factorial of a number by calling the function: factorial() which uses recursion to calculate and return the value. I have also included a loop to break the program when the User inputs the word "off". Please suggest any improvements</p>
<p>Here is the code:</p>
<pre><code>def factorial(base):
if base == 0 or base == 1:
return 1
else:
return base * factorial(base - 1)
while True:
base: int = int(input("Enter a base number: "))
Result = factorial(base)
print(f"The factorial of {base} is: {Result}")
offf: str = input("Enter 'off' to terminate calculations: ")
if offf == "off":
print("Calculations Terminated")
break
</code></pre>
<p>Here is the terminal:</p>
<p><a href="https://i.stack.imgur.com/O4pNb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O4pNb.png" alt="Output of my code" /></a></p>
| [
{
"answer_id": 74193520,
"author": "matszwecja",
"author_id": 9296093,
"author_profile": "https://Stackoverflow.com/users/9296093",
"pm_score": 2,
"selected": true,
"text": "base"
},
{
"answer_id": 74195513,
"author": "assume_irrational_is_rational",
"author_id": 11622508... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329537/"
] |
74,193,192 | <p>can you tell me how to check if my xml contains nested element in array with exact values? Here is my sample XML:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<items>
<item>
<identifier>100</identifier>
<value>ABC</value>
</item>
<item>
<identifier>200</identifier>
<value>XYZ</value>
</item>
<item>
<identifier>100</identifier>
<value>DEF</value>
</item>
<item>
<identifier>300</identifier>
<value>GFH</value>
</item>
</items>
</code></pre>
<p>For instance, I need check if xml above contains element with <code>identifier = 100</code> and element with this identifier must has <code>value = DEF</code>. It could be on any index in array items.</p>
| [
{
"answer_id": 74193520,
"author": "matszwecja",
"author_id": 9296093,
"author_profile": "https://Stackoverflow.com/users/9296093",
"pm_score": 2,
"selected": true,
"text": "base"
},
{
"answer_id": 74195513,
"author": "assume_irrational_is_rational",
"author_id": 11622508... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6456586/"
] |
74,193,193 | <p>I want to create a layout like this :</p>
<p><a href="https://i.stack.imgur.com/7bTux.png" rel="nofollow noreferrer">Example layout</a></p>
<p>I want to display the whole page in that black element, How to do this with html and css.
It has scrollabe content, and the content should stay within that black element.</p>
| [
{
"answer_id": 74193520,
"author": "matszwecja",
"author_id": 9296093,
"author_profile": "https://Stackoverflow.com/users/9296093",
"pm_score": 2,
"selected": true,
"text": "base"
},
{
"answer_id": 74195513,
"author": "assume_irrational_is_rational",
"author_id": 11622508... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329619/"
] |
74,193,198 | <p>I need to run my function <code>MyFunc()</code> every five seconds using the parameters in the code (i.e. minimum code changes).</p>
<p>There are two parameters in the code: <code>ts</code> and <code>std::chrono::system_clock::now()</code></p>
<p>What do I write in <code>condition</code> so that I can run my function at the interval?</p>
<pre><code>auto ts = std::chrono::system_clock::now() + std::chrono::seconds(1);
do {
// 1s timer
if ( ts <= std::chrono::system_clock::now()) {
// ... doing some work
// here I need to start MyFunc() every 5s
if (condition) {
MyFunc();
}
ts += std::chrono::seconds(1);
}
} while (isWork);
</code></pre>
| [
{
"answer_id": 74193520,
"author": "matszwecja",
"author_id": 9296093,
"author_profile": "https://Stackoverflow.com/users/9296093",
"pm_score": 2,
"selected": true,
"text": "base"
},
{
"answer_id": 74195513,
"author": "assume_irrational_is_rational",
"author_id": 11622508... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20251832/"
] |
74,193,214 | <p>I'm trying to simply add a column from another dataframe of the same length using df['columnname'] = df2['columnname'], but the column appears in df with the lines in a different order.</p>
<p>Is there any rhyme or reason to this? Am I doing pandas wrong? Would love any help for this low level data transformation.</p>
| [
{
"answer_id": 74193218,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "df = pd.DataFrame({'col': [0,1,2]})\ndf2 = pd.DataFrame({'columnname': [5,6,7]}, index=[1,0,2])\n\ndf['columnname'] =... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20327418/"
] |
74,193,216 | <p>Is it allowed for <code>srand(0)</code> to have the same effect as <code>srand(1)</code>?</p>
<p>C11, 7.22.2.2 The srand function (empahasis added):</p>
<blockquote>
<p>The srand function uses the argument as a seed for a <strong>new sequence</strong> of pseudo-random numbers to be returned by subsequent calls to rand.</p>
</blockquote>
<p>However, in glibc <code>srand(0)</code> has <a href="https://github.com/bminor/glibc/blob/b92a49359f33a461db080a33940d73f47c756126/stdlib/random_r.c#L178" rel="nofollow noreferrer">the same effect</a> as <code>srand(1)</code>:</p>
<pre><code> /* We must make sure the seed is not 0. Take arbitrarily 1 in this case. */
if (seed == 0)
seed = 1;
</code></pre>
<p>Hence, the <a href="https://godbolt.org/z/xEK7b1e58" rel="nofollow noreferrer">same sequence</a> of pseudo-random numbers is returned by subsequent calls to <code>rand</code>, which is confusing.</p>
<p>Extra: We see that in MSVC <code>srand(0)</code> does not have the same effect as <code>srand(1)</code>.</p>
| [
{
"answer_id": 74193994,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 3,
"selected": false,
"text": "srand()"
},
{
"answer_id": 74194222,
"author": "Artyer",
"author_id": 5754656,
"author_pr... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778275/"
] |
74,193,230 | <p>We are using Elasticsearch 7.9</p>
<p>Our index, called <em>method_info_tree</em>, contains two-level nested fields:</p>
<ul>
<li>The top level described a java method,</li>
<li>the nested level below it describes a thread that ran the method, and</li>
<li>the third nested level within a thread describes the states of that thread over time.</li>
</ul>
<p>Below is the mapping of the index in Elasticsearch:</p>
<pre><code>{
"mappings": {
"properties": {
"method_id" : {
"type" : "long"
},
"threads": {
"type": "nested",
"properties": {
"thread_id": {
"type": "long"
},
"states": {
"type": "nested",
"properties": {
"collect_time": {
"type": "date"
},
"state": {
"type": "keyword"
},
"elapsed_time": {
"type" : "integer"
}
}
}
}
}
}
}
}
</code></pre>
<p>Here is a sample document in the index:</p>
<pre><code>{
"took" : 13,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 5198,
"relation" : "eq"
},
"max_score" : 0.0,
"hits" : [
{
"_index" : "method_info_tree-000001",
"_type" : "_doc",
"_id" : "WiHCCYQBhPdvF01n3kp1",
"_score" : 0.0,
"_routing" : "86163-d5c064d0-55a3-44b9-88fb-c44b7233cfa4",
"_source" : {
"timestamp" : 1666610993800,
"method_id" : 140280075031760,
"threads" : [
{
"thread_id" : 1,
"states_hit" : [
{
"state" : "RUNNABLE",
"collect_time" : 1666610994750,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610994800,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610994850,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610994900,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610994950,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610995000,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610995050,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610995100,
"elapsed_time" : 50
},
{
"state" : "IO",
"collect_time" : 1666610995150,
"elapsed_time" : 50
}
]
}
]
}
}
]
}
}
</code></pre>
<p>Note that for each <em>method_id</em> we have many documents for various <em>thread_id</em>s.</p>
<p>I would like, for each <em>method_id</em>, to calculate the sum of <em>elapsed_time</em> field per <em>state</em> (for all threads), something like:</p>
<pre><code>method_id ->
[
{
"state" : "IO",
"elapsed_time" : 566622.0
},
{
"state" : "RUNNABLE",
"elapsed_time" : 566572.0
},
{
"state" : "BLOCKED",
"elapsed_time" : 50.0
}
]
</code></pre>
<p>Below is my Elasticsearch query:</p>
<pre><code>GET method_info_tree/_search
{
"from": 0,
"size": 0,
"track_total_hits": true,
"query": {
"bool": {
"filter": [
{
"term": {
"session_id": "86163-d5c064d0-55a3-44b9-88fb-c44b7233cfa4"
}
},
{
"nested": {
"path": "threads.states_hit",
"query": {
"bool": {
"filter": [
{
"range": {
"threads.states_hit.collect_time": {
"gte": 0,
"lte": 2000000000000
}
}
}
]
}
}
}
}
]
}
},
"aggs": {
"top_methods_agg": {
"terms": {
"field": "method_id",
"size": 20
},
"aggs": {
"elapsed_time_agg": {
"nested": {
"path": "threads.states_hit"
},
"aggs": {
"states_range": {
"range": {
"field": "threads.states_hit.collect_time",
"ranges": [
{
"from": 0,
"to": 2000000000001
}
]
},
"aggs": {
"elapsed_time_per_state_agg": {
"terms": {
"field": "threads.states_hit.state",
"size": 10
},
"aggs": {
"elapsed_time": {
"sum": {
"field": "threads.states_hit.elapsed_time"
}
}
}
},
"total_self_elapsed_time": {
"sum": {
"field": "threads.states_hit.elapsed_time"
}
},
"wasted_elapsed_time": {
"filter": {
"terms": {
"threads.states_hit.state": [
"BLOCKED",
"IO"
]
}
},
"aggs": {
"total_wasted": {
"sum": {
"field": "threads.states_hit.elapsed_time"
}
}
}
}
}
}
}
}
}
}
}
}
</code></pre>
<p>A sample result would be:</p>
<pre><code>{
"took" : 218,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 5727,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"top_methods_agg" : {
"doc_count_error_upper_bound" : 1,
"sum_other_doc_count" : 73,
"buckets" : [
{
"key" : 140280074341584,
"doc_count" : 728,
"elapsed_time_agg" : {
"doc_count" : 21838,
"states_range" : {
"buckets" : [
{
"key" : "1970-01-01T00:00:00.000Z-2033-05-18T03:33:20.001Z",
"from" : 0.0,
"from_as_string" : "1970-01-01T00:00:00.000Z",
"to" : 2.000000000001E12,
"to_as_string" : "2033-05-18T03:33:20.001Z",
"doc_count" : 21838,
"total_self_elapsed_time" : {
"value" : 1133244.0
},
"wasted_elapsed_time" : {
"doc_count" : 1,
"total_wasted" : {
"value" : 50.0
}
},
"elapsed_time_per_state_agg" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "IO",
"doc_count" : 10919,
"elapsed_time" : {
"value" : 566622.0
}
},
{
"key" : "RUNNABLE",
"doc_count" : 10918,
"elapsed_time" : {
"value" : 566572.0
}
},
{
"key" : "BLOCKED",
"doc_count" : 1,
"elapsed_time" : {
"value" : 50.0
}
}
]
}
}
]
}
}
},
{
"key" : 140282650318928,
"doc_count" : 3,
"elapsed_time_agg" : {
"doc_count" : 3,
"states_range" : {
"buckets" : [
{
"key" : "1970-01-01T00:00:00.000Z-2033-05-18T03:33:20.001Z",
"from" : 0.0,
"from_as_string" : "1970-01-01T00:00:00.000Z",
"to" : 2.000000000001E12,
"to_as_string" : "2033-05-18T03:33:20.001Z",
"doc_count" : 3,
"total_self_elapsed_time" : {
"value" : 150.0
},
"wasted_elapsed_time" : {
"doc_count" : 0,
"total_wasted" : {
"value" : 0.0
}
},
"elapsed_time_per_state_agg" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "RUNNABLE",
"doc_count" : 3,
"elapsed_time" : {
"value" : 150.0
}
}
]
}
}
]
}
}
}
]
}
}
}
</code></pre>
<p>Note that I deleted some of the result buckets for better coherence of the example.</p>
<p><strong>My problem:</strong>
I need to sort the results by '<em>total_self_elapsed_time</em>' and return only the top 5 results.
Since the result is nested, I cannot access the calculated field 'total_self_elapsed_time'.
Can you please direct me to how I can add to my query sorting by this aggregated field?</p>
| [
{
"answer_id": 74193936,
"author": "jaspreet chahal",
"author_id": 9279354,
"author_profile": "https://Stackoverflow.com/users/9279354",
"pm_score": 3,
"selected": true,
"text": " \"aggs\": {\n \"top_methods_agg\": {\n \"terms\": {\n \"field\": \"method_id\",\n \"s... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5524030/"
] |
74,193,250 | <p>I would like to create another dictionary where the output will be</p>
<pre class="lang-py prettyprint-override"><code>new_dic = {key: len(value)}
</code></pre>
<p>Given a dictionary containing lists in its values.</p>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>dic = {'a':[1,2,3], 'b':[4,5], 'c':[6]}
</code></pre>
<p>And I want to create <code>new_dic</code> from <code>dic</code> where the <code>new_dic</code> map keys to length of value like this:</p>
<pre class="lang-py prettyprint-override"><code>new_dic = {'a':3, 'b':2, 'c':1}
</code></pre>
| [
{
"answer_id": 74193309,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 0,
"selected": false,
"text": "int"
},
{
"answer_id": 74193329,
"author": "Ankan Das",
"author_id": 8309797,
"author_profi... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329630/"
] |
74,193,262 | <p>There is a simple class with parameterized constructor. I'm looking for a way to apply it for JSON deserialization with minimal annotations usage.</p>
<p>How to make Jackson recognize <code>id</code> field by its name without explicit <code>JsonProperty</code>?</p>
<p><strong>Class:</strong></p>
<pre><code>public final class MyRec {
final String id;
public MyRec1(String id) {
this.id = id;
}
}
</code></pre>
<p>Deserialization fails unless annotation <code>@JsonProperty("id")</code> is present on the field.</p>
<p><strong>Deserialization attempt:</strong></p>
<pre><code>new ObjectMapper().readValue("""{"id":"abc"}""", MyRec.class);
</code></pre>
<p><strong>Exception:</strong></p>
<pre><code>Cannot construct instance of `sample.MyRec` (although at least one Creator exists):
cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"id":"abc"}"; line: 1, column: 2]
com.fasterxml.jackson.databind.exc.MismatchedInputException:
Cannot construct instance of `sample.MyRec` (although at least one Creator exists):
cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"id":"abc"}"; line: 1, column: 2]
at app//com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
</code></pre>
| [
{
"answer_id": 74194780,
"author": "Rob Spoor",
"author_id": 1180351,
"author_profile": "https://Stackoverflow.com/users/1180351",
"pm_score": 0,
"selected": false,
"text": "-parameters"
},
{
"answer_id": 74244580,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2774914/"
] |
74,193,284 | <p>I´m trying to set a volatile boolean variable, called <code>accelerationCheck</code>, in other thread and retrieve its value from a "main thread". This variable has to be true if the acceleration is below -7 during at least 500ms if not, false. The thing is I'm getting sometimes true when it should be false and vice versa. Why do you think this is happening? The code below is contained in the "main thread", this main thread is executed every 30ms with an <code>Executor</code>:</p>
<pre class="lang-java prettyprint-override"><code>if(vehicleData.getVehicleAcceleration() < -7) {
if(this.accTimer == null) {
this.accTimer = new CustomTimer();
}
this.accTimer.start();
this.accelerationObserver = new Runnable() {
public void run() {
accTimer.stop();
if(accTimer.getElapsedMilliseconds() >= 500) {
accelerationCheck = true;
accTimer.stop();
accTimer.start();
}
}
};
this.executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(accelerationObserver, 0, 100, TimeUnit.MILLISECONDS);
}
else {
this.accelerationObserver = null;
this.executor = null;
this.accTimer.stop();
this.accTimer = null;
this.accelerationCheck = false;
}
</code></pre>
<p>CustomTimer class:</p>
<pre><code>public class CustomTimer {
private final long nanoSecondsPerMillisecond = 1000000;
private long stopWatchStartTime = 0;
private long stopWatchStopTime = 0;
private boolean stopWatchRunning = false;
public void start() {
this.stopWatchStartTime = System.nanoTime();
this.stopWatchRunning = true;
}
public void stop() {
this.stopWatchStopTime = System.nanoTime();
this.stopWatchRunning = false;
}
public boolean isRunning() {
return this.stopWatchRunning;
}
public long getElapsedMilliseconds() {
long elapsedTime;
if (stopWatchRunning)
elapsedTime = (System.nanoTime() - stopWatchStartTime);
else
elapsedTime = (stopWatchStopTime - stopWatchStartTime);
return elapsedTime / nanoSecondsPerMillisecond;
}
}
</code></pre>
<p>Variable <code>vehicleData</code> is an object of this class:</p>
<pre><code>public class VehicleDataStore extends Thread implements VehicleDataValueListener{
private long yawRate = 32767;
private long lateralAcceleration = 161;
private long vehicleAcceleration = 161;
private long speed = 16383;
private double accelerationPedal = 0.0;
private double brakePressure = 0.0;
private int accelerationControl = 0;
private int driveDirection = 2;
// Lights
private boolean highBeam = false;
private boolean lowBeam = false;
private boolean dayTimeRunning = false;
private boolean reverseLight = false;
private boolean fogLight = false;
private boolean parkingLights = false;
// AcelerationControl
private boolean emergencyBrake = false;
private boolean collisionWarning = false;
private boolean speedLimiter = false;
private boolean acc = false;
private boolean cruiseControl = false;
private boolean brakeActivated = false;
private boolean gasPedalActivated = false;
private long curvature = 1023;
private int hazardLights;
// private double vehicleSpeedKM100 = 0.0;
private boolean turnLeft = false;
private boolean turnRight = false;
private int warningLights = 0;
private int vehicleRole = Activator.vehicleRole;
private int stationType = Activator.stationType;
private DatagramSocket socket;
InetAddress inetAddress;
private int etsiPort = 12346;
private boolean isRunning = false;
private boolean embarkationStatus = false;
private int ptActivationType = 0;
private byte[] ptActivationData = null;
private int dangerousGoods = 0;
private boolean ligthSirenLb = false;
private boolean ligthSirenS = false;
private int steeringWheel = 512;
private int brakePressure05;
private boolean emergencyServiceCan = false;
private VehicleDataService service;
public VehicleDataStore(VehicleDataService service) {
this.service = service;
registerListeners(service);
this.isRunning = true;
}
public void onVehicleDataChange(String name, Cell cell) {
if (name.equalsIgnoreCase("AccelerationPedal")) {
setAccelerationPedal(cell);
} else if (name.equalsIgnoreCase("VehicleAcceleration")) {
setVehicleAcceleration(cell);
} else if (name.equalsIgnoreCase("VehicleSpeed")) {
setVehicleSpeed(cell);
} else if (name.equalsIgnoreCase("DriveDirection")) {
setDriveDirection(cell);
setReverseLight(cell);
} else if (name.equalsIgnoreCase("YawRate")) {
setYawRate(cell);
} else if (name.equalsIgnoreCase("LateralAcceleration")) {
setLateralAcceleration(cell);
} else if (name.equalsIgnoreCase("BrakePressure")) {
setBrakePressure(cell);
} else if (name.equalsIgnoreCase("AccelerationControl")) {
setAccelerationControl(cell);
} else if (name.equalsIgnoreCase("LowBeam")) {
setLowBeam(cell);
} else if (name.equalsIgnoreCase("HighBeam")) {
setHighBeam(cell);
} else if (name.equalsIgnoreCase("HazardLigths")) {
setHazardLigths(cell);
} else if (name.equalsIgnoreCase("TurnLeft")) {
setTurnLeft(cell);
} else if (name.equalsIgnoreCase("TurnRight")) {
setTurnRight(cell);
} else if (name.equalsIgnoreCase("WarningLights")) {
setWarningLights(cell);
} else if (name.equalsIgnoreCase("SteeringWheel")) {
setSteeringWheel(cell);
} /*else if (name.equalsIgnoreCase("EmergencyService")) {
setEmergencyService(cell);
}*/
}
private void registerListeners(VehicleDataService vehicleDataService) {
HashMap<String, VehicleData> vehicleDataMap = vehicleDataService.getMapVehicleDatabyName();
if (vehicleDataMap.containsKey("AccelerationPedal")) {
VehicleData data = vehicleDataMap.get("AccelerationPedal");
data.addCellValueListener(this);
setAccelerationPedal(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("VehicleAcceleration")) {
VehicleData data = vehicleDataMap.get("VehicleAcceleration");
data.addCellValueListener(this);
setVehicleAcceleration(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("VehicleSpeed")) {
VehicleData data = vehicleDataMap.get("VehicleSpeed");
data.addCellValueListener(this);
setVehicleSpeed(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("DriveDirection")) {
VehicleData data = vehicleDataMap.get("DriveDirection");
data.addCellValueListener(this);
setDriveDirection(data.getVehicleDataCell());
setReverseLight(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("YawRate")) {
VehicleData data = vehicleDataMap.get("YawRate");
data.addCellValueListener(this);
setYawRate(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("LateralAcceleration")) {
VehicleData data = vehicleDataMap.get("LateralAcceleration");
data.addCellValueListener(this);
setLateralAcceleration(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("BrakePressure")) {
VehicleData data = vehicleDataMap.get("BrakePressure");
data.addCellValueListener(this);
setBrakePressure(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("AccelerationControl")) {
VehicleData data = vehicleDataMap.get("AccelerationControl");
data.addCellValueListener(this);
setAccelerationControl(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("LowBeam")) {
VehicleData data = vehicleDataMap.get("LowBeam");
data.addCellValueListener(this);
setLowBeam(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("HighBeam")) {
VehicleData data = vehicleDataMap.get("HighBeam");
data.addCellValueListener(this);
setHighBeam(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("HazardLigths")) {
VehicleData data = vehicleDataMap.get("HazardLigths");
data.addCellValueListener(this);
setHazardLigths(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("TurnLeft")) {
VehicleData data = vehicleDataMap.get("TurnLeft");
data.addCellValueListener(this);
setTurnLeft(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("TurnRight")) {
VehicleData data = vehicleDataMap.get("TurnRight");
data.addCellValueListener(this);
setTurnRight(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("WarningLights")) {
VehicleData data = vehicleDataMap.get("WarningLights");
data.addCellValueListener(this);
setWarningLights(data.getVehicleDataCell());
}
if (vehicleDataMap.containsKey("SteeringWheel")) {
VehicleData data = vehicleDataMap.get("SteeringWheel");
data.addCellValueListener(this);
setSteeringWheel(data.getVehicleDataCell());
}
/*if (vehicleDataMap.containsKey("EmergencyService")) {
VehicleData data = vehicleDataMap.get("EmergencyService");
data.addCellValueListener(this);
setEmergencyService(data.getVehicleDataCell());
}*/
}
/*
private void setEmergencyService(Cell cell) {
int emergencyServiceInt = 0;
if (cell.getCellType() == CellType.StateDataCell) {
StateDataCell dataCell = (StateDataCell) cell;
emergencyServiceInt = (int) dataCell.getCellValue();
if (emergencyServiceInt == 1) {
this.emergencyServiceCan = true;
} else {
this.emergencyServiceCan = false;
}
Activator.println("EmergencyServiceCan: " + emergencyServiceCan);
checkEmergency();
}
}
private void checkEmergency() {
if (emergencyServiceCan) {
Activator.println("Priority Activated");
setLigthSirenLb(true);
CanWriterThread.setStatus(1);
} else {
setLigthSirenLb(false);
CanWriterThread.setStatus(2);
}
}*/
// AccelerationPedal
private void setAccelerationPedal(Cell cell) {
if (cell.getCellType() == CellType.DataCell) {
DataCell dataCell = (DataCell) cell;
this.accelerationPedal = dataCell.getCellValue();
if (this.accelerationPedal > 0.0) {
setGasPedalActivated(true);
} else {
setGasPedalActivated(false);
}
Activator.println("AccPedal: " + accelerationPedal);
}
}
// BrakePressure
private void setBrakePressure(Cell cell) {
if (cell.getCellType() == CellType.DataCell) {
DataCell dataCell = (DataCell) cell;
this.brakePressure = dataCell.getCellValue();
this.brakePressure05 = (int) (dataCell.getCellValue() / 0.5);
if (this.brakePressure > 0.0) {
setBrakeActivated(true);
} else {
setBrakeActivated(false);
}
Activator.println("BrakePressure: " + brakePressure);
}
}
public int getBrakePressure() {
return this.brakePressure05;
}
// AccelerationControl
private void setAccelerationControl(Cell cell) {
if (cell.getCellType() == CellType.StateDataCell) {
StateDataCell dataCell = (StateDataCell) cell;
this.accelerationControl = (int) dataCell.getCellValue();
setSpeedLimiter(false);
setAcc(false);
setCruiseControl(false);
switch (this.accelerationControl) {
case 1:
setCruiseControl(true);
break;
case 2:
setSpeedLimiter(true);
break;
case 3:
setAcc(true);
break;
default:
break;
}
Activator.println("AccControl: " + accelerationControl);
}
}
// VehicleSpeed
private void setVehicleSpeed(Cell cell) {
// 0.01ms
if (cell.getCellType() == CellType.DataCell) {
// Speed in Km/h
DataCell dataCell = (DataCell) cell;
// Change to 0.01 m/s
this.speed = (long) (dataCell.getCellValue() * 3.6);
// this.vehicleSpeedKM100 = dataCell.getCellValue() * 100;
if (this.speed < 0 || this.speed > 16382) {
this.speed = SpeedValue.unavailable;
this.curvature = CurvatureValue.unavailable;
} else {
setCurvature();
}
Activator.println("Speed: " + this.speed);
}
}
public long getVehicleSpeed() {
return this.speed;
}
// VehicleAcceleration
private void setVehicleAcceleration(Cell cell) {
if (cell.getCellType() == CellType.DataCell) {
DataCell dataCell = (DataCell) cell;
// Acceleration in 0.1 m/s2
this.vehicleAcceleration = (long) (dataCell.getCellValue());
if (this.vehicleAcceleration < -160 || this.vehicleAcceleration > 160) {
this.vehicleAcceleration = 161;
}
Activator.println("VehicleAcc: " + vehicleAcceleration);
}
}
public long getVehicleAcceleration() {
return this.vehicleAcceleration;
}
// YawRate
private void setYawRate(Cell cell) {
if (cell.getCellType() == CellType.DataCell) {
DataCell dataCell = (DataCell) cell;
// YawRate in 0.01 º/s
this.yawRate = (long) (dataCell.getCellValue());
if (this.yawRate < -32766 || this.yawRate > 32766) {
this.yawRate = 32767;
}
Activator.println("YawRate: " + yawRate);
}
}
public long getYawRate() {
return this.yawRate;
}
private void setSteeringWheel(Cell cell) {
DataCell dataCell = (DataCell) cell;
this.steeringWheel = (int) (dataCell.getCellValue() / 1.5);
if (this.steeringWheel >= 511) {
this.steeringWheel = 511;
}
if (this.steeringWheel <= -511) {
this.steeringWheel = -511;
}
Activator.println("SteeringWheel: " + steeringWheel);
}
public int getSteeringWheelAngle() {
return this.steeringWheel;
}
// LateralAcceleration
private void setLateralAcceleration(Cell cell) {
if (cell.getCellType() == CellType.DataCell) {
DataCell dataCell = (DataCell) cell;
this.lateralAcceleration = (long) (dataCell.getCellValue());
if (this.lateralAcceleration < -160 || this.lateralAcceleration > 160) {
this.lateralAcceleration = 161;
}
Activator.println("LatAcc: " + lateralAcceleration);
}
}
public long getLateralAcceleration() {
return this.lateralAcceleration;
}
// Curvature
public long getCurvature() {
return this.curvature;
}
public void setCurvature() {
this.curvature = 1023;
if (this.speed > 0) {
double radius = (this.yawRate / this.speed) * (Math.PI / 180);
this.curvature = (long) (1 / radius) * 10000;
}
if (this.curvature < -1023) {
this.curvature = -1023;
}
if (this.curvature > 1022) {
this.curvature = 1022;
}
}
public boolean isHighBeam() {
return highBeam;
}
public void setHighBeam(boolean highBeam) {
this.highBeam = highBeam;
}
private void setHighBeam(Cell cell) {
int highBeamInt = 0;
if (cell.getCellType() == CellType.StateDataCell) {
StateDataCell dataCell = (StateDataCell) cell;
highBeamInt = (int) dataCell.getCellValue();
if (highBeamInt == 1) {
this.highBeam = true;
} else {
this.highBeam = false;
}
Activator.println("HighBeam: " + highBeam);
}
}
// LowBeam
private void setLowBeam(Cell cell) {
int lowBeamInt = 0;
if (cell.getCellType() == CellType.StateDataCell) {
StateDataCell dataCell = (StateDataCell) cell;
lowBeamInt = (int) dataCell.getCellValue();
if (lowBeamInt == 1) {
this.lowBeam = true;
} else {
this.lowBeam = false;
}
Activator.println("LowBeam: " + lowBeam);
}
}
public boolean isLowBeam() {
return this.lowBeam;
}
public boolean isDayTimeRunning() {
return dayTimeRunning;
}
public void setDayTimeRunning(boolean dayTimeRunning) {
this.dayTimeRunning = dayTimeRunning;
}
public boolean isReverseLight() {
return reverseLight;
}
public void setReverseLight(boolean reverseLight) {
this.reverseLight = reverseLight;
}
private void setReverseLight(Cell cell) {
int reverseLightInt = 0;
if (cell.getCellType() == CellType.StateDataCell) {
StateDataCell dataCell = (StateDataCell) cell;
reverseLightInt = (int) dataCell.getCellValue();
if (reverseLightInt == 1) {
this.reverseLight = true;
} else {
this.reverseLight = false;
}
Activator.println("ReverseLight: " + reverseLight);
}
}
public boolean isFogLight() {
return fogLight;
}
public void setFogLight(boolean fogLight) {
this.fogLight = fogLight;
}
public boolean isParkingLights() {
return parkingLights;
}
public void setParkingLights(boolean parkingLights) {
this.parkingLights = parkingLights;
}
// DriveDirection
private void setDriveDirection(Cell cell) {
if (cell.getCellType() == CellType.StateDataCell) {
StateDataCell dataCell = (StateDataCell) cell;
int canDriveDirection = (int) dataCell.getCellValue();
this.driveDirection = canDriveDirection;
// switch (canDriveDirection) {
// case 0:
// this.driveDirection = 2;
// break;
// case 1:
// this.driveDirection = 0;
// break;
// case 2:
// this.driveDirection = 1;
// break;
// case 3:
// this.driveDirection = 2;
// break;
//
// default:
// break;
// }
Activator.println("DriveDirection: " + driveDirection);
}
}
public final int getDriveDirection() {
return this.driveDirection;
}
// SpeedLimiter
public boolean isSpeedLimiter() {
return speedLimiter;
}
private void setSpeedLimiter(boolean speedLimiter) {
this.speedLimiter = speedLimiter;
}
// Acc
public boolean isAcc() {
return acc;
}
private void setAcc(boolean acc) {
this.acc = acc;
}
// CruiseControl
public boolean isCruiseControl() {
return cruiseControl;
}
private void setCruiseControl(boolean cruiseControl) {
this.cruiseControl = cruiseControl;
}
// BrakeActivated
public boolean isBrakeActivated() {
return brakeActivated;
}
private void setBrakeActivated(boolean brakeActivated) {
this.brakeActivated = brakeActivated;
}
// GasPedalActivated
public boolean isGasPedalActivated() {
return gasPedalActivated;
}
private void setGasPedalActivated(boolean gasPedalActivated) {
this.gasPedalActivated = gasPedalActivated;
}
public boolean isEmergencyBrake() {
return emergencyBrake;
}
public void setEmergencyBrake(boolean emergencyBrake) {
this.emergencyBrake = emergencyBrake;
}
public boolean isCollisionWarning() {
return collisionWarning;
}
public void setCollisionWarning(boolean collisionWarning) {
this.collisionWarning = collisionWarning;
}
// HazardLights
private void setHazardLigths(Cell cell) {
StateDataCell dataCell = (StateDataCell) cell;
this.hazardLights = (int) dataCell.getCellValue();
Activator.println("HazardLights: " + hazardLights);
}
public boolean isHazardLights() {
boolean hazardLights = false;
if (this.hazardLights == 1) {
hazardLights = true;
}
return hazardLights;
}
// TurnRight
private void setTurnRight(Cell cell) {
// TODO Auto-generated method stub
StateDataCell dataCell = (StateDataCell) cell;
if ((int) (dataCell.getCellValue()) == 0) {
this.turnRight = false;
} else {
this.turnRight = true;
}
Activator.println("TurnRight: " + turnRight);
}
public boolean isTurnRightActivated() {
return turnRight;
}
// TurnLeft
private void setTurnLeft(Cell cell) {
// TODO Auto-generated method stub
StateDataCell dataCell = (StateDataCell) cell;
if ((int) (dataCell.getCellValue()) == 0) {
this.turnLeft = false;
} else {
this.turnLeft = true;
}
Activator.println("TurnLeft: " + turnLeft);
}
public boolean isTurnLeftActivated() {
return turnLeft;
}
// WarningLights
private void setWarningLights(Cell cell) {
// TODO Auto-generated method stub
StateDataCell dataCell = (StateDataCell) cell;
this.warningLights = (int) dataCell.getCellValue();
Activator.println("WarningLights: " + warningLights);
}
public boolean isWarningLightsActivated() {
boolean warningLights = false;
if (this.warningLights == 1) {
warningLights = true;
}
return warningLights;
}
public int getVehicleRole() {
return vehicleRole;
}
public void setVehicleRole(int vehicleRole) {
this.vehicleRole = vehicleRole;
}
public int getStationType() {
return stationType;
}
public void setStationType(int stationType) {
this.stationType = stationType;
}
public boolean isEmbarkationStatus() {
return embarkationStatus;
}
public void setEmbarkationStatus(boolean embarkationStatus) {
this.embarkationStatus = embarkationStatus;
}
public int getPtActivationType() {
return ptActivationType;
}
public void setPtActivationType(int ptActivationType) {
this.ptActivationType = ptActivationType;
}
public byte[] getPtActivationData() {
return ptActivationData;
}
public void setPtActivationData(byte[] ptActivationData) {
this.ptActivationData = ptActivationData;
}
public int getDangerousGoods() {
return dangerousGoods;
}
public void setDangerousGoods(int dangerousGoods) {
this.dangerousGoods = dangerousGoods;
}
public boolean isLigthSirenLb() {
return ligthSirenLb;
}
public void setLigthSirenLb(boolean ligthSirenLb) {
this.ligthSirenLb = ligthSirenLb;
}
public boolean isLigthSirenS() {
return ligthSirenS;
}
public void setLigthSirenS(boolean ligthSirenS) {
this.ligthSirenS = ligthSirenS;
}
public void stopThread() {
this.isRunning = false;
if (this.socket != null) {
this.socket.close();
}
}
}
</code></pre>
<p>AccelerationChecker class code:</p>
<pre><code>public class AccelerationChecker{
private long currentAcceleration;
private double startTime;
private double currentTime;
private double elapsedTime;
private boolean flag;
public AccelerationChecker() {
this.currentAcceleration = 0;
this.flag = false;
this.startTime = 0;
this.currentTime = 0;
}
public void handleAccelerationCheck(long newValue) {
if(newValue < -7) {
this.startTime = System.nanoTime();
this.currentTime = System.nanoTime();
this.elapsedTime = this.currentTime - this.startTime;
if(this.elapsedTime >= 500) {
this.flag = true;
}
else {
this.flag = false;
}
}
}
public boolean getFlag() {
return flag;
}
}
</code></pre>
| [
{
"answer_id": 74194780,
"author": "Rob Spoor",
"author_id": 1180351,
"author_profile": "https://Stackoverflow.com/users/1180351",
"pm_score": 0,
"selected": false,
"text": "-parameters"
},
{
"answer_id": 74244580,
"author": "Alexander Ivanchenko",
"author_id": 17949945,
... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18556811/"
] |
74,193,288 | <p>I'm trying to implement the calculation of the distance from a point to a line in a 3d space in C++. For the line I'm given the direction of the line and a point on the line, as well as the point I'm calculating the distance from. How would I go about doing this?</p>
<p>I've never done this before when given the direction of the line and a point, I've only done it when given the start and end points of line, so I'm a bit stuck, and I'm not really sure what to search and can't find much info of what to do when only given the direction.</p>
<p>Any help would be appreciated. Thanks.</p>
| [
{
"answer_id": 74193631,
"author": "Aconcagua",
"author_id": 1312382,
"author_profile": "https://Stackoverflow.com/users/1312382",
"pm_score": 1,
"selected": false,
"text": "b"
},
{
"answer_id": 74194660,
"author": "Soonts",
"author_id": 126995,
"author_profile": "htt... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19232648/"
] |
74,193,316 | <p>I want to filter/search on negative dates/times in a column. I already filtered the difference between dates, dropped NaN and create frame via:</p>
<pre><code>df = (df['date1'] - df['date2']).dropna().to_frame(name=None)
</code></pre>
<p><strong>Result of dataset</strong></p>
<pre><code> 0
0 8 days 00:00:00
1 8 days 00:00:00
2 43 days 00:00:00
3 -42 days 06:50:00
4 147 days 23:00:00
</code></pre>
<p><strong>I tried this:</strong></p>
<p>I tried using timedelta or searching on values but that did not work.</p>
<p><strong>Expected result</strong></p>
<pre><code> 0
3 -42 days 06:50:00
</code></pre>
<p>Appreciate the help and effort. Thank you!</p>
| [
{
"answer_id": 74193631,
"author": "Aconcagua",
"author_id": 1312382,
"author_profile": "https://Stackoverflow.com/users/1312382",
"pm_score": 1,
"selected": false,
"text": "b"
},
{
"answer_id": 74194660,
"author": "Soonts",
"author_id": 126995,
"author_profile": "htt... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20301326/"
] |
74,193,320 | <p>Help fix the code. I tried to write a code that helps to sum 15 given fractions, but when i run the code it throws an error:</p>
<blockquote>
<p>"error CS9010: Primary constructor body is not allowed"</p>
</blockquote>
<p>An error was detected in a method that should sum fractions.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
public static void Main(string[] args)
{
MyStruct Q = new MyStruct(0, 0);
Q.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + Q.c);
Q.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + Q.z);
MyStruct W = new MyStruct(0, 0);
W.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + W.c);
W.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + W.z);
MyStruct E = new MyStruct(0, 0);
E.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + E.c);
E.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + E.z);
MyStruct R = new MyStruct(0, 0);
R.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + R.c);
R.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + R.z);
MyStruct T = new MyStruct(0, 0);
T.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + T.c);
T.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + T.z);
MyStruct Y = new MyStruct(0, 0);
Y.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + Y.c);
Y.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + Y.z);
MyStruct U = new MyStruct(0, 0);
U.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + U.c);
U.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + U.z);
MyStruct I = new MyStruct(0, 0);
I.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + I.c);
I.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + I.z);
MyStruct O = new MyStruct(0, 0);
O.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + O.c);
O.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + O.z);
MyStruct P = new MyStruct(0, 0);
P.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + P.c);
P.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + P.z);
MyStruct A = new MyStruct(0, 0);
A.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + A.c);
A.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + A.z);
MyStruct S = new MyStruct(0, 0);
S.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + S.c);
S.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + S.z);
MyStruct D = new MyStruct(0, 0);
D.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + D.c);
D.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + D.z);
MyStruct F = new MyStruct(0, 0);
F.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + F.c);
F.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + F.z);
MyStruct G = new MyStruct(0, 0);
G.c = int.Parse(Console.ReadLine());
Console.WriteLine("Числитель дроби = " + G.c);
G.z = int.Parse(Console.ReadLine());
Console.WriteLine("Знаменатель дроби = " + G.z);
MyStruct c;
c = Program.SummStruct(Q,W,E,R,T,Y,U,I,O,P,A,S,D,F,G);
Console.WriteLine("Cложение: " + Q.ToString() + "+" + W.ToString() + "+" + E.ToString() + "+" + R.ToString() + "+" + T.ToString() + "+" + Y.ToString() + "+" + U.ToString() + "+" + I.ToString() + "+" + O.ToString() + "+" + P.ToString() + "+" + A.ToString() + "+" + S.ToString() + "+" + D.ToString() + "+" + F.ToString() + "+" + G.ToString() + "=" + c.ToString());
Console.ReadKey();
}
public static MyStruct SummStruct(params MyStruct[] p) => p.Aggregate((f,s) => SummStruct(f,s)); //error here
{
MyStruct t = new MyStruct(0, 0);
t.c = (a.c * b.z + a.z * b.c);
t.z = a.z * b.z;
return t;
}
public struct MyStruct
{
public double c;
public double z;
public MyStruct(int c, int z)
{
this.c = c;
this.z = z;
}
public override string ToString()
{
return "(" + c.ToString() + "/" + z.ToString() + ")";
}
}
}
</code></pre>
| [
{
"answer_id": 74193475,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 1,
"selected": false,
"text": ";"
},
{
"answer_id": 74193583,
"author": "Midnight Lizard",
"author_id": 16041376,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329627/"
] |
74,193,324 | <p>I have a Django app that was running without any problem with SQL server 2008,
I have an issue like this after I upgraded the MS SQL server 2008 into 2019.
I didn't change anything in the code but when I'm calling the DB, I face this error:</p>
<blockquote>
<p>42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot find either column "dbo" or the user-defined function or aggregate dbo.REGEXP_LIKE", or the name is ambiguous.<br />
(4121) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]<br />
Statement(s) could not be prepared. (8180)</p>
</blockquote>
| [
{
"answer_id": 74193475,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 1,
"selected": false,
"text": ";"
},
{
"answer_id": 74193583,
"author": "Midnight Lizard",
"author_id": 16041376,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3672820/"
] |
74,193,339 | <p>I have tried to use datediff however it only gives the hour difference between two dates. I would like to receive only the hours that are during the working days and working hours. Example provided below:</p>
<p>Start Date:
19/08/2022 09:42:13</p>
<p>End Date:
22/08/2022 09:54:22</p>
<p>Outcome I receive from Datediff("HH", [Start Date], [End Date]) = 72.20</p>
<p>The actual outcome I would like would be approx. = 8.13</p>
| [
{
"answer_id": 74193475,
"author": "hossein sabziani",
"author_id": 4301195,
"author_profile": "https://Stackoverflow.com/users/4301195",
"pm_score": 1,
"selected": false,
"text": ";"
},
{
"answer_id": 74193583,
"author": "Midnight Lizard",
"author_id": 16041376,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329714/"
] |
74,193,340 | <p>I am running a finance related web portal which involve millions of debit credit transactions in MySQL , getting the balance of a specific user at a certain limit i.e. with 3 million rows becomes slow.</p>
<blockquote>
<p>Now I am thinking to create separate MySQL container for each user and record only the relevant user transactions in every container and I am sure It will be fast to calculate balance of any user.
I have around 20 thousands of user and I wants to know is it practical to create separate MySQL container for each user ? or shall I go for any other approach. Thanks</p>
</blockquote>
| [
{
"answer_id": 74212580,
"author": "Rick James",
"author_id": 1766831,
"author_profile": "https://Stackoverflow.com/users/1766831",
"pm_score": 0,
"selected": false,
"text": "History"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20281703/"
] |
74,193,346 | <p>I am trying to open an existing .txt file to iterate through its lines. To do this, in my <code>HelloArActivityTest2.java</code> class, I have used the commonly used code, that uses a Scanner that takes a file as a parameter:</p>
<pre><code>File myObj = new File("app/src/main/assets/models/prov.txt");
Scanner myReader = new Scanner(myObj);
int counter = 0;
while (myReader.hasNextLine() && counter <= 10) {
String data = myReader.nextLine();
System.out.println(data);
counter ++;
}
myReader.close();
</code></pre>
<p>But I get this error:</p>
<pre><code>2022-10-25 12:49:56.172 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: java.io.FileNotFoundException: C:/Users/serer/Desktop/Proyecto02/project_name/project_name/app/src/main/assets/models/prov.txt: open failed: ENOENT (No such file or directory)
2022-10-25 12:49:56.172 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
2022-10-25 12:49:56.172 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:160)
2022-10-25 12:49:56.172 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at java.util.Scanner.<init>(Scanner.java:620)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at com.google.ar.core.examples.java.helloar.HelloArActivityTest2.helloArActivityTest(HelloArActivityTest2.java:210)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:549)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.rules.RunRules.evaluate(RunRules.java:20)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
2022-10-25 12:49:56.173 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
2022-10-25 12:49:56.174 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:162)
2022-10-25 12:49:56.174 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.Suite.runChild(Suite.java:128)
2022-10-25 12:49:56.174 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.Suite.runChild(Suite.java:27)
2022-10-25 12:49:56.174 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
2022-10-25 12:49:56.174 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
2022-10-25 12:49:56.174 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
2022-10-25 12:49:56.176 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
2022-10-25 12:49:56.176 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
2022-10-25 12:49:56.176 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
2022-10-25 12:49:56.176 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
2022-10-25 12:49:56.176 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
2022-10-25 12:49:56.176 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
2022-10-25 12:49:56.177 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:444)
2022-10-25 12:49:56.177 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2205)
2022-10-25 12:49:56.179 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
2022-10-25 12:49:56.180 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at libcore.io.Linux.open(Native Method)
2022-10-25 12:49:56.180 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
2022-10-25 12:49:56.180 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
2022-10-25 12:49:56.180 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
2022-10-25 12:49:56.180 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
2022-10-25 12:49:56.180 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
2022-10-25 12:49:56.180 12110-12132/com.google.ar.core.examples.java.helloar W/System.err: ... 33 more
</code></pre>
<p>I have tried to copy the <code>prov.txt</code> file to other project locations, to see if the path was taken properly. And I also read other discussions on forums like this, and tried other ways. But the error still persists. Do you know what could be happening? To clarify it more, these are two screenshots of extra places where I copied the <code>prov.txt</code> file to debug.</p>
<p><a href="https://i.stack.imgur.com/Gqb3d.jpg" rel="nofollow noreferrer">Copied file (I)</a></p>
<p><a href="https://i.stack.imgur.com/4hV6N.jpg" rel="nofollow noreferrer">Copied file (II)</a></p>
<p>Also, this is the code that I am using in my <code>HelloArActivityTest2.java</code> class, with all the tries I did:</p>
<pre><code>try {
//File myObj = new File("app/assets/models/prov.txt");
//File myObj = new File("app/src/main/assets/models/prov.txt");
//File myObj = new File("prov.txt");
//File myObj = new File(new File("app/src/main/assets/models/prov.txt").getAbsolutePath());
//File myObj = new File(path.trim());
//File myObj = new File(Objects.requireNonNull(HelloArActivityTest2.class.getResource("app/src/main/assets/models/prov.txt")).toURI());
//System.out.println("user.dir = " + System.getProperty("user.dir"));
//String path = System.getProperty("user.dir") + "src/androidTest/prov.txt";
//String path = System.getProperty("user.dir") + "\\src\\androidTest\\prov.txt";
//MockHttpServletRequest request = new MockHttpServletRequest();
//String path = request.getSession().getServletContext().getRealPath("/");
File myObj = new File("app/src/main/assets/models/prov.txt");
//myObj.setReadable(true);
//myObj.setWritable(true);
System.out.println("myObj.mkdirs() = " + myObj.mkdirs()); //false
System.out.println("myObj.exists() = " + myObj.exists()); //false
System.out.println("myObj.isDirectory() = " + myObj.isDirectory()); //false
System.out.println("myObj.canRead() = " + myObj.canRead()); //false
System.out.println("Current directory: " + new File(".").getAbsolutePath()); // /.
Scanner myReader = new Scanner(myObj);
int counter = 0;
while (myReader.hasNextLine() && counter <= 10) {
String data = myReader.nextLine();
System.out.println(data);
counter ++;
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
</code></pre>
<p>Any help is welcome. Thanks in advance.</p>
| [
{
"answer_id": 74212580,
"author": "Rick James",
"author_id": 1766831,
"author_profile": "https://Stackoverflow.com/users/1766831",
"pm_score": 0,
"selected": false,
"text": "History"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19328615/"
] |
74,193,382 | <p>I have a json array called <strong>attachments</strong> where I need to sort based on <strong>sort_based_on_this_order</strong> array.</p>
<pre><code>var sort_based_on_this_order = ['1666432801510', '1666434048280', '1666433926644', '1666434169913', '1666433101760', '1666434194815', '1666432849037', '1666432764144', '1666432044571', '1666432742444']
</code></pre>
<p>sort_based_on_this_order array contains the filename key value of attachments json array</p>
<pre><code>var attachments = [
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978911/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666433926644.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978911
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978910/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666434169913.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978910
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978909/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666434048280.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978909
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978907/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666433101760.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978907
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978905/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666434194815.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978905
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978904/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666432849037.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978904
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978903/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666432801510.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978903
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978902/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666432764144.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978902
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978901/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666432044571.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978901
},
{
"download_small_url": "https://kf.kobotoolbox.org/api/v2/assets/ajDWYWQoe9Gw6WAnK8H4fG/data/194338021/attachments/82978900/",
"mimetype": "image/jpeg",
"filename": "deploymentsmaster/attachments/a46854ceb37c4e55b4a2c5ea565c4ebf/04ac3197-7d0f-4301-bbaf-68daaee2b1a8/1666432742444.jpg",
"instance": 194338021,
"xform": 740320,
"id": 82978900
}
]
</code></pre>
<p>I have tried with</p>
<pre><code>attachments.sort.forEach(zz => {
return zz["filename"].match(/\b[0-9]{13}(?=\.[^.]+$)/)
})
</code></pre>
| [
{
"answer_id": 74193487,
"author": "D.J. Kalmann",
"author_id": 4654757,
"author_profile": "https://Stackoverflow.com/users/4654757",
"pm_score": -1,
"selected": false,
"text": "attachments"
},
{
"answer_id": 74193538,
"author": "flyingfox",
"author_id": 3176419,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5549354/"
] |
74,193,415 | <p>I'm practicing with BeautifulSoup and HTML requests in general for the first time. The goal of the programme is to load a webpage and it's HTML, then search through the webpage (in this case a recipe, to get a sub string of it's ingredients). I've managed to get it working with the following code:</p>
<pre><code>url = "https://www.bbcgoodfood.com/recipes/healthy-tikka-masala"
result = requests.get(url)
myHTML = result.text
index1 = myHTML.find("recipeIngredient")
index2 = myHTML.find("recipeInstructions")
ingredients = myHTML[index1:index2]
</code></pre>
<p>But when I try and use BeautifulSoup here:</p>
<pre><code>url = "https://www.bbcgoodfood.com/recipes/healthy-tikka-masala"
result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")
ingredients = doc.find(text = "recipeIngredient")
print(ingredients)
</code></pre>
<p>I understand that the code above (even if I could get it working) would produce a different output of just ["recipeIngredient"] but that's all I'm focused on for now whilst I get to grips with BS. Instead the code above just outputs None. I printed "doc" to the terminal and it would only output what appears to be the second half of the HTML (or at least : not all of it). Whereas , the text file does contain all HTML, so I assume that's where the problem lies but i'm not sure how to fix it.</p>
<p>Thank you.</p>
| [
{
"answer_id": 74193487,
"author": "D.J. Kalmann",
"author_id": 4654757,
"author_profile": "https://Stackoverflow.com/users/4654757",
"pm_score": -1,
"selected": false,
"text": "attachments"
},
{
"answer_id": 74193538,
"author": "flyingfox",
"author_id": 3176419,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6714815/"
] |
74,193,441 | <p>I'm trying to make a vue3 app run in a apache2 server, I did apache configuration of the site in sites-available and also did the symlink to sites-enabled. I don't have the ServerName ready bc I wanted to test it using the direct path from /var and when it's ready use the DNS. Here is the file:</p>
<pre><code><VirtualHost *:80>
# ServerName xyz.example.com.br
# ServerAlias xyz.example.com.br
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/agenda/dist
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code></pre>
<p>and my app is at var/www/html with the dist folder generated from <em>yarn run build</em>, as it is referenced in the file above. Here is the index.html from the dist folder:</p>
<pre><code><!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/hrg.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Agenda Eletrônica</title>
<script type="module" crossorigin src="./assets/index.02c23677.js"></script>
<link rel="stylesheet" type="text/css" href="./assets/index.db6e77a5.css">
</head>
<body>
<div id="app"></div>
</body>
</html>
</code></pre>
<p>I added the dot before the href links because otherwise it interprets as the files are located at the /, not /dist (at least it was happening with the js file).</p>
<p>Anyways it just does not work. When I access the IP of the server followed by /agenda/dist it does not show anything, only favicon is loaded. It also doesn't bring any errors on browser console.</p>
<p>I would try to use nginx, but we do not use it here so I would like to keep it that way and only use it if necessary (maybe that's the case).</p>
<p>P.S: I'm using vite</p>
| [
{
"answer_id": 74193487,
"author": "D.J. Kalmann",
"author_id": 4654757,
"author_profile": "https://Stackoverflow.com/users/4654757",
"pm_score": -1,
"selected": false,
"text": "attachments"
},
{
"answer_id": 74193538,
"author": "flyingfox",
"author_id": 3176419,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20111247/"
] |
74,193,442 | <p>In my <code>nextjs</code>-app I have <code>Navbar</code>-component, where I pass the menu items as a props:</p>
<pre><code><Navbar navitems={navigationItems} />
</code></pre>
<p>the <code>navigationItems</code> is an array of objects.</p>
<p>then in the <code>Navbar</code>-component I have this:</p>
<pre><code>export interface INavBarItem {
id: string;
text: string;
path: {
slug: string;
};
}
export type INavBar = INavBarItem[];
const Navbar: React.FC<INavBar> = ({ navitems }) => { ... }
</code></pre>
<p>Now I get the error <code>Type error: Type '{ navitems: any; }' is not assignable to type 'IntrinsicAttributes & INavBar'.Property 'navitems' does not exist on type 'IntrinsicAttributes & INavBar'.</code></p>
<p>what am I doing wrong here?</p>
| [
{
"answer_id": 74193487,
"author": "D.J. Kalmann",
"author_id": 4654757,
"author_profile": "https://Stackoverflow.com/users/4654757",
"pm_score": -1,
"selected": false,
"text": "attachments"
},
{
"answer_id": 74193538,
"author": "flyingfox",
"author_id": 3176419,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3955607/"
] |
74,193,446 | <p>I have this code here and I'm trying to do decimal to hexadecimal conversion without using arrays. It is working pretty much but it gives me wrong answers for values greater than 1000. What am I doing wrong? are there any counter solutions? kindly can anyone give suggestions how to improve this code.</p>
<pre><code>for(int i = num; i > 0; i = i/16)
{
temp = i % 16;
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
num = num * 100 + temp;
}
cout<<"Hexadecimal = ";
for(int j = num; j > 0; j = j/100)
{
ch = j % 100;
cout << ch;
}
</code></pre>
| [
{
"answer_id": 74193487,
"author": "D.J. Kalmann",
"author_id": 4654757,
"author_profile": "https://Stackoverflow.com/users/4654757",
"pm_score": -1,
"selected": false,
"text": "attachments"
},
{
"answer_id": 74193538,
"author": "flyingfox",
"author_id": 3176419,
"aut... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19724304/"
] |
74,193,493 | <p>I have this problem where I can't replace elements for 'numVect' through a function 'InputNumbers()' using user input. I tried to create a new vector in the function, and then define it as 'numVect' but no success.</p>
<pre><code>#include <iostream>
#include <vector>
using namespace std;
vector <int> InputNumbers(vector <int> numVect) {
vector <int> numVect2 = {};
cout << "Input 5 numbers into a vector: " << endl;
for (int i = 0; i < 5; i++) {
cin >> numVect2[i];
}
return numVect2;
}
// void VectorRow();
// void VectorStack();
// void VectorTwoStacks();
void OutputNumbers(vector <int> numVect) {
cout << "Vector: " << endl;
for (auto i : numVect) {
cout << i << " ";
}
cout << endl;
}
int main() {
vector <int> numVect = {4, 5, 6, 7, 8};
enum menu {Input = 1, Row = 2, Stack = 3,
Twostacks = 4, Numbers = 5};
int choice;
do {
cout << "1. Input numbers\n";
cout << "2. Row\n";
cout << "3. Stack\n";
cout << "4. Two stacks\n";
cout << "5. Output numbers\n";
cout << "6. End\n";
cout << "--------------------------\n";
cout << "Choice: "; cin >> choice; cout << endl;
switch (choice) {
case Input: InputNumbers(numVect); break;
// case Row: VectorRow(); break;
// case Stack: VectorStack(); break;
// case Twostacks: VectorTwoStacks(); break;
case Numbers: OutputNumbers(numVect); break;
}
} while (choice != 6);
return 0;
}
</code></pre>
<p>Also, when I run the function 'InputNumbers()', it stops the terminal after user inputs the [0] element for 'numVect2'</p>
<pre><code>Input 5 numbers into a vector:
1
PS C:\Users\leval\Desktop\majasdarbi\praktiskais_darbs2> 2
2
PS C:\Users\leval\Desktop\majasdarbi\praktiskais_darbs2>
</code></pre>
| [
{
"answer_id": 74197480,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 1,
"selected": false,
"text": "InputNumbers()"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18487151/"
] |
74,193,508 | <p>I am trying to generate a personal access token, I have followed steps mentioned in github documentation for the same</p>
<p>Expected output:</p>
<p><a href="https://i.stack.imgur.com/E9onj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E9onj.png" alt="enter image description here" /></a></p>
<p>but instead, the <strong>token is not visible</strong> as soon as click the generate button</p>
<p>Actual output:</p>
<p><a href="https://i.stack.imgur.com/qBRFb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qBRFb.png" alt="enter image description here" /></a></p>
<p><a href="https://youtu.be/bs3W7QkeZ3w" rel="nofollow noreferrer">proof-of-concept video</a></p>
<p>why the token is not visible here, are there any changes needed to be done before generating personal access token?</p>
| [
{
"answer_id": 74232354,
"author": "shreeramaute",
"author_id": 9639790,
"author_profile": "https://Stackoverflow.com/users/9639790",
"pm_score": 1,
"selected": true,
"text": "it must be checked with different platforms/browsers"
}
] | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9639790/"
] |
74,193,522 | <p>For the first time I encountered such a task, to implement a multi-threaded application using a database but without high-level libraries like Hibernate. Only JDBC.
The essence of the game: there is a Clan object that enters into battle with other clans and, depending on the result, the state of its treasury changes. Along with this, the Event object is stored in the database, which stores information about who fought with whom, how it ended, etc.
First, I implemented a clan repository:</p>
<pre><code>public class ClanRepository implements TestTaskRepository<Clan> {
private static Connection connection = ConnectionManager.open();
private static ResultSetConverter resultSetConverter = new ResultSetConverter();
private static Lock lock = new ReentrantLock();
@Override
public Clan findById(Long id) {
lock.lock();
try {
Clan clan = null;
try (PreparedStatement preparedStatement =
connection.prepareStatement("SELECT * FROM clans WHERE clan_id=?")) {
preparedStatement.setLong(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
clan = resultSetConverter.getClanFromResultSet(resultSet);
} catch (SQLException e) {
e.printStackTrace();
}
return clan;
} finally {
lock.unlock();
}
}
@Override
public void update(Clan clan) {
lock.lock();
try (PreparedStatement preparedStatement =
connection.prepareStatement("UPDATE clans SET clan_name =?, clan_gold=? WHERE clan_id=?")) {
preparedStatement.setString(1, clan.getName());
preparedStatement.setInt(2, clan.getGold());
preparedStatement.setLong(3, clan.getId());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
</code></pre>
<p>I set up a lock in the hope that this would change something and wrote a thread class in which the battle takes place:</p>
<pre><code>@Override
public void run() {
Random random = new Random();
boolean result = random.nextBoolean();
Clan currentClan = clanRepository.findById(CurrentUser.getClan().getId());
Clan enemyClan = clanRepository.findById(choiceOfEnemy().getClan().getId());
if (result) {
currentClan.setGold(currentClan.getGold + 100);
enemyClan.setGold(enemyClan.getGold - 100);
} else {
currentClan.setGold(currentClan.getGold - 100);
enemyClan.setGold(enemyClan.getGold + 100);
}
clanRepository.update(currentClan);
clanRepository.update(enemyClan);
}
</code></pre>
<p>As long as there is only one thread, everything works fine. When a second thread is connected, the data in the database is not saved correctly.
I decided that the point is that there is a time gap between receiving clans and saving them in a modified state. In this regard, I wrote the ActionServise class where I collected everything in one method and took the code of this method into lock(), unlock().</p>
<pre><code>public void action() {
lock.lock();
try {
Random random = new Random();
boolean result = random.nextBoolean();
Clan currentClan = clanRepository.findById(CurrentUser.getClan().getId());
Clan enemyClan = clanRepository.findById(choiceOfEnemy().getClan().getId());
if (result) {
currentClan.setGold(currentClan.getGold + 100);
enemyClan.setGold(enemyClan.getGold - 100);
} else {
currentClan.setGold(currentClan.getGold - 100);
enemyClan.setGold(enemyClan.getGold + 100);
}
clanRepository.update(currentClan);
clanRepository.update(enemyClan);
} finally {
lock.unlock();
}
</code></pre>
<p>In the run() method, I left only the call to this action() method
It still saves incorrect data.</p>
<p>Among other things, even if this solution worked, it represents a point at which all threads will queue up and there will be no parallel battles (please correct if this is not true)</p>
<p>Then I googled on the Internet that the problem is in the connection, in that it is one for all threads. I tried creating a connection for each thread and passing it along the chain to the repository itself. Did not help.</p>
<p>Considering the age of the technologies in question, I am sure that my problem has been solved a long time ago, Please tell me how this is done.</p>
| [
{
"answer_id": 74193993,
"author": "Stephen C",
"author_id": 139985,
"author_profile": "https://Stackoverflow.com/users/139985",
"pm_score": 2,
"selected": false,
"text": " BEGIN\n SELECT 1\n SELECT 2\n UPDATE 3\n UPDATE 4\n COMMIT\n"
},
{
"answer_id": 74194684,
"author": "Ma... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18146547/"
] |
74,193,524 | <p>I'm having a doble problems with my checkboxes on livewire component.</p>
<p>I'm trying to save in my form's table two checkboxes. This checkboxes take their value in an other table named "Garde_type".
Checkbox "home" save in my form's table the ID 1, checkbox "visit" save ID 2.
Here all is simple...but</p>
<p>Laravel livewire ask me property rules to save my data. Ok ! But when i put in rules my 2 checkboxes : in my form the checkbox can't be checked..when i check them they check/uncheck immediately = first problem.
Second problem : no matter check/uncheck...everytime i submit my form, the 2 checkboxes are consider "checked" and then saved in my DB.</p>
<p>Here you can take a look to my code, i tried many things but i have no idea any more.</p>
<p><strong>This is the livewire component "controler" :</strong></p>
<pre><code>class VilleSelect extends Component {
public $visit;
public $home;
public $user_id;
protected function rules() {
return [
'visit' => 'nullable',
'home' => 'nullable',
];
}
public function submit() {
$annonces=annonces::create([
'home' => $this->home->id,
'visit' => $this->visit->id,
]);
$annonces->save();
}
</code></pre>
<p>This is the checkboxes :</p>
<pre><code> <div class="mt-4 space-y-4">
<div class="flex items-start">
<div class="flex h-5 items-center">
<x-jet-input wire:model="home" value="{{$home->id}}" type="checkbox"/>
</div>
<div class="ml-3 text-sm">
<x-jet-label for="home" value="{{$home->garde_type}}"/>
</div>
</div>
<div class="flex items-start">
<div class="flex h-5 items-center">
<x-jet-input wire:model='visit' value="{{$visit->id}}" type="checkbox"/>
</div>
<div class="ml-3 text-sm">
<x-jet-label for="visit" value="{{$visit->garde_type}}"/>
</div>
</div>
</div>
</code></pre>
| [
{
"answer_id": 74193993,
"author": "Stephen C",
"author_id": 139985,
"author_profile": "https://Stackoverflow.com/users/139985",
"pm_score": 2,
"selected": false,
"text": " BEGIN\n SELECT 1\n SELECT 2\n UPDATE 3\n UPDATE 4\n COMMIT\n"
},
{
"answer_id": 74194684,
"author": "Ma... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20224440/"
] |
74,193,542 | <p>In quarto, we have the option to control the default <a href="https://quarto.org/docs/computations/r.html#data-frames" rel="nofollow noreferrer">printing of dataframes</a>, e.g.</p>
<pre><code>---
title: "Example"
format:
html:
df-print: kable
---
## example kable
```{r}
mtcars |> head()
dim(mtcars)
```
</code></pre>
<p><a href="https://i.stack.imgur.com/eX8MK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eX8MK.png" alt="example kable" /></a></p>
<p>Now I would like to make some <code>kable_styling</code> to make it more appealing. I found an option that works,</p>
<pre><code>---
title: "Example"
format:
html
---
```{r}
#| include: false
knit_print.data.frame = function(x, ...) {
res = paste(c("", "",
knitr::kable(x, digits = 2) |>
kableExtra::kable_styling()), collapse = "\n")
knitr::asis_output(res)
}
registerS3method(
"knit_print", "data.frame", knit_print.data.frame,
envir = asNamespace("knitr")
)
```
## example kable
```{r}
mtcars |> head()
dim(mtcars)
```
</code></pre>
<p><a href="https://i.stack.imgur.com/EwCF5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EwCF5.png" alt="enter image description here" /></a></p>
<p>My problem is that it works on a stand-alone HTML file, but when I have several <code>.qmd</code>'s for a book, it does not work. Hence, I look for a solution that adds the styling inside the YAML or to make the above mentioned solution work for all qmd-files in a Quarto book.</p>
| [
{
"answer_id": 74194747,
"author": "shafee",
"author_id": 10858321,
"author_profile": "https://Stackoverflow.com/users/10858321",
"pm_score": 1,
"selected": false,
"text": "global.R"
},
{
"answer_id": 74300268,
"author": "Julian",
"author_id": 14137004,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14137004/"
] |
74,193,551 | <p>I have a 'users' table for general information of every user (primary key is 'user_id') and a table 'chat' to store messages (primary key is 'msg_id') that have 'incoming_msg_id' (which eventually corresponds with 'users.user_id') and 'outgoing_msg_id' (which eventually corresponds with 'users.user_id').
'chat.read_at' is 'null' as long as the message is not read but is a date/time field.</p>
<p>I wish to list all users and their corresponding last message, if there is any.</p>
<p>With the following statement I have errors as I get also messages that are not from or to the corresponding user.</p>
<p>I am pretty new to SQL and trying to dig my way through it and did several attempts to do it with (INNER) JOIN but never got so far as with this statement:</p>
<pre><code> SELECT user_id, username, image, status, active,
CASE WHEN status IN ("Active Now") THEN true ELSE false END AS isonline,
(SELECT msg
FROM chat
WHERE
(incoming_msg_id = users.user_id) OR
(outgoing_msg_id = users.user_id)
ORDER BY msg_id DESC LIMIT 1
) AS last_msg,
(SELECT msg_id
FROM chat
WHERE
(incoming_msg_id = users.user_id) OR
(outgoing_msg_id = users.user_id)
ORDER BY msg_id DESC LIMIT 1 ) AS last_msg_id,
(SELECT outgoing_msg_id
FROM chat
WHERE msg_id = last_msg_id
) AS outgoing_msg_id,
(SELECT incoming_msg_id
FROM chat
WHERE msg_id = last_msg_id
) AS incoming_msg_id,
(SELECT created_at
FROM chat
WHERE msg_id = last_msg_id
) AS last_interaction,
(SELECT IF(read_at = null, false, true)
FROM chat
WHERE msg_id = last_msg_id
) AS has_unread_msg,
(SELECT read_at
FROM chat
WHERE msg_id = last_msg_id
) AS read_at,
(SELECT IF(user_id = incoming_msg_id, true, false) AS isme
FROM chat
WHERE msg_id = last_msg_id
) AS self
FROM users
WHERE
(NOT user_id = ?) AND
(users.username LIKE ?)
ORDER BY active DESC, status ASC, has_unread_msg DESC, last_interaction DESC
</code></pre>
<p>My code after the first comment with the exact same result (showing messages that do not belong to me and some of the other users listed:</p>
<pre><code> WITH
cte1 AS (
SELECT *, incoming_msg_id as user_id FROM chat
UNION ALL
SELECT *, outgoing_msg_id FROM chat
),
cte2 AS (
SELECT *, IF(ISNULL(read_at), true, false) AS has_unread_msg, msg AS last_msg, IF(user_id = incoming_msg_id, true, false) AS self, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) rn
FROM cte1
)
SELECT *, IF(status = "Active now", true, false) AS isonline
FROM users
JOIN cte2 USING (user_id)
WHERE rn = 1
</code></pre>
<p>Create and inserts of the tables:</p>
<pre><code>CREATE TABLE `chat` (
`msg_id` int(11) NOT NULL,
`incoming_msg_id` int(255) NOT NULL,
`outgoing_msg_id` int(255) NOT NULL,
`msg` varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`read_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `chat` (`msg_id`, `incoming_msg_id`, `outgoing_msg_id`, `msg`, `read_at`, `created_at`) VALUES
(3, 1, 5, 'no way', '2022-10-23 17:53:13', '2022-10-23 17:53:13'),
(4, 1, 5, 'I am sitting here and nothing happens!', '2022-10-23 17:53:13', '2022-10-23 17:53:13'),
(5, 1, 5, 'Still sitting here...', '2022-10-23 17:53:13', '2022-10-23 17:53:13'),
(9, 5, 1, 'Hi there', '2022-10-23 16:13:25', '2022-10-23 16:13:25'),
...
(45, 5, 25, 'Hey there. How is ya doing??', '2022-10-22 08:16:18', '2022-10-22 08:16:18'),
(46, 3, 25, 'hello there! Are you available?', '2022-10-23 18:16:08', '2022-10-23 18:16:08'),
(47, 3, 25, 'Something?', '2022-10-23 18:16:08', '2022-10-23 18:16:08'),
(48, 1, 25, 'hi!', '2022-10-24 11:45:13', '2022-10-24 11:45:13'),
(49, 1, 25, 'hi!', '2022-10-24 11:45:13', '2022-10-24 11:45:13'),
...
(63, 25, 5, 'nothing special here!', '2022-10-23 21:29:04', '2022-10-23 21:29:04'),
(64, 5, 25, 'What if we meet next week?', '2022-10-22 08:16:18', '2022-10-22 08:16:18'),
(65, 5, 25, 'What if we meet next week?', '2022-10-22 08:16:18', '2022-10-22 08:16:18'),
...
(365, 2, 5, 'sechs', NULL, '2022-10-21 20:49:09'),
(366, 2, 5, 'sieben', NULL, '2022-10-21 20:49:10'),
(367, 2, 5, 'acht', NULL, '2022-10-21 20:50:18'),
(368, 2, 5, 'neun', NULL, '2022-10-21 20:50:19'),
</code></pre>
<p>msg_id is primary and incremental</p>
<p>This is the users table:</p>
<pre><code>CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`username` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) CHARACTER SET armscii8 NOT NULL,
...
`image` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
...
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
...
`active` tinyint(1) DEFAULT 0,
`status` varchar(16) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Not active',
`last_chat_notification_id` int(11) DEFAULT NULL,
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code></pre>
<p><img src="https://partnerschaftradikal.de/wp-content/uploads/2022/10/so-sql.png" alt="screenshot of output" /></p>
<p>The first users are correct (talking to me as I am logged in with the user_id 25)
But from the 6th user on it shows messages that are not between us.</p>
<p>The list shows every existing user but only the last message between them and the currently logged in user (or non if not applicable).
The current user should also be excluded from the list.</p>
| [
{
"answer_id": 74194747,
"author": "shafee",
"author_id": 10858321,
"author_profile": "https://Stackoverflow.com/users/10858321",
"pm_score": 1,
"selected": false,
"text": "global.R"
},
{
"answer_id": 74300268,
"author": "Julian",
"author_id": 14137004,
"author_profil... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19724961/"
] |
74,193,555 | <p>I want to sort by property name in array object.</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 arr = [
{id:1, name: 'A1'},
{id:2, name: 'A2'},
{id:3, name: 'A3'},
{id:4, name: 'B1'},
{id:5, name: 'B2'},
{id:6, name: 'A21'},
{id:7, name: 'A11'},
{id:8, name: 'A4'},
{id:9, name: 'A12'},
]
arr.sort((a,b) => a.name.localeCompare(
b.name,
undefined,
{ numeric: true }
))
console.log(arr)</code></pre>
</div>
</div>
</p>
<p>The result I am looking for is 1:A1, 2:A2, 3:A3, 7:A11, 6:A21, 4:B1, 5:B2.</p>
<p>Thank you :)</p>
| [
{
"answer_id": 74193701,
"author": "Robo Robok",
"author_id": 4403732,
"author_profile": "https://Stackoverflow.com/users/4403732",
"pm_score": 2,
"selected": true,
"text": "localeCompare"
},
{
"answer_id": 74193811,
"author": "A1exandr Belan",
"author_id": 87713,
"au... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19665096/"
] |
74,193,574 | <p>Input below:</p>
<pre><code>list_1 = [TeamA,TeamB,TeamC,TeamD]
</code></pre>
<p>Output should be like below</p>
<pre><code>TeamA TeamB
TeamA TeamC
TeamA TeamD
TeamB TeamC
TeamB TeamD
TeamC TeamD
</code></pre>
| [
{
"answer_id": 74193609,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 0,
"selected": false,
"text": "list_1 = [\"TeamA\",\"TeamB\",\"TeamC\",\"TeamD\"]\n\nfixtures = [[a, b] for i, a in enumerate(list_1) for b in list_1... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20121460/"
] |
74,193,577 | <p>I'm working with an XML data that gives all information for my vue app. Everything works fine except one value.</p>
<p>I need to get the date from an element, but it comes in this format :</p>
<pre><code>['2022-10-25']
</code></pre>
<p>It should be 25-10-2022</p>
<p>I get this item using :</p>
<pre><code>item.datum.join().toString()
</code></pre>
<p>How can I change it ?</p>
<p>Since it's an Object, I can not find a solution for this, better would be to handle it as data, I have MomentJS installed but I also did not get it to work.</p>
| [
{
"answer_id": 74193609,
"author": "Aymen",
"author_id": 5165980,
"author_profile": "https://Stackoverflow.com/users/5165980",
"pm_score": 0,
"selected": false,
"text": "list_1 = [\"TeamA\",\"TeamB\",\"TeamC\",\"TeamD\"]\n\nfixtures = [[a, b] for i, a in enumerate(list_1) for b in list_1... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19433886/"
] |
74,193,581 | <p>I want to perform select query if else in innner join
if IsStatus =0 then i want to inner join with T_valDob and show val column from that table.
if IsStatus =1 then i want to inner join with T_valSob and show val column from that table.
IsStatus is bit type.</p>
<p>T_MappingTable</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>MappingID</th>
<th>valID</th>
<th>IsStatus</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>0</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>0</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>7</td>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>8</td>
<td>4</td>
<td>1</td>
</tr>
<tr>
<td>9</td>
<td>5</td>
<td>1</td>
</tr>
<tr>
<td>10</td>
<td>6</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>T_valDob</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>valID</th>
<th>val</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>val1</td>
</tr>
<tr>
<td>2</td>
<td>val2</td>
</tr>
<tr>
<td>3</td>
<td>val3</td>
</tr>
<tr>
<td>4</td>
<td>val4</td>
</tr>
<tr>
<td>5</td>
<td>val5</td>
</tr>
<tr>
<td>6</td>
<td>val6</td>
</tr>
<tr>
<td>7</td>
<td>val7</td>
</tr>
<tr>
<td>8</td>
<td>val8</td>
</tr>
</tbody>
</table>
</div>
<p>T_valSob</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>valID</th>
<th>val</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>valSop1</td>
</tr>
<tr>
<td>2</td>
<td>valSop2</td>
</tr>
<tr>
<td>3</td>
<td>valSop3</td>
</tr>
<tr>
<td>4</td>
<td>valSop4</td>
</tr>
<tr>
<td>5</td>
<td>valSop5</td>
</tr>
<tr>
<td>6</td>
<td>valSop6</td>
</tr>
<tr>
<td>7</td>
<td>valSop7</td>
</tr>
<tr>
<td>8</td>
<td>valSop8</td>
</tr>
</tbody>
</table>
</div>
<p>Like i want final output like this in single resultset</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>MappingID</th>
<th>valID</th>
<th>IsStatus</th>
<th>val</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>0</td>
<td>val1</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>0</td>
<td>val2</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>0</td>
<td>val3</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>0</td>
<td>val4</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>0</td>
<td>val5</td>
</tr>
<tr>
<td>5</td>
<td>1</td>
<td>1</td>
<td>valSop1</td>
</tr>
<tr>
<td>6</td>
<td>2</td>
<td>1</td>
<td>valSop2</td>
</tr>
<tr>
<td>7</td>
<td>3</td>
<td>1</td>
<td>valSop3</td>
</tr>
<tr>
<td>8</td>
<td>4</td>
<td>1</td>
<td>valSop4</td>
</tr>
<tr>
<td>9</td>
<td>5</td>
<td>1</td>
<td>valSop5</td>
</tr>
<tr>
<td>10</td>
<td>6</td>
<td>1</td>
<td>valSop6</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74193858,
"author": "JMabee",
"author_id": 8126219,
"author_profile": "https://Stackoverflow.com/users/8126219",
"pm_score": 3,
"selected": true,
"text": "SELECT MT.MappingID, MT.valID,MT.IsStatus, TD.val\nFROM T_MappingTable MT\nINNER JOIN T_valDob TD on MT.valID = TD.val... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19901465/"
] |
74,193,587 | <p>I have a function <code>void Foo(MyType* mt)</code>. I want callers to be able to pass any pointer type to this function (e.g. <code>unique_ptr</code>, <code>shared_ptr</code> or <code>iterator</code>) and not require passing a raw pointer. Is there any way to express this? I could write:</p>
<pre><code>template <typename T>
void Foo(T t);
</code></pre>
<p>This will work since it will only compile if <code>T</code> supports <code>operator-></code> and <code>operator*</code> which I use inside <code>Foo</code>, it will also only work if <code>T</code> has the same interface as <code>MyType</code> but it seems wrong to not specify in the API that I expect that template argument to be a pointer to <code>MyType</code>. I could also write my own wrapper:</p>
<pre><code>template <typename T>
class PointerWrapper {
public:
PointerWrapper(T* t) : raw_ptr(t) {}
PointerWrapper(const std::unique_ptr<T>& t) : raw_ptr(t.get()) {}
...
private:
T* raw_ptr;
};
void Foo(PointerWrapper<MyType> mt);
</code></pre>
<p>This seems clunky because I will need to extend PointerWrapper for every smart pointer type under the sun.</p>
<p>Is there an accepted way to support this?</p>
| [
{
"answer_id": 74193822,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 4,
"selected": true,
"text": "template <typename P, typename T>\nconcept points_to = requires(P p) {\n { *p } -> std::common_reference_with<T &>\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/919578/"
] |
74,193,598 | <p>I'm using SubtitleEdit and I'd like to locate all the lines that do not contain a line break.</p>
<p>Because lines containing a line break indicates they are bilingual, which I want.</p>
<p>But those that do not have line breaks are mono-lingual, and I'd like to quickly locate them all and delete them. TIA!</p>
<p>Alternatively, if there is a regex expression that can find lines which do not contain any English characters, that would also work.</p>
| [
{
"answer_id": 74193822,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 4,
"selected": true,
"text": "template <typename P, typename T>\nconcept points_to = requires(P p) {\n { *p } -> std::common_reference_with<T &>\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9852363/"
] |
74,193,606 | <p>I have made an endless runner game. There, a cube is sliding on a slippery plane. Therefore I created multiple prefabs of planes with obstacles on it which are random placed one after another. Now, when I start the game and my player (a cube) slides on the planes, it sometimes seems to collide with the edges of a plane, which causes the cube to fly away.</p>
<pre><code>private void Update(){
if (rb != null){
if (rb.position.y > 0.513f){
pos = rb.transform.position;
pos.y = 0.51f;
rb.transform.position = pos;
}
rot = rb.transform.rotation;
rot.y = 0;
rot.x = 0;
rot.z = 0;
rb.transform.rotation = rot;
if (rb.position.y > 1.01f)
forwardForce = 2500f;
else
forwardForce = 5300f;
if (Input.GetKey("d"))
rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
if (Input.GetKey("a"))
rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
</code></pre>
<p>Here, rb is the Rigidbody of the cube. And as you can see, I have tried to solve the problem by detecting if the player position is too high, and then putting it just slightly above the y-position of the plane, so that caused by possible bad floating point precision, it doesn't get stuck inside the plane. Now the cube doesn't fly away, but it kind of bounces very aggressively instead. And while writing this question I found out, that you can freeze the y-coordinate of the player, which helps a bit, but instead of bouncing it slows down now, which is also bad but better.</p>
<p>Edit: I 'fixed' it now by just letting the cube fly slightly above the platform. By that it doesn't collide with the edges or whatever the reason was</p>
| [
{
"answer_id": 74193822,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 4,
"selected": true,
"text": "template <typename P, typename T>\nconcept points_to = requires(P p) {\n { *p } -> std::common_reference_with<T &>\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20329428/"
] |
74,193,633 | <p>Losing my will to live with this one.</p>
<p>Went to start up my BigCommerce project and the localhost URL is just showing a blank screen. Zero errors in command line or in the browser console so I have absolutely no clue why it's just a blank screen.</p>
<p>Running Stencil Version 5.2.2
NVM 14.20.0
NPM 6.14.17</p>
<p>Not really sure what else to share, as I said, I'm getting no errors anywhere to give me a clue as to what's going on. Has anyone else experienced this?</p>
| [
{
"answer_id": 74193822,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 4,
"selected": true,
"text": "template <typename P, typename T>\nconcept points_to = requires(P p) {\n { *p } -> std::common_reference_with<T &>\... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74193633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9478887/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.