instruction stringlengths 0 30k β |
|---|
null |
I am plotting some lines with Seaborn:
```python
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# dfs: dict[str, DataFrame]
fig, ax = plt.subplots()
for label, df in dfs.items():
sns.lineplot(
data=df,
x="Iteration",
y="Loss",
errorbar="sd",
label=label,
ax=ax,
)
ax.set(xscale='log', yscale='log')
```
The result looks like [this][1].
Note the clipped negative values in the lower error band of the "effector_final_velocity" curve, since the standard deviation of the loss is larger than its mean, for those iterations.
However, if `ax.set(xscale='log', yscale='log')` is called *before* the looped calls to `sns.lineplot`, the result looks like [this][2]
I'm not sure where the unclipped values are arising.
Looking at the source of `seaborn.relational`: at the end of `lineplot`, the `plot` method of a `_LinePlotter` instance is called. It plots the error bands by passing the already-computed standard deviation bounds to `ax.fill_between`.
Inspecting the values of these bounds right before they are passed to `ax.fill_between`, the negative values (which would be clipped) are still present. Thus I had assumed that the "unclipping" behaviour must be something matplotlib is doing during the call to `ax.fill_between`, since `_LinePlotter.plot` appears to do no other relevant post-transformations of any data before it returns, and `lineplot` returns immediately.
However, consider a small example that calls `fill_between` where some of the lower bounds are negative:
```python
import numpy as np
fig, ax = plt.subplots(1, 1, figsize=(5, 5))
np.random.seed(5678)
ax.fill_between(
np.arange(10),
np.random.random((10,)) - 0.2,
np.random.random((10,)) + 0.75,
)
ax.set_yscale('log')
```
Then it makes no difference if `ax.set_yscale('log')` is called before `ax.fill_between`; in both cases the result is [this](https://i.stack.imgur.com/ctRUi.png).
I've spent some time searching for answers about this in the Seaborn and matplotlib documentation, and looked for answers on SA and elsewhere, but I haven't found any information about what is going on here.
[1]: https://i.stack.imgur.com/hTsMw.png
[2]: https://i.stack.imgur.com/EURJq.png |
import pandas as pd
import numpy as np
terms = ['A.B3.C4', 'A.B3.C5', 'A.B4.C6', 'A.B5.C6',
'A1.B1.C1.D1', 'A1.B1.C1.D2', "D1",
"A.B10.C10.D1", "A.B20.C10.D1", "A.B20.C20.D1",
"A.B100.C100.D100.D1", "A.B200.C100.D100.D1",
"A.B300.C200.D100.D1", "A.B300.C300.D100.D1",
""
]
def rem_mid_words(txt1):
if "." in txt1:
l1 = txt1.split(".")
txt2 = f"{l1[0]}.{l1[-1]}" # pos 0 term & . & (-1 =) last term
return txt2
else:
pass # string does not contain "."
term_count = {rem_mid_words(txt1): 0 for txt1 in terms} # initial counting dictionary
for x in terms:
key = rem_mid_words(x)
term_count[key] += 1
new_terms = [rem_mid_words(txt1)
if term_count[rem_mid_words(txt1)] < 2
else txt1 for txt1 in terms]
print(new_terms)
# start of adjusted answer
def rem_one_word(txt1, len1, pos):
# Example "A1.B2.C3.D4.E5"
# pos 0. 1. 2. 3. 4
# length 5
# if len1 is 5 and pos = 1 then remove B2 and return A1.C3.D4.E5
# otherwise return original txt1
if txt1 != None and "." in txt1:
l1 = txt1.split(".")
if len(l1) == len1:
txt1 = ".".join(l1[:pos] + l1[(1+pos):])
return txt1
def word_len(txt1):
if "." in txt1:
return len(txt1.split("."))
else: return 0
def shorten_words(terms): # input list of strings
# get longest word in terms of "."
# iterate by reducing length by one and replace if count < 2
max_len = max([word_len(txt1) for txt1 in terms])
terms1 = terms
for len1 in np.arange(max_len, 2, -1):
print("string length", len1)
for pos in (1 + np.arange((len1)-2)):
print("pos", pos)
temp_words = [rem_one_word(txt1, len1, pos) for txt1 in terms1]
temp_count = {x: 0 for x in temp_words}
for x in temp_words: temp_count[x] += 1
terms2 = [temp_words[i] if temp_count[temp_words[i]] < 2
else terms1[i] for i in range(len(terms1))]
terms1 = terms2
return terms1
terms1 = shorten_words(terms)
for i in range(len(terms)):
print(terms[i], " ", terms1[i])
|
I don't understand what's wrong, I just copy pasted it in my professor's powerpoint that's supposed to run withour errors.
Here's the query:
```
SELECT student.admission_no, student.first_name,
student.last_name, fee.course, fee.amount_paid
FROM student
FULL OUTER JOIN fee
ON student.admission_no = fee.admission_no;
```
Here's the error:
> #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'OUTER JOIN fee
> ON student.admission_no = fee.admission_no LIMIT 0, 25' at line 4
>
I just copy pasted it based on the syntax and code query provided, maybe he got something wrong? |
What's supposed to be the problem in this query? |
|mysql|localhost| |
null |
I have a json data and I want to write data keys once using twig. But when I try to store keys in uniqueArray to check the key is exists in the array, it is not working.
Here is my twig code, where is the problem ?
```
{% macro fetch(uArray, data) %}
<ul>
{{ _self.keys(uArray, data) }}
</ul>
{% endmacro %}
{% macro keys(uniqueArray, data) %}
{% if data is iterable %}
{% for key, val in data %}
{% if key not in uniqueArray %}
{% set uniqueArray = uniqueArray|merge([key]) %}
<li>
{{ key }}
</li>
{% if val is iterable %}
{{ _self.fetch(uniqueArray, val) }}
{% endif %}
{% endif %}
{% endfor %}
{% endif %}
{% endmacro %}
<div class="table-map">
<ul>
{% set unique = [] %}
{{ _self.keys(unique, data) }}
</ul>
</div>
``` |
Spark generally wants to minimize the movements of data during shuffling, So it will perform "group by" first on the partitions and then shuffle the data to bring related groups together again.
Example: When you perform groupBy("city","country") it will shuffle within the partitions(intra) and then inter partitions to bring together (same city and country) together in same partition for final movement.
Though there are other factors this depends on. |
I use IdeaVim and have gotten in the habit of tapping Esc frequently to get out of insert mode, etc. I also use Esc to go from the Terminal window back to the Editor. So basically I tap Esc a lot.
I've recently starting doing some android dev in Android Studio.
One thing that I keep doing by accident is pressing Esc while I'm focused on the emulator window.
When this happens, it simulates a "Back" action on the emulated Android device.
Is there any way to change this keybind? It's pretty annoying because I'm currently working on something where Back just closes the app and goes to the home screen, so every time I press Esc I have to re-open the app. And since I'm using Flutter, this seems to mean I need to re-run my `main.dart`. |
Is there any way to disable [Esc] from being "Back" in Android Studio's Android emulator? |
|flutter|android-studio|android-emulator| |
I am building a basic registration feature for a school project and keep getting an error when I try to check the username and password from a database. The idea is to have a user type in their login info and then have a function receive that information and compare it with the user info from the database. if it matches it will retrieve the user id from the table and attach it to a variable for later use. I am having an issue now where it seems like when I pass in the user input into the password match function, the function only receives the first char of the input. That's what the debugger shows. I may be reading the debugger wrong but I am not sure here is the first function
void loginUser(){
char email[100];
char password[50];
// Input login details
printf("Enter email: ");
fgets(email, sizeof(email), stdin);
email[strcspn(email, "\n")] = '\0'; // Remove newline character
printf("Enter password: ");
fgets(password, sizeof(password), stdin);
password[strcspn(password, "\n")] = '\0'; // Remove newline character
printf("Email: %s\n", email);
printf("Email: %s\n", password);
// Check email and password against database
if(password_match(email, password)){
printf("Success");
};
// If authenticated, proceed to main menu
// Else, show error message and redirect to login
};
and this is the function that gets the username and password from mysql database
int password_match(const char *email, const char *password) {
// printf("Email: %s\n", email);
// printf("Email: %s\n", password);
MYSQL_RES *result;
MYSQL_ROW row;
char query[512];
snprintf(query, sizeof(query), "SELECT consumerID FROM CurrentConsumer WHERE email='%s' AND password='%s'", email, password);
if (mysql_query(con, query)) {
fprintf(stderr, "Error querying database: %s\n", mysql_error(con));
return 0; // Failure
}
result = mysql_store_result(con);
if (result == NULL) {
fprintf(stderr, "Error storing result: %s\n", mysql_error(con));
return 0; // Failure
}
row = mysql_fetch_row(result);
if (row == NULL) {
mysql_free_result(result);
return 0; // No match
}
// Print the consumer ID
printf("Consumer ID: %s\n", row[0]);
mysql_free_result(result);
return 1; // Match
}
I tried using both pass by value and pass by reference but cant get it to work. It's weird because I have another function that inserts data into the database just fine. I used that to build this function but cant get it to work. |
Writing each key once in twig |
|symfony|duplicates|twig| |
|mariadb|localhost| |
{"OriginalQuestionIds":[44153287],"Voters":[{"Id":11107541,"DisplayName":"starball","BindingReason":{"GoldTagBadge":"visual-studio-code"}}]} |
It is presumed that the string array is the same length as the number of rows of the double array.
- iterate over the number of rows doing the following:
- print the string value for given row.
- then print the double values for that row.
- then print a new line.
- done iterating
You may need to pad the values with spaces to properly format it. |
I am now studying the concept of OOD and I have created a program for a pizza shop. The base class here is pizza. I want to put a spicy characteristic for pizza as an interface, but I find a problem in the actual application. Here is the code. How can I combine making pizza with it being spicy?
how i can make beef spicy pizza object [how can i make pizza and make it spicy via interface]
how to use interface here.
```
#include <iostream>
#include <string>
using namespace std;
// base-class
class Pizza
{
private:
void MakeDough()
{
cout << "Make " << getPizzaType() << " Pizza Dough is Done.." << endl;
}
void Bake()
{
cout << "Bake " << getPizzaType() << " Pizza is Done.." << endl;
}
void AddToppings()
{
cout << "Adding " << PizzaToppings() << " is Done.." << endl;
}
protected:
virtual string getPizzaType() = 0;
virtual string PizzaToppings() = 0;
public:
void MakePizza()
{
MakeDough();
AddToppings();
Bake();
cout << "======================================\n";
cout << getPizzaType() << " Pizza is Done..\n" << endl;
}
};
//interface
class Spicy
{
public:
virtual void makePizzaSpicy() = 0;
};
class BeefPizza : public Pizza, public Spicy
{
protected:
// from Pizza Class
virtual string getPizzaType()
{
return "Beef";
}
virtual string PizzaToppings()
{
return "Beef Pizza Toppings";
}
public:
// from spicy class
virtual void makePizzaSpicy()
{
// code
}
};
class ChickenPizza : public Pizza
{
protected:
virtual string getPizzaType()
{
return "Chicken";
}
virtual string PizzaToppings()
{
return "Chicken Pizza Toppings";
}
};
class MakingPizza
{
public:
void MakePizza(Pizza* pizza)
{
pizza->MakePizza();
}
};
int main()
{
// here how i can make beef spicy pizza object
}
```
|
How do I apply the interface concept with the base-class in design? |
|c++|oop|interface|base-class| |
null |
I ran into the same issue; assuming you are injecting the Router instance using the inject method, please note that there is a difference between `Inject(Router)` and `inject(Router)`
import { Inject, inject } from '@angular/core';
You need to use the latter. i.e.
import { inject } from '@angular/core'; |
Flutter ran into error:
ββββββββ Exception caught by widgets library βββββββββββββββββββββββββββββββββββ
Null check operator used on a null value
The relevant error-causing widget was:
In Visual studio code, the above message did not show file and line number. |
```Bot is ready
/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/ext/commands/common_bot_base.py:464: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Ignoring exception in on_ready
Traceback (most recent call last):
File "/home/runner/BattleEx/.pythonlibs/lib/python3.10/site-packages/disnake/client.py", line 703, in _run_event
await coro(*args, **kwargs)
File "/home/runner/BattleEx/main.py", line 13, in on_ready
await bot.load_extensions("cogz")
TypeError: object NoneType can't be used in 'await' expression
```
This is my redis.py
I don't understand why this is happening there is nothing that can be Nonetype here I guess.
redis.py
```
import aioredis,asyncio
from disnake.ext import commands
import os
from disnake.ext import commands
import os
class Redis(commands.Cog):
"""For Redis."""
def __init__(self, bot: commands.Bot):
self.bot = bot
self.pool = None
self._reconnect_task = self.bot.loop.create_task(self.connect())
#all funcs here
async def setup(bot: commands.Bot):
print("Here")
redis_cog = Redis(bot)
print("Setting up Redis cog...")
await redis_cog.connect()
await bot.add_cog(redis_cog)
```
I tried it with discord.py using bot.load_extension("cogz,redis"), but I am still getting the same error. |
{"OriginalQuestionIds":[3402371],"Voters":[{"Id":20002111,"DisplayName":"Friede"},{"Id":17562044,"DisplayName":"Sunderam Dubey"},{"Id":22180364,"DisplayName":"Jan"}]} |
Interest is supposed to be Percentages. Your formula expressed it as a decimal value.
Change the line below to:
// Convert annual interest rate percentage to decimal and then into monthly interest rate.
double monthlyInterestRate = (annualInterestRate / 100) / 12.0; |
Having some problem of ressources on my environment, I tried to implement an MixedImageDataGenerator relying on underlying ImageDataGenerator, in order to generate Inmges and lables at training time.
The idea was to generate all images with a limitation for each underlyine generators for each epochs refreshing the limits between epochs.
I 'm running the following version:
Keras version: 2.3.1
TensorFlow version: 2.1.0
Here is the code of the MixedImageDataGenerator:
```
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import threading
class MixedImageDataGenerator(object):
"""
Wrapper class that mixes data from multiple ImageDataGenerator instances.
Args:
generators (list): List of ImageDataGenerator objects.
limits (list): List of integers representing the number of batches
to be generated from each generator before switching.
generator_type: type of generato 0 = train, 1 = validate , 2 = test
Attributes:
generators (list): List of ImageDataGenerator objects.
limits (list): List of integers representing batch limits.
current_generator_index (int): Index of the currently active generator.
remaining_batches (list): List of integers representing remaining
batches per generator.
data_queue (deque): Queue to store generated batches (optional for efficiency).
"""
TYPE = ['train','validate','test']
TRAIN = 0
VALIDATE = 1
TEST = 2
def __init__(self, generators, limits,generator_type,debug=False):
self.lock = threading.Lock()
self.generators = generators
self.limits = limits
self.current_generator_index = 0
self.remaining_batches = limits.copy() # Directly assign the limits list
self.debug=debug
if self.debug:
print(f'Create Generator :{MixedImageDataGenerator.TYPE[generator_type]}')
self.generator_type = generator_type
def get_step_number(self):
return sum(self.limits)
def get_remaining_batches(self):
return sum(self.remaining_batches)
def getType(self):
return self.generator_type
def getGeneratorNumber(self):
return(len(self.generators))
def __iter__(self):
"""
Makes the MixedImageDataGenerator object iterable,
allowing it to be used in a for loop.
Returns:
self: The MixedImageDataGenerator object itself.
"""
if self.get_remaining_batches() == 0:
return self.repeat()
else:
return self
def __next__(self):
"""
Returns the next batch of data from the mixed generators.
Raises:
StopIteration: If all limits have been exhausted.
"""
if self.debug:
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}]: next called [pre lock]')
with self.lock:
#if self.debug:
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}]: next call ...')
while True:
#print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}]Remaining batch: {self.remaining_batches} limits: {self.limits}')
if sum(self.remaining_batches) <= 0:
#if self.debug:
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}] all limits exhausted')
raise StopIteration
data = None
while data is None:
# Check if current generator has remaining batches
if self.remaining_batches[self.current_generator_index] > 0:
# Ensure the current generator is advanced if its queue is empty
data = self.generators[self.current_generator_index].next()
# Decrease the remaining batches of the current generator
self.remaining_batches[self.current_generator_index] -= 1
if self.debug:
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}]Remaining batch: {self.remaining_batches} limits: {self.limits}')
# Move to the next generator
self.current_generator_index = (self.current_generator_index + 1) % len(self.generators)
# If all generators have exhausted their limits, raise StopIteration
if all(remaining_batch <= 0 for remaining_batch in self.remaining_batches):
if self.debug:
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}] all step data generated')
raise StopIteration
if self.debug:
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}]: RETURN {type(data)}')
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}]: next called')
if not data:
print('EMPTY================')
return data
def refresh(self, argument=None):
with self.lock:
if self.debug:
print(f'[{MixedImageDataGenerator.TYPE[self.generator_type]}] refresh')
self.current_generator_index = 0
self.remaining_batches = self.limits.copy() # Directly assign the limits list
# self.data_queue = deque(maxlen=10) # Optional queue for efficiency
def repeat(self):
print('repeat called')
while True:
try:
yield next(self)
except StopIteration:
self.refresh() ```
The following call back, should take care for the refresh limits
```
"""
Custom callback to log epoch and step information, and refresh the generator.
"""
class EpochStepLogger(tf.keras.callbacks.Callback):
def __init__(self, generator):
"""
Args:
generator: The data generator object to be refreshed.
"""
self.generator = generator
self.current_epoch = 0
self.current_step = 0
def on_epoch_begin(self, epoch, logs=None):
"""
Called at the beginning of each epoch.
Args:
epoch: The current epoch number.
logs: Dictionary of logs accumulated during the previous epoch.
"""
self.current_epoch = epoch
self.current_step = 0
self.log(f"Epoch {epoch} started!")
self.refresh_generator()
def on_batch_end(self, batch, logs=None):
"""
Called at the end of each batch.
Args:
batch: The index of the current batch.
logs: Dictionary of logs accumulated at the end of the current batch.
"""
self.current_step += 1
self.log(f"Epoch {self.current_epoch}, Step {self.current_step} completed.")
# in case where there is more than one call to next() per step
# if self.generator:
# if self.generator.get_remaining_batches() < 1:
# self.refresh_generator()
def on_train_end(self, logs=None):
"""
Called at the end of training.
Args:
logs: Dictionary of logs accumulated at the end of training.
"""
self.log("Training completed!")
def on_train_begin(self, logs=None):
"""
Called at the begining of training.
Args:
logs: Dictionary of logs accumulated at the end of training.
"""
self.refresh_generator()
self.log("Training started!")
def refresh_generator(self):
"""
Refreshes the data generator.
"""
if self.generator:
self.generator.refresh() # Assuming your generator has a refresh method
def log(self, message):
"""
Logs a message with epoch and step information.
"""
print(f"[Epoch {self.current_epoch}, Step {self.current_step}] {message}")
def on_test_begin(self,logs=None):
print(f'[ON_TEST_BEGIN]')
def on_test_end(self,logs=None):
print(f'[ON_TEST_END]') ```
This is the code to train the model:
```
"""
Custom callback to log epoch and step information, and refresh the generator.
"""
class EpochStepLogger(tf.keras.callbacks.Callback):
def __init__(self, generator):
"""
Args:
generator: The data generator object to be refreshed.
"""
self.generator = generator
self.current_epoch = 0
self.current_step = 0
def on_epoch_begin(self, epoch, logs=None):
"""
Called at the beginning of each epoch.
Args:
epoch: The current epoch number.
logs: Dictionary of logs accumulated during the previous epoch.
"""
self.current_epoch = epoch
self.current_step = 0
self.log(f"Epoch {epoch} started!")
self.refresh_generator()
def on_batch_end(self, batch, logs=None):
"""
Called at the end of each batch.
Args:
batch: The index of the current batch.
logs: Dictionary of logs accumulated at the end of the current batch.
"""
self.current_step += 1
self.log(f"Epoch {self.current_epoch}, Step {self.current_step} completed.")
# in case where there is more than one call to next() per step
# if self.generator:
# if self.generator.get_remaining_batches() < 1:
# self.refresh_generator()
def on_train_end(self, logs=None):
"""
Called at the end of training.
Args:
logs: Dictionary of logs accumulated at the end of training.
"""
self.log("Training completed!")
def on_train_begin(self, logs=None):
"""
Called at the begining of training.
Args:
logs: Dictionary of logs accumulated at the end of training.
"""
self.refresh_generator()
self.log("Training started!")
def refresh_generator(self):
"""
Refreshes the data generator.
"""
if self.generator:
self.generator.refresh() # Assuming your generator has a refresh method
def log(self, message):
"""
Logs a message with epoch and step information.
"""
print(f"[Epoch {self.current_epoch}, Step {self.current_step}] {message}")
def on_test_begin(self,logs=None):
print(f'[ON_TEST_BEGIN]')
def on_test_end(self,logs=None):
print(f'[ON_TEST_END]') ```
With 3 underlying generators within my MixedDataGenerator with a limits of: [80, 80, 80]
I got the following trace:
`[Epoch 0, Step 223] Epoch 0, Step 223 completed.
[train]: next called [pre lock]
[train]: next call ...
[train]Remaining batch: [0, 0, 0] limits: [80, 80, 80]
[train] all step data generated
[Epoch 0, Step 224] Epoch 0, Step 224 completed.
[Epoch 0, Step 225] Epoch 0, Step 225 completed.
[Epoch 0, Step 226] Epoch 0, Step 226 completed.
[Epoch 0, Step 227] Epoch 0, Step 227 completed.
[Epoch 0, Step 228] Epoch 0, Step 228 completed.
[Epoch 0, Step 229] Epoch 0, Step 229 completed.
[Epoch 0, Step 230] Epoch 0, Step 230 completed.
[Epoch 0, Step 231] Epoch 0, Step 231 completed.
[Epoch 0, Step 232] Epoch 0, Step 232 completed.
[Epoch 0, Step 233] Epoch 0, Step 233 completed.
[Epoch 0, Step 234] Epoch 0, Step 234 completed.
[Epoch 0, Step 235] Epoch 0, Step 235 completed.
[Epoch 0, Step 236] Epoch 0, Step 236 completed.
[Epoch 0, Step 237] Epoch 0, Step 237 completed.
[Epoch 0, Step 238] Epoch 0, Step 238 completed.
[Epoch 0, Step 239] Epoch 0, Step 239 completed.
[Epoch 0, Step 240] Epoch 0, Step 240 completed.
[ON_TEST_BEGIN]
[ON_TEST_END]
Epoch 00001: val_loss improved from inf to 1.20102, saving model to E__chest_ray_VGG_F_2XDO_512_best.h5
240/240 - 209s - loss: 404.7601 - accuracy: 0.3000 - val_loss: 1.2010 - val_accuracy: 0.4000
[Epoch 1, Step 0] Epoch 1 started!
[train] refresh
Epoch 2/7
WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate at least `steps_per_epoch * epochs` batches (in this case, 1680 batches). You may need to use the repeat() function when building your dataset.
WARNING:tensorflow:Can save best model only with val_loss available, skipping.
WARNING:tensorflow:Early stopping conditioned on metric `val_loss` which is not available. Available metrics are:
[Epoch 1, Step 0] Training completed!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-77-3cc9dfbc0a95> in <module>
78 #class_weight=class_weight,
79 batch_size=model_batch_size,
---> 80 verbose=2)
81 # End timing
82 end_time = time.time()
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
817 max_queue_size=max_queue_size,
818 workers=workers,
--> 819 use_multiprocessing=use_multiprocessing)
820
821 def evaluate(self,
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
340 mode=ModeKeys.TRAIN,
341 training_context=training_context,
--> 342 total_epochs=epochs)
343 cbks.make_logs(model, epoch_logs, training_result, ModeKeys.TRAIN)
344
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in run_one_epoch(model, iterator, execution_function, dataset_size, batch_size, strategy, steps_per_epoch, num_samples, mode, training_context, total_epochs)
185
186 # End of an epoch.
--> 187 aggregator.finalize()
188 return aggregator.results
189
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_utils.py in finalize(self)
142 def finalize(self):
143 if not self.results:
--> 144 raise ValueError('Empty training data.')
145 self.results[0] /= (self.num_samples or self.steps)
146
ValueError: Empty training data.
After training for some time, look at the performa`
Specifying the steps_per_epoch is also difficult because it seems that I can't predict what the fix method does behind the hood.
I'm stuck, does someone have an idea?
david
|
If you're writing something that does "the same thing, with just one thing changing at each step", that's a loop. You don't use separate `if` statements. Not even when, as you say, "you're being lazy": being lazy is an _excellent_ trait to have when you're a programmer, because it means you want to do as little work as possible for the maximum result. Of course, in this case that means "why am I even doing this, [`npm install marked`](https://www.npmjs.com/package/marked), oh look I'm done", but even if you insist on implementing a markdown parser yourself (because sometimes you just want to write code to see if you can do it) you don't use a sequence of `if` statements because it takes more time to write, and will take more time to fix or update (as you discovered).
Lazy is excellent. Lazy saves you _so_ much time. Lazy programmers are efficient programmers. But _sloppy_ is your worst enemy.
That said, even if you _do_ use `if` statements, resolve them either such that you handle "the largest thing first", to ensure there's no fall-through, _or_ with if-else statements, so there's no fall-though. (And based on your question about whether to use a switch: you almost never want switches in JS. The switch statement is a hold-over from programming languages that didn't have dictionaries/key-value objects to perform O(1) lookups with, which JS, Pything, etc. all do. So in JS you're almost _always_ better off using a mapping object with your case values as property keys, turning an O(n) code path with a switch into an O(1) immediate lookup)
However, you don't need any of this, because what you're really doing is simple text matching, so you can use the best tool in the toolset for that: you can trivially get both the `#` sequence and "remaining text" with a regex, and then generate the replacement HTML [using the captured data](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#replacement):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function markdownToHTML(doc) {
return convertMultiLineMD(doc.split(`\n`)).join(`\n`);
}
function convertMultiLineMD(lines) {
// convert tables, lists, etc, while also making sure
// to perform inline markup conversion for any content
// that doesn't span multiple lines. For the purpose of
// this answer, we're going to ignore multi-line entirely:
return convertInlineMD(lines);
}
function convertInlineMD(lines) {
return lines.map((line) => {
// convert headings
line = line.replace(
// two capture groups, one for the markup, and one for the heading,
// with a third optional group so we don't capture EOL whitespace.
/^(#+)\s+(.+?)(\s+)?$/,
// and we extract the first group's length immediately
(_, { length: h }, text) => `<h${h}>${text}</h${h}>`
);
// then wrap bare text in <p>, convert bold, italic, etc. etc.
return line;
});
}
// And a simple test based on what you indicated:
const docs = [`## he#llo\nthere\n# yooo `, `# he#llo\nthere\n## yooo`];
docs.forEach((doc, i) => console.log(`[doc ${i + 1}]\n`, markdownToHTML(doc)));
<!-- end snippet -->
However, this is also a naive approach to writing a transpiler, and will have dismal runtime performance compared to writing [a stack parser](https://spec.commonmark.org/0.31.2/#appendix-a-parsing-strategy) or [a DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton) based on the markdown grammar (the "markup language specification" grammar, i.e. the rules that say which tokens can follow which other tokens), where you run through your document by tracking what kind of token we're dealing with, and convert on the fly as we pass token terminations.
(This is, in fact, how regular expressions work: they generate a DFA from the [regular grammar](https://en.wikipedia.org/wiki/Regular_grammar) pattern you specify, then run the input through that DFA, achieving near-perfect runtime performance)
Explaining how to get started with stack parsing or DFAs is of course wildly beyond the scope of this answer, but absolutely worth digging into if you're doing this "just to see if you can": anyone can write code "that works" but is extremely inefficient, so that's not an exercise that's going to improve your skill as a programmer. |
```js
let promise = ''
function A() {
return new Promise((resolve) => {
resolve(promise)
})
}
function callbackA(res) {
console.log("callbackA:", res)
return new Promise(resolve => {
promise = 'A'
resolve()
})
}
function B() {
return new Promise((resolve) => {
resolve(promise)
})
}
function callbackB(res) {
console.log("callbackB:", res)
}
function C() {
promise = 'C'
return promise
}
function callbackC(res) {
console.log("callbackC:", res)
}
function promiseThen(maybePromise, callback) {
}
promiseThen(A, callbackA)
promiseThen(B, callbackB)
promiseThen(C, callbackC)
```
The function `promiseThen` accepts two parameters: `maybePromise`, which may be a promise or a regular function, and `callback`, which receives their results to operate on them.
I want the promise to be executed first, completing all of its `then` functions, and then proceed to the next promise. So the result of the above code should be:
```bash
callbackC: C
callbackA: C
callbackB: A
```
Just like restoring the execution order of promises to that of regular functions. |
How to make promises execute in order? |
UnicodeEncodeError when building ESP-IDF project |
|esp32|esp-idf| |
I have a script that process millions of data. Same data are corrupted, thus the framework I use is fail and throws exception. I am dependent to a framework that I cannot change/update. I have use it as it is. Every time I use function of this framework I use try/catch. Therefore, I am using lots of try/catch blocks as a result the code become unreadable I want to get rid of try/catch and handle exceptions separately from my code.
I want o have a global exception handler so whenever framework throws Exception it should catch and log and the loop that process data should be continue. There are web frameworks like spring and jersey which have a global exception handler. I want similar behaviour for script.
I tried Thread.UncaughtExceptionHandler but the default behavior of UncaughtExceptionHandler is stop the process when exception occurred so it is not worked.
Currently my code looks like this. I want to get rid of try/catch blocks.
public static void main(String[] args) throws FrameworkException {
List<Element> elements = new ArrayList<>(); //Millons of data
processItems(elements)
}
public void processItems(List<Element> items) throws FrameworkException{
for (int i = 0; i < elements.size(); i++) {
try{
framework.doSomething(elements.get(i));
}
catch(FrameworkException e){
// handle
}
// . . .
try{
framework.doDifferentThing(elements.get(i));
}
catch(FrameworkException e){
// handle
}
// . . .
}
System.out.println("Processing completed.");
}
My dream code and exceptions are handled in globally.
public void processItems(List<Element> items) throws FrameworkException{
for (int i = 0; i < elements.size(); i++) {
framework.doSomething(elements.get(i));
// . . .
framework.doDifferentThing(elements.get(i));
// . . .
}
System.out.println("Processing completed.");
}
|
I'm trying to build an exe file.
The code imports pylibdmtx to decode data matrices. I found somewhere that this might cause issues with ctypes but i have no clue how to procede here. [Picture of the error I get when i try to start the exe](https://i.stack.imgur.com/VaDO9.png)
Tried reinstalling everything but have no clue what to do now. |
Error when trying to build an exe file with pyinstaller (pylibdmtx) |
|python|pyinstaller| |
null |
Maybe should think about it the other way around. Instead of checking the search value and printing static results, you could have the results in an array and filter this array by the entered search term.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [
"Ragno seat skeleton 20Β’ No.1",
"Ragno seat trim pcs 50Β’ No.3",
"Ragno headrest top skeleton and connection bar 5Β’ No.58",
"Ragno luxury sport trim whole seat and Spyder headrest 80Β’ No.101"
];
const searchtermInput = document.querySelector('.searchterm');
searchData = (e) => {
let searchterm = searchtermInput.value;
let foundData = data;
if (searchterm != '') {
foundData = data.filter(entry => entry.toLowerCase().includes(searchterm.trim().toLowerCase()));
}
console.log(foundData);
}
searchtermInput.addEventListener('input', searchData);
<!-- language: lang-html -->
<input type="text" class="searchterm" placeholder="Enter search term">
<!-- end snippet -->
You could improve the data.filter even more to handle space seperated words for example but that's up to you. Example: Split the search termin by spaces and filter for each segmet. |
flutter Null check error: did not show file and line number |
|flutter|visual-studio-code| |
I have the following:
```
syms x;
F = {3*x,2*x,x};
```
I would like to make ```F``` the following array ```G```:
```
G = [3*x,2*x,x];
```
To do this, I have tried this:
```
G = double(F);
```
and this:
```
G = double([F{:}]).';
```
Neither options work. Is there a way to do this in MATLAB? |
Convert Cell Array of Symbolic Functions to Double Array of Symbolic Functions MATLAB |
|matlab|double|symbolic-math|cell-array|sym| |
In order to assign a *static* IP address on your AWS Fargate task, you will have to create a static IP address (AWS calls this an elastic IP address) that will serve as the origin address of traffic originating your VPC from network outsiders point of view. To implement this:
You need the following:
- A [VPC][1]
- 1x private subnet
- 1x public subnet
- 1x Internet gateway attached to the public subnet
- An elastic IP address (will serve as a static IP address of all resources inside the private subnets)
- 1x [NAT][2] gateway
- A route table attached to `private` subnet with route `0.0.0.0/0` pointing to the NAT Gateway
- A route table attached to `public` subnet with route `0.0.0.0/0` pointing to the internet gateway
You will then need to make sure that:
- Your ECS Fargate task is using the VPC mentioned above (use `awsvpc` as the network mode, and configure your ECS service to use the private subnet)
- And that the private subnet(s) mentioned above is selected as the `service task placement`
If my explanation is still confusing, you could try giving [this guide][3] a read.
[1]: https://en.wikipedia.org/wiki/Virtual_private_cloud
[2]: https://en.wikipedia.org/wiki/Network_address_translation
[3]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-configure-network.html
|
I basically have to create a method that takes in a string array and a 2D array consisting of three double arrays and puts the first string with the first array, second string with the second array, etc.
```
public static void printData(String[] c, double[][] d) {
String cname = "";
for (int i = 0; i < c.length; ++i) {
cname = c[i];
for (int row = 0; row < d.length; ++row) {
for (int col = 0; col < d[0].length; ++col) {
System.out.print(d[row][col] + " ");
}
System.out.println();
}
}
}
```
Printed out the array a few times
//String word = "";
//for(int i = 0; i < c.length; ++i)
//{
//for(int row = 0; row < d.length; ++row)
//{
//System.out.println();
//for(int col = 0; col < d[0].length; ++col)
//{
//word = c[i];
//System.out.println(d[i][col]);
//}
//}
//}
I did get to the point where I was able to print the city names out with the entire 2D array under them.
|
Using ACF I created a :
field group: customers
repeater field: global_regions
repeater sub-field: continents
text subfield: continent_name
repeater subfield: countries
I have also created posts for this category and populated them with relevant data.
Now I want to create a facet on WPGridBuilder that allows the user to filter the customers either based on continent or country. For example, if they selected North America, then USA and Canada would get selected too but then the user should be able to deselect one if they wanted.
This does not seem to be possible to do within the WPGridBuilder. Could someone please help me with writing a php function for it?
I've tried this code from chagtp and it did not work, the facet it was connected to did not respond to anything in the code.
```
`add_filter('wp_grid_builder_facet_choices', function ($choices, $facet_id) {
// Replace 'your_facet_id' with the actual ID of your facet.
if ('11' == $facet_id) {
// Adjust 'your_post_type' to match your specific post type.
$posts = get_posts([
'post_type' => 'post',
'numberposts' => -1, // Retrieve all posts
'fields' => 'ids', // Only get post IDs to improve performance
]);
foreach ($posts as $post_id) {
// Assuming 'parent_field' is your ACF parent field's key.
// And 'nested_field' is your repeater or flexible content field.
// 'sub_field_value' is the sub field within the repeater you want to filter by.
if (have_rows('group_66019ebed864c', $post_id)) {
while (have_rows('group_66019ebed864c', $post_id)) {
the_row();
// Adjust according to your ACF fields' structure
if (have_rows('continents')) {
while (have_rows('continents')) {
the_row();
$value = get_sub_field('countries');
// Ensure the value does not already exist to avoid duplicates
if (!in_array($value, $choices)) {
$choices[$value] = $value;
}
}
}
}
}
}
}
return $choices;
}, 10, 2);`
``` |
It seems like my function is only receiving the first char of a string when being called |
I am trying to downlead a file form a shared Dropbox location.
I have been given a URL form a client and URL is public.
for example
https://www.dropbox.com/scl/fi/cr9zwyye5bz573ix4sjos/801NMSV621R-M570_1.jpg?rlkey=cupnu908llx3h2vzmmec97z9z&dl=0
I was excepting a normal httpclient would be able to do the job but it is not working.
public static async Task DownloadFile(string url, string saveAs)
{
using (var client = GetHttpClient())
{
await client.DownloadFileTaskAsync(url, saveAs);
}
}
I can download the image but when I open it, I see following message.
[![enter image description here][1]][1]
I have URL of hundreds of images and I can't download them manually form the browser.
[1]: https://i.stack.imgur.com/KM1Ob.png |
I just realized that I forgot to add `(.*?)` before the role attr
$str = preg_replace('~<(.*?)role="button"(.*?)</(.*?)>~Usi', "", $str);
That way it words fine. |
```
@override
Widget build(BuildContext context) {
double currentSliderValue = 100.0;
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Slider(
value: currentSliderValue,
onChanged: (double value) {
setState(() {
currentSliderValue = value;
});
},
label: '$currentSliderValue',
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
```
I tyied to make a slider , its very similir as other example, its value could be changed, but didnt move at all |
My slider have value well changed , but cant move it , or cant display changes |
|dart|slider| |
null |
After publishing the pod, the `cocoapods.org` server is still showing the previous version (`0.1`). Second attempt to publish returned `duplicate` error, but version is not found if pulled.
Is this just a delay, or were there some changes in the system? I can't pull `0.2` despite its published output.
```
Congrats
irishpod (0.2) successfully published
January 17th, 16:23
https://cocoapods.org/pods/irishpod
Tell your friends!
```
|
I am trying to filter this JSON object by the keys:
The data looks like this
```JSON
key1: value1
key2: value2
key3: value3
key4: value4
key5: value5
key6: value6
key7: value7
key8: value8
key9: value9
```
Currently what I am doing right now is renaming the keys to fit that strucure and then try to filter it out.
```JS
var reassaignedKeys;
props.data.map((entries, valuesIndex) => {
reassaignedKeys = Object.assign({}, {Owner: entries[0], ApplicationId: entries[1], ApplicationName: entries[2], Status: entries[3], DeploymentStatus: entries[4], Classification: entries[5], PersonalBindle: entries[6], PerviouslyCertified: entries[7], Goal: entries[8]})
})
console.log(reassaignedKeys)
```
This code above is what I am using to rename the keys, I am now confused on how to filter out the key and value using the key.
I know I can use
```JS
Object.keys.filter
```
But I am not getting the results I want is it keeps returning the same array back to me
|
|javascript|promise| |
That is not a "something"-delimited file, it's fixed width.
```r
readLines(unz("~/Downloads/2018029_ascii.zip", "FRSS108PUF.dat"), n=3)
# [1] "100011331 1 1 1 1 2 1 2 2 2 2 2 4 1 1 1 1 1 1 2 1 2 3 3 3 3 3 2 2 3 3 3 2 3 2 1 2 3 2 2 2 1 1 1 1 2 1 1 2 1 1 1 1 2 5 3 3 3 3 3 3 3 5 1 5 4 4 4 4 4 4 4 4 12000000000000000000000000000000000000000000000000000000000000000000000000017.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.30382293817.303822938 18.5837245717.927828408 18.5837245718.02058140118.02058140117.92782840818.471095936 0 18.5837245718.471095936 18.5837245718.47109593617.92782840818.36509251618.47109593617.92782840818.47109593618.36509251617.927828408"
# [2] "100022331 2 1 2 2 2 1 2 2 2 2 2 4 1 1 2 1 1 1 2 2 1 4 3 3 2 3 3 4 2 3 4 4 3 2 1 4 1 2 2 2 2 2 1 4 2 2 1 1 3 1 2 1 2 4 4 4 4 4 3 3 2 4 1 4 3 4 3 3 3 2 2 3 1200000000000000000000000000000000000000000000000000000000000000000000000005.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.4137039431 5.318726681 5.3187266815.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.4137039431 5.318726681 5.3187266815.33290239175.33290239175.4137039431 0 5.318726681 5.3187266815.41370394315.4137039431 5.3187266815.22702449685.41370394315.41370394315.41370394315.41370394315.41370394315.39811066135.39811066135.39811066135.41370394315.41370394315.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.2292535051"
# [3] "100032331 2 1 1 1 2 1 2 2 2 2 2 4 1 1 1 2 2 1 1 1 3 5 4 4 4 3 4 5 5 5 5 4 4 5 4 4 3 5 2 2 5 1 1 4 1 1 1 1 3 1 1 1 2 3 4 4 5 2 2 1 1 3 1 4 3 4 5 2 2 1 1 2 1200000000000000000000000000000000000000000000000000000000000000000000000005.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.4137039431 5.318726681 5.3187266815.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.41370394315.4137039431 5.318726681 5.3187266815.33290239175.33290239175.41370394315.4137039431 5.318726681 5.3187266815.41370394315.4137039431 5.3187266815.22702449685.41370394315.4137039431 05.41370394315.41370394315.39811066135.39811066135.39811066135.41370394315.41370394315.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.22925350515.2292535051"
```
The hard part about fixed-width formats is determining the widths of each field. Fortunately (somewhat), the documentation zip has `LayoutPUF.pdf` that contains each field and the columns for each.
The widths for that file should total 1441, since that's what we're getting from the file:
```r
nchar(readLines(unz("~/Downloads/2018029_ascii.zip", "FRSS108PUF.dat"), n=3))
# [1] 1441 1441 1441
```
Counting up the columns, we can use
```r
widths <- c(5, rep(1, 4), rep(2, 73), rep(1, 74), rep(12, 101))
out <- read.fwf(unz("~/Downloads/2018029_ascii.zip", "FRSS108PUF.dat"), widths = widths)
# Warning in readLines(file, n = thisblock) :
# incomplete final line found on '~/Downloads/2018029_ascii.zip:FRSS108PUF.dat'
str(out)
# 'data.frame': 1527 obs. of 253 variables:
# $ V1 : int 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 ...
# $ V2 : int 1 2 2 3 2 2 1 1 2 3 ...
# $ V3 : int 3 3 3 2 2 2 4 4 3 2 ...
# $ V4 : int 3 3 3 1 1 1 2 4 4 2 ...
# $ V5 : int 1 1 1 1 1 1 1 1 1 1 ...
# $ V6 : int 1 2 2 2 2 1 2 2 2 2 ...
# $ V7 : int 1 1 1 1 1 2 1 1 1 1 ...
# $ V8 : int 1 2 1 2 2 2 2 1 2 1 ...
# $ V9 : int 1 2 1 2 2 2 2 2 2 2 ...
# [list output truncated]
```
Over to you to name all 253 columns. You can transcribe from the pdf (you might be able to scrape it, but that doesn't look like an awesome scrape-able pdf), starting with something like
```r
colnames(out) <- c("IDNUMBER", "DSIZCL3", "URBAN", "OEREG", "Q1", "Q2", ...)
```
It will be laborious, no doubt.
---
*Edit*: try this.
```r
m <- pdftools::pdf_text(unz("~/Downloads/2018029_documentation.zip", "LayoutPUF.pdf")) |>
strsplit("\n") |>
unlist()
head(m, 20)
# [1] "U.S. DEPARTMENT OF EDUCATION" "NATIONAL CENTER FOR EDUCATION STATISTICS (NCES)"
# [3] "FAST RESPONSE SURVEY SYSTEM" "CAREER AND TECHNICAL EDUCATION PROGRAMS IN PUBLIC SCHOOL DISTRICTS"
# [5] "PUBLIC USE FILE" ""
# [7] "" " Variable Name Type Column(s) Description"
# [9] "--------------- ------ ----------- -----------" "IDNUMBER Char 1-5 Random Number assigned to each record"
# [11] "" "DSIZCL3 Num 6 District enrollment size in 3 categories"
# [13] " 1 = Less than 2,000" " 2 = 2,000-4,999"
# [15] " 3 = 5,000 or more" ""
# [17] "URBAN Num 7 Community type" " 1 = City"
# [19] " 2 = Suburban" " 3 = Town"
length(m)
# [1] 1323
m[1280:1289]
# [1] ""
# [2] "FWT98 Num 1406-1417 Replicate Weight 98"
# [3] ""
# [4] "FWT99 Num 1418-1429 Replicate Weight 99"
# [5] ""
# [6] "FWT100 Num 1430-1441 Replicate Weight 100"
# [7] ""
# [8] ""
# [9] ""
# [10] ""
head(m[10:1289])
# [1] "IDNUMBER Char 1-5 Random Number assigned to each record" ""
# [3] "DSIZCL3 Num 6 District enrollment size in 3 categories" " 1 = Less than 2,000"
# [5] " 2 = 2,000-4,999" " 3 = 5,000 or more"
tail(m[10:1289])
# [1] "" "FWT100 Num 1430-1441 Replicate Weight 100" ""
# [4] "" "" ""
nms <- grep("^\\S+", m[10:1289], value = TRUE) |>
grep(x = _, "[", fixed = TRUE, invert = TRUE, value = TRUE)
head(nms)
# [1] "IDNUMBER Char 1-5 Random Number assigned to each record"
# [2] "DSIZCL3 Num 6 District enrollment size in 3 categories"
# [3] "URBAN Num 7 Community type"
# [4] "OEREG Num 8 REGION"
# [5] "Q1 Num 9 Does your district offer CTE programs to students at the high school level?"
# [6] "Q2A Num 10-11 Does an area/regional CTE center or a group/consortium of school districts"
head(sub(" .*", "", x = nms))
# [1] "IDNUMBER" "DSIZCL3" "URBAN" "OEREG" "Q1" "Q2A"
colnames(out) <- sub(" .*", "", x = nms)
out[1:3, 1:10]
# IDNUMBER DSIZCL3 URBAN OEREG Q1 Q2A Q2B Q2C Q2D Q2E
# 1 10001 1 3 3 1 1 1 1 1 2
# 2 10002 2 3 3 1 2 1 2 2 2
# 3 10003 2 3 3 1 2 1 1 1 2
```
If you need the questions themselves, you may be able to get some of it from the `nms` object (some `substring` might be useful), though the filtering will leave many of those sentences incomplete. |
null |
null |
I have a c++ template in .cpp file defined as
template <typename T>
void `rank_filter(T* in, T* out, int arr_len, int win_len, int order, Mode mode, T cval, int origin)`
where `Mode` is enum.
Following [this][1] answer, I am trying to wrap it up by Cython, by a .pyx file:
cimport cython
cimport numpy as np
ctypedef fused numeric_t:
np.float32_t
np.float64_t
np.int32_t
np.int64_t
@cython.boundscheck(False) # Deactivate bounds checking
@cython.wraparound(False) # Deactivate negative indexing.
cdef extern from "_rank_filter_1d.cpp" nogil:
void rank_filter[T](T* in, T* out, int arr_len, int win_len, int order, Mode mode, T cval, int origin)
def rank_filter_1d(numeric_t[:] in_arr, numeric_t[:] out_arr, int win_len, int order, int mode, numeric_t cval, int origin):
rank_filter(&in_arr[0], &out_arr[0], in_arr.shape[0], win_len, order, mode, cval, origin)
return out_arr
unfortunately, running `python setup.py build_ext --inplace` in the terminal results in an error:
cdef extern from "_rank_filter_1d.cpp" nogil:
void rank_filter[T](T* in, T* out, int arr_len, int win_len, int order, Mode mode, T cval, int origin)
^
------------------------------------------------------------
rank_filter_1d_cython.pyx:13:27: Expected ')', found 'in'
I tried to add `cdef` before the void, which did not work well. Any other ideas?
[1]: https://stackoverflow.com/a/46628292/8443371
|
wrapping c++ function template with Cython |
|c++|templates|cython| |
I don't believe you can do that with `ffprobe`, but `ffmpeg` can do that, and output the subtitles to stdout.
```
ffmpeg -i video.mkv -f srt -
```
You can switch out `srt` for any other subtitle format `ffmpeg` understands, such as `ass`. |
From the [C23 draft](https://open-std.org/JTC1/SC22/WG14/www/docs/n3220.pdf):
7.23.6.1 The `fprintf` function
> 8. The conversion specifiers and their meanings are:
>
> * `p` The argument shall be a pointer to void or a pointer to a character type. The value of the pointer is converted to a sequence of printing characters, in an **implementation-defined** manner.
That means that different implementations may produce different output, even if the actual pointer values would happen to be the same.
Typically, no more than the significant non-zero digits will be printed so if you get 9 digits on your Mac, that's just an effect of that. The 32 bit address `0x00000FFF` will often be printed as just `0xFFF`.
---
If you want the same format on all platforms and implementations, you could cast the pointer to `uintptr_t` and print that instead.
Example:
```c
#include <inttypes.h> // PRIxPTR
#include <stdint.h> // uintptr_t
//...
printf("&n stores the address of n = 0x%016" PRIxPTR "\n", (uintptr_t)&n);
```
Possible output:
```none
&n stores the address of n = 0x000000016fa13224
``` |
How to create a facet for WP gridbuilder that displays both parent and child custom fields? |
|php|wordpress|advanced-custom-fields| |
null |
Sorry for my bad english)
I created a dynamic array of structures. This structures contains dynamic array of doubles.
When I add the structure, I fill it this way
The number of sides and the length of the side are filled in calmly, but when it comes to the vertices, or rather to one vertex (along which I have to restore the rest), after entering any number, the program crashes
```sh
struct regular_polygon {
int count_sides;
double length;
double square;
double perimeter;
double *x = new double[count_sides];
double *y = new double[count_sides];
};
void SetData(regular_polygon* reg_pol, int amount, int* output)
{
cout << "Enter count of sides:" << '\n';
cin >> reg_pol[amount-1].count_sides;
bool flag = false;
if (reg_pol[amount].count_sides > 2) flag = true;
while (flag == false)
{
cout << "Incorrect! Sides must be more than 2. Try again" << '\n';
cin >> reg_pol[amount].count_sides;
if (reg_pol[amount].count_sides > 2) flag = true;
}
cout << "Enter length of the side:" << '\n';
cin >> reg_pol[amount].length;
flag = false;
if (reg_pol[amount].length > 0) flag = true;
while (flag == false)
{
cout << "Incorrect! Length must be more than 0. Try again" << '\n';
cin >> reg_pol[amount].count_sides;
if (reg_pol[amount].length > 0) flag = true;
}
cout << "Enter vertex coordinates" << '\n';
cout << "Enter x:" << '\n';
cin >> reg_pol[amount - 1].x[ 0]; /// Π’Π£Π’ ΠΠ¨ΠΠΠΠ
cout << "Enter y:" << endl;
cin >> reg_pol[amount - 1].y[ 0];
coordinates(reg_pol, amount);
}
cout << "Enter vertex coordinates" << '\n';
cout << "Enter x:" << '\n';
cin >> reg_pol[amount - 1].x[ 0]; /// There is an error
```
I tried to replace dynamic array of doubles to static array of doubles, but it didnot help, unfortunately |
Dynamic array of structures in C++/ cannot fill a dynamic array of doubles in structure from dynamic array of structures |
|c++|function|double|structure|dynamic-arrays| |
null |
Here's what worked for me using Qt 6 and CMake.
First of all, an `.rc` file is different than `.qrc`. This isn't explained *at all* in the Qt documentation for setting up an application icon ([link][1]), they just assume everyone knows that. Both formats are *text files*, they don't contain any pixel data. They're just text files with a different extension.
I'm assuming you already have an .ico file. This post isn't about creating one. Ideally, it should have multiple versions embedded inside of it at different resolutions: 64x64, 48x48, 40x40, 32x32, 24x24, 20x20, 16x16.
In my project folder I have it as "./res/img/favicon.ico" but the name of the .ico file doesn't matter, you can name it "appicon.ico" if you want, or whatever.
And a text file renamed as `favicon.rc` next to it, with the following contents:
IDI_ICON1 ICON "favicon.ico"
And as a side note, Visual Studio generated an .rc file (in another project) with the following comment above the app icon which is interesting:
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_ICON1 ICON "LearnOpenGL.ico"
So the "IDI_ICON1" name seems to serve an actual purpose.
You could, technically, rename that label anything you wanted, like "MyAppIcon" instead of "IDI_ICON1". Just like the OP did in the question at the very top.
However, then only the .exe icon will be set, not the window icon as well. Which I suppose can be set separately, using Qt Designer (or editing the .ui in Qt Creator) for the top-most widget "QMainWindow", since there's a "windowIcon" field there. Or programmatically with `.setWindowIcon()`. But that's besides the point. It doesn't make sense (to me) to have separate icons for the .exe and for the window. As long as it's set in CMake correctly, it will apply to both the .exe and the window.
Moving on.
In the `CMakeLists.txt` file, create an `app_icon_resource_windows` variable (with `set`) before adding it to `qt_add_executable(...)`:
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
set(app_icon_resource_windows "${CMAKE_CURRENT_SOURCE_DIR}/res/img/favicon.rc")
qt_add_executable(YourCoolProjectNameHere
MANUAL_FINALIZATION
${PROJECT_SOURCES}
${app_icon_resource_windows}
)
AND THAT'S IT!
Rebuild your project (or Clear + Build, same thing) and enjoy!
PS: The `app_icon_resource_windows` CMake variable is in lowercase in my example (same as in the Qt documentation), while the OP had it in uppercase. It doesn't matter, as long as it's consistent in both places. Otherwise it compiles fine but with no icon and without even a WARNING!
PS #2: If you don't want the .rc file next to your .ico files or images or whatever, you can place it 2 folders above it, but then the contents of the file should point to it correctly:
IDI_ICON1 ICON "res/img/favicon.ico"
And then obviously update "CMakeLists.txt" to stop looking for the .rc file in "/res/img/":
set(app_icon_resource_windows "${CMAKE_CURRENT_SOURCE_DIR}/favicon.rc")
The idea is to have CMake point at a .res file, which itself points at an .ico file. As long as you set the paths correctly, it will work out just fine.
[1]: https://doc.qt.io/qt-6/appicon.html |
I have used recast for my code generation with babel as i jhave checked it is compatable with babel but recast is removing all my comments
Here is my recast code
const generatedAst = recast.print(ast, {
tabWidth: 2,
quote: 'single',
});
i am passing AST generated from babel parse
and directly if i use babel generate to generate my code than parenthesis are getting removed
Can anyone help me with this
Thankyou in advance
i don't know any other package that is compatible with babel
i used recast because i have checked this [text](https://github.com/babel/babel/issues/8974) and in this it is mentioned that babel removes parenthesis |
No, you cannot transition a background.
The simplest solution is to use an SVG element in your HTML. This is what SVG is good at: vector graphics. You then apply styles to that element using CSS.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.heart {
width: 200px;
aspect-ratio: 1;
transition: .5s;
fill: red;
}
.heart:hover {
fill: blue;
}
<!-- language: lang-html -->
<svg class="heart" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<path d="M 200 60 C 200 75.138 194.394 88.967 185.144 99.523 L 100 200.009 L 14.856 99.523 C 5.606 88.967 0 75.138 0 60 C 0 26.863 26.863 0 60 0 C 75.367 0 89.385 5.777 100 15.278 C 110.615 5.777 124.633 0 140 0 C 173.137 0 200 26.863 200 60 Z"/>
</svg>
<!-- end snippet -->
But if you are stuck with HTML from somewhere else and therefore want to do it all in CSS, you could achieve it using two pseudo-elements and animating the `opacity` of one of them.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.heart {
width: 200px;
aspect-ratio: 1;
position: relative;
}
.heart::before, .heart::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.heart::before {
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M 200 60 C 200 75.138 194.394 88.967 185.144 99.523 L 100 200.009 L 14.856 99.523 C 5.606 88.967 0 75.138 0 60 C 0 26.863 26.863 0 60 0 C 75.367 0 89.385 5.777 100 15.278 C 110.615 5.777 124.633 0 140 0 C 173.137 0 200 26.863 200 60 Z' style='fill: red;'/%3E%3C/svg%3E");
}
.heart::after {
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M 200 60 C 200 75.138 194.394 88.967 185.144 99.523 L 100 200.009 L 14.856 99.523 C 5.606 88.967 0 75.138 0 60 C 0 26.863 26.863 0 60 0 C 75.367 0 89.385 5.777 100 15.278 C 110.615 5.777 124.633 0 140 0 C 173.137 0 200 26.863 200 60 Z' style='fill: blue;'/%3E%3C/svg%3E");
opacity: 0;
transition: 0.5s;
}
.heart:hover::after {
opacity: 1;
transition: 0.5s;
}
<!-- language: lang-html -->
<div class="heart">
<button id="widget-toggle" class="widget-toggle-open drawer-toggle widget-toggle-style-default" data-toggle-target="#widget-drawer" data-toggle-body-class="showing-widget-drawer" aria-expanded="false" data-set-focus=".widget-toggle-close">
<span class="widget-toggle-label">MENU</span>
<span class="widget-toggle-icon">
</span>
</button>
</div>
<!-- end snippet -->
|
I have a data frame with a column of the date:
[](https://i.stack.imgur.com/3ejSV.png)
I would like to partition the DF into 3 DF based on time:
1. 00:00-12:00.
2. 12:00-18:00.
3. 18:00:00:00.
How can it be achieved without a loop?
I could implement this by using a loop over each time stamp, yet it was very slow.
A sample data could be generated by:
```python
df = pd.DataFrame(pd.date_range(start='2024-01-01', end='2024-01-10', freq='10min'))
df['data'] = np.random.randint(100, size=len(df))
df.columns = ['date', 'data']
``` |
This the workaround I'm now using as an answer until I can get something less fragile.
Instead of importing the correct module 'dyna.ts' instead provides an object (cryptoState) that can be given the correct crypto module by importing (for its side effects alone) a different module (provideNode.ts or provideWeb.ts) that will ensure any other module importing the cryptoState object will use the desired crypto functions (just remember never to point directly at the functions instead use: ```cryptoState.core.fuctionName(args)```).
For forwards compatibility with a 'dyna.ts' that actually works as desired the needed crypto functions are available as arrow functions that call the functions inside cryptoState. (This also makes it backwards compatible with modules written before I ran into the problems being solved here.)
dyna.ts:
```
import { CryptoBox } from "../types";
import box from './web'; //for fallback purposes, this is expected to fail internally and respond with {hash:undefined;random:undefined}
class CryptoState{
private _givenCore:false|"node"|"web"|"unspecified"|"webFallback";
private _coreWrites:bigint;
private _core:undefined|CryptoBox;
constructor(){
this._givenCore=false;
this._coreWrites=0n;
this._core=undefined;
}
get givenCore():false|"node"|"web"|"unspecified"|"webFallback"{
return this._givenCore;
}
set givenCore(arg:"node"|"web"){
console.log("setting givenCore to:",arg)
if (this._givenCore==="unspecified"||this._givenCore==="webFallback") this._givenCore=arg;
else if (this._givenCore===false) throw new Error("CryptoState will not set givenCore string before having a core object");
else if (this._givenCore!==arg) throw new Error("CryptoState will not set givenCore string to something contradicting prior givenCore string")
}
get core(){
if (this._givenCore && this._core) return this._core;
if (box.hash && box.random) {//todo keep updated
this._givenCore="webFallback";
this._core=box as CryptoBox;
this._coreWrites++
return this._core;
}else throw new Error("CryptoState core access attempted prior to initialization without fallback");
}
set core(arg:CryptoBox){
console.log("setting core");
if (this._core===undefined) this._core=arg;
this._coreWrites++
if (this._givenCore===false) this._givenCore="unspecified";
}
setCore(core:CryptoBox,envStr:"node"|"web"){
this.core=core;
this.givenCore=envStr;
}
}
export const cryptoState=new CryptoState();//! do not point directly at its functions instead keep using cryptoState.core.functionName as the value of core may be replaced
export const hash=(data: string, salt: string, ...moreSalt: string[])=>{
return cryptoState.core.hash(data,salt,...moreSalt);
}
export const random=(range:bigint)=>{
return cryptoState.core.random(range);
}
```
provideNode.ts:
```
import { cryptoState } from "./dyna";
import core from "./node";
cryptoState.setCore(core,"node");
export default cryptoState;
```
provideWeb.ts:
```
import { CryptoBox } from "../types";
import { cryptoState } from "./dyna";
import core from "./web";
cryptoState.setCore(core as CryptoBox,"node");
export default cryptoState;
```
To ensure that having ```import box from './web'``` as an available fallback in 'dyna.ts' 'web.ts' is written to fail without emitting an error:
web.ts:
```
import { CryptoBox } from "../types";
//* run when node is unavailable (edge & client side)
const box:Partial<CryptoBox>={};
try{
if (typeof crypto === "undefined") throw new Error("lacking web crypto");
async function hash(data:string,salt:string,...extraSalt:string[]):Promise<string>
async function hash(...data:string[]):Promise<string>{
...omitted function content
}
box.hash=hash;
function random(range:bigint){
...omitted function content
}
box.random=random;
}catch(error){
console.warn(error);
box.hash=undefined;
box.random=undefined;
}
export default box;
```
And finally 'node.ts' remains unchanged but for compleatnesses sake:
node.ts:
```
const _crypto:typeof import('node:crypto') = require('node:crypto');
//* run only when node environment is available (not the edge runtime nor client side)
async function hash(data:string,salt:string,...moreSalt:string[]):Promise<string>
async function hash(...stuff:string[]):Promise<string>{//asynchronous to maintain identical interface to the web API version
const x=_crypto.createHash('sha256');
if (stuff.length<2) throw new Error("hash() not given valid salt")
x.update("".concat(...stuff)+"RestaurantApp");
return x.digest('hex');
}
const maxSecRan=2n**48n-1n;
function random(range:bigint):bigint{
return (range<=maxSecRan)?
BigInt(_crypto.randomInt(Number(range))):
_crypto.randomInt(1)?
BigInt(random(range/2n)):
range/2n+BigInt(random(range-(range/2n)));
}
export default {hash:hash,random:random};
```
for an example as to how this ends up working the middleware running on edge runtime imports as follows:
```
import './lib/crypto/provideWeb'; //sets up the correct crypto functions to make the auth functions work
import { getValidatedSessionData } from './lib/server_only/auth/login';
```
and the module containing the server actions available to the client imports as follows:
```
'use server'
import './crypto/provideNode'; //! this will break in the edge runtime !
import { signIn,getAccountByID,fakeSalt, getValidatedSessionData } from "@/lib/server_only/auth/login";
``` |
[Error image ][1]Added the AspNetCore.Mvc.Razor.RuntimeCompilation package for live updating of .cshtml pages. But when writing builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); an error occurs in the Program.cs file An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately. When compiled with the usual builder.Services.AddControllersWithViews(), everything works correctly.
The package version is correct and no other errors occur. Please tell me what could be the problem?
[1]: https://i.stack.imgur.com/0oD95.png |
Python is an interpreted language.
When you write something like:
```
print("1"*n)
```
The Python interpreter performs a loop internally.
It is more efficient in Python because the interpreter is usually written in a compiled language like C (or C++) and so the loop is more efficient when done internally.
But since C itself is a compiled language writting a simple loop (which will be done in **O(n)** as you requested), is the most efficient thing you can do. This loop can be either "manually" written or via some library function like `memset` which is implemented with a loop.
Note that such a loop can be replaced with a recursion, but this is not expected to improve performance (recursion is _usually less efficient_ than a simple loop).
The most "expensive" operation in this case is actually the I/O which might be buffered.
So the best you can do might be to build the final string (with a loop) into a buffer, and then use one `printf` statement to dump it the console.
As usual with matters of performance, you should profile it to check.
**Note:**
The answer above assumes that `n` isn't known in advance, and can be arbitrarily large.
I used this assumption because:
(1) The python statement used as a reference hints to that.
(2) The OP mentioned O(n) complexity which is meaningful only when `n` is relatively large. |
{"OriginalQuestionIds":[23937262,10714251],"Voters":[{"Id":4279155,"DisplayName":"Dominique"},{"Id":9245853,"DisplayName":"BigBen","BindingReason":{"GoldTagBadge":"excel"}}]} |
I try to implement simple delay-typing functionality in React component
What is working but still without debounce:
```
const handleChange = useCallback(
(ev: ChangeEvent<HTMLInputElement>) => {
if (!isNaN(ev.target.value as unknown as number)) {
setTextField(ev.target.value as string);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[value]
);
```
And here very important point: setTextField is defined in ancestor component (setTextField sets regular state created with useState) Why? I need a way to make this setTextField available in other component B (to clear input; what is side activity for component B, but anyway it's a must; I would rather quit debounce and leave this structure).
So, setTextField is delivered simply as a prop.
My attempts are like this:
```
const act = (ev: ChangeEvent<HTMLInputElement>) => {
if (!isNaN(ev.target.value as unknown as number)) {
setTextField(ev.target.value as string);
}
};
const debouncedChangeHandler = useMemo(() => {
const changeHandler = (event: any) => {
act(event);
};
return debounce(changeHandler, 300);
}, []);
```
but this is not neither first nor last try. None of them works (by that I mean that typed number is not visible in the text field). I have logged also that ev.target.value in debounced version is undefined. It might be that event after 300 ms does not exist any more β but I am not sure. Any way, have no idea how to fix the issue. Could someone help?
``` |
I essentially want to write a program that takes F and decrements it until its 0, displaying the results like : F E D C B A 9 8 7 6 5 4 3 2 1 0. I specifically have to use a loop to write these out, i can't just say "db 'F E D C B A 9 8 7 6 5 4 3 2 1' , 10, 0". Since I can't use system calls to print (write) hex digits I abandoned that way of thinking. Wherever I go I'm told to use printf since it doesn't require a conversion from number to character. However, printf seems to require a parameter that's usually something along the lines of "db '%x', 10, 0" within a label. That 10 usually being a LF makes it seemingly impossible to write a *horizontal* list and instead writes a *vertical* list which I really don't want.
So I tried to take this program:
```asm
extern printf
global main
section .data
format_specifier:
db '%x', 10, 0 ;format specifier for printf with LF
section .text
main:
mov rbx, qword 16
loop1: ;loop to decrement and print number in rsi
dec rbx
mov rdi, format_specifier
mov rsi, rbx
xor rax, rax
call printf
cmp rbx, qword 0
jne loop1
mov rax, 60
syscall
```
and replace the 10 in the format specifier with 0x20 (the space ASCII) to separate the hex digits as they printed. This, of course, resulted in nothing outputting whatsoever.
I have seen that LF flushes the output buffer and I have tried using fflush to do the same with no avail as seen:
```asm
extern printf
extern fflush
global main
section .data
format_specifier:
db '%x', 0x20, 0 ;format specifier for printf with LF
section .text
main:
mov rbx, qword 16
loop1: ;loop to decrement and print number in rsi
dec rbx
mov rdi, format_specifier
mov rsi, rbx
xor rax, rax
xor rsi, rsi
call fflush
call printf
cmp rbx, qword 0
jne loop1
mov rax, 60
syscall
```
I'm unsure whether it is even the right idea to try and use fflush for my program or if I'm just going in the wrong direction. Please help. |
|java|arrays|multidimensional-array| |
We've built a Teams tab app following pretty much this sample https://github.com/OfficeDev/TeamsFx-Samples/tree/dev/hello-world-tab-with-backend
It is working fine on all platforms (Teams Web, Teams Desktop, Teams Mobile, Outlook Web, Outlook Desktop) except Outlook Mobile. It seems that outlook mobile is not getting sso token from:
```
import { useTeamsUserCredential } from '@microsoft/teamsfx-react';
```
We're getting this on Outlook Mobile:
[enter image description here](https://i.stack.imgur.com/Up7Xf.jpg)
My understanding is that the Auth flow should work exactly same on all platforms |
Teams tab application returns SSO error in mobile Outlook |
|reactjs|microsoft-graph-api|microsoft-teams| |
null |
A bit better patch:
+ if (p->nullValue[0] != '\0' && cli_strcmp(z, p->nullValue)==0) sqlite3_bind_null(pStmt, i+1);
+ else sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
Now, when .nullvalue is set this value is replaced to NULL while importing CSV/TSV file. |
A bit beter patch:
+ if (p->nullValue[0] != '\0' && cli_strcmp(z, p->nullValue)==0) sqlite3_bind_null(pStmt, i+1);
+ else sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
Now, when .nullvalue is set this value is replaced to NULL while importing CSV/TSV file. |
I am trying formula `if` with multi conditions in Excel.
but the result `#VALUE!`is there is something wrong with my formula please guide me
Thanks
| DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT |
| -------- | -------- |-------- |-------- |-------- |--------|
| 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 | |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 | |
| 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 | |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 | |
| 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 | |
| | IN | | | | |
```
=IF(A2="",""),IF(AND(B2="OUT",E2<=C2,),"NORMAL","LATE"),IF(AND(B2="IN",D2<=C2),"NORMAL","LATE")
```
Result from above formula
| DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT |
| -------- | -------- |-------- |-------- |-------- |--------|
| 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |#VALUE! |
| 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 |#VALUE! |
| | IN | | | |#VALUE! |
[Screenshot IN EXCEL](https://i.stack.imgur.com/qCgFE.png)
Desired Result
| DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT |
| -------- | -------- |-------- |-------- |-------- |--------|
| 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 |NORMAL |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |NORMAL |
| 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 |LATE |
| 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |NORMAL |
| 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 |LATE |
| | IN | | | | |
|
How to formula if with multi conditions in Excel |
|excel|excel-formula|excel-2010| |
null |
As of [JMeter 5.6.3][1] it's not possible.
As a workaround you can use [Backend Listener][2] to send test metrics to a database like [InfluxDB][3]. Then you can plot whatever charts you want in [Grafana][4]
Alternatively you can customize the dashboard by manipulating the files in the [report-template][5] folder, you will need to be familiar with [Apache FreeMarker][6] for that.
[1]: https://lists.apache.org/thread/o906of55x1n8z2zm8fyj3w9k3lqf8y0c
[2]: https://jmeter.apache.org/usermanual/component_reference.html#Backend_Listener
[3]: https://www.influxdata.com/
[4]: https://www.blazemeter.com/blog/jmeter-grafana
[5]: https://github.com/apache/jmeter/tree/rel/v5.6.3/bin/report-template
[6]: https://freemarker.apache.org/index.html |
I have used recast for my code generation with babel as i jhave checked it is compatable with babel but recast is removing all my comments
Here is my recast code
const generatedAst = recast.print(ast, {
tabWidth: 2,
quote: 'single',
});
i am passing AST generated from babel parse
and directly if i use babel generate to generate my code than parenthesis are getting removed
Can anyone help me with this
Thankyou in advance
i don't know any other package that is compatible with babel
i used recast because i have checked this [link](https://github.com/babel/babel/issues/8974) and in this it is mentioned that babel removes parenthesis |
Attempts at running conpot is giving me a illegal instruction (core dumped) error.
I am running an Ubuntu 22.04.4 server and I am attempting to run a conpot on it. It was working this morning and I went to boot up another vm from the same ISO and now when I attempt to start conpot. (conpot -f --template default). I get an illegal instruction (core dumped) error. I am running Python 3.10.12. |
Why am I getting an Illegal instruction (core dumped) error when attempting to run conpot in a vm? |
|python|ubuntu-22.04|honeypot| |
null |
{"Voters":[{"Id":23922491,"DisplayName":"Piotr GasidΕo"}],"DeleteType":1} |