text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Android ViewPager2 FragmentStateAdapter shows Menu from every Fragment i have an activity with bottom navigation view with 3 Fragments associated.
One of them is a Fragment with a ViewPager2 that uses a FragmentStateAdapter.
Inside the createfragment(int position) method of the Adapter I return a couple Instances of another Fragment which has an Options Menu and inside it's onCreate() i call setHasOptionsMenu(true).
The Problem is that on initialization of the adapter, the menu from all fragments are visible not just the menu of the currently visible fragment.
After the first swipe it seems that the menu gets invalidated and everything is as it should be.
The problem also occurs if i notify the adapter about changes that another fragment is added, then another menu item appears for the newly added fragment.
I saw a similar question but the answer was to call setHasOptionsMenu() inside the onResume() method of the fragment but that doesn't seem to be the right behavior to handle this. In a comment another user suggested to upgrade ViewPager2 to another version but I am using the latest version.
Can anybody tell me how to handle this?
A: I joined StackOverflow just to reply to this question as I've also wasted time on this exact issue.
The fix is to update to the latest alpha01 version of ViewPager2.
implementation "androidx.viewpager2:viewpager2:1.1.0-alpha01"
See: https://developer.android.com/jetpack/androidx/releases/viewpager2#1.1.0-alpha01
Fixed FragmentStateAdapter issue with initial fragment menu visibility when adding a fragment to the FragmentManager. (I9d2ff, b/144442240)
A: I tried updating to the latest viewpager2 alpha as suggested in the currently accepted answer, but it didn't help.
I have seen answers to similar questions where they say to clear the entire menu first. That should work, too, but I have some menu items that are loaded in the Activity, which do not duplicate, and some that load in the fragment, which do duplicate. I want to keep the ones inflated in the Activity and remove only all the ones from all fragments (not just the current fragment, just in case).
My work-around, therefore, is to each time remove only the items added in all fragments, checking to make sure each is actually there (not null) before removing each one. Then, once those have been removed, I inflate the menu(s) needed for all/each fragment.
Note that the existing menu is removed item by item (R.id...) while the inflated one is added by menu (R.menu...) as usual.
In the below sample, the search menu will always be inflated, while the second menu to be inflated will depend on which fragment it currently active.
@Override public void onCreateOptionsMenu (@NonNull Menu menu, @NonNull MenuInflater
inflater)
{
super.onCreateOptionsMenu (menu, inflater);
removeMenuItemIfPresent (menu, R.id.menu_search);
removeMenuItemIfPresent (menu, R.id.menu_sample_filter1);
removeMenuItemIfPresent (menu, R.id.menu_sample_filter2);
inflater.inflate (R.menu.menu_search_menu, menu);
inflater.inflate (mCurrentSection == 0 ? R.menu.menu_frag0 : R.menu.menu_frag1, menu);
}
private void removeMenuItemIfPresent (@NonNull Menu menu, int resourceIDToRemove)
{
MenuItem menuItemToRemove = menu.findItem (resourceIDToRemove);
if (menuItemToRemove != null) {
menu.removeItem (menuItemToRemove.getItemId ());
}
}
A: I am not sure if it worked before but now im having issues with ViewPager2. When, I add fragments, each with different menuitems, the menuitem does not reflect on the first fragment added.
It works when offscreenpagelimit is not set. However, its performance is bad. Didnt have issues with ViewPager.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62153744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Riverpod: How to read provider after async gap I am trying to build a simple login screen. For this I have set up a StateProvider to indicate whether to show a loading indicator:
final loginIsLoadingProvider = StateProvider<bool>((ref) => false);
When a button is pressed I call the following function:
void logInUser(WidgetRef ref) async {
ref.read(loginIsLoadingProvider.notifier).state = true;
await Future.delayed(1.seconds); //login logic etc.
ref.read(loginIsLoadingProvider.notifier).state = false; //Exception
return;
But calling ref.read(...) after awaiting the future throws the following exception:
FlutterError (Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.)
Why cant I call ref.read() after an async gap? Is there any way to do this?
A: A solution is to read your providers before the async gap, but not use them immediately.
For example:
Future<void> logInUser(WidgetRef ref) async {
final isLoadingNotifier = ref.read(loginIsLoadingProvider.notifier);
isLoadingNotifier.state = true;
await someAsyncOperation();
isLoadingNotifier.state = false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73802238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Calculate statistics PDR, Delay ,Broadcast Success rate For Protocol works in Phy Layer ,Link Layer using OMNET 5.0,VEINS 4.4? What are The Programming instructions that can be written in omnet.ini file or .ned file for calculating the statistics Packet Delivery Ratio, Delay ,Broadcast Success rate For Protocol works in Physical Layer ,Link Layer using OMNET 5.0 ,VEINS 4.4???
Please reply ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72877124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Printing a generator in python tensor flow I am trying to follow the tensor flow tutorial as described in this link
I am trying to print the predicted result as described :
print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))
But I am not able to print the result. I am getting the following error.
print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))
TypeError: %d format: a number is required, not generator
How do I print the generator in python.
I tried to write a loop and iterate over the elements it didn't work and I tried to use next to print the generator. That also didn't work. How do I print it ?
A: This is how I solved it
new_samples = np.array([test_data[8]], dtype=float)
y = list(classifier.predict(new_samples, as_iterable=True))
print('Predictions: {}'.format(str(y)))
print ("Predicted %s, Label: %d" % (str(y), test_labels[8]))
A: No tensorflow here, so let's mock up a generator and test it against your print expression
In [11]: def predict(a, b):
...: for i in range(10):
...: yield i, i*i
...:
In [12]: print('a:%d, b:%d'%(predict(0, 0)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-29ec761936ef> in <module>()
----> 1 print('a:%d, b:%d'%(predict(0, 0)))
TypeError: %d format: a number is required, not generator
So far, so good: I have the same problem that you've experienced.
The problem is, of course, that what you get when you call a generator function are not values but a generator object...
You have to iterate on the generator objects, using whatever is returned from each iteration, e.g.,
In [13]: print('\n'.join('a:%d, b:%d'%(i,j) for i, j in predict(0,0)))
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81
or, if you don't like one-liners,
In [14]: for i, j in predict(0, 0):
...: print('a:%d, b:%d'%(i,j))
...:
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81
In other words, you have to explicitly consume what the generator is producing.
A: From the documentation:
Runs inference to determine the class probability predictions.
(deprecated arguments)
SOME ARGUMENTS ARE DEPRECATED. They will be removed after 2016-09-15.
Instructions for updating: The default behavior of predict() is
changing. The default value for as_iterable will change to True, and
then the flag will be removed altogether. The behavior of this flag is
described below.
Try:
classifier.predict(x=test_data[0])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41611518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: task shedule, sharing form label variable I am writting some easy program in Java FX. I am begginer in Java.
I would like make,
You fill textbox (time in minutes) and run it.
And than it run timer.schedule that it will every minute refresh label with time. Something like stopwatch.
(You set time whitch you want remember time).
I have Controller
public class Controller implements Initializable {
@FXML
public Label label;
@FXML
private TextField timeEnd;
.
.
And method onClick
@FXML
private void handleButtonAction(ActionEvent event) {
Integer timeEndVal = Integer.parseInt(timeEnd.getText());
Date startDate = new Date();
Date endDate = new Date();
endDate.setTime(startDate.getTime() + (timeEndVal * 60000));
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
long currentMinutes = currentTime().getTime() - startDate.getTime();
System.out.println(currentMinutes / 60000 + " / " + timeEndVal + " min");
label.setText(String.valueOf(currentMinutes / 60000 + " / " + timeEndVal + " min"));
}
}, 0, 60000);
But I don't know, how I get label variable to timer.schedule.
What I do wrong. Thank for helping.
A: Here is a non Controller version that you can use to get some ideas from. I suggest you use TimeLine instead of Timer. This is not a complete program!
import java.util.concurrent.atomic.AtomicInteger;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* @author blj0011
*/
public class JavaFXApplication267 extends Application
{
@Override
public void start(Stage primaryStage)
{
AtomicInteger timeInSeconds = new AtomicInteger();
TextField textField = new TextField();
Label label = new Label(Integer.toString(timeInSeconds.get()));
Button btn = new Button("Play");
textField.setPromptText("Enter the number of minutes");
textField.textProperty().addListener((obs, oldValue, newValue) -> {
//This assume the input is corret!
timeInSeconds.set(Integer.parseInt(newValue) * 60);//Number of minutes times 60 seconds
label.setText(getMinsSeconds(timeInSeconds.get()));
});
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> {
if (timeInSeconds.get() > 0) {
label.setText(getMinsSeconds(timeInSeconds.decrementAndGet()));
}
}));
timeline.setCycleCount(Timeline.INDEFINITE);
btn.setOnAction((ActionEvent event) -> {
switch (btn.getText()) {
case "Play":
timeline.play();
btn.setText("Pause");
textField.setEditable(false);
break;
case "Pause":
timeline.pause();
btn.setText("Play");
textField.setEditable(true);
break;
}
});
VBox root = new VBox(label, btn, textField);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
String getMinsSeconds(int seconds)
{
return String.format("%02d:%02d", (seconds / 60), (seconds % 60));
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52448890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Different themes for different languages in Visual Studio Code I've tried searching for the answer to this but am coming up blank.
In sublime text, it's possible to have different themes for different file types as specified in the preferences file. For example, you can have a light coloured theme for Markdown/Plain text files and a normal Monokai type theme for all other languages. I find this very useful as I prefer to have different fonts and settings when typing compared to when coding.
As far as I can see, this functionality isn't present in VSCode. Am I wrong or is there a way to achieve the above?
A: You are right, there is no way to do that.
You can however, define different themes (color and icon) for each workspace (Preferences: Open Workspace Settings). It's not exactly what you are looking for, but it may be useful if your different languages are located/related in different workspaces.
A: It's now possible to do using an extension called "Theme by language" from Julien Saulou. It can be downloaded from Visual Studio Code Marketplace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40263971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Spring Data Rest: Null Pointer If-Modified-Since Header Present and Resource Not Auditable If a Client makes a request for a Resource and specifies the If-Modified-Since header when the mapped Entity does not have any of the Spring Data JPA auditing annotations (@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate ) then this appears to result in a null-pointer exception in the class org.springframework.data.rest.webmvc.HttpHeadersPreparer:
public boolean isObjectStillValid(Object source, HttpHeaders headers) {
Assert.notNull(source, "Source object must not be null!");
Assert.notNull(headers, "HttpHeaders must not be null!");
if (headers.getIfModifiedSince() == -1) {
return false;
}
//THE WRAPPER IS NULL IF NO AUDITING ANNOTATIONS PRESENT
AuditableBeanWrapper wrapper = auditableBeanWrapperFactory.getBeanWrapperFor(source);
long current = wrapper.getLastModifiedDate().getTimeInMillis() / 1000 * 1000;
return current <= headers.getIfModifiedSince();
}
Is this a bug and, short of adding a field to the Entity to prevent this, is there any other workround.
A: If fetching the entity doesn't emit a Last-Modified header, then I would say this is a bug in the client, not SDR.
If none of your entities support Last-Modified, maybe create a filter that strips If-Modified-Since from the request or catches it early and responds appropriately.
All of that said, I also don't think a NPE is acceptable and a SDR bug should be filed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40025685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: hide the name of app in windows task manager
Possible Duplicate:
Hide a C# program from the task manager?
Hi.
I write WinForms app and i want to hide my app name in this place windows Task Manager>>Applications .how can hide when i run my app??
thanks.
A: The application name that Task Manager shows is the Window text of the taskbar window. If you want to hide it you'll just have to set that text to an empty string.
If a blank string is no good, and you don't want your app to appear in the list at all, then don't register a taskbar button.
If you don't want your app to appear in the process list, then don't start it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5273983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VB.Net Listview Groups I am new here and come up with my first question:
I have a listview with some groups, every groups has some items.
I added a ContextMenuStrip to the Listview, and when I rightclick on the selected item, I like to get the Name of the Group which it belongs to.
Can someone help me how to do this?
If LV1.SelectedItems(0).Text = LV1.Groups(0).ToString Then
MsgBox("Hi")
End If
A: Get LV group name for the item the mouse is down over:
Private thisGroupName As String = ""
Private Sub MouseDown(sender, e As MouseEventArgs)...
If e.Button = MouseButtons.Right Then
thisGroupName = GetLVGroupAt(e.X, e.Y)
End If
End Sub
Private Function GetLVGroupAt(X As Integer, Y as Integer) As String
Dim theGrp As String = ""
Dim ht As ListViewHitTestInfo = myLV.HitTest(X, Y)
' the mouse might be down over a NON item area, like a blank "row"
' AND if the items does not belong to a Group, 'Group' will
' be Nothing:
If (ht.Item IsNot Nothing) AndAlso (ht.Item IsNot Nothing) Then
theGrp = ht.Item.Group.Name
End If
Return theGrp
End Function
Evaluating the Group name is left for the consuming code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23969976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where are SKNode positioned in the responder chain? SKNode inherits from NSResponder but I'm having trouble understanding how nodes are included in the responder chain and where they are inserted.
For example, how does a SKNode receive the mouseDown: message?
When a view is clicked, a hit testing process occurs to determine the deepest view at the hit location and then mouseDown: is sent up the responder chain from that point.
SKNodes are not views so they cannot get send this message directly (because it it handled by the SKView). So how are they included in the responder chain?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29318501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Django: query filter I have two models that are related: one is a list of participants. The other is a list of times they have checked in or out of an office.
The table (Checkin) has one record for every checkin/checkout pair. So, there can be many records for any participant.
How can I retrieve only the very last (most recent) record for a participants checkin and then pass the participant and only that most recent Checkin record to my template?
From what I can tell there's no ability to do something like a last() in my template, so how would I go about filtering to get just that single record?
Thank you.
Models:
class Participant(models.Model):
first_name = models.CharField(max_length=50)
middle_initial = models.CharField(max_length=50, blank=True)
class CheckIn(models.Model):
adult = models.ForeignKey(
Participant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin')
checkin = models.DateTimeField(blank=True, null=True)
checkout = models.DateTimeField(blank=True, null=True)
View snipit:
p_checkins = Participant.objects.all().order_by('created')
queryset = p_checkins
context_object_name = "the_list"
template_name = 'list_of_checkins.html'
A: You can fetch data through most recent checkin or checkout.
For checkin :
p_checkins = CheckIn.objects.all().order_by('-checkin')[0]
For checkout :
p_checkins = CheckIn.objects.all().order_by('-checkout')[0]
To get the participant name by :
name = p_checkins.adult.first_name
A: When you use (-) your latest update will be query from database.
p_checkins = CheckIn.objects.all().order_by('-checkin')
or
p_checkins = CheckIn.objects.all().order_by('-checkout')
A: you can annotate the latest value via a subquery to the participant
from django.db.models import OuterRef, Subquery
checkin_q = CheckIn.objects.filter(adult=OuterRef('pk')).order_by('-checkin')
queryset = Participant.objects.annotate(last_checkin=Subquery(checkin_q.values('checkin')[:1]))
see https://docs.djangoproject.com/en/4.0/ref/models/expressions/#subquery-expressions
A: Most of the answers so far are correct in several aspects. One thing to note is that if your check_in or check_out values (whichever you use) isn't chronological (and by "most recent", you mean the last added), you'll want to add a created_at datetime field with auto_now option True, or order by the pk.
In addition to the other answers provided and my comment above, you can also get the most recent check in by using the related manager on the participant object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73031666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to show an Android dialog without graying out the back drop? I want to pop open a DatePickerDialog in a certain screen, but I am required to not grey out the rest of the screen (the view behind the dialog) when the DatePickerDialog window opens. Is there a way to achieve this?
A: You probably would want to create your own custom dialog. You can extend DialogFramgent and change it accordingly.
See the Android doc HERE for a great example.
Or, use PopupWindow if you want a popover dialog with control of the background, see this SO post.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25799144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: format JSON object into array like structure I am quite new to Python but trying to do some machine learning with it.
My problem is to format a received JSON object into an array like structure to submit this to my predictor function of the ML model.
JSON object looks like when I do a print of it
{u'CRIM': 0.62739, u'ZN': 0, u'B': 395.62, u'LSTAT': 8.47, u'AGE': 56.5, u'TAX': 307, u'RAD': 4, u'CHAS': 0, u'NOX': 0.538, u'MEDV': 19.9, u'RM': 5.834, u'INDUS': 8.14, u'PTRATIO': 21, u'DIS': 4.4986}
what i need is
[0.62739, 0, 395.62, 8.47, 56.5, 307, 4, 0, 0.538, 19.9, 5.834, 8.14, 21, 4.4986]
Can anybody help here
thanks
Peter
A: try:
json_var = {u'CRIM': 0.62739, u'ZN': 0, u'B': 395.62, u'LSTAT': 8.47, u'AGE': 56.5, u'TAX': 307, u'RAD': 4, u'CHAS': 0, u'NOX': 0.538, u'MEDV': 19.9, u'RM': 5.834, u'INDUS': 8.14, u'PTRATIO': 21, u'DIS': 4.4986}
value_array = json_var.values()
A: What you are looking for is
d = {'a':1, 'b': 2, 'c': 3}
num_list = d.values()
# num_list = [1,2,3]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33681858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Query to match a subset of data I have a table that looks like:
CLASS VALUE
1 A
1 B
1 C
2 A
2 C
3 B
3 D
4 A
5 C
5 A
I have a user-submitted data-set of values that I want to find any classes whose values are a subset of the user-submitted data-set.
For example,
If data-set was A, B, and C then the results would be class 1, 2, 4, and 5.
If data-set was A and C the results would be class 2, 4, and 5.
If data-set was A, then result would be class 4.
The platform I am on is SQL Server, but really any SQL-based answer would be best.
A: As per the comment It's passed as a table. - assuming the table is the variable @UserInput with a single column of Value, you can use a WHERE EXISTS clause to check for the existence of that value in the user-input fields, and pull the DISTINCT Class values.
Select Distinct Class
From YourTable T
Where Exists
(
Select *
From @UserInput U
Where T.Value = U.Value
)
Your SQL syntax will vary, but this should point you in the right direction, syntactically.
A full example of how to implement this would be as follows:
Creating the User-defined Table Type
Create Type dbo.UserInput As Table
(
Value Varchar (10)
)
Go
Creating the Stored Procedure
Create Proc dbo.spGetClassesByUserInput
(
@UserInput dbo.UserInput ReadOnly
)
As Begin
Select Distinct Class
From YourTable T
Where Exists
(
Select *
From @UserInput U
Where T.Value = U.Value
)
End
Go
Calling the Stored Procedure with user input
Declare @Input dbo.UserInput
Insert @Input
Values ('A'), ('B'), ('C')
Execute dbo.spGetClassesByUserInput @Input
A: You can create a stored procedure an pass the user entry as it as string for ex. A,B,C
Create Procedure dbo.GetClasses
@v_UserEntry Varchar(200)
As
Begin
Declare @SQLQuery AS NVarchar(1000)
Declare @ParamDefinition AS NVarchar(300)
SET @v_UserEntry= REPLACE(@v_UserEntry,',',''',N''')
Set @SQLQuery ='Select Class'
Set @SQLQuery = @SQLQuery + ' From TableName'
Set @SQLQuery = @SQLQuery + ' Where Value in (N'''+@v_UserEntry+''')'
Set @SQLQuery = @SQLQuery + ' Group By Class'
Execute sp_executesql @SQLQuery
End
Go
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39757285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can python read this type of config file? good morning. I want you help. I'm making a project using python but i want know if python2 can read this type of config file. Example:
[SETTINGS]
{
"Name": "SKY",
"SuggestedBots": 50,
"MaxCPM": 3000,
"LastModified": "2019-11-03T23:24:24.0854425-03:00",
"AdditionalInfo": "",
"Author": "KATO",
"Version": "1.1.4",
"IgnoreResponseErrors": false,
"MaxRedirects": 8,
"NeedsProxies": true,
"OnlySocks": false,
"OnlySsl": false,
"MaxProxyUses": 0,
"BanProxyAfterGoodStatus": false,
"EncodeData": false,
"AllowedWordlist1": "",
"AllowedWordlist2": "",
"DataRules": [],
"CustomInputs": [],
"ForceHeadless": false,
"AlwaysOpen": false,
"AlwaysQuit": false,
"DisableNotifications": false,
"CustomUserAgent": "",
"RandomUA": false,
"CustomCMDArgs": ""
}
I tryed with tutorials from internet but doesn't work. I think it's JSON.
A: If you drop the first line, then it can be used in python.
import json
test = '''{
"Name": "SKY",
"SuggestedBots": 50,
"MaxCPM": 3000,
"LastModified": "2019-11-03T23:24:24.0854425-03:00",
"AdditionalInfo": "",
"Author": "KATO",
"Version": "1.1.4",
"IgnoreResponseErrors": false,
"MaxRedirects": 8,
"NeedsProxies": true,
"OnlySocks": false,
"OnlySsl": false,
"MaxProxyUses": 0,
"BanProxyAfterGoodStatus": false,
"EncodeData": false,
"AllowedWordlist1": "",
"AllowedWordlist2": "",
"DataRules": [],
"CustomInputs": [],
"ForceHeadless": false,
"AlwaysOpen": false,
"AlwaysQuit": false,
"DisableNotifications": false,
"CustomUserAgent": "",
"RandomUA": false,
"CustomCMDArgs": ""
}'''
json.loads(test)
# {u'AlwaysQuit': False, u'Author': u'KATO', u'LastModified': u'2019-11-03T23:24:24.0854425-03:00', u'DataRules': [], u'AlwaysOpen': False, u'Version': u'1.1.4', u'DisableNotifications': False, u'NeedsProxies': True, u'CustomInputs': [], u'EncodeData': False, u'BanProxyAfterGoodStatus': False, u'SuggestedBots': 50, u'ForceHeadless': False, u'RandomUA': False, u'AdditionalInfo': u'', u'Name': u'SKY', u'CustomUserAgent': u'', u'MaxRedirects': 8, u'CustomCMDArgs': u'', u'OnlySocks': False, u'MaxProxyUses': 0, u'IgnoreResponseErrors': False, u'AllowedWordlist1': u'', u'AllowedWordlist2': u'', u'OnlySsl': False, u'MaxCPM': 3000}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60044151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pymodm can't find an object, while pymongo successfully finds it I have a problem getting an object from the mongodb instance. If I search for this object with pymongo interface, everything is fine - object can be found. If try to do the very same thing with pymodm - it fails with error.
Here is what I'm doing:
from pymodm import connect, MongoModel, fields
from pymongo import MongoClient
class detection_object(MongoModel):
legacy_id = fields.IntegerField()
client = MongoClient(MONGODB_URI)
db = client[MONGODB_DEFAULT_SCHEME]
collection = db['detection_object']
do = collection.find_one({'legacy_id': 1437424})
print(do)
connect(MONGODB_URI)
do = detection_object.objects.raw({'legacy_id': 1437424}).first()
print(do)
The first print outputs this: {'_id': ObjectId('5c4099dcffa4fb11494d983d'), 'legacy_id': 1437424}. However, during the execution of this command: do = detection_object.objects.raw({'legacy_id': 1437424}).first() interpreter fails with the following error:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pymodm/queryset.py", line 127, in first
return next(iter(self.limit(-1)))
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/konsof01/PycharmProjects/testthisfuckingshit/settings.py", line 29, in <module>
do = detection_object.objects.raw({'legacy_id': 1437424}).first()
File "/usr/local/lib/python3.7/site-packages/pymodm/queryset.py", line 129, in first
raise self._model.DoesNotExist()
__main__.DoesNotExist
How can this be? I'm trying to query the very same object, with the same connection and collection. Any ideas, please?
A: you could try it as follows:
detection_object.objects.raw({'legacy_id': "1437424"} ).first()
probably the legacy_id is stored as string.
Othewise, make sure the db name is present at the end of the MONGO_URI as it is underlined in the docs.
A: Each document in your 'detection_object' collection requires to have '_cls' attribute. The string value stored in this attribute should be
__main__.classname
(class name according to your code is detection_object).
For example a document in your database needs to look like this:
{'_id': ObjectId('5c4099dcffa4fb11494d983d'), 'legacy_id': 1437424, '_cls': '__ main __.detection_object'}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54239030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django Elasticbeanstalk: Cannot access static files when Debug = False My static files are served with no issue when Debug = True. I have read the documentation on https://docs.djangoproject.com/en/1.8/howto/static-files/deployment/ but still cannot get it to work when Debug = False. These are my settings (works fine when Debug = True):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = 'myapp/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"myapp","static","static-only")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR),"myapp","static"),
)
I have edited the config file to be:
container_commands:
collectstatic:
command: "myapp/manage.py collectstatic --noinput"
option_settings:
"aws:elasticbeanstalk:application:environment":
DJANGO_SETTINGS_MODULE: "myapp.settings"
PYTHONPATH: "/opt/python/current/app/myapp:$PYTHONPATH"
"aws:elasticbeanstalk:container:python":
WSGIPath: "myapp/myapp/wsgi.py"
"aws:elasticbeanstalk:container:python:staticfiles":
"/static/": "myapp/static/"
I have been banging my head on this for some time so any help would be much appreciated!
A: I don't have a direct answer to your question, other than to ask you why are you trying to do it this way. The best practice is to move your static files to S3 or ideally, CloudFront (or another non-AWS solution).
Use django-storages-redux (https://github.com/jschneier/django-storages) to use static files from S3 for production. Google 'django s3 static' and you will find several blogs explaining the process. The documentation is here.
A: collectstatic command would have collected all your static file to STATIC_ROOT which you had set as "/PATH/TO/myapp/static/static-only.
So I suspect that you pointed your static files to the wrong directory in the config file.
Try "/static/": "myapp/static/static-only"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33140147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: running load testing on selenium and api tests in Visual studio Team Services I am trying to run load tests on my existing selenium web tests and my api(unit) tests. The tests run in Visual studio using load test editor but does not collect all the metrics like response time and requests per seconds. Are there any additional parameters that I need to add to collect all the metrics ?
A: Load testing; how many selenium clients are you running? One or two will not generate much load. First issue to think about; you need load generators and selenium is a poor way to go about this (unless you are running grid headless but still).
So the target server is what, Windows Server 2012? Google Create a Data Collector Set to Monitor Performance Counters.
Data collection and analysis of same is your second issue to think about. People pays loads of money for tools like LoadRunner because they provide load generators and sophisticated data collection of servers, database, WANs and LANS and analysis reports to pinpoint bottlenecks. Doing this manually is hard and not easily repeatable. Most folks who start down your path eventually abandon it. Look into the various load/performance tools to see what works best for you and that you can afford.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40142206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: git remote /home/username/www/lorem.git
How can I use /home/username/www/example.git with remote add command?
if I use this:
git remote add origin [email protected]:/home/user/www/example.git
git push origin master
I got this error:
error: src refspec master does not match any.
error: failed to push some refs to '[email protected]:/home/user/www/example.git'
A: Default behaviour of git push is just to push "matching refs", i.e. branches which are present both in the local and the remote repository. In your example, there are no such branches, so you need to tell git push which branches to push explicitly, i.e. via
git push origin branch-to-be-pushed
or, if you want to push all branches,
git push --all origin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5218573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: No runtime warning when content compression/hugging constraints conflict with specific width/height constraints Example
A UIButton that has:
*
*1000 priority width constraint (say width = 20)
*1000 priority horizontal compression resistance priority
*wide content that is bigger than 20
I don't get any runtime warning (the one in debugger), but for me it seems that i should. The content (button title) gets truncated. Why there is no warning and how do i enable it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38720953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can you write a generic function that will compare any numeric type (e.g. int, float, double) against zero? We're trying to write a simple gain/loss function to return a color based on a value relative to zero. If it's positive, we return green. If negative, we return red. If zero, we return gray.
The current function is written specifically to take a double, like so:
func getChangeColor(value:Double) -> UIColor {
if value > 0 {
return Theme.Colors.gain
} else if value < 0 {
return Theme.Colors.loss
} else {
return Theme.Colors.noChange
}
}
But I'm wondering if it can be updated to take any numeric value?
My first thought was to write it against Comparable but the problem is we need to compare it against zero in that same type, whatever it is.
In other languages like C#, you can get the default value for a type, which in the case of numerics, is zero. Does Swift have anything similar? If so, we could do this...
func getChangeColor<T:Comparable>(value:T) -> UIColor {
let defaultValue = default(T.self)
if value > defaultValue {
return Theme.Colors.gain
} else if value < defaultValue {
return Theme.Colors.loss
} else {
return Theme.Colors.noChange
}
}
...or is this approach wrong in the first place?
A: My solution adds a second protocol conformance: Numeric provides basic arithmetic operators for scalar types.
Then you are able to calculate the zero value in the generic type
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {
let zero = value - value
if value > zero {
return Theme.Colors.gain
} else if value < zero {
return Theme.Colors.loss
} else {
return Theme.Colors.noChange
}
}
or with a switch statement
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {
let zero = value - value
switch value {
case zero: return Theme.Colors.noChange
case zero...: return Theme.Colors.gain
default: return Theme.Colors.loss
}
}
or with the ternary operator (added by OP)
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {
let zero = value - value
return value > zero
? Theme.Colors.gain
: value < zero
? Theme.Colors.loss
: Theme.Colors.noChange
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50066206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: SQL Query Return Entries with no Occurences in Other Table I have two tables, orders and customers, and I am trying to return the customerID and name of customers with no orders.
customers
customerID: integer
name: string
orders
orderID: integer
itemID: integer
customerID: integer
date: date
What I currently have is not returning any results:
SELECT customers.customerID, customers.fName, orders.date
FROM orders INNER JOIN customers
ON orders.customerID = customers.customerID
GROUP BY orders.customerID
HAVING COUNT(*) = 0
A: You need a LEFT OUTER JOIN to accomplish this:
SELECT customers.customerID, customers.fName
FROM customers LEFT OUTER JOIN orders on customers.customerID = orders.customerID
WHERE orders.customerID IS NULL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42542460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nearby Messages using an IntentService Initially I setup a BroadcastReceiver to receive intents from the Nearby Messages API.
class BeaconMessageReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Nearby.getMessagesClient(context).handleIntent(intent, object : MessageListener() {
override fun onFound(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Found iBeacon=$id")
sendNotification(context, "Found iBeacon=$id")
}
override fun onLost(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Lost iBeacon=$id")
sendNotification(context, "Lost iBeacon=$id")
}
})
}
private fun sendNotification(context: Context, text: String) {
Timber.d("Send notification.")
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification = NotificationCompat.Builder(context, Notifications.CHANNEL_GENERAL)
.setContentTitle("Beacons")
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification_white)
.build()
manager.notify(NotificationIdGenerator.nextID(), notification)
}
}
Then registered this receiver in my MainActivity after location permissions have been granted.
class MainActivity : AppCompatActivity() {
// ...
private fun onLocationPermissionsGranted() {
val filter = MessageFilter.Builder()
.includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
.build()
val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()
Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
}
private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
this, 0, Intent(context, BeaconMessageReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
}
This worked well while the app was open, but does not work when the app is closed. So I found this example, that demonstrates how to setup an IntentService to receive messages while the app is in the background.
The example does use the Nearby.Messages class, which was deprecated in favor of the MessagesClient. So I replaced the deprecated code with the MessagesClient implementation.
class MainActivity : AppCompatActivity() {
// ...
private fun onLocationPermissionsGranted() {
val filter = MessageFilter.Builder()
.includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
.build()
val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()
Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
.addOnSuccessListener {
Timber.i("Subscribed successfully.")
startService(Intent(this, BeaconMessageIntentService::class.java))
}.addOnFailureListener {
Timber.e(exception, "Subscription failed.")
}
}
private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
this, 0, Intent(context, BeaconMessageIntentService::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
}
And this is the IntentService (which is almost identical to my BroadcastReceiver).
class BeaconMessageIntentService : IntentService("BeaconMessageIntentService") {
override fun onHandleIntent(intent: Intent?) {
intent?.let {
Nearby.getMessagesClient(this)
.handleIntent(it, object : MessageListener() {
override fun onFound(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Found iBeacon=$id")
sendNotification("Found iBeacon=$id")
}
override fun onLost(message: Message) {
val id = IBeaconId.from(message)
Timber.i("Lost iBeacon=$id")
sendNotification("Lost iBeacon=$id")
}
})
}
}
private fun sendNotification(text: String) {
Timber.d("Send notification.")
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notification = NotificationCompat.Builder(this, Notifications.CHANNEL_GENERAL)
.setContentTitle("Beacons")
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification_white)
.build()
manager.notify(NotificationIdGenerator.nextID(), notification)
}
}
onHandleIntent is called, and the Intent is not null; yet for some reason onFound() and onLost() are never called. Why would this be the case?
A: It's not really a solution but what I found is this (credit to this answer):
I've tried a few configurations including a BroadcastReceiver and adding a JobIntentService to run the code in the background, but every time I got this the onExpired callback which you can set to the SubscribeOptions:
options.setCallback(new SubscribeCallback() {
@Override
public void onExpired() {
super.onExpired();
Toast.makeText(context.get(), "No longer Subscribing!", Toast.LENGTH_SHORT).show();
}
}
When the subscribe occurred in the background it was delayed, but it was still called.
Notes:
1. When I've tested with Strategy.BLE_ONLY I did not get the onFound callback.
2. From Google's documentation:
Background subscriptions consumes less power than foreground
subscriptions, but have higher latency and lower reliability
When testing I found this "lower reliability" to be an understatement: onFound was rarely called and I never got the onLost.
A: I know this is a late reply, but I had the same problem and found out by debugging that it is an issue related to this error: "Attempting to perform a high-power operation from a non-Activity Context". This can be solved when calling Nearby.getMessagesClient(this) by passing in an activity context instead of this.
In my case I added a class extending Application which helps in returning this context (the below is in java but should be translatable to kotlin easily)
public class MyApplication extends Application {
private Activity currentActivity = null;
public Activity getCurrentActivity(){
return currentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.currentActivity = mCurrentActivity;
}
}
And in my base activity, from which all activities extend, I set the current activity by calling ((MyApplication) this.getApplicationContext()).setCurrentActivity(this); in the constructor.
My service can then call getMessagesClient with the correct context like below:
final Activity context = ((MyApplication)getApplicationContext()).getCurrentActivity();
Nearby.getMessagesClient(context).[...]
Do not forget to register your Application class in the AndroidManifest:
<application
android:name="com.example.xxx.MyApplication"`
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53637194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Scanf doesn't work with fork in a loop after the second iteration I don't understand why scanf won't wait for input the second time in the loop. it only works in the first iteration. Also somewhat wait(&Status) won't print the correct Status.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int x ;
int Status =-99;
char* cmds[5];
cmds[1] = "who";
cmds[2] = "ls";
cmds[3] = "date";
cmds[4] = "kldsfjflskdjf";
int i=10;
while (i--) {
printf("\nMenu:\n");
printf("1)who \n"); printf("2)ls \n");printf("3)date\n");
printf("choice :");
scanf("%d", &x);
int child = fork();
if (child != 0) {
execlp(cmds[x], cmds[x], NULL);
printf("\nERROR\n");
exit(99);
} else {
wait(&Status);
printf("Status : %d", Status);
}
}
}
A: Like the comment posted above says, there are two problems here:
*
*You're running the command in the parent, rather than the child. See the fork manual.
*wait does not give you the return code. It gives you an integer that you need to decode. See the wait manual.
Here's the corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int x ;
int Status =-99;
char* cmds[6];
cmds[1] = "who";
cmds[2] = "ls";
cmds[3] = "date";
cmds[4] = "kldsfjflskdjf";
int i=10;
while (i--) {
printf("\nMenu:\n");
printf("1)who \n"); printf("2)ls \n");printf("3)date\n");
printf("choice :");
scanf("%d", &x);
int child = fork();
if (child == 0) {
execlp(cmds[x], cmds[x], NULL);
printf("\nERROR\n");
exit(99);
} else {
wait(&Status);
printf("Status : %d", WEXITSTATUS(Status));
}
}
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54134093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: undefined reference yaml-cpp I'm on Manjaro Linux using gcc and codelite to compile my code.
It's a project with sfml and yaml-cpp in C++.
My GCC version is 4.9.2 (20150304)
GCC compiler flags are -pg;-g;-O0;-O2;-Wall;-std=c++14
My yaml-cpp version is 0.5.1-1
When I compile I have the followings errors:
/bin/sh -c '/usr/bin/make -j4 -e -f "MyProject.mk" all'
----------Building project:[ MyProject - Debug ]----------
/usr/bin/g++ -c "/home/myuser/.codelite/MyProject/MyProject/sprite.cpp" -pg -g -O0 -O2 -Wall -std=c++14 -o ./Debug/sprite.cpp.o -I. -I/usr/include/
/usr/bin/g++ -c "/home/myuser/.codelite/MyProject/MyProject/tile.cpp" -pg -g -O0 -O2 -Wall -std=c++14 -o ./Debug/tile.cpp.o -I. -I/usr/include/
/usr/bin/g++ -c "/home/myuser/.codelite/MyProject/MyProject/main.cpp" -pg -g -O0 -O2 -Wall -std=c++14 -o ./Debug/main.cpp.o -I. -I/usr/include/
/usr/bin/g++ -c "/home/myuser/.codelite/MyProject/MyProject/grid.cpp" -pg -g -O0 -O2 -Wall -std=c++14 -o ./Debug/grid.cpp.o -I. -I/usr/include/
/usr/bin/g++ -c "/home/myuser/.codelite/MyProject/MyProject/loader.cpp" -pg -g -O0 -O2 -Wall -std=c++14 -o ./Debug/loader.cpp.o -I. -I/usr/include/
/usr/bin/g++ -o ./Debug/MyProject @"MyProject.txt" -L. -L/lib/ -lsfml-graphics -lsfml-window -lsfml-system -lsfml-network -lsfml-audio
./Debug/loader.cpp.o: in function « Mercenaries::Loader::Loader(std::string, std::vector<std::string, std::allocator<std::string> >) »:
/home/myuser/.codelite/MyProject/MyProject/loader.cpp:10: undefined reference to « YAML::LoadFile(std::string const&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::Node::AssignNode(YAML::Node const&) »:
/usr/include/yaml-cpp/node/impl.h:270: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o:/usr/include/yaml-cpp/node/detail/node_ref.h:29: more undefined reference follow to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::Node::AssignNode(YAML::Node const&) »:
/usr/include/yaml-cpp/node/impl.h:270: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o:/usr/include/yaml-cpp/node/detail/node_ref.h:29: more undefined reference follow to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node& YAML::detail::node_data::get<std::string>(std::string const&, boost::shared_ptr<YAML::detail::memory_holder>) »:
/usr/include/yaml-cpp/node/detail/impl.h:89: undefined reference to « YAML::detail::node_data::convert_to_map(boost::shared_ptr<YAML::detail::memory_holder>) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_scalar(std::string const&) »:
/usr/include/yaml-cpp/node/detail/node_ref.h:35: undefined reference to « YAML::detail::node_data::set_scalar(std::string const&) »
./Debug/loader.cpp.o: in function « convert_to_node<std::basic_string<char> > »:
/usr/include/yaml-cpp/node/detail/impl.h:162: undefined reference to « YAML::detail::memory_holder::merge(YAML::detail::memory_holder&) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node& YAML::detail::node_data::get<std::string>(std::string const&, boost::shared_ptr<YAML::detail::memory_holder>) »:
/usr/include/yaml-cpp/node/detail/impl.h:102: undefined reference to « YAML::detail::node_data::insert_map_pair(YAML::detail::node&, YAML::detail::node&) »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
./Debug/loader.cpp.o: in function « YAML::detail::memory_holder::create_node() »:
/usr/include/yaml-cpp/node/detail/memory.h:30: undefined reference to « YAML::detail::memory::create_node() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::mark_defined() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
/usr/include/yaml-cpp/node/detail/node_ref.h:29: undefined reference to « YAML::detail::node_data::mark_defined() »
./Debug/loader.cpp.o: in function « YAML::detail::node_ref::set_null() »:
/usr/include/yaml-cpp/node/detail/node_ref.h:34: undefined reference to « YAML::detail::node_data::set_null() »
Loader.cpp
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <iostream>
#include "loader.hpp"
namespace Mercenaries
{
Loader::Loader(std::string config_path, std::vector<std::string> fields_list) : m_config_path(config_path), m_fields_list(fields_list)
{
m_config_file = YAML::LoadFile(m_config_path);
}
void Loader::parse_file()
{
// if the file exist
if(!m_config_file.IsNull())
{
//the first node is the file
YAML::Node current_node = m_config_file;
// we get the next node
YAML::Node node = move_into_node(current_node, "Grid");
// get the data inside the node
auto data = node;
}
else
{
// the file doesn't exist
std::cout << "Failed to load " << m_config_path << " settings file.";
}
}
YAML::Node Loader::move_into_node(YAML::Node current_node, std::string next_node)
{
YAML::Node node;
// we verify that the node exist
if(current_node[next_node])
{
node = current_node[next_node]; // get the value
}
else
{
// the node doesn't exist in the yaml file
std::cout << next_node << " node is not found in " << m_config_path << " goal file";
}
return(node);
}
}
Loader.hpp
#ifndef DEF_LOADER
#define DEF_LOADER
#include <yaml-cpp/yaml.h>
namespace Mercenaries
{
class Loader
{
public:
Loader(std::string config_path, std::vector<std::string> fields_list);
void parse_file();
YAML::Node move_into_node(YAML::Node current_node, std::string next_node);
private:
std::string m_config_path;
YAML::Node m_config_file;
std::vector<std::string> m_fields_list;
};
}
#endif
Do you think that it's an yaml-cpp issue ?
Is there an error in my code that make it bug ?
Should I report it if it's a yaml issue ?
A: It looks like you're not linking to yaml-cpp; you need to add the argument -lyaml-cpp (to the command that begins /usr/bin/g++ -o ./Debug/MyProject).
A: If you are considering a CMakeLists.txt project ...
cmake_minimum_required(VERSION 3.10)
project(Test_yaml_cpp)
set(CMAKE_CXX_STANDARD 14)
# In case of third party library
#find_package(yaml-cpp PATHS ./thirparty/yaml-cpp/build)
# In case of installed library
find_package(yaml-cpp)
add_executable(yaml_exec main.cpp)
target_link_libraries(yaml_exec yaml-cpp)
In case of the third-party approach, the yaml-cpp library should be already built inside build folder and recommended by their documentation.
A: Try add following to your cmakelist:
find_package(PkgConfig REQUIRED)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29196832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C# MySQL Connection problems I'm trying to connect a C# application (using Visual C# 2008 Express Edition) to a remote MySQL server. I have the drivers for this, but when I followed the tutorials (including adding the pooling and connection reset properties), I get an error that: Object reference not set to an instance of an object. I've included the two lines of code that should be making a connection. The error is thrown on the second line.
MySqlConnection connect = new MySqlConnection("database=d*******;Data Source=mysql.netfirms.com;user id=*******;pwd=*****;pooling=false;connection reset=false");
connect.Open();
A: I'd try setting the connection string outside of the constructor to help narrow down the issue:
MySqlConnection connect = new MySqlConnection();
//Do you get the null exception in this next line?
connect.ConnectionString = "your conn string here";
connect.Open(); //-> If you get the exception here then the problem is with the connection string and not the MySqlConnection constructor.
If you do get the exception in the connect.ConnectionString = ... line, then the problem is with the driver and sounds like you need to reinstall it.
I would also try a simpler connection string, without the pooling and reset keys.
A: Can you post more code? The exception line is probably a bit off due to compiler optimization or related. Constructors must return an object or throw an exception. It is impossible to say
MyType item = new MyType();
Debug.Fail(item == null); // will never fail.
The null reference is probably on the line just above your instantiation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/403398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: g:submitButton- onclick doesn't work I have the following g:submitButton:
<g:submitButton name="next" class="signup-button skyblue-btn pull-right pl-pr-36" value="${message(code:"buttons.ok")}" onclick="return showSpinnerSignUp()"/>
I define the showSpinnerSignUp() in the JS file:
$(function() {
function showSpinnerSignUp(){
$('.spinner-ctn').show();
return true;
}
});
The spinner is not displayed (the onclick doesn't work).
A: This is the default behaviour of a form submission in the browser. You have registered a showSpinnerSignUp() method on the click of a button while the click on that same button is responsible for submitting the enclosing form.
Since the browser's built-in behavior for submitting forms works by making a full roundtrip to the server, that immediately interrupts your code execution of onclick event because your browser is navigating away from your current page.
This can be simulated as if you had clicked your button and refreshed the page immediately. Your current setup might work when you deploy this to the production server, but the possibility of working this setup locally is low because a local development server used to run on a faster machine so the page refresh time of form submission is quite faster.
To verify this happening, open your browser's console and call the method showSpinnerSignUp() directly (remember to remove it from $(function() {}) temporarily) and see if the spinner is showing up.
Also, there is an option to Preserve Logs which keeps the Javascript console logs even after page refresh. So, put a simple console.log() inside your method call and then try hitting that button. You'll see your method is called but no spinner is displayed due to form submission.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33151056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iPhone/iPod Touch: application executable contains unsupported architeture(s): armv7s i'im seeing a problem releasing on AppStore my App!
The validation process say: "iPhone/iPod Touch: application executable contains unsupported architeture(s): armv7s"
this is my library linked:
CoreLocation (required)
Twitter (optional)
QuartzCore (required)
MapKit (required)
UIKit (required)
Foundation (required)
CoreGraphics (required)
libGoogleAnalytics.a (required)
libsqlite3.dylib (required)
CFNetwork (required)
I've also tryed to remove GoogleAnalytics Library but the problem is the same! Do you have any idea?
Thanks
A: Based on discussions at the Apple dev forums (https://devforums.apple.com/message/749949) it looks like this is a bug affecting a lot of people. Probably due to a change in Apple's validations servers.
I was able to work around it by changing the build architecture in Build Settings from Standard(armv7,armv7s) to armv7 and rebuilding. This should only have the effect that the compiled code is not optimized for iPhone 5. It will still run, but may not be quite as fast as if it were compiled for armv7s. I suspect the performance difference would be negligible in most cases.
A: This helped me:
Project -> Build Settings -> remove the architecture from "valid
architectures" as well as setting the "Build Active Architecture Only"
to Yes in the Project
A: I had the same problem today. My app has no third-party libraries.
12 days ago I submitted a build from Xcode 4.5.1 that was subsequently reviewed and released to the App Store. Today I tried to submit a new build and suddenly received this error.
I then tried to validate the same executable (not a rebuild) from within Xcode that I had submitted 12 days ago and that had passed validation and is now available for download in the App Store, but this time it failed validation with the above error.
Performing step 4 above allowed me to submit the new build. But the executable is smaller even though I have added a small amount of code and three small png/jpegs. This makes me think that armv7s code is missing from the archive.
What is happening? Why should step 4 above 'work'? Why does an executable that previously submitted OK and was released suddenly no longer pass validation?
Note: this is not a duplicate of any previous post that I was able to find 15 hours ago. This is the first time I have seen any mention made of seeing this error when submitting to iTunes Connect rather than receiving a compiler warning. So please do not mark this as a duplicate. It is not.
A: Most of the answers here are ones that I did not find ideal, mainly because they essentially suggest that you remove armv7s support from your app. While that will make you app pass validation, that could potentially make your app run slower on the iPhone 5.
Here is the workaround I'm using (though, I must say that I wouldn't call this a solution).
Instead of using XCode Organizer, I'm uploading the binary using Application Loader.
To upload the binary using Application Loader
Open Organizer > Right Click on Archive > Reveal in Finder.
Right Click the Archive file > Show Archive Content
Go to Products > Application > YourAPP.app
Compress YourAPP.app and upload using Application Loader.
A: My problem was the fact I was using an old version of Application Loader.
The solution for me was to download the latest version of Application Loader iTunes Connect > Manage Your Applications > Download Application Loader and try again.
A: Try this:
1.Select your project in Xcode (with the blue icon)
2.Select Build Settings
3.Set the view to All/Combined
4.Set "Build Active Architecture Only" to Yes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13148083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Values from checkbox group are correct in querystring, but are not arrays in the $_GET variable I have a form, with a checkbox group which looks like this:
<label><input type="checkbox" name="countries" value="US" class="chkcountries" checked="checked" /> United States</label><br />
<label><input type="checkbox" name="countries" value="FR" class="chkcountries" checked="checked" /> France</label><br />
<label><input type="checkbox" name="countries" value="CA" class="chkcountries" checked="checked" /> Canada</label><br />
<label><input type="checkbox" name="countries" value="AU" class="chkcountries" checked="checked" /> Australia</label><br />
<label><input type="checkbox" name="countries" value="UK" class="chkcountries" checked="checked" /> United Kingdom</label><br />
<label><input type="checkbox" name="countries" value="DE" class="chkcountries" checked="checked" /> Germany</label><br />
<label><input type="checkbox" name="countries" value="Ja" class="chkcountries" checked="checked" /> Japan</label><br />
<label><input type="checkbox" name="countries" value="IT" class="chkcountries" checked="checked" /> Italy</label><br />
<label><input type="checkbox" name="countries" value="IN" class="chkcountries" checked="checked" /> India</label><br />
<label><input type="checkbox" name="countries" value="ES" class="chkcountries" checked="checked" /> Spain</label><br />
<label><input type="checkbox" name="countries" value="BR" class="chkcountries" checked="checked" /> Brazil</label><br />
<label><input type="checkbox" name="countries" value="NL" class="chkcountries" checked="checked" /> Netherlands</label><br />
<label><input type="checkbox" name="countries" value="MX" class="chkcountries" checked="checked" /> Mexico</label><br />
When I select more than one country and run the form and print_r both the query string and the $_GET array, the querystring looks like this:
report=rawdata&sales=sales&kenp=kenp&startdate=&enddate=&format=table&track=unit&countries=US&countries=CA&countries=AU&countries=UK&allchannels=All&channels=2&channels=1&books=5&submit=Get+Report
and the $_GET array looks like this:
Array ( [report] => rawdata [sales] => sales [kenp] => kenp [startdate] => [enddate] => [format] => table [track] => unit [countries] => UK [allchannels] => All [channels] => 1 [books] => 5 [submit] => Get Report [SQLiteManager_currentLangue] => 2 )
As you can see, it's only selecting the last item in the countries array. (The same thing happens in checkbox groups on this form, e.g. channels).
I'm working in a test environment running MAMP on my Mac, FWIW.
What's weird is that it was working properly. (I've tried rebooting MAMP and then rebooting my entire system to see if that makes a difference, and it doesn't seem to.)
It's possible I've missed something dumb somewhere, but I've now been looking at it so long, I'm going cross-eyed. Any assistance would be greatly appreciated.
A: I think that you need to do an array for your select :
<select name="countries[]" multiple>
And then deal with the array in your php code.
A: PHP determines if form data should be presented as a string or an array based on the name of the field, not the number of times it appears.
Append [] to the name attribute in the HTML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40205062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Import SQL File into existing DB-Table (phpmyadmin) I have an SQL-File defining a table with 2 columns - product-id and product-reference. I need to import that file into an existing table that has the same structure (plus some extra columns), where product-id corresponds to the product-id from the backup file. Is there a simple way to do that via phpmyadmin?
A: One approach is to use load data infile (see here) with the set option to assign column values. Columns that are not being set will be given their default values, which is typically NULL.
Personally, I would load the data into a staging table with two columns and then insert the data from the staging table into the final table. This makes it easier to validate the data before putting it into the "real" table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27331719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ gdb breakpooint in second thread causing core dump I have a C++ program I'm trying to debug in a new docker instance that is causing the program to crash when I try to hit a breakpoint in a created thread (but not the launch thread). Another version of the program run on a separate computer (different g++, gdb versions) works. I've created a test app to replicate the problem.
I'm using a ubuntu docker image (which is new to me). I've started a docker container with:
docker run -it -v "/home/test/":"/home/test" -w "/home/test" ubuntu
I've attached to this container in VS Code, in the /home/test/ folder. I've then installed g++ and gdb with: apt-get update then apt-get install g++ gdb.
This installs versions g++: 4:11.2.0-1ubuntu1 gdb: 12.0.90-0ubuntu1
I then create a main.cpp with the following code:
#include <iostream>
#include <chrono>
#include <thread>
void thread_runner()
{
while (1) {
std::cout << "Background Thread" << std::endl; //Second Breakpoint
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
int main()
{
std::cout << "Test App" << std::endl; // First Breakpoint
std::thread ioc_thread = std::thread(thread_runner); // Create a separate (background) thread to run the io_context on
ioc_thread.join();
}
And I set breakpoints on the 2 std::cout ... lines.
I create a tasks.json file to compile this, which looks like:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "Task generated by Debugger."
},
],
"version": "2.0.0"
}
Then I run the command "Run and Debug" and use that task to compile. I hit the first breakpoint at "Test App" okay but it crashes before hitting "Background Thread", the terminal output is:
Test App
Aborted (core dumped)
[1] + Aborted (core dumped) "/usr/bin/gdb" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-mv2ltsxy.3ok" 1>"/tmp/Microsoft-MIEngine-Out-0zvvty3q.t43"
If I remove the second breakpoint the app runs printing "Background Thread" every second.
Apologies for the long winded description. I'm not sure where I'm going wrong so I looked to include everything. The other computer that appears to work (using my full original program) using g++ 9.3 and gdb 8.1.
A: I had a similar issue where my program would coredump when there was a breakpoint present in a thread. I found out that my instance of gdb (12.0.9) was not working, and installing 12.1 from launchpad fixed my issue.
Found solution here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72287460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Azure giving subscription level resource group access to application I created a application in active directory and gave access to it at the resource group level and I am able to access the resources inside the resource group. But I don't see any option in preview portal to give access to the application at the subscription level.
When I am running the following code
ResourceManagementClient client =
testMain.createResourceManagementClient();
ResourceGroupOperations gpoperations = client.getResourceGroupsOperations();
ResourceGroup gp1 = new ResourceGroup("West US");
ResourceGroupCreateOrUpdateResult res = gpoperations.createOrUpdate("test123", gp1);
System.out.println("Resource group creation result" + res.getRequestId()+res.toString());
I am getting the following exception
Exception in thread "main"
com.microsoft.windowsazure.exception.ServiceException:
AuthorizationFailed: The client '2e027029-1019-46dc-b540-cbfe4a761647'
with object id '2e027029-1019-46dc-b540-cbfe4a761647' does not have
authorization to perform action
'Microsoft.Resources/subscriptions/resourcegroups/write' over scope
'/subscriptions/88335ad5-6fe2-4532-b3d5-1af946310f85/resourcegroups/test123'.
at com.microsoft.windowsazure.exception.ServiceException.createFromJson(ServiceException.java:292)
at com.microsoft.azure.management.resources.ResourceGroupOperationsImpl.createOrUpdate(ResourceGroupOperationsImpl.java:495)
at com.mycompany.resourcegroup.testMain.main(testMain.java:70)
How can i give access to the application, so that it can create and manage any resource group in my subscription ?
A: *
*GO to your Azure Active Directory
*Click on Groups
*Click “+ New Group”
*Select the group type “Security”
*Enter group name (any name you want)
*Select Membership type “Assigned”
*In the owner select the owner of the application
*In the members select the application that you created/registered in the active directory.
*Now you are able to create your resources directly from your java client.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33382836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CentOS 6 not displaying I installed CentOS on Oracle VirtualBox and it run perfectly fine on command line but then I installed desktop environment by typing the following command:
yum groupinstall "X windows system" "KDE Desktop", edit the initdefault id from 3 (command line) to 5 (GUI), save the file and reboot the system but it doesn't display the login screen, in fact it hangs on loading. . Please help me out in this.
I can't attach the image as the message pops up stating that i need at least 10 reputation to post images...
I will write down the last two lines when it hangs..
Starting postfix : [OK]
Starting httpd: [OK]
Starting crond: [OK]
Thanks.
A: It seems that some yum commands are case sensitive (atleast install and groupinstall), so the correct command is
$ yum groupinstall "X Window System" "KDE Desktop"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25088274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Select sub element based on classes it has Below is the HTML that I have
<ul id="QBS">
<li>
<a class="qb_mode starting Rodgers" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Manning" href="#">See Stats</a>
</li>
<li>
<a class="qb_mode Brady" href="#">See Stats</a>
</li>
</ul>
I want to find this unordered list, then tell which item has the starting qb class and then return the class that has their name (brady rodger manning) etc.
What's throwing me in a loop is the fact that the link is wrapped in the list element.
Here is what I am trying:
element = $("#qbs"); // pretty sure I want this vs getElementbyDocumentID
children = element.children();` // gets me all the list elements
for (i=0;i<children.length;i++) {
grandchild = children[i].children();
???? How would I get the 3rd class on this element?
}
Sorry about the formatting.
A: How about this?
var allClasses = $("#QBS").find('li a[class^="qb_"]')
.map(function () {
return this.className.split(" ").pop();
}).get();
console.log(allClasses);
Fiddle
Provided the class started with qb_* is at the beginning and you want to take only the last class of the match.
if all your class names are qb_mode then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
return this.className.split(" ").pop();
}).get();
if you want all of them then:
var allClasses = $("#QBS").find('.qb_mode').map(function () {
var cls = this.className.replace(/qb_mode/,'');
return cls.trim().split(/\W+/);
}).get();
console.log(allClasses);
Fiddle
A: If I understood you correctly, how about:
var name = $('#QBS a.qb_mode.starting').prop('class').replace(/\s*(qb_mode|starting)\s*/g,'');
console.log(name); // Rogers
See demo here.
A: a=document.getElementById('QBS');
var b=a.getElementsByClassName("qb_mode");
var i, j=b.length, result=[];
for(i=0;i<j;i++) {
c=b[i].className.split(" ");
result.push(c.pop());
}
return result;
A: fiddle http://jsfiddle.net/3Amt3/
var names=[];
$("#QBS > li a").each(function(i){
var a=$(this).attr("class").split(" ");
names[i]=a[(a.length-1)];
console.log("Name is " + names[i]);
});
or a more precise selector
$("#QBS > li a.qb_mode").each( ....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17458856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to fetch with method GET And Type script I'm true beginner with type script
can you help me with this simple fetch
this is function
export async function askForList(){
return await fetch('http://127.0.0.1:3333/applist').then((res) => res.json())
}
this is expected data
interface RnMcharacter{
id: number,
img: string,
name: string,
number: number
};
I'v tried many combination but moast common error is
ERROR in src/transmission/apiserv.ts:27:4
@typescript-eslint/no-unsafe-return: Unsafe return of an any typed value.
Can you show me example of proper function so I can understad what mi doing wrong.
Thx
A: You can type the data prop as RnMcharacter.
You can also remove the then call as you're using async|await
export async function askForList(){
const res = await fetch('http://127.0.0.1:3333/applist');
const { data }: { data: RnMcharacter } = await res.json();
return data;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71592960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Akka cluster error Is it mandatory to use sbt for cluster usage in akka. I have tried to add a few jars to the classpath. While the compiling goes well, running the relevant class generates an error.
scala -cp
../akka-2.2.1/lib/akka/akka-cluster_2.10-2.2.1.jar:../akka-2.2.1/lib/akka/netty-3.6.6.Final.jar:../akka-2.2.1/lib/akka/akka-remote_2.10-2.2.1.jar:../akka-2.2.1/lib/akka/protobuf-java-2.4.1.jar:./
TransformationFrontend 2551
here's the issue encountered:
java.lang.NoSuchMethodException:
akka.cluster.ClusterActorRefProvider.(java.lang.String,
akka.actor.ActorSystem$Settings, akka.event.EventStream,
akka.actor.Scheduler, akka.actor.DynamicAccess) at
java.lang.Class.getConstructor0(Class.java:2800) at
java.lang.Class.getDeclaredConstructor(Class.java:2043)
This is the official Akka cluster example. Can someone throw some light on my query?
A: The issue here is probably that you have an akka-actor.jar in your scala distributuion that is Akka 2.1.x and you're trying to use Akka 2.2.x.
You'll have to run your code by running the java command and add the scala-library.jar and the correct akka-actor.jar and typesafe-config.jar to the classpath.
A: Are you using Scala 2.10? This is the Scala version you need for Akka 2.2.
What does the following yield?
scala -version
It should show something like
$ scala -version
Scala code runner version 2.10.3 -- Copyright 2002-2013, LAMP/EPFL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19131003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: actionscript facebook get url of uploaded image using the latest facebook actionscript library, I upload an image using:
Facebook.api('me/photos', etc...)
it returns an ID, which method would I call to get the url of the uploaded image?
Thanks.
A: Looks like it's a simple REST service call: https://graph.facebook.com/10150146071831729
Take a look at the "Example" at the bottom of this page: https://developers.facebook.com/docs/reference/api/photo/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7135748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: My worker threads are not being picked up I'm implementing worker threads in my Node/Typescript application. Now I've come quite far except for the fact that it seems my worker threads are not being picked up/executed. I've added some loggers inside function which should be executed by the worker thread, but for some reason it doesn't show.
I'm calling a function to create a worker. Like this:
create_worker("./src/core/utils/worker.js", {
term: "amsterdam",
search_grid: chunked_maps_service![i],
path: "../../adapters/worker.ts",
})
And this is the function to create a worker:
import { Worker } from "worker_threads";
const create_worker = (file: string, workerData: {}) =>
new Promise<void>((resolve, reject) => {
const worker = new Worker(file, {
workerData: workerData,
});
worker.on("message", resolve);
worker.on("error", reject);
worker.on("exit", (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
export default create_worker;
Because I'm using typescript I need to compile the typescript code to javascript code to make the worker understand it: Like this:
const path = require("path");
const { workerData } = require("worker_threads");
require("ts-node").register();
require(path.resolve(__dirname, workerData.path));
And then this is the function which should be executed in the worker thread:
import { parentPort } from "worker_threads";
async function worker() {
console.log("started");
parentPort.postMessage("fixed!");
}
Is there anything I'm forgetting?
A: You aren't ever calling the function in your worker.
This code in the worker:
import { parentPort } from "worker_threads";
async function worker() {
console.log("started");
parentPort.postMessage("fixed!");
}
Just defines a function named worker. It never calls that function.
If you want it called immediately, then you must call it like this:
import { parentPort } from "worker_threads";
async function worker() {
console.log("started");
parentPort.postMessage("fixed!");
}
worker();
FYI, in the worker implementations I've built, I usually either execute something based on data passed into the worker or the worker executes something based on a message it receives from the parent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74828363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Issues with validation in rails I have a working validation on my user model. But since we're discovered that users tend to give up during their long registration form, we've split up registration form into steps so that user can give up any time and still use the site.
I'm having issues with the first step of user registration with validations. Here is the relevant bit of my User model :
with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
user.validates :firstname, presence: true, length: { maximum: 50 }
user.validates :surname, presence: true, length: { maximum: 50 }
user.validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX }
user.validates :password_digest, presence: true
user.validates :password, length: { minimum: 6 }
end
This validation works perfectly. However we now added facebook so its possible to login with facebook and we have hidden fields in our form facebook_uid. So I want to validate password only if these fields are nil.
Here is how I tried to modify my current validation :
with_options :if => lambda { |u| u.current_step == "get_started" } do |user|
user.validates :firstname, presence: true, length: { maximum: 50 }
user.validates :surname, presence: true, length: { maximum: 50 }
user.validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX }
with_options :if => lambda { |u| u.facebook_uid.nil? } do |user|
user.validates :password_digest, presence: true
end
with_options :if => lambda { |u| u.user.password_digest_changed? && !u.password.nil? } do |user|
user.validates :password, length: { minimum: 6 }
end
end
Or inline (the relevant password part only) :
user.validates :password_digest, presence: true, if: lambda { |u| u.facebook_uid.nil? }
user.validates :password, length: { minimum: 6 }, if: lambda { |u| u.user.password_digest_changed? && !u.password.nil? }
None of these worked for me, whatever I tried I get this error :
undefined method `user' for #<User:0x00000008e924a8>
Again if I remove ifs and lambdas works as charm. Is there another way of accomplishing this or something I'm currently doing wrong with my code?
A: In your password validation lambda, you're calling
u.user.password_digest_changed? && !u.password.nil?
ie, you're sending a user method to the u object, which is your User instance. That object doesn't respond to user. You probably just want
u.password_digest_changed? && !u.password.nil?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20883188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Navigation Drawer does not cover an activity I am writing an organiser app and I am stuck at this problem. Navigation drawer stacks itself with the listview in activity 1 . There is no exception and the app is working, but the listview elements and navigation drawer elements are clicked at the same time.
Here is the activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EventActivity">
<androidx.drawerlayout.widget.DrawerLayout
android:id="@+id/my_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
A: DrawerLayout should be the parent of your layout. Here`s my example:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false"
tools:openDrawer="end">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
//my code
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/navrapoarte"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
>
//my code
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="200dp"
android:orientation="vertical">
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72363247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Click “Accept Cookies” popup with Selenium in Python I've been trying to scrape some information of this E-commerce website with selenium. However when I access the website I need to accept cookies to continue. This only happens when the bot accesses the website, not when I do it manually. When I try to find the corresponding element either by xpath, as I find it when I inspect the page manually I always get this error message:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
My code is mentined below.
import time
import pandas
pip install selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup #pip install beautifulsoup4
PATH = "/Users/Ziye/Desktop/Python/chromedriver"
delay = 15
driver = webdriver.Chrome(PATH)
driver.implicitly_wait(10)
driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()
This is the HTML corresponding to the button "That's ok". The XPATH is as above.
<button aria-label="" id="uc-btn-accept-banner" class="uc-btn uc-btn-primary">
That’s OK <span id="uc-optin-timer-display"></span>
</button>
Does anyone know where my mistake lies?
A: You should add explicit wait for this button:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.implicitly_wait(10)
driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="uc-btn-accept-banner"]')))
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()
Your locator is correct.
As css selector, you can use .uc-btn-footer-container .uc-btn.uc-btn-primary
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67274590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Inverse process of :keys destructuring: construct map from sequence The more I write in Clojure, the more I come across the following sort of pattern:
(defn mapkeys [foo bar baz]
{:foo foo, :bar bar, :baz baz})
In a certain sense, this looks like the inverse process that a destructuring like
(let [{:keys [foo bar baz]}] ... )
would achieve.
Is there a "built-in" way in Clojure to achieve something similar to the above mapkeys (mapping name to keyword=>value) - perhaps for an arbitrary length list of names?
A: No such thing is built in, because it doesn't need to be. Unlike destructuring, which is fairly involved, constructing maps is very simple in Clojure, and so fancy ways of doing it are left for ordinary libraries. For example, I long ago wrote flatland.useful.map/keyed, which mirrors the three modes of map destructuring:
(let [transforms {:keys keyword
:strs str
:syms identity}]
(defmacro keyed
"Create a map in which, for each symbol S in vars, (keyword S) is a
key mapping to the value of S in the current scope. If passed an optional
:strs or :syms first argument, use strings or symbols as the keys instead."
([vars] `(keyed :keys ~vars))
([key-type vars]
(let [transform (comp (partial list `quote)
(transforms key-type))]
(into {} (map (juxt transform identity) vars))))))
But if you only care about keywords, and don't demand a docstring, it could be much shorter:
(defmacro keyed [names]
(into {}
(for [n names]
[(keyword n) n])))
A: I find that I quite frequently want to either construct a map from individual values or destructure a map to retrieve individual values. In the Tupelo Library I have a handy pair of functions for this purpose that I use all the time:
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test))
(dotest
(let [m {:a 1 :b 2 :c 3}]
(with-map-vals m [a b c]
(spyx a)
(spyx b)
(spyx c)
(spyx (vals->map a b c)))))
with result
; destructure a map into values
a => 1
b => 2
c => 3
; construct a map
(vals->map a b c) => {:a 1, :b 2, :c 3}
P.S. Of course I know you can destructure with the :keys syntax, but it always seemed a bit non-intuitive to me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66951309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Inconsistent date between SSAS Cube and Tabular Model I have a very weird problem. I have built a tabular model which takes data from a SSAS cube. In the data source cube, there is a column called "Process Date" and it is in UK date format (dd/mm/yyyy). When I bring this column into my model, the dates are messed up, where the date and month values are swapped for some dates!
Below are the images to illustrate this and I have highlighted one particular date in red. In the data source SSAS cube, the date is 12/02/2019, and when it goes to the tabular model, this date beomces 02/12/2019. I have added a check_month column in the tabular model and found that the tabular model thinks its December i.e. the day/month has been swapped!
data source date
model date
Thank you
JC
Edit: This has been solved by changing the Locale Identifier in the connection. See the comment in the answer below by userfl89. This is due to the data source cube is using a different locale (US English) then what I am using in the model, changing the locale identifier will override this and hence solve the problem
A: The date format can be defined from SSDT. Highlight the date column and go to the properties window (press F4). For the Data Format property select the desired date format. If you need a date format that's not listed a calculated column using the FORMAT function can be created based off the original column, with the data type of this column then set to Date. An example of this is below. Additionally, confirm the Locale Identifier (LCID) in SSDT. This can by viewed by selecting Model > Existing Connections > Edit > Build > All > then the Locale Identifier property. The Microsoft documentation provides details in regards to identifying the correct LCID.
=FORMAT('Process'[Process Date], "dd-MM-yyyy")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55001834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to properly consume a WCF Web Service in a Classic Xamarin Solution? I'm following the documentation on Consuming a WCF Web Service and need clarification on how best to do this in a Classic Xamarin (not Xamarin Forms) solution that uses a .NET Standard library.
Specifically, I need to understand whether separate API calls must be wrapped in the interface class e.g. ISoapService so that they can be made asynchronously? The project already as an auto-generated Reference.cs class that documents all the available web service endpoints. Does the interface class need to include all potential API calls?
How do ensure that my interface class is properly referenced from the Xamarin.Android and Xamarin.IOS projects? Is there something specifically required aside from referencing the .NET Standard Project from the mobile projects?
I've looked high and low for WCF web service integration with Classic Xamarin but have not found any helpful samples Any links would be helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52732458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Thread scheduling in .NET regarding blocking calls Suppose I spawn 3 threads in a C# application: T1, T2 and T3 and issue Run calls for each.
Usually, the processor will schedule the threads in a round-robin fashion (single processor and all threads have same priority).
However, suppose Thread T1 issues a Blocking web service call.
Will it be preempted immediately or after completion of its time slice?
Basically does issuing the web service network call (or any other call) cause the thread to be in a blocked state?
A: Once a thread issues a blocking system call (any request to IO) it is suspended, and only marked as "Ready" (not yet running) when that system call completes.
So yes it will be preempted immediately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8226681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: android : LayoutInflater in static method i want to call LayoutInflater from static method as below :
private static void inflateLayout_keluarga_pp(int counter2, String name) {
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.layoutkeluarga, null);
..................
..................
}
this is how i call method inflateLayout_keluarga_pp :
public static void onRetrieve(int position){
List<ModelKeluargaPP> mk = helper.getSelectTable_Marital();
for (int i=0; i<mk.size();i++){
inflateLayout_keluarga_pp(i,mk.get(position).getAnggota_pp());
}
}
but i got error in getActivity(), they said : Cannot make a static reference to the non-static method getActivity() from the type Fragment i need to make this method into static. how to fix it? i hope someone can help to solve my problem, thank you.
A: getActivity() belongs to the instance of the current Fragment; it cannot be part of a static context.
When you declare a method static, you are stating that this method will not belong to each particular instance of the Class; it belongs to the Class itself. Since the static method will be available regardless if you instantiate an object of the Class, you cannot guarantee that object members and methods (that are not static) will be available. Hence you cannot reference "things" that will be available only when the object is instantiated inside a static method that will always be available.
Like Jems said, if you need to access the Fragment you need to always make it available within the method's scope. This can be accomplished by either passing a Fragment to the static method or by instantiating it inside the static method.
A: If it must be static, pass a reference to the Fragment you want to call getActivity on into the method.
private static void inflateLayout_keluarga_pp(int counter2, String name, Fragment myFragment) {
LayoutInflater inflater = (LayoutInflater)myFragment.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21273387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Create a Mobile Responsive Version of a PowerBI report that is Published to the Web I've recently published a specific PowerBI report and despite creating a 'Phone' View on PowerBI Desktop this didn't show up in the final embed code.
I've looked into PowerBI Embedded Playground and managed to generate the relevant access tokens and even try it out, but still couldn't figure out how to modify the code in such a way to generate a mobile view.
The questions and answers below somehow didn't give me the insight I needed, still somehow need some additional work:
Mobile view is not being shown for embedded powerbi report
Create Report in Embed View via PowerBI API
Power BI RS web embedding in mobile web browser
What do I need to do to get started? Which documentation do I need to look into exactly? I need to embed this report in a Sharepoint 2010 Page and I need it to be mobile responsive on page load and not via a seperate link.
A: This isn't related to the access token in any way. It is generated before configuring the embedding process. To embed the report in phone view, you must specify MobilePortrait layout type in the embed configuration, i.e. something like this:
var config = {
.....
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true,
layoutType: models.LayoutType.MobilePortrait <-- THIS ONE
}
};
If you omit layoutType, it will be shown in the landscape view (i.e. like in the desktop). For more information about the configuration see Embed Configuration Details, and for embedding in general you should start from Embedding Basics.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62113403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Replace NULL with SUBTOTAL and TOTAL in a ROLLUP I have tried to use IFNULL to replace the NULL fields returned by ROLLUP for subtotals and totals but it doesn't appear to be working.
Query:
select IFNULL(usergroups.name, 'GROUP') AS DEALER,
IFNULL(users.name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
and vcrs.vcrSubStatus = 4
group by DEALER, SERVICE_ADVISOR with ROLLUP;
Output:
DEALER SERVICE_ADVISOR COMPLETED IDENTIFIED AUTHORISED
Aston Martin Chris 3 664.56 0
Aston Martin Graham 6 0 0
Aston Martin (NULL) 15 664.56 0
Bentley Sukraj 1 0 0
Bentley Terry 4 0 0
Bentley (NULL) 5 0 0
Jaguar Emma 10 2448 1224
Jaguar Paul 1 0 0
Jaguar Simon 7 2754 918
Jaguar (NULL) 18 5202 2142
(NULL) (NULL) 2611 96591.62 42130.14
Desired Output:
DEALER SERVICE_ADVISOR COMPLETED IDENTIFIED AUTHORISED
Aston Martin Chris 3 664.56 0
Aston Martin Graham 6 0 0
Aston Martin TOTAL 15 664.56 0
Bentley Sukraj 1 0 0
Bentley Terry 4 0 0
Bentley TOTAL 5 0 0
Jaguar Emma 10 2448 1224
Jaguar Paul 1 0 0
Jaguar Simon 7 2754 918
Jaguar TOTAL 18 5202 2142
GROUP TOTAL 2611 96591.62 42130.14
A: To resolve the issue with COALESCE/IFNULL still returning NULL for the WITH ROLLUP placeholders, you need to GROUP BY the table column names, rather than the aliased column expressions.
The issue is caused by the GROUP BY clause being specified on the aliased column expressions, because the aliases are assigned after the column expression is processed.
Resulting in the WITH ROLLUP NULL placeholders not being in the recordset to be evaluated by COALESCE.
Meaning the aliases DEALER, SERVICE_ADVISOR in the GROUP BY do not exist until after IFNULL/COALESCE have already been executed.
See MySQL Handling of GROUP BY for more details.
Example DB-Fiddle
CREATE TABLE foo (
`amount` INTEGER,
`created` INTEGER
);
INSERT INTO foo
(`amount`, `created`)
VALUES
('1', '2019'),
('2', '2019');
Query #1 (Reproduce Issue)
SELECT
SUM(amount) AS amounts,
COALESCE(created, 'Total') AS created_coalesce
FROM foo
GROUP BY created_coalesce WITH ROLLUP;
| amounts | created_coalesce |
| ------- | ---------------- |
| 3 | 2019 |
| 3 | |
Query #2 (Corrected)
SELECT
SUM(amount) AS amounts,
COALESCE(created, 'Total') AS created_coalesce
FROM foo
GROUP BY foo.created WITH ROLLUP;
| amounts | created_coalesce |
| ------- | ---------------- |
| 3 | 2019 |
| 3 | Total |
Use-Case Specific
Example DB-Fiddle
SELECT
COALESCE(usergroups.name, 'GROUP') AS DEALER,
COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
/* ... */
GROUP BY usergroups.name, users.name WITH ROLLUP;
Query #1 (Original)
SELECT
COALESCE(usergroups.name, 'GROUP') AS DEALER,
COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED
/* ... */
GROUP BY DEALER, SERVICE_ADVISOR WITH ROLLUP;
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo | Jane Doe | 1 |
| Foo | John Doe | 1 |
| Foo | | 2 |
| | | 2 |
Query #2 (Corrected)
SELECT
COALESCE(usergroups.name, 'GROUP') AS DEALER,
COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED
/* ... */
GROUP BY usergroups.name, users.name WITH ROLLUP;
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo | Jane Doe | 1 |
| Foo | John Doe | 1 |
| Foo | TOTAL | 2 |
| GROUP | TOTAL | 2 |
Considerations
*
*
With MySQL 5.7+ and ONLY_FULL_GROUP_BY enabled, selected
non-aggregate columns that are not specified in the GROUP BY clause
will fail. Meaning the following query will not work as expected: DB-Fiddle
SELECT COALESCE(YEAR(foo), 'foo') /* ... */ GROUP BY YEAR(foo) WITH ROLLUP
-> ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.foo_bar.foo' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
*
COALESCE,
IFNULL,
IF(... IS NULL)
and CASE WHEN ... IS NULL
will all function
similarly. Where IFNULL is the proprietary to MySQL and is a less
functional replacement of COALESCE. As COALESCE can accept more
than two parameters to check against NULL, returning the first non-NULL value.
mysql> SELECT COALESCE(NULL, NULL, 1, NULL);
-> 1
mysql> SELECT IFNULL(NULL, 1);
-> 1
mysql> SELECT IF(NULL IS NULL, 1, '');
-> 1
mysql> SELECT CASE WHEN NULL IS NULL THEN 1 END;
-> 1
*
nullable columns in the GROUP BY as either aliases or column names, will result in the NULL values being
displayed as the WITH ROLLUP placeholder. This applies to using WITH ROLLUP in general. For example if
users.name can return NULL. DB-Fiddle
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo | TOTAL | 1 |
| Foo | Jane Doe | 1 |
| Foo | John Doe | 1 |
| Foo | TOTAL | 3 |
| GROUP | TOTAL | 3 |
Prevent NULL column values from being displayed
To ensure that nullable columns are not accidentally included, you would need to specify in the criteria to exclude them.
Example DB-Fiddle
SELECT
COALESCE(usergroups.name, 'GROUP') AS DEALER,
COALESCE(users.name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED
FROM vcrs
LEFT JOIN users
ON users.id = vcrs.uid
LEFT JOIN usergroups
ON usergroups.id = users.group_id
WHERE vcrs.vcrSubStatus = 4
AND users.name IS NOT NULL
GROUP BY usergroups.name, users.name
WITH ROLLUP;
Result
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo | Jane Doe | 1 |
| Foo | John Doe | 1 |
| Foo | TOTAL | 2 |
| GROUP | TOTAL | 2 |
Since LEFT JOIN is used on the vcrs table, IS NOT NULL must be
applied to the WHERE clause, instead of the ON clause. As LEFT JOIN returns NULL for non-matching criteria. To circumvent the
issue, use an INNER JOIN to limit the resultset to only those with
matching ON criteria.
/* ... */
INNER JOIN users
ON users.id = vcrs.uid
AND users.name IS NOT NULL
/* ... */
WHERE vcrs.vcrSubStatus = 4
GROUP BY usergroups.name, users.name
WITH ROLLUP;
Include NULL columns values
To explicitly include nullable column values, without duplicating the WITH ROLLUP placeholder name, you would need to utilize a derived table subquery to substitute the NULL value as a textual value.
Example DB-Fiddle
SELECT
COALESCE(v.usergroup_name, 'GROUP') AS DEALER,
COALESCE(v.user_name, 'TOTAL') AS SERVICE_ADVISOR,
COUNT(DISTINCT v.uid) AS COMPLETED
FROM (
SELECT
usergroups.name AS usergroup_name,
COALESCE(users.name, 'NULL') AS user_name,
vcrs.uid
FROM vcrs
LEFT JOIN users
ON users.id = vcrs.uid
LEFT JOIN usergroups
ON usergroups.id = users.group_id
WHERE vcrs.vcrSubStatus = 4
) AS v
GROUP BY v.usergroup_name, v.user_name
WITH ROLLUP;
Result
| DEALER | SERVICE_ADVISOR | COMPLETED |
| ------ | --------------- | --------- |
| Foo | Jane Doe | 1 |
| Foo | John Doe | 1 |
| Foo | NULL | 1 |
| Foo | TOTAL | 3 |
| GROUP | TOTAL | 3 |
You can also optionally replace the 'NULL' textual placeholder as desired and even display it as NULL.
SELECT
COALESCE(v.usergroup_name, 'GROUP') AS DEALER,
CASE v.user_name WHEN 'NULL' THEN NULL ELSE COALESCE(v.user_name, 'TOTAL') END AS SERVICE_ADVISOR,
COUNT(DISTINCT v.uid) AS COMPLETED
FROM (
/* ... */
) AS v
GROUP BY v.usergroup_name, v.user_name
WITH ROLLUP;
A: I'm only 2 years too late, but since I came across the same issue as @the_gimlet I thought I'd post the answer.
So don't know if this is a mySQL versioning or something, but using mysql 5.6 I get the same problem... ifnull will not replace the rollup 'nulls'.
Simply get around this by making your rollup a subquery, and doing the ifnulls in the main select... annoying to repeat the select, but it works!
e.g. for example above
SELECT
IFNULL(`DEALER`, 'GROUP') AS DEALER,
IFNULL(`SERVICE_ADVISOR`, 'TOTAL') AS SERVICE_ADVISOR,
`COMPLETED`,
/* .......... */
FROM (SELECT
usergroups.name AS DEALER,
users.name AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
/* .......... */
AND vcrs.vcrSubStatus = 4
GROUP BY DEALER, SERVICE_ADVISOR with ROLLUP);
A: Do you want something like this?
SELECT COALESCE(usergroups.name, 'GROUP') AS DEALER,
COALESCE(users.name, IF(usergroups.name IS NULL, 'TOTAL', 'SUBTOTAL')) AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
AND vcrs.vcrSubStatus = 4
GROUP BY DEALER, SERVICE_ADVISOR with ROLLUP;
Test:
mysql;root@localhost(playground)> select * from t;
+------+----------+-------+--------+
| id | car | state | tstamp |
+------+----------+-------+--------+
| 1 | toyota | new | 1900 |
| 2 | toyota | old | 1950 |
| 3 | toyota | scrap | 1980 |
| 4 | mercedes | new | 1990 |
| 5 | mercedes | old | 2010 |
| 6 | tesla | new | 2013 |
+------+----------+-------+--------+
6 rows in set (0.04 sec)
mysql;root@localhost(playground)> select car, sum(tstamp) from t group by car with rollup;
+----------+-------------+
| car | sum(tstamp) |
+----------+-------------+
| mercedes | 4000 |
| tesla | 2013 |
| toyota | 5830 |
| NULL | 11843 |
+----------+-------------+
4 rows in set (0.03 sec)
mysql;root@localhost(playground)> select coalesce(car, 'huhu'), sum(tstamp) from t group by car with rollup;
+-----------------------+-------------+
| coalesce(car, 'huhu') | sum(tstamp) |
+-----------------------+-------------+
| mercedes | 4000 |
| tesla | 2013 |
| toyota | 5830 |
| huhu | 11843 |
+-----------------------+-------------+
4 rows in set (0.00 sec)
A: What you're looking for is a case statement.
What you're saying is that under a certain condition replace the found value with the one specified. You can use multiple when/then statements depending on how customised you'd like the replacements to be.
select IFNULL(usergroups.name, 'GROUP') AS DEALER,
case when(users.name is null) then 'TOTAL' else users.name end AS SERVICE_ADVISOR,
COUNT(DISTINCT vcrs.uid) AS COMPLETED,
..........
..........
and vcrs.vcrSubStatus = 4
group by DEALER, SERVICE_ADVISOR with ROLLUP;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25443822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Laravel: One relation, multiple models I have a model "User", and each user has "Posts". Now there are different types of posts, like "TextPost", "VideoPost", etc.
I want to get all posts of a user like this:
$user->posts()->get()
This should return an array of objects with the correct class, so e.g. an array like this:
[App\VideoPost{}, App\TextPost{}]
I tried to use polymorphic relationships as described in the docs, but it doesn't work. Any ideas?
A: There isn't really a relationship type in Laravel for your specific use case. The easiest thing you can do in this case is create a separate hasMany relationship for each of your post types, and then write a function that returns a combination of all the results.
So you'd end up with something like this in your User class:
public function videoPosts()
{
return $this->hasMany(App\VideoPost::class);
}
public function textPosts()
{
return $this->hasMany(App\TextPost::class);
}
public function getPosts()
{
return $this->textPosts->concat($this->videoPosts);
}
You can then just keep chaining concat calls for every other post type you may want to add.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47081863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenXML excel sheet creation. Formula does not work automatically when I use Indirect to reference a list I am creating an excel template using OpenXML through c# for users to populate and import into our system.
Part of the process is for the user to select options from dropdowns and hidden columns are populated with the Id's of those selections using VLOOKUP formula. All of the ones with direct list references work fine.
I have one instance where the selection from a list called "Application Group" drives what list is used in the next column called "Application". This is done using the INDIRECT function in excel and works fine. The problem comes when trying to get the id for the dynamic list. I will post the code below but put simply opening the excel and selecting an option from application group correctly puts the correct list in Application. Selecting application does not populate the applicationid column automatically. If I select the applicationid column to see the formula is is fine. If I click into the edit box at the top of excel and then tab out of it the formula then triggers and will work from then on. Once again this is a VLOOKUP using the INDIRECT to creat the reference to the list.
I've done a few tests and it seems the INDIRECT is the issue as if I hard code the list name the vlookup triggers as it should.
I also removed the substitute functions but this did not make any difference.
I've checked the calculation mode on the column and it is set to automatic.
I've already searched online but found nothing relevant
// Application Group
cell = new Cell() { CellReference = "AI" + rownumber };
cell.CellValue = new CellValue();
cellFormula = new CellFormula()
{
Text = "VLOOKUP(AH" + rownumber.ToString() + " ,ApplicationGroupList,2,FALSE)"
};
cell.CellFormula = cellFormula;
row.Append(cell);
// Application
cell = new Cell() { CellReference = "AK" + rownumber };
cell.CellValue = new CellValue();
cellFormula = new CellFormula()
{
Text = "VLOOKUP(AJ" + rownumber.ToString() + ",INDIRECT(SUBSTITUTE(SUBSTITUTE(AH" + rownumber.ToString() + ",\" \",\"\"),\"/\",\"\") & \"Id\") ,2,FALSE)"
};
cell.CellFormula = cellFormula;
row.Append(cell);
There are no error messages and the formula is correct as simply clicking in the edit box triggers the formula and it works from then on. It seems like excel is not recognising it as a formula even though it was set up in the same way as others that work fine. See the code above. Application group works fine. Application doesn't but the formula created is fine syntactically and functionally.
Does anyone have any experience of something similar and how to get the formula to work as all the others do.
A: Ok well as seems often to be the case I've spent ages looking at this myself. Exhausted all the options, or so I thought. Just after I post this I think I'll just try this thing I've not had to do for any of the other formula just in case. Bingo!
So I had to add
cellFormula.CalculateCell = true;
And this seemed to solve the problem. Why I needed it I don't know as everything else seems to work without explicitly setting this flag but problem seems to be solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56474036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking for distance history using google API (or other) I've been searching and i thought i could ask you directly in here.
I'm looking for an API (maybe Google) that does the same work as Google fit history API as of recording every distance you made and the transportation mode. It is not necessary for me to get the exact latitude or longitude by at least the number of kilometer/meter(or miles) made by day in cars/foot/run/bike by a user(using an Android App). Google fit History API is great but, if i'm correct, it only records physical activities such as foot/run/bike.
I've look for Google ActivityRecognitionClient API that gives me a way to know the transportation mode and confidence % for a certain time but still, i need to have the distance made with this transportation mode.
What i need is something like :
Date : 2019-04-24
Activity : 1
TransportationMode : Foot
distance : 10km
Date : 2019-04-24
Activity : 2
TransportationMode : car
distance : 100km
etc.
Any of you know a way to do this?
A: I don't know about an API that you can use. However I found a research paper on ML model that predicts travel mode on the basis of GPS information. If you have sufficient time to develop your own AI model you may try this:
AI model Predicting travel mode
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55840663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: F# Type providers and Sky Biometry Has anyone used the F# type providers with Sky Biometry?
A majority of the calls work great with the type providers. However, when I call the faces/recognize method, I am getting fails using both the Json and the Xml type provider.
Using the Json one, I declare the type like this:
type skybiometryJsonFaceRecognition = JsonProvider<"http://api.skybiometry.com/fc/faces/recognize.json?uids=default@ImageComparer&urls=https://lg2014dev.blob.core.windows.net/d69bdda9-d934-448c-acae-99019f3a564f/01ee184f-ff0b-426f-872a-cbc81ef58d90.jpg&api_key=XXXXX&api_secret=yyyyy">
When I try and use the type in my code, it is failing on the last part of the graph:
let recognition = skybiometryJsonFaceRecognition.Load(stringBuilder.ToString())
It should be:
recognition.Photos.[0].Tags.[0].Uids.[0].confidence
But instead I get:
recognition.Photos.[0].Tags.[0].Uids.[0].JsonValue
I then swapped over to the Xml type provider for just this one call and I am getting intellisense working:
let recognition = skybiometryXmlFaceRecognition.Load(stringBuilder.ToString())
recognition.Photos.Photo.Tags.Tag.Uids.Uid.Confidence
But when I run it, I get
System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
Looking at the XML in a call from my browser, it sure looks fine to me:
Does anyone have any suggestions? Thanks
A: Thanks to ntr's suggestion, I changed the type def to use local storage. The Json TP then found all of the props and the actual call worked as expected. Thanks everyone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24309686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to do WHERE IN with sqlalchemy? Here is what I'm trying to do. The database is Postgres.
numbers is a Python set() or some other iterable.
session.execute(table.update().\
where(func.substring(table.c.number,1 ,5) in numbers).\
values(provider="testprovider")
The problem with this is that in numbers doesn't seem to work. It will work for a single number if I do something like where(func.substring(table.c.number,1, 5)== '12345')
I've googled a lot on how to do WHERE IN with sqlalchemy, but all of them are with a SELECT query or do use the .in_() function on the column itself. For example this answer: link
The documentation also says the .in_() only works on the columns.
So, I don't really know how to proceed here. How can I write this expression?
A: Ah nevermind, although the documentation doesn't say it, I can use the .in_() function on the result of func.substring.
So
where(func.substring(table.c.number, 1, 5).in_(numbers))
worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64793016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JPA 2: mapping a map where the key is an entity, value is Boolean We are trying to map a relation where an entity has a map where the key is another entity and the value is a Boolean:
@Id Long id;
@ElementCollection
@CollectionTable(name = "APPROVALS_PRODUCT_APPROVALS", joinColumns = @JoinColumn(name = "PRODUCT_APPROVAL_ID", referencedColumnName = "ID"))
@Column(name = "EXCLUDED")
private Map<Approval, Boolean> approvals = new HashMap<Approval, Boolean>();
For some reason, Eclipselink gives a BigDecimal for each value in the map, instead of Boolean.
approvals.get(testApproval); // returns a BigDecimal :-(
Is there anything that doesn't look right? Is this us, or is this a bug in Eclipselink?
EDIT:
Tried this (Approval has 2 @Id fields):
@ElementCollection
@CollectionTable(name = "APPROVALS_PRODUCT_APPROVALS", joinColumns = @JoinColumn(name = "PRODUCT_APPROVAL_ID", referencedColumnName = "ID"))
@Column(name = "EXCLUDED")
@MapKeyJoinColumns({ @MapKeyJoinColumn(name = "CREDENTIAL_VALUE", referencedColumnName = "CREDENTIAL_VALUE"), @MapKeyJoinColumn(name = "CREDENTIAL_TYPE", referencedColumnName = "CREDENTIAL_TYPE") })
private Map<Approval, Boolean> approvals = new HashMap<Approval, Boolean>();
and got the same result (BigDecimal instead of Boolean)
EDIT2:
We are using Eclipselink 2.3.0, also tried with 2.3.2 with same result.
A: Your code is wrong,
targetClass on ElementCollection is for specifying an Embeddable class (if generics are not used), so should be not used.
You also need a @MapKeyJoinColumn if you want the Map key to be another object (or @MapKeyClass if it is an Embeddable.
Most databases do not have a Boolean type, so booleans are normally stored as numbers, 0/1. So you may be missing a conversion somehow. You can define an @Convert with a @TypeConverter for this, although it should be getting defaulted, so you may log a bug for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9770836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I'm getting java.lang.IllegalStateException: sequencer not open. What's the solution? This is the code I'm trying to run but I keep getting IllegalStateException. I'm relatively new to java and I need some help figuring this out. Thanks:)
This is the code:
import javax.sound.midi.*;
public class MiniMusicApp {
public static void main(String[] args){
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}//Close main
public void play(){
try{
Sequencer player = MidiSystem.getSequencer();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
}catch(Exception ex){
ex.printStackTrace();
}
}//close play
}//close class
And I'm getting this:
java.lang.IllegalStateException: sequencer not open
at java.desktop/com.sun.media.sound.RealTimeSequencer.start(RealTimeSequencer.java:232)
at MiniMusicApp.play(MiniMusicApp.java:21)
at MiniMusicApp.main(MiniMusicApp.java:6)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:421)
at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:192)
at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:132)
A: For demonstration only, don't do this
As @Abra said, you need to call the open method:
import javax.sound.midi.*;
public class MiniMusicApp {
public static void main(String[] args){
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}//Close main
public void play(){
try{
Sequencer player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
}catch(Exception ex){
ex.printStackTrace();
}
}//close play
}//close class
However you should also close it at the end:
import javax.sound.midi.*;
public class MiniMusicApp {
public static void main(String[] args){
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}//Close main
public void play(){
Sequencer player = null;
try{
player = MidiSystem.getSequencer();
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
}catch(Exception ex){
ex.printStackTrace();
}
finally {if(player!=null) player.close();}
}//close play
}//close class
The correct way
But this way is error prone, so in modern Java you should use try-with-resource to close it automatically:
import javax.sound.midi.*;
public class MiniMusicApp {
public static void main(String[] args){
MiniMusicApp mini = new MiniMusicApp();
mini.play();
}//Close main
public void play(){
Sequencer debug = null; // just for demonstrating that it is really closed at the end
try(Sequencer player = MidiSystem.getSequencer())
{
debug = player;
player.open();
Sequence seq = new Sequence(Sequence.PPQ, 4);
Track track = seq.createTrack();
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent noteOff = new MidiEvent(b, 16);
track.add(noteOff);
player.setSequence(seq);
player.start();
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println(debug.isOpen());
}//close play
}//close class
A: You forgot to open the Sequencer, which is why you got an exception. To open the player
Sequencer player = MidiSystem.getSequencer();
player.open();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72137060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Diff: ignoring lines with just tabs I'm trying to diff files, and determine if they are the same, but ignoring ALL whitespace.
When using diff, the -b tells diff to ignore whitespace on a given line. The -B option tells it to ignore all blank lines. But, if you have a line which contains only spaces, the -B and -b don't seem to work together.
I've resorted to using the -I option, where I want diff to ignore all lines which only contain whitespaces, which works fine when the line contains only spaces, but the \t doesn't seem to match tab characters.
I found one reference online that mentioned that you need to use POSIX regexp, but POSIX states that :blank: will match any whitespace (including tab). That does not work either.
Here's a sample of what I'm trying to do. Ideally, my diff line would state that t1.txt, t2.txt and t3.txt were all the same.
bash#> echo hi > t1.txt
bash#> echo hi > t2.txt
bash#> echo hi > t3.txt
bash#> echo " " >> t2.txt
bash#> echo -e "\t" >> t3.txt
bash#> diff -BbaNq -I "^[ \t]*$" t1.txt t2.txt
bash#> diff -BbaNq -I "^[ \t]*$" t1.txt t3.txt
Files t1.txt and t3.txt differ
bash#> diff -BbaNq -I "^[:blank:]*$" t1.txt t3.txt
Files t1.txt and t3.txt differ
bash#>
Any help in what the syntax for diff would be would be very helpful.
A: try this:
diff -wBt -u t1.txt t2.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12538748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Google Maps Marker Clusterer: markers never cluster I don't know why the marker clusterer don't show my markers grouped, like here: http://media.svennerberg.com/2009/01/screenshot_clusterereffect.jpg
I am facing a problem in Google map marker clustering. I am using api v3, but due to some reasons, which I am not able to figure out, I cannot apply marker clustering. I'd be thankful for any help and suggestions.
My Code is like this:
<!DOCTYPE HTML>
<html lang="pl">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD_n_0mOPCs7DxlW4t6rzSiD0KyUXQktVY&callback=myMap"></script>
<script type="text/javascript">
var map;
var infoWindow;
var markersData = [
{lat: 50.25202,
lng: 19.015023,
name: "Test1",
address1: "Test1",
address2: "Test1",
address3: "2019-03-13",
address4: "2019-03-13",
ikona: "http://historia-lokalna.pl/images/places.png" ,
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"},
{lat: 49.824791,
lng: 19.040867,
name: "Test2",
address1: "Test2",
address2: "Test2",
address3: "2019-03-22",
address4: "2019-03-22",
ikona: "http://historia-lokalna.pl/images/places.png" ,
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"},
{lat: 50.334918,
lng: 18.14136,
name: "Test3",
address1: "Test3",
address2: "Test3",
address3: "2019-03-08",
address4: "2019-03-08",
ikona: "http://historia-lokalna.pl/images/places.png" ,
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"},
{lat: 49.825794,
lng: 19.040889,
name: "Test4",
address1: "Test4",
address2: "Test4",
address3: "2019-03-13",
address4: "2019-03-13",
ikona: "http://historia-lokalna.pl/images/places.png" ,
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"},
]
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(50.57628900072813,21.356987357139587),
zoom: 9,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
displayMarkers();
// I added a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, marker,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
// End
}
google.maps.event.addDomListener(window, 'load', initialize);
function displayMarkers(){
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersData.length; i++){
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var address3 = markersData[i].address3;
var address4 = markersData[i].address4;
var image = markersData[i].ikona;
var wwwsite = markersData[i].wwwsite;
createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite);
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
function createMarker(latlng, name, address1, address2,address3,address4, image, wwwsite){
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + name + '</div>' +
'<div class="iw_content">' + address1 + '<br />' +
address2 + '<br />' +address3 + '<br />' +address4 + '<br />' +
wwwsite + '</div></div>';
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
}
</script>
<!-- I added a javascript markerclusterer -->
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<!-- End -->
</head>
<body>
<h2 class="przeg">Map:</h2>
<div id="map-canvas"style="width:100%;height:600px;"> </div>
</body>
</html>
A: Looking at the example in the documentation and your code, probably the simplest "fix" is to instantiate the marker clusterer inside your display markers routine, then add each marker to the clusterer as it is created:
Comments:
*
*you have have a callback specified in you script include (&callback=myMap), but no function of that name (just remove that from your script include). Causes this error in the console:
"myMap is not a function"
*There is a javascript error Uncaught ReferenceError: marker is not defined on this line: var markerCluster = new MarkerClusterer(map, marker, because there is no variable marker available in that scope (and as @MrUpsidown observed in his comment, that should be the array of markers). To address that I suggest using the MarkerClusterer.addMarker method to add markers to it in displayMarkers, and changing your createMarker function to return the marker it creates.
function displayMarkers() {
// marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var address3 = markersData[i].address3;
var address4 = markersData[i].address4;
var image = markersData[i].ikona;
var wwwsite = markersData[i].wwwsite;
markerCluster.addMarker(createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite));
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
function createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + name + '</div>' +
'<div class="iw_content">' + address1 + '<br />' +
address2 + '<br />' + address3 + '<br />' + address4 + '<br />' +
wwwsite + '</div></div>';
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
return marker;
}
proof of concept fiddle
code snippet:
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script type="text/javascript">
var map;
var infoWindow;
var markersData = [
{
lat: 50.25202,
lng: 19.015023,
name: "Test1",
address1: "Test1",
address2: "Test1",
address3: "2019-03-13",
address4: "2019-03-13",
ikona: "http://historia-lokalna.pl/images/places.png",
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"
},
{
lat: 49.824791,
lng: 19.040867,
name: "Test2",
address1: "Test2",
address2: "Test2",
address3: "2019-03-22",
address4: "2019-03-22",
ikona: "http://historia-lokalna.pl/images/places.png",
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"
},
{
lat: 50.334918,
lng: 18.14136,
name: "Test3",
address1: "Test3",
address2: "Test3",
address3: "2019-03-08",
address4: "2019-03-08",
ikona: "http://historia-lokalna.pl/images/places.png",
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"
},
{
lat: 49.825794,
lng: 19.040889,
name: "Test4",
address1: "Test4",
address2: "Test4",
address3: "2019-03-13",
address4: "2019-03-13",
ikona: "http://historia-lokalna.pl/images/places.png",
wwwsite: "<a href=https://www.historia-lokalna.pl target=_blank >Strona www</a>"
},
]
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(50.57628900072813, 21.356987357139587),
zoom: 9,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
displayMarkers();
// End
}
google.maps.event.addDomListener(window, 'load', initialize);
function displayMarkers() {
// marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
var name = markersData[i].name;
var address1 = markersData[i].address1;
var address2 = markersData[i].address2;
var address3 = markersData[i].address3;
var address4 = markersData[i].address4;
var image = markersData[i].ikona;
var wwwsite = markersData[i].wwwsite;
markerCluster.addMarker(createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite));
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
function createMarker(latlng, name, address1, address2, address3, address4, image, wwwsite) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: name,
// icon: image - so shows default icon in code snippet
});
google.maps.event.addListener(marker, 'click', function() {
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">' + name + '</div>' +
'<div class="iw_content">' + address1 + '<br />' +
address2 + '<br />' + address3 + '<br />' + address4 + '<br />' +
wwwsite + '</div></div>';
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
return marker;
}
</script>
<!-- markerclusterer script -->
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<!-- End -->
<h2 class="przeg">Map:</h2>
<div id="map-canvas" style="width:100%;height:80%;"> </div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55074734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to call methods from other class?
I am trying to write a Java program to book hotel rooms. I have written methods in one class and am trying to call it from my main class, but I don't know how to do it.
The program asks the user to input necessary info for the methods, but I just don't know how to execute it.
I also want to know how to change the status of a room to "B" - for booked, when the user enters the RoomId and confirms their booking and then to print the information using the print() method in Room.java. Any help would be great. Thanks
Room.java
package utilities;
public class Room
{
private String roomId;
private String description;
private String status;
private double dailyRate;
private DateTime bookingStartDate;
private DateTime bookingEndDate;
public Room(String roomId, String description, double dailyRate)
{
this.setRoomId(roomId);
this.setDescription(description);
this.setDailyRate(dailyRate);
this.status = "A";
}
public boolean bookRoom (String customerID, int nightsRequired)
{
if (status.equals('A'))
{
System.out.println("You have booked the room");
status = "B";
return true;
}
else
{
System.out.println("This room cannot be booked");
return false;
}
}
public void print()
{
System.out.println("Room ID: " + getRoomId());
System.out.println("Description: "+ getDescription());
System.out.println("Status: " + status);
System.out.println("Daily Rate: " + getDailyRate());
if (status.equals('B'))
{
System.out.println(bookingStartDate);
System.out.println(bookingEndDate);
}
else{
}
}
/**
* @return the dailyRate
*/
public double getDailyRate() {
return dailyRate;
}
/**
* @param dailyRate the dailyRate to set
*/
public void setDailyRate(double dailyRate) {
this.dailyRate = dailyRate;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the roomId
*/
public String getRoomId() {
return roomId;
}
/**
* @param roomId the roomId to set
*/
}
TestRoom.java
package stuff;
import java.util.Scanner;
import utilities.Room;
public class TestRoom {
public static void main(String[] args)
{
Room [] rooms =
{
new Room("GARDEN0001", "NorthWest Garden View", 45.00),
new Room("GARDEN0002", "SouthEast Garden View", 65.0),
new Room("GARDEN0003", "North Garden View", 35.00),
new Room("GARDEN0004", "South Garden View", 52.0),
new Room("GARDEN0005", "West Garden View", 35.00),
new Room("GARDEN0006", "East Garden View", 35.00)
};
Scanner userInput = new Scanner(System.in);
System.out.println("Input a lower price range. ");
int lower = userInput.nextInt();
System.out.println("Input an upper price range. ");
int upper = userInput.nextInt();
if (lower < 65)
{
for ( int i = 0; i < rooms.length; i++ )
{
if (rooms[i].getDailyRate() > lower && rooms[i].getDailyRate() < upper )
{
System.out.println("ID: \t" + rooms[i].getRoomId() );
System.out.println("DESC: \t" + rooms[i].getDescription() );
System.out.println("RATE: \t" + rooms[i].getDailyRate() + "\n");
}
}
}
else
{
System.out.println("There are no rooms that fit your criteria.");
}
System.out.println("Input the ID of the room you wish to book.");
String roomId = userInput.next();
System.out.println("Please enter your customer ID");
String customerID = userInput.next();
System.out.println("Please enter the amount of nights you wish to stay.");
int nightsRequired = userInput.nextInt();
// Code to actually make the booking. I don't know what goes here.
A: Just get the instance of the Room and call the method.
The hard-coding method will be like this:
Room toBook = null;
for (Room r : rooms) {
if (r.getRoomId().equals(roomId))
toBook = r;
}
if (toBook != null) {
if (toBook.bookRoom(customerID, nightsRequired)) {
// room booked succesfully
} else {
// can't book the room
}
} else {
// room does not exists
}
But, as long as this will be a bigger app I recommend you to code your own equals method then Arrays.contains() will find the Room.
Room toBook = new Room(roomid);
if (rooms.contains(toBook) && toBook.bookRoom(customerID, nightsRequired)){
// room booked succesfully
} else if (rooms.contains(toBook)) {
// can't book the room
} else {
// room does not exists
}
A: Add the code at the end of the main() method in Test class
Room r=null;
boolean val=false;
for(int i=0;i<rooms.length;i++){
if(rooms[i].getRoomId().equals(roomId)){
r=new Room(rooms[i].getRoomId(), rooms[i].getDescription(), rooms[i].getDailyRate());
r.bookRoom(customerID, nightsRequired);
val=true;
break;
}
}
if(val){
r.print();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30524230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How do I create a proxy object that forwards method calls in c#? I'm trying to use selenium to run tests; seems like there isn't a good way to run the same set of unit tests on multiple browsers.
I read this post about running tests in parallel:
http://slmoloch.blogspot.com/2009/12/design-of-selenium-tests-for-aspnet_19.html
However, I'm using the visual studio unit testing framework.
I can create a proxy class like this:
public class SeleniumProxy {
private List<DefaultSelenium> targets;
public SeleniumProxy() {
targets = new List<DefaultSelenium>();
targets.Add(new DefaultSelenium(... "firefox"...));
targets.Add(new DefaultSelenium(... "iexplore"...));
}
public void Open(String url) {
foreach (var i in targets) {
i.Open(url);
}
}
...
}
My question is this? How can I do it without having to rewrite the entire class as a proxy?
I thought maybe passing a lamda in to map arguments, or passing by a function that takes the name of the method to invoke, but these all seem like pretty lame ideas.
What I really want is to add a member like:
public class SeleniumProxy {
public dynamic proxy;
....
}
And invoke this like:
var selenium = getProxy();
selenium.proxy.Open("...");
Does c# allow this kind of syntax for dynamic objects?
Or some kind of meta-handler for classes that lets them catch no-such-method exceptions and handle them manually?
Basically:
How can I create a proxy object that dynamically invokes methods on an internal member of the class?
(Edit: perhaps... using reflection on the DefaultSelenium object and creating function stubs on the dynamic proxy object for each entry..?)
A: If I understand what you're attempting, I think you can extend DynamicObject to achieve this.
class Proxy : System.Dynamic.DynamicObject
{
public Proxy(object someWrappedObject) { ... }
public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
{
// Do whatever, binder.Name will be the called method name
}
}
//Do whatever... would become some code that pokes at some other object's internal members (via reflection, presumably) using binder.Name as part of the lookup process.
There are TryGetMember and TryGetIndex methods to override if you need to wrap up anything fancier that simple method invokes.
You will have to cast instances of Proxy to dynamic after construction to make arbitrary calls, just like when dealing with ExpandoObject.
A: You could leverage inheritance and have your tests defined in an abstract base class with a factory method to create your selenium instance, then inherit this for each type of browser you want to model. The tests will then be run for each inherited class with the appropriate browser. Using NUnit as an example:
public abstract class AbstractTests
{
protected abstract DefaultSelenium CreateSelenium();
[Test]
public void TestSomethingA()
{
DefaulSelenium selenium = CreateSelenium();
//Do some testing with selenium.
}
}
[TestFixture]
public class IETests : AbstractTests
{
protected override DefaultSelenium CreateSelenium()
{
return new DefaultSelenium("iexplore");
}
}
[TestFixture]
public class FirefoxTests : AbstractTests
{
protected override DefaultSelenium CreateSelenium()
{
return new DefaultSelenium("firefox");
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6327290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rails weird result with find and where Can someone point me the reason for following:
JobType.find 17
#=>
#<JobType id: 17, title: "some_title", description: "one description", reward: # <BigDecimal:1009bbb48,'0.1E1',9(18)>, min_payout: 0.019999999552965164, min_skill_score: 0.6000000238418579, max_payout: 1.0, max_skill_score: 0.9300000071525574, difficulty_level: 2.0, variable_reward: true>
JobType.where(id: 17).first
#=>
#<JobType id: 17, title: "some_title", description: "one description", reward: #<BigDecimal:1009bbb48,'0.1E1',9(18)>, min_payout: 0.02, min_skill_score: 0.6, max_payout: 1.0, max_skill_score: 0.93 difficulty_level: 2.0, variable_reward: true>
In database, The values for min_payout is 0.6, max_skill_score is 0.93, but the find returns that weird long float.
SQL queries logged:
# find
JobType Load (0.5ms) SELECT `job_types`.* FROM `job_types` WHERE `job_types`.`id` = ? LIMIT [["id", 17]]
# where
JobType Load (0.6ms) SELECT `job_types`.* FROM `job_types` WHERE `job_types`.`id` = 17
Why is find behaving like that.
I am using rails 3.2.13 and mysql gem.
A: This is due to the use floating point numbers. Floating point numbers involve a binary representation, in which some numbers that can be exactly represented in decimal notation easily are not stored exactly.
For example, 0.6 in decimal is (approximately) 0.111111000110011001100110011010 in binary. When converted back to decimal this number is (approximately) 0.6000000238418579.
Due to this, when you store 0.6 in a float column, the value returned to you will be (slightly) different. The exact value you receive depends on the specific handling that the value has gone through, which may differ depending on a variety of factors.
In order to avoid this, you would be better off using a BigDecimal, and setting the storage type on that column to :decimal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17669163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: my cloud front URL redirect to S3 URL my cloud front distribution's origin is my S3 bucket . to access a S3 bucket object we put a url in such as like "cloudfront_domainname/object_name" it should be show the object if the object is public . but in my case the cloud front URL in the URL bar redirects a S3 URL, the data retrieved from S3 not from cloud front distribution. why it cause ?
A: You can optionally secure the content in your Amazon S3 bucket so users can access it through CloudFront but cannot access it directly by using Amazon S3 URLs. This prevents anyone from bypassing CloudFront and using the Amazon S3 URL to get content that you want to restrict access to. This step isn't required to use signed URLs, but we recommend it.
To require that users access your content through CloudFront URLs, you perform the following tasks:
*
*Create a special CloudFront user called an origin access identity.
*Give the origin access identity permission to read the objects in your bucket.
*Remove permission for anyone else to use Amazon S3 URLs to read the objects.
Please see documentation here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47570309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# dependecies aren't being included with publish I'm trying to publish a web API built in .NET Core to a Ubuntu server but am having difficulty with the dependencies. I am new to doing this in C# and haven't found a concise answer to how dependencies are included with the publish command. I was lead to believe that they were complied into a .dll but I am getting this error when running my app
Error:
An assembly specified in the application dependencies manifest (api.deps.json) was not found:
package: 'Newtonsoft.Json', version: '11.0.2'
path: 'lib/netstandard2.0/Newtonsoft.Json.dll'
Shouldn't that have been included in the "Release" directory after being published?
I'm using .NET Core on a Mac and then publishing to an Ubuntu sever should that affect anything here.
.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
</Project>
A:
Shouldn't that have been included in the "Release" directory after being published?
No.
When you publish a project, you specify a different directory for the publish output when creating the publish profile.
The Release directory is only for assets that are used during debugging. During development, the NuGet dependencies are not in the Release folder, they are in the NuGet cache. So, you cannot always just copy the Release folder and expect it to run.
After publishing, the entire application (including all dependencies) are output to the publish location. Do note that the publish output doesn't necessarily have to be a folder. For example, depending on the type of project it may be published to IIS with web deploy or to an FTP location.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49848924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Keep receving segmentation fault when using scanf on an array inside a struct I m kind of new at C and i try to learn data structures by doing exercises. This is the code I've written. I don t understand why it dosen't even enter the for loop.
/* Define a structure to store the name, an array
marks[] which stores the marks of three different
subjects, and a character grade. Write a program
to display the details of the student whose name
is entered by the user.*/
#include <stdio.h>
int main()
{
struct stud_info
{
char name[20];
int marks [2][5];
int char_grade;
};
struct stud_info array[20];
struct stud_info stud1;
int i,j;
printf("Enter name of student:\n");
scanf("%s",stud1.name);
printf("Enter student char_grade:\n");
scanf("%d",stud1.char_grade);
for( i=0;i<=2;i++)
for( j=0;j<=5;j++)
{
printf("Enter grade for [%d]st subject:\n",i);
scanf("%d",&stud1.marks[i][j]);
}
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67430520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: q.all for angular2 observables is there something like q.all to resolve all http api requests in angular2?
In angular1, I can do something like this:
var promises = [api.getA(),api.getB()];
$q.all(promises).then(function(response){
// response[0] --> A
// response[1] --> B
})
In angular2, the http module returns Observable,
api.getA().subscribe(A => {A})
api.getB().subscribe(B => {B})
But I want to resolve A and B together, then do something.
A: You will need the .forkJoin operator for that
Observable.forkJoin([observable1,observable2])
.subscribe((response) => {
console.log(response[0], response[1]);
});
You can import the Observable with;
import {Observable} from 'rxjs/Rx';
A: Angular < 6:
import {Observable} from 'rxjs/Observable';
...
return Observable.forkJoin(
this.http.get('someurl'),
this.http.get('someotherurl'));
Angular >= 6:
import {forkJoin} from 'rxjs';
...
return forkJoin(
this.http.get('someurl'),
this.http.get('someotherurl'));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37172093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: How to handle jOOQ depreciation warning on procedure that returns a trigger? I use the following stored procedure to maintain the edit time on a few tables via triggers on those tables:
CREATE OR REPLACE FUNCTION maintain_edit_time()
RETURNS TRIGGER AS $t_edit_time$
BEGIN
NEW.edit_timestamp = NOW();
RETURN NEW;
END;
$t_edit_time$ LANGUAGE plpgsql;
When generating jOOQ objects for the database in question, I get the following generated code:
/**
* @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
*/
@java.lang.Deprecated
public static Object maintainEditTime(Configuration configuration) {
MaintainEditTime f = new MaintainEditTime();
f.execute(configuration);
return f.getReturnValue();
}
/**
* @deprecated Unknown data type. Please define an explicit {@link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
*/
@java.lang.Deprecated
public static Field<Object> maintainEditTime() {
MaintainEditTime f = new MaintainEditTime();
return f.asField();
}
I assume this is because I do not have a jOOQ binding between TRIGGER and a Java object. However, I do not have a clue what I would define this binding as, nor do I have any need for a binding to exist.
Left alone, though, this generates a compile warning. What's the cleanest, easiest way to resolve this?
Options seem to include turning off deprecation, using ignoreProcedureReturnValues, or creating a binding. Ideally, I'd like to simply not generate a Java object for this procedure, but I could not find a way to do that.
Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value. But, I hate to limit future use. Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag. Is the flag going away, or is support for stored procedure return types going away? A brief dig through the jOOQ github issues didn't yield me an answer.
Tempted to simply turn off deprecation. This also seems like a global and not beneficial change, but it would serve the purpose.
If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to. I assume I'd specify as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.
A: Well, after noting that an ideal way to do this would be to ignore that procedure, I did find how to ignore the procedure by name in the generally excellent jOOQ website documentation. Don't know how I missed in on first pass. If I needed to call this procedure in Java, I'm unclear which of the above options I would have used.
Luckily, there was no need for this procedure to be referenced in code, and I excluded it as shown below in in the jOOQ XML configuration.
<excludes>
databasechangelog.*
| maintain_edit_time
</excludes>
A: You've already found the perfect solution, which you documented in your own answer. I'll answer your various other questions here, for completeness' sake
Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value. But, I hate to limit future use. Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag. Is the flag going away, or is support for stored procedure return types going away? A brief dig through the jOOQ github issues didn't yield me an answer.
That flag has been introduced because of a backwards incompatible change in the code generator that affected only SQL Server: https://github.com/jOOQ/jOOQ/issues/4106
In SQL Server, procedures always return an INT value, just like functions. This change allowed for fetching this INT value using jOOQ generated code. In some cases, it was desireable to not have this feature enabled when upgrading from jOOQ 3.5 to 3.6. Going forward, we'll always generate this INT return type on SQL Server stored procedures.
This is why the flag has been deprecated from the beginning, as we don't encourage its use, except for backwards compatibility usage. It probably won't help you here.
Stored procedure support is definitely not going to be deprecated.
Tempted to simply turn off deprecation. This also seems like a global and not beneficial change, but it would serve the purpose.
Why not. A quick workaround. You don't have to use all the generated code. The deprecation is there to indicate that calling this generated procedure probably won't work out of the box, so its use is discouraged.
If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to. I assume I'd specify as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.
Indeed, that wouldn't really add much value to your use cases as you will never directly call the trigger function in PostgreSQL.
Again, your own solution using <exclude> is the ideal solution here. In the future, we might offer a new code generation configuration flag that allows for turning on/off the generation of trigger functions, with the default being off: https://github.com/jOOQ/jOOQ/issues/9270
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58085398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HorizontalAlignment not working for Image inside Button (UWP) I have a button with an Image inside it
<Button BorderThickness="0" Background="Black" Grid.Column="0" Width="400" >
<Image HorizontalAlignment="Right" Height="20" Source="ms-appx:///Assets/LockScreenLogo.scale-200.png" Width="20" />
</Button>
I want the image to be on the right end of the button so gave HorizontalAlignment="Right". But the Image always comes in the middle of the button. How can I fix this?
A: In the default style of Button, there is a ContentPresenter control to display the content of Button, it uses HorizontalContentAlignment property to control the horizontal alignment of the control's content. The default value is Center. So if you want to put the image in the right of Button, you can change the HorizontalContentAlignment to Right.
<Button HorizontalContentAlignment="Right" BorderThickness="0" Background="Black" Grid.Column="0" Width="400" >
<Image Height="20" Source="ms-appx:///Assets/LockScreenLogo.scale-200.png" Width="20" />
</Button>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61804894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need to build a java file through ANT This is my java file.
package test;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MyTest{
@Test
public void startWebDriver(){
WebDriver driver;
driver = new FirefoxDriver();
driver.navigate().to("http://google.com");
Assert.assertTrue("title should start with google",driver.getTitle().startsWith("Google"));
driver.close();
driver.quit();
}
}
I have stored all the selenium and Junit dependencies in a file named Xjars.
This is my build.xml
<?xml version="1.0"?>
<project name="AntSelenium" default="main" basedir=".">
<!-- Sets variables which can later be used. -->
<!-- The value of a property is accessed via ${} -->
<property name="src.dir" location="src" />
<property name="build.dir" location="classes" />
<!-- Variables used for JUnit testin -->
<property name="test.dir" location="src" />
<property name="test.report.dir" location="testreport" />
<property name="jar.dir" location="Xjars"/>
<path id="classpath">
<pathelement path="${basedir}"/>
<fileset dir="${jar.dir}" >
<include name="**/*.jar"/>
</fileset>
</path>
<!-- Define the classpath which includes the junit.jar and the classes after compiling-->
<path id="junit.class.path">
<pathelement location="Xjars/junit-4.8.2.jar" />
<pathelement location="${build.dir}" />
</path>
<!-- Deletes the existing build, docs and dist directory-->
<target name="clean">
<delete dir="${build.dir}" />
<delete dir="${test.report.dir}" />
</target>
<!-- Creates the build, docs and dist directory-->
<target name="makedir">
<mkdir dir="${build.dir}" />
<mkdir dir="${test.report.dir}" />
</target>
<!-- Compiles the java code (including the usage of library for JUnit -->
<target name="compile" depends="clean, makedir">
<javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includeantruntime="false" />
<!-- <pathelement path="Xjars/cglib-nodep-2.1_3.jar"/>
<pathelement path="Xjars/commons-codec-1.10.jar"/>
<pathelement path="Xjars/commons-collections-3.2.1.jar"/>
<pathelement path="Xjars/commons-exec-1.3.jar"/>
<pathelement path="Xjars/commons-io-2.4.jar"/>
<pathelement path="Xjars/commons-lang3-3.4.jar"/>
<pathelement path="Xjars/commons-logging-1.2.jar"/>
<pathelement path="Xjars/cssparser-0.9.16.jar"/>
<pathelement path="Xjars/gson-2.3.1.jar"/>
<pathelement path="Xjars/guava-18.0.jar"/>
<pathelement path="Xjars/htmlunit-2.18.jar"/>
<pathelement path="Xjars/htmlunit-core-js-2.17.jar"/>
<pathelement path="Xjars/httpclient-4.5.1.jar"/>
<pathelement path="Xjars/httpcore-4.4.3.jar"/>
<pathelement path="Xjars/httpmime-4.5.jar"/>
<pathelement path="Xjars/jetty-io-9.2.12.v20150709.jar"/>
<pathelement path="Xjars/jetty-util-9.2.12.v20150709.jar"/>
<pathelement path="Xjars/jna-4.1.0.jar"/>
<pathelement path="Xjars/jna-platform-4.1.0.jar"/>
<pathelement path="Xjars/junit-4.8.2.jar"/>
<pathelement path="Xjars/junit-4.8.2-sources.jar"/>
<pathelement path="Xjars/nekohtml-1.9.22.jar"/>
<pathelement path="Xjars/netty-3.5.2.Final.jar"/>
<pathelement path="Xjars/sac-1.3.jar"/>
<pathelement path="Xjars/selenium-api-2.48.2.jar"/>
<pathelement path="Xjars/selenium-chrome-driver-2.48.2.jar"/>
<pathelement path="Xjars/selenium-edge-driver-2.48.2.jar"/>
<pathelement path="Xjars/selenium-firefox-driver-2.48.2.jar"/>
<pathelement path="Xjars/selenium-htmlunit-driver-2.48.2.jar"/>
<pathelement path="Xjars/selenium-java-2.48.2.jar"/>
<pathelement path="Xjars/selenium-leg-rc-2.48.2.jar"/>
<pathelement path="Xjars/selenium-remote-driver-2.48.2.jar"/>
<pathelement path="Xjars/selenium-safari-driver-2.48.2.jar"/>
<pathelement path="Xjars/selenium-support-2.48.2.jar"/>
<pathelement path="Xjars/serializer-2.7.2.jar"/>
<pathelement path="Xjars/webbit-0.4.14.jar"/>
<pathelement path="Xjars/websocket-api-9.2.12.v20150709.jar"/>
<pathelement path="Xjars/websocket-client-9.2.12.v20150709.jar"/>
<pathelement path="Xjars/websocket-common-9.2.12.v20150709.jar"/>
<pathelement path="Xjars/xalan-2.7.2.jar"/>
<pathelement path="Xjars/xercesImpl-2.11.0.jar"/>
<pathelement path="Xjars/xml-apis-1.4.01.jar"/> -->
</target>
<!-- Run the JUnit Tests -->
<!-- Output is XML, could also be plain-->
<target name="junit" depends="compile">
<junit printsummary="on" haltonfailure="yes">
<classpath refid="junit.class.path" />
<formatter type="plain" usefile="false" />
<batchtest todir="${test.report.dir}">
<fileset dir="${src.dir}">
<include name="**/*Test*.java" />
</fileset>
</batchtest>
</junit>
</target>
<target name="main" depends="compile, junit">
<description>Main target</description>
</target>
</project>
But finally I'm getting this error Buildfile:
C:\Users\manish\workspace\AntSelenium\build.xml clean: [delete]
Deleting directory C:\Users\manish\workspace\AntSelenium\classes
[delete] Deleting directory
C:\Users\manish\workspace\AntSelenium\testreport makedir:
[mkdir] Created dir: C:\Users\manish\workspace\AntSelenium\classes
[mkdir] Created dir: C:\Users\manish\workspace\AntSelenium\testreport compile:
[javac] Compiling 2 source files to C:\Users\manish\workspace\AntSelenium\classes junit:
[junit] Running test.MyTest
[junit] Testsuite: test.MyTest
[junit] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
[junit] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
[junit] Caused an ERROR
[junit] org/openqa/selenium/WebDriver
[junit] java.lang.NoClassDefFoundError: org/openqa/selenium/WebDriver
[junit] at java.lang.Class.forName0(Native Method)
[junit] at java.lang.Class.forName(Unknown Source)
[junit] at org.eclipse.ant.internal.launching.remote.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:36)
[junit] at org.eclipse.ant.internal.launching.remote.InternalAntRunner.run(InternalAntRunner.java:452)
[junit] at org.eclipse.ant.internal.launching.remote.InternalAntRunner.main(InternalAntRunner.java:139)
[junit] Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.WebDriver
[junit] at java.lang.ClassLoader.loadClass(Unknown Source)
BUILD FAILED C:\Users\manish\workspace\AntSelenium\build.xml:94: Test
test.MyTest failed
Total time: 4 seconds Ant is not able to find the org.openqa.selenium.WebDriver class,
although the jar which I have included is a part of Xjars folder.
A: putting here for clarity but its more a comment than an answer
add this in your ant build file to debug the classpath used
<target name="compile" depends="clean, makedir">
<property name="myclasspath" refid="classpath"/>
<echo message="Classpath = ${myclasspath}"/>
<javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" includeantruntime="false" />
</target>
It will print out the classpath and help you debug if the jars are correctly picked up
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33956907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: while loop to read from file skips first line i have to read data from a file into a struct array line by line, but it skips the first line. i found somewhere else that because of the fgets and the sscanf combo the 2nd line is the first read, but i dont understand why or how i can fix this. any suggestions or pointing in the right direction would be awesome!
void readData(){
char line[50];
char name1[1][50];
int O, M, R, W;
input = fopen("input2.dat", "r");
//count = 0;
while(fgets(line, 50, input) != NULL){
hasReadData = 1;
sscanf_s(line, "%20s %d %d %d %d", name1[0], 50, &O, &M, &R, &W);
for(i=0; i<200; i++){
if(strcmp(name1[0], player_arr[i].name) == 0){
if(O<0 || M<0 || R<0 || W<0){
printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
printf_s("\tNegative value, data invalid\n");
break;
}
if(O<M){
printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
printf_s("\tOvers less than Maidens, data invalid\n");
break;
}
if(W>10){
printf_s("%s %d %d %d %d", name1[0], O, M, R, W);
printf_s("\tWickets greater than 10, data invalid\n");
break;
}
player_arr[i].oversOverall += O;
player_arr[i].maidensOverall += M;
player_arr[i].runsOverall += R;
player_arr[i].wicketsOverall += W;
player_arr[i].oversLatest = O;
player_arr[i].maidensLatest = M;
player_arr[i].runsLatest = R;
player_arr[i].wicketsLatest = W;
}
}
}
fclose(input);
}
A: If your while is skipping first line while reading from the file then use this command inside the while loop:
file_pointer.seekg(0,ios::beg);
This file pointer will set your pointer to the beginning of the file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26171987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting csv to xls using Data::Table::Excel? How do you use Data::Table::Excel for converting .csv to .xls file format.
I want to do the conversion with the tables2xls subroutine:
my $t = Data::Table::fromFile("testresults-2013-07-01.csv");
my @arr = $t->csv;
Data::Table::Excel::tables2xls("results.xls", $t ,\@arr);
I tried the code above but I was not able get what I expected.
A: Last line must be:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"]);
And here is colors example like you want:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"], [["white","silver","gray"]]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17423885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: im using ajax but its not executing asynchronously function send(seat_id, seat, seat_name, seat_price, seat_class){
if(ing_order_yn == "y"){
alert("결제창 이동 중 입니다. 좌석 변경이 불가능합니다.");
return false;
}
var data1_val = "";
var data1_val_f = "";
var e_id = $('input[name=e_id]').val(); //사용자가 선택한 event_id
var floor = $('input[name=floor_value]').val();//층
var seat_list;
$.ajax({
url: '/seat_catch.do?group_id=<%=group_id%>',
type : 'POST',
data : { 'event_id' : e_id, 'seat_id' : seat_id },
datatype : 'html',
async : true,
success : function( data1 ){
data1_val = data1.trim().substring(0,4);
data1_val_f = data1.trim().substring(0,6); //[선택불가]
//로그인 세션이없는 경우 ajax 리턴 값은 "session_out" 이다.
if(data1.trim() == "session_out"){
alert('로그아웃 된 상태입니다.\n로그인 후 사용해 주시기 바랍니다.')
document.location.href="/login.do";
}else{
if(data1_val == "담기성공"){
document.getElementById(seat).className = "sel";
//클릭 한 좌석 정보 레이어 보여주기
$('#msg_popup2').html(seat_name + "<br>" + seat_price +"원");
$('#msg_popup2').show();
$('#msg_popup2').delay(5000).fadeOut(1000);
var e_id = $('input[name=e_id]').val(); //사용자가 선택한 event_id
//좌석 선점 처리 후. 좌석 현행화
orderSeatOp(e_id,'1',floor, function(htmll)
alert(htmll);
$('#seat').html(htmll);
});
<%-- $.ajax({
url : '/seat.do',
type : 'POST',
async : true,
data : { 'event_id' : e_id ,'group_id' : <%=group_id%> , 'floor' : floor },
success : function( res ){
$('#seat').html(res);
return false;
}
});
--%>
I think it has a problem in code for last section.
I did this two way
*
*one way is ajax code(annotating in last section)
*callback function.
$('#seat').html(res); it takes whole jsp code of layer popup and makes refresh. I want to make it as asynchronously but it still execute for refresh.
I don't know what can I do. please help me.
and sorry for my shortly English.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53551263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Serve static files with Node/Express I created a node express app and defined a path for static resources in my express app, app.ts:
app.use(express.static(path.join(__dirname, 'public')));
My static files are well served when I am on a main level, for example localhost:3000/products but I get a 404 return code on secondary paths, for example localhost:3000/products/details with this instruction:
<img src="images/image1.jpg" class="card-img" alt="...">
What am I doing wrong?
Thank you in advance for your help.
A: Don't use relative paths for your URLs in the page. Start them all with a /. Change this:
<img src="images/image1.jpg" class="card-img" alt="...">
to this:
<img src="/images/image1.jpg" class="card-img" alt="...">
When the path does not start with a /, then the browser adds the path of the containing page URL to the URL before requesting it from the server because ALL requests to the server must be absolute URLs. That makes things break as soon as you are no longer on a top level page. But, if your URLS always start with /, then the browser doesn't have to mess with the path of the URL before requesting it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74623791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Docker run: uwsgi gives permission denied This is so weid… I have a docker image that runs a web app. WHen I run it, nothing shows in containers… no error. Nothing under docker ps -a.
I ran docker events& and tried again, and it reported an error 1… which is apparently an app error, Okay.
So, I re-ran as:
docker run -it --entrypoint /bin/bash -p 80:80 --name NAME -d
NAME:latest -s
And then ran each item in the runall.sh
The first three items gave a permission denied:
uwsgi --http-socket 127.0.0.1:3009 --file
/var/www/cgi-bin/tireorder/main.wsgi --processes 1 --uid root
--enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder/tireorder.log --pidfile
/var/www/cgi-bin/tireorder/tireorder.pid
Looking this up, and it appears to be a user permission, but all the directories and files are full access to root.
What is really freaky is that, I get it to run in windows and a mint linux VM… but in production(RHEL)) or on my linode VMs(Centos 8, Debian 10, Ubuntu 21) is gives the same permission denied!?
here's the docker file.
FROM lovato/python-2.6.6:latest
WORKDIR /
COPY trotta.tar.gz /
COPY runall.sh /
RUN chmod ugo+x runall.sh
RUN apt-get update
RUN apt-get install haproxy python python-pip python-dev nginx python-paste python-pastewebkit python-babel -y
RUN ["tar", "-xvzf", "trotta.tar.gz"]
RUN ["rm", "/etc/nginx/sites-enabled/default"]
RUN ["cp", "-R", "/usr/lib/python2.6/site-packages/Muntjac-1.1.2-py2.6.egg/muntjac", "/usr/lib/python2.7/dist-packages/"]
COPY uwsgi /usr/local/bin/
COPY /etc/default.conf /etc/nginx/conf.d/
COPY /etc/tireorder.conf /etc/
CMD ./runall.sh
Here is the runall.sh:
uwsgi --http-socket 127.0.0.1:3009 --file /var/www/cgi-bin/tireorder/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder/tireorder.log --pidfile /var/www/cgi-bin/tireorder/tireorder.pid
uwsgi --http-socket 127.0.0.1:3310 --file /var/www/cgi-bin/tireorder2/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder2/tireorder.log --pidfile /var/www/cgi-bin/tireorder2/tireorder.pid --chdir /var/www/cgi-bin/tireorder2
uwsgi --http-socket 127.0.0.1:3610 --file /var/www/cgi-bin/tireorder3/main.wsgi --processes 1 --uid root --enable-threads -b 32768 --daemonize /var/www/cgi-bin/tireorder3/tireorder.log --pidfile /var/www/cgi-bin/tireorder3/tireorder.pid --chdir /var/www/cgi-bin/tireorder3
service nginx start
/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid
tail -f /var/www/cgi-bin/tireorder/tireorder.log &
tail -f /var/www/cgi-bin/tireorder2/tireorder.log &
tail -f /var/www/cgi-bin/tireorder3/tireorder.log
A: Per Ashok:
Add RUN chmod -R 775 above the CMD command in your dockerfile
This resolved it when applied the folders and the uwsgi.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68808746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add/remove JFXPanel on Swing JFrame I want to add and remove JFXPanel on JFrame container but not able to do that. I am stuck here and get no proper solution on button click I want to add and remove the JFXPanel control.
What is the wrong in this code?
public class abc extends JFrame
{
JFXPanel fxpanel;
Container cp;
public abc()
{
cp=this.getContentPane();
cp.setLayout(null);
JButton b1= new JButton("Ok");
JButton b2= new JButton("hide");
cp.add(b1);
cp.add(b2);
b1.setBounds(20,50,50,50);
b2.setBounds(70,50,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
fxpanel= new JFXPanel();
cp.add(fxpanel);
fxpanel.setBounds(600,200,400,500);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("OK"))
{
fxpanel= new JFXPanel();
cp.add(fxpanel);
fxpanel.setBounds(600,200,400,500);
}
if(ae.getActionCommand().equals("hide"))
{
cp.remove(fxpanel);
}
}
public static void main(String args[])
{
abc f1= new abc();
f1.show();
}
}
A: *
*Dont extend JFrame call unnecessarily
*Dont use null/Absolute LayoutManager
*why use show() to set JFrame visible? you should be using setVisible(true)
*Dont forget Swing components should be created a manipulated on Event Dispatch Thread via SwingUtilities.invokeXXX and JavaFX components via Platform.runLater()
Besides the above the biggest problem you have is that you dont refresh GUI/container after adding/removing components,thus no changes are shown.:
call revalidate() and repaint() on JFrame instance to reflect changes after adding/removing components from a visible container.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13738294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remove excess whitespace from a string by jQuery and only count the actual number of characters? today I want to design a block text more than 70 characters will hide the extra text and appear show more
But I can't predict if the user will add extra blank lines, which will cause them to be counted as a character. How do I remove the extra white space and count only the parts that actually have words?
$(function(){
let len = 70
$('.demo').each(function(){
if($(this).html().length >len){
var str=$(this).html().substring(0,len-1)+"<a class='more'>...顯示更多</a>";
$(this).html(str);
}
});
});
.content{
display: flex;
justify-content:space-between;
border:1px solid #222;
padding:10px;
}
.demo{
overflow:hidden;
text-overflow:clip;
display:-webkit-box;
-webkit-box-orient:vertical;
-webkit-line-clamp:2;
}
.photo{
width: 100px;
height: 100px;
border:1px;
border-radius:16px;
margin-left: 10px;
}
.more{
text-decoration:none;
color:blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<div class="demo">
Lorem ipsum dolor sit amet consectetur Lore
</div>
<img class="photo" src="https://images.unsplash.com/photo-1622734659223-f995527e6c7b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=668&q=80" alt="">
</div>
A: You can use .trim() as in if ($(this).html().trim().length > len) {
Demo
$(function() {
let len = 70
$('.demo').each(function() {
if ($(this).html().trim().length > len) {
var str = $(this).html().substring(0, len - 1) + "<a class='more'>...顯示更多</a>";
$(this).html(str);
}
});
});
.content {
display: flex;
justify-content: space-between;
border: 1px solid #222;
padding: 10px;
}
.demo {
overflow: hidden;
text-overflow: clip;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.photo {
width: 100px;
height: 100px;
border: 1px;
border-radius: 16px;
margin-left: 10px;
}
.more {
text-decoration: none;
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<div class="demo">
Lorem ipsum dolor sit amet consectetur Lore
</div>
<img class="photo" src="https://images.unsplash.com/photo-1622734659223-f995527e6c7b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=668&q=80" alt="">
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67834643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Boost::regex_match isn't firing I have some boost Regex code which I think should fire. I'm new to boost but I know a little bit of Regex. Here's the code that I'm using.
re = boost::basic_regex<TCHAR>(_T("-+\\s+Original\\s+Message\\s+-+"), boost::regex_constants::icase);
boost::match_results<TSTRING::const_iterator> result;
if(boost::regex_match(RawBody, result, re))
and here is the test string I'm using.
this is a test
-------- Original Message --------
everything under here should disappear
My code compiles and runs, it just doesn't trigger the if statement. I tried debugging into the boost code and ... yeah...
A: regex_match
The algorithm regex_match determines whether a given regular
expression matches all of a given character sequence denoted by a pair
of bidirectional-iterators, the algorithm is defined as follows, the
main use of this function is data input validation.
regex_search
The algorithm regex_search will search a range denoted by a pair of
bidirectional-iterators for a given regular expression. The algorithm
uses various heuristics to reduce the search time by only checking for
a match if a match could conceivably start at that position. The
algorithm is defined as follows:
So, use boost::regex_search. Example.
http://liveworkspace.org/code/fa35778995c4bd1e191c785671ab94b6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11767483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to fix inconvertible types in Android Studio I am trying to start an application based on google maps in Android Studio. I followed the instructions and started an Google Maps activity.
Then I created according to the instructions an API key and enabled the maps SDK android for android and copied the key into the app.
but then when I'm trying to run the app (didnt change a thing) I get this error:
Inconvertible types; cannot cast 'android.support.v4.app.Fragment' to 'com.google.android.gms.maps.SupportMapFragment'
for this line of code:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
and this error: Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:12:5-42:19 to override.
in the event.
Here is the code:
package com.example.android.myfirstmap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
I looked around to see if there is a solution that fixes also my problem but none of what I tried was the right one.
does anyone knows how to fix it? evreything is updated.
A: Support Map Fragment extends androidx.fragment.app.Fragment.
You are importing android.support.v4.app.FragmentActivity which uses android.support.v4.app.Fragment. These are two different classes so they are incompatible.
You need to migrate your app to Android X: https://developer.android.com/jetpack/androidx/migrate
Then, in your build.gradle file, replace com.android.support:support-fragment with androidx.fragment:fragment.
Hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57350146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: drupal 6 - can i use one exposed views filter to search/filter several similar cck fields? i have a decent understanding of configuring drupal and using modules for basic stuff, but just getting into module development and overriding functions and stuff due to my very basic understanding of php and mysql.
i have a custom content type ('books') and a 3 cck field for genres (primary, secondary, tertiary). i'd like a user to be able to filter a view of all books with one exposed multi-selectable 'genre' filter. that's where i'm stuck-- i understand how to have three exposed filters for the 3 genre 'weights' (primary, secondary, tertiary)--i want one filter that would allow users to select any or all of those weights.
is a custom search form my only option? was there a better way to set things up? would i have been better off using one cck field for 'genres' with multiple entries? i ruled this out because i thought it would be harder to determine the genre 'weight' (primary, secondary, tertiary).
thanks a million.
A: Think about what the meaning of genres to a book is. Taxonomy is just what you use for this kind of thing. There are several pros using the taxonomy rather than using CCK fields.
*
*Taxonomy is meta data, CCK fields are not. This mean that the way the html is generated for taxonomy terms, it will help SE to understand that these genres are important and it will give you a free SEO
*You can setup how genres should be selected in far more detail than a CCK field. Again since taxonomy is made for exactly this kind of thing. You can setup how users are presentated with the genre selection in various ways. You can predefine genres or let users enter their own as they like. You can make child-parent relation ships and more
*It's easier and more lightweight to use taxonomy than CCK fields.
*If there only is 1 or 2 genre inputted you wont have to have empty CCK fields.
*probably more that I can't think of right now
Using taxonomy you can pretty easily make a search with views, where you make it possible for users to select genres using a multiple select list. You can decide if you require all terms or only one of them. Simply put you should really use taxonomy, it should solve all of your problems, if not, you should still use it and try to solve the problems you could get using taxonomy instead of CCK fields.
A: Jergason has a good point saying that taxonomy would probably be a good fit for your fields. However this wouldn't solve your problem of weighted genres.
A possible (though hacky) solution would be to have a fourth field which combined the values of the other three which is only set when a node is saved. This field could then be used for searching.
The non hacky solution is to write your own views filter but this is very advanced.
There may be a way to do this with views out of the box it is flexible, hopefully someone else knows of an easier non hacky solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1242882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: javascript invalid quantifier breaks my jQuery in asp.net I want to select, Highlight & convert the matching string into a link. So far it works find in jsFiddle.
But same script breaks when i try to use it in asp.net web forms i get following error
SyntaxError: invalid quantifier
[Break On This Error]
var pattern = new RegExp("("+this+")", ["gi"]);
Actual Code
function HighlightKeywords(keywords)
{
var el = $("#article-detail-desc");
$(keywords).each(function()
{
var pattern = new RegExp("("+this+")", ["gi"]);
var rs = "<a href='search.aspx?search=$1'<span style='background-color:#FFFF00;font-weight: bold;background-color:#FFFF00;'>$1</span></a>";
el.html(el.html().replace(pattern, rs));
});
}
HighlightKeywords(["got", "the","keywords", " tags " ]);
http://jsfiddle.net/LE3sg/6/
i am not sure why i keep getting this error in asp.net webform page
A: When looping an array with jQuery each should always use the arguments in callback to access the array element and use $.each method as opposed to $(selector).each
$.each(keyowrds, function(index, item)
{
var pattern = new RegExp("("+item+")", ["gi"]);
In code you are using if you log typeof this to console will find it is not actually a string
API reference: http://api.jquery.com/jQuery.each/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15861925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hibernate constraint violation exception hangs sql server I am trying to save a set of records into db like shown below. I have set unique constraint on 2 columns of the table. I have handled the constraint exception. If I insert new set of records I have no issues. If I try to insert duplicate records, exception is handled but ms sql server says
executing query. waiting for response from data source.
Also after this if I try to insert new set of records the http request is not completed and the records are not inserted. How should I handle constraint exception so that ms sql server does not hang?
public void addStepFlow(List<StepFlow> stepFlows) {
Session session = this.sessionFactory.openSession();
try {
Transaction tx = session.beginTransaction();
for (StepFlow stepFlow : stepFlows) {
session.save(stepFlow);
session.flush();
session.clear();
}
tx.commit();
session.close();
} catch (JDBCException e) {
SQLException cause = (SQLException) e.getCause();
System.out.println(cause.getMessage());
}
}
A: Try to rollback on exception.. and also close the session no matter what heppens:
Session session = this.sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
for (StepFlow stepFlow : stepFlows) {
session.save(stepFlow);
session.flush();
session.clear();
}
tx.commit();
} catch (JDBCException e) {
SQLException cause = (SQLException) e.getCause();
System.out.println(cause.getMessage());
tx.rollback();
}finally{
session.close();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42924240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: stroke-dasharray can't bind with angular 6 I used this Chart with angular 6 , I faced the some conflict on this chart, i try to bind data , but i cant do that, its not working correctly,
This stroke-dasharray="5, 100" to I replaced this one
stroke-dasharray="{{this.master.locationVsStatusMap.size}}, 100"
stackblitz
anyone know how to do that correctly ?
Thanks in advance!
.single-chart {
width: 33%;
justify-content: space-around ;
}
.circular-chart {
display: block;
margin: 10px auto;
max-width: 70%;
max-height: 150px;
}
.circle-bg {
fill: none;
stroke: #3c9ee5;
stroke-width: 3.8;
}
.circle {
fill: none;
stroke-width: 3.8;border-right: 1px solid white; border-left: 1px solid white;
stroke-linecap:square;
animation: progress 1s ease-out forwards;
}
@keyframes progress {
0% {
stroke-dasharray: 0 100;
}
}
.circular-chart.orange .circle {
stroke: #ff9f00;border-right: 1px solid white; border-left: 1px solid white;
}
.circular-chart.green .circle {
stroke: #4CC790;
}
.circular-chart.blue .circle {
stroke: #3c9ee5;
}
.percentage {
fill: #666;
font-family: sans-serif;
font-size: 0.3em;
text-anchor: middle;
}
.flex-wrapper {
display: flex;
flex-flow: row nowrap;
}
<div class="flex-wrapper">
<div class="single-chart">
<svg viewBox="0 0 36 36" class="circular-chart orange">
<path class="circle-bg"
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
/>
<path class="circle"
stroke-dasharray="5, 100"
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
/>
<text x="18" y="20.35" class="percentage">50%</text>
</svg>
</div>
</div>
A: Use style binding - https://coryrylan.com/blog/angular-progress-component-with-svg
style.stroke-dasharray="{{varible}}, 100"
A: Try attribute binding
attr.stroke-dasharray="{{this.master.locationVsStatusMap.size}}, 100"
Forked Example:https://stackblitz.com/edit/angular-wqjlc5
Ref this: https://teropa.info/blog/2016/12/12/graphics-in-angular-2.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53911327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: String trend-analysis (suggestions for data structure) I want to keep track of strings from text files over time (reading them in). What would be the best method to programmatically keep track? This is the desired end result after 3 entries.
String|frequency|date-Col1|date-Col2|..date-Col N|
==================================================
hello | 2 | 1/1/16 | 3/5/16 |
motto | 1 | 2/3/16
Some ideas I'm kicking around: using python dictionaries, java arrayLists, R?
Any suggestions, thanks?
A: from collections import defaultdict
words_seen = defaultdict(list)
for word,filedate in get_words():
words_seen[word].append(filedate)
then frequency is len(words_seen[word]).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34572672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why I cant access pages of my Classic ASP site? I am setting up a classic ASP site on my computer. I have installed all the necessary DLL's, configured the IIS and enabled ASP on my IIS. All the files of the website are in a folder named ClassicASP.This Folder is in wwwroot Folder of IIS.
Now my problem is that I am able to access the Login Page of my site. But when I enter credentials It doesnot redirects to the next page. Its gives
"
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
"
However the file is in the same folder. I can only access Login Page no other page is working it says Resource not Found.
Can some one help. I am new to ClassicASP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38082145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why doesn't object-fit affect width or height? I have a 240*240px image inside a 100*300px div (demo values, actual values vary and are unknown). I use object-fit: contain to make the image completely visible inside the div and also keep it's aspect ratio. The problem is that object-fit isn't modifying the width of the image, resulting in a weird "padding" (so to say).
How can I make the image take only as much width as required, instead of taking the original width?
Demo: http://codepen.io/alexandernst/pen/ONvqzN
.wrapper {
height: 100px;
width: 300px;
border: 1px solid black;
}
.flex {
display: flex;
}
img {
object-fit: contain;
}
<div class="flex wrapper">
<img src="https://unsplash.it/240/240" />
</div>
A: The object-fit property normally works together with width, height, max-width and max-height. Example:
.wrapper {
height: 100px;
width: 300px;
border: 1px solid black;
}
.flex {
display: flex;
}
img {
object-fit: contain;
height: 100%;
width: auto;
}
<div class="flex wrapper">
<img src="https://unsplash.it/240/240" />
</div>
In fact, it works fine too even without object-fit, see this jsFiddle.
A:
.wrapper {
height: auto;
width: 100%;
border: 1px solid black;
background-image: url(https://unsplash.it/240/240);
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.flex {
display: flex;
}
img {
object-fit: contain;
}
<div class="flex wrapper">
<img src="https://unsplash.it/240/240" />
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36636754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Cannot show notification at lock screen Android Studio I'm using NotificationCompat.Builder to show notification music player mini.
I have been show success notfication but without at lock screen. I tried NotificationCompat.Builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC), NotificationCompat.Builder.setPriority(NotificationCompat.PRIORITY_MAX) but all them not worked. My device android version is 9.0.1.
This is my code.
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Test";
String description = "Đây là bản test";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("CHANNEL_ID", name, importance);
channel.setShowBadge(true);
channel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getContext().getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
This is function call main.
createNotificationChannel();
// Create an explicit intent for an Activity in your app
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Intent prevIntent = new Intent(this,NotificationReceiver.class).setAction("ActionPrev");
Intent pauseIntent = new Intent(this,NotificationReceiver.class).setAction("ActionPause");
Intent nextIntent = new Intent(this,NotificationReceiver.class).setAction("ActionNext");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
PendingIntent prevpendingIntent = PendingIntent.getBroadcast(this,0,prevIntent,PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pausependingIntent = PendingIntent.getBroadcast(this,0,pauseIntent,PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent nextpendingIntent = PendingIntent.getBroadcast(this,0,nextIntent,PendingIntent.FLAG_UPDATE_CURRENT);
if(mangbaihat.get(position).getFields().getImage_Url().contains("/storage/emulated/0/Download")){
final BitmapFactory.Options options = new BitmapFactory.Options();
picture = BitmapFactory.decodeFile(mangbaihat.get(position).getFields().getImage_Url(), options);
}else{
picture = getBitmapFromURL(mangbaihat.get(position).getFields().getImage_Url());
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID")
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.logo)
.setLargeIcon(picture)
.setContentTitle(mangbaihat.get(position).getFields().getMusic_Title())
.setContentText(mangbaihat.get(position).getFields().getComposed())
// .setDefaults(NotificationCompat.DEFAULT_ALL)
.addAction(R.drawable.iconpreview_mini,"Previous",prevpendingIntent)
.addAction(R.drawable.iconpause_mini,"Pause",pausependingIntent)
.addAction(R.drawable.iconnext_mini,"Next",nextpendingIntent)
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle().
setShowActionsInCompactView(1 /* #1: pause button */).
setMediaSession(mediaSession.getSessionToken()))
.setPriority(NotificationCompat.PRIORITY_MAX)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, builder.build());
Pls,Can anyone help me!
Thank you so much!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71089241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Applescript for changing filenames I would like to change thousand of filenames with an applescript.
The filenames are all made in this way:
firstPart - secondPart XX.xxx
with the XX a certain number and the .xxx either a jpg or a png extension.
I would like to simply change the parts around so that it would become:
secondPart - firstPart XX.xxx
I have come up with this but my codings skills fail me.
tell application "Finder" to set aList to every file in folder "ImageRename"
set text item delimiters to {" - ", "."}
repeat with i from 1 to number of items in aList
set aFile to (item i of aList)
try
set fileName to name of aFile
set firstPart to text item 1 of fileName
set secondPart to text item 2 of fileName
set thirdPart to text item 3 of fileName
set newName to secondPart & " - " & firstPart & "." & thirdPart
set name of aFile to newName
end try
end repeat
This works only the number sticks to the second part.
So it becomes:
SecondPart XX - firstPart.xxx
How can I make two integers as a text item delimiter?
Please help me out and teach me along the way :-)
A: To answer your question how to use an integer as an text item delimiters is just:
set AppleScript's text item delimiters to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
You can set multiple text item delimiters at once but the problem is that when using multiple text item delimiters you have actually no idea what was between the two text items. Also the order of how the delimiters appear in the text is not important when using text item delimiters. Therefore I would suggest using regular expressions instead, you define a certain format instead of separating a string and guessing which character was actually the separator.
tell application "Finder" to set aList to every file in folder "ImageRename"
repeat with i from 1 to number of items in aList
set aFile to item i of aList
set fileName to name of aFile as string
set newName to do shell script "perl -pe 's/^(.*) - (.*) ([0-9]{2}\\.(jpeg|png))$/\\2 - \\1 \\3/i' <<<" & quoted form of fileName
if newName is not fileName then set name of aFile to newName
end repeat
The reason I use perl and not sed is because perl does support the I flag in the substitution which makes the comparison of the expression case insensitive.
edit (requested explanation):
The format of the old string is something like: String can start with any character (^.*) up to the literal string " - " ( - ) then followed by any character (.*) again. The string have to end with a string starting with space and 2 digits ( [0-9]{2}), followed by a literal period (\.) and end with either jpeg or png ((jpeg|png)$). If we put this all together we get a regex like "^.* - .* [0-9]{2}\.(jpeg|png)$". but we want to group the match in different sections and return them in a different order as our new string. Therefore we group the regular expression into 3 different sub matches by placing parentheses:
^(.*) - (.*) ([0-9]{2}\.(jpeg|png))$
The first group will match the firstPart, the second group will match secondPart and the third group (XX.xxx) will match the remaining part. The only thing we need to do is reorder them when we return the new string. A backslash followed by a number in the new string will be replaced by the matching group. In the substitution command this will be notated as /s/search/\2 - \1 \3/flags.
The last part of our substitution are some flags, I place I as a flag for case insensitive matching.
Putting this all together gets me
s/^(.*) - (.*) ([0-9]{2}\.(jpeg|png))$/\2 - \1 \3/I
note: because \ is in applescript a special character we have to write a \ down as \\
A: Just use the space as the delimiter and build the parts.
Edited: to allow for spaces in the text parts.
tell application "Finder" to set aList to every file in folder "ImageRename"
set AppleScript's text item delimiters to " "
repeat with i from 1 to number of items in aList
set aFile to (item i of aList)
try
set fileName to name of aFile
set lastParts to text item -1 of fileName
set wordParts to (text items 1 thru -2 of fileName) as string
set AppleScript's text item delimiters to " - "
set newName to {text item 2 of wordParts, "-", text item 1 of wordParts, lastParts}
set AppleScript's text item delimiters to " "
set name of aFile to (newName as string)
end try
end repeat
set AppleScript's text item delimiters to ""
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28099452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between setup.py files If I were to develop and distribute a python package, I know I can probably make a setup.py file like this:
from setuptools import setup, find_packages
setup(name='mypackage',
version='0.1',
packages=find_packages()
)
However, when I look at the setup.py in some installed packages on my PC. It is written quite differently. For instance, setup.py in Scipy looks like:
def configuration(parent_package='',top_path=None):
from scipy._build_utils.system_info import get_info, NotFoundError
lapack_opt = get_info("lapack_opt")
from numpy.distutils.misc_util import Configuration
config = Configuration('scipy',parent_package,top_path)
config.add_subpackage('cluster')
config.add_subpackage('constants')
config.add_subpackage('fft')
config.add_subpackage('fftpack')
config.add_subpackage('integrate')
config.add_subpackage('interpolate')
config.add_subpackage('io')
config.add_subpackage('linalg')
config.add_data_files('*.pxd')
config.add_subpackage('misc')
config.add_subpackage('odr')
config.add_subpackage('optimize')
config.add_subpackage('signal')
config.add_subpackage('sparse')
config.add_subpackage('spatial')
config.add_subpackage('special')
config.add_subpackage('stats')
config.add_subpackage('ndimage')
config.add_subpackage('_build_utils')
config.add_subpackage('_lib')
config.make_config_py()
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
Can anyone please explain why and which style I should use when developing my own packages?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70105069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eclipse plugin - creating a new class I'm trying to write an eclipse plugin to auotmatically generate a java class from a text file. How can I do this in JDT?
The name of the class will be derived from the name of the text file, and I will want to generate some methods based on the contents of the text file.
I can probably do this the hard way, just writing to a file, but it seems like the JDT is the best way to go about this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7202749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding elements to model space the correct way using .NET API Method One
_AcDb.Line oLine = new _AcDb.Line(ptStart, ptEnd);
AddToModelSpace("PLOT", oLine);
Where AddToModelSpace is:
public static void AddToModelSpace(string strLayer, _AcDb.Entity oEntity)
{
_AcAp.Document acDoc = _AcAp.Application.DocumentManager.MdiActiveDocument;
_AcDb.Database acCurDb = acDoc.Database;
_AcEd.Editor ed = acDoc.Editor;
using (_AcDb.BlockTable bt = acCurDb.BlockTableId.GetObject(_AcDb.OpenMode.ForRead) as _AcDb.BlockTable)
using (_AcDb.BlockTableRecord ms = bt[_AcDb.BlockTableRecord.ModelSpace].GetObject(_AcDb.OpenMode.ForWrite) as _AcDb.BlockTableRecord)
ms.AppendEntity(oEntity);
oEntity.Layer = strLayer;
oEntity.Dispose();
}
Method Two
// Get the current document and database
_AcAp.Document docActive = _AcAp.Application.DocumentManager.MdiActiveDocument;
_AcDb.Database docDB = docActive.Database;
// Start a transaction
using (_AcDb.Transaction acTrans = docDB.TransactionManager.StartTransaction())
{
// Open the Block table for read
_AcDb.BlockTable acBlkTbl;
acBlkTbl = acTrans.GetObject(docDB.BlockTableId,
_AcDb.OpenMode.ForRead) as _AcDb.BlockTable;
// Open the Block table record Model space for write
_AcDb.BlockTableRecord acBlkTblRec;
acBlkTblRec = acTrans.GetObject(acBlkTbl[_AcDb.BlockTableRecord.ModelSpace],
_AcDb.OpenMode.ForWrite) as _AcDb.BlockTableRecord;
// Create line
using (_AcDb.Line acLine = new _AcDb.Line(ptStart, ptEnd))
{
// Add the new object to the block table record and the transaction
acBlkTblRec.AppendEntity(acLine);
acTrans.AddNewlyCreatedDBObject(acLine, true);
}
// Save the new object to the database
acTrans.Commit();
}
I have used AddToModelSpace in my project so I hope it is fine!
A: Method Two is the way Autodesk recommends in the developer's documentation (you can read this section).
In Method One, you use the ObjectId.GetObject() method to open the BlockTable and the model space 'BlockTableRecord'. This method uses the top transaction to open object which means that there's an active transaction you should use to add the newly created entity. You can get it with Database.TransactionManager.TopTransaction. If you don't want to use a transaction at all, you have to use the "for advanced use only" ObjectId.Open() method.
A Method Three should be using some extension methods to be called from within a transaction. Here's a simplified (non error checking) extract of the ones I use.
static class ExtensionMethods
{
public static T GetObject<T>(
this ObjectId id,
OpenMode mode = OpenMode.ForRead,
bool openErased = false,
bool forceOpenOnLockedLayer = false)
where T : DBObject
{
return (T)id.GetObject(mode, openErased, forceOpenOnLockedLayer);
}
public static BlockTableRecord GetModelSpace(this Database db, OpenMode mode = OpenMode.ForRead)
{
return SymbolUtilityServices.GetBlockModelSpaceId(db).GetObject<BlockTableRecord>(mode);
}
public static ObjectId Add (this BlockTableRecord owner, Entity entity)
{
var tr = owner.Database.TransactionManager.TopTransaction;
var id = owner.AppendEntity(entity);
tr.AddNewlyCreatedDBObject(entity, true);
return id;
}
}
Using example:
using (var tr = db.TransactionManager.StartTransaction())
{
var line = new Line(startPt, endPt) { Layer = layerName };
db.GetModelSpace(OpenMode.ForWrite).Add(line);
tr.Commit();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56136939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make X-Axis Lables, value labels and other axis and labels bold in Ggplot2 I work inside a research environment and I can't copy paste the code I used there, but I have previously generated this plot, and have been helped by various people in labelling it with the count number. The problem arises when I screenshot the plot from inside the research environment, and the legends are illegible. I am hoping I can address this by making the labels (including the X-axis label) all bold.
I used some mock-data outside the environment and this is what I have so far.
library(ggplot2)
library(reshape2)
md.df = melt(df, id.vars = c('Group.1'))
tmp = c("virginica","setosa","versicolor")
md.df2 = md.df[order(match(md.df$Group.1, tmp)),]
md.df2$Group.1 = factor(as.character(md.df2$Group.1), levels = unique(md.df2$Group.1))
ggplot(md.df2, aes(x = Group.1, y = value, group = variable, fill = variable)) +
geom_bar(stat="identity",color='black', position = "dodge") +
xlab('Species') + ylab('Values') + theme_bw()+
ylim(0,8)+
theme(text = element_text(size=16),
axis.text.x = element_text(angle=0, hjust=.5),
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5))+
ggtitle("Order variables in barplot")+
geom_text(aes(label=value), vjust=-0.3, size=4, # adding values
position = position_dodge(0.9))+ element_text(face="bold")
I need to make the labels onto bold, and the element_text isn't working mainly because I am probably using it in the wrong way. I'd appreciate any help with this.
An example of this plot which I haven't been able to find mock data to re-create outside the environment, have asked a question about in the past, is the one where the axis ticks also need to be made bold. This is because the plot is illegible from the outside.
I've tried addressing the illegibility by saving all my plots using ggsave in 300 resolution but it is very illegible.
I'd appreciate any help with this, and thank you for taking the time to help with this.
A: As I mentioned in my comment to make the value labels bold use geom_text(..., fontface = "bold") and to make the axis labels bold use axis.text.x = element_text(angle=0, hjust=.5, face = "bold").
Using a a minimal reproducible example based on the ggplot2::mpg dataset:
library(ggplot2)
library(dplyr)
# Create exmaple data
md.df2 <- mpg |>
count(Group.1 = manufacturer, name = "value") |>
mutate(
variable = value >= max(value),
Group.1 = reorder(Group.1, -value)
)
ggplot(md.df2, aes(x = Group.1, y = value, group = variable, fill = variable)) +
geom_col(color = "black", position = "dodge") +
geom_text(aes(label = value), vjust = -0.3, size = 4, position = position_dodge(0.9), fontface = "bold") +
labs(x = "Species", y = "Values", title = "Order variables in barplot") +
theme_bw() +
theme(
text = element_text(size = 16),
axis.text.x = element_text(angle = 90, vjust = .5, face = "bold"),
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)
)
A: In addition to @stefan 's answer, you can also set tick length and thickness like so:
## ... plot code +
theme(## other settings ...,
axis.ticks = element_line(linewidth = 5),
axis.ticks.length = unit(10, 'pt'))
However, the example "phenotype conditions" will probably remain hard to appraise, regardless of optimization on the technical level. On the conceptual level it might help to display aggregates, e. g. condition counts per Frequency and supplement a textual list of conditions (sorted alphabetically and by Frequency, or the other way round) for those readers who indeed want to look up any specific condition.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74564625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL expression in oracle data integrator
I have the following interface in Oracle Data Integrator
http://i44.tinypic.com/2mrsmxt.png
It execute successfully before inserting the following SQL expression
In the mapping I insert the following SQL expression to get the average when the quantity is 0
AVG(
CASE WHEN TEST.QUN = 0 THEN
(SELECT TEST.QUN
FROM TEST
WHERE TEST1.PRUDU=TEST.PRUDU
AND TEST1.FLOW=TEST.UNIT
AND TEST1.UNIT=TEST.UNIT
AND to_char(TEST.DATEDDD,'MON')= to_char(TEST1.DATEDDD,'MON')
AND TEST1.DATEDDD !=TEST.DATEDDD
GROUP BY TEST.QUN )
ELSE TEST.QUN
END)
When I check this expression in ODI the SQL expression is correct for this RDBMS but when I executed the interface I get this error
Caused By: java.sql.SQLSyntaxErrorException:
ORA-00937: not a single-group group function
any idea?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20298732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compare numbers in NSMutableArray with indexPath.row I have an NSMutableArray that gets edited quite often as a TableView is edited. What I want to do is run a check and see if rows in the TableView match up with any numbers in the NSMutableArray, and if they do, perform an action. So, in the TableView code I have:
if([thearray containsObject:indexPath.row] {
//perform action here
}
However I keep getting the error:
Incompatible integer to pointer conversion sending 'NSInteger' (aka 'int') to parameter of type 'id';
What am I doing wrong and how can I do this?
A: Use this code...
if([thearray containsObject:[NSNumber numberWithInt:indexPath.row]]) {
//perform action here
}
A: I think the best you can do here is check if the current count of the array is greater than indexPath.row the (since in theory there will be no gaps in the indexes). The method you are currently calling takes an object and tells you if it is a member of the array. There is also objectAtIndex:, but that raises an exception if the integer you pass is out of bounds.
if(thearray.count > indexPath.row) {
// array has at least indexPath.row + 1 items, so you can get objectAtIndex:indexPath.row
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13942004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why getting the `This page isn't working... ERR_TOO_MANY_REDIRECTS`? Generated same script file with multiple times in index.html file, I recently upgraded project to angular 8.0.2 version
After upgrading the angular version, am getting this replication problem in index.html file.
This is JavaDemoProject java project, i run the angular application with this javaproject with the help of pom.xml file
I build the project through maven command(mvn clean install -Penv-dev -DskipTests -DbuildNumber=04)
*
*pom.xml file
<plugin>
<groupId>com.github.testDemo</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.6</version>
<configuration>
<workingDirectory>../Angular-Project</workingDirectory>
<installDirectory>temp</installDirectory>
</configuration>
<executions>
<!-- It will install nodejs and yarn -->
<execution>
<id>install node and yarn</id>
<goals>
<goal>install-node-and-yarn</goal>
</goals>
<configuration>
<nodeVersion>v11.7.0</nodeVersion>
<yarnVersion>v1.9.4</yarnVersion>
</configuration>
</execution>
<!-- It will execute command "yarn install" inside "/angular"
directory -->
<execution>
<id>yarn install</id>
<goals>
<goal>yarn</goal>
</goals>
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<!-- It will execute command "yarn build" inside "/angular"
directory to clean and create "/dist" directory -->
<execution>
<id>yarn javaDemoprod </id>
<goals>
<goal>yarn</goal>
</goals>
<configuration>
<arguments>javaDemoprod --outputPath=../JavaDemoProject/
src/main/resources/templates/dist</arguments>
</configuration>
</execution>
</executions>
</plugin>
*tsconfig.json file:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"module": "commonjs",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2015",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
],
"resolveJsonModule": true,
"esModuleInterop": true
}
}
*This is the angular.json file:
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/Angular-Project",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"showCircularDependencies": false,
"assets": [
"src/favicon.ico",
"src/eg.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": [],
"aot": true
}
}
*Package.json
"dependencies": {
"@angular/animations": "^8.0.1",
"@angular/cdk": "^8.0.1",
"@angular/common": "^8.0.1",
"@angular/compiler": "^8.0.1",
"@angular/core": "^8.0.1",
"@angular/forms": "^8.0.1",
"@angular/material": "^8.0.1",
"@angular/platform-browser": "^8.0.0",
"@angular/platform-browser-dynamic": "^8.0.1",
"@angular/router": "^8.0.1",
"core-js": "^2.5.4",
"hammerjs": "^2.0.8",
"ngx-loading": "^3.0.1",
"node-sass": "^4.10.0",
"rxjs": "6.5.2",
"underscore": "^1.9.1",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.800.0",
"@angular/cli": "~8.0.2",
"@angular/compiler-cli": "^8.0.1",
"@angular/language-service": "^8.0.1",
"@types/jasmine": "~2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"bootstrap-sass": "^3.3.7",
"codelyzer": "^5.0.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-scss-preprocessor": "^3.0.0",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1",
"typescript": "~3.4.5"
}
After build the application in index.html path of the
file JavaDemoProject\src\main\resources\templates\dist\index.html am getting this replication of script files, how can i prevent this replicate script files.
<body>
<app-root></app-root>
<script src="runtime-es2015.js" type="module"></script>
<script src="polyfills-es2015.js" type="module"></script>
<script src="runtime-es5.js" nomodule></script>
<script src="polyfills-es5.js" nomodule></script>
<script src="styles-es2015.js" type="module"></script>
<script src="styles-es5.js" nomodule></script>
<script src="vendor-es2015.js" type="module"></script>
<script src="main-es2015.js" type="module"></script>
<script src="vendor-es5.js" nomodule></script>
<script src="main-es5.js" nomodule></script>
</body>
This replications of script file am getting the output of the application showing
This page isn't working...
ERR_TOO_MANY_REDIRECTS
Can anyone help me out to solve this problem.
Thanks in Advance.
A: The scripts which you are able to see is because of the differential loading feature.
Angular 8 has a new feature to generate a separate bundle to the older browser and new browsers.
You can control which browser you want to support, you can read more about this feature on
https://angular.io/guide/deployment#differential-loading
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56929757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error message when trying to read an excel file Hi pretty new to angular2 so apologizes if this is something simple - i'm trying to read an excel file using a lib called ts-xlsx and inject the data into the main app root component - The error i'm getting is
zone.js:355Unhandled Promise rejection: Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: !CompObj is not a function ; Zone: ; Task: Promise.then ; Value:
app-service.ts
import { Injectable } from '@angular/core';
import { read, IWorkBook, IWorkSheet, utils } from 'ts-xlsx';
@Injectable()
export class OperationDataService {
private xbFile = 'test.xlsx';
private wb: IWorkBook = read(this.xbFile);
private wbSheet: IWorkSheet = this.wb.Sheets[1];
objAr: any[];
constructor() { }
getData() {
this.objAr = utils.sheet_to_json(this.wbSheet, { header: 1 });
}
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { OperationDataService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [OperationDataService]
})
export class AppComponent implements OnInit {
ObjArray: any[];
constructor(private _operationDataService: OperationDataService) { }
ngOnInit() {
this.ObjArray[1] = this._operationDataService.getData();
}
}
i can't find much documentation on it so any help would be much appreciated.
Update:
Even-though the information online is small it seems that there are a few problems with the way i grabbed the file above - so i re-wrote the service component to align to original alax example converted to typescript
import { Injectable } from '@angular/core'; import { read, IWorkBook, IWorkSheet, utils } from 'ts-xlsx';
@Injectable() export class OperationDataService {
url: string;
oReq: any;
wb: IWorkBook;
wbSheet: IWorkSheet;
arraybuffer: any;
data: any;
arr: any;
bstr: any;
objAr: any[];
constructor() {
this.url = '../assets/data/Operations.xlsx';
this.oReq = new XMLHttpRequest();
this.oReq.open('GET', this.url, true);
this.oReq.responseType = 'arraybuffer';
}
getdata() {
this.oReq.onload = function(): any {
this.arraybuffer = this.oReq.response;
/* convert data to binary string */
this.data = new Uint8Array(this.arraybuffer);
this.arr = new Array();
for (let item of this.data) {
this.arr[item] = String.fromCharCode(this.data[item]);
}
this.bstr = this.arr.join('');
console.log(this.oReq.responseText);
this.wb = read(this.bstr, {type: 'binary'});
this.wbSheet = this.wb.Sheets[0];
this.objAr = utils.sheet_to_json(this.wbSheet, { header: 1 });
console.log(utils.sheet_to_json(this.wbSheet, { header: 1 }));
return this.objAr;
};
} }
Now i'm not receiving any errors but i can't see the json - any idead what i'm doing wrong?
A: From the code you posted, this looks good in theory, but still has a few errors.
*
*You're using ObjArray in AppComponent without initializing it, so you can't access it with [1]
*The getData method in your service doesn't actually return anything
Here are my proposed changes for the service:
getData() {
this.objAr = utils.sheet_to_json(this.wbSheet, { header: 1 });
return this.objAr;
}
and for the component:
export class AppComponent implements OnInit {
ObjArray: any[] = [];
constructor(private _operationDataService: OperationDataService) { }
ngOnInit() {
let data = this._operationDataService.getData();
this.ObjArray.push(data);
}
}
A: this it's work :
Upload() {
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.arrayBuffer = fileReader.result;
/* convert data to binary string */
var data = new Uint8Array(this.arrayBuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
console.log('excel data:',XLSX.utils.sheet_to_json(worksheet,{raw:true}));
}
fileReader.readAsArrayBuffer(this.file);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40240861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert SQL (Left Outer Join's) to LINQ I am having trouble converting a Oracle Sql Query with multiple LEFT OUTER JOIN to LINQ. My attempts don't return the expected results. Could somebody help to convert the SQL Query below to LINQ.
string currentCulture = Culture.GetCulture();
string query = @"SELECT *
FROM CTGLBL g, CTTGLBL ct, CTLANG lang
WHERE g.sysctglbl = ct.sysctglbl(+) AND
ct.sysctlang = lang.sysctlang (+) AND
NVL(lang.activeflag, 1)= 1 AND
(ISOCODE LIKE '" + currentCulture + "%' OR ISOCODE IS NULL)";
ISOCODE belongs to CTLANG Table.
ps. I can't use tools like LINQPAD or Linqer.
A: But a better practice for your sql (and here converted to linq) is to use join to join tables and not the where:
string currentCulture = Culture.GetCulture();
var result = from g in CTGLBL
join ct in CTTGLBL on g.sysctglbl equals ct.sysctglbl into ctj
from ct in ctj.DefaultIfEmpty()
join lang in CTLANG on ct.sysctlang equals lang.sysctlang into langj
from lang in langj.DefaultIfEmpty()
where (lang == null ? 1 : (lang.activeflag ?? 1)) == 1 &&
(lang?.ISOCODE.StartsWith(currentCulture) || lang?.ISOCODE == null)
select new { g, ct, lang };
You can also have a "nested select" for your CTLANG like this:
string currentCulture = Culture.GetCulture();
var result = from g in CTGLBL
join ct in CTTGLBL on g.sysctglbl equals ct.sysctglbl into ctj
from ct in ctj.DefaultIfEmpty()
join lang in CTTGLBL.Where(lang => lang.activeflag ?? 1 == 1 &&
(lang.ISOCODE.Contains(currentCulture) ||
lang.ISOCODE == null))
on ct.sysctlang equals lang.sysctlang into langj
from lang in langj.DefaultIfEmpty()
select new { g, ct, lang };
A: (What I see is a left join, not right)
Assuming you have the proper relations between the tables in your schema, with SQL server (Linq TO SQL) this would work, not sure if it would supported for Oracle:
string currentCulture = Culture.GetCulture();
var data = from g in db.CTGLBL
from ct in g.CTTGLBL.DefaultIfEmpty()
from lang in g.CTLANG.DefaultIfEmpty()
where !g.CTLANG.Any() ||
( lang.activeflag == 1 &&
lang.ISOCODE.StartsWith(currentCulture))
select new {g, ct, lang};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38914184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do exit a while loop with a JOptionPane I am having trouble with my code, I am trying to exit this loop if the user clicks on the CANCEL.OPTION or the CLOSED.OPTION. I handled the exception but can't seem to be able to use the buttons on the window. The program gets the users birthyear from their input of their age. The problem i am having is that I cannot end the loop through the buttons. Thanks in advance!
public Integer getBirthYear() {
boolean prompt = true;
while(prompt) {
String enteredAge = showInputDialog(null,"Enter age:");
try {
age = Integer.parseInt(enteredAge);
if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
System.out.println("MADE IT INTO IF");
}
age = year - age;
prompt = false;
showMessageDialog(null,age);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
return age;
}
A: There are several overloaded versions of showInputDialog, with different parameters. Only the javadoc of the last version documents correctly that the return value is null when the user pressed cancel.
public int getBirthYear() {
boolean prompt = true;
while (prompt) {
String enteredAge = showInputDialog(null,"Enter age:");
if (enteredAge == null) { // Cancel pressed
age = -1;
prompt = false;
} else {
try {
age = Integer.parseInt(enteredAge);
age = year - age;
prompt = false;
showMessageDialog(null, age);
} catch (NumberFormatException e) {
showMessageDialog(null, "Enter a valid number");
}
}
}
return age;
}
It might be you want to restructure the program a bit; make age a local variable or whatever. Use int for real integer values. Integer is the Object wrapper class for an int.
A: The most easiest answer to your question is, just put promp = false outside of your try and catch clause and it should work:
public Integer getBirthYear() {
boolean prompt = true;
while(prompt) {
String enteredAge = showInputDialog(null,"Enter age:");
try {
age = Integer.parseInt(enteredAge);
if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
System.out.println("MADE IT INTO IF");
}
age = year - age;
showMessageDialog(null,age);
} catch (NumberFormatException e) {
e.printStackTrace();
}
prompt = false;
}
return age;
}
A: The problem was in the scope. The entered age wasnt making it into the catch block. I resolved that issue.
public Integer getBirthYear() {
boolean prompt = true;
do {
try {
age = year - Integer.parseInt(showInputDialog(null,"Enter age:"));
prompt = false;
showMessageDialog(null, age);
} catch (NumberFormatException e) {
String ageEntered = showInputDialog(null,"Enter age:");
e.printStackTrace();
if(ageEntered == null) { //close the file if Cancel is chosen
prompt = false;
}
}
} while(prompt);
return age;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47026099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to send form data as csv file or as pdf in email in android studio i have a form from where i have taken user input and it includes checkbox and edittext field; i need to send this through email i tried using itext for pdf and even csv files but none works below is my csv file it sends email but does not send data along with it.
MainActivity:
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void export(View view) {
//generate data
StringBuilder data = new StringBuilder();
data.append("Time,Distance");
for(int i = 0; i<5; i++){
data.append("\n"+String.valueOf(i)+","+String.valueOf(i*i));
}
try{
//saving the file into device
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
out.write((data.toString()).getBytes());
out.close();
//exporting
Context context = getApplicationContext();
File filelocation = new File(getFilesDir(), "data.csv");
Uri path = FileProvider.getUriForFile
(context, "com.example.exportcsv.fileprovider", filelocation);
Intent fileIntent = new Intent(Intent.ACTION_SEND);
fileIntent.setType("text/csv");
fileIntent.putExtra(Intent.EXTRA_SUBJECT, "Data");
fileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
fileIntent.putExtra(Intent.EXTRA_STREAM, path);
startActivity(Intent.createChooser(fileIntent, "Send mail"));
}
catch(Exception e){
e.printStackTrace();
}
}
}
Provider_paths:
<paths>
<files-path
name="data"
path="."/>
</paths>
Activity_main:
<ScrollView
android:id="@+id/scrollView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#72C8E8"
android:padding="4sp"
android:paddingLeft="4sp"
android:paddingTop="4sp"
android:paddingRight="4sp"
android:paddingBottom="4sp"
android:text="@string/name"
android:textColor="@color/colorPrimaryDark"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="@+id/textView2"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#72C8E8"
android:text="@string/age"
android:padding="4sp"
android:paddingLeft="4sp"
android:paddingTop="4sp"
android:paddingRight="4sp"
android:paddingBottom="4sp"
android:textColor="@color/colorPrimaryDark"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<TextView
android:id="@+id/textView3"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#72C8E8"
android:padding="4sp"
android:paddingLeft="4sp"
android:paddingTop="4sp"
android:paddingRight="4sp"
android:paddingBottom="4sp"
android:text="@string/gender"
android:textColor="@color/colorPrimaryDark"
android:textSize="30sp"
android:textStyle="bold" />
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="onCheckboxClicked"
android:text="@string/m"
android:textSize="24sp" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:onClick="onCheckboxClicked"
android:text="@string/f"
android:textSize="24sp" />
<TextView
android:id="@+id/textView4"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#72C8E8"
android:padding="4sp"
android:paddingLeft="4sp"
android:paddingTop="4sp"
android:paddingRight="4sp"
android:paddingBottom="4sp"
android:text="@string/address"
android:textColor="@color/colorPrimaryDark"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPostalAddress" />
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_marginTop="20dp"
android:layout_height="wrap_content"
android:background="#72C8E8"
android:text="@string/phone"
android:padding="4sp"
android:paddingLeft="4sp"
android:paddingTop="4sp"
android:paddingRight="4sp"
android:paddingBottom="4sp"
android:textColor="@color/colorPrimaryDark"
android:textSize="30sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<Button
android:id="@+id/button"
android:layout_marginTop="30dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:textSize="24sp"
android:onClick="export"
android:padding="4sp"
android:background="#72C8E8"
android:paddingLeft="4sp"
android:paddingTop="4sp"
android:paddingRight="4sp"
android:paddingBottom="4sp"
android:text="@string/export" />
</LinearLayout>
</ScrollView>
A: Please refer this tutorial to send an email with attachment: https://www.google.com/amp/s/javatutorial.net/send-email-with-attachments-android/amp
You also don't need the "text/csv" mimetype, this is for the email and wrong as you need plain text or html, as you prefer.
In addition to that, do you have the file read permission?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61121769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Missing Character For KeyEvent When using the KeyTyped method for the KeyListener, sometimes I get "missing characters". I'll show the code I use to get them, then ask my question.
public class KeyInput implements KeyListener
{
public void keyTyped(KeyEvent e)
{
System.out.println(e.getKeyChar());
}
}
I left out a few required methods because they are unrelated to my question. If I press a letter, it prints the letter to console. But if I use a key combination, ie. control + g, The character printed to console is just a square with a question mark.
Is there a way to detect if the character is a "missing character"?
A: Maybe you can use the canDisplay(...) method of the Font class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64083572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ktor modify request on retry not working as expected I have a custom retry policy on receiving 5XX errors from the server. The idea is to retry until I get a non-5XX error with an exponential delay between each retry request also I would like to update the request body on every retry.
Here is my code
import io.ktor.client.*
import io.ktor.client.engine.java.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.request.*
import io.ktor.server.routing.*
import kotlinx.coroutines.*
import kotlin.time.Duration.Companion.seconds
suspend fun main() {
val serverJob = CoroutineScope(Dispatchers.Default).launch { startServer() }
val client = HttpClient(Java) {
install(HttpTimeout) {
connectTimeoutMillis = 5.seconds.inWholeMilliseconds
}
install(HttpRequestRetry)
}
client.post {
url("http://127.0.0.1:8080/")
setBody("Hello")
retry {
retryOnServerErrors(maxRetries = Int.MAX_VALUE)
exponentialDelay(maxDelayMs = 128.seconds.inWholeMilliseconds)
modifyRequest { it.setBody("With Different body ...") } // It's not working! if I comment this out then my retry logic works as expected
}
}
client.close()
serverJob.cancelAndJoin()
}
suspend fun startServer() {
embeddedServer(Netty, port = 8080) {
routing {
post("/") {
val text = call.receiveText()
println("Retrying exponentially... $text")
call.response.status(HttpStatusCode(500, "internal server error"))
}
}
}.start(wait = true)
}
As you can see, if I comment out modifyRequest { it.setBody("With Different body ...") } line from retry logic then everything works fine. If I include that line it only tries once and stuck there, what I'm doing wrong here? how to change the request body for every retry?
A: The problem is that rendering (transformation to an OutgoingContent) of a request body happens during the execution of the HttpRequestPipeline, which takes place only once after making an initial request. The HTTP request retrying happens after in the HttpSendPipeline.
Since you pass a String as a request body it needs to be transformed before the actual sending. To solve this problem, you can manually wrap your String into the TextContent instance and pass it to the setBody method:
retry {
retryOnServerErrors(maxRetries = Int.MAX_VALUE)
exponentialDelay(maxDelayMs = 128.seconds.inWholeMilliseconds)
modifyRequest {
it.setBody(TextContent("With Different body ...", ContentType.Text.Plain))
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75219405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Affect Second Spinner Choices based on First Spinner So I can see that there are questions about this, but not in the scope of mine. I am buliding an app for Android that has two spinners. The first has an array of choices. However, I am not sure how to affect what choices the second one has based on the first one. I know that you can put in
AdapterView.OnItemSelectedListener
but I'm not sure how to implement this. I've read on this but it's not quite what I'm looking for. I'm also curious as to how I tell the spinner which array to choose, is it in the .xml or in the .java file?
A: Try this,
firstSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
string selectedValue = arg0.getSelectedItem().toString();
if(selectedValue.equalsIgnoreCase(string1)
{
ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, firstArray);
secondSpinner.setAdapter(firstAdapter);//
}
else if(selectedValue.equalsIgnoreCase(string2)
{
ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);
secondSpinner.setAdapter(firstAdapter);
}
}
Hope it will help you.
A: If it's a String array you could define it in XML then use getResource().getStringArray() or declare it in Java.
In your listener for the first spinner, you could do the following to set the choices for the second spinner.
secondSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, newArray);
secondSpinner.setAdapter(secondSpinnerAdapter);
Tested and working
A: update the array list of second spinner in 1st spinner setOnItemSelectedListener
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
string str=spinner1.getSelectedItem().toString();
if(str.equals("spinner item"))//spinner item is selected item of spinner1
{
ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, array1);
//adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter1);//
}else if{
ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);
//adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter2);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18648489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I do closures in Emacs Lisp? I'm trying to create a function on the fly that would return one constant value.
In JavaScript and other modern imperative languages I would use closures:
function id(a) {
return function() {return a;};
}
but Emacs lisp doesn't support those.
I can create mix of identity function and partial function application but it's not supported either.
So how do I do that?
A: Emacs lisp only has dynamic scoping. There's a lexical-let macro that approximates lexical scoping through a rather terrible hack.
A: Found another solution with lexical-let
(defun foo (n)
(lexical-let ((n n)) #'(lambda() n)))
(funcall (foo 10)) ;; => 10
A: Emacs 24 has lexical binding.
http://www.emacswiki.org/emacs/LexicalBinding
A: ;; -*- lexical-binding:t -*-
(defun create-counter ()
(let ((c 0))
(lambda ()
(setq c (+ c 1))
c)))
(setq counter (create-counter))
(funcall counter) ; => 1
(funcall counter) ; => 2
(funcall counter) ; => 3 ...
A: Real (Not Fake) Closures in Emacs 24.
Although Emacs 24 has lexical scooping when the variable lexical-binding has value t, the defun special form doesn’t work properly in lexically bound contexts (at least not in Emacs 24.2.1.) This makes it difficult, but not impossible, to define real (not fake) closures. For example:
(let ((counter 0))
(defun counting ()
(setq counter (1+ counter))))
will not work as expected because the symbol counter in the defun will be bound to the global variable of that name, if there is one, and not the lexical variable define in the let. When the function counting is called, if the global variable doesn’t, exist then it will obviously fail. Hoever if there is such a global variable it be updated, which is probably not what was intended and could be a hard to trace bug since the function might appear to be working properly.
The byte compiler does give a warning if you use defun in this way and presumably the issue will be addressed in some future version of Emacs, but until then the following macro can be used:
(defmacro defun** (name args &rest body)
"Define NAME as a function in a lexically bound context.
Like normal `defun', except that it works correctly in lexically
bound contexts.
\(fn NAME ARGLIST [DOCSTRING] BODY...)"
(let ((bound-as-var (boundp `,name)))
(when (fboundp `,name)
(message "Redefining function/macro: %s" `,name))
(append
`(progn
(defvar ,name nil)
(fset (quote ,name) (lambda (,@args) ,@body)))
(if bound-as-var
'nil
`((makunbound `,name))))))
If you define counting as follows:
(let ((counter 0))
(defun** counting ()
(setq counter (1+ counter))))
it will work as expected and update the lexically bound variable count every time it is invoked, while returning the new value.
CAVEAT: The macro will not work properly if you try to defun** a function with the same name as one of the lexically bound variables. I.e if you do something like:
(let ((dont-do-this 10))
(defun** dont-do-this ()
.........
.........))
I can’t imagine anyone actually doing that but it was worth a mention.
Note: I have named the macro defun** so that it doesn’t clash with the macro defun* in the cl package, however it doesn’t depend in any way on that package.
A: Stupid idea: how about:
(defun foo (x)
`(lambda () ,x))
(funcall (foo 10)) ;; => 10
A: http://www.emacswiki.org/emacs/FakeClosures
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/593383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.