My program had Vertex shader, fragment shader. I want to add Compute shader, can I add it to my program and how?
from Recent Questions - Stack Overflow https://ift.tt/2NUm9md
https://ift.tt/eA8V8J
My program had Vertex shader, fragment shader. I want to add Compute shader, can I add it to my program and how?
I'm trying to work out img/canvas scaling but it's not working. I've got an image, and I want to compress it, so I'm using canvas to do this using the following code:
<img id='srcimg'>
<img id='copyimg'>
and
function doSendToCanvasThenCopyImg(srcimg, destimg) {
var scale = 1;
var natW = srcimg.naturalWidth;
var natH = srcimg.naturalHeight;
var newCanvas = document.createElement('canvas');
newCanvas.width = parseInt(natW * scale);
newCanvas.height = parseInt(natH * scale);
var ctx = newCanvas.getContext("2d");
ctx.drawImage(srcimg, 0, 0, natW, natH, 0, 0, newCanvas.width, newCanvas.height);
var base64 = newCanvas.toDataURL('image/jpeg', 1);
destimg.src = base64;
}
and
function scaleToFit(img, newW, natW, natH) {
var scale = newW / natW;
var newCanvas = document.createElement('canvas');
var ctx = newCanvas.getContext("2d");
ctx.drawImage(img, 0, 0, natW, natH, 0, 0, parseInt(natW * scale), parseInt(natH * scale));
var base64 = newCanvas.toDataURL('image/jpeg',1);
img.src = base64;
}
but this seems to only show the top left corner of the src image. Why is this and how can I get the whole image?
Secondly, I am trying to measure the diskspace size of the image, so I use the function:
function getImageSize(img) {
var can = document.createElement('canvas');
var natW = img.naturalWidth;
var natH = img.naturalHeight;
can.width = natW;
can.height = natH;
var ctx = can.getContext("2d");
ctx.drawImage(img, 0, 0, natW, natH, 0, 0, natW, natH);
var base64 = can.toDataURL('image/jpeg',1);
return base64.length;
}
But this seems to result in an incorrect result - after the copy the img [base64] src is blank - can anyone help?
I have a running sample found on https://jsfiddle.net/Abeeee/9bzk7h6w/ (sorry - it includes a very large base64 image as I couldn't find a way to include images in jsfiddle and external images will cause security issues with the script).
To recap - I'm trying to resize an image in javascript and want to see the resulting filesize as I go.
What goes on?
Thanks. Abe
The grammar:
E -> E E +
E -> num
I tried to use the formula for left recursion elimination and got:
E -> num E'
E' -> E Op E' | ɛ
I think I am missing something but this doesn't seem equivalent to me.
In the first grammar, it seems to me that every word in the language doesn't start with more than 2 num
s, but in the second grammar this seems entirely possible.
I have two third party php libraries, phpMyEdit and ical which were working on PHP 7.4. When I upgraded the server to Ubuntu 20.04 the php engine went to 8.0. Then these two libraries broke on an error for curly braces {} which is now illegal in php 8. In those libraries I changed the braces {} to bracketts [] as was recommended elsewhere. In some of my own code that had {} I changed that to [] and it is now working. However those two libraries when called never return and there is nothing left in the error logs for me to look at.
What should I try to sort this out.
I want to run a script like this:
while(Date.now() < dateToStop){
doSomething()
await new Promise(r => setTimeout(r, 2000));
doSomething()
await new Promise(r => setTimeout(r, 2000));
}
The only thing is, I want to exit the loop the "instant" Date.now() < dateToStop
is false, whereas this function could exit 4 seconds after due to its asynchronous nature nature.
How do I solve this?
I am not sure why but when I press the right key and then press the left key while moving my player it will glitch it throw the rectangle VIDEO it works perfectly the other way around but it will keep doing that if I hold right key and then click left key while holding the right key it will teleport me throw the block I am not sure how to fix this at all any help is appreciated! VIDEO < another video of the problem
my collisions for the sides
# sides for player and player screen movement
platform_rect_list = [p.rect for p in collids]
player_rect = playerman.get_rect()
player_rect.topleft = (px, py)
playerman.y = py
if player_rect.collidelist(platform_rect_list) < 0:
playerman.x = px
move_right = keys[pygame.K_RIGHT]
move_left = keys[pygame.K_LEFT]
if move_right:
base1.x -= playerman.speed
base2.x -= playerman.speed
base3.x -= playerman.speed
base4.x -= playerman.speed
base5.x -= playerman.speed
base6.x -= playerman.speed
crate1.x -= playerman.speed
base44.x -= playerman.speed
end1.x -= playerman.speed
base45.x -= playerman.speed
stopmove1.x -= playerman.speed
text_show_collision.x -= playerman.speed
text1.x -= playerman.speed
rop1.x -= playerman.speed
text22.x -= playerman.speed
text_show_collision2.x -= playerman.speed
portal1.x -= playerman.speed
base46.x -= playerman.speed
for shot in shots:
shot.x -= playerman.speed
for collid in collids:
collid.x -= playerman.speed
if move_left:
base1.x += playerman.speed
base2.x += playerman.speed
base3.x += playerman.speed
base4.x += playerman.speed
base5.x += playerman.speed
base6.x += playerman.speed
crate1.x += playerman.speed
base44.x += playerman.speed
end1.x += playerman.speed
base45.x += playerman.speed
stopmove1.x += playerman.speed
text_show_collision.x += playerman.speed
text1.x += playerman.speed
rop1.x += playerman.speed
text22.x += playerman.speed
text_show_collision2.x += playerman.speed
portal1.x += playerman.speed
base46.x += playerman.speed
for shot in shots:
shot.x += playerman.speed
for collid in collids:
collid.x += playerman.speed
platform_rect_list = [p.get_rect() for p in collids] # get_rect()
player_rect = playerman.get_rect()
player_rect.topleft = (px, py)
playerman.y = py
cI = player_rect.collidelist(platform_rect_list)
if cI >= 0:
# undo movement of platforms dependent on the direction and intersection distance
dx = 0
if move_right:
dx = platform_rect_list[cI].left - player_rect.right
if move_left:
dx = platform_rect_list[cI].right - player_rect.left
for collid in collids:
collid.x -= dx
collid.get_rect() # update rectangle
base1.x -= dx
base2.x -= dx
base3.x -= dx
base4.x -= dx
base5.x -= dx
base6.x -= dx
crate1.x -= dx
base44.x -= dx
end1.x -= dx
base45.x -= dx
stopmove1.x -= dx
text_show_collision.x -= dx
text1.x -= dx
rop1.x -= dx
text22.x -= dx
text_show_collision2.x -= dx
portal1.x -= dx
base46.x -= dx
for shot in shots:
shot.x -= dx
I used the head function with the head dataset[,head("column")]. But this displays all the rows in column 1 not just few.
Thanks for your help
if I have a csv file of 1000 list and I wanna add all of them to firebase cloud firestore the obvious option is to call forEach and give it => FirebaseFirestore.instance.collection('Products').add(blablabla) but it would take too much time, I wanna show a loading indicator during this process but I can't get the progress for it
I have been stocked into this for quite a while now. Whenever I pass this code
app.get("/", function (req, res) {
const rf_token = "Hello Express Cookies";
res.cookie("refreshtoken", rf_token, {
httpOnly: true,
path: "/api/users/refresh_token",
maxAge: 7 * 24,
});
console.log("refresh_token: ", req.cookies.refreshtoken);
});
Sadly, this is what it returns
refresh_token: undefined
I read through some solutions provided here but it seems not to run for me
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(cookieParser());
app.use("/api/users", userRouter);
I initialized cookie-parser before my route.
Kindly check this out. Thanks in anticipation!
I have a table tbl_a
.
id | name
----+-------
1 | item1
2 | item2
3 | item3
I also have a table tbl_aprops
which stores properties prop
associated with items a
from tbl_a
.
a_id | prop
------+------
1 | xx
1 | yy
2 | xx
2 | zz
3 | yy
I wish to perform a LEFT JOIN
where all the information from the left table tbl_a
is returned along with the associated properties prop
from table_aprops
in an array in a new column called props
. I wish to filter out items not associated with property yy
while still returning all associated properties prop
from tbl_aprops
.
id | name | props
----+-------+-----------
1 | item1 | {'xx','yy'}
3 | item3 | {'yy'}
I try to contribute to a Wikimedia opensource project but I don't get what ##*/
means in bash ${qidpath##*/}
. Searching on google for ##*/
is chaotic.
/tmp/datasets/raw/* contains a list of folders.
for qidpath in /tmp/datasets/raw/*;
do
qid=$(echo ${qidpath##*/} | cut -d'-' -f 1)
if [[ $qid == Q* ]] ; then
echo "--> Processing ${qid}..."
/usr/bin/python3.5 /home/www/CommonsDownloadTool/commons_download_tool.py --keep --sparqlurl https://lingualibre.org/bigdata/namespace/wdq/sparql --sparql "SELECT ?file ?filename WHERE { ${query} ?record prop:P4 entity:${qid}. }" --threads 4 --directory /tmp/datasets/raw/ --output "/tmp/datasets/${qidpath##*/}.zip" --fileformat ogg
fi
done
I'll try to be as specific as possible so it's easy to understand.
Let's say you have a class that holds a rectangle in the form of (x, y, w, h)
when working on a 2d plane with (0,0)
being the top left of the display. The first instance of this class holds the values (0,0,1920,1080)
, which sets the display dimensions for a program.
Now, from here, I want to have all the next instances of Rectangle
to exist within the previous one, such that their coordinates act as relative positions to it.
For example, let's work with the next 2 Rectangle
instances. I'll declare one called rect1 to have the values (100,100,500,500)
, and then the second instance called rect2 to exist within rect1. Its values will be (50,50,50,50)
.
Now, I want the heirarchy of values to apply to all instances to allow the relative positioning. What this would mean is that (relative to the original display's rectangle's first instance), rect1 will have a relative position in the form (x,y)
of (100,100)
, however rect2 will have a relative position of (150,150)
TO THE ORIGINAL DISPLAY'S RECTANGLE's FIRST INSTANCE.
But, to make life easy and follow the heirarchy, rect2 will have a RELATIVE POSITION TO rect1 of (50,50)
, yet in terms of the predasessor of rect1, its relative position is (150,150)
, as explained before.
Here is a picture of what I am trying to demonstrate:
So, with that type of structure in mind, how would I be able to translate that concept into code that follows the same idea?
Here is the code
(([(''+ 'e[' + str(i) + ']') for i in range(4)]))
Output :['e[0]', 'e[1]', 'e[2]', 'e[3]', 'e[4]']
I would like it to change to give me the following intended output: [e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10]]
I am coding a simple chat in 100% PHP, that uses WebSocket (with no external library like in this article).
Obviously, this requires a constantly-running PHP script / daemon / event-loop (similar to how Node.JS works), that we start with:
php -q websockets.php
or nohup ...
, or with a dedicated Systemd service (started with systemctl start myservice.service
), or with service myservice start
.
Question: let's say the person who installs this chat software has no access to command-line (or doesn't know about it enough to do it), how can we start the websockets.php
daemon directly from a web page, and keep it constantly running?
The admin could click on a button in his admin panel and, through a XHR/AJAX request, this would trigger a server-side code startup.php
. What would be necessary in this startup.php
, in order to start and keep websockets.php
running forever?
I know exec
, but is it adapted in this case?
(More precisely, let's say this admin has no command-line/SSH access, and has only been able to upload the code via (S)FTP; then they can only use a web interface to start or stop the chat daemon server)
Struct a weird effect in R. When coding a math expression as a function you get a different output than when coded directly? Any good explanations/solutions?
myfun <- function(x) x^(1/4)
myfun(-238194.65) returns: NaN
-238194.65^(1/4) returns: -22.0919
Im struggling a problem.This is for a trading bot, In an exchange, there is a rule. You can not trade after a trade, If you want to trade, you have to wait 5 seconds after first trade. After 5 seconds, trade is up to you, buy,sell or do nothing.
I have stopwatch and I call aFunction
, after end of the function, timer will start and I call bFunction
,if timer value < 5 seconds, It should wait until 5 seconds pass.
I make a while(true)
and I can check if(timer>5)
but it will eat cpu and if its single core it will be endless loop during 5 seconds.
Is there any c# way for this ? or any idea ? Sorry for my english and any help appreciated.
UPDATE
It shouldnt wait 5 seconds, if there is no trade before(5 seconds or more). So thread sleep or Timer doesnt work.
I have a main folder that contains multiple movie folders with different names and each folder has a movie and sometimes a subtitle file (.srt format), and some folders have 2-3 subtitle files, tree structure below:
movie-folder$ tree
.
├── 100.Yen.Love.(2014).BluRay.1080p
│ ├── 100.Yen.Love.2014.1080p.BluRay.x264-.mp4
│ └── 100.Yen.Love.2014.720p.BluRay.x264.-English.srt
├── Afternoon.Affair.Rear.Window.(1972).1080p.BluRay
│ ├── Afternoon.Affair.Rear.Window.1972.1080p.BluRay.x264.AAC-.mp4
│ └── Afternoon.Affair.Rear.Window.1972.1080p.BluRay.x264.AAC-.srt
├── A.Page.Of.Madness.(1926).BluRay.1080p
│ └── A.Page.Of.Madness.1926.1080p.BluRay.x264-.mp4
├── Asaki.Yumemishi.(1974).BluRay.1080p
│ ├── Asaki.Yumemishi.1974.1080p.BluRay.x264-.mp4
│ ├── Asaki.Yumemishi.1974.1080p.BluRay.x264-.srt
│ └── English.srt
I have found several different Q&A trying to complete the same, but through running and modifying I am not achieving with their scripts. This is why I do not want to include any bad script with the question to allow more of an innovative way to complete this request.
As requested, including script I have tried/modified without success:
for f in *\ *.{srt,ssa,sub} ; do
if [ -e "$f" ]; then
if [[ "$f" =~ ([0-9]+)([0-9][0-9]) || "$f" =~ s([0-9]+)e([0-9]+) || "$f" =~ ([0-9]+)x([0-9]+) ]]; then
echo "Found '$f'"
for movie in *\ *.{avi,mkv,mp4} ; do
if [ -e "$movie" ]; then
NEW_NAME=`echo "${movie%.*}".srt`
if [ "$f" = "${NEW_NAME}" ]; then
echo " Already ok"
elif [ -e "${NEW_NAME}" ]; then
echo " A file named '${NEW_NAME}' already exist, skipping"
else
mv "$f" "${NEW_NAME}"
echo " Renamed '$f' in '${NEW_NAME}'"
fi
break;
fi
done
fi
fi
done
If there's a simpler way to achieve the same, please share.
Thanks for help!
I have data coming from the backend contains a table with the element input
and when data came I append this table to the body of my table.
So my problem input element is not updated a value even if I press inspect and set the value manually also is not display the value. I don't know what is going on.
This my code coming from backend (PHP):
public function get_target_type_record(Request $request){
//...
foreach ($routes as $list) {
$table .= "<tr class='collapse order" . $i . " business_type_id_" . $item->id . "'>";
$table .= "<td><i class=\"fa fa-minus-square\"></i> </td>";
$table .= "<td>--</td>";
$table .= " <td>" . $list->id . "</td>";
$table .= "<td>" . $list->route_name . "</td>";
$table .= "<td>
<input type='text' class='form-control dynamic-input'
value='0'>
</td>";
$table .= "<td></td></tr>";
}
return response()->json($table);
}
blade file (html):
<table class="table table-hover users-table">
<thead>
<tr>
<th>#</th>
<th>ID</th>
<th>Name</th>
<th>Quantity</th>
</tr>
</thead>
<tbody id="target-table">
</tbody>
</table>
and this my jQuery code:
$('#select2-target_type_group_menu2').on('change', function(event) {
var menu2_id = this.value;
var menu1_id = document.getElementById('menu1_id').value;
event.preventDefault();
$.ajax({
url: "",
type: "GET",
dataType: 'json',
data:{
item_type : [
menu1_id,
menu2_id
],
},
success: function (data) {
document.getElementById('item_IDs').value = data.item_IDs;
$("#target-table").empty();
$('#target-table').append(data.table);
}
});
});
I have been trying to install Rust via rustup
on a Windows Subsytem for Linux (wsl) as mentioned here.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
which keeps erring to
curl: (60) SSL certificate problem: self signed certificate in certificate chain
More details here: https://curl.haxx.se/docs/sslcerts.html
curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
Some SO answers mention using -k/--insecure
to get around this, so I executed curl --insecure --proto ...
to no avail. Some issues on GitHub mention using export RUST_USE_HYPER=1
pre curl
ing but I didn't do that as I have no idea what that means (or if it works). I also tried downloading rustup-init.sh
directly (from https://sh.rustup.rs
) and then just running it but it also gives the same error. I haven't yet found a lead on some other way of being able to do this.
How does one install rustup
in wsl?
Env:
Windows 10 ver 20H2 WSL ver 1
I'm new to Blazor and working in a server-side Blazor app (.NET 5) have the following:
I have the following form:
<EditForm Model="@MyObject" OnValidSubmit="Submit">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText id="name" @bind-Value="MyObject.Name" />
<button type="submit">Submit</button>
</EditForm>
Code behind:
public MyObject MyObject { get; set; } = new MyObject();
[Inject]
private IMyObjectService myObjectService { get; set; }
[Inject]
private NavigationManager navigationManager { get; set; }
void Submit()
{
var created = myObjectService.CreateMyObject(MyObject);
if (created != null)
{
navigationManager.NavigateTo("myobjects/manage");
} else
{
// do something
}
}
Repo:
private readonly ApplicationDbContext _dbContext;
public MyObjectRepo(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<MyObject> CreateMyObject(MyObject MyObject)
{
_dbContext.Add(MyObject);
await _dbContext.SaveChangesAsync();
return MyObject;
}
public async Task<bool> DoesMyObjectExistByName(string name)
{
var exists = await _dbContext.MyObjects.AnyAsync(x => x.Name == name);
if (exists) return true;
return false;
}
I then have a MyObjectService
private readonly IMyObjectRepo _myObjectRepo ;
public MyObjectService(IMyObjectRepo myObjectRepo )
{
_myObjectRepo = myObjectRepo;
}
public async Task<MyObject> CreateMyObject(MyObject MyObject)
{
if (MyObject == null) throw new ArgumentNullException("MyObject cannot be null.");
// THIS LINE THROWS THE EF ERROR
var exists = await _myObjectRepo.DoesMyObjectExistByName(MyObject.Name);
if (!exists)
{
return await _myObjectRepo.CreateMyObject(MyObject);
} else
{
return null;
}
}
But every time I call the service to createMyObject method, EF throws an error:
Error: System.InvalidOperationException: A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext.
In Startup.cs (.NET 5), I configure with a Transient lifetime.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Default")),
ServiceLifetime.Transient);
services.AddAutoMapper(typeof(Startup));
services.AddScoped<IMyObjectRepo, MyObjectRepo>();
services.AddScoped<IMyObjectService, MyObjectService>();
I think I'm using all the correct syntax for async/await and thread safety, any ideas?
I am making a music app where the user can add FX to playing music through a pad. I am using FFmpeg in C++ to dsp. In FFmpeg you can create an audio filter and set it parameters just like the following:
beat_fx = avfilter_get_by_name("aecho");
beat_fx_ctx = avfilter_graph_alloc_filter(filterGraph, beat_fx, "echo");
av_opt_set(beat_fx_ctx, "decays", std::to_string(std::max(0.00001, (beatFX.xSoundPerc + 1) / (double)2)).c_str(), AV_OPT_SEARCH_CHILDREN);
av_opt_set(beat_fx_ctx, "delays", std::to_string(beatFX.ms).c_str(), AV_OPT_SEARCH_CHILDREN);
av_opt_set_double(beat_fx_ctx, "in_gain", 1.0, AV_OPT_SEARCH_CHILDREN);
av_opt_set_double(beat_fx_ctx, "out_gain", 1.0, AV_OPT_SEARCH_CHILDREN);
if (avfilter_init_str(beat_fx_ctx, nullptr) < 0) {
LOGE("FXProcessor::FXProcessor Could not initialize the beat_fx_ctx filter!");
isOff = true;
return;
}
My problem is since the user will use a FX pad to change these parameters I need to be able to modify these parameters during runtime.
Looking at ffmpeg filter documentation:
Some options can be changed during the operation of the filter using a command. These options are marked ’T’ on the output of ffmpeg -h filter=. The name of the command is the name of the option and the argument is the new value.
I looked at aecho, agate, acrusher
and more but nearly all the effects I want have 0 modifiable option which makes my FX pad nonadjustable. I am not using command line to process my effects, so maybe the link above is irrelevant.
Is there a way to make ffmpeg audio filters change their parameters during runtime?
I have a custom ValueGenerator as follows:
public class UtcDateTimeGenerator : ValueGenerator<DateTime>
{
public override DateTime Next(EntityEntry entry)
{
// This method never seems to be called
return DateTime.UtcNow;
}
protected override object NextValue(EntityEntry entry)
{
// This one is called.
return DateTime.UtcNow;
}
public override bool GeneratesTemporaryValues => false;
}
On my entity's IEntityTypeConfiguration
I have this:
builder.Property(x => x.Created)
.ValueGeneratedOnAdd()
.HasValueGenerator<UtcDateTimeGenerator>()
.IsRequired();
I have a generic repository:
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : class
{
private readonly EmpiresDbContext _dbContext;
private readonly DbSet<TEntity> _table;
public Repository(EmpiresDbContext dbContext)
{
_dbContext = dbContext;
_table = _dbContext.Set<TEntity>();
}
public async Task<IQueryable<TEntity>> GetQueryAsync()
{
return _table;
}
public async Task<TEntity> GetByIdAsync(object id)
{
return await _table.FindAsync(id).ConfigureAwait(false);
}
public void Insert(TEntity obj)
{
_table.Add(obj);
}
public void Update(TEntity obj)
{
_table.Attach(obj);
_dbContext.Entry(obj).State = EntityState.Modified;
}
public async Task DeleteAsync(object id)
{
var existing = await _table.FindAsync(id).ConfigureAwait(false);
_table.Remove(existing);
}
public async Task SaveAsync()
{
await _dbContext.SaveChangesAsync().ConfigureAwait(false);
}
public IDatabaseTransaction StartTransaction()
{
return new DatabaseTransaction(_dbContext);
}
}
When I call Insert()
I have used the debugger to verify that the call to _table.Add(obj);
does in fact call the protected override object NextValue(EntityEntry entry)
method on the UtcDateTimeGenerator
, and after the call to _table.Add(obj);
I can inspect the obj
and see that the Created
property has a value.
However, when public async Task SaveAsync()
calls await _dbContext.SaveChangesAsync().ConfigureAwait(false);
I get an exception
SqlException: Cannot insert the value NULL into column 'Created'
Insert()
and SaveAsync()
are called from within a service using the following code:
var player = new Player(externalId, displayName, email); // The entity we're creating
await using (var transaction = _repository.StartTransaction())
{
try
{
_repository.Insert(player);
// TODO Add any other new player setup here
await _repository.SaveAsync().ConfigureAwait(false);
await transaction.CommitAsync().ConfigureAwait(false);
}
catch
{
await transaction.RollbackAsync().ConfigureAwait(false);
throw;
}
}
DatabaseTransaction
is as follows:
public sealed class DatabaseTransaction : IDatabaseTransaction
{
private readonly IDbContextTransaction _transaction;
public DatabaseTransaction(EmpiresDbContext dbContext)
{
_transaction = dbContext.Database.BeginTransaction();
}
public void Commit()
{
_transaction.Commit();
}
public void Rollback()
{
_transaction.Rollback();
}
public async Task CommitAsync()
{
await _transaction.CommitAsync();
}
public async Task RollbackAsync()
{
await _transaction.RollbackAsync();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed = false;
private void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
_transaction?.Dispose();
}
_disposed = true;
}
public ValueTask DisposeAsync()
{
try
{
Dispose();
return default;
}
catch (Exception exception)
{
return new ValueTask(Task.FromException(exception));
}
}
}
I have a dataset like this:
data = pd.DataFrame({'order_date-time':['2017-09-13 08:59:02', '2017-06-28 11:52:20', '2018-05-18 10:25:53', '2017-08-01 18:38:42', '2017-08-10 21:48:40','2017-07-27 15:11:51',
'2018-03-18 21:00:44','2017-08-05 16:59:05', '2017-08-05 16:59:05','2017-06-05 12:22:19'],
'delivery_date_time':['2017-09-20 23:43:48', '2017-07-13 20:39:29','2018-06-04 18:34:26','2017-08-09 21:26:33','2017-08-24 20:04:21','2017-08-31 20:19:52',
'2018-03-28 21:57:44','2017-08-14 18:13:03','2017-08-14 18:13:03','2017-06-26 13:52:03']})
I want to calculate the time differences between these dates as the number of days and add it to the table as the delivery delay column. But I need to include both day and time for this calculation for example, if the difference is 7 days 14:44:46 we can round this to 7 days.
Im following Facebook's Graph API, trying to upload a Custom Conversion without success (https://developers.facebook.com/docs/marketing-api/audiences/guides/custom-audiences#upload). I managed to create the audience, nomalize and hash my data accordingly (I know this to be true as I us it on other requests) but can´t update my audience.
const upload = {
"payload": {
"schema": [
"FN",
"LN",
"EMAIL",
],
"data": users.transactions.map(transaction => ([
normalizeData(transaction.customer.firstName),
normalizeData(transaction.customer.lastName),
normalizeData(transaction.customer.email),
]))
},
"access_token": access_token, 'www-authenticate': `OAuth "Facebook Platform" "invalid_request" "Unsupported post request. Object with ID 'xxxxxx' does not exist,
};
async function uploadUsersCA(audienceID, payload) {
try {
return await axios.post(`https://graph.facebook.com/${api_version}/${audienceID}/users`, payload);
} catch (error) {
console.error(error);
}
}
Please help! I keep geting
status: 400,
statusText: 'Bad Request', 'www-authenticate': `OAuth "Facebook Platform" "invalid_request" "Unsupported post request. Object with ID 'xxxxxxxx' does not exist,
And I know as a fact it exists and have permisions as I can GET, DELETE it and more! I think the mistake could be on const upload, but cant find it, Please help!
I have to create a real time report web app to display data from a SQL Server. The data will be inserted by other application and everytime that a new record is inserted, I have to display the new changes in my app.
I have been thinking about and Angular application for the frontend and spring for the backend. To get the data updates in real time, I have been reading about websockets, spring cloud data flow or even triguers to call an url after intert data but I don't know wich option is better or what is the best way to do it.
I am replacing strings of text with automation with DocVariable fields. The only issues is when these strings, going forward I will referrer to as TAGS, is when the TAG is located within "TextBox" Controls.
I use two modules to replace tags with DOCVARIABLES
***TAG Example: "DEPARTMENT_NAME" string text
DOCVARIABLE EXAMPLE: {DOCVARIABLE "Department_Name" * MERGEFORMAT}***
Module 1
Public Function PopulateDocuments() As Boolean
Dim Department_Name As String
Department_Name = "Department_Name"
ReplaceWithDocVar "DEPARTMENT_NAME", "Department_Name"
End Function
Module 2
Public Function ReplaceWithDocVar(strFind As String, strVarName As String) As Boolean
Dim oStory As Range
Dim TextColor As Range
Dim strDocName As String
Dim orgDocName As String
Dim orgPath As String
Dim intPos As Integer
Dim docpath As String
Dim docname As String
Application.DisplayAlerts = False
For Each oStory In ActiveDocument.StoryRanges
With oStory.Find
Do While .Execute(FindText:=strFind, MatchCase:=True, MatchWholeWord:=True)
oStory.Text = ""
'oStory.Text = wdBlue
oStory.Fields.Add Range:=oStory, _
Type:=wdFieldDocVariable, _
Text:=Chr(34) & strVarName & Chr(34), _
PreserveFormatting:=True
oStory.Collapse 0
Loop
End With
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
With oStory.Find
Do While .Execute(FindText:=strFind, MatchCase:=True, MatchWholeWord:=True)
oStory.Text = ""
'oStory.Text = wdBlue
oStory.Fields.Add Range:=oStory, _
Type:=wdFieldDocVariable, _
Text:=Chr(34) & strVarName & Chr(34), _
PreserveFormatting:=True
'oStory.Font.ColorIndex = wdBlue
oStory.Collapse 0
Loop
End With
Wend
End If
Next oStory
Set oStory = Nothing
lbl_Exit:
Exit Function
End Function
Note: I am not the author of this code but it runs very well all of the same.
I do not see any error messages when replacing those TAGs that I can locate. All TAGS excluding those in textboxes are correctly replaced with DOCVARIABLES.
I'm trying to find a way to typesafe a recursion (which returns a number by the end) using generics.
What I tried:
function recursion<N,T>(value:N, lim:N):T|N {
if(value < lim) return recursion<N, T>(value+1,lim);
return value;
}
recursion<number, Function>(0,10);
Despite passing type number
, Typescript decided to give me an error:
TSError: ⨯ Unable to compile TypeScript:
src/main.ts:2:41 - error TS2365: Operator '+' cannot be applied to types 'N' and 'number'.
2 if(value < lim) return recursion<N, T>(value+1,lim);
I assumed that operations were possible as long as I passed number
type on the generic, but it doesn't seem to be the case. Why is that and is there any possible workaround?
I read JSON from URL and display as table format in MVC View DotnetCore.I have @Html.TextBoxFor control inside this same view under form control.
To display in table format, i have used both register @model and using statement inside view.So i can't able to access @Html.TextBoxFor values in controller action method.Is any way of accessing HTML:Textboxfor inside view in action Controller?
@model System.Data.DataTable
@using System.Data;
@using (Html.BeginForm("Index", "Admin", FormMethod.Post)){ @Html.TextBoxFor(s => s.ImportJsonUrlName, new { id = "PickUrlID", style = "width:800px" })
<table class="table table-bordered table-dark">
<thead>
<tr>
@foreach (DataColumn col in Model.Columns)
{
<th>@col.ColumnName</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@foreach (DataColumn col in Model.Columns)
{
<td>@row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
Controller code:
[HttpPost]
public IActionResult Index(AdminModel model)
{
DataTable dt = new DataTable();
string json = (new WebClient()).DownloadString("https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json");
dt = JsonConvert.DeserializeObject<DataTable>(json);
return View(dt);
}
I am attempting to open a file I have created called "inputs.txt" using ubuntu on Windows. In the Linux manual I found that the O_DIRECTORY flag is used for files in the same directory and will fail if they are not in that directory. I used this flag and saved the "inputs.txt" file in the same folder as my .c file. Any ideas why it is failing to open?
int main(){
int fd;
fd = open("inputs.txt", O_DIRECTORY);
if (fd == -1){
printf("Failed");
exit(1);
}
return 0;
}
I was trying to make a const member but it says "TypeError: Cannot read property 'users' of undefined"
module.exports = {
name: 'welcome',
description: 'welcome',
execute(message, args, Discord) {
const member = message.mentions.users.first();
if(message.member.permissions.has('ADMINISTRATOR')){
message.channel.send(
new MessageEmbed()
.setTitle('title')
.setImage('imageurl')
.setDescription('desc')
)
}else{
return message.channel.send(`You don't have any permissions to do that!`)
}
}
}
I've got a JSON object that looks like this
Key1 = Value1
Key2 = Value2
This pattern continues x times, always
If I JSON.Stringify I get
Key1 = Value1\nKey2 = Value2\nKey3 = Value3\n
How can I get an array along the lines of
{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}
I'm not even sure how to Google what I need. Any pointers greatly appreciated.
I have multiple ASP.NET Core 3.1 programs using http.sys being started by a single process running as a windows service. The service puts all processes in the same job to make sure that if it should die all processes are terminated as well.
This works perfectly fine, except sometimes when restarting the service I get the following error during startup:
[Error] [Microsoft.AspNetCore.Server.HttpSys.HttpSysListener] Start
Microsoft.AspNetCore.Server.HttpSys.HttpSysException (183): The prefix 'http://+:31955/' is already registered.
at Microsoft.AspNetCore.Server.HttpSys.UrlGroup.RegisterPrefix(String uriPrefix, Int32 contextId)
at Microsoft.AspNetCore.Server.HttpSys.UrlPrefixCollection.RegisterAllPrefixes(UrlGroup urlGroup)
at Microsoft.AspNetCore.Server.HttpSys.HttpSysListener.Start()
Waiting a few seconds and then starting the service again allows the processes to start without problems every time. My assumption therefore is that there is a race condition between http.sys freeing the url registration from the killed process and giving it to the new one.
What is the best way to avoid such a problem?
How (or where) do I change my StackOverflow/StackExchange password? (I've spent about 5 minutes trying to find this. I found it, but then saw something shiny and can't find it again.)
I've been trying to get puppeteer to launch a unique instance for every profile stored in a .json file. This is because currently I am stuck creating a new folder with all my code and a unique .json file for every account/instance I want to run. I'd prefer if I could just store all my info in 1 .json file and then have my code launch a unique instance for each profile.
Goal:
Example: Puppeter instance 1 launch with profile 1, puppeteer instance 2 launch with profile 2, etc.
Example of settings.json
[
{
"email": "email1@gmail.com"
},
{
"email": "email2@gmail.com"
},
{
"email": "email3@gmail.com"
}
]
Example of main.js
const fs = require('fs');
const puppeteer = require('puppeteer');
const profile = JSON.parse(fs.readFileSync('./settings.json'));
var id = 0
while (id <= 2) {
emailInfo = profile[id].email;
console.log(emailInfo)
botRun()
id++;
}
function botRun() {
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.waitForTimeout(500)
console.log('function ' + emailInfo) //pretend this is page.type --> it would result in 'email3@gmail.com' for all instances since this is what the var is now but I want it to stay with the info in the loop
await browser.close();
})();
}
Obviously this is horrendously wrong since emailInfo var will update therefore resulting in puppeteer applying the latest value. Is there any way I can make each puppeteer instance stick with the unique data?
enter code here
package application;
public class Person {
String Id;
String fullName;
String street;
String city;
String gender;
String zip;
public Person(String Id) {
this.Id = Id;
}
public Person(String Id,String fullName, String street, String city, String gender, String zip) {
this(Id);
this.fullName=fullName;
this.street = street;
this.city = city;
this.gender = gender;
this.zip = zip;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getSUID() {
return Id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
@Override
public String toString() {
return "Id: " + Id +"Full Name: " + fullName + " | Street: " + street +
" | City: " + city + " | Gender: " + gender + " | Zip: " + zip;
}
}
enter code herepackage application;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.io.*;
import java.nio.file.DirectoryStream.Filter;
import java.util.ArrayList;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
AddressBook addrPane = new AddressBook("C:\\Users\\fener\\eclipse-
workspace\\Projectfx\\src");
primaryStage.setScene(new Scene(addrPane));
primaryStage.setTitle("Address Book");
primaryStage.show();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText("Look, an Information Dialog");
}
}
class BasicAddressPane extends GridPane {
// Labels
Label lblId;
Label lblSUID;
Label lblName;
Label lblStreet;
Label lblCity;
Label lblGender;
Label lblZip;
// TextFields
TextField tfId;
TextField tfSUID;
TextField tfName;
TextField tfStreet;
TextField tfCity;
TextField tfGender;
TextField tfZip;
BasicAddressPane() {
// Grid pane settings
this.setPadding(new Insets(10));
this.setHgap(140);
this.setVgap(10);
// Create Labels with Textfield
lblId = createComponent(" ID:", 0, tfId = new TextField(), 0);
lblSUID = createComponent("Search/UpdateID:", 0, tfSUID = new TextField(), 0);
lblName = createComponent("Name:", 0, tfName = new TextField(), 0);
lblStreet = createComponent("Street:", 0, tfStreet = new TextField(), 0);
lblCity = createComponent(" City:", 140, tfCity = new TextField(), 100);
lblGender = createComponent("Gender:", 90, tfGender = new TextField(), 40);
lblZip = createComponent("Zip:", 138, tfZip = new TextField(), 110);
// add id on first row
this.add(lblId, 0, 0, 4, 1);
tfId.setPrefColumnCount(4);
// add id on first row
this.add(lblSUID, 1, 0, 4, 1);
tfSUID.setPrefColumnCount(9);
// add name on second row
this.add(lblName, 0, 1, 4, 1);
tfName.setPrefColumnCount(27);
// add street on third row
this.add(lblStreet, 0, 2, 4, 1);
tfStreet.setPrefColumnCount(27);
// add city, state, zip on fourth row
HBox hBox = new HBox();
hBox.getChildren().addAll(lblCity, lblGender, lblZip);
hBox.setMaxWidth(410);
hBox.setSpacing(1);
this.add(hBox, 0, 3, 4, 1);
}
/**
* @param name - Name of Label
* @param lblWidth - Label max width: 0 = default
* @param textField - TextField to be attached with label
* @param tfWidth - TextField max width: 0 = default
* @return Label
*/
private Label createComponent(String name, double lblWidth, TextField textField, double tfWidth)
{
Label label = new Label(name, textField);
label.setContentDisplay(ContentDisplay.RIGHT);
// set textfield and label custom min width if needed
if (lblWidth > 0) {
label.setMaxWidth(lblWidth);
}
if (tfWidth > 0) {
textField.setMaxWidth(tfWidth);
}
return label;
}
protected void setTextFields(String Id,String SUID,String name, String street, String city,
String gender, String zip) {
tfId.setText(Id);
tfSUID.setText(SUID);
tfName.setText(name);
tfStreet.setText(street);
tfCity.setText(city);
tfGender.setText(gender);
tfZip.setText(zip);
}
}
class AddressBook extends BasicAddressPane {
ArrayList<Person> persons;
int index = 0;
// Buttons
Button btnAdd;
Alert alert = new Alert(AlertType.INFORMATION);
Button btnFirst;
Button btnNext;
Button btnPrev;
Button btnLast;
Button btnSearch;
Button btnUpdate;
Button btnClear;
boolean isNewFile;
String fileName = "AddressBook.dat";
File file;
AddressBook() {
this(System.getProperty("user.dir")); // default path is current working directory
}
AddressBook(String path) {
btnAdd = new Button("Add");
btnFirst = new Button("First");
btnNext = new Button("Next");
btnPrev = new Button("Prev");
btnLast = new Button("Last");
btnSearch = new Button("SearchById");
btnUpdate = new Button("UpdateById");
btnClear = new Button ("CleanTextFields");
// Init buttons and create bottom button panel
HBox hBox = new HBox(10, btnAdd, btnFirst, btnPrev, btnNext, btnLast, btnSearch, btnUpdate,
btnClear);
//hBox.setAlignment(Pos.CENTER);
this.add(hBox, 0, 4, 5, 1);
// create listeners
btnAdd.setOnAction(e -> addPerson());
btnUpdate.setOnAction(e -> updatePerson());
btnFirst.setOnAction(e -> {
index = 0;
refresh();
});
btnLast.setOnAction(e -> {
index = persons.size() - 1;
refresh();
});
btnNext.setOnAction(e -> next());
btnPrev.setOnAction(e -> previous());
btnClear.setOnAction(e -> clear());
// Get address book file
file = new File(path + fileName);
// if file doesn't exist, create it
try {
isNewFile = file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (!isNewFile) {
syncPersons();
} else {
persons = new ArrayList<>();
}
refresh();
}
private void previous() {
if (index > 0) {
index--;
refresh();
tfId.setDisable(true);
}
}
private void next() {
if (index != persons.size() - 1) {
index++;
refresh();
tfId.setDisable(true);
}
}
private void refresh() {
if (persons.isEmpty()) return;
Person c = persons.get(index);
setTextFields(
c.getId(),
c.getSUID(),
c.getFullName(),
c.getStreet(),
c.getCity(),
c.getGender(),
c.getZip()
);
}
private void clear() {
cleanTextFields();
tfId.setDisable(false);
}
private void cleanTextFields() {
tfId.clear();
tfSUID.clear();
tfName.clear();
tfStreet.clear();
tfCity.clear();
tfGender.clear();
tfZip.clear();
}
public void searchID(){
}
public void addPerson() {
persons.add(getCurrentPerson());
index = persons.size() - 1;
refresh();
savePersons();
alert.setContentText("Record is added successfully");
alert.showAndWait();
cleanTextFields();
}
public void updatePerson() {
persons.remove(index);
persons.add(index, getCurrentPerson());
savePersons();
tfId.setDisable(true);
}
public Person getCurrentPerson() {
return new Person(
tfId.getText(),
tfName.getText(),
tfStreet.getText(),
tfCity.getText(),
tfGender.getText(),
tfZip.getText()
);
}
/**
* Reads address book and saves Persons to ArrayList
*/
private void syncPersons() {
// Init new buffer array
persons = new ArrayList<>();
// Byte array for each field
byte[] Id = new byte[4];
byte[] name = new byte[32];
byte[] street = new byte[32];
byte[] city = new byte[20];
byte[] gender = new byte[2];
byte[] zip = new byte[5];
try (FileInputStream input = new FileInputStream(file)) {
while (input.available() >= 95 && -1 != input.read(Id)) {
input.read(name);
input.read(street);
input.read(city);
input.read(gender);
input.read(zip);
persons.add(new Person(
new String(Id, "UTF-8"),
new String(name, "UTF-8"),
new String(street, "UTF-8"),
new String(city, "UTF-8"),
new String(gender, "UTF-8"),
new String(zip, "UTF-8")
));
}
} catch (IOException e) {
e.printStackTrace();
}
}
//FileOperations test= new FileOperations();
public byte[] getFixedSizeByteArray(String string, int fixedSize) {
byte[] src = string.getBytes();
byte[] fixedArray = new byte[fixedSize];
System.arraycopy(src, 0, fixedArray, 0, Math.min(src.length, fixedSize));
return fixedArray;
}
private void savePersons() {
try (FileOutputStream out = new FileOutputStream(file)) {
for (Person c : persons) {
out.write(getFixedSizeByteArray(c.getId(), 4));
out.write(getFixedSizeByteArray(c.getFullName(), 32));
out.write(getFixedSizeByteArray(c.getStreet(), 32));
out.write(getFixedSizeByteArray(c.getCity(), 20));
out.write(getFixedSizeByteArray(c.getGender(), 2));
out.write(getFixedSizeByteArray(c.getZip(), 5));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I type the Id number in the Search / UpdateId textfield and press the SearchById button, the person with that ID should come. I need a search function that does them. And SearchByID textfields must be empty, but The Search / Update ID textfield shows the id's number, it should only get input from the user.
I'm trying to take a string find if the string contains a word, in my case the word "Message", and then if it contains that word find the word directly after it. My relevant code so far is as follows.
public bool Find(string Word,string Text)
{
return Text.Contains(Word);
}
And then it uses the function in various ways but for this specific purpose It needs to find "Message" as follows
if (Find("Message", MessageText))
{
//I don't know what to put here
}
I need to take the string MessageText and Then find Message within the string and then output the first word after the word Message. e.g "Whatever random string Message Brad and more random string" I want to output Brad
I have data with three groups and would like to perform a different custom function on each of the three groups. Rather than write three separate functions, and calling them all separately, I'm wondering whether I can easily wrap all three into one function with a 'group' parameter.
For example, say I want the mean for group A:
library(tidyverse)
data(iris)
iris$Group <- c(rep("A", 50), rep("B", 50), rep("C", 50))
f_a <- function(df){
out <- df %>%
group_by(Species) %>%
summarise(mean = mean(Sepal.Length))
return(out)
}
The median for group B
f_b <- function(df){
out <- df %>%
group_by(Species) %>%
summarise(median = median(Sepal.Length))
return(out)
}
And the standard deviation for group C
f_c <- function(df){
out <- df %>%
group_by(Species) %>%
summarise(sd= sd(Sepal.Length))
return(out)
}
Is there any way I can combine the above functions and run them according to a group parameter?? Like: fx(df, group = "A")
Which would produce the results of the above f_a function??
Keeping in mind that in my actual use context, I can't simply group_by(group) in the original function, since the actual functions are more complex. Thanks!!
Consider:
from __future__ import annotations
class A:
@classmethod
def get(cls) -> A:
return cls()
class B(A):
pass
def func() -> B: # Line 12
return B.get()
Running mypy on this we get:
$ mypy test.py
test.py:12: error: Incompatible return value type (got "A", expected "B")
Found 1 error in 1 file (checked 1 source file)
Additionally, I have checked to see if old-style recursive annotations work. That is:
# from __future__ import annotations
class A:
@classmethod
def get(cls) -> "A":
# ...
...to no avail.
Of course one could do:
from typing import cast
def func() -> B: # Line 12
return cast(B, B.get())
Every time this case pops up. But I would like to avoid doing that.
How should one go about typing this?
i have an User Class and i want to retreive from CompletableFuture<Optional>
CompletableFuture<Optional<User>> userCache = plugin.getBPApi().getUser(player.getUniqueId());
User user = userCache.get();
return String.valueOf(user.getTier());
But when i compile it throws the following error:
java.util.Optional<io.github.battlepass.objects.user.User> cannot be converted to io.github.battlepass.objects.user.User
What i'm doing wrong ?
Is it possible to use a variable inside the template define function? I attempted to wrap the variable in brackets but it seems to fail. Example
.deployment -}}
I am using the ChartJS library to display a bar chart on my HTML page. The issue I am facing is when the page loads, it displays an empty bar chart without the data I have passed into it and without rendering the bars. After one click to the legend, the chart resizes and my labels appear on the x-axis, on the second click the bars are rendered and the y-axis populates to my passed in data. I am not sure why the chart is behaving this way.
I tested the chart with the code provided in the chart.js documentation and it appears instantly. I think the issue has to do with how I am calling my express backend to retrieve data from my endpoint.
Not sure how to resolve this issue. Any help is appreciated.
index.html:
<canvas
id="patents-per-category-bar-chart"
width="400"
height="400"
></canvas>
<script type="text/javascript">
var categoryLabels = [];
var categoryValues = [];
var centerLabels = [];
var centerValues = [];
$.getJSON("http://localhost:5000/api").done((data) => {
for (let item in data.patentsPerCategory) {
if (!data.patentsPerCategory.hasOwnProperty(item)) {
continue;
}
categoryLabels.push(item);
categoryValues.push(data.patentsPerCategory[item]);
}
for (let item in data.patentsPerCenter) {
if (!data.patentsPerCenter.hasOwnProperty(item)) {
continue;
}
centerLabels.push(item);
centerValues.push(data.patentsPerCenter[item]);
}
});
var ctx = document
.getElementById("patents-per-category-bar-chart")
.getContext("2d");
var barChartConfig = {
type: "bar",
data: {
labels: categoryLabels,
datasets: [
{
backgroundColor: "blue",
label: "# Patents Per Category",
data: categoryValues,
},
],
},
options: {
legend: {
onClick: null,
},
responsive: true,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
};
var categoryBarChart = new Chart(ctx, barChartConfig);
</script>
mock data returned from the api:
{
"category": {
"health medicine and biotechnology": 37,
"instrumentation": 38,
"storage": 30,
"systems": 71,
"aeronautics": 1,
"electronics": 47,
"optics": 60,
"materials": 119,
"undefined": 3,
"communications": 32,
"sensors": 102,
"robotics": 37,
"software": 49,
"propulsion": 9,
"manufacturing": 40,
"environment": 24,
"aerospace": 79
}
}
After returning this data from the api, I iterate over it and push the keys and values into separate arrays which are categoryLabels, categoryValues. Then pass these arrays directly into the labels and data for the chart
Created a jsFiddle: https://jsfiddle.net/tkdamxr5/1/
It works fine in the jsFiddle enviornment so the issue must be in the way I am calling my data using jQuery. Can anyone clarify how I need to call my express backend to get the data and pass it into the chart so it works correctly?
I am initializing my Binding value in my custom way, which is working just fine, Now I like to make this custom initialisation be able to effect the source of truth, how I could possibly make this happen? For giving you more information about what I just said: my BindingView controls the incoming value right in the front door and decide the action with some logic, while this happening my Binding value became in some way unable/forgot to update source of truth, after Initialisation BindingView, ContentView and BindingView have deferent prospective of value! the goal is putting some kind of codes in initializing BindingView to make this happen, to having same value for both Views. thanks for reading and helping.
import SwiftUI
struct ContentView: View {
@State private var value: Int = Int()
var body: some View {
Text("value of ContentView:" + value.description)
.padding()
Button ("update value to 0") {
value = 0
}
.padding()
Button ("update value to 1") {
value = 1
}
.padding()
BindingView(value: $value)
.padding()
}
}
struct BindingView: View {
@Binding var value: Int
init(value: Binding<Int>) {
print("initializing Binding,", "incoming value:", value.wrappedValue.description)
if value.wrappedValue == 0 {
_value = .constant(100)
}
else {
_value = value
}
}
var body: some View {
Text("value of BindingView:" + value.description)
}
}
I created a table in HTML but I am dynamically adding rows that are editable so the user can add values to the table. If the user presses cancel, the table row they no longer want to add is removed from the table. However, I can't seem to figure out how to remove the table row when they press the cancel button. Additionally, I console logged table.rows.length and it outputs incorrect values. I have attached an image, to provide an example. For some reason, it's incrementing an additional "click" and decreasing the table value when I will press the button. When there are no entries in the table, it says the length is 2. And inside my eventlistener for the cancel button, it increments multiple times with different values.
I have seen solutions saying to use table.deleteRow(tables.rows.length-1) but it doesn't work for me. To remove the table I am using table.deleteRow(-1);
, which works initally but after the third time, I starts to delete about the row, click again and it deletes the thead section with the table titles which basically deleted the entire table.
How can I remove the final row in my table. Also why is tables.row.length giving me incorrect values? Any help would be greatly appreciated. I have been stuck on this for quite some time.
JS:
function addMilestone(){
//Get edit functionalty buttons
var save_btn = document.getElementById("milestone-save-btn");
var cancel_btn = document.getElementById("milestone-cancel-btn");
var btn_container = document.getElementById("milestone-btns-container");
// get notification popup for user
var status = document.getElementById("status");
//Display the buttons
btn_container.setAttribute("style", "opacity:1");
// btn_container.setAttribute("style", "display:flex");
save_btn.setAttribute("cursor", "pointer");
cancel_btn.setAttribute("cursor", "pointer");
//Hide edit button
milestone_btn.setAttribute("style", "opacity:0");
//Add table row with editable textboxs
const table = document.getElementById("milestone-table");
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.setAttribute("style", "text-align:center");
cell1.setAttribute("contenteditable", true);
cell2.setAttribute("style", "text-align:center");
cell2.setAttribute("contenteditable", true);
//Add delete button row
var delete_span = document.createElement("span");
delete_span.className = "delete";
delete_span.setAttribute("style", "display:inline");
delete_span.innerHTML = "×"
cell3.appendChild(delete_span);
var deleteMilestone_btn = document.querySelectorAll(".delete");
deleteMilestone_btn.forEach(btn => {
//Display all buttons
btn.setAttribute("style", "display:inline");
//If button is clicked, remove row from table
btn.addEventListener("click", function(){
var td = event.target.parentNode; //event.target is the input element
var tr = td.parentNode; //the row we want to remove
tr.parentNode.removeChild(tr);
}
//Cancel when clicked
cancel_btn.addEventListener("click", function(){
console.log("clicked");
console.log("Table : ", table.rows.length);
//remove the table row added that wont be used
table.deleteRow(-1);
//remove buttons
btn_container.setAttribute("style", "opacity:0");
btn_container.setAttribute("style", "width:0");
save_btn.setAttribute("cursor", "default");
cancel_btn.setAttribute("cursor", "default");
// Display Edit Button
milestone_btn.setAttribute("style", "opacity:1");
});
}
HTML:
<!-- Table -->
<div class="milestone-container">
<table id="milestone-table">
<thead>
<tr>
<th>Milestones</th>
<th>Progress</th>
<th style="width: 5%;"></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
</div>
<div id="milestone-btns-container">
<div class="editing-btns">
<div id="milestone-cancel-btn">Cancel</div>
<div id="milestone-save-btn">Save</div>
</div>
</div>
<button id="milestone-btn">Add Milestone</button>
Using Python 3.8 I am trying to scrape a page with Pyppeteer. This code works on a different computer but not the current desktop I am running it on.
My code is:
async def main():
# launches a chromium browser, can use chrome instead of chromium as well.
browser = await pyppeteer.launch(headless=False)
# creates a blank page
page = await browser.newPage()
# follows to the requested page and runs the dynamic code on the site.
options = {'timeout': 15000}
await page.goto('link', options)
# provides the html content of the page
cont = await page.content()
await page.close()
await browser.close()
return cont
# stores the html code
page=(asyncio.get_event_loop().run_until_complete(main()))
When I run this it opens a Chromium browser but does not try to load the link. It sits on a tab that says "about:blank". If i manually put in a link it goes to the page, but still does not pull the html code.
I also tried running this with Chrome in case the issue was Chromium but the same thing happened. This leads me to believe that it is an issue with my code, but yet it runs fine on a different desktop so I cannot solve what the issue is.
Solved
nest_asyncio was updated from 1.4.2 to 1.4.3
Moving from PHP 7.4 to PHP 8.0, I've got a problem with some code throwing a warning. Code works, but I would like to figure out the problem. There were no Warnings in PHP 7.4. Here are the Warnings: (modified to take my info out of the error)
PHP Warning: XML::open(): Argument #1 ($parser) must be passed by reference, value given in .../classes/xml_5.php on line 89
PHP Warning: XML::open(): Argument #1 ($parser) must be passed by reference, value given in .../classes/xml_5.php on line 89
PHP Warning: XML::open(): Argument #1 ($parser) must be passed by reference, value given in .../classes/xml_5.php on line 89
PHP Warning: XML::data(): Argument #1 ($parser) must be passed by reference, value given in .../classes/xml_5.php on line 89
PHP Warning: XML::close(): Argument #1 ($parser) must be passed by reference, value given in .../classes/xml_5.php on line 89
PHP Warning: XML::open(): Argument #1 ($parser) must be passed by reference, value given in .../classes/xml_5.php on line 89
(they keep going on the same)
The code:
function __construct(){
$this->parser = xml_parser_create();
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, 'open', 'close');
xml_set_character_data_handler($this->parser, 'data');
}
function destruct(){ xml_parser_free($this->parser); }
function & parse(&$data){
$this->document = array();
$this->stack = array();
$this->parent = &$this->document;
$return_data = xml_parse($this->parser, $data, true) ? $this->document : NULL;
return $return_data;
}
The problem line (89) is at the end, this line:
$return_data = xml_parse($this->parser, $data, true) ? $this->document : NULL;
I see that in PHP 8 that xml_parse changed: 8.0.0 parser expects an XMLParser instance now; previously, a resource was expected.
I have spent days on this, and I am missing something! Thanks, everyone!
I am migrating a module from primeng 7 to primeng11 along with angular11 the code runs perfectly fine on ng serve the functionalities are working too but on build I am getting a weird error
error TS2339: Property 'value' does not exist on type 'FilterMetadata | FilterMetadata[]'.
Property 'value' does not exist on type 'FilterMetadata'.
the error is for the below code
<input *ngIf='!col.noFilter' [style.width]="'98%'" [style.height]="'25px'" pInputText type="text"
[placeholder]="col.filterPlaceHolder ? col.filterPlaceHolder : ''"
(input)="dt.filter($event.target.value, col.field, col.filterMatchMode)"
[value]="dt.filters[col.field]?.value" />
I have verified the primeng FilterMetaData
interface and it has the property value like below
export interface FilterMetadata {
value?: any;
matchMode?: string;
operator?: string;
}
the code syntax is fine i have veriified the same on primeng page docuemntation https://www.primefaces.org/primeng/showcase/#/table
Please kindly help not sure why ng serve has no ssues but build is failing. My node version is node v10.23.0
I have a Dash application that lets the user filter a pandas dataframe, which results in a graph. They can also download a CSV of the filtered dataframe. This is accomplished by passing arguments to the URL, retrieving the arguments using flask.request.args
, refiltering the database, and writing the output to a file.
While working on this solution, I added print statements to help me track variable values. Although the download link is working with the desired result, I came across some behavior that I don't fully understand. I think this may have something to do with @app.server.route
and when/how it is executed.
For example:
Print
statements are not always executed. They are executed sometimes.print
statements to execute, reloading the app and applying the same filter may result in the print
statements not executing.The download link always performs as intended, but I do not understand how the dataframe is being filtered and written via @app.server.route('/download_csv')
, while also skipping over the print
statements.
UPDATE
I have produced an MRE for Jupyter notebooks. Please note that you must pip install jupyter-dash
for this code to execute.
Some notes:
The MRE is below:
Update 2
After waiting 24hrs and running the code again, all of the lines in @app.server.route
seem to be executing. That is, until I click the download button quickly after changing filters. When this happens, I can get the print
statements to not execute. Despite not executing, the other lines are. Some guesses as to what is going on:
print
statements don't execute, it seems that a previous version of the code is being executed. Perhaps it is stored in some temporary memory location?print
statements don't execute.print
statements seem to execute less frequently after quick filter changes and download requests.import plotly.express as px
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
# Load Data
df = pd.DataFrame({'id':np.arange(100), 'name':['cat', 'dog', 'mouse', 'bird', 'rabbit']*20, 'age':np.random.randint(1,30,size=100)})
# Build App
app = JupyterDash(__name__)
app.layout = html.Div([
html.H1("JupyterDash Demo"),
dcc.Graph(id='graph'),
html.Label([
"names",
dcc.Dropdown(
id='names', clearable=False,
value='cat', options=[
{'label': names, 'value': names}
for names in df.name.unique()
])
]),
html.Label([
"age",
dcc.Dropdown(
id='age', clearable=True,
options=[
{'label': att, 'value': att}
for att in df.age.unique()
])
]),
html.Br(),
html.A(
"Download CSV",
id="download_csv",
href="#",
className="btn btn-outline-secondary btn-sm"
)
])
# Define callback to update graph
@app.callback(
[Output('graph', 'figure'),
Output('download_csv', 'href')],
[Input("names", "value"),
Input('age', 'value')]
)
def update_figure(names, age):
if not names:
names = 'Null'
fil_df = df
else:
fil_df = df[df['name'].isin([names])]
fig = px.bar(
fil_df, x='id', y='age',
title="Animals"
)
if not age:
age = 'Null'
fil_df = fil_df
else:
fil_df = fil_df[(fil_df['age'].isin([age]))]
fig = px.bar(
fil_df, x='id', y='age', title="Animals"
)
return fig, "/download_csv?value={}/{}".format(names, age)
app.run_server(mode='inline')
@app.server.route('/download_csv')
def download_csv():
value = flask.request.args.get('value')
value = value.split('/')
selected_1 = value[0]
selected_2 = value[1]
print(selected_1)
print(selected_2)
str_io = io.StringIO()
df.to_csv(str_io)
mem = io.BytesIO()
mem.write(str_io.getvalue().encode('utf-8'))
mem.seek(0)
str_io.close()
return flask.send_file(mem,
mimetype='text/csv',
attachment_filename='downloadFile.csv',
as_attachment=True)
New to access and vba.
I have a bound main form (FormA) with a combobox on it and two unbound subforms (subfrmA & subfrmB). (Both forms are attached to a table however I want them to load onto the main form where I placed an unbound subform as a placeholder)
The combobox has two values “a” and “b.” When a is selected I want subfrm A to load onto Form A. When b is selected I want subfrmB to load onto Form A. — So far I think have this part working
However when I select a record on the main form the associated subforms doesn’t appear. When I try to link the subforms to the main form an error message appears saying I can’t build a link between unbound forms.
The packageID is the link between the main form and subform snd is a hidden field on all forms. Whenever the packageID is automatically updated the psckageID in the subform fields are also updated.
Case”A”
Me.subfrmAB.SourceObject=“FormA
Me.packageDetailsID=Me.subfrmAB.packageDetailsID
Case “B”
Me.subfrmAB.SourceObject=“FormB”
Me.packageDetailsID=Me.subfrmAB.packageDetailsID
I have a folder that contains several folders. The sub folders contain each of the following, one or more .csv
files and one .tif
file. What I am trying to do is grab one of the .csv
files and the .tif
. The .tif
will be used with the GetGeoTransform()
function and the .csv
will provide column and row values to ultimately output coordinates (The .csv
files contain column and row data from the relative tif
. I understand the issue that glob.glob
returns a class type list and gdal.Open()
requires it to be in string format. I initally tried relative_tif_file = str(glob.glob(path_tif + '/*.tif')
, but that doesn't work because it is still in a list format.
Any suggestions on how to get around this?
Folder
subfolder1
1.csv
2.csv
3.csv
1.tif
subfolder2
1.csv
1.tif
...
root = 'D:/data/export_csv2/'
for i in os.listdir(root):
path_csv = root + str(i)
path_tif = root + str(i)
all_csv_files = glob.glob(path_csv + '/*.csv')
relative_tif_file = glob.glob(path_tif + '/*.tif')
ds = gdal.Open(relative_tif_file)
c, a, b, f, d, e = ds.GetGeoTransform()
RuntimeError: not a string
I deployed to My Godaddy using Asp.net Mvc, but I got errors , could not open my Url, so I edited My Web config, but still got this same error, I edited my Web.Config. but I have no idea. "Compiler Error Message: CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'."
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit
http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<customErrors mode="Off"/>
<trust level="Full" />
<compilation debug="true" targetFramework="4.7.2" >
<assemblies>
<add assembly="netstandard, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=cc7b13ffcd2ddd51"/>
</assemblies>
</compilation>
<httpRuntime targetFramework="4.7.2" />
<authentication mode="Forms">
<forms loginUrl="EmpInput/Login"></forms>
</authentication>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe"
publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral"
/>
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.AspNetCore.Http.Features"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Encodings.Web" publicKeyToken="cc7b13ffcd2ddd51"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration.Abstractions"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.DependencyInjection.Abstractions"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.FileProviders.Abstractions"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Options" publicKeyToken="adb9793829ddae60"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.DependencyInjection"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource"
publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging" publicKeyToken="adb9793829ddae60"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Hosting.Abstractions"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration.EnvironmentVariables"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Configuration.FileExtensions"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.FileProviders.Physical"
publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
</system.codedom>
<connectionStrings>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,
EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.net>
<mailSettings>
<smtp>
</smtp>
</mailSettings>
</system.net>
</configuration>
There is json data in png, and I want to read that metadata in the PNG file. I am using reactjs. After upload an image file, and then any idea?
import React, { useState } from 'react'
import {Typography, Button, Form, Input} from 'antd';
import Axios from 'axios';
function test() {
const [imgBase64, setImgBase64] = useState("");
const [imgages, setImages] = useState([]);
const fileupload = (event) => {
const readit = new FileReader();
reader.onloadend = () => {
const base64 = readit.result;
if (base64) {
setImgBase64(base64.toString());
}
}
if (event.target.files[0]) {
readit.readAsDataURL(event.target.files[0]);
setImages(event.target.files[0]);
console.log(event.target.files[0]);
}
}
return (
<div style=>
</div>
<input type="file" onChange={fileupload}/>
</div>
</div>
);
}
export default test
I'm having more trouble than I'd like to admit to structure a simple project in Python to develop using Visual Studio Code.
How should I structure in my filesystem a project that is a simple Python module, just a bunch of *.py files together. My requisites are:
I may use another linter, even another test framework.
Nothing fancy, but I'm really having trouble to get it right.
If I build a .NET 5 project that produces an executable, I get the following files:
Why are all these three files created? Older versions of .NET just generated an EXE. Why do we need two identically named DLLs in different folders to go along with the EXE?
package pprof documentation says "The package is typically only imported for the side effect of registering its HTTP handlers. The handled paths all begin with /debug/pprof/."
The documentation says if you already have an http server running you don't need to start another one but if you are not using DefaultServeMux, you will have to register handlers with the mux you are using.
Shouldn't I always use a separate port for pprof? Is it okay to use the same port that I am using for prometheus metrics?