instruction stringlengths 0 30k ⌀ |
|---|
How to merge duplicate rows when with same ID with different data |
You don't need to use exec for it, just store these fields inside a dictionary and loop through them creating sql statements.
# List of field names
flds = ["foo", "bar", "foobar"]
# Dictionary mapping field names to their values
values = {
"foo": "red",
"bar": "",
"foobar": "green"
}
# Initial SQL statement
sql = "UPDATE table SET a = 1"
# Iterate over the list of fields and construct the SQL dynamically
for fld in flds:
value = values.get(fld)
if value == "":
sql += f", {fld} = NULL"
elif value is not None:
sql += f", {fld} = '{value}'"
print(sql) |
I'm facing an issue in my Spring Boot application where I'm unable to display the ObjectMessage body. The error message I receive is 'jakarta.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: ' The code involves sending and receiving JMS messages. Could you assist me in identifying the root cause and providing a solution to resolve this serialization issue?
Here is the code snippet:
```java
public void send(Test test) {
try {
log.info("Sending Message with JMSCorrelationID: {}", test);
ObjectMessage message = jmsTemplate.getConnectionFactory().createContext().createObjectMessage();
message.setObject(test);
jmsTemplate.convertAndSend(destinationName, message);
} catch (Exception e) {
throw new RuntimeException("Cannot send message to the Queue");
}
}
@JmsListener(destination = "yourQueueName")
public void receiveMessage(Message message) {
try {
ObjectMessage objectMessage = (ObjectMessage) message;
log.info("Received Message: " + objectMessage.getObject());
} catch (Exception e) {
log.error("Received Exception: " + e);
}
}
```
I appreciate your help in resolving this issue. |
jakarta.jms.JMSException: Failed to build body from content. Serializable class not available to broker |
|spring|activemq-classic| |
null |
|flutter|firebase|dart|google-cloud-firestore| |
null |
There does not appear to be any way around the issue until Google fixes it. As you can see from Google's Issue Tracker in the link shared by darrelltw (Updated link as the issues have now been consolidated: https://issuetracker.google.com/issues/326802543), it has been impacting users in many places around the world.
In the interest of adding some more information (as many people are trying to get answers), I am including the following link providing Google's confirmation of the issue here: https://support.cloud.google.com/portal/system-status?product=WORKSPACE.
Screenshot from the above site:
[![Screenshot][1]][1]
**Update:**
Here in my region of the USA, my Apps Script projects are now currently accessible for the first time this morning. But this is apparently not universal because the upvotes on Google's Issue Tracker continue to increase.
[1]: https://i.stack.imgur.com/C1Fnc.png |
I have swiper which works perfectly with existing elements. But when i scroll down my script creates dyncamically elements and my swiper are not work because at beggining it doesnt add event listiner.
```
var swiperContainer = document.querySelectorAll('.swiper1')
swiperContainer.forEach(function (elem) {
var swiper = new Swiper(elem, {
spaceBetween: 30,
pagination: {
el: elem.parentElement.querySelector('.swiper-pagination1'),
clickable: true,
dynamicBullets: true,
},
navigation: {
nextEl: elem.parentElement.querySelector('.swiper-button-next1'),
prevEl: elem.parentElement.querySelector('.swiper-button-prev1'),
},
});
})```
I tried this using jquery still didnt work. I know it works if i remove this event listener and add again after loaded more elements. Is there any way to to do it better ? |
how to add event listener to dynamically created elements? |
|javascript|swiper.js| |
null |
I want to be able to measure any code snippet time complexity. Is there a general rule or step by step approach to measure any big o (besides dominant term, removing constants and factors)? What math skills should I have, if so, what are the prerequisites for those skills? Also, what is enough for interviews?
Here is one of those:
```
int fun(int n) {
int count = 0;
for (i = n; i > 0; i /= 2) {
for (j = 0; j < i; j++) {
count += 1;
}
}
return count;
}
```
I've read many algorithms books, but they're mathy and not beginner-friendly. |
Postgres (like SQL) is strictly typed. Functions cannot change their return type on the fly - including number, names and types of columns for a function returning a row type.
There is a limited workaround with a [**polymorphic functions**][1], where the return type is determined by given input. The trick is to pass the actual return type to the function. See:
- https://stackoverflow.com/questions/11740256/refactor-a-pl-pgsql-function-to-return-the-output-of-various-select-queries/11751557#11751557
Only makes sense for exotic use cases.
That said, here is how you pull off such a stunt:
~~~pgsql
-- create desired return types
CREATE TYPE public.result1 AS (col1 text, col2 text);
CREATE TYPE public.result2 AS (col2 int, col3 int);
-- create polymorphis function
CREATE OR REPLACE FUNCTION public.get_parameterbased_return_table1(_return_type anyelement)
RETURNS SETOF anyelement
LANGUAGE plpgsql AS
$func$
BEGIN
CASE pg_typeof(_return_type)
WHEN 'public.result1'::regtype THEN
RETURN QUERY
SELECT t.col1, t.col2
FROM parameterbased_return_table t;
WHEN 'public.result2'::regtype THEN
RETURN QUERY
SELECT t.col3, t.col4 -- returning actual int values
FROM parameterbased_return_table t;
ELSE
-- Handle other conditions or return an empty result set
-- just don't return anything (simpler)
END CASE;
END
$func$;
~~~
Call:
```
SELECT * FROM public.get_parameterbased_return_table1(null::public.result1);
```
| col1 | col2 |
|:-----|:-----|
| A | B |
| dfdf | dfe |
```
SELECT * FROM public.get_parameterbased_return_table1(null::public.result2);
```
| col3 | col4 |
|-----:|-----:|
| 11 | 22 |
| 14 | 545 |
[fiddle](https://dbfiddle.uk/bbHKSai0)
[1]: https://www.postgresql.org/docs/current/extend-type-system.html#EXTEND-TYPES-POLYMORPHIC |
Need to parse/merge a csv and excel file, and create a new table with discrepancies between 2 datasets |
|python|excel|csv| |
null |
Instead of pyreadstat you can use pyspssio.
If it's the first time you're using this library, you may need to install it:
pip install pyspssio
To read the data in, you can use similar syntax to pyreadstat:
import pyspssio
df, meta = pyspssio.read_sav("C:/my_doc.sav")
To export with the metadata, use metadata=... argument:
pyspssio.write_sav("C:/my_doc v2.sav",df,metadata=meta)
You can find more details here:
[https://pyspssio.readthedocs.io/en/stable/readme.html][1]
[1]: https://pyspssio.readthedocs.io/en/stable/readme.html |
So in newer version first thing u have to do is add this code in the main js file you should add
1. require('@electron/remote/main').initialize();
Then you add this after app.on('ready', createWindow);
2. app.on('browser-window-created', (_, window) => {
require("@electron/remote/main").enable(window.webContents)
});
In renderer after defining electron you should add this:
3.const { BrowserWindow } = require('@electron/remote');
And that is it, took me a while to read docs and find few solutions online, there is no much. |
Give this measure a try
Count Winning Streak =
VAR person =
SELECTEDVALUE ( 'table'[ Name ] )
VAR last_week =
MAX ( 'table'[ Week ] )
VAR lastweekStart =
CALCULATE (
MAX ( 'table'[ Week ] ),
FILTER (
ALL ( 'table' ),
'table'[ Name ] = person
&& 'table'[ DidItHappen ] = 0
&& 'table'[ Week ] < last_week
)
)
VAR streak =
CALCULATE (
COUNTROWS ( 'table' ),
FILTER (
ALL ( 'table' ),
'table'[ Name ] = person
&& 'table'[ Week ] <= last_week
&& 'table'[ Week ] >= lastweekStart
&& 'table'[ DidItHappen ] = 1
)
)
RETURN
IF ( SELECTEDVALUE ( 'table'[ DidItHappen ] ) = 0, 0, streak )
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/z97Ju.png |
For Lambda function URL:
In the AWS console, go to **Lambda** -> **Functions** -> (select the function) -> **Configuration** -> **Function URL** -> **Edit**
Check **Configure cross-origin resource sharing (CORS)** and enter * for **Allow origin**, **Allow headers**, and **Allow methods**
**Save** |
You can call `increaseOpcodeBudget()`. This will create/delete an app for more opcode budget. More sophisticated methods are possible in the future, but this AVM PR might change the need for that: https://github.com/algorand/go-algorand/pull/5943
TEALScript docs: https://tealscript.netlify.app/api/functions/increaseopcodebudget/#_top |
Try by adding this `request.format = :csv` before `respond_to`
```
request.format = :csv
respond_to do |format|
format.csv { render text: ["a", "b"].to_csv }
end
```
|
To enable syntax highlighting for JBehave stories in Eclipse: You can Install JBehave Eclipse Plugin (Optional):There's a JBehave Eclipse Plugin available that provides features like syntax highlighting and step completion. You can install it from the Eclipse Marketplace or through the Eclipse IDE.
**Associate File Extension:** Ensure that your JBehave story files have the correct file extension (usually `.story`). Right-click on a `.story` file in Eclipse and select `Open With` > `Other...`. Choose a text editor (such as the default Text Editor or any other preferred editor).
**Configure Syntax Highlighting:** Once you've associated the `.story` files with a text editor, you may need to configure the syntax highlighting preferences. Go to `Window` > `Preferences` > `General` > `Editors` > `File Associations`. Here, you can select the file type (e.g., "*.story") and associate it with the text editor.
After configuring the syntax highlighting preferences, click `Apply` or `OK` to save the changes.
The above solution worked for me . |
I’m going to recommend a slightly different approach that I think gets at the functionality you are looking for.
First, as noted by others, an interface is a Typescript language feature not a Javascript language feature. It’s used for static type checking during compile time, and that’s ir; there is no object or class that gets created in the resulting JavaScript. As such, you can’t extend it. If you wanted to be able to extend it you’d need to use a class instead of an interface.
What you can do, however, is define special functions that will evaluate a given instance of your Product interface and inform Typescript whether or not it it has additional properties. These special functions are referred to as type guards (https://www.typescriptlang.org/docs/handbook/advanced-types.html).
So, for instance, you could write a *hasAbc* type guard like so:
function hasAbc (p : Product): p is Product & { abc: string } {
return _.isString(p.abc);
}
Now if you use this function in an if-block, the typescript compiler will be happy when you reference the field *abc* from a Product:
function work(p: Product) {
…
if (hasAbc(p)) (
// no type script error!
const abc = p.abc;
…
}
…
} |
I have a .cdf file which have variables `Epoch, FEDU and L`. I want to plot a spectrogram having `Epoch` (which represents time) on x axis and varying `L` and `FEDU`. The data I used is located at [text](https://rbsp-ect.newmexicoconsortium.org/data_pub/rbspa/rept/level3/pitchangle/2014/). Also I tried plotting for 3 days consecutively.
I tried this, but dont know how to insert `L`
```
def plot_spectrogram(cdf_file, variable_name, datetime_values):
# Open the CDF file
cdf = cdflib.CDF(cdf_file)
# Read the variable data
data = cdf[variable_name][...]
# Define values to remove
values_to_remove = [-1.e+31, -1.00000e+31, -9.9999998e+30]
# Filter out the values
filtered_data = np.where(np.isin(data, values_to_remove), np.nan, data)
# Average or sum the filtered data across the alpha dimension
averaged_data = np.nanmean(filtered_data, axis=2) # Using np.nanmean to ignore NaN values
# Convert datetime objects to numerical timestamps for plotting
numerical_times = date2num(datetime_values)
# Plot the aggregated spectrogram
plt.figure(figsize=(10, 6))
plt.imshow(averaged_data.T, aspect='auto', origin='lower', cmap='rainbow', extent=[numerical_times[0], numerical_times[-1], 0, averaged_data.shape[1]])
plt.colorbar(label='Intensity ($cm^2$ s sr keV)')
plt.xlabel('Time')
plt.ylabel('Energy (keV)')
plt.title('Aggregated Spectrogram of {}'.format(variable_name))
plt.gca().xaxis.set_major_formatter(DateFormatter('%Y-%m-%d %H:%M:%S')) # Format x-axis ticks as datetime
plt.xticks(rotation=15)
plt.tight_layout()
plt.show()
# Usage example
cdf_files = ['C:/Users/User/Desktop/AB/cdf/H1/rbspa_ect-elec-L3_20140923_v1.0.0.cdf',
'C:/Users/User/Desktop/AB/cdf/H1/rbspa_ect-elec-L3_20140924_v1.0.0.cdf',
'C:/Users/User/Desktop/AB/cdf/H1/rbspa_ect-elec-L3_20140925_v1.0.0.cdf']
# Concatenate spectrogram data from all files
datetime_values = []
for cdf_file in cdf_files:
cdf = cdflib.CDF(cdf_file)
epoch_values = cdf['Epoch'][...]
datetime_values.extend(cdflib.cdfepoch.encode(epoch_values))
cdf.close()
# Plot the concatenated spectrogram
plot_spectrogram(cdf_files[0], 'FEDU', datetime_values) # Assuming same variable name for all files
```
|
1. Not, only like this
```java
for(int i = start; i < end; i++) {
array[i] = true;
}
```
2. Same like 1.
```java
for(int i = start; i < end; i+=2) {
array[i] = true;
}
```
3. You don't modify the array if u don't assign it.
```java
boolean[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
``` |
We have the following CSP Header in our site:
default-src 'self' https: blob: data: 'unsafe-inline' 'unsafe-eval' script-src: https://ajax.googleapis.com https://analytics.kaltura.com https://api.peer5.com https://bat.bing.com https://cdnapisec.kaltura.com https://cookie-cdn.cookiepro.com https://maps.googleapis.com https://players.brightcove.net https://s7.addthis.com https://secure.perk0mean.com https://static.cloud.coveo.com https://tag.demandbase.com https://www.google.com https://www.googleadservices.com https://www.googletagmanager.com https://www.gstatic.com object-src: https://fonts.gstatic.com connect-src: *.google-analytics.com *.analytics.google.com img-src: *.google-analytics.com *.analytics.google.com;
Due to a security problem, we are trying to remove policy values like **unsafe-inline** and **unsafe-eval** from our CSP header.
In our project structure, we have a lot of external scripts, inline scripts and inline styles. In a few places, we are not able to avoid inline styles and scripts.
Inline style example:
```html
<div class="some-class" style= "background-color: red;">
</div>
```
We are using formats like this in more places. How do we remove the **unsafe-inline** and **unsafe-eval** without heavy code changes? It means I am asking for any other alternatives for CSP policies or any other alternative solutions. |
In website due to CSP configuration inline style and script as well as external scripts are not loading |
null |
I would like to configure my github action to run based on one of two conditions:
- A source file has changed
- A configuration file has changed
Conditions should be evaluated on `OR`.
To solve the first issue I configured the action by using the paths parameter
```
on:
push:
branches:
- main
paths:
- 'src/**'
```
This works and run the action on every push if at least one file in the `src` folder and its subfolders has changed. I have then added the following (inspired by [this](https://stackoverflow.com/a/76975099/23137927))
```
on:
push:
branches:
- main
paths:
- 'src/**'
- 'myconfigurationfile.json'
```
But it does not work as expected. |
Run github action when a configuration file has changed OR source code has changed |
|github|github-actions| |
null |
Thank you @Bitmask and others.
I have come up with an alternative approach.
I have a non-template base class and for it I declare a virtual function for all types I will use. I define empty functions for all these types, since I don't use them. I instead use a derived class, which has a base class pointer to the next block.
The derived block is templated by its type and its neighbours type. I override the base function for its type.
The downsides are having to explicitly declare the needed types in the base class, and explicitly give an empty implementation. For my purposes this is too bad.
#include <iostream>
#include <typeinfo>
#include<string>
class BaseBlock
{
public:
BaseBlock* next;
virtual void Apply(char sample);
virtual void Apply(int sample);
virtual void Apply(float sample);
virtual void Apply(double sample);
virtual void Apply(short sample);
virtual void Apply(std::string sample);
};
template <typename T, typename U>
class DerivedBlock : public BaseBlock
{
public:
void Apply(T sample);
};
template <typename T, typename U>
void::DerivedBlock<T, U>::Apply(T sample)
{
std::cout << "DerivedBlock::Apply - typeid: " << typeid(sample).name() << " value: " << sample << std::endl << std::endl;
if (next != 0)
{
next->Apply((U)sample);
}
}
template <>
void::DerivedBlock<short, std::string>::Apply(short sample)
{
std::cout << "DerivedBlock::Apply - typeid: " << typeid(sample).name() << " value: " << sample << std::endl << std::endl;
if (next != 0)
{
next->Apply(std::to_string(sample));
}
}
template <>
void::DerivedBlock<std::string, int>::Apply(std::string sample)
{
std::cout << "DerivedBlock::Apply - typeid: " << typeid(sample).name() << " value: " << sample << std::endl << std::endl;
if (next != 0)
{
next->Apply(std::stoi(sample));
}
}
int main()
{
DerivedBlock<int, float> db_int_float;
DerivedBlock<float, char> db_float_char;
DerivedBlock<char, int> db_char_int;
DerivedBlock<int, double> db_int_double;
DerivedBlock<double, short> db_double_short;
DerivedBlock<short, std::string> db_short_stdString;
DerivedBlock<std::string, int> db_stdString_int;
db_int_float.next = &db_float_char;
db_float_char.next = &db_char_int;
db_char_int.next = &db_int_double;
db_int_double.next = &db_double_short;
db_double_short.next = &db_short_stdString;
db_short_stdString.next = &db_stdString_int;
db_stdString_int.next = 0; // End of list
db_int_float.Apply(83U);
return 0;
}
void BaseBlock::Apply(char sample) {};
void BaseBlock::Apply(int sample) {};
void BaseBlock::Apply(float sample) {};
void BaseBlock::Apply(double sample) {};
void BaseBlock::Apply(short sample) {};
void BaseBlock::Apply(std::string sample) {};
Produces:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/l2Npb.png |
spectrogram for a .cdf file |
|pandas|python-2.7|matplotlib|netcdf| |
null |
Why is my deployment on Vercel stuck in the queue, and what can I do about it?
[](https://i.stack.imgur.com/EWJid.png)
Your deployment may be stuck in the queue due to a delay in build processing for Hobby users, as Vercel is investigating an issue affecting build queue processing times. This doesn't affect existing deployments or live traffic. While this is being resolved, you can:
[](https://i.stack.imgur.com/TvrIP.png)
Wait for a resolution: Vercel will update their status page as they investigate and resolve the issue.
Subscribe for Updates: Use the 'Subscribe To Updates' feature on Vercel's status page to receive notifications.
Upgrade Your Plan: If your work is time-sensitive, consider upgrading from the Hobby plan to a paid plan for prioritized build processing.
Check for Workarounds: Sometimes, the community may suggest temporary workarounds on forums or in discussion groups.
Contact Support: Reach out to Vercel support for more personalized assistance or to report your specific issue.
|
Vercel Deployment Stuck on queue |
|next.js|queue|vercel| |
null |
run_multiple <- function (parameter_name, parameter_values) {
parameter_name <- as.character(substitute(parameter_name))
for (value in parameter_values) {
arg <- setNames(list(value), parameter_name)
do.call(run_function, arg)
}
}
run_function <- function (x = "a", y = "a", z = "a") {
print(sprintf("X is %s, Y is %s, Z is %s", x, y, z))
}
run_multiple("x", c("a", "b"))
#[1] "X is a, Y is a, Z is a"
#[1] "X is b, Y is a, Z is a"
run_multiple(x, c("a", "b"))
# [1] X is a, Y is a, Z is a
# [1] X is b, Y is a, Z is a
This can be extended to multiple parameter names. Of course that would be easier without non-standard evaluation because then you could just use a vector of parameter names and a list or matrix of corresponding value vectors as input. |
|amazon-web-services|terraform|terraform-provider-aws|aws-security-group| |
1. Sure you did not update accidentaly to 4.27.**3** or later? I got exactly your problem, after I installed the 4.28.0 Version - see below...
2. You need Hyper-V enabled for this: is it working correctly on your machine? If you are using Windows Home Edition there is no chance: upgrade your Windows to Professional Edition - see maybe [tag:docker-for-windows]?
From my view, at this time the Docker Desktop Version 4.28.0 seems to have a problem with at least Windows 10, because after I deinstalled the 4.28.0 and replaced it with a fresh install of the Docker Desktop Version 4.27.2 (see [Docker Desktop release notes][2]) everything works fine for me with VS 2022 and ASP.NET 8.
... don't Update DD until this is fixed! ;)
In [GitHub, docker/for-win: ERROR: request returned Internal Server Error for API route and version...][1] there is a hint upgrading the WSL2 which might help too.
[1]: https://github.com/docker/for-win/issues/13909
[2]: https://docs.docker.com/desktop/release-notes/#4272 |
I am following the book "Learn Python The Hard Way" and in ex 46 we make a skeleton structure for projects and install Pytest to test the project code. All cool and dandy until I try to run the test for my package. The test marks as successful but nothing from my module code shows up, only when I test individually the module with a "test_Dandy2.py" file that the code run.
This is how my directory is organized (based on the book exercise):
project_1\
bin\
docs\
project1\
__init__.py
Dandy2.py
tests\
__init__.py
test_project1.py
test_Dandy2.py
setup.py
I tried to write import Dandy2 on my __init__ file in my package directory and then I got an ImportError. I looked up all over stack overflow and most answers talk about my project file being out of the python PATH. However my test marks as successful and when running the a test for the module individually it runs the code normally.
I don't know if this is how it should work, as the book gives no explanation whatsoever and the LPTHW forum is very dead. Maybe it is because I am using a windows os, and running the pytest in Powershell and have something to twist in order to make it work (like I had to do to run scripts, where I needed to change the execution policy of my system). |
Pytest does not run the code from my package module |
|python|python-3.x|pytest| |
null |
|powershell|azure-devops| |
I have a view with two fields: one for the email and another for the phone number. I need to validate them by updating a button on the view.
There is the code:
```
@HiltViewModel
class CreateAccountEnterEmailViewModel @Inject constructor(
appData: AppData,
) : ViewModel() {
private var email by mutableStateOf("")
private var phoneNumber by mutableStateOf("")
private var _isPhoneNumberFieldVisibleState: MutableStateFlow<Boolean> = MutableStateFlow(appData.isPhoneNumberRequiredForRegistrationParam.orDef())
val isPhoneNumberFieldVisible: LiveData<Boolean> = _isPhoneNumberFieldVisibleState.asLiveData()
class PairMediatorLiveData<F, S>(firstLiveData: LiveData<F>, secondLiveData: LiveData<S>) : MediatorLiveData<Pair<F?, S?>>() {
init {
addSource(firstLiveData) { firstLiveDataValue: F -> value = firstLiveDataValue to secondLiveData.value }
addSource(secondLiveData) { secondLiveDataValue: S -> value = firstLiveData.value to secondLiveDataValue }
}
}
private val isEmailValid: LiveData<Boolean> =
snapshotFlow { email }
.map { validateEmail(email = it) }
.asLiveData()
private val isPhoneValid: LiveData<Boolean> =
snapshotFlow { phoneNumber }
.map { validatePhone(phone = it) }
.asLiveData()
val isContinueBtnEnabled: LiveData<Boolean> = PairMediatorLiveData(isEmailValid, isPhoneValid)
.switchMap {
return@switchMap liveData {
emit(it.first ?: false && it.second ?: false)
}
}
fun updateEmail(email: String) {
this.email = email
}
fun updatePhoneNumber(phoneNumber: String) {
this.phoneNumber = phoneNumber
}
```
The idea is that when the user updates their email or phone number, this update is intercepted by a mediator that provides the appropriate state depending on whether validation has passed or not.
However, for some reason, I see that nothing goes beyond calling the `updateEmail` or `updatePhoneNumber` method. What am I doing wrong?
P.S. There is, of course, a subscription in the view to `isContinueBtnEnabled`.
|
**The goal**
I want to run dominance analysis on a Dirichlet regression, to approximate the relative importance of a set of predictors (scaled continuous predictors, continuous predictors with splines, and factors). Dirichlet regression is an extension of beta regression to model proportions that are not derived from counts, and that are split between more than 2 categories, see Douma&weedon (2019).
**The modelling approach: the syntax is potentially important**
I am using the `DirichletReg` package to fit a Dirichlet regression, with an `"alternative"` parametrization: this allows to estimate simultaneously the parameters and the precision of the estimation. The syntax is: `response ~ parameters | precision`. The estimation of parameters can be done with different predictors from those used to estimate precision: `response ~ predictor1 + predictor2 | predictor3`. If left undeclared, the model assumes fixed precision: `response ~ predictors`, which can be declared explicilty as: `response ~ predictors | 1`.
**I think that the error is related to the vertical bar in the formula, which separates the predictors used to estimate parameters from the predictors used to estimate precision.**
I rely on `performance::r2()` to calculate a metric of model quality: Nagelkerke's pseudo-R2. However, for the actual analysis, I am thinking of either McFadden or Estrella's pseudo-R2, as they appear suitable to run dominance analysis on multinomial responses, see Luchman 2014.
**The obstacle**
I get the error message: `"fitstat requires at least two elements".`
**A reproducible example**
From data available in the `DirichletReg` package. The response is only two categories, but in any case, it yields the same error message as in the actual analysis.
``` r
library(DirichletReg)
#> Warning: package 'DirichletReg' was built under R version 4.1.3
#> Loading required package: Formula
#> Warning: package 'Formula' was built under R version 4.1.1
library(domir)
library(performance)
#> Warning: package 'performance' was built under R version 4.1.3
# Assemble data
RS <- ReadingSkills
RS$acc <- DR_data(RS$accuracy)
#> only one variable in [0, 1] supplied - beta-distribution assumed.
#> check this assumption.
RS$dyslexia <- C(RS$dyslexia, treatment)
# Fit Dirichlet regression
rs2 <- DirichReg(acc ~ dyslexia + iq | dyslexia + iq, data = RS, model = "alternative")
summary(rs2)
#> Call:
#> DirichReg(formula = acc ~ dyslexia + iq | dyslexia + iq, data = RS, model =
#> "alternative")
#>
#> Standardized Residuals:
#> Min 1Q Median 3Q Max
#> 1 - accuracy -1.5279 -0.7798 -0.343 0.6992 2.4213
#> accuracy -2.4213 -0.6992 0.343 0.7798 1.5279
#>
#> MEAN MODELS:
#> ------------------------------------------------------------------
#> Coefficients for variable no. 1: 1 - accuracy
#> - variable omitted (reference category) -
#> ------------------------------------------------------------------
#> Coefficients for variable no. 2: accuracy
#> Estimate Std. Error z value Pr(>|z|)
#> (Intercept) 2.22386 0.28087 7.918 2.42e-15 ***
#> dyslexiayes -1.81261 0.29696 -6.104 1.04e-09 ***
#> iq -0.02676 0.06900 -0.388 0.698
#> ------------------------------------------------------------------
#>
#> PRECISION MODEL:
#> ------------------------------------------------------------------
#> Estimate Std. Error z value Pr(>|z|)
#> (Intercept) 1.71017 0.32697 5.230 1.69e-07 ***
#> dyslexiayes 2.47521 0.55055 4.496 6.93e-06 ***
#> iq 0.04097 0.27537 0.149 0.882
#> ------------------------------------------------------------------
#> Significance codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> Log-likelihood: 61.26 on 6 df (33 BFGS + 1 NR Iterations)
#> AIC: -110.5, BIC: -99.81
#> Number of Observations: 44
#> Links: Logit (Means) and Log (Precision)
#> Parametrization: alternative
as.numeric(performance::r2(rs2))
#> [1] 0.4590758
# Run dominance analysis: error
# If left undeclared, the model assumes fixed precision: parameters | 1
domir::domin(acc ~ dyslexia + iq,
reg = function(y) DirichletReg::DirichReg(y, data = RS, model = "alternative"),
fitstat = list(\(x) list(r2.nagelkerke = as.numeric(performance::r2(x)), "r2.nagelkerke"))
)
#> Error in domir::domin(acc ~ dyslexia + iq, reg = function(y) DirichletReg::DirichReg(y, : fitstat requires at least two elements.
domir::domin(acc ~ dyslexia + iq | 1,
reg = function(y) DirichletReg::DirichReg(y, data = RS, model = "alternative"),
fitstat = list(\(x) list(r2.nagelkerke = as.numeric(performance::r2(x)), "r2.nagelkerke"))
)
#> Error in domir::domin(acc ~ dyslexia + iq | 1, reg = function(y) DirichletReg::DirichReg(y, : fitstat requires at least two elements.
domir::domin(acc ~ dyslexia + iq | dyslexia + iq,
reg = function(y) DirichletReg::DirichReg(y, data = RS, model = "alternative"),
fitstat = list(\(x) list(r2.nagelkerke = as.numeric(performance::r2(x)), "r2.nagelkerke"))
)
#> Error in domir::domin(acc ~ dyslexia + iq | dyslexia + iq, reg = function(y) DirichletReg::DirichReg(y, : fitstat requires at least two elements.
domir::domin(acc ~ dyslexia + iq,
reg = function(y) DirichletReg::DirichReg(y, data = RS, model = "alternative"),
fitstat = list(\(x) list(r2.nagelkerke = as.numeric(performance::r2(x)), "r2.nagelkerke")),
consmodel = "| dyslexia + iq"
)
#> Error in domir::domin(acc ~ dyslexia + iq, reg = function(y) DirichletReg::DirichReg(y, : fitstat requires at least two elements.
sessionInfo()
#> R version 4.1.0 (2021-05-18)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 19045)
#>
#> Matrix products: default
#>
#> locale:
#> [1] LC_COLLATE=Spanish_Spain.1252 LC_CTYPE=Spanish_Spain.1252
#> [3] LC_MONETARY=Spanish_Spain.1252 LC_NUMERIC=C
#> [5] LC_TIME=Spanish_Spain.1252
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] performance_0.10.0 domir_1.0.1 DirichletReg_0.7-1 Formula_1.2-4
#>
#> loaded via a namespace (and not attached):
#> [1] rstudioapi_0.13 knitr_1.38 magrittr_2.0.3 insight_0.19.1
#> [5] lattice_0.20-44 rlang_1.1.0 fastmap_1.1.0 stringr_1.5.0
#> [9] highr_0.9 tools_4.1.0 grid_4.1.0 xfun_0.30
#> [13] cli_3.6.0 withr_2.5.0 htmltools_0.5.2 maxLik_1.5-2
#> [17] miscTools_0.6-28 yaml_2.3.5 digest_0.6.29 lifecycle_1.0.3
#> [21] vctrs_0.6.1 fs_1.5.2 glue_1.6.2 evaluate_0.15
#> [25] rmarkdown_2.13 sandwich_3.0-1 reprex_2.0.1 stringi_1.7.6
#> [29] compiler_4.1.0 generics_0.1.2 zoo_1.8-9
```
<sup>Created on 2023-07-27 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)</sup>
**References**
[Luchman Relative Importance Analysis With Multicategory Dependent Variables:: An Extension and Review of Best Practices (2014) Organizational research methods](https://doi.org/10.1177/1094428114544509)
[Douma & Weedon. Analysing continuous proportions in ecology and evolution: A practical introduction to beta and Dirichlet regression (2019) Methods in Ecology and Evolution](https://doi.org/10.1111/2041-210X.13234)
**EDIT (31 July 2023)**
Many thanks to Joseph Luchman for the solution! I have modified the function to avoid the use of pipes, and I have added the formula for precision inside the `paste0()` call. Unfortunately, `reprex::reprex()` won't render the result, so I paste an screenshot below.
domir::domir(acc ~ dyslexia + iq, function(y) {
iv <- attr(terms(y), "term.labels")
fml <- paste0("acc ~ ", paste0(iv, collapse = "+"), "| dyslexia + iq", collapse = "")
print(fml)
performance::r2( DirichReg(as.formula(fml), data = RS, model = "alternative") )[[1]]})
[![screenshot result dirichlet dominance analysis][1]][1]
[1]: https://i.stack.imgur.com/chnJz.jpg
**EDIT (26 February 2024)**
The solution no longer works, which is puzzling, see discussion over at GitHub: https://github.com/jluchman/domir/discussions/8. I've contacted the author of the DirichletReg package. |
I have a problem. I want to integrate my oauth server to Apache Superset. My Superset configs
```
CUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager
```
```
OAUTH_PROVIDERS = [
{
"name": "orion",
"icon": "fa-google",
"token_key": "access_token",
"remote_app": {
"client_id": "*****",
"client_secret": "***************************",
"client_kwargs": {"scope": "*"},
"access_token_url": "https://oauth.my.ru/oauth/token",
"access_token_method": "POST",
"authorize_url": "https://oauth.my.ru/oauth/authorize",
"authorize_method": "POST",
},
},
]
```
```
class CustomSsoSecurityManager(SupersetSecurityManager):
def oauth_user_info(self, provider, response=None):
logger.warning("Oauth2 provider: {0}.".format(provider))
logger.error("Oauth2 provider: {0}.".format(provider))
if provider == 'orion':
# As example, this line request a GET to base_url + '/' + userDetails with Bearer Authentication,
# and expects that authorization server checks the token, and response with user details
me = self.appbuilder.sm.oauth_remotes[provider].get('userinfo').data
logger.warning("user_data: {0}".format(me))
logger.warning(f"AaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaa{me}")
logger.warning(f"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb{provider}")
return { 'name' : me['name'], 'email' : me['email'], 'id' : me['user_name'], 'username' : me['user_name'], 'first_name':'', 'last_name':''}
else:
logger.warning(f"Это не Орион {provider}, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
logger.error(
f"Это не Орион {provider}, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
```
My oauth api
```
@flask_cors.cross_origin()
@app.route('/oauth/token', methods=['POST'])
def access_token() -> Response:
"""
@api {post} /oauth/token
@apiHeaderExample {json} Header-Example:
{
"content-type": "application/x-www-form-urlencoded"
}
@apiSuccessExample
{
'scope': '*',
'expires_in': ...,
'expires_at': ...,
'token_type': 'Bearer',
'access_token': '...',
'refresh_token': '...'
}
"""
return authorization.create_token_response()
```
My oauth server response
```
{
'scope': '*',
'expires_in': ...,
'expires_at': ...,
'token_type': 'Bearer',
'access_token': '...',
'refresh_token': '...'
}
```
And I have this problem **2024-02-26 14:22:14,163:ERROR:flask_appbuilder.security.views:Error authorizing OAuth access token: invalid literal for int() with base 10: '2024-02-26 15:22:13'**
I think, that flask cannot parse my response |
Apache Superset. ERROR:flask_appbuilder.security.views:Error authorizing OAuth access token: invalid literal for int() with base 10 |
|python|flask|oauth-2.0|apache-superset| |
Problem with changing font of text in javascript |
|javascript|html|text|output|svelte| |
null |
I got my hit layout in a grid when using import "instantsearch.css/themes/algolia-min.css";
I am currently trying to reuse that theme and customize it to overwrite some styles, but I haven't achieved that yet.
this is the documentation page that has led me thus far
https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react/#style-your-widgets
|
Your `php.ini` error reporting settings might be set not to report errors. If that is the case, you can see the errors by doing this in your code, before where you think it is crashing like.
error_reporting(E_ALL);
ini_set('display_errors', 1);
This should show you the errors you need to see.
|
[MacVim](https://macvim.org/) is a macOS application with a file open dialog that calls [NSOpenPanel](https://developer.apple.com/documentation/appkit/nsopenpanel) with a simple view to show hidden files (see [MMAppController.m's fileOpen method](https://github.com/macvim-dev/macvim/blob/master/src/MacVim/MMAppController.m) and [Miscellaneous.m's showHiddenFilesView method](https://github.com/macvim-dev/macvim/blob/master/src/MacVim/Miscellaneous.m)).
When I open files with MacVim, I can use ⌘A to select all files. But I don't see what it's doing that's any different than what I do below, which does *not* allow me to use ⌘A to select all files.
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setCanChooseFiles:YES];
[panel setCanChooseDirectories:YES];
[panel setAllowsMultipleSelection:YES];
if ([panel runModal] == NSModalResponseOK) {
for ( NSURL* URL in [panel URLs] ) {
NSLog( @"%@", [URL path] );
}
} else {
NSLog( @"ok button not pressed");
}
The docs for `NSOpenPanel` and [NSSavePanel](https://developer.apple.com/documentation/appkit/nssavepanel), which `NSOpenPanel` inherits don't make any mention of key bindings or other booleans that I might set. The only thing that I saw that might be useful is a custom view but MacVim doesn't appear to be doing anything with `NSView` that relates.
Below is the entire MCV example and how it's compiled. I suspect there's something wrong with the example since I have to click the graphics rectangle first before I can get the open panel to behave. But I don't think that's having an effect on the key bindings.
#import <Cocoa/Cocoa.h>
void openDialog () {
@try {
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setCanChooseFiles:YES];
[panel setCanChooseDirectories:YES];
[panel setAllowsMultipleSelection:YES];
if ([panel runModal] == NSModalResponseOK) {
for ( NSURL* URL in [panel URLs] ) {
NSLog( @"%@", [URL path] );
}
} else {
NSLog( @"ok button not pressed");
}
} @catch (NSException *exception) {
NSLog(@"%@", [exception callStackSymbols]);
}
}
void setup () {
NSWindow *myWindow;
NSRect graphicsRect = NSMakeRect(100.0, 350.0, 400.0, 400.0);
myWindow = [ [NSWindow alloc]
initWithContentRect: graphicsRect
styleMask:NSWindowStyleMaskTitled
|NSWindowStyleMaskClosable
|NSWindowStyleMaskMiniaturizable
backing:NSBackingStoreBuffered
defer:NO ];
[myWindow setTitle:@"Open File App"];
[myWindow makeKeyAndOrderFront: nil];
openDialog();
}
int main ( ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSApp = [NSApplication sharedApplication];
setup();
[NSApp run];
[NSApp release];
[pool release];
return(EXIT_SUCCESS);
}
gcc -o $@ $(INC) -framework Cocoa -F $(JAVA_HOME)/../.. -isysroot $(SDK) -fobjc-exceptions -std=c99 ofdtest.m |
What is a possible issue with LiveData that doesn't return a value? |
null |
Instead of `pyreadstat` you can use `pyspssio`.
If it's the first time you're using this library, you may need to install it:
pip install pyspssio
To read the data in, you can use similar syntax to pyreadstat:
import pyspssio
df, meta = pyspssio.read_sav("C:/my_doc.sav")
To export with the metadata, use the metadata=... argument:
pyspssio.write_sav("C:/my_doc v2.sav",df,metadata=meta)
You can find more details here:
[https://pyspssio.readthedocs.io/en/stable/readme.html][1]
[1]: https://pyspssio.readthedocs.io/en/stable/readme.html |
|github|azure-devops| |
Check the network waterfall:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/pE8ln.png
I guess your api calls just get throttled on the backend side. Your request are queued on the backend side too.
If you replace the api calls with timeouts, `Promise.all` works just fine:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const getSomeData = () => {
try {
return new Promise(r => setTimeout(r, 1000))
} catch (error) {
console.log('Failed to get data...');
}
};
const promiseList = [];
const log = [];
for (let i = 0; i < 100; i += 1) {
promiseList.push(new Promise(async (res) => {
const startTime = performance.now();
await getSomeData();
const stopTime = performance.now();
log.push(`time taken by promise: ${stopTime - startTime}`);
res();
}));
}
const main = async () => {
const startTime = performance.now();
await Promise.all(promiseList);
const stopTime = performance.now();
log.forEach(l => console.log(l));
console.log(`total time taken: ${stopTime - startTime}`);
};
main();
<!-- end snippet -->
|
I created an MVC application with EF Core.
Several problems appeared one after the other. I eventually could create a controller on the orders table of Northwind database. It went with views automatically.
When launching the application, this opened the HomeController, that is provided by default.
As I want to open the OrdersController, in the address bar, after
> https://localhost:7290/
I add ``order``
But I get a transient error, whereas the content has this property :
> ` .UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=EFMiscellanous.ConnectionResiliency;Trusted_Connection=True",
options => options.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: System.TimeSpan.FromSeconds(30),
errorNumbersToAdd: null)
);`
I first tried with nothing in the parenthesis for EnableRetryOnFailure, and then tried something I saw in the forums. Well the example was on MySql, as I use Sql Express, perhaps good to know.
The database is on an instance of SQL Express rather than on localdb, but I am not sure this is the point.
I remember that the two controllers can target two ports, how do I verify that?
And supposing it is not the point either, what must I do?
|
I've been trying to achieve the result in the table above with no luck so far .. I have table called Nodes consists of ( base doc, current done and target ).
BaseDocType . BaseDocID
DocType . DocID
TargetDocType . TargetDocID ..
I want to fetch all the related nodes for any specific node if that's possible ..if any one can help I will be appreciate it a lot ..
it's a sql server database .
`
With CTE1 (ID, BaseDocType, BaseDocID, DocType, DocID, TargetDocType, TargetDocID)
As
(
Select ID, BaseDocType, BaseDocID, DocType, DocID, TargetDocType, TargetDocID
From Doc.Nodes Where DocType=8 and DocID = 2
Union All
Select a.ID, a.BaseDocType, a.BaseDocID, a.DocType, a.DocID, a.TargetDocType, a.TargetDocID
From Doc.Nodes a
Inner Join CTE1 b ON
(a.BaseDocType = a.BaseDocType and a.BaseDocID = b.BaseDocID and a.DocType != b.DocType and a.DocID != b.DocID)
)
Select *
From CTE1`
this query is not working .. |
Sql Server recursive query issue |
|sql|database| |
null |
Even though the input to embedding layer is type `torch.int64` I am still getting the error `expected argument of scalar type long or int, but got torch.FloatTensor`.
for epoch in range(inital_epoch, config[‘number_epochs’]):
model.train()
batch_iterator = tqdm(train_dataloader, desc = f’Processing epoch {epoch:02d}')
for batch in batch_iterator:
encoder_input = batch[‘encoder_input’].to(device) # (batch_size, context_len)
decoder_input = batch[‘decoder_input’].to(device) # (batch_size, context_len)
encoder_mask = batch[‘encoder_mask’].to(device) # (batch_size, 1, context_len)
decoder_mask = batch[‘decoder_mask’].to(device) # (batch_size, context_len, context_len)
print(f"encoder_input dtype: {encoder_input.dtype}")
print(f"encoder_input shape: {encoder_input.shape}")
encoder_output = model.encoder(encoder_input, encoder_mask)
In above code, I have added print statement to inspect the dtype and shape of the encoder_input.
When I execute the file I’m getting below error:
Using device cpu
Processing epoch 00: 0%| | 0/12771 [00:00<?, ?it/s]
encoder_input dtype: torch.int64
encoder_input shape: torch.Size([8, 440])
Processing epoch 00: 0%| | 0/12771 [00:00<?, ?it/s]
Traceback (most recent call last):
File "E:\Fahad\College\BE\Project\MT using Transformers\train.py", line 137, in <module>
train_model(config)
File "E:\Fahad\College\BE\Project\MT using Transformers\train.py", line 107, in train_model
encoder_output = model.encoder(encoder_input, encoder_mask) # (batch_size, context_len, embedding_size)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Fahad\College\BE\Project\MT using Transformers\model.py", line 246, in encoder
return self.encoder(src, src_mask)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Fahad\College\BE\Project\MT using Transformers\model.py", line 240, in encoder
src = self.input_embedding(src)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\fahad\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\fahad\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Fahad\College\BE\Project\MT using Transformers\model.py", line 18, in forward
return self.embedding(x) * math.sqrt(self.embedding_dim)
^^^^^^^^^^^^^^^^^
File "C:\Users\fahad\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\fahad\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\fahad\AppData\Roaming\Python\Python311\site-packages\torch\nn\modules\sparse.py", line 163, in forward
return F.embedding(
^^^^^^^^^^^^
File "C:\Users\fahad\AppData\Roaming\Python\Python311\site-packages\torch\nn\functional.py", line 2237, in embedding
return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Expected tensor for argument #1 'indices' to have one of the following scalar types: Long, Int; but got torch.FloatTensor instead (while checking arguments for embedding)
|
Same as @Nico Zhu but rather than getting actual height from element directly, getting it from sender object.
Compositor _compositor = App.MainWindow.Compositor;
SpringVector3NaturalMotionAnimation _springAnimation;
private void CreateOrUpdateSpringAnimation(float finalValue)
{
if (_springAnimation == null)
{
_springAnimation = _compositor.CreateSpringVector3Animation();
_springAnimation.Target = "Scale";
}
_springAnimation.FinalValue = new Vector3(finalValue);
}
private void element_PointerEntered(object sender, PointerRoutedEventArgs e)
{
// Scale up to 1.5
CreateOrUpdateSpringAnimation(1.5f);
var element = sender as FrameworkElement; // Cast sender to FrameworkElement
element.CenterPoint = new Vector3((float)(element.ActualWidth / 2.0), (float)(element.ActualHeight / 2.0), 1f);
element.StartAnimation(_springAnimation);
}
private void element_PointerExited(object sender, PointerRoutedEventArgs e)
{
// Scale back down to 1.0
CreateOrUpdateSpringAnimation(1.0f);
var element = sender as FrameworkElement; // Cast sender to FrameworkElement
element.CenterPoint = new Vector3((float)(element.ActualWidth / 2.0), (float)(element.ActualHeight / 2.0), 1f);
element.StartAnimation(_springAnimation);
} |
my Company wants me to enable Push-Notifications for a Fiori-App from SAP. But I can't find anyone who knows how to do that (even the Basis Team).
As far is I know now from googling it has to do something with workflows, where I don't have any experience. I tried to search the Workflow Items in SWI1, but cant find the right one (there are 1300 to choose from). I activated the Business Workflow in SPRO. In transaction SWF_PUSH_NOTIF1 it shows the green dot. But that's all I got to work right now.
Dows anyone know how I find the right one? Or knows a help article on that or have a summary of Transactions, that you need when working with Workflows? I'm completely lost right now.
If it helps, currently it's this app: [Simulating Modeling and Forecasting][1].
But in the future I need it for others too.
[1]: https://help.sap.com/docs/CARAB/e95c8443f589486bbfec99331049704a/593a912124e1474e904b8b21309acb32.html?locale=en-US |
while doing simple in python print statement found one issue
print("123456".count(""))
print 7
why it print 7 in python .
print("123456".count(""))
7
why it is provide 7 instead of 6 ? |
Python count() with print() |
|python|count| |
null |
The copyright info is rotated correctly, reading up and down along the left edge.
*However*, when I hover over the parent `<div>` instead of rotating 90º degrees, so that ireading left-to-right along the bottom edge, it rotates 180º so that it is facing the opposite way!
The only way to get the text to transition from reading up and down along the left edge, to reading right to left along the bottom is to rotate it 360º, which makes no sense to me.
What on earth have I done?
<script async src="//jsfiddle.net/davidgs/qjow7hzb/23/embed/html,css,result/dark/"></script>
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.parent {
height: 100vh;
}
.copy-txt {
color: rgba(255, 255, 255, 0.5);
font-size: 10px;
text-align: center;
}
.copy-txt > a {
color: rgba(255, 255, 255, 0.5);
font-size: 10px;
}
.copyright {
position: absolute;
rotate: -90deg;
transition: rotate 0.3s ease-in-out;
margin-left: 45px;
background-color: rgb(10, 28, 46);
width: 150px;
height: 60px;
padding-top: 0px;
top: 40%;
color: rgba(255, 255, 255, .5);
text-align: center;
}
.parent:hover .copyright {
display: block;
rotate: 360deg;
transition: rotate 0.3s ease-in-out;
}
<!-- language: lang-html -->
<div class="parent">
<div class="copyright">
<p>
<span class="copy-txt">
© <a href="https://davidgs.com/">David G. Simmons 2023
</a>
</span>
<br />
<span class="copy-txt">All rights reserved</span>
</p>
</div>
</div>
<!-- end snippet -->
|
|html|css| |
I'm struggling with my custom registration fields for WooCommerce.
I need 2 registration fields.
1. B2B
2. B2C
So I was thinking to create two registration pages, one for B2B and one for B2C.
I created the pages, added the code and registered the new fields in the database. This works all fine, but not for 1 field. It's a dropdown field for choosing the country.
The code below is a normal input. This field is registered in the database at registration and de value is added to the WooCommerce account page from the registered user.
```html
<div class="col-md-12">
<label for="reg_billing_city"><?php _e( 'City', 'woocommerce' ); ?><span class="required">*</span></label>
<input type="text" class="input-text" name="billing_city" id="reg_billing_city" value="<?php if ( ! empty( $_POST['billing_city'] ) ) esc_attr_e( $_POST['billing_city'] ); ?>" />
</div>
```
I also need the country of the registered user at the account page. I'm using the code below:
```html
<div class="col-md-12">
<label for="reg_billing_country"><?php _e( 'Country', 'woocommerce' ); ?><span class="required">*</span></label>
<select class="input-text" name="billing_country" id="reg_billing_country" value="<?php if ( ! empty( $_POST['billing_country'] ) ) esc_attr_e( $_POST['billing_country'] ); ?>">
<option value="Nederland">Nederland</option>
<option value="Belgie">Belgie</option>
<option value="Duitsland">Duitsland</option>
<option value="Frankrijk">Frankrijk</option>
</select>
</div>
```
But the value from billing_country is not added to the customs account page.
```html
if ( isset( $_POST['billing_country'] ) ) {
update_user_meta( $customer_id, 'billing_country', sanitize_text_field( $_POST['billing_country'] ) );
}
```
So how to get the value of the dropdown updated to the user meta ?
|
MVC : Selecting the controller |
|entity-framework|model-view-controller|port| |
Since **Laravel 10** there is a method in scheduler that allows to run commands every second:
```php
$schedule->call(function () {
// Do your stuff
})->everySecond();
```
You can read more in Laravel documentation: [Sub-Minute Scheduled Tasks][1]
[1]: https://laravel.com/docs/10.x/scheduling#sub-minute-scheduled-tasks |
This script deletes all Kubernetes resources blocking the deletion of a specified namespace.
It first removes the finalizers of each resource, then deletes the resource itself.
Finally, it deletes the specified namespace.
#!/bin/bash
#
# This script deletes all Kubernetes resources blocking the deletion of a specified namespace.
# It first removes the finalizers of each resource, then deletes the resource itself.
# Finally, it deletes the specified namespace.
#
# Usage: ./delete_namespace_resources.sh [OPTIONS]
# Options:
# -n, --namespace <terminating-namespace> Namespace to be deleted
# -h, --help Display this help and exit
#
set -euo pipefail
# log messages
log() {
local message=$1
echo "[INFO] $message"
}
delete_finalizers() {
local resource_name=$1
local namespace=$2
# Get the resource with finalizers removed
log "Deleting finalizers of $resource_name"
kubectl patch "$resource_name" -n "$namespace" --type='json' -p='[{"op": "remove", "path": "/metadata/finalizers"}]'
}
delete_resource() {
local resource_name=$1
local namespace=$2
# Delete the resource
log "Deleting resource: $resource_name in namespace: $namespace"
kubectl delete "$resource_name" -n "$namespace" --ignore-not-found
}
delete_blocking_resources() {
local terminating_namespace=$1
# Get all Kubernetes resources in the namespace
resources=$(kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n "$terminating_namespace" | tail -n +2)
# Loop through each resource
while read -r resource; do
local resource_name=$(echo "$resource" | awk '{print $1}')
# Delete finalizers of the resource
delete_finalizers "$resource_name" "$terminating_namespace"
# Delete the resource itself
delete_resource "$resource_name" "$terminating_namespace"
done <<< "$resources"
}
display_help() {
cat <<EOF
Usage: $0 [OPTIONS]
Options:
-n, --namespace <terminating-namespace> Namespace to be deleted
-h, --help Display this help and exit
EOF
}
# Parse command line options
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-n|--namespace)
TERMINATING_NAMESPACE="$2"
shift
shift
;;
-h|--help)
display_help
exit 0
;;
*)
echo "Unknown option: $1" >&2
display_help
exit 1
;;
esac
done
# Check if terminating namespace is provided
if [ -z "${TERMINATING_NAMESPACE:-}" ]; then
echo "Error: Terminating namespace not provided." >&2
display_help
exit 1
fi
# Delete resources blocking namespace deletion
delete_blocking_resources "$TERMINATING_NAMESPACE"
# Delete the namespace
log "Deleting namespace $TERMINATING_NAMESPACE"
kubectl delete namespace "$TERMINATING_NAMESPACE"
log "Namespace $TERMINATING_NAMESPACE successfully deleted"
|
I have swiper which works perfectly with existing elements. But when i scroll down my script creates dyncamically elements and my swiper are not work because at beggining it doesnt add event listiner.
```
var swiperContainer = document.querySelectorAll('.swiper1')
swiperContainer.forEach(function (elem) {
var swiper = new Swiper(elem, {
spaceBetween: 30,
pagination: {
el: elem.parentElement.querySelector('.swiper-pagination1'),
clickable: true,
dynamicBullets: true,
},
navigation: {
nextEl: elem.parentElement.querySelector('.swiper-button-next1'),
prevEl: elem.parentElement.querySelector('.swiper-button-prev1'),
},
});
})
```
I tried this using jquery still didnt work. I know it works if i remove this event listener and add again after loaded more elements. Is there any way to to do it better ? |
I've been trying to convert a Markdown file into HTML code with python for a few days - without success.
The markdown file contains inline code and code blocks.
However, I can't find a solution to display the code blocks in HTML like stackoverlflow or GitHub does. In other words, a rectangle containing the code.
The Markdown file looks like this:
```markdown
### Output of `df`
'''Bash
Filesystem 1K-blocks Used Available Use% Mounted on
tmpfs 809224 1552 807672 1% /run
/dev/sda3 61091660 37443692 20512276 65% /
tmpfs 4046120 54604 3991516 2% /dev/shm
'''
```
The corresponding part of my HTML version looks like this:
```html
<h3>Output of <code>df</code></h3>
<div class="codehilite">
<pre><span></span><code>
Filesystem<span class="w"> </span>1K-blocks<span class="w"> </span>Used<span class="w"> </span>Available<span class="w"> </span>Use%<span class="w"> </span>Mounted<span class="w"> </span>on
tmpfs<span class="w"> </span><span class="m">809224</span><span class="w"> </span><span class="m">1552</span><span class="w"> </span><span class="m">807672</span><span class="w"> </span><span class="m">1</span>%<span class="w"> </span>/run
/dev/sda3<span class="w"> </span><span class="m">61091660</span><span class="w"> </span><span class="m">37443692</span><span class="w"> </span><span class="m">20512276</span><span class="w"> </span><span class="m">65</span>%<span class="w"> </span>/
tmpfs<span class="w"> </span><span class="m">4046120</span><span class="w"> </span><span class="m">54604</span><span class="w"> </span><span class="m">3991516</span><span class="w"> </span><span class="m">2</span>%<span class="w"> </span>/dev/shm
</code></pre>
</div>
```
I use the following code to convert.
```python
converted = markdown2.markdown(lfmd, extras=['fenced-code-blocks'])
```
If I now open the HTML version in the browser, I have the code in a different font, but that's it. But I need these nice code blocks.
[What it looks like](https://i.stack.imgur.com/u4b4T.png)
[What it should look like](https://i.stack.imgur.com/ZLbl9.png)
Another problem is that this HTML code is then sent as an HTML e-mail. That's why playing around with Javascript etc. doesn't work.
I have tried to change the text background with CSS. This works quite well for inline code.
However, code blocks then look bad because they are aligned on the left and then fray on the right.
[What my crappy CSS looks like](https://i.stack.imgur.com/jvSQl.png)
This is my HTML/CSS code, as I have no control over the HTML body:
```html
<head>
<style>
body {font-family: TeleNeo Office, sans-serif; color: #000000;}
body {background-color: #ffffff;}
code {
font-family: Source Sans Pro, monospace;
font-weight: normal;
font-size: small;
color: black;
background-color: #E3E6E8;
border-radius: 5px;
height: fit-content;
width: auto;
padding: 3px 10px 3px 10px;
}
</style>
</head>
```
Can anyone give me a tip on how I could implement this instead? |
I have a button that renders correctly on windows, and mobile simulations. However, on my iPhone, the button color, and position attributes are incorrect, Any and all help is greatly appreciated!
html:
<button class="more-projects-button" type="button" onclick="window.location.href='Projects.html';">More Projects</button>
css:
.more-projects-button {
position: relative;
top: 40px;
left: 50%;
transform: translateX(-50%);
background-color: #007bff;
color: white;
border: none;
border-radius: 10px;
padding: 10px 20px;
text-decoration: none;
}
Thanks for looking at my code, as I'm new to web development |
ios not rendering button attributes |
|html|css|web| |
Error: Asset validation failed Missing required icon file. The bundle does not contain an app icon for iPad of exactly '152x152' pixels, in .png format for iOS versions >= 10.0
I am trying to open up Images.xcassets and then open appicon to fill in the missing icons.
but when i try to open the project navigator, the following is shown
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/tPQie.png
I have tried the all the other suggestions, but the wrong project navigator and Images.xcassets not showing up is confusing me. |
missing required icon file |
|ios|mobile| |
I'm facing an issue where the navigation bar title of a SwiftUI view does not display correctly on the first render. It only appears correctly after switching to another tab and then coming back. Alongside this issue, I'm receiving the following constraint error in the console:[![enter image description here][1]][1]
> [UIKitCore] Unable to simultaneously satisfy constraints. ... Will
> attempt to recover by breaking constraint
> <NSLayoutConstraint:0x600002206260
> V:[Overview]-(0)-[UIFocusContainerGuide:0x600003def750'UINavigationControllerContentFocusContainerGuide']
> (active, names: Overview:0x112d9aee0 )> ...
struct ContentView: View {
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 20) {
ForEach(0..<10) { index in
VStack {
Text("Section \(index)").font(.headline).padding()
ForEach(0..<5) { itemIndex in
Text("Item \(itemIndex)").padding()
}
}
.frame(maxWidth: .infinity)
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
.padding(.horizontal)
}
}
}.navigationTitle("Overview").navigationBarTitleDisplayMode(.automatic)
}
}
}
class ExpoContentView: ExpoView {
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
self.backgroundColor = .white
// Init the view controller
let contentView = ContentView()
let hostingController = UIHostingController(rootView: contentView)
setupHostingController(hostingController)
func setupHostingController(_ hostingController: UIHostingController<some View>) {
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
hostingController.view.backgroundColor = .clear
addSubview(hostingController.view)
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(equalTo: self.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
hostingController.view.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor)
])
}
}
}
How can I achieve that it is correctly shown at the first render?
[1]: https://i.stack.imgur.com/edLWe.png |
Python: Convert Markdown to html with Codeblocks like in stackoverflow |
|python|html|css|markdown|html-email| |
null |
I'm currently developing an Android application aimed at managing GPIO pins on a Raspberry Pi 4 running the Android OS directly.
While I understand that Android operates within a sandboxed environment, potentially limiting access to certain filesystem directories, I'm investigating the feasibility of using /dev/gpiomem to directly map GPIO pins into memory.
My question is:
Is it feasible to employ Memory-Mapped I/O (MMIO) techniques within an Android application running on a Raspberry Pi 4 to interact with GPIO pins via /dev/gpiomem, utilizing native code? If not, are there alternative solutions available to access GPIO pins from my Android application? |
Accessing GPIO via MMIO in Android App on Raspberry Pi 4 |