id
stringlengths 40
40
| text
stringlengths 29
2.03k
| original_text
stringlengths 3
154k
| subdomain
stringclasses 20
values | metadata
dict |
---|---|---|---|---|
d918f28ebd7df4dd931586b1dcf46fef0f28cc22
|
Stackoverflow Stackexchange
Q: What is the correct syntax to pass a base64 instead of a url to Microsoft Azure Computer vision API using Ruby require 'net/http'
uri = URI('https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/ocr')
uri.query = URI.encode_www_form({
'language' => 'unk',
'detectOrientation ' => 'true'
})
request = Net::HTTP::Post.new(uri.request_uri)
request['Content-Type'] = 'application/octet-stream'
request['Ocp-Apim-Subscription-Key'] = 'MY_SUBSCRIPTION_KEY'
request.body = "raw_image_binary"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts response.body
I got this as a response.
{"code":"InvalidImageFormat","requestId":"3aee7147-2acc-4f64-b1c6-8453815eda38","message":"Input data is not a valid image."}
HELP!!
A: It sounds like you want to pass an image file to Azure Computer Vision API via application/octet-stream content type in Ruby, so you need to pass binary image data to response.body, not pass the base64 string of an image.
Please use the code below instead of the current one to make it works.
# Supported image formats: JPEG, PNG, GIF, BMP.
request.body = File.binread("<your image file name>")
# Or `request.body = File.open("<your image file name>") {|io| io.read}` also works
|
Q: What is the correct syntax to pass a base64 instead of a url to Microsoft Azure Computer vision API using Ruby require 'net/http'
uri = URI('https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/ocr')
uri.query = URI.encode_www_form({
'language' => 'unk',
'detectOrientation ' => 'true'
})
request = Net::HTTP::Post.new(uri.request_uri)
request['Content-Type'] = 'application/octet-stream'
request['Ocp-Apim-Subscription-Key'] = 'MY_SUBSCRIPTION_KEY'
request.body = "raw_image_binary"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts response.body
I got this as a response.
{"code":"InvalidImageFormat","requestId":"3aee7147-2acc-4f64-b1c6-8453815eda38","message":"Input data is not a valid image."}
HELP!!
A: It sounds like you want to pass an image file to Azure Computer Vision API via application/octet-stream content type in Ruby, so you need to pass binary image data to response.body, not pass the base64 string of an image.
Please use the code below instead of the current one to make it works.
# Supported image formats: JPEG, PNG, GIF, BMP.
request.body = File.binread("<your image file name>")
# Or `request.body = File.open("<your image file name>") {|io| io.read}` also works
|
stackoverflow
|
{
"language": "en",
"length": 159,
"provenance": "stackexchange_0000F.jsonl.gz:863055",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536437"
}
|
b8b9d6b3fc9a1139d239b42d6003e7ffcb58db8d
|
Stackoverflow Stackexchange
Q: Get current slide data of slick Angularjs How can I get the data of the current slide of the slick using Angularjs? I've been solving this one for hours and I only got to read about how they got it using jQuery, which is not what I needed because I'm using angularjs.
This is my code:
<div ng-if="data && ready">
<slick infinite="true" slides-to-show="1" slides-to-scroll="1" current-index="" dots="true" arrows="true" init-onload="true" data="data">
<div ng-repeat="xx in data" >
<img src="@{{xx.banner}}" alt="grid-1"/>
<p>@{{xx.referno}}</p>
<p>@{{xx.name}}</p>
<p>@{{xx.address}}</p>
</div>
</slick>
</div>
A: If you simply want the index of the current slide you are almost there! As you have already done, use the current-index attribute. But make sure you initialize it beforehand by using ng-init.
Let's assume your current index is myIndex. I have edited your code as follows:
<div ng-if="data && ready" ng-init="myIndex = 0">
<slick current-index="myIndex" infinite="true" slides-to-show="1" slides-to-scroll="1" dots="true" arrows="true" init-onload="true" data="data">
<div ng-repeat="xx in data" >
<img src="@{{xx.banner}}" alt="grid-1"/>
<p>@{{xx.referno}}</p>
<p>@{{xx.name}}</p>
<p>@{{xx.address}}</p>
</div>
<p>Current index: {{ myIndex }}</p>
</slick>
</div>
Let me know how it goes :)
|
Q: Get current slide data of slick Angularjs How can I get the data of the current slide of the slick using Angularjs? I've been solving this one for hours and I only got to read about how they got it using jQuery, which is not what I needed because I'm using angularjs.
This is my code:
<div ng-if="data && ready">
<slick infinite="true" slides-to-show="1" slides-to-scroll="1" current-index="" dots="true" arrows="true" init-onload="true" data="data">
<div ng-repeat="xx in data" >
<img src="@{{xx.banner}}" alt="grid-1"/>
<p>@{{xx.referno}}</p>
<p>@{{xx.name}}</p>
<p>@{{xx.address}}</p>
</div>
</slick>
</div>
A: If you simply want the index of the current slide you are almost there! As you have already done, use the current-index attribute. But make sure you initialize it beforehand by using ng-init.
Let's assume your current index is myIndex. I have edited your code as follows:
<div ng-if="data && ready" ng-init="myIndex = 0">
<slick current-index="myIndex" infinite="true" slides-to-show="1" slides-to-scroll="1" dots="true" arrows="true" init-onload="true" data="data">
<div ng-repeat="xx in data" >
<img src="@{{xx.banner}}" alt="grid-1"/>
<p>@{{xx.referno}}</p>
<p>@{{xx.name}}</p>
<p>@{{xx.address}}</p>
</div>
<p>Current index: {{ myIndex }}</p>
</slick>
</div>
Let me know how it goes :)
A: You can get the current slide data using the beforeChange event of slick
// On before slide change
$('your_slick_element_id_or_class').on('beforeChange', function(event, slick, currentSlide, nextSlide){
console.log(currentSlide);
$scope.$apply(); // use this if the changes not applied or remove if you get the error "digest method is already running"
});
A: To anyone who has the same problem with mine. I had a hard time using vasyabigi angular slick, then i found this one
https://github.com/devmark/angular-slick-carousel
It solved my problem.
I hope it helps.
|
stackoverflow
|
{
"language": "en",
"length": 254,
"provenance": "stackexchange_0000F.jsonl.gz:863056",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536439"
}
|
4130516a55756e4488af3e0f6f59b7123ce47216
|
Stackoverflow Stackexchange
Q: How to create custom list filters based on month and year in Django admin I have a Django model which has a date field and I want to create a list filter which will show the following options,
Current
2017
2016
2015
upon clicking on the year link it will collapse into the months as,
2017
01
02
03
04 ...
I tried the default DateFieldListFilter but it has only the following options,
Any
Today
Past 7 days
This month
This year
I was trying to solve this using SimpleListFilter but could not succeed.
class MonthFilter(admin.SimpleListFilter):
title = 'Month'
parameter_name = 'month'
def lookups(self, request, model_admin):
months = [["current", "Current"]]
qs = model_admin.model.objects.exclude(ts_from=None).order_by('ts_from')
last= qs[0]
last_year = last.ts_from.year
current = timezone.now()
current_year = current.year
months.append([current_year, current_year])
months.append([last_year, last_year])
return months
def queryset(self, request, queryset):
if self.value():
return queryset.filter(ts_from__contains=self.value())
else:
return queryset
A: I guess you didn't filter yet with month in queryset
def queryset(self, request, queryset):
month = request.GET.get('month') or datetime.now().month
if self.value():
return queryset.filter(ts_from__contains=self.value(), created__month=month)
else:
return queryset
|
Q: How to create custom list filters based on month and year in Django admin I have a Django model which has a date field and I want to create a list filter which will show the following options,
Current
2017
2016
2015
upon clicking on the year link it will collapse into the months as,
2017
01
02
03
04 ...
I tried the default DateFieldListFilter but it has only the following options,
Any
Today
Past 7 days
This month
This year
I was trying to solve this using SimpleListFilter but could not succeed.
class MonthFilter(admin.SimpleListFilter):
title = 'Month'
parameter_name = 'month'
def lookups(self, request, model_admin):
months = [["current", "Current"]]
qs = model_admin.model.objects.exclude(ts_from=None).order_by('ts_from')
last= qs[0]
last_year = last.ts_from.year
current = timezone.now()
current_year = current.year
months.append([current_year, current_year])
months.append([last_year, last_year])
return months
def queryset(self, request, queryset):
if self.value():
return queryset.filter(ts_from__contains=self.value())
else:
return queryset
A: I guess you didn't filter yet with month in queryset
def queryset(self, request, queryset):
month = request.GET.get('month') or datetime.now().month
if self.value():
return queryset.filter(ts_from__contains=self.value(), created__month=month)
else:
return queryset
A: I made 2 filters one for year and the other one for month:
class YearFilter(SimpleListFilter):
title = _("Year")
parameter_name = _("year")
def lookups(self, request: HttpRequest, model_admin: ModelAdmin) -> list:
qs = model_admin.model.objects.exclude(ts_from=None).order_by(
"ts_from"
)
first_year = qs[0].ts_from.year
current_year = datetime.now().year
return [(y, y) for y in range(first_year, current_year + 1)]
def queryset(self, request: HttpRequest, queryset: QuerySet) -> QuerySet:
if self.value():
return queryset.filter(ts_from__year=self.value())
else:
return queryset
class MonthFilter(SimpleListFilter):
title = _("Month")
parameter_name = _("month")
def lookups(self, request: HttpRequest, model_admin: ModelAdmin) -> list:
return [(m, m) for m in range(1, 13)]
def queryset(self, request: HttpRequest, queryset: QuerySet) -> QuerySet:
if self.value():
return queryset.filter(ts_from__month=self.value())
else:
return queryset
it is not ideal as a solution but I guess better than installing a package to filter just per month
result (it is showing only 2020 as I do not have any data in 2019:
|
stackoverflow
|
{
"language": "en",
"length": 310,
"provenance": "stackexchange_0000F.jsonl.gz:863067",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536492"
}
|
0082d82ab8917ede3bfc8e02e104a47c7565ca2b
|
Stackoverflow Stackexchange
Q: Java out of memory errors Why does this following code
List<Object> list = new ArrayList<>();
while (true) {
for(int i = 0; i < 1000000; i++){
list.add(new Object());
}
}
produce an out of memory error
But this code doesn't
while(true) {
List<Object> list = new ArrayList<>();
for(int i = 0; i < 1000000; i++){
list.add(new Object());
}
}
I can see that it has something to do with the list being created either inside the while loop or outside of it obviously, but I am unsure on the reason why this happens.
A: In the first snippet, the list is created (and retained!) outside the loop, so you just keep endlessly adding elements to it until you consume all the available memory.
In the second snippet, each iteration of the while loop creates a new ArrayList object. Since you no longer hold a reference to that instance once the iteration ends, this list is eligible for garbage collection, so the old lists keep getting freed and you don't exhaust your memory.
|
Q: Java out of memory errors Why does this following code
List<Object> list = new ArrayList<>();
while (true) {
for(int i = 0; i < 1000000; i++){
list.add(new Object());
}
}
produce an out of memory error
But this code doesn't
while(true) {
List<Object> list = new ArrayList<>();
for(int i = 0; i < 1000000; i++){
list.add(new Object());
}
}
I can see that it has something to do with the list being created either inside the while loop or outside of it obviously, but I am unsure on the reason why this happens.
A: In the first snippet, the list is created (and retained!) outside the loop, so you just keep endlessly adding elements to it until you consume all the available memory.
In the second snippet, each iteration of the while loop creates a new ArrayList object. Since you no longer hold a reference to that instance once the iteration ends, this list is eligible for garbage collection, so the old lists keep getting freed and you don't exhaust your memory.
A: In your second case the list created (and where the elements are added) is going out of scope and eligible for GC. This will be GCed to make memory for the new ArrayList. Thus for every iteration, a new ArrayList is created and then it becomes eligible for GC (when the loop ends). Thus when memory is low, these objects will be GCed.
In the first case you are adding elements to the same ArrayList. Nothing is being GCed.
A: Because when you create the list inside the while loop your previous list gets dumped and you have a new empty list. Afterwards your memory gets freed by the java garbage collector and you add 1000000 elements to the list. Then a new list gets created and everything repeats itself.
A: In the first scenario, the list object is declared outside the while loop, which again is running indefinitely ( as while (true )), thus it keeps on adding till it runs out of memory, while in the second one because you have declared the list inside the while, the max size is restricted to the number of iterations of the for loop.
Each time the for loop exists, the list object is reset that is new one is created to which you start adding, thus you have an upper limit. The old object is garbage collected thus clearing the JVM.
A: This question is well answered by @Eran, @TheLostMind and all, so I am not putting same point, I just want to take the opportunity make a point on how SoftReference and WeakReference helps to "delay" the out of memory exception.
Run below code with JVM arguments as -Xms64m -Xmx64m so that you can see the results quickly.
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OOM {
public static void main(String[] args) {
System.out.println(new Date());
try {
scenario1(false, false); // in my box, OOM occurred with average of 2 seconds.
//scenario1(true, false); // in my box, OOM occurred average of 6 seconds.
//scenario1(false, true); // in my box, OOM occurred average of 8 seconds.
} catch (Exception e) {
} catch (Error err){
}
System.out.println(new Date());
}
private static void scenario1(boolean useSoftReference, boolean useWeakReference) {
List<Object> list = new ArrayList<>();
while (true) {
for(int i = 0; i < 1000000; i++){
if(useSoftReference){
list.add(new SoftReference<Object>(new Object()));
} else if(useWeakReference){
list.add(new WeakReference<Object>(new Object()));
} else{
list.add(new Object());
}
}
}
}
}
A: In the first example, you create a list, add items to it and then the loop finishes. In the second example, you create a list, add things to it, then create a new List, add a bunch of things to it and repeat infinitely. Since in the first example your variable is created outside the loop, there is only 1 list to fill.
A: The only difference between the two codes is the location of List list = new ArrayList<>(); line. For the first code, ArrayList declared outside of the while loop and it keeps adding infinite numbers of objects into the one ArrayList instance so the out of memory occurs. On the other hand, the second one declares ArrayList inside of while loop so it will instantiate a new ArrayList after the each loop cycle(many ArrayList instances). By the rule of Garbage Collector in Java, the previous cycle's instances will be removed since it is no longer pointed. As a result, the GC in Java prevents the out of memory in the second case.
A: In the first case, you have a single ArrayList instance and you keep adding to it new Object instances until you run out of memory.
In the second case, you create a new ArrayList in each iteration of the while loop and add 1000000 Object instances to it, which means the ArrayList created in the previous iteration and the 1000000 Object instances it contains can be garbage collected, since the program no longer has references to them.
Note that the second snippet can also cause out of memory error if the new Objects are created faster than the garbage collector can release the old ones, but that depends on the JVM implementation.
|
stackoverflow
|
{
"language": "en",
"length": 869,
"provenance": "stackexchange_0000F.jsonl.gz:863097",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536558"
}
|
88de3a8b771ec67257bb53455980ed0661c1c0b7
|
Stackoverflow Stackexchange
Q: override a linq attribute c# [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Gender", DbType="Int NOT NULL", UpdateCheck=UpdateCheck.Never)]
public int Gender
{
get
{
return this._Gender;
}
set
{
if ((this._Gender != value))
{
this.OnGenderChanging(value);
this.SendPropertyChanging();
this._Gender = value;
this.SendPropertyChanged("Gender");
this.OnGenderChanged();
}
}
}
there is an attribute for update check which I set it to never. But when ever I made a small change in dbml I must set this property of this field to never again. How can I override this attribute for ever in an partial class?
Update: as an example I can change dbml connection string like this, one time for ever:
partial class DataBaseDataContext : System.Data.Linq.DataContext
{
public DataBaseDataContext() :
base(ConfigurationManager.ConnectionStrings["MyConnection"].ToString())
{
OnCreated();
}
}
A: Open the dbml file in the designer and set Update Check for the property to the desired value. Don't modify the generated files directly, it will be overwritten.
|
Q: override a linq attribute c# [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Gender", DbType="Int NOT NULL", UpdateCheck=UpdateCheck.Never)]
public int Gender
{
get
{
return this._Gender;
}
set
{
if ((this._Gender != value))
{
this.OnGenderChanging(value);
this.SendPropertyChanging();
this._Gender = value;
this.SendPropertyChanged("Gender");
this.OnGenderChanged();
}
}
}
there is an attribute for update check which I set it to never. But when ever I made a small change in dbml I must set this property of this field to never again. How can I override this attribute for ever in an partial class?
Update: as an example I can change dbml connection string like this, one time for ever:
partial class DataBaseDataContext : System.Data.Linq.DataContext
{
public DataBaseDataContext() :
base(ConfigurationManager.ConnectionStrings["MyConnection"].ToString())
{
OnCreated();
}
}
A: Open the dbml file in the designer and set Update Check for the property to the desired value. Don't modify the generated files directly, it will be overwritten.
|
stackoverflow
|
{
"language": "en",
"length": 142,
"provenance": "stackexchange_0000F.jsonl.gz:863133",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536675"
}
|
7781fa459c4930e0375923ab5f2fa417e0aaf759
|
Stackoverflow Stackexchange
Q: Concourse CI: Use Metadata (Build number, URL etc) in on_success/on_failure How is it possible to use Metadata in on_success/on_failure? For example, to send emails via https://github.com/pivotal-cf/email-resource?
I haven't found a way, as I can't change content of files where email resources reside (subject/body), as the metadata is not available to tasks.
And yep, that might be a duplicate for Concourse CI and Build number
But still my question IMHO is a valid use case for notifications.
A: The metadata you are referring to, I assume, is the environment variables provided to resources, not tasks.
This can be used with the slack resource to provide information about what build failed.
For example:
on_failure:
put: slack-alert
params:
text: |
The `science` pipeline has failed. Please resolve any issues and ensure the pipeline lock was released. Check it out at:
$ATC_EXTERNAL_URL/teams/$BUILD_TEAM_NAME/pipelines/$BUILD_PIPELINE_NAME/jobs/$BUILD_JOB_NAME/builds/$BUILD_NAME
The email resource, you're referencing has an open PR to support these environment variables. I'd discuss your need for that feature there.
|
Q: Concourse CI: Use Metadata (Build number, URL etc) in on_success/on_failure How is it possible to use Metadata in on_success/on_failure? For example, to send emails via https://github.com/pivotal-cf/email-resource?
I haven't found a way, as I can't change content of files where email resources reside (subject/body), as the metadata is not available to tasks.
And yep, that might be a duplicate for Concourse CI and Build number
But still my question IMHO is a valid use case for notifications.
A: The metadata you are referring to, I assume, is the environment variables provided to resources, not tasks.
This can be used with the slack resource to provide information about what build failed.
For example:
on_failure:
put: slack-alert
params:
text: |
The `science` pipeline has failed. Please resolve any issues and ensure the pipeline lock was released. Check it out at:
$ATC_EXTERNAL_URL/teams/$BUILD_TEAM_NAME/pipelines/$BUILD_PIPELINE_NAME/jobs/$BUILD_JOB_NAME/builds/$BUILD_NAME
The email resource, you're referencing has an open PR to support these environment variables. I'd discuss your need for that feature there.
|
stackoverflow
|
{
"language": "en",
"length": 161,
"provenance": "stackexchange_0000F.jsonl.gz:863149",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536716"
}
|
3640b2a7c33791cd721da5e996db9021971ca6ec
|
Stackoverflow Stackexchange
Q: Rendering and navigating multiple charts in highcharts I'm working on an exercise to plot multiple charts in one page. I would like to use the navigator to pan through these data.
Is there a way I could navigate 10+ multiple charts simultaneously more smoothly?
The more charts I have the more sluggish it becomes.
Also if the data set becomes too large, when moving the navigator the data seems to jump out the plotting area rather than slowly translating outside the plotting area.
Please see the jsFiddle
function afterSetExtremes(event) {
var globalMax = event.max;
var globalMin = event.min;
for (var i = 0; i < charts.length; i++) {
charts[i].xAxis[0].setExtremes(globalMin, globalMax, true, false);
}
3 Charts running seems to be able panning smoothly. (Points move out of the viewing window point by point)
12 Charts seems to struggle panning smoothly. The effect I'm seeing is that chucks of data gets move out the viewing window instead translating by points.
** Click hyperlinks to see the videos **
Any suggestions to this will be grateful. Thanks
|
Q: Rendering and navigating multiple charts in highcharts I'm working on an exercise to plot multiple charts in one page. I would like to use the navigator to pan through these data.
Is there a way I could navigate 10+ multiple charts simultaneously more smoothly?
The more charts I have the more sluggish it becomes.
Also if the data set becomes too large, when moving the navigator the data seems to jump out the plotting area rather than slowly translating outside the plotting area.
Please see the jsFiddle
function afterSetExtremes(event) {
var globalMax = event.max;
var globalMin = event.min;
for (var i = 0; i < charts.length; i++) {
charts[i].xAxis[0].setExtremes(globalMin, globalMax, true, false);
}
3 Charts running seems to be able panning smoothly. (Points move out of the viewing window point by point)
12 Charts seems to struggle panning smoothly. The effect I'm seeing is that chucks of data gets move out the viewing window instead translating by points.
** Click hyperlinks to see the videos **
Any suggestions to this will be grateful. Thanks
|
stackoverflow
|
{
"language": "en",
"length": 175,
"provenance": "stackexchange_0000F.jsonl.gz:863153",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536734"
}
|
a6acef1471be4dd88fb92ffa98dfd75c583d1f71
|
Stackoverflow Stackexchange
Q: Sed | awk to remove line after matching next line if Name comes back to back then delete first name
Name john
Age 30
Name Alice
Name Travis
Age 12
Name Monty
Name Hannah
desired output
Name john
Age 30
Name Travis
Age 12
Name Hannah
Commands I tried:
sed '/^Name/ {N; /\n$/d}' file.txt
sed '/Name/{$!N;/\n\nName/!P;D}' file.txt
A: You can use this awk command:
awk 'NF && /^Name/ {n=NR; p=$0; next}
NF && n {if ($0 !~ /^Name/) print p; n=0} END{if (n) print p} 1' file
Name john
Age 30
Name Travis
Age 12
Name Hannah
|
Q: Sed | awk to remove line after matching next line if Name comes back to back then delete first name
Name john
Age 30
Name Alice
Name Travis
Age 12
Name Monty
Name Hannah
desired output
Name john
Age 30
Name Travis
Age 12
Name Hannah
Commands I tried:
sed '/^Name/ {N; /\n$/d}' file.txt
sed '/Name/{$!N;/\n\nName/!P;D}' file.txt
A: You can use this awk command:
awk 'NF && /^Name/ {n=NR; p=$0; next}
NF && n {if ($0 !~ /^Name/) print p; n=0} END{if (n) print p} 1' file
Name john
Age 30
Name Travis
Age 12
Name Hannah
A: Here's a method by using awk,
awk_script:
BEGIN{a=0}
/Name/{ if(a==1){print $0;name=""}else{name=$0"\n"} a=1 }
/Age/{printf "%s%s\n\n",name,$0; a=0;}
Then execute:
$ awk -f awk_sc file.txt
Name john
Age 30
Name Travis
Age 12
Name Hannah
Brief explaination:
The variable a is the flag used to record if Name is shown up previously. Set a=0 after the line has been printed
A: May not be exactly what you are looking for, but why not try to keep only what you are interested in.
sed -n '/^Name/ {N; /Age.*/p}' file.txt
Will give you following result
Name john
Age 30
Name Travis
Age 12
|
stackoverflow
|
{
"language": "en",
"length": 198,
"provenance": "stackexchange_0000F.jsonl.gz:863164",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536782"
}
|
c5f802386f3edc4e49d0cec0dba792fa4b74411f
|
Stackoverflow Stackexchange
Q: Mutliple SQL statements in a single HTTP Request - metamug In the following resource file, I'm trying to perform 2 insert operations for the same request.(form submit)
But getting 500 error from the API.
<?xml version="1.0" encoding="UTF-8" ?>
<Resource xmlns="http://xml.metamug.net/resource/1.0" v="1.0">
<Request method="POST">
<Desc> CRICKET INFO </Desc>
<Update>
insert into CRICKET (NAME,DOB,BATTING_STYLE,BOWLING_STYLE,TEAM)
values($xname,$birthdate,$batstyle,$bowlstyle,$st);
insert into DETAILS (FORMAT,RUNS,WICKETS,AVERAGE)
values($sf,$rns,$wkts,$avg);
</Update>
</Request>
</Resource>
A: You'll have to use <Sql> tag twice to achieve this, you can't write more than one query inside a single <Sql>.
So your resource file should be like this
<?xml version="1.0" encoding="UTF-8" ?>
<Resource xmlns="http://xml.metamug.net/resource/1.0" v="1.0">
<Request method="POST">
<Desc> CRICKET INFO </Desc>
<Sql id="first">
insert into CRICKET (NAME,DOB,BATTING_STYLE,BOWLING_STYLE,TEAM)
values($xname,$birthdate,$batstyle,$bowlstyle,$st);
</Sql>
<Sql id="second">
insert into DETAILS (FORMAT,RUNS,WICKETS,AVERAGE)
values($sf,$rns,$wkts,$avg);
</Sql>
</Request>
</Resource>
|
Q: Mutliple SQL statements in a single HTTP Request - metamug In the following resource file, I'm trying to perform 2 insert operations for the same request.(form submit)
But getting 500 error from the API.
<?xml version="1.0" encoding="UTF-8" ?>
<Resource xmlns="http://xml.metamug.net/resource/1.0" v="1.0">
<Request method="POST">
<Desc> CRICKET INFO </Desc>
<Update>
insert into CRICKET (NAME,DOB,BATTING_STYLE,BOWLING_STYLE,TEAM)
values($xname,$birthdate,$batstyle,$bowlstyle,$st);
insert into DETAILS (FORMAT,RUNS,WICKETS,AVERAGE)
values($sf,$rns,$wkts,$avg);
</Update>
</Request>
</Resource>
A: You'll have to use <Sql> tag twice to achieve this, you can't write more than one query inside a single <Sql>.
So your resource file should be like this
<?xml version="1.0" encoding="UTF-8" ?>
<Resource xmlns="http://xml.metamug.net/resource/1.0" v="1.0">
<Request method="POST">
<Desc> CRICKET INFO </Desc>
<Sql id="first">
insert into CRICKET (NAME,DOB,BATTING_STYLE,BOWLING_STYLE,TEAM)
values($xname,$birthdate,$batstyle,$bowlstyle,$st);
</Sql>
<Sql id="second">
insert into DETAILS (FORMAT,RUNS,WICKETS,AVERAGE)
values($sf,$rns,$wkts,$avg);
</Sql>
</Request>
</Resource>
|
stackoverflow
|
{
"language": "en",
"length": 123,
"provenance": "stackexchange_0000F.jsonl.gz:863165",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536786"
}
|
1a2c3e4eed767e2dbe258ac5d1b67e3723ab257d
|
Stackoverflow Stackexchange
Q: MKMapView memory leak in iOS 10 I have integrated MKMapView in my project but when i pop that controller it not able to free the Memory .I am facing this issue in iOS 10 only I have tested in iOS 9 it's working fine.
I tried to free the memory with below code but it's not working.
let overlays = self.mapView.overlays
self.mapView.removeOverlays(overlays)
self.mapView.mapType = MKMapType.standard
self.mapView.showsUserLocation = false
self.mapView.removeAnnotations(self.containerView.mapView.annotations)
self.mapView.delegate = nil
self.mapView.removeFromSuperview()
self.mapView = nil
|
Q: MKMapView memory leak in iOS 10 I have integrated MKMapView in my project but when i pop that controller it not able to free the Memory .I am facing this issue in iOS 10 only I have tested in iOS 9 it's working fine.
I tried to free the memory with below code but it's not working.
let overlays = self.mapView.overlays
self.mapView.removeOverlays(overlays)
self.mapView.mapType = MKMapType.standard
self.mapView.showsUserLocation = false
self.mapView.removeAnnotations(self.containerView.mapView.annotations)
self.mapView.delegate = nil
self.mapView.removeFromSuperview()
self.mapView = nil
|
stackoverflow
|
{
"language": "en",
"length": 77,
"provenance": "stackexchange_0000F.jsonl.gz:863193",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536893"
}
|
ade91affd9cd3c6f92f47b1b2971f7b942d36997
|
Stackoverflow Stackexchange
Q: pg_query like with timestamp I get 0 results if I query the timestamp column for entries that contain 2017 (or any other year).
The data in w_presse_erscheinung is a "timestamp without timezone"
and looks like this for example: 2017-06-01 00:00:00
I assume there is something wrong with the LIKE part of the query ...
My query looks like this:
$result = pg_query("
SELECT
name,
w_presse_link,
w_presse_erscheinung,
w_presse_quelle,
description
FROM adempiere.w_presse
WHERE isactive ='Y'
AND description='PS' AND w_presse_erscheinung LIKE '%2017%'
ORDER BY w_presse_erscheinung
DESC
")
A: Instead of relying on string conversions, you could explicitly extract the year from the timestamp:
EXTRACT(YEAR FROM w_presse_erscheinung) = 2017
|
Q: pg_query like with timestamp I get 0 results if I query the timestamp column for entries that contain 2017 (or any other year).
The data in w_presse_erscheinung is a "timestamp without timezone"
and looks like this for example: 2017-06-01 00:00:00
I assume there is something wrong with the LIKE part of the query ...
My query looks like this:
$result = pg_query("
SELECT
name,
w_presse_link,
w_presse_erscheinung,
w_presse_quelle,
description
FROM adempiere.w_presse
WHERE isactive ='Y'
AND description='PS' AND w_presse_erscheinung LIKE '%2017%'
ORDER BY w_presse_erscheinung
DESC
")
A: Instead of relying on string conversions, you could explicitly extract the year from the timestamp:
EXTRACT(YEAR FROM w_presse_erscheinung) = 2017
A: You cannot use like with a timestamp field like that. Either typecast the timestamp field to varchar then use like or use extract function to match the year from the field.
|
stackoverflow
|
{
"language": "en",
"length": 138,
"provenance": "stackexchange_0000F.jsonl.gz:863201",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44536915"
}
|
10022e3eb6a6d81464d8b9e97ee62c68481ed1b8
|
Stackoverflow Stackexchange
Q: how do I convert "YYYY/MM" type date into "MMM-YYYY" in pandas in python What I want to do:
# I have col names in pandas DF such as :
data 2017/01 2017/02 2017/03 ....
ABC 12 22 08 ....
EFG 07 16 12 ....
I want to convert col names:
data Jan-2017 Feb-2017 Mar-2017 ....
ABC 12 22 08 ....
EFG 07 16 12 ....
I have tried the following:
pd.to_datetime(pd.Series(['2017/01']), format="%Y/%m")
Which, resulted in:
0 2017-01-01
dtype: datetime64[ns]
But I am not sure how to get the result I want.
Any idea?
A: You are close, need DatetimeIndex.strftime:
df.columns = pd.to_datetime(df.columns, format="%Y/%m").strftime('%b-%Y')
print (df)
Jan-2017 Feb-2017 Mar-2017
data
ABC 12 22 8
EFG 7 16 12
EDIT:
Thank you piRSquared for idea:
df.columns = pd.PeriodIndex(df.columns, freq='M').strftime('%b-%Y')
print (df)
Jan-2017 Feb-2017 Mar-2017
data
ABC 12 22 8
EFG 7 16 12
|
Q: how do I convert "YYYY/MM" type date into "MMM-YYYY" in pandas in python What I want to do:
# I have col names in pandas DF such as :
data 2017/01 2017/02 2017/03 ....
ABC 12 22 08 ....
EFG 07 16 12 ....
I want to convert col names:
data Jan-2017 Feb-2017 Mar-2017 ....
ABC 12 22 08 ....
EFG 07 16 12 ....
I have tried the following:
pd.to_datetime(pd.Series(['2017/01']), format="%Y/%m")
Which, resulted in:
0 2017-01-01
dtype: datetime64[ns]
But I am not sure how to get the result I want.
Any idea?
A: You are close, need DatetimeIndex.strftime:
df.columns = pd.to_datetime(df.columns, format="%Y/%m").strftime('%b-%Y')
print (df)
Jan-2017 Feb-2017 Mar-2017
data
ABC 12 22 8
EFG 7 16 12
EDIT:
Thank you piRSquared for idea:
df.columns = pd.PeriodIndex(df.columns, freq='M').strftime('%b-%Y')
print (df)
Jan-2017 Feb-2017 Mar-2017
data
ABC 12 22 8
EFG 7 16 12
A: Use the arrow library. Arrow is supposed to be datetime for humans.
It's clean, simple and intuitive.
import arrow
arrow.get('2017/03').format('MMM-YYYY')
returns Mar-2017
|
stackoverflow
|
{
"language": "en",
"length": 165,
"provenance": "stackexchange_0000F.jsonl.gz:863230",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537001"
}
|
fd7a882fad4fde42c42af74e0f4ddcd6e593a660
|
Stackoverflow Stackexchange
Q: Unable to use ReactiveUI I've developed a UWP and would like to use ReactiveUI but it introduces incompatibility when I install the 7.4.0 Nuget package. I target Universal Windows Anniversary edition and get the following when I build:
Error CS0433 The type 'Unit' exists in both 'System.Reactive.Core,
Version=2.2.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and
'System.Reactive.Core, Version=3.0.4000.0, Culture=neutral,
PublicKeyToken=94bc3704cddfc263'
The same messages appear for a variety of types *Disposable. The 2.2.5.0 version is in .nuget\packages\Rx-Core\2.2.5\lib\windows8\System.Reactive.Core.dll and the 3.0.4000.0 version is in .nuget\packages\System.Reactive.Core\3.1.1\lib\uap10.0\System.Reactive.Core.dll.
When I uninstalled ReactiveUI most of the dependencies had a 2.2.5 suffix. I also have ReactiveProperty 3.6.0 installed that seems to be the source of the incompatibility. I uninstalled ReactiveProperty and kept ReactiveUI but got errors on references to ReactiveProperty.
Is there no way or combination of versions by which I can use both ReactiveUI and ReactiveProperty? Specifically, with just ReactiveProperty I am unable to create an observable with WhenAny as like this:
var canClickMeObservable = this.WhenAny(vm => vm.SomeText,
s => !string.IsNullOrWhiteSpace(s.Value));
ClickMe = new ReactiveCommand(canClickMeObservable);
...as described here: http://jen20.com/blog/2013/05/30/reactive-ui-part-3-commands/
Hopefully, there is a way for me to use ReactiveUI and there is some obvious error and bonehead mistake...Anyone? Many thanks for your thoughts..
|
Q: Unable to use ReactiveUI I've developed a UWP and would like to use ReactiveUI but it introduces incompatibility when I install the 7.4.0 Nuget package. I target Universal Windows Anniversary edition and get the following when I build:
Error CS0433 The type 'Unit' exists in both 'System.Reactive.Core,
Version=2.2.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and
'System.Reactive.Core, Version=3.0.4000.0, Culture=neutral,
PublicKeyToken=94bc3704cddfc263'
The same messages appear for a variety of types *Disposable. The 2.2.5.0 version is in .nuget\packages\Rx-Core\2.2.5\lib\windows8\System.Reactive.Core.dll and the 3.0.4000.0 version is in .nuget\packages\System.Reactive.Core\3.1.1\lib\uap10.0\System.Reactive.Core.dll.
When I uninstalled ReactiveUI most of the dependencies had a 2.2.5 suffix. I also have ReactiveProperty 3.6.0 installed that seems to be the source of the incompatibility. I uninstalled ReactiveProperty and kept ReactiveUI but got errors on references to ReactiveProperty.
Is there no way or combination of versions by which I can use both ReactiveUI and ReactiveProperty? Specifically, with just ReactiveProperty I am unable to create an observable with WhenAny as like this:
var canClickMeObservable = this.WhenAny(vm => vm.SomeText,
s => !string.IsNullOrWhiteSpace(s.Value));
ClickMe = new ReactiveCommand(canClickMeObservable);
...as described here: http://jen20.com/blog/2013/05/30/reactive-ui-part-3-commands/
Hopefully, there is a way for me to use ReactiveUI and there is some obvious error and bonehead mistake...Anyone? Many thanks for your thoughts..
|
stackoverflow
|
{
"language": "en",
"length": 193,
"provenance": "stackexchange_0000F.jsonl.gz:863234",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537012"
}
|
82269252935c95d8125ac1654dba8830491382f9
|
Stackoverflow Stackexchange
Q: I didn't get '+' button beside build option in iTunes connect? My developer account is new account, I am uploading first app, but I am not getting + sign button beside build option in iTunes connect. like this image...
This is from https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html
In my iTunes page ...I am getting like this....
Image from Activity.
A: If you are uploading App, then in Activity Section it displays, and its status is processed whenever the status is active then display + (Plus) button. You can add the build.
|
Q: I didn't get '+' button beside build option in iTunes connect? My developer account is new account, I am uploading first app, but I am not getting + sign button beside build option in iTunes connect. like this image...
This is from https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/SubmittingTheApp.html
In my iTunes page ...I am getting like this....
Image from Activity.
A: If you are uploading App, then in Activity Section it displays, and its status is processed whenever the status is active then display + (Plus) button. You can add the build.
A: I am assuming your app build is listed on iOS Builds screen with (Processing) status?
If not, then it will mean it did not deploy correctly from Xcode.
Note: you have to wait until Processing is finished before submitting your App to TestFlight.
Expected Activity tab screen view:
A: Updated:
In my case. Apple sent an e-mail when they completed the automatic test stage. It may take time.
|
stackoverflow
|
{
"language": "en",
"length": 157,
"provenance": "stackexchange_0000F.jsonl.gz:863242",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537041"
}
|
04ddc1b923632440cac50fdb68103d3977c0d57e
|
Stackoverflow Stackexchange
Q: How to make a dictionary of dictionaries with multiple lists There is one index list which will be the key of the parent dictionary:
index = [1,2,3]
and then multiple lists of which will be the child dicts:
triangles = [4,5,6]
circles = [7,8,9]
squares = [10,11,12]
the sequential elements being the data, resulting in:
{1:{'triangles':4, 'circles':7, 'squares': 10},
2: {'triangles': 5, 'circles': 8, 'squares': 11},
3: {'triangles': 6, 'circles': 9, 'squares': 12}}
how can I do this ?
Do you think easier to do in pandas ?
A: You can zip the lists, create the subdicts and then zip the subdicts with the indices. No restrictions on the indices; they can be non-sequencial/non-numerical:
dct = dict(zip(index, ({'triangles': i, 'circles': j, 'squares': k}
for i,j,k in zip(triangles, circles, squares))))
print(dct)
{1: {'circles': 7, 'squares': 10, 'triangles': 4},
2: {'circles': 8, 'squares': 11, 'triangles': 5},
3: {'circles': 9, 'squares': 12, 'triangles': 6}}
On another note, if you only need sequential counts, the index list can be replaced with enumerate:
dct = dict(enumerate(({'triangles': i, 'circles': j, 'squares': k}
for i,j,k in zip(triangles, circles, squares)), 1))
|
Q: How to make a dictionary of dictionaries with multiple lists There is one index list which will be the key of the parent dictionary:
index = [1,2,3]
and then multiple lists of which will be the child dicts:
triangles = [4,5,6]
circles = [7,8,9]
squares = [10,11,12]
the sequential elements being the data, resulting in:
{1:{'triangles':4, 'circles':7, 'squares': 10},
2: {'triangles': 5, 'circles': 8, 'squares': 11},
3: {'triangles': 6, 'circles': 9, 'squares': 12}}
how can I do this ?
Do you think easier to do in pandas ?
A: You can zip the lists, create the subdicts and then zip the subdicts with the indices. No restrictions on the indices; they can be non-sequencial/non-numerical:
dct = dict(zip(index, ({'triangles': i, 'circles': j, 'squares': k}
for i,j,k in zip(triangles, circles, squares))))
print(dct)
{1: {'circles': 7, 'squares': 10, 'triangles': 4},
2: {'circles': 8, 'squares': 11, 'triangles': 5},
3: {'circles': 9, 'squares': 12, 'triangles': 6}}
On another note, if you only need sequential counts, the index list can be replaced with enumerate:
dct = dict(enumerate(({'triangles': i, 'circles': j, 'squares': k}
for i,j,k in zip(triangles, circles, squares)), 1))
A: Dict comprehnesions to the rescue!
Note, BTW, that the indices stored in index seem to be one-based although python lists are zero-based:
result = {i : {'triangles' : triangles[i-1], 'circles' : circles[i-1], 'squares' : squares[i-1]} for i in index}
A: The simplest method is with dict comprehension :
>>> d = {i:{'triangles':triangles[i-1],'circles':circles[i-1],'squares':squares[i-1]} for i in index}
{1: {'circles': 7, 'squares': 10, 'triangles': 4},
2: {'circles': 8, 'squares': 11, 'triangles': 5},
3: {'circles': 9, 'squares': 12, 'triangles': 6}}
A: Actually this is very easy and can be achieved with a simple for-loop:
index = [1,2,3]
triangles = [4,5,6]
circles = [7,8,9]
squares = [10,11,12]
dictionary = {}
for i in range(0, len(index)):
dictionary[index[i]] = {'triangles':triangles[i], 'circles':circles[i], 'squares':squares[i]}
print(dictionary)
Output:
{1: {'triangles': 4, 'circles': 7, 'squares': 10}, 2: {'triangles': 5, 'circles': 8, 'squares': 11}, 3: {'triangles': 6, 'circles': 9, 'squares': 12}}
A: You could do something like this,
results = {}
for index, item in enumerate(zip(triangles,circles,squares)):
results.update({index+1:{'triangles':item[0], 'circles':item[1], 'squares':item[2]}})
Out[6]:
{1: {'circles': 7, 'squares': 10, 'triangles': 4},
2: {'circles': 8, 'squares': 11, 'triangles': 5},
3: {'circles': 9, 'squares': 12, 'triangles': 6}}
A: If you got a lot of variables and you don't want to hardcode your dictionary comprehension, here is a way.
NOTE: you need to have all variables declared.
Also you need to declare list of variable names.
list_of_var_names = ['triangles', 'circles', 'squares']
dict(zip(index, [dict(zip(list_of_var_names, i))
for i in (globals().get(i) for i in list_of_var_names)]))
And to divide step by step:
In [1]: index = [1,2,3]
...:
...: triangles = [4,5,6]
...: circles = [7,8,9]
...: squares = [10,11,12]
...:
In [2]: list_of_var_names = ['triangles', 'circles', 'squares']
In [3]: [globals().get(i) for i in list_of_var_names] # getting list of variable values in list_of_var_names order
Out[3]: [[4, 5, 6], [7, 8, 9], [10, 11, 12]]
In [4]: [dict(zip(list_of_var_names, i)) for i in (globals().get(i) for i in lis
...: t_of_var_names)]
Out[4]:
[{'circles': 5, 'squares': 6, 'triangles': 4},
{'circles': 8, 'squares': 9, 'triangles': 7},
{'circles': 11, 'squares': 12, 'triangles': 10}]
In [5]: dict(zip(index, [dict(zip(list_of_var_names, i))
...: for i in (globals().get(i) for i in list_of_var_names)]
...: ))
...:
Out[5]:
{1: {'circles': 5, 'squares': 6, 'triangles': 4},
2: {'circles': 8, 'squares': 9, 'triangles': 7},
3: {'circles': 11, 'squares': 12, 'triangles': 10}}
I want to mention one more time that this solution if good if you get a ton of variables and you don't want explicitly declare dict comprehension. In other cases it would be more suitable and more readable to use other solutions that are presented here.
A: Another variety using double zip() and dict comprehension:
triangles = [4,5,6]
circles = [7,8,9]
squares = [10,11,12]
index = [1,2,3]
b = {k:{'triangles': x, 'circles': y, 'squares': z} for k, (x,y,z) in zip(
index, zip(triangles, circles, squares))}
print(b)
Output:
{1: {'circles': 7, 'squares': 10, 'triangles': 4},
2: {'circles': 8, 'squares': 11, 'triangles': 5},
3: {'circles': 9, 'squares': 12, 'triangles': 6}}
|
stackoverflow
|
{
"language": "en",
"length": 655,
"provenance": "stackexchange_0000F.jsonl.gz:863243",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537042"
}
|
081529becf0da2a002f722ff0a3f0012d9c19813
|
Stackoverflow Stackexchange
Q: Image Orientation (python+openCV) Using Python and OpenCV, I try to read an image which size is (3264*2448), but the resulting size is always (2448*3264). That means the direction of the image is changed by 90 degrees. The code is following:
img1 = cv2.imread("C:\\Users\\test.jpg", 0)
cv2.namedWindow("test", 0)
cv2.imshow("test", img1)
the orignal image is this:
but I get this image:
A: OpenCV only applys EXIF 'Orientation' tags with an OpenCV version >= 3.1.
If you are stuck with a lower version and PIL is available:
import PIL, cv2, numpy
path = 'test.jpg'
pix = PIL.Image.open(path)
# get correction based on 'Orientation' from Exif (==Tag 274)
try:
deg = {3:180,6:270,8:90}.get(pix._getexif().get(274,0),0)
except:
deg = 0
if deg != 0:
pix=pix.rotate(deg, expand=False)
# convert PIL -> opencv
im0 = numpy.array(pix)
if len(im0.shape)==3 and im0.shape[2] >= 3:
# fix bgr rgb conventions
# note: this removes a potential alpha-channel (e.g. if path point to a png)
im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2RGB)
|
Q: Image Orientation (python+openCV) Using Python and OpenCV, I try to read an image which size is (3264*2448), but the resulting size is always (2448*3264). That means the direction of the image is changed by 90 degrees. The code is following:
img1 = cv2.imread("C:\\Users\\test.jpg", 0)
cv2.namedWindow("test", 0)
cv2.imshow("test", img1)
the orignal image is this:
but I get this image:
A: OpenCV only applys EXIF 'Orientation' tags with an OpenCV version >= 3.1.
If you are stuck with a lower version and PIL is available:
import PIL, cv2, numpy
path = 'test.jpg'
pix = PIL.Image.open(path)
# get correction based on 'Orientation' from Exif (==Tag 274)
try:
deg = {3:180,6:270,8:90}.get(pix._getexif().get(274,0),0)
except:
deg = 0
if deg != 0:
pix=pix.rotate(deg, expand=False)
# convert PIL -> opencv
im0 = numpy.array(pix)
if len(im0.shape)==3 and im0.shape[2] >= 3:
# fix bgr rgb conventions
# note: this removes a potential alpha-channel (e.g. if path point to a png)
im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2RGB)
A: I faced a similar issue in one program. In my case, the problem was due to the camera orientation data stored in the image.
The problem was resolved after I used CV_LOAD_IMAGE_COLOR instead of CV_LOAD_IMAGE_UNCHANGED in OpenCV Java.
|
stackoverflow
|
{
"language": "en",
"length": 194,
"provenance": "stackexchange_0000F.jsonl.gz:863250",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537075"
}
|
352596edca0499506ab2fea5fa064d9670929377
|
Stackoverflow Stackexchange
Q: Grouping by with Where conditions in Pandas Have a dataframe like this:
I created column 'dif_pause' based on subtracting 'pause_end' and 'pause_start' column values and doing the mean value aggregation using groupby () function just like this:
pauses['dif_pause'] = pauses['pause_end'] - pauses['pause_start']
pauses['dif_pause'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)
pauses_df=pauses.groupby(["subscription_id"])["dif_pause"].mean().reset_index(name="avg_pause")
I'd like to include in the groupby section the checking whether pause_end>pause_start (some equialent of WHERE clause in SQL). How can one do that?
Thanks.
A: It seems you need query or boolean indexing first for filtering:
pauses.query("pause_end > pause_start")
.groupby(["subscription_id"])["dif_pause"].mean().reset_index(name="avg_pause")
pauses[pauses["pause_end"] > pauses["pause_start"]]
.groupby(["subscription_id"])["dif_pause"].mean().reset_index(name="avg_pause")
|
Q: Grouping by with Where conditions in Pandas Have a dataframe like this:
I created column 'dif_pause' based on subtracting 'pause_end' and 'pause_start' column values and doing the mean value aggregation using groupby () function just like this:
pauses['dif_pause'] = pauses['pause_end'] - pauses['pause_start']
pauses['dif_pause'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)
pauses_df=pauses.groupby(["subscription_id"])["dif_pause"].mean().reset_index(name="avg_pause")
I'd like to include in the groupby section the checking whether pause_end>pause_start (some equialent of WHERE clause in SQL). How can one do that?
Thanks.
A: It seems you need query or boolean indexing first for filtering:
pauses.query("pause_end > pause_start")
.groupby(["subscription_id"])["dif_pause"].mean().reset_index(name="avg_pause")
pauses[pauses["pause_end"] > pauses["pause_start"]]
.groupby(["subscription_id"])["dif_pause"].mean().reset_index(name="avg_pause")
|
stackoverflow
|
{
"language": "en",
"length": 96,
"provenance": "stackexchange_0000F.jsonl.gz:863294",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537249"
}
|
2ab488c7508e5a7f26ff212a109afb4a68ca6fb8
|
Stackoverflow Stackexchange
Q: Electron : How to print only a part of html (div) in electron silently? What i am trying to achieve is that the web page which is remotely hosted and is being loaded in my electron app would want the Electron app to print only a particular div element . I know if i use webContents.print({silent:true}) the entire page would get printed silently . But i want the same thing to happen on only a particular div .
Thanks in advance.
A: One way of doing it is to send the div a new hidden window and then print from there.
main.js
app.on('ready', function(){
mainWindow = new BrowserWindow({ width: 1080, height:720})
workerWindow = new BrowserWindow();
workerWindow.loadURL("file://" + __dirname + "/printerWindow.html");
workerWindow.hide();
});
// retransmit it to workerWindow
ipcMain.on("printPDF", function(event, content){
workerWindow.webContents.send("printPDF", content);
});
// when worker window is ready
ipcMain.on("readyToPrintPDF", (event) => {
workerWindow.webContents.print({silent: true});
})
controller.js
// target the object you want to print and send it to the new window
ipcRenderer.send("printPDF", div_to_be_targeted);
|
Q: Electron : How to print only a part of html (div) in electron silently? What i am trying to achieve is that the web page which is remotely hosted and is being loaded in my electron app would want the Electron app to print only a particular div element . I know if i use webContents.print({silent:true}) the entire page would get printed silently . But i want the same thing to happen on only a particular div .
Thanks in advance.
A: One way of doing it is to send the div a new hidden window and then print from there.
main.js
app.on('ready', function(){
mainWindow = new BrowserWindow({ width: 1080, height:720})
workerWindow = new BrowserWindow();
workerWindow.loadURL("file://" + __dirname + "/printerWindow.html");
workerWindow.hide();
});
// retransmit it to workerWindow
ipcMain.on("printPDF", function(event, content){
workerWindow.webContents.send("printPDF", content);
});
// when worker window is ready
ipcMain.on("readyToPrintPDF", (event) => {
workerWindow.webContents.print({silent: true});
})
controller.js
// target the object you want to print and send it to the new window
ipcRenderer.send("printPDF", div_to_be_targeted);
|
stackoverflow
|
{
"language": "en",
"length": 165,
"provenance": "stackexchange_0000F.jsonl.gz:863301",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537272"
}
|
021e19054f199466ba0e129866dc9ff2a2a2212c
|
Stackoverflow Stackexchange
Q: How to subtract date in angularjs I try make list from curent date until last 31 days. I try use ng-repeat to make list today until 31 day. I can make list but not date. I try code like this
HTML
<ion-list>
<ion-item class="animate-repeat" ng-repeat="i in rep">
{{trip}}
{{besok}}
</ion-item>
</ion-list>
JS
$scope.rep = [];
for (var i=0; i < 31; i++) {
$scope.trip = new Date();
$scope.besok = $scope.trip.setDate($scope.trip.getDate()- i);
$scope.rep.push(i);
}
and it will show like this. It cannot subtract day. How to reduce it properly in angularjs ? please help me solved this problem. Thanks
A: Try like this. i know this is not angularjs code. same logic would work in both
var rep = [];
for (var i=0; i < 31; i++) {
var trip = new Date();
var besok =new Date(trip.getTime() - i*(24*60*60*1000));
rep.push(besok);
}
console.log(rep);
|
Q: How to subtract date in angularjs I try make list from curent date until last 31 days. I try use ng-repeat to make list today until 31 day. I can make list but not date. I try code like this
HTML
<ion-list>
<ion-item class="animate-repeat" ng-repeat="i in rep">
{{trip}}
{{besok}}
</ion-item>
</ion-list>
JS
$scope.rep = [];
for (var i=0; i < 31; i++) {
$scope.trip = new Date();
$scope.besok = $scope.trip.setDate($scope.trip.getDate()- i);
$scope.rep.push(i);
}
and it will show like this. It cannot subtract day. How to reduce it properly in angularjs ? please help me solved this problem. Thanks
A: Try like this. i know this is not angularjs code. same logic would work in both
var rep = [];
for (var i=0; i < 31; i++) {
var trip = new Date();
var besok =new Date(trip.getTime() - i*(24*60*60*1000));
rep.push(besok);
}
console.log(rep);
|
stackoverflow
|
{
"language": "en",
"length": 142,
"provenance": "stackexchange_0000F.jsonl.gz:863309",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537309"
}
|
784b26772a6be7478304e13b338d7395c2bc3e4b
|
Stackoverflow Stackexchange
Q: What is the job for oe_runmake in yocto? I want to know about the oe_runmake in yocto.
A: oe_runmake function is used to run make.
oe_runmake
*
*passes EXTRA_OEMAKE settings to make
*displays the make command
*checks for errors generated via the call.
In OE environment you should not call make directly rather use oe_runmake when you need to run make.
oe_runmake is one of many helper functions defined by the base class.
For a list of helper functions you can refer OEManual
|
Q: What is the job for oe_runmake in yocto? I want to know about the oe_runmake in yocto.
A: oe_runmake function is used to run make.
oe_runmake
*
*passes EXTRA_OEMAKE settings to make
*displays the make command
*checks for errors generated via the call.
In OE environment you should not call make directly rather use oe_runmake when you need to run make.
oe_runmake is one of many helper functions defined by the base class.
For a list of helper functions you can refer OEManual
|
stackoverflow
|
{
"language": "en",
"length": 84,
"provenance": "stackexchange_0000F.jsonl.gz:863310",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537312"
}
|
940a9c573ef0fc6dc9a3c47ecf2acdf624d59860
|
Stackoverflow Stackexchange
Q: Scala-test having issues with read file I'm working on Scalatest where I need to validate a few parameters against my inputs(in Excel file). My problems are:
*
*How to insert/read excel sheet using Scalatest
*How to validate the outputs against the corresponding input from excel
More details
Suppose for test case,on clicking on webpage XYZ,parameter/property "ads" should "Y" is fetched and I have given the condition that test case should be PASSED if excel sheet (having property "ads" is "Y" for Webpage XYZ),matches with the parameters fetched from webpage
Any pointers will be appreciated!!
A: You can use spoiwo or Apache Poi to read the excel files. You can follow any simple tutorials on how to read and write to excel file using apache poi. Here simple example of reading files from excel.
You can test in scalatest after retrieving the values from excel and write back the test results.
Hope this was useful.
|
Q: Scala-test having issues with read file I'm working on Scalatest where I need to validate a few parameters against my inputs(in Excel file). My problems are:
*
*How to insert/read excel sheet using Scalatest
*How to validate the outputs against the corresponding input from excel
More details
Suppose for test case,on clicking on webpage XYZ,parameter/property "ads" should "Y" is fetched and I have given the condition that test case should be PASSED if excel sheet (having property "ads" is "Y" for Webpage XYZ),matches with the parameters fetched from webpage
Any pointers will be appreciated!!
A: You can use spoiwo or Apache Poi to read the excel files. You can follow any simple tutorials on how to read and write to excel file using apache poi. Here simple example of reading files from excel.
You can test in scalatest after retrieving the values from excel and write back the test results.
Hope this was useful.
|
stackoverflow
|
{
"language": "en",
"length": 155,
"provenance": "stackexchange_0000F.jsonl.gz:863326",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537360"
}
|
5757d13654e253cb1c0d5319a5f4b48889f30e1b
|
Stackoverflow Stackexchange
Q: How to collect tuple into separate variables def giveMeTuple: Tuple2[String, String] = {
Tuple2("one", "two")
}
def testFive: Unit = {
val one, two = giveMeTuple
println(one)
println(two)
()
}
testFive
Produces:
(one,two)
(one,two)
But I was expecting:
one
two
What is going on with the initialization of one and two?
A: Almost there.
This is what you need:
val (one, two) = giveMeTuple
With
val one, two = giveMeTuple
you are saying: initialize one with value returned by giveMeTuple and initialize two value returned by giveMeTuple (in this case giveMeTuple will be called twice)
Another similar example is
val one, two = 1
where both will be initialized to value 1
Instead you want to deconstruct the value return by giveMeTuple and take the first and second values from the tuple. In that case giveMeTuple will be called only once of course.
|
Q: How to collect tuple into separate variables def giveMeTuple: Tuple2[String, String] = {
Tuple2("one", "two")
}
def testFive: Unit = {
val one, two = giveMeTuple
println(one)
println(two)
()
}
testFive
Produces:
(one,two)
(one,two)
But I was expecting:
one
two
What is going on with the initialization of one and two?
A: Almost there.
This is what you need:
val (one, two) = giveMeTuple
With
val one, two = giveMeTuple
you are saying: initialize one with value returned by giveMeTuple and initialize two value returned by giveMeTuple (in this case giveMeTuple will be called twice)
Another similar example is
val one, two = 1
where both will be initialized to value 1
Instead you want to deconstruct the value return by giveMeTuple and take the first and second values from the tuple. In that case giveMeTuple will be called only once of course.
A: You're missing parenthesis:
val (one, two) = giveMeTuple
If we decompile the code above, we'll see that this is just the Tuple Pattern which is part of Scalas Pattern Matching feature:
def main(args: Array[String]): Unit = {
private[this] val x$1: (String, String) = (TupleTest.this.giveMeTuple: (String, String) @unchecked) match {
case (_1: String, _2: String)(String, String)((one @ _), (two @ _)) => scala.Tuple2.apply[String, String](one, two)
};
val one: String = x$1._1;
val two: String = x$1._2;
()
}
While your example is double invocation of the same method and assignment to a fresh value:
def giveMeTuple: (String, String) = scala.Tuple2.apply[String, String]("one", "two");
def main(args: Array[String]): Unit = {
val one: (String, String) = TupleTest.this.giveMeTuple;
val two: (String, String) = TupleTest.this.giveMeTuple;
()
}
|
stackoverflow
|
{
"language": "en",
"length": 266,
"provenance": "stackexchange_0000F.jsonl.gz:863348",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537431"
}
|
8f41242a0b72e0b192070f215bd5a786ed5dd495
|
Stackoverflow Stackexchange
Q: Android grid view Change number of columns depending on data
i want to arrange the grid view like below image.
A: You need to use RecyclerView with GridLayoutManager for that. Then you can use GridLayoutManager.setSpanSizeLookup to set the column count dynamically.
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (adapter.getItemViewType(position)) {
case VIEW_TYPE_1:
return 1;
case VIEW_TYPE_2:
return 2;
default:
return -1;
}
}
});
|
Q: Android grid view Change number of columns depending on data
i want to arrange the grid view like below image.
A: You need to use RecyclerView with GridLayoutManager for that. Then you can use GridLayoutManager.setSpanSizeLookup to set the column count dynamically.
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (adapter.getItemViewType(position)) {
case VIEW_TYPE_1:
return 1;
case VIEW_TYPE_2:
return 2;
default:
return -1;
}
}
});
A: You can take RecyclerView instead of GridView and write like this
RecyclerView mRecyclerView=(RecyclerView)findViewById(R.id.card_recycler_view);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 4);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position % 3 == 2) {
return 4;
} else {
return 2;
}
}
});
mRecyclerView.setLayoutManager(glm);
A: You need to spacify viewType in recycler adapter.
DEMO HERE
public class RVStatisticAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Statistic> mList;
public RVStatisticAdapter(List<Statistic> list) {
this.mList = list;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case CITY_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.statistic_row_one, parent, false);
return new CityViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.statistic_row_two, parent, false);
return new EventViewHolder(view);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Statistic object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case CITY_TYPE:
((CityViewHolder) holder).mTitle.setText(object.getTitle());
((CityViewHolder) holder).no.setText(object.getNo());
((CityViewHolder) holder).playerone.setText(object.getPlayer_one());
break;
case EVENT_TYPE:
((EventViewHolder) holder).mTitle.setText(object.getTitle());
((EventViewHolder) holder).no.setText(object.getNo());
((EventViewHolder) holder).playerone.setText(object.getName());
((EventViewHolder) holder).playertwo.setText(object.getPlayer_two());
break;
}
}
}
@Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
@Override
public int getItemViewType(int position) {
if (mList != null) {
Statistic object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
public static class CityViewHolder extends RecyclerView.ViewHolder {
private TextView mTitle,no,playerone;
public CityViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.tv_title);
no = (TextView) itemView.findViewById(R.id.tv_no);
playerone = (TextView) itemView.findViewById(R.id.tv_player_one);
}
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
private TextView mTitle,no,playerone,playertwo;
public EventViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.tv_title);
no = (TextView) itemView.findViewById(R.id.tv_no);
playerone = (TextView) itemView.findViewById(R.id.tv_player_one);
playertwo = (TextView) itemView.findViewById(R.id.tv_player_two);
}
}
}
A: This One will Work. Try this
RecyclerView RecyclerView=RecyclerView)findViewById(R.id.card_recycler_view);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 4);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch(position%3) {
case 0:
return 4;
break;
case 1:
return 2;
break;
case 2:
return 2;
break;
}
}
});
mRecyclerView.setLayoutManager(glm);
A: you can use StaggeredGridLayoutManager
private StaggeredGridLayoutManager gaggeredGridLayoutManager;
gaggeredGridLayoutManager = new StaggeredGridLayoutManager(2, 1);
recyclerView.setLayoutManager(gaggeredGridLayoutManager);
for more information follow this link StaggeredGridLayoutManager
for example see this image
|
stackoverflow
|
{
"language": "en",
"length": 398,
"provenance": "stackexchange_0000F.jsonl.gz:863373",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537514"
}
|
486c0ea8f0647798b967dd9497a358232a6b1387
|
Stackoverflow Stackexchange
Q: Laravel how to return a whole item data with the highest value How can I return the whole item data, I've used max to get the hieghest value but it only returns the value of the field not the whole item
public static function getTeamLeaders($competitionId, $teamId) {
if($teamId){
$ppg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->get()
->max('Points');
$apg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->get()
->max('Assists');
$fgpg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->get()
->max('FieldGoals');
$data = ['ppg' => $ppg, 'apg' => $apg, 'fgpg' => $fgpg];
return $data;
}
}
Result:
array:3 [▼
"ppg" => 15.18
"apg" => 3.76
"fgpg" => 12.04
]
A: You can use orderBy to sort on the field that you want the max of, and then select the first result.
docs:
https://laravel.com/docs/5.4/queries#ordering-grouping-limit-and-offset
https://laravel.com/docs/5.4/queries#retrieving-results
$ppg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->orderBy('Points', 'desc')
->first();
|
Q: Laravel how to return a whole item data with the highest value How can I return the whole item data, I've used max to get the hieghest value but it only returns the value of the field not the whole item
public static function getTeamLeaders($competitionId, $teamId) {
if($teamId){
$ppg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->get()
->max('Points');
$apg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->get()
->max('Assists');
$fgpg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->get()
->max('FieldGoals');
$data = ['ppg' => $ppg, 'apg' => $apg, 'fgpg' => $fgpg];
return $data;
}
}
Result:
array:3 [▼
"ppg" => 15.18
"apg" => 3.76
"fgpg" => 12.04
]
A: You can use orderBy to sort on the field that you want the max of, and then select the first result.
docs:
https://laravel.com/docs/5.4/queries#ordering-grouping-limit-and-offset
https://laravel.com/docs/5.4/queries#retrieving-results
$ppg = self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->orderBy('Points', 'desc')
->first();
A: Instead of using max use orderBy
self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->orderBy('Points', 'desc')
->first();
A: I think you should update your code like :
public static function getTeamLeaders($competitionId, $teamId) {
if($teamId){
$ppg = self::where('competitionId', $competitionId)
->whereRaw('Points = (select max(`Points`) from table_name)')
->where('teamId', $teamId)
->get();
$apg = self::where('competitionId', $competitionId)
->whereRaw('Assists = (select max(`Assists`) from table_name)')
->where('teamId', $teamId)
->get());
$fgpg = self::where('competitionId', $competitionId)
->whereRaw('FieldGoals = (select max(`FieldGoals`) from table_name)')
->where('teamId', $teamId)
->get();
$data = ['ppg' => $ppg, 'apg' => $apg, 'fgpg' => $fgpg];
return $data;
}
}
Hope this work for you!
A: Only change 'max' to 'orderBy'.
$something= self::where('competitionId', $competitionId)
->where('teamId', $teamId)
->orderBy('Points', 'desc')
->first();
|
stackoverflow
|
{
"language": "en",
"length": 239,
"provenance": "stackexchange_0000F.jsonl.gz:863377",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537535"
}
|
9b2f756ba6c8c3d1f98c0203cf64f3a6426f871c
|
Stackoverflow Stackexchange
Q: Android button elevation shadow not working I am trying to make a button that has a shadow using elevation with a background image being my sign in with gmail png. The button is contained within a relative layout. The elevation won't show no matter what I try to do. I tried solutions from other forum questions and none worked.
Here is my code for the button
<Button
android:id="@+id/google"
android:layout_width="270dp"
android:layout_height="38dp"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:background="@drawable/google"
android:elevation="10dp"
android:layout_below="@id/slogan"/>
The google drawable is a png image that I exported from Adobe XD.
Could someone please give me a pointer on what I am doing wrong? Thanks.
Additionally, I realize that if I set the background of the button to android:color/white the shadow appears. So I think the issue is with the png drawable? Does elevation not work with png images? Is there a workaround?
A: For Material Button, I tried the following and it worked
android:translationZ="5dp"
|
Q: Android button elevation shadow not working I am trying to make a button that has a shadow using elevation with a background image being my sign in with gmail png. The button is contained within a relative layout. The elevation won't show no matter what I try to do. I tried solutions from other forum questions and none worked.
Here is my code for the button
<Button
android:id="@+id/google"
android:layout_width="270dp"
android:layout_height="38dp"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:background="@drawable/google"
android:elevation="10dp"
android:layout_below="@id/slogan"/>
The google drawable is a png image that I exported from Adobe XD.
Could someone please give me a pointer on what I am doing wrong? Thanks.
Additionally, I realize that if I set the background of the button to android:color/white the shadow appears. So I think the issue is with the png drawable? Does elevation not work with png images? Is there a workaround?
A: For Material Button, I tried the following and it worked
android:translationZ="5dp"
A: Use below the line of code to show an elevation in button
android:outlineProvider="bounds" – K. Sopheak
That works, thanks!
A: try this I hope it helps, because another view or layout just after your button is hiding shadow
android:layout_marginBottom="16dp"
A: Since you're using an image, replace the <Button> tag with that of an <ImageButton>. So, your workaround code would be:
<ImageButton
android:id="@+id/google"
android:layout_width="270dp"
android:layout_height="38dp"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:src="@drawable/google"
android:elevation="10dp"
android:layout_below="@id/slogan"/>
Take note that the android:src attribute is being used here rather than the android:background attribute.
This one worked for me!
A: try this , I hope this help you ||
android:layout_margin="5dp"
|
stackoverflow
|
{
"language": "en",
"length": 254,
"provenance": "stackexchange_0000F.jsonl.gz:863382",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537554"
}
|
1a2c73f28c98f307314ad8f3bf877c9d60445808
|
Stackoverflow Stackexchange
Q: Using Sequelize with Node.js and React.js I want to use sequelize in my app with mysql.
I think I forget something.. I try to do the configuration, but I have an error : "cannot use new with an expression whose type lacks a call or construct signature" So how can I use a constructor here .. ? Must I create a component in React ?
This is my code :
import * as Sequelize from 'sequelize'
const sequelize = new Sequelize('mysql://root@localhost:3306/dbtestseq', {
timestamps: true,
paranoid: true
} as Sequelize.Options)
export default sequelize
Thank you
|
Q: Using Sequelize with Node.js and React.js I want to use sequelize in my app with mysql.
I think I forget something.. I try to do the configuration, but I have an error : "cannot use new with an expression whose type lacks a call or construct signature" So how can I use a constructor here .. ? Must I create a component in React ?
This is my code :
import * as Sequelize from 'sequelize'
const sequelize = new Sequelize('mysql://root@localhost:3306/dbtestseq', {
timestamps: true,
paranoid: true
} as Sequelize.Options)
export default sequelize
Thank you
|
stackoverflow
|
{
"language": "en",
"length": 95,
"provenance": "stackexchange_0000F.jsonl.gz:863383",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537558"
}
|
9e8a745727f164cf082dce6bb52467ced9e488bf
|
Stackoverflow Stackexchange
Q: Create view in postgres sql with comments I create a view in postgres sql with sql statement
CREATE OR REPLACE VIEW {ViewName} as
Select
.....
I am asking is there any way to create comments for columns in the view.
After the view is created, it generates an error when a comment is added to a column :
ERROR: "{ViewName}" is not a table, composite type, or foreign table.
A: To define a comment on a column (or a view) use comment on:
create view some_view
as
select x as col1, y as col2, z as col3
from some_table;
Then:
comment on view some_view is 'Some View';
comment on column some_view.col1 is 'Originally column X';
|
Q: Create view in postgres sql with comments I create a view in postgres sql with sql statement
CREATE OR REPLACE VIEW {ViewName} as
Select
.....
I am asking is there any way to create comments for columns in the view.
After the view is created, it generates an error when a comment is added to a column :
ERROR: "{ViewName}" is not a table, composite type, or foreign table.
A: To define a comment on a column (or a view) use comment on:
create view some_view
as
select x as col1, y as col2, z as col3
from some_table;
Then:
comment on view some_view is 'Some View';
comment on column some_view.col1 is 'Originally column X';
A: Use a dummy select statement.
select 'general information for the use of the comments' as c1;
It's clunky but the only way I can find to embed comments.
For larger items, I create a commentary in a header.
with query_header as (
select 'purpose - statement' as c1,
select 'revision - revised 16 Oct 2019 by WDH' as c2
select 'owner - contact details' as c3
select 'lines 234-312 to declutter orders with no valid partnmber' as c4
select 'join on itemtable changed to left join 23July2018 by WDH' as c5
)
|
stackoverflow
|
{
"language": "en",
"length": 209,
"provenance": "stackexchange_0000F.jsonl.gz:863412",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537656"
}
|
edf660f2eb2d418b38c6d86eaef6c23834619d38
|
Stackoverflow Stackexchange
Q: How to access a value in the application.properties file in Spring Boot app with main method I have a application.properties in my src/main/resources folder.
it has one property
username=myname
I have a class
public class A
{
@Value("${username}")
private String username;
public void printUsername()
{
System.out.println(username);
}
}
when i call printusername function in my main method as follws
public static void main(String[] args)
{
A object=new A();
object.printUsername();
}
it prints null.
please some one can tell me what i have missed?
A: The @Value annotation, as @Autowired, works only if your class is instantiated by Spring IoC container.
Try to annotate your class with @Component annotation:
@Component
public class A
{
@Value("${username}")
private String username;
public void printUsername()
{
System.out.println(username);
}
}
Then in your runnable class:
public class RunnableClass {
private static A object;
@Autowired
public void setA(A object){
RunnableClass.object = object;
}
public static void main(String[] args)
{
object.printUsername();
}
}
This way should work...
|
Q: How to access a value in the application.properties file in Spring Boot app with main method I have a application.properties in my src/main/resources folder.
it has one property
username=myname
I have a class
public class A
{
@Value("${username}")
private String username;
public void printUsername()
{
System.out.println(username);
}
}
when i call printusername function in my main method as follws
public static void main(String[] args)
{
A object=new A();
object.printUsername();
}
it prints null.
please some one can tell me what i have missed?
A: The @Value annotation, as @Autowired, works only if your class is instantiated by Spring IoC container.
Try to annotate your class with @Component annotation:
@Component
public class A
{
@Value("${username}")
private String username;
public void printUsername()
{
System.out.println(username);
}
}
Then in your runnable class:
public class RunnableClass {
private static A object;
@Autowired
public void setA(A object){
RunnableClass.object = object;
}
public static void main(String[] args)
{
object.printUsername();
}
}
This way should work...
|
stackoverflow
|
{
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:863419",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537674"
}
|
58c82cd88c041d97b86ead73db6c7e04b46852ef
|
Stackoverflow Stackexchange
Q: Floating point operations in linux kernel module (again) I searched a lot of other questions inside StackOverflow, but none of them really solved my problem.
I am writing a linux kernel module and I need to compute a percentage value by diving an integer number by another integer number in order to get a float value ranging between 0 and 100:
int v1 = 5;
int v2 = 25;
float perc = v1 / v2;
For all the reasons we already know, when I try to compile it I get the "SSE register return with SSE disabled" error.
Is there a workaround to compute such division inside a Linux Kernel Module?
Thank you so much.
Antonio
A: You can just use integer arithmetic, e.g.
int perc = 100 * v1 / v2;
This will give an integer percentage. If you need higher resolution than 1% then use a scale factor larger than 100 and insert a decimal point for display purposes as required.
|
Q: Floating point operations in linux kernel module (again) I searched a lot of other questions inside StackOverflow, but none of them really solved my problem.
I am writing a linux kernel module and I need to compute a percentage value by diving an integer number by another integer number in order to get a float value ranging between 0 and 100:
int v1 = 5;
int v2 = 25;
float perc = v1 / v2;
For all the reasons we already know, when I try to compile it I get the "SSE register return with SSE disabled" error.
Is there a workaround to compute such division inside a Linux Kernel Module?
Thank you so much.
Antonio
A: You can just use integer arithmetic, e.g.
int perc = 100 * v1 / v2;
This will give an integer percentage. If you need higher resolution than 1% then use a scale factor larger than 100 and insert a decimal point for display purposes as required.
|
stackoverflow
|
{
"language": "en",
"length": 164,
"provenance": "stackexchange_0000F.jsonl.gz:863436",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537716"
}
|
083edc355f8972011732f8637a5e7279bcb886e0
|
Stackoverflow Stackexchange
Q: When does Browsers Garbage Collect? Do Browsers allocate memory for each tab? If that's true, how much memory is allocated for each tab. And when Browsers do GC? It's my doubts that are improving our Web App's performance. I need this one. So please help me. Thanks in advance.
A: For Google Chrome, every single tab that is opened work as a standalone process. So I supposed that the garbage collect works for every tab independetly.
However, in the developer page of Mozilla, there are some documentation related to Memory Management, and how other browsers work with it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
|
Q: When does Browsers Garbage Collect? Do Browsers allocate memory for each tab? If that's true, how much memory is allocated for each tab. And when Browsers do GC? It's my doubts that are improving our Web App's performance. I need this one. So please help me. Thanks in advance.
A: For Google Chrome, every single tab that is opened work as a standalone process. So I supposed that the garbage collect works for every tab independetly.
However, in the developer page of Mozilla, there are some documentation related to Memory Management, and how other browsers work with it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
|
stackoverflow
|
{
"language": "en",
"length": 100,
"provenance": "stackexchange_0000F.jsonl.gz:863457",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537764"
}
|
181415e1b2922335072baddd143df830d0f84c11
|
Stackoverflow Stackexchange
Q: Where I need to put UDID info in diawi? I need to create the diawi link for current UDID. So I have build and have archived the project in xcode -> then export -> have saved Ad Hoc Deployment -> a few next and finally i have gotten .ipa file.
Then I go to the diawi.com and send add .ipa file and send. And now I get a link to the webapp.diawi.com where I can see the link for download the app but I am totally don't understand where I need to put current UDID.
When I am uploading .ipa file in diawi.com there no place where I can put this one.
A: You don't need to put the UDID in diawi. Only those devices whose UDID is added to the provisioning profile with which you have archived the app can install the app from that diawi link.
|
Q: Where I need to put UDID info in diawi? I need to create the diawi link for current UDID. So I have build and have archived the project in xcode -> then export -> have saved Ad Hoc Deployment -> a few next and finally i have gotten .ipa file.
Then I go to the diawi.com and send add .ipa file and send. And now I get a link to the webapp.diawi.com where I can see the link for download the app but I am totally don't understand where I need to put current UDID.
When I am uploading .ipa file in diawi.com there no place where I can put this one.
A: You don't need to put the UDID in diawi. Only those devices whose UDID is added to the provisioning profile with which you have archived the app can install the app from that diawi link.
A: You need to add all UUID's in Provisioning Profile(on apple developer portal).
Import that profile in Xcode and then create and upload the new ipa or zip in diawi.
No need to add any UUID's in diawi.
|
stackoverflow
|
{
"language": "en",
"length": 187,
"provenance": "stackexchange_0000F.jsonl.gz:863469",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537807"
}
|
bd1ad8a47cead32ed1e47aca321ee14225c1a47e
|
Stackoverflow Stackexchange
Q: Unknown parameter UInt8 in '_specialize attribute': Xcode 9 This code used for building bit pattern from array of bits gives me error in Xcode 9 (works in 8.3.3)
@_specialize(UInt8)
func integerFrom<T: UnsignedInteger>(_ bits: Array<Bit>) -> T {
var bitPattern: T = 0
for idx in bits.indices {
if bits[idx] == Bit.one {
let bit = T(UIntMax(1) << UIntMax(idx))
bitPattern = bitPattern | bit
}
}
return bitPattern
}
Error
Unknown parameter UInt8 in '_specialize attribute'
Any leads/suggestion on this?
A: You just need to include a where clause in the specialize definition like this
@_specialize(where T == UInt8)
|
Q: Unknown parameter UInt8 in '_specialize attribute': Xcode 9 This code used for building bit pattern from array of bits gives me error in Xcode 9 (works in 8.3.3)
@_specialize(UInt8)
func integerFrom<T: UnsignedInteger>(_ bits: Array<Bit>) -> T {
var bitPattern: T = 0
for idx in bits.indices {
if bits[idx] == Bit.one {
let bit = T(UIntMax(1) << UIntMax(idx))
bitPattern = bitPattern | bit
}
}
return bitPattern
}
Error
Unknown parameter UInt8 in '_specialize attribute'
Any leads/suggestion on this?
A: You just need to include a where clause in the specialize definition like this
@_specialize(where T == UInt8)
|
stackoverflow
|
{
"language": "en",
"length": 99,
"provenance": "stackexchange_0000F.jsonl.gz:863475",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537821"
}
|
17b15a71c1c04bf239a06bec99d781ed366f228f
|
Stackoverflow Stackexchange
Q: How to add badge to UINavigationItem (UIBarButtonItem) - Swift 3 Dose ios providing badge on UIBarButtonItem?
if not then how to do it programmatically or use any library(what are the best library)
In image i want to show badge on UIBarButtonItem (Refresh button icon) like red color round or numbers any thing.
A: I'm using MIBadgeButton its working like a charm.
var appNotificationBarButton: MIBadgeButton! // Make it global
self.appNotificationBarButton = MIBadgeButton(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
self.appNotificationBarButton.setImage(UIImage(named: "bell"), for: .normal)
self.appNotificationBarButton.badgeEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 10)
self.appNotificationBarButton.addTarget(self, action: #selector(self.appNotificationClicked), for: .touchUpInside)
let App_NotificationBarButton : UIBarButtonItem = UIBarButtonItem(customView: self.appNotificationBarButton)
self.navigationItems.rightBarButtonItem = App_NotificationBarButton
|
Q: How to add badge to UINavigationItem (UIBarButtonItem) - Swift 3 Dose ios providing badge on UIBarButtonItem?
if not then how to do it programmatically or use any library(what are the best library)
In image i want to show badge on UIBarButtonItem (Refresh button icon) like red color round or numbers any thing.
A: I'm using MIBadgeButton its working like a charm.
var appNotificationBarButton: MIBadgeButton! // Make it global
self.appNotificationBarButton = MIBadgeButton(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
self.appNotificationBarButton.setImage(UIImage(named: "bell"), for: .normal)
self.appNotificationBarButton.badgeEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 10)
self.appNotificationBarButton.addTarget(self, action: #selector(self.appNotificationClicked), for: .touchUpInside)
let App_NotificationBarButton : UIBarButtonItem = UIBarButtonItem(customView: self.appNotificationBarButton)
self.navigationItems.rightBarButtonItem = App_NotificationBarButton
|
stackoverflow
|
{
"language": "en",
"length": 105,
"provenance": "stackexchange_0000F.jsonl.gz:863486",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537849"
}
|
a5b96481f36c3fb1de829b3fd68b19860b742299
|
Stackoverflow Stackexchange
Q: What are the platform common classes in Kotlin? I'd like to use Kotlin to define interfaces between client and server.
Currently, Kotlin can be used in 3 platforms: Java, Android, Web(JS).
What Kotlin build-in classes can I use across all these platform?
I would expect some common library dependency between kotlin-stdlib and kotlin-stdlib-js, but couldn't find one.
On the other hand, I managed to create the following interface that can be used on all 3 platforms:
interface SomeApi {
fun update(params: Collection<String>)
}
So, how can I figure out what can be used across all platforms, in addition to Collection?
A: You should be able to use all classes in kotlin-runtime and kotlin-stdlib, especially everything that's in the stdlib/common folder in the Github repo.
Multiplatform projects are currently in development and once they're released, it should be easier to write platform independent code.
|
Q: What are the platform common classes in Kotlin? I'd like to use Kotlin to define interfaces between client and server.
Currently, Kotlin can be used in 3 platforms: Java, Android, Web(JS).
What Kotlin build-in classes can I use across all these platform?
I would expect some common library dependency between kotlin-stdlib and kotlin-stdlib-js, but couldn't find one.
On the other hand, I managed to create the following interface that can be used on all 3 platforms:
interface SomeApi {
fun update(params: Collection<String>)
}
So, how can I figure out what can be used across all platforms, in addition to Collection?
A: You should be able to use all classes in kotlin-runtime and kotlin-stdlib, especially everything that's in the stdlib/common folder in the Github repo.
Multiplatform projects are currently in development and once they're released, it should be easier to write platform independent code.
|
stackoverflow
|
{
"language": "en",
"length": 144,
"provenance": "stackexchange_0000F.jsonl.gz:863494",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537871"
}
|
7e27d9c1b50bc65e4fdc6d738d035b1cd6856fd5
|
Stackoverflow Stackexchange
Q: Write/store dataframe in text file I am trying to write dataframe to text file. If a file contains single column then I am able to write in text file. If file contains multiple column then I a facing some error
Text data source supports only a single column, and you have 2
columns.
object replace {
def main(args:Array[String]): Unit = {
Logger.getLogger("org").setLevel(Level.ERROR)
val spark = SparkSession.builder.master("local[1]").appName("Decimal Field Validation").getOrCreate()
var sourcefile = spark.read.option("header","true").text("C:/Users/phadpa01/Desktop/inputfiles/decimalvalues.txt")
val rowRDD = sourcefile.rdd.zipWithIndex().map(indexedRow => Row.fromSeq((indexedRow._2.toLong+1) +: indexedRow._1.toSeq)) //adding prgrefnbr
//add column for prgrefnbr in schema
val newstructure = StructType(Array(StructField("PRGREFNBR",LongType)).++(sourcefile.schema.fields))
//create new dataframe containing prgrefnbr
sourcefile = spark.createDataFrame(rowRDD, newstructure)
val op= sourcefile.write.mode("overwrite").format("text").save("C:/Users/phadpa01/Desktop/op")
}
}
A: I would recommend using a csv or other delimited formats. The following is an example with the most concise/elegant way to write to .tsv in Spark 2+
val tsvWithHeaderOptions: Map[String, String] = Map(
("delimiter", "\t"), // Uses "\t" delimiter instead of default ","
("header", "true")) // Writes a header record with column names
df.coalesce(1) // Writes to a single file
.write
.mode(SaveMode.Overwrite)
.options(tsvWithHeaderOptions)
.csv("output/path")
|
Q: Write/store dataframe in text file I am trying to write dataframe to text file. If a file contains single column then I am able to write in text file. If file contains multiple column then I a facing some error
Text data source supports only a single column, and you have 2
columns.
object replace {
def main(args:Array[String]): Unit = {
Logger.getLogger("org").setLevel(Level.ERROR)
val spark = SparkSession.builder.master("local[1]").appName("Decimal Field Validation").getOrCreate()
var sourcefile = spark.read.option("header","true").text("C:/Users/phadpa01/Desktop/inputfiles/decimalvalues.txt")
val rowRDD = sourcefile.rdd.zipWithIndex().map(indexedRow => Row.fromSeq((indexedRow._2.toLong+1) +: indexedRow._1.toSeq)) //adding prgrefnbr
//add column for prgrefnbr in schema
val newstructure = StructType(Array(StructField("PRGREFNBR",LongType)).++(sourcefile.schema.fields))
//create new dataframe containing prgrefnbr
sourcefile = spark.createDataFrame(rowRDD, newstructure)
val op= sourcefile.write.mode("overwrite").format("text").save("C:/Users/phadpa01/Desktop/op")
}
}
A: I would recommend using a csv or other delimited formats. The following is an example with the most concise/elegant way to write to .tsv in Spark 2+
val tsvWithHeaderOptions: Map[String, String] = Map(
("delimiter", "\t"), // Uses "\t" delimiter instead of default ","
("header", "true")) // Writes a header record with column names
df.coalesce(1) // Writes to a single file
.write
.mode(SaveMode.Overwrite)
.options(tsvWithHeaderOptions)
.csv("output/path")
A: You can save as text CSV file (.format("csv"))
The result will be a text file in a CSV format, each column will be separated by a comma.
val op = sourcefile.write.mode("overwrite").format("csv").save("C:/Users/phadpa01/Desktop/op")
More info can be found in the spark programming guide
A: I think using "substring" is more appropriate for all scenarios I feel.
Please check below code.
sourcefile.rdd
.map(r => { val x = r.toString; x.substring(1, x.length-1)})
.saveAsTextFile("C:/Users/phadpa01/Desktop/op")
A: you can convert the dataframe to rdd and covert the row to string and write the last line as
val op= sourcefile.rdd.map(_.toString()).saveAsTextFile("C:/Users/phadpa01/Desktop/op")
Edited
As @philantrovert and @Pravinkumar have pointed that the above would append [ and ] in the output file, which is true. The solution would be to replace them with empty character as
val op= sourcefile.rdd.map(_.toString().replace("[","").replace("]", "")).saveAsTextFile("C:/Users/phadpa01/Desktop/op")
One can even use regex
A: I use databricks api to save my DF output into text file.
myDF.write.format("com.databricks.spark.csv").option("header", "true").save("output.csv")
|
stackoverflow
|
{
"language": "en",
"length": 322,
"provenance": "stackexchange_0000F.jsonl.gz:863502",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537889"
}
|
e04667bf30875e75ade34b87ebace32183b18140
|
Stackoverflow Stackexchange
Q: Convert nngraph model to nn model I want to convert the pix2pix Image to Image translation model (https://github.com/phillipi/pix2pix) which is built using nngraph.
When I try to convert it to caffe model using torch to caffe tool (https://github.com/facebook/fb-caffe-exts#torch2caffe) I get the error "unknown class nn.gModule".
I also try to load torch model in pytorch by load_lua from torch.utils.serialization where I get similar error.
Since, it seems nngraph is not supported for conversion. Is there a way to convert nngraph model to nn model without the need of rewriting or retraining? Down the line, I want to convert the pix2pix model into various formats like caffe, caffe2, coreML and others to test the performance in mobile environment.
Thanks
|
Q: Convert nngraph model to nn model I want to convert the pix2pix Image to Image translation model (https://github.com/phillipi/pix2pix) which is built using nngraph.
When I try to convert it to caffe model using torch to caffe tool (https://github.com/facebook/fb-caffe-exts#torch2caffe) I get the error "unknown class nn.gModule".
I also try to load torch model in pytorch by load_lua from torch.utils.serialization where I get similar error.
Since, it seems nngraph is not supported for conversion. Is there a way to convert nngraph model to nn model without the need of rewriting or retraining? Down the line, I want to convert the pix2pix model into various formats like caffe, caffe2, coreML and others to test the performance in mobile environment.
Thanks
|
stackoverflow
|
{
"language": "en",
"length": 118,
"provenance": "stackexchange_0000F.jsonl.gz:863506",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537895"
}
|
d1dc227ebeaf6258c5bad5a4f2b1bc5c9b07f84c
|
Stackoverflow Stackexchange
Q: Wait for curl to finish before continuing? I am using an script to send date thru curl to an webshop.
In the same script there is an mail sent when this script is executed.
The mail is often send before the curl is complete and therefore missing crucial parameters.
How to change the script so the mail is send after the curl is executed?
// Some more curl code here
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
// execute post
$result = curl_exec($ch);
$data = json_decode($result);
// close connection
curl_close($ch);
// send mail
require('assets/phpmailer/class.phpmailer.php');
$mail = new phpmailer();
$mail->IsHTML(true);
// Some more mail code here
A: You should have a check on the curl response
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
die('Request failed: HTTP status code: ' . $resultStatus);
}
else{
//send the mail
}
}
|
Q: Wait for curl to finish before continuing? I am using an script to send date thru curl to an webshop.
In the same script there is an mail sent when this script is executed.
The mail is often send before the curl is complete and therefore missing crucial parameters.
How to change the script so the mail is send after the curl is executed?
// Some more curl code here
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
// execute post
$result = curl_exec($ch);
$data = json_decode($result);
// close connection
curl_close($ch);
// send mail
require('assets/phpmailer/class.phpmailer.php');
$mail = new phpmailer();
$mail->IsHTML(true);
// Some more mail code here
A: You should have a check on the curl response
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
die('Request failed: HTTP status code: ' . $resultStatus);
}
else{
//send the mail
}
}
A: Try return transfer parameter as true to wait for the response:
// Some more curl code here
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute post
$result = curl_exec($ch);
$data = json_decode($result);
// close connection
curl_close($ch);
// send mail
require('assets/phpmailer/class.phpmailer.php');
$mail = new phpmailer();
$mail->IsHTML(true);
// Some more mail code here
|
stackoverflow
|
{
"language": "en",
"length": 226,
"provenance": "stackexchange_0000F.jsonl.gz:863520",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537939"
}
|
e84b13c9cceeb155a5856d1bc28d22b112fa0cc8
|
Stackoverflow Stackexchange
Q: Where to put the image file for CFBundleTypeIconFiles in iOS? I want to inform iOS that my app can open pdf file, I follow this guide Importing Documents the importing document part, but I need to add an icon for my app in CFBundleDocumentTypes, I add a key named CFBundleTypeIconFiles and its type is array, I add a string for example "myIcon.png", but I don't know where to put the myIcon.png file, can anybody help?
A: The guide that you are following is using a pretty old version of iOS and Xcode but assuming you are on an updated version there should be an AppAssets.xcassets catalog created in your folder structure that you can put all your images/icons in, you should be able to access them from there.
Here is a link to apple documentation about asset catalogs.
|
Q: Where to put the image file for CFBundleTypeIconFiles in iOS? I want to inform iOS that my app can open pdf file, I follow this guide Importing Documents the importing document part, but I need to add an icon for my app in CFBundleDocumentTypes, I add a key named CFBundleTypeIconFiles and its type is array, I add a string for example "myIcon.png", but I don't know where to put the myIcon.png file, can anybody help?
A: The guide that you are following is using a pretty old version of iOS and Xcode but assuming you are on an updated version there should be an AppAssets.xcassets catalog created in your folder structure that you can put all your images/icons in, you should be able to access them from there.
Here is a link to apple documentation about asset catalogs.
|
stackoverflow
|
{
"language": "en",
"length": 139,
"provenance": "stackexchange_0000F.jsonl.gz:863523",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44537949"
}
|
3a5363d3a41fa82aaf8f42f02a0bb946caaa4518
|
Stackoverflow Stackexchange
Q: How to control page margin when printing HTML document? I'm printing a long HTML document and i want to set the margin between the pages in the CSS file.
Unfortunately, the padding/margin only take effect in the first page (padding-top) and the last page (padding-bottom).
Any way to set the margin between pages?
A: It's not margin between pages but page margin. It's controlled by a specific CSS media @page:
@page {
margin: 1cm;
}
Please refer to linked specs for all the details (especially about how @page combines with, for example, <body> margins).
Note that with pseudo-selectors you can control the aspect of :left, :right and :first pages (just to mention few common use cases).
|
Q: How to control page margin when printing HTML document? I'm printing a long HTML document and i want to set the margin between the pages in the CSS file.
Unfortunately, the padding/margin only take effect in the first page (padding-top) and the last page (padding-bottom).
Any way to set the margin between pages?
A: It's not margin between pages but page margin. It's controlled by a specific CSS media @page:
@page {
margin: 1cm;
}
Please refer to linked specs for all the details (especially about how @page combines with, for example, <body> margins).
Note that with pseudo-selectors you can control the aspect of :left, :right and :first pages (just to mention few common use cases).
|
stackoverflow
|
{
"language": "en",
"length": 117,
"provenance": "stackexchange_0000F.jsonl.gz:863545",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538020"
}
|
397b24fdd71a091cc4d430f8c1462ded165b9e76
|
Stackoverflow Stackexchange
Q: How to set current file location as work directory in R markdown? I have mydata.RDATA to be used in R, then I need to load(), which means I need to setwd() curent directory first. I already know how to do it in R.
When I do it in R markdown:
{r echo=FALSE}
dirname(parent.frame(2)$ofile)
script.dir <- dirname(sys.frame(1)$ofile)
setwd(script.dir)
I get error as below:
Error in dirname(parent.frame(2)$ofile) : a character vector argument expected calls :<Anonymous>...
A: If your .Rmd file is in a subfolder you need to specify the root directory for knitr, even if you've specified a working directory with setwd() or even an RSudio project.
Fortunately this is as easy as adding the following chunk to the start of your .Rmd file, right after the YAML:
{r "setup", include=FALSE}
require("knitr")
opts_knit$set(root.dir = "~/path/to/project")
The ~/ is your HOME directory on Linux (and maybe Mac). If you're on Windows you'll have to tweak this.
|
Q: How to set current file location as work directory in R markdown? I have mydata.RDATA to be used in R, then I need to load(), which means I need to setwd() curent directory first. I already know how to do it in R.
When I do it in R markdown:
{r echo=FALSE}
dirname(parent.frame(2)$ofile)
script.dir <- dirname(sys.frame(1)$ofile)
setwd(script.dir)
I get error as below:
Error in dirname(parent.frame(2)$ofile) : a character vector argument expected calls :<Anonymous>...
A: If your .Rmd file is in a subfolder you need to specify the root directory for knitr, even if you've specified a working directory with setwd() or even an RSudio project.
Fortunately this is as easy as adding the following chunk to the start of your .Rmd file, right after the YAML:
{r "setup", include=FALSE}
require("knitr")
opts_knit$set(root.dir = "~/path/to/project")
The ~/ is your HOME directory on Linux (and maybe Mac). If you're on Windows you'll have to tweak this.
|
stackoverflow
|
{
"language": "en",
"length": 154,
"provenance": "stackexchange_0000F.jsonl.gz:863557",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538066"
}
|
74c114e56b76fd152753c220c404dec9adf0c533
|
Stackoverflow Stackexchange
Q: React Navigation onPress in own function I've implemented the React Navigation example as in the tutorial https://reactnavigation.org/docs/intro/ and it works fine.
<Button
onPress={() => navigate('Chat')}
title="Chat with Lucy"
/>
Instead of calling navigate direct in onPress, I want to call it in a separate function btnToChat. I've tried to call it with this.props.navigation.navigate, but it doesn't work. Do you have any suggestions? Thank you!
btnToChat(){
console.log("test");
this.props.navigation.navigate('Chat');
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={this._btnToChat}
/>
</View>
);
}
}
The following error appears: undefined is not an object (evaluating this.props.navigation)
A: Everything is proper, you just need to bind the _btnToChat method to access (correct context) this keyword inside that.
Like this:
btnToChat = () => { //here use arrow function
console.log("test");
this.props.navigation.navigate('Chat');
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={this._btnToChat}
/>
</View>
);
}
Or define the binding of _btnToChat method inside constructor:
constructor(){
super();
this._btnToChat = this._btnToChat.bind(this);
}
btnToChat (){
console.log("test");
this.props.navigation.navigate('Chat');
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={this._btnToChat}
/>
</View>
);
}
|
Q: React Navigation onPress in own function I've implemented the React Navigation example as in the tutorial https://reactnavigation.org/docs/intro/ and it works fine.
<Button
onPress={() => navigate('Chat')}
title="Chat with Lucy"
/>
Instead of calling navigate direct in onPress, I want to call it in a separate function btnToChat. I've tried to call it with this.props.navigation.navigate, but it doesn't work. Do you have any suggestions? Thank you!
btnToChat(){
console.log("test");
this.props.navigation.navigate('Chat');
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={this._btnToChat}
/>
</View>
);
}
}
The following error appears: undefined is not an object (evaluating this.props.navigation)
A: Everything is proper, you just need to bind the _btnToChat method to access (correct context) this keyword inside that.
Like this:
btnToChat = () => { //here use arrow function
console.log("test");
this.props.navigation.navigate('Chat');
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={this._btnToChat}
/>
</View>
);
}
Or define the binding of _btnToChat method inside constructor:
constructor(){
super();
this._btnToChat = this._btnToChat.bind(this);
}
btnToChat (){
console.log("test");
this.props.navigation.navigate('Chat');
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={this._btnToChat}
/>
</View>
);
}
|
stackoverflow
|
{
"language": "en",
"length": 186,
"provenance": "stackexchange_0000F.jsonl.gz:863560",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538072"
}
|
28339388e996780c6284f04bb9d9edf3998f266c
|
Stackoverflow Stackexchange
Q: How to format numbers in VueJS I couldn't find a way of formatting numbers in VueJS. All I found was the builtin currency filter and vue-numeric for formatting currencies, which needs some modification to look like a label. And then you can't use it for displaying iterated array members.
A: try this one. If you are using vue.js 2
<template>
{{lowPrice | currency}}
</template>
<script>
data:(){
return {lowPrice: 200}
}
filters:{
currency(value) {
return new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD" }).format(value);
}
}
</script>
vue.js 3 no longer supports filters, so you can use this logic in computed
<template>
{{currency}}
</template>
<script>
data:(){
return {lowPrice: 200}
}
computed:{
currency() {
return new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD" }).format(this.lowPrice);
}
}
</script>
|
Q: How to format numbers in VueJS I couldn't find a way of formatting numbers in VueJS. All I found was the builtin currency filter and vue-numeric for formatting currencies, which needs some modification to look like a label. And then you can't use it for displaying iterated array members.
A: try this one. If you are using vue.js 2
<template>
{{lowPrice | currency}}
</template>
<script>
data:(){
return {lowPrice: 200}
}
filters:{
currency(value) {
return new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD" }).format(value);
}
}
</script>
vue.js 3 no longer supports filters, so you can use this logic in computed
<template>
{{currency}}
</template>
<script>
data:(){
return {lowPrice: 200}
}
computed:{
currency() {
return new Intl.NumberFormat("en-US",
{ style: "currency", currency: "USD" }).format(this.lowPrice);
}
}
</script>
A: Install numeral.js:
npm install numeral --save
Define the custom filter:
<script>
var numeral = require("numeral");
Vue.filter("formatNumber", function (value) {
return numeral(value).format("0,0"); // displaying other groupings/separators is possible, look at the docs
});
export default
{
...
}
</script>
Use it:
<tr v-for="(item, key, index) in tableRows">
<td>{{item.integerValue | formatNumber}}</td>
</tr>
A: Intl.NumberFormat(), default usage:
...
created: function() {
let number = 1234567;
console.log(new Intl.NumberFormat().format(number))
},
...
//console -> 1 234 567
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
A: Vue 3
Note that filters are removed in vue 3, so we define it in global properties:
app.config.globalProperties.$filters = {
formatNumber(number) {
return Intl.NumberFormat().format(number);
}
}
Usage:
<h3>{{ $filters.formatNumber(count) }}</h3>
A: JavaScript has a built-in function for this.
If you're sure the variable is always Number and never a “number String”, you can do:
{{ num.toLocaleString() }}
If you want to be safe, do:
{{ Number(num).toLocaleString() }}
Source: https://forum.vuejs.org/t/filter-numeric-with-comma/16002/2
A: I'm from Chile and add custom format... for example: $50.000.000,56
install npm install numeral --save
import numeral from 'numeral'
// load a locale
numeral.register('locale', 'cl', {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'm',
million: 'M',
billion: 'B',
trillion: 'T'
},
ordinal: function (number) {
return number === 1 ? 'er' : 'ème'
},
currency: {
symbol: '$'
}
})
// switch between locales
numeral.locale('cl')
After that add format custom...
Vue.filter('formatNumberMoney', function (value) {
return numeral(value).format('0,0.')
// displaying other groupings/separators is possible, look at the docs
})
A: Just in case if you really want to do something simple:
<template>
<div> {{ commission | toUSD }} </div>
</template>
<script>
export default {
data () {
return {
commission: 123456
}
},
filters: {
toUSD (value) {
return `$${value.toLocaleString()}`
}
}
}
</script>
If you like to get bit more complicated then use this code or the code below:
in main.js
import {currency} from "@/currency";
Vue.filter('currency', currency)
in currency.js
const digitsRE = /(\d{3})(?=\d)/g
export function currency (value, currency, decimals) {
value = parseFloat(value)
if (!isFinite(value) || (!value && value !== 0)) return ''
currency = currency != null ? currency : '$'
decimals = decimals != null ? decimals : 2
var stringified = Math.abs(value).toFixed(decimals)
var _int = decimals
? stringified.slice(0, -1 - decimals)
: stringified
var i = _int.length % 3
var head = i > 0
? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
: ''
var _float = decimals
? stringified.slice(-1 - decimals)
: ''
var sign = value < 0 ? '-' : ''
return sign + currency + head +
_int.slice(i).replace(digitsRE, '$1,') +
_float
}
and in template:
<div v-for="product in products">
{{product.price | currency}}
</div>
you can also refer answers here.
A: You could always give vue-numeral-filter a try.
A:
<template>
<input v-model="model" type="text" pattern="\d+((\.|,)\d+)?">
</template>
<script>
export default {
name: "InputNumber",
emits: ['update:modelValue'],
props: {modelValue},
computed: {
model: {
get() {
return this.modelValue ? this.modelValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : this.modelValue
},
set(value) {
this.$emit('update:modelValue', Number(value.replaceAll(',','')))
}
},
}
}
</script>
A: To format numbers such as 12000 to 12,000 use the following Vue filter examples
*
*Global filter that is available across all your components
Go to the file where your Vue instance is created, mostly (main.js)
Vue.filter('format_number', function (value){
return parseInt(value).toLocaleString()
})
To use in your Vue pages,
{{ 12000 | format_number}}
*For use in your single vue file, add the following to your component options
filters: {
format_number: function (value){
return parseInt(value).toLocaleString()
}
},
To use in your Vue pages:
{{ 12000 | format_number}}
To learn more about filters, visit this docs page
Note that Filters are not supported in Vue 3x
|
stackoverflow
|
{
"language": "en",
"length": 712,
"provenance": "stackexchange_0000F.jsonl.gz:863574",
"question_score": "43",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538110"
}
|
717091ebcb03f5b6abe66f7487654618c2d8c106
|
Stackoverflow Stackexchange
Q: Java 8 - stream convert map's value type I would like to convert type List<A> to List<B>. can I do this with java 8 stream method?
Map< String, List<B>> bMap = aMap.entrySet().stream().map( entry -> {
List<B> BList = new ArrayList<B>();
List<A> sList = entry.getValue();
// convert A to B
return ???; Map( entry.getKey(), BList) need to return
}).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
I tried with this code, but cannot convert it inside map().
A: You can instantiate AbstractMap.simpleEntry in the map function and perform the transformation.
E.g. the following code converts List<Integer> to List<String>:
Map<String, List<Integer>> map = new HashMap<>();
Map<String, List<String>> transformedMap = map.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<String, List<String>>(e.getKey(), e.getValue().stream().map(en -> String.valueOf(en)).collect(Collectors.toList())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
Q: Java 8 - stream convert map's value type I would like to convert type List<A> to List<B>. can I do this with java 8 stream method?
Map< String, List<B>> bMap = aMap.entrySet().stream().map( entry -> {
List<B> BList = new ArrayList<B>();
List<A> sList = entry.getValue();
// convert A to B
return ???; Map( entry.getKey(), BList) need to return
}).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
I tried with this code, but cannot convert it inside map().
A: You can instantiate AbstractMap.simpleEntry in the map function and perform the transformation.
E.g. the following code converts List<Integer> to List<String>:
Map<String, List<Integer>> map = new HashMap<>();
Map<String, List<String>> transformedMap = map.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<String, List<String>>(e.getKey(), e.getValue().stream().map(en -> String.valueOf(en)).collect(Collectors.toList())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
A: You may do it like this:
public class Sandbox {
public static void main(String[] args) {
Map<String, List<A>> aMap = null;
Map<String, List<B>> bMap = aMap.entrySet().stream().collect(toMap(
Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(Sandbox::toB)
.collect(toList())));
}
private static B toB(A a) {
// add your conversion
return null;
}
class B {}
class A {}
}
A: If I understood it correctly you have a Map<String, List<A>> and you want to convert it to a Map<String, List<B>>. You can do something like:
Map<String, List<B>> result = aMap.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey(), // Preserve key
entry -> entry.getValue().stream() // Take all values
.map(aItem -> mapToBItem(aItem)) // map to B type
.collect(Collectors.toList()) // collect as list
);
|
stackoverflow
|
{
"language": "en",
"length": 231,
"provenance": "stackexchange_0000F.jsonl.gz:863638",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538354"
}
|
4c6a7f901117dbbbf27d07e0607c28cecc5b6776
|
Stackoverflow Stackexchange
Q: JS querySelector only first child without iterating children How can I select a first child of type X which is a direct descendant of the element using the elements querySelector
For example :
<div id="target">
<span>1</span>
<span>2</span>
<span>3</span>
<div>
<span>4</span>
</div>
</div>
I would like to select only first child SPANs of the target div using querySelector.
target.querySelector('span'); // This would return all spans in target
The other alternatives I know and wouldn't like to use :
Using CSS :
#target > span
Using JS :
[].filter.call(target.children, f=>{ return f.tagName == 'SPAN' })
I would like to use querySelector anyway...
is there a way to call querySelectorAll on a given element, to select only first child elements?
A: If you don't want to depend on the #target selector, you can use the :scope pseudo-class:
const target = document.querySelector("#target");
const child = target.querySelector(":scope > span");
|
Q: JS querySelector only first child without iterating children How can I select a first child of type X which is a direct descendant of the element using the elements querySelector
For example :
<div id="target">
<span>1</span>
<span>2</span>
<span>3</span>
<div>
<span>4</span>
</div>
</div>
I would like to select only first child SPANs of the target div using querySelector.
target.querySelector('span'); // This would return all spans in target
The other alternatives I know and wouldn't like to use :
Using CSS :
#target > span
Using JS :
[].filter.call(target.children, f=>{ return f.tagName == 'SPAN' })
I would like to use querySelector anyway...
is there a way to call querySelectorAll on a given element, to select only first child elements?
A: If you don't want to depend on the #target selector, you can use the :scope pseudo-class:
const target = document.querySelector("#target");
const child = target.querySelector(":scope > span");
A: querySelector gets the first element that matches the selector. Just use the direct descendant selector with it. You don't need any other pseudo selectors.
var target = document.querySelector("#target");
var child = target.querySelector("#target > span");
A: You can use :first-child if you want to get the first child of its parent
target.querySelector('span:first-child');
Or you can use :first-of-type if you want to specify the type like in your case is a span
target.querySelector('span:first-of-type');
See example:
var target = document.querySelector('span:first-of-type');
target.style.color = 'red';
<div id="target">
<span>1</span>
<span>2</span>
<span>3</span>
<div>
<span>4</span>
</div>
</div>
A:
var target = document.querySelector('#target > :first-of-type');
target.style.color = 'red';
<div id="target">
<i>1</i>
<span>2</span>
<b>3</b>
<div>
<span>4</span>
</div>
</div>
A:
Why not use this if you want to use querySelector anyway:
target.querySelector('#target span').first();
OR
target.querySelector('#target span:first-child');
A: in this solution i assume you know how many item
you have to select
var x = document.querySelectorAll("span");
x[0].style.backgroundColor = "red";
x[1].style.backgroundColor = "red";
x[2].style.backgroundColor = "red";
the result will be the same as
#target > span {
background-color:red;
}
A: You can give an id by assigning a condition to the structures you want to search and then you can remove those elements directly under the data of the ids appointed, it worked for me.
const carouselIndicators = document.querySelectorAll("#topSliderSingle");
carouselIndicators.forEach((item) => {
item.querySelector(".carousel-indicators")?.remove();
});
|
stackoverflow
|
{
"language": "en",
"length": 357,
"provenance": "stackexchange_0000F.jsonl.gz:863663",
"question_score": "11",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538425"
}
|
bb9f5324e3128c9166209164f29d09b536b94f14
|
Stackoverflow Stackexchange
Q: Cocoapods iOS - [!] Google has been deprecated - How to get rid of the warning? Steps I did:
*
*pod repo remove master
*pod setup
*pod update --verbose (Just to check the progress especially when updating the Google SDKs, took so long to finish).
And there, I got the warning. In my logs, Google SDKs were updated successfully:
-> Installing Google 3.1.0 (was 3.0.3)
-> Installing GoogleMaps 2.3.0 (was 2.2.0)
Podfile:
target 'MyProj' do
...
pod 'Google/Analytics'
pod 'GoogleMaps'
...
target 'MyProjTests' do
inherit! :search_paths
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '3.0'
end
end
end
end
I would like to know how to get rid of this warning.
A: Change pod 'Google/Analytics' to pod 'GoogleAnalytics' removing the slash.
|
Q: Cocoapods iOS - [!] Google has been deprecated - How to get rid of the warning? Steps I did:
*
*pod repo remove master
*pod setup
*pod update --verbose (Just to check the progress especially when updating the Google SDKs, took so long to finish).
And there, I got the warning. In my logs, Google SDKs were updated successfully:
-> Installing Google 3.1.0 (was 3.0.3)
-> Installing GoogleMaps 2.3.0 (was 2.2.0)
Podfile:
target 'MyProj' do
...
pod 'Google/Analytics'
pod 'GoogleMaps'
...
target 'MyProjTests' do
inherit! :search_paths
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '3.0'
end
end
end
end
I would like to know how to get rid of this warning.
A: Change pod 'Google/Analytics' to pod 'GoogleAnalytics' removing the slash.
A: Extending on Paul Beusterien answer:
First, remove old import from your bridging header:
#import <Google/Analytics.h>
Then, add the following to the bridging header instead:
#import "GAI.h"
#import "GAIDictionaryBuilder.h"
#import "GAIEcommerceFields.h"
#import "GAIEcommerceProduct.h"
#import "GAIEcommerceProductAction.h"
#import "GAIEcommercePromotion.h"
#import "GAIFields.h"
#import "GAILogger.h"
#import "GAITrackedViewController.h"
#import "GAITracker.h"
Finally you might want to recheck:
https://developers.google.com/analytics/devguides/collection/ios/v3/
You don't need GGLContext line anymore.
Hope this helps.
|
stackoverflow
|
{
"language": "en",
"length": 187,
"provenance": "stackexchange_0000F.jsonl.gz:863680",
"question_score": "42",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538472"
}
|
d3c028a0a681cb40b6c81a57148a045b7028d01e
|
Stackoverflow Stackexchange
Q: Clipboard SetText fails whereas SetDataObject does not I was trying to copy a string to the clipboard via
System.Windows.Clipboard.SetText(someString);
and it was failing (Clearing before setting before setting did not work because Clear also needs to open the clipboard). The call to GetOpenClipboardWindow() indicated that some window was keeping the clipboard open (in this case it was notepad++).
By changing the above line to:
System.Windows.Clipboard.SetDataObject(someString);
the call succeeds every time and the contents of the clipboard are what I expect.
Does anybody have an explanation for this behaviour?
The documentation does not state much about what it does differently (except for clearing the clipboard when the program exits).
A: From MSDN
Clipboard.SetDataObject() :
This method attempts to set the data ten times in 100-millisecond intervals, and throws an ExternalException if all attempts are unsuccessful.
Clipboard.SetText(): Clears the Clipboard and then adds text data to it.
|
Q: Clipboard SetText fails whereas SetDataObject does not I was trying to copy a string to the clipboard via
System.Windows.Clipboard.SetText(someString);
and it was failing (Clearing before setting before setting did not work because Clear also needs to open the clipboard). The call to GetOpenClipboardWindow() indicated that some window was keeping the clipboard open (in this case it was notepad++).
By changing the above line to:
System.Windows.Clipboard.SetDataObject(someString);
the call succeeds every time and the contents of the clipboard are what I expect.
Does anybody have an explanation for this behaviour?
The documentation does not state much about what it does differently (except for clearing the clipboard when the program exits).
A: From MSDN
Clipboard.SetDataObject() :
This method attempts to set the data ten times in 100-millisecond intervals, and throws an ExternalException if all attempts are unsuccessful.
Clipboard.SetText(): Clears the Clipboard and then adds text data to it.
A: When looking at the code for the two methods, I see the following differences:
public static void SetText(string text, TextDataFormat format)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
if (!DataFormats.IsValidTextDataFormat(format))
{
throw new InvalidEnumArgumentException("format", (int)format, typeof(TextDataFormat));
}
Clipboard.SetDataInternal(DataFormats.ConvertToDataFormats(format), text);
}
[SecurityCritical]
public static void SetDataObject(object data, bool copy)
{
SecurityHelper.DemandAllClipboardPermission();
Clipboard.CriticalSetDataObject(data, copy);
}
The SetDataObject method is marked as security-critical, which might seem like the important difference. However, the SetText method eventually just calls SetDataObject internally. The difference being:
/* From SetText: */
Clipboard.SetDataObject(dataObject, true);
/* From SetDataObject: */
Clipboard.SetDataObject(data, false);
SetText(text) never clears the Clipboard when the application exits, while SetDataObject(object) always does. That is the only real difference between calls. Try calling SetDataObject(someString, false) and SetDataObject(SomeString, true) to see any difference. If both behave the same, the difference must lie somewhere else.
|
stackoverflow
|
{
"language": "en",
"length": 284,
"provenance": "stackexchange_0000F.jsonl.gz:863693",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538513"
}
|
e78e1ab4c9382906163b3b0d127a430ba39faa2d
|
Stackoverflow Stackexchange
Q: unit testing - How can I pass string with comma to a testcase in DUnitX If I have a unit test with string parameter, and I want to check if the input string has a comma (,) somewhere, I should create an input string with a comma in it.
But how to pass it to the TestCase?
[Test]
[TestCase('TestA', '12,34')] //AValue1 gets only '12' instead of '12,34'
[TestCase('TestB', '12,,34')] //AValue1 gets only '12' instead of '12,34'
[TestCase('TestC', '12/,34')] //AValue1 gets only '12/' instead of '12,34'
[TestCase('TestD', '12\,34')] //AValue1 gets only '12\' instead of '12,34'
procedure ValueShouldHaveComma(const AValue1: string);
A: I have found it:
[Test]
[TestCase('TestA', '12,34', ';')] //AValue1 gets '12,34'
procedure ValueShouldHaveComma(const AValue1: string);
The last optional parameter of the TestCase is the separator.
|
Q: unit testing - How can I pass string with comma to a testcase in DUnitX If I have a unit test with string parameter, and I want to check if the input string has a comma (,) somewhere, I should create an input string with a comma in it.
But how to pass it to the TestCase?
[Test]
[TestCase('TestA', '12,34')] //AValue1 gets only '12' instead of '12,34'
[TestCase('TestB', '12,,34')] //AValue1 gets only '12' instead of '12,34'
[TestCase('TestC', '12/,34')] //AValue1 gets only '12/' instead of '12,34'
[TestCase('TestD', '12\,34')] //AValue1 gets only '12\' instead of '12,34'
procedure ValueShouldHaveComma(const AValue1: string);
A: I have found it:
[Test]
[TestCase('TestA', '12,34', ';')] //AValue1 gets '12,34'
procedure ValueShouldHaveComma(const AValue1: string);
The last optional parameter of the TestCase is the separator.
|
stackoverflow
|
{
"language": "en",
"length": 125,
"provenance": "stackexchange_0000F.jsonl.gz:863703",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538544"
}
|
e7f3c0ecbb7b7b6adf90fc5257fd4930d030e32c
|
Stackoverflow Stackexchange
Q: AmbiguousViewMatcherException multiple RecyclerViews I have a Fragment that contains RecyclerView. But since I have a lot of elements in this Fragment, I want to swipe up the list to see and check all the elements that are in this Fragment.
Earlier this method helped me, but now for some reason it does not work:
Espresso.onView(ViewMatchers.withId(R.id.recyclerView)).perform(ViewActions.swipeUp())
I have many RecyclerViews with same id in my project:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
Also in my tests I've written something like this:
onView(allOf( withId(R.id.recyclerView), isDisplayed()))
onView(withId(R.id.recyclerView)).perform(swipeUp())
But caught error only on second line.
android.support.test.espresso.AmbiguousViewMatcherException: 'with id: com.fentury.android:id/recyclerView' matches multiple views in the hierarchy.
Problem views are marked with '****MATCHES****' below.
A: You have multiple views with id R.id.recyclerView in your view hierarchy, therefore espresso lacks to perform correct matching. Make the ids of those RecyclerViews unique.
onView(allOf(withId(R.id.recyclerView), isDisplayed()))
onView(withId(R.id.recyclerView)).perform(swipeUp())
But caught error only on second line.
Then perform matching this way:
onView(allOf(withId(R.id.recyclerView), isDisplayed())).perform(swipeUp())
|
Q: AmbiguousViewMatcherException multiple RecyclerViews I have a Fragment that contains RecyclerView. But since I have a lot of elements in this Fragment, I want to swipe up the list to see and check all the elements that are in this Fragment.
Earlier this method helped me, but now for some reason it does not work:
Espresso.onView(ViewMatchers.withId(R.id.recyclerView)).perform(ViewActions.swipeUp())
I have many RecyclerViews with same id in my project:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
Also in my tests I've written something like this:
onView(allOf( withId(R.id.recyclerView), isDisplayed()))
onView(withId(R.id.recyclerView)).perform(swipeUp())
But caught error only on second line.
android.support.test.espresso.AmbiguousViewMatcherException: 'with id: com.fentury.android:id/recyclerView' matches multiple views in the hierarchy.
Problem views are marked with '****MATCHES****' below.
A: You have multiple views with id R.id.recyclerView in your view hierarchy, therefore espresso lacks to perform correct matching. Make the ids of those RecyclerViews unique.
onView(allOf(withId(R.id.recyclerView), isDisplayed()))
onView(withId(R.id.recyclerView)).perform(swipeUp())
But caught error only on second line.
Then perform matching this way:
onView(allOf(withId(R.id.recyclerView), isDisplayed())).perform(swipeUp())
A: Solution:
onView(allOf(withId(R.id.recyclerview), isDisplayed())).perform(swipeUp());
A: You should use on data for recycler view where you can assert using recycler view's id as well as type of data it holds. This should help assuming different recycler views would not have same type of data but its better practice to use different ids for different view based on what its used for.
You may also want to use perform(ViewActions.scrollTo())
A: I had a similar problem with multiple RecyclerViews in two fragments inside a ViewPager when I found this question.
Both fragments used the same layout file, containing just the RecyclerView with id = @id/list.
As there was no parent to match I made this custom ViewMatcher to match the list by Adapter-Class: (Kotlin)
fun hasAdapterOfType(T: Class<out RecyclerView.Adapter<out RecyclerView.ViewHolder>>): BoundedMatcher<View, RecyclerView> {
return object : BoundedMatcher<View, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description) {
description.appendText("RecycleView adapter class matches " + T.name)
}
override fun matchesSafely(view: RecyclerView): Boolean {
return (view.adapter.javaClass.name == T.name)
}
}
}
Usage like this:
onView(allOf(withId(list), hasAdapterOfType(AccessAttemptListAdapter::class.java))).check(blabla)
|
stackoverflow
|
{
"language": "en",
"length": 317,
"provenance": "stackexchange_0000F.jsonl.gz:863706",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538552"
}
|
b0fa0bdcf0416a8554b2e05893b3adb33128f6a1
|
Stackoverflow Stackexchange
Q: No devices are booted. Print: Entry, ":CFBundleIdentifier", Does Not Exist When I run react-native run-ios, I get this error.
The following build commands failed:
CompileC
/Users/huanghongxia/work/react-native/appProject/ios/build/Build/Intermediates/React.build/Debug-iphonesimulator/third-party.build/Objects-normal/x86_64/Bits.o
/Users/huanghongxia/work/react-native/appProject/node_modules/react-native/third-party/folly-2016.09.26.00/folly/Bits.cpp
normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/appProject.app
No devices are booted.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier
build/Build/Products/Debug-iphonesimulator/appProject.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
I have tried these steps:
*
*Delete the node_modules folder - rm -rf node_modules && npm install
*Reset packager cache - rm -fr $TMPDIR/react-* or node_modules/react-
native/packager/packager.sh --reset-cache
*Clear watchman watches - watchman watch-del-all
*Recreate the project from scratch
But it doesn't work.
|
Q: No devices are booted. Print: Entry, ":CFBundleIdentifier", Does Not Exist When I run react-native run-ios, I get this error.
The following build commands failed:
CompileC
/Users/huanghongxia/work/react-native/appProject/ios/build/Build/Intermediates/React.build/Debug-iphonesimulator/third-party.build/Objects-normal/x86_64/Bits.o
/Users/huanghongxia/work/react-native/appProject/node_modules/react-native/third-party/folly-2016.09.26.00/folly/Bits.cpp
normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/appProject.app
No devices are booted.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier
build/Build/Products/Debug-iphonesimulator/appProject.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
I have tried these steps:
*
*Delete the node_modules folder - rm -rf node_modules && npm install
*Reset packager cache - rm -fr $TMPDIR/react-* or node_modules/react-
native/packager/packager.sh --reset-cache
*Clear watchman watches - watchman watch-del-all
*Recreate the project from scratch
But it doesn't work.
|
stackoverflow
|
{
"language": "en",
"length": 101,
"provenance": "stackexchange_0000F.jsonl.gz:863727",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538619"
}
|
65c855edef6f7376d7d6d970c389f539b662da92
|
Stackoverflow Stackexchange
Q: sbt-scoverage's coverageExcludedPackages does not exclude packages I'm using sbt scoverage 1.3.5 (Scala 2.11.8) and I have a bunch of classes that I do not want to include the the coverage reports. In particular the base classes and their tests are located in com/corp/something/something_else in both main and test. I have added the following lines to my buld.sbt:
coverageEnabled := true
coverageMinimum := 90
coverageFailOnMinimum := true
coverageExcludedPackages := """com.corp.something.something_else.*;"""
I have tried it with single quotes and \\. in place of the dots, with and without the final .* and with and without the final semicolon but so far when I run sbt clean coverage test coverageReport the report contains everything and it does not exclude the packages I have listed. What am I missing?
Perhaps in a similar vein is that the coverage report does not fail even though across all packages the coverage is below 90% and it should fail based on the option I set, right?
|
Q: sbt-scoverage's coverageExcludedPackages does not exclude packages I'm using sbt scoverage 1.3.5 (Scala 2.11.8) and I have a bunch of classes that I do not want to include the the coverage reports. In particular the base classes and their tests are located in com/corp/something/something_else in both main and test. I have added the following lines to my buld.sbt:
coverageEnabled := true
coverageMinimum := 90
coverageFailOnMinimum := true
coverageExcludedPackages := """com.corp.something.something_else.*;"""
I have tried it with single quotes and \\. in place of the dots, with and without the final .* and with and without the final semicolon but so far when I run sbt clean coverage test coverageReport the report contains everything and it does not exclude the packages I have listed. What am I missing?
Perhaps in a similar vein is that the coverage report does not fail even though across all packages the coverage is below 90% and it should fail based on the option I set, right?
|
stackoverflow
|
{
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:863747",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538694"
}
|
1bf3014ed1b029daca217d3719b8e83c238eaf09
|
Stackoverflow Stackexchange
Q: ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response Sending a form POST HTTP request (Content-Type: application/x-www-form-urlencoded) to the below controller results into a HTTP 415 Unsupported Media Type response.
public class MyController : Controller
{
[HttpPost]
public async Task<IActionResult> Submit([FromBody] MyModel model)
{
//...
}
}
Form post HTTP headers:
POST /submit HTTP/1.1
Host: example.com:1337
Connection: keep-alive
Content-Length: 219
Pragma: no-cache
Cache-Control: no-cache
Origin: https://example.com:1337
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: https://example.com:1337/submit
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,nl;q=0.6
This used to work with ASP.NET MVC 5 on .NET 4.6.
A: This is my case: it's run
Environment: AspNet Core 2.1
Controller:
public class MyController
{
// ...
[HttpPost]
public ViewResult Search([FromForm]MySearchModel searchModel)
{
// ...
return View("Index", viewmodel);
}
}
View:
<form method="post" asp-controller="MyController" asp-action="Search">
<input name="MySearchModelProperty" id="MySearchModelProperty" />
<input type="submit" value="Search" />
</form>
|
Q: ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response Sending a form POST HTTP request (Content-Type: application/x-www-form-urlencoded) to the below controller results into a HTTP 415 Unsupported Media Type response.
public class MyController : Controller
{
[HttpPost]
public async Task<IActionResult> Submit([FromBody] MyModel model)
{
//...
}
}
Form post HTTP headers:
POST /submit HTTP/1.1
Host: example.com:1337
Connection: keep-alive
Content-Length: 219
Pragma: no-cache
Cache-Control: no-cache
Origin: https://example.com:1337
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: https://example.com:1337/submit
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,nl;q=0.6
This used to work with ASP.NET MVC 5 on .NET 4.6.
A: This is my case: it's run
Environment: AspNet Core 2.1
Controller:
public class MyController
{
// ...
[HttpPost]
public ViewResult Search([FromForm]MySearchModel searchModel)
{
// ...
return View("Index", viewmodel);
}
}
View:
<form method="post" asp-controller="MyController" asp-action="Search">
<input name="MySearchModelProperty" id="MySearchModelProperty" />
<input type="submit" value="Search" />
</form>
A: In my case 415 Unsupported Media Types was received since I used new FormData() and sent it with axios.post(...) but did not set headers: {content-type: 'multipart/form-data'}. I also had to do the same on the server side:
[Consumes("multipart/form-data")]
public async Task<IActionResult> FileUpload([FromForm] IFormFile formFile) { ... }
A: With .NET 5 I have a .NET API Controller method that looks like this:
[HttpPost("{rootEntity}/{id}")]
public ActionResult Post(RootEntity rootEntity, int id, [FromBody] string message)
{
...
}
I had this request:
POST /api/Comment/1/1 HTTP/1.1
Host: localhost:12345
Content-Type: text/plain
Content-Length: 4
test
It resulted in the following Status Code response: 415 Unsupported Media Type
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "00-e7ca54e9f313c24699c3ca4697b9363d-be4719bd10735245-00"
}
I then switched to Content-Type: application/json like the answer from @BjornBailleul says but got this error instead:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-0549e2c73842c249a93c8dc2f817e250-796e99fc0000224d-00",
"errors": {
"$": [
"'test' is an invalid JSON literal. Expected the literal 'true'. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
]
}
}
Got it working by also encapsulate the string in quotation marks like this: "test".
Complete working request:
POST /api/Comment/1/1 HTTP/1.1
Host: localhost:12345
Content-Type: application/json
Content-Length: 6
"test"
A: For forms, use the [FromForm] attribute instead of the [FromBody] attribute.
The below controller works with ASP.NET Core 1.1:
public class MyController : Controller
{
[HttpPost]
public async Task<IActionResult> Submit([FromForm] MyModel model)
{
//...
}
}
Note: [FromXxx] is required if your controller is annotated with [ApiController]. For normal view controllers it can be omitted.
A: Follow the below steps:
*
*Add to sending request header Content-Type field:
axios.post(`/Order/`, orderId,
{
headers: {'Content-Type': 'application/json'}
})
*Every data (simple or complex type) sent with axios should be placed without any extra brackets (axios.post('/Order/', orderId, ...)).
WARNING! There is one exception for string type - stringify it before send (axios.post('/Order/', JSON.stringify(address), ...)).
*Add method to controller:
[HttpPost]
public async Task<IActionResult> Post([FromBody]int orderId)
{
return Ok();
}
A: the problem can because of MVC MW.you must set formatterType in MVC options:
services.AddMvc(options =>
{
options.UseCustomStringModelBinder();
options.AllowEmptyInputInBodyModelBinding = true;
foreach (var formatter in options.InputFormatters)
{
if (formatter.GetType() == typeof(SystemTextJsonInputFormatter))
((SystemTextJsonInputFormatter)formatter).SupportedMediaTypes.Add(
Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain"));
}
}).AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
A: Another trap of note is making sure you're not decorating controllers with the Consume Attribute as below:
[Produces("application/json")]
[Consumes("application/json")]
public class MyController : Controller
This will fail with a 415 Unsupported Media Type if the upload is NOT JSON.
A "friend of mine" was recently caught out by this like so:
public class MyFileUploadController : MyCustomController {
}
[Produces("application/json")]
[Consumes("application/json")]
public class MyCustomController : ControllerBase {
}
A: You can use [FromBody] but you need to set the Content-Type header of your request to application/json, i.e.
Content-Type: application/json
A: First you need to specify in the Headers the Content-Type, for example, it can be application/json.
If you set application/json content type, then you need to send a json.
So in the body of your request you will send not form-data, not x-www-for-urlencoded but a raw json, for example {"Username": "user", "Password": "pass"}
You can adapt the example to various content types, including what you want to send.
You can use a tool like Postman or curl to play with this.
A: As addition of good answers, You don't have to use [FromForm] to get form data in controller. Framework automatically convert form data to model as you wish. You can implement like following.
[HttpPost]
public async Task<IActionResult> Submit(MyModel model)
{
//...
}
A: "HTTP 415 Unsupported Media Type response" stems from Content-Type in header of your request. for example in javascript by axios:
Axios({
method: 'post',
headers: { 'Content-Type': 'application/json'},
url: '/',
data: data, // an object u want to send
}).then(function (response) {
console.log(response);
});
A: In my case, I received the HTTP 415 Unsupported Media Type response, since I specified the content type to be TEXT and NOT JSON, so simply changing the type solved the issue.
Please check the solution in more detail in the following blog post:
https://www.howtodevelop.net/article/20/unsupported-media-type-415-in-aspnet-core-web-api
A: In my case, I had a method in my controller which was requiring an input parameter; unfortunately, the caller (an HttpClient) wasn't passing it.
Shame on me.
A: You must specify Encoding and Content Type, for instance:
var request = new HttpRequestMessage
{
Method = new HttpMethod("POST"),
RequestUri = new Uri(CombineUrl(_baseUrl, _resource))
};
request.Content = new StringContent(contentBody, System.Text.Encoding.UTF8, "application/json");
A: I copied a POST request & changed to GET in postman, then getting the 415 error.
the fix is to delete the key-value pair in Body, since this is a GET request.
A: ASP.NET Core : [FromBody] vs [FromForm]
That unsupported media type error is common when you are trying to send in form field data to ASP.NET via a POST but using one of its specialized WebAPI endpoint handlers that does not accept name-value pairs. [FromBody] is the problem and does not accept traditional HTML5 form field name-value pairs, but requires a JavaScript POST via JSON. Please read on...
Use [FromForm] for traditional HTML form post capture. It can be used to capture either a single form field value from the name-value pair (from the POST HTML data stored in the body of the Http Request) or all the field values in one batch. But you have to modify the WebAPI C# method for each.
In a traditional HTML Form field POST to the server, on submit, the browser sends all the name-value pairs of the form using the Http body of the Request sent to the server. So submitting the following HTML and changing its method to POST sends all your fields to the server as plain text:
<form id="form1" name="form1" method="post" action="https://localhost:44347/api/test/edit">
<input type="text" id="field1" name="field1" size="20" value="" /><br />
<input type="text" id="field2" name="field2" size="20" value="" /><br />
<input type="text" id="field3" name="field3" size="20" value="" /><br />
<!-- SEND POST as traditional Name-Value pair. -->
<button id="formbutton" name="formbutton" form="form1" value="submit">Form Submit (POST)</button>
</form>
To capture only one of the form field values in a ASP.NET WebAPI you can do the following using [FromForm]...
[HttpPost]
public string EditByPost([FromForm] string myfield1)
{
return "Success: " + myfield1;
}
...or you can capture all of the form fields as a set using a C# matching object...
[HttpPost]
public ActionResult EditByPost([FromForm] Form1 form)
{
// Here I am just returning the full set of form fields
// back as a JSON object.
return new JsonResult(form);
}
// Here is the C# Class I created that matches the HTML
// form fields being captured by [FormForm]:
public class Form1
{
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
}
The Strange Creature Called [FromBody]
[FromBody] is different. It breaks the traditional HTML form field POST that has worked the same for 20+ years and uses something different! It works much like [FromForm] does, but it is a new design, requiring JavaScript and its form data formatted in JSON with the JSON mime-type or "Content-Type" Http header in the Request that is sent to the server. It is also sent via the Http POST inside the body or payload section of the Request, but formatted as JSON with the 'application/json' Content-type, telling your ASP.NET WebAPI Core endpoint method to parse JSON objects, not traditional HTML form name-value pairs.
Because regular HTML4/HTML5 forms cannot POST JSON or its content-type, you must use JavaScript tricks plus decorate your attribute in C# with [FromBody] to do that. This is what confuses people using regular HTML.
The example below is now listening for JSON form data, not name-value pairs. It's not obvious it is doing that as it looks the same as the [FromForm] version...
[HttpPost]
public ActionResult EditByPost([FromBody] Form1 form)
{
return new JsonResult(form);
}
To post form field data with JSON to the [FromBody] WebAPI above, you have to use JavaScript and extract out the form fields from the HTML manually, then send them with the JSON data and JSON content-type to the server. Most modern JavaScript APIs just bypass HTML and store and send raw JSON data to the listening WebAPI POST now.
Below, I am using a new ECMAScript/JavaScript trick to extract out the same HTML form field values used above. I then call a Promise Object (wrapped by fetch) using async-await, manually add the right JSON header content-type for the listening server, then POST this new form data package directly to the server, bypassing HTML. This might be added to the HTML submit button above as a function to shut down the HTML submit process and use JavaScript instead:
async function JavaScriptPOST() {
var form = document.getElementById('form1');
var myfield1 = form.querySelector('#field1').value;
var myfield2 = form.querySelector('#field2').value;
var myfield3 = form.querySelector('#field3').value;
const response = await fetch('https://example.com/editbypost',
{
method: 'POST',
body: JSON.stringify({
field1: myfield1,
field2: myfield2,
field2: myfield3
}),
headers: {
'Content-type':'application/json; charset=UTF-8',
}
}).then(...);
}
Realize one thing...HTML is still the dominant technology around the world. Most HTML forms still post data using traditional POST name-value techniques. JavaScript tricks like this are becoming the new norm, but they do not replace the original HTML form technology and will not via scripting alone.
But knowing how the older technology works always helps when these tech vendors rewrite the technology stack from how it has always worked for decades and decades. Sadly, instead of making it easier or faster or intuitive for developers, they just end up confusing people like this poster.
|
stackoverflow
|
{
"language": "en",
"length": 1719,
"provenance": "stackexchange_0000F.jsonl.gz:863773",
"question_score": "316",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538772"
}
|
0532b2e9272fe4e1089216c521509bf3b2b49b6d
|
Stackoverflow Stackexchange
Q: ruby set isn't unique For some reason the following code produce a set with duplicate values.
I'm not sure how uniqueness of an array in ruby is defined so maybe this is somehow expectable?
require 'set'
xs = [1, 2, 3]
xss = Set.new []
xs.each do |x|
xss.merge xss.to_a.map{|xs| xs.push x}
xss.add [x]
p xss
end
will prints
#<Set: {[1]}>
#<Set: {[1, 2], [1, 2], [2]}>
#<Set: {[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [1, 2, 3, 3], [2, 3], [3]}>
What's wrong?
EDIT
change xs.push x to xs + [x] will fix it.
A: You are effectively altering the objects within the set, which is not allowed.
From the documentation:
Set assumes that the identity of each element does not change while it is stored. Modifying an element of a set will render the set to an unreliable state.
Regarding your comment
I want #<Set: {[1], [1, 2], [2], [1, 3], [1, 2, 3], [2, 3], [3]}>
You could use Array#combination:
a = [1, 2, 3]
(1..a.size).flat_map { |n| a.combination(n).to_a }
#=> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
|
Q: ruby set isn't unique For some reason the following code produce a set with duplicate values.
I'm not sure how uniqueness of an array in ruby is defined so maybe this is somehow expectable?
require 'set'
xs = [1, 2, 3]
xss = Set.new []
xs.each do |x|
xss.merge xss.to_a.map{|xs| xs.push x}
xss.add [x]
p xss
end
will prints
#<Set: {[1]}>
#<Set: {[1, 2], [1, 2], [2]}>
#<Set: {[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [1, 2, 3, 3], [2, 3], [3]}>
What's wrong?
EDIT
change xs.push x to xs + [x] will fix it.
A: You are effectively altering the objects within the set, which is not allowed.
From the documentation:
Set assumes that the identity of each element does not change while it is stored. Modifying an element of a set will render the set to an unreliable state.
Regarding your comment
I want #<Set: {[1], [1, 2], [2], [1, 3], [1, 2, 3], [2, 3], [3]}>
You could use Array#combination:
a = [1, 2, 3]
(1..a.size).flat_map { |n| a.combination(n).to_a }
#=> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
|
stackoverflow
|
{
"language": "en",
"length": 190,
"provenance": "stackexchange_0000F.jsonl.gz:863803",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538881"
}
|
9fe5b4583e74e6232c8f4307ff34784996dd8103
|
Stackoverflow Stackexchange
Q: Angular 2 test: load AppComponent first We have, in the constructor of AppComponent, a function that loads some variables and sets them in the environment.ts file. But our tests fail because it uses those variables and run individually and it doesn't load AppComponent which sets them.
Is there a way to make AppComponent load/construct before a test runs?
A: If you would like to run code before the test, you should put it in a beforeAll code.
I don't undarstand why would you change the static configuration from app component, it sounds wrong.
The configuration is either static, then it will be set in environment file and won't change, or it's dynamic, then you should create a service, which you can read from easily, and test properly...
|
Q: Angular 2 test: load AppComponent first We have, in the constructor of AppComponent, a function that loads some variables and sets them in the environment.ts file. But our tests fail because it uses those variables and run individually and it doesn't load AppComponent which sets them.
Is there a way to make AppComponent load/construct before a test runs?
A: If you would like to run code before the test, you should put it in a beforeAll code.
I don't undarstand why would you change the static configuration from app component, it sounds wrong.
The configuration is either static, then it will be set in environment file and won't change, or it's dynamic, then you should create a service, which you can read from easily, and test properly...
|
stackoverflow
|
{
"language": "en",
"length": 128,
"provenance": "stackexchange_0000F.jsonl.gz:863833",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44538971"
}
|
04239921d9bec6ff04dd8b2c3574bb39361bc1ae
|
Stackoverflow Stackexchange
Q: Django `TransactionTestCase` test cases with AWS RDS are very slow I am trying to set up Django tests to use AWS RDS as a Postgres database backnend (tests are executed on Heroku CI which does not allow you create and destroy test databases). The tests are running, but test cases that use TransactionTestCase are extremely slow (sometimes up to a minute compared to a fraction of a second when not using RDS). I am using RDS in the same region as my Heroku deployment (EU/Ireland) and test cases based on TestCase class run as usual.
Any ideas what could be causing this?
A: TransactionTestCase is very slow compared to TestCase. I have started inheriting from TestCase and then putting each block of celery and db calls inside a transaction.atomic(): block, and doing my queries and asserts outside that block. You get the speed of a TestCase.
Example:
with transaction.atomic():
Foo.objects.create(...)
Bar.objects.get_or_create(...)
self.assertEqual(Foo.objects.count(), 1)
self.assertTrue(Bar.objects.first().trueproperty)
|
Q: Django `TransactionTestCase` test cases with AWS RDS are very slow I am trying to set up Django tests to use AWS RDS as a Postgres database backnend (tests are executed on Heroku CI which does not allow you create and destroy test databases). The tests are running, but test cases that use TransactionTestCase are extremely slow (sometimes up to a minute compared to a fraction of a second when not using RDS). I am using RDS in the same region as my Heroku deployment (EU/Ireland) and test cases based on TestCase class run as usual.
Any ideas what could be causing this?
A: TransactionTestCase is very slow compared to TestCase. I have started inheriting from TestCase and then putting each block of celery and db calls inside a transaction.atomic(): block, and doing my queries and asserts outside that block. You get the speed of a TestCase.
Example:
with transaction.atomic():
Foo.objects.create(...)
Bar.objects.get_or_create(...)
self.assertEqual(Foo.objects.count(), 1)
self.assertTrue(Bar.objects.first().trueproperty)
|
stackoverflow
|
{
"language": "en",
"length": 155,
"provenance": "stackexchange_0000F.jsonl.gz:863934",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539308"
}
|
bb41961537b236e1d6e2a857332995bcc2788930
|
Stackoverflow Stackexchange
Q: Indirect modification of overloaded element of Illuminate\Support\Collection has no effect im quite new in laravel framework, and im from codeigniter.
I would like to add new key and value from database
static function m_get_promotion_banner(){
$query = DB::table("promotion_banner")
->select('promotion_banner_id','promotion_link','about_promotion')
->where('promotion_active','1')
->get();
if($query != null){
foreach ($query as $key => $row){
$query[$key]['promotion_image'] = URL::to('home/image/banner/'.$row['promotion_banner_id']);
}
}
return $query;
}
that code was just changed from codeigniter to laravel, since in codeigniter there are no problem in passing a new key and value in foreach statement
but when i tried it in laravel i got this following error :
Indirect modification of overloaded element of Illuminate\Support\Collection has no effect
at HandleExceptions->handleError(8, 'Indirect modification of overloaded element of Illuminate\Support\Collection has no effect', 'C:\xampp\htdocs\laravel-site\application\app\models\main\Main_home_m.php', 653, array('query' => object(Collection), 'row' => array('promotion_banner_id' => 1, 'promotion_link' => 'http://localhost/deal/home/voucher', 'about_promotion' => ''), 'key' => 0))
please guide me how to fix this
thank you (:
A: For others who needs a solution you can use jsonserialize method to modify the collection.
Such as:
$data = $data->jsonserialize();
//do your changes here now.
|
Q: Indirect modification of overloaded element of Illuminate\Support\Collection has no effect im quite new in laravel framework, and im from codeigniter.
I would like to add new key and value from database
static function m_get_promotion_banner(){
$query = DB::table("promotion_banner")
->select('promotion_banner_id','promotion_link','about_promotion')
->where('promotion_active','1')
->get();
if($query != null){
foreach ($query as $key => $row){
$query[$key]['promotion_image'] = URL::to('home/image/banner/'.$row['promotion_banner_id']);
}
}
return $query;
}
that code was just changed from codeigniter to laravel, since in codeigniter there are no problem in passing a new key and value in foreach statement
but when i tried it in laravel i got this following error :
Indirect modification of overloaded element of Illuminate\Support\Collection has no effect
at HandleExceptions->handleError(8, 'Indirect modification of overloaded element of Illuminate\Support\Collection has no effect', 'C:\xampp\htdocs\laravel-site\application\app\models\main\Main_home_m.php', 653, array('query' => object(Collection), 'row' => array('promotion_banner_id' => 1, 'promotion_link' => 'http://localhost/deal/home/voucher', 'about_promotion' => ''), 'key' => 0))
please guide me how to fix this
thank you (:
A: For others who needs a solution you can use jsonserialize method to modify the collection.
Such as:
$data = $data->jsonserialize();
//do your changes here now.
A: The result of a Laravel query will always be a Collection. To add a property to all the objects in this collection, you can use the map function.
$query = $query->map(function ($object) {
// Add the new property
$object->promotion_image = URL::to('home/image/banner/' . $object->promotion_banner_id);
// Return the new object
return $object;
});
Also, you can get and set the properties using actual object properties and not array keys. This makes the code much more readable in my opinion.
A: The problem is the get is returning a collection of stdObject
Instead of adding the new field to the result of your query, modify the model of what you are returning.
So, assuming you have a PromotionBanner.php model file in your app directory, edit it and then add these 2 blocks of code:
protected $appends = array('promotionImage');
here you just added the custom field. Now you tell the model how to fill it:
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
Now, you get your banners through your model:
static function m_get_promotion_banner(){
return \App\PromotionBanner::where('promotion_active','1')->get();
}
Now you can access your promotionImage propierty in your result
P.D:
In the case you are NOT using a model... Well, just create the file app\PromotionImage.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PromotionImage extends Model
{
protected $appends = array('imageAttribute');
protected $table = 'promotion_banner';
public function getPromotionImageAttribute() {
return (url('home/image/banner/'.$this->promotion_banner_id));
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'promotion_banner_id','promotion_link','about_promotion','promotion_active'
];
A: just improving, in case you need to pass data inside the query
$url = 'home/image/banner/';
$query = $query->map(function ($object) use ($url) {
// Add the new property
$object->promotion_image = URL::to( $url . $object->promotion_banner_id);
// Return the new object
return $object;
});
A: I've been struggling with this all evening, and I'm still not sure what my problem is.
I've used ->get() to actually execute the query, and I've tried by ->toArray() and ->jsonserialize() on the data and it didn't fix the problem.
In the end, the work-around I found was this:
$task = Tasks::where("user_id", $userId)->first()->toArray();
$task = json_decode(json_encode($task), true);
$task["foo"] = "bar";
Using json_encode and then json_decode on it again freed it up from whatever was keeping me from editing it.
That's a hacky work-around at best, but if anyone else just needs to push past this problem and get on with their work, this might solve the problem for you.
|
stackoverflow
|
{
"language": "en",
"length": 569,
"provenance": "stackexchange_0000F.jsonl.gz:863962",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539395"
}
|
0f1ddddb6c6ade8996fe8c0da22a9964a33c8ee1
|
Stackoverflow Stackexchange
Q: Google Drive API - sharing 'appDataFolder' Is it possible to share folders that are inside Google drive 'Application Data' directory?
I've saw quite a few similar questions on SO, but none with the answer.
|
Q: Google Drive API - sharing 'appDataFolder' Is it possible to share folders that are inside Google drive 'Application Data' directory?
I've saw quite a few similar questions on SO, but none with the answer.
|
stackoverflow
|
{
"language": "en",
"length": 35,
"provenance": "stackexchange_0000F.jsonl.gz:863977",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539448"
}
|
d6d71f1e1cd0472dc32cfdb231674c09b04d26c9
|
Stackoverflow Stackexchange
Q: ASP.NET Entity Framework Code First Migration process between environments I'm working in a team of four developers and we sometimes run into issues with EF Code First Migrations between different branches and releasing to staging from dev. We are using git.
What is the best process flow to follow between:
*
*Devs working on different branches/features and eventually merging changes without loosing any migrations created in these branches/features.
*Releasing to staging/live.
A: *
*Read this MSDN article that addresses issues related to EF Code First Migrations in team environments.
*There are a lot of branching strategies available out there, you could explore them and use the one that best suits your needs. Have a look at git-flow, which is one of the branching models for Git.
|
Q: ASP.NET Entity Framework Code First Migration process between environments I'm working in a team of four developers and we sometimes run into issues with EF Code First Migrations between different branches and releasing to staging from dev. We are using git.
What is the best process flow to follow between:
*
*Devs working on different branches/features and eventually merging changes without loosing any migrations created in these branches/features.
*Releasing to staging/live.
A: *
*Read this MSDN article that addresses issues related to EF Code First Migrations in team environments.
*There are a lot of branching strategies available out there, you could explore them and use the one that best suits your needs. Have a look at git-flow, which is one of the branching models for Git.
|
stackoverflow
|
{
"language": "en",
"length": 127,
"provenance": "stackexchange_0000F.jsonl.gz:863978",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539453"
}
|
755d5e4a1968ac45910775d93c6456b8b7d709a6
|
Stackoverflow Stackexchange
Q: Spring @JmsListener is not able to convert json into object I was expecting @JmsListener will automatically convert json object into my object, but its payload is returning the data as string in json format rather than actual object.
@JmsListener(destination = "${default-queue-name-to-listen}")
public void receiveMessage(final Message<MyObject> message) throws JMSException {
logger.info("message received from the queue/topic : {}", message);
MyObject response = message.getPayload();
}
But we receive response in a String format like this: {"id":"1","name":"2222"}
And this is failing it at runtime.
My other piece of code is:
@Bean
public JmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) throws URLSyntaxException {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setSubscriptionDurable(true);
factory.setPubSubDomain(true);
return factory;
}
A: It depends on what the producer sent.
If a TextMessage was sent, you get a String. If an ObjectMessage sent, you can get an Object.
|
Q: Spring @JmsListener is not able to convert json into object I was expecting @JmsListener will automatically convert json object into my object, but its payload is returning the data as string in json format rather than actual object.
@JmsListener(destination = "${default-queue-name-to-listen}")
public void receiveMessage(final Message<MyObject> message) throws JMSException {
logger.info("message received from the queue/topic : {}", message);
MyObject response = message.getPayload();
}
But we receive response in a String format like this: {"id":"1","name":"2222"}
And this is failing it at runtime.
My other piece of code is:
@Bean
public JmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) throws URLSyntaxException {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setSubscriptionDurable(true);
factory.setPubSubDomain(true);
return factory;
}
A: It depends on what the producer sent.
If a TextMessage was sent, you get a String. If an ObjectMessage sent, you can get an Object.
|
stackoverflow
|
{
"language": "en",
"length": 132,
"provenance": "stackexchange_0000F.jsonl.gz:864020",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539599"
}
|
35c9ccbb97295fa8d18ce158505486b692677f76
|
Stackoverflow Stackexchange
Q: Query Performance: single column vs multiple column Which table structure is better among below 2?
OR
in first query i use LIKE operator in query.
In second i use AND operator.
Does first table design has any advantages over second on selecting data?
On what situation i need to decide between first table structure and second one?
A: Second table obviously have advantages over first. If you have to query type or currency from first table, you might have to use right, left or any other functions.
Also if you align keys/constraints for second table, follows 2nd normal form.
|
Q: Query Performance: single column vs multiple column Which table structure is better among below 2?
OR
in first query i use LIKE operator in query.
In second i use AND operator.
Does first table design has any advantages over second on selecting data?
On what situation i need to decide between first table structure and second one?
A: Second table obviously have advantages over first. If you have to query type or currency from first table, you might have to use right, left or any other functions.
Also if you align keys/constraints for second table, follows 2nd normal form.
A: The first one would be better if you never needed to work with the Type or the Currency attributes in any way and you used allways only the whole text stored as MEASUREMENT_NAME.
If you plan to work with the values of the Type or the Currency attributes separately, like using their values in where conditions etc., the second option will allways be a better choice.
You can also eventually create a combined structure containing both the whole text MEASUREMENT_NAME and separated values Type & Currency for filtering purposes. This would take more space on disk and would not be optimized, but the whole text or MEASUREMENT_NAME can in the future also eventually contain atributes that are now unknown to you. That could be the reason for storing MEASUREMENT_NAME in the raw format.
In case that the attribute MEASUREMENT_NAME is not something you get from external sources, but it is a data structure made by yourself and you seek a way how to store records with flexible (changing) structure, you better store it as JSON or XML data, Oracle has built in functions for JSON data.
I also recommend to use linked tables for Type or Currency values, so that the main table contains only ID link as a foreign key.
|
stackoverflow
|
{
"language": "en",
"length": 312,
"provenance": "stackexchange_0000F.jsonl.gz:864026",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539615"
}
|
64ce0e877e5c4e6ddab718bd69ef1ca42958ef36
|
Stackoverflow Stackexchange
Q: Oracle - Create an index only if not exists Is there any way to create indexes in oracle only if they don't exists ?
Something like
CREATE INDEX IF NOT EXISTS ord_customer_ix
ON orders (customer_id);
A: CREATE INDEX IN ORACLE IF NOT EXISTS.
ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG;
DECLARE
INDEX_EXISTS NUMBER;
BEGIN
SELECT COUNT(1)
INTO INDEX_EXISTS
FROM ALL_INDEXES AI,
ALL_IND_COLUMNS AIC
WHERE AI.TABLE_OWNER = 'PROD_INTG'
AND AI.TABLE_NAME = 'PROCESS_APPLICATION'
AND AI.INDEX_NAME = AIC.INDEX_NAME
AND AI.OWNER = AIC.INDEX_OWNER
AND AIC.COLUMN_NAME IN ('PST_CODE', 'PIZ_TYPE_ID');
IF (INDEX_EXISTS) > 0
THEN
DBMS_OUTPUT.PUT_LINE('INDEX EXISTS :');
ELSE
EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG';
EXECUTE IMMEDIATE 'CREATE INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ
ON PROD_INTG.PROCESS_APPLICATION (PST_CODE, PIZ_TYPE_ID) PARALLEL 16';
EXECUTE IMMEDIATE 'ALTER INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ NOPARALLEL';
DBMS_OUTPUT.PUT_LINE('INDEX created :');
END IF;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE IN (-2275, -955, -02431, -01430, -01451, -01408)
THEN
NULL;
ELSE
RAISE;
END IF;
END;
/
|
Q: Oracle - Create an index only if not exists Is there any way to create indexes in oracle only if they don't exists ?
Something like
CREATE INDEX IF NOT EXISTS ord_customer_ix
ON orders (customer_id);
A: CREATE INDEX IN ORACLE IF NOT EXISTS.
ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG;
DECLARE
INDEX_EXISTS NUMBER;
BEGIN
SELECT COUNT(1)
INTO INDEX_EXISTS
FROM ALL_INDEXES AI,
ALL_IND_COLUMNS AIC
WHERE AI.TABLE_OWNER = 'PROD_INTG'
AND AI.TABLE_NAME = 'PROCESS_APPLICATION'
AND AI.INDEX_NAME = AIC.INDEX_NAME
AND AI.OWNER = AIC.INDEX_OWNER
AND AIC.COLUMN_NAME IN ('PST_CODE', 'PIZ_TYPE_ID');
IF (INDEX_EXISTS) > 0
THEN
DBMS_OUTPUT.PUT_LINE('INDEX EXISTS :');
ELSE
EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG';
EXECUTE IMMEDIATE 'CREATE INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ
ON PROD_INTG.PROCESS_APPLICATION (PST_CODE, PIZ_TYPE_ID) PARALLEL 16';
EXECUTE IMMEDIATE 'ALTER INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ NOPARALLEL';
DBMS_OUTPUT.PUT_LINE('INDEX created :');
END IF;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE IN (-2275, -955, -02431, -01430, -01451, -01408)
THEN
NULL;
ELSE
RAISE;
END IF;
END;
/
A: Add an index only if not exists:
declare
already_exists exception;
columns_indexed exception;
pragma exception_init( already_exists, -955 );
pragma exception_init(columns_indexed, -1408);
begin
execute immediate 'create index ord_customer_ix on orders (customer_id)';
dbms_output.put_line( 'created' );
exception
when already_exists or columns_indexed then
dbms_output.put_line( 'skipped' );
end;
A: A script can be used to drop the index if it exists, then create it. With error checking on the drop if exists:
BEGIN
EXECUTE IMMEDIATE 'DROP INDEX ord_customer_ix';
EXCEPTION
WHEN OTHERS
THEN
IF SQLCODE != -955
THEN -- ORA-00955 index does not exist
RAISE;
END IF;
END;
/
CREATE INDEX ord_customer_ix
ON orders (customer_id);
;
This is pretty straight-forward and easy to code and understand.
|
stackoverflow
|
{
"language": "en",
"length": 254,
"provenance": "stackexchange_0000F.jsonl.gz:864040",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539663"
}
|
bf364d236e38c03d739f7352e0724bc71cf34623
|
Stackoverflow Stackexchange
Q: Exclude paths with duplicated nodes In my flight modelization, I would like to search for path with 1 stop which is equivalent in the graph to have a 4 hops relationships from the source to the destination. When searching the path with :
match (s:Airport{airportName:'CAN'}),
(d:Airport{airportName:'ICN'})
with s,d
match p = (s)<-[*4]->(d)
return nodes(p), relationships(p)
But this also give me path with airport node that are visited twice, like this : airport node
So my question is, how to exclude paths which contains duplicated nodes ?
How to detect whether there is a duplicated node within a path ?
Thank you !
A: If you have access to APOC Procedures, you can try using apoc.algo.allSimplePaths(), which will not contain any loops back to a previously visited node in the path.
match (s:Airport{airportName:'CAN'}),
(d:Airport{airportName:'ICN'})
call apoc.algo.allSimplePaths(s, d, '', 4) yield path
return nodes(path), relationships(path)
|
Q: Exclude paths with duplicated nodes In my flight modelization, I would like to search for path with 1 stop which is equivalent in the graph to have a 4 hops relationships from the source to the destination. When searching the path with :
match (s:Airport{airportName:'CAN'}),
(d:Airport{airportName:'ICN'})
with s,d
match p = (s)<-[*4]->(d)
return nodes(p), relationships(p)
But this also give me path with airport node that are visited twice, like this : airport node
So my question is, how to exclude paths which contains duplicated nodes ?
How to detect whether there is a duplicated node within a path ?
Thank you !
A: If you have access to APOC Procedures, you can try using apoc.algo.allSimplePaths(), which will not contain any loops back to a previously visited node in the path.
match (s:Airport{airportName:'CAN'}),
(d:Airport{airportName:'ICN'})
call apoc.algo.allSimplePaths(s, d, '', 4) yield path
return nodes(path), relationships(path)
|
stackoverflow
|
{
"language": "en",
"length": 144,
"provenance": "stackexchange_0000F.jsonl.gz:864041",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539664"
}
|
a37a09ca34b279a10acc8d7f2a9e8b514749e9bf
|
Stackoverflow Stackexchange
Q: Eureka - StepperRow - How do I only show the integer number on label I would like to show only Integer numbers on the StepperRow.
That is what my initialisation looks like:
StepperRow()
{
$0.title = "Integer"
$0.tag = "integer"
$0.value = 0
}.cellSetup
{ cell, row in
cell.stepper.minimumValue = 0
}
It looks like this now:
A: Use onChange callback to update your label and force the text of the cell to have integer Value
This is the code
<<< StepperRow().cellSetup({ (cell, row) in
row.title = "Integer"
row.tag = "integer"
row.value = 0
cell.valueLabel.text = "\(Int(row.value!))"
}).cellUpdate({ (cell, row) in
if(row.value != nil)
{
cell.valueLabel.text = "\(Int(row.value!))"
}
}).onChange({ (row) in
if(row.value != nil)
{
row.cell.valueLabel.text = "\(Int(row.value!))"
}
})
It works, was tested
I hope this helps
|
Q: Eureka - StepperRow - How do I only show the integer number on label I would like to show only Integer numbers on the StepperRow.
That is what my initialisation looks like:
StepperRow()
{
$0.title = "Integer"
$0.tag = "integer"
$0.value = 0
}.cellSetup
{ cell, row in
cell.stepper.minimumValue = 0
}
It looks like this now:
A: Use onChange callback to update your label and force the text of the cell to have integer Value
This is the code
<<< StepperRow().cellSetup({ (cell, row) in
row.title = "Integer"
row.tag = "integer"
row.value = 0
cell.valueLabel.text = "\(Int(row.value!))"
}).cellUpdate({ (cell, row) in
if(row.value != nil)
{
cell.valueLabel.text = "\(Int(row.value!))"
}
}).onChange({ (row) in
if(row.value != nil)
{
row.cell.valueLabel.text = "\(Int(row.value!))"
}
})
It works, was tested
I hope this helps
|
stackoverflow
|
{
"language": "en",
"length": 130,
"provenance": "stackexchange_0000F.jsonl.gz:864042",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539665"
}
|
bfa1a910af3304b823d1ce3419ea3f9a770ad381
|
Stackoverflow Stackexchange
Q: What is an idiomatic way to have shared utility functions for integration tests and benchmarks? I have Rust project with both integration tests (in the /tests dir) and benchmarks (in the /benches dir). There are a couple of utility functions that I need in tests and benches, but they aren't related to my crate itself, so I can't just put them in the /utils dir.
What is idiomatic way to handle this situation?
A: You could add those utility-functions to a pub-module inside your main crate and use the #[doc(hidden)] or #![doc(hidden)] attribute to hide them from the docs-generator. Extra comments will guide the reader to why they are there.
|
Q: What is an idiomatic way to have shared utility functions for integration tests and benchmarks? I have Rust project with both integration tests (in the /tests dir) and benchmarks (in the /benches dir). There are a couple of utility functions that I need in tests and benches, but they aren't related to my crate itself, so I can't just put them in the /utils dir.
What is idiomatic way to handle this situation?
A: You could add those utility-functions to a pub-module inside your main crate and use the #[doc(hidden)] or #![doc(hidden)] attribute to hide them from the docs-generator. Extra comments will guide the reader to why they are there.
A: Create a shared crate (preferred)
As stated in the comments, create a new crate. You don't have to publish the crate to crates.io. Just keep it as a local unpublished crate inside your project and mark it as a development-only dependency.
This is best used with version 2 of the Cargo resolver. For better performance, consider using a Cargo workspace.
.
├── Cargo.toml
├── src
│ └── lib.rs
├── tests
│ └── integration.rs
└── utilities
├── Cargo.toml
└── src
└── lib.rs
Cargo.toml
# ...
[dev-dependencies]
utilities = { path = "utilities" }
utilities/src/lib.rs
pub fn shared_code() {
println!("I am shared code");
}
tests/integration.rs
extern crate utilities;
#[test]
fn a_test() {
utilities::shared_code();
}
A test-only module
You could place a module inside your crate that is only compiled when a specific feature is passed. This is the same concept used for unit tests. This has the advantage that it can access internals of your library code. It has the disadvantage that you need to pass the flag each time you run the code.
This is best used with version 2 of the Cargo resolver.
Cargo.toml
# ...
[features]
test-utilities = []
src/lib.rs
#[cfg(feature = "test-utilities")]
pub mod test_utilities {
pub fn shared_code() {
println!("I'm inside the library")
}
}
tests/integration.rs
extern crate the_library;
#[test]
fn a_test() {
the_library::test_utilities::shared_code();
}
execution
cargo test --features=test-utilities
This is best used with version 2 of the Cargo resolver.
Use a module from an arbitrary file path
This is just ugly to me, and really goes out of the normal path.
utilities.rs
pub fn shared_code() {
println!("This is just sitting out there");
}
tests/integration.rs
#[path = "../utilities.rs"]
mod utilities;
#[test]
fn a_test() {
utilities::shared_code();
}
See also:
*
*Where should I put test utility functions in Rust?
A: Whilst this doesn't help for benchmarks, I came here looking for a way to do this with multiple integration tests, and later found that you can do the following for integration tests:
Modules with common code follow the ordinary modules rules, so it's ok to create common module as tests/common/mod.rs.
Source: https://doc.rust-lang.org/rust-by-example/testing/integration_testing.html
|
stackoverflow
|
{
"language": "en",
"length": 456,
"provenance": "stackexchange_0000F.jsonl.gz:864058",
"question_score": "28",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539729"
}
|
4969834fb03085bbd663657123b9583c0ba29048
|
Stackoverflow Stackexchange
Q: How to convert number (int or float64) to string in Golang How do I convert any given number which can be a int or float64 to string ?
Using strconv.FormatFloat or FormatInt I have to specify that the given number is a float or integer.
In my case it is unknown what I get.
Behaviour:
When I get a 5 it should be converted into "5" and not "5.00"
When I get a 1.23 it should be converted into "1.23" and not "1"
A: If you don't know what type the number you need to convert to string will be, you can just use fmt.Sprintf with the %v verb:
fmt.Sprintf("%v", 1.23) // "1.23"
fmt.Sprintf("%v", 5) // "5"
|
Q: How to convert number (int or float64) to string in Golang How do I convert any given number which can be a int or float64 to string ?
Using strconv.FormatFloat or FormatInt I have to specify that the given number is a float or integer.
In my case it is unknown what I get.
Behaviour:
When I get a 5 it should be converted into "5" and not "5.00"
When I get a 1.23 it should be converted into "1.23" and not "1"
A: If you don't know what type the number you need to convert to string will be, you can just use fmt.Sprintf with the %v verb:
fmt.Sprintf("%v", 1.23) // "1.23"
fmt.Sprintf("%v", 5) // "5"
A: You may use fmt.Sprint
fmt.Sprint returns string format of any variable passed to it
Sample
package main
import (
"fmt"
)
func main() {
f := fmt.Sprint(5.03)
i := fmt.Sprint(5)
fmt.Println("float:",f,"\nint:",i)
}
play link
|
stackoverflow
|
{
"language": "en",
"length": 153,
"provenance": "stackexchange_0000F.jsonl.gz:864074",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539789"
}
|
3ecb5f34dde7d33155301da7a4531c4597fcafbe
|
Stackoverflow Stackexchange
Q: Textarea with defaultValue not updating Hey I've got a problem with changing the content of a textarea.
This is my textarea
<textarea
className="fixedTextArea"
defaultValue={this.props.predefValueSets[this.props.selection].values}
onChange={(event) => this.changeHandle(event)}
/>
Now when this.props.selection changes I want to have the content of the textarea to change as well.
I can't use value instead of defaultValue, because my textarea has to be editable.
When I look in the browser and inspect my textarea I see, how the content changes, but they aren't reflected.
Any idea how to handle this?
A: The solution that fits best for me atm is to use <div> instead of <textarea>.
I am using:
<div
className="fixedTextArea"
contentEditable
suppressContentEditableWarning>
{this.props.predefValueSets[this.props.selection].values}
</div>
This took an easy way to manage onChange(...) (cause a <div> doesn't fire onChange-Events), but that isn't important in my specific case.
|
Q: Textarea with defaultValue not updating Hey I've got a problem with changing the content of a textarea.
This is my textarea
<textarea
className="fixedTextArea"
defaultValue={this.props.predefValueSets[this.props.selection].values}
onChange={(event) => this.changeHandle(event)}
/>
Now when this.props.selection changes I want to have the content of the textarea to change as well.
I can't use value instead of defaultValue, because my textarea has to be editable.
When I look in the browser and inspect my textarea I see, how the content changes, but they aren't reflected.
Any idea how to handle this?
A: The solution that fits best for me atm is to use <div> instead of <textarea>.
I am using:
<div
className="fixedTextArea"
contentEditable
suppressContentEditableWarning>
{this.props.predefValueSets[this.props.selection].values}
</div>
This took an easy way to manage onChange(...) (cause a <div> doesn't fire onChange-Events), but that isn't important in my specific case.
A: use ref
<textarea
className="fixedTextArea"
ref="fixedTextArea"
defaultValue={this.props.predefValueSets[this.props.selection].values}
onChange={(event) => this.changeHandle(event)}
/>
everytime the value changes, update the text area.
changeHandle(value){
this.refs.fixedTextArea.value = value
}
|
stackoverflow
|
{
"language": "en",
"length": 157,
"provenance": "stackexchange_0000F.jsonl.gz:864087",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539833"
}
|
7573bd4bb8962de17af1a8fd714d43b8a36f1f64
|
Stackoverflow Stackexchange
Q: How to convert ByteArray to String with specified charset in Kotlin I found there is a ByteArray.toString(charset:Charset) function in Kotlin,when I use that function in android studio IDE,it gets a syntax error. But I have tried the same code in Kotlin org site, it works well. How can I convert a ByteArray to String in Kotlin?
A: It seems that you didn't configure your project for Kotlin (there is no kotlin-runtime.jar in your classpath). Try to select the line with the error, press Alt+Enter and in context menu choose "Kotlin not configured" -> "Configure"
Or manually add kotlin-runtime.jar to your classpath
|
Q: How to convert ByteArray to String with specified charset in Kotlin I found there is a ByteArray.toString(charset:Charset) function in Kotlin,when I use that function in android studio IDE,it gets a syntax error. But I have tried the same code in Kotlin org site, it works well. How can I convert a ByteArray to String in Kotlin?
A: It seems that you didn't configure your project for Kotlin (there is no kotlin-runtime.jar in your classpath). Try to select the line with the error, press Alt+Enter and in context menu choose "Kotlin not configured" -> "Configure"
Or manually add kotlin-runtime.jar to your classpath
|
stackoverflow
|
{
"language": "en",
"length": 102,
"provenance": "stackexchange_0000F.jsonl.gz:864092",
"question_score": "9",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44539851"
}
|
ced877d598be80ba60f2d3ec0a111e0599eb9078
|
Stackoverflow Stackexchange
Q: Click from controller HTML Ionic 2 How i can run function from string in controller in Ionic 2. My code:
export class ProjectsPage {
text:string = '' ;
constructor() {
this.text = '<a (click)="myAlert()">Show allert</a>' ;
}
myAlert() {
alert(1) ;
}
}
A: You can do this by using DomSanitizationService. Import the service
import {DomSanitizationService} from '@angular/platform-browser';
Now, in class constructor do this
constructor(sanitizer: DomSanitizationService) {
this.text = '<a (click)="myAlert()">Show allert</a>' ;
this.text = sanitizer.bypassSecurityTrustHtml(this.text);
}
Use like this in template
<div [innerHTML]="text"></div> // here the DOM will be appended
Have a look at this answer to follow up the updates in the release versions and imports
|
Q: Click from controller HTML Ionic 2 How i can run function from string in controller in Ionic 2. My code:
export class ProjectsPage {
text:string = '' ;
constructor() {
this.text = '<a (click)="myAlert()">Show allert</a>' ;
}
myAlert() {
alert(1) ;
}
}
A: You can do this by using DomSanitizationService. Import the service
import {DomSanitizationService} from '@angular/platform-browser';
Now, in class constructor do this
constructor(sanitizer: DomSanitizationService) {
this.text = '<a (click)="myAlert()">Show allert</a>' ;
this.text = sanitizer.bypassSecurityTrustHtml(this.text);
}
Use like this in template
<div [innerHTML]="text"></div> // here the DOM will be appended
Have a look at this answer to follow up the updates in the release versions and imports
A: I can only guess what you are asking for, but your mistake is most likely caused by passing string in (click) function. Change is to:
this.text = '<a (click)="'+this.myAlert()+'">Show allert</a>' ;
This should do the trick.
|
stackoverflow
|
{
"language": "en",
"length": 146,
"provenance": "stackexchange_0000F.jsonl.gz:864146",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540013"
}
|
e01411bcc8a297d77aac55e1df34bd2a8a480449
|
Stackoverflow Stackexchange
Q: Java 8 stream - merge collections of objects sharing the same Id I have a collection of invoices :
class Invoice {
int month;
BigDecimal amount
}
I'd like to merge these invoices, so I get one invoice per month, and the amount is the sum of the invoices amount for this month.
For example:
invoice 1 : {month:1,amount:1000}
invoice 2 : {month:1,amount:300}
invoice 3 : {month:2,amount:2000}
Output:
invoice 1 : {month:1,amount:1300}
invoice 2 : {month:2,amount:2000}
How can I do this with java 8 streams?
EDIT : as my Invoice class was mutable and it was not a problem to modify them, I choosed Eugene's solution
Collection<Invoice> invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
})).values();
A: If you are OK returning a Collection it would look like this:
Collection<Invoice> invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
})).values();
If you really need a List:
list.stream().collect(Collectors.collectingAndThen(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
}), m -> new ArrayList<>(m.values())));
Both obviously assume that Invoice is mutable...
|
Q: Java 8 stream - merge collections of objects sharing the same Id I have a collection of invoices :
class Invoice {
int month;
BigDecimal amount
}
I'd like to merge these invoices, so I get one invoice per month, and the amount is the sum of the invoices amount for this month.
For example:
invoice 1 : {month:1,amount:1000}
invoice 2 : {month:1,amount:300}
invoice 3 : {month:2,amount:2000}
Output:
invoice 1 : {month:1,amount:1300}
invoice 2 : {month:2,amount:2000}
How can I do this with java 8 streams?
EDIT : as my Invoice class was mutable and it was not a problem to modify them, I choosed Eugene's solution
Collection<Invoice> invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
})).values();
A: If you are OK returning a Collection it would look like this:
Collection<Invoice> invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
})).values();
If you really need a List:
list.stream().collect(Collectors.collectingAndThen(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
}), m -> new ArrayList<>(m.values())));
Both obviously assume that Invoice is mutable...
A: If you could add the following copy constructor and merge method to your Invoice class:
public Invoice(Invoice another) {
this.month = another.month;
this.amount = another.amount;
}
public Invoice merge(Invoice another) {
amount = amount.add(another.amount); // BigDecimal is immutable
return this;
}
You could reduce as you want, as follows:
Collection<Invoice> result = list.stream()
.collect(Collectors.toMap(
Invoice::getMonth, // use month as key
Invoice::new, // use copy constructor => don't mutate original invoices
Invoice::merge)) // merge invoices with same month
.values();
I'm using Collectors.toMap to do the job, which has three arguments: a function that maps elements of the stream to keys, a function that maps elements of the stream to values and a merge function that is used to combine values when there are collisions on the keys.
A: Collection<Invoice> result = invoices.stream().collect(groupingBy(i -> i.month,
collectingAndThen(
reducing((Invoice i1, Invoice i2) -> new Invoice(i1.month, i1.amount + i2.amount)),
Optional::get))).values();
A: You can do something like
Map<Integer, Invoice> invoiceMap = invoices.stream()
.collect(Collectors.groupingBy( // group invoices by month
invoice -> invoice.month
))
.entrySet().stream() // once you have them grouped stream then again so...
.collect(Collectors.toMap(
entry -> entry.getKey(), // we can mantain the key (month)
entry -> entry.getValue().stream() // and streaming all month's invoices
.reduce((invoice, invoice2) -> // add all the ammounts
new Invoice(invoice.month, invoice.amount.add(invoice2.amount)))
.orElse(new Invoice(entry.getKey(), new BigDecimal(0))) // In case we don't have any invoice (unlikeable)
));
A: Here is the solution by My library: abacus-common
Stream.of(invoices)
.groupBy2(Invoice::getMonth, Invoice::getAmount, BigDecimal::add)
.map(e -> new Invoice(e.getKey(), e.getValue())) // Probably we should not modify original invoices. create new instances.
.toList();
A: I think if your application do not support lambda than this might be a suitable answer eg (Android minSdkVersion=16 do not support lambda)
public static List<Invoice> mergeAmount(List<Invoice> invoiceList) {
List<Invoice> newInvoiceList = new ArrayList<>();
for(Invoice inv: invoiceList) {
boolean isThere = false;
for (Invoice inv1: newInvoiceList) {
if (inv1.getAmount() == inv.getAmount()) {
inv1.setAmount(inv1.getAmoount()+inv.getAmount());
isThere = true;
break;
}
}
if (!isThere) {
newInvoiceList.add(inv);
}
}
return newInvoiceList;
}
|
stackoverflow
|
{
"language": "en",
"length": 495,
"provenance": "stackexchange_0000F.jsonl.gz:864156",
"question_score": "15",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540040"
}
|
efe5ac67301011e303a7ced204ad9c11a15c73e6
|
Stackoverflow Stackexchange
Q: Hash for tree structure How to define hash function for a tree structure which depends only on the structure of the tree, and is same irrespective of node labels?
For example, 2--1--3--4 should have same hash function as 1--4--2--3 or 4--1--3--2.
A: Find the centre of the tree. Then run a recursive algorithm as such from the centre:
recurse(u, p):
hash = INITH
vector childrenhash = {}
for each (u,v) in G:
if v!=p:
childrenhash.insert(recurse(v,u))
childrenhash.sort()
for elem in childrenhash:
hash = (hash * (elem xor PR)) % MOD
return hash
Choose some appropriate values for INITH, MOD and PR.
Two isomorphic trees will have the same hash.
|
Q: Hash for tree structure How to define hash function for a tree structure which depends only on the structure of the tree, and is same irrespective of node labels?
For example, 2--1--3--4 should have same hash function as 1--4--2--3 or 4--1--3--2.
A: Find the centre of the tree. Then run a recursive algorithm as such from the centre:
recurse(u, p):
hash = INITH
vector childrenhash = {}
for each (u,v) in G:
if v!=p:
childrenhash.insert(recurse(v,u))
childrenhash.sort()
for elem in childrenhash:
hash = (hash * (elem xor PR)) % MOD
return hash
Choose some appropriate values for INITH, MOD and PR.
Two isomorphic trees will have the same hash.
A: If you throw out node labels, what is left is the number of children for each node. So you could just count the number of children for each node and write them all in one string( array, vector, ...).
Example:
a 2
/ \ / \
b c => 0 2 => 2,0,2,0,0
/ \ / \
d e 0 0
Now, suppose you're saying, the following trees should be considered equal:
a a
/ | \ / | \
b c d b c d
/ \ \ / \ |
d e f d e f
You can add more transformation step to the same idea: sort the children:
a 3 3
/ | \ / | \ / | \
b c d => 0 2 1 => 0 1 2 => 3,0,1,2,0,0,0
/ \ \ / \ \ | / \
d e f 0 0 0 0 0 0
a 3 3
/ | \ / | \ / | \
b c d => 2 0 1 => 0 1 2 => 3,0,1,2,0,0,0
/ \ | / \ | | / \
d e f 0 0 0 0 0 0
I'm probably following idea in the link by @gilleain: https://math.stackexchange.com/questions/1604260/algorithm-for-equality-of-trees-of-restricted-depth
|
stackoverflow
|
{
"language": "en",
"length": 317,
"provenance": "stackexchange_0000F.jsonl.gz:864172",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540101"
}
|
0a0900e2d1a9f8f1ffdb3ad4c4be1ef66df58987
|
Stackoverflow Stackexchange
Q: How to refer NPM installed libraries from web pages and templates? I have installed, say, jQuery:
npm install jquery
Now my site has
ROOT/node_modules/jquery/*
subdirectory.
What to do next? Just write
<script src="/node_modules/jquery/src/jquery.js"></script>
Or I can do something to take jquery.js out this path and/or encode reference in some portable way?
For example, suppose I am using Jade template. Shoud I write just
script(src="/node_modules/jquery/src/jquery.js")
A: To answer your question shortly: yes, you can copy jquery.js and move it to whatever folder you want. Then, you would have to change the src attribute in the script element, like this:
<script src="/new/path/jquery.js"></script>
However, in production cases, you would most likely want to join all the js files, and then only load a few files, like the following:
<script src="/path/libs.js"></script>
where libs.js contains all of our dependencies in correct order.
|
Q: How to refer NPM installed libraries from web pages and templates? I have installed, say, jQuery:
npm install jquery
Now my site has
ROOT/node_modules/jquery/*
subdirectory.
What to do next? Just write
<script src="/node_modules/jquery/src/jquery.js"></script>
Or I can do something to take jquery.js out this path and/or encode reference in some portable way?
For example, suppose I am using Jade template. Shoud I write just
script(src="/node_modules/jquery/src/jquery.js")
A: To answer your question shortly: yes, you can copy jquery.js and move it to whatever folder you want. Then, you would have to change the src attribute in the script element, like this:
<script src="/new/path/jquery.js"></script>
However, in production cases, you would most likely want to join all the js files, and then only load a few files, like the following:
<script src="/path/libs.js"></script>
where libs.js contains all of our dependencies in correct order.
A: The short answer to your question is : yes, you use it with the relative path as you put
<script src="/node_modules/jquery/src/jquery.js"></script>
To elaborate on use of NPM, it helps in the following ways
*
*Keeps the dependencies outside your code. So in your git repository you can ignore them (saves space and network). Also change of a library is done at one place instead of everywhere.
*You can recreate the dependencies easily. In case where you have deleted the dependencies or when new repo is built, you can run npm install and all dependencies are updated.
*Automatic dependency management - Where one package depends on another and in case where they are updated, nom automatically manages all dependencies.
So, in summary you are saved from managing the external packages.
Now in our code, you could use them the following way
*
*We could refer to each library by giving relative path. This is straightforward approach.
*Howewver, if you want to give alias root path, you can do that in builders like gulp or web pack by having variables.
*The best approach is to bundle them as one js file and also minify them and use the bundle.js. For example, in web pack, you could mention all such files as vendor.bundle.js in web pack configuration and run it once. This will create vendor.bundle.js. You can use this bundle instead of jQuery. The benefit is while nom manages the dependent modules at lower level, you can bundle them in to another js which will result in smaller single file that will be performance wise better.
A: If you are not using any build tool then you can have a scripts folder where you can copy the required libraries manually. That way your source itself is your build that you will eventually deploy. Or if you are working on a medium or big project, you can take a more common approach and use a build tool like webpack, gulp or browserify which can import all the dependencies automatically. Webpack is great for big projects can do a number of things for you:
*
*can import your dependencies into chunks of files
*assets management
*minifies your dependencies to reduce the size
*compiles compile-to-js and compile-to-css languages like typescript and sass
*offers a dev server with hot reloading
*supports dynamic loading to download parts of js only if required on runtime
and many others. It adds a good bit of complexity to your code though.
For small projects however I think it is better to go with manually adding libraries and keeping things simple
A: Dear what ever dependencies you are taking inside node project must be in Node_Modules and you must Specify the Dependencies path from Node_Module/dependency_path it will be better in Development of Project and in Production.May this be helpful for you
|
stackoverflow
|
{
"language": "en",
"length": 608,
"provenance": "stackexchange_0000F.jsonl.gz:864183",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540131"
}
|
d1009b99606aa4c49a0971ea8488844f2b30e68f
|
Stackoverflow Stackexchange
Q: Laravel validation required|exists with exception of 0 HTML form has select dropdown with list of existing categories and no category with id=0.
CategoryStoreRequest must check if the category_id from the form belongs to existing category or is 0
Something like that
public function rules() {
return [
"name" => "required|min:3",
"category_id" => "required|exists:categories,id,except_if_value_is_0"
];
}
What is the most elegant way to achieve it?
A: you can create new validation to handle
see this example:
in your_project_name/app/providers/AppServicesProviders.php
Validator::extend(
'exists_or_null',
function ($attribute, $value, $parameters)
{
if($value == 0 || is_null($value)) {
return true;
} else {
$validator = Validator::make([$attribute => $value], [
$attribute => 'exists:' . implode(",", $parameters)
]);
return !$validator->fails();
}
}
);
in your example do that
public function rules() {
return [
"name" => "required|min:3",
"category_id" => "required|exists_or_null:categories,id"
];
}
|
Q: Laravel validation required|exists with exception of 0 HTML form has select dropdown with list of existing categories and no category with id=0.
CategoryStoreRequest must check if the category_id from the form belongs to existing category or is 0
Something like that
public function rules() {
return [
"name" => "required|min:3",
"category_id" => "required|exists:categories,id,except_if_value_is_0"
];
}
What is the most elegant way to achieve it?
A: you can create new validation to handle
see this example:
in your_project_name/app/providers/AppServicesProviders.php
Validator::extend(
'exists_or_null',
function ($attribute, $value, $parameters)
{
if($value == 0 || is_null($value)) {
return true;
} else {
$validator = Validator::make([$attribute => $value], [
$attribute => 'exists:' . implode(",", $parameters)
]);
return !$validator->fails();
}
}
);
in your example do that
public function rules() {
return [
"name" => "required|min:3",
"category_id" => "required|exists_or_null:categories,id"
];
}
A: Instead of checking for exists or 0, you could set your custom zero value to NULL or an empty string.
You need to change a little bit of your logic, but then you can validate it correctly by using the sometimes rule:
public function rules() {
return [
"name" => "required|min:3",
"category_id" => "sometimes|exists:categories,id"
];
}
A: You can use sometimes. In this case, the rule will only be applied if a filled category_id is submitted.
public function rules() {
return [
"name" => "required|min:3",
"category_id" => "sometimes|exists:categories,id"
];
}
Change your html, so that there's no value set:
<select name="category_id">
<option value="">No category selection</option>
<option value="1">Cat 1</option>
</select>
A: It turns out that nullable is one quite elegant way to do it. When submitting the form then category_id array key is still present but its value is null. nullable allows the key to be null also.
public function rules() {
return [
"name" => "required|min:3",
"category_id" => "nullable|exists:categories,id"
];
}
In addition the select value must be ""
<select name="category_id">
<option value="">No category selection</option>
<option value="1">Cat 1</option>
</select>
|
stackoverflow
|
{
"language": "en",
"length": 313,
"provenance": "stackexchange_0000F.jsonl.gz:864204",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540208"
}
|
8d758d8301bcb7c90e86a4106313a093d5a52271
|
Stackoverflow Stackexchange
Q: Resource merging in Instant Apps features modules In an Instant App feature module, I'm importing an aar (using "api" statement from a maven repository) which contains an activity declaration in its manifest and a "style" resource used in this declaration.
The resulting manifest merging fails because the style resource is not found in the base feature project.
It seems resources from imported aar in features modules are not included in the base feature module.
Since the plugin is still in alpha mode I'm not sure if I'm doing something wrong, if it is a bug or the expected behaviour.
Any advice on this?
A: Actually it seems that for now this is the intended behaviour.
They now affirmn in the official FAQ:
"In addition, all the resources referenced by the manifest of a feature module must be present in the base feature module. "
In case such as the one described it that can be troublesome because either you are forced to include the library providing the resources in the base module or at least redeclare in the base module (trough overriding), resources used in the manifest.
Source: https://developer.android.com/topic/instant-apps/faqs.html
|
Q: Resource merging in Instant Apps features modules In an Instant App feature module, I'm importing an aar (using "api" statement from a maven repository) which contains an activity declaration in its manifest and a "style" resource used in this declaration.
The resulting manifest merging fails because the style resource is not found in the base feature project.
It seems resources from imported aar in features modules are not included in the base feature module.
Since the plugin is still in alpha mode I'm not sure if I'm doing something wrong, if it is a bug or the expected behaviour.
Any advice on this?
A: Actually it seems that for now this is the intended behaviour.
They now affirmn in the official FAQ:
"In addition, all the resources referenced by the manifest of a feature module must be present in the base feature module. "
In case such as the one described it that can be troublesome because either you are forced to include the library providing the resources in the base module or at least redeclare in the base module (trough overriding), resources used in the manifest.
Source: https://developer.android.com/topic/instant-apps/faqs.html
|
stackoverflow
|
{
"language": "en",
"length": 190,
"provenance": "stackexchange_0000F.jsonl.gz:864224",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540262"
}
|
f2e70d9b3eb055a46e700a01c2662df462b822f1
|
Stackoverflow Stackexchange
Q: Elasticsearch List Indices Using Boolean Query I have elastic cluster with hundreds of indices. Is there any way to list (search) indices using boolean query? e.g.
( index.alias:*read_index* AND doc.count:<1000 ) OR ( index.name* ) OR (index.size:<2gb) OR (index.replica:>2)
I need to filter out required indices from the list of hundreds of indices.
Kindly suggest.
A: Using plain elasticsearch bool queries :), just store the JSON format cat output into an index, then make the queries you need, automatize the collection with a cronjob to gather this every X time, my python script looks like this:
# install dependencies: pip install requests
import requests
import json
ES_URL = "http://localhost:9200"
res = requests.get("{}{}".format(ES_URL, "/_cat/indices"),
params={"format": "json", "bytes": "m"})
for index_info in res.json():
index_url = "{}/{}/{}/{}".format(
ES_URL, "cat_to_index", "doc", index_info["index"]
)
requests.post(
index_url,
data=json.dumps(index_info),
headers={'Content-type': 'application/json'}
)
# ready to query http://localhost:9200/cat_to_index/_search
# ready to keep up-to-date with a cronjob, as the index name is the ID new values will be overwritten.
hope it helps.
|
Q: Elasticsearch List Indices Using Boolean Query I have elastic cluster with hundreds of indices. Is there any way to list (search) indices using boolean query? e.g.
( index.alias:*read_index* AND doc.count:<1000 ) OR ( index.name* ) OR (index.size:<2gb) OR (index.replica:>2)
I need to filter out required indices from the list of hundreds of indices.
Kindly suggest.
A: Using plain elasticsearch bool queries :), just store the JSON format cat output into an index, then make the queries you need, automatize the collection with a cronjob to gather this every X time, my python script looks like this:
# install dependencies: pip install requests
import requests
import json
ES_URL = "http://localhost:9200"
res = requests.get("{}{}".format(ES_URL, "/_cat/indices"),
params={"format": "json", "bytes": "m"})
for index_info in res.json():
index_url = "{}/{}/{}/{}".format(
ES_URL, "cat_to_index", "doc", index_info["index"]
)
requests.post(
index_url,
data=json.dumps(index_info),
headers={'Content-type': 'application/json'}
)
# ready to query http://localhost:9200/cat_to_index/_search
# ready to keep up-to-date with a cronjob, as the index name is the ID new values will be overwritten.
hope it helps.
|
stackoverflow
|
{
"language": "en",
"length": 164,
"provenance": "stackexchange_0000F.jsonl.gz:864229",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540278"
}
|
b07d9d24f2eb353c25ab5de08041263fc31e799c
|
Stackoverflow Stackexchange
Q: Javascript cannot set property 0 of undefined This code generates error:
Uncaught TypeError: Cannot set property '0' of undefined
While I want to assign random numbers in array, please help.
var array;
for (var i = 1; i < 10; i++) {
array[i] = Math.floor(Math.random() * 7);
}
console.log(array);
A: You haven't told that array is an array Tell to javascript that treat that as an array,
var array = [];
|
Q: Javascript cannot set property 0 of undefined This code generates error:
Uncaught TypeError: Cannot set property '0' of undefined
While I want to assign random numbers in array, please help.
var array;
for (var i = 1; i < 10; i++) {
array[i] = Math.floor(Math.random() * 7);
}
console.log(array);
A: You haven't told that array is an array Tell to javascript that treat that as an array,
var array = [];
A: You are missing the array initialization:
var array = [];
Taking this into your example, you would have:
var array = []; //<-- initialization here
for(var i = 1; i<10;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
Also you should starting assigning values from index 0. As you can see in the log all unassigned values get undefined, which applies to your index 0.
So a better solution would be to start at 0, and adjust the end of for to <9, so that it creates the same number of elements:
var array = [];
for(var i = 0; i<9;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
A: you need to initialize the array first
var array = [];
after adding this line your code should work properly
|
stackoverflow
|
{
"language": "en",
"length": 201,
"provenance": "stackexchange_0000F.jsonl.gz:864271",
"question_score": "10",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540391"
}
|
b7076ee39159d3f7eb8f3f33cc547542ff30185c
|
Stackoverflow Stackexchange
Q: Difference between secondary name node and standby name node in Hadoop I couldn't understand the difference between secondary name node and standby name node and backup name node. I am looking for in depth understanding of these terms. Kindly help me out with this.
A: However, the answer explained above is satisfactory but I want to add some points to it.
About Standby-Namenode
Both active and standby Namenode use a shared directory and standby Namenode sync through that directory from time to time so there must be no delay in activating it if the active Namenode goes down.
But the main factor is about the block reports, Block reports are not written in edit-logs, they are stored in local disk space. So syncing with a shared directory is not enough.
To avoid this conflict, data-nodes has the addresses of both the name-nodes,
and they send the block reports to both of them but they only follow the block commands coming from the active Namenode.
Hope this is helpful
|
Q: Difference between secondary name node and standby name node in Hadoop I couldn't understand the difference between secondary name node and standby name node and backup name node. I am looking for in depth understanding of these terms. Kindly help me out with this.
A: However, the answer explained above is satisfactory but I want to add some points to it.
About Standby-Namenode
Both active and standby Namenode use a shared directory and standby Namenode sync through that directory from time to time so there must be no delay in activating it if the active Namenode goes down.
But the main factor is about the block reports, Block reports are not written in edit-logs, they are stored in local disk space. So syncing with a shared directory is not enough.
To avoid this conflict, data-nodes has the addresses of both the name-nodes,
and they send the block reports to both of them but they only follow the block commands coming from the active Namenode.
Hope this is helpful
A: Standby Node : In the case of an unplanned event such as a machine crash, the cluster would be unavailable until an operator restarted the NameNode.Planned maintenance events such as software or hardware upgrades on the NameNode machine could result in whole cluster downtime. So a Standby Node comes in action which is nothing but a backup for the Name Node .
Secondary NameNode : It is one of the poorest named part of the hadoop ecosystem usually beginners get confused thinking of it as a backup.Secondary NameNode in hadoop is a specially dedicated node in HDFS cluster whose main function is to take checkpoints of the file system metadata present on namenode. It is not a backup namenode. It just checkpoints namenode’s file system namespace. The Secondary NameNode is a helper to the primary NameNode but not replace for primary namenode.
A: Secondary namenode is just a helper for Namenode.
It gets the edit logs from the namenode in regular intervals and applies to fsimage.
Once it has new fsimage, it copies back to namenode.
Namenode will use this fsimage for the next restart, which will reduce the startup time.
Secondary Namenode's whole purpose is to have a checkpoint in HDFS. Its just a helper node for namenode. That’s why it also known as checkpoint node.
But, It cant replace namenode on namenode's failure.
So, Namenode still is Single-Point-of-Failure.
To overcome this issue; STANDBY-NAMENODE comes into picture.
It does three things:
*
*merging fsimage and edits-log files. (Secondary-namenode's work)
*receive online updates of the file system meta-data, apply them to its memory state and persist them on disks just like the name-node does.
Thus at any time the Backup node contains an up-to-date image of the namespace both in memory and on local disk(s).
*Cluster will switch over to the new name-node (this standby-node) if the active namenode dies.
A: The Secondary namenode maps the fsimage and the edit log transactions periodically stores them in a shared storage location in case of HA enabled HDFS Cluster.
In other hand, Standby node has the ability to transfer the latest built fsimage to the Active NameNode via HTTP Get call .
So the main difference between Secondary and standby namenode is secondary namenode does not upload the merged Fsimage with editlogs to active namenode
where as the standby node uplods the merged new image back to active Namenode.
So the NameNode need to fetch the state from the Secondary NameNode
|
stackoverflow
|
{
"language": "en",
"length": 579,
"provenance": "stackexchange_0000F.jsonl.gz:864309",
"question_score": "7",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540533"
}
|
bb1e3828de7905130bda73120a6d4262e4fe4266
|
Stackoverflow Stackexchange
Q: WebApi "The requested resource does not support http method 'DELETE" Using WebApi angularjs project and trying to delete function as
`
[HttpDelete]
public String DeleteCountry(string cntryId)
{
if (cntryId != null)
{
return repoCountry.DeleteCountry(Convert.ToInt32(cntryId));
}
else
{
return "0";
}
}
js function is
$http({
method: "delete",
url: '/api/Country/DeleteCountry/',
dataType: "json",
data: { cntryId: cntryId }
}).then(function (response) {});
Here I am getting exception
{"Message":"The requested resource does not support http method 'DELETE'."}
Insertion,update and get functionalities are working correctly.Giv a solution and why it is happening for delete only
A: Adorn your method with the Route attribute (I see this give me more control on the routing behavior in web API) and pass your data parameters as constructor args in this format: [HttpDelete, Route("{cntryId}"):
[HttpDelete, Route("{cntryId}")]
public String DeleteCountry(string cntryId)
{
//....
}
in the angular controller, you can just do this:
$http.delete('/api/Country/' + cntryId).then(function (response) {
//if you're waiting some response
})
|
Q: WebApi "The requested resource does not support http method 'DELETE" Using WebApi angularjs project and trying to delete function as
`
[HttpDelete]
public String DeleteCountry(string cntryId)
{
if (cntryId != null)
{
return repoCountry.DeleteCountry(Convert.ToInt32(cntryId));
}
else
{
return "0";
}
}
js function is
$http({
method: "delete",
url: '/api/Country/DeleteCountry/',
dataType: "json",
data: { cntryId: cntryId }
}).then(function (response) {});
Here I am getting exception
{"Message":"The requested resource does not support http method 'DELETE'."}
Insertion,update and get functionalities are working correctly.Giv a solution and why it is happening for delete only
A: Adorn your method with the Route attribute (I see this give me more control on the routing behavior in web API) and pass your data parameters as constructor args in this format: [HttpDelete, Route("{cntryId}"):
[HttpDelete, Route("{cntryId}")]
public String DeleteCountry(string cntryId)
{
//....
}
in the angular controller, you can just do this:
$http.delete('/api/Country/' + cntryId).then(function (response) {
//if you're waiting some response
})
A: is not a webapi issue is more a the format of your query .
the message says that does not support http method 'DELETE' because the webapi delete method is expecting an id as a parameter. and the route has the following format routeTemplate: "api/{controller}/{id}",
to resolve your issue try to use fiddler to intercept your request and ensure that your delete request is sent as '/api/Country/DeleteCountry/'+cntryId,
A: I faced same issue and solved it finally. This is simple and stupid solution.
Earlier code
public String DeleteCountry(string cntryId)
Changed code
public String DeleteCountry(int id)
so just use 'int id' not 'cntryId'. I did not use [HttpDelete] before method name but it worked.
A: Option 1:
$http({
method: "delete",
url: '/api/Country/Country?cntryId=' + cntryId,
}).then(function (response) {});
Option 2:
public String DeleteDeleteCountry([FromBody]string cntryId)
{
if (cntryId != null)
{
return repoCountry.DeleteCountry(Convert.ToInt32(cntryId));
}
else
{
return "0";
}
}
Best Option:
API
[Route("{countryId}")]
public IHttpActionResult Delete(int countryId)
{
try
{
repoCountry.DeleteCountry(countryId);
}
catch (RepoException ex)
{
if (ex == notfound)
this.NotFound();
if (ex == cantdelete)
this.Confict();
this.InternalServerError(ex.message);
}
return this.Ok();
}
Javascript
$http({
method: "delete",
url: '/api/country/' + cntryId,
}).then(function (response) {});
A: Assuming that u did not change the default routing. Same error can happen if u fail to declare [HttpDelete] attribute for the action in webAPI. Please try following
[HttpDelete]
public IHttpActionResult Delete(int id)
{
}
A: This will usually happen if you are trying to do a PUT or a DELETE and you don't have the API configured to allow it.
This post shows you how to solve this 405 error and get it working properly.
The easiest way to edit the ExtensionlessUrlHandler-Integrated-4.0 line in the web.config file of the Web API project
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
|
stackoverflow
|
{
"language": "en",
"length": 453,
"provenance": "stackexchange_0000F.jsonl.gz:864311",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540539"
}
|
7ca229939a7e15a25c2c77030b3fdf80a5a328fe
|
Stackoverflow Stackexchange
Q: SignalR in Delphi or C++Builder I need to send data in real time between Delphi/C++Builder apps placed in different PCs not connected in the same LAN, only using Internet.
My first approach was via DataSnap REST server but it is not practical due proxy and router problems. The configuration was too hard for the users plus that some people do not like to have a web server running in their machines opening the corresponding ports.
My second approach is using a server in the middle. I am checking SignalR technology that seems to fit very well. It is well solved for C# but I cannot find any information about VCL, Delphi or C++ Builder.
Is there some library or do I need to work from scratch via WebSockets?
Is there another way to communicate VCL applications that run in separated PCs only connected to Internet?
A: /n Software has a WebSockets library - with C++Builder support.
https://www.nsoftware.com/ipworks/ws/
Docs at https://cdn.nsoftware.com/help/IWF/bcb/
Download (there is a trial edition) at https://www.nsoftware.com/ipworks/ws/download.aspx
|
Q: SignalR in Delphi or C++Builder I need to send data in real time between Delphi/C++Builder apps placed in different PCs not connected in the same LAN, only using Internet.
My first approach was via DataSnap REST server but it is not practical due proxy and router problems. The configuration was too hard for the users plus that some people do not like to have a web server running in their machines opening the corresponding ports.
My second approach is using a server in the middle. I am checking SignalR technology that seems to fit very well. It is well solved for C# but I cannot find any information about VCL, Delphi or C++ Builder.
Is there some library or do I need to work from scratch via WebSockets?
Is there another way to communicate VCL applications that run in separated PCs only connected to Internet?
A: /n Software has a WebSockets library - with C++Builder support.
https://www.nsoftware.com/ipworks/ws/
Docs at https://cdn.nsoftware.com/help/IWF/bcb/
Download (there is a trial edition) at https://www.nsoftware.com/ipworks/ws/download.aspx
|
stackoverflow
|
{
"language": "en",
"length": 169,
"provenance": "stackexchange_0000F.jsonl.gz:864321",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540579"
}
|
21d8bd9243f6d9929fbe859cdec74d89f1191237
|
Stackoverflow Stackexchange
Q: Typescript - initialize a 2D array ERROR I'm trying to create a 2D array for coordinates like [[x_1,y_1,z_1], [x_2,y_2,z_2], [...],...].
Here is my code for initialization and initial declaration:
var ALLcoordinates:number[][];
for (var i=0; i< dims; i++) {
ALLcoordinates[i]=[];
for (var j=0; j<chainSize; j++){
ALLcoordinates[i][j]=0;
}
}
After that, I assign new values for each row in this loop :
for (var i = 0; i < chainSize; i++) {
var alea1 = Math.floor(Math.random()*(3-0+1))+0;
var alea2 = Math.floor(Math.random()*(3-0+1))+0;
var alea3 = Math.floor(Math.random()*(3-0+1))+0;
var coordinates:number[];
coordinates = [alea1,alea2,alea3];
ALLcoordinates[i]=coordinates;
}
But when I compile it, I get this error Uncaught TypeError: Cannot set property '0' of undefined for this line ALLcoordinates[i] = [];
I would appreciate any help, thanks
A: Declaring an array does not initialize it.
You are missing the ALLcoordinates initialization:
var ALLcoordinates:number[][];
ALLcoordinates = []; // ◄ initialize the array
for (var i=0; i< dims; i++) {
ALLcoordinates[i]=[];
for (var j=0; j<chainSize; j++){
ALLcoordinates[i][j]=0;
}
}
|
Q: Typescript - initialize a 2D array ERROR I'm trying to create a 2D array for coordinates like [[x_1,y_1,z_1], [x_2,y_2,z_2], [...],...].
Here is my code for initialization and initial declaration:
var ALLcoordinates:number[][];
for (var i=0; i< dims; i++) {
ALLcoordinates[i]=[];
for (var j=0; j<chainSize; j++){
ALLcoordinates[i][j]=0;
}
}
After that, I assign new values for each row in this loop :
for (var i = 0; i < chainSize; i++) {
var alea1 = Math.floor(Math.random()*(3-0+1))+0;
var alea2 = Math.floor(Math.random()*(3-0+1))+0;
var alea3 = Math.floor(Math.random()*(3-0+1))+0;
var coordinates:number[];
coordinates = [alea1,alea2,alea3];
ALLcoordinates[i]=coordinates;
}
But when I compile it, I get this error Uncaught TypeError: Cannot set property '0' of undefined for this line ALLcoordinates[i] = [];
I would appreciate any help, thanks
A: Declaring an array does not initialize it.
You are missing the ALLcoordinates initialization:
var ALLcoordinates:number[][];
ALLcoordinates = []; // ◄ initialize the array
for (var i=0; i< dims; i++) {
ALLcoordinates[i]=[];
for (var j=0; j<chainSize; j++){
ALLcoordinates[i][j]=0;
}
}
A: When you did var ALLcoordinates:number[][];, you did not initialize it with any value. You just specified its type. It will still be undefined at runtime. So undefined[0] throws the error. Initialize it before using it:
var ALLcoordinates: number[][] = [];
|
stackoverflow
|
{
"language": "en",
"length": 200,
"provenance": "stackexchange_0000F.jsonl.gz:864322",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540585"
}
|
25fd9534b8a4eec421153cfec2409b75a14fee3f
|
Stackoverflow Stackexchange
Q: initialScrollIndex not working for FlatList react native I am experiencing an issue with the initialScrollIndex of FlatList - the argument of initialScrollIndex is simply ignored and the first item is shown.
https://snack.expo.io/Bk1mkK0zZ
A: Using RN 0.61.5
I've solved this with setting:
*
*onContentSizeChange which will handle scroll to index whenever flatlist data is changed and all items rendered ( you can handle how many items will be rendered on initial render with setting initialNumToRender if needed)
*onScrollToIndexFailed which is necessary to use when using scrollToIndex function:
<FlatList
ref={ref => (this.flatList = ref)}
data={dataArray}
style={style}
eyExtractor={(item, index) => String(index)}
onContentSizeChange={() => {
if (this.flatList && this.flatList.scrollToIndex && dataArray && dataArray.length) {
this.flatList.scrollToIndex({ index: dataArray.length - 1 });
}
}}
onScrollToIndexFailed={() => {}}
renderItem={({ item, index }) => {
return (
<Text>Stackoverflow Answer</Text>
);
}}
/>
|
Q: initialScrollIndex not working for FlatList react native I am experiencing an issue with the initialScrollIndex of FlatList - the argument of initialScrollIndex is simply ignored and the first item is shown.
https://snack.expo.io/Bk1mkK0zZ
A: Using RN 0.61.5
I've solved this with setting:
*
*onContentSizeChange which will handle scroll to index whenever flatlist data is changed and all items rendered ( you can handle how many items will be rendered on initial render with setting initialNumToRender if needed)
*onScrollToIndexFailed which is necessary to use when using scrollToIndex function:
<FlatList
ref={ref => (this.flatList = ref)}
data={dataArray}
style={style}
eyExtractor={(item, index) => String(index)}
onContentSizeChange={() => {
if (this.flatList && this.flatList.scrollToIndex && dataArray && dataArray.length) {
this.flatList.scrollToIndex({ index: dataArray.length - 1 });
}
}}
onScrollToIndexFailed={() => {}}
renderItem={({ item, index }) => {
return (
<Text>Stackoverflow Answer</Text>
);
}}
/>
A: I used getItemLayout and every thing work like charm
const getItemLayout=(data, index)=> {
return { length: wp(100), offset: wp(100)* index, index };
}
<FlatList
horizontal
pagingEnabled
initialScrollIndex={1}
snapToAlignment={"start"}
decelerationRate={"fast"}
showsHorizontalScrollIndicator={false}
data={routes}
getItemLayout={getItemLayout}
renderItem={rowItem}/>
A: I had the exact same problem, which is why I found your question. After a lot of testing, I found a workaround, which seems to work. Instead of using initialScrollIndex I used the function scrollToIndex once the list is rendered. Applying it to your code, it will look like
import React, { Component } from 'react';
import { FlatList, Dimensions, View, Text } from 'react-native';
const WIDTH = Dimensions.get('window').width;
const HEIGHT = Dimensions.get('window').height;
export default class App extends Component {
render() {
const data = [{id: 0},{id: 1},{id: 2},{id: 3},{id: 4}];
return (
<View onLayout={() => this.onLayout()}>
<FlatList
ref={el => this.list = el}
data={data}
renderItem={this.renderItem}
keyExtractor={item => item.id}
pagingEnabled={true}
horizontal={true}
showsHorizontalScrollIndicator={false}
getItemLayout={this.getItemLayout}
debug={true}
/>
</View>
)
}
onLayout() {
this.list.scrollToIndex({index: 2})
}
renderItem = ({ item }) => {
return (
<View style={{flex: 1, backgroundColor: 'lightblue', width: WIDTH, height: HEIGHT, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{color: 'white', fontSize: 300, fontWeight: 'bold'}}>{item.id}</Text>
</View>
);
};
getItemLayout = (data, index) => (
{length: WIDTH, offset: WIDTH * index, index}
);
}
Hope it works for you.
By the way, putting this.list.scrollToIndex({index: 2}) in componentDidMount, does for some reason not work for me, which is why I used onLayout instead
A: I had the same issue but my situation was a little different. In my case, I was starting off with a WIDTH of 0 and waiting for the onLayout event callback to set the correct width. Therefore, on initial render, it didn't matter what value initialScrollIndex was, it couldn't scroll with a zero width. Using Dimensions to set an initial width fixed it for me.
A: Just remove the following:
pagingEnabled = { true }
This will fix your example.
|
stackoverflow
|
{
"language": "en",
"length": 448,
"provenance": "stackexchange_0000F.jsonl.gz:864333",
"question_score": "15",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540621"
}
|
ae45af2dd8ceda988b26715da14c5759f6121d56
|
Stackoverflow Stackexchange
Q: How to pass data between two ViewController using closure I want to know how to pass data using closure. I know that there are three types of data pass approaches:
*
*delegate
*Notification Center
*closure
I want proper clarification of closure with an example.
A: Well passing data with blocks / closures is a good and reasonable approach and much better than notifications.
Below is the same code for it.
First ViewController (where you make object of Second ViewController)
@IBAction func push(sender: UIButton) {
let v2Obj = storyboard?.instantiateViewControllerWithIdentifier("v2ViewController") as! v2ViewController
v2Obj.completionBlock = {[weak self] dataReturned in
//Data is returned **Do anything with it **
print(dataReturned)
}
navigationController?.pushViewController(v2Obj, animated: true)
}
Second ViewController (where data is passed back to First VC)
import UIKit
typealias v2CB = (infoToReturn :String) ->()
class v2ViewController: UIViewController {
var completionBlock:v2CB?
override func viewDidLoad() {
super.viewDidLoad()
}
func returnFirstValue(sender: UIButton) {
guard let cb = completionBlock else {return}
cb(infoToReturn: "any value")
}
}
|
Q: How to pass data between two ViewController using closure I want to know how to pass data using closure. I know that there are three types of data pass approaches:
*
*delegate
*Notification Center
*closure
I want proper clarification of closure with an example.
A: Well passing data with blocks / closures is a good and reasonable approach and much better than notifications.
Below is the same code for it.
First ViewController (where you make object of Second ViewController)
@IBAction func push(sender: UIButton) {
let v2Obj = storyboard?.instantiateViewControllerWithIdentifier("v2ViewController") as! v2ViewController
v2Obj.completionBlock = {[weak self] dataReturned in
//Data is returned **Do anything with it **
print(dataReturned)
}
navigationController?.pushViewController(v2Obj, animated: true)
}
Second ViewController (where data is passed back to First VC)
import UIKit
typealias v2CB = (infoToReturn :String) ->()
class v2ViewController: UIViewController {
var completionBlock:v2CB?
override func viewDidLoad() {
super.viewDidLoad()
}
func returnFirstValue(sender: UIButton) {
guard let cb = completionBlock else {return}
cb(infoToReturn: "any value")
}
}
A: This example explains use of service call with Alamofire and send the response back to calling View Controller with closure.
Code in Service Wrapper Class:
Closure declaration
typealias CompletionHandler = (_ response: NSDictionary?, _ statusCode: Int?, _ error: NSError?) -> Void
Closure implementation in method
func doRequestFor(_ url : String, method: HTTPMethod, dicsParams : [String: Any]?, dicsHeaders : [String: String]?, completionHandler:@escaping CompletionHandler) {
if !NetworkReachablity().isNetwork() {
return
}
if (dicsParams != nil) {print(">>>>>>>>>>>>>Request info url: \(url) --: \(dicsParams!)")}
else {print(">>>>>>>>>>>>>Request info url: \(url)")}
Alamofire.request(url, method: method, parameters: dicsParams, encoding:
URLEncoding.default, headers: dicsHeaders)
.responseJSON { response in
self.handleResponse(response: response, completionHandler: completionHandler)
}
}
Code at calling view controller:
ServiceWrapper().doRequestFor(url, method: .post, dicsParams: param, dicsHeaders: nil) { (dictResponse, statusCode, error) in
}
|
stackoverflow
|
{
"language": "en",
"length": 278,
"provenance": "stackexchange_0000F.jsonl.gz:864395",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540818"
}
|
77119526e1dc6630564e3e734ed883b7b1037817
|
Stackoverflow Stackexchange
Q: Alternative to ui-grid(doesn't support angular2/4) I am using ui-grid.
We are migrating our project from angular 1 to 2, but ui-grid doesn't have angular 2 support.
please suggest free (MIT) license grid alternative for ui-grid.
A: I was researching this recently, since I have an application that I used ui-grid on, and may be upgrading to angular 2 soon.
I've found...
Angular Datatables
https://l-lin.github.io/angular-datatables/#/getting-started
ag-Grid which has a free version https://www.ag-grid.com/
|
Q: Alternative to ui-grid(doesn't support angular2/4) I am using ui-grid.
We are migrating our project from angular 1 to 2, but ui-grid doesn't have angular 2 support.
please suggest free (MIT) license grid alternative for ui-grid.
A: I was researching this recently, since I have an application that I used ui-grid on, and may be upgrading to angular 2 soon.
I've found...
Angular Datatables
https://l-lin.github.io/angular-datatables/#/getting-started
ag-Grid which has a free version https://www.ag-grid.com/
A: I have implemented UI grid(AngularJS) into angular 2 using UpgradeModule and it is working fine, and I have also done some modification into that for gridOption which we can sent gridOption from typescript to UI grid.
Please find demo application : https://github.com/Umesh-Markande/Angular-4-Ui-grid
A: I know this is an old question but in case some people are still looking for alternatives...
I'm the author of Angular-Slickgrid, which is a wrapper on top of SlickGrid but specific for Angular, it is most probably the closest you can get to UI-Grid. There's over 300 stars for the project and it's very well maintained with lots of Wikis and samples, I have constantly added new features for the past 3 years since its creation and most UI-Grid features, and more, exists in Angular-Slickgrid. It also has 100% unit test coverage with Jest and also multiple E2E tests with Cypress.
Ag-Grid is another good alternatives but their best features are simply not free (quite expensive too) which is the biggest reason that I've built Angular-Slickgrid for our multiple projects.
See for yourself, here's a Live Demo with 30 different examples
A: Check out the Table component in Angular Material. Check out this example to see how it supports filtering, pagination, and more.
|
stackoverflow
|
{
"language": "en",
"length": 280,
"provenance": "stackexchange_0000F.jsonl.gz:864412",
"question_score": "8",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540864"
}
|
ef3dd5dc55f9eef809365b45f6d6a807833bf731
|
Stackoverflow Stackexchange
Q: Drag and Drop using swift 4 on mac OS I'm using swift 4 and Xcode 9 and I have a problem with implementation of drag and drop. I have a custom 'destination' view for drops and in swift 3 i call
register(forDraggedTypes: Array(NSURLPboardType))
to accept drags that contain those types.
How can I do somethings like this in swift 4?
Now I have this code
registerForDraggedTypes([.pdf])
And no one NSDraggingDestination method calls when I drop a pdf in my view.
(my custom view sits on top)
A: So my colleague found solution of this problem, in swift 4 you have to use kUTTypes casted as String for drag and drop, like this:
registerForDraggedTypes([NSPasteboard.PasteboardType(rawValue: kUTTypeFileURL as String), NSPasteboard.PasteboardType(rawValue: kUTTypeItem as String)])
With this code all NSDraggingDestination methods works fine, you can drop any file from finder in your view.
|
Q: Drag and Drop using swift 4 on mac OS I'm using swift 4 and Xcode 9 and I have a problem with implementation of drag and drop. I have a custom 'destination' view for drops and in swift 3 i call
register(forDraggedTypes: Array(NSURLPboardType))
to accept drags that contain those types.
How can I do somethings like this in swift 4?
Now I have this code
registerForDraggedTypes([.pdf])
And no one NSDraggingDestination method calls when I drop a pdf in my view.
(my custom view sits on top)
A: So my colleague found solution of this problem, in swift 4 you have to use kUTTypes casted as String for drag and drop, like this:
registerForDraggedTypes([NSPasteboard.PasteboardType(rawValue: kUTTypeFileURL as String), NSPasteboard.PasteboardType(rawValue: kUTTypeItem as String)])
With this code all NSDraggingDestination methods works fine, you can drop any file from finder in your view.
|
stackoverflow
|
{
"language": "en",
"length": 139,
"provenance": "stackexchange_0000F.jsonl.gz:864424",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540898"
}
|
843c918a6498ca5dda020ca3f081659d05546f92
|
Stackoverflow Stackexchange
Q: What is the type of a type in Typescript Here's a valid typescript snippet:
class A{
}
// what is the type of x ? i.e. f( x: <TYPE HERE>)...
function f(x) {
return new x();
}
const t = f(A);
It is obvious that the type of x is the type of the constructor function but it is not clear to me how one would specify it in Typescript.
Is it possible to type the parameter x ?
If yes, what is the type?
A: You can use:
interface Newable<T> {
new (): T;
}
As follows:
class A {}
interface Newable<T> {
new (): T;
}
function f(x: Newable<A>) {
return new x();
}
const t = f(A);
If you want to allow constructor arguments you will need to type them:
class A {
constructor(someArg1: string, someArg2: number) {
// ...
}
}
interface Newable<T> {
new (someArg1: string, someArg2: number): T;
}
function f(x: Newable<A>) {
return new x("someVal", 5);
}
const t = f(A);
And you could also do something more generic if needed:
interface Newable<T> {
new (...args: any[]): T;
}
|
Q: What is the type of a type in Typescript Here's a valid typescript snippet:
class A{
}
// what is the type of x ? i.e. f( x: <TYPE HERE>)...
function f(x) {
return new x();
}
const t = f(A);
It is obvious that the type of x is the type of the constructor function but it is not clear to me how one would specify it in Typescript.
Is it possible to type the parameter x ?
If yes, what is the type?
A: You can use:
interface Newable<T> {
new (): T;
}
As follows:
class A {}
interface Newable<T> {
new (): T;
}
function f(x: Newable<A>) {
return new x();
}
const t = f(A);
If you want to allow constructor arguments you will need to type them:
class A {
constructor(someArg1: string, someArg2: number) {
// ...
}
}
interface Newable<T> {
new (someArg1: string, someArg2: number): T;
}
function f(x: Newable<A>) {
return new x("someVal", 5);
}
const t = f(A);
And you could also do something more generic if needed:
interface Newable<T> {
new (...args: any[]): T;
}
|
stackoverflow
|
{
"language": "en",
"length": 187,
"provenance": "stackexchange_0000F.jsonl.gz:864451",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44540994"
}
|
21295b4ecafb6cc207ab4c0278195d676b7f301a
|
Stackoverflow Stackexchange
Q: ThreeJS : objects don't cast shadow on others I'm using three v0.85.2.
By default, all my objects are configured to cast and receive shadows :
const mesh = new Mesh(geometry, material)
mesh.castShadow = meshConfig.castShadow
mesh.receiveShadow = meshConfig.receiveShadow
shadowMap of the renderer is enabled.
Self shadows seem to be correctly rendered (green squares in the image below).
But shadows casted to other objects are missing (red squares).
The problem seems to occur with all my meshes.
I don't find a way to make them appear.
A: DirectionalLightShadow, there you can read how to work with shadows when you use THREE.DirectionalLight() in your scene.
Also you can play around with .left, .top, .right and .bottom properties of the shadow camera of your light source.
var light = new THREE.DirectionalLight(0xffffff,1);
light.position.set(50, 500, 22);
light.target.position.set(300, 400, 200);
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 5000;
light.shadow.camera.left = -500;
light.shadow.camera.bottom = -500;
light.shadow.camera.right = 500;
light.shadow.camera.top = 500;
light.castShadow = true;
scene.add(light);
three.js r85
jsfiddle example
|
Q: ThreeJS : objects don't cast shadow on others I'm using three v0.85.2.
By default, all my objects are configured to cast and receive shadows :
const mesh = new Mesh(geometry, material)
mesh.castShadow = meshConfig.castShadow
mesh.receiveShadow = meshConfig.receiveShadow
shadowMap of the renderer is enabled.
Self shadows seem to be correctly rendered (green squares in the image below).
But shadows casted to other objects are missing (red squares).
The problem seems to occur with all my meshes.
I don't find a way to make them appear.
A: DirectionalLightShadow, there you can read how to work with shadows when you use THREE.DirectionalLight() in your scene.
Also you can play around with .left, .top, .right and .bottom properties of the shadow camera of your light source.
var light = new THREE.DirectionalLight(0xffffff,1);
light.position.set(50, 500, 22);
light.target.position.set(300, 400, 200);
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 5000;
light.shadow.camera.left = -500;
light.shadow.camera.bottom = -500;
light.shadow.camera.right = 500;
light.shadow.camera.top = 500;
light.castShadow = true;
scene.add(light);
three.js r85
jsfiddle example
|
stackoverflow
|
{
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:864495",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541143"
}
|
5a0096f6456550cc116e39d3b222abff3113647a
|
Stackoverflow Stackexchange
Q: Arrays.asList(int_array).indexOf(int_element) returns -1 even if element is present java I have taken an int[] as input. For searching the index of an integer in the array I used Arrays.asList(arr).indexOf(element) method. However, I am getting index as -1 even if the element is present in the array.
A: int[] is one object, so Arrays.asList(arr) puts one object in the list, you need to put values from int[] one by one
|
Q: Arrays.asList(int_array).indexOf(int_element) returns -1 even if element is present java I have taken an int[] as input. For searching the index of an integer in the array I used Arrays.asList(arr).indexOf(element) method. However, I am getting index as -1 even if the element is present in the array.
A: int[] is one object, so Arrays.asList(arr) puts one object in the list, you need to put values from int[] one by one
|
stackoverflow
|
{
"language": "en",
"length": 70,
"provenance": "stackexchange_0000F.jsonl.gz:864532",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541247"
}
|
d1904edf695267fa6d7629c0bc4f7dcb9496f8d6
|
Stackoverflow Stackexchange
Q: What is the equivalent of 'Cache line size' in PCIE? In PCI configuration space, Cache line size indicates system cacheline size in units of DWORDs. This register must be implemented by master devices that can generate the Memory Write and Invalidate command.
The value in this register is also used by master devices to determine whether to use Read, Read Line, or Read Multiple commands for accessing memory.
Slave devices that want to allow memory bursting using cacheline wrap addressing mode must implement this register to know when a burst sequence wraps to the beginning of the cacheline.
But this field is implemented by PCI Express devices as a read-write field for legacy compatibility purposes but has no effect on any PCI Express device behavior.
Then how PCIe system implements memory-write-invalidate feature ?
A: The PCIe has a supplement protocol that is called Address Translation Services (ATS), in this protocol, there is a description for invalidation (chapter 3). The bottom line is a MsgD Transaction Layer Packet (TLP) called Invalidate that can do that.
Note that in general, it is completely separate (protocol-wise) from the MWr TLP.
|
Q: What is the equivalent of 'Cache line size' in PCIE? In PCI configuration space, Cache line size indicates system cacheline size in units of DWORDs. This register must be implemented by master devices that can generate the Memory Write and Invalidate command.
The value in this register is also used by master devices to determine whether to use Read, Read Line, or Read Multiple commands for accessing memory.
Slave devices that want to allow memory bursting using cacheline wrap addressing mode must implement this register to know when a burst sequence wraps to the beginning of the cacheline.
But this field is implemented by PCI Express devices as a read-write field for legacy compatibility purposes but has no effect on any PCI Express device behavior.
Then how PCIe system implements memory-write-invalidate feature ?
A: The PCIe has a supplement protocol that is called Address Translation Services (ATS), in this protocol, there is a description for invalidation (chapter 3). The bottom line is a MsgD Transaction Layer Packet (TLP) called Invalidate that can do that.
Note that in general, it is completely separate (protocol-wise) from the MWr TLP.
A: As far as I know, PCIe does not have an explicit message memory write and invalidate. Instead, a root complex that recieves a write that happens to cover an entire cacheline can avoid reading that cacheline and invalidate it immediately.
I think in most cases you would simply generate MaxPayloadSize requests if possible, and hopefully also trigger this behaviour. If you must know the cacheline size from the device, I would suggest designing a device-specific mechanism, and configuring it from your driver.
|
stackoverflow
|
{
"language": "en",
"length": 271,
"provenance": "stackexchange_0000F.jsonl.gz:864537",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541262"
}
|
8184e578605f1d13ff915dfe343e38ec97fdefd2
|
Stackoverflow Stackexchange
Q: WebExtension: Bypass permission denied to access property "target" Using FF WebExtension, I am trying to clone an element from a website that I don't own. This is what I use(taken from W3C).
// Get the last <li> element ("Milk") of <ul> with id="myList2"
var itm = document.getElementById("myList2").lastChild;
// Copy the <li> element and its child nodes
var cln = itm.cloneNode(true);
// Append the cloned <li> element to <ul> with id="myList1"
document.getElementById("myList1").appendChild(cln);
However, this error appears:
Error: Permission denied to access property "target"
Here is my manifest:
{
"manifest_version": 2,
"name": "w",
"version": "0.1",
"description": "w",
"icons": {
"48": "icons/border-48.png"
},
"content_scripts": [
{
"matches": ["http://localhost/*"],
"js": ["rh-addbutton.js","rh-addpage.js"]
}
],
"permissions": ["http://localhost/*"]
}
Am I missing a permission? I can't find the right permission on MDN.
|
Q: WebExtension: Bypass permission denied to access property "target" Using FF WebExtension, I am trying to clone an element from a website that I don't own. This is what I use(taken from W3C).
// Get the last <li> element ("Milk") of <ul> with id="myList2"
var itm = document.getElementById("myList2").lastChild;
// Copy the <li> element and its child nodes
var cln = itm.cloneNode(true);
// Append the cloned <li> element to <ul> with id="myList1"
document.getElementById("myList1").appendChild(cln);
However, this error appears:
Error: Permission denied to access property "target"
Here is my manifest:
{
"manifest_version": 2,
"name": "w",
"version": "0.1",
"description": "w",
"icons": {
"48": "icons/border-48.png"
},
"content_scripts": [
{
"matches": ["http://localhost/*"],
"js": ["rh-addbutton.js","rh-addpage.js"]
}
],
"permissions": ["http://localhost/*"]
}
Am I missing a permission? I can't find the right permission on MDN.
|
stackoverflow
|
{
"language": "en",
"length": 126,
"provenance": "stackexchange_0000F.jsonl.gz:864542",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541271"
}
|
eba97e1ee1d90b5a974c188332225b0164b71ab9
|
Stackoverflow Stackexchange
Q: Get IPAddress of iPhone or iPad device Using Swift 3 How to retrieve the device's IP address without using any third-party libraries using Swift 3 programming language? I have used the following code in order to get the IP address:
func getIPAddress() -> String? {
var address : String?
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr.memory.ifa_next }
let interface = ptr.memory
let addrFamily = interface.ifa_addr.memory.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
if let name = String.fromCString(interface.ifa_name) where name == "en0" {
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.memory.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String.fromCString(hostname)
}
}
}
freeifaddrs(ifaddr)
}
return address
}
But the UnsafeMutablePointer<ifaddrs> syntax is not working. It throws a syntax error. Do I need to import a framework to try to help me?
A: Add #include<ifaddrs.h> in your bridging header.
This is the framework needed to get IP address.
Also you can refer the following link:
Swift - Get device's IP Address
|
Q: Get IPAddress of iPhone or iPad device Using Swift 3 How to retrieve the device's IP address without using any third-party libraries using Swift 3 programming language? I have used the following code in order to get the IP address:
func getIPAddress() -> String? {
var address : String?
var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr.memory.ifa_next }
let interface = ptr.memory
let addrFamily = interface.ifa_addr.memory.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
if let name = String.fromCString(interface.ifa_name) where name == "en0" {
var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.memory.sa_len),
&hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST)
address = String.fromCString(hostname)
}
}
}
freeifaddrs(ifaddr)
}
return address
}
But the UnsafeMutablePointer<ifaddrs> syntax is not working. It throws a syntax error. Do I need to import a framework to try to help me?
A: Add #include<ifaddrs.h> in your bridging header.
This is the framework needed to get IP address.
Also you can refer the following link:
Swift - Get device's IP Address
A: try this (no bridging header is necessary, it works in Playground)
//: Playground - noun: a place where people can play
import Darwin
var temp = [CChar](repeating: 0, count: 255)
enum SocketType: Int32 {
case SOCK_STREAM = 0, SOCK_DGRAM, SOCK_RAW
}
// host name
gethostname(&temp, temp.count)
// create addrinfo based on hints
// if host name is nil or "" we can connect on localhost
// if host name is specified ( like "computer.domain" ... "My-MacBook.local" )
// than localhost is not aviable.
// if port is 0, bind will assign some free port for us
var port: UInt16 = 0
let hosts = ["localhost", String(cString: temp)]
var hints = addrinfo()
hints.ai_flags = 0
hints.ai_family = PF_UNSPEC
for host in hosts {
print("\n\(host)")
print()
// retrieve the info
// getaddrinfo will allocate the memory, we are responsible to free it!
var info: UnsafeMutablePointer<addrinfo>?
defer {
if info != nil
{
freeaddrinfo(info)
}
}
var status: Int32 = getaddrinfo(host, String(port), nil, &info)
guard status == 0 else {
print(errno, String(cString: gai_strerror(errno)))
continue
}
var p = info
var i = 0
var ipFamily = ""
var ipType = ""
while p != nil {
i += 1
// use local copy of info
var _info = p!.pointee
p = _info.ai_next
switch _info.ai_family {
case PF_INET:
_info.ai_addr.withMemoryRebound(to: sockaddr_in.self, capacity: 1, { p in
inet_ntop(AF_INET, &p.pointee.sin_addr, &temp, socklen_t(temp.count))
ipFamily = "IPv4"
})
case PF_INET6:
_info.ai_addr.withMemoryRebound(to: sockaddr_in6.self, capacity: 1, { p in
inet_ntop(AF_INET6, &p.pointee.sin6_addr, &temp, socklen_t(temp.count))
ipFamily = "IPv6"
})
default:
continue
}
print(i,"\(ipFamily)\t\(String(cString: temp))", SocketType(rawValue: _info.ai_socktype)!)
}
}
it prints on my computer
localhost
1 IPv6 ::1 SOCK_RAW
2 IPv6 ::1 SOCK_DGRAM
3 IPv4 127.0.0.1 SOCK_RAW
4 IPv4 127.0.0.1 SOCK_DGRAM
Ivos-MacBook-Pro.local
1 IPv6 fe80::18a2:e892:fbd7:558e SOCK_RAW
2 IPv6 fe80::18a2:e892:fbd7:558e SOCK_DGRAM
3 IPv4 172.20.10.3 SOCK_RAW
4 IPv4 172.20.10.3 SOCK_DGRAM
A: I did following things in order to get the exact IP address of the device. Since I want to include the updated code to get IP address using Swift 3, I am posting the answer here. Referred from Swift - Get device's IP Address
*
*Add #include<ifaddrs.h> in your bridging header
*Create following function in order to get the IP Address.
func getIP()-> String? {
var address: String?
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr?.pointee.ifa_next } // memory has been renamed to pointee in swift 3 so changed memory to pointee
let interface = ptr?.pointee
let addrFamily = interface?.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
if let name: String = String(cString: (interface?.ifa_name)!), name == "en0" { // String.fromCString() is deprecated in Swift 3. So use the following code inorder to get the exact IP Address.
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
getnameinfo(interface?.ifa_addr, socklen_t((interface?.ifa_addr.pointee.sa_len)!), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
}
return address
}
*In order to get the IP Address, print(getIP())
For verification:
-> Goto Settings -> Wi-Fi -> Click i symbol -> you can check your device IP Address.
OUTPUT SCREENSHOT:
|
stackoverflow
|
{
"language": "en",
"length": 687,
"provenance": "stackexchange_0000F.jsonl.gz:864546",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541280"
}
|
8258d2d03a63c24c594f80c0b61ebbbc1ca15b28
|
Stackoverflow Stackexchange
Q: Parallelism of window-functions in Spark 2 I have a rather simple (but essential) question about Spark window functions (such as e.g. lead, lag, count, sum, row_number etc):
If a specify my window as Window.partitionBy(lit(0)) (i.e. I need to run the window fucntion accross the entire dataframe), is the window aggregate function running in parallel, or are all records moved in one single tasks?
EDIT:
Especially for "rolling" operations (e.g. rolling average using something like avg(...).Window.partitionBy(lit(0)).orderBy(...).rowsBetween(-10,10)), this operation could very well be split up into different tasks even tough all data is in the same partition of the window because only 20 row are needed at once to compute the average
A: If you define as Window.partitionBy(lit(0)) or if you don't define partitionBy at all, then all of the partitions of a dataframe will be collected as one in one executor and that executor is going to perform the aggregating function on whole dataframe. So parallelism will not be preserved.
The collection is different than the collect() function as collect() function will collect all the partitions into driver node but partitionBy function will collect data to executor where the partitions are easy to be collected.
|
Q: Parallelism of window-functions in Spark 2 I have a rather simple (but essential) question about Spark window functions (such as e.g. lead, lag, count, sum, row_number etc):
If a specify my window as Window.partitionBy(lit(0)) (i.e. I need to run the window fucntion accross the entire dataframe), is the window aggregate function running in parallel, or are all records moved in one single tasks?
EDIT:
Especially for "rolling" operations (e.g. rolling average using something like avg(...).Window.partitionBy(lit(0)).orderBy(...).rowsBetween(-10,10)), this operation could very well be split up into different tasks even tough all data is in the same partition of the window because only 20 row are needed at once to compute the average
A: If you define as Window.partitionBy(lit(0)) or if you don't define partitionBy at all, then all of the partitions of a dataframe will be collected as one in one executor and that executor is going to perform the aggregating function on whole dataframe. So parallelism will not be preserved.
The collection is different than the collect() function as collect() function will collect all the partitions into driver node but partitionBy function will collect data to executor where the partitions are easy to be collected.
|
stackoverflow
|
{
"language": "en",
"length": 195,
"provenance": "stackexchange_0000F.jsonl.gz:864579",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541401"
}
|
c0666d50e6b4a17ced07a1d030f88fc78a924528
|
Stackoverflow Stackexchange
Q: Custom font for all labels Xamarin Forms I have downloaded a font from fonts.google.com and would like to set the font family for all labels in my Xamarin Forms app.
Adding the following code to all labels seems like an excessive amount of work
<Label.FontFamily>
<OnPlatform x:TypeArguments="x:String">
<OnPlatform.Android>Mogra-Regular.ttf#Mogra-Regular</OnPlatform.Android>
</OnPlatform>
</Label.FontFamily>
Ideally I would set the font family in the Resource Dictionary where I've already succesfully set text colour and font attributes, however, I've been unsuccesful in doing so.
I have managed to change the font family using a custom renderer but the moment I alter the label text colour or font attributes using dynamic resources the font family is reset to default.
Is there any way that will allow me to universally use my custom font and still be allowed to dynamically change other aspects of any given label?
A: Create an implicit Style (a Style without an x:Key) in your App.xaml and it'll be applied to all Labels
<Style TargetType="Label">
<Setter Property="FontFamily">
<Setter.Value>
<OnPlatform x:TypeArguments="x:String">
<OnPlatform.Android>Mogra-Regular.ttf#Mogra-Regular</OnPlatform.Android>
</OnPlatform>
</Setter.Value>
</Setter>
</Style>
|
Q: Custom font for all labels Xamarin Forms I have downloaded a font from fonts.google.com and would like to set the font family for all labels in my Xamarin Forms app.
Adding the following code to all labels seems like an excessive amount of work
<Label.FontFamily>
<OnPlatform x:TypeArguments="x:String">
<OnPlatform.Android>Mogra-Regular.ttf#Mogra-Regular</OnPlatform.Android>
</OnPlatform>
</Label.FontFamily>
Ideally I would set the font family in the Resource Dictionary where I've already succesfully set text colour and font attributes, however, I've been unsuccesful in doing so.
I have managed to change the font family using a custom renderer but the moment I alter the label text colour or font attributes using dynamic resources the font family is reset to default.
Is there any way that will allow me to universally use my custom font and still be allowed to dynamically change other aspects of any given label?
A: Create an implicit Style (a Style without an x:Key) in your App.xaml and it'll be applied to all Labels
<Style TargetType="Label">
<Setter Property="FontFamily">
<Setter.Value>
<OnPlatform x:TypeArguments="x:String">
<OnPlatform.Android>Mogra-Regular.ttf#Mogra-Regular</OnPlatform.Android>
</OnPlatform>
</Setter.Value>
</Setter>
</Style>
|
stackoverflow
|
{
"language": "en",
"length": 172,
"provenance": "stackexchange_0000F.jsonl.gz:864588",
"question_score": "5",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541437"
}
|
fc0ae2ed03abe62ef75350cb2f6c4ad8574f5c8c
|
Stackoverflow Stackexchange
Q: How to apply WorksheetFunction.CountIfs depending on time? I am trying to count records on Sheet2.
Dim wksdata As Worksheet
Dim xyz as String
Dim Time as String
Set wksdata = Sheets("Data")
Time = Date + TimeValue("08:00:00") 'Set Time value as todays date 8am
'set calculations worksheet cell I15 as the time value
Worksheets("Calculations").Range("I15").Value = Time
'converts time column to time format
Worksheets("Data)").Range("U:U").NumberFormat = "dd/mm/yyyy hh:mm:ss"
xyz = WorksheetFunction.CountIfs(wksdata.Range("I:I"), "xyz", _
wksdata.Range("K:K"), "C", wksdata.Range("U:U"), "<" & _
Worksheets("Calculations").Range("I15").Value)
If I apply this directly in a worksheet it works with the same logic.
Why isn't it working in VBA?
A: Try and use a different variable for setting the date and time. "Time" is built in VBA and will return the current time and so Range("I15").Value will be set to the current time and not 08:00 as required
Dim wksdata As Worksheet
Dim xyz as String
Dim startTime as String
Set wksdata = Sheets("Data")
startTime = Date + TimeValue("08:00:00") 'Set Time value as todays date 8am
Worksheets("Calculations").Range("I15").Value = startTime 'set calculations
worksheet cell I15 as the time value
Worksheets("Data)").Range("U:U").NumberFormat = "dd/mm/yyyy hh:mm:ss"
'converts time column to time format
xyz = WorksheetFunction.CountIfs(wksdata.Range("I:I"), "xyz",
wksdata.Range("K:K"), "C", wksdata.Range("U:U"), "<" &
Worksheets("Calculations").Range("I15").Value)
|
Q: How to apply WorksheetFunction.CountIfs depending on time? I am trying to count records on Sheet2.
Dim wksdata As Worksheet
Dim xyz as String
Dim Time as String
Set wksdata = Sheets("Data")
Time = Date + TimeValue("08:00:00") 'Set Time value as todays date 8am
'set calculations worksheet cell I15 as the time value
Worksheets("Calculations").Range("I15").Value = Time
'converts time column to time format
Worksheets("Data)").Range("U:U").NumberFormat = "dd/mm/yyyy hh:mm:ss"
xyz = WorksheetFunction.CountIfs(wksdata.Range("I:I"), "xyz", _
wksdata.Range("K:K"), "C", wksdata.Range("U:U"), "<" & _
Worksheets("Calculations").Range("I15").Value)
If I apply this directly in a worksheet it works with the same logic.
Why isn't it working in VBA?
A: Try and use a different variable for setting the date and time. "Time" is built in VBA and will return the current time and so Range("I15").Value will be set to the current time and not 08:00 as required
Dim wksdata As Worksheet
Dim xyz as String
Dim startTime as String
Set wksdata = Sheets("Data")
startTime = Date + TimeValue("08:00:00") 'Set Time value as todays date 8am
Worksheets("Calculations").Range("I15").Value = startTime 'set calculations
worksheet cell I15 as the time value
Worksheets("Data)").Range("U:U").NumberFormat = "dd/mm/yyyy hh:mm:ss"
'converts time column to time format
xyz = WorksheetFunction.CountIfs(wksdata.Range("I:I"), "xyz",
wksdata.Range("K:K"), "C", wksdata.Range("U:U"), "<" &
Worksheets("Calculations").Range("I15").Value)
A: The date part needs to be converted into a Long. Once this is done, the formula works correctly. Here is a sample of how this could be done using a similar formula:
Sub test_method()
Range("B1") = Now()
Range("B1").NumberFormat = "dd/mm/yyyy hh:mm:ss"
'Trying to calculate using a VBA date in the worksheet formula doesn't work
'This returns 0
Debug.Print WorksheetFunction.CountIfs(Range("B1:B10"), ">" & (Now() - 0.75))
'Now we change it to a long and it yields the correct answer
'returns 1
Debug.Print WorksheetFunction.CountIfs(Range("B1:B10"), ">" & CLng((Now() - 0.75)))
End Sub
|
stackoverflow
|
{
"language": "en",
"length": 286,
"provenance": "stackexchange_0000F.jsonl.gz:864630",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541556"
}
|
5af5ae02c89f2b8c526be7ea9ce4bd85aa8427c1
|
Stackoverflow Stackexchange
Q: How to get the lists' length in one column in dataframe spark? I have a df whose 'products' column are lists like below:
+----------+---------+--------------------+
|member_srl|click_day| products|
+----------+---------+--------------------+
| 12| 20161223| [2407, 5400021771]|
| 12| 20161226| [7320, 2407]|
| 12| 20170104| [2407]|
| 12| 20170106| [2407]|
| 27| 20170104| [2405, 2407]|
| 28| 20161212| [2407]|
| 28| 20161213| [2407, 100093]|
| 28| 20161215| [1956119]|
| 28| 20161219| [2407, 100093]|
| 28| 20161229| [7905970]|
| 124| 20161011| [5400021771]|
| 6963| 20160101| [103825645]|
| 6963| 20160104|[3000014912, 6626...|
| 6963| 20160111|[99643224, 106032...|
How to add a new column product_cnt which are the length of products list? And how to filter df to get specified rows with condition of given products length ?
Thanks.
A: Pyspark has a built-in function to achieve exactly what you want called size. http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.size .
To add it as column, you can simply call it during your select statement.
from pyspark.sql.functions import size
countdf = df.select('*',size('products').alias('product_cnt'))
Filtering works exactly as @titiro89 described. Furthermore, you can use the size function in the filter. This will allow you to bypass adding the extra column (if you wish to do so) in the following way.
filterdf = df.filter(size('products')==given_products_length)
|
Q: How to get the lists' length in one column in dataframe spark? I have a df whose 'products' column are lists like below:
+----------+---------+--------------------+
|member_srl|click_day| products|
+----------+---------+--------------------+
| 12| 20161223| [2407, 5400021771]|
| 12| 20161226| [7320, 2407]|
| 12| 20170104| [2407]|
| 12| 20170106| [2407]|
| 27| 20170104| [2405, 2407]|
| 28| 20161212| [2407]|
| 28| 20161213| [2407, 100093]|
| 28| 20161215| [1956119]|
| 28| 20161219| [2407, 100093]|
| 28| 20161229| [7905970]|
| 124| 20161011| [5400021771]|
| 6963| 20160101| [103825645]|
| 6963| 20160104|[3000014912, 6626...|
| 6963| 20160111|[99643224, 106032...|
How to add a new column product_cnt which are the length of products list? And how to filter df to get specified rows with condition of given products length ?
Thanks.
A: Pyspark has a built-in function to achieve exactly what you want called size. http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.size .
To add it as column, you can simply call it during your select statement.
from pyspark.sql.functions import size
countdf = df.select('*',size('products').alias('product_cnt'))
Filtering works exactly as @titiro89 described. Furthermore, you can use the size function in the filter. This will allow you to bypass adding the extra column (if you wish to do so) in the following way.
filterdf = df.filter(size('products')==given_products_length)
A: First question:
How to add a new column product_cnt which are the length of products list?
>>> a = [(12,20161223, [2407,5400021771]),(12,20161226,[7320,2407])]
>>> df = spark.createDataFrame(a,
["member_srl","click_day","products"])
>>> df.show()
+----------+---------+------------------+
|member_srl|click_day| products|
+----------+---------+------------------+
| 12| 20161223|[2407, 5400021771]|
| 12| 20161226|[7320, 2407, 4344]|
+----------+---------+------------------+
You can find a similar example here
>>> from pyspark.sql.types import IntegerType
>>> from pyspark.sql.functions import udf
>>> slen = udf(lambda s: len(s), IntegerType())
>>> df2 = df.withColumn("product_cnt", slen(df.products))
>>> df2.show()
+----------+---------+------------------+-----------+
|member_srl|click_day| products|product_cnt|
+----------+---------+------------------+-----------+
| 12| 20161223|[2407, 5400021771]| 2|
| 12| 20161226|[7320, 2407, 4344]| 3|
+----------+---------+------------------+-----------+
Second question:
And how to filter df to get specified rows with condition of given products length ?
You can use filter function docs here
>>> givenLength = 2
>>> df3 = df2.filter(df2.product_cnt==givenLength)
>>> df3.show()
+----------+---------+------------------+-----------+
|member_srl|click_day| products|product_cnt|
+----------+---------+------------------+-----------+
| 12| 20161223|[2407, 5400021771]| 2|
+----------+---------+------------------+-----------+
|
stackoverflow
|
{
"language": "en",
"length": 331,
"provenance": "stackexchange_0000F.jsonl.gz:864650",
"question_score": "32",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541605"
}
|
9702f7c707d9398a93d64e7ac9a69bdc3765bc14
|
Stackoverflow Stackexchange
Q: Error : No providers for Component I have a directive where I defined a radio button and I want to call a method of a component ..
Whene I inject the component in constructor I got this error : ERROR Error: No provider for FoldersComponent!
directive.ts
import { FoldersComponent } from '../folders/folders.component';
import { Directive, ElementRef, HostListener, Input, AfterViewInit, ViewChild, EventEmitter, Output } from '@angular/core';
declare var jQuery: any;
@Directive({
selector: '[icheck]'
})
export class IcheckDirective implements AfterViewInit {
@Output('icheck')
callComponentFunction: EventEmitter<any> = new EventEmitter<any>();
constructor(private el: ElementRef, private parentCmp: FoldersComponent) {
jQuery(this.el.nativeElement).iCheck({
checkboxClass: 'icheckbox_square-aero',
radioClass: 'iradio_square-aero'
}).on('ifChecked', function(event) {
if (jQuery('input').attr('type') === 'radio') {
this.parentCmp.selectType();
}
});
}
ngAfterViewInit(): void {
}
}
folder.component.ts
@Component({
selector: 'app-folders',
templateUrl: './folders.component.html',
styleUrls: ['./folders.component.css'],
})
export class FoldersComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
selectType() {
// alert();
console.log("Ici");
}
}
folder.component.html
<input type="radio" icheck name="filters.type" [(ngModel)]="filters.type" value="IN"> (IN)
My @NgModule
@NgModule({
declarations: [
AppComponent,
LoginComponent,
FoldersComponent,
],
A: It seems you have missed to register FoldersComponent to @NgModule({})
Can you post your main file where you have used NgModule
|
Q: Error : No providers for Component I have a directive where I defined a radio button and I want to call a method of a component ..
Whene I inject the component in constructor I got this error : ERROR Error: No provider for FoldersComponent!
directive.ts
import { FoldersComponent } from '../folders/folders.component';
import { Directive, ElementRef, HostListener, Input, AfterViewInit, ViewChild, EventEmitter, Output } from '@angular/core';
declare var jQuery: any;
@Directive({
selector: '[icheck]'
})
export class IcheckDirective implements AfterViewInit {
@Output('icheck')
callComponentFunction: EventEmitter<any> = new EventEmitter<any>();
constructor(private el: ElementRef, private parentCmp: FoldersComponent) {
jQuery(this.el.nativeElement).iCheck({
checkboxClass: 'icheckbox_square-aero',
radioClass: 'iradio_square-aero'
}).on('ifChecked', function(event) {
if (jQuery('input').attr('type') === 'radio') {
this.parentCmp.selectType();
}
});
}
ngAfterViewInit(): void {
}
}
folder.component.ts
@Component({
selector: 'app-folders',
templateUrl: './folders.component.html',
styleUrls: ['./folders.component.css'],
})
export class FoldersComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
selectType() {
// alert();
console.log("Ici");
}
}
folder.component.html
<input type="radio" icheck name="filters.type" [(ngModel)]="filters.type" value="IN"> (IN)
My @NgModule
@NgModule({
declarations: [
AppComponent,
LoginComponent,
FoldersComponent,
],
A: It seems you have missed to register FoldersComponent to @NgModule({})
Can you post your main file where you have used NgModule
A: I was facing the same issue. Turns out I had missed updating the following in my code:
*
*@Injectable({ providedIn: 'root' })
in the .ts file of the component that you want to import.
*Add the component in the NgModule of your appModule.
A: try this, you have not imported your component.
import { FoldersComponent } from '../path/to/component
constructor(private _foldersComponent : FoldersComponent){}
@Directive({
selector: '[icheck]'
})
... rest of file
Then to call methods from FoldersComponent just use _foldersComponent.
For example, this._foldersComponent.someMethod()
|
stackoverflow
|
{
"language": "en",
"length": 269,
"provenance": "stackexchange_0000F.jsonl.gz:864652",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541613"
}
|
9cd456ca6cf573885518053285269133da87173c
|
Stackoverflow Stackexchange
Q: How to make `_logger.isDebugEnabled()` condition false in Junit? How to make _logger.isDebugEnabled() condition false in Junit ?
private static final Logger _logger = Logger.getLogger(InstanceReleaseMachine.class);
if (_logger.isDebugEnabled())
{
_logger.debug("Error from Releasing Instance: " + failure);
}
i tried to my knowledge i can't do it , Please let me know if anyone have done this .
A: You can set level = OFF programmatically in unit test:
Logger.getRootLogger().setLevel(Level.OFF);
|
Q: How to make `_logger.isDebugEnabled()` condition false in Junit? How to make _logger.isDebugEnabled() condition false in Junit ?
private static final Logger _logger = Logger.getLogger(InstanceReleaseMachine.class);
if (_logger.isDebugEnabled())
{
_logger.debug("Error from Releasing Instance: " + failure);
}
i tried to my knowledge i can't do it , Please let me know if anyone have done this .
A: You can set level = OFF programmatically in unit test:
Logger.getRootLogger().setLevel(Level.OFF);
|
stackoverflow
|
{
"language": "en",
"length": 68,
"provenance": "stackexchange_0000F.jsonl.gz:864667",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541661"
}
|
b33560769d2c2f654adc7788cf990c4d3370e25a
|
Stackoverflow Stackexchange
Q: Angular - (click) event on a generated table cell I've been trying to add a (click) event on a cell in a dynamically generated table.
HTMLtoAdd:any;
@Input() roles:string;
ngOnInit() {
let alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
let table = document.createElement('table');
for (let i=0;i<10;i++){
let newRow = document.createElement('tr');
for (let j=0;j<10;j++) {
let newCell = document.createElement('td');
let cellId = alphabet[i]+j;
newCell.setAttribute("id",cellId);
newCell.setAttribute("(click)","alert(this.id)");
newRow.appendChild(newCell);
}
table.appendChild(newRow);
}
this.HTMLtoAdd = table.outerHTML;
};
When I do this, I get this error :
'setAttribute' on 'Element': '(click)' is not a valid attribute name.
How could I add this event, provided I need to generate that table ?
Feel free to ask for more details if needed.
A: Here is how I solved it:
Template :
<table>
<tr *ngFor="let row of columns">
<td *ngFor="let cell of rows" (click)="log(row+cell)"></td>
</tr>
</table>
Component :
columns:string[]=[];
rows:number[]=[];
ngOnInit() {
let gridSize = 10;
for (let i=0; i<gridSize;i++){
this.columns.push(String.fromCharCode(65+i));
};
for (let i=0; i<gridSize;i++){
this.rows.push(i);
}
};
|
Q: Angular - (click) event on a generated table cell I've been trying to add a (click) event on a cell in a dynamically generated table.
HTMLtoAdd:any;
@Input() roles:string;
ngOnInit() {
let alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
let table = document.createElement('table');
for (let i=0;i<10;i++){
let newRow = document.createElement('tr');
for (let j=0;j<10;j++) {
let newCell = document.createElement('td');
let cellId = alphabet[i]+j;
newCell.setAttribute("id",cellId);
newCell.setAttribute("(click)","alert(this.id)");
newRow.appendChild(newCell);
}
table.appendChild(newRow);
}
this.HTMLtoAdd = table.outerHTML;
};
When I do this, I get this error :
'setAttribute' on 'Element': '(click)' is not a valid attribute name.
How could I add this event, provided I need to generate that table ?
Feel free to ask for more details if needed.
A: Here is how I solved it:
Template :
<table>
<tr *ngFor="let row of columns">
<td *ngFor="let cell of rows" (click)="log(row+cell)"></td>
</tr>
</table>
Component :
columns:string[]=[];
rows:number[]=[];
ngOnInit() {
let gridSize = 10;
for (let i=0; i<gridSize;i++){
this.columns.push(String.fromCharCode(65+i));
};
for (let i=0; i<gridSize;i++){
this.rows.push(i);
}
};
|
stackoverflow
|
{
"language": "en",
"length": 156,
"provenance": "stackexchange_0000F.jsonl.gz:864671",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541671"
}
|
058d56d4525f67d1c3365cef82a4750b0df05784
|
Stackoverflow Stackexchange
Q: How Do I Add Google Analytics OnClick To Wordpress Contact Form 7 Submit Button As above, I need to add the following...
onclick="goog_report_conversion ('http://example.com/your-link')" href="http://example.com/your-link"
to the submit button being generated by Contact Form 7 in Wordpress.
How can I do this?
Thanks in advance
A: Using event Listener trigger analytics while click contact form submit button,
document.addEventListener( 'wpcf7mailsent', function( event ) {
ga( 'send', 'event', 'Contact Form', 'submit' );
}, false );
REF : https://contactform7.com/tracking-form-submissions-with-google-analytics/
|
Q: How Do I Add Google Analytics OnClick To Wordpress Contact Form 7 Submit Button As above, I need to add the following...
onclick="goog_report_conversion ('http://example.com/your-link')" href="http://example.com/your-link"
to the submit button being generated by Contact Form 7 in Wordpress.
How can I do this?
Thanks in advance
A: Using event Listener trigger analytics while click contact form submit button,
document.addEventListener( 'wpcf7mailsent', function( event ) {
ga( 'send', 'event', 'Contact Form', 'submit' );
}, false );
REF : https://contactform7.com/tracking-form-submissions-with-google-analytics/
|
stackoverflow
|
{
"language": "en",
"length": 77,
"provenance": "stackexchange_0000F.jsonl.gz:864690",
"question_score": "4",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541732"
}
|
ff0c761b0d0853a6899f0bd3f5f6b720202a0389
|
Stackoverflow Stackexchange
Q: Remove NA in a data.table in R I'm trying to do in R something apparently very easy (sorry but i'm very newbie with data.tables) but I don't manage to get the right solution. I try to delete the rows with NA values on a specific column("Ground_Tru". This is my attempt so far;
all_data <- fread ("all_vbles.txt",header=TRUE, na.strings=c("NA","N/A",""))
na.omit (all_data, cols="Ground_Tru")
I get the message
Empty data.table (0 rows) of 75 cols: OID_,IN_FID,Polygon_ID,DIST_highw,DIST_railw,DIST_port...
however the "Ground_Tru" field has many NA values
thanks in advance for any help,
A: Use complete.cases:
all_data <- all_data[complete.cases(all_data[, 'Ground_Tru'])]
|
Q: Remove NA in a data.table in R I'm trying to do in R something apparently very easy (sorry but i'm very newbie with data.tables) but I don't manage to get the right solution. I try to delete the rows with NA values on a specific column("Ground_Tru". This is my attempt so far;
all_data <- fread ("all_vbles.txt",header=TRUE, na.strings=c("NA","N/A",""))
na.omit (all_data, cols="Ground_Tru")
I get the message
Empty data.table (0 rows) of 75 cols: OID_,IN_FID,Polygon_ID,DIST_highw,DIST_railw,DIST_port...
however the "Ground_Tru" field has many NA values
thanks in advance for any help,
A: Use complete.cases:
all_data <- all_data[complete.cases(all_data[, 'Ground_Tru'])]
A: At the end I managed to solve the problem. Apparently there are some issues with R reading column names using the data.table library so I followed one of the suggestions provided here:
read.table doesn't read in column names
so the code became like this:
library(data.table)
read.table("all_vbles.txt",header=T,nrow=1,sep=",",dec=".",quote="")
all_data <- fread ("all_vbles.txt",header=FALSE, skip=1, ,sep="auto", na.strings=c("NA","N/A",""))
setnames (all_data,header)
test_data <- na.omit (all_data, "Ground_Tru")
which seemed to work fine.
|
stackoverflow
|
{
"language": "en",
"length": 160,
"provenance": "stackexchange_0000F.jsonl.gz:864706",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541777"
}
|
edb34fd3674ca14abb6cab7406e9d8a8486e9f9d
|
Stackoverflow Stackexchange
Q: How can I use my PC (running on windows) as a bluetooth audio device for my android phone? Suppose I get a call at my android phone. What I want is this call to be routed to my bluetooth/wifi connected PC just like it is routed to any other android audio device.
A: *
*If you have embedded Bluetooth hardware just use accompanying software and set your PC (after pairing) headset/speakers as a Hands-free device. That's it.
*If you have BT USB-dongle try to install Bluesoleil software and do the same as above. It's simple but not very stable piece of s..oftware, so it may work or it may not. In this case you can try Broadcom WIDCOMM Bluetooth Driver 12.0.1.940 and again set that so you could use your PC headset as a Hands-free device.
I'm sorry I can't tell you exact steps because I don't have Bluetooth on my PC atm. But believe me it's very easy. It was some time ago but it was like half a minute to set things up.
Hope this will help.
|
Q: How can I use my PC (running on windows) as a bluetooth audio device for my android phone? Suppose I get a call at my android phone. What I want is this call to be routed to my bluetooth/wifi connected PC just like it is routed to any other android audio device.
A: *
*If you have embedded Bluetooth hardware just use accompanying software and set your PC (after pairing) headset/speakers as a Hands-free device. That's it.
*If you have BT USB-dongle try to install Bluesoleil software and do the same as above. It's simple but not very stable piece of s..oftware, so it may work or it may not. In this case you can try Broadcom WIDCOMM Bluetooth Driver 12.0.1.940 and again set that so you could use your PC headset as a Hands-free device.
I'm sorry I can't tell you exact steps because I don't have Bluetooth on my PC atm. But believe me it's very easy. It was some time ago but it was like half a minute to set things up.
Hope this will help.
|
stackoverflow
|
{
"language": "en",
"length": 180,
"provenance": "stackexchange_0000F.jsonl.gz:864721",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541806"
}
|
e4ebed1ab34a11d049ac381dbab0b7de56252016
|
Stackoverflow Stackexchange
Q: Azure Cosmos DB each partition size limit In Azure Cosmos DB partinioned collection, does each partition has any size limit?
As per this old document, they have a size limit of 10 GB. Is that the same now also?
https://azure.microsoft.com/en-in/blog/10-things-to-know-about-documentdb-partitioned-collections/
Regards,
Karthikeyan V.
A: A partitioned collection has individual 10GB partition spaces. For a given partition key, you cannot exceed 10GB of data. This has not changed.
You'll need to pick a partition key which distributes your data across many partitions, vs creating "hot" partitions which could fill up (where you'd then get an error when attempting to write content).
|
Q: Azure Cosmos DB each partition size limit In Azure Cosmos DB partinioned collection, does each partition has any size limit?
As per this old document, they have a size limit of 10 GB. Is that the same now also?
https://azure.microsoft.com/en-in/blog/10-things-to-know-about-documentdb-partitioned-collections/
Regards,
Karthikeyan V.
A: A partitioned collection has individual 10GB partition spaces. For a given partition key, you cannot exceed 10GB of data. This has not changed.
You'll need to pick a partition key which distributes your data across many partitions, vs creating "hot" partitions which could fill up (where you'd then get an error when attempting to write content).
A: There are two type of collection
*
*Single Partition Collection (10GB and 10,000 RU/s)
*Partitioned Collection (250 GB and 250,000 RU/s)- you can increase the limit as needed after contacting azure team.
For partitioned collection you mush have to specify a partition key based on your query filter for better read performance and if you will not mention it will be by default single partition collection.
Note: Collection is a logical space and it can span across multiple node(hence quorum) in background based on the RU and other param, in short it's a PAAS and the infra handling is automated behind the screen, you will not have much control over it.
More info here:
Partitioning and horizontal scaling in Azure Cosmos DB
|
stackoverflow
|
{
"language": "en",
"length": 224,
"provenance": "stackexchange_0000F.jsonl.gz:864723",
"question_score": "6",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541811"
}
|
3098741b0f30d02e8152a55fdc42c770b47cac8d
|
Stackoverflow Stackexchange
Q: Restrict Payload for some method CommonsRequestLoggingFilter Spring I am using CommonsRequestLoggingFilter to log payload of incoming request . But for one method i don't want to log the payload as it contains user confidential data . I have following configuration in web.xml
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>org.springframework.web.filter.CommonsRequestLoggingFilter</filter-class>
<init-param>
<param-name>includePayload</param-name>
<param-value >true</param-value>
</init-param>
<init-param>
<param-name>includeQueryString</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>MaxPayloadLength</param-name>
<param-value>10000</param-value>
</init-param>
</filter>
Help me in restricting with one method .
Thanks in advance
A: You could create your own class extending CommonsRequestLoggingFilter and in that class you could do:-
@Override
protected String createMessage(HttpServletRequest request, String prefix, String suffix) {
//based on uri you could print payload or not.
}
|
Q: Restrict Payload for some method CommonsRequestLoggingFilter Spring I am using CommonsRequestLoggingFilter to log payload of incoming request . But for one method i don't want to log the payload as it contains user confidential data . I have following configuration in web.xml
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>org.springframework.web.filter.CommonsRequestLoggingFilter</filter-class>
<init-param>
<param-name>includePayload</param-name>
<param-value >true</param-value>
</init-param>
<init-param>
<param-name>includeQueryString</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>MaxPayloadLength</param-name>
<param-value>10000</param-value>
</init-param>
</filter>
Help me in restricting with one method .
Thanks in advance
A: You could create your own class extending CommonsRequestLoggingFilter and in that class you could do:-
@Override
protected String createMessage(HttpServletRequest request, String prefix, String suffix) {
//based on uri you could print payload or not.
}
|
stackoverflow
|
{
"language": "en",
"length": 107,
"provenance": "stackexchange_0000F.jsonl.gz:864759",
"question_score": "3",
"source": "stackexchange",
"timestamp": "2023-03-29T00:00:00",
"url": "https://stackoverflow.com/questions/44541940"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.