text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: What color does plot.xts use? Does anybody know what colours plot.xts uses? I can't find anything on the help page.
I would like to use the same colours in my legend.
Or is there another way to get the same plot with addLegend()?
Here the code I am using:
library(xts)
library(PerformanceAnalytics)
library(TTR)
xts1 <- xts(matrix(rnorm(300), ncol = 3), order.by = as.Date(1:100))
xts2 <- xts(matrix(rnorm(300), ncol = 3), order.by = as.Date(1:100))
colnames(xts1) <- c("A", "B", "C")
colnames(xts2) <- c("A", "B", "C")
plot_chart <- function(x) {
ff <- tempfile()
png(filename = ff)
chart.CumReturns(x)
dev.off()
unlink(ff)
}
m <- matrix(c(1, 2, 3, 3), nrow = 2, ncol = 2, byrow = TRUE)
layout(mat = m, heights = c(0.8, 0.1))
par(mar = c(2, 2, 1, 1))
plot_chart(xts1)
addSeries(reclass(apply(xts1, 2, runSD), xts1))
par(mar = c(2, 2, 1, 1))
plot_chart(xts2)
addSeries(reclass(apply(xts2, 2, runSD), xts2))
par(mar=c(0, 0, 1, 0))
plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
# which colors do I have to insert in here?
plot_colors <- c("blue", "green", "pink")
legend(x = "top", inset = 0,
legend = colnames(xts1),
col = plot_colors, lwd = 7, cex = .7, horiz = TRUE)
A: Answer
Use the colorset argument of chart.CumReturns:
plot_chart <- function(x, col) {
ff <- tempfile()
png(filename = ff)
chart.CumReturns(x, colorset = col)
dev.off()
unlink(ff)
}
par(mar = c(2, 2, 1, 1))
plot_chart(xts1, col = plot_colors)
addSeries(reclass(apply(xts1, 2, runSD), xts1))
par(mar = c(2, 2, 1, 1))
plot_chart(xts2, col = plot_colors)
addSeries(reclass(apply(xts2, 2, runSD), xts2))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67884036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to develop custom cocoa-pod of your existing Xcode project? If you want to create you own cocoapods with storyboards, XIBs, resources and with other frameworks such as Alamofire, MBProgressHUD etc.
A:
Easy steps to create Cocoapod from existing xcode project
*
*Create a repository on your git account (Repo name, check README,
choose MIT under license).
*Copy the url of your repository.Open terminal and run following command.
git clone copied your repository url
*Now copy your Xcode project inside the cloned repository folder on
your Mac. Now run following commands
git add -u to add all files (if not added use: git add filepath/folder)
git commit -m "your custom message"
git push origin master
*Create a new release to go to your git repository or run following commands
git tag 1.0.0
git push --tags
*First, we need to make sure that you have CocoaPods installed and
ready to use in your Terminal. run the following command:
sudo gem install cocoapods --pre
Creating a Podspec
*
*All Pods have a podspec file. A podspec, as its name suggests,
defines the specifications of the Pod! Now let’s make one, run
following command on terminal
touch PodName.podspec
*After adding and modifying your .podspec file. Validate your .podspec
file by hitting following command on terminal
pod lib lint
*Once you validate it successfully without errors run following
command to register you and build cocoapod respectively
pod trunk register
pod trunk push PodName.podspec
If all goes well, you will get this on terminal
PodName (1.0.0) successfully published
February 5th, 02:32
https://cocoapods.org/pods/PodName
Tell your friends!
Yeah!!!!! congrats you have got your pod link. Use wherever you want to use it.
A: Here is some useful links . You can follow the same.
https://www.appcoda.com/cocoapods-making-guide/
https://www.raywenderlich.com/5823-how-to-create-a-cocoapod-in-swift
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60143421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: IBM Worklight 6.0 - iOS app always stuck on the second launch I have an issue with Worklight 6.0 while testing my app in an iOS device and iOS Simulator.
*
*First, when I install the app on iOS device / iOS Simulator using Xcode "run" button, it works.
*But after I stop it and launch it again from the Springboard, it freezes / is blocked on splash screen.
I am using Eclipse 4.2.1 for Mac with Worklight 6.0 plugin. I also use Xcode 4.6.
I have tested with three newly created projects, and also with a blank one, and I always have the same issue.
When I test with a project created by a previous Worklight version, it works (for example athe HelloWorklightApp sample project).
A: *
*What's the difference between "newly created projects" and "a blank one"?
*Did you change the HTML filename of the application in your-project\apps\your-app\common prior to deployment?
*Also, while this is probably not related, but do note that if using Worklight 6.0, make sure that you have installed it in Eclipse 4.2.2; not 4.0 not 4.1 not 4.2.1, only 4.2.2.
*Is this an upgraded installation of Worklight, or a new one in a new Eclipse instance and a new workspace?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18616857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 3D Camera Rotation in OpenGL: How to prevent camera jitter? I'm fairly new to OpenGL and 3D programming but I've begun to implement camera rotation using quaternions based on the tutorial from http://www.cprogramming.com/tutorial/3d/quaternions.html . This is all written in Java using JOGL.
I realise these kind of questions get asked quite a lot but I've been searching around and can't find a solution that works so I figured it might be a problem with my code specifically.
So the problem is that there is jittering and odd rotation if I do two different successive rotations on one or more axis. The first rotation along the an axis, either negatively or positively, works fine. However, if I rotate positively along the an axis and then rotate negatively on that axis then the rotation will jitter back and forth as if it was alternating between doing a positive and negative rotation.
If I automate the rotation, (e.g. rotate left 500 times then rotate right 500 times) then it appears to work properly which led me to think this might be related to the keypresses. However, the rotation is also incorrect (for lack of a better word) if I rotate around the x axis and then rotate around the y axis afterwards.
Anyway, I have a renderer class with the following display loop for drawing `scene nodes':
private void render(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(70, Constants.viewWidth / Constants.viewHeight, 0.1, 30000);
gl.glScalef(1.0f, -1.0f, 1.0f); //flip the y axis
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
camera.rotateCamera();
glu.gluLookAt(camera.getCamX(), camera.getCamY(), camera.getCamZ(), camera.getViewX(), camera.getViewY(), camera.getViewZ(), 0, 1, 0);
drawSceneNodes(gl);
}
private void drawSceneNodes(GL2 gl) {
if (currentEvent != null) {
ArrayList<SceneNode> sceneNodes = currentEvent.getSceneNodes();
for (SceneNode sceneNode : sceneNodes) {
sceneNode.update(gl);
}
}
if (renderQueue.size() > 0) {
currentEvent = renderQueue.remove(0);
}
}
Rotation is performed in the camera class as follows:
public class Camera {
private double width;
private double height;
private double rotation = 0;
private Vector3D cam = new Vector3D(0, 0, 0);
private Vector3D view = new Vector3D(0, 0, 0);
private Vector3D axis = new Vector3D(0, 0, 0);
private Rotation total = new Rotation(0, 0, 0, 1, true);
public Camera(GL2 gl, Vector3D cam, Vector3D view, int width, int height) {
this.cam = cam;
this.view = view;
this.width = width;
this.height = height;
}
public void rotateCamera() {
if (rotation != 0) {
//generate local quaternion from new axis and new rotation
Rotation local = new Rotation(Math.cos(rotation/2), Math.sin(rotation/2 * axis.getX()), Math.sin(rotation/2 * axis.getY()), Math.sin(rotation/2 * axis.getZ()), true);
//multiply local quaternion and total quaternion
total = total.applyTo(local);
//rotate the position of the camera with the new total quaternion
cam = rotatePoint(cam);
//set next rotation to 0
rotation = 0;
}
}
public Vector3D rotatePoint(Vector3D point) {
//set world centre to origin, i.e. (width/2, height/2, 0) to (0, 0, 0)
point = new Vector3D(point.getX() - width/2, point.getY() - height/2, point.getZ());
//rotate point
point = total.applyTo(point);
//set point in world coordinates, i.e. (0, 0, 0) to (width/2, height/2, 0)
return new Vector3D(point.getX() + width/2, point.getY() + height/2, point.getZ());
}
public void setAxis(Vector3D axis) {
this.axis = axis;
}
public void setRotation(double rotation) {
this.rotation = rotation;
}
}
The method rotateCamera generates the new permenant quaternions from the new rotation and previous rotations while the method rotatePoint merely multiplies a point by the rotation matrix generated from the permenant quaternion.
The axis of rotation and the angle of rotation are set by simple key presses as follows:
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
camera.setAxis(new float[] {1, 0, 0});
camera.setRotation(0.1f);
}
if (e.getKeyCode() == KeyEvent.VK_A) {
camera.setAxis(new float[] {0, 1, 0});
camera.setRotation(0.1f);
}
if (e.getKeyCode() == KeyEvent.VK_S) {
camera.setAxis(new float[] {1, 0, 0});
camera.setRotation(-0.1f);
}
if (e.getKeyCode() == KeyEvent.VK_D) {
camera.setAxis(new float[] {0, 1, 0});
camera.setRotation(-0.1f);
}
}
I hope I've provided enough detail. Any help would be very much appreciated.
A: About the jittering: I don't see any render loop in your code. How is the render method triggered? By a timer or by an event?
Your messed up rotations when rotating about two axes are probably related to the fact that you need to rotate the axis of the second rotation along with the total rotation of the first axis. You cannot just apply the rotation about the X or Y axis of the global coordinate system. You must apply the rotation about the up and right axes of the camera.
I suggest that you create a camera class that stores the up, right and view direction vectors of the camera and apply your rotations directly to those axes. If this is an FPS like camera, then you'll want to rotate the camera horizontally (looking left / right) about the absolute Y axis and not the up vector. This will also result in a new right axis of the camera. Then, you rotate the camera vertically (looking up / down) about the new right axis. However, you must be careful when the camera looks directly up or down, as in this case you can't use the cross product of the view direction and up vectors to obtain the right vector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10328262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get key value of matching case insensitive string I'm attempting to pull some specific data from the "id" field but jq matches are being case sensitive and creating an issue with the searches (not matching, basically, so returning 0 results).
JSON Example:
{
"created_at": "2020-01-17T12:54:02Z",
"primary": true,
"verified": true,
"deliverable_state": "deliverable",
"undeliverable_count": 0,
"updated_at": "2020-01-17T12:54:03Z",
"url": "http://www.website.com",
"id": 376062709553,
"user_id": 374002305374,
"type": "email",
"value": "[email protected]"
}
{
"created_at": "2019-02-07T20:49:41Z",
"primary": false,
"verified": true,
"deliverable_state": "deliverable",
"undeliverable_count": 0,
"updated_at": "2019-02-07T20:49:41Z",
"url": "http://www.website.com",
"id": 366235941554,
"user_id": 374002305374,
"type": "email",
"value": "[email protected]"
}
When running jq against the following, I get the correct return:
$ jq -r '. | select(.value=="[email protected]") .id' sample.json
366235941554
But if I run with the incorrect case, eg.
$ jq -r '. | select(.value=="[email protected]") .id' sample.json
...I do not get a result. I've read through some of the documentation but unfortunately, I do not understand the test/match/capture flags for insensitive search (https://stedolan.github.io/jq/manual/#RegularexpressionsPCRE) or how to get it to operate with this "locate and give me the value" request.
I've searched seemingly everywhere but I'm unable to find any examples of this being used.
A: You don't really need regexp for this.
select(.value | ascii_downcase == "[email protected]") .id
But if you insist on it, below is how you perform a case-insensitive match using test/2.
select(.value | test("[email protected]"; "i")) .id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59969841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I update a pre-formatted DataGridView bound to a list? I have a DataGridView that I am binding to the Values collection of a dictionary. In my form's constructor, I can create the dictionary and bind the columns of the DataGridView to fields in the structure that will be contained in the dictionary:
m_tasks = new Dictionary<int,OperationsTaskLabeledData>();
var taskArray = from task in m_tasks.Values select new {
StartDate = task.m_start_task_date.ToString("M/dd H:mm"),
EndDate = task.m_task_date.ToString("M/dd H:mm"),
Description = task.m_short_desc,
Object = task.m_device_id,
InitialLocation = task.m_initial_location,
FinalLocation = task.m_final_location };
dgvFutureTasks.DataSource = taskArray.ToArray();
I want this code in the form's constructor so that the columns can be formatted, and I won't have to reformat them every time data in the grid is updated.
When I actually have data to display in this datagridview, what do I do with it? I will call this function:
private void DisplayFutureTasks(IEnumerable<OperationsTaskLabeledData> tasks)
But I don't know what to do inside this function.
I can just re-bind the datagridview control and reformat all of the columns each time the control is updated, but that seems very wasteful. I'm sure there's a better way to do it, and I'd much rather do this in some reasonable fashion instead of using ugly brute force.
A: I have now figured out how to do what I want to do.
I know the columns I will need at design time, so in the IDE I add the columns to my datagridview and format them as desired. I then set the AutoGenerateColumns property of the grid view to false. For some unknown reason, that property is not available in the designer and has to be set in code. Finally, I can set the DataPropertyName of each column to the name of the corresponding field in the structure I will be linking to. For example, here is the LINQ code I will be using to generate the data source:
taskArray = from task in tasks select new {
StartDate = task.m_start_task_date.ToString("M/dd H:mm"),
EndDate = task.m_task_date.ToString("M/dd H:mm"),
Description = task.m_short_desc,
Object = task.m_device_id,
InitialLocation = task.m_initial_location,
FinalLocation = task.m_final_location };
.DataSource = taskArray.ToArray();
And here is the code in my form's constructor to set the DataPropertyName properties:
dgvFutureTasks.AutoGenerateColumns = false;
dgvFutureTasks.Columns["colStartTime"].DataPropertyName = "StartDate";
dgvFutureTasks.Columns["colFinishTime"].DataPropertyName = "EndDate";
dgvFutureTasks.Columns["colDescription"].DataPropertyName = "Description";
dgvFutureTasks.Columns["colObject"].DataPropertyName = "Object";
dgvFutureTasks.Columns["colInitialLocation"].DataPropertyName = "InitialLocation";
dgvFutureTasks.Columns["colFinalLocation"].DataPropertyName = "FinalLocation";
At this point, the DataGridView displayed the data as expected.
RobR
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15372939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: previous website advertise on the google advert on the currently visited website I have observed that when I visit some websites (e.g. ebay, flipkart, etc) and move on to another website, I start to see items from the previous website on the google advert on the currently visited website.
ie , when the visitor moves on from 'mysite.com' to another website 'example.com', i need to display advertisement of 'mysite.com' (to promote mysite.com) on exmaple.com's google advert area.
how this works? is we have any control on this? or google is handling this?
A: Although this is off-topic but to answer your question, this is called re-targeting. You can do that using google adwords program - it works through the use of cookies.
A: It's called remarketing in AdWords and there are various flavours of it on the platform. There are dedicated remarketing campaign type templates available when creating a new campaign in AdWords.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32331421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: rowExpansion inside datatable inside multiple tabs inside tabview referring to row object in last tab only I have a p:tabView several dynamic p:tab, each of these tabs contain an identical p:dataTable. Ech datatable row contains a p:rowExpansion.
Problem:
When I click the rowToggler for any row it always uses the row from the last tab.
Symptoms:
If I go to tab1 and click expand on row1, then the contents are build using the row1 from the last tab.
If I go to tab1 and click expand on row10 where there is only 9 rows in the last tab, then the row object is null.
Solutions?
I understand that the rowExpansion is loaded lazily, so only once the rowToggler is clicked. Is there a way to prevent this and load the contents upfront? This would solve my problem perfectly.
Alternatively, is there a way to give the rowExpansion any hint as to which row it belongs to? Can I access the current rowKey or rowIndex in order to pass it on to the backing bean?
What I tried
Ideally, the tabs should be dynamic, so I use c:forEach and put my datatable under that.
I also tried to hardcode the tabs and use ui:include under those with my datatable in a separate xhtml file, but no change.
The closest question related to my problem I found was:
Primefaces dataTable inside tabView the row selection not working correctly
But there was no answer for it.
Here is what is looks like:
<p:tabView rendered="#{controller.model.hasPerformances}"
styleClass="#{controller.fontClass} }"
activeIndex="#{controller.model.performanceIndex}">
<p:ajax event="tabChange" listener="#{controller.onTestTabChanged}"/>
<c:forEach var="performance" items="#{controller.model.performances}">
<p:tab title="#{controller.getPerformanceDisplayName(performance)}">
<p:dataTable id="testTable"
var="row"
value="#{controller.model.testData.getRows(performance)}"
styleClass="#{controller.fontClass}"
style="margin-top: 10px;"
widgetVar="testTable">
<f:facet name="header">
<div style="height:30px;">
#{controller.getPerformanceTestTitleName(performance)}
</div>
</f:facet>
<p:column style="width:1ch" class="tlga-table-column-expand" exportable="false">
<p:rowToggler/>
</p:column>
<p:columns value="#{controller.model.testData.columns}"
var="column"
style="#{column.style}"
styleClass="#{row.getCellClass(column)}"
columnIndexVar="colIndex">
<f:facet name="header">
<h:outputText value="#{column.title}"/>
</f:facet>
<h:outputText value="#{row.getCellValue(column)}"/>
</p:columns>
<p:rowExpansion>
<p:dataGrid columns="3"
styleClass="test-collapsed-area"
value="#{row.collapsedCells}"
var="collapsedCell">
<p:panelGrid columns="2" styleClass="test-collapsed-value">
<h:outputLabel value="#{collapsedCell.title}"
class="#{controller.fontClass} presentation-label"/>
<h:outputText value="#{collapsedCell.value}"
class="#{controller.fontClass} presentation-text"/>
</p:panelGrid>
</p:dataGrid>
</p:rowExpansion>
</p:dataTable>
</p:tab>
</c:forEach>
</p:tabView>
</p:panel>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57558609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to keep a variable in memory until the app quits I have a singleton object in iOS that when instantiated parses a CSV file and then holds the results. I would like to make this object universally accessible and I would like it to not be released from memory until the app quits. I am running ARC so I cannot do manual retains.
Is there a way I can do this so it will work with ARC?
Header File:
#import <Foundation/Foundation.h>
#import "CHCSV.h"
#import "RCParserObject.h"
@interface ParserStore : NSObject <CHCSVParserDelegate>
{
// CSV Variables
RCParserObject *item;
NSMutableArray *data;
NSMutableArray *parsedData;
int fields;
bool open;
}
@property (atomic, retain) RCParserObject *item;
@property (atomic, retain) NSMutableArray *data;
@property (atomic, retain) NSMutableArray *parsedData;
@property (atomic) int fields;
@property (atomic) bool open;
+ (ParserStore *) defaultStore;
- (void) parseCSVFile:(NSString*)file;
- (void) categorizeData;
Implementation File
#import "ParserStore.h"
#import "RCParserObject.h"
#import "RCDetailItem.h"
static ParserStore *defaultStore;
@implementation ParserStore
@synthesize item, data, parsedData, fields, open;
# pragma mark -
# pragma mark Singleton Methods
+ (ParserStore *) defaultStore
{
if (!defaultStore)
{
defaultStore = [[super allocWithZone:NULL] init];
}
return defaultStore;
}
+ (id) allocWithZone:(NSZone *)zone
{
return [self defaultStore];
}
- (id) init
{
NSLog(@"Running init on parser store");
if (defaultStore)
{
NSLog(@"Self data count is %d, right before return", self.parsedData.count);
return defaultStore;
}
// NSLog(@"This better only happen once");
self = [super init];
[self setParsedData:[[NSMutableArray alloc] init]];
[self parseCSVFile:@"ContentNoPathFileExt2ASCII"];
[self categorizeData];
// NSLog(@"Self data count is %d when first created", self.parsedData.count);
return self;
}
@property (atomic, retain) RCParserObject *item;
@property (atomic, retain) NSMutableArray *data;
@property (atomic, retain) NSMutableArray *parsedData;
@property (atomic) int fields;
@property (atomic) bool open;
+ (ParserStore *) defaultStore;
- (void) parseCSVFile:(NSString*)file;
- (void) categorizeData;
@end
A: +(MySingleton *)singleton {
static dispatch_once_t pred;
static MySingleton *shared = nil;
dispatch_once(&pred, ^{
shared = [[MySingleton alloc] init];
shared.someVar = someValue; // if you want to initialize an ivar
});
return shared;
}
From anywhere:
NSLog(@"%@",[MySingleton singleton].someVar);
Note that your iOS app already has a singleton that you can access anywhere:
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
A: a simple singleton would be something like... in the .h:
@interface Foo : NSObject
+ (Foo *)sharedInstance;
@end
and in the .m:
static Foo *_foo = nil;
@implementation Foo
+ (Foo *)sharedInstance {
if (!_foo)
_foo = [[Foo alloc] init];
return _foo;
}
@end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8774602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Continuous Animation Android I want to make an image move on the Y axis downwards but then come back in the initial position not by redrawing but also by animation. How can I do this? I have tried 2 ways: creating 2 separate animations in the .java file, and then by creating an xml. In the xml I've tried writing a command inside another < set> command and didn't work. Also i've tried a command inside another < translate> command. So ... any ideas may be appreciated!
A: Android includes some commands in code rather than XML that will move things around. There's a great guide here that will help you learn how to implement them.
From there, implement an animation listener to tell when the first animation ends (as seen in the Google documentation here) ain order to start the second animation after the first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18167101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Tkinter - Entry widget text to go to next line instead of continuing to the side so I made my entry widget for user input and made ipady larger. I thought this would make it so the text will automatically go to the next line but the text continues on. Is it possible to make the entry so that the text goes down instead and if it passes the length of ipady then create a scrollbar?
def body(self, master):
#input fields for username and passwords
Label(master, text="Name:").grid(row=1, column=1, sticky=W),
Label(master, text="Date:").grid(row=2, column=1, sticky=W)
Label(master, text=":").grid(row=4)
Label(master, text=":").grid(row=3, column=3)
Label(master, text=":").grid(row=5)
Label(master, text=":").grid(row=7)
Label(master, text="L").grid(row=6)
self.text = tk.StringVar()
self.text.set(':')
self.text1 = tk.StringVar()
self.text1.set(':')
#input fields for tags
#Entry fields
self.e1 = Entry(master)
self.e2 = Entry(master)
self.e3 = Entry(master, textvariable = self.text)
self.e4 = Entry(master)
self.e5 = Entry(master, textvariable = self.text1)
self.e6 = Entry(master)
self.e7 = Entry(master)
#Entry field Placement
self.e1.grid(row=1, column=1, columnspan=2, ipadx=50)
self.e2.grid(row=2, column=1, columnspan=2, ipadx=50)
self.e3.grid(row=4, column=1, ipadx=150)
self.e4.grid(row=4, column=3, ipadx=150, ipady=75)
self.e5.grid(row=5, column=1, ipadx=150, ipadx=75)
self.e6.grid(row=5, column=3, ipadx=150)
self.e7.grid(row=6, column=1, ipadx=10, sticky=W)
A:
Is it possible to make the entry so that the text goes down instead ...?
No, it is not. The Entry widget is specifically designed for single-line input. If you need multiple lines you need to use the Text widget.
A: Entry widgents have only a single line. You'll have to use a 'Text' widget and print ('\n') for every entery letter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65415224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tabs click not working when using ng-repeat I have a script to add custom tabs on runtime.All the tabs are being created but for some reason those created with ng-repeat can't be selected, is like a plain label. What am I missing?
<ul class="clearfix tabs-list tabamount6 tabs">
<li data-tab="tab-1">News</li>
<li data-tab="tab-2">Meet the team</li>
<li class="current" data-tab="tab-3">Related articles</li>
<li data-tab="tab-4">Videos</li>
<li ng-repeat="t in tabs" data-tab="ctab-{{t.Id}}">{{t.Title}}</li>
<asp:Literal ID="AddNewTab" runat="server"></asp:Literal>
</ul>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49502519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL most efficient way to check if rows from one table are also present in another I have two DB tables each containing email addresses
One is mssql with 1.500.000.000 entries
One is mysql with 70.000.000 entries
I now want to check how many identical email addresses are present in both tables.
i.e. the same address is present in both tables.
Which approach would be the fastest:
1. Download both datasets as csv, load it into memory and compare in program code
2. Use the DB queries to get the overlapping resultset.
if 2 is better: What would be a suggested SQL query?
A: I would go with a DBQuery. Set up a linked server connection between the two DBs (probably on the MSSQL side), and use a simple inner join query to produce the list of e-mails that occur in both tables:
select a.emailAddress
from MSDBServ.DB.dbo.Table1 a
join MySqlServ.DB..Table2 b
on a.EmailAddress = b.EmailAddress
Finding the set difference, that's going to take more processor power (and it's going to produce at least 1.4b results in the best-case scenario of every MySql row matching an MSSQL row), but the query isn't actually that much different. You still want a join, but now you want that join to return all records from both tables whether they could be joined or not, and then you specifically want the results that aren't joined (in which case one side's field will be null):
select a.EmailAddress, b.EmailAddress
from MSDBServ.DB.dbo.Table1 a
full join MySqlServ.DB..Table2 b
on a.EmailAddress = b.EmailAddress
where a.EmailAddress IS NULL OR b.EmailAddress IS NULL
A: Table1 has the 70,000,000 email addresses, table2 has the 1,500,000,000. I use Oracle so the Upper function may or may not have an equivalent in MySQL.
Select EmailAddress from table1 where Upper(emailaddress) in (select Upper(emailaddress) from table2)
Quicker than comparing spreadsheets and this assumes both tables are in the same database.
A: You could do a sql query to check how many identical email addresses are present in two databases: first number is how many duplicates, second value is the email address.
SELECT COUNT(emailAddr),emailAddr FROM table1 A
INNER JOIN
table2 B
ON A.emailAddr = B.emailAddr
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43354185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET DataList for a single item Context: In an ASP.NET application, I need the behavior of the ItemTemplate / EditItemTemplate that the DataList control provides. However, I only need one item in my control, which makes the DataList seems like overkill.
Question: Is there a control in ASP.NET made to store a single item that has the template content behavior of the DataList and DataGrid? Should I use a DataList for only one item?
A: Why don't you use the FormView or DetailsView? They are meant to display one item (at the time).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3495590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Plotly.js draw shape to ymax In plotly.js i want do draw a rectangle, that goes from a certain y-coordinate to the top of the plot (i.e. max y that is displayed). Following figure shows what i currently have. And here the code that i am using to draw it:
{
type: 'rect',
xref: 'x',
yref: 'y',
x0: 0,
y0: 0,
x1: 5,
y1: 9000,
// ... visuals
}
Instead i want the y-coordinates of the rectangle to begin at 9000 (something like y0: 9000) and always end at the top of the plot (y1: ~12400), without having to manually declare y1. Is that possible?
Thank you very much for help!
A: y0 and y1 value 0-1 refer the yaxis amplitude.
So you can set y0 and y1 value 0-1 in your layout configuration of the shape and setting the yref as 'paper'. Further documentation can be found here.
{
type: 'rect',
xref: 'x',
yref: 'paper',
x0: 0,
y0: 0, //y0: 0~1 range
x1: 5,
y1: 1,//y1: 0~1 range
// ... visuals
}
Example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51131837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting null values while reading application.yaml file in java I am trying to fetch the data from my application.yaml file which contain profile details, into variables
application.yaml file contents
spring.profiles.active: dev
---
spring.config.activate.on-profile: dev
application.id : dev-app
my.server : localhost:8080
---
spring.config.activate.on-profile: uat
application.id : uat-app
my.server : localhost:8081
App.java
@SpringBootApplication
public class App {
@Value("${application.id}")
private String applicationId;
@Value("${my.server}")
private String server;
public static void main(String args[]) {
SpringApplication.run(App.class, args);
App app = new App();
app.display();
}
public void display(){
System.out.println("Application Id : "+ applicationId);
System.out.println("Server : "+ server);
}
}
Output:
2022-06-08 19:38:29 main INFO App:640 - The following 1 profile is active: "dev"
2022-06-08 19:38:30 main INFO App:61 - Started App in 2.266 seconds (JVM running for 3.345)
Application Id : null
Server : null
Could you please help me to understand why it is not picking the values from yaml file?
A: in your yml, what you have is formatted in a ".properties' file format, you need to format your property to yml format. So, your yml file should be in the format (something like this):
spring:
profiles:
active: dev
config:
activate:
onProfile: dev
application:
id : dev-app
etc...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72547261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to replace youtube link to using Regex in Yahoo pipe Most of Youtube video included to the website using tag,
Is there any way to convert such iframe:
<iframe height="360" frameborder="0" width="640" src="www.youtube.com/embed/Xz3zC0axQwA?feature=player_detailpage" allowfullscreen=""></iframe>
to finally look only like this:
http://www.youtube.com/embed/Xz3zC0axQwA
I would like to use Regex + Yahoo pipe
A: RegEx: (?:<iframe.+src=")([^"]+)(?:.*>)
Then you'll have a captured group $1 containing only the src url.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21118136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Image path to stored in Pinia not passing through to component I'm creating a card carousel with a Spotify style thumbnail, (image as background, text on top). Content is stored in a Pinia store which I will be hooking up to Firebase eventually. I'm trying to set the image background but am getting this error
GET http://127.0.0.1:5173/%60$%7B%7Bcontent.image%7D%7D%60 404 (Not Found)
Here is my store code (condensed to the important bits)
export const useContentStore = defineStore('contentStore', {
state: () => {
return {
guides: [{
title: 'XX',
date: 'X',
description: "X",
image: './assets/images/content/thumbnail.png',
id: '1',
}]
}
}
})
Here is where I am trying to access that image path
<template>
<div class="card">
<img class="card-image" src="{{content.image}}"/>
<h1 class="title">{{content.title}}</h1>
<h2 class="subtitle"></h2>
</div>
</template>
<script setup>
/*
store
*/
import { useContentStore } from "@/stores/contentStore";
const contentStore = useContentStore();
/*
props
*/
const props = defineProps({
content: {
type: Object,
required: true,
},
});
</script>
And here is where the cards are being called
<template>
<div class="guides-container">
<h2 class="title">Guides</h2>
<div class="guides-list">
<GeneralCard
v-for="(content, index) in contentStore.guides"
:key="content.id"
:content="content"
/>
</div>
</div>
</template>
<script setup>
/*
imports
*/
import GeneralCard from "@/components/GeneralCard.vue";
/*
data
*/
const contentStore = useContentStore();
</script>
My gut instinct is that it's an issue with transferring the string through the store to the template, but I don't have any clue how to fix it. I've tried escaping the characters, using template literals on both the stored path and the image tag, played with URL() a bit, and I'm pretty sure it's not an issue with the actual path of the image (it works when I plug the path directly into the image tag)
Thanks for any help you can give!
A: The src attribute on the img is set improperly. It should be
<img class="card-image" :src="content.image"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73515069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Micro optimize pointer + unsigned + 1 Hard as it may be to believe the construct p[u+1] occurs in several places in innermost loops of code I maintain such that getting the micro optimization of it right makes hours of difference in an operation that runs for days.
Typically *((p+u)+1) is most efficient. Sometimes *(p+(u+1)) is most efficient. Rarely *((p+1)+u) is best. (But usually an optimizer can convert *((p+1)+u) to *((p+u)+1) when the latter is better, and can't convert *(p+(u+1)) with either of the others).
p is a pointer and u is an unsigned. In the actual code at least one of them (more likely both) will already be in register(s) at the point the expression is evaluated. Those facts are critical to the point of my question.
In 32-bit (before my project dropped support for that) all three have exactly the same semantics and any half decent compiler simply picks the best of the three and the programmer never needs to care.
In these 64-bit uses, the programmer knows all three have the same semantics, but the compiler doesn't know. So far as the compiler knows, the decision of when to extend u from 32-bit to 64-bit can affect the result.
What is the cleanest way to tell the compiler that the semantics of all three are the same and the compiler should select the fastest of them?
In one Linux 64-bit compiler, I got nearly there with p[u+1L] which causes the compiler to select intelligently between the usually best *((p+u)+1) and the sometimes better *(p+( (long)(u) + 1) ). In the rare case *(p+(u+1)) was still better than the second of those, a little is lost.
Obviously, that does no good in 64-bit Windows. Now that we dropped 32-bit support, maybe p[u+1LL] is portable enough and good enough. But can I do better?
Note that using std::size_t instead of unsigned for u would eliminate this entire problem, but create a larger performance problem nearby. Casting u to std::size_t right there is almost good enough, and maybe the best I can do. But that is pretty verbose for an imperfect solution.
Simply coding (p+1)[u] makes a selection more likely to be optimal than p[u+1]. If the code were less templated and more stable, I could set them all to (p+1)[u] then profile then switch a few back to p[u+1]. But the templating tends to destroy that approach (A single source line appears in many places in the profile adding up to serious time, but not individually serious time).
Compilers that should be efficient for this are GCC, ICC and MSVC.
A: The answer is inevitably compiler and target specific, but even if 1ULL is wider than a pointer on whatever target architecture, a good compiler should optimize it away. Which 2's complement integer operations can be used without zeroing high bits in the inputs, if only the low part of the result is wanted? explains why a wider computation truncated to pointer width will give identical results as doing computation with pointer width in the first place. This is why compilers can optimize it away even on 32bit machines (or x86-64 with the x32 ABI) when 1ULL leads to promotion of the + operands to a 64bit type. (Or on some 64bit ABI for some architecture where long long is 128b).
1ULL looks optimal for 64bit, and for 32bit with clang. You don't care about 32bit anyway, but gcc wastes an instruction in the return p[u + 1ULL];. All the other cases are compiled to a single load with scaled-index+4+p addressing mode. So other than one compiler's optimization failure, 1ULL looks fine for 32bit as well. (I think it's unlikely that it's a clang bug and that optimization is illegal).
int v1ULL(std::uint32_t u) { return p[u + 1ULL]; }
// ... load u from the stack
// add eax, 1
// mov eax, DWORD PTR p[0+eax*4]
instead of
mov eax, DWORD PTR p[4+eax*4]
Interestingly, gcc 5.3 doesn't make this mistake when targeting the x32 ABI (long mode with 32bit pointers and a register-call ABI similar to SySV AMD64). It uses a 32bit address-size prefix to avoid using the upper 32b of edi.
Annoyingly, it still uses an address-size prefix when it could save a byte of machine code by using a 64bit effective address (when there's no chance of overflow/carry into the upper32 generating an address outside the low 4GiB). Passing the pointer by reference is a good example:
int x2 (char *&c) { return *c; }
// mov eax, DWORD PTR [edi] ; upper32 of rax is zero
// movsx eax, BYTE PTR [eax] ; could be byte [rax], saving one byte of machine code
Err, actually I forget. 32bit addresses might sign-extend to 64b, not zero-extend. If that's the case, it could have used movsx for the first instruction, too, but that would have cost a byte because movsx has a longer opcode than mov.
Anyway, x32 is still an interesting choice for pointer-heavy code that wants more registers and a nicer ABI, without the cache-miss hit of 8B pointers.
The 64bit asm has to zero the upper32 of the register holding the parameter (with mov edi,edi), but that goes away when inlining. Looking at godbolt output for tiny functions is a valid way to test this.
If we want to make doubly sure that the compiler isn't shooting itself in the foot and zeroing the upper32 when it should know it's already zero, we could make test functions with an arg passed by reference.
int v1ULL(const std::uint32_t &u) { return p[u + 1ULL]; }
// mov eax, DWORD PTR [rdi]
// mov eax, DWORD PTR p[4+rax*4]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34512319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Azure pipeline powershell and git on windows server 2019 gives error in output I have a problem with azure pipeline and one of my servers.
The server where it fails is a windows 2019 server.
If I in powershell call git, then it treats all warnings and following lines as errors.
If I do the same thing on two og my different servers - no issues - even though same outout.
This is the error returned:
CD to D:\web\test\testsite.com
##[error]git : Warning: Permanently added the RSA host key for IP address 'X' to the list of known hosts.
##[error]git : From bitbucket.org:SITE
##[error]At C:\azagent\A1\_work\_temp\c1ff2d2b-c773-4adc-9040-155e92a914bd.ps1:12 char:1
+ git pull origin master
+ ~~~~~~~~~~~~~~~~~~~~~~
##[error] + CategoryInfo : NotSpecified: (From bitbucket....b/fletcocarpets:String) [], RemoteException
##[error] + FullyQualifiedErrorId : NativeCommandError
##[error]
##[error]PowerShell exited with code '1'.
Git does make the pull and everything is actually OK. But for some reason - on this server - azure pipelines treats the text as errors.
Any ideas why? hard to explain the problem aswell properly on text.
This is how its returned on the server where it works, as an example:
CD to D:\web\testsite.com
Warning: Permanently added the RSA host key for IP address 'X' to the list of known hosts.
From bitbucket.org:SITE
* branch master -> FETCH_HEAD
...
1 file changed, 27 insertions(+), 23 deletions(-)
##[section]Finishing: PowerShell Script - GIT
A: I found out what helped me. Thought I had tried it - but seems not:
Added this to the top. for some reason this server and git needs this:
$env:GIT_REDIRECT_STDERR = '2>&1'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58485585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Brought a Linux C++ Console Application to a Win32 C++ App using VS2010 and the search function from is no longer working Just like the title says, I've been working on a fairly large program and have come upon this bug. I'm also open to alternatives for searching a file for a string instead of using . Here is my code narrowed down:
istreambuf_iterator<char> eof;
ifstream fin;
fin.clear();
fin.open(filename.c_str());
if(fin.good()){
//I outputted text to a file to make sure opening the file worked, which it does
}
//term was not found.
if(eof == search(istreambuf_iterator<char>(fin), eof, term.begin(), term.end()){
//PROBLEM: this code always executes even when the string term is in the file.
}
So just to clarify, my program worked correctly in Linux but now that I have it in a win32 app project in vs2010, the application builds just fine but the search function isn't working like it normally did. (What I mean by normal is that the code in the if statement didn't execute because, where as now it always executes.)
NOTE: The file is a .xml file and the string term is simply "administration."
One thing that might or might not be important is to know that filename (filename from the code above) is a XML file I have created in the program myself using the code below. Pretty much I create an identical xml file form the pre-existing one except for it is all lower case and in a new location.
void toLowerFile(string filename, string newloc, string& newfilename){
//variables
ifstream fin;
ofstream fout;
string temp = "/";
newfilename = newloc + temp + newfilename;
//open file to read
fin.open(filename.c_str());
//open file to write
fout.open(newfilename.c_str());
//loop through and read line, lower case, and write
while (fin.good()){
getline (fin,temp);
//write lower case version
toLowerString(temp);
fout << temp << endl;
}
//close files
fout.close();
fin.close();
}
void toLowerString(string& data){
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}
A: I'm afraid your code is invalid - the search algorithm requires forward iterators, but istreambuf_iterator is only an input iterator.
Conceptually that makes sense - the algorithm needs to backtrack on a partial match, but the stream may not support backtracking.
The actual behaviour is undefined - so the implementation is allowed to be helpful and make it seem to work, but doesn't have to.
I think you either need to copy the input, or use a smarter search algorithm (single-pass is possible) or a smarter iterator.
(In an ideal world at least one of the compilers would have warned you about this.)
A: Generally, with Microsoft's compiler, if your program compiles and links a main() function rather than a wmain() function, everything defaults to char. It would be wchar_t or WCHAR if you have a wmain(). If you have tmain() instead, then you are at the mercy of your compiler/make settings and it's the UNICODE macro that determines which flavor your program uses. But I doubt that char_t/wchar_t mismatch is actually the issue here because I think you would have got an warning or error if all four of the search parameters didn't use the same the same character width.
This is a bit of a guess, but try this:
if(eof == search(istreambuf_iterator<char>(fin.rdbuf()), eof, term.begin(), term.end())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20864512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get a User's Group from Azure Active Directory after Authentication After registering an app in my azure active directory, i can get the user in a callback :
object(Magium\ActiveDirectory\Entity)#262 (1) {
["data":protected]=>
array(16) {
["aud"]=> string(36) "xxxxxxxxxxxxxxxxxxxx"
["iss"]=> string(75) "https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxx/v2.0"
["iat"]=> int(xxxxxxxxxxxxxxxxxxxx)
["nbf"]=> int(xxxxxxxxxxxxxxxxxxxx)
["exp"]=> int(xxxxxxxxxxxxxxxxxxxx)
["aio"]=> string(140) "xxxxxxxxxxxxxxxxxxxx"
["email"]=> string(20) "[email protected]"
["idp"]=> string(61) "https://sts.windows.net/xxxxxxxxxxxxxxxxxxxx/"
["name"]=> string(13) "xxxxxxxxxxxxxxxxxxxx"
["oid"]=> string(36) "xxxxxxxxxxxxxxxxxxxx"
["preferred_username"]=> string(20) "[email protected]"
["sub"]=> string(43) "xxxxxxxxxxxxxxxxxxxx"
["tid"]=> string(36) "xxxxxxxxxxxxxxxxxxxx"
["uti"]=> string(22) "xxxxxxxxxxxxxxxxxxxx"
["ver"]=> string(3) "2.0"
["access_token"]=> string(1910) "xxxxxxxxxxxxxxxxxxxx"
}
}
but how do i access the group he belongs to which i have declared in my azure active directory?
ps: the code to get the user is this:
@php
session_start();
$config = [
'authentication' => [
'ad' => [
'client_id' => 'xxxxxxx',
'client_secret' => 'xxxxxxx',
'enabled' => 'yes',
'directory' => "xxxxxxx",
'return_url' => 'xxxxxxx'
]
]
];
$request = new \Zend\Http\PhpEnvironment\Request();
$ad = new \Magium\ActiveDirectory\ActiveDirectory(
new \Magium\Configuration\Config\Repository\ArrayConfigurationRepository($config),
Zend\Psr7Bridge\Psr7ServerRequest::fromZend(new \Zend\Http\PhpEnvironment\Request())
);
$entity = $ad->authenticate();
echo $entity->getName() . '<Br />';
echo $entity->getPreferredUsername() . '<Br />';
@endphp
I clicked on Azure Active Directory-> Groups -> Create a group -> add users -> done.
Thats how i created the group.
But in my callback for the user i cant get it to work.
I am completely clueless please help.
Thanks a ton guys!
A: You are looking for a memberOf attribute which it seems is not present. If you are using openLDAP, memberof attribute is hidden by default. Check that setting once. Also make sure that anonymous access is allowed for this attribute.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58959861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to add a sliding div to these CSS Message Bubbles? new to webdev so bear with me. I am developing a prototype of a Messaging Application, I have most of the basics worked out and I'm trying to add the little touches to make it feel nicer to use. I'm trying to make it so that when an individual message is hovered over, the time that message was sent will slide out from the message.
Here is my code at the moment: http://codepen.io/RBrNx/pen/GNzOWr
(Note: Click on "Toni" again and his message will appear, small bug. You can also send messages from the text box).
Now here are some images showing what I mean:
http://imgur.com/a/elB04
Ideally I think the 2nd one would look better.
I tried to implement it by adding a span inside the bubble like so:
<div class="bubble you">Test Message<span class="hover-time">13.45</span></div>
.hover-time{
position: relative;
left: 60px;
}
But that made the inside of the bubble stretch to account for the Span.
How can this be done?
EDIT: Thanks to Antidecaf I managed to get the left side working and figured out the right hand side as well. Here is the CSS I added:
.container .right .bubble.you .hover-time {
display: none;
position: absolute;
left: 110%;
color: #999;
width: 100px;
}
.container .right .bubble.me .hover-time {
display: none;
position: absolute;
right: 90%;
color: #999;
width: 100px;
}
These deal with the left hand messages (from the person you are messaging) and the right hand messages (from me). I also added:
.container .right .bubble.you:hover .hover-time{
display: inline-block;
}
.container .right .bubble.me:hover .hover-time{
display: inline-block;
}
So that the hover-time span is shown on hover.
A: You can do this with the markup you suggested by positioning .hover-time relative to .bubble. To do this, add position: relative to .bubble and position: absolute to .hover-time. Here's some more info on the technique.
<div class="bubble you"><span class="hover-time">13.45</span>Test Message</div>
CSS for positioning timestamp to the right:
.bubble {
position: relative;
}
.hover-time {
position: absolute;
left: 110%;
color: #999;
}
Same approach goes for positioning it to the left, but in this case you'll need to add a bit of margin to the bubble in order to free up space for the timestamp:
.bubble {
position: relative;
margin-left: 50px;
}
.hover-time {
position: absolute;
left: -50px;
color: #999;
}
A: <style>
.hover-time {
position: relative;
left: 60px;
display: none;
}
.bubble:hover .hover-time {
background-color: #ccc;
color: #000;
display: inline-block;
}
</style>
<div class="bubble you">Test Message <span class="hover-time">13.45</span></div>
Works for me. You'll probably want to spice it up a little with some transform or other fancy anim stuff.
EDIT: Perhaps you meant like so:
<style>
.bubble {
border: 1px solid #ccc;
width: 300px;
}
.hover-time {
float: right;
display: none;
}
.bubble:hover .hover-time {
background-color: #ccc;
color: #000;
display: inline-block;
}
</style>
<div class="bubble you">Test Message <span class="hover-time">13.45</span></div>
Border and width just to have a visual guide.
A: Maybe I'm misunderstanding, but are you styling the DIV as the speech bubble, then taking the span inside the div and telling it 'but not you buddy, you are special'?
If so, isn't it cleaner and less headaches to put your text message in a span also, styling the span as text bubble, and keeping the div as an invisible structural element?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41222185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React Native overlapping touchables trigger at the same time I've got two Touchables that overlap. Clicking the overlapping area makes them both fire. I want only the child onPress event to trigger (i.e. only the onUpVote/onDownVote function).
<TouchableHighlight onPress={onPress} underlayColor={colors.focus}>
<View style={styles.container}>
<AppText>{question.content}</AppText>
<View style={styles.voteContainer}>
<UpVoteButton
voted={voted}
voteCount={question.upVotes}
onPress={onUpVote}
/>
<DownVoteButton
voted={false}
voteCount={question.downVotes}
onPress={onDownVote}
/>
</View>
</View>
</TouchableHighlight>
and that's the VoteButton element
<TouchableWithoutFeedback onPress={onPress}>
<View style={styles.voteContainer}>
<AppText style={styles.voteCount}>{voteCount}</AppText>
<AntDesign
name={voted ? "like1" : "like2"}
style={{
fontSize: 18,
color: defaultStyles.colors.focus,
paddingBottom: 3,
}}
/>
</View>
</TouchableWithoutFeedback>
The idea is that if the user presses the thumbs up/down icon area then the onDownVote gets handled. Pressing anywhere else within the list item is supposed to take you to a different screen.
App layout
A: I'd suggest to import TouchableOpacity from here:
https://github.com/software-mansion/react-native-gesture-handler
Both overlapping touchables should fire onPress prop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63741492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DeepStack - Prepare dataset / custom models with Python and LabelIMG I'm looking to buy Blue Iris as it incorporates DeepStack AI and the capability to train custom models.
I started to follow the DeepStack win / PC "Prepare dataset / custom models" guide, see below
https://docs.deepstack.cc/custom-models/datasetprep/index.html#step-1-install-labelimg
*
*Install Python 3.10.7 (ok)
*Type pip3 install pyqt5 lxml in Python - however this syntax does not work?
I hope someone can provide guidance to resolve this issue or recommend an alternative option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74029624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to inject an instance of configuration when creating instance of the injected class? I have a simple situation:
class MyClass @Inject() (configuration: Configuration) {
val port = configuration.get[String]("port")
...
}
and now I want to use MyClass in some other object:
object Toyota extends Car {
val myClass = new MyClass(???)
...
}
but I dont know how when I use MyClass i give it the configuration instance i annotated that will be injected when MyClass is going to be instantiated..
im using play2.6/juice/scala
thanks!
A: First of all, you should decide if dependency injection is really what you need. Basic idea of DI: instead of factories or objects themselves creating new objects, you externally pass the dependencies, and pass the instantiation problem to someone else.
You suppose to go all in with it if you rely on framework, that is why no way of using new along with DI. You cannot pass/inject a class into the scala object, here is a draft of what you can do:
Play/guice require some preparation.
Injection Module to tell guice how to create objects (if you cannot do this if annotations, or want to do it in one place).
class InjectionModule extends AbstractModule {
override def configure() = {
// ...
bind(classOf[MyClass])
bind(classOf[GlobalContext]).asEagerSingleton()
}
}
Inject the injector to be able to access it.
class GlobalContext @Inject()(playInjector: Injector) {
GlobalContext.injectorRef = playInjector
}
object GlobalContext {
private var injectorRef: Injector = _
def injector: Injector = injectorRef
}
Specify which modules to enable, because there can be more than one.
// application.conf
play.modules.enabled += "modules.InjectionModule"
And finally the client code.
object Toyota extends Car {
import GlobalContext.injector
// at this point Guice figures out how to instantiate MyClass, create and inject all the required dependencies
val myClass = injector.instanceOf[MyClass]
...
}
A simple situation expanded with a frameworks help. So, you should really consider other possibilities. Maybe it would be better to pass the configs as an implicit parameter in your case?
For dependency injection with guice take a look at:
ScalaDependencyInjection with play and Guice wiki
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44814304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: the onset time column of the edge.spells argument to networkDynamic must be numeric I am trying to create a networkDynamic object and have tried following all of skyebend's suggestions in oymonk's post how upload a dataframe to ndtv in R in setting up the columns in the right order and the data types for each column here correctly. Unfortunately, my example below continues to return that my onset column is not numeric when str() clearly shows it is. I would appreciate any suggestions for what I am missing.
library("dplyr")
library("ndtv")
time =
structure(list(onset = c(1571011200, 1571616000, 1571011200,
1570406400, 1571616000, 1570406400, 1570406400, 1571011200, 1571011200,
1571616000, 1572220800, 1570406400, 1570406400, 1571616000, 1571011200,
1571011200, 1570406400, 1571616000, 1571011200, 1570406400, 1571616000,
1570406400, 1571011200, 1570406400, 1570406400, 1570406400, 1571011200,
1570406400, 1571616000, 1571616000, 1570406400, 1571011200, 1571011200,
1570406400, 1570406400, 1571011200, 1572220800, 1571616000, 1571616000,
1571011200, 1572220800, 1571616000, 1570406400, 1570406400, 1571011200,
1571011200, 1571616000, 1571011200, 1571616000, 1571616000),
terminus = c(1571356800, 1571961600, 1571356800, 1570752000,
1571961600, 1570752000, 1570752000, 1571356800, 1571356800,
1571961600, 1572566400, 1570752000, 1570752000, 1571961600,
1571356800, 1571356800, 1570752000, 1571961600, 1571356800,
1570752000, 1571961600, 1570752000, 1571356800, 1570752000,
1570752000, 1570752000, 1571356800, 1570752000, 1571961600,
1571961600, 1570752000, 1571356800, 1571356800, 1570752000,
1570752000, 1571356800, 1572566400, 1571961600, 1571961600,
1571356800, 1572566400, 1571961600, 1570752000, 1570752000,
1571356800, 1571356800, 1571961600, 1571356800, 1571961600,
1571961600), tail = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 11L, 12L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 25L, 12L, 5L, 26L, 27L, 28L, 29L, 30L,
31L, 32L, 33L, 34L, 35L, 25L, 36L, 37L, 38L, 39L, 39L, 40L,
41L, 42L, 43L, 44L, 45L), head = c(307L, 308L, 309L, 310L,
307L, 311L, 312L, 308L, 313L, 313L, 308L, 309L, 308L, 308L,
308L, 308L, 314L, 307L, 315L, 308L, 307L, 308L, 314L, 313L,
309L, 313L, 308L, 315L, 313L, 312L, 310L, 309L, 307L, 309L,
308L, 308L, 313L, 308L, 316L, 312L, 312L, 307L, 315L, 309L,
317L, 317L, 307L, 312L, 309L, 314L)), row.names = c(NA, -50L
), class = c("tbl_df", "tbl", "data.frame"))
time_dyn = time %>% networkDynamic(edge.spell = .)
time %>% str()
I really don't understand what I am missing here. Any help would be appreciated and please let me know if any other info is required to reproduce this example.
A: I don't understand the formatting behind this but it seems that converting my edgelist from a tbldf to a regular dataframe did the trick.
I did this simply by executing the following before converting to networkDynamic
time = time %>% data.frame()
time = time %>% networkDynamic(edge.spells = time)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62175573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python drop rows containing ending characters from any column Is there a way other than specifying each column, i.e. df.drop(df[Col1]...,
where rows can be deleted based on a condition?
For example, can I iterate through Col1, Col2, ...through Col15 and delete all rows ending with the letter "A"?
I was able to delete columns using
df.loc[:,~ df.columns.str.startswith('A')]
A: IIUC, you have a pandas DataFrame and want to drop all rows that contain at least one string that ends with the letter 'A'. One fast way to accomplish this is by creating a mask via numpy:
import pandas as pd
import numpy as np
Suppose our df looks like this:
0 1 2 3 4 5
0 ADFC FDGA HECH AFAB BHDH 0
1 AHBD BABG CBCA AHDF BCAG 1
2 HEFH GEHH CBEF DGEC DGFE 2
3 HEDE BBHE CCCB DDGB DCAG 3
4 BGEC HACB ACHH GEBC GEEG 4
5 HFCC CHCD FCBC DEDF AECB 5
6 DEFE AHCH CHFB BBAA BAGC 6
7 HFEC DACC FEDA CBAG GEDD 7
Goal: we want to get rid of rows with index 0, 1, 6, 7.
Try:
mask = np.char.endswith(df.to_numpy(dtype=str),'A') # create ndarray with booleans
indices_true = df[mask].index.unique() # Int64Index([0, 1, 6, 7], dtype='int64')
df.drop(indices_true, inplace=True) # drop indices_true
print(df)
out:
0 1 2 3 4 5
2 HEFH GEHH CBEF DGEC DGFE 2
3 HEDE BBHE CCCB DDGB DCAG 3
4 BGEC HACB ACHH GEBC GEEG 4
5 HFCC CHCD FCBC DEDF AECB 5
A: A bit unclear on your requirements but maybe this fits. Generate some words in columns for which end in 'A'. If any string in the designated columns ends with 'A' then delete the row.
nb_cols = 9
nb_vals = 6
def wgen():
return ''.join(random.choices(string.ascii_lowercase, k=5)) + random.choice('ABCDEFGH')
df = pd.DataFrame({'Col'+str(c): [wgen() for c in range(1,nb_vals)] for c in range(1,nb_cols+1)})
print(df)
Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9
0 aawivA qorjeA qfjuoD nkwgzF auablC aehnqE cwuvzF diqwaF qlnpzG
1 aidjuH ljalaB ldhgsC zaangH mdtgkF lypfnB kynrxG qlnygH zzqyrC
2 pzqibD jdumcF ddufmG xstdcH vqpbkG rjnqxD ugscrA kmvyaE cykutE
3 gqpycH ynaeeA onirjE mnbtyH swjuzF dyvmvC tpxgsH ssnhbD spsojD
4 isptdF qzpitH akzwgE klgqpH pqpcqH psryiD tjaurC daaieC piduzE
Say that we are looking for the "ending A" in Col4-Col7. Then row with index 2 needs to be deleted:
df[~df[['Col'+str(c) for c in range(4,7+1)]]
.apply(lambda x: x.str.match('.*A$').any(), axis=1)]
Col1 Col2 Col3 Col4 Col5 Col6 Col7 Col8 Col9
0 aawivA qorjeA qfjuoD nkwgzF auablC aehnqE cwuvzF diqwaF qlnpzG
1 aidjuH ljalaB ldhgsC zaangH mdtgkF lypfnB kynrxG qlnygH zzqyrC
3 gqpycH ynaeeA onirjE mnbtyH swjuzF dyvmvC tpxgsH ssnhbD spsojD
4 isptdF qzpitH akzwgE klgqpH pqpcqH psryiD tjaurC daaieC piduzE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72522060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Enable the order meta box How do I enable the order meta box? I want it to set the order.
<?php $loop = new WP_Query( array( 'post_type' => 'bocker', 'posts_per_page' => 10, 'product_category' => 'spanskt', 'orderby' => 'meta_value', 'order' => 'ASC', ) ); ?>
A: This link should have the information you need: http://codex.wordpress.org/Function_Reference/add_meta_box
There's also a tutorial on this subject here:
http://wptheming.com/2010/08/custom-metabox-for-post-type/
A: This post solved my problem: order posts by custom field
I made a custom field instead (which suited this even better than a metabox) named "pub_year":
<?php $loop = new WP_Query( array( 'post_type' => 'bocker', 'posts_per_page' => 10, 'product_category' => 'ex-jugoslaviskt', 'meta_key' => 'pub_year', 'orderby' => 'meta_value', 'order' => 'DESC' ) ); ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11910867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to convert yyyymmdd to dd-mm-yyyy in Oracle? I have a column which contains dates in varchar2 with varying formats such as 19.02.2013, 29-03-2013, 30/12/2013 and so on. But the most annoying of all is 20130713 (which is July 13, 2013) and I want to convert this to dd-mm-yyyy or dd-mon-yyyy.
A: The comments about datatypes while true, don't do much to help you with your current problem. A combination of to_date and to_char might work.
update yourtable
set yourfield = to_char(to_date(yourfield, 'yyyymmdd'), 'dd-mm-yyyy')
where length(yourfield) = 8
and yourfield not like '%-%'
and yourfield not like '%.%'
A: If the column contains all those various formats, you'll need to deal with each one. Assuming that your question includes all known formats, then you have a couple of options.
You can use to_char/to_date. This is dangerous because you'll get a SQL error if the source data is not a valid date (of course, getting an error might be preferable to presenting bad data).
Or you can simply rearrange the characters in the string based on the format. This is a little simpler to implement, and doesn't care what the delimiters are.
Method 1:
case when substr(tempdt,3,1)='.'
then to_char(to_date(tempdt,'dd.mm.yyyy'),'dd-mm-yyyy')
when substr(tempdt,3,1)='-'
then tempdt
when length(tempdt)=8
then to_char(to_date(tempdt,'yyyymmdd'),'dd-mm-yyyy')
when substr(tempdt,3,1)='/'
then to_char(to_date(tempdt,'dd/mm/yyyy'),'dd-mm-yyyy')
Method 2:
case when length(tempdt)=8
then substr(tempdt,7,2) || '-' || substr(tempdt,5,2) || '-' || substr(tempdt,1,4)
when length(tempdt)=10
then substr(tempdt,1,2) || '-' || substr(tempdt,4,2) || '-' || substr(tempdt,7,4)
end
SQLFiddle here
A: Convert to date, then format to char:
select to_char(to_date('20130713', 'yyyymmdd'), 'dd MON yyyy') from dual;
gives 13 JUL 2013.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17970892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jstatd, command not found CentOS 7 I am trying to monitor VisualGC from my workstation.
Command: java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
So i created a policy file and tried starting jstatd like below.
file name: jstatd.all.policy
grant codebase "file:${java.home}/../lib/tools.jar" {
permission java.security.AllPermission;
};
Command tried: jstatd -J-Djava.security.policy=jstatd.all.policy
error:
-bash: jstatd: command not found
command: rpm -qa | grep java
Output:
tzdata-java-2017c-1.el7.noarch
javapackages-tools-3.4.1-11.el7.noarch
java-1.8.0-openjdk-headless-1.8.0.151-5.b12.el7_4.x86_64
java-1.8.0-openjdk-1.8.0.151-5.b12.el7_4.x86_64
python-javapackages-3.4.1-11.el7.noarch
Also, on visualvm, Tab: Visual GC, I am seeing "Not supported for this JVM"
A: Note that jstatd in CentOS 7 is now part of the package java-1.8.0-openjdk-devel.
To install it:
yum install java-1.8.0-openjdk-devel
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48235839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to pick files from my device? I am doing career form, in this form have resume upload concept. I searched how to browse file form ios device but i am not getting any solution so please some one can help to solve this problem. I am new in ios.
A: You cannot browse any files on iOS device.
You have to update your app to say what type of files it can edit/read.
Then another app would have to share that file. When that source app shares a file type tht your app accept, it would listed as a destination the user can select.
A: Asper my knowledge because of the security reasons we can't access all files. You can access albums,images,contacts ... but not documents. I think try to load the png files of the resume in Photos and try to access it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28169477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Git rebase commits not repeatable When I have 2 branches pointing at the same commit, and then rebase them both onto the same new base commit, why do the rebased branches diverge?
I expected that they'd replay in the same way, and end up pointing at the same new commit.
touch a; touch b; touch c
git add a
git commit -m 'a'
git add b
git commit -m 'b'
git checkout -b branch-01 HEAD^
git add c
git commit -m 'c'
git checkout -b branch-02
git rebase master branch-01
git rebase master branch-02
git log --all --graph --decorate --pretty=oneline --abbrev-commit
A: To explain what happened, try this as an experiment:
$ git checkout -b exp1 master
<modify some file; git add; all the usual stuff here>
$ git commit -m commit-on-exp1
At this point you have an experimental branch named exp1 with one commit that's not on master:
...--A--B <-- master
\
C1 <-- exp1
Now we'll make an exp2 branch pointing to commit B, and copy commit C1 to a new commit C2 on branch exp2:
$ git checkout -b exp2 master
$ git cherry-pick exp1
The result is:
C2 <-- exp2
/
...--A--B <-- master
\
C1 <-- exp1
Now let's repeat with exp3, creating it so that it points to commit B and then copying exp1 again:
$ git checkout -b exp3 master
$ git cherry-pick exp1
Do you expect exp3 to point to commit C2? If so, why? Why did exp2 point to C2 rather than to C1 like exp1?
The issue here is that commits C1 and C2 (and now C3 on exp3) are not bit-for-bit identical. It's true they have the same snapshot, the same author, the same log message, and even the same parent (all three have B as their one parent). But all three have different committer date-and-time-stamps, so they are different commits. (Use git show --pretty=fuller to show both date-and-time-stamps. Cherry-pick, and hence rebase too, copies the original author information including date-and-time, but because it's a new commit, uses the current date-and-time for the committer timestamp.)
When you use git rebase, in general, you have Git copy commits, as if by cherry-pick. At the end of the copying, Git then moves the branch name so that it points to the last copied commit:
...--A--B <-- mainline
\
C--D--E <-- sidebranch
becomes:
C'-D'-E' <-- sidebranch
/
...--A--B <-- mainline
\
C--D--E
Here C' is the copy of C that's changed to use B as its parent (and perhaps has a different source snapshot than C), D' is the copy of D, and E' is the copy of E. There was only one name pointing to E; that name is now moved, so there is no name pointing to E.
But if you have two names pointing to E originally, one of those two names still points to E:
C'-D'-E' <-- sidebranch
/
...--A--B <-- mainline
\
C--D--E <-- other-side-branch
If you ask Git to copy C-D-E again, it does that—but the new copies are not C'-D'-E' because they have new date-and-time stamps. So you end up with what you saw.
Hence, if you want to move two or more names while copying some chain of commits, you'll be OK using git rebase to move the first name, but you will have to do something else—such as run git branch -f—to move the remaining names, so that they point to the commit copies made during the one rebase.
(I've always wanted to have a fancier version of git rebase that can do this automatically, but it's clearly a hard problem in general.)
A: Why the Branches Diverged
Among the metadata used to calculate the hash for a git commit, not only is there an Author and an AuthorDate; there is also a Committer and a CommitterDate. This can be seen by running e.g.
git show --pretty=fuller branch-01 branch-02
Each rebase (or cherry-pick) command updates the committer date in the new commit(s) according to the current time. Since the two rebases in the question were performed at different times, their CommitterDates differ, thus their metadata differ, thus their commit hashes differ.
How To Move Branches/Tags Together
torek correctly notes that
if you want to move two or more names while copying some chain of commits, you'll be OK using git rebase to move the first name, but you will have to do something else—such as run git branch -f—to move the remaining names, so that they point to the commit copies made during the one rebase.
About Author vs Committer
From Difference between author and committer in Git?:
The author is the person who originally wrote the code. The committer, on the other hand, is assumed to be the person who committed the code on behalf of the original author. This is important in Git because Git allows you to rewrite history, or apply patches on behalf of another person. The FREE online Pro Git book explains it like this:
You may be wondering what the difference is between author and committer. The author is the person who originally wrote the patch, whereas the committer is the person who last applied the patch. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56877839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need to write a script that runs two scripts, but needs to stop the first one before the 2nd runs This is a CentOS 6.x box, on it I have two things that I need to run one right after the other - a shell script and a .sql script.
I want to write a shell script that calls the first script, lets it run and then terminates it after a certain number of hours, and then calls the .sql script (they can't run simultaneously).
I'm unsure how to do the middle part, that is terminating the first script after a certain time limit, any suggestions?
A: script.sh &
sleep 4h && kill $!
script.sql
This will wait 4 hours then kill the first script and run the second. It always waits 4 hours, even if the script exits early.
If you want to move on immediately, that's a little trickier.
script.sh &
pid=$!
sleep 4h && kill "$pid" 2> /dev/null &
wait "$pid"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35900202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: EasySMPP library for C# does not work without Console.Readline() call I have strange problem with EasySMPP open source library for C#, while trying to send sms using SmppClient:
This always fails (Console writline shows "Error"):
SmsClient client = new SmsClient();
client.Connect();
if (client.SendSms("MyNumber", "XXXXXXXXX", "Hi"))
Console.WriteLine("Message sent");
else
Console.WriteLine("Error");
client.Disconnect();
Console.ReadLine();
But when i just add this stupid Console.Readline call its works fine:
SmsClient client = new SmsClient();
**string stupidstring = Console.Readline();** //Thats it
client.Connect();
if (client.SendSms("MyNumber", "XXXXXXXXX", "Hi"))
Console.WriteLine("Message sent");
else
Console.WriteLine("Error");
client.Disconnect();
Console.ReadLine();
If i don't add Console.Readline() call it's not working. Could you please help me with this. Thank you.
A: Although this is a very old question. I was also looking but couldnt find the answer until i found out what the problem is.
EasySMPP library is using asynchronous calls to connect to the SMSC which is why when you run the readline() command line you are requested to put your text as readline and while there is a delay in your typing the SMSC has already binded by then. So it works with the stupid Console.Readline()
When you run without the readline() the code executes super fast and by that time the your application has not binded to the SMSC and it fails.
SmsClient client = new SmsClient();
client.Connect();
System.Threading.Thread.Sleep(5000);
if (client.SendSms("MyNumber", "XXXXXXXXX", "Hi"))
Console.WriteLine("Message sent");
else
Console.WriteLine("Error");
client.Disconnect();
Console.ReadLine();
A: Try surrounding it by Try and catch , make the if in try and return error at catch exception.Message .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20063299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to submit image and text field in single API endpoint using drf and angular Good day guy i'm working on an drf api endpoint that requires user uploading image and text to the same endpoint, i've done all that is required but i still keep getting error, below is snippet of my code and error msg
APIVIEW
class CreateProfileView(APIView):
parser_classes = (MultiPartParser,)
serializer_class = schoolProfileSerializer
queryset = schoolProfile.objects.all()
permission_classes = [permissions.AllowAny]
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def post(self, request):
file_upload = schoolProfileSerializer(data =request.data, instance=request.user)
if file_upload.is_valid():
file_upload.save()
return Response(file_upload.data, status=status.HTTP_201_CREATED)
else:
return Response(file_upload.errors, status=status.HTTP_400_BAD_REQUEST )
SERIALIZER
class Base64Imagefield(serializers.ImageField):
def to_internal_value(self, data):
if isinstance(self, six.string_types):
if 'data: ' in data and ';base64, ' in data:
header, data = data.split(';base64,')
try:
decode_file = base64.b64decode(data)
except TypeError:
self.fail('invalide image')
file_name = str(uuid.uuid4())[:16]
file_extension = self.get_file_extension(file_name, decode_file)
complete_file_name = "%s.%s" %(file_name, file_extension)
data = ContentFile(decode_file, name=complete_file_name)
return super(Base64Imagefield, self).to_internal_value(data)
def get_file_extension(self, file_name, decode_file):
extension = imghdr.what(file_name, decode_file)
extension = 'jpg' if extension == 'jpeg' else extension
return extension
class schoolProfileSerializer(serializers.ModelSerializer):
parser_classes = (MultiPartParser, FormParser, )
id = serializers.IntegerField(source='pk', read_only=True)
email = serializers.CharField(source='user.email', read_only=True)
username = serializers.CharField(source='user.username', read_only=True)
badge = Base64Imagefield(max_length=None, use_url=True)
class Meta:
model = schoolProfile
fields = ( 'email', 'id', 'username', 'school_name',
'address', 'badge', 'gender', 'level',
)
def create(self, validated_data, instance=None):
if 'user' in validated_data:
user = validated_data.pop('user')
else:
user = CustomUser.objects.create(**validated_data)
profile, created_profile = schoolProfile.objects.update_or_create(user=user,
**validated_data)
return profile
Angular service
postSchoolProfile(profile: schoolProfile):Observable<schoolProfile>{
const url= `${environment.mainUrl}/school-profile/create`
return this.httpClient.post<schoolProfile>(url, {profile})
}
Error msg
detail "Unsupported media type \"application/json\" in request.
can anyone help out pls ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65377527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does C# is keyword return true for double, but false for float even though casting to float works? Motivation: I have a method that returns a dynamic datatype. The value is coming from a database and I know that the value will either be a float, double, or string. I don't want to use the value if it is a string, so I wrote the following code:
if (value is float)
{
myVariable = (float)value;
}
My expectation was that this code would execute whether the actual type of value was double or float because of the following snippet from the documentation of the 'is' keyword:
An is expression evaluates to true if the provided expression is non-null,and the provided object can be cast to the provided type without causing an exception to be thrown.
Found here: is (C# Reference)
However, when the type is double, (value is float) returns false and the assignment does not execute. But, I changed my code to this:
if (value is double)
{
myVariable = (float)value;
}
and it works fine when the type of value is double - even though according to the documentation I shouldn't be able to cast to a float because (value is float) returns false.
My Question: Why does (value is float) return false in the case where value is a double (which can be cast to a float without exception)?
EDIT - Short program demonstrating
class Program
{
static void Main(string[] args)
{
dynamic d = 1.0;
Console.WriteLine(d is double);
Console.WriteLine(d is float);
float f = (float)d;
Console.WriteLine(f);
Console.ReadKey();
}
}
A: Right, this is because the type is dynamic. That basically means the meaning of the float cast depends on the execution-time type of the value.
The is operator is checking whether float and double are the same type - and they're not, which is why it's returning false.
However, there is an explicit conversion from double to float, which is why the cast is working. I wouldn't use that MSDN C# reference to work out the finer details of how the language behaves - the language specification is normally a better bet.
A: Not sure, but I guess it is because there is no implicit conversion. See Implicit Numeric Conversions Table (C# Reference)
A: You explicitly casting double value to float variable. It is perfectly fine.
When you checking the type, it is exact type match.
What you need is:
if (value is double || value is float)
{
myVariable = (float)value;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31631120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Looking for testing matrices/systems for iterative linear solver I am currently working on a C++-based library for large, sparse linear algebra problems (yes, I know many such libraries exist, but I'm rolling my own mostly to learn about iterative solvers, sparse storage containers, etc..).
I am to the point where I am using my solvers within other programming projects of mine, and would like to test the solvers against problems that are not my own. Primarily, I am looking to test against symmetric sparse systems that are positive definite. I have found several sources for such system matrices such as:
Matrix Market
UF Sparse Matrix Collection
That being said, I have not yet found any sources of good test matrices that include the entire system- system matrix and RHS. This would be great to have in order to check results. Any tips on where I can find such full systems, or alternatively, what I might do to generate a "good" RHS for the system matrices I can get online? I am currently just filling a matrix with random values, or all ones, but suspect that this is not necessarily the best way.
A: I would suggest using a right-hand-side vector obtained from a predefined 'goal' solution x:
b = A*x
Then you have a goal solution, x, and a resulting solution, x, from the solver.
This means you can compare the error (difference of the goal and resulting solutions) as well as the residuals (A*x - b).
Note that for careful evaluation of an iterative solver you'll also need to consider what to use for the initial x.
The online collections of matrices primarily contain the left-hand-side matrix, but some do include right-hand-sides and also some have solution vectors too.:
http://www.cise.ufl.edu/research/sparse/matrices/rhs.txt
By the way, for the UF sparse matrix collection I'd suggest this link instead:
http://www.cise.ufl.edu/research/sparse/matrices/
A: I haven't used it yet, I'm about to, but GiNAC seems like the best thing I've found for C++. It is the library used behind Maple for CAS, I don't know the performance it has for .
http://www.ginac.de/
A: it would do well to specify which kind of problems are you solving...
different problems will require different RHS to be of any use to check validity..... what i'll suggest is get some example code from some projects like DUNE Numerics (i'm working on this right now), FENICS, deal.ii which are already using the solvers to solve matrices... generally they'll have some functionality to output your matrix in some kind of file (DUNE Numerics has functionality to output matrices and RHS in a matlab-compliant files).
This you can then feed to your solvers..
and then again use their the libraries functionality to create output data
(like DUNE Numerics uses a VTK format)... That was, you'll get to analyse data using powerful tools.....
you may have to learn a little bit about compiling and using those libraries...
but it is not much... and i believe the functionality you'll get would be worth the time invested......
i guess even a single well-defined and reasonably complex problem should be good enough for testing your libraries.... well actually two
one for Ax=B problems and another for Ax=cBx (eigenvalue problems) ....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4328251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to jump a commit in the same branch at git Suppose I'm in the branch develop.
I'm in commit (A) and I do some bad things and make another commit (B).
Supposing that undoing the bad things I did is a very painful job, how can I manage to put another commit ahead of (B) in the same branch develop?
CURRENT STATE:
_______________________________________
|develop| (A) ----> (B)
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
WHAT I IMAGINE:
_______________________________________
|develop| (A) ----> (B) (D)
‾‾‾‾‾‾‾‾‾‾‾‾|‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
| |
_______________________________|______
|bugfix | (C) -----------------'
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
I have no intention of merging, since I don't want to utilize (B). I also cannot erase (B), so doing force push isn't an option.
What should I do in this situation?
If there is a way to put a new commit (ahead of (B)) whose state is equal to (A), this would be also an acceptable solution.
A: You can 'revert' B. This effectively creates a new commit which 'undoes' the changes made by B. This works with one bad commit or a whole series of bad commits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63626345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Chrome mobile browser cross domain request Issue I am using pure JavaScript to make cross domain post request. Its working for all the desktop browser including Chrome. However request is getting failed with statusCode: 0 in the chrome mobile browser.
function MakeAJAXRequest(jsonData){
var ajaxRequest = new window.XMLHttpRequest();
ajaxRequest.onload = function () { . . . };
ajaxRequest.onreadystatechange = function () { . . . };
ajaxRequest.onerror = function () {. . . };
ajaxRequest.ontimeout = function () { . . .};
ajaxRequest.open("POST", 'https://someotherdomain.com/myservice/postSomeData', true);
ajaxRequest.send(jsonData);
}
Any help would be much appreciated.
PS: I am getting the correct response in default android browser.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28819690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Primeng12 Table with virtual scroll + lazyload + checkbox selection I have an old v12 angular/primeng based app that I am trying to retro fit checkbox selections on a table with virtual scrolling and lazy loading. I can initially toggle to select all the visible rows, but when performing a scroll to lazy load more items, the main checkbox header control doesnt stay selected, and the new rows that appear dont get marked as checked either.
https://stackblitz.com/edit/angular-zavyn1?file=src/app/app.module.ts
I know I am on an older primeng version, just wondering if there are any workarounds to get this functionality behaving, I did consider implementing my own checkbox selection behaviour, but that seems overkill.
I see this was tracked in an issue here which has since been fixed from v13 onwards in this commit I believe. Wondering if there is a way to override the methods on the table\checkbox header instance for the table in my stackblitz example above and bring in the patch fixes?
A: I'm sorry for making a wrong assumption before. The behavior you described is how it should work.
The current version is not working as they implemented it wrong, so ver 12 won't work. Detail: https://github.com/primefaces/primeng/issues/10697
But the new version is working as expected. I just forked the link from the homepage and make some changes. You can see the forked link here:
https://stackblitz.com/edit/primeng-tablevirtualscroll-demo-p2j757?file=src/app/app.component.ts
Your original code also missed the part where you need to listen for the select/click event on the header.
If you wanted to "fix" the issue in the old version, you can just copy the patch from the new version. The code is under updateCheckedState
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74864845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: nginx refuses connections after some time I have a problem with my nginx configuration, my server works fine but after 1 or 2 days it just hangs and stop responding. It's not possible to connect to the server anymore.
(7) Failed to connect to XX.XX.XX.XX port 80: Connection refused
The main job of this server is running heavy PHP tasks, I run cron jobs every 5 seconds for many tasks. Restart helps and again nginx works correctly for the next 1-2 days. I don't have any error logs, nginx dosn't report anything in /var/log/nginx/error.log. It simply fails all connections. Any ideas where to start looking for a problem?
I run nginx on Ubuntu 16.04, 2 CPUs, 4 GB ram with PHP 7.0.
nginx version: nginx/1.10.0 (Ubuntu)
here is config file:
user www-data;
worker_processes 2;
pid /run/nginx.pid;
events {
worker_connections 4096;
#multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 300;
types_hash_max_size 2048;
server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
here is default file:
server {
large_client_header_buffers 4 128k;
listen XX:XX:XX:XX:80;
set $root_path '/var/www/web/public/';
root $root_path;
index index.php;
server_name XX:XX:XX:XX;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_read_timeout 14400;
proxy_set_header Connection "";
proxy_http_version 1.1;
}
location /status {
stub_status on;
access_log off;
allow XX:XX:XX:XX;
deny all;
}
location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
root $root_path;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
location ~ /\.ht {
deny all;
}
}
And the main thing, my cron jobs I run, for example:
* * * * * sleep 5; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 10; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 15; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 20; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 25; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 30; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 35; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 40; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 45; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
* * * * * sleep 50; curl --request GET http://XX:XX:XX:XX/queue/fire > /dev/null 2>&1
etc.
UPDATE:
PHP FPM Status
* php7.0-fpm.service - The PHP 7.0 FastCGI Process Manager
Loaded: loaded (/lib/systemd/system/php7.0-fpm.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2017-01-13 10:46:41 CET; 3 days ago
Process: 1439 ExecStartPre=/usr/lib/php/php7.0-fpm-checkconf (code=exited, status=0/SUCCESS)
Main PID: 1662 (php-fpm7.0)
Status: "Processes active: 0, idle: 25, Requests: 164215, slow: 0, Traffic: 0req/sec"
Tasks: 26
Memory: 377.3M
CPU: 5h 57min 32.279s
CGroup: /system.slice/php7.0-fpm.service
|- 1662 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf)
|- 1752 php-fpm: pool www
|- 8751 php-fpm: pool www
|-12078 php-fpm: pool www
|-14053 php-fpm: pool www
|-14338 php-fpm: pool www
|-14639 php-fpm: pool www
|-14763 php-fpm: pool www
|-16188 php-fpm: pool www
|-16212 php-fpm: pool www
|-16900 php-fpm: pool www
|-17620 php-fpm: pool www
|-17621 php-fpm: pool www
|-17766 php-fpm: pool www
|-18802 php-fpm: pool www
|-19084 php-fpm: pool www
|-22064 php-fpm: pool www
|-24245 php-fpm: pool www
|-24690 php-fpm: pool www
|-25120 php-fpm: pool www
|-27714 php-fpm: pool www
|-29415 php-fpm: pool www
|-30182 php-fpm: pool www
|-30391 php-fpm: pool www
|-32053 php-fpm: pool www
`-32358 php-fpm: pool www
Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.
A: I would check php fpm logs. Maybe running out of php fpm processes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41629266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Screen layout doesn't look good on bigger screens I have 3 horizontal LinearLayouts, I've been making xml on 4.7 screen and it looked good, then i switched to bigger screen and it doesnt look good. So my xml looks good on screen size of 4.7 but on 10.01 and 7 it screws up
on 4.7 screen:
on 10,01 :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/backgroun"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Load" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Play"
android:layout_weight="1" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Mute"
android:layout_weight="1"/>
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Volume up"
android:layout_weight="1" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Volume up"
android:layout_weight="1" />
<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Mute"
android:layout_weight="1"/>
<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Play"
android:layout_weight="1"/>
<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Load"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="horizontal" >
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="7"/>
<Button
android:id="@+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="@+id/button10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<SeekBar
android:id="@+id/seekBar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="7"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<SeekBar
android:id="@+id/seekBar3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<SeekBar
android:id="@+id/seekBar4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
A: First of all when you use android:layout_weight you should set the android:layout_width="0dp"
Besides that now, I would suggest having a separate layout for xlarge screens. The way to do that is to create a separate folder that will contain a layout with the same name as your original layout (eg. main.xml). The folder name for 10" screens should be something like layout-xlarge. For more details you should check here.
A: For different size screens. you can also make another layout for bigger screen.
res/layout-small
res/layout-large
res/layout-xlarge
create a new folder as named "layout-xlarge" and copy your xml layout in there and you can adjust the sizes.
Android will automatically select the appropriate layout for the current device. Remember that, layout name should be the same in each folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16985640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to post php variables in swf? I have in test.php this:
$domain = $_GET['domain'];
$user = $_GET['user'];
and in my Action Script i have:
getURL("http://test.com/file.php?domain=?&user=?", "_blank");
How do get variables from php and put in my swf?
I'm beginner in flash!!!
A: To send variables from flash to PHP:
//Actionscript:
loadVariables ("test.php?myVariable=" + myFlashVar , _root);
//PHP can retrieve it using
$myVar = $_GET['myVariable'];
To send from PHP to flash, use exactly the same:
//Actionscript:
loadVariables ("test.php?" , _root);
//PHP:
echo "&myVariable=hello";
//Now in your flash movie, _root.myVariable will be equal to 'hello'
I hope this is enough to get you started :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21531007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Connect android to database I am doing a school project where we need to create an android application which needs to connect to a database. the application needs to gain and store information for people's profiles on the database. But unfortunatly we are a little bit stuck at this point because there are numerous ways to link the application such as http request through apache or through the SOAP/REST protocol.
But it's really hard to find good instructions or tutorials on the problem since I can't really find them. Maybe that's cause i'm probably using the wrong words on google. Unfortunately I have little relevant information. So if anyone can help me with finding relevant links to good online tutorials or howto's than those are very welcome.
A: I'd recommend using REST and JSON to communicate to a PHP script running on Apache. Don't worry about the database on the Android side of things, just focus on what kinds of queries you might need to make and what data you need returned. Then put together a PHP script to take those queries and generate the necessary SQL to query the database on the server. For example, You need look look up a person by name and show their address in your Android app. A REST Query is just a simple HTTP GET to request data. For example, to look up John Smith, you might request: http://www.example.org/lookup.php?name=John+Smith which will return a short JSON snippet generated by PHP:
{
name: "John Smith",
address: "1234 N Elm St.",
city: "New York",
state: "New York"
}
You can instruct PHP to use the content type text/plain by putting this at the top of your PHP script:
Then you can just navigate to the above URL in your browser and see your JSON response printed out nicely as a page. There should be a good JSON parser written in Java out there you can use with Android. Hopefully, this will get you started.
A: This tutorial really helped me: http://www.screaming-penguin.com/node/7742
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2947826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reload page with anchor after submit I have a big form in PHP with several tables, each of one calculates a sum (of price and quantity) and then there's one at the end that calculates the total.
The structure is, more or less, this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="purchase_form">
<div id="purchase_1">
<table>
<input id="price_1">
<input id="quantity_1">
<input type="submit" name="calculate" value="Click here to calculate the partial">
</table>
</div>
<div id="purchase_2">
<table>
<input id="price_2">
<input id="quantity_2">
<input type="submit" name="calculate" value="Click here to calculate the partial">
</table>
</div>
<tr>
<td id="price_sum"><?php *script* ?></td>
<td id="quantity_sum"><?php *script* ?></td>
</tr>
</form>
Now, when I click on submit to calculate the "partial", it gives me the total, at the same time. I know it's not a state-of-the-art form, but anyway, just try to turn a blind eye on that.
What I want is, when I click on submit button, to have the page reloaded showing the form I have clicked on. Like, if I click on submit of the #purchase_1 table, I want the page to reload on #purchase_1 table, and so on.
Is it possible to do that with javascript?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36626646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Swift NSPredicate filtering using set operations I'm trying to filter such that criteria is met for each AND every item in a set vice each OR every item.
If I use groceryItem IN %@, desiredGroceries, it acts like an OR statement.
Example: I'm trying to return all grocery lists of groceryItems that included milk AND eggs (desiredGroceries=Set("Milk", "Eggs")).
If I use the above code, it returns all lists that included milk as well as lists that included eggs.
But I only want the lists that include BOTH milk and eggs.
What's the correct Predicate for this?
UPDATE:
From the Willeke's comments, I tried using .@count==%lu
This works if each groceryList only has one item. However, if it has multiple items, I see inconsistent results when showing groceryLists. Sometimes the filter works, other times it reports nothing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64255573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: Files assigned variable path not printing or editing I have most of the program done. The last part of this program needs to open the file in append mode> Add 2 names > close file. Then, it has to open file in read mode> print contents> close file.
The file path has been assigned to a variable.
I keep getting the below error. (code is below that)
I don't know what to do to fix this
Traceback (most recent call last):
File "C:\Users\gorri\Desktop\College Work\CPT180_ShellScripting\Assignments\Programs\workWithFiles2.py", line 34, in
cat_files = open(cat_files, 'a')
TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper
from pathlib import Path
import os
import os.path
path_E = Path('E:/CPT180Stuff')
os.chdir(path_E)
cat_files = (path_E / 'pets' / 'cats' / 'catnames.txt')
#opens catnames file to append end and add names.
cat_files = open(cat_files, 'a')
cat_files.write('Princess\nFreya\n')
cat_files.close()
cat_files = open(cat_files, 'r')
cat_files = cat_files.read()
print(cat_files)
cat_files.close()
A: In your current code, you are first assigning cat_files to the file name, but then in this line:
cat_files = open(cat_files, 'r')
You are now assigning cat_files to a file handle, which is not a string. This is why the next statement fails: it is expecting the filename string, not the file handle. You should use a different variable name for the handle, e.g.:
#opens catnames file to append end and add names.
f = open(cat_files, 'a')
f.write('Princess\nFreya\n')
f.close()
f = open(cat_files, 'r')
f = f.read()
print(f)
f.close()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66307711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Change colorpicker for nicedit.js to photoshop like I want to change the default color picker for nicedit.js
While going through the js file, I can see that the below code is generating the color-picker. Data is set up using colorList variable. Can anyone please help me to get a color-picker like photoshop or more relavant.
var nicEditorColorButton = nicEditorAdvancedButton.extend({
addPane : function() {
var colorList = {0 : '00',1 : '33',2 : '66',3 :'99',4 : 'CC',5 : 'FF'};
var colorItems = new bkElement('DIV').setStyle({width: '270px'});
for(var r in colorList) {
for(var b in colorList) {
for(var g in colorList) {
var colorCode = '#'+colorList[r]+colorList[g]+colorList[b];
var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems);
var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare);
var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder);
if(!window.opera) {
colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent;
}
}
}
}
this.pane.append(colorItems.noSelect());
}
});
A: I would change the colorList to array containing photoshop hex values and then use it like this:
var nicEditorColorButton = nicEditorAdvancedButton.extend({
addPane : function() {
var colorList = {0 : '000000',1 : 'FFFFFF'}; /* here goes color list */
var colorItems = new bkElement('DIV').setStyle({width: '270px'});
for(var g in colorList) {
var colorCode = '#'+colorList[g];
var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems);
var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare);
var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder);
if(!window.opera) {
colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent;
}
}
this.pane.append(colorItems.noSelect());
}});
Not sure if my code is edited correctly but you get the basic idea. Remove 2 for loops and loop within the colorList directly
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37234606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Setting Apollo client header dynamically is not working I am trying to set the header of Apollo client dynamically according to official doc, but I am getting an error:
TypeError: (0 , _apollo.default) is not a function
This is my apollo.js
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { AsyncStorage } from 'react-native';
const httpLink = createHttpLink({
uri: 'http://192.168.2.4:8000/api/',
});
const authLink = setContext((_, { headers }) => {
const token = AsyncStorage.getItem('token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
export default client;
UPDATE
I am adding App.js:
import { ApolloProvider } from 'react-apollo';
import Routes from './app/config/routes';
import makeApolloClient from './app/config/apollo';
export default function App() {
const client = makeApolloClient();
return (
<ApolloProvider client={client}>
<Routes />
</ApolloProvider>);
}
How can I solve this issue?
A: makeApolloClient isnt a function, the file just exports an instance of the apollo client. Just import it as if it's a variable.
import client from './app/config/apollo'
export default function App() {
return (
<ApolloProvider client={client}>
<Routes />
</ApolloProvider>
);
}
A:
Storing JWT in local storage and session storage is not secure!
Use cookie with http-only enabled!
This code automatically reads and sets Authorization header after localStorage.setItem('jwt_token', jwt_token) in SignIn mutation.
import {ApolloClient, createHttpLink} from "@apollo/client";
import {setContext} from "@apollo/client/link/context";
import {InMemoryCache} from "@apollo/client";
const apolloHttpLink = createHttpLink({
uri: process.env.REACT_APP_APOLLO_SERVER_URI || 'http://localhost/graphql',
})
const apolloAuthContext = setContext(async (_, {headers}) => {
const jwt_token = localStorage.getItem('jwt_token')
return {
headers: {
...headers,
Authorization: jwt_token ? `Bearer ${jwt_token}` : ''
},
}
})
export const apolloClient = new ApolloClient({
link: apolloAuthContext.concat(apolloHttpLink),
cache: new InMemoryCache(),
})
A: Apollo usequery has a context option that allows you to dynamically change or update the values of the header object.
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
cache: new InMemoryCache(),
uri: "/graphql"
});
client.query({
query: MY_QUERY,
context: {
// example of setting the headers with context per operation
headers: {
special: "Special header value"
}
}
});
The code above was copied from the Apollo docs.
To find out more check out https://www.apollographql.com/docs/react/networking/advanced-http-networking/#overriding-options
A: Try this
const authLink = setContext(async (_, { headers }) => {
const token = await AsyncStorage.getItem('token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
A: In React Native, AsyncStorage methods are async not like localStorage in Web. And the other methods doesn't work, except this.
https://github.com/apollographql/apollo-client/issues/2441#issuecomment-718502308
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61495727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: how to load data fast from webservice in android? Am access data from web service,but when moving from one activity to other its showing black screen till that get loaded then its displaying my activity.
how to avoid black screen and access data fast?
code:
JSONObject json = getJSONfromURL(url);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();is =entity.getContent();
A: Here is a AsyncTask example - http://www.vogella.com/articles/AndroidPerformance/article.html
Here is a Progress dialogue example - http://www.vogella.com/articles/AndroidDialogs/article.html
should get you started in the right direction.
A: Use Asynchronous Task to display progress dialog when it is performing parsing. do in background method write all code that you perform and the on post method show result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10240477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Navigate user to particular message in channel upon clicking a button in Personal Chat adaptive card I am sending a message to the user using an Adaptive card. With the click of a button, I would like to redirect the user to a particular message in the channel. Is there any way we can achieve this?
A: On click of button you can add a deeplink of message in channel
Use below deep link format to navigate to a particular conversation within channel thread:
https://teams.microsoft.com/l/message//?tenantId=&groupId=&parentMessageId=&teamName=&channelName=&createdTime=
Example: https://teams.microsoft.com/l/message//1648741500652?tenantId=&groupId=&parentMessageId=1648741500652&teamName=&channelName=&createdTime=1648741500652
Ref Doc: https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links?tabs=teamsjs-v2#generate-deep-links-to-channel-conversation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73536698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Project compiles on Ubuntu but not on Debian I have a strange problem where one of my projects is compiling just fine on Ubuntu 22.04 and Windows but gives a strange linker error on Debian bullseye even with the same gcc and cmake versions.
On Debian I get this linker error here:
#16 953.5 `_ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateEPZNS8_8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_E305_ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_.Frame.destroy' referenced in section `.rodata.cst8' of src/gw2cc/Release/libgw2cc_lib.a(SecureTokenServerClient.cpp.o): defined in discarded section `.text._ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateEPZNS8_8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_E305_ZN5boost4asio12async_resultINS0_15use_awaitable_tINS0_15any_io_executorEEEJFvNS_6system10error_codeEmEEE8initiateINS0_6detail36initiate_async_write_buffer_sequenceINS0_19basic_stream_socketINS0_2ip3tcpES3_EEEEJSt5arrayINS0_12const_bufferELm4EENSA_14transfer_all_tEEEENS0_9awaitableImS3_EET_S4_DpT0_.Frame.destroy[_ZN7network6socks56socketIN5boost4asio19basic_stream_socketINS3_2ip3tcpENS3_15any_io_executorEEEE10do_connectERKNS5_14basic_endpointIS6_EERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESL_]' of src/gw2cc/Release/libgw2cc_lib.a(SecureTokenServerClient.cpp.o)
The project is using vcpkg to download and build all dependencies. Would be great if somebody could tell me what is causing this. All Linux compilations were done in a clean docker image with just the necessary dependencies installed. I even tried different gcc versions on Debian without any success.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73248262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In which scenario I should use IS(Information Service) Parameters or SS(Solution Sets) Parameters in 3gpp notifications I am reading through the 3gpp ts for notifications like notifyNewAlarm, where I see IS Parameters and SS Parameters, unsure which one to use and the sample data for the fields, Please help me with some starting point.
Difference is
IS Parameters is with "objectClass" and "objectInstance" fields
SS Parameters is with "href".
I have figured out the sample data for IS Parameters. If you have any for IS parameter, please comment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73568229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the difference between ForAll and Select in PLINQ In the intro to PLINQ, the docs seem to show two different ways of getting data back from a process unordered. In one case, AsParallel can be used with Unsorted and the Select or SelectMany method. SelectMany says it
Projects in parallel each element of a sequence to an IEnumerable
and flattens the resulting sequences into one sequence.
So to get a return list from a function, I call it like this:
def genGraph(node,constData):
#do something
return (constData+1,constData+2,constData+3)
newGraph = Graph.AsParallel().SelectMany(lambda node: genGraph(node,constData) ).ToList()
The other way would be using ForAll and a ConcurrentBag that is added to, and nothing returned.
For faster query execution when order preservation is not required and
when the processing of the results can itself be parallelized, use the
ForAll method to execute a PLINQ query.
def genGraph(node,constData,newGraph):
#do something
newGraph.Add(constData+1,constData+2,constData+3)
newGraph = Concurrent.ConcurrentBag[type((0,0,0))]()
Graph.AsParallel().ForAll(lambda node: genGraph(node,constData,newGraph) )
So the first one says it projects in parallel to an IEnumerable, and the second one says it is faster when processing can be parallelized. It sounds to me the same thing. In my code, it currently runs the same amount of time as well, but I am wondering if there is some other case I am not understanding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55884571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to append objects on a file in Java? I'm trying to make a small program inJava in which I need to save An array of objects on a file. I was looking for how to do this and I found the next code:
//this is the array that will be stored
private Atributtes list[]=new Atributtes [100];
/*
this is the way i save the data in the array,i always save them in
index 0,and i made a for to put away the previous data because always
there will have data in index 0
*/
for (int i = totalElments; i>0; i--){
list[i] = list[i-1];
}
list[0]=new Atributtes ("Atributtes data");
save.storeInfile(list);
totalElments++;
private static final String filename="file.obj";
public void storeInfile(Object array[]){
try{
FileOutputStream file= new FileOutputStream(filename,true);
ObjectOutputStream object= new ObjectOutputStream(file);
object.writeObject(array);
object.close();
file.close();
System.out.println("recording successfully");
System.out.println("-----------------------------------");
}catch(Exception exceccao){
System.out.println("recording wasn't successfull");
}
}
My problem now is that when I want to save the same Array of objects but with another data,or when I reopen the file, the first data that was in the file is overwritten.
Note1:i was said to put the true boolean on FileoutPutSTream,but when i put it the recording doesn't happen anymore,but when i remove the true boolean the recording happens but with overwritten data always.
Note2: I've read about FileWriter and the PrintWriter, but I need to write only Objects, not Strings.thanks!!!!
Could someone tell how to append this new data on the file?
Thank you.
A: Change this line
FileOutputStream file= new FileOutputStream(filename);
to this
FileOutputStream file= new FileOutputStream(filename, true)
The true stands for append enable or disable. In default it is disabled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60889169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I efficiently concatenate multiple Arduino Strings? I was looking for an Arduino way of efficiently concatenating strings. I was looking for something like std::format(" {} blah blah {}", str1, str2);
I don't want to do something that will be slow such as
" " + str1 + " blah blah " + str2.
A: There is already a concat function.
myString.concat(parameter);
You can use it as that. Reference: Arduino Official Link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72372959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Test a Spring multipart/form-data controller with uploading of some files I am trying to test this controller:
@RequestMapping(value="/u",consumes="multipart/form-data", method = RequestMethod.POST)
public @ResponseBody String register(
@RequestParam String u,
@RequestParam CommonsMultipartFile filea,
@RequestParam CommonsMultipartFile fileb,
@RequestParam CommonsMultipartFile filec,
@RequestParam CommonsMultipartFile filed) {
return "hi";
}
Whit this mock of a request:
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/u")
.file("filea","id.jpg".getBytes())
.file("fileb","pc.jpg".getBytes())
.file("filec","cl.jpg".getBytes())
.file("filed","fo.jpg".getBytes())
.param("u", u))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
Although, I guess I am writing the MockMvcRequest wrongly because the test fails (the status returned is 500).
Thanks in advance.
A: The issue is a very small one - just change your CommonsMultipartFile to MultipartFile and your test should run through cleanly.
The reason for this issue is the mock file upload parameter that is created is a MockMultipartFile which cannot be cast to the more specific CommonsMultipartFile type.
A: The simple way how to test multipart upload is use StandardServletMultipartResolver.
and for test use this code:
final MockPart profilePicture = new MockPart("profilePicture", "stview.jpg", "image/gif", "dsdsdsd".getBytes());
final MockPart userData = new MockPart("userData", "userData", "application/json", "{\"name\":\"test aida\"}".getBytes());
this.mockMvc.perform(
fileUpload("/endUsers/" + usr.getId().toString()).with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.addPart(profilePicture);
request.addPart(userData);
return request;
}
})
MockPart class
public class MockPart extends MockMultipartFile implements Part {
private Map<String, String> headers;
public MockPart(String name, byte[] content) {
super(name, content);
init();
}
public MockPart(String name, InputStream contentStream) throws IOException {
super(name, contentStream);
init();
}
public MockPart(String name, String originalFilename, String contentType, byte[] content) {
super(name, originalFilename, contentType, content);
init();
}
public MockPart(String name, String originalFilename, String contentType, InputStream contentStream) throws IOException {
super(name, originalFilename, contentType, contentStream);
init();
}
public void init() {
this.headers = new HashMap<String, String>();
if (getOriginalFilename() != null) {
this.headers.put("Content-Disposition".toLowerCase(), "form-data; name=\"" + getName() + "\"; filename=\"" + getOriginalFilename() + "\"");
} else {
this.headers.put("Content-Disposition".toLowerCase(), "form-data; name=\"" + getName() + "\"");
}
if (getContentType() != null) {
this.headers.put("Content-Type".toLowerCase(), getContentType());
}
}
@Override
public void write(String fileName) throws IOException {
}
@Override
public void delete() throws IOException {
}
@Override
public String getHeader(String name) {
return this.headers.get(name.toLowerCase());
}
@Override
public Collection<String> getHeaders(String name) {
List<String> res = new ArrayList<String>();
if (getHeader(name) != null) {
res.add(getHeader(name));
}
return res;
}
@Override
public Collection<String> getHeaderNames() {
return this.headers.keySet();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23072562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use Clutter.ShaderEffect.set_uniform_value() properly? I am trying set a uniform float of a Clutter.ShaderEffect. This works well if floating point Numbers are passed to set_uniform_value(). However, when you pass an integer Number, an OpenGL error (1282, Invalid operation) is thrown. It seems that the implementation assumes in this case that the uniform is actually of type int. Here is a minimal example:
const {Clutter, GObject} = imports.gi;
Clutter.init(null);
let stage = new Clutter.Stage({width: 200, height: 200});
let shader = new Clutter.ShaderEffect({shader_type: Clutter.ShaderType.FRAGMENT_SHADER});
shader.set_shader_source(`
uniform float value;
void main(void) {
cogl_color_out = vec4(value, 0, 0, 1);
}
`);
// This creates the OpenGL Error.
// shader.set_uniform_value('value', 1);
// This works however:
shader.set_uniform_value('value', 0.999);
stage.add_effect(shader);
stage.connect('destroy', () => Clutter.main_quit());
stage.show();
Clutter.main();
So how do I force set_uniform_value() to interpret the value as floating point number? Reading the documentation (https://gjs-docs.gnome.org/clutter6~6_api/clutter.shadereffect#method-set_uniform_value), I would assume that I could pass a GObject.Value - maybe like this:
let value = new GObject.Value();
value.init(GObject.TYPE_FLOAT);
value.set_float(1.0);
shader.set_uniform_value('value', value);
But this yields the error Invalid uniform of type 'GValue' for name 'value'. Maybe I now have a GObject.Value containing a GObject.Value containing a GObject.TYPE_FLOAT?
A: if someone looks for this question, I have the answer:
https://gjs-docs.gnome.org/clutter7~7_api/clutter.shadereffect#method-set_uniform_value value - a GObject.Value GObject.TYPE_FLOAT for float
and in gjs GTK Javascript they have https://gjs-docs.gnome.org/clutter7~7_api/clutter.value_set_shader_float
value_set_shader_float(value,[float]) method - Value must have been initialized using %CLUTTER_TYPE_SHADER_FLOAT.
and in Javascript version of GTK they dont have any way to initialize that CLUTTER_TYPE_SHADER_FLOAT or GObject.TYPE_FLOAT
The solution is:
function make_float(val) {
return Math.floor(val)==val?val+0.000001:val;
}
A: As of GJS 1.68.0 (GNOME 40), passing a GObject.Value works:
let value = new GObject.Value();
value.init(GObject.TYPE_FLOAT);
value.set_float(1);
shader.set_uniform_value('value', value);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62254719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to register trigger in PostgreSQL? I have trigger and procedure. I want to be sure that string saved to database will have no '-' characters.
After executing
UPDATE interesant SET interesant_nip = '555-555-5555'
I get error
value is too long for varchar(10).
This suggests that '-' characters were not removed before insert-update.
Why is my trigger not being executed?
CREATE FUNCTION normalize_nip() RETURNS TRIGGER AS $$
BEGIN
-- replace '' to NULL
IF (NEW.interesant_nip LIKE '') THEN
NEW.interesant_nip := NULL;
RETURN NEW;
END IF;
-- remove '-' from string
NEW.interesant_nip := REPLACE(NEW.interesant_nip, '-', '');
RETURN NEW;
END; $$ LANGUAGE plpgsql;"
CREATE TRIGGER interesant_nip_normalize BEFORE INSERT OR UPDATE ON public.interesant FOR EACH ROW EXECUTE PROCEDURE normalize_nip()
A: The updated or inserted value is always treated as type varchar(10) - before and after the trigger function. So, you cannot handle the value because the input type does not fit the value even if the trigger function converts it into a valid one.
It works if you have an unbounded text type. There you can see that the trigger is executed:
demo:db<>fiddle
So, the only chance to handle this, is, to normalize it before inserting or updating:
demo:db<>fiddle
INSERT INTO interesant VALUES (normalize_nip('555-555-5555'));
UPDATE interesant SET interesant_nip = normalize_nip('555-555-5555')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57954768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Two list element wise comparison using filter I have two lists of numbers:
l1 = [12, 3, 4, 5, 7]
l2 = [ 6, 8, 4, 2, 4]
I want to retrieve all the elements from l1 that are bigger than the elements from l2 (element-wise comparison)
So far I only achieved
results = list(map(operator.gt,l1,l2)
Which returns me a [True,False,...] list. But I want the values itself.
I would like to do it without any for loop thanks. I was thinking about filter() or itertools()
Thanks
A: you can use a list comprehension:
[a for a, b in zip(l1, l2) if a > b]
or you can use:
from operator import gt, itemgetter
list(map(itemgetter(1), filter(itemgetter(0), zip(map(gt, l1, l2), l1))))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60891048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UI Multitouch Architecture? I am developing a game with multitouch controllers. But I have problems with UI Image multi touching
I want to create this architecture.
*
*Green Cycles will work as button. (Touch End)
*Red Cycle will work as a button.I need touch move or touch stay events for serial shoting. (Touch Move | Touch Stay)
*Yellow Box will work as a touchpad(UI Image Element). When finger moves over the box, It will trigger to Rotate method.
I tried some methods but all is failed.
I created a class named MultiTouchElement.
var touches = Input.touches;
for (int i = 0; i < touches.Count; i++)
{
Touch touch = Input.GetTouch(i);
TouchPhase phase = touch.phase;
PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current);
eventDataCurrentPosition.position = touch.position;
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
var touchOnThisObject = results.Any(x => x.gameObject.name.ToLower() == this.gameObject.name.ToLower());
if (!touchOnThisObject)
return;
if (phase == TouchPhase.Began)
{
this.GetComponent<Image>().color = Color.red;
}
if (phase == TouchPhase.Ended)
{
this.GetComponent<Image>().color = Color.blue;
}
}
Are there any tutorial for my architecture?
A: I found solution :)
Thank you Bro @IsGreen
Source : http://forum.unity3d.com/threads/solved-raycast-multitouch-input-convert-local-recttransform-rect-to-screen-position.318115/
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
public class UImageRayCast : MonoBehaviour
{
Image image;
Color colorOn, colorOff;
void Start()
{
this.image = this.GetComponent<Image>();
this.colorOff = this.image.color;
this.colorOn = new Color(this.colorOff.r, this.colorOff.g, this.colorOff.b, this.colorOff.a * 0.5f);
}
void Update()
{
this.image.color = this.colorOff;
PointerEventData pointer = new PointerEventData(EventSystem.current);
List<RaycastResult> raycastResult = new List<RaycastResult>();
foreach (Touch touch in Input.touches)
{
pointer.position = touch.position;
EventSystem.current.RaycastAll(pointer, raycastResult);
foreach (RaycastResult result in raycastResult)
{
if (result.gameObject == this.gameObject)
{
if(touch.phase == TouchPhase.Began)
{
Debug.Log("Began " + result.gameObject.name );
}
else if(touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
this.image.color = this.colorOn;
}
else if (touch.phase == TouchPhase.Ended)
{
Debug.Log("End " + result.gameObject.name);
}
//this.gameObject.transform.position = touch.position;
//Do Stuff
}
}
raycastResult.Clear();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33778532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Box shadow effect I'm trying to apply a shadow to a div, however I have been unable to achieve the desired effect. Effect to be 'below' the element.
Example: http://www.paulund.co.uk/creating-different-css3-box-shadows-effects
JSFiddle: http://jsfiddle.net/Ck7pG/
CSS
ul#nav li {
display: inline;
line-height: 40px;
}
/* Shadow effect */
.shadow-effect {
position: relative;
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.shadow-effect:before, .shadow-effect:after {
content: "";
position: absolute;
z-index: -1;
-webkit-box-shadow: 0 0 10px rgba(0,0,0,0.8);
-moz-box-shadow: 0 0 10px rgba(0,0,0,0.8);
box-shadow: 0 0 10px rgba(0,0,0,0.8);
top: 20%;
bottom: 0;
left: 50px;
right: 50px;
-moz-border-radius: 100px / 10px;
border-radius: 100px / 10px;
}
A: I just assumed your requirement from the website you provided,i think this is what you need
DEMO
.shadow-effect {
position:relative;
-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.shadow-effect:before, .shadow-effect:after {
content:"";
position:absolute;
z-index:-1;
-webkit-box-shadow:0 0 10px rgba(0,0,0,0.8);
-moz-box-shadow:0 0 10px rgba(0,0,0,0.8);
box-shadow:0 0 10px rgba(0,0,0,0.8);
top:20%;
bottom:0;
left:50px;
right:50px;
-moz-border-radius:100px / 10px;
border-radius:100px / 10px;
}
.box h3{
text-align:center;
position:relative;
top:80px;
}
.box {
width:70%;
height:100px;
background:#FFF;
margin:40px auto;
}
.effect6
{
position:relative;
-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.effect6:before, .effect6:after
{
content:"";
position:absolute;
z-index:-1;
-webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
-moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
box-shadow:0 0 20px rgba(0,0,0,0.8);
top:50%;
bottom:0;
left:10px;
right:10px;
-moz-border-radius:100px / 10px;
border-radius:100px / 10px;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21332425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: issue with empty slide in JSSOR Slider and goto currentIndex property not working in javascript Hi I am working on JSSOR SLider and am trying to load a set of images on to it from database.
I am able to load therse images onto slider but i am getting first slide as an empty slide and rest are working fine.
In my index.html
<div data-role="main" id="galleryItemMainDetails">
<!--blue-->
<div id="MasterTemplate" style="min-width: 300px; min-height: 330px; background: #6699FF;">
<!--purple-->
<div id="slider1_container" style="position: relative; top: 0px; left: 5px; width: 270px; height: 260px; background: #990099; overflow: hidden; ">
<!-- Slides Container -->
<!--light green-->
<div id="HomeImgSliders" u="slides" style="cursor: move; position: relative; overflow: hidden; left: 5px; top: 5px; width: 250px; height: 250px; background: #99FF99;">
<div id="HomeSlides"></div>
</div>
</div>
</div>
</div>
in my js file
$('#galleryItem').on('pageshow', function () {
var verticaltext = "";
if ($('#galleryItem').has('#HomeImgSliders').length) {
$("#HomeImgSliders").append("");
}
var allItems = Tables.images.all().order("capturedYear", false).order("capturedMonth", false).order("capturedDate", false);
allItems.list(null, function (results) {
var verticaltext = "";
results.forEach(function (r) {
// alert(JSON.stringify(r));
imageDetailsarr.push([r.capturedDate, r.name, r.ratingTreatment, r.ratingSkinCleansing, r.ratingPlucking, r.ratingView, r.ratingLastVal, r.capturedDate, r.capturedMonth, r.capturedYear]);
// console.log("record is " + r.name);
verticaltext = verticaltext + "<div><img alt='Image not found' src=" + r.name + " class='vSlideImg'/></div>"
// <div><img src=" + value[1] "></div>
});
$("#HomeImgSliders").append(verticaltext);
// $("#HomeSlides").append(verticaltext);
sliderDataReady(verticaltext);
});
});
How can i get rid of this empty image that is appearing as the first slide
2) Also how can i set the slider set to a particular slide image based on some integer value that changes every time. I tried GoTO/slideIndex /currentIndex properties but could not get it ?
Any help would be appreciated ?Thanks
A: Re 1: Please dump value of 'verticaltext', with it you can create a static slider to see why there is an empty slide.
Re 2: Please use $StartIndex option
var options = {
...,
$StartIndex: 0, //specify slide index to display at the beginning.
...
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28526749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Char movement, getting x/y speeds from 2 points So i'm trying to make a program in java and i need to figure out how much I should add to x and y to make the player movement a constant speed at any angle. The information i have is 2 points, a starting point and an and and I need the char to move from a to b at a constant speed. I'm currently trying to figure out a bunch of different Math methods but I just cant get it right. Thanks in advance.
A: It's actually quite simple. You have points A (A.x, A.y) and B (B.x, B.y) and need the update for your character position.
Start by calculating the direction vector dir = B - A (subtract component-wise, such that dir.x = B.x - A.x; dir.y = B.y - A.y).
If you add this entire vector to your character's position, you will move it by sqrt(dir.x^2 + dir.y^2) (Pythagorean theorem). Hence, the speed will be: speed = sqrt(dir.x^2 + dir.y^2) / frameTime.
So if you want a constant speed, you have to find a multiple of the direction vector. This will be:
update = dir * speed / sqrt(dir.x^2 + dir.y^2) * frameTime
characterPosition = characterPosition + update
Don't bother with angle calculations. Vector arithmetic is usually way more robust and expressive.
A: Since u didn't provide us code I can just guess what exactly you are trying.
So I'll start with some basics.
I guess you are not just trying to make a program
but the basic movement of an 2d based game engine.
However a constant moving is based of an update method
that reads the player input about 30 times while rendering.
Example from my Projects:
public void run() {
boolean isRunning = true;
long lastNanoTime = System.nanoTime(),nowNanoTime = System.nanoTime();
final double secondAsNano = 1000000000.0;
final double sixtiethOfSecondAsNano = secondAsNano / 30.0;
int delta = 1;
while(isRunning){
nowNanoTime = System.nanoTime();
if(delta * sixtiethOfSecondAsNano + lastNanoTime < nowNanoTime){
update();
delta++;
if(delta == 30){
delta = 1;
lastNanoTime = nowNanoTime;
}
}
render();
}
}
public update(){
if(Input.moveUP) setPlayerY(getPlayerY() - 0.2);
if(Input.moveDOWN) setPlayerY(getPlayerY() + 0.2);
if(Input.moveRIGHT) setPlayerX(getPlayerX() + 0.2);
if(Input.moveLEFT) setPlayerX(getPlayerX() - 0.2);
}
I just cut it down to be easy readable so it might not work correct but it should explain you how its basically done.
A: Mathematically (I won't provide code, sorry), assuming you can move in any direction on a two dimensional plane, from the top of my head it could be something like this (taken from old school geometry):
*
*Having a speed, let's say 20 pixels per second (it could also be any other unit you chose, including in-game distance)
*Having a polling system, where you have 2 main variables: the last known coords for the char (point A: Ax, Ay), the time of the last known update.
*Having the time of the current update.
*Having the coords for the destination (point B: Bx, By).
*Figure out the current position of your character, which could be done like this (without converting from cartesian to polar coord system):
*Figure out angle of movement: find the deltas for X and Y (Dx=Bx-Ax and Dy=By-Ay respectively), and use tangent to find the angle where Angle = tan-1(Dy/Dx).
*Figure out the travelled distance (TD) from last poll to current poll where TD = speed * elapsed time
*Figure out the coords for the new position (Cx and Cy) using sine and cosine, where travelled X is Tx=TD*sin(Angle) and travelled Y is Ty=TD*cos(Angle).
*Now add the travelled distances to your original coords, and you get the current position. Where Cx=Ax+Tx and Cy=Ay+Ty.
How "smooth" movement is depends highly on the quality of your polling and somehow also on rounding for small distances.
A: I ended up figuring this out almost an hour after posting this. Sorry that my question was so vague, what I was looking for was the math behind what i was trying to do not the code itself but thanks to people who answered. Here is the solution I came up with in code :
if (q.get(0)[0][0] > q.get(0)[1][0]) {
if(q.get(0)[0][0] == q.get(0)[1][0]) {
currentLocation[0] -= 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
currentLocation[1] += 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
}
else{
currentLocation[0] -= 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
currentLocation[1] -= 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
}
} else {
if(q.get(0)[0][0] == q.get(0)[1][0]) {
currentLocation[0] += 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
currentLocation[1] -= 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
}
else{
currentLocation[0] += 5 * Math.cos((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
currentLocation[1] += 5 * Math.sin((Math.atan(((double) q.get(0)[0][1] - (double) q.get(0)[1][1]) / ((double) q.get(0)[0][0] - (double) q.get(0)[1][0]))));
}
}
I figured out a way to get the result I wanted though I probably over complicated it. q is an ArrayList that holds 2d arrays that are 2x2 [a/b][x/y]. and currentLocation a 2 index array that's just [x/y]. The result is the affect I wanted where it draws a line in (X units) a pass from point a to b in any direction at the same speed. This question was poorly worded and i'm sorry for wasting peoples time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37461862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Trigger doesn't work (if statement) I have a problem. I want to create a trigger.
DELIMITER $
Create trigger xyz
before delete on worker
FOR EACH ROW
Begin
IF salary>2000
then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Zakaz usuwania';
end if;
End$
DELIMITER ;
delete from pracownik where id=5
I get an error:
Error Code: 1054. Unknown column 'salary' in 'where clause'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49285268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sass styles are not applying I wanted to know why my styles of class="project-borders" and class="project-overlay" are not applying to div elements of data-modal="modal3" and data-modal="modal6". These styles are applying to every div element where used, except these two. I don't understand what's the problem even though the classes are the same across every div element. You can see the styles by removing class="project-borders" from div elements of data-modal="modal3" and data-modal="modal6".
Here is the visual representation:- Codepen
Please any help would be appreciated.
My HTML:
<div class="projects">
<div data-modal="modal1" class="project-borders">
<div class="project-overlay">
<p>Coffee Grounds</p>
</div>
<img src="https://upload.wikimedia.org/wikipedia/commons/4/45/A_small_cup_of_coffee.JPG" alt="">
</div>
<div data-modal="modal2" class="project-borders">
<div class="project-overlay">
<p>Startup Employee Directory</p>
</div>
<img src="https://www.hofstra.edu/images/positioning/id-directories.jpg" alt="">
</div>
<div data-modal="modal3" class="project-borders">
<div class="project-overlay">
<p>Words Guessing Game</p>
</div>
<img src="https://images.newindianexpress.com/uploads/user/imagelibrary/2019/10/15/w900X450/PUBG_.JPG" alt="">
</div>
<div data-modal="modal4" class="project-borders">
<div class="project-overlay">
<p>Motorcycle Parallax</p>
</div>
<img src="https://cdp.azureedge.net/products/USA/ZERO/2020/MC/MCY/SR-F/50/BOARDWALK_RED/2000000002.jpg" alt="">
</div>
<div data-modal="modal5" class="project-borders">
<div class="project-overlay">
<p>Picture Portfolio</p>
</div>
<img src="https://media.wired.com/photos/598e35fb99d76447c4eb1f28/master/pass/phonepicutres-TA.jpg" alt="">
</div>
<div data-modal="modal6" class="project-borders">
<div class="project-overlay">
<p>Video Creator Portfolio</p>
</div>
<img src="https://storage.googleapis.com/proudcity/petalumaca/uploads/2020/01/video-infographic.jpg" alt="">
</div>
</div>
My SASS:
.projects{
display: grid;
grid-template-columns: 1fr 1fr 1fr;
width: 80%;
margin: 0 auto;
column-gap: 50px;
row-gap: 50px;
// margin-top: 60px;
padding-top: 6%;
img{
width: 100%;
height: 100%;
cursor: pointer;
}
}
.project-borders{
position: relative;
border: 2px solid #000;
img{
width: 100%;
height: 100%;
cursor: pointer;
position: absolute;
left: 10px;
top: 10px;
}
&::before{
position: absolute;
border: 2px solid #ffde59;
content: "";
display: block;
position: absolute;
top: 25px;
left: 25px;
right: -20px;
bottom: -20px;
}
.project-overlay{
position: absolute;
left: 10px;
top: 10px;
bottom: 0;
transition: .5s;
background-color: rgb(76, 72, 68);
transition: .5s ease;
width: 100%;
height: 100%;
opacity: 0;
& p{
position: absolute;
font-size: 20px;
top: 45%;
width: 100%;
text-align: center;
color: #fff;
transition: .5s;
opacity: 0;
}
}
&:hover .project-overlay{
cursor: pointer;
opacity: 1;
z-index: 1;
}
&:hover .project-overlay p{
cursor: pointer;
display: block;
opacity: 1;
z-index: 1;
}
}
A: Based on your codepen, it doesn't seem like the 3rd and 6th modals are the problem with the styles displaying. The real problem is that all the content in your modals are absolutely positioned which takes them out of the ordinary context of the document, which causes the project-borders containers to have a height that only consists of the borders. You'll need to define a fixed height for that container for things to display correctly like so...
.project-borders {
position: relative;
border: 2px solid #000;
height: 209px;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65271351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parsing dl tag using Jsoup I am trying to parse a <dl> tag using Jsoup. The <dl> tag contains <dt> tags and <dd> tags. I have a HashMap (HashMap<String, List<String>) in which I want to put the <dt>s as keys and <dd>s as values (there are multiple <dd> tags per <dt> tag.
The HTML looks like this:
<dl>
<dt>
<span class="paramLabel">Parameters:</span>
</dt>
<dd>
<code>y</code> - the ordinate coordinate
</dd>
<dd>
<code>x</code> - the abscissa coordinate
</dd>
<dt>
<span class="returnLabel">Returns:</span>
</dt>
<dd>
the <i>theta</i> component of the point (<i>r</i>, <i>theta</i>) in polar coordinates that corresponds to the point (<i>x</i>, <i>y</i>) in Cartesian coordinates.
</dd>
I've tried the following:
String title = "";
List<String> descriptions = new ArrayList<>();
for (int i = 0; i < children.size(); i++) {
Element child = children.get(i);
if(child.tagName().equalsIgnoreCase("dt")) {
if(descriptions.size() != 0) {
block.fields.put(title, descriptions);
descriptions.clear();
}
title = child.text();
}
else if(child.tagName().equalsIgnoreCase("dd")) {
descriptions.add(child.text());
if(i == children.size() - 1) {
block.fields.put(title, descriptions);
}
}
}
I expected to get this:
* Parameters -> y - the ordinate coordinate
* x - the abscissa coordinate
* Returns -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.
But I got this:
* Parameters -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.
* Returns -> the theta component of the point (r, theta) in polar coordinates that corresponds to the point (x, y) in Cartesian coordinates.
A: You need to insert a copy of your descriptions list into the map, currently you manipulate 1 instance of the list. So instead of:
block.fields.put(title, descriptions);
create a new list, e.g.:
block.fields.put(title, new ArrayList<>(descriptions));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43497940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make links have the same distance I am trying to make a simple website and I need some help.
I have this div
<div id="header">
<?php require "./Pages/header.html"; ?>
</div>
And the header html:
<a href="index.php?p=home">Home</a>
<a href="index.php?p=shopinfo">Shop Information</a>
<a href="index.php?p=products">Products</a>
<a href="index.php?p=cart">Cart</a>
<a href="index.php?p=login">Login</a>
<a href="index.php?p=contact">Contact</a>
I want something like this:
Home Shop Information Products Cart Login Contact
where Home will be at the beggining of the div and Contact will be at the end of the div and all these links will have the same distance, but I dont want to use spaces.
A: Make use of ul
<ul>
<li><a href="index.php?p=home">Home</a></li>
<li><a href="index.php?p=shopinfo">Shop Information</a></li>
<li><a href="index.php?p=products">Products</a></li>
<li><a href="index.php?p=cart">Cart</a></li>
<li><a href="index.php?p=contact">Contact</a></li>
</ul>
CSS
ul li
{
display:inline;
padding:5px;
}
Here is the Demo
A: There are a lot of options. You can use margin-right or padding.
JS-fiddle:
http://jsfiddle.net/7Uq9y/
<a href="index.php?p=home">Home</a>
<a href="index.php?p=shopinfo">Shop Information</a>
<a href="index.php?p=products">Products</a>
<a href="index.php?p=cart">Cart</a>
<a href="index.php?p=login">Login</a>
<a href="index.php?p=contact">Contact</a>
css:
a{
margin-right: 50px;
}
A: Can you try using <nav> tag
<nav>
<a href="index.php?p=home">Home</a>
<a href="index.php?p=shopinfo">Shop Information</a>
<a href="index.php?p=products">Products</a>
<a href="index.php?p=cart">Cart</a>
<a href="index.php?p=login">Login</a>
<a href="index.php?p=contact">Contact</a>
</nav>
CSS:
nav {
display:block;
margin-left:auto;
margin-right:auto;
}
A: CSS Using your existing html/php code :
div#header a {
margin-right: 10px;
width: 150px;
display: inline-block;
}
A: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Test Website</title>
<style>
#menubar{
position: relative;
margin: 25px auto;
padding-top: 20px;
width: 900px;
height: 100px;
list-style: none;
background: rgba(0,0,0,0.8);
color: #ffffff;
border-left: 2px solid #010000;
border-right: 2px solid #010000;
}
#menubar ul {
margin-top:15px;
}
#menubar ul li{
display: inline;
margin: 25px 10px 15px 15px;
padding: 25px;
}
#menubar ul li a{
font-weight: bold;
text-decoration: none;
color: #ffffff;
font-size: 15px;
}
#menubar ul li a:hover{
border-bottom: 2px solid #ffffff;
transition: opacity .5s ease-in;
opacity: 1;
}
</style>
</head>
<body>
<div id="menubar">
<ul>
<li><a href="index.php?p=home">Home</a></li>
<li><a href="index.php?p=shopinfo">Shop Information</a></li>
<li><a href="index.php?p=products">Products</a></li>
<li><a href="index.php?p=cart">Cart</a></li>
<li><a href="index.php?p=login">Login</a></li>
<li><a href="index.php?p=contact">Contact</a></li>
</ul>
</div>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20817406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unknown column 'Username' in 'where clause' mysql_select_db($database_binary, $binary);
$query_account = sprintf("SELECT * FROM users WHERE Username = %s", GetSQLValueString($colname_account, "text"));
$account = mysql_query($query_account, $binary) or die(mysql_error());
$row_account = mysql_fetch_assoc($account);
$totalRows_account = mysql_num_rows($account);
$maxRows_trade = 20;
$pageNum_trade = 0;
if (isset($_GET['pageNum_trade'])) {
$pageNum_trade = $_GET['pageNum_trade'];
}
$startRow_trade = $pageNum_trade * $maxRows_trade;
$colname_trade = "-1";
if (isset($_SESSION['MM_Username'])) {
$colname_trade = $_SESSION['MM_Username'];
}
mysql_select_db($database_binary, $binary);
$query_trade = sprintf("SELECT * FROM asset WHERE Username = %s", GetSQLValueString($colname_trade, "text"));
$query_limit_trade = sprintf("%s LIMIT %d, %d", $query_trade, $startRow_trade, $maxRows_trade);
$trade = mysql_query($query_limit_trade, $binary) or die(mysql_error());
$row_trade = mysql_fetch_assoc($trade);
if (isset($_GET['totalRows_trade'])) {
$totalRows_trade = $_GET['totalRows_trade'];
} else {
$all_trade = mysql_query($query_trade);
$totalRows_trade = mysql_num_rows($all_trade);
}
$totalPages_trade = ceil($totalRows_trade/$maxRows_trade)-1;
$maxRows_withdrawreq = 10;
$pageNum_withdrawreq = 0;
if (isset($_GET['pageNum_withdrawreq'])) {
$pageNum_withdrawreq = $_GET['pageNum_withdrawreq'];
}
$startRow_withdrawreq = $pageNum_withdrawreq * $maxRows_withdrawreq;
$colname_withdrawreq = "-1";
if (isset($_SESSION['Username'])) {
$colname_withdrawreq = $_SESSION['Username'];
}
mysql_select_db($database_binary, $binary);
$query_withdrawreq = sprintf("SELECT * FROM withdrawal WHERE Username = %s", GetSQLValueString($colname_withdrawreq, "text"));
$query_limit_withdrawreq = sprintf("%s LIMIT %d, %d", $query_withdrawreq, $startRow_withdrawreq, $maxRows_withdrawreq);
$withdrawreq = mysql_query($query_limit_withdrawreq, $binary) or die(mysql_error());
$row_withdrawreq = mysql_fetch_assoc($withdrawreq);
I am getting an error:
Unknown column 'Username' in 'where clause'
How can I solve it?
A: The asset and withdrawal tables do not have a column called Username. So add that column to these tables or change WHERE condition in the sql statement related to these tables.These sql statements refer to the Username column in the WHERE clause that does not exist:
SELECT * FROM **asset** WHERE **Username**
SELECT * FROM **withdrawal** WHERE **Username**
New CREATE statements including Username column:
CREATE TABLE asset ( Asset varchar(100) NOT NULL, optiontype varchar(200)
NOT NULL,
Invested varchar(200) NOT NULL, Username varchar(100) NOT NULL,
Entry Rate varchar(200) NOT NULL, Rate varchar(200) NOT NULL, Entry Time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Expiration Time varchar(200) NOT NULL, Status varchar(200) NOT NULL, Returns varchar(200) NOT NULL, Customer varchar(200) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8;
CREATE TABLE withdrawal ( id varchar(100) NOT NULL, Username varchar(100) NOT NULL,
Date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, Customer varchar(200) NOT NULL, Amount varchar(100) NOT NULL, currency varchar(100) NOT NULL, email varchar(100) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=armscii8;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45578690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Firebase storage upload stopped working on react-native I am using
"firebase": "^3.6.0",
"react": "15.3.2",
"react-native": "0.37.0",
"react-native-camera": "git+https://github.com/lwansbrough/react-native-camera.git",
"react-native-fetch-blob": "^0.10.0",
"react-native-vector-icons": "^3.0.0",
"react-native-video": "^0.9.0"
And i'm trying to upload a video recorded with react-native-video to firebase - this worked but suddenly it stopped working and now it doesn't succeed.
I'm using the following code where this.props.file.path looks something like this:
file:///storage/emulated/0/Pictures/vidid.mp4
accept = () => {
let rnfbURI = RNFetchBlob.wrap(this.props.file.path)
Blob
.build(rnfbURI, { type : 'video/mp4;'})
.then((blob) => {
// upload image using Firebase SDK
firebase.storage()
.ref()
.child('testImageName')
.put(blob, { contentType : 'video/mp4' })
.then((snapshot) => {
console.log(snapshot)
blob.close()
done()
})
})
}
I tried writing Firebase support, but then won't help me since this is a workaround.
My blob object looks like this:
{ listeners: {},
isRNFetchBlobPolyfill: true,
multipartBoundary: null,
_ref: 'file:///storage/emulated/0/Pictures/VID_20161113_142100.mp4',
_blobCreated: true,
_closed: false,
cacheName: 'blob-559cd5c4-e880-4742-a3fe-dfae7e1a0df0',
type: 'video/mp4;',
size: '3665375' }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40574378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to reuse objects between Automake program and tests targets? I have a non-recursive Makefile.am with something like the following:
SHARED_SRCS = src/bar.cpp src/baz.cpp
bin_PROGRAMS = foo
foo_SOURCES = src/main.cpp $(SHARED_SRCS)
foo_CXXFLAGS = -I$(srcdir)/src $(SOME_CFLAGS)
foo_LDADD = $(SOME_LIBS)
check_PROGRAMS = test1 test2 test3
TESTS = test1 test2 test3
test1_SOURCES = tests/test1.cpp $(SHARED_SRCS)
test2_SOURCES = tests/test2.cpp $(SHARED_SRCS)
test3_SOURCES = tests/test3.cpp $(SHARED_SRCS)
test1_CXXFLAGS = $(foo_CXXFLAGS)
test2_CXXFLAGS = $(foo_CXXFLAGS)
test3_CXXFLAGS = $(foo_CXXFLAGS)
test1_LDADD = $(foo_LDADD)
test2_LDADD = $(foo_LDADD)
test3_LDADD = $(foo_LDADD)
However, every target builds its own SHARED_SRCS, getting them built 4 times, even when sharing the same flags.
Is there a way to get them built without creating a convenience library, e.g. libbar.a or libtool's libbar.la?
A: No, there's not. The point is that you're not rebuilding the sources, you're rebuilding binaries.
What you can do is build an intermediate .o consisting only of the shared sources, and then use that in your tests, and binaries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28747475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to move changes as uncommitted from one branch to another on Git I want to move all changes that are in a branch relative to master to another branch.
I don't want them as commits just as changes so that i can modify them and remove some of the changes and commit as one. I don't want to retain the old committed history.
I tried git format-patch master --stdout > mypatch.path
and git apply
but that applies as commits which i can't modify after that.
A: I would do this to move the changes from branch1 to branch2:
git checkout branch2
git merge --squash branch1
No commit has been created or "copied" between the branches. The changes can be modified before committing if need be.
A: If I understand what you want to do correctly, one way would be to start with your first branch:
git checkout branch1
Create a new branch from there:
git checkout -b branch2
Reset back to master, which will remove any commits that were made on branch1, but leave the changes as unstaged:
git reset master
You can then modify the files further and commit them as one commit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27956431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Popup not working and no errors Popup.alert is not working using "ionic-framework: 2.0.0-alpha.42".
I am using "ionic-framework: 2.0.0-alpha.42" locally and "[email protected]" globally in NPM.
Using this document as an example.
this.popup.alert({
title: "New Friend!",
template: "Your friend, Obi wan Kenobi, just accepted your friend request!",
cssClass: 'my-alert'
}).then(() => {
console.log('Alert closed');
});
That code is not working. I do not see a popup and i do not see "Alert closed" ever shown in the console. I pull in "popup" through the constructor.
private popup: Popup;
constructor(popup: Popup) {
this.popup = popup;
}
A: I figured out the issue. You need to add
<ion-overlay></ion-overlay>
to your app.html. I saw that no where in the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35027248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to run a python script using the google API / Oauth function without needing to authenticate the account every time the script runs? Here is a quickpython script that I wrote to upload a file to Google Drive:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
upload_file_list = [#placeholderfilename]
for upload_file in upload_file_list:
gfile = drive.CreateFile({'parents': [{'id': '#placeholderdriveID'}]})
# Read file and set it as the content of this instance.
gfile.SetContentFile(upload_file)
gfile.Upload() # Upload the file.
This script works, but every time it runs it also opens a window to authenticate the account accessing the drive. My goal for this script is to run it every morning with no input. Is there a way to set up the API so I don't need to manually authenticate the account every time I access google drive? Or does Google not allow that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75525507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: is register_next_step_handler exist in aiogram? we have something like:
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start'])
def process_start(message):
text = 'start'
bot.send_message(message.chat.id, text)
bot.register_next_step_handler(message, process_mid)
def process_mid(message):
text = 'mid'
bot.send_message(message.chat.id, text)
bot.register_next_step_handler(message, process_end)
def process_end(message):
text = 'end'
bot.send_message(message.chat.id, text)
bot.polling(none_stop=True)
in pyTelegramBotAPI
this function is for when you ask user for like a number and after he/she sends num you process it in that special func that you mentioned
A: evgfilim1:
Hello. You need to use FSM, it's more flexible than register_next_step_handler.
Check the example: https://github.com/aiogram/aiogram/blob/dev-2.x/examples/finite_state_machine_example.py
The linked page won't break as the implementation is not going to change in aiogram 2.x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73240068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring MVC Test with Hamcrest: How compare a XML's node directly against a Java object I am working with:
*
*Spring MVC Test
*Hamcrest
For an item from a collection such as:
<collection>
<item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="persona">
<id>087</id>
<nombre>Leonardo</nombre>
<apellido>Jordan</apellido>
<fecha>1981-07-05</fecha>
</item>
....
The following works:
.andExpect(xpath("collection/item[1]").exists())
.andExpect(xpath("collection/item[1]/*").nodeCount(is(4)))
.andExpect(xpath("collection/item[1]/id").exists())
.andExpect(xpath("collection/item[1]/id").string(is("087")))
.andExpect(xpath("collection/item[1]/id").string(is(personasArray[0].getId())))
.andExpect(xpath("collection/item[1]/nombre").exists())
.andExpect(xpath("collection/item[1]/nombre").string(is("Leonardo")))
.andExpect(xpath("collection/item[1]/nombre").string(is(personasArray[0].getNombre())))
.andExpect(xpath("collection/item[1]/apellido").exists())
.andExpect(xpath("collection/item[1]/apellido").string(is("Jordan")))
.andExpect(xpath("collection/item[1]/apellido").string(is(personasArray[0].getApellido())))
I want to know if is possible do a direct comparison against an object and not for each field, consider an entity with 15 to 45 fields.
I need something like this:
.andExpect(xpath("collection/item[1]/*").how(is(personasArray[0])))
See the how part, it represents what is the correct method to use.
Same consideration for the path's String content.
A: It is possible to do such an assertion. But you'll need to write your custom ResultMatcher for that. I don't think it is a good idea to convert XML (nodes) to Java objects just to do a simple comparison in a unit test.
You may run into problems with XML namespace resolution or the Java hashCode equals contract if not implemented right.
Instead, you should use libraries that lets you focus on your unit tests and not on the details of a technology or a programming language.
I recommend you to use XMLUnit in your test. XMLUnit is a Java library for XML comparison.
The example below depicts how easy it is to compare a XML document with XMLUnit and a custom ResultMatcher.
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xmlunit.builder.Input;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.xmlunit.matchers.CompareMatcher.isSimilarTo;
@RunWith(SpringRunner.class)
@WebMvcTest(XmlUnitDemoTests.XmlUnitDemo.class)
public class XmlUnitDemoTests {
static final String XML_CONTENT = "<node1><node2 id=\"1\">text</node2></node1>";
@Autowired
MockMvc mockMvc;
@Test
public void xmlUnit() throws Exception {
mockMvc.perform(get("/xml"))
.andExpect(xml(XML_CONTENT));
}
static ResultMatcher xml(String bodyValue) {
return MockMvcResultMatchers.content().source(equalXml(bodyValue));
}
static Matcher equalXml(String value) {
return isSimilarTo(Input.fromString(value).build());
}
@SpringBootApplication
@RestController
static class XmlUnitDemo {
@RequestMapping(value = "xml", produces = "text/xml")
String xml() {
return XML_CONTENT;
}
}
}
Of course, you may load big XML files from classpath or select a node with XPatch before doing a comparison. Take a look at the XMLUnit documentation for more information on that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39476751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I pass a subdirectory path to the GunDB S3 storage driver so the same S3 bucket can be shared with non-Gun data? I see examples referencing a few parameters for the S3 storage driver for GunDB that look like this:
var Gun = require('gun');
var gun = Gun({
file: 'data.json',
s3: {
key: '', // AWS Access Key
secret: '', // AWS Secret Token
bucket: '' // The bucket you want to save into
}
});
I don't see a parameter to define a subdirectory/path within the S3 bucket, to facilitate sharing the bucket with non-GunDB data. Is there such an option/parameter?
A: @hillct there is an option called prefix, thank you for pointing out that the options aren't documented. Here is how to use it:
var Gun = require('gun');
var gun = Gun({
file: 'data.json',
s3: {
key: '', // AWS Access Key
secret: '', // AWS Secret Token
bucket: '', // The bucket you want to save into
prefix: 'gun/'
}
});
And just in case, here are some of the other options:
{
throttle: 15 // Throttle writes to S3 in 15 second intervals, keeps S3 API costs down.
batch: 10 // Or if there are more than 10 things in queue, don't wait.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41007311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to set values in a 2d numpy array given 1D indices for each row? In numpy you can set the indices of a 1d array to a value
import numpy as np
b = np.array([0, 0, 0, 0, 0])
indices = [1, 3]
b[indices] = 1
b
array([0, 1, 0, 1, 0])
I'm trying to do this with multi-rows and an index for each row in the most programmatically elegant and computationally efficient way possible. For example
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
indices = [[1, 3], [0, 1], [0, 3]]
The desired result is
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])
I tried b[indices] and b[:,indices] but they resulted in an error or undesired result.
From searching, there are a few work arounds, but each tends to need at least 1 loop in python.
Solution 1: Run a loop through each row of the 2d array. The draw back for this is that the loop runs in python, and this part won't take advantage of numpy's c processing.
Solution 2: Use numpy put. The draw back is put works on a flattened version of the input array, so the indices need to be flattened too, and altered by the row size and number of rows, which would use a double for loop in python.
Solution 3: put_along_axis seems to only be able to set 1 value per row, so I would need to repeat this function for the number of values per row.
What would be the most computationally and programatically elegant solution? Anything where numpy would handle all the operations?
A: In [330]: b = np.zeros((3,5),int)
To set the (3,2) columns, the row indices need to be (3,1) shape (matching by broadcasting):
In [331]: indices = np.array([[1,3],[0,1],[0,3]])
In [332]: b[np.arange(3)[:,None], indices] = 1
In [333]: b
Out[333]:
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])
put along does the same thing:
In [335]: b = np.zeros((3,5),int)
In [337]: np.put_along_axis(b, indices,1,axis=1)
In [338]: b
Out[338]:
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])
A: On solution to build the indices in each dimension and then use a basic indexing:
from itertools import chain
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
# Find the indices along the axis 0
y = np.arange(len(indices)).repeat(np.fromiter(map(len, indices), dtype=np.int_))
# Flatten the list and convert it to an array
x = np.fromiter(chain.from_iterable(indices), dtype=np.int_)
# Finaly set the items
b[y, x] = 1
It works even for indices lists with variable-sized sub-lists like indices = [[1, 3], [0, 1], [0, 2, 3]]. If your indices list always contains the same number of items in each sub-list then you can use the (more efficient) following code:
b = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
indices = np.array(indices)
n, m = indices.shape
y = np.arange(n).repeat(m)
x = indices.ravel()
b[y, x] = 1
A: Simple one-liner based on Jérôme's answer (requires all items of indices to be equal-length):
>>> b[np.arange(np.size(indices)) // len(indices[0]), np.ravel(indices)] = 1
>>> b
array([[0, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0]])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72341143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set the active profile when creating Spring context programmatically? tl;dr: how to create a Spring context based on an annotation-based configuration class, while supplying active profiles?
I am trying to create a Spring context using a class with the configuration specified using annotations.
org.springframework.context.ApplicationContext context =
new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );
However when it starts up it crashes because it cannot find a required bean, but that bean does exist : albeit only under a certain profile "myProfile".
How do I specify the active profile? I have a feeling I need to use one the org.springframework.context.annotation.AnnotationConfigApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory) constructor but I'm not sure which ones is appropriate.
PS- I am not using Spring Boot, but am on Spring 4.2.4.RELEASE.
A: If you want classpath:resources/application-${spring.profiles.active}.yml to be working, setting system properties before refreshing is the way to go.
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
applicationContext.scan("com.sample");
applicationContext.refresh();
A: This should do the trick...
final AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.getEnvironment().setActiveProfiles( "myProfile" );
appContext.register( com.initech.ReleaserConfig.class );
appContext.refresh();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40268574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Javascript variable & ajax ; with JsonForm. Using .jsonForm() with a variable I'm using JsonForm: https://github.com/joshfire/jsonform/wiki#wiki-getting-started
I'm trying to load a form schema into $('form').Jsonfrom(), from an external .txt file,
attempting this by loading it into my .html file with ajax, putting it in a javascript variable , then calling $('form').Jsonfrom() with a click event .
Here is my code:
<script>
#Load in .txt to javascript variable using ajax
var stringData = $.ajax({
url: "schema.txt",
async: false
}).responseText;
#check that file is loaded correctly .- have check this works.
#alert(stringData);
#on clicking of a piece of text in a <p> wrapper call jsonForm function.
$(document).ready(function(){
$("p").click(function(){
$('form').jsonForm(stringData )
});
});
</script>
the error I'm getting in firebug is:
"TypeError: this.formDesc.schema is undefined"
& my stack trace is this:
http://tinypic.com/r/2uiybo4/5
Think my problem may be in the way in loading in the .txt file with ajax.
however if I comment in: alert(stringData); . . . the scheme for the for is displayed perfectly.
Like so: http://tinypic.com/r/2ynl9qh/5
Also there is no problem with the scheme, as i have tried putting it directly into in $('form').Jsonfrom("here") & it works fine.
A: Managed to solve this .
had to use a templating language (jinja2) instead of ajax, to get my form schema into my html document.. so that json form ( a jquery form builder) couple execute on a full html doc on the page loading .
Silly !
Hope this helps .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17490318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Checking DB health in github actions Im running a container with mssql, and want to know if the DB is healthy after a set of second, cant figure out how to return the value of this step that has the docker inspect command in it
docker inspect --format={{.State.Health.Status}} test-db
so I can tell it in a next step, ex. the output == 'healthy' and if this is true then go forward with the steps onto build down the line..
I dont know the format and my head is starting to explode.
If anyone could help me understand how to do this?
EDIT:
I know im close:
EDIT:
solution was to use those damned single quotes or the $() docker inspect --format={{.State.Health.Status}} test-db
A: try surrounding the {{ with single quote like
docker inspect --format='{{.State.Health.Status}}' test-db
and executing in the if condition like:
if [[ $(docker inspect --format='{{.State.Health.Status}}' test-db) == "healthy" ]]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73662127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get functions called with GDB I am using GDB to understand a C++ program. I put a break in the middle of the running which turns to be something like:
break main.cpp:500
and I would like to see which functions have been called before. I tried "backtrace" but it shows only info about main, as previous calls to previous functions have already finished.
My question is how can I get (with GDB or another method) the info about which functions have been called before this point, even if the call has been returned.
Thanks
A: A gdb script might be a solution for your problem.
Create a script that puts break point to each possibly called function.
At break prints the stack with 'bt' and continue the execution.
You should put an other break point to main.cpp:500 to quit from debugging.
b 'main.cpp::500'
commands 1
detach
quit
end
break 'A::f1()'
break 'A::f2()'
while true
continue
bt
end
You can start the script like this:
gdb --command ./gdbscript.gdb fpmanager
If you have too much possibly called function you can grep the code to find all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2764020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Label the midpoint of a segment in ggplot In the plot below I'd like to label the arrows with the text in bar$lbl. I'd like to do so in a way that would keep any labels from overlapping (they wouldn't in the simple example below). I'd prefer not to calculate the label position by hand.
I'm familiar with getting pretty, non-overlapping labels on points with ggrepel and curious if there is a similar way to label the midpoints of segments?
Any advice appreciated.
library(ggplot2)
foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
y1=c(0.1,0.9),y2=c(0.6,0.5),
lbl=c("Arrow 1", "Arrow 2"))
p1 <- ggplot(data=foo,aes(x=x,y=y))
p1 <- p1 + geom_point(color="grey")
p1 <- p1 + geom_segment(data=bar,aes(x=x1, xend=x2, y=y1, yend=y2),
size = 0.75,arrow = arrow(length = unit(0.5, "cm")))
p1
A: I know you would prefer not to calculate the mid points by hand, however, it is often easier to work with variables inside the aesthetics then with statistics, so I did it calculating the midpoints before hand and mapping to the axis
library(ggplot2)
library(directlabels) # provides a geom_dl that works easier with labels
foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
y1=c(0.1,0.9),y2=c(0.6,0.5),
midx = c(0.45, 0.1), # x mid points
midy = c(0.35, 0.7), # y midpoints
lbl=c("Arrow 1", "Arrow 2"))
p1 <- ggplot(data=foo,aes(x=x,y=y))
p1 <- p1 + geom_point(color="grey")
p1 <- p1 + geom_segment(data=bar,aes(x=x1, xend=x2, y=y1, yend=y2),
size = 0.75,arrow = arrow(length = unit(0.5, "cm")))
p1 + geom_dl(data = bar, aes(x = midx, y = midy, label = lbl),
method = list(dl.trans(x = unit(x, 'cm'), y = unit(y, 'cm'))))
A: Here are two ways to do it with a lot of tidying. You don't need to do anything by hand if you think about the fact that the midpoint has coordinates that are just the means of x values and the means of y values of the 2 endpoints. First way is to tidy your data frame, calculate the midpoints, then make it wide again to have x and y columns. That data frame goes into ggplot, so it's passed through all the geoms, but we override with data arguments to geom_point and geom_segment. geom_segment gets just the original copy of the bar data frame.
library(tidyverse)
foo <- data.frame(x=runif(50),y=runif(50))
bar <- data.frame(x1=c(0.2,0),x2=c(0.7,0.2),
y1=c(0.1,0.9),y2=c(0.6,0.5),
lbl=c("Arrow 1", "Arrow 2"))
bar %>%
gather(key = coord, value = value, -lbl) %>%
mutate(coord = str_sub(coord, 1, 1)) %>%
group_by(lbl, coord) %>%
summarise(value = mean(value)) %>%
ungroup() %>%
spread(key = coord, value = value) %>%
ggplot() +
geom_point(aes(x = x, y = y), data = foo, color = "grey") +
geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = bar, size = 0.75, arrow = arrow(length = unit(0.5, "cm"))) +
geom_text(aes(x = x, y = y, label = lbl))
But maybe you don't want to do all that piping at the beginning, or you have to do this several times, so you want a function to calculate the midpoints. For the second version, I wrote a function that does basically what was piped into ggplot in the first version. You supply it with the bare column name where your labels are kept, which is the column it will be grouped on. Then you can just use that in your geom_text.
## cool function!
tidy_midpt <- function(df, lbl_col) {
lbl_quo <- enquo(lbl_col)
df %>%
gather(key = coord, value = value, -!!lbl_quo) %>%
mutate(coord = str_sub(coord, 1, 1)) %>%
group_by(lbl, coord) %>%
summarise(value = mean(value)) %>%
ungroup() %>%
spread(key = coord, value = value)
}
ggplot(data = bar) +
geom_point(aes(x = x, y = y), data = foo, color = "grey") +
geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), size = 0.75, arrow = arrow(length = unit(0.5, "cm"))) +
geom_text(aes(x = x, y = y, label = lbl), data = . %>% tidy_midpt(lbl))
Created on 2018-05-03 by the reprex package (v0.2.0).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50163855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MongoDB findOneAndUpdate not updating So, I've been working with MongoDB for a couple days, I have been doing a per-server mute role command but when I was doing the set muterole command, when using findOneAndUpdate function, it doesn't seem to update the values, I've been searching for other answers and I've tried multiple of them, yet it doesn't seem to work, this is my code:
muteSchema.findOne(
{
guildId: message.guild.id
}, async (err, data) => {
if(err) console.log(err)
if(data)
{
muteSchema.findOneAndUpdate(
{
guildId: data.guildId
},
{
guildId: message.guild.id,
roleId: role.id
}
)
}
else
{
data = new muteSchema(
{
guildId: message.guild.id,
roleId: role.id
}
)
data.save().catch((err) => console.log(err) )
}
}
)
I do have the muteSchema import on top and this is my muteSchema file:
const mongoose = require("mongoose")
let MuteroleSchema = mongoose.Schema(
{
guildId: String,
roleId: String
},
{
strict: false
}
)
module.exports = mongoose.model("muterole", MuteroleSchema)
The values are registered the first time it is used, but they don't update once they are there.
A: You are making things too complex for yourself. Why do you first find then again find and then update?
Simply go with the following flow
Update using filter
Code Sample:
exports.updateToken = async (id, forgotToken) => {//function
return User.updateOne({ _id: id }, { resetPasswordToken: forgotToken });//_id:id is a filter while the reset is code to update
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69368210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sound sequence on iphone - best practice? I'd like to make a sound sequencer on iPhone, almost like "dropphone" LINK
So I would need to
*
*play multiple samples (1~6seconds) at the same time
*keeping them synchronized with an NSTimer.
*being able to stop them / change the global volume
I've tried 2 approaches but I'm not that convinced :
*
*AVAudioPlayer
Downside: I get half a second lag when I want to play a sound
*AudioServices
Downside: I can't control/stop the sounds once they're launched
Is there another method to handle sounds that would be optimized to play overlapping sounds?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6495406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Uncaught TypeError: Cannot read property 'tcp' of undefined in chrome extension I am trying to develop an extension in chrome which can snoop browser history and send it to a remote machine. I need to establish socket connection for transporting data.
But I am getting the above error. Read a lot of posts online which say there must be errors in the manifest file in context with socket permissions. Can anyone find out the error? Please check the code beneath.
Manifest File:
{
"manifest_version": 2,
"name": "Browser History Snooping",
"description": "This extension snoops browser history and sends it to a remote machine",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"history"
],
"sockets": {
"tcp": {
"connect": ""
}
}
}
JavaScript
var histories = [];
var visits = [];
chrome.history.search({
text: '',
maxResults: 0
}, function (historyItems) {
var historiesProcessed = 0;
for (var i = 0; i < historyItems.length; i++) {
//histories.push(historyItems[i]);
console.log(historyItems[i]);
chrome.history.getVisits({
url: historyItems[i].url
}, function (visitItems) {
for (var i = 0; i < visitItems.length; i++) {
visits.push(visitItems[i]);
}
historiesProcessed++;
if (historiesProcessed === historyItems.length) {
console.log(visits.length + ' visits');
}
});
}
console.log(histories);
});
chrome.sockets.tcp.create({}, function (createInfo) {
chrome.sockets.tcp.connect(createInfo.socketId, '127.0.0.1', 8888,
function (result) {
if (result >= 0) {
console.log('Successfully connected');
}
});
});
A: The error is self-explanatory: chrome.sockets is undefined.
There's no sockets API in the extension documentation, but it is defined for the chrome apps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32400490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SAME70 read external interrupt polarity in ISR I'm currently working on a SAME70 board made by Atmel. I plugged on it an extention OLED1 board (Atmel too) on EXT1 port. My goal is to recover the information about interrupt type (falling or raising) when I'm pressing the button 3 on OLED1 board. I have a function which allows me to set the different registers related to an interrupts. But unfortunately the register which indicates the polarity (FLHSR) stay always at 0 whatever the state of the button.
Below my code.
#include <asf.h>
void set_Interupt_Pin()
{
uint32_t mask = 1 << 19; /*bitmasking*/
PIOA->PIO_IER = mask; /*enable interruptions*/
PIOA->PIO_AIMER = mask; /*add new interruption*/
PIOA->PIO_ESR = mask; /*set interrupt source on edge*/
PIOA->PIO_REHLSR = mask; /* set interrupt to rising edge*/
PIOA->PIO_FELLSR= mask; /* set interrupt to falling edge*/
NVIC_DisableIRQ(ID_PIOA);
NVIC_ClearPendingIRQ(ID_PIOA);
NVIC_EnableIRQ(ID_PIOA); /*set NVIC to get interruptions from PIOA*/
NVIC_SetPriority(ID_PIOA, 4); /*priority 4*/
}
void PIOA_Handler(void)
{
printf("FRLHSR: %x\n",PIOA->PIO_FRLHSR); /*state of polarity event */
printf("ISR: %x\n",PIOA->PIO_ISR);
printf("ELSR: %x\n",PIOA->PIO_ELSR);
printf("AIMMR: %x\n",PIOA->PIO_AIMMR);
}
int main(void)
{
const usart_serial_options_t usart_serial_options = {
.baudrate = CONF_UART_BAUDRATE,
.charlength = CONF_UART_CHAR_LENGTH,
.paritytype = CONF_UART_PARITY,
.stopbits = CONF_UART_STOP_BITS
};
sysclk_init();
board_init();
stdio_serial_init(CONF_UART, &usart_serial_options);
set_Interupt_Pin();
while(1){}
}
You can see here the result of print when I press button (first part) and I release button (second part).
Best regards
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68755878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write MDS business rules directly in SQL I'm using Master Data Services to check business rules in SQL. The use of MDS makes it easy for any (non-coder) to add business rules. However, I initially need to add a large amount of business rules and this is a very tedious procedure in MDS.
Is there a way to write the MDS business rules directly in code and add them to the MDS database?
A: There are quite a couple of stored procedures used for updating the MDS, but is is quite difficult to figure out how to use them. (And you can mess up the model if used incorrectly)
Easier would be to try the Business Rules Create method.
This is where you can get started with webservices:
http://sqlblog.com/blogs/mds_team/archive/2010/01/12/getting-started-with-the-web-services-api-in-sql-server-2008-r2-master-data-services.aspx
This is where the method is defined:
https://msdn.microsoft.com/en-us/library/microsoft.masterdataservices.services.servicecontracts.iservice.businessrulescreate(v=sql.120).aspx
You will need to weigh your options whether it would be faster to figure out how to do one of the above, or just knuckle down and create the business rules. MDS 2016 is much more user friendly than the previous versions when creating business rules(fyi)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37136659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The ~ prefix in Objective C I've been learning core audio on the iPhone, and when looking through Apple's sample code I found this:
#include <AudioToolbox/AudioToolbox.h>
#include "CAStreamBasicDescription.h"
#include "CAXException.h"
#define kNumberBuffers 3
class AQPlayer
{
public:
AQPlayer();
~AQPlayer();
OSStatus StartQueue(BOOL inResume);
OSStatus StopQueue();
OSStatus PauseQueue();
AudioQueueRef Queue() { return mQueue;}
CAStreamBasicDescription DataFormat() const { return mDataFormat; }
Boolean IsRunning() const { return (mIsRunning) ? true : false; }
Boolean IsInitialized() const { return mIsInitialized; }
CFStringRef GetFilePath() const { return (mFilePath) ? mFilePath : CFSTR(""); }
Boolean IsLooping() const { return mIsLooping; }
void SetLooping(Boolean inIsLooping) { mIsLooping = inIsLooping; }
void CreateQueueForFile(CFStringRef inFilePath);
void DisposeQueue(Boolean inDisposeFile);
private:
UInt32 GetNumPacketsToRead() { return mNumPacketsToRead; }
SInt64 GetCurrentPacket() { return mCurrentPacket; }
AudioFileID GetAudioFileID() { return mAudioFile; }
void SetCurrentPacket(SInt64 inPacket) { mCurrentPacket = inPacket; }
void SetupNewQueue();
AudioQueueRef mQueue;
AudioQueueBufferRef mBuffers[kNumberBuffers];
AudioFileID mAudioFile;
CFStringRef mFilePath;
CAStreamBasicDescription mDataFormat;
Boolean mIsInitialized;
UInt32 mNumPacketsToRead;
SInt64 mCurrentPacket;
UInt32 mIsRunning;
Boolean mIsDone;
Boolean mIsLooping;
static void isRunningProc( void * inUserData,
AudioQueueRef inAQ,
AudioQueuePropertyID inID);
static void AQBufferCallback( void * inUserData,
AudioQueueRef inAQ,
AudioQueueBufferRef inCompleteAQBuffer);
void CalculateBytesForTime( CAStreamBasicDescription & inDesc,
UInt32 inMaxPacketSize,
Float64 inSeconds,
UInt32 *outBufferSize,
UInt32 *outNumPackets);
};
Does anyone know what this line does: ~AQPlayer();
I haven't seen the symbol ~ used before.
A: This is not a c related. It looks like c++ in which case the ~ is the desctructor for the class. You might want to read about destructors in the C++ FAQ
A: This is a C++ class, not an Objective-C class. The ~ symbol is used to declare or define a destructor method, a method that is automatically called when an instance's lifetime ends. The destructor method of a C++ class is used in the same way that a dealloc method is used in Objective-C classes (to clean up resources, and so on). The difference is that in Objective-C, dealloc is not invoked until it has no owners (i.e. all owners have relinquished their ownership by sending release).
If you wish to know what this code does, perhaps ask a C++ crowd, although, from a quick glance, it looks like an audio player utilising Apple's AudioToolbox framework.
A: That looks like C++ to me. It is supported on iOS, so that's why you’re seeing it.
A: That is c++ code, to develop with these from Objective-C you'd use Objective-C++. Files with .mm are Obj-c++ and .m are just standard obj-c.
A: thats the destructor. in C++ the destructors are as this, while this code looks more like C++, in objective C you can write the destructor with "~"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5136300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dragonruby-game-toolkit Excerpt from their website:
DragonRuby Game Toolkit is a professional grade (yet beginner-friendly) 2D game engine. It's tiny (~3MB), fast as hell, and cross-platform (including consoles).
So what's so great about DragonRuby Game Toolkit?
*
*Dirt simple APIs capable of creating complex 2D games.
*Fast as hell. Powered by highly-optimized C code written by Ryan C. Gordon, one of the core contributors of SDL (a library that powers every commercial game engine in the world).
*Battle-tested by Amir Rajan, a critically acclaimed indie game dev.
Tiny. Like really tiny. The entire engine is a few megabytes.
Hot loaded, realtime coding, optimized to provide constant feedback to the dev. Productive and an absolute joy to use.
*Turnkey builds for Windows, MacOS, and Linux with seamless publishing to Itch.io.
*Cross platform: PC, Mac, Linux, iOS, Android, Nintendo Switch, XBOX One, and PS4 (mobile and console compilation requires a business entity, NDA verification, and a Professional GTK License, contact us).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63506549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I use a multiline footer in TCPDF? // Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-15);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 10, 'Seite '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
Right now my footer looks like this:
]
But I need a more komplex footer with multiple lines:
]
How can I achieve this?
I tried to solve it with this stack overflow suggestion:
TCPDF Multiple Footers
But I had no success.
A: Try using MultiCell with some cell width combination, like this:
public function Footer() {
// Make more space in footer for additional text
$this->SetY(-25);
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 10, 'Seite '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
// New line in footer
$this->Ln(8);
// First line of 3x "sometext"
$this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
$this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
$this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
// New line for next 3 elements
$this->Ln(4);
// Second line of 3x "sometext"
$this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
$this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
$this->MultiCell(55, 10, 'Sometext', 0, 'C', 0, 0, '', '', true, 0, false, true, 10, 'M');
// and so on...
}
You can see more examples of how to use MultiCell function in TCPDF official examples: https://tcpdf.org/examples/example_005/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42553709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Overriding parameterized methods in Scala Note: I apologise for altering this question, previously I wan't able to express the exact issue I am facing.
Let's say we have an abstract parameterized class abs,
abstract class abs[T] {
def getA(): T
}
class ABS[Int] extends abs[T] {
override def getA(): Int = 4
}
gives the following incomprehensible error:
<console>:28: error: type mismatch;
found : scala.Int(4)
required: Int
override def getA(): Int = 4
^
I want to override the method getA.
Also an explanation or some helpful link would be really appreciated.
A: With the current base method signature this is impossible since generics are erased.
Take a type tag (I also renamed the method's T to U to prevent confusion because of shadowing):
abstract class abs[T] {
def getA[U: TypeTag](): U
}
class ABS[T] extends abs[T] {
override def getA[U]()(implicit tag: TypeTag[U]): U = {
if (tag == typeTag[Int]) new Integer(1)
else if (tag == typeTag[Char]) new Character('1')
else throw new Exception("bad type")
}.asInstanceOf[U]
}
A: Maybe you want something like this
abstract class Abs[T] {
def getA: T
def getA(i: T): T
}
class Absz extends Abs[Int]{
override def getA = 4
override def getA(i: Int) = i
}
(new Absz()).getA //> res0: Int = 4
(new Absz()).getA(3) //> res1: Int = 3
A: You can do it with Shapeless polymorphic functions: https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0
import shapeless._
object Abs extends Poly0{
implicit def caseInt = at[Int](4)
implicit def caseChar = at[Char]('4')
}
println(Abs.apply[Int])
println(Abs.apply[Char])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27551454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In Javascript While loop repeats last number when counting from 1 to 5 when run on console When running following code on console:
var counter=0; while(counter<5){ console.log(counter); counter++; }
console o\p:
0
1
2
3
4
4
whereas for following code works fine, without repeating last value:
for(var i=0; i<5; i++){ console.log(i); }
console o\p:
0
1
2
3
4
Now, if I place above for loop after above mentioned while loop , output is perfectly fine:
var counter=0; while(counter<5){ console.log(counter); counter++; }
for(var i=0; i<5; i++){ console.log(i); }
console o\p:
0
1
2
3
4
0
1
2
3
4
whereas, if I place while loop after for loop , repetition of last number found.
for(var i=0; i<5; i++){ console.log(i); }
var counter=0;while(counter<5){ console.log(counter); counter++; }
console o\p:
0
1
2
3
4
0
1
2
3
4
4
Request all to provide a reason on this unexpected behavior of while loop.
Thanks.
A: When performing operations in the console, the return value of the last executed line is always output.
That means that simply writing
var counter = 0; ++counter;
will log 1 to the console.
The same is happening in your loop, the return value of the last counter++ is output to the console as the value of the last executed expression.
A: The output of the log method depends on the javascript engine of the browser. The last value printed is not output of the loop itself.
Try: var counter=0; while(counter<5){ console.log(counter++); }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31434942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: R convert nested values to new columns and rows With a dataframe like the following:
currencyDetails = c("Dollar:40, Euro:80, valid",
"Yen:400, Pound:50",
"Dollar:40, Pound:50, currency",
NA)
Can someone recommend a method to append to that dataframe new columns and rows that correspond to the pairs and values in the each row please? The number of pairs or values in each string is not fixed, and not ordered.
For sample output:
Dollar = c(40,NA,NA,NA)
Pound = c(NA,50,50,NA)
Euro = c(80,NA,NA,NA)
Yen = c(NA,400,NA,NA)
valid = c(1,0,0,0)
currency = c(0,0,1,0)
df = data.frame(Dollar, Pound, Euro,Yen,valid, currency)
cbind(currencyDetails, df)
currencyDetails Dollar Pound Euro Yen valid currency
1 Dollar:40, Euro:80, valid 40 NA 80 NA 1 0
2 Yen:400, Pound:50 NA 50 NA 400 0 0
3 Dollar:40, Pound:50, currency NA 50 NA NA 0 1
4 <NA> NA NA NA NA 0 0
I think it's different to the supplied previous answers as there's the extra complexity of splitting out the key:value pair, it's not that each element is turned into a column name as is. For example, Pound:50 is not the column, Pound is, with 50 as it's value.
A: Try this solution:
splitted<-trimws(unlist(strsplit(aDataFrame,",")))
t(bind_rows(sapply(splitted[grep(":",splitted)],strsplit,split=":")))
[,1] [,2]
Dollar:40 "Dollar" "40"
Euro:80 "Euro" "80"
Yen:400 "Yen" "400"
Pound:50 "Pound" "50"
Update
df<-data.frame(t(bind_rows(sapply(splitted[grep(":",splitted)],strsplit,split=":"))))
> library(reshape2)
> acast(df, X2 ~ X1)
Using X2 as value column: use value.var to override.
Dollar Euro Pound Yen
40 40 <NA> <NA> <NA>
400 <NA> <NA> <NA> 400
50 <NA> <NA> 50 <NA>
80 <NA> 80 <NA> <NA>
Levels: 40 400 50 80
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49997610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Finding objects between two dates Okay so I have a parse database with two keys (startedAt) and (endedAt) basically I would like to return all the objects between these two given times. However, I store the times as strings, not dates. I would really like to not have to change them to dates as that would force me to rework code in a lot of other parts of my program. So is it possible to do the following
NSDate *leftDate = leftClassRoomAfterDatePicker.date;
NSDate *arrivedDate = arrivedBeforeDatePicker.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM-dd hh:mm"];
NSString *leftDateString = [dateFormat stringFromDate:leftDate];
NSString *arrivedDateString = [dateFormat stringFromDate:arrivedDate];
NSLog(leftDateString);
NSLog(arrivedDateString);
PFQuery *query = [PFQuery queryWithClassName:@"PassData"];
[query whereKey:@"startTime" greaterThan:leftDate];
[query whereKey:@"timeArrived" lessThan:arrivedDate];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
NSLog(@"Successfully retrieved %d objects.", objects.count);
}];
When I run this code I get the following error
The problem is that the strings are not returning the correct value. In my parse database I have a value of startTime: Dec 08, 18:28
and endTime: Dec 08, 18:28
But it still does not work (no objects are returned). I think this is because the greaterthan/lessthan functions will not work on strings like this.
A:
Error: startTime contains string values but got a date (Code: 102,
Version: 1.2.21)
The error clearly indicates that you are comparing two different objects one is string and second one is date. So there are two things you can either convert any one into date or string. So to implement the same in a easy way, you can write one category with function which will convert either into date or string and use that method to perform the comparison.
A: You've converted leftDate and arrivedDate to leftDateString and arrivedDateString, but you're still using leftDate and arrivedDate in your query. I think you meant to write:
PFQuery *query = [PFQuery queryWithClassName:@"PassData"];
[query whereKey:@"startTime" greaterThan:leftDateString];
[query whereKey:@"timeArrived" lessThan:arrivedDateString];
in which case you'd no longer get the error since you'd be comparing string to string.
Although I generally recommend that you store and sort your dates with NSDate objects, in this case where your format is in the same descending order of importance as a typical NSDate sort of month, day, hour, then minute, i.e. "MM-dd hh:mm", as long as year or seconds don't matter to you and as long as the queried time format matches the database time format, this query should work since greaterThan and lessThan will compare the string objects alphabetically/numerically.
A: I guess for that to work you have to have Date fields in database, then you pass NSDate to whereKey: on iOS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27369238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Set max time a user can be logged in, regardless of their activity I'm working on a blue green pattern for a system with continuous delivery. I would like to force the users to switch server after 30 min. I'm developing my application in JSF 2. Is there an easy way to make the sessions end after a certain time no matter if the user is active or not?
A: Implement a filter which does basically the following job:
HttpSession session = request.getSession();
if (session.isNew()) {
session.setAttribute("start", System.currentTimeMillis());
}
else {
long start = (Long) session.getAttribute("start");
if (System.currentTimeMillis() - start > (30 * 60 * 1000)) {
session.invalidate();
response.sendRedirect("expired.xhtml");
return;
}
}
chain.doFilter(request, response);
Map this on the servlet name or URL pattern of interest.
This is only sensitive to changes in system clock, make sure that your server runs UTC all the time. Otherwise better grab System#nanoTime() instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10685488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Optimizing a set 20 webrequests with threads This is for ASP.NET. I want to improve the time it takes run my function, today it takes around 20-30 seconds, more towards 30secs than 20secs though. That's running on one thread making 20 webrequests.
I'm thinking threads that do all the 20 webreqeusts, in order to quickly find the result or just go through the data (IE do all the 20 requests not finding anything).
Here's how it works.
1. I'm using html agility pack to fetch htmldocuments. 2. Then I parse them for information 3. Lastly I add that information to a dictionary OR I move on to the next webrequest until I reach 20 requests made.
I make at most 20 webRequests, at minimum 1. I have set the function to end when the info I'm searching for is found. Sometimes the info isn't there hence the 20 webrequests(it goes through all the data).
Every webrequest adds between 5-20 entries to the dictionary. This is then compared with the information I sent to it, if it's in the list I get the Key back, otherwise it returns 201. If found it gets added to the database.
QUESTIONS
*A:*If I want to do this with threads, how many should I create? 20 One for each request and let them all loose to do the job? Or should i create like 4 of them making at most 5 requests each?B: What if two threads are finished at the same time and wants to add info to the directory, can it lock the whole site(I'm using ASP.NET), or will it try to add one from thread A and then one result from Thread B? I have a check already today that checks if the key exists before adding it.
C:What would be the fastest way to this?
This is my code, depicting the loop which just shows that 20 requests are being made?
public void FetchAndParseAllPages()
{
int _maxSearchDepth = 200;
int _searchIncrement = 10;
PageFetcher fetcher = new PageFetcher();
for (int i = 0; i < _maxSearchDepth; i += _searchIncrement)
{
string keywordNsearch = _keyword + i;
ParseHtmldocuments(fetcher.GetWebpage(keywordNsearch));
if (GetPostion() != 201)
{ //ADD DATA TO DATABASE
InsertRankingData(DocParser.GetSearchResults(), _theSearchedKeyword);
return;
}
}
}
A: *
*.NET allows only 2 requests open at the same time. If you want more than that, you need to configure it in web.config. Look here: http://msdn.microsoft.com/en-us/library/aa480507.aspx
*You can the Parallel.For method which is very straightforward and handles the "how much threads" for you. Of course you can tweak it to set how much threads (or tasks) you want with ParallelOptions. Look here: http://msdn.microsoft.com/en-us/library/dd781401.aspx
*For making a thread-safe dictionary you can use the ConcurrentDictionary. Look here: http://msdn.microsoft.com/en-us/library/dd287191.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13220432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extract a complex String from between two Strings I have a String which contains the following sub string:
[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]
I'd like to extract the part between [Text: and ] i.e. PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1.
How do I do this?
A: Pattern p = Pattern.compile("\\[Text:(.*?)\\]");
Matcher m = p.matcher("[Qual:3] [Text:PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1] [Elem:123]");
m.find();
System.out.println(m.group(1));
Gives:
PIX 1252471471953/YHYF/PPP121.40/10RTY10/NOLXX08X1
The \\[ and \\] are to escape the brackets, which are special characters in regexes. The .*? is a non-greedy quantifier, so it stops gobbling up characters when it reaches the closing bracket. This part of the regex is given inside a capturing group (), which you can access with m.group(1).
A: Use the following string as the regex:
"\\[Text:(.*?)\\]"
The first capture group will give you exactly the substring you want.
The non-greedy match (.*?) is required to make it stop at the first ] rather than also including [Elem:123].
A: String.substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
You could use this to remove the start and end of the string,
or....
You could use
String.indexOf(String str)
To get the index of the start and end of the match and copy the contents to a new result string.
You could use
String.matches(String regex)
However writing regular expressions can get difficult,
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
I hope this helps.
A: Instead of using "\\[Text:(.*?)\\]", as others have suggested, I'd go one step further and use lookarounds to filter out the text you don't want:
(?<=\\[Text:).*?(?=\\])
This will match exactly the text you want without having to select a capturing group.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9379784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to design an installer so it can be used in automated acceptance tests Background:
We have a windows installer which simply installs and starts our custom WinForms installation program. This custom installer does the real installation: creating an IIS Web Application, copying dlls, installing database, etc...
We now want to write some automated acceptance tests, which will include installing the software using the same installation procedure as we use in production. We want to start by running the acceptance tests every night on a dedicated machine, and later as part of a continuous integration pipeline.
Problem:
It is proving difficult to automate the WinForms installation program. And we do not want special installation code for the acceptance tests.
Question:
What advice do you clever people have for integrating the deployment process into an automated test?
I suspect that the decision to use WinForms for the installer was a bad choice - particularly because the resulting application does not clearly separate the UI code from the real installation code.
A: My recommendation would be to use an MSI based installer instead of trying to roll your own using Windows Forms. Look into using the Windows Installer XML (WiX) toolset which is a popular free open source toolset for creating installers.
Using MSI has many advantages, in particular it makes it fairly difficult to mix installer logic and UI (kind of like falling into the pit of success) and so making an unattended installer suitable for running on a remote machine is a piece of cake.
If you are already committed to your current installation method then you need to work on separating your UI and logic to the point where you can run an installation without showing any UI - its difficult to give any specific advice on how to do this without a more concrete example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7337120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.