instruction stringlengths 0 30k ⌀ |
|---|
|firebase-cloud-messaging|vite|service-worker| |
|php|sql-server|pdo|sqlsrv|table-valued-parameters| |
The simplest option to find the `project-id`:
1. Right-click the main GitLab page of your project
2. Select "View Page Source" (`Ctrl + U` in Chrome)
3. Search for:
```txt
Project ID:
```
There you go.
I discovered that it is displayed depending on your role in the project. But GitLab apparently just “hide” it on the client side. |
The `jarModule` is intended as you suggested to hold third party libraries which can indeed be packaged inside skinny war artifacts.
I think it more come in needs when there is common dependencies between war modules inside a single ear one. |
**Context:**
Let's say i'm building a finance app where the transactions are linked (like blockchain).
In the sense, `Transaction 1` has no link, `Transaction 2` should have link to `transaction 1`, `Transaction 3` should have link to `transaction 2` and so on.
And these links should be specific to `accounts`. In the sense, `Account A` will have transaction its own transaction links and `Account B` will have its own.
**Implementation**
I want to use a queuing mechanism(Preferably RabbitMQ) to where these transactions are executed one after the other so that we don't need to worry about concurrency issues.
**Problems**
1. Problem with this approach is, if we have a queue for the entire application, then the amount of transactions increase drastically as we increase accounts.
2. To solve the first problem we can create queue per accounts so that we can execute these transactions concurrently per account. But problem with this approach is number of queues and consumers will increase. And, since accounts can be created at runtime, Adding listeners dynamically might be a problem (I may be wrong here).
So, I want to know if there are any ways we can solve the problem.
Your help is appreciated.
|
- Use `REDUCE` to iterate through the string
- Find the number of `-`s by (``REGEX``)``REPLAC``ing all characters that are not `-`( `[^-]`) with nothing and calculate the remaining `LEN`gth of the string. This is the number of times we need to iterate.
- In each iteration, we use `REGEXEXTRACT` using
- regex `"(.*?,)([^,]+)-([^,]+)(.*$)"` to get
- Capture group #1: `(.*?,)` - get `p`revious match ending with `,`, i.e., `1,2,`
- Capture group #2: `(\d+)` - get `s`tarting ``d``igit before the `-`, i.e., `4`
- Literal `-`
- Capture group #3: `(\d+)`- get `e`nding digit after the `-`, i.e., `10`
- Capture group #4: `(.*$)` - get remaining `s`u`f`ix until end of string `$`, i.e., `,12,15-19`
- Create the `SEQUENCE` of numbers between `s`tarting and `e`nding digit and `JOIN` the `p`refix and `s`u``f``fix.
- Repeat the above until all dashes are removed.
```
=REDUCE(
A1,
SEQUENCE(LEN(REGEXREPLACE(A1,"[^-]",))),
LAMBDA(
a,c,
LET(
res,REGEXEXTRACT(a,"(.*?,)(\d+)-(\d+)(.*$)"),
i, LAMBDA(i, INDEX(res,i)),
p,i(1),
s,i(2),
e,i(3),
sf,i(4),
p&JOIN(",",SEQUENCE(e-s+1,1,s))&sf
)
)
)
``` |
How top app updating the UI component without app update from play store? |
|android|flutter|on-demand-feature-function|deferred-components| |
I have just resolved this issue. It appears that you may have used a Macbook M1 for the pip install process.
The solution involves not using a different runtime to build the layer file.
Use Docker to create an environment identical to that of your lambda function. For me, the issue is resolved.
If you use arm64 for lambda layer
```
docker pull arm64v8/ubuntu
docker run -it arm64v8/ubuntu
```
then create your layer file in docker
after that, copy to local and upload to aws lambda
```
docker cp {container_id}:{path_of_layer.zip} {local_path}
``` |
For this problem, I would like to model out this constraint in cplex.But I am not sure if the indexes that I put is correct or not. Can anyone help me to explain if I did it wrong. Here are some of my codes:
```
Data:
Products = {P1 P2 P3};
NbOperations = 10;
NbPeriods = 3;
LeadTime = [1,1,3,5,0,0,3,0,0,0];
{string} Products = ...;
int NbOperations = ...; range Operations = 1..NbOperations;
int NbPeriods = ...; range Periods = 1..NbPeriods;
int LeadTime[Operations]= ...;
dvar int+ Y[Products][0..NbOperations][Periods];
dvar int+ Xin[Products][-4..NbPeriods];
forall(p in Products,l in Operations,t in Periods)
ct3:
Xin[p][t-LeadTime[l]] == Y[p][l][t];
```
The LeadTime is the estimated lead time of l operation of product p. In my case, I am assuming the lead time is the same for all products.
I felt like the -4 there is wrong. But, I don't know how to change it.
Thanks in advance. |
You can do it in 2 different ways:
If you use `<androidx.fragment.app.FragmentContainerView` tag in xml, it is as follows:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var navigationController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigationController = supportFragmentManager.findFragmentById(R.id.fragmentContainerView)
?.findNavController()!!
NavigationUI.setupActionBarWithNavController(this,navigationController)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navigationController, null)
}
}
```
[![enter image description here][1]][1]
Use is not recommended. If you use `<fragment>` tag in xml, it is as follows:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var navigationController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navigationController = Navigation.findNavController(this,R.id.fragmentContainerView)
NavigationUI.setupActionBarWithNavController(this,navigationController)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navigationController, null)
}
}
```
Note: It should be added to your `build.gradle` file.
```gradle
....
// Navigation
val nav_version = "2.7.6"
implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
implementation("androidx.navigation:navigation-ui-ktx:$nav_version")
....
```
[1]: https://i.stack.imgur.com/qRKTU.png |
Nginx unable to get request from React Native app over internet |
|spring-boot|react-native|nginx| |
null |
I have used below peace of code for calling third party API from my spring boot application.
```
@GetMapping("/client-call")
public String getResponseFromClient(){
String result = null;
for (int i = 0; i < 100; i++) {
RestTemplate restTemplate = new RestTemplate();
String uri = "https://blockstream.info/testnet/api/address/tb1qswa0hq3px3arz229y98m67fprw7ujpvxkztgszvt090rkgnq2hysf85hlg/txs";
result = restTemplate.getForObject(uri, String.class);
System.out.println(i + "\t" + result);
System.out.println("---------------------------------------------");
}
return result;
}
```
when I deployed this spring boot jar file on microsoft azure vm, it throws an error of too many request
[logs](https://i.stack.imgur.com/jrHbp.png) |
Third party API call not working from microsoft azure |
|spring-boot|azure|azure-devops|azure-web-app-service| |
null |
If you are not allowed to modify COPY1 as @BruceMartin suggests, try...
COPY COPY1 REPLACING
==01 AREA1 PIC X (10).== BY ====
==01 AREA3 PIC X (10).== BY ====
.
|
1. If you're using [CSV Data Set Config][1] - it will read next line on next iteration of each virtual user. In order to read all values during 1st iteration - convert them into 29 columns instead of 29 rows
2. In case you cannot control the CSV file format the options are in:
- switch to [__CSVRead() function][2]
- or add a [JSR223 PreProcessor][3] as a child of the request and create the values using [Groovy language][4] like:
sampler.addField('00', '0100')
sampler.addField('02','52250000000015')
//etc
[1]: https://jmeter.apache.org/usermanual/component_reference.html#CSV_Data_Set_Config
[2]: https://jmeter.apache.org/usermanual/functions.html#__CSVRead
[3]: https://jmeter.apache.org/usermanual/component_reference.html#JSR223_PreProcessor
[4]: https://www.blazemeter.com/blog/apache-groovy |
I use segmented picker in iOS which contains few items. When user tap on not selected item this item becomes selected. Some of items can contain sub items. So when user tap on already selected type I need to show modal window with subitems for choosing one of them.
But taps on already selected items of segmented picker are not handling. I tried to use "long press" but it not works as well.
I would like to use native iOS design that's why I don't want use "buttons" instead segmented picker.
So the question is how I can handle tap on already selected item of segmented picker for showing sub items to choosing one of them? It can be "long press" or other alternative which will be intuitive for user.
```
import SwiftUI
struct CustomSegmentedPicker: View {
@State private var showModalSelectD: Bool = false
enum periods {
case A, B, C, D, All
}
@State var predefinedPeriod: periods = periods.All
@State var predefinedPeriodC: String = "C1"
@State var predefinedPeriodD: String = "D1"
func predefinedPeriodSelected(predefinedPeriod: periods) {
if predefinedPeriod == .D {
showModalSelectD.toggle()
}
}
var body: some View {
ZStack {
Color.clear
.sheet(isPresented: $showModalSelectD, content: {
List {
Picker("D", selection: $predefinedPeriodD) {
Text("D1").tag("D1")
Text("D2").tag("D2")
Text("D3").tag("D3")
}
.pickerStyle(.inline)
}
})
VStack {
HStack {
Picker("Please choose a currency", selection: $predefinedPeriod) {
Text("A").tag(periods.A)
Text("B").tag(periods.B)
Text("C").tag(periods.C)
Text("D (\(predefinedPeriodD))").tag(periods.D)
.contentShape(Rectangle())
.simultaneousGesture(LongPressGesture().onEnded { _ in
print("Got Long Press")
showModalSelectD.toggle()
})
.simultaneousGesture(TapGesture().onEnded{
print("Got Tap")
showModalSelectD.toggle()
})
Text("All").tag(periods.All)
}
.pickerStyle(SegmentedPickerStyle())
.onChange(of: predefinedPeriod, perform: { (value) in
predefinedPeriodSelected(predefinedPeriod: value)
})
}
}
}
}
}
``` |
```ts
// GameFactory.ts
export default class GameFactory {
public static create(): AbstractGame {
DependencyRegistrar.registerDependencies();
return container.get<AbstractGame>(TYPES.Game);
}
}
```
```ts
// AbstractGame.ts
export default abstract class AbstractGame {
constructor(
@inject(TYPES.Player)
@named("localPlayer")
protected localPlayer: AbstractPlayer,
@inject(TYPES.Player)
@named("opponent")
protected opponent: AbstractPlayer,
) {}
}
```
```ts
// AbstractPlayer.ts
export default abstract class AbstractPlayer {
@inject(TYPES.InputManager) inputManager!: InputManager;
@inject(TYPES.CharacterController) protected charCtrl!: CharacterController;
constructor() {}
...
}
```
```ts
// CharacterController.ts
export default class CharacterController {
@inject(TYPES.InputManager) inputManager!: InputManager;
constructor() {}
...
}
```
```ts
// DependencyRegistrar.ts
export default class DependencyRegistrar {
public static registerDependencies(): void {
container
.bind<InputManager>(TYPES.InputManager)
.to(InputManager)
container
.bind<CharacterController>(TYPES.CharacterController)
.to(CharacterController);
container
.bind<AbstractGame>(TYPES.Game)
.to(Game)
.inSingletonScope()
container
.bind<AbstractPlayer>(TYPES.Player)
.to(LocalPlayer)
.inSingletonScope()
.whenTargetNamed("localPlayer");
container
.bind<AbstractPlayer>(TYPES.Player)
.to(Opponent)
.inSingletonScope()
.whenTargetNamed("opponent");
}
}
```
Hi. These are a por1tion of my bindings. My `AbstractPlayer` injects the `InputManager` and the `CharacterController` classes. Also, the `CharacterController` class injects the `InputManager` class and I want to get the same instance of `InputManager` that the `AbstractPlayer` class injects.
I tired using `inRequestScope` method but it didn't work and I'm getting the same instance of `InputManager` for both the local player and the opponent. |
How does inRequestScope method works? |
|inversifyjs| |
null |
Okay, it was due to the missing `await` keyword:
```js
await producer.publishMessage("info", "somemessage");
await producer.publishMessage("info", "somemessage");
``` |
Use `keydown` and `keyup` to store state of `ctrlKey` and `shiftKey`. In case of the special key combo, we cancel the event and insert text to textarea in a patchy manner.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var ctrl = false
var shift = false
textarea.addEventListener('paste', function(ev) {
var clipboardData = (event.clipboardData || window.clipboardData);
var pastedText = clipboardData.getData('text');
if (ctrl && shift) {
pastedText = "*" + pastedText + "*"
ev.preventDefault()
// this code - i don't like it - because you can't ctrl+z
var cursorPosition = textarea.selectionStart;
var currentValue = textarea.value;
var newValue = currentValue.substring(0, cursorPosition) + pastedText + currentValue.substring(textarea.selectionEnd);
textarea.value = newValue;
textarea.selectionStart = textarea.selectionEnd = cursorPosition + pastedText.length;
}
})
textarea.addEventListener('keydown', function(ev) {
ctrl = ev.ctrlKey
shift = ev.shiftKey
})
textarea.addEventListener('keyup', function(ev) {
ctrl = ev.ctrlKey
shift = ev.shiftKey
})
<!-- language: lang-html -->
<textarea id="textarea" style="width:100%" rows="8"></textarea>
<!-- end snippet -->
|
the one that worked for me
Caching your GitHub credentials in Git
GitHub Docs
https://docs.github.com › getting-started-with-git › cachi... |
# [Binary Search][1] (ES6)
---
These functions return the element's position (index) within the sorted array if it was found or `-1` if it wasn't.
### Bottom-up
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function binarySearch(arr, val) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === val) {
return mid;
}
if (val < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
const arr = [0,1,2,3,4,6,100,10000];
console.log(binarySearch(arr, 100)); // 6
<!-- end snippet -->
### Recursive
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function binarySearch(arr, val, start = 0, end = arr.length - 1) {
const mid = Math.floor((start + end) / 2);
if (val === arr[mid]) {
return mid;
}
if (start >= end) {
return -1;
}
return val < arr[mid]
? binarySearch(arr, val, start, mid - 1)
: binarySearch(arr, val, mid + 1, end);
}
const arr = [0,1,2,3,4,6,100,10000];
console.log(binarySearch(arr, 1000)); // -1
<!-- end snippet -->
[1]: https://en.wikipedia.org/wiki/Binary_search_algorithm |
If you want the words with Jack and there must be at least `Jack#` you can match the part of the string containing Jack# using a negated character class `[^,\n]*` excluding matching comma's or newlines.
If there is a match, then split the match on one or more whitspace characters and filter the result containing the word Jack using word boundaries `\b`
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const text = 'A Jack# Jack#aNyWord Jack, Jack';
const regexpWords = /[^,\n]*\bJack#[^,\n]*/g;
const m = text.match(regexpWords);
if (m) {
const result = m[0]
.split(/\s+/)
.filter(s => s.match(/\bJack\b/));
console.log(result);
}
<!-- end snippet -->
<hr>
After the question was edited, you can match all words with Jack:
`\bJack[^,\s]*` or `(?<!\S)Jack[^,\s]*`
See a [regex demo](https://regex101.com/r/WGUnTE/1) for the matches. |
I have webservices hosted on server but I am using Retrofit to fetch data from the server but When I am running my app it is showing exception `Unresolve host` but when I am using the same Url in Postman and browser it is working fine.I have also add Internet permission in app manifest file.
Below is my code:
**RetrofitClient.java**
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getInstance(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(22, TimeUnit.SECONDS)
.readTimeout(22, TimeUnit.SECONDS)
.writeTimeout(22, TimeUnit.SECONDS)
.build();
if(retrofit == null)
retrofit = new Retrofit.Builder()
.baseUrl("https://adbhutbharat.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
}
**ApiService.java**
public interface ApiService {
@GET("app/getAgents.php")
Call<List<Agents>> allAgents();
}
The above endpoint is working properly in postman and browser but not when requesting using retrofit in android to fetch data.
How can I resolve this error?
|
import requests
from database_utils import connect_to_database
class Tick:
def __init__(self):
self.symbol = ""
self.name = ""
self.last = 0.0
self.high = 0.0
def tickprice(code):
url = f"http://qt.gtimg.cn/q={code}"
# print(f"API URL: {url}")
headers = {
'If-None-Match': '1'
}
response = requests.get(url, headers=headers).text
# print(f"API Response: {response}")
data = response.split('~')
# print(f"API Data: {data}")
if len(data) >= 34:
tick = Tick()
tick.last = float(data[3])
return tick
return None
# Connect to the database
conn, cursor = connect_to_database()
try:
# Execute the SELECT statement to extract specific columns from the stocks table
cursor.execute("SELECT stockCode, shsz FROM stocks")
# Fetch the result
rows = cursor.fetchall()
# Convert rows to dictionaries
results = []
column_names = [description[0] for description in cursor.description] # Extract column names
# print("Retrieved rows:")
for row in rows:
# print(row)
result = dict(zip(column_names, row))
results.append(result)
# Access 'stockCode' from the dictionary
stock_code = result['stockCode'].strip()
market = result['shsz'] # Convert market to a string
if market is None:
continue # Skip the iteration if market is None
if market == 1:
market = "sh"
if market == 0:
market = "sz"
# print(market)
stock_code = market + stock_code
# print(stock_code)
# Retrieve stock prices using tickprice function
tick = tickprice(stock_code)
if tick is not None:
# Update the stock price in the dictionary
result['price'] = tick.last
# Update all stock prices in a single database transaction
for result in results:
stock_code = result['stockCode']
price = result['price']
cursor.execute("UPDATE stocks SET price=%s WHERE stockCode=%s", (price, stock_code))
# Commit the changes
conn.commit()
except Exception as e:
print(f"Error occurred: {e}")
finally:
# Close the cursor and database connection
cursor.close()
conn.close()
print("Execution completed.") |
How can the code be optimized? The execution takes too long. It recalls API to retrieve many stock prices and writes those prices into a table |
|python|sqlite|optimization|query-optimization| |
I am working on an indoor navigation application that involves two floor plan images: one is the original floor plan, and the other includes nodes and paths (used for navigation). Using Python and the OpenCV library, I have successfully extracted the XY coordinates of all nodes from the navigation floor plan. However, I am facing challenges when translating these coordinates to position a map pin on the ImageView in Android Studio.
When I attempted to position an ImageView as a map pin on a FloorPlan ImageView using these coordinate, the map pin does not align with the nodes as expected in the Android ImageView. The scaling and translation seem to be incorrect.
Here is my imageView:
```
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/floorPlan"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:src="@drawable/floor5" />
<!-- ImageView for the map pin marker -->
<ImageView
android:id="@+id/mapPin"
android:layout_width="30dp"
android:layout_height="30dp"
android:visibility="gone"
android:src="@drawable/map_pin" />
</FrameLayout>
```
Here is what i tried for scaling:
```
private void updateMapPinPosition(int xCoordinate, int yCoordinate) {
// Convert 30dp to pixels based on screen density
int pinSizeInPixels = (int) (30 * getResources().getDisplayMetrics().density);
// Get the ImageView and its dimensions
ImageView mapPin = findViewById(R.id.mapPin);
Drawable floorPlanDrawable = mapImageView.getDrawable();
if (floorPlanDrawable != null) {
// Get the dimensions of the drawable (the floor plan image)
int drawableWidth = floorPlanDrawable.getIntrinsicWidth();
int drawableHeight = floorPlanDrawable.getIntrinsicHeight();
// Get the dimensions of the ImageView (the view displaying the floor plan)
int imageViewWidth = mapImageView.getWidth();
int imageViewHeight = mapImageView.getHeight();
// Calculate the scale based on the drawable dimensions and view dimensions
float xScale = (float) imageViewWidth / drawableWidth;
float yScale = (float) imageViewHeight / drawableHeight;
// Scale the coordinates from the server to fit the ImageView
int scaledX = (int) (xCoordinate * xScale);
int scaledY = (int) (yCoordinate * yScale);
// Adjust the position of the map pin based on the pin size
scaledX -= pinSizeInPixels / 2; // Center the pin horizontally
scaledY -= pinSizeInPixels; // Anchor the pin to the bottom
// Use absolute coordinates to place the pin
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
pinSizeInPixels, // Width in pixels
pinSizeInPixels // Height in pixels
);
params.leftMargin = scaledX; // X position
params.topMargin = scaledY; // Y position
mapPin.setLayoutParams(params); // Apply the layout parameters to the map pin
mapPin.setVisibility(View.VISIBLE); // Make the map pin visible
}
}
``` |
WebServices not working with Retrofit but working properly in Postman |
We can use a vectorized operation using `cbind`: ` M[cbind(indices, 1:ncol(M))]`
```
set.seed(123)
(M <- matrix(rnorm(25), 5))
indices <- c(2, 3, 1, 4, 4)
# vectorized
vect1 <- M[cbind(indices, 1:ncol(M))]
# loop
vect <- c()
for(i in 1:5) {
vect <- c(vect, M[indíces[i], i])
}
# benchmark
library(microbenchmark)
mbm = microbenchmark(
vectorized = M[cbind(indices, 1:ncol(M))],
loop = for(i in 1:5) {
vect <- c(vect, M[indíces[i], i])
},
times=50
)
mbm
Unit: microseconds
expr min lq mean median uq max neval cld
vectorized 2.1 2.8 5.158 6.30 6.5 15.6 50 a
loop 2062.8 2089.2 2143.418 2114.55 2183.8 2391.0 50 b
autoplot(mbm)
```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/QdBwU.png |
null |
[Constraint][1]
For this problem, I would like to model out this constraint in cplex.But I am not sure if the indexes that I put is correct or not. Can anyone help me to explain if I did it wrong. Here are some of my codes:
```
Data:
Products = {P1 P2 P3};
NbOperations = 10;
NbPeriods = 3;
LeadTime = [1,1,3,5,0,0,3,0,0,0];
{string} Products = ...;
int NbOperations = ...; range Operations = 1..NbOperations;
int NbPeriods = ...; range Periods = 1..NbPeriods;
int LeadTime[Operations]= ...;
dvar int+ Y[Products][0..NbOperations][Periods];
dvar int+ Xin[Products][-4..NbPeriods];
forall(p in Products,l in Operations,t in Periods)
ct3:
Xin[p][t-LeadTime[l]] == Y[p][l][t];
```
The LeadTime is the estimated lead time of l operation of product p. In my case, I am assuming the lead time is the same for all products.
I felt like the -4 there is wrong. But, I don't know how to change it.
Thanks in advance.
[1]: https://i.stack.imgur.com/LqXXt.png |
In the WordPress core, WordPress uses the sanitize_title hook to apply its own filter (you can find that in this code):
https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php
The function it call is sanitize_title_with_dashes:
https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/
That's the function you are looking for. |
**service.py**
def add_goods_to_cart(goods_id, user, addend):
goods = Goods.objects.filter(pk=goods_id).first()
if goods:
the_goods_already_in_cart = Cart.objects.filter(user=user, goods=goods, order=None).first()
if the_goods_already_in_cart:
the_goods_already_in_cart.quantity = (the_goods_already_in_cart.quantity + addend)
if the_goods_already_in_cart.quantity == 0:
the_goods_already_in_cart.delete()
else:
the_goods_already_in_cart.save()
else:
Cart.objects.create(user=user, goods=goods, quantity=1)
status = 200
else:
status = 400
return status
**views.py**
class AddToCart(LoginRequiredMixin,
View):
def post(self, request):
goods_id = request.POST.get('goods_id')
addend = int(request.POST.get('addend'))
assert (addend == 1 or addend == -1)
status = add_goods_to_cart(goods_id, request.user, addend)
if status == 200:
act = "added to cart" if addend > 0 else "removed from cart"
messages.add_message(request, messages.INFO, 'Goods "{}" {}.'.format(goods.name, act))
return redirect(request.META['HTTP_REFERER'])
else:
return HttpResponse("Wrong goods id", status=status)
What troubles me:
1. Can I transmit request from views.py to service.py? A view is
something that operates on request. In my logic, it is reasonable
not to transmit request out of view. Receive data from request,
transmit the data to the service.
2. What will create the message? In my logic, it is the responsibility
of the view. But the view doesn't know anything about the name of
the goods. Look here: this code will not work just because there is
no name of the goods for the message.
Well, anyway, the architecture of this code stinks. Maybe I should return from the service not the status code, but the name of the added goods?
How can I refactor this code?
|
Here is somewhat a basic question but the reason is not spelled out clearly anywhere.
Say we have 2 web applications running on `https://one.abc.com` and `htts://two.xyz.com`.
I visit `https://one.abc.com` and a page is displayed which has a button on it and when clicked, submits to `https://one.abc.com` and responds with a redirect to `htts://two.xyz.com`.
On `htts://two.xyz.com` there is another button and when clicked, submits to `htts://two.xyz.com` and responds with a redirect to `https://one.abc.com`.
As everything is happening over https, in both redirections, everything like URL, query params, headers are encrypted.
Using the above setup we can do data exchange between 2 web application using query params.Also, we can do data exchange with auto-form-post (dynamically create form and auto submit using js) instead of query params.
This technique is used in SAML, OIDC for SSO.
Why data exchange using redirection via query params/auto-form-post CANNOT be trusted even on https?
Please review the below answer and let me know if my understanding is correct.
|
[Example](https://i.stack.imgur.com/ujcMb.jpg)
I need to choose a hierarchical database management system for my project, which hierarchical database management system would you advise me to use? Thank you in advance. Thank you
haven't tried anything yet. |
I have this route defined:
Route::match(['get', 'post'], '/{class}/{function}/', [OldBackendController::class, 'apiV1']);
If I do this request:
POST /api/v2_1/wishlist/archive
Laravel enters int the `OldBackendController`, and the value of `$class` variable (in the controller), is this:
api/v2_1/wishlist
Why? It shouldn't enter in the controller, cause the request does not contains 2 variables, but 4.
The strange thing is if in the controller I print `$request->segments()` value, I get all 4 segment:
Array
(
[0] => api
[1] => v2_1
[2] => wishlist
[3] => archive
) |
Laravel controller does not get correct parameter from route definition, and enters in the wrong controller function |
|php|laravel|laravel-10| |
While on the transaction in parallel situation, prisma throw error like that message
so i wanna know why it error occured, and how to resolove it,
ERROR MESSAGE
```
[Nest] 43187 - 2024. 03. 17. 오후 4:14:56 ERROR [ExceptionsHandler] Transaction API error: Transaction not found. Transaction ID is invalid, refers to an old closed transaction Prisma doesn't have information about anymore, or was obtained before disconnecting.
PrismaClientKnownRequestError: Transaction API error: Transaction not found. Transaction ID is invalid, refers to an old closed transaction Prisma doesn't have information about anymore, or was obtained before disconnecting.
at xt.transaction (/src/node_modules/.pnpm/@prisma+client@5.11.0(prisma@5.11.0)/node_modules/@prisma/client/runtime/library.js:111:12322)
at Proxy._transactionWithCallback (/src/node_modules/.pnpm/@prisma+client@5.11.0(prisma@5.11.0)/node_modules/@prisma/client/runtime/library.js:127:9568)
at AccountService.recharge (/src/src/account/charge.service.ts:34:5)
at /src/node_modules/.pnpm/@nestjs+core@10.3.3(@nestjs+common@10.3.3)(@nestjs+platform-express@10.3.3)(reflect-metadata@0.2.1)(rxjs@7.8.1)/node_modules/@nestjs/core/router/router-execution-context.js:46:28
at /src/node_modules/.pnpm/@nestjs+core@10.3.3(@nestjs+common@10.3.3)(@nestjs+platform-express@10.3.3)(reflect-metadata@0.2.1)(rxjs@7.8.1)/node_modules/@nestjs/core/router/router-proxy.js:9:17
```
TEST CODE
```
const willChargeAmount = Array.from({ length: 20 }, () =>
randomIntByRange(1000, 5000),
);
console.log(willChargeAmount);
console.log('-------------------------------------------------');
const responses = await Promise.all(
willChargeAmount.map((amount) =>
request(app.getHttpServer())
.post(`/users/${foundUser?.user_id}/recharge`)
.set('Authorization', `Bearer ${jwt}`)
.send({ amount }),
),
);
console.log('-------------------------------------------------');
```
charge.service.ts
```
public async recharge(rechargeRequest: chrageDatas) {
await this.accountRepository.recharge(rechargeRequest);
}
```
accountRepository.ts
```
public async recharge(
rechargeRequest: chrageDatas,
) {
return this.prismaService.prisma.$transaction(async (tx) => {
const amounts = await tx.accounts.findMany({
where: {
AND: [
{ user_id: rechargeRequest.user.userId }
],
},
});
const points = amounts.filter(
(amount) => amount.type === PERMANENT,
);
if (points.length >= 1) {
return tx.accounts.update({
where: {
account_id: points[0].account_id,
},
data: {
amount: rechargeRequest.amount,
},
});
}
return tx.accounts.create({
data: {
users: {
connect: {
user_id: rechargeRequest.user.userId,
},
},
type: PERMANENT,
amount: rechargeRequest.amount,
},
});
});
}
```
prisma.service.ts
```
@Injectable()
export class PrismaService implements OnModuleInit, OnModuleDestroy {
public prisma: PrismaClient;
public async onModuleDestroy() {
await this.prisma.$disconnect();
}
public async onModuleInit() {
this.prisma = new PrismaClient();
await this.prisma.$connect();
}
}
```
and prisma connected on booting and destory at "OnModuleDestroy"
i'm expection nothing error occured, and finish transcation successfully |
How to accurately translate image coordinates from Python/OpenCV to Android ImageView? |
|android|opencv|coordinates|android-imageview| |
|powerbi|dax|powerbi-desktop| |
There is a function inside which determines whether metadata is saved (by metadata I mean saving dtypes). When I save a Dataframe to a parquet file and then read data from that file I expect to see metadata persistence. I will perform this check in this way:
```
In [6]:(pd.read_parquet(os.path.join(folder, 's_parquet.parquet'), engine='fastparquet').dtypes == df_small.dtypes).all()
Out [6]: Fasle
```
```
In [7]: pd.read_parquet(os.path.join(folder, 's_parquet.parquet'), engine='fastparquet').dtypes == df_small.dtypes
Out [7]:
date True
tournament_id True
team_id True
members True
location False
importance False
avg_age True
prize True
prob True
win True
dtype: bool
```
If you look at the data types directly you can see the following result:
```
In [8]: df_small.dtypes
Out [8]:
date datetime64[ns]
tournament_id int32
team_id int16
members int8
location category
importance category
avg_age float32
prize float32
prob float32
win bool
dtype: object
```
```
In [9]: pd.read_parquet(os.path.join(folder, 's_parquet.parquet'), engine='fastparquet').dtypes
Out [9]:
date datetime64[ns]
tournament_id int32
team_id int16
members int8
location category
importance category
avg_age float32
prize float32
prob float32
win bool
dtype: object
```
And even if you compare the categorical data directly, you get the expected result.
```
In [10]: df_small['location'].dtypes == pd.read_parquet(os.path.join(folder, 's_parquet.parquet'), engine='fastparquet')['location'].dtypes
Out [10]: True
```
What could be the reason for this behavior? |
Problem in defining dtypes of categorical data obtained from parquet file |
|pandas|dataframe|parquet| |
null |
I'm using AG Grid table v31 for `agDateColumnFilter` I'm trying to change default date format from `mm/dd/yyyy` to `dd.mm.yyyy`.
If I use the exact `valueFormatter` just for column it works but in the filter doesn't work.
[![enter image description here][1]][1]
```typescript
{
field: 'createdDate',
headerName: 'Created',
filter: 'agDateColumnFilter',
filterParams: dateFilterButtonsConfig,
},
export const dateFilterButtonsConfig = {
buttons: ['reset', 'apply'],
maxNumConditions: 1,
valueFormatter: (params: ValueFormatterParams) => formatDate(params),
};
function formatDate(dateString: string) {
const [day, month, year] = dateString.split('/');
return `${day}.${month}.${year}`;
}
```
[1]: https://i.stack.imgur.com/Ixn2h.png |
AG Grid table format date value in the filter "agDateColumnFilter" doesnt't work |
I use Prisma to generate data types.
model artworks {
id String @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
title String @db.VarChar(255)
artistid String @db.Uuid
description String?
dataadded DateTime? @default(now()) @db.Time(6)
isavailable Boolean? @default(true)
imageurl String @db.VarChar(500)
artworkimages artworkimages[]
users users @relation(fields: [artistid], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "fk_artistid")
}
model artworkimages {
id String @id(map: "artworkimage_pkey") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
artworkid String @db.Uuid
url String @db.VarChar(255)
name String? @db.VarChar(255)
createddate DateTime? @default(now()) @db.Timestamp(6)
artworks artworks @relation(fields: [artworkid], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "artworkimage_artworkid_fkey")
}
Here is the method to get artwork with images
export async function getArtwork(id: string): Promise<artworks | null> {
try {
const artwork = await prisma.artworks.findUnique({
where: { id },
include: {
artworkimages: true,
}
});
return artwork;
} catch (error) {
console.error('Failed to fetch artwork:', error);
throw new Error('Failed to fetch artwork.');
}
}
When I try to access the `artwork.artworkimages` , it errors out saying
> Property 'artworkimages' does not exist on type '{ id: string; title:
> string; artistid: string; description: string | null; dataadded: Date
> | null; isavailable: boolean | null; imageurl: string; }'.
How can I get access to it? |
How to access the nested objects in Prisma |
|reactjs|next.js|prisma| |
I'm writing a function that decodes a morse code message to plain text. The problem I'm running into, is that it doesn't add spaces where needed. Keep in mind that every morse code character/letter, is separated with a blank space and every full word, is separated by 3 spaces. I want the function to add a single blank space to the plain text when it detects 3 blank spaces in a row in the morse code. I can't figure it out so i've come here.
Here is the function as it is now.
public function decode($morseCode)
{
// 1 space between characters, 3 spaces between words
// split the string
$morseArray = preg_split('/\s+/', $morseCode, -1);
$plainText = '';
$blankSpaceCount = 0;
// set each string as a morse code character
foreach ($morseArray as $morseChar)
{
if ($morseChar != ' ')
{
// check if the morsecode character is in the array
if(isset($this->plainTextsByMorseCode[$morseChar]))
{
// if it is, convert it to the corresponding plain text
$plainText .= $this->plainTextsByMorseCode[$morseChar];
$blankSpaceCount = 0;
}
}
else {
$blankSpaceCount++;
if ($blankSpaceCount === 3)
{
$plainText .= ' '; // Append a single blank space
$blankSpaceCount = 0;
}
}
}
return trim($plainText);
}
If it helps, the phrase i'm trying to decode is as follows.
-.-- --- ..- ... .... .- .-.. .-.. -. --- - .--. .- ... ...
It says "YOU SHALL NOT PASS" and you can clearly see the triple blank spaces between the words and the singular blank space between the letters.
|
Is there a way to get all values level by all level in a Pandas MultiIndex? |
|pandas| |
I have an HTML/CSS/JS website where I'm embedding facebook posts, and adding some text (with various info and action buttons) to the top of each post. I'm adding the text that goes above each post dynamically in Javascript, so that the embedded post (iframe) is in a separate container than the text that goes above it.
As you can see in the image below, the text is positioned as `absolute` so that it appears above the post, and not next to it. However, I can't seem to get the post to move *down* nor the text to move up in order to create some separation between them. Any help or ideas would be greatly appreciated!!
UPDATE: I meant to include a codepen that reproduces the issue with minimal code: https://codepen.io/Mickey_Vershbow/pen/dyLzLNV?editors=1111
See below for code as well:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// Array of facebook post ID's
facebookArr = [{
post_id: "pfbid0cm7x6wS3jCgFK5hdFadprTDMqx1oYr6m1o8CC93AxoE1Z3Fjodpmri7y2Qf1VgURl"
},
{
post_id: "pfbid0azgTbbrM5bTYFEzVAjkVoa4vwc5Fr3Ewt8ej8LVS1hMzPquktzQFFXfUrFedLyTql"
}
];
// Variables to store post ID, embed code, parent container
let postId = "";
let embedCode = "";
let facebookContainer = document.getElementById("facebook-feed-container");
$(facebookContainer).empty();
// Loop through data to display posts
facebookArr.forEach((post) => {
let relativeContainer = document.createElement("div");
postId = post.post_id;
postLink = `${postId}/?utm_source=ig_embed&utm_campaign=loading`;
// ---> UPDATE: separate container element
let iframeContainer = document.createElement("div");
embedCode = `<iframe src="https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2FIconicCool%2Fposts%2F${postId}&show_text=true&width=500" width="200" height="389" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" id=fb-post__${postId}></iframe>`;
// Update the DOM
iframeContainer.innerHTML = embedCode;
// ADDITIONAL TEXT
let additionalTextParentContainer = document.createElement("div");
additionalTextParentContainer.className = "risk-container";
let additionalText = document.createElement("div");
additionalText.className = "absolute";
additionalText.innerText = "additional text to append";
additionalTextParentContainer.append(additionalText);
relativeContainer.append(additionalText, iframeContainer);
facebookContainer.append(relativeContainer);
});
<!-- language: lang-css -->
#facebook-feed-container {
display: flex;
flex-direction: row;
row-gap: 1rem;
column-gap: 3rem;
padding: 1rem;
}
.absolute {
position: absolute;
margin-bottom: 5rem;
color: red;
}
.risk-container {
margin-top: 3.5rem;
}
<!-- language: lang-html -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="facebook-feed-container">
</div>
<!-- end snippet -->
[1]: https://i.stack.imgur.com/33joo.jpg |
how do i detect 3 blank spaces in a string array |
|php|arrays|string| |
## Need: `getDownloadURL` on external bucket
We have a Firebase/GCP project and we want to use the [`getDownloadURL` Firebase storage function][1] in Node.js to create a permanent signed URL for an object in a bucket in a different project.
Specifically, we have an asset bucket and we want to generate long-lived (forever) URLs for objects in it, but not make the bucket public otherwise. The asset bucket serves many projects and we want all those projects to all be able to generate URLs against the asset bucket (without having to do anything exotic).
## Error: Permission Denied
When we run the `getDownloadURL` we get the following error:
> "Error: Permission denied. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources."
The error suggests that we add the bucket to the Firebase project. When we attempt to add a bucket via the Firebase Console we can create or import a bucket, but it's not clear what "import" means (copy? move bucket across projects? etc), whether it would work across projects. We can't find any documentation indicating what this does or whether it would help, but it also seems unnecessary/irrelevant to the permissions question (which one would expect to be solved by IAM permissions).
## Attempted fixes
We've also found some suggestions that we've tried:
1. granted Storage Admin to firebase-storage@system.gserviceaccount.com on the bucket
1. [set storage rules to allow-all][2] on the Firebase project
1. grant Storage Admin on the bucket to the service account that runs the Firebase function
The error gives no useful indication of how to fix this, there's no apparent documentation on what permissions are needed, and most of the information from Google/etc is outdated or wrong.
## Workaround
As a workaround we've also considered using [long-lived V2 Signed URLs][3] but the documentation specifically says to keep it short-lived, and V4 Signed URLs have an arbitrary 7-day limit, but the `getDownloadURL` function would appear to be the correct/ideal thing to do here (if it worked).
How can we use `getDownloadURL` on an object in a bucket outside the GCP project?
Related:
- https://firebase.google.com/docs/storage/admin/start#shareable_urls
- https://www.sentinelstand.com/article/guide-to-firebase-storage-download-urls-tokens
- https://github.com/firebase/firebase-admin-node/issues/1352
- https://stackoverflow.com/questions/42956250
- https://stackoverflow.com/a/76744881/19212
[1]: https://firebase.google.com/docs/storage/admin/start#shareable_urls
[2]: https://stackoverflow.com/a/70950285/19212
[3]: https://cloud.google.com/storage/docs/access-control/signed-urls-v2 |
Firebase-admin node.js getDownloadURL permission error on external bucket |
|firebase|google-cloud-platform|google-cloud-storage|firebase-storage|firebase-admin| |
Based on [Yoast SEO][1], it determine whether the title is too long based on its width instead of number of characters.
So, how to know the font, font size, and font style used in Google search results?
Also how to know the visible width for Google search results, from moz, it is said to be 600 pixels
```
procedure TMainForm.Button2Click(Sender: TObject);
var
Bitmap: TBitmap;
Width: Integer;
begin
Bitmap := TBitmap.Create;
try
// What is the font, font size, and font style used in Google search results?
Bitmap.Canvas.Font.Assign(Self.Font);
Width := Bitmap.Canvas.TextWidth('This is to test the title and to make sure it is not too long to be invisi');
// What is the max width of Google search results, based on https://moz.com/learn/seo/title-tag, it is 600pixels
Application.MessageBox(PChar(Format('Title width is %d', [Width])), 'Information', MB_OK);
finally
Bitmap.Free;
end;
end;
```
[1]: https://yoast.com/page-titles-seo/#width-vs-length |
{"OriginalQuestionIds":[43969277],"Voters":[{"Id":11107541,"DisplayName":"starball","BindingReason":{"GoldTagBadge":"visual-studio-code"}}]} |
Refer to this ticket: [Error message when trying to add a Team Member][1]
The cause of the issue is that the Product Team made some changes to boards a few weeks ago. it leads to issues of identity.
Now, Product Team has reverted the change that was causing the issues with assigned to.
You can try to assign to the users in the work item again and check if it can work.
[1]: https://developercommunity.visualstudio.com/t/Error-message-when-trying-to-add-a-Team-/10616251#T-ND10626985 |
I am trying to implement circuit breaker pattern in my spring boot application. I am referring to https://redhat-scholars.github.io/spring-boot-k8s-tutorial/spring-boot-tutorial/05-resiliency.html this tutorial. I am getting above error. Not sure what point I am missing.
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
@Configuration
public class CircuitBreakerConfiguration {
private CircuitBreakerConfig circuitBreakerConfig() {
return CircuitBreakerConfig.custom()
.failureRateThreshold(2)
.waitDurationInOpenState(Duration.ofMillis(1000))
.slidingWindowSize(2)
.build();
}
// Create a Customizer<Resilience4JCircuitBreakerFactory> bean to configure the Resilience4JCircuitBreakerFactory
@Bean
@ConditionalOnMissingBean
public Customizer<Resilience4JCircuitBreakerFactory> resilience4jCircuitBreakerCustomizer() {
return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.circuitBreakerConfig(circuitBreakerConfig())
.timeLimiterConfig(timeLimiterConfig())
.build());
}
private TimeLimiterConfig timeLimiterConfig() {
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofSeconds(4))
.build();
return timeLimiterConfig;
}
Few of the dependencies
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-starter-config'
implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j:2.0.2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.kafka:spring-kafka'
implementation 'io.github.resilience4j:resilience4j-spring-boot2:1.7.0'
implementation 'io.github.resilience4j:resilience4j-circuitbreaker:1.7.0'
implementation 'io.github.resilience4j:resilience4j-consumer:1.7.0'
implementation 'io.github.resilience4j:resilience4j-core:1.7.0'
implementation 'io.github.resilience4j:resilience4j-spring:1.7.0'
implementation 'io.github.resilience4j:resilience4j-annotations:1.7.0'
implementation 'io.github.resilience4j:resilience4j-timelimiter:1.7.0'
Using constructor injection I am trying to inject bean into my class
private CircuitBreaker circuitBreaker;
public ProductEventConsumer(Resilience4JCircuitBreakerFactory circuitBreakerFactory) {
this.circuitBreaker = circuitBreakerFactory.create("circuitbreaker");
} |
|angular|typescript|ag-grid-angular| |
please help me to understand the problem. I recently made a build with expo dev, everything went well. But after some time, I needed to make another build and I got the following error:
`✔ Preparing the list of your Firebase projects
Firebase project not found or not correctly mentioned on config.json
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
yarn install exited with non-zero code: 1`
Mobile app build, react, expo dev
I tried rolling back to a backup to remove all changes, didn't help. Also, on the local device I wrote yarn install, yarn - no errors. The old build works with firebase normally, but exactly the same code is not buildable now. Also, I checked all settings and config - everything is normal. I do not understand what the problem is. Please help. Thanks
|
Expo dev - have a build error "Firebase project not found or not correctly mentioned on config.json" |
|android|ios|reactjs|mobile|expo| |
null |
I have a simple animation where I have a static rectangle slowly moving horizontally so that it pushes a circle across the 'floor'.
How can I make the circle roll instead of slide?
I tried adding friction to the circle and the floor, and removing friction from the pushing rectangle, but it makes no difference.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var container = document.getElementById('container');
var w = 1000;
var h = 500;
const Engine = Matter.Engine;
const Render = Matter.Render;
const World = Matter.World;
const Bodies = Matter.Bodies;
const MouseConstraint = Matter.MouseConstraint;
const Bounds = Matter.Bounds;
const Events = Matter.Events;
const Body = Matter.Body;
const engine = Engine.create();
const render = Render.create({
element: container,
engine: engine,
options: {
width: w,
height: h,
wireframes: true,
showAngleIndicator: true,
background: 'transparent',
}
});
var boxX = 10;
var boxY = 390;
const ball = Bodies.circle(100, 400, 80, {
friction: 100
});
const box = Bodies.rectangle(boxX, boxY, 20, 20, {
friction: 0,
isStatic: true
});
const floor = Bodies.rectangle(500, 480, 1000, 20, {
isStatic: true
});
World.add(engine.world, [
ball,
box,
floor
]);
engine.gravity.y = 3;
Matter.Runner.run(engine);
Render.run(render);
move();
function move() {
boxX += 1;
Matter.Body.setPosition(box, {
x: boxX,
y: boxY
}, [updateVelocity = true]);
window.requestAnimationFrame(move);
};
<!-- language: lang-html -->
<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js" integrity="sha512-0z8URjGET6GWnS1xcgiLBZBzoaS8BNlKayfZyQNKz4IRp+s7CKXx0yz7Eco2+TcwoeMBa5KMwmTX7Kus7Fa5Uw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- end snippet -->
|
User
```dart
TextFormField(
enableInteractiveSelection: false,
controller: _runningKmsController,
keyboardType: TextInputType.number,
inputFormatters: [
LengthLimitingTextInputFormatter(3)
],
onChanged: (value) {
calculateTotalKms();
monthlyTotalCost();
monthlyTotalEvCost();
calculateTotalCostPerMonth();
calculateTotalCostPerMonthEv();
calculateMonthlySavings();
},
cursorColor: AppTheme.appColors,
textAlign: TextAlign.center,
decoration: InputDecoration(
fillColor: Colors.white,
// hintText: 'Enter your text here',
border: UnderlineInputBorder(
borderSide: BorderSide(color: AppTheme.appColors),
),
),
),
TextFormField(
enableInteractiveSelection: false,
textAlign: TextAlign.center,
keyboardType: TextInputType.number,
cursorColor: AppTheme.appColors,
controller: _noOfWorkDaysController,
inputFormatters: [LengthLimitingTextInputFormatter(2)],
onChanged: (value) {
calculateTotalKms();
monthlyTotalCost();
monthlyTotalEvCost();
calculateTotalCostPerMonth();
calculateTotalCostPerMonthEv();
calculateMonthlySavings();
},
decoration: InputDecoration(
fillColor: Colors.white,
// hintText: 'Enter your text here',
border: UnderlineInputBorder(
// borderRadius: BorderRadius.circular(2.0),
borderSide: BorderSide(color: AppTheme.appColors),
),
),
),
```
I have 2 text form fields. Restrictions are required from 50 to 250 in the runningkmscontroller. A pop-up should be shown once the user shifts to the next tab. If the user enters a value less than or greater than the given range, validation should be performed. Additionally, onChange() function calculates different values. How can I achieve this? Please provide a solution.
|
Consider defining a bean of type 'org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory' in your configuration |
|spring-cloud|circuit-breaker|resilience4j| |
It happens sometimes because of Android Studio cache issues. Try to invalidate caches and restart the studio. In below image select all the options.[][1]
[1]: https://i.stack.imgur.com/x06qu.png |
> I think it probably requires to use `index_sequence` but I'm not sure
> how.
Yes, it's very easy to do this using `index_sequence`:
template<typename... Args, std::size_t... Is>
void foo_impl(std::index_sequence<Is...>, const Args&... args)
{
using typeLists = std::tuple<Args...>;
bar( SomeClass<Args, std::tuple_element_t<Is, typeLists>>{ args }... );
}
template<typename... Args>
void foo(const Args&... args)
{
foo_impl( std::index_sequence_for<Args...>{}, args... );
} |
To successfully serve static files in production, I used WhiteNoise and deployed it to Azure App Service.
I used your git repo code and made the necessary changes.
To use whitenoise, I added the lines below in the settings. py file, as shown below:
Note: Add whitenoise middleware after the security middleware.
**settings. py**:
```python
INSTALLED_APPS = [
'otherInstalledApps
"whitenoise.runserver_nostatic",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'other middlewares'
]
STATIC_ROOT = BASE_DIR / "static"
STATIC_URL = "static/"
STATICFILES_DIRS = [
BASE_DIR / "assets"
]
STATICFILES_STORAGE = ('whitenoise.storage.CompressedManifestStaticFilesStorage')
```
I added the white noise to the requirements.txt file, as shown below.
**requirements.txt**:
```html
Django==4.2.1
requests==2.31.0
whitenoise==6.6.0
```
I ran the commands below to install whitenoise and collect static files for production.
```
pip install whitenoise
python manage.py collectstatic
python manage.py migrate
```
**LocalOutput**:

It was deployed successfully to azure app service.
**Azure App Service Output**:
 |
I've been using Firebase for several years now and have recently set up a new project to run with Firebase.
The problem occurs when I try to run `firebase deploy`.
I get the errors:
`[project root]/functions/.eslintrc.js`
`0:0 error Parsing error: Cannot read file '[project root]/functions/functions/tsconfig.json'`
and
`[project root]/functions/src/index.ts`
`0:0 error Parsing error: Cannot read file '[project root]/functions/functions/tsconfig.json'`
I tried replacing
```"functions": {
"predeploy": [
"npm --prefix "$RESOURCE_DIR" run lint",
"npm --prefix "$RESOURCE_DIR" run build"
]
}
```
with
```"functions": {
"predeploy": [
"npm --prefix ./functions/ run lint",
"npm --prefix ./functions/ run build"
]
}
```
as per this answer https://stackoverflow.com/a/48591027/5348742,but I still get the same error.
If I checkout my previous commit, it works fine but using DIFF, I can't find any difference that could change the behaviour.
The `firebase.json` files are identical in the two versions.
|
Get Width of Title Like Yoast SEO does |
|fonts|seo|yoast| |
As the first step of a larger process, I'm trying to get the column names from some .dat files. I'm getting the "FileNotFoundError: [Errno 2] No such file or directory:" error, but I'm passing it the directory path and it is telling me the first file in the folder, so it doesn't seem to be the usual suspect of the relative/absolute path issue.
dir_path = "C:/Projects/acs5-2022/Datasource/TestSample"
column_list = []
for path, subs, file_names in os.walk(dir_path):
for file in file_names:
datafile = pandas.read_csv(file, delimiter='|')
for col in datafile.columns:
col.append(column_list)
print(column_list)
And I get:
FileNotFoundError: [Errno 2] No such file or directory: 'acsdt5y2022-b02009.dat'
acsdt5y2022-b02009.dat is the first file in the TestSample folder. I'm not giving it that information, so it can, in fact, see the files.
The header in this particular file is GEO_ID|B02009_E001|B02009_M001
I've tried various formats for the path directory - "C:/.....", r"C:\.....", "C:\\....." - it doesn't seem to matter.
Any suggestions? Is it the .dat format? Is it the pipes? I'm using PyCharm and I've seen some posts on that, but again, I'm specifying the directory.
Thank you in advance for any direction you can give me!
|
Python - "FileNotFoundError: [Errno 2] No such file or directory:" |
|python|pandas| |
null |
The answer with `declare global { ...` didn't work out for me.
The recommanded approach is to create a type declaration file, for example `env.d.ts` with the following declaration:
```ts
declare namespace NodeJS {
interface ProcessEnv {
JWT_TOKEN: string;
}
}
```
And then add this reference in your `tsconfig.json` file's `include`:
```json
{
"include": [
"next-env.d.ts",
"env.d.ts",
]
}
```
**Discouraged approach**
Do not add a reference in `next-end.d.ts`, Next.js [docs mention][1] that:
> A file named next-env.d.ts will be created at the root of your project [...] You should not remove it or edit it as it can change at any time.
Instead, please use a recommended approach:
> Instead of editing next-env.d.ts, you can include additional types by adding a new file e.g. additional.d.ts and then referencing it in the include array in your tsconfig.json.
[1]: https://nextjs.org/docs/basic-features/typescript#existing-projects |
Using a *hacky* [`defaultdict`][1] :
```
from collections import defaultdict
genid = defaultdict(lambda: len(genid) + 1)
out = {
k: v if v in ("VDD", "GND")
else genid[v] for k, v in my_dict.items()
}
```
Output (*before/after*) :
```
{ # {
"1": "VDD", # "1": "VDD", # < unchanged
"2": "VDD", # "2": "VDD", # < unchanged
"7": "VDD", # "7": "VDD", # < unchanged
"0": 0, # "0": 1, # < updated : grp1
"3": 0, # "3": 1, # < updated : grp1
"4": 0, # "4": 1, # < updated : grp1
"6": 9, # "6": 2, # < updated : grp2
"13": 9, # "13": 2, # < updated : grp2
"GND": "GND", # "GND": "GND", # < unchanged
"15": "GND", # "15": "GND", # < unchanged
"12": 12 # "12": 3 # < updated : grp3
} # }
```
[1]: https://docs.python.org/3/library/collections.html#collections.defaultdict |
You certainly can use `parfor` in the functions invoked using `parfeval`. It is difficult to do this in a non-trivial manner in R2019b though. In later releases of MATLAB (>=R2020a), you can use a [thread pool][1] inside each local process worker. It's awkward to set up though, and even then there might be challenges getting everything you need running on thread-pool workers.
The approach I would explore is converting your `select_data` so that you can run it directly in chunks inside `parfeval`. I.e. instead of something like this
```matlab
function out = select_data(in)
parfor i = 1:n
out(i) = dostuff(i);
end
end
```
You somehow work out how many iterates you need and then effectively call the guts of the `parfor` loop directly from the client via `parfeval`, like this:
```matlab
for i = 1:n
fut(i) = parfeval(@dostuff, 1, i);
end
fetchOutputs(fut);
```
This also would let you use e.g. [`afterAll`][2] on the array of futures to do something else asynchronously once the work is all finished.
[1]: https://www.mathworks.com/help/parallel-computing/parallel.threadpool.html
[2]: https://www.mathworks.com/help/matlab/ref/parallel.future.afterall.html |
I'm implementing a custom WOPI host and currently is working with word, excel and power points documents. But when I try to open a visio document (vsdx extension) I'm getting the following error:
[![WOPI error opening visio documents][1]][1]
I found the following searching on the web but I was not able to solve the problem.
https://learn.microsoft.com/en-us/answers/questions/712841/is-it-visio-edit-enabled-at-office-online-cloud-fo
https://stackoverflow.com/questions/58135342/wopi-error-sorry-you-dont-have-permission-to-edit-this-document
Thanks for your help.
[1]: https://i.stack.imgur.com/tfo9F.png |
Wopi host implementation unable to open visio documents |
|visio|ms-wopi| |
You can get index of selected item and then remove that item from your list and insert that removed item into your list(now it appears as the first element in your list).
for example, selected item index is 5
myList.removeAt(5) // 5 is your selected item index
then
myList.insert(0, element) // element is type of your list(if your list type
//is string then element type will be string like "A" if it is a model
//class, then it will be model class)
**Happy Coding :)**
|
I'm normally very comfortable performing joins in my work/on online practice sets but sort of blanked when I got this question.
Here's the data: The image for the data set > (https://i.stack.imgur.com/iUmN0.png)
I was asked to perform a select * statement on the two tables, and write down the result for all 5 kinds of joins.
So basically:
select * from table_a a left join table_b b on a.column_a = b.column_b
For this I answered: 1 1 0 0 1 1 1 1 0 0 null
Can somebody tell me if the answer is wrong/right?
Also, can you please list down the output for all 5 types of joins (left, right, inner outer, cross) for this? With a good explanation
Any help would be appreciated!
Listed out my answer in the block above. |
<!-- language-all: lang-dos -->
This works:
if exist %1\* echo Directory
Works with directory names that contains spaces:
C:\>if exist "c:\Program Files\*" echo Directory
Directory
Note that the quotes are necessary if the directory contains spaces:
C:\>if exist c:\Program Files\* echo Directory
Can also be expressed as:
C:\>SET D="C:\Program Files"
C:\>if exist %D%\* echo Directory
Directory
This is safe to try at home, kids! |