问:
What is needed to get mupdf to compile on macOS (Monterey)
Mupdf no longer compiles on macOS 12.16.1. Using MacPorts for instance gives:

```<code>:info:build mkdir -p build/shared-release/generated/resources/fonts/noto/ ; /usr/bin/clang -ffunction-sections -fdata-sections -pipe -O2 -DNDEBUG -fomit-frame-pointer -Os -arch x86_64 -Iinclude -MMD -MP -o build/shared-release/generated/resources/fonts/noto/NotoSansOldPermic-Regular.otf.o -c generated/resources/fonts/noto/NotoSansOldPermic-Regular.otf.c -Wall -Wsign-compare -fPIC -O0
:info:build mkdir -p build/shared-release/generated/resources/fonts/noto/ ; /usr/bin/clang -ffunction-sections -fdata-sections -pipe -O2 -DNDEBUG -fomit-frame-pointer -Os -arch x86_64 -Iinclude -MMD -MP -o build/shared-release/generated/resources/fonts/noto/NotoSansOldPersian-Regular.otf.o -c generated/resources/fonts/noto/NotoSansOldPersian-Regular.otf.c -Wall -Wsign-compare -fPIC -O0
:info:build clang: note: diagnostic msg:
:info:build ********************
:info:build PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
:info:build Preprocessed source(s) and associated run script(s) are located at:
:info:build clang: note: diagnostic msg: /opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/.tmp/SourceHanSerif-Regular-5d1585.c
:info:build clang: note: diagnostic msg: /opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/.tmp/SourceHanSerif-Regular-5d1585.sh
:info:build clang: note: diagnostic msg: Crash backtrace is located in
:info:build clang: note: diagnostic msg: /opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/.home/Library/Logs/DiagnosticReports/clang_<YYYY-MM-DD-HHMMSS>_<hostname>.crash
:info:build clang: note: diagnostic msg: (choose the .crash file that corresponds to your crash)
:info:build clang: note: diagnostic msg:
:info:build ********************
:info:build make[1]: *** [build/shared-release/generated/resources/fonts/han/SourceHanSerif-Regular.ttc.o] Error 254
:info:build make[1]: *** Waiting for unfinished jobs....
:info:build make[1]: Leaving directory `/opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/mupdf-1.20.3-source'
:info:build make: *** [shared-release] Error 2
:info:build make: *** Waiting for unfinished jobs....
:info:build make: Leaving directory `/opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/mupdf-1.20.3-source'
:info:build Command failed:  cd "/opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/mupdf-1.20.3-source" && /usr/bin/make -j6 -w all PREFIX=/opt/local CC=/usr/bin/clang CXX=/usr/bin/clang++ CPP=/usr/bin/cpp XCFLAGS="-Os -arch x86_64" XLIBS="-L/opt/local/lib -Wl,-headerpad_max_install_names -arch x86_64" HAVE_GLUT=yes HAVE_X11=no USE_SYSTEM_LIBS=yes build=release verbose=yes shared
:info:build Exit code: 2
:error:build Failed to build mupdf: command execution failed
:debug:build Error code: CHILDSTATUS 99706 2
:debug:build Backtrace: command execution failed
:debug:build     while executing
:debug:build "system {*}$notty {*}$callback {*}$nice $fullcmdstring"
:debug:build     invoked from within
:debug:build "command_exec -callback portprogress::target_progress_callback build"
:debug:build     (procedure "portbuild::build_main" line 8)
:debug:build     invoked from within
:debug:build "$procedure $targetname"
:error:build See /opt/local/var/macports/logs/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/main.log for details.
</code>```

In MacPorts this is a known issue and it seems related to clang not being able to compile something because it runs out of resources when compiling NotoSansOldPersian-Regular.otf

Is there maybe a config or something we could temporary workaround by telling the mupdf configure not to compile this font? People (see ticket) already tried turning optimization off, using another compiler, but it is a more fundamental problem.

Body:
Mupdf no longer compiles on macOS 12.16.1. Using MacPorts for instance gives:

:info:build mkdir -p build/shared-release/generated/resources/fonts/noto/ ; /usr/bin/clang -ffunction-sections -fdata-sections -pipe -O2 -DNDEBUG -fomit-frame-pointer -Os -arch x86_64 -Iinclude -MMD -MP -o build/shared-release/generated/resources/fonts/noto/NotoSansOldPermic-Regular.otf.o -c generated/resources/fonts/noto/NotoSansOldPermic-Regular.otf.c -Wall -Wsign-compare -fPIC -O0
:info:build mkdir -p build/shared-release/generated/resources/fonts/noto/ ; /usr/bin/clang -ffunction-sections -fdata-sections -pipe -O2 -DNDEBUG -fomit-frame-pointer -Os -arch x86_64 -Iinclude -MMD -MP -o build/shared-release/generated/resources/fonts/noto/NotoSansOldPersian-Regular.otf.o -c generated/resources/fonts/noto/NotoSansOldPersian-Regular.otf.c -Wall -Wsign-compare -fPIC -O0
:info:build clang: note: diagnostic msg:
:info:build ********************
:info:build PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
:info:build Preprocessed source(s) and associated run script(s) are located at:
:info:build clang: note: diagnostic msg: /opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/.tmp/SourceHanSerif-Regular-5d1585.c
:info:build clang: note: diagnostic msg: /opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/.tmp/SourceHanSerif-Regular-5d1585.sh
:info:build clang: note: diagnostic msg: Crash backtrace is located in
:info:build clang: note: diagnostic msg: /opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/.home/Library/Logs/DiagnosticReports/clang_<YYYY-MM-DD-HHMMSS>_<hostname>.crash
:info:build clang: note: diagnostic msg: (choose the .crash file that corresponds to your crash)
:info:build clang: note: diagnostic msg:
:info:build ********************
:info:build make[1]: *** [build/shared-release/generated/resources/fonts/han/SourceHanSerif-Regular.ttc.o] Error 254
:info:build make[1]: *** Waiting for unfinished jobs....
:info:build make[1]: Leaving directory `/opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/mupdf-1.20.3-source'
:info:build make: *** [shared-release] Error 2
:info:build make: *** Waiting for unfinished jobs....
:info:build make: Leaving directory `/opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/mupdf-1.20.3-source'
:info:build Command failed:  cd "/opt/local/var/macports/build/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/work/mupdf-1.20.3-source" && /usr/bin/make -j6 -w all PREFIX=/opt/local CC=/usr/bin/clang CXX=/usr/bin/clang++ CPP=/usr/bin/cpp XCFLAGS="-Os -arch x86_64" XLIBS="-L/opt/local/lib -Wl,-headerpad_max_install_names -arch x86_64" HAVE_GLUT=yes HAVE_X11=no USE_SYSTEM_LIBS=yes build=release verbose=yes shared
:info:build Exit code: 2
:error:build Failed to build mupdf: command execution failed
:debug:build Error code: CHILDSTATUS 99706 2
:debug:build Backtrace: command execution failed
:debug:build     while executing
:debug:build "system {*}$notty {*}$callback {*}$nice $fullcmdstring"
:debug:build     invoked from within
:debug:build "command_exec -callback portprogress::target_progress_callback build"
:debug:build     (procedure "portbuild::build_main" line 8)
:debug:build     invoked from within
:debug:build "$procedure $targetname"
:error:build See /opt/local/var/macports/logs/_Users_gerben_MacPortsDev_macports-ports_graphics_mupdf/mupdf/main.log for details.

In MacPorts this is a known issue and it seems related to clang not being able to compile something because it runs out of resources when compiling NotoSansOldPersian-Regular.otf

Is there maybe a config or something we could temporary workaround by telling the mupdf configure not to compile this font? People (see ticket) already tried turning optimization off, using another compiler, but it is a more fundamental problem.


来源: stackexchange

问:
WebAuthN standard - identify available method
if a service is implementing the WebAuthN standard is it possible to get data which kind of platform authenticator is currently used? For a better usability we would like to know if the device has an fingerprint, face recognition etc. to text this while setup and usage.

Do you know the standard provides such information? If not what would be the alternative?

Looked through the W3 documentation but did not found the information needed.

ContentLicense: CC BY-SA 4.0


问:
How to enable "Build whenever a SNAPSHOT dependency is built" via Groovy-Multibranch-Pipeline
I have installed the Pipeline Maven Integration Plugin. Now I am trying to enable the Option "Build whenever a SNAPSHOT dependency is built" in my Multibranch pipelines via Groovy. I have tried integrating the following snippet, as suggested here.

```<code>properties([
    pipelineTriggers([
        snapshotDependencies()
    ])
])
</code>```

However, Jenkins is telling me that [t]he ‘properties’ section has been renamed as of version 0.8. Use ‘options’ instead. I am not sure, though, if options can anyhow be used for this purpose. Any help is much appreciated.

Body:
I have installed the Pipeline Maven Integration Plugin. Now I am trying to enable the Option "Build whenever a SNAPSHOT dependency is built" in my Multibranch pipelines via Groovy. I have tried integrating the following snippet, as suggested here.

properties([
    pipelineTriggers([
        snapshotDependencies()
    ])
])

However, Jenkins is telling me that [t]he ‘properties’ section has been renamed as of version 0.8. Use ‘options’ instead. I am not sure, though, if options can anyhow be used for this purpose. Any help is much appreciated.


问:
Spark performance issues when iteratively adding multiple columns
I am seeing performance issues when iteratively adding columns (around 100) to a Dataframe.

I know that it is more efficient to use select to add multiple columns however I have to add the columns in order because column2 may depend on column 1 etc. etc.

The columns are being added following a join which resulted in skew so I have explicitly repartitioned by a salt key to evenly distribute data on the cluster.

When I ran locally I was seeing OOM errors even for fairly small (100 row, 500 column) datasets.

I was able to get the job running locally by checkpointing after the addition of every x columns so I suspect spark lineage issues are causing my problems however I am still unable to run the job at scale on the cluster.

Any advice on where to look or on best practice in this scenario would be greatly received.

At a high level my job looks like this:

```<code>val df1 = ??? // Millions of rows, ~500 cols, from parquet
val df2 = ??? // 1000 rows, from parquet
val newExpressions = ??? // 100 rows, from Oracle

val joined = df1.join(broadcast(df2), <join expr>)

val newColumns = newExpressions.collectAsList.map(<get columnExpr and columnName>)

val salted = joined.withColumn("salt", rand()).repartition(x, col("salt"))

newColumns.foldLeft(joined) {
  case (df, row) => df.withColumn(col(row.expression).as(row.name))
} // Checkpointing after ever x columns seems to help

</code>```

Cheers

Terry

Body:
I am seeing performance issues when iteratively adding columns (around 100) to a Dataframe.

I know that it is more efficient to use select to add multiple columns however I have to add the columns in order because column2 may depend on column 1 etc. etc.

The columns are being added following a join which resulted in skew so I have explicitly repartitioned by a salt key to evenly distribute data on the cluster.

When I ran locally I was seeing OOM errors even for fairly small (100 row, 500 column) datasets.

I was able to get the job running locally by checkpointing after the addition of every x columns so I suspect spark lineage issues are causing my problems however I am still unable to run the job at scale on the cluster.

Any advice on where to look or on best practice in this scenario would be greatly received.

At a high level my job looks like this:

val df1 = ??? // Millions of rows, ~500 cols, from parquet
val df2 = ??? // 1000 rows, from parquet
val newExpressions = ??? // 100 rows, from Oracle

val joined = df1.join(broadcast(df2), <join expr>)

val newColumns = newExpressions.collectAsList.map(<get columnExpr and columnName>)

val salted = joined.withColumn("salt", rand()).repartition(x, col("salt"))

newColumns.foldLeft(joined) {
  case (df, row) => df.withColumn(col(row.expression).as(row.name))
} // Checkpointing after ever x columns seems to help

Cheers

Terry


问:
How to stop the localhost redirection to https automatically?
When i try to run the react project which is present in my localsystem it automatically opens in https connection whereas few of my api's are integrated in http. So it throws mixed content error. I cant update my code to https as of now.. Is there any way to make my browser open localhost in HTTP??

I tried open localhost using http but it shows "Your connection is not secure".. I tried few possible ways to resolve like changing security settings, But still it doesnt work.


问:
Filter by method attribute in Doxygen
I am new to Doxygen but I want to use it for a technical documentation for our team.
The background: We have several services in .NET which are going to be called from a JAVA backend through RPC.
Therefore it is quite useful to have those services documented for the JAVA guys.

Using the Doxywizard did help in the first place, but it created a huge overflow of data, which I want to filter, but have no clue how to.

What I want to achieve is, that Doxygen ONLY will use methods, which does have a specific attribute.

For example:

```<code>[RpcMethod(id: "GetNumDemo", description: "A demo method")]
public async Task<int> GetNumDemo(JavaDTO dtoObject, int randNum)
</code>```

I want to have the method within the documentation found by Doxygen since it has the RpcMethod attribute and also cause it have a JavaDTO object, I want to have this class documented as well.
But I am overwhelmed with it ... do you guys can help me? ... at least with a hint within the Doxygen documentation.

Read through the documentation and goodled

Title: Filter by method attribute in Doxygen

Body:
I am new to Doxygen but I want to use it for a technical documentation for our team.
The background: We have several services in .NET which are going to be called from a JAVA backend through RPC.
Therefore it is quite useful to have those services documented for the JAVA guys.

Using the Doxywizard did help in the first place, but it created a huge overflow of data, which I want to filter, but have no clue how to.

What I want to achieve is, that Doxygen ONLY will use methods, which does have a specific attribute.

For example:

[RpcMethod(id: "GetNumDemo", description: "A demo method")]
public async Task<int> GetNumDemo(JavaDTO dtoObject, int randNum)

I want to have the method within the documentation found by Doxygen since it has the RpcMethod attribute and also cause it have a JavaDTO object, I want to have this class documented as well.
But I am overwhelmed with it ... do you guys can help me? ... at least with a hint within the Doxygen documentation.

Read through the documentation and goodled


问:
How to fix time in queryParameters in flutter?
I want to make a get request with DateTime inside query parameters, but DateTime takes not that form that I want. How to fix that?

I want to set this currentDate to query parameter

```<code>final currentDate = DateFormat('yyyy-MM-ddTHH:mm:ss').format(DateTime.now().toLocal());
log(currentDate); //from=2022-12-06T16:17:46
</code>```

But I get this

```<code>final data = await _apiService.getNfbByPeriod(from: currentDate, to: DateTime(2022), token: accessToken!);
// currentDate = 2022-12-06T16%3A17%3A46

// /sessions/avg-nfb-by-period?from=2022-12-06T16%3A17%3A46&to=2022-01-01+00%3A00%3A00.000
</code>```

Body:
I want to make a get request with DateTime inside query parameters, but DateTime takes not that form that I want. How to fix that?

I want to set this currentDate to query parameter

final currentDate = DateFormat('yyyy-MM-ddTHH:mm:ss').format(DateTime.now().toLocal());
log(currentDate); //from=2022-12-06T16:17:46

But I get this

final data = await _apiService.getNfbByPeriod(from: currentDate, to: DateTime(2022), token: accessToken!);
// currentDate = 2022-12-06T16%3A17%3A46

// /sessions/avg-nfb-by-period?from=2022-12-06T16%3A17%3A46&to=2022-01-01+00%3A00%3A00.000


问:
How to create an .net core api to accept the slack notification request
How to create an .net core api to accept the slack notification request with below

1.Application Name
2.slack channel name
3.subject
4.body


问:
request.security function cause repaint eventhough the timeframe is same with the chart?
The tradingview help center says that request.security function can cause repaint issue

if the timeframe argument is not the same as the chart timeframe.

Then, vice versa, if the timeframe argument is the same as the chart time frame, It never causes repaint??

below is the example I'm struggling with

=>

I`m using, for example, three security functions A & B & C with the same timeframe as the chart.

say,

A = request.security("AVAXBUSD","",ta.rsi(close,14))

B = request.security("UNIBUSD","",ta.rsi(close,14))

C = request.security("BTCBUSD","",ta.rsi(close,14))

and at the close,

compare A,B,C and

(1) plot the biggest one on the chart bar.

(2) simultaneously, send alert texting the biggest one.

usually, the (1) and (2) are making the same results.

However, I found that sometimes, (1) is not equal to  (2)

I thought it is a kind of repaint issue.

(of course, I didn`t use other risky functions such as valuewhen, barstate series and so on)

So, my question is :

I guess it happens because at the close, sometimes, there may be a slow chart symbol that not completed yet due to data lagging from the exchange. is it right?

or it is caused by other issues?
(for example, at 2:00 pm, is may be possible that AVAXBUSD, BTCBUSD 1hour bar are completed but UNIBUSD bar is not completed yet?)

[
As an example scenario: at 2:00 pm, UNIBUSD 1-hour bar is not completed.

so when sending alert, the logic have no other way than comparing the remained AVAXBUSD and BTCBUSD.

so it can send alert meaning BTCBUSD is the biggest one.

on the other hand, when plotting on the chart after a few seconds, UNIBUSD 1hour bar would be completed.

so it is possible sending the actual truely biggest one UNIBUSD.
]

FYI, this happens more frequently on a lower chart timeframe than a higher chart timeframe.

Best regards


问:
mlxtend Sequential Feature Selector (SFS) for Regression
I have used SFS from mlxtend with r2 scorer. The thing about R2 is that in regression models, with addition of new features R2 will always increase. Hence, is it ever useful to use R2 as a scorer or should a custom function with adjusted r2 be always used?

While I have seen R2 used in practice, I have seen the plot where with more features I see R2 dropping. For example in this notebook https://www.kaggle.com/code/jorijnsmit/linear-regression-by-sequential-feature-selection the validation section has the SFS plot where R2 is dropping on adding new features.

SFS Plot

Can someone pls help me understand how this is possible?


问:
How to properly terminate server instance in python gstreamer api and restart with new settings?
I have written a simple python API to control a gstreamer RTSP server.
I have a couple of configurable parameters for the stream that I want to change from the API.

The way I stop the stream does indeed prevent new connections from being made(so something right is happening), but I have two problems:
It doesn't kill existing connections(I'm assuming it's therefore not a complete reset) and more importantly it doesn't load the new settings if changed unless I restart the whole fastapi server.

```<code>from threading import Thread
import json, os
import gi

gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import GLib, Gst, GstRtspServer

from fastapi import FastAPI

app = FastAPI()
loop = GLib.MainLoop()

CONFIG_DEFAULTS = {
    'host': '127.0.0.1',
    'port': '8554',
    'mount': '/test',
    'width': '1280',
    'height': '800',
    'bitrate': '50000',
    'fps': '30'
}
CONFIGFILE = "config.cfg"

def load_config():
    with open(CONFIGFILE) as f:
        return json.load(f)

def save_config(config):
    with open(CONFIGFILE, 'w') as f:
        json.dump(config, f)
    return True

@app.on_event("startup")
async def startup_event():
    if not os.path.exists(CONFIGFILE):
        with open(CONFIGFILE, 'w') as f:
            json.dump(CONFIG_DEFAULTS, f)

@app.get("/get-fps")
def get_fps():
    config = load_config()
    return config['fps']

@app.get("/set-fps/{fps}")
def set_fps(fps: int):
    config = load_config()
    config['fps'] = fps
    save_config(config)
    return True

@app.get("/get-bitrate")
def get_bitrate():
    config = load_config()
    return config['bitrate']

@app.get("/set-bitrate/{bitrate}")
def set_bitrate(bitrate: int):
    config = load_config()
    config['bitrate'] = bitrate
    save_config(config)
    return True

@app.get("/get-resolution")
def get_resolution():
    config = load_config()
    return {
        'width': config['width'],
        'height': config['height'],
    }

@app.get("/set-resolution/{width}&{height}")
def set_resolution(width: int, height: int):
    config = load_config()
    config['width'] = width
    config['height'] = height
    save_config(config)
    return True

@app.get("/get-url")
def get_url():
    config = load_config()
    return config['host'] + ":" + config['port'] + config['mount']

@app.get("/start-stream")
def start_stream():

    Gst.init(None)
    config = load_config()
    server = GstRtspServer.RTSPServer()
    port = config['port']
    mount = config['mount']
    width = str(config['width'])
    height = str(config['height'])
    fps = str(config['fps'])
    bitrate = str(config['bitrate'])
    server.service = port
    mounts = server.get_mount_points()
    factory = GstRtspServer.RTSPMediaFactory()
    pipeline = "v4l2src device=/dev/video0 io-mode=2  ! " + \
                "image/jpeg,width="+width+",height="+height+",framerate="+fps+"/1 ! " + \
                "nvjpegdec ! " + \
                "video/x-raw ! " + \
                "omxh264enc bitrate="+bitrate+" control-rate=constant ! " + \
                "rtph264pay name=pay0 pt=96"

    factory.set_launch(pipeline)
    factory.set_shared(True)
    mounts.add_factory(mount, factory)
    server.attach()

    loop_thread = Thread(target=run_loop)
    loop_thread.start()
    return 'stream ready at rtsp://127.0.0.1:%s%s' % (port, mount)

def run_loop():
    global loop
    loop.run()

@app.get("/stop-stream")
def stop_stream():
    global loop
    loop.quit()
    return True
</code>```

I have also tried with an unref call to context but perhaps I am missing something in how the server is setup.

```<code>    loop.quit()
    loop.get_context().unref()
</code>```

Body:
I have written a simple python API to control a gstreamer RTSP server.
I have a couple of configurable parameters for the stream that I want to change from the API.

The way I stop the stream does indeed prevent new connections from being made(so something right is happening), but I have two problems:
It doesn't kill existing connections(I'm assuming it's therefore not a complete reset) and more importantly it doesn't load the new settings if changed unless I restart the whole fastapi server.

from threading import Thread
import json, os
import gi

gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import GLib, Gst, GstRtspServer

from fastapi import FastAPI

app = FastAPI()
loop = GLib.MainLoop()

CONFIG_DEFAULTS = {
    'host': '127.0.0.1',
    'port': '8554',
    'mount': '/test',
    'width': '1280',
    'height': '800',
    'bitrate': '50000',
    'fps': '30'
}
CONFIGFILE = "config.cfg"

def load_config():
    with open(CONFIGFILE) as f:
        return json.load(f)

def save_config(config):
    with open(CONFIGFILE, 'w') as f:
        json.dump(config, f)
    return True

@app.on_event("startup")
async def startup_event():
    if not os.path.exists(CONFIGFILE):
        with open(CONFIGFILE, 'w') as f:
            json.dump(CONFIG_DEFAULTS, f)

@app.get("/get-fps")
def get_fps():
    config = load_config()
    return config['fps']

@app.get("/set-fps/{fps}")
def set_fps(fps: int):
    config = load_config()
    config['fps'] = fps
    save_config(config)
    return True

@app.get("/get-bitrate")
def get_bitrate():
    config = load_config()
    return config['bitrate']

@app.get("/set-bitrate/{bitrate}")
def set_bitrate(bitrate: int):
    config = load_config()
    config['bitrate'] = bitrate
    save_config(config)
    return True

@app.get("/get-resolution")
def get_resolution():
    config = load_config()
    return {
        'width': config['width'],
        'height': config['height'],
    }

@app.get("/set-resolution/{width}&{height}")
def set_resolution(width: int, height: int):
    config = load_config()
    config['width'] = width
    config['height'] = height
    save_config(config)
    return True

@app.get("/get-url")
def get_url():
    config = load_config()
    return config['host'] + ":" + config['port'] + config['mount']

@app.get("/start-stream")
def start_stream():

    Gst.init(None)
    config = load_config()
    server = GstRtspServer.RTSPServer()
    port = config['port']
    mount = config['mount']
    width = str(config['width'])
    height = str(config['height'])
    fps = str(config['fps'])
    bitrate = str(config['bitrate'])
    server.service = port
    mounts = server.get_mount_points()
    factory = GstRtspServer.RTSPMediaFactory()
    pipeline = "v4l2src device=/dev/video0 io-mode=2  ! " + \
                "image/jpeg,width="+width+",height="+height+",framerate="+fps+"/1 ! " + \
                "nvjpegdec ! " + \
                "video/x-raw ! " + \
                "omxh264enc bitrate="+bitrate+" control-rate=constant ! " + \
                "rtph264pay name=pay0 pt=96"

    factory.set_launch(pipeline)
    factory.set_shared(True)
    mounts.add_factory(mount, factory)
    server.attach()

    loop_thread = Thread(target=run_loop)
    loop_thread.start()
    return 'stream ready at rtsp://127.0.0.1:%s%s' % (port, mount)

def run_loop():
    global loop
    loop.run()

@app.get("/stop-stream")
def stop_stream():
    global loop
    loop.quit()
    return True

I have also tried with an unref call to context but perhaps I am missing something in how the server is setup.

    loop.quit()
    loop.get_context().unref()


问:
How to make natural batching on Flux?
Is there any easy way to make natural batching (smart batching) on Flux?

What is natural batching (read more here: https://mechanical-sympathy.blogspot.com/2011/10/smart-batching.html )?

Batching, which is done in single thread with end-less loop like:

collect all items in queue (at least single item)

do operation on them (batch insert into DB for example)

This would mean that logic of project reactor is a bit "reversed". Instead of "take(x)", we need to collect things in buffer, while doing operations on previous batch and limit how match items to "pre-fetch" for next batch.

PS: I would expect some info here https://projectreactor.io/docs/core/release/reference/#advanced-three-sorts-batching about natural batching

PS2: Is would make some Publisher to achieve this  behavior perhaps. Is this OK approach?

Title: How to make natural batching on Flux?


问:
ffmpeg command for overlaying a video onto am image with blend
I have these requirements but cant seem to get this even close :

ffmpeg to produce a mp4 video

inputs : an image of varying size, an audio wav of X length, a video for the overlay such as particles or dust

create an mp4 with the image as the final video size, the overlay video light blended into the image using zoom/crop (no stretching of size), length of video is size of audio

assume the video overlay is bigger than the image as far as height and width


问:
NetworkX graph object slower than using dictionary mapping
I recently made an implementation of the PageRank algorithm used by google which displays the most relevant web pages. There are two ways to approach the PageRank algorithm, with random internet surfers who browse the internet (walkers) -stochastic algorithm- or with the probability of landing on a specific page -distribution algorithm.

I first tried using dictionaries to store the nodes as keys and the list of their outgoing edges as their values. However, this approach requires a lot of time to run the algorithms - especially the stochastic one. For example, on my machine the distribution algorithm requires roughly 1.5s (30 steps) while the stochastic one requires roughly 50s (30 steps, 100,000 repeats).

Next, I tried using the library NetworkX to optimize the performance of the algorithms, but instead of running faster, it runs slower. Using the same parameters, distribution requires
around 6s and stochastic requires about 280s. I was wondering why this is the case and if there is any other way to optimize the code, either by using networkx differently or using a different library of which I am not aware.

In both approaches, I read a file in which each line is a node and a target separated by space.

Here is the code:

Creating the dictionary

```<code>def load_graph(args):
    """Load graph from text file

    Parameters:
    args -- arguments named tuple

    Returns:
    A dict mapping a URL (str) to a list of target URLs (str).
    """
    dictionary = {}
    nodes = []
    targets = []
    # Iterate through the file line by line
    for line in args.datafile:
        # And split each line into two URLs
        node, target = line.split()
        nodes.append(node)
        if node not in dictionary.keys():
            targets = []
        targets.append(target)
        dictionary[node] = targets
    return dictionary
</code>```

Networkx approach:

```<code>def load_graph(args):
    """Load graph from text file

    Parameters:
    args -- arguments named tuple

    Returns:
    A graph object mapping all URLs (str) to their target URLs (str).
    """
    # Use networkx to load the graph
    graph = nx.read_edgelist(args.datafile, create_using=nx.DiGraph())
    return graph
</code>```

Body:
I recently made an implementation of the PageRank algorithm used by google which displays the most relevant web pages. There are two ways to approach the PageRank algorithm, with random internet surfers who browse the internet (walkers) -stochastic algorithm- or with the probability of landing on a specific page -distribution algorithm.

I first tried using dictionaries to store the nodes as keys and the list of their outgoing edges as their values. However, this approach requires a lot of time to run the algorithms - especially the stochastic one. For example, on my machine the distribution algorithm requires roughly 1.5s (30 steps) while the stochastic one requires roughly 50s (30 steps, 100,000 repeats).

Next, I tried using the library NetworkX to optimize the performance of the algorithms, but instead of running faster, it runs slower. Using the same parameters, distribution requires
around 6s and stochastic requires about 280s. I was wondering why this is the case and if there is any other way to optimize the code, either by using networkx differently or using a different library of which I am not aware.

In both approaches, I read a file in which each line is a node and a target separated by space.

Here is the code:

Creating the dictionary

def load_graph(args):
    """Load graph from text file

    Parameters:
    args -- arguments named tuple

    Returns:
    A dict mapping a URL (str) to a list of target URLs (str).
    """
    dictionary = {}
    nodes = []
    targets = []
    # Iterate through the file line by line
    for line in args.datafile:
        # And split each line into two URLs
        node, target = line.split()
        nodes.append(node)
        if node not in dictionary.keys():
            targets = []
        targets.append(target)
        dictionary[node] = targets
    return dictionary

Networkx approach:

def load_graph(args):
    """Load graph from text file

    Parameters:
    args -- arguments named tuple

    Returns:
    A graph object mapping all URLs (str) to their target URLs (str).
    """
    # Use networkx to load the graph
    graph = nx.read_edgelist(args.datafile, create_using=nx.DiGraph())
    return graph


问:
How to get mouse position x,y,z in matplot 3d bar plot based on Python
I am currently working on 3D bar chart with Matplotlib in Python environment.
I want to visualize information when the mouse is over the target position as follows:

Display pre-defined information when the mouse is over the position (X, Y, Z).

I tried various library (Plotly, Folium, chart, cursor, or etc.,); however, it is reuqired to work on custom map information, I should do with '3D Bar plot' in matplotlib.

I implemented the custom map, but there is no idea how to get mouse position and visualize the information board.

```<code>fig = plt.figure(figsize=(8,8), facecolor='grey')
ax = fig.add_subplot(projection='3d', facecolor='grey')

for each_building in buildings:

    x_center = each_building[0][-1] - (each_building[0][-1] - each_building[0][0])
    y_center = np.take(each_building[1], each_building[1].size // 2)

    # ax.bar3d(each_building[0], each_building[1], each_building[2], 1, 1, 1, zsort='average', color='grey', alpha=0.4, shade=True)
    ax.bar3d(each_building[0], each_building[1], each_building[2],\
    np.ones(len(each_building[0])), np.ones(len(each_building[0])), np.ones(len(each_building[0])),\
    zsort='average', color='grey', alpha=0.4, shade=True
    )
    # ax.bar(each_building[0], each_building[1], color='grey', alpha=0.4)

    if each_building[-1] == 'nursing station':
        ax.text(x_center+2, y_center, 0.4, each_building[-1], size=10, zorder=20, color='lightblue')
    else:
        ax.text(x_center, y_center, 0.9, each_building[-1], size=10, zorder=20, color='lightblue')

ax.set_xlim(-5.0, 40.0)
ax.set_ylim(0, 60.0)
ax.set_zlim(0, 5)
</code>```

It would be very nice to get me any hints or helps :))

Body:
I am currently working on 3D bar chart with Matplotlib in Python environment.
I want to visualize information when the mouse is over the target position as follows:

Display pre-defined information when the mouse is over the position (X, Y, Z).

I tried various library (Plotly, Folium, chart, cursor, or etc.,); however, it is reuqired to work on custom map information, I should do with '3D Bar plot' in matplotlib.

I implemented the custom map, but there is no idea how to get mouse position and visualize the information board.

fig = plt.figure(figsize=(8,8), facecolor='grey')
ax = fig.add_subplot(projection='3d', facecolor='grey')

for each_building in buildings:

    x_center = each_building[0][-1] - (each_building[0][-1] - each_building[0][0])
    y_center = np.take(each_building[1], each_building[1].size // 2)

    # ax.bar3d(each_building[0], each_building[1], each_building[2], 1, 1, 1, zsort='average', color='grey', alpha=0.4, shade=True)
    ax.bar3d(each_building[0], each_building[1], each_building[2],\
    np.ones(len(each_building[0])), np.ones(len(each_building[0])), np.ones(len(each_building[0])),\
    zsort='average', color='grey', alpha=0.4, shade=True
    )
    # ax.bar(each_building[0], each_building[1], color='grey', alpha=0.4)

    if each_building[-1] == 'nursing station':
        ax.text(x_center+2, y_center, 0.4, each_building[-1], size=10, zorder=20, color='lightblue')
    else:
        ax.text(x_center, y_center, 0.9, each_building[-1], size=10, zorder=20, color='lightblue')

ax.set_xlim(-5.0, 40.0)
ax.set_ylim(0, 60.0)
ax.set_zlim(0, 5)

It would be very nice to get me any hints or helps :))


问:
Concatenating two pandas dataframes horizontally
Before concatenating both Dataframes have 7841 rows but after concatenation, the number of rows suddenly increased to 9005.

```<code>trans_features=['Customer_Age',
            'Dependent_count',
            'Contacts_Count_12_mon',
            'Months_Inactive_12_mon',
            'Credit_Limit',
            'Total_Revolving_Bal',
            'Total_Amt_Chng_Q4_Q1',
            'Total_Trans_Amt',
            'Total_Ct_Chng_Q4_Q1',
            'Avg_Utilization_Ratio']

df_trans_feat = df_bank[trans_features]

pt = PowerTransformer()   # By default it's yeo-johnson transformation
transformed = pt.fit_transform(df_trans_feat)

df_transformed = pd.DataFrame(transformed,
columns=df_trans_feat.columns)
print("df_transformed:", df_transformed.shape)
df_bank.drop(df_trans_feat, axis=1, inplace=True)
print("df_bank:", df_bank.shape)

df_bank_comb = pd.concat([df_bank, df_transformed], axis=1)
print("df_bank_comb:", df_bank_comb.shape)

Output:
df_transformed: (7841, 10)
df_bank: (7841, 7)
df_bank_comb: (9005, 17)
</code>```

The increase in number of rows is baffling.
My intention is to combine the two dataframes horizontally. Is there any problem in my concat statement?

Body:
Before concatenating both Dataframes have 7841 rows but after concatenation, the number of rows suddenly increased to 9005.

trans_features=['Customer_Age',
            'Dependent_count',
            'Contacts_Count_12_mon',
            'Months_Inactive_12_mon',
            'Credit_Limit',
            'Total_Revolving_Bal',
            'Total_Amt_Chng_Q4_Q1',
            'Total_Trans_Amt',
            'Total_Ct_Chng_Q4_Q1',
            'Avg_Utilization_Ratio']

df_trans_feat = df_bank[trans_features]

pt = PowerTransformer()   # By default it's yeo-johnson transformation
transformed = pt.fit_transform(df_trans_feat)

df_transformed = pd.DataFrame(transformed,
columns=df_trans_feat.columns)
print("df_transformed:", df_transformed.shape)
df_bank.drop(df_trans_feat, axis=1, inplace=True)
print("df_bank:", df_bank.shape)

df_bank_comb = pd.concat([df_bank, df_transformed], axis=1)
print("df_bank_comb:", df_bank_comb.shape)

Output:
df_transformed: (7841, 10)
df_bank: (7841, 7)
df_bank_comb: (9005, 17)

The increase in number of rows is baffling.
My intention is to combine the two dataframes horizontally. Is there any problem in my concat statement?


问:
Attached document in SOAP request (MTOM), does not arrive at webservice
I've created a SOAP webserice that upload document (using MTOM), but on the server side the DataHandler object is empty (dataHandler.getInputStream is empty too).

my dataHandler object

And this is the document in my request:

```<code><content><inc:Include href="cid:BP_275627594_SP39274815_46048927_49441074-49441075_1666846379.pdf" xmlns:inc="http://www.w3.org/2004/08/xop/include"/></content>
</code>```

My request properties

I've tried to solve it this way:

```<code>    <xs:element name="DocumentRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="ID" type="xs:string"/>
                <xs:element name="Level" type="xs:string"/>
                <xs:element name="content" type="xs:base64Binary" xmime:expectedContentTypes="*/*"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</code>```
```<code>@XmlRootElement(name = "DocumentRequest")
public class DocumentRequest
    implements Serializable
{

    private final static long serialVersionUID = 1L;
    @XmlElement(required = true)
    protected String ID;
    @XmlElement(required = true)
    protected String Level;
    @XmlElement(required = true)
    @XmlMimeType("*/*")
    protected DataHandler content;

</code>```
```<code>@MTOM(enabled = true)
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "DocumentRequest")
@ResponsePayload
public DocumentResponse document(@RequestPayload DocumentRequest request) throws Exception {
    System.out.println(request.getContent().getInputStream().available());

</code>```

In summary, why I can't reach the attached file from code?

Thank You!

Body:
I've created a SOAP webserice that upload document (using MTOM), but on the server side the DataHandler object is empty (dataHandler.getInputStream is empty too).

my dataHandler object

And this is the document in my request:

<content><inc:Include href="cid:BP_275627594_SP39274815_46048927_49441074-49441075_1666846379.pdf" xmlns:inc="http://www.w3.org/2004/08/xop/include"/></content>

My request properties

I've tried to solve it this way:

    <xs:element name="DocumentRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="ID" type="xs:string"/>
                <xs:element name="Level" type="xs:string"/>
                <xs:element name="content" type="xs:base64Binary" xmime:expectedContentTypes="*/*"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

@XmlRootElement(name = "DocumentRequest")
public class DocumentRequest
    implements Serializable
{

    private final static long serialVersionUID = 1L;
    @XmlElement(required = true)
    protected String ID;
    @XmlElement(required = true)
    protected String Level;
    @XmlElement(required = true)
    @XmlMimeType("*/*")
    protected DataHandler content;

@MTOM(enabled = true)
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "DocumentRequest")
@ResponsePayload
public DocumentResponse document(@RequestPayload DocumentRequest request) throws Exception {
    System.out.println(request.getContent().getInputStream().available());

In summary, why I can't reach the attached file from code?

Thank You!


问:
want to find the files name that containes specified pattern in my bitbucket repo
From many previous years, we have had massive Bitbucket repos that contained too large production files. We're trying to identify the names of the files that contain a certain pattern (regex pattern ).

Cloning the repo and using Linux grep is also a solution but it's too heavy work and not feasible at this moment.
If it is solved by directly providing the URL address of the repo and performing a pattern search within it and recording the name list of those files whose content matches the provided pattern (regex or any pattern) please let us know.


问:
Wait for retry in OkHttp interceptor, but cancel happens on timeout
The OkHttp client cancels a call once it times out. I'd like a retry interceptor that resets this and calls once more.

I read here that the time out includes retries.
https://square.github.io/okhttp/4.x/okhttp/okhttp3/-ok-http-client/-builder/call-timeout/

Is there a way to retry a cancelled call in the interceptor? I found that if you clone the call its request maintains the 'cancelled' status.


问:
Typescript / Express.js - Not able to send back User object on req.user in TS
I am really stable with normal JS but as I started migrating to TS I am getting a lot of trubles. Normally I would return req.user = user, but right now with TS I am not anymore able to do that, can anyone help me? Thanks

```<code>
export const auth = async(req: Request, res:Response, next: NextFunction) => {
    try {
        const token = req.headers["authorization"]?.replace('Bearer ' , '');
        const isValidToken: any = verify(<string>token, 'secret');

        const driver = await Driver.findById({_id: isValidToken._id});

        req.user = driver; //  <= Here I get an Error

        //Property 'user' does not exist on type 'Request<ParamsDictionary, any, any,
        //ParsedQs, Record<string, any>>'.ts(2339)

        next();
    } catch(e) {
        res.status(400).send({e});
    }

}
</code>```

Normally I would return req.user = user, but right now with TS I am not anymore able to do that, can anyone help me? Thanks

Body:
I am really stable with normal JS but as I started migrating to TS I am getting a lot of trubles. Normally I would return req.user = user, but right now with TS I am not anymore able to do that, can anyone help me? Thanks

export const auth = async(req: Request, res:Response, next: NextFunction) => {
    try {
        const token = req.headers["authorization"]?.replace('Bearer ' , '');
        const isValidToken: any = verify(<string>token, 'secret');

        const driver = await Driver.findById({_id: isValidToken._id});

        req.user = driver; //  <= Here I get an Error

        //Property 'user' does not exist on type 'Request<ParamsDictionary, any, any,
        //ParsedQs, Record<string, any>>'.ts(2339)

        next();
    } catch(e) {
        res.status(400).send({e});
    }

}

Normally I would return req.user = user, but right now with TS I am not anymore able to do that, can anyone help me? Thanks


问:
Sum of rows having same value python pandas
I have a dataframe like this:

```<code>col1 col2   col3
1    apple   50
2    apple   25
3    banana  30
4    banana  20
5    apple   100
6    apple   10
</code>```

I want to get the sum of col3 for unique col2.

For example--

```<code>col1 col2     col3
1     apple    185
2     banana    50
</code>```

Body:
I have a dataframe like this:

col1 col2   col3
1    apple   50
2    apple   25
3    banana  30
4    banana  20
5    apple   100
6    apple   10

I want to get the sum of col3 for unique col2.

For example--

col1 col2     col3
1     apple    185
2     banana    50


问:
TypeORM : Create custom serialization for an object
I want to know how I can create a custom serialization for my object in my model:

I have my class Job which contains :

Job ID

Job EXP

And my model for mapping contains:

Job (my class job)

ID (int)
etc...

And I want to serialize it as json on my mysql database but I can't find a way to do it.

Can someone help me please ?

Thanks you

Have a nice day

I try to search for documentation or some others sources.

Explore on some code on github who use typeorm.


问:
Is it possible to get email address as principalId while using Google OAuth with Spring security
I have an app that works with multiple Oauth2 sources, google being one of them. I want to be able to get the principalID or basically OAuth2AuthenticationToken.getName to be the email address rather than the long number that google provides. This is because I want to map this ID to some app specific user information and having to find out the long num for every user is a bit of a pain. Alternatively is there an easy way to get the identifier for every user?</p>


问:
Electron JS Deep Linking not passing the link atribute when cold starting the app
I am attempting to open a deep link example://example.com in electron, It works perfectly when the aplication is already running however it does not seam to pass the link if it is not. opening the pre-defined variable

```<code>deeplinkingUrl
</code>```

instead

My whole attempt is as follows

```<code>const { app, BrowserWindow } = require('electron')
// Module with utilities for working with file and directory paths.
const path = require('path')
// Module with utilities for URL resolution and parsing.
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

// Deep linked url
let deeplinkingUrl = "https://example.com/"

const gotTheLock = app.requestSingleInstanceLock()

// Force Single Instance Application

if (!gotTheLock) {
    app.quit()
} else {
    app.on('second-instance', (event, argv, cwd) => {
        if (process.platform == 'win32') {
            deeplinkingUrl = argv.slice(1)
            deeplinkingUrl = deeplinkingUrl[1]
            deeplinkingUrl = deeplinkingUrl.replace("exmaple", "https")
        }
        logEverywhere("#app", deeplinkingUrl)
        mainWindow.loadURL(deeplinkingUrl)

        if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore()
            mainWindow.focus()
        }
    })
}

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({ width: 800, height: 600, icon: __dirname + '/icon.png', })
    mainWindow.loadURL(deeplinkingUrl)
    mainWindow.webContents.openDevTools()
    if (process.platform == 'win32') {
        // deeplinkingUrl = process.argv.slice(1)
        // deeplinkingUrl = deeplinkingUrl[1]
        // deeplinkingUrl = deeplinkingUrl.replace("exmaple", "https")
    }
    logEverywhere("#newWindow", deeplinkingUrl)
    mainWindow.loadURL(deeplinkingUrl)
    mainWindow.webContents.openDevTools()
    logEverywhere("#argv", process.argv)

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null
    })
}

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function () {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
})

// Define custom protocol handler. Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('exmaple')

// Protocol handler for osx
app.on('open-url', function (event, url) {
    event.preventDefault()
    deeplinkingUrl = url
    logEverywhere("#app", "open-url# " + deeplinkingUrl)
})

// Log both at dev console and at running node console instance
function logEverywhere(s) {
    console.log(s)
    if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
    }
}
</code>```

I am not sure where to go off from here.

App is bubilt using

```<code>"electron-builder": "^23.6.0"
</code>```

and running

```<code>"electron": "^21.3.1",
</code>```

I am running on Win 10

Body:
I am attempting to open a deep link example://example.com in electron, It works perfectly when the aplication is already running however it does not seam to pass the link if it is not. opening the pre-defined variable

deeplinkingUrl

instead

My whole attempt is as follows

const { app, BrowserWindow } = require('electron')
// Module with utilities for working with file and directory paths.
const path = require('path')
// Module with utilities for URL resolution and parsing.
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

// Deep linked url
let deeplinkingUrl = "https://example.com/"

const gotTheLock = app.requestSingleInstanceLock()

// Force Single Instance Application

if (!gotTheLock) {
    app.quit()
} else {
    app.on('second-instance', (event, argv, cwd) => {
        if (process.platform == 'win32') {
            deeplinkingUrl = argv.slice(1)
            deeplinkingUrl = deeplinkingUrl[1]
            deeplinkingUrl = deeplinkingUrl.replace("exmaple", "https")
        }
        logEverywhere("#app", deeplinkingUrl)
        mainWindow.loadURL(deeplinkingUrl)

        if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore()
            mainWindow.focus()
        }
    })
}

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({ width: 800, height: 600, icon: __dirname + '/icon.png', })
    mainWindow.loadURL(deeplinkingUrl)
    mainWindow.webContents.openDevTools()
    if (process.platform == 'win32') {
        // deeplinkingUrl = process.argv.slice(1)
        // deeplinkingUrl = deeplinkingUrl[1]
        // deeplinkingUrl = deeplinkingUrl.replace("exmaple", "https")
    }
    logEverywhere("#newWindow", deeplinkingUrl)
    mainWindow.loadURL(deeplinkingUrl)
    mainWindow.webContents.openDevTools()
    logEverywhere("#argv", process.argv)

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null
    })
}

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function () {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
})

// Define custom protocol handler. Deep linking works on packaged versions of the application!
app.setAsDefaultProtocolClient('exmaple')

// Protocol handler for osx
app.on('open-url', function (event, url) {
    event.preventDefault()
    deeplinkingUrl = url
    logEverywhere("#app", "open-url# " + deeplinkingUrl)
})

// Log both at dev console and at running node console instance
function logEverywhere(s) {
    console.log(s)
    if (mainWindow && mainWindow.webContents) {
        mainWindow.webContents.executeJavaScript(`console.log("${s}")`)
    }
}

I am not sure where to go off from here.

App is bubilt using

"electron-builder": "^23.6.0"

and running

"electron": "^21.3.1",

I am running on Win 10


问:
Chrome Extension icon not showing up
So I'm trying to build a chrome extension but when I load it locally to test it, it all works perfectly except for the icon which doesn't show up and I find instead this blue puzzle piece:

My manifest looks like this:

```<code>{
  "manifest_version": 3,
  "name": "The World News",
  "version": "1.0.0",
  "action": {
    "default_popup": "hello.html",
    "default_icon": {
      "128": "icon128.png"
    }
  },
  "description": "Chrome extensions that takes the top threads from the subreddit WorldNews",
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "author": "Adrian Aranda"
}
</code>```

and my folders are looking like this:

How can I do it so the icon shows up?

I've been trying different icons, removing some sizes and researching on how the manifest should be, but none of it worked and all I could see was the blue puzzle icon.

Title: Chrome Extension icon not showing up

Body:
So I'm trying to build a chrome extension but when I load it locally to test it, it all works perfectly except for the icon which doesn't show up and I find instead this blue puzzle piece:

My manifest looks like this:

{
  "manifest_version": 3,
  "name": "The World News",
  "version": "1.0.0",
  "action": {
    "default_popup": "hello.html",
    "default_icon": {
      "128": "icon128.png"
    }
  },
  "description": "Chrome extensions that takes the top threads from the subreddit WorldNews",
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "author": "Adrian Aranda"
}

and my folders are looking like this:

How can I do it so the icon shows up?

I've been trying different icons, removing some sizes and researching on how the manifest should be, but none of it worked and all I could see was the blue puzzle icon.


问:
How to capture the backbuffer that has been rendered in another thread
I'm making a function that captures the screen within a game.

I implemented it like this.

```<code>void somecapture()
{
    d3dDevice->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);
    d3dDevice->CreateOffscreenPlainSurface(width, height, format, D3DPOOL_SYSTEMMEM, &surface, NULL);
    d3dDevice->GetRenderTargetData(backbuffer, surface);
    surface->LockRect(&rect, NULL, 0);

    ... loop rect.pBits memcpy...

    surface->UnlockRect();
}
</code>```

The function works fine, but there is a problem.

The function is called from a sub-thread, not from the main thread.

Captured images created as a result are often in an incomplete rendering state.

I tried using GetFrontBufferData, but the purpose was to capture only the game screen, but I couldn't use it because other overlayed windows were also taken.

I would like to know how to capture the screen rendered in sub-thread.
Or is there a way to get the screenshot without performance hit on the main thread?

Body:
I'm making a function that captures the screen within a game.

I implemented it like this.

void somecapture()
{
    d3dDevice->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);
    d3dDevice->CreateOffscreenPlainSurface(width, height, format, D3DPOOL_SYSTEMMEM, &surface, NULL);
    d3dDevice->GetRenderTargetData(backbuffer, surface);
    surface->LockRect(&rect, NULL, 0);

    ... loop rect.pBits memcpy...

    surface->UnlockRect();
}

The function works fine, but there is a problem.

The function is called from a sub-thread, not from the main thread.

Captured images created as a result are often in an incomplete rendering state.

I tried using GetFrontBufferData, but the purpose was to capture only the game screen, but I couldn't use it because other overlayed windows were also taken.

I would like to know how to capture the screen rendered in sub-thread.
Or is there a way to get the screenshot without performance hit on the main thread?


问:
Kivy: Black Boxes Font Format Issue

import kivy
import main
from main import *
#kivy.require('1.2.0')
from kivy.app import App
from kivy.uix.label import Label

class MainWindow(App): #this builds the window
    pass

class ArabMemoriseApp(App): #this displays what should be in the window
    font_name = 'fonts/Lateef/Lateef-Regular.TTF'

    def build(self):
        return Label(text = ayah_evolving,
        markup = True,
        font_size = 40,
        font_name = self.font_name)

if __name__ == '__main__':
    ArabMemoriseApp().run()

```

This is my code. Ayah Evolving is an array that contains arabic words with underscores in some of those arrays instead, not important.

When I use Lateef or a font known as Scheherazade font, it gives me the following: with black boxes as you can see in the image.

Font Not working:

However, when I use a different font, Amiri, it works fine and looks perfect.

Amiri Font works fine:

I feel like this issue is to do with UTF or encoding etc. But I don't know what to do.

I have used arabic-reshaper, I don't think thats the issue because Amiri font works. Just the others that don't.

How can I get them working properly?

Title: Kivy: Black Boxes Font Format Issue

Body:
import kivy
import main
from main import *
#kivy.require('1.2.0')
from kivy.app import App
from kivy.uix.label import Label

class MainWindow(App): #this builds the window
    pass

class ArabMemoriseApp(App): #this displays what should be in the window
    font_name = 'fonts/Lateef/Lateef-Regular.TTF'

    def build(self):
        return Label(text = ayah_evolving,
        markup = True,
        font_size = 40,
        font_name = self.font_name)

if __name__ == '__main__':
    ArabMemoriseApp().run()

This is my code. Ayah Evolving is an array that contains arabic words with underscores in some of those arrays instead, not important.

When I use Lateef or a font known as Scheherazade font, it gives me the following: with black boxes as you can see in the image.

Font Not working:

However, when I use a different font, Amiri, it works fine and looks perfect.

Amiri Font works fine:

I feel like this issue is to do with UTF or encoding etc. But I don't know what to do.

I have used arabic-reshaper, I don't think thats the issue because Amiri font works. Just the others that don't.

How can I get them working properly?


问:
not all PWMs are generated in Pi4 wiringPI language C
I am working on a project where I have to use multi-threading to generate multiple pwms. I am working on raspberry and I use WiringPI to generate softPWMs.

The problems is my raspberry does not want to generate 5 PWMs. Each time a run the code, the PWMs are generated randomly on 3 of the five pins I have setted. I do not know if it is the OS putting some threads on sleep or not.

I have no idea where the problem might be from. In fact, I tries using the same code to send periodically send many variable and it did work. But when I try using the same code with PWM it does not work. The code I am using is right below. If any of you has any idea please help

```<code>#include <wiringPi.h>
#include <stdio.h>
#include <softPwm.h>
#include <stdlib.h>
#include <pthread.h>

#define THREAD_NUM 1

struct thArg{
    int PWM_pin1;
    int rapportCyclique1;
    int PWM_pin2;
    int rapportCyclique2;
    int PWM_pin3;
    int rapportCyclique3;
    int PWM_pin4;
    int rapportCyclique4;

};

struct thArg data = {
    22,20,
    23,40,
    24,80,
    25,60
};

void* routine(void* args){

    //int PWM_pin = *(int*)args->PWM_pin;
    //int intensity = *(int*)args->rapportCyclique;
    //pthread_mutex_lock(&mutexBuffer);
    struct thArg *arrgs = (struct thArg *) args;
    int PWM_pin1 = arrgs->PWM_pin1;
    int rapportCyclique1 = arrgs->rapportCyclique1;
    int PWM_pin2 = arrgs->PWM_pin2;
    int rapportCyclique2 = arrgs->rapportCyclique2;
    int PWM_pin3 = arrgs->PWM_pin3;
    int rapportCyclique3 = arrgs->rapportCyclique3;
    int PWM_pin4 = arrgs->PWM_pin4;
    int rapportCyclique4 = arrgs->rapportCyclique4;

    pinMode(PWM_pin1, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);
    pinMode(PWM_pin2, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);
    pinMode(PWM_pin3, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);
    pinMode(PWM_pin4, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);

    softPwmWrite(PWM_pin1, rapportCyclique1);
    softPwmWrite(PWM_pin2, rapportCyclique2);
    softPwmWrite(PWM_pin3, rapportCyclique3);
    softPwmWrite(PWM_pin4, rapportCyclique4);

    //pthread_mutex_unlock(&mutexBuffer);

}

void* routine(void*);

int main(int argc, char** argv)
{
    wiringPiSetup();
    pthread_t th[THREAD_NUM];
    for(int i=0; i<THREAD_NUM; i++)
    {
        struct thArg *a = malloc(sizeof(struct thArg));
        *a = data;
        if(pthread_create(&th[i], NULL, &routine, a) != 0)
        {
            perror("failed to create thread\n");
            exit( EXIT_FAILURE );
        }
    }

    for(int i = 0; i<THREAD_NUM; i++){
        if(pthread_join(th[i], NULL)!= 0)
        {
            perror("Failed to join thread\n");
            exit( EXIT_FAILURE );
        }
    }

    //pthread_mutex_destroy(&mutexBuffer);
    return EXIT_SUCCESS;

}
</code>```

Body:
I am working on a project where I have to use multi-threading to generate multiple pwms. I am working on raspberry and I use WiringPI to generate softPWMs.

The problems is my raspberry does not want to generate 5 PWMs. Each time a run the code, the PWMs are generated randomly on 3 of the five pins I have setted. I do not know if it is the OS putting some threads on sleep or not.

I have no idea where the problem might be from. In fact, I tries using the same code to send periodically send many variable and it did work. But when I try using the same code with PWM it does not work. The code I am using is right below. If any of you has any idea please help

#include <wiringPi.h>
#include <stdio.h>
#include <softPwm.h>
#include <stdlib.h>
#include <pthread.h>

#define THREAD_NUM 1

struct thArg{
    int PWM_pin1;
    int rapportCyclique1;
    int PWM_pin2;
    int rapportCyclique2;
    int PWM_pin3;
    int rapportCyclique3;
    int PWM_pin4;
    int rapportCyclique4;

};

struct thArg data = {
    22,20,
    23,40,
    24,80,
    25,60
};

void* routine(void* args){

    //int PWM_pin = *(int*)args->PWM_pin;
    //int intensity = *(int*)args->rapportCyclique;
    //pthread_mutex_lock(&mutexBuffer);
    struct thArg *arrgs = (struct thArg *) args;
    int PWM_pin1 = arrgs->PWM_pin1;
    int rapportCyclique1 = arrgs->rapportCyclique1;
    int PWM_pin2 = arrgs->PWM_pin2;
    int rapportCyclique2 = arrgs->rapportCyclique2;
    int PWM_pin3 = arrgs->PWM_pin3;
    int rapportCyclique3 = arrgs->rapportCyclique3;
    int PWM_pin4 = arrgs->PWM_pin4;
    int rapportCyclique4 = arrgs->rapportCyclique4;

    pinMode(PWM_pin1, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);
    pinMode(PWM_pin2, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);
    pinMode(PWM_pin3, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);
    pinMode(PWM_pin4, OUTPUT);
    softPwmCreate(PWM_pin1, 1, 100);

    softPwmWrite(PWM_pin1, rapportCyclique1);
    softPwmWrite(PWM_pin2, rapportCyclique2);
    softPwmWrite(PWM_pin3, rapportCyclique3);
    softPwmWrite(PWM_pin4, rapportCyclique4);

    //pthread_mutex_unlock(&mutexBuffer);

}

void* routine(void*);

int main(int argc, char** argv)
{
    wiringPiSetup();
    pthread_t th[THREAD_NUM];
    for(int i=0; i<THREAD_NUM; i++)
    {
        struct thArg *a = malloc(sizeof(struct thArg));
        *a = data;
        if(pthread_create(&th[i], NULL, &routine, a) != 0)
        {
            perror("failed to create thread\n");
            exit( EXIT_FAILURE );
        }
    }

    for(int i = 0; i<THREAD_NUM; i++){
        if(pthread_join(th[i], NULL)!= 0)
        {
            perror("Failed to join thread\n");
            exit( EXIT_FAILURE );
        }
    }

    //pthread_mutex_destroy(&mutexBuffer);
    return EXIT_SUCCESS;

}


问:
Shiny CRUD not working in golem module (but working in simple shiny app)
I have adapted some CRUD code which works perfectly in a classical shiny app. I decided to include it in a golem module. But in golem the edit and delete buttons don't launch the modal window.

I checked if I missed some ns(), but I don't think so. I have also tried to load in a different way the get_id() function (see below) but it changed nothing.

The only curious clue I found was in the browser dev environment which indicated "Couldn't find table with id CRUD_1-dt_table"

I am new to Stack Overflow. Thank your for your help.

Please find below the code in script.js which seems to be loaded normally

```<code>function get_id(clicked_id) {
  Shiny.setInputValue("current_id", clicked_id, {priority: "event"});
}
</code>```

The code is simple for the UI part of the module

```<code>mod_CRUD_ui <- function(id){
  ns <- NS(id)
  tagList(

    #  Button to add a project -> it works
    div(
      class = "container",
      div(
        style = "margin-top: 50px;", shiny::actionButton(
          inputId = ns("add_project"), label = "Ajouter un projet",
          icon = shiny::icon("plus"), class = "btn-success"
        )
      )
    ),

    #  To display the DT table
    div(
      class = "container",
      style = "margin-top: 50px;",
      DT::DTOutput(outputId = ns("dt_table"), width = "100%")
    ),

    shiny::includeScript(system.file("app/www", "script.js", package = "REXDI"))
    # shiny::includeScript("app/www/script.js")
  # tags$script(src= "script.js")

  )
}
</code>```

The data is first  contained in global$CRUD_init  (reactiveValues) which is initialized when the app is launched in another module

```<code>#' CRUD Server Functions

mod_CRUD_server <- function(id, global){
  moduleServer( id, function(input, output, session){
    ns <- session$ns

    observeEvent(global$CRUD_init , {

      global$CRUD_init_co <-  global$CRUD_init

# the get_id() function from the script.js file is used in the next part of # the code. Normally it works

      global$create_btns <- function(x) {
        x %>%
          purrr::map_chr(~
                           paste0(
                             '<div class = "btn-group">',
                                  '<button class="btn btn-default action-button btn-info action_button" id="edit_',
                                      .x, '" type="button" onclick=get_id(this.id)>

                                    <i class="fas fa-edit"></i>
                                  </button>
                                  <button class="btn btn-default action-button btn-danger action_button" id="delete_',
                                     .x, '" type="button" onclick=get_id(this.id)>
                                     <i class="fa fa-trash-alt"></i>
                                  </button>
                             </div>'
                           ))
      }

      # Buttons in df global$CRUD
      x <- global$create_btns(global$CRUD_init_co$id)
      global$CRUD_init_co <- global$CRUD_init_co %>%
        dplyr::bind_cols(tibble("Buttons" = x))

      ##  reactiveValues global$CRUD ----
      global$CRUD <-  shiny::reactiveValues(
        df = global$CRUD_init_co  %>%
          dplyr::select(-id),
        dt_row = NULL,
        add_or_edit = NULL,
        edit_button = NULL,
        keep_track_id = max(global$CRUD_init_co$id) + 1
      )

    })
</code>```

It is followed by the function modal_dialog (because it's long I kept only few arguments and inputs

```<code>    modal_dialog <- function(Projet,
                             Centre,
                             ...and so forth...,
                             edit) {

      if(edit) {
        x <- "Soumettre modifications"
      } else {
        x <- "Ajouter un projet"
      }

      shiny::modalDialog(
        title = "Editer un projet",
        div(
          class = "text-center",
          div(
            style = "display: inline-block;",
            shiny::textInput(inputId = ns("Projet"),
                             label = "Projet",
                             value = Projet,
                             placeholder = "",
                             width = "200px")
          ),
          div(
            style = "display: inline-block;",
            shiny::textInput(inputId = ns("Centre"),
                             label = "Centre",
                             value = Centre,
                             placeholder = "Entrer un Centre",
                             width = "200px")
          ),
...and so forth...
        ),
        size = 'm',
        easyClose = TRUE,
        footer = div(
          class = "pull-right container",
          shiny::actionButton(inputId = ns("final_edit"),
                              label   = x,
                              icon = shiny::icon("edit"),
                              class = "btn-info"),
          shiny::actionButton(inputId = ns("dismiss_modal"),
                              label   = "Fermer",
                              class   = "btn-danger")
        )

      ) %>% shiny::showModal()

    }

</code>```

I also tried to add ns("dt_table") to DT::dataTableProxy("dt_table") but it did not work and I am not really sure to understand the dataTableProxy in a module

```<code>    ## output DT ----
    output$dt_table <- DT::renderDT(
      {
        shiny::isolate(global$CRUD$df)
      },
      escape = F,
      rownames = FALSE,
      options = list(processing = FALSE)
    )

    ## Proxy DT ----
    proxy <- DT::dataTableProxy("dt_table")
    shiny::observe({
      DT::replaceData(proxy, global$CRUD$df, resetPaging = FALSE, rownames = FALSE)
    })
</code>```

The code for deleting is clear

```<code>    ## delete row ----
    shiny::observeEvent(input$current_id, {

      shiny::req(!is.null(input$current_id) &
                   stringr::str_detect(input$current_id,
                                       pattern = "delete"
                   ))
      global$CRUD$dt_row <- which(stringr::str_detect(global$CRUD$df$Buttons,
                                             pattern = paste0("\\b", input$current_id, "\\b")
      ))
</code>```

The purpose of the next chunk of code is only for keeping memory of what has been deleted, so I did not include it in this post

then deleting

```<code>      sql_id <- global$CRUD$df[global$CRUD$dt_row, ][["Buttons"]] %>%
        stringr::str_extract_all(pattern = "delete_[0-9]+") %>%
        unlist() %>%
        readr::parse_number()

      query <- stringr::str_glue("DELETE FROM TDP WHERE id = {sql_id}")
      DBI::dbSendQuery(
        con,
        query
      )
     ...
    })
</code>```

The edit part like the deleting part is not launched when clicking on the buttons. All the code works in a classic shiny app, and I don't see any missing ns(), so it is a mystery for me

```<code>    # when edit button is clicked, modal dialog shows current editable row filled out ----
    shiny::observeEvent(input$current_id, {
      shiny::req(!is.null(input$current_id) &
                   stringr::str_detect(input$current_id,
                                       pattern = "edit"
                   ))
      global$CRUD$dt_row <- which(stringr::str_detect(global$CRUD$df$Buttons,
                                             pattern = paste0("\\b", input$current_id, "\\b")
      ))
      df <- global$CRUD$df[global$CRUD$dt_row, ]
      modal_dialog(

        ### A modifier -----

        Projet                                = df$Projet,
        Centre                                = df$Centre,
        ...and so forth or else the code is too long...
        edit                                  = TRUE

      )
      global$CRUD$add_or_edit <- NULL
    })

    # when final edit button is clicked, table will be changed ----
    shiny::observeEvent(input$final_edit, {
      shiny::req(!is.null(input$current_id) &
                   stringr::str_detect(input$current_id, pattern = "edit") &
                   is.null(global$CRUD$add_or_edit))

      global$CRUD$edited_row <- dplyr::tibble(

        Projet    = input$Projet,
        Centre    = input$Centre,
      ....and so forth...or else it is too long
        Buttons   = global$CRUD$df$Buttons[global$CRUD$dt_row]

      )

      sql_row <- global$CRUD$edited_row %>%
        dplyr::select(-Buttons)

      id <- global$CRUD$df[global$CRUD$dt_row, ][["Buttons"]] %>%
        stringr::str_extract_all(pattern = "delete_[0-9]+") %>%
        unlist() %>%
        readr::parse_number()
      # browser()
      query <- paste0(
        "UPDATE TDP SET ",
        paste0(names(sql_row), "=", "'", unlist(c(sql_row)), "'", collapse = ", "),
        stringr::str_glue("WHERE id = {id}")
      )
      DBI::dbSendQuery(
        global$con,
        query
      )

      global$CRUD$df[global$CRUD$dt_row, ] <- global$CRUD$edited_row
    })
</code>```

The next part is for adding a project which works so it is not added below and then code to remove modals

Body:
I have adapted some CRUD code which works perfectly in a classical shiny app. I decided to include it in a golem module. But in golem the edit and delete buttons don't launch the modal window.

I checked if I missed some ns(), but I don't think so. I have also tried to load in a different way the get_id() function (see below) but it changed nothing.

The only curious clue I found was in the browser dev environment which indicated "Couldn't find table with id CRUD_1-dt_table"

I am new to Stack Overflow. Thank your for your help.

Please find below the code in script.js which seems to be loaded normally

function get_id(clicked_id) {
  Shiny.setInputValue("current_id", clicked_id, {priority: "event"});
}

The code is simple for the UI part of the module

mod_CRUD_ui <- function(id){
  ns <- NS(id)
  tagList(

    #  Button to add a project -> it works
    div(
      class = "container",
      div(
        style = "margin-top: 50px;", shiny::actionButton(
          inputId = ns("add_project"), label = "Ajouter un projet",
          icon = shiny::icon("plus"), class = "btn-success"
        )
      )
    ),

    #  To display the DT table
    div(
      class = "container",
      style = "margin-top: 50px;",
      DT::DTOutput(outputId = ns("dt_table"), width = "100%")
    ),

    shiny::includeScript(system.file("app/www", "script.js", package = "REXDI"))
    # shiny::includeScript("app/www/script.js")
  # tags$script(src= "script.js")

  )
}

The data is first  contained in global$CRUD_init  (reactiveValues) which is initialized when the app is launched in another module

#' CRUD Server Functions

mod_CRUD_server <- function(id, global){
  moduleServer( id, function(input, output, session){
    ns <- session$ns

    observeEvent(global$CRUD_init , {

      global$CRUD_init_co <-  global$CRUD_init

# the get_id() function from the script.js file is used in the next part of # the code. Normally it works

      global$create_btns <- function(x) {
        x %>%
          purrr::map_chr(~
                           paste0(
                             '
',
                                  '<button class="btn btn-default action-button btn-info action_button" id="edit_',
                                      .x, '" type="button" onclick=get_id(this.id)>

                                  </button>
                                  <button class="btn btn-default action-button btn-danger action_button" id="delete_',
                                     .x, '" type="button" onclick=get_id(this.id)>

                                  </button>

'
                           ))
      }

      # Buttons in df global$CRUD
      x <- global$create_btns(global$CRUD_init_co$id)
      global$CRUD_init_co <- global$CRUD_init_co %>%
        dplyr::bind_cols(tibble("Buttons" = x))

      ##  reactiveValues global$CRUD ----
      global$CRUD <-  shiny::reactiveValues(
        df = global$CRUD_init_co  %>%
          dplyr::select(-id),
        dt_row = NULL,
        add_or_edit = NULL,
        edit_button = NULL,
        keep_track_id = max(global$CRUD_init_co$id) + 1
      )

    })

It is followed by the function modal_dialog (because it's long I kept only few arguments and inputs

    modal_dialog <- function(Projet,
                             Centre,
                             ...and so forth...,
                             edit) {

      if(edit) {
        x <- "Soumettre modifications"
      } else {
        x <- "Ajouter un projet"
      }

      shiny::modalDialog(
        title = "Editer un projet",
        div(
          class = "text-center",
          div(
            style = "display: inline-block;",
            shiny::textInput(inputId = ns("Projet"),
                             label = "Projet",
                             value = Projet,
                             placeholder = "",
                             width = "200px")
          ),
          div(
            style = "display: inline-block;",
            shiny::textInput(inputId = ns("Centre"),
                             label = "Centre",
                             value = Centre,
                             placeholder = "Entrer un Centre",
                             width = "200px")
          ),
...and so forth...
        ),
        size = 'm',
        easyClose = TRUE,
        footer = div(
          class = "pull-right container",
          shiny::actionButton(inputId = ns("final_edit"),
                              label   = x,
                              icon = shiny::icon("edit"),
                              class = "btn-info"),
          shiny::actionButton(inputId = ns("dismiss_modal"),
                              label   = "Fermer",
                              class   = "btn-danger")
        )

      ) %>% shiny::showModal()

    }

I also tried to add ns("dt_table") to DT::dataTableProxy("dt_table") but it did not work and I am not really sure to understand the dataTableProxy in a module

    ## output DT ----
    output$dt_table <- DT::renderDT(
      {
        shiny::isolate(global$CRUD$df)
      },
      escape = F,
      rownames = FALSE,
      options = list(processing = FALSE)
    )

    ## Proxy DT ----
    proxy <- DT::dataTableProxy("dt_table")
    shiny::observe({
      DT::replaceData(proxy, global$CRUD$df, resetPaging = FALSE, rownames = FALSE)
    })

The code for deleting is clear

    ## delete row ----
    shiny::observeEvent(input$current_id, {

      shiny::req(!is.null(input$current_id) &
                   stringr::str_detect(input$current_id,
                                       pattern = "delete"
                   ))
      global$CRUD$dt_row <- which(stringr::str_detect(global$CRUD$df$Buttons,
                                             pattern = paste0("\\b", input$current_id, "\\b")
      ))

The purpose of the next chunk of code is only for keeping memory of what has been deleted, so I did not include it in this post

then deleting

      sql_id <- global$CRUD$df[global$CRUD$dt_row, ][["Buttons"]] %>%
        stringr::str_extract_all(pattern = "delete_[0-9]+") %>%
        unlist() %>%
        readr::parse_number()

      query <- stringr::str_glue("DELETE FROM TDP WHERE id = {sql_id}")
      DBI::dbSendQuery(
        con,
        query
      )
     ...
    })

The edit part like the deleting part is not launched when clicking on the buttons. All the code works in a classic shiny app, and I don't see any missing ns(), so it is a mystery for me

    # when edit button is clicked, modal dialog shows current editable row filled out ----
    shiny::observeEvent(input$current_id, {
      shiny::req(!is.null(input$current_id) &
                   stringr::str_detect(input$current_id,
                                       pattern = "edit"
                   ))
      global$CRUD$dt_row <- which(stringr::str_detect(global$CRUD$df$Buttons,
                                             pattern = paste0("\\b", input$current_id, "\\b")
      ))
      df <- global$CRUD$df[global$CRUD$dt_row, ]
      modal_dialog(

        ### A modifier -----

        Projet                                = df$Projet,
        Centre                                = df$Centre,
        ...and so forth or else the code is too long...
        edit                                  = TRUE

      )
      global$CRUD$add_or_edit <- NULL
    })

    # when final edit button is clicked, table will be changed ----
    shiny::observeEvent(input$final_edit, {
      shiny::req(!is.null(input$current_id) &
                   stringr::str_detect(input$current_id, pattern = "edit") &
                   is.null(global$CRUD$add_or_edit))

      global$CRUD$edited_row <- dplyr::tibble(

        Projet    = input$Projet,
        Centre    = input$Centre,
      ....and so forth...or else it is too long
        Buttons   = global$CRUD$df$Buttons[global$CRUD$dt_row]

      )

      sql_row <- global$CRUD$edited_row %>%
        dplyr::select(-Buttons)

      id <- global$CRUD$df[global$CRUD$dt_row, ][["Buttons"]] %>%
        stringr::str_extract_all(pattern = "delete_[0-9]+") %>%
        unlist() %>%
        readr::parse_number()
      # browser()
      query <- paste0(
        "UPDATE TDP SET ",
        paste0(names(sql_row), "=", "'", unlist(c(sql_row)), "'", collapse = ", "),
        stringr::str_glue("WHERE id = {id}")
      )
      DBI::dbSendQuery(
        global$con,
        query
      )

      global$CRUD$df[global$CRUD$dt_row, ] <- global$CRUD$edited_row
    })

The next part is for adding a project which works so it is not added below and then code to remove modals


问:
How to enforce Decimal dtype in pandas DataFrame
How can I stricly enforce a dtype Decimal in a pandas DataFrame?

To clarify: I am not looking for weak workarounds, such as rounding every time I write to or read from a column (and hope that no other operations happend elsewhere that might lead to unwanted results).

I really want to be 100% sure that whatever is written in that column, no matter where it might have come from, will always have exactly 2 significant digits behind the decimal point, end of story. And if a user intends to write something that's not in agreement, the whole thing should blow up (either producing a TypeError or ValueError). --> To avoid theoretical dicussions and motivate the usage a bit: I am dealing with a trading system, that's why saving anything other than 2 decimal points in that frame would be a hard error, always.

I have tried to assign a dtype, but without success:

```<code>from decimal import Decimal
df[col].astype(Decimal)
</code>```

Pydantic comes to mind: but if I bake the df into a class (say class MyDfType), then do I need to write my own setter/getter functions into MyDfType for the contained dataframe (MyDFType().df) ensure that all values to/from certain cols are manually enforced to be Decimal?

Body:
How can I stricly enforce a dtype Decimal in a pandas DataFrame?

To clarify: I am not looking for weak workarounds, such as rounding every time I write to or read from a column (and hope that no other operations happend elsewhere that might lead to unwanted results).

I really want to be 100% sure that whatever is written in that column, no matter where it might have come from, will always have exactly 2 significant digits behind the decimal point, end of story. And if a user intends to write something that's not in agreement, the whole thing should blow up (either producing a TypeError or ValueError). --> To avoid theoretical dicussions and motivate the usage a bit: I am dealing with a trading system, that's why saving anything other than 2 decimal points in that frame would be a hard error, always.

I have tried to assign a dtype, but without success:

from decimal import Decimal
df[col].astype(Decimal)

Pydantic comes to mind: but if I bake the df into a class (say class MyDfType), then do I need to write my own setter/getter functions into MyDfType for the contained dataframe (MyDFType().df) ensure that all values to/from certain cols are manually enforced to be Decimal?


问:
How to select particular action button for particular data which contains particular text
I have total for ex. 5 properties and action button for every property as shown in the picture. Each property has a status either manual or post. I need to find the property which has 'manual' status and click the action button for that corresponding property using selenium python page object model. I have thought about for and if loop but not coming to any conclusion. Kindly help.

The first html tag is for the status 'Manual' or 'Post' and the second Tag is for action button. Like this 5 + 5 tags will be there for every property's status and action button.

I have tried for and if loop but not able to find the solution.


Title: Segmented Regression with two zero constraints at beginning and end boundaries

Body:
I am having trouble with this segmented regression as it requires two constraints and so far I have only treated single constraints.

Here is an example of some data I am trying to fit:

library(segmented)
library("readxl")
library(ggplot2)

#DATA PRE-PROCESSING
yields <- c(-0.131, 0.533, -0.397, -0.429, -0.593, -0.778, -0.92, -0.987, -1.113,       -1.314, -0.808, -1.534, -1.377, -1.459, -1.818, -1.686, -1.73, -1.221, -1.595, -1.568, -1.883, -1.53, -1.64, -1.396, -1.679, -1.782, -1.033, -0.539, -1.207, -1.437, -1.521, -0.691, -0.879, -0.974, -1.816, -1.854, -1.752, -1.61, -0.602, -1.364, -1.303, -1.186, -1.336)
maturities <- c(2.824657534246575, 2.9013698630136986, 3.106849315068493, 3.1534246575342464, 3.235616438356164, 3.358904109589041, 3.610958904109589, 3.654794520547945, 3.778082191780822, 3.824657534246575, 3.9013698630136986, 3.9863013698630136, 4.153424657534247, 4.273972602739726, 4.32054794520548, 4.654794520547945, 4.778082191780822, 4.986301369863014, 5.153424657534247, 5.32054794520548, 5.443835616438356, 5.572602739726028, 5.654794520547945, 5.824425480949174, 5.941911819746988, 6.275245153080321, 6.4063926940639275, 6.655026573845348, 6.863013698630137, 7.191780821917808, 7.32054794520548, 7.572602739726028, 7.693150684931507, 7.901369863013699, 7.986301369863014, 8.32054794520548, 8.654794520547945, 8.986301369863014, 9.068493150684931, 9.32054794520548, 9.654794520547945, 9.903660453626769, 10.155026573845348)

 off_2 <- 2.693277939965566
 off_10 <- 10.655026573845348

 bond_data = data.frame(yield_change = yields, maturity = maturities) code here

I am trying to fit a segmented model (with a formula of "yield_change~maturity") that has the following constraints:

At maturity = 2 I want the yield_change to be zero

At maturity = 10, I want the yield_change to zero

I want breakpoints(fixed in x) at the 3, 5 and 7-year maturity values.

The off_2 and off_10 variables are the offsets I must use (to set the yields to zero at the 2 and 10-year mark)

As I mentioned before, my previous regressions only required one initial constraint, having one offset value I had to use, I did the following:

I subtracted the offset value from the maturity vector (for example I had maturity = c(10.8,10.9,11,14,16,18, etc... then subtracted the offset, always lower than the initial vector value, 10,4 for example and then fitted a lm with an origin constraint)

From there I could use the segmented package and fit as many breakpoints as I wanted)

As the segmented() function requires a lm object as an input that was possible.

However in this case I cannot to the previous approach as I have two offsets and cannot subtract all the values by off_2 or off_10 as it would fix one point at the zero and not the other.

What I have tried doing is the following:

Separate the dataset into maturities below 5 and maturities over 5 (and essentially apply a segmented model to each of these (with only one breakpoint being 3 or 7).

The issue is that I need to have the 5 year point yield the same for the two models.

I have done this:

bond_data_sub5 <- bond_data[bond_data$maturity < 5,]
bond_data_over5 <- bond_data[bond_data$maturity > 5,]

bond_data_sub5["maturity"] <- bond_data_sub5$maturity - off_2

#2 to 5 year model
model_sub5 <- lm(yield_change~maturity+0, data = bond_data_sub5)

plot(bond_data_sub5$maturity,bond_data_sub5$yield_change, pch=16, col="blue",
     xlab = "maturity",ylab = "yield_change", xlim = c(0,12))

abline(model_sub5)

Which gives me the following graph:

The fact that the maturities have an offset of off_2 is not a problem as when I input my predictions to the function I will create, I will then subtract them by off_2.

The worrying thing is that the 5-year prediction is not at all close to where the actual 5 year should be. Looking at the scatter plot of all maturities we can see this:

five_yr_yield <- predict(model_sub5,data.frame(maturity = 5 - off_2))
plot(bond_data$maturity,bond_data$yield_change, pch=16, col="blue",
 xlab = "maturity",ylab = "yield_change", xlim = c(0,12), ylim  = c(-3,0.5))
points(5,five_yr_yield, pch=16, col = "red")

Gives:

The issue with this method is that if I set the model_sub5 5-year prediction as the beginning constraint of model_over5, I will have the exact same problem I am trying to resolve, two constraints in one lm (but this time (5,five_yr_yield) and (10,0) constraints.

Isn't there a way to fit a lm with no slope and zero as an intercept from (2,0) to (10,0) and then apply the segmented function with breakpoints at 3,5 and 7?

If that isn't possible how would I make the logic I am trying to apply work? Or is there another way of doing this?

If anyone has any suggestions I would greatly appreciate them!

Thank you very much!