instruction stringlengths 0 30k ⌀ |
|---|
I had the same problem with an IntelliJ IDE.
In my case setting `"sourceMap": true` in tsconfig.json did the trick. |
I have a constraint in a MILP formulated in pyomo.
Thats a general formulation of it:
def constraint(m, t):
return (m.y[t] <= max(0,m.x1[t] - m.x2[t]))
model.constraint_c = pyo.Constraint(model.timeindex, rule=constraint)
y, x1 and x2 are timeindexed Non Negative Real Variables.
In own words: y should be (x1-x2) only in case (x1-x2) is positive, otherwise y=0.
I found different methods for linearizing the Min/Max function but nothing fits my pupose.
Thanks a lot for your help! |
I'd like to log a value which resides in a `ScopedValue` (currently [in preview](https://openjdk.org/jeps/429) in Java 21+). I'm guessing I'd have to somehow bridge this to MDC, however all attempts fail, e.g. overwriting the `MDCAdapter` (Logback doesn't seem to use e.g. `MDCAdapter.get` to actually read the MDC's value).
The advantage of `ScopedValue`s in comparison with setting the MDC directly is that the former is inherited, which makes a lot of difference esp when a lot of virtual threads are forked from within each other. |
Logback: using a ScopedValue inside a log message |
|java|logback|mdc|virtual-threads|project-loom| |
# Update
Starting from Android Studio 2022.2.1 Device mirroring is under "Tools" menu in "Preferences" or "Settings" (For mac users).
https://stackoverflow.com/questions/75888209/how-to-show-the-screen-of-a-physical-device-inside-android-studio
# Old Answer
[Droid@Screen][1] might work for you. I've never used it on a Mac but it's just a jar so it should work.
[1]: https://github.com/ribomation/DroidAtScreen1 "Droid@Screen" |
I'm encountering an issue with Playwright while sending a POST request using the `request.post()` method. However, when I send the same request using Postman, I receive the response correctly.
Here's the error message I'm receiving:
Response:
```
{
"message" : "Required request body is missing: public org.springframework.http.ResponseEntity<org.scd.model.User>)",
"errorCode" : "BAD_REQUEST",
"validationErrors" : [ ]
}
```
Playwright code:
<!-- language: javascript -->
test("POST Create Post request", async ({ request }) => {
const raw = JSON.stringify({
"iban": "DE8123456781234567898",
"creditor": "",
"accountHolder": "Max Miller",
"signatureDate": "2024-02-21T06:21:57.306Z",
"signatureLocation": "Reynoldston",
});
const headers = {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
};
const createPostRequestUrl = 'https://test.system.companyname.io/service/v1/872f774d-12d34-67jj4-abcde-4566743450/mandate';
// Make the actual request
const response = await request.post(createPostRequestUrl, {
headers: headers,
body: raw
});
// Process the response
const responseBody = await response.text();
console.log(responseBody);
});
[](https://i.stack.imgur.com/W62T2.png)
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/p0mHQ.png |
Check if minikube is running then you can use dashboard which will give you local minikube cluster link to open in browser and verify your cluster.
minikube status
minikube dashboard
|
Above post needs two modification to make it work properly
1. Create a new pageable object with `created_at` and pass that in the native query, because native query understands table column and not the attribute of the entity class.
2. The query will again include filtered data when the post gets reported by another user.
so, correct implementation will be
String sortBy = "created_at";
Sort sort = Sort.by(sortBy).descending();
Pageable pageable = PageRequest.of(pageNumber, limit, sort);
postRepository. findAllByReportedByNullOrReportedByNot(@Param("reportedBy") String reportedBy, Pageable pageable)
Definition of the query will look like:
@Query(
value =
"SELECT DISTINCT p.* FROM posts p WHERE p.id NOT IN (SELECT DISTINCT pr.post_id FROM post_reports pr WHERE pr.reported_by = : reportedBy)",
nativeQuery = true)
Page<Post> findAllByReportedByNullOrReportedByNot(
@Param("reportedBy") String reportedBy, Pageable pageable); |
|excel|vba|outlook| |
To make the country code non-editable while showing a placeholder in `react-phone-input-2`, you've mostly got it right. However, ensure your `countryCodeEditable` prop is set to `false` as you've done. The placeholder showing after the country code and being uneditable should work with the `placeholder` prop as you've set it to 5xxxxxxxx. If the placeholder isn't showing as expected, double-check the `inputStyle` and other CSS that might be overriding the visibility of the placeholder. Also, ensure that `react-phone-input-2`'s version you're using supports these features as expected.
|
Python Code:
```python
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import base64
def encrypt_string(input_string, key_base64, str_iv):
try:
key = key_base64.encode('utf-8')
if str_iv:
iv = base64.b64decode(str_iv)
else:
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_data = pad(input_string.encode(), AES.block_size)
cipher_data = cipher.encrypt(padded_data)
combined_data = iv + cipher_data
return base64.b64encode(combined_data).decode()
except Exception as e:
print(e)
if __name__ == "__main__":
key = "1bd393e7a457f9023d9ba95fffb5a2e1"
iv = "1oTOhV9xGyu1mppmWZWa5w=="
input_string = "AAAAAAA"
encrypted_data = encrypt_string(input_string, key, iv)
print("Encrypted string:", encrypted_data)`
```
OUTPUT :
Encrypted string: 1oTOhV9xGyu1mppmWZWa5+kzveiTRzRH+gRVHx+7Ad0=
PHP code:
```php
<?php
function encrypt_string($input_string, $key_base64, $str_iv) {
try {
$key = base64_decode($key_base64);
if ($str_iv) {
$iv = base64_decode($str_iv);
} else {
$iv = openssl_random_pseudo_bytes(16);
}
$ciphertext = openssl_encrypt($input_string, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$combined_data = $iv . $ciphertext;
return base64_encode($combined_data);
} catch (Exception $e) {
echo $e->getMessage();
}
}
$key = "1bd393e7a457f9023d9ba95fffb5a2e1";
$iv = "1oTOhV9xGyu1mppmWZWa5w==";
$input_string = "AAAAAAA";
$encrypted_data = encrypt_string($input_string, $key, $iv);
echo "Encrypted string: " . $encrypted_data . "\n";
?>
```
OUTPUT:
Encrypted string: 1oTOhV9xGyu1mppmWZWa53Nc8rxWTultBWLvWitUICQ=
Please, does anyone know how to make the output of these two codes the same? |
I have the following configuration
Client(Browser) ---> Nginx ——————> Auth backend
|
————————> Protected Backend
When the browser hits Nginx for `Protected Backend`, it is directed to the Identity Provider (Azure Active Directory). The IDP then provides an authorization code in response, which the browser subsequently sends to Nginx. Nginx forwards this to the `Auth Backend`, where it is exchanged for a token. The Auth Backend responds with an access token setting it in the `Set-Cookie` header. However, Nginx omits this header when sending the response back to the client. How should I tell Nginx not to omit this header?
Nginx conf
```
upstream auth_pool {
least_conn;
server localhost:7771;
server localhost:7772;
}
server {
listen 80;
server_name _;
resolver 10.0.0.6:8600;
set $domain service.eastus-1.consul;
error_page 401 = @error401;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 100M;
proxy_hide_header 'Access-Control-Allow-Origin';
proxy_hide_header 'Access-Control-Allow-Credentials';
proxy_hide_header 'Cache-Control';
proxy_hide_header 'Pragma';
proxy_hide_header 'Expires';
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Cache-Control' 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0' always;
add_header 'Pragma' 'no-cache' always;
add_header 'Expires' '0' always;
expires -1;
proxy_no_cache 1;
proxy_cache_bypass 1;
if_modified_since off;
types_hash_max_size 4096;
location / {
auth_request /auth_backend;
auth_request_set $x_myorg_user $upstream_http_x_myorg_user;
auth_request_set $backend_status "500";
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Myorg-User $x_myorg_user;
proxy_set_header Accept-Encoding gzip;
proxy_redirect off;
proxy_pass http://localhost:8080;
}
location /auth_backend {
internal;
proxy_set_header X-Myorg-Original-Uri $request_uri;
proxy_set_header Content-Length 0;
proxy_pass_request_body off;
proxy_pass http://auth_pool;
}
location @error401 {
return 302 https://login.microsoftonline.com/xxx-xxx/oauth2/v2.0/authorize?client_id=xxx-xxx&response_type=code&redirect_uri=http://localhost&scope=openid;
}
```
|
Pyomo linearization of min(0,x1-x2) in MILP |
|linear-programming|pyomo|linearization| |
I should say first that I have found and read most (if not all) of the questions with the same error message. So far, none of lead to a solution. Most seemed to be aimed at IIS hosted apps. And the ones that are Azure hosted are old and just don't have solutions, or have dead links to old articles that no longer exist.
The error is sporadic. And, the error is happening only in Prod. We are not able to reproduce in QA or in Dev or in Local. The errors began immediately after pushing a release that contained an upgrade from .NET Framework 4.7 to .NET Framework 4.8. (No other changes in this release). So, obviously, there is some difference between QA and Prod, but so far we can't track it down.
Some of the other posts on this same error have indicated that it's a permissions issue. We have checked the permissions on everything we can think of, and they are the same between the QA and Prod. That being said, our Azure guy is (as I type) doing his best to compare everything he can think of between QA and Prod to find any differences.
Our method is generating a bar code. The error is on this line:
graphic.DrawString(string.Format("*{0}*", Code), newFont, black, point);
Here is the entire method:
*(Please note that we are aware that some of this code can be cleaned up with newer versions of C#. We're working on that!)*
public static byte[] BarcodeImageGenerator(string Code)
{
byte[] BarCode;
int Height; // = 50
int Width;// = 100
Code = Code.ToUpper();
PrivateFontCollection customfont = new PrivateFontCollection();
customfont.AddFontFile(string.Format("{0}{1}", HttpRuntime.AppDomainAppPath, "fonts\\FRE3OF9X.TTF"));
Font newFont = new Font(customfont.Families[0], 60, FontStyle.Regular);
SizeF stringSize = Graphics.FromImage(new Bitmap(1, 1)).MeasureString(Code, newFont);
Width = (int)stringSize.Width + 50;
Height = (int)stringSize.Height;
Bitmap objBitmap = new Bitmap(Width, Height);
using (Graphics graphic = Graphics.FromImage(objBitmap))
{
PointF point = new PointF(2f, 2f);
SolidBrush black = new SolidBrush(Color.Black);
SolidBrush white = new SolidBrush(Color.White);
graphic.FillRectangle(white, 0, 0, objBitmap.Width, objBitmap.Height);
graphic.DrawString(string.Format("*{0}*", Code), newFont, black, point);
}
using (MemoryStream Mmst = new MemoryStream())
{
objBitmap.Save(Mmst, ImageFormat.Jpeg);
BarCode = Mmst.GetBuffer();
return BarCode;
}
}
Here are the first few lines of the stack trace:
> System.Runtime.InteropServices.ExternalException (0x80004005): A
> generic error occurred in GDI+. at
> System.Drawing.Graphics.CheckErrorStatus(Int32 status) at
> System.Drawing.Graphics.DrawString(String s, Font font, Brush brush,
> RectangleF layoutRectangle, StringFormat format) at
> System.Drawing.Graphics.DrawString(String s, Font font, Brush brush,
> PointF point)
|
I'm trying to setup SMTP for Kiwi TCMS. When trying to send a test email I'm getting a long error and at the bottom it says OSError: \[Errno 99\] Cannot assign requested address
Here is the SMTP setup on the common.py file:
```
SERVER_EMAIL = DEFAULT_FROM_EMAIL = 'emailaddress'
EMAIL_SUBJECT_PREFIX = "[Kiwi-TCMS] "
```
```
# SMTP specific settings
EMAIL_HOST = 'smtp.office365.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'emailaddress'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = True
```
I have tried restarting the container and recreating the container |
**EDIT**
Asof @BigBen comment rephrased the answer.
The faulty code is that if you want to copy the entire row, but the target is not cover an entire row. Therefore try this:
````
myCell.EntireRow.Copy Worksheets("TestSheet").Range("B" & Rows.Count).End(xlUp)(2).EntireRow
````
If you want to paste in the first empty row use the `Offset`
````
myCell.EntireRow.Copy Worksheets("TestSheet").Range("A" & Rows.Count).End(xlUp).Offset(1)
````
If in the original range there are formulas and you need only the values either use only absolute references, or cannot directly copy/paste the range. Then as you solved has to use `PasteSpecial`
````
myCell.EntireRow.Copy
Worksheets("TestSheet").Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial(xlPasteValues)
````
|
|html|css|flexbox|pseudo-element| |
{"Voters":[{"Id":20643658,"DisplayName":"Black cat"}]} |
From the [*Guards* section of the The Gleam Language Tour][1]:
[1]: https://tour.gleam.run/flow-control/guards/
> Only a limited set of operators can be used in guards, and **functions cannot be called at all**.
This restriction of not calling functions in guards is to avoid side effects in pattern matching since any function may be impure, e.g., it can perform an I/O operation.
You can just pattern-match again on the result of `function(h)`:
pub fn filter(list: List(a), function: fn(a) -> Bool) -> List(a) {
case list {
[] -> []
[h, ..t] -> case function(h) {
True -> [h, ..filter(t, function)]
False -> filter(t, function)
}
}
} |
I have a Windows Forms application VS2010 C# which displays a MessageBox with an OK button.
How can I make it so that, if the user walks away, the message box automatically closes after a timeout of, say, 5 seconds? |
I run Linux Mint 21.3 x86_64, I use the Eclipse IDE (version 2023-12 (4.30.0)) for Java development. I have a Java application (Eclipse Scout) that was working until this morning.
I tried to run the application from the IDE by clicking on the icon ***Run -> [webapp] all***. This has always worked before by launching a Jetty server and a URL for accessing the application BUT now, a dialog is displayed saying:
> *"Launching [webapp] all" has encountered a problem*
When I click the details button in the dialog box, I get the following message/explanation:
> *Exception occurred executing command line.
Cannot run program "/home/jd/eclipse-scout-workspace/ygapp/ygapp/run-configs/js build.sh" (in directory "/home/jd/eclipse-scout-workspace/ygapp/ygapp.ui.html"): error=13, Permission denied*
I have no idea why suddenly the **js build.sh** is behaving like this. I have read/write access to the file, so I am a bit confused. I've updated the project ***Maven -> Update Project*** several times but the problem persists.
Can anyone please help me resolve this problem?
|
setState will update the variable on the next rerender.
Try this:
```
function App() {
const [userData, setData] = useState([]);
const getData = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await res.json();
setData(data);
};
console.log(userData);
return (
<>
<button onClick={getData}>get data</button>
<div>
{userData?.map((user) => {
return (
<p key={user.id}>
{user.name} {user.email}
</p>
);
})}
</div>
</>
);
}
export default App;
``` |
Set-Cookie header not forwarded by nginx to the client |
|authentication|nginx|authorization|webapi| |
Once it reaches `DB::commit`, it throws an error. However, if I comment out the `Schema::table` code, it works in PHP 8.3. In PHP 7.3, it still works as expected.
```
try {
DB::beginTransaction();
// sm model::create() operations
if(!empty($table)){
Schema::table($table, function (Blueprint $table) use ($newProfileField) {
$column_type = isset($newProfileField->fieldType) ? $newProfileField- >fieldType->sql_column_type : 'string';
$table->$column_type($newProfileField->field_name)->nullable();
});
}
DB::commit();
}
catch(Exception $ex) {
DB::rollback();
}
```
This is happening once I upgraded my PHP version to 8.3
PDOException. There is no active transaction.
|
|excel|vba|outlook| |
It is actually just a curiosity, but here's how I came up with it.
#### tl;dr
I could have wondered how to write a sensible `Enum` `instance` for a type larger than `Int`, say `(Int, Int)`.
#### A bit longer
But actually I was wondering: why does `Enum`'s minimal definition assumes that the possible values of `Int` are enough to enumerate the type of which I want to write the `Enum` class?
At [`fromEnum`](https://hackage.haskell.org/package/base-4.19.1.0/docs/Prelude.html#v:fromEnum) I do read that
> Convert to an `Int`. It is implementation-dependent what `fromEnum` returns when applied to a value that is too large to fit in an `Int`.
which I interpret as saying that I _can indeed_ define an `Enum` class for a type that doesn't fit `Int`. I just have to accept that I'll have to return nonsense form `fromEnum` for some values of my type.
But how could `succ` and `pred` possibly work with such a broken type, given [their implementations](https://hackage.haskell.org/package/base-4.19.1.0/docs/src/GHC.Enum.html#succ) use `toEnum` and `fromEnum`?
```haskell
succ = toEnum . (+ 1) . fromEnum
pred = toEnum . (subtract 1) . fromEnum
```
Or maybe I should define manually `succ` and `pred` so that they don't make use `toEnum`/`fromEnum`?
But if that's the case, then way isn't `succ`&`pred` a minimal definition?
Yes, I have read the comment from [dfeuer](https://stackoverflow.com/users/1477667/dfeuer) [here](https://stackoverflow.com/questions/35119428/how-can-integer-have-an-instance-of-enum-toenum-and-fromenum-only-use-int-whic), and [the answer](https://stackoverflow.com/a/35119484/5825294), but the question remains as to why I need to define `fromEnum`/`toEnum`.
---
#### The origin of the question (in case you have spare suggestions)
I was using [`Word32`](https://hackage.haskell.org/package/base-4.19.1.0/docs/Data-Word.html#t:Word32), but then it took me quite a while to undertand the reason of a but in my program. Essentially, quite a good chunk of my logic was assuming that the value of `Word32`s is not `0`.
Therefore, I thought of using a more appropriate data type implementing appropriate `class`es. I came across [`Integer.Positive`](https://hackage.haskell.org/package/integer-types-0.1.4.0/docs/Integer-Positive.html), but that's only [`BoundedBelow`](https://hackage.haskell.org/package/integer-types-0.1.4.0/docs/Integer-BoundedBelow.html#t:BoundedBelow), not [`Bounded`](https://hackage.haskell.org/package/base-4.19.1.0/docs/Prelude.html#t:Bounded), whereas `Word32` is `Bounded`, so I decided to write a `data`type myself and came up with a module like this:
```haskell
module Positive32 (Positive32, positive32, getNum) where
import Data.Word (Word32)
newtype Positive32 = Positive32 { getNum :: Word32 } deriving (Enum, Eq, Ord, Show)
instance Bounded Positive32 where
minBound = Positive32 1
maxBound = Positive32 (maxBound :: Word32)
positive32 :: Word32 -> Positive32
positive32 0 = error "Attempt to create `Positive32` from `0`"
positive32 i = Positive32 i
```
so that
```haskell
λ> minBound :: Positive32
Positive32 {getNum = 1}
λ> positive32 2
Positive32 {getNum = 2}
λ> positive32 0
Positive32 {getNum = *** Exception: Attempt to create `Positive32` from `0`
CallStack (from HasCallStack):
error, called at ......
```
However, soon I realized that, even though I have not exported `Positive32`'s constructor, I can still create `Positive32 0` via its derived `Enum` instance:
```haskell
λ> pred $ minBound :: Positive32
Positive32 {getNum = 0}
```
Hence I tried to write the `Enum` instance myself, think it would have a minimal definition [`succ :: a -> a`](https://hackage.haskell.org/package/base-4.19.1.0/docs/Prelude.html#v:succ) and [`pred :: a -> a`](https://hackage.haskell.org/package/base-4.19.1.0/docs/Prelude.html#v:pred), but in reality it requires [`toEnum :: Int -> a`](https://hackage.haskell.org/package/base-4.19.1.0/docs/Prelude.html#v:toEnum) and [`fromEnum :: a -> Int`](https://hackage.haskell.org/package/base-4.19.1.0/docs/Prelude.html#v:fromEnum).
Now, in my specific usecase, that poses no problem, because `Word32` fits in `Int`, so I can't possibly overflow `Int` with `Word32`, but I'm still left puzzled with the question of why I can't have an `Enum` for types that have more possible values than `Int`. |
Why does Enum require to implement toEnum and fromEnum, if that's not enough for types larger than Int? |
|haskell|enums|functional-programming|typeclass|bounded-types| |
I get the following errors when republishing the image I took with ros2 run ffmpeg.;
ros2 run image_transport republish ffmpeg in/ffmpeg:=image_raw/ffmpeg raw out:=image_raw/uncompressed --ros-args -p "ffmpeg_image_transport.map.hevc_rkmpp:=hevc"`
terminate called after throwing an instance of 'image_transport::TransportLoadException'
what(): Unable to load plugin for transport 'image_transport/ffmpeg_sub', error string:
According to the loaded plugin descriptions the class image_transport/ffmpeg_sub with base class type image_transport::SubscriberPlugin does not exist. Declared types are image_transport/compressedDepth_sub image_transport/compressed_sub image_transport/raw_sub image_transport/theora_sub
[ros2run]: Aborted
I don't want to replace the parameters specified in the errors. I want to do this with ffmpeg. how can i fix this
After running ros2, I want to list the topics, echo them and view them with rviz2 and image uncompressed.Afterwards, I want to use and show this uncompressed image in my Python detection project.
|
Once it reaches `DB::commit`, it throws an error. However, if I comment out the `Schema::table` code, it works in PHP 8.3. In PHP 7.3, it still works as expected.
```
try {
DB::beginTransaction();
// performing some model::create() operations
if(!empty($table)){
Schema::table($table, function (Blueprint $table) use ($newProfileField) {
$column_type = isset($newProfileField->fieldType) ? $newProfileField- >fieldType->sql_column_type : 'string';
$table->$column_type($newProfileField->field_name)->nullable();
});
}
DB::commit();
}
catch(Exception $ex) {
DB::rollback();
}
```
This is happening once I upgraded my PHP version to 8.3
PDOException. There is no active transaction.
|
I have a list `List<IVehicle> vehicles = new List<IVehicle>();` and in that list I want to store objects (`Car`, `Boat`, `Mc`) that implement `IVehicle`.
How can I print out how many objects of ex car I have in the list?
I tried using LINQ `int count = vehicles.Count(x => x == car);` but it does now count correct. |
Kiwi TCMS - Test Email failing |
|kiwi-tcms| |
null |
**EDIT**
____
Working solution found. See **NEW SECTION** below.
____
Original Question:
Trying to make a classic function to call a file, read a csv, ask the user which columns to keep, and then return the resulting minimized dataframe.
The outcome is that the dialog works, but it doesn't update the result of the table. It just outputs the whole table as if the user did not do anything.
I've tried using goroutines to block execution, but then the dialog wouldn't work either. In fact, the whole program froze permanently.
If you have done something like this before, don't bother reading what I did and trying to correct it, feel free to just tell me how you might handle it.
(Related: I've checked https://stackoverflow.com/questions/68738840/main-not-waiting-for-update-of-file-dialog-in-golang-using-fyne-for-file-dial but I don't know how I could do a direct `Set()` here given the more complex return types.)
Here's what I've got:
```
func callFile(path string, w2 fyne.Window) (*widget.Table, *dataframe.DataFrame) {
file, err := os.Open(path)
if err != nil {
fmt.Println(err)
return nil, nil
}
csvDf := dataframe.ReadCSV(file)
NewDF := csvDf.Select(csvDf.Names())
table := widget.NewTable(
//[REMOVED TO SHORTEN THE POST]
)
//THIS NEXT SECTION IS ONLY RELEVANT TO MAKING THE DIALOG UI TEXT. FEEL FREE TO SKIP
---------------
coln := csvDf.Names()
typn := []string{}
for _, colName := range coln {
currcol := csvDf.Col(colName)
// Get the data type of the column
typn = append(typn, fmt.Sprint(currcol.Type()))
}
----------------
checks := []*widget.FormItem{}
boundChecks := make(map[string]bool)
for i, v := range coln {
//making the specific key for the column
staticref := v + " (" + fmt.Sprint(typn[i]) + ")"
boundChecks[staticref] = true
tempFI := widget.NewFormItem(staticref,
widget.NewCheck("", func(value bool) {
boundChecks[staticref] = value
}))
checks = append(checks, tempFI)
}
columnsToKeep := []string{}
dialog.ShowForm("Smart Select", "That should do it", "Close", checks, func(b bool) {
if b {
for i, v := range coln {
staticref := v + " (" + fmt.Sprint(typn[i]) + ")"
keep := boundChecks[staticref]
if keep {
// if the user checked this box
columnsToKeep = append(columnsToKeep, v)
}
}
NewDF = csvDf.Select(columnsToKeep)
table = ... // make the table again with NewDF instead of csvDf
} else {
// if the user doesn't check any boxes then all the columns will be selected
}
}, w2)
return table, &NewDF
}
```
**NEW SECTION**
____
A working solution using data bindings worked here, but that might not be the best solution. It takes in an untyped list data binding. That gets initialized as:
```
BT := binding.NewUntypedList()
var BTinit []interface{}
BT.Set(BTinit)
```
Then the callFile function is handled as:
```
// add a listener to respond to do whatever you want with the dataframe that
// the callFile function will return
nbt := binding.NewDataListener(func() {
currBT, emptyError := BT.Get()
if emptyError == nil && len(currBT) > 0 {
switch dfpInter := currBT[0].(type) {
case *widget.Table:
switch DFInter := currBT[1].(type) {
case dataframe.DataFrame:
//do whatever you want with your dataframe DFInter
}
default:
fmt.Println("for some reason it didn't return a dataframe")
}
}
})
BT.AddListener(nbt)
callFile(FPATH, w2, BT)
```
Now actually make the dialog that lets the user open the file and pick their data:
```
func callFile(path string, w2 fyne.Window, BT binding.UntypedList) {
// Open the file at the given path
file, err := os.Open(path)
if err != nil {
fmt.Println(err)
return
}
// Read the CSV file into a dataframe
csvDf := dataframe.ReadCSV(file)
// Determine the data types of each column in the dataframe
coln := csvDf.Names()
typn := []string{}
for _, colName := range coln {
currcol := csvDf.Col(colName)
typn = append(typn, fmt.Sprint(currcol.Type()))
}
// Create checkboxes for each column to allow the user to select which columns to keep
checks := []*widget.FormItem{}
boundChecks := make(map[string]bool)
for i, v := range coln {
staticref := v + " (" + fmt.Sprint(typn[i]) + ")"
boundChecks[staticref] = false
this_check := widget.NewCheck("", func(value bool) {
boundChecks[staticref] = value
})
if i == 0 {
this_check.SetChecked(true)
}
tempFI := widget.NewFormItem(staticref, this_check)
checks = append(checks, tempFI)
}
// Show a dialog to the user to select which columns to keep
dialog.ShowForm("Select the columns you are interested in", "That should do it", "Close", checks, func(b bool) {
if b {
columnsToKeep := []string{}
for i, v := range coln {
staticref := v + " (" + fmt.Sprint(typn[i]) + ")"
keep := boundChecks[staticref]
if keep {
columnsToKeep = append(columnsToKeep, v)
}
}
NewDF := csvDf.Select(columnsToKeep)
// Create a table widget to display the selected columns
table := widget.NewTable(
func() (int, int) {
return NewDF.Nrow() + 1, NewDF.Ncol()
},
func() fyne.CanvasObject {
return widget.NewLabel("December 15")
},
func(i widget.TableCellID, o fyne.CanvasObject) {
if i.Row == 0 {
o.(*widget.Label).SetText(NewDF.Names()[i.Col])
o.(*widget.Label).Alignment = fyne.TextAlignCenter
} else {
colName := NewDF.Names()[i.Col]
txt_0 := NewDF.Col(colName).Subset(i.Row - 1).String()
txt_0 = txt_0[1:]
txt_0 = txt_0[:len(txt_0)-1]
o.(*widget.Label).SetText(txt_0)
}
},
)
// Update the binding with the table and the new dataframe
BT.Set([]interface{}{table, NewDF})
}
}, w2)
}
```
This is different than the original solution in that it doesn't recreate the table but instead waits for the user to pick the columns of data that they want before creating it.
|
I found a solution which worked for me . Give it a try if it works !!.
Go to index.js file and replace <React.StrictMode> to <BrowserRouter>
Attached the snippet for reference.
Good Luck [enter image description here][1]
[1]: https://i.stack.imgur.com/XMtZe.png |
Checking a float-like type with
isinstance(x, float)
or
type(x) is float
will return `False` if the type is not exactly a float, but, for example, a numpy.float32:
import pandas as pd
import numpy as np
x = pd.Series([0.2], dtype=np.float32)[0]
As pointed out in [a comment of this thread][1], numpy's `issubdtype` can be used for this purpose.
**To detect float-like types:**
np.issubdtype(type(x), np.floating)
- returns True for `2.0`, `pd.Series([2.0], dtype=np.float32)[0]`, and generally any float, np.float32, np.float64, ... type
- returns False for `2`, `"2.0"` (string), `[2.0, 1.2]` (list), and the like
**To detect numeric (float- and int-like) types:**
np.issubdtype(type(x), np.number)
- returns True for `2`, `2.0`, `pd.Series([2.0], dtype=np.float32)[0]`, `pd.Series([2.0], dtype=np.int32)[0]`, and generally any float, np.float32, np.float64, ... type
- returns False for `"2"` (string), `[2.0, 1.2]` (list) and the like
[1]: https://stackoverflow.com/questions/28292542/how-to-check-if-a-number-is-a-np-float64-or-np-float32-or-np-float16#comment120383989_28293294 |
This is my Gmail SMTP Sample with Google Xoauth2 using the Google .net client library
// Copyright 2023 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
var to = "XXXX@gmail.com";
// TODO: figure out how to get the users email back from the smtp server without having to request the profile scope.
var from = "XXXX@gmail.com";
var path = @"C:\Development\FreeLance\GoogleSamples\Credentials\Credentials.json";
var scopes = new[] { "https://mail.google.com/" }; // You can only use this scope to connect to the smtp server.
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(path).Secrets,
scopes,
"GmailSmtpUser",
CancellationToken.None,
new FileDataStore(Directory.GetCurrentDirectory(), true)).Result;
var message = new EmailMessage()
{
From = from,
To = to,
MessageText = "This is a test message using https://developers.google.com/gmail/imap/xoauth2-protocol",
Subject = "Testing GmailSMTP with XOauth2"
};
try
{
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 465, true);
var oauth2 = new SaslMechanismOAuth2 (message.From, credential.Token.AccessToken);
await client.AuthenticateAsync (oauth2, CancellationToken.None);
client.Send(message.GetMessage());
client.Disconnect(true);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
public class EmailMessage
{
public string To { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string MessageText { get; set; }
public MimeMessage GetMessage()
{
var body = MessageText;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("From a user", From));
message.To.Add(new MailboxAddress("To a user", To));
message.Subject = Subject;
message.Body = new TextPart("plain") { Text = body };
return message;
}
}
You need to figure out DKIM the part on your own I have not configured that on my workspace account there are a few questions on stack that might help [C# DKIM gmail site:stackoverflow.com](https://www.google.com/search?q=C%23+DKIM+gmail+site:stackoverflow.com&sca_esv=a6f2d24d067aab7e&sxsrf=ACQVn0-F1j-irYPryqn5NKsOCiIsEoxayA:1710514208107&sa=X&ved=2ahUKEwi5lof-wfaEAxXfhP0HHRsgBdwQrQIoBHoECCkQBQ&biw=1731&bih=1137&dpr=1)
|
How do list all keys including disabled from Azure Key vault |
|azure|azure-keyvault| |
Have just come across a problem where I believe this is the solution.
At the moment I have the following code:
function siteUsers()
{
global $database;
$q = "SELECT username, id FROM ".TBL_USERS."";
return mysql_query($q, $this->connection);
}
function generateUserArray()
{
$u = array();
$i = array();
$result = $this->siteUsers();
while( $row=mysql_fetch_assoc($result))
{
$u[] = $row['username'];
$i[] = $row['id'];
}
return $u, $i;
}
As you can see, when I then go onto use foreach, the `$u` and `$i` get split apart.
Is there anyway that I could keep them together?
foreach ($u as $username) {
echo"<option value='$i'>$username</option>";
}
What I need it the option value to be the id and the visual value to be the username.
Is this possible? |
Return two separate columns of data from a function |
null |
You can use a `RoundedRectangle` to provide the base shape, then the sides can be hidden using blocks of the same Color and blend mode `.destinationOut`. For the thin line that goes all the way round, just paint another `RoundedRectangle` on top.
This shape can be applied as an overlay over the image. It is important that `.compositingGroup()` or `.drawingGroup()` is then applied to the group, so that the blend mode doesn't take effect for the underlying image too.
```swift
Image(systemName: "lizard.fill")
.resizable()
.scaledToFit()
.padding(6)
.frame(width: 200, height: 250)
.foregroundStyle(.orange)
.background(.blue)
.overlay {
ZStack {
RoundedRectangle(cornerRadius: 10)
.stroke(.white, lineWidth: 2)
.padding()
Color.white
.padding(.vertical, 40)
.blendMode(.destinationOut)
Color.white
.padding(.horizontal, 40)
.blendMode(.destinationOut)
RoundedRectangle(cornerRadius: 10)
.stroke(.white.opacity(0.2), lineWidth: 1)
.padding()
}
.compositingGroup() // or .drawingGroup()
}
```
 |
I have HTML table with following structure:
```
<table>
<thead>..</thead>
<tbody>
<tr class="certain">
<td><div class="that-one"></div>some</td>
<td>content</td>
<td>etc</td>
</tr>
several other rows..
<tbody>
</table>
```
And I am trying to figure out what to do with the `<div class="that-one">` (or any other element, if needed) inside the table so it can be painted outside the table.
I have tried negative left property, transform: translateX(-20px) and overflow: visible.
I know that there is something different with rendering HTML tables. I cannot change structure of the table just can add whetever element inside.
Finding: both negative left property and transform: translateX(-20px) work in Firefox but dont work in Chrome (behaves like overflow: hidden).
Have some Javascript workaround on my mind, but would rather stay without it.
Also, I dont want it as CSS pseudoelement, because there will be some click event binded. |
In such cases `for` loops can be much faster.
> for (s in seq_along(my_list)) {
+ x <- my_list[[s]]
+ if ('col3' %in% names(x)) {
+ x$col3[is.na(x$col3) & x$col1 %in% c('v2', 'v3')] <- 'VAL'
+ my_list[[s]] <- x
+ }
+ }
> my_list
[[1]]
col1 col2 col3 col4
1 v1 wood cup <NA>
2 v2 <NA> VAL pear
3 v3 water fork banana
4 v2 <NA> VAL <NA>
5 v1 water <NA> apple
[[2]]
col1 col2 col4
1 v1 wood <NA>
2 v2 <NA> pear
[[3]]
col1 col3 col4
1 v1 cup <NA>
2 v2 VAL pear
3 v3 VAL banana
4 v3 VAL <NA>
## Benchmark
Runs 80% faster, which is quite significant. Demonstrated on a list with just 1,000 elements.
$ Rscript --vanilla foo.R
Unit: milliseconds
expr min lq mean median uq max neval cld
floop 18.84617 19.95898 22.17803 22.08178 24.21662 27.02679 100 a
lapply 100.05645 106.24458 111.66269 111.17931 116.06089 150.08886 100 b
*Benchmark code*
set.seed(42)
big_list <- my_list[sample(1:3, 1e3, replace=TRUE)]
microbenchmark::microbenchmark(
floop={
for (s in seq_along(big_list)) {
x <- big_list[[s]]
if ('col3' %in% names(x)) {
x$col3[is.na(x$col3) & x$col1 %in% c('v2', 'v3')] <- 'VAL'
big_list[[s]] <- x
}
}
big_list
},
lapply=lapply(
big_list,
\(x) if ('col3' %in% names(x)) {
transform(x, col3=replace(col3,
is.na(col3) & col1 %in% c('v2', 'v3'),
'VAL'))
} else {
x
}),
check='identical')
----
*Data:*
> dput(my_list)
list(structure(list(col1 = c("v1", "v2", "v3", "v2", "v1"), col2 = c("wood",
NA, "water", NA, "water"), col3 = c("cup", NA, "fork", NA, NA
), col4 = c(NA, "pear", "banana", NA, "apple")), class = "data.frame", row.names = c(NA,
-5L)), structure(list(col1 = c("v1", "v2"), col2 = c("wood",
NA), col4 = c(NA, "pear")), class = "data.frame", row.names = c(NA,
-2L)), structure(list(col1 = c("v1", "v2", "v3", "v3"), col3 = c("cup",
NA, NA, NA), col4 = c(NA, "pear", "banana", NA)), class = "data.frame", row.names = c(NA,
-4L))) |
[file routing here](https://i.stack.imgur.com/ea8I7.png)
Every Page generated from static routes works fine on vercel but not the one from [slug] page js
`{workshops.map((workshop) => (<Link href={`/workShops/${workshop.title}`} key={workshop.id} passHref>
<PersonalCard workshop={workshop} /></Link>))}`
here is the link.workshops are from dummy data here.
`const SingleWorkshopPage = ({ params }) => {const { slug } = params; const workshop = workshops.find((w) => w.title === slug); return <PersonalCardPage title={workshop.title}></PersonalCardPage>};`
and this is the singlePage.
I have been searching for something sprcific but i haven't found anything yet.
The problem is that it works on localhost but on vercel all the other pages are ok except from this one from the slug.It dows not throw any errors however it just directs me to homepage.
params are all ok as far as i can understand. It is the first time deploy something using next 14 on vercel so i can't figure it out.Any help would be highly appreciated.Thnks!!! |
The new operator in C++ performs the following actions:
1. Allocates Memory: It allocates memory on the heap for a single object or an array of objects. The amount of memory allocated is enough to hold the object(s) of the specified type.
2. Initializes Object(s): After allocating memory, new initializes the object(s) by calling their constructor(s). For a single object, it calls the constructor directly. For an array of objects, it calls the constructor for each object in the array.
3. Returns a Pointer: It returns a pointer of the object's type that points to the first byte of the allocated memory where the object is stored. For an array, it returns a pointer to the first element of the array.
Whether a pointer has been returned, but the constructor has not fully executed with out-of-order execution of CPU
```
class Singleton
{
private:
static Singleton * pinstance_;
static std::mutex mutex_;
protected:
Singleton()
{
//
}
~Singleton() {}
public:
Singleton(Singleton &other) = delete;
void operator=(const Singleton &) = delete;
static Singleton *GetInstance();
};
Singleton* Singleton::pinstance_{nullptr};
std::mutex Singleton::mutex_;
Singleton *Singleton::GetInstance(const std::string& value)
{
if (pinstance_ == nullptr)
{
std::lock_guard<std::mutex> lock(mutex_);
if (pinstance_ == nullptr)
{
pinstance_ = new Singleton();
}
}
return pinstance_;
}
```
Thread A executes the new operator after getting the lock, and does not complete the constructor function, but the pointer has pointed to the requested memory. At this time, thread B comes in and finds that the pointer is not NULL in the first if judgment, and uses the pointer for subsequent processing
Is the above situation possible in the case of multithreading ? |
|c++|singleton|cpu|cpu-architecture|new-operator| |
Note: I am by no means a coder, but this is just a task I have been assigned. Any help is greatly appreciated.
The software outputting on port 2000 is a flight simulator, which automatically outputs flight data in some sort of encoding.
The code I am using to receive the data is in Python.
```
import socket
import logging
import os
def portLogger(port):
# Configure logging
logging.basicConfig(filename=f'LOGS\\test_from_port_{port}.txt', level=logging.INFO, format='%(message)s')
# Specify the host and port to connect to
host = 'localhost' # Change this to the appropriate host
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
client_socket.connect((host, port))
# Receive data from the server and log it
while True:
data = client_socket.recv(1024) # Adjust the buffer size as needed
if not data:
break
decoded_data = data
logging.info(decoded_data)
print(decoded_data)
# Close the socket
client_socket.close()
if __name__ == '__main__':
port = input('Enter port number: ')
portLogger(int(port))
```
An example of data that I receive is as follows:
b'Z\\xa5\\xff\\xfe\\x13\\x83\\x00\\x00\\x00\\x00\\x03\\x00\\xe6\\x8b\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xbf\\x16\\x08\\xab\\xc1;\\xff\\xb1\\x00\\x1e\\xff\\xd3\\x00K\\x00\\x00\\xf8G\\xf8\\x16\\xfab\\x0f\\xf9g\\xd4\\x00\\n\\x00\\x19\\xff\\xf4\\x02X\\x008\\x00\\x08\\x00\\x00\\x00\\x07H\\xd5\\x00\\x00d\\x01\\xe4\\x80\\xf1"\\xa0\\x05Ef\\xfe\\x07\\xa0O\\x00\\x14d\\xf1\\x07\\x13\\x7f'\\xe7z\\xfd\]\\x01\\xdc\\xee\\x00!J\\x00\\x00\\x00\\x01\\x00\\x02\\xe0\\x00\\t\\x01\\x0f\\x0f\\x12\\xfa\\x00\\x12\\x01\\x95g\\xc2\\x07\\x90\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xbf\\x16\\x08\\x8e\\xc1=\\x00$\\x00\\x1b\\xff\\xd3\\x00R\\xff\\xfc\\xf8J\\xf8\\x14\\xfac\\x0f\\xf9g\\xde\\x00\\n\\x00\\x19\\xff\\xf4\\x02X\\x008\\x00\\x04\\x00\\x00\\x00\\x07H\\xd5\\x00\\x00d\\x01\\xe4\~/\\x86\\xa0\\x05\\x1d#\\x00\\x02\\x00\\x08\\x00!J\\xe0\\x00\\xfc\\x00\\x10\\x0c\\x00\\x03\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x16\\xa8\\x06\\x01\\x00\\x00d\\xe2\\xa0\\x05Ef\\xfe\\x07\\xa0O\\x00\\x14e\\xb9\\x07\\x13\\x7f'\\xe7z\\xfd\]\\x01\\xd8\\t'
and
b"Z\\xa5\\xff\\xfe\\x13\\x83\\x00\\x00\\x00\\x00\\x03\\x00\\xe6\\x8b\\xdc\\xed\\x00!J\\x00\\x00\\x00\\x02\\x00\\x02\\xe0\\x00\\t\\x01\\x0f\\x0f\\x13\\xc2\\x00\\x1a\\x01\\x96g\\xc9\\x07\\x91\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xbf\\x16\\x08\\xbd\\xc19\\xff\\xd2\\x00\\x0e\\x00\\x17\\x00Q\\xff\\xf2\\xf8J\\xf8\\x17\\xfac\\x0f\\xf7g\\xd4\\x00\\n\\x00 \\xff\\xfa\\x02X\\x00C\\x00\\x04\\x00\\x00\\x00\\x0fH\\xd5\\x00\\x00d\\x01\\xe4}0\\xa8\\xa0\\x05Ef\\xfe\\x07\\xa0O\\x00\\x14f\\x81\\x07\\x13\\x7f'\\xe7z\\xfd^\\x01\\xdc\\xed\\x00!J\\x00\\x01\\x00\\x04\\x00\\x02\\xe0\\x00\\t\\x01\\x0f\\x0f\\x14\\x8a\\x00\\x13\\x01\\x93g\\xc7\\x07\\x93\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xbf\\x16\\x08\\x98\\xc1:\\xff\\xdc\\xff\\xf9\\xff\\xf1\\x00J\\xff\\xf7\\xf8H\\xf8\\x10\\xfaj\\x0f\\xf9h\\n\\x00\\n\\x00\\x19\\xff\\xf4\\x02X\\x008\\x00\\x04\\x00\\x00\\x00\\x07H\\xd5\\x00\\x00d\\x01\\xe4\\x80\\xff\\xd7\\xa0\\x05Ef\\xfe\\x07\\xa0O\\x00\\x14gI\\x07\\x13\\x7f'\\xe7z\\xfd^\\x01\\xdc\\xed\\x00!J\\x00\\x03\\x00\\x04\\x00\\x02\\xe0\\x00\\t\\xba\\xf4"
I have tried various methods of decoding, such as UTF-8, ASCII, and Latin-1, but I have no idea how to turn this data into usable data. It is supposed to give telemetry data from the software, such as latitude, longitude, Airspeed, and various other data values. An example of what I would like to receive is something along the lines of this:
> 5987161 2024 3 21 19 53 9.09 0.5755009939 -1.9944146531 218.100000 1.470000 2.160000 0.050000 2.612757 0.973240 0XE000 11.690000 0.278000 4.960000 0.120000 0 0 0 0 0 42.000000 213.119995 0.360997 28.000000 99334.000000 0.075031 0.069200 0.053800 0.022800 -0.105000 0.445000 -9.974999 0.002300 0.077800 0.871500 0.860900 0.150000 2368 0 136.500000 1026.000000 0.000000 0.000000 100 -59 0.002500 -0.002500 0.062300 0.106500 0.000800 0.403100 0.050700 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.009000 0.012000 0.002000 0.000000 0.000000 -0.150000 174.199997 -166.800003 396.399994 OFF 3 0 1.00 ON 92 0 AUTO 29.003012 AUTO 519.000000 AUTO 0.000000 AUTO 0.174533 AUTO -0.103410 AUTO -0.257222 AUTO 0.000000 OFF 0.000000 B 27757.049634 415.058652 1310.869939 2.301440 -1.236936 -0.048633 1.000000 4666.632324 3903.174316 3477.648438 GPSINS 1 1 1 1 1 1 1 1 1 1 1 1 2306 417189091 NA NA NA NA NA NA NA NA NA NA NA NA 0.0000000000 0.0000000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0X6008 -54 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 0x0 100.0 16.6 100.0 16.8
Please let me know if you could help or if you need more information to help me out. Really appreciate it! |
I have data coming through port 2000 on my computer from a simulator software. How can I convert the raw data to usable data? |
|python|telemetry|bytestream| |
null |
If I read your requirements as:
*select any text node that is a* child *of `u` (i.e. not inside another element such as `desc` or `del`), but exclude text nodes that are in-between two `anchor` elements*
then I arrive at the following expression:
//u/text()[not(preceding-sibling::*[1][self::anchor] and following-sibling::*[1][self::anchor])]
Applying it to the given input produces:
"
I want this but
**
I want this
"
which is different from the output you *say* you want, but nevertheless conforms to the stated requirements.
|
In an HTML document, suppose I have something like a link that starts after another non-whitespace character, e.g.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
p {
max-width: 140px;
}
<!-- language: lang-html -->
<p>This is some text that includes a link (<a href="https://example.com">example</a>)</p>
<!-- end snippet -->
If the viewport width is such that the line has to break in the middle of the first word of the link text, then the preceding character (the opening parenthesis, in this case) "sticks" to the link, i.e. the standard layout algorithm breaks the line at the closest preceding whitespace.
However, if I want to insert an SVG icon at the start of the `a` element:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
p {
max-width: 140px;
}
<!-- language: lang-html -->
<p>This is some text that includes a link (<a href="https://example.com"><svg style="height: 1em; color: green;" viewbox="0 0 10 10" fill="currentColor"><circle cx="5" cy="5" r="5" /></svg>example</a>)</p>
<!-- end snippet -->
Then the line is now allowed to break either side of the SVG.
## Question
Is there any way to make the layout engine treat the svg the same as it would normal text characters, so that the open parenthesis still "sticks" to the link text?
I can't make the whole paragraph or the whole link `white-space: nowrap` - I _want_ the text to be able to wrap normally both within and outside the link, I just need it _not_ to break around the `<svg>` (unless the link as a whole is preceded by whitespace). Basically I want to be able to insert an icon at the start of the link without interfering with the normal text layout behaviour, as if the icon were just another character with all the same Unicode properties as the first character of the existing link text.
Is this possible?
[1]: https://i.stack.imgur.com/hTZej.png
[2]: https://i.stack.imgur.com/K8MCt.png |
Next 14 App Router pages from dynamic routes not generating when deployed on vercel but only work on localhost |
|deployment|vercel|production|app-router|nextjs-dynamic-routing| |
null |
The issue is caused by a malformed request URL.
To run the GET function you must be request with GET method.
Example:
const getBookings = async () => {
try {
const res = await fetch('http://<your-site-host>/api/v1/bookings',{
method: 'GET',
headers: {
'content-type': 'application/json'
}
})
if(res?.ok){
console.log(res)
}else{
console.log("Oops! Something is wrong.")
}
} catch (error) {
console.log(error)
}
}
Your logs contains a item with a GET method request to **/api/v1/bookings/get** but to correct path is **/api/v1/bookings**
[For more examples please look for official docs.](https://nextjs.org/docs/app/api-reference/file-conventions/route) |
I am trying to convert some R code I've written into an R shiny app so others can use it more readily. The code utilizes a package called `IPDfromKM`. The main function of issue is `getpoints()`, which in R will generate a plot and the user will need to click the max X and max Y coordinates, followed by clicking through the entire KM curve, which extracts the coordinates into a data frame. However, I cannot get this to work in my R shiny app.
There is a [link ](https://biostatistics.mdanderson.org/shinyapps/IPDfromKM/)to the working R shiny app from the creator
This is the getpoints() code:
```
getpoints <- function(f,x1,x2,y1,y2){
## if bitmap
if (typeof(f)=="character")
{ lfname <- tolower(f)
if ((strsplit(lfname,".jpeg")[[1]]==lfname) && (strsplit(lfname,".tiff")[[1]]==lfname) &&
(strsplit(lfname,".bmp")[[1]]==lfname) && (strsplit(lfname,".png")[[1]]==lfname) &&
(strsplit(lfname,".jpg")[[1]]==lfname))
{stop ("This function can only process bitmap images in JPEG, PNG,BMP, or TIFF formate.")}
img <- readbitmap::read.bitmap(f)
} else if (typeof(f)=="double")
{
img <- f
} else {
stop ("Please double check the format of the image file.")
}
## function to read the bitmap and points on x-axis and y-axis
axispoints <- function(img){
op <- par(mar = c(0, 0, 0, 0))
on.exit(par(op))
plot.new()
rasterImage(img, 0, 0, 1, 1)
message("You need to define the points on the x and y axis according to your input x1,x2,y1,y2. \n")
message("Click in the order of left x-axis point (x1), right x-axis point(x2),
lower y-axis point(y1), and upper y-axis point(y2). \n")
x1 <- as.data.frame(locator(n = 1,type = 'p',pch = 4,col = 'blue',lwd = 2))
x2 <- as.data.frame(locator(n = 1,type = 'p',pch = 4,col = 'blue',lwd = 2))
y1 <- as.data.frame(locator(n = 1,type = 'p',pch = 3,col = 'red',lwd = 2))
y2 <- as.data.frame(locator(n = 1,type = 'p',pch = 3,col = 'red',lwd = 2))
ap <- rbind(x1,x2,y1,y2)
return(ap)
}
## function to calibrate the points to the appropriate coordinates
calibrate <- function(ap,data,x1,x2,y1,y2){
x <- ap$x[c(1,2)]
y <- ap$y[c(3,4)]
cx <- lm(formula = c(x1,x2) ~ c(x))$coeff
cy <- lm(formula = c(y1,y2) ~ c(y))$coeff
data$x <- data$x*cx[2]+cx[1]
data$y <- data$y*cy[2]+cy[1]
return(as.data.frame(data))
}
## take the points
ap <- axispoints(img)
message("Mouse click on the K-M curve to take the points of interest. The points will only be labled when you finish all the clicks.")
takepoints <- locator(n=512,type='p',pch=1,col='orange4',lwd=1.2,cex=1.2)
df <- calibrate(ap,takepoints,x1,x2,y1,y2)
par()
return(df)
}
```
I'm a bit at a loss in how to execute this in my main panel. I've tried using `plotOutput()`, `imageOutput()`, and calling variations of the below functions, but nothing pops up or seems to work like it does in R studio. I feel like the issue is that the 'getpoints()' function executes 3 things :
1. Generating a plot from an uploaded file.
2. Allow user to click and store multiple points.
3. Return a data frame.
Will I need to split out the components of the function into individual steps?
```
createPoints<-reactive({
#Read File
file <- input$file1
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "png", "Please upload a .png file"))
##should run the function that generates a plot for clicking coordinates and stores them in a data frame
points<-getpoints(file,x1=0, x2=input$Xmax,y1=0, y2=100)
return(points)
})
```
```
output$getPointsPlot<-renderPlot(
createPoints()
)
``` |
I'm integrating Google sign-in with Firebase authentication in my Flutter app. When trying to assign the result of `GoogleSignIn().signIn(`) to a `GoogleSignInAccount` variable, I encounter a type mismatch error. Here's the relevant part of my code:
```
// ignore: import_of_legacy_library_into_null_safe
import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
Future<Map<String, dynamic>> signInWithGoogle() async {
final GoogleSignInAccount googleUser = await GoogleSignIn().signIn();
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
return {
"email": googleUser.email,
"photoUrl": googleUser.photoUrl,
"credentials": await FirebaseAuth.instance.signInWithCredential(credential),
};
}
Future<bool> signInWithEmail(String email, String password) async {
try {
FirebaseAuth.instance.
signInWithEmailAndPassword(email: email, password: password);
return true;
} on FirebaseAuthException catch(e){
print(e.code);
return false;
}
}
Future<bool> signUpWithEmail(String email, String password) async {
try {
FirebaseAuth.instance.
createUserWithEmailAndPassword(email: email, password: password);
return true;
} on FirebaseAuthException catch(e){
print(e.code);
return false;
}
}
```
**Flutter's suggestion is:**
> A value of type 'GoogleSignInAccount?' can't be assigned to a variable of type 'GoogleSignInAccount'.
> Try changing the type of the variable, or casting the right-hand type to 'GoogleSignInAccount'.
I've attempted to cast the variable to the non-nullable type but still face issues. How can I correctly assign a value of type 'GoogleSignInAccount?' to a variable of type 'GoogleSignInAccount' in this context?
|
Error Assigning 'GoogleSignInAccount?' to 'GoogleSignInAccount' in Flutter Authentication |
|flutter|dart|firebase-authentication|google-signin| |
I found a solution which worked for me . Give it a try if it works !!.
Go to index.js file and replace <React.StrictMode> to
<BrowserRouter>
Attached the snippet for reference.
Good Luck [enter image description here][1]
[1]: https://i.stack.imgur.com/XMtZe.png |
I have two apps using MUI, each has a theme. I have a separate npm package containing components used by both apps. This works fine except when I import a component from my npm package, it doesn't use the theme of the app consuming it, it appears to just use the default theme (as the separate package has no theme defined). Is there a way of ensuring the shared components imported from my npm package use the theme of the consuming app?
Thanks! |
Components using MUI in shared library not using parent app theme |
|reactjs|next.js|material-ui| |
please explain why my map is not displayed on the site. Now I have my top bar of the site and a blank white background, but there should be a map. please help me fix it. My API is connected to the project and also billing is connected.
I would also like to help with a question regarding adding a lot of markers to Google maps on my website. I ask for help.
```
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Znajdź i zgadnij</title>
<link rel="stylesheet" href="libs/bootstrap-reboot.min.css" />
<link rel="stylesheet" href="libs/bootstrap-grid.min.css" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,400;0,700;1,400&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" type="text/css" href="style.css" />
<style>
@import url("https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&display=swap");
</style>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script type="module" src="script.js"></script>
</head>
<body>
<div class="main">
<div class="navbar">
<div class="container">
<a href="index.html" class="navbar-brand"
>Słupsk<span class="navbar-brand" id="go">Go</span></a
>
<div class="navbar-wrap">
<ul class="navbar-menu">
<li><a href="zasadygry.html">Zasady gry</a></li>
<li><a href="kontakt.html"> Kontakt</a></li>
</ul>
<a href="mapa.html" class="kontakt">Mapa</a>
</div>
</div>
</div>
</div>
<div id="map"></div>
<script>
function initMap() {
let uluru = { lat: 54.464778, lng: 17.027122 };
let map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
center: uluru,
});
let marker = new google.maps.Marker({ position: uluru, map: map });
}
</script>
<script>
((g) => {
var h,
a,
k,
p = "The Google Maps JavaScript API",
c = "google",
l = "importLibrary",
q = "__ib__",
m = document,
b = window;
b = b[c] || (b[c] = {});
var d = b.maps || (b.maps = {}),
r = new Set(),
e = new URLSearchParams(),
u = () =>
h ||
(h = new Promise(async (f, n) => {
await (a = m.createElement("script"));
e.set("libraries", [...r] + "");
for (k in g)
e.set(
k.replace(/[A-Z]/g, (t) => "_" + t[0].toLowerCase()),
g[k]
);
e.set("callback", c + ".maps." + q);
a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
d[q] = f;
a.onerror = () => (h = n(Error(p + " could not load.")));
a.nonce = m.querySelector("script[nonce]")?.nonce || "";
m.head.append(a);
}));
d[l]
? console.warn(p + " only loads once. Ignoring:", g)
: (d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n)));
})({ key: "AIzaSyDgKBm5DUC", v: "weekly" });
</script>
</body>
</html>
```
|
Uncaught TypeError: google.maps.LatLng is not a constructor at init (script.js:7:13) |
|html|css|api|google-maps| |
null |
OP Here.
The command that is working is:
curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r 'echo $1 $(unescape_html "$2")' | bash | rg -o '(https?://\S+)\s(.*)' -r 'echo $1 $(unescape_html "$2")' -r '{"url": "$1", "title": "$2"}' | jq -s '.'
I am still looking for a better solution. |
What is the relationship between "Composite indexing" and "Index Skip Scan"?
If you create a composite indexing on 3 columns `eid`, `ename`, `esal`?
- If I mention only `eid=10` after where clause will the indexing be called ?
```
select * from emp where eid=10;
```
- If I mention only eid=10 and ename='Raj' will the indexing be called ?
```
select * from emp where eid=10 and ename='Raj';
```
- If I mention in different order like esal=1000 and eid=10 will the indexing be called ?
```
select * from emp where esal=1000 and eid=10;
```
- If I mention in reverse order like esal = 1000 and ename = 'Raj' and eid = 10 will the indexing be called ?
```
select * from emp where esal=1000 and enam='Raj' and eid=10;
```
Need a solution for this with detail table representation with data how it does? |
|oracle|indexing| |
I am trying to convert some R code I've written into an R shiny app so others can use it more readily. The code utilizes a package called `IPDfromKM`. The main function of issue is `getpoints()`, which in R will generate a plot and the user will need to click the max X and max Y coordinates, followed by clicking through the entire KM curve, which extracts the coordinates into a data frame. However, I cannot get this to work in my R shiny app.
There is a [link ](https://biostatistics.mdanderson.org/shinyapps/IPDfromKM/)to the working R shiny app from the creator
This is the getpoints() code:
```
getpoints <- function(f,x1,x2,y1,y2){
## if bitmap
if (typeof(f)=="character")
{ lfname <- tolower(f)
if ((strsplit(lfname,".jpeg")[[1]]==lfname) && (strsplit(lfname,".tiff")[[1]]==lfname) &&
(strsplit(lfname,".bmp")[[1]]==lfname) && (strsplit(lfname,".png")[[1]]==lfname) &&
(strsplit(lfname,".jpg")[[1]]==lfname))
{stop ("This function can only process bitmap images in JPEG, PNG,BMP, or TIFF formate.")}
img <- readbitmap::read.bitmap(f)
} else if (typeof(f)=="double")
{
img <- f
} else {
stop ("Please double check the format of the image file.")
}
## function to read the bitmap and points on x-axis and y-axis
axispoints <- function(img){
op <- par(mar = c(0, 0, 0, 0))
on.exit(par(op))
plot.new()
rasterImage(img, 0, 0, 1, 1)
message("You need to define the points on the x and y axis according to your input x1,x2,y1,y2. \n")
message("Click in the order of left x-axis point (x1), right x-axis point(x2),
lower y-axis point(y1), and upper y-axis point(y2). \n")
x1 <- as.data.frame(locator(n = 1,type = 'p',pch = 4,col = 'blue',lwd = 2))
x2 <- as.data.frame(locator(n = 1,type = 'p',pch = 4,col = 'blue',lwd = 2))
y1 <- as.data.frame(locator(n = 1,type = 'p',pch = 3,col = 'red',lwd = 2))
y2 <- as.data.frame(locator(n = 1,type = 'p',pch = 3,col = 'red',lwd = 2))
ap <- rbind(x1,x2,y1,y2)
return(ap)
}
## function to calibrate the points to the appropriate coordinates
calibrate <- function(ap,data,x1,x2,y1,y2){
x <- ap$x[c(1,2)]
y <- ap$y[c(3,4)]
cx <- lm(formula = c(x1,x2) ~ c(x))$coeff
cy <- lm(formula = c(y1,y2) ~ c(y))$coeff
data$x <- data$x*cx[2]+cx[1]
data$y <- data$y*cy[2]+cy[1]
return(as.data.frame(data))
}
## take the points
ap <- axispoints(img)
message("Mouse click on the K-M curve to take the points of interest. The points will only be labled when you finish all the clicks.")
takepoints <- locator(n=512,type='p',pch=1,col='orange4',lwd=1.2,cex=1.2)
df <- calibrate(ap,takepoints,x1,x2,y1,y2)
par()
return(df)
}
```
I'm a bit at a loss in how to execute this in my main panel. I've tried using `plotOutput()`, `imageOutput()`, and calling variations of the below functions, but nothing pops up or seems to work like it does in R studio. I feel like the issue is that the 'getpoints()' function executes 3 things :
1. Displaying an image from an uploaded file.
2. Allow user to click and store multiple points.
3. Return a data frame.
Will I need to split out the components of the function into individual steps?
```
createPoints<-reactive({
#Read File
file <- input$file1
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "png", "Please upload a .png file"))
##should run the function that generates a plot for clicking coordinates and stores them in a data frame
points<-getpoints(file,x1=0, x2=input$Xmax,y1=0, y2=100)
return(points)
})
```
```
output$getPointsPlot<-renderPlot(
createPoints()
)
``` |
I am sharing the whole code fixed:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Taskboard</title>
<link rel="stylesheet" href="/static/styling/home.css">
<style>
body, html {
height: 100%;
margin: 0;
font-family: Arial, sans-serif;
background-color: #333;
color: white;
}
header {
background-color: #222;
padding: 10px 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
nav {
position: relative; /* Ensure nav is positioned for absolute positioning of children */
}
nav h1 {
margin: 0;
display: flex;
align-items: center;
background: #007bff; /* Set the background color to blue */
position: relative; /* Ensure relative positioning for the nav h1 */
padding: 5px;
font-size: 16px;
transform: skewX(-20deg);
}
nav .hamburger {
cursor: pointer;
font-size: 24px;
margin-left: 10px;
color: white; /* Change the color of the hamburger icon to white for better visibility */
}
.menu {
list-style: none;
align-items: center;
padding: 0;
position: absolute;
left: 100%; /* Position to the right of the nav h1 */
transform: scaleX(0); /* Initially collapsed along the X axis */
transform-origin: left;
transition: transform 350ms ease-in-out; /* Animate the transform property */
background-color: #222;
box-shadow: 0 2px 5px rgba(0,0,0,0.2); /* Optional: Add a shadow for better visibility */
}
.showNavMenu {
transform: scaleX(1); /* Expand to full width */
}
ul li {
display: block; /* Change to block for vertical list */
padding: 5px;
}
.button-blue {
background: #007bff; /* Assuming a solid blue; replace with gradient if needed */
color: white;
border: none;
padding: 10px 15px;
font-size: 16px;
font-weight: bold;
border-radius: 4px; /* Adjust as needed */
margin-left: 10px; /* Space between buttons */
transition: background-color 0.3s ease; /* Smooth transition for hover effect */
text-transform: uppercase; /* If the text should be uppercase as in the screenshot */
transform: skewX(-20deg);
}
nav {
display: flex;
justify-content: space-between; /* Adjust this to align the nav items as in the screenshot */
align-items: center;
padding: 10px; /* Adjust as needed */
}
/* Style for the hamburger icon */
nav .hamburger {
cursor: pointer;
font-size: 24px;
color: white; /* Change the color of the hamburger icon to white for better visibility */
}
/* You might also want to style the <ul> element to have padding and margin 0 */
nav ul {
padding: 0;
margin: 0;
display: flex; /* To align the buttons horizontally */
}
/* Style for the <li> elements to remove list styles and margins */
nav ul li {
list-style: none;
margin: 0;
}
ul li button.button-blue:hover {
background-color: blue; /* Keep the background color blue on hover */
}
.button-blue:hover {
background: linear-gradient(to bottom right, #0056b3, #004291);
box-shadow: 0 2px #002b5e;
transform: translateY(2px) skewX(-20deg); /* Add skew transformation here as well */
}
#new-taskboard-form {
display: none;
margin: 20px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
background-color: #f9f9f9;
}
#new-taskboard-form input[type="text"],
#new-taskboard-form input[type="file"] {
width: 100%;
padding: 10px;
margin: 10px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
#new-taskboard-form button {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
#new-taskboard-form button:hover {
background-color: #45a049;
}
#new-taskboard-form input[type="text"]::placeholder {
color: #888;
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
padding-top: 60px;
}
.modal-content {
background-color: #fefefe;
margin: 5% auto; /* 5% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
border-radius: 8px; /* Optional: Rounded corners */
}
.close-button {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close-button:hover,
.close-button:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
.taskboard-selector {
width: 100%;
padding: 10px;
margin: 10px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
header {
background-color: #222;
padding: 10px 20px;
display: flex;
justify-content: space-between; /* Aligns items on opposite ends */
align-items: center;
}
#settings-button {
margin-right: 20px; /* Add some margin for spacing */
}
</style>
</head>
<body>
<header>
<nav>
<h1>My New Taskboard <span class="hamburger">☰</span></h1>
<ul class="menu">
<li><button id="update-button" class="button-blue">Update</button></li>
<li><button id="edit-button" class="button-blue">Edit</button></li>
<li><button id="open-button" class="button-blue">Open</button></li>
<li><button id="new-button" class="button-blue">New</button></li>
</ul>
</nav>
<button id="settings-button" class="button-blue">Settings</button> <!-- Moved outside of the nav, into the header -->
</header>
<main>
<section class="taskboard-grid" id="taskboard-grid">
<!-- Task cards will be dynamically added here -->
</section>
<!-- Hidden form for creating a new taskboard -->
<div id="new-taskboard-form">
<input type="text" id="new-taskboard-name" placeholder="Enter Taskboard Name">
<input type="file" id="new-taskboard-file" accept=".xlsx">
<button id="submit-new-taskboard">Create Taskboard</button>
</div>
</main>
<div id="taskboard-selection-modal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<h2>Select a Taskboard</h2>
<select id="taskboard-selector" class="taskboard-selector">
<!-- Taskboard options will be dynamically populated here -->
</select>
<button id="select-taskboard-button" class="button-blue">Open Taskboard</button>
</div>
</div>
<script>
// Toggle menu visibility
const hamburger = document.querySelector('.hamburger');
const menu = document.querySelector('.menu');
hamburger.addEventListener('click', () => {
menu.classList.toggle('showNavMenu');
});
// Open settings page
document.getElementById('settings-button').addEventListener('click', function() {
window.location.href = 'settings';
});
// Global variable to keep track of the currently selected taskboard
let currentTaskboard = null;
// Update taskboard functionality
document.getElementById('update-button').addEventListener('click', function() {
if (!currentTaskboard) {
alert('Please select a taskboard first.');
return;
}
var fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.xlsx';
fileInput.addEventListener('change', function(event) {
var file = event.target.files[0];
var formData = new FormData();
formData.append('file', file);
formData.append('name', currentTaskboard);
fetch('/upload/', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
fetchTaskboardData(currentTaskboard);
})
.catch(error => {
console.error('Error:', error);
});
});
fileInput.click();
});
// Open taskboard selection modal
document.getElementById('open-button').addEventListener('click', function() {
fetch('/list/')
.then(response => response.json())
.then(taskboards => {
populateTaskboardSelector(Object.values(taskboards));
showModal();
})
.catch(error => {
console.error('Error fetching taskboards:', error);
});
});
// Populate taskboard selector in modal
function populateTaskboardSelector(taskboards) {
var selector = document.getElementById('taskboard-selector');
selector.innerHTML = '';
taskboards.forEach(taskboard => {
var option = document.createElement('option');
option.value = taskboard;
option.textContent = taskboard;
selector.appendChild(option);
});
}
// Show modal
function showModal() {
var modal = document.getElementById('taskboard-selection-modal');
modal.style.display = 'block';
}
// Close modal functionality
document.querySelector('.close-button').addEventListener('click', function() {
var modal = document.getElementById('taskboard-selection-modal');
modal.style.display = 'none';
});
window.onclick = function(event) {
var modal = document.getElementById('taskboard-selection-modal');
if (event.target == modal) {
modal.style.display = 'none';
}
}
// Handle taskboard selection from modal
document.getElementById('select-taskboard-button').addEventListener('click', function() {
var selectedTaskboard = document.getElementById('taskboard-selector').value;
if (selectedTaskboard) {
openTaskboard(selectedTaskboard);
var modal = document.getElementById('taskboard-selection-modal');
modal.style.display = 'none';
} else {
alert('Please select a taskboard.');
}
});
// Edit taskboard functionality
document.getElementById('edit-button').addEventListener('click', function() {
if (!currentTaskboard) {
alert('Please select a taskboard first.');
return;
}
window.location.href = `/edit?name=${encodeURIComponent(currentTaskboard)}`;
});
// New taskboard functionality
document.getElementById('new-button').addEventListener('click', function() {
document.getElementById('new-taskboard-form').style.display = 'block';
});
// Submit new taskboard
document.getElementById('submit-new-taskboard').addEventListener('click', function() {
var taskboardName = document.getElementById('new-taskboard-name').value;
var fileInput = document.getElementById('new-taskboard-file');
var file = fileInput.files[0];
if (!taskboardName || !file) {
alert('Please enter a taskboard name and select a file.');
return;
}
var formData = new FormData();
formData.append('name', taskboardName);
formData.append('file', file);
fetch('/create', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log('Taskboard created:', data);
document.getElementById('new-taskboard-form').style.display = 'none';
document.getElementById('new-taskboard-name').value = '';
fileInput.value = '';
})
.catch(error => {
console.error('Error:', error);
});
});
// Function to fetch and display taskboard data
function fetchTaskboardData(taskboardName) {
console.log('Fetching data for:', taskboardName); // Debug log
fetch(`/get/?name=${encodeURIComponent(taskboardName)}`)
.then(response => response.json())
.then(data => {
console.log('Data received:', data); // Debug log
var taskboardGrid = document.getElementById('taskboard-grid');
taskboardGrid.innerHTML = ''; // Clear existing content
// Check if data is an object and not an array
if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
Object.values(data).forEach(createCard); // Iterate over object values
} else {
console.error('Unexpected data format:', data);
}
})
.catch(error => {
console.error('Error fetching taskboard data:', error);
});
}
// Function to create a card for each task
function createCard(row) {
console.log('Creating card for:', row); // Debug log
var card = document.createElement('div');
card.className = 'task-card';
Object.keys(row).forEach(key => {
if (row[key] !== null && row[key] !== undefined) {
var p = document.createElement('p');
p.textContent = `${key}: ${row[key]}`;
card.appendChild(p);
}
});
document.getElementById('taskboard-grid').appendChild(card); // Append card to taskboard grid
}
// Open taskboard function
function openTaskboard(taskboardName) {
currentTaskboard = taskboardName;
fetchTaskboardData(taskboardName);
}
// DOMContentLoaded event listener
document.addEventListener('DOMContentLoaded', function() {
const urlParams = new URLSearchParams(window.location.search);
const taskboardName = urlParams.get('name');
if (taskboardName) {
openTaskboard(taskboardName);
}
});
</script>
</body>
</html>
``` |
How can I accumulate a binary array containing 0 and 1 into an integer?
vector<int> arr = {1,0,1,0,1,1,1,0,1,0,0};
int num = accumulate(arr.begin(), arr.end(), [] (int &a, int &b)
{ // ??? });
At each step I need something like this:
if(arr[i] % 2) num += pow(2, i);
But how to implement this in lambda? How to get `i` in lambda? |
After updating to Next.js 14.1, I get these build messages telling me that all my pages are deopted into client-side rendering due to "useSearchParams().
Here is an example from the terminal when running next build:
Entire page "/404" deopted into client-side rendering due to "useSearchParams()". Read more: https://nextjs.org/docs/messages/deopted-into-client-rendering
I have no custom /404 page, so that is automatically generated by next, and I have search through the entire code base for useSearchParams, and I couldn't find anything
What am I doing wrong? |
How to fix useSearchParams deopted into client-side rendering? |
|next.js| |
null |
There has to be a better way... but a quick short hack following up on @user1579943's comments with a bit of additional detail.
Subclass your custom user from IdentityUser
public class MyUser : IdentityUser
{
public string? Name { get; set; } = "";
public string? Street { get; set; } = "";
public string? City { get; set; } = "";
public string? State { get; set; } = "";
public string? Zip { get; set; } = "";
public string? Phone { get; set; } = "";
}
Create a matching Dto
public record CreateUserDto(
string Email,
string Password,
string Name,
string Street,
string City,
string State,
string Zip,
[Required]
string Phone,
);
Hack the IdentityApiEndpointRouteBuilderExtensions to match.
public static class IdentityApiEndpointRouteBuilderExtensions
{
private static readonly EmailAddressAttribute _emailAddressAttribute = new();
public static IEndpointConventionBuilder MapCustomIdentityApi<TUser>(this IEndpointRouteBuilder endpoints, TUser user)
where TUser : MyUser, new()
{
.....
routeGroup.MapPost("/register", async Task<Results<Ok, ValidationProblem>>
([FromBody] CreateUserDto registration, HttpContext context, [FromServices] IServiceProvider sp) =>
{
.....
var user = new TUser
{
Name = registration.Name,
Street = registration.Street,
City = registration.City,
State = registration.State,
Zip = registration.Zip,
Phone = registration.Phone,
};
}
}
....
}
|
You are allowed to call `fork()` on iOS, just not on watchOS and tvOS. However, despite being allowed to call it, `fork()` will always fail as an application process is not allowed to manage other processes on iOS, so you cannot directly create a child process by yourself. Also not using `system()` or `posix_spawn()` or any other API that would allow you to do so. Yet the fact that you try to call it will not cause your app review to fail, it is public and official API after all on iOS, you just may not expect this call to do anything useful. And it's not like `fork()` would not work on iOS in general, it does work for applications that have the appropriate permissions to use it. |
I had a similar issue with getting my `jest` tests to run. They ran fine locally, but not in Azure Pipelines. I ended up discovering that there was a hanging process that was never closed after my tests were done causing it to freeze.
I used the command `jest ./tests --detectOpenHandles` to find the process and after I made sure the process was closed, the tests ran fine in Azure. |
I think the best solution (from both a code, accessibility and UI point of view) is to use the `selection:` parameter of `List`.
This has the main benefit of automatically highlighting the cell on tap, and handling the tap gesture states correctly (triggering the selection change only on touch up if the finger is still inside the cell):
```swift
import SwiftUI
struct Fruit: Hashable, Identifiable {
let id = UUID()
let name: String
}
struct ContentView: View {
let fruits = [
Fruit(name: " Banana"),
Fruit(name: " Apple"),
Fruit(name: " Orange")
]
@State private var selectedFruit: Fruit.ID?
var body: some View {
NavigationStack {
List(fruits, selection: $selectedFruit) { fruit in
Text(fruit.name)
.foregroundStyle(Color(uiColor: .label))
.listRowBackground(fruit.id == selectedFruit ? Color(uiColor: .systemGray4) : nil)
}
.navigationTitle("Fruits")
}
.onChange(of: selectedFruit) { _, newValue in
if let newValue {
print("Touched \(fruits.first(where: { $0.id == newValue })!.name)")
}
}
}
}
```
We unfortunately need these 2 lines :
```swift
.foregroundStyle(Color(uiColor: .label))
.listRowBackground(fruit.id == selectedFruit ? Color(uiColor: .systemGray4) : nil)
```
Because otherwise the selected cell will use your app's tint color as its background [when an hardware keyboard is connected](https://stackoverflow.com/questions/71664454/swiftui-how-to-change-list-selected-item-color).
--------
If you want the cell do immediately lose its selected state after tap, you can modify `.onChange` like so :
```swift
.onChange(of: selectedFruit) { _, newValue in
if let newValue {
print("Touched \(fruits.first(where: { $0.id == newValue })!.name)")
Task {
try? await Task.sleep(for: .milliseconds(80))
selectedFruit = nil
}
}
}
```
(adjust the delay as you see fit)
---------
This is the final result:
[![demo of the sample code on iPad simulator][1]][1]
[1]: https://i.stack.imgur.com/WTamx.gif |
|emacs|themes|dot-emacs| |
I have given code like below. But the accountsGroup is of empty list as the FetchAccountGroups() event is not calling while debugged.
```
class AccountsScreen extends StatelessWidget {
final bool fromAddEditScreen;
const AccountsScreen({
super.key,
this.fromAddEditScreen = false,
});
@override
Widget build(BuildContext context) {
return BlocProvider<AccountsBloc>(
create: (context) => getIt<AccountsBloc>()
..add(
FetchAccountGroups(),
),
child: Builder(
builder: (context) {
return Scaffold(
appBar: CommonAppBar(
showBackButton: fromAddEditScreen,
title: context.t.accounts,
leftPadding: fromAddEditScreen ? null : 18.0,
action: Padding(
padding: const EdgeInsets.only(right: 12.0),
child: IconButton(
visualDensity: VisualDensity.comfortable,
style: IconButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
backgroundColor: Colors.white,
),
onPressed: () async {
await showDialog(
context: context,
builder: (_) => AddEditAccountsDialog(
accountGroups: BlocProvider.of<AccountsBloc>(context, listen: true).getAccountGroups,
isEdit: false,
onSaveTapped: () {},
),
);
},
icon: Row(
children: [
SvgPicture.asset(
SvgAssetPaths.plusIcon,
colorFilter: const ColorFilter.mode(Colors.black, BlendMode.srcIn),
),
8.hGap,
Text(
context.t.accountScreen.addAccount,
style: context.textStyleTheme.medium14.copyWith(
color: Colors.black,
),
),
],
),
),
),
),
);
},
),
);
}
}
```
But if I change my code like this (assign bloc into a variable and pass to the bloc provider), it works perfectly fine. What will be the issue as I am not able to find it. Is it the issue with Flutter or with Bloc?
```
class AccountsScreen extends StatelessWidget {
final bool fromAddEditScreen;
const AccountsScreen({
super.key,
this.fromAddEditScreen = false,
});
@override
Widget build(BuildContext context) {
final accountsBloc = getIt<AccountsBloc>()
..add(
FetchAccountGroups(),
);
return BlocProvider<AccountsBloc>(
create: (context) => accountsBloc,
child: Builder(
builder: (context) {
return Scaffold(
appBar: CommonAppBar(
showBackButton: fromAddEditScreen,
title: context.t.accounts,
leftPadding: fromAddEditScreen ? null : 18.0,
action: Padding(
padding: const EdgeInsets.only(right: 12.0),
child: IconButton(
visualDensity: VisualDensity.comfortable,
style: IconButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
backgroundColor: Colors.white,
),
onPressed: () async {
await showDialog(
context: context,
builder: (_) => AddEditAccountsDialog(
accountGroups: BlocProvider.of<AccountsBloc>(context, listen: true).getAccountGroups,
isEdit: false,
onSaveTapped: () {},
),
);
},
icon: Row(
children: [
SvgPicture.asset(
SvgAssetPaths.plusIcon,
colorFilter: const ColorFilter.mode(Colors.black, BlendMode.srcIn),
),
8.hGap,
Text(
context.t.accountScreen.addAccount,
style: context.textStyleTheme.medium14.copyWith(
color: Colors.black,
),
),
],
),
),
),
),
);
},
),
);
}
}
```
I will provide the bloc event also:
```
List<AccountGroupsModel> _accountGroups = [];
List<AccountGroupsModel> get getAccountGroups => _accountGroups;
FutureOr<void> _onFetchAccountGroups(FetchAccountGroups event, emit) async {
final int initialItemCount = _accountGroups.length;
_accountGroups = await _accountsRepository.getAccountGroups();
if (_accountGroups.length > initialItemCount) {
emit(AddedAccountGroupsSuccessfully());
}
emit(
FetchedAccountGroups(
accountGroups: _accountGroups,
),
);
}
```
|
Bloc not calling while calling event with cascade in BlocProvider. But working fine if assigned to a variable and passed to BlocProvider |
|flutter|dart|flutter-bloc| |
As I found out that the issue is as follows:
While in the first case as I am using cascade to add an event and in the widget subtree I am not using any BlocBuilder or Listeners, so the bloc is managing to not even create the instance and pass to the widget tree. And while I am calling this
```
BlocProvider.of<AccountsBloc>(context, listen: true).getAccountGroups
```
then only the tree is activated with bloc but that event I added at first is void and never called.
So, I solved this issue by adding `lazy=true` inside the `BlocProvider` which will anyway pass down the bloc even if it is not using anywhere. |
I am making `MultiVector` class for Entity Component System. It is used for storing objects of different types for iterating over them efficiently.
I use vectors of bytes as raw storage and `reinterpret_cast` it to whichever type I need. Basic functionality (`push_back` by const reference and `pop_back`) seems to work.
However, when I try to implement move semantics for `push_back` (commented lines), clang gives me incomprehensible 186 lines error message, something about 'allocate is declared as pointer to a reference type'. As I understand, vector tries to `push_back` reference to `T`, which it cannot do because it must own contained objects.
How am I supposed to do it?
```
#include <iostream>
#include <vector>
using namespace std;
int g_class_id { 0 };
template <class T>
const int get_class_id()
{
static const int id { g_class_id++ };
return id;
}
class MultiVector {
public:
MultiVector() : m_vectors(g_class_id + 1) {}
template <typename T>
vector<T>& vector_ref() {
const int T_id { get_class_id<T>() };
if (T_id >= m_vectors.size()) {
m_vectors.resize(T_id + 1);
}
vector<T>& vector_T { *reinterpret_cast<vector<T>*>(&m_vectors[T_id]) };
return vector_T;
}
template<typename T>
void push_back(const T& value) {
vector_ref<T>().push_back(value);
}
// Move semantics, take rvalue reference
template<typename T>
void push_back(T&& value) {
vector_ref<T>().push_back(std::move(value));
}
template <typename T>
void pop_back() {
vector_ref<T>().pop_back();
}
private:
vector<vector<byte>> m_vectors;
};
template<typename T>
void show(const vector<T>& vct)
{
for (const auto& item : vct) cout << item << ' ';
cout << '\n';
}
int main(int argc, const char *argv[])
{
string hello = "hello";
string world = "world";
MultiVector mv;
mv.push_back(10);
mv.push_back(20);
mv.push_back(2.7);
mv.push_back(3.14);
mv.push_back(hello);
mv.push_back(world);
show(mv.vector_ref<int>());
show(mv.vector_ref<double>());
show(mv.vector_ref<string>());
mv.vector_ref<int>().pop_back();
show(mv.vector_ref<int>());
return 0;
}
```
Tried to replace rvalue reference `T&&` to just value `T`, does not compile too because call to `push_back` becomes ambiguous.
Edit: In function with `T&& value` argument `vector_ref<T>()` cannot even push default value to rewrite it via placement `new` operator, because type of vector deduced as `vector<T&>`. How do I make compiler deduce type of vector as `vector<T>`? |
I want PHP to generate an HTML table from a nested JSON object. I want the output to resemble the format shown in the image. The main challenges lie in handling the rowspan and colspan. While I can calculate the rowspan, I am encountering difficulties with the colspan. I need a recursive PHP function. The current one creates a table in each `<td>`, but I want `<tr>` to be like in the [image][1]. The JSON can have an unlimited number of levels.
```
$data = json_decode($jsonData, true);
function generateTable($data) {
$html = '<table border="1">';
foreach ($data as $item) {
if(is_array($item['node']['value']))
{
$rowspan = count($item['node']['value']);
}
$html .= '<tr rowspan='.$rowspan.'>';
$html .= '<tr>';
$html .= '<th>' . $item['node']['key'] . '</th>';
$html .= '<td>';
if (isset($item['node']['value']) && is_array($item['node']['value'])) {
$html .= generateTable($item['node']['value']);
} else {
$html .= $item['node']['value'];
}
$html .= '</td>';
$html .= '</tr>';
}
$html .= '</table>';
return $html;
}
echo generateTable($data);
```
```
[
{
"node":{
"key":"header",
"value":[
{
"node":{
"key":"msg_id",
"value":"236001"
},
"type":"string",
"minLength":1,
"maxLength":12,
"desc":"Message ID, this field should be unique id for each Api call. This will be generated from client side. \n\n If the same message ID is used the system will decline the API call with Error Description “Duplicate Message ID” ",
"req":"required"
},
{
"node":{
"key":"msg_type",
"value":"TRANSACTION"
},
"type":"string",
"minLength":1,
"maxLength":12,
"desc":"Message Type – This can have either “TRANSACTION” or “ENQUIRY” \n\n As for this API the value expected is “TRANSACTION” ",
"req":"required"
},
{
"node":{
"key":"msg_function",
"value":"REQ_ACCOUNT_CREATE"
},
"type":"string",
"minLength":1,
"maxLength":50,
"desc":"Message functions: Should be “REQ_ACCOUNT_CREATE” ",
"req":"required"
},
{
"node":{
"key":"src_application",
"value":"IVR"
},
"type":"string",
"minLength":1,
"maxLength":10,
"desc":"Source Application: This is a free Text and the client can populate the source system from where the API is Initiated \n\n Example: IVR, IB, MB \n\n No Validations of these are kept at Network Systems",
"req":"required"
},
{
"node":{
"key":"target_application",
"value":"WAY4"
},
"type":"string",
"minLength":1,
"maxLength":10,
"desc":"The target_application can hold any value from FI side, this can be used by FI to check the target system of the API call",
"req":"required"
},
{
"node":{
"key":"timestamp",
"value":"2020-07-20T10:49:02.366+04:00"
},
"type":"string",
"minLength":1,
"maxLength":30,
"desc":"Timestamp of the request - Format YYYY-MM-DDtHH:MM:SS.SSS+04:00",
"req":"required"
},
{
"node":{
"key":"bank_id",
"value":"NIC"
},
"type":"string",
"minLength":1,
"maxLength":4,
"desc":"Bank Id is Unique Id 4 digit code for each client and the same will be provided once the client setup is completed in our core system. \n\n For sandbox testing – Please use “NIC” ",
"req":"required"
}
]
},
"type":"object",
"minLength":null,
"maxLength":null,
"desc":"",
"req":"false"
},
{
"node":{
"key":"body",
"value":[
{
"node":{
"key":"customer_id",
"value":"100000027"
},
"type":"string",
"minLength":1,
"maxLength":20,
"desc":"Customer ID: Customer Identification number \n\n This should be a unique number",
"req":"required"
},
{
"node":{
"key":"card_type",
"value":"CREDIT"
},
"type":"string",
"minLength":1,
"maxLength":7,
"desc":"Informative value to the request, does not have any functional impact, the value can be PREPAID/CREDIT/DEBIT",
"req":"required"
},
{
"node":{
"key":"account",
"value":[
{
"node":{
"key":"customer_id",
"value":"100000027"
},
"type":"string",
"minLength":1,
"maxLength":20,
"desc":"Customer ID: Customer Identification number \n\n This should be a unique number",
"req":"required"
},
{
"node":{
"key":"account_number",
"value":"0009821110000000008"
},
"type":"string",
"minLength":1,
"maxLength":64,
"desc":"Account number, if not provided CMS will generate it",
"req":"false"
},
{
"node":{
"key":"parent_account_number",
"value":"0009821110000000008"
},
"type":"string",
"minLength":1,
"maxLength":64,
"desc":"Parent account number - Applicable only for Corporate products",
"req":"false"
},
{
"node":{
"key":"branch_code",
"value":"982"
},
"type":"string",
"minLength":1,
"maxLength":10,
"desc":"Branch Code, if no branches are used, the code must be same as bank_code",
"req":"required"
},
{
"node":{
"key":"product_code",
"value":"982_AED_002_A"
},
"type":"string",
"minLength":1,
"maxLength":32,
"desc":"Product code, this code is generated by CMS after creating the product, this code is FI spesific code 982_AED_002_A is just used as an example in Sandbox",
"req":"required"
},
{
"node":{
"key":"billing_day",
"value":""
},
"type":"string",
"minLength":1,
"maxLength":10,
"desc":"Billing date, applicable only for credit card products",
"req":"false"
},
{
"node":{
"key":"currency",
"value":"AED"
},
"type":"string",
"minLength":1,
"maxLength":3,
"desc":"Informative value to the request, does not have any functional impact, the currency will be taken from the product",
"req":"required"
},
{
"node":{
"key":"limit",
"value":[
{
"node":{
"key":"type",
"value":"FIN_LIMIT"
},
"type":"string",
"minLength":1,
"maxLength":32,
"desc":"Credit limit type - applicable only for credit card products",
"req":"false"
},
{
"node":{
"key":"currency",
"value":"SAR"
},
"type":"string",
"minLength":1,
"maxLength":3,
"desc":"Credit limit currency - applicable only for credit card products",
"req":"false"
},
{
"node":{
"key":"value",
"value":"55000"
},
"type":"string",
"minLength":1,
"maxLength":20,
"desc":"Credit limit value - applicable only for credit card products",
"req":"false"
}
]
},
"type":"object",
"minLength":null,
"maxLength":null,
"desc":"",
"req":"false"
},
{
"node":{
"key":"custom_fields",
"value":[
{
"node":{
"key":"key",
"value":"contract_idt_scheme"
},
"type":"string",
"minLength":1,
"maxLength":20,
"desc":"Custom Tag. Example: contract_idt_scheme",
"req":"false"
},
{
"node":{
"key":"value",
"value":"CONTRACT_NUMBER"
},
"type":"string",
"minLength":1,
"maxLength":128,
"desc":"Tag value. Example: CONTRACT_NUMBER",
"req":"false"
}
]
},
"type":"array",
"minLength":null,
"maxLength":null,
"desc":"",
"req":"false"
}
]
},
"type":"object",
"minLength":null,
"maxLength":null,
"desc":"",
"req":"required"
}
]
},
"type":"object",
"minLength":null,
"maxLength":null,
"desc":"",
"req":"false"
}
]
```
[1]: https://i.stack.imgur.com/P8gbu.png |
Generate HTML table with complex nested JSON |
|php|html|json| |
*There is very good post about trimming 1fr to 0: https://stackoverflow.com/questions/52861086/why-does-minmax0-1fr-work-for-long-elements-while-1fr-doesnt*
In general I would like to have a cell which expands as the content grows, but within the limits of its parent.
Currently I have a grid with cell with such lengthy content that even without expanding it is bigger than the entire screen. So I would to do two things -- clip the size of the cell, and secondly -- provide the scroll.
I used `minmax(0, 1fr)` from the post I mentioned, so grid has free hand to squash the cell to zero, but it still allows to grow it up to the content size (which is too big). As the effect the scrolling is not triggered.
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body
{
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
overflow: hidden;
}
.page
{
height: 100%;
/*display: flex;
flex-direction: column;*/
display:grid;
grid-template-rows: min-content minmax(0, 1fr);
}
.header
{
}
.content
{
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
}
.quiz-grid
{
height: 100%;
max-height: 100%;
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr) min-content;
grid-template-areas:
"left main right"
"footer footer footer";
}
.quiz-cell-left
{
grid-area: left;
min-height: 0;
}
.quiz-cell-right
{
grid-area: right;
min-height: 0;
}
.quiz-cell-main
{
grid-area: main;
border: 1px red solid;
min-height: 0;
}
.quiz-cell-footer
{
grid-area: footer;
justify-self: center;
align-self: center;
}
/* my scroll view component */
.scroll-container
{
position: relative;
width: 100%;
min-height: 0;
background-color: azure;
max-height: 100%;
}
.scroll-content
{
height: 100%;
width: 100%;
overflow-y: auto;
}
/* simplified scroller */
.scroll-direct
{
overflow-y: auto;
background-color: azure;
width: 100%;
min-height: 0;
max-height: 100%;
}
</style>
</head>
<body>
<div class="page">
<div class="header">Header</div>
<div class="content">
<div class="quiz-grid">
<div class="quiz-cell-main">
<div class="scroll-container"> <div class="scroll-content">
<!-- <div class="scroll-direct">-->
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
</div> </div>
<!--</div>-->
</div>
<div class="quiz-cell-footer">
footer
</div>
</div>
</div>
</div>
</body>
</html>
<!-- end snippet -->
*Comment to the code: the content sits in cell "main", the other elements (header, footer) are just to make sure the solution would not be over simplified.*
**Update**: originally I used "flex" for outer layout, I switched to grid and I managed to achieve the clip+scroll behavior with single-div scroller, but I am still stuck with my real two-div one. |
On Android Studio Hedgehog 2023.1.1 Patch 2 sticky services don't restart too if you launch your app with the debugger due to a bug in it. Tested on Android 12. |
I have an element in my HTML like this. While the user types, I'm showing successive filtrations in a list to pick from. Once the user clicks on that component, I want to update the value typed in the search box below and replace it with the full name available in the clicked item.
<input #userSelector (keyup)="onKeyUpUser($event)">
In order to communicate easily, I have set up a view child as shown below. Then, in the handler of the click, I set the value picked.
@ViewChild("userSelector") userSelector: ElementRef;
...
onClickUser(user: User) {
this.userSelector.nativeElement.value = user.name;
...
}
This works as expected. Now, I wanted to be clever and realized that the view child is not only a general `ElementRef` but, in fact, `HTMLInputElement`, so I replaced the code like this.
@ViewChild("userSelector") userSelector: HTMLInputElement;
...
onClickUser(user: User) {
this.userSelector.value = user.name;
...
}
To my surprise, it doesn't update the contents visible on the screen. In the console, I can see that the field `value` has appeared and has the value I assigned. But it won't show. It's the same element, so I'm confused why this happens.
What's the reason this occurs and (how) can I use the more specific type of the view child (hence allowing to avoid the detour through `nativeElement` to get to the value field? |