id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23526500
|
In React, the picture tag does not work. It is written in plain html in JSX. No functions, no variables, etc. Just plain hard coded tags.
It had failed to load local images as well as online images.
I had copied the very same html in the JSX file and pasted into an html file. The html file rendered without fail.
This is the code snippet below was the that could render in a html file but not a jsx file through React.
<picture className="dice">
<source id="img512" className="img512" media="" srcSet="./512x512.png" />
<source id="img256" className="img256" media="" srcSet="./256x256.png" />
<source id="img144" className="img144" media="" srcSet="./144x144.png" />
<source id="img96" className="img96" media="" srcSet="./96x96.png" />
<img src="./512x512.png" alt="Icon" />
</picture>
I have tried a single source tag. I have tried removing every attribute exluding srcSet. I have tried using src instead of srcSet and also tried srcset. All have failed rendering an image. The only thing that rendered was the alt text.
Am I missing something here? Is there something that React doesn't like what I have done here?
Here is a link of the post I initially had read before posting:
picture tag in React
Update:
So as "Jesper We" mentioned I be using className instead of class. I personally already knew that this was a common mistake and would have caught this mistake. Since I posted the wrong code early I had ran the code again for the sake of confirmation. Still a no pictures unfortunately
I worked towards "Robin's" comment and check out his suggestion. I copied the code he provided in the link and pasted it into my code. Everything was working. Then I filled in the media queries of my original code. Oddly enough it did not work. Then I used other online images then those images worked. I had tried both png and jpg images and the both worked. Then I used my own images again that were png images and none of them worked.
Now it looks like there something wrong with the images I have but I think problem now no longer revolves around the code. I hope...
A: You need to modify your code, then it will work perfectly, see this code
https://stackblitz.com/edit/react-jessyq
Resize the output window, you will see the different images for different sizes. Hope your problem will be solved. HAPPY CODING :)
picture tag is used for responsive image, As far i know image will be change according to device width. For this purpose you should use picture tag with media query like this
<picture>
<source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
<source media="(min-width: 465px)" srcset="img_white_flower.jpg">
<img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>
For Details: https://www.w3schools.com/tags/tag_picture.asp
And you can't use class in react, use className instead of class.
A: <picture>
<source media="(min-width: 650px)" srcset="logo.png" width="170" height="100"/>
<img src="smallLogo.png" alt="smallLogo" width="50" height="50" />
</picture>
| |
doc_23526501
|
- (void) handlePanGesture: (UIPanGestureRecognizer*) sender
{
CGPoint foo = [sender translationInView:XXX];
}
Now when I place the cursor at the point marked as XXX and press Esc to get a list of completion suggestions, Xcode happily suggests all sensible symbols regardless of their type (including NSArray*, CGSize, or even SEL). Since Xcode presumably has enough information to know the argument type, why doesn’t it filter the suggestions down to only those compatible with UIView*?
| |
doc_23526502
|
What I would like to do is to take the value of the Elimn field for one record (where Account = 1113) and copy it to the record where Account = 3104 (I am off setting Receivables from one company with payable from the other) Is there any way to do this?
I was thinking of using a variable, BUT I cannot seem to figure out how to put a calculated field into a variable when it would require such a complex Select statement (using joins and multiple fields and calculations)
I DO NOT want to save the data!! PLEASE do not give me an answer with Alter table or Insert etc. I only want to display the results.
Any ideas??
Current output:
Account AcctName Ccode Balance Elmin
1112 Accounts Receivable - (U.S.) C 1250923.94 0
1112 Accounts Receivable (U.S.) U 0 0
1113 Accounts Receivable - I/C U 223780.55 223780.55
3104 Accounts Payable - I/C C -254000 0
Would like:
Account AcctName Ccode Balance Elmin
1112 Accounts Receivable - (U.S.) C 1250923.94 0
1112 Accounts Receivable (U.S.) U 0 0
1113 Accounts Receivable - I/C U 223780.55 223780.55
3104 Accounts Payable - I/C C -254000 223780.55
Code:
SELECT T1.Account, T2.AcctName, 'U' AS Ccode, SUM(T1.Debit - T1.Credit) AS 'Balance',
CASE
WHEN T1.Account IN (1113) THEN SUM(T1.Debit - T1.Credit) ELSE 0
END AS Elmin
FROM OJDT AS T0 INNER JOIN
JDT1 AS T1 ON T0.TransId = T1.TransId INNER JOIN
OACT AS T2 ON T1.Account = T2.AcctCode
WHERE (CAST(T0.RefDate AS date) >= @Start_Date) AND (CAST(T0.RefDate AS date) <= @End_Date) AND (T2.GroupMask IN ('1', '2', '3'))
GROUP BY T1.Account, T2.AcctName, T2.GroupMask, T2.FatherNum
union all
SELECT T1.Account, T2.AcctName, 'C' AS Ccode, SUM(T1.Debit - T1.Credit) AS 'Balance',
CASE WHEN T1.Account IN (1251) THEN SUM(T1.Debit - T1.Credit) ELSE 0
END AS Elmin
FROM CANADACO.dbo.OJDT AS T0 INNER JOIN
CANADACO.dbo.JDT1 AS T1 ON T0.TransId = T1.TransId INNER JOIN
CANADACO.dbo.OACT AS T2 ON T1.Account = T2.AcctCode
WHERE (CAST(T0.RefDate AS date) >= @Start_Date) AND (CAST(T0.RefDate AS date) <= @End_Date) AND (T2.GroupMask IN ('1', '2', '3'))
GROUP BY T1.Account, T2.AcctName, T2.GroupMask, T2.FatherNum
ORDER BY T1.Account
A: You could wrap to those subqueries into common table expressions (CTE's). This would give you separate result sets to combine with union all and cross apply.
Sample data
Simplified data, but the Elmin can still be a calculated field.
declare @Database1Table table
(
Account int,
Ccode nvarchar(1),
Elmin money
);
insert into @Database1Table (Account, Ccode, Elmin) values
(1112, 'U', 0.0),
(1113, 'U', 223780.55);
declare @Database2Table table
(
Account int,
Ccode nvarchar(1),
Elmin money
);
insert into @Database2Table (Account, Ccode, Elmin) values
(1112, 'C', 0.0),
(3104, 'C', 0.0);
Simplified query, Elmin is calculated as a sum:
select d1.Account, d1.Ccode, sum(d1.Elmin) as Elmin
from @Database1Table d1
group by d1.Account, d1.Ccode
union all
select d2.Account, d2.Ccode, sum(d2.Elmin) as Elmin
from @Database2Table d2
group by d2.Account, d2.Ccode
order by d1.Account;
Current result:
Account Ccode Elmin
----------- ----- ---------------------
1112 C 0,00
1112 U 0,00
1113 U 223780,55
3104 C 0,00
Solution
Move the subqueries in two CTE's (cte_d1 and cte_d2). Use a cross apply to fetch the replacement value for the Account=3104 row (case expression).
with cte_d1 as
(
select d1.Account, d1.Ccode, sum(d1.Elmin) as Elmin
from @Database1Table d1
group by d1.Account, d1.Ccode
),
cte_d2 as
(
select d2.Account, d2.Ccode, sum(d2.Elmin) as Elmin
from @Database2Table d2
group by d2.Account, d2.Ccode
)
select c1.Account, c1.Ccode, c1.Elmin
from cte_d1 c1
union all
select c2.Account, c2.Ccode, case c2.Account when '3104' then c4.Elmin else c2.Elmin end as Elmin
from cte_d2 c2
outer apply ( select top 1 c3.Elmin
from cte_d1 c3
where c3.Account = '1113' ) c4
order by c1.Account;
This gives:
Account Ccode Elmin
----------- ----- ---------------------
1112 C 0,00
1112 U 0,00
1113 U 223780,55
3104 C 223780,55
| |
doc_23526503
|
I followed some tutorials and created a web application project, then created a web service client. Netbeans created an index.jsp file, where I can access the webservice perfectly, but I want to access the webservice thru a java class.
I created a java class file where I put the same code I have in the jsp page and I get the error :
"Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at: http://...... It failed with:
Invalid WSDL http://..... , expected {http:// schemas.xmlsoap. org/wsdl/}definitions found HTML at (lineLine number = 1"
If I debug the jsp page, I get no errors, but I can't compile in java class. I don't understand!
This is my jsp code that works perfectly:
<%-- start web service invocation --%>
<%
try {
com.epq.tipocambio.TipoCambio service = new com.epq.tipocambio.TipoCambio();
com.epq.tipocambio.TipoCambioSoap port = service.getTipoCambioSoap();
com.epq.tipocambio.InfoVariable result = port.tipoCambioDia();
Float cambio = result.getCambioDolar().getVarDolar().get(0).getReferencia();
out.println("Cambio = " + cambio);
} catch (Exception ex) {
//TODO handle custom exceptions here
System.out.println(ex);
}
%>
And this is my java class code that is giving me the errors:
package com.epq.tipocambio;
public class EPQTipoCambioDia {
private static InfoVariable tipoCambioDia() {
com.epq.tipocambio.TipoCambio service = new com.epq.tipocambio.TipoCambio();
com.epq.tipocambio.TipoCambioSoap port = service.getTipoCambioSoap();
return port.tipoCambioDia();
}
public static void main(String[] args){
InfoVariable c = EPQTipoCambioDia.tipoCambioDia();
Float cambio = c.getCambioDolar().getVarDolar().get(0).referencia;
System.out.print(cambio);
}
}
Any Ideas of what could be the problem?
| |
doc_23526504
|
A: As per JavaDocs of EmptyInterceptor, the onSave method receives "id" as parameter. See here:http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/EmptyInterceptor.html
So, you can use that id value.
I am assuming you have created interceptor similar to the way explained here: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html
A: In my case I was need to get filled entity. When we add entity to collection (e.g., HashSet), this entities changes own state during interceptor lifecycle. So, I just added entity to HashSet and then in afterTransactionCompletion() get entities from HashSet. Entity was fully filled and has an Id.
| |
doc_23526505
|
The problem is the bool snap is going to be false the code doesnt execute any line below DataSnapshot snapshot = task.Result;. But if DataSnapshot snapshot = task.Result; returns 1 result, it works fine.
void CheckUser()
{
reference.Child("Stars").Child("Users").Child(login).LimitToFirst(1)
.GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
info.text = "falha";
}
else if (task.IsCompleted)
{
//info.text = task.Result.ToString();
DataSnapshot snapshot = task.Result;
//info.text = snapshot.ToString();
bool snap = snapshot.Exists;
info.text = snap.ToString();
if (snap)
{
info.text = "login existente, selecione outro sff";
}
else
{
info.text = "falha 4 ";
writeLogin();
}
// Do something with snapshot...
}
else
{
info.text = "falha 3 ";
}
}
);
}
A: void CheckUser()
{
reference.Child("Stars").Child("Users")
.GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
info.text = "Verifique a Internet e tente de novo";
}
else if (task.IsCompleted)
{
//info.text = task.Result.ToString();
IDictionary snapshot = (IDictionary) task.Result.Value;
bool snap = false;
if (snapshot[login]!= null)
{
snap = true;
}
Debug.Log(snap.ToString());
if (snap)
{
info.text = "login existente, selecione outro sff";
}
else
{
//info.text = "falha 4 ";
writeLogin();
}
// Do something with snapshot...
}
else
{
info.text = "Verifique a Internet e tente de novo";
}
});
}
| |
doc_23526506
|
// Create Top Right JPanel and JList
String[] listB = { "Some content on the right panel", "More content", "Some more content", "More and more content", "More and more content", "More and more content",
"More and more content", "More and more content", "More and more content", "More and more content", "More and more content", "More and more content", "More and more content", "More and more content",
"More and more content" };
final JList listBottom = new JList(listB);
listBottom.setVisibleRowCount(12);
JScrollPane scrollPaneB = new JScrollPane(listBottom);
panelBottom.add(scrollPaneB);
scrollPaneB.setViewportView(listBottom);
scrollPaneB.setBorder(BorderFactory.createTitledBorder("Bottom Panel"));
scrollPaneB.setVisible(true);
//listBottom.setVisible(true);
listBottom.setBorder(BorderFactory.createLoweredBevelBorder());
// Create Top Right Action Listener
listBottom.addListSelectionListener(new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent arg0) {
Selection selectionB = (Selection)listBottom.getSelectedValue();
textField.setText(selectionB.getContents());
}
});
A: You simply add a mouseClicked listener, and check if the mouse clicks the JList.
String[] listB = { "Some content on the right panel", "More content", "Some more content", "More and more content", "More and more content", "More and more content",
"More and more content", "More and more content", "More and more content", "More and more content", "More and more content", "More and more content", "More and more content", "More and more content",
"More and more content" };
final JList listBottom = new JList(listB);
....//other code
listBottom.addMouseListener(new MouseAdapter(){
//Called when you click the JList
public void mouseClicked(MouseEvent e) {
JList list = (JList)e.getSource();
//Makes sure it only registers for single clicks(always registers even on double clicks, just registers twice.)
if (e.getClickCount() == 1) {
//Gets the point where you clicked and returns the index of the element at that point
int index = list.locationToIndex(e.getPoint());
//Makes sure that where you clicked was an element and that it is a String(We know it will be but its better to be safe)
if(list.getModel().getElementAt(index) != null&&list.getModel().getElementAt(index) instanceof String){
//Populates your textField with the element at this index
textField.setText(list.getModel().getElementAt(index));
}
}
}
});
Hope it helps!
A:
I am trying to populate a JTextArea from a JList when the user double clicks the item.
When designing a GUI the user should be able to use the mouse or the keyboard to invoke an Action on a component.
Check out List Action. It will invoke an Action when you double click or use the Enter key. All you have to do is create the Action.
| |
doc_23526507
|
I added a new column by fetching URLs:
"http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + escape(value, "url")
Then the resulting JSON is as follows:
{ "results" : [ { "address_components" : [ { "long_name" : "44", "short_name" : "44", "types" : [ "street_number" ] }, { "long_name" : "Homer Street", "short_name" : "Homer St", "types" : [ "route" ] }, { "long_name" : "London", "short_name" : "London", "types" : [ "locality", "political" ] }, { "long_name" : "Greater London", "short_name" : "Gt Lon", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "United Kingdom", "short_name" : "GB", "types" : [ "country", "political" ] }, { "long_name" : "W1H 4NW", "short_name" : "W1H 4NW", "types" : [ "postal_code" ] }, { "long_name" : "London", "short_name" : "London", "types" : [ "postal_town" ] } ], "formatted_address" : "44 Homer Street, London, Greater London W1H 4NW, UK", "geometry" : { "location" : { "lat" : 51.51981750, "lng" : -0.16534040 }, "location_type" : "ROOFTOP", "viewport" : { "northeast" : { "lat" : 51.52116648029151, "lng" : -0.1639914197084980 }, "southwest" : { "lat" : 51.51846851970851, "lng" : -0.1666893802915020 } } }, "types" : [ "street_address" ] } ], "status" : "OK" }
After browsing through a few blogs to find the relevant code, I then tried transforming the column using this...
value.parseJson().results[0]["formatted_address"]
...which works great for the full address.
The problem occurs when I try to extract the postcode. I tried fiddling around and got nowhere, then I downloaded JSONPad and pasted the JSON into a tree map to get the path:
value.parseJson().results[0]["address_components"][5]["long_name"]
The problem is that this extracts the postcode perfectly for some entries, and not so perfectly for others, where it extracts something else - town or country, for example.
Changing the [5] to [6] seems to extract the postcodes for the other addresses, but is there a way to extract ONLY the postcode, regardless of where it falls in the structure?
Any help much appreciated!
A: What you'd probably have to do is loop over the structs in the address_components array, checking the "types" of each one. When types contains "postal_code", then tada, that's your postcode.
Something like the following code (which worked for me):
<script type="text/javascript">
var stuData =
{
"results": [{
"address_components": [{
"long_name": "44",
"short_name": "44",
"types": ["street_number"]
}, {
"long_name": "Homer Street",
"short_name": "Homer St",
"types": ["route"]
}, {
"long_name": "London",
"short_name": "London",
"types": ["locality", "political"]
}, {
"long_name": "Greater London",
"short_name": "Gt Lon",
"types": ["administrative_area_level_2", "political"]
}, {
"long_name": "United Kingdom",
"short_name": "GB",
"types": ["country", "political"]
}, {
"long_name": "W1H 4NW",
"short_name": "W1H 4NW",
"types": ["postal_code"]
}, {
"long_name": "London",
"short_name": "London",
"types": ["postal_town"]
}
],
"formatted_address": "44 Homer Street, London, Greater London W1H 4NW, UK",
"geometry": {
"location": {
"lat": 51.51981750,
"lng": -0.16534040
},
"location_type": "ROOFTOP",
"viewport": {
"northeast": {
"lat": 51.52116648029151,
"lng": -0.1639914197084980
},
"southwest": {
"lat": 51.51846851970851,
"lng": -0.1666893802915020
}
}
},
"types": ["street_address"]
}
],
"status": "OK"
};
var myPostcode;
for (var i = 0; i < stuData.results[0].address_components.length; i++) {
for (var j = 0; j < stuData.results[0].address_components[i].types.length; j++) {
if (stuData.results[0].address_components[i].types[j] == "postal_code") {
myPostcode = stuData.results[0].address_components[i].long_name;
break;
}
}
}
console.log(myPostcode);
</script>
A: You could translate duncan's answer from Javascript to Python and use it with the Jython interpreter or you could use the following GREL expression (which I posted to Google Groups in response to your query):
filter(forEach(value.parseJson().results[0].address_components,c,if(c.types[0]=='postal_code',c.long_name,'')),v,v!='')[0]
Of course, this all presumes that you're using this data for display on a Google Map, per the API's Terms of Service.
| |
doc_23526508
|
Is there any way that this can be enabled? I have tried adding the allowFullScreen tag (see below) to the iframe tag but that doesn't seem to make any difference:
function getIframeHtml(url) {
return '<div class="wrapper full-size"><iframe src="' +
app.sanitizer.sanitizeUrl(url || '') +
'" frameborder="0" allowFullScreen="allowFullScreen" class="full-size"></iframe></div>';
}
A: It seems to be infeasible, since it is not explicitly allowed by App Script:
| |
doc_23526509
|
For example, at 00:20, I get data timestamped 00:10; at 00:35, I get from 00:20; at 00:50, I get from 00:40. So the interval that I can get new data "fixed" (every 15 minutes), although the interval on timestamps change slightly.
I am trying to consume this data on Dataflow (Apache Beam) and for that I am playing with Sliding Windows. My idea is to collect and work on 4 consecutive datapoints (4 x 15min = 60min), and ideally update my calculation of sum/averages as soon as a new datapoint is available. For that, I've started with the code:
PCollection<TrafficData> trafficData = input
.apply("MapIntoSlidingWindows", Window.<TrafficData>into(
SlidingWindows.of(Duration.standardMinutes(60)) // (4x15)
.every(Duration.standardMinutes(15))) . // interval to get new data
.triggering(AfterWatermark
.pastEndOfWindow()
.withEarlyFirings(AfterProcessingTime.pastFirstElementInPane()))
.withAllowedLateness(Duration.ZERO)
.accumulatingFiredPanes());
Unfortunately, looks like when I receive a new datapoint from my input, I do not get a new (updated) result from the GroupByKey that I have after.
Is this something wrong with my SlidingWindows? Or am I missing something else?
A: One issue may be that the watermark is going past the end of the window, and dropping all later elements. You may try giving a few minutes after the watermark passes:
PCollection<TrafficData> trafficData = input
.apply("MapIntoSlidingWindows", Window.<TrafficData>into(
SlidingWindows.of(Duration.standardMinutes(60)) // (4x15)
.every(Duration.standardMinutes(15))) . // interval to get new data
.triggering(AfterWatermark
.pastEndOfWindow()
.withEarlyFirings(AfterProcessingTime.pastFirstElementInPane())
.withLateFirings(AfterProcessingTime.pastFirstElementInPane()))
.withAllowedLateness(Duration.standardMinutes(15))
.accumulatingFiredPanes());
Let me know if this helps at all.
A: So @Pablo (from my understanding) gave the correct answer. But I had some suggestions that would not fit in a comment.
I wanted to ask whether you need sliding windows? From what I can tell, fixed windows would do the job for you and be computationally simpler as well. Since you are using accumulating fired panes, you don't need to use a sliding window since your next DoFn function will already be doing an average from the accumulated panes.
As for the code, I made changes to the early and late firing logic. I also suggest increasing the windowing size. Since you know the data comes every 15 minutes, you should be closing the window after 15 minutes rather than on 15 minutes. But you also don't want to pick a window which will eventually collide with multiples of 15 (like 20) because at 60 minutes you'll have the same problem. So pick a number that is co-prime to 15, for example 19. Also allow for late entries.
PCollection<TrafficData> trafficData = input
.apply("MapIntoFixedWindows", Window.<TrafficData>into(
FixedWindows.of(Duration.standardMinutes(19))
.triggering(AfterWatermark.pastEndOfWindow()
// fire the moment you see an element
.withEarlyFirings(AfterPane.elementCountAtLeast(1))
//this line is optional since you already have a past end of window and a early firing. But just in case
.withLateFirings(AfterProcessingTime.pastFirstElementInPane()))
.withAllowedLateness(Duration.standardMinutes(60))
.accumulatingFiredPanes());
Let me know if that solves your issue!
EDIT
So, I could not understand how you computed the above example, so I am using a generic example. Below is a generic averaging function:
public class AverageFn extends CombineFn<Integer, AverageFn.Accum, Double> {
public static class Accum {
int sum = 0;
int count = 0;
}
@Override
public Accum createAccumulator() { return new Accum(); }
@Override
public Accum addInput(Accum accum, Integer input) {
accum.sum += input;
accum.count++;
return accum;
}
@Override
public Accum mergeAccumulators(Iterable<Accum> accums) {
Accum merged = createAccumulator();
for (Accum accum : accums) {
merged.sum += accum.sum;
merged.count += accum.count;
}
return merged;
}
@Override
public Double extractOutput(Accum accum) {
return ((double) accum.sum) / accum.count;
}
}
In order to run it you would add the line:
PCollection<Double> average = trafficData.apply(Combine.globally(new AverageFn()));
Since you are currently using accumulating firing triggers, this would be the simplest coding way to solve the solution.
HOWEVER, if you want to use a discarding fire pane window, you would need to use a PCollectionView to store the previous average and pass it as a side input to the next one in order to keep track of the values. This is a little more complex in coding but would definitely improve performance since constant work is done every window, unlike in accumulating firing.
Does this make enough sense for you to generate your own function for discarding fire pane window?
| |
doc_23526510
|
Unfortunately, .setData always returns an OverflowError related to libshiboken:
RuntimeWarning: libshiboken: Overflow: Value [1000 2000 3000 4000] exceeds limits of type [signed] "int" (4bytes).
When I try exactly the same code without a pg.GraphicsLayout, it works fine. So the GraphicsLayout seems to have some effect on the PlotItem objects that I don't understand and find in the source code.
Here are my two minimal working examples:
Single plot:
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
pg.mkQApp()
pw = pg.GraphicsView()
pw.show()
# layout
l = pg.PlotItem()
pw.setCentralWidget(l)
# first data and plot
x = np.array([1000, 2000, 3000, 4000])
y1 = np.array([5*10**4, 6*10**4, 7*10**4, 8*10**4])
p1 = l.plot(x, y1)
# second data and setData
x = np.array([1000, 2000, 3000, 4000])
y1 = np.array([5*10**5, 6*10**5, 7*10**5, 8*10**5])
p1.setData(x,y1)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
Multi-plot that isn't working:
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
pg.mkQApp()
pw = pg.GraphicsView()
pw.show()
# layout
l = pg.GraphicsLayout()
pw.setCentralWidget(l)
p1 = pg.PlotItem()
p2 = pg.PlotItem()
l.addItem(p1, row=0, col=0)
l.addItem(p2, row=1, col=0)
# first data and plot
x = np.array([1000, 2000, 3000, 4000])
y1 = np.array([5*10**4, 6*10**4, 7*10**4, 8*10**4])
y2 = np.array([0,5,7,9])
p1.plot(x, y1, pen=pen)
p2.plot(x, y2, pen=pen)
# second data and setData
x = np.array([1000, 2000, 3000, 4000])
y1 = np.array([5*10**4, 6*10**4, 7*10**4, 8*10**4])
y2 = np.array([0,5,7,9])
p1.setData(x,y1)
p2.setData(x,y2)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
A: I just solved this same issue. The issue is that you are calling setData on p1 and p2, which are PlotItem objects. Instead, you need to call the setData method from PlotDataItem objects, which are returned when you call the plot method from the PlotItem objects (e.g. p1.plot(...))
For your multi-plot example, I believe it should look something like this:
p1_plotdataitem = p1.plot(x, y1, pen=pen)
...
p1_plotdataitem.setData(x, y1)
You can see that it's not so much that the multi-plotting isn't working - it's that you defined p1 as a PlotItem (incorrect) in the multi-plot example, while you defined p1 as a PlotDataItem (correct) in the single plot example.
From the source code, the plot method of PlotItem creates a PlotDataItem. The constructor for the PlotDataItem takes the passed-along parameters and calls its own setData using the passed-along parameters. This is why rendering the graph using the first plot call works. However, when the first update is attempted through a manual setData call, the wrong method is actually being used here.
I am not sure how PlotItem even has a setData method exposed since it's not defined in the PlotItem class or any of its parents (I may just be lacking some Python knowledge here).
I opened an issue here: https://github.com/pyqtgraph/pyqtgraph/issues/1585
| |
doc_23526511
|
$ ./configure --help | grep -i ucs
--enable-unicode[=ucs[24]]
Searching the official documentation, I found this:
sys.maxunicode: An integer giving the
largest supported code point for a
Unicode character. The value of this
depends on the configuration option
that specifies whether Unicode
characters are stored as UCS-2 or
UCS-4.
What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.
The code is expected to work on Python 2.6+.
A: It's 0xFFFF (or 65535) for UCS-2, and 0x10FFFF (or 1114111) for UCS-4:
Py_UNICODE
PyUnicode_GetMax(void)
{
#ifdef Py_UNICODE_WIDE
return 0x10FFFF;
#else
/* This is actually an illegal character, so it should
not be passed to unichr. */
return 0xFFFF;
#endif
}
The maximum character in UCS-4 mode is defined by the maxmimum value representable in UTF-16.
A: When built with --enable-unicode=ucs4:
>>> import sys
>>> print sys.maxunicode
1114111
When built with --enable-unicode=ucs2:
>>> import sys
>>> print sys.maxunicode
65535
A: I had this same issue once. I documented it for myself on my wiki at
http://arcoleo.org/dsawiki/Wiki.jsp?page=Python%20UTF%20-%20UCS2%20or%20UCS4
I wrote -
import sys
sys.maxunicode > 65536 and 'UCS4' or 'UCS2'
A: sysconfig will tell the unicode size from the configuration variables of python.
The buildflags can be queried like this.
Python 2.7:
import sysconfig
sysconfig.get_config_var('Py_UNICODE_SIZE')
Python 2.6:
import distutils
distutils.sysconfig.get_config_var('Py_UNICODE_SIZE')
A: I had the same issue and found a semi-official piece of code that does exactly that and may be interesting for people with the same issue: https://bitbucket.org/pypa/wheel/src/cf4e2d98ecb1f168c50a6de496959b4a10c6b122/wheel/pep425tags.py?at=default&fileviewer=file-view-default#pep425tags.py-83:89.
It comes from the wheel project which needs to check if the python is compiled with ucs-2 or ucs-4 because it will change the name of the binary file generated.
A: Another way is to create an Unicode array and look at the itemsize:
import array
bytes_per_char = array.array('u').itemsize
Quote from the array docs:
The 'u' typecode corresponds to Python’s unicode character. On narrow Unicode builds this is 2-bytes, on wide builds this is 4-bytes.
Note that the distinction between narrow and wide Unicode builds is dropped from Python 3.3 onward, see PEP393. The 'u' typecode for array is deprecated since 3.3 and scheduled for removal in Python 4.0.
A: 65535 is UCS-2:
Thus code point U+0000 is encoded as the number 0, and U+FFFF is encoded as 65535 (which is FFFF16 in hexadecimal).
| |
doc_23526512
|
The variable mydatadf contains a very simple representative example of my actual data.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
mydata = dict()
participant = ['participantA', 'participantB']
for p in participant:
ses = dict()
session = ['ses_1', 'ses_2']
for s in session:
series = dict()
set = ['s_1', 's_2', 's_3']
for se in set:
reps = dict()
rep = ['r_1', 'r_2', 'r_3', 'r_4', 'r_5']
for r in rep:
vars = dict()
vars = {'var1': np.sin(np.random.rand(1000)*2),
'var2': np.sin(np.random.rand(1000)*2)}
varsdf = pd.DataFrame(data=vars)
reps[r] = vars
series[se] = reps
ses[s] = series
mydata[p] = ses
mydatadf = pd.DataFrame(mydata)
How could I effectively average (for example) var1 across the nesting levels reps, series, ses and/or participant?
Eventually, I would like to plot all var1 objects and highlight with different colours averaged data across any desired nesting level.
for p in mydatadf.keys():
for ses in mydatadf[p].keys():
for set in mydatadf[p][ses].keys():
for rep in mydatadf[p][ses][set].keys():
data = mydatadf[p][ses][set][rep]['var1']
plt.plot(data)
plt.show()
A: You can always flatten the dataframe and do standard groupby operations (I don't know if it is optimal, but it works):
df = pd.io.json.json_normalize(mydata) #this will give a nested dataframe
df_flat = pd.DataFrame(df.T.index.str.split('.').tolist()).assign(values=df.T.values)
df_flat.head(3)
>> 0 1 2 3 4 \
0 participantA ses_1 s_1 r_1 var1
1 participantA ses_1 s_1 r_1 var2
2 participantA ses_1 s_1 r_2 var1
values
0 [0.7267196257553268, 0.9822775511169437, 0.991...
1 [0.6633676714415264, 0.2823588336690545, 0.977...
2 [0.2211576389168905, 0.9399581790280525, 0.645...
Edit: to groupby and apply a function (say, mean):
# in this case I choose column 4, corresponding to 'var'.
# You can change the name of the column using df_flat.columns.rename
# note that I use np.hstack as you are dealing with a an array of arrays
column = 4
df_flat.groupby(column)['Values'].apply(lambda x: np.hstack(x).mean())
>> 4
var1 0.707803
var2 0.707821
Name: Values, dtype: float64
| |
doc_23526513
|
My input and label shape worked well when I use model.fit() without Kfold. But with Kfold in sklearn it throws an error. Below is my code.
input_ids = []
attention_masks = []
token_type_ids = []
all_data_labels = []
for all_sent, all_label in tqdm(zip(all_data["symptom"], all_data["label"]), total=len(all_data)):
try:
input_id, attention_mask, token_type_id = bert_tokenizer(all_sent, MAX_LEN)
input_ids.append(input_id)
attention_masks.append(attention_mask)
token_type_ids.append(token_type_id)
all_data_labels.append(all_label)
except Exception as e:
print(e)
print(all_sent)
pass
all_symptom_input_ids = np.array(input_ids, dtype=int)
all_symptom_attention_masks = np.array(attention_masks, dtype=int)
all_symptom_type_ids = np.array(token_type_ids, dtype=int)
all_symptom_inputs = (all_symptom_input_ids, all_symptom_attention_masks, all_symptom_type_ids)
all_data_labels = np.asarray(all_data_labels, dtype=np.int32)
class TFBertClassifier(tf.keras.Model):
def __init__(self, model_name, dir_path, num_class):
super(TFBertClassifier, self).__init__()
self.bert = TFBertModel.from_pretrained(model_name, cache_dir=dir_path)
self.dropout = tf.keras.layers.Dropout(self.bert.config.hidden_dropout_prob)
self.classifier = tf.keras.layers.Dense(num_class,
kernel_initializer=tf.keras.initializers.TruncatedNormal(self.bert.config.initializer_range),
name="classifier")
def call(self, inputs, attention_mask=None, token_type_ids=None, training=False):
outputs = self.bert(inputs, attention_mask=attention_mask, token_type_ids=token_type_ids)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output, training=training)
logits = self.classifier(pooled_output)
return logits
from keras.wrappers.scikit_learn import KerasClassifier
def create_model():
model = TFBertClassifier(model_name='bert-base-multilingual-cased',
dir_path='bert_ckpt',
num_class=num_classes)
optimizer = tf.keras.optimizers.Adam(5e-5)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy')
model.compile(optimizer=optimizer, loss=loss, metrics=[metric], experimental_run_tf_function=False)
return model
model = KerasClassifier(build_fn=create_model, epochs=150, batch_size=10, verbose=0)
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import cross_val_score, cross_validate
scoring = {'precision' : make_scorer(precision_score),
'recall' : make_scorer(recall_score),
'f1_score' : make_scorer(f1_score)}
kfold = model_selection.KFold(n_splits=10, shuffle=True, random_state=1234)
results = model_selection.cross_validate(estimator=model,
X=all_symptom_inputs,
y=all_data_labels,
cv=kfold,
scoring=scoring)
and below is the error. all inputs are shaped as [3,None] and I can't find why this error is thrown.
ValueError Traceback (most recent call last)
<ipython-input-24-9559fde88ed9> in <module>()
10 y=all_data_labels,
11 cv=kfold,
---> 12 scoring=scoring)
2 frames
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
210 if len(uniques) > 1:
211 raise ValueError("Found input variables with inconsistent numbers of"
--> 212 " samples: %r" % [int(l) for l in lengths])
213
214
ValueError: Found input variables with inconsistent numbers of samples: [3, 51134]
Can I get some help?
A: I think the issue is that your input is currently the tuple (all_symptom_input_ids, all_symptom_attention_masks, all_symptom_type_ids), but the KFold input is looking for an iterable where each element is a single example.
What you'd want to do is to convert the inputs to a list of tuples where each element is a single example.
all_symptom_inputs = np.array(list(zip(
all_symptom_input_ids,
all_symptom_attention_masks,
all_symptom_type_ids
)))
The above operation might be slow if you're input is very large, so I'd recommend trying something more efficient like numpy's stack function (I think np.stack(..., axis=-1). might work here).
| |
doc_23526514
|
<?php
// open a connection
$dhost = 'localhost';
$duser = 'user';
$dpw = 'pass';
$dname = 'db_name';
$connection = mysqli_connect($dhost, $duser, $dpw, $dname);
// test the connection
if(mysqli_connect_errno()){
die('Something went wrong with the database<br><br> '
. mysqli_connect_error() . ':'
. mysqli_connect_errno());
}
$query = "Isn't it nice that we don't have to escape ' characters all by ourselves?";
echo $query.'<br>';
$escaped = mysqli_real_escape_string($connection , $query);
echo $escaped.'<br>';
mysqli_query($connection,"INSERT into emp (name) VALUES ('$escaped')");
mysqli_close($connection);
?>
when I print $escaped variable it gives output like :
Isn\'t it nice that we don\'t have to escape \' characters all by ourselves?
But when I saw the database field I found this :
Isn't it nice that we don't have to escape ' characters all by ourselves?
| |
doc_23526515
|
SOAP-ERROR: Parsing WSDL: No address associated with <port>
This is the WSDL:
<definitions name="AritmeticaServicio"
targetNamespace="urn:Aritmetica"
xmlns:tns="urn:Aritmetica"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
<message name="AritmeticaPeticion">
<part name="operando1" type="xsd:float" />
<part name="operando2" type="xsd:float" />
</message>
<message name="AritmeticaRespuesta">
<part name="respuesta" type="xsd:float" />
</message>
<portType name="AritmeticaPort">
<operation name="sumar">
<input message="tns:AritmeticaPeticion" />
<output message="tns:AritmeticaRespuesta" />
</operation>
<operation name="restar">
<input message="tns:AritmeticaPeticion" />
<output message="tns:AritmeticaRespuesta" />
</operation>
</portType>
<binding name="AritmeticaBinding" type="tns:AritmeticaPort">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="sumar">
<soap:operation soapAction="urn:Aritmetica#sumar" />
<input>
<soap:body use="encoded" namespace="urn:Aritmetica"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body use="encoded" namespace="urn:Aritmetica"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
<operation name="restar">
<soap:operation soapAction="urn:Aritmetica#restar" />
<input>
<soap:body use="encoded" namespace="urn:Aritmetica"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body use="encoded" namespace="urn:Aritmetica"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
<service name="AritmeticaServicio">
<port name="AritmeticaPort" binding="tns:AritmeticaBinding">
<soap:address location="http://127.0.0.1/WSCemex/index.php" />
</port>
</service>
</definitions>
this is my index.php:
if(!extension_loaded("soap")){
dl("php_soap.dll");
}
ini_set("soap.wsdl_cache_enabled","0");
$server = new SoapServer("aritmetica.wsdl");
function sumar($operando1,$operando2){
return $operando1+$operando2;
}
function restar($operando1,$operando2){
return $operando1-$operando2;
}
$server->AddFunction("sumar");
$server->AddFunction("restar");
$server->handle();
and this is what i get on http://127.0.0.1/WSCemex/index.php:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<link type="text/css" id="dark-mode" rel="stylesheet" href=""/>
<style type="text/css" id="dark-mode-custom-style"/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>WSDL</faultcode>
<faultstring>SOAP-ERROR: Parsing WSDL: No address associated with <port></faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
right now im using it in localhost windows with xampp to test it, hope you can help me
| |
doc_23526516
|
I am currently learning about fragments and found a video for the similar need. Here is the link to it.
What I have basically done is make two fragments, One fragment(FragmentA) contains a simple ListView and when I click on the List item , the corresponding content should be shown in the fragment below namely : FragmentB.
I have followed all the steps as shown in the tutuorial, but still at the runtime I get the following error :
08-04 15:19:47.038 22144-22144/com.example.abhishek.fragmentmodularui E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abhishek.fragmentmodularui/com.example.abhishek.fragmentmodularui.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2107)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2132)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:313)
at android.app.Activity.setContentView(Activity.java:1920)
at com.example.abhishek.fragmentmodularui.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:5185)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2132)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.abhishek.fragments.FragmentA: make sure class name exists, is public, and has an empty constructor that is public
at android.app.Fragment.instantiate(Fragment.java:584)
at android.app.Fragment.instantiate(Fragment.java:552)
at android.app.Activity.onCreateView(Activity.java:4828)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:313)
at android.app.Activity.setContentView(Activity.java:1920)
at com.example.abhishek.fragmentmodularui.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:5185)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2132)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.example.abhishek.fragments.FragmentA
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.Fragment.instantiate(Fragment.java:574)
at android.app.Fragment.instantiate(Fragment.java:552)
at android.app.Activity.onCreateView(Activity.java:4828)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:313)
at android.app.Activity.setContentView(Activity.java:1920)
at com.example.abhishek.fragmentmodularui.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:5185)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2132)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
at dalvik.system.NativeStart.main(Native Method)
Here is my rest of the code :
1) MainActivity.java : http://pastebin.com/6r2a15AN
2)FragmentA.java : http://pastebin.com/UMDMKWVi
3)FragmentB.java : http://pastebin.com/i5q1pHdq
4)Communicator.java : http://pastebin.com/fw0HbQa7
5)strings.xml : http://pastebin.com/Q0Qb7D6n
6)activity_main.xml : http://pastebin.com/8mw2cEHs
7)fragment_a.xml : http://pastebin.com/mq7RmSLe
8)fragment_b.xml : http://pastebin.com/Px90HWLN
9)AndroidManifest.xml : http://pastebin.com/bX71e80s
What is the problem here ? Any kind of help will be appreciated!
A: Your Fragments and Activity seem to be in package com.example.abhishek.fragmentmodularui. In your activity_main.xml, both the fragment names point to files that do not exist:
android:name="com.example.abhishek.fragments.FragmentA"
This should probably be
android:name="com.example.abhishek.fragmentmodularui.FragmentA"
and respectively
android:name="com.example.abhishek.fragmentmodularui.FragmentB"
Additionally your implementation of the respond() method is wrong. Shown below for reference.
public void respond(int i) {
FragmentManager fragmentManager = getFragmentManager();
FragmentB fragmentB = new FragmentB(); //This is WRONG
fragmentB.changeData(i);
}
Here you should not create a new Fragment like you do, because they are created when Activity starts. What now happens a new fragment is created but is not initialized so you see errors. You should get the existing fragment from FragmentManager. The correct way is
public void respond(int i) {
FragmentManager fragmentManager = getFragmentManager();
FragmentB fragmentB = (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2);
fragmentB.changeData(i);
}
but you will have to figure out the parameters bundle and key on your own.
A: Buddy there are some things you are doing wrong way it will be better if you study some details from android developer site
http://developer.android.com/training/basics/fragments/fragment-ui.html
there is download link to download sample project study that
you have done this which is wrong
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
communicator = (Communicator)getActivity();
listView = (ListView)getActivity().findViewById(R.id.listView);
ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(getActivity(),R.array.titles,android.R.layout.simple_list_item_1);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
}
You should do like this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a,container,false);
listView = (ListView)view.findViewById(R.id.listView);
ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(getActivity(),R.array.titles,android.R.layout.simple_list_item_1);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(this);
return view;
}
| |
doc_23526517
|
echo 111;
$status = ob_get_status(true);
print_r($status);
/*
Array ( [0] => Array ( [name] => default output handler [type] => 0 [flags] => 112 [level] => 0 [chunk_size] => 4096 [buffer_size] => 8192 [buffer_used] => 3 ) )
*/
var_dump(ob_end_flush()); // true
Is it different from using ob_start() first?
What happening about PHP output buffer ?
| |
doc_23526518
|
I lost them forever, or there is a way to fix this ?
| |
doc_23526519
|
If I link someone to example.test?name=joe&email=test then the form resets to have a name of joe and an email of test. It doesn't actually reset the form?
The filters object being passed to the Filters components in page.svelte
let filters = [
{
name: 'name',
label: 'Name',
type: 'text',
value: urlParams.get('name') || ''
},
{
name: 'email',
label: 'Email',
type: 'text',
value: urlParams.get('email') || ''
},
]
The Filter component
<script>
import { page, useForm } from '@inertiajs/inertia-svelte'
import { Inertia } from '@inertiajs/inertia'
import debounce from 'lodash/debounce'
import {
LinkButton
} from '@/Shared'
export let searchUrl = $page.url;
export let filters = [];
let nakedUrl = searchUrl.split('?')[0];
// use filters.values as object
let form = useForm(filters.reduce((obj, item) => {
obj[item.name] = item.value
return obj
}, {}))
$form.reset()
$: search = debounce(function () {
$form.get(searchUrl, {
replace: true
})
}, 300)
</script>
<div>
{filters.length}
<div class="md:flex-row flex flex-col mb-4 space-x-4">
<slot name="title"></slot>
<div class="flex space-x-4">
<!-- reset filters-->
<LinkButton el="button" type="button" style="secondary" on:click={() => {
//clear filters
filters.forEach(filter => {
filter.value = ''
})
// try everything in my power to reset the dang form
$form.reset(filters.reduce((obj, item) => {
obj[item.name] = null
return obj
}, {}))
// nope not a thing
$form.reset()
// doesn't do anything
$form.reset('', '')
// clear all inputs? nope does nothing
let inputs = document.querySelectorAll('input')
inputs.forEach(input => {
input.value = ''
})
// the filters MUST be empty because this search brings back all results?!?
search(filters)
}}>
Clear Filters
</LinkButton>
<LinkButton href={nakedUrl} style="secondary">
Clear Filters
</LinkButton>
</div>
</div>
<div>
<form id="filters" class="md:flex-row flex flex-col mb-4 space-x-4" on:input={() => search($form)}>
{#each filters as filter}
<div class="md:w-1/2 lg:w-1/3 xl:w-1/4">
<label class="block mb-1" for="{filter.name}">{filter.label}</label>
<input
type="text"
placeholder="{filter.label}"
bind:value={$form[filter.name]}>
</div>
{/each}
</form>
</div>
<slot/>
</div>
The filtering with the search function does work, and clearing the filters with either button does bring back all results. But for some crazy reason I can't unset the inputs back to blank.
| |
doc_23526520
|
I want an AJAX or Javascript that would make the output dynamic (that is changing figures like normal timer). I do know that AJAX can make the page refresh every second in the background (asynchronously), but I've not been able to achieve that.
Presently, the output only changes when I refresh the HTML page. I also want a PHP script to be triggered when countdown gets to zero.
countdown.php
<?php
//some codes left out
$remainingHour=floor($secsdiff/3600);
$remainingMinute=floor(($secsdiff-($remainingHour*60*60))/60);
$remainingSecond=floor(($secsdiff-($remainingHour*60*60))-($remainingMinute*60));
?>
index.html
<div id="timer">
<?php echo "$remainingHour hours, $remainingMinute minutes,
$remainingSecond seconds";?>
</div>
A: Make sure your using JQuery in your HTML page (Follow the tutes on the JQ website if this is new to you, It's really very easy)
Then once your up and running with that, use JQuerys Get function to update your div:
http://api.jquery.com/jQuery.get/
You should be able to get it up and working in 30 mins or less, it's very simple.
A: If this is just a small item on a larger page, I would use Ajax or JavaScript. With Ajax you should be able to check for 0 values and if it is reached, notify that to the server, where server will perform specification action.
You probably can do that with JavaScript a s well which might be more desirable for such small tasks.
A: You should use setTimeout function in javascript, see https://stackoverflow.com/search?q=[javascript]+setTimeout&submit=search
When the timer will be over, simply call a new URL to execute the next php script (still in javascript), like :
document.location.href = http://foobar.tld/new_page
| |
doc_23526521
|
User Model:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "User_Id")
private int id;
@Column(name = "Username")
@NotBlank(message = "Username cannot be empty!")
@NotNull(message = "Username cannot be empty!")
@Pattern(regexp = "[a-zA-Z0-9]+", message = "Only alphanumeric characters allowed !")
private String userName;
@Column(name = "Password")
@NotBlank(message = "Password cannot be empty!")
@NotNull(message = "Password cannot be empty!")
@Pattern(regexp = "[a-zA-Z0-9 _!@#&.]+", message = "Password pattern mismatch !")
private String password;
@Column(name = "Name")
@NotBlank(message = "Name cannot be empty!")
@NotNull(message = "Name cannot be empty!")
private String name;
}
Controller:
@GetMapping("/register")
public ModelAndView registerPage(){
ModelAndView modelAndView = new ModelAndView();
User user = new User();
modelAndView.addObject("user", user);
modelAndView.setViewName("register");
return modelAndView;
}
@PostMapping("/register")
public ModelAndView createNewUser(@Valid @ModelAttribute("user") User user, BindingResult bindingResult) {
ModelAndView modelAndView = new ModelAndView();
System.out.println(user.getName() + "-" + user.getUserName() + "-" + user.getPassword());
if (bindingResult.hasErrors()) {
modelAndView.setViewName("register");
} else {
userService.saveUser(user);
modelAndView.addObject("successMessage", "User has been registered successfully");
modelAndView.addObject("user", new User());
modelAndView.setViewName("register");
}
return modelAndView;
}
JSP:
<form:form action="register" method="POST" modelAttribute="user">
<p>Name</p>
<form:input path="name"/>
<form:errors path="name"/>
<p>*Username</p>
<form:input path="userName"/>
<form:errors path="userName"/>
<p>*Password</p>
<form:input path="password"/>
<form:errors path="password"/>
<br><br>
<input type="submit" value="Sign Up" />
</form:form>
I even tried adding the following dependency, but still it didn't work:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
| |
doc_23526522
|
Here is some code:
<div id="draggable" style="position: absolute; top: 100px; left: 200px; background-color: red; width: 100px; height: 100px;"></div>
<div style="background-color: green; width: 100px; height: 100px;"></div>
Can this be done?
If so, how?
Edit: I do not want to use jQuery, just plain old JavaScript!
A: A plain old JS solution
Below is a "plain old JavaScript" rewrite of the overlap detection function found in this answer to the question titled "jQuery/Javascript collision detection".
The only real difference between the two is the replacement of the use of jQuery to get element position and width for calculating the bounding box.
Native JavaScript makes this task easy via the Element.getBoundingClientRect() method, which returns the four values needed to create the position matrix returned by the getPositions function.
I added a click handler for the boxes as a simple demonstration of how you might use the function to compare a target (clicked, dragged, etc.) element to a set of selected elements.
var boxes = document.querySelectorAll('.box');
boxes.forEach(function (el) {
if (el.addEventListener) {
el.addEventListener('click', clickHandler);
} else {
el.attachEvent('onclick', clickHandler);
}
})
var detectOverlap = (function () {
function getPositions(elem) {
var pos = elem.getBoundingClientRect();
return [[pos.left, pos.right], [pos.top, pos.bottom]];
}
function comparePositions(p1, p2) {
var r1, r2;
if (p1[0] < p2[0]) {
r1 = p1;
r2 = p2;
} else {
r1 = p2;
r2 = p1;
}
return r1[1] > r2[0] || r1[0] === r2[0];
}
return function (a, b) {
var pos1 = getPositions(a),
pos2 = getPositions(b);
return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
};
})();
function clickHandler(e) {
var elem = e.target,
elems = document.querySelectorAll('.box'),
elemList = Array.prototype.slice.call(elems),
within = elemList.indexOf(elem),
touching = [];
if (within !== -1) {
elemList.splice(within, 1);
}
for (var i = 0; i < elemList.length; i++) {
if (detectOverlap(elem, elemList[i])) {
touching.push(elemList[i].id);
}
}
if (touching.length) {
console.log(elem.id + ' touches ' + touching.join(' and ') + '.');
alert(elem.id + ' touches ' + touching.join(' and ') + '.');
} else {
console.log(elem.id + ' touches nothing.');
alert(elem.id + ' touches nothing.');
}
}
#box1 {
background-color: LightSeaGreen;
}
#box2 {
top: 25px;
left: -25px;
background-color: SandyBrown;
}
#box3 {
left: -50px;
background-color: SkyBlue;
}
#box4 {
background-color: SlateGray;
}
.box {
position: relative;
display: inline-block;
width: 100px;
height: 100px;
color: White;
font: bold 72px sans-serif;
line-height: 100px;
text-align: center;
cursor: pointer;
}
.box:hover {
color: Black;
}
<p>Click a box to see which other boxes are detected as touching it.<br />
<em>If no alert dialog box appears, open your console to view messages.</em></p>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>
A: Update: I realize now that this only accounts for the intersection of the top left corner of the target element and therefore, doesn't provide a complete solution. But I'll leave it up for posterity in case someone finds it useful for other purposes.
Use element.getBoundingClientRect() and document.elementFromPoint()
*
*You can use element.getClientBoundingRect() (src) to get the position of the target (clicked, dragged, etc.) element.
*Temporarily hide the target element, then use document.elementFromPoint(x, y) (src) to get the top-most element at that position, and then check it's class name for comparison (you could compare any attribute or property instead, if you prefer).
To achieve cross-browser compatible behavior from this method
read: document.elementFromPoint – a jQuery solution (You don't
have to use jQuery to achieve this result. The method can be
replicated in pure JS.)
Addendum:
I am only showing the function for detecting overlap instead of showing drag-and-drop or drag-to-move functionality because it isn't clear which of those, if either, you are trying to implement and there are other answers showing how to accomplish various drag patterns.
In any case, you can use the detectCollision() function below in combination with any drag solution.
var box2 = document.getElementById('box2'),
box3 = document.getElementById('box3');
box2.onclick = detectCollision;
box3.onclick = detectCollision;
function detectCollision(e) {
var elem = e.target,
elemOffset = elem.getBoundingClientRect(),
elemDisplay = elem.style.display;
// Temporarily hide element
elem.style.display = 'none';
// Check for top-most element at position
var topElem = document.elementFromPoint(elemOffset.left, elemOffset.top);
// Reset element's initial display value.
elem.style.display = elemDisplay;
// If a top-most element is another box
if (topElem.className.match(/box/)) {
alert(elem.id + " is touching " + topElem.id);
} else {
alert(elem.id + " isn't touching another box.");
};
}
#box1 {
background-color: LightSeaGreen;
}
#box2 {
top: 25px;
left: -25px;
background-color: SandyBrown;
}
#box3 {
background-color: SkyBlue;
}
.box {
position: relative;
display: inline-block;
width: 100px;
height: 100px;
}
.clickable {
cursor: pointer;
}
<div class="box" id="box1"></div>
<div class="box clickable" id="box2"></div>
<div class="box clickable" id="box3"></div>
| |
doc_23526523
|
I'm using MySQL as a database backend. Do I need to worry about the integrity of my database when something goes wrong with South? Do transactions ensure that all problems are rolled back on error?
A: The database should rollback nicely:
http://south.aeracode.org/docs/migrationstructure.html#transactions
Anyway, can't you just check the db tables?
A couple of notes:
*
*You can print the existing migrations with
manage.py migrate --list
This also shows which migrations have been applied
*You can also manually rollback to a previous migration using
manage.py migrate <app_name> 0010
where 10 is the last safe migration
Hope this helps
| |
doc_23526524
|
The Problem: It says I do not have permission to access the Application.UserAppDataPath directory
Is there a way to set permissions within my application source code?
Something like:
Application.UserAppDataPath.SetPermissions()
A: Its probably a UAC issue, Try running your application as an elevated process, and see if the error persists
A: Looking at your comment, you say this is your code:
StreamReader sr = new StreamReader(Application.UserAppDataPath);
Application.UserAppDataPath is a directory, not a file. If you try to open that directly, it's the same as trying to open a file one level below the AppData folder, which you really don't have permission to do.
Use Path.Combine to construct a path to a file inside the AppData folder, i.e.
string fileName = Path.Combine(Application.UserAppDataPath, "settings.xml");
StreamReader sr = new StreamReader(fileName);
Of course this is just an example - in reality you should probably be using a sub-folder inside AppData specific to your application.
| |
doc_23526525
|
heroku open
I get the standard "We're sorry, but something went wrong." When I type:
heroku logs
I get (abbreviated, I've selected the relevant output, it appears three times with slight differences):
Processing by StaticPagesController#home as HTML
Rendered static_pages/home.html.erb within layouts/application (1.6ms)
Completed 500 Internal Server Error in 9ms
4: <title><%= full_title(yield(:title)) %></title>
ActionView::Template::Error (Invalid CSS after " *": expected "{", was "= require_self"
2: <html>
(in /app/app/assets/stylesheets/application.css)):
My application.css file is unaltered and entirely commented out.
Any ideas on what the problem is? I have a gemfile with gem 'bootstrap-sass', '2.0.0' in it.
A: If there is a *= require_self in your css, I would guess it means your assets didn't compile.
I'd double-check your stylesheets, and remember you generally should not put any actual css in the application.css file.
Also, Im pretty sure Rails compiles all your stylesheets into one big stylesheet for production, which means if there is an issue in one of them the whole thing might have issues.
Thats all i got- its a bizarre error because css is usually very forgiving.
A: /app/app/assets/stylesheets/application.css
You've got two /app directories in the path. To verify, run
rails console
> Rails.application.config.assets.paths
| |
doc_23526526
|
Is this true and if so can someone explain why?
A: Calling virtual methods from a finalizer/Dispose is unsafe, for the same reasons it is unsafe to do in a constructor. It is impossible to be sure that the derived class has not already cleaned-up some state that the virtual method requires to execute properly.
Some people are confused by the standard Disposable pattern, and its use of a virtual method, virtual Dispose(bool disposing), and think this makes it Ok to use any virtual method durring a dispose. Consider the following code:
class C : IDisposable {
private IDisposable.Dispose() {
this.Dispose(true);
}
protected virtual Dispose(bool disposing) {
this.DoSomething();
}
protected virtual void DoSomething() { }
}
class D : C {
IDisposable X;
protected override Dispose(bool disposing) {
X.Dispose();
base.Dispose(disposing);
}
protected override void DoSomething() {
X.Whatever();
}
}
Here's what happens when you Dispose and object of type D, called d:
*
*Some code calls ((IDisposable)d).Dispose()
*C.IDisposable.Dispose() calls the virtual method D.Dispose(bool)
*D.Dispose(bool) disposes of D.X
*D.Dispose(bool) calls C.Dispose(bool) statically (the target of the call is known at compile-time)
*C.Dispose(bool) calls the virtual methods D.DoSomething()
*D.DoSomething calls the method D.X.Whatever() on the already disposed D.X
*?
Now, most people who run this code do one thing to fix it -- they move the base.Dispose(dispose) call to before they clean-up their own object. And, yes, that does work. But do you really trust Programmer X, the Ultra-Junior Developer from the company you developed C for, assigned to write D, to write it in a way that the error is either detected, or has the base.Dispose(disposing) call in the right spot?
I'm not saying you should never, ever write code that calls a virtual method from Dispose, just that you'll need to document that virtual method's requirement that it never use any state that's defined in any class derived below C.
A: Virtual methods are discouraged in both constructors and destructors.
The reason is more practical than anything: virtual methods can be overridden in any manner chosen by the overrider, and things like object initialization during construction, for example, have to be ensured lest you end up with an object that has random nulls and an invalid state.
A: I do not believe there is any recommendation against calling virtual methods. The prohibition you are remembering might be the rule against referencing managed objects in the finalizer.
There is a standard pattern that is defined the .Net documentation for how Dispose() should be implemented. The pattern is very well designed, and it should be followed closely.
The gist is this: Dispose() is a non-virtual method that calls a virtual method Dispose(bool). The boolean parameter indicates whether the method is being called from Dispose() (true) or the object's destructor (false). At each level of inheritance, the Dispose(bool) method should be implemented to handle any cleanup.
When Dispose(bool) is passed the value false, this indicates that the finalizer has called the dispose method. In this circumstance, only cleanup of unmanaged objects should be attempted (except in certain rare circumstances). The reason for this is the fact that the garbage collector has just called the finalize method, therefore the current object must have been marked ready-for-finalization. Therefore, any object that it references may also have been marked read-for-finalization, and since the sequence in non-deterministic, the finalization may have already occurred.
I highly recommend looking up the Dispose() pattern in the .Net documentation and following it precisely, because it will likely protect you from bizarre and difficult bugs!
A: To expand on Jon's answer, instead of calling virtual methods you should be overriding the dispose or the destructor on sub classes if you need to handle resources at that level.
Although, I don't believe there is a "rule" in regards to behavior here. But the general thought is that you want to isolate resource cleanup to only that instance at that level of the implementation.
| |
doc_23526527
|
Below is the code I have used for dragging and dropping the element
WebElement draggable = objectIdentifierType(
objectIdentificationKeyword, objectValue);
WebElement droppable = GetBrowserDriver.driver.findElement(By.xpath(objectData));
/*WebElement droppable = objectIdentifierType(
objectIdentificationKeyword, objectValue);*/
if (draggable != null) {
System.out.println(draggable.getText()+"Draged element");
System.out.println(droppable.getText()+"Droped element");
//System.out.println(droppable.getText());
new Actions(GetBrowserDriver.driver).dragAndDrop(
draggable,droppable).build()
.perform();
HTMLReport.bw.write("<script type='text/javascript'>addDetailRow('"
+ GenericFunctions.testCaseName + "','"
+ HTMLReport.testcaseTABLESNO() + "','\""
+ "Drag Value: "
+ draggable.getText()
+ "','Drop Value \""
+ droppable.getText()
+ "\" ','"
+ "','Passed' )</script>");
// new
// Actions(GetBrowserDriver.driver).dragAndDrop(draggable,
// droppable);
String actualResult = "The Slider value is changed to the expected value.";
CreateExcel updatePassed = new CreateExcel();
updatePassed.updatePassedTestSteps(actualResult,
expectedResult, objectData);
A: Clearly, you changed the DOM with this action. You need to assign draggable.getText() and droppable.getText() strings
I'm not familiar with java so much, but I think this should work:
if (draggable != null) {
String draggableText = draggable.getText();
String droppableText = droppable.getText();
//continue your code from here using new variables
PS Sorry for my bad English
| |
doc_23526528
|
I'm just wondering why my static variables declared in my Activity are not updated by my Service in time for the getTimeStamp() method call. Is this because the service is run concurrently and if so is there anyway I can give it a token which ensures it finishes before underneath code is run. You can see this in the validation method. The service is fired first which for instance will update the 'type' variable. However when the program gets to getTimeStamp() 'type' is still null even though it should now equal "Login".
Thanks,
This is my Main activity
public class MainActivity extends Activity {
//TAG.
public static final String TAG = "BOE_TEST";
//UI elements.
Button TestNow;
ListView listView;
ArrayAdapter<String> adapter;
//Timer.
Timer repeatTask = new Timer();
//Global variables and data structures.
int repeatInterval = 10000 * 1; // 10 sec
static Boolean success = true;
static String type;
ArrayList<String> values = new ArrayList<String>();
static int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this,
R.layout.listview_each_item, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
TestNow = (Button) findViewById(R.id.button_test);
repeatTask.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
validation("Login");
}
});
}
}, 0, repeatInterval);
TestNow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
runOnUiThread(new Runnable() {
@Override
public void run() {
validation("Login");
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void validation(String validate) {
Intent i;
i = new Intent(MainActivity.this, LoginService.class);
MainActivity.this.startService(i);
MainActivity.this.stopService(i);
values.add(0, getTimeStamp());
adapter.notifyDataSetChanged();
try {
if (success == true) {
listView.getChildAt(count).setBackgroundColor(Color.parseColor("#009900"));
count++;
} else {
listView.getChildAt(count).setBackgroundColor(Color.parseColor("#cc0000"));
count++;
}
} catch (NullPointerException e) {
}
}
public static String getTimeStamp() {
String s = "";
String whiteSpaces = " ";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");//Date
s += "\n" + "Time: " + sdf.format(new Date()) + whiteSpaces ;
sdf = new SimpleDateFormat("dd.MM.yyyy");//Time
Date date = new Date();
s += "Date: " + sdf.format(date) + whiteSpaces+ "/*" + type + "*/";
return s;
}
}
This is my Service
public class LoginService extends Service {
//TAG
private static final String TAG = "loginService";
//final variables
private static final String email = "xxxxxxxxxx";
private static final String password = "xxxxxxxxxxx";
private static final String login = "login";
private static final String BOE_LOGIN = "http://thebookofeveryone.com/account/";
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
Login task = new Login();
task.execute();
return START_STICKY;
}
public class Login extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(BOE_LOGIN);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("action", login));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute HTTP Post Request
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
if (response.getStatusLine().getStatusCode() < 400) {
} else {
Log.d(TAG, "Response error: "
+ response.getStatusLine().getStatusCode());
}
HttpEntity entity = response.getEntity();
String responseString = null;
try {
responseString = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
@Override
protected void onPostExecute(String s) {
MainActivity.type="Login";
if(s.contains("We could not find a matching account")){
Log.i(TAG,"Login Failed");
createNotification("Login Failed");
MainActivity.success = false;
}else{
Log.i(TAG,"Login Successfull");
MainActivity.success = true;
}
}
}
public void createNotification(String s) {
Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
R.drawable.boelogo);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.boelogo)
.setLargeIcon(icon)
.setContentTitle( getResources().getString(R.string.app_name))
.setContentText(s);
// Add as notification
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(001,builder.build());
}
}
A: I solved this using a LocalBroadcastManager in the service, When I finished the service I fired the broadcast and had the method in my Activity to listen for it
Service
@Override
public void onCreate() {
super.onCreate();
broadcaster = LocalBroadcastManager.getInstance(this);
}
private void sendResult() {
Intent intent = new Intent("sendResult");
sendLocationBroadcast(intent);
}
private void sendLocationBroadcast(Intent intent){
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Activity
//In onCreate()
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("sendResult"));
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
validation();
}
};
| |
doc_23526529
|
I need to be able to install multiple different versions of Node.js because different projects under the same company use different versions of Node.js as a necessity.
Is the only way to uninstall the installed version and install a new version every time? Is there any way I can have v10 under C:\Program Files\node10, and v14 under C:\Program Files\node14?
To be clear, the admins are willing to grant me specific privileges or install any software needed in order to get this working. We have tried using something called RunAsTool to try to let me run NVM as an admin, but this doesn't work because of its limitations.
Another option would be to grant me admin rights to any files and directories needed for NVM to function, but there is no list of those files/folders that I can find.
A third option would be to simply install two different versions, but when you install a new version, the previous version gets removed, even if it's installed under an unusual path like C:\Program Files\node16.
A: There's no easy way to do this, I think. Broadly you need two things to get node working on Windows: the nodejs folder with the executable in it, by default c:\Program Files\nodejs, and the path to that to be on the system path before any other node paths.
Unfortunately both writing to c:\Program Files and changing the system path require admin rights.
However, there is a somewhat clunky workaround. The overall idea is to put the nodejs folder somewhere where you have write access, point the system path at it, and it should run. Then you can switch versions without admin rights by replacing the folder. To do this:
*
*With admin, install the first version you want to use. Copy the c:\Program Files\nodejs folder somewhere where it won't get deleted on a new install: say c:\nodejsbackups\v10\nodejs if it's version 10.
*Install the second version you want to use, and copy the nodejs file to the same place, say c:\nodejsbackups\v14\nodejs.
*Also copy it to a place you will run it from and where you have write access, say c:\nodejs if you have write access on the c: drive, or your user profile somewhere if not.
*Still with admin rights, edit the system Path environment variable (NOT the user path). Find the entry to c:\Program Files\nodejs and remove it. Add an entry for c:\nodejs. Or just edit it.
*I found that to get Visual Studio node apps to work I then had to also uninstall the original node using Control Panel/Programs and Features.
Now fire up a command prompt and do node --version and npm --version and you should see the second version is working.
To switch versions, without admin delete c:\nodejs and then copy the first version to there from c:\nodejsbackups\v10\nodejs. Restart your command prompt, issue the same commands, and you should see the first version is now working.
This seems to work on some very limited testing, but I think you need to test it all works for your use cases. There may be programs like Visual Studio that assume node is at c:\Program Files without using the path. In the end it may be better to beg for admin rights.
A: *
*Install here:
*Delete %NVM_HOME% and %NVM_SYMLINK%
*Add path relative
*Enjoy :)
| |
doc_23526530
|
this is my function:
void my_split(const char *source, char *first, char *second, const char delim){
int ree = 1;
while(*source != '\n'){
if(*source == delim){
ree = 0;
*source++;
}
else{
if(ree == 1){
*first++ = *source++;
}
else {
*second++ = *source++;
}
}
}
*first = '\0';
*second = '\0';
}
Main function:
int main(void){
int max_n = 200;
char source[max_n];
char strA[max_n];
char strB[max_n];
int T;
scanf("%d%*c", &T);
for(int i = 0; i < T; i++){
fgets (source, max_n, stdin);
my_split(source, strA, strB, ';');
printf("First: %s\n", strA);
printf("Second: %s\n", strB);
}
}
^^^ teacher gave us this one.
TXT FILE:
2
2345.454;6737.98
this is the line;splitted by semicolon
My output is:
First:
Second:
First: 2345.454
Second: 6737.98
The desired output is:
First: 2345.454
Second: 6737.98
First: this is the line
Second: splitted by semicolon
I'm trying to make above function, but It didn't workout, well it works half-succesfull
A: Your function seem to work. Try it like this...
#include <stdio.h>
void my_split(const char *, char *, char *, const char);
int main() {
FILE* fp;
fp = fopen("data.txt", "r");
if (NULL == fp) {
printf("file can't be opened \n");
return 0;
}
char source[100];
while (fgets(source, 100, fp) != NULL) {
char first[100] = "", second[100] = "";
my_split(source, first, second, ';');
printf("First: %s\n", first);
printf("Second: %s\n", second);
}
// Closing the file
fclose(fp);
return 0;
}
void my_split(const char *source, char *first, char *second, const char delim){
int ree = 1;
while(*source != '\n'){
if(*source == delim){
ree = 0;
*source++;
}
else{
if(ree == 1){
*first++ = *source++;
}
else {
*second++ = *source++;
}
}
}
*first = '\0';
*second = '\0';
}
It outputs:
First: 2
Second:
First: 2345.454
Second: 6737.98
First: this is the line
Second: splitted by semicolon
| |
doc_23526531
|
At first I thought that, for whatever reason, the browser thought it was clicking outside the dialog so it closed itself (as that is the default behavior), so I added data-backdrop="static" data-keyboard="false" to the HTML.
<div id="myModal" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-body">
<div class="flex-video widescreen" style="margin: 0 auto;text-align:center;">
<iframe allowfullscreen="" src="http://www.youtube.com/embed/Aq8X4l7aGiU?rel=0" frameborder="0"></iframe>
</div>
</div>
<div class="modal-footer">
<p style="text-align:left;"> Colaboración en equipo para el desarrollo del concepto, la historia, aspecto general del corto.<br /> Y desarrollo de tareas personales como, modelación de personajes, personalización de esqueletos automáticos, blend shapes, asistente de texturización, animación 2D, animación de colisiones y compositing.<br /> </p>
<button class="btn" data-dismiss="modal">Cerrar Video</button>
</div>
</div>
And while the dialog is not closing on its own anymore, it won't listen to any commands. The video can't be played (or paused) and the dialog can't be closed until I fullsize the window again. Is there any way to solve this problem?
| |
doc_23526532
|
But csv files are in different folders.
Here's the thing
1. /current/a/1/op/one.csv
2. /current/a/1/no/two.csv
3. /current/a/2/op/three.csv
4. /current/b/1/op/four.csv
so I want to assign csv files in /op folders to grape by stacking
and I want to assign csv files in /no folders to apple
this is my code
grape1 = pd.read_csv('current/a/1/op/one.csv')
grape2 =pd.read_csv('current/a/2/op/three.csv')
grape3 = pd.read_csv('current/b/1/op/four.csv')
apple = pd.read_csv('current/a/1/no/two.csv')
grape= grape1+grape2+grape3
but I have many files and folders, so my code will be too long.
how can I solve it?
A: You could use a loop
import glob
import panda as pd
df_list = []
for f in glob.glob('current/*/*/op/*.csv'):
df_list.append(pd.read_csv)
grape = pd.concat(df_list)
| |
doc_23526533
|
Thanks!
<tr>
<td bgcolor="#fdfcf8" style="padding:10px; padding-top:0; border-top: 0px solid #fdfcf8; font-family:arial, sans-serif; border-left:1px solid #fdfcf8; border-right:1px solid #fdfcf8; border-bottom:1px solid #fdfcf8;color: #003F6B;">hehe
</td>
<td bgcolor="#fdfcf8" style="padding:10px; padding-top:0; border-top: 0px solid #fdfcf8; font-family:arial, sans-serif; border-left:1px solid #fdfcf8; border-right:1px solid #fdfcf8; border-bottom:1px solid #fdfcf8;color: #003F6B;">hehe
</td>
</tr>
A: It's impossible to tell from your example code - look in other rows above/below for wide content which is pushing the width of that column.
Content widths in one row will affect the width of cells in other rows that are part of the same table.
| |
doc_23526534
| ||
doc_23526535
|
A: I once used JQuery datepicker with BE calendar and i used https://code.google.com/p/jquery-ui-datepicker-extension-buddhist-era/
and because primefaces does use JQuery datepicker try to include this extension after jquery and add in your page:
<script type="text/javascript">
$(document).ready(function(){
$( ".datepicker").datepicker({
isBE: true,
autoConversionField: true
});
});
</script>
This should do the trick.
| |
doc_23526536
|
I'd would like to query the table for the most matching row for a given Code c. The 'most matching' criteria (in order of importance):
*
*1) select a row whose Code matches c
*2) select a row whose Code is greater than c (but the very first one). For example, if c = 4 and t
contains 1, 2, 3, 5, 6, and 7, I'd like to select 5.
*3) select a row whose
Code is less than c. For example, if c = 4 and t contains 3, 2, and
1, I'd like to select 3.
The code is going to be in a stored procedure.
Could someone please suggest how to accomplish the above.
Thanks.
Sample data and expected results:
1, "Name1"
2, "Name2"
4, "Name4"
5, "Name5"
If c=2, result: 2,"Name2"
If c=3, result: 4,"Name4"
if c=6, result: 5,"Name5"
A: I'd order the rows by two criteria - the absolute distance from the target number and whether it's greater or lesser than it, and just pick the top row. E.g., assuming the target code is 4:
SELECT TOP 1 *
FROM t
ORDER BY ABS(code - 4) ASC, CASE WHEN code > 4 THEN 1 ELSE 0 END DESC
A: That is a top 1 query; you want the one best matching record. So select TOP 1 along the desired order in ORDER BY.
select top 1 *
from mytable
order by
case when code = @code then 1
when code > @code then 2
else 3
end,
abs(code - @code);
| |
doc_23526537
|
AnchorPane
|
ScrollPane
|
FlowPane
|
SplitPane
|
StackedBarChart
TableView
How can I, duplicate my SplitPane with its children for a unknown numbers of duplicates?
How can i set for each copy new variable names?
In Scene Builder i right click on SplitPane and select Duplicate. But, the problem is the number of duplicates is not available before writting the program and is not known until runtime.
A: The best approach for this would be to create a separate FXML for SplitPane, load it as many times as you want and add it to your FlowPane.
Let us call the new fxml as split.fxml. A controller for the fxml called as SplitController
Then,we will load this fxml as many times as required, get the root and add it to the FlowPane, which is now present in a separate fxml.
Let us call the main fxml as container.fxml. A controller for the fxml called as ContainerController
Answering some of your questions :
How can I, duplicate my SplitPane with its children for a unknown numbers of duplicates?
Just load the fxml as many times you need.
How can i set for each copy new variable names?
You have the controller, you can identify it with a variable. You may also set a class or id to the splitpane.
The complete code...
split.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.CategoryAxis?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.chart.StackedBarChart?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<SplitPane fx:id="splitPane" dividerPositions="0.25" prefHeight="363.0" prefWidth="773.0" fx:controller="SplitController" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<items>
<TableView fx:id="tableView" prefHeight="458.0" prefWidth="251.0">
<columns>
<TableColumn prefWidth="75.0" text="C1" />
<TableColumn prefWidth="75.0" text="C2" />
</columns>
</TableView>
<StackedBarChart fx:id="stackedBarChart" prefHeight="210.0" prefWidth="107.0">
<xAxis>
<CategoryAxis fx:id="categoryAxis" side="BOTTOM" label="Year" />
</xAxis>
<yAxis>
<NumberAxis fx:id="numberAxis" side="LEFT" label="Value"/>
</yAxis>
</StackedBarChart>
</items>
</SplitPane>
SplitController.java
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.StackedBarChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableView;
import java.net.URL;
import java.util.ResourceBundle;
public class SplitController implements Initializable{
@FXML
private SplitPane splitPane;
@FXML
private StackedBarChart<String, Number> stackedBarChart;
@FXML
private TableView<String> tableView;
@FXML
private CategoryAxis categoryAxis;
@FXML
private NumberAxis numberAxis;
private ObservableList<String> tableList;
private ObservableList<Integer> chartValueList = FXCollections.observableArrayList();
public void setTableList(ObservableList<String> tableList) {
this.tableList = FXCollections.observableList(tableList);
}
public void setChartValueList(ObservableList<Integer> chartValueList) {
this.chartValueList = FXCollections.observableList(chartValueList);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void setChart(){
XYChart.Series<String,Number> series1 = new XYChart.Series();
series1.getData().add(new XYChart.Data("January", chartValueList.get(0)));
series1.getData().add(new XYChart.Data("February", chartValueList.get(1)));
series1.getData().add(new XYChart.Data("March", chartValueList.get(2)));
series1.getData().add(new XYChart.Data("April", chartValueList.get(3)));
XYChart.Series<String,Number> series2 = new XYChart.Series();
series2.getData().add(new XYChart.Data("January", chartValueList.get(0)));
series2.getData().add(new XYChart.Data("February", chartValueList.get(1)));
series2.getData().add(new XYChart.Data("March", chartValueList.get(2)));
series2.getData().add(new XYChart.Data("April", chartValueList.get(3)));
stackedBarChart.getData().addAll(series1, series2);
}
}
container.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.FlowPane?>
<BorderPane xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ContainerController">
<center>
<ScrollPane fx:id="scrollPane" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" BorderPane.alignment="CENTER">
<content>
<FlowPane fx:id="flowPane" maxHeight="-Infinity" maxWidth="-Infinity" prefHeight="353.0" prefWidth="745.0">
</FlowPane>
</content>
</ScrollPane>
</center>
</BorderPane>
ContainerController.java
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;
public class ContainerController implements Initializable{
@FXML
private AnchorPane anchorPane;
@FXML
private ScrollPane scrollPane;
@FXML
private FlowPane flowPane;
private final int NUMBER_OF_COPIES = 5;
private final int NUMBER_OF_ROWS = 10;
private ObservableList<String> tableList = FXCollections.observableArrayList();
private ObservableList<Integer> chartValueList = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
try {
for(int i=0; i<NUMBER_OF_COPIES; i++) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/split.fxml"));
SplitPane pane = loader.load();
SplitController controller = loader.getController();
fillChartValueList();
controller.setChartValueList(chartValueList);
controller.setChart();
flowPane.getChildren().add(pane);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillChartValueList(){
// clear previous values
chartValueList.clear();
Random rand = new Random();
int min = 1000;
int max = 8000;
for(int i=0; i<NUMBER_OF_ROWS; i++) {
int randomNum = rand.nextInt((max - min) + 1) + min;
chartValueList.add(randomNum);
}
}
}
Main.java - to load the container, set it to a stage and show
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
public Main() {
super();
}
@Override
public void start(Stage primaryStage) throws IOException{
FXMLLoader loader = new FXMLLoader(getClass().getResource("/container.fxml"));
Parent parent = loader.load();
ContainerController controller = loader.getController();
Scene scene = new Scene(parent, 600, 600);
Stage stage = new Stage();
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Screenshot
Note - The TableView is empty as I didn't consider it important to fill it, as per the question.
A: That works:
SplitPane sp=new SplitPane(splitPane);
sp.setId(machine);
flowPane.getChildren().add(new SplitPane(sp));
| |
doc_23526538
|
*
*User
*Question
*QuestionCategories
*Answers
NOw i am confused whether my user class should have any link to questions or just answers
User will answer the question shown on the form.
So every year there will different answers for different questions
A: I'll assume a user can ask a question, a question can belong to a category, and a number of users can post answers. It's about what a site like stackoverflow is like, actually.
create table user (
user_id integer primary key,
name varchar(40) not null
);
create table category (
category_id integer primary key,
category varchar(40) not null
);
create table question (
question_id integer primary key,
question text,
asked_by_id integer not null,
category_id integer not null,
foreign key asked_by_id references user(user_id),
foreign key category_id references categor(category_id)
);
create table answer (
answers_id integer not null,
answered_by_id integer not null,
answer text,
primary key (answers_id, answered_by_id), -- we allow one answer per person for a question
foreign key answers_id references question(question_id),
foreign key answered_by_id references user(user_id)
);
And then the query:
select qu.name as asked_by, question, category,
au.name as answered_by, answer
from user qu -- iterating through users
join question q on qu.user_id = asked_by_id -- joining them to their questions
join category c on c.category_id = q.category_id -- find the category
join answer on answers_id = question_id -- join by what answers this question
join user au on au.user_id = answered_by_id; -- looking up the user who answered it
(I didn't try it on a server so there might be typos. Feel free to correct.)
A: Well, it makes sense depending on what you want to do. Is a user able to post a question? If yes, link it. If not, linking doesnt make sense because it would stay emty.
A: instead of updating multiple rows, you can simply convert your questions along with their options and answers into json and store as a single field.
| |
doc_23526539
|
For Example: I have 3 columns.
Event, number of days and Date when this event started
Event DaysLost
Injury 30 25/12/2016
Injury 588 06/08/2012
Days in 2016 - 6
Days in 2017 - 24
For the second case:
Days in 2012 - 146
Days in 2013 - 365
Days in 2014 - 77
Now for above case there are only 6 days which need to be counted in 2016 and the rest of the days should automatically be counted in 2017. But i cannot figure out how to do it.
In my output i would like to put years in one column and days lost for year in front of that particular year.
I have a calendar table and i want sum of days to populate for a particular year.
I tried calculating it by getting end date, by adding number of days to First start date and then if days were more that remaining days in that year. subtract remaining days from total days and remaining days should move to next year. But i cannot figure out how to keep adding days for next years if days extends for many years and list them after words.
Sept 4, 2017
Please see the excel solution below
Excel solution of the problem
A: This is a Power Query based approach...
I started with this:
Then I added a custom column by clicking the Add Column tab and Custom Column button and completing the pop-up window like this:
...and clicking OK.
Then I changed the type for that new column by selecting it and then clicking the Transform tab and then Data Type and Date.
Then I added another custom column, completing the pop-up like this:
Then I added another custom column, completing the pop-up like this:
Then I added yet another custom column, completing the pop-up like this:
Then I expanded that last column I added by clicking on the at the top of the column and Expand to New Rows.
Then I added a final custom column, completing the pop-up like this:
Finally, I grouped by the Event, DaysLost, Started, and Year columns and summed the DaysLostForYear column by clicking the Transform tab and Group By button and completing the pop-up like this:
I end up with this:
You might want a different grouping, but this should get you close. It shows how many days were lost in the years associated with each instance of an injury's total days lost. For instance, the first injury, which was 30 days in duration, started on 12/25/2016: 7 of those days occurred in 2016 and 23 in 2017. The second injury was 588 days, started on 8/6/2012: 148 days were in 2012, 365 in 2013, and 75 in 2014.
Note that I count the started date as a lost day.
Note also that I account for leap years.
I hope this helps.
Here's the query code:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Event", type text}, {"DaysLost", Int64.Type}, {"Started", type date}}),
#"Added Custom" = Table.AddColumn(#"Changed Type", "Ended", each Date.AddDays([Started],[DaysLost]-1)),
#"Changed Type1" = Table.TransformColumnTypes(#"Added Custom",{{"Ended", type date}}),
#"Added Custom3" = Table.AddColumn(#"Changed Type1", "DaysYearStarted", each Number.From(Date.From(Text.From(Date.Year([Started]))&"/12/31")-[Started])+1),
#"Added Custom4" = Table.AddColumn(#"Added Custom3", "DaysYearEnded", each Number.From([Ended]-Date.From(Text.From(Date.Year([Ended])-1)&"/12/31"))),
#"Added Custom5" = Table.AddColumn(#"Added Custom4", "Year", each List.Numbers(Date.Year([Started]),Date.Year([Ended])-Date.Year([Started])+1)),
#"Expanded Custom" = Table.ExpandListColumn(#"Added Custom5", "Year"),
#"Added Custom1" = Table.AddColumn(#"Expanded Custom", "DaysLostForYear", each if [Year]=Date.Year([Started]) then [DaysYearStarted] else
if [Year]=Date.Year([Ended]) then [DaysYearEnded] else
if Date.IsLeapYear([Year]) then 366 else 365),
#"Grouped Rows" = Table.Group(#"Added Custom1", {"Event", "DaysLost", "Started", "Year"}, {{"DaysLostForYear", each List.Sum([DaysLostForYear]), type number}})
in
#"Grouped Rows"
A: 0) Importing the data from your Excel screenshot into Power BI results in this.
1) Create a new column in that table using the following formula for end date (to help with future formulas).
EndDate = Injuries[First Start Date] + Injuries[Days]
You stated that you have a calendar table, so you can skip to step 3
2) Create a new table by clicking on Modeling -> New Table and entering the following formula. This gives a single column table with a list of years.
Years = GENERATESERIES(2000, 2020, 1)
3) Create another new table using the following formula. This gives a table with all of the fields from the initial data table crossjoined with the Year table that was just created. The formula also filters the resulting table to only return rows where the value in the Year column is between the First Start Date and the First Start Date plus Days. To learn more about the CROSSJOIN function, check of the documentation here.
InjuriesByYear = FILTER(
CROSSJOIN(Years, Injuries),
Years[Year] >= Injuries[First Start Date].[Year] &&
Years[Year] <= Injuries[EndDate].[Year]
)
4) Create relationships from the InjuriesByYear table back to the initial data table and the Year table. This will help facilitate nicer reporting efforts.
5) In the InjuriesByYear table, create a new column by clicking on Modeling -> New Column and entering the following formula. The first IF checks if all of the days lost are in a single year. The second IF handles when the days are spread across multiple years, with the True clause handling the first year, and the False clause handling all other years.
DayPerYear = IF(
InjuriesByYear[Year] = InjuriesByYear[First Start Date].[Year] && InjuriesByYear[Year] = InjuriesByYear[EndDate].[Year], InjuriesByYear[Days],
IF(
InjuriesByYear[Year] = InjuriesByYear[First Start Date].[Year], DATEDIFF(InjuriesByYear[First Start Date], DATE(InjuriesByYear[First Start Date].[Year], 12, 31), DAY),
DATEDIFF(DATE(InjuriesByYear[Year], 1, 1), MIN(InjuriesByYear[EndDate], DATE(InjuriesByYear[Year], 12, 31)), DAY) + 1
)
)
6) To test it all out, create a pivot table as configured in below. Following these steps, the pivot table should match your Excel solution.
| |
doc_23526540
|
please help me! :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 20
void printsFriends(int friends, char** friendBook);
void changeFriends(int friends, char** friendsBook);
int main(void)
{
int i = 0, num = 0,friends=0;
char str[LENGTH];
int flag = 0;
int changeTo = 0;
printf("Hello friend,how U doin'?\nTell me how many friends do you have?\n");
scanf("%d", &friends);
getchar();
char** friendBook = (char**)malloc(sizeof(char*)*friends);
changeTo = friends;
if (friendBook)
{
for (i = 0; i < changeTo; i++)
{
friendBook[i] = malloc(LENGTH*sizeof(char));
}
changeFriends(changeTo, friendBook);
printsFriends(changeTo, friendBook);
while (!flag)
{
printf("\n\nPlease enter one of options:\n1.Change name of friend\n2.Change number of friends\n3.Exit and free the memory\n");
scanf("%d",&num);
getchar();
switch (num)
{
case 1:
printf("What number of friend do you want to change?\n");
scanf("%d", &num);
getchar();
printf("Enter name to change for\n");
fgets(str, LENGTH, stdin);
str[strcspn(str, "\n")] = 0;
friendBook[num - 1] =realloc(friendBook[num-1], (sizeof(char)*(strlen(str) + 1)));
if (*(friendBook + num - 1))
{
strcpy(*(friendBook + num - 1), str);
}
printsFriends(changeTo, friendBook);
break;
case 2:
printf("Enter number of friends you want:\n");
scanf("%d", &changeTo);
getchar();
friendBook = (char**)realloc(friendBook,sizeof(char*)*changeTo);
for (i = 0; i < changeTo; i++)
{
friendBook[i] = malloc(LENGTH*sizeof(char));
}
changeFriends(changeTo,friendBook );
printsFriends(changeTo, friendBook);
break;
case 3:
flag = 1;
printf("BYE BYE!\n");
break;
default:
printf("not good choice, enter again\n");
break;
}
}
}
for (i = 0; i < changeTo; i++)
{
free(friendBook[i]);
}
free(friendBook);
system("PAUSE");
return 0;
}
/*
This function get number of friends and friends book pointer to pointer and prints all the names.
input: number of friends and pointer to pointer of char's(array of strings)
output: none
*/
void printsFriends(int friends, char** friendBook)
{
int i = 0;
for (i = 0; i < friends; i++)
{
printf("Friend: %s\tLength of friend name %d\n", friendBook[i], strlen(friendBook[i]));
}
}
/*
this function gets number of friends and friends book and save to the array of strings names from stdin by the length of every string.
input: friends number and array of strings
output: none
*/
void changeFriends(int friends, char** friendBook)
{
int i = 0;
char str[LENGTH];
for (i = 0; i < friends; i++)
{
printf("Enter friend number %d: \n", i + 1);
fgets(str, LENGTH, stdin);
str[strcspn(str, "\n")] = 0;
friendBook[i] = realloc(friendBook[i], (sizeof(char)*(strlen(str) + 1))); // dynamic memory for every string(name)
if (friendBook[i])
{
strcpy(friendBook[i], str);
}
}
}
A: Whenever calling option 2, the old friendBook[i] pointers (for each i) are not freed.
| |
doc_23526541
|
I am using the following properties for the stream:
Properties properties = new Properties();
properties.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfig.getGroupId());
properties.put(StreamsConfig.CLIENT_ID_CONFIG, kafkaConfig.getClientId());
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, kafkaConfig.getApplicationId());
properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfig.getBootstrapServers());
properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, KafkaProtobufSerde.class);
properties.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, kafkaConfig.getSchemaRegistryUrl());
properties.put(KafkaProtobufDeserializerConfig.SPECIFIC_PROTOBUF_VALUE_TYPE, ProtobufData.class);
return properties;
}
but while running I encounter this error:
Caused by: java.lang.ClassCastException: class com.google.protobuf.DynamicMessage cannot be cast to class model.schema.proto.input.ProtobufDataProto$ProtobufData (com.google.protobuf.DynamicMessage and model.schema.proto.input.ProtobufDataProto$ProtobufData are in unnamed module of loader 'app')
My .proto files looks as follows:
import "inner_data.proto";
package myPackage;
option java_package = "model.schema.proto.input";
option java_outer_classname = "ProtobufDataProto";
message OuterData {
string timestamp = 1;
string x = 3;
repeated InnerObject flows = 4;
}
(I have two separate proto files)
package myPackage;
option java_package = "model.schema.proto.input";
option java_outer_classname = "InnerDataProto";
message InnerData {
string a = 1;
string b = 2;
string c = 3;
}
I would like to know why Kafka uses DynamicMessage even though I gave the specific protobuf value class in the properties and how to fix this?
A: I had the same issue while trying to make Kafkastream working with protobuf,
I solved this issue by using specifically KafkaProtobufSerde to configure the streambuilder AND by specifiing explicitly the class to deserialize to with this line: serdeConfig.put(SPECIFIC_PROTOBUF_VALUE_TYPE,ProtobufDataProto.class.getName());
/*
* Define SpecificSerde for Even in protobuff
*/
final KafkaProtobufSerde< ProtobufDataProto > protoSerde = new KafkaProtobufSerde<>();
Map<String, String> serdeConfig = new HashMap<>();
serdeConfig.put(SCHEMA_REGISTRY_URL_CONFIG, registryUrl);
/*
* Technically, the following line is only mandatory in order to de-serialize object into GeneratedMessageV3
* and NOT into DynamicMessages : https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/DynamicMessage
*/
serdeConfig.put(SPECIFIC_PROTOBUF_VALUE_TYPE,ProtobufDataProto.class.getName());
protoSerde.configure(serdeConfig, false);
Then i can create my input stream and it will be deserialized:
//Define a Serde for the key
final Serde<byte[]> bytesSerde = Serdes.ByteArray();
//Define the stream
StreamsBuilder streamsBuilder = new StreamsBuilder();
streamsBuilder.stream("inputTopic", Consumed.with(bytesSerde, protoSerde));
/*
add your treatments, maps, filter etc
...
*/
streamsBuilder.build();
| |
doc_23526542
|
MainActivity extends AppCompatActivity implements View.OnClickListener
init snackbar like this:
snackbar = Snackbar.make(view, R.string.msg, Snackbar.LENGTH_LONG);
snackbar.setAction(R.string.action_undo, this);
but I cannot handle it on implemented OnClickListener interface method
@Override
public void onClick(View v) {
// this not work!
// snackbar id is different from snackbar action id
if (v.getId() == snackbar.getView().getId()) {
}
}
Someone know how to get action view from snackbar?
A: For every Snackbar, the Snackbar textview resource id is
android.support.design.R.id.snackbar_text
And the Snackbar action view resource id is
android.support.design.R.id.snackbar_action
If I correctly understood your question, you want to get the Snackbar action resource id. you can easily get that as I mentioned above and in onClick() , you can use it like -
@Override
public void onClick(View v) {
if (v.getId() == android.support.design.R.id.snackbar_action) {
}
}
A: v.getId()
is always (Reserved) :
android.support.design.R.id.snackbar_action
Doc
A: You can try this to set action on a snackbar.
View.OnClickListener snackbarClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
}
};
snackbar = Snackbar.make(view, R.string.msg, Snackbar.LENGTH_LONG);
snackbar.setAction(R.string.action_undo, snackbarClickListener);
| |
doc_23526543
|
can someone please help me ?
if (isset($_POST['submit1'])) {
$cakename = $_POST['cakeName'];
$Beschreibung = $_POST['beschreibung'];
$Preis = $_POST['preis'];
$file = $_FILES['image'];
$fileName = $file["name"];
$filetype = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 2000000) {
$imageFullName = $cakename.".". uniqid("", true).".". $fileActualExt;
$fileDestination = "../Bake_my_cake1/image/".$imageFullName;
include_once 'lib/db_connector.php';
$db = dbconnect();
if (empty($Beschreibung) || empty($Preis)) {
header("Location: ../Bake_my_cake1/Profile_baker1.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM Cake;";
$stmt = mysqli_stmt_init($db);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed 1";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "INSERT INTO Cake (CakeName, Beschreibung, Preis, orderGallery) VALUES(?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed 2";
} else {
mysqli_stmt_bind_param($stmt, "ssss", $imageFullName, $Beschreibung, $Preis, $setImageOrder);
mysqli_stmt_execute($stmt);
echo "error 1";
move_uploaded_file($fileTempName, $fileDestination);
header("Location ../Bake_my_cake1/Profile_baker1.php?upload=sucess");
}
}
}
dbclose($db);
} else {
echo"File Size is too Big";
exit();
}
} else {
echo"You have an error";
exit();
}
} else {
echo"You need to upload a proper file type";
exit();
}
}
?>
else{
mysqli_stmt_bind_param($stmt,"ssss", $imageFullName, $Beschreibung, $Preis, $setImageOrder);
mysqli_stmt_execute($stmt);
echo "error 1";
move_uploaded_file($fileTempName,$fileDestination);
header("Location ../Bake_my_cake1/Profile_baker1.php?upload=sucess");
it is showing error 1 .
A: according to your variable name i'm assuming that your function dbconnect() returns database object. And you're passing that $db in mysqli_stmt_init instead of DB connection object.
ex.
If you are returning database connection object and storing it in $con then your code will be look like $stmt = mysqli_stmt_init($con).
Using this code you will not see "SQL statement failed 1" message and your code will be executed as expected.
| |
doc_23526544
|
Now I have to add a third-party client that can access some of our resources. For this, I created a client.
Now for a user that can authorize this third-party client for access the resources on behalf of him have to come to our website and login and then needs to authorize to get the authorization code. This I want to do in our own web app. For that, I need to create an API where as a request I will receive client_id, client_secret, grant_type, redirect_url, scopes, etc and return the authorization code.
But nowhere I see an option to create a custom API for generating the authorization code?
-- Edited
https://laravel.com/docs/9.x/passport#approving-the-request
As mentioned here Passport will automatically display a template to the user allowing them to approve or deny the authorization request
We have our own SPA, we can't use the template provided by Passport. Somehow we need to override this and create an API that our SPA can call for authoring or denying the authorization request.
A: To create custom api for authorization, you'll need to override default Passport routes in AuthServiceProvider.php
app/Providers/AuthServiceProvider.php
use Illuminate\Support\Facades\Route;
public function boot()
{
$this->registerPolicies();
Passport::routes();
Route::post('<route_you_want_to_override>', [
'uses' => '<YourCustomAuthorizationController@Method>',
'as' => 'passport.token',
]);
}
Once done make sure to clear the route cache
php artisan route:clear
And to override Passport default template, you'll first to need to publish the passport views so that required views are available at resources/views/vendor/passport path and you can modify the required view
php artisan vendor:publish --tag=passport-views
A: We had a similar need in our app a while ago.
We ended up using passport api for our need (with password grant) and we have put in place Sanctum for our end user/customer.
For customer, is much simpler/easy to get a unique token from Sanctum and then make api call with it.
The good part, is that you will have two separate system dedicated to two separate needs (yours and your customer).
I hope this helps you.
| |
doc_23526545
|
abc()
def()
...
ghi()
jkl()
Inside of a new function, what's the best way to call one of these chosen at random?
A: Create a list all <- list(abc, def, ... , ghi, jkl) and then call a random function from the list all[[sample(1:length(all),1]]()
| |
doc_23526546
|
public static <T> void printArray(T[] arr){
for(T t: arr){
System.out.print(t+" ");
}
System.out.println("");
}
but this one only works for class arrays, what if I have a char[] instead of a Character[], or a int[] instead of an Integer[], or is there a way to cast them before hand? Thanks
A: java.util.Arrays.toString(array) should do.
*
*commons-lang also have that - ArrayUtils.toString(array) (but prefer the JDK one)
*commons-lang allows for custom separator - StringUtils.join(array, ',')
*guava also allows a separator, and has the option to skip null values: Joiner.on(',').skipNulls().join(array)
All of these return a String, which you can then System.out.println(..) or logger.debug(..). Note that these will give you meaningful input if the elements of the array have implemented toString() in a meaningful way.
The last two options, alas, don't have support for primitive arrays, but are nice options to know.
A: You cant write a generic definition for primitive arrays. Instead, you can use method overloading and write a method for each primitive array type like this,
public static void printArray(int[] arr)
public static void printArray(short[] arr)
public static void printArray(long[] arr)
public static void printArray(double[] arr)
public static void printArray(float[] arr)
public static void printArray(char[] arr)
public static void printArray(byte[] arr)
public static void printArray(boolean[] arr)
A: private static void printArray(Object arr) {
// TODO Auto-generated method stub
String arrayClassName=arr.getClass().getSimpleName();
if (arrayClassName.equals("int[]"))
System.out.println(java.util.Arrays.toString((int[]) arr));
if (arrayClassName.equals("char[]"))
System.out.println(java.util.Arrays.toString((char[]) arr));
}
A: You can't pass primitive arrays to the printArray() method
| |
doc_23526547
|
I would like to count how many cells have a value (number or string) and display that number at the top of the column.
For example:
Hello
World
123
Some string
The above column would give me the answer of "4"
I have not managed to find a formula that does this.
A: An additional trick beside using =COUNTIF(...) and =COUNTA(...) is:
=COUNTBLANK(A2:C100)
That will count all the empty cells.
This is useful for:
*
*empty cells that doesn't contain data
*formula that return blank or null
*survey with missing answer fields which can be used for diff criterias
A: Shorter and dealing with a column (entire, not just a section of a column):
=COUNTA(A:A)
COUNTA
Beware, a cell containing just a space would be included in the count.
A: You could also use =COUNTA(A1:A200) which requires no conditions.
From Google Support:
COUNTA counts all values in a dataset, including those which appear
more than once and text values (including zero-length strings and
whitespace). To count unique values, use COUNTUNIQUE.
A: In the cell you want your result to appear, use the following formula:
=COUNTIF(A1:A200,"<>")
That will count all cells which have a value and ignore all empty cells in the range of A1 to A200.
A: The SUBTOTAL function can be used if you want to get the count respecting any filters you use on the page.
=SUBTOTAL(103, A1:A200)
will help you get count of non-empty rows, respecting filters.
103 - is similar to COUNTA, but ignores empty rows and also respects filters.
Reference : SUBTOTAL function
| |
doc_23526548
|
A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.) (.Net SqlClient Data Provider)
Help
| |
doc_23526549
|
The (simplified) code looks as follows:
mask0 = (df['condition'] == 1)
mask1 = (df['condition'] == 0)
df.loc[mask0, 'newColumn'] = df['otherColumn1']
df.loc[mask1, 'newColumn'] = df['otherColumn2']
However upon execution of the third line I get the following error:
ValueError: cannot reindex from a duplicate axis
If I simply do this, it works:
df.loc[mask0, 'newColumn'] = 1
What am I doing wrong?
A: You need to mask the "data provider" as well:
df.loc[mask0, 'newColumn'] = df[mask0, 'otherColumn1']
df.loc[mask1, 'newColumn'] = df[mask1, 'otherColumn2']
If the first condition is true if the latter is false and vice versa, we can use np.where(..):
df['newColumn'] = np.where(mask0, df['otherColumn0'], df['otherColumn2'])
or you can use np.select(..) in case the two can be both false where we fallback on the old values in case both conditons are False:
df['newColumn'] = np.select(
[mask0, mask1],
[df['otherColumn1'], df['otherColumn2']],
default=df['newColumn']
)
Here of course we make the assumption that newColumn already exists in the dataframe (for example through some previous processing).
A: Another solution with np.where:
df['newColumn'] = np.where(df['condition'].eq(1), df['otherColumn1'], df['condition'])
df['newColumn'] = np.where(df['condition'].eq(0), df['otherColumn2'], df['condition'])
A: You have to filter in both sides:
mask0 = (df['condition'] == 1)
mask1 = (df['condition'] == 0)
df.loc[mask0, 'newColumn'] = df.loc[mask0, 'otherColumn1']
df.loc[mask1, 'newColumn'] = df.loc[mask1, 'otherColumn2']
But here is better use numpy.select for avoid repeating code:
df['newColumn'] = np.select([mask0, mask1],
[df['otherColumn1'], df['otherColumn2']],
default=np.nan)
| |
doc_23526550
| ||
doc_23526551
|
Since I am using Windows Server and MSSQL for all my other projects I would very much like to use it on my Wordpress blog too. The wordpress site is quite big and important. The blog is beloved for its adult content. It has a revenue on thousands of dollars/month so I don't want to rush in anything here.
The Brandoo Wordpress is a part of the application gallery in Windows Platform Installer and also in Windows Azure.
So my questions are:
Since Brandoo Wordpress is a part of the apps in Azure, do you think it is quality assured by Microsoft?
I guess before Microsoft adds a web app to Azure and Platform Installer it has to be safe and bug free? Right?
I have tested my Wordpress locally with Brandoo Wordpress and it seems to work great so far.
A: I'm member of Brandoo WordPress team and I think I can help You. So... Brandoo WordPress is based on MSSQL. If You are using plugins that uses non-standard (same for MS and My SQL) db query You must face situation when You will must drop those plugins untill we will create translation for those queries that are not translated yet. There is also one thing. Brandoo WordPress is one step behind mainline right now. It's because some MySQL speciffic query in onsite search function. We do not want to fork WP and change it to MS schema so we are still working on translation or disabling this subfunction (If we willagree that this is a safe way to do it). If this is ok for You, then Brandoo WordPress is good for Your production.
A: I wouldn't call this a guarantee, but one of the principles of submission to the web app store is to "Be Safe"
| |
doc_23526552
|
Ie, Jobs have Quotes which have QuoteItems
var job = db.Jobs
.Where(x => x.JobID == id)
.Include(x => x.Quotes)
.Include(x => x.Quotes.QuoteItems) // This doesn't work
.SingleOrDefault();
Just to be clearer - I'm trying to retrieve a single Job item, and it's associated Quotes (one to many) and for each Quote the associated QuoteItems (One Quote can have many QuoteItems)
The reason I'm asking is because in my Quote Index view I'm trying to show the Total of all the Quote items for each Quote by SUMming the Subtotal, but it's coming out as 0. I'm calling the Subtotal like this:
@item.QuoteItem.Sum(p => p.Subtotal)
I believe the reason I have this issue is that my Linq query above isn't retrieving the associated QuoteItems for each Quote.
A: This did the trick for me as @flindeberg said here .
Just added checking if there are children in each parent item in the list
List<WCF.DAL.Company> companies = dbCtx.Companies.Where(x=>x.CompanyBranches.Count > 0)
.Include(c => c.CompanyBranches)
.Include("CompanyBranches.Address")
.ToList();
A: To get a job and eager load all its quotes and their quoteitems, you write:
var job = db.Jobs
.Include(x => x.Quotes.Select(q => q.QuoteItems))
.Where(x => x.JobID == id)
.SingleOrDefault();
You might need SelectMany instead of Select if QuoteItems is a collection too.
Note to others; The strongly typed Include() method is an extension method so you need to include using System.Data.Entity; at the top of your file.
A: The method in the accepted answer doesn't work in .NET Core.
For anyone using .NET Core, while the magic string way does work, the cleaner way to do it would be ThenInclude:
var job = db.Jobs
.Where(x => x.JobID == id)
.Include(x => x.Quotes)
.ThenInclude(x => x.QuoteItems)
.SingleOrDefault();
Source: Work with data in ASP.NET Core Apps | Microsoft Learn
A: This will do the job (given that we are talking entity framework and you want to fetch child-entities):
var job = db.Jobs
.Include(x => x.Quotes) // include the "Job.Quotes" relation and data
.Include("Quotes.QuoteItems") // include the "Job.Quotes.QuoteItems" relation with data
.Where(x => x.JobID == id) // going on the original Job.JobID
.SingleOrDefault(); // fetches the first hit from db.
For more information about the Include statement have a look at this: https://learn.microsoft.com/en-us/dotnet/api/system.data.objects.objectquery-1.include
This answer has been getting upvotes throught the years, so I'd just like to clarify, try https://stackoverflow.com/a/24120209/691294 first. This answer is for those cases where all else fails and you have to resort to a black magic solution (i.e. using magic strings).
| |
doc_23526553
|
org.dbunit.dataset.NoSuchColumnException: TOYOTA.CAR_MAKE - (Non-uppercase input column: CRTE_DT_TM) in ColumnNameToIndexes cache map. Note that the map's column names are NOT case sensitive.
when trying to populate a H2 DB using DbUnit in the context of a Spring JUnit test. The DDL for the H2 DB is created from JPA-annotated classes. However, the column does exist, it is in an abstract class that is extended by the core class.
Let me explain. The core JPA class looks like this:
@Entity
@Table(name = "TOYOTA")
public class Toyota extends Car {
@Id
@Column(name = "TOYOTA_REF")
private String toyotaRef;
@Column(name = "TOYOTA_DEALER")
private String toyotaDealer;
// etc.
The parent class looks like this:
public abstract class Car {
@Column(name = "CAR_MAKE")
private String carMake;
@Column(name = "CAR_MODEL")
private String carModel;
I'm initiating tests like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/test-spring-config.xml") // Load Spring Test context
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class}) // Used to load test data onto DB})
@DatabaseSetup(value = {"classpath:/integrationTestData/Toyota.xml"})
@Test
@Transactional
public void testSomething() {
and my Toyota.xml data file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<TOYOTA TOYOTA_REF="TOY123"
TOYOTA_DEALER="Big Dealer"
CAR_MAKE="Toyota"
CAR_MODEL="Corolla"
/>
</dataset>
Any thoughts?
A: Fixed this myself. I had to add this JPA annotation to the parent class:
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class Car {
| |
doc_23526554
|
var result = 0;
$('li').each(function(){
result += $(this).height();
alert(result);
if(result > 100){
$(this).css("color", "red");
}
});
But it seemed to not reinitialize the count when changing the ul. So it colors at 4th till the end. But what I want is to color only the 4th li because only him make the height exceed inside a ul. I tried to loop through ul but it did something weird..
Here is a fiddle: https://jsfiddle.net/ybonmbgt/31/
Thanks.
A: Then iterate all ul first and reset the counter before iterating over li under this ul
$('ul').each(function() {
var result = 0;
$(this).find("li").each(function() {
result += $(this).height();
if (result > 100) {
$(this).css("color", "red");
}
});
});
ul {
max-height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
<ul>
<li>Hello</li>
<li>how are you ? </li>
</ul>
</div>
<div class="list">
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
<li> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </li>
<li> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</li>
</ul>
</div>
<div class="list">
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</li>
<li> Ut enim ad minim veniam </li>
<li> Excepteur</li>
</ul>
</div>
Take a look at this fiddle
| |
doc_23526555
|
N=4e7 #number of simulation runs
n=2e5 #number of simulation runs between calculating time elapsed
meanStorer=rep(0,N);
toc=rep(0,N/n);
x=rep(0,50);
for (i in 1:N){
if(i%%n == 1){tic=proc.time()[3]}
x[]=runif(50);
meanStorer[i] = mean(x);
if(i%%n == 0){toc[i/n]=proc.time()[3]-tic; print(toc[i/n])}
}
plot(toc)
meanStorer is certainly large, but it is pre-allocated, so I am not sure why the loop slows down as time goes on. If I clear my workspace and run this code again it will start just as slow as the last few calculations! I am using Rstudio (in case that matters). Also here is some of my system information
*
*OS: Windows 7
*System Type: 64-bit
*RAM: 8gb
*R version: 2.15.1 ($platform yields "x86_64-pc-mingw32")
Here is a plot of toc, prior to using pre-allocation for x (i.e. using x=runif(50) in the loop)
Here is a plot of toc, after using pre-allocation for x (i.e. using x[]=runif(50) in the loop)
Is ?rm not doing what I think it's doing? Whats going on under the hood when I clear the workspace?
Update: with the newest version of R (3.1.0), the problem no longer persists even when increasing N to N=3e8 (note R doesn't allow vectors too much larger than this)
Although it is quite unsatisfying that the fix is just updating R to the newest version, because I can't seem to figure out why there was problems in version 2.15. It would still be nice to know what caused them, so I am going to continue to leave this question open.
A: As you state in your updated question, the high-level answer is because you are using an old version of R with a bug, since with the newest version of R (3.1.0), the problem no longer persists.
| |
doc_23526556
|
using:
Windows 8 Release Preview
Visual Studio 2012.
A: That is because WebView is not a typical XAML control. Hence, It doesn't support any Pointer/Gesture related events.
| |
doc_23526557
|
Way 1.
for(int i = 0; i < 100; i++){
Patterns.ask(Props.create(Worker.class),$someJobs, timeout);
}
Way 2.
for(int i = 0; i < 100; i++){
new Thread(new Runnable() {
@Override
public void run() {
//
getContext().actorOf(Props.create(Worker.class)).tell($someJobs, getSelf());
}
}).start();
}
In the way1, I print out the thread name like -akka.actor.default-dispatcher-4, but the dispatcher never come to 100. Why?
Thanks a lot
| |
doc_23526558
|
java.lang.ClassNotFoundException: com.ibm.db2.jcc.DB2Driver from [Module deployment.Shopping.war:main" from Service Module Loader]
How can I find a solution for that ?
A: Most probably you did not deploy the required DB2 JDBC driver correctly.
The simplest way to do this is to copy the drivers .jar file (should be called db2jcc-9.jar or similar) into the lib directory of your server configuration.
(For the default configuration, the /lib directory is *[JBOSS-HOME]/server/default/lib*).
| |
doc_23526559
|
Also, I know about auto_link, but it doesn't quite do what I'm trying to achieve. I just simply need a hash of all the url's from a string.
Thanks!
A: From http://www.regular-expressions.info/ruby.html
"To collect all regex matches in a string into an array, pass the regexp object to the string's scan() method, e.g.: myarray = mystring.scan(/regex/)."
So you probably need strings that start with "http". So check the docs for that :)
A: I don't program in Ruby and I'm not very good with regex but maybe this will help you out:
http://www.ozzu.com/programming-forum/url-regex-t104809.html
| |
doc_23526560
|
I add an NSView called tableView as a subview of workingBox. workingBox also contains some other subviews that were added with Interface Builder
[self.window setFrame:frame display:YES animate:YES];
[workingBox addSubview:tableView];
My problem is that if any of the other subviews touch tableView then they will get resized in the animation. The subviews that are not near where tableView is being added remain the correct size. I have already tried setting NSViewNotSizable resizeMask on the subviews that are getting resized but it does not work. The only thing that works is moving the subview upwards (into the wrong position.
EDIT: I have added a constraint in code:
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(divider);
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[divider(==1)]"
options:0
metrics:nil
views:viewsDictionary];
[workingBox addConstraints:constraints];
This keeps the NSView at 1px height but if I lock it to the top it prevents the superview growing
A: I could not make this work by adding a constraint in code. However in Interface Builder I could see that there was a constraint for the NSView in question that was named 'Bottom Alignment'. I changed this to a priority of 1 in the inspector and it stopped the NSView getting stretched down when the window expanded. I think this auto added constraint that I mentioned in my comment above had been the problem all along.
| |
doc_23526561
|
<EditForm Model="@samples" OnValidSubmit="@HandleValidSubmit">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in samples)
{
<tr>
<td><input type="checkbox" id="delete" name="delete" value="@forecast.Id" bind="@forecast.Id" /></td>
<td>@forecast.Id</td>
<td>@forecast.Title</td>
<td>@forecast.Description</td>
</tr>
}
<button type="submit">Delete selected</button>
<button @onclick=@Navigate>Add</button>
</tbody>
</table>
</EditForm>
My issue is that I cant figure out how to detect if the user has selected the checkbox.
private async void HandleValidSubmit()
{
using var context = DbFactory.CreateDbContext();
foreach (var sample in samples)
{
// check here if checkbox was checked.
//context.Samples.Remove(sample);
}
await context.SaveChangesAsync();
}
A: I ended up creating something to hold the samples that were deleted
<input type="checkbox" @onchange="@(async (e) => ToggleDelete(@sample))"/>
Then in code I add them to a list.
private List<Sample> deleteSamples = new List<Sample>();
private void ToggleDelete(Sample sample)
{
if (deleteSamples.Contains(sample))
{
deleteSamples.Remove(sample);
}
else
{
deleteSamples.Add(sample);
}
}
Which then lets me delete everything
private async void HandleValidSubmit()
{
using var context = DbFactory.CreateDbContext();
foreach (var sample in deleteSamples)
{
context.Samples.Remove(sample);
}
await context.SaveChangesAsync();
}
| |
doc_23526562
|
A: Two tables is not really enough to produce a good solution. You need a table for student, book, loan and inventory. This is a crude and basic setup but it will have the following definition:
CREATE TABLE student
(
studentId // key
// other columns
)
CREATE TABLE book
(
bookId // key
// other columns
)
CREATE TABLE inventory
(
bookId // FK
quantity
// other columns
)
CREATE TABLE loan
(
loanId int // key
studentId // FK
bookId // FK
// other columns
)
So now you can track who has book issued to them and the current number of books in the library.
| |
doc_23526563
|
My question is, how can I insert the image into PowerPoint using a VBA Macro? Or since the image always will have the same file path, but will be replaced with a different image, can I somehow "Update" the image on the slide? Sorry if it's confusing.
This is the VBA I tried:
Sub insert()
Dim oPic As Shape
Set oPic = ActivePresentation.Slides(1).Shapes.AddPicture("http://localhost/image.png", False, True, 0, 0, -1, -1)
End Sub
I could also get the path of the image on the computer, not the server.
When I run the macro, I get a "file not found" error. Does anyone know what's wrong?
Thanks!
PS: If anyone's interested, the plugin is called Signature Pad.
A: Looks like I can insert an image if it's in the exact same folder:
Sub insert()
Dim oPic As Shape
Set oPic = ActivePresentation.Slides(1).Shapes.AddPicture("image.png", False, True, 0, 0, -1, -1)
End Sub
This works, but if anyone knows how to go into another folder, please let me know. If I try folder/image.png or /folder/image.png as the file path, it doesn't work.
A: It doesn't need to be in the exact same folder, but you do need to use Mac-style paths:
#If Mac Then
imagePath = (MacScript("get path to startup disk as string") & "Users:name:Desktop:SomeFolder:My_Picture.png")
#Else
imagePath = "C:\path\to\My_Picture.png"
#End If
activeSlide.Shapes.AddPicture(imagePath, False, True, 10, 10)
Hope that helps.
| |
doc_23526564
|
For example the app with the AppID of 1 should only display one record displaying an average Rating of 3.333 and the other record should be AppID of 14 with an avg rating of 4.
SELECT reviews.Rating, reviews.AppID, apps.AppID, apps.image, apps.AppName, apps.Accepted
FROM reviews
JOIN apps
WHERE reviews.AppID = apps.AppID
So far the results give a separate rating for each ID.
I tried
GROUP BY AppID
with
AVG(Rating)
but I just cant quite get it.
Appreciate the help.
A: This should work for you:
SELECT AppID, AVG(Rating) AS AverageRating
FROM reviews
GROUP BY AppID
If you need the fields from the apps table, you can try this:
SELECT r.AverageRating, a.AppID, a.image, a.AppName, a.Accepted
FROM apps a
INNER JOIN (
SELECT AppID, AVG(Rating) AS AverageRating
FROM reviews
GROUP BY AppID) r
ON r.AppID = a.AppID
A: I believe the answer already given is correct. However, the OP was trying to get a bunch of columns. Perhaps the only issue was the group by needed to be wider. The OP did not comment on why the group by failed, whether it returned an unwanted result or if it didn't work. Using the OP's select target list, the group by would have to be pretty wide, like:
SELECT reviews.Rating, reviews.AppID, apps.AppID, apps.image, apps.AppName, apps.Accepted
FROM reviews
JOIN apps
WHERE reviews.AppID = apps.AppID
group by reviews.AppID, apps.AppID, apps.image, apps.AppName, apps.Accepted
-g
| |
doc_23526565
|
try
{
glogger.debug("Calling getReportData (BudgetInBriefDAO)");
lHashData = objBudgetInBriefDAO.getReportData(lStrFinYrId, lStrLangId, lStrContextPath, lStrFinYrDesc);
glogger.debug("Returning from getReportData (BudgetInBriefDAO)");
}
// catch( InvocationTargetException ie )
// {
// glogger.error("InvocationTargetException !!!");
// glogger.error("InvocationTargetException in calling BudgetInBriefBean -> getReportData");
// glogger.error("Target Exception is : " + ie.getTargetException());
// glogger.error("Cause is : " + ie.getCause());
// ie.printStackTrace();
// }
catch( Exception e )
{
glogger.error("Exception !!!");
glogger.error( "Error in calling BudgetInBriefBean -> getReportData. Error is :- " + e );
e.printStackTrace();
}
I am getting following Error:
FATAL : AJPRequestHandler-ApplicationServerThread-25
com.tcs.sgv.common.util.GenericEJBObject - InvocationTargetException
:java.lang.reflect.InvocationTargetException - 14 Feb 2012
12:36:00,155 - 5210474 milliseconds
It is not printing Stack Trace. How would I know the Cause of the Exception ?
I have uncommented code & still not getting the Stack Trace printed.
Between, my BudgetInBriefDAO Implementation (BudgetInBriefDAOImpl) contains 4 classes.
BudgetInBriefDAOImpl & 3 other Thread classes
I have decompiled all the class file successfullly without corruption.
Please help to find out Actual Cause of Exception.
Thanks in advance.
A: Try to decompile com.tcs.sgv.common.util.GenericEJBObject; maybe it swallows the exception.
Alternatively, start the app in debug mode and set a break point in all the constructors of InvocationTargetException.
Note: This might turn out to be impractical because other code causes a ton of these exceptions long before you get to the place you want to debug. If that happens, disable these breakpoints, add a new breakpoint at the first glogger.debug and enable the exception's breakpoints again when this one is hit.
When you have stack trace in your debugger, set a breakpoint in the place where the exception is thrown before doing anything else.
Last option: Set a breakpoint in glogger.fatal (or the place where the exception is logged).
| |
doc_23526566
|
__ __ _
/ / / /___ ____ _____ _(_)
/ / / / __ \/ __ / /
/ /_/ / / / / /_/ / /_/ / /
\____/_/ /_/\__,_/\__, /_/
/____/
So I added following at the end of .bashrc:
echo " __ __ _
/ / / /___ ____ _____ _(_)
/ / / / __ \/ __ `/ __ `/ /
/ /_/ / / / / /_/ / /_/ / /
\____/_/ /_/\__,_/\__, /_/
/____/ "
And it prints:
It seems that it is misinterpreting slash in ascii art as escape sequence, that why it is printing -bash: /: Is a directory. How can I get rid of it? If I add something simple to .bashrc, like echo "Hello World!!", it does not print this error message.
A: Use the single quote instead:
echo \
' __ __ _
/ / / /___ ____ _____ _(_)
/ / / / __ \/ __ `/ __ `/ /
/ /_/ / / / / /_/ / /_/ / /
\____/_/ /_/\__,_/\__, /_/
/____/
'
A: Try like this:
text=(
' __ __ _'
' / / / /___ ____ _____ _(_)'
' / / / / __ \/ __ `/ __ `/ /'
'/ /_/ / / / / /_/ / /_/ / /'
'\____/_/ /_/\__,_/\__, /_/'
' /____/'
)
printf '%s\n' "${text[@]}"
A: For a multi-line text literal, a HereDoc is very appropriate:
# Use a quoted heredoc 'marker' to disable expansion of backticks
cat <<'LOGO'
__ __ _
/ / / /___ ____ _____ _(_)
/ / / / __ \/ __ `/ __ `/ /
/ /_/ / / / / /_/ / /_/ / /
\____/_/ /_/\__,_/\__, /_/
/____/
LOGO
Un-quoted heredoc marker:
cat <<EOF
hello `echo world`
EOF
Output:
hello world
Quoted heredoc 'marker':
cat <<'EOF'
hello `echo world`
EOF
Output:
hello `echo world`
| |
doc_23526567
|
I found two functions for this: search:search, and cts:search. Which matches my needs best?
A: search:search is built on top of cts:search (as well as other APIs). They’re designed to work together. You should start with search:search, though. It is designed specifically for your faceted search use case and includes many conveniences and best practices that might not be obvious with the lower-level APIs, for example, concurrent facet resolution and pagination. If you need to do something more sophisticated than what search:search provides out-of-the-box, you can call out to other libraries.
| |
doc_23526568
|
Using the USA example, here is my code:
<script src="js/jquery.vmap.js"></script>
<script src="js/jquery.vmap.usa.js"></script>
<script>
jQuery('#vmap').vectorMap({
map: 'usa_en',
backgroundColor: null,
color: '#ffffff',
hoverColor: '#999999',
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
selectedRegions: ['MO', 'FL', 'OR']
});
</script>
<div id="vmap" style="width: 600px; height: 400px;"></div>
Here is the demo:
plnkr.co/edit/Znj282gvC0AdPMun14Az
A: The issue is a typo:
jquery.vmap.europe.js?dl=0 // you have this vmap "europe"
and you have referenced:
map: 'usa_en', // "usa"
change it to:
map: 'europe_en',
| |
doc_23526569
|
A: These are the differences between asp.net controls and html controls
*
*HTML server controls :
HTML server controls :are HTML tags understood by the server.
HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The id reference can be used to manipulate the server control at run time.
Note: All HTML server controls must be within a < form > tag with the
runat="server" attribute. The runat="server" attribute indicates that
the form should be processed on the server. It also indicates that the
enclosed controls can be accessed by server scripts.
Ex:
< input type="text" id="id1" runat="server" /> It will work.
HtmlTextControl class
< input type="button" id="id2" runat="sever" /> It will not work.
For html button control there is no compatiable version of control class.
corrected one is
< input type="submit" id="id2" runat="server" />
htmlButton class
< input type="reset" id="id2" runat="sever" /> This one will not work.
*
*ASP.NET - Web Server Controls
Web server controls are special ASP.NET tags understood by the server.
Like HTML server controls, Web server controls are also created on the
server and they require a runat="server" attribute to work. However,
Web server controls do not necessarily map to any existing HTML
elements and they may represent more complex elements.
The syntax for creating a Web server control is:
< asp:textbox id="Textbox1" runat="server" />
These are also case insensitive. Here the important thing is to compulsory write runat="server". For HTML controls this is optional.
all HTML < input type="text" /> control's attributes are also available for these asp tagged server controls. Some special attributes are also there which we will discuss on Ajax for special attributes.
A: The biggest deference in my opinion is that ASP.NET controls are executed on the server, with the resultant HTML sent to the client and that ASP .NET Server Controls can detect the target browser's capabilities and render themselves accordingly.
| |
doc_23526570
|
my_list = ['Paul', 'Robinson', 'Hismith', 'Smith']
I need to filter it and order the results by relevance:
> filter_list(my_list, 'smith')
> ['Smith', 'Hismith']
>
> filter_list(my_list, 'paul')
> ['Paul']
My list is small and it would be nice if I could use as less logic/libraries as possible.
How would you do this?
Thanks!
A: Try something like the following (you may want to tweak the cutoff= option though):
import difflib
my_list = ['Paul', 'Robinson', 'Hismith', 'Smith']
print difflib.get_close_matches('Paul', my_list)
# ['Paul']
print difflib.get_close_matches('Smith', my_list)
# ['Hismith', 'Smith']
A: Difficult to tell, what is the "relevance". In my answer I accept only if the sought word is within the element and sort the results by their length (good chances that 100% matches will appear first):
def filter_list(li, word):
return sorted((elem for elem in li if word.lower() in elem.lower()), key=len)
| |
doc_23526571
|
I have 500 products and I want to select cheapest and most expensive I am trying to get it as fast as possible because there will be more products everytime so
*
*TWO SELECTS
SELECT * FROM table ORDER BY price ASC LIMIT 1;
SELECT * FROM table ORDER BY price DESC LIMIT 1;
*ONE SELECT
SELECT min(price), max(price) FROM table;
second option looks faster but is limited by what i can get any types? ideas?
Thanks
A: ~1.4 million records, hope this provides some rough metrics
First query:
1 row in set (1.23 sec)
Second query:
1 row in set (1.21 sec)
Third query:
1 row in set (0.40 sec)
A: The Answer of your question really depends on your database server, from the tags I guess you're using MySQL, but even versions can really make a difference. A great database server executes the query in the fastest possible way.
Furthermore, your database structure can influence your query performance, using the right attributes as keys can increase the performance of searches by tenfold. (You'll lose performance on inserts).
In this particular case you should try both these query and test which is faster. (I think PHPmyAdmin has this functionality).
| |
doc_23526572
|
Is there same folder hierarchy as in PC Windows?
A: In order to access directories such as Pictures or Documents for a current user from an UWP app, you should use:
(Picture library in this case)
Windows.Storage.StorageLibrary.GetLibraryAsync
(Windows.Storage.KnownLibraryId.Pictures);
msdn article
| |
doc_23526573
|
I want to know why there would only be an encode function create_signed_value and no decode_signed_value or verify_signed_value.
Are you expected to set it in a cookie and use the get_secure_cookie although I'm struggling with actually setting it too?
A: UPDATE:
To decode a signed value created using create_signed_value, you can pass the signed value to the get_secure_cookie method (see docs):
signed_value = self.create_signed_value(name='auth', value='John Doe')
decoded_value = self.get_secure_cookie(name='auth', value=signed_value)
When I wrote the original answer, I was unaware of the API which I've mentioned above.
| |
doc_23526574
|
class X {
std::string& text;
public:
auto GetText() -> decltype(text) * { return &text); // doesn't work
X(std::string& text): text(text) {}
};
The easy way is to pass a pointer to this class. But if I pass a reference, can I get a pointer with a getter?
Edit: here is the error message
error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
^
A: Firstly,
auto GetText() -> decltype(text) * { return &text); // doesn't work
is a positively abominable way to declare this signature. Prefer
std::string* GetText(){ return &text);
or even just
auto GetText(){ return &text);
But this isn't code review.
The problem here is that you're asking for a pointer to the declared type of the text member variable which is a string reference (std::string&). From the comment section, it seems you were unaware that decltype respects the 'reference'ness, 'const'ness, and 'volatile'ness of its argument.
You cannot have a pointer to a reference in C++, e.g. std::string&* is malformed. Calling to std::remove_reference_t should resolve that issue, e.g.
auto GetText() -> std::remove_reference_t<decltype(text)> * { return &text);
However, in this case, auto would have correctly deduced your type anyway, so your explicit declaration is unnecessary.
A: I've made a test program for my initial problem. The program has a class with a pointer and a getter that returns a reference and a second class with a reference and a getter that returns a pointer.
And it seems that -> std::remove_reference_t<decltype(text)> can be substituted with -> decltype(&text).
Feel free to comment.
// g++ main.cpp -o test_reference_pointer && strip -s test_reference_pointer && ./test_reference_pointer
#include <iostream>
// A class with a pointer and a getter that returns a reference.
class A {
std::string *text;
public:
std::string& GetText_old_way() { return *text; }
auto GetText_pure_auto() { return *text; }
auto GetText_pointer_arithmetic() -> decltype(*text) & { return *text; }
public:
A(std::string *text): text(text) {}
};
// A class with a reference and a getter that returns a pointer.
class B {
std::string& text;
public:
std::string *GetText_old_way() { return &text; }
auto GetText_pure_auto() { return &text; }
auto GetText_pointer_arithmetic() -> decltype(&text) { return &text; }
auto GetText_remove_reference() -> std::remove_reference_t<decltype(text)> * { return &text; }
public:
B(std::string& text): text(text) {}
};
int main() {
std::string text = "hello, world";
{//TEST
A a(&text);
unsigned int i{0};
std::cout << "-- Test 1:"<< std::endl;
++i; std::cout << i << ". " << a.GetText_old_way() << std::endl;
++i; std::cout << i << ". " << a.GetText_pointer_arithmetic() << std::endl;
++i; std::cout << i << ". " << a.GetText_pure_auto() << std::endl;
std::cout << std::endl;
}
{//TEST
B b(text);
unsigned int i{0};
std::cout << "-- Test 2:"<< std::endl;
++i; std::cout << i << ". " << *b.GetText_old_way() << std::endl;
++i; std::cout << i << ". " << *b.GetText_pointer_arithmetic() << std::endl;
++i; std::cout << i << ". " << *b.GetText_remove_reference() << std::endl;
++i; std::cout << i << ". " << *b.GetText_pure_auto() << std::endl;
std::cout << std::endl;
}
return 0;
}
| |
doc_23526575
|
ID
Name
app_A
app_B
app_C
Total
0001
John Smith
0
5
3
8
0002
Peter Piper
2
0
3
5
0003
Susan Jones
1
0
0
7
0003
Susan Jones
0
2
4
7
...
...
...
...
...
...
You can see that there are some Duplicate IDs (and Names), and in these individual rows, the Totals are not correct, but if you were to add the columns together from both rows, then the total would be correct. How can I merge the duplicate rows so that I do not have duplicate IDs, and that the totals are correct.
The desired output is like below:
ID
Name
app_A
app_B
app_C
Total
0001
John Smith
0
5
3
8
0002
Peter Piper
2
0
3
5
0003
Susan Jones
1
2
4
7
...
...
...
...
...
...
A: Simple..aggregate app like columns with sum and Total with first
c = df.filter(like='app_')
df.groupby(['ID', 'Name']).agg({**dict.fromkeys(c, 'sum'), 'Total': 'first'})
Result
app_A app_B app_C Total
ID Name
0001 John Smith 0 5 3 8
0002 Peter Piper 2 0 3 5
0003 Susan Jones 1 2 4 7
| |
doc_23526576
|
Any ideas how we can make a float activity like the mini player that Google has implemented in their YouTube app?
A: You have to use ViewDragHelper with Service. Check this for creating dragView like youtube. You will get some idea from it.
A: You may set your Activity's window to be floating. You can do this either by giving your activity the Dialog style defined by Android (android:style/Theme.Dialog), or define your own style, like this:
<style name="MiniWindow">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:background">@android:color/transparent</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowNoTitle">true</item>
</style>
Explore more!
| |
doc_23526577
|
my expectation admin can add question first and admin can add options for that particular question question.
here i have added my code "ADD QUESTION" is working properly but once question added we need to create options for that particular question "ADD OPTIONS" not working properly
i have added both "ADD QUESTION" and "ADD OPTIONS" but when you add 2 or 3 question and remove its not working properly
for example i have added one question and 4 options for that qustion .after that if i click "ADD QUESTION" button question form is coming with 4 options field, here it should come only one option form field .its repeating the first question options
help me out to move forward
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {
name: '',
email: '',
questions: [
{
id: 'choice1'
}
],
questionoption: [
{
id: 'option1'
}
]
};
$scope.addNewChoice = function() {
var newItemNo = $scope.data.questions.length + 1;
$scope.data.questions.push({
'id': 'choice' + newItemNo
});
};
$scope.removeChoice = function() {
var lastItem = $scope.data.questions.length - 1;
$scope.data.questions.splice(lastItem);
};
$scope.OnSave = function() {
console.log($scope.data);
};
$scope.addNewoptions = function() {
var newItemNo = $scope.data.questionoption.length + 1;
$scope.data.questionoption.push({
'id': 'option' + newItemNo
});
};
$scope.removeOption = function() {
var lastItem = $scope.data.questionoption.length - 1;
$scope.data.questionoption.splice(lastItem);
};
});
fieldset {
background: #FCFCFC;
padding: 16px;
border: 1px solid #D5D5D5;
}
.fields {
background: #FCFCFC;
padding: 18px;
border: 1px solid red;
}
.addfields {
margin: 10px 0;
}
#choicesDisplay {
padding: 10px;
background: rgb(227, 250, 227);
border: 1px solid rgb(171, 239, 171);
color: rgb(9, 56, 9);
}
.remove {
background: #C76868;
color: #FFF;
font-weight: bold;
font-size: 21px;
border: 0;
cursor: pointer;
display: inline-block;
padding: 4px 9px;
vertical-align: top;
line-height: 100%;
}
input[type="text"],
select {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<button class="addfields" ng-click="addNewChoice()">Add question</button>
<br>
<label class="control-label col-sm-2">name</label>
<input type="text" ng-model="data.name" name="" placeholder="Add name">
<br>
<br>
<label class="control-label col-sm-2">email</label>
<input type="text" ng-model="data.email" name="" placeholder="Add emalil">
<br>
<br>
<fieldset data-ng-repeat="choice in data.questions">
<button class="addfields" ng-click="addNewoptions()">Add options</button><br>
<label class="control-label col-sm-2">Add Question</label>
<input type="text" ng-model="choice.name" name="" placeholder="Add Question">
<br>
<br>
<label class="control-label col-sm-2">Question order</label>
<input type="text" ng-model="choice.order" name="" placeholder="Add Question order">
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button><br><br>
<div class="fields" data-ng-repeat="option in data.questionoption">
<br>
<label class="control-label col-sm-2">Add options</label>
<input type="text" ng-model="option.options" name="" placeholder="Add options">
<br>
<br>
<label class="control-label col-sm-2">options order</label>
<input type="text" ng-model="option.order" name="" placeholder="Add Question order">
<button class="remove" ng-show="$last" ng-click="removeOption()">-</button>
</div>
</fieldset>
<br>
<br>
<button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>
<br>
<br>
<br>
<div id="choicesDisplay">
{{ data.questions }}
</div>
</div>
IF admin added one question(my expecttion result):
{
"name": "test",
"email": "as@gmail.com",
"questions": [{
"question": "Which of the following is the most important characteristic for a supervisor?",
"questionorder": "1",
"options": [{
"val": "Approachable",
"key": "options1"
},
{
"val": "Qualified",
"key": "options3"
},
{
"val": "Honest",
"key": "options2"
}
]
}]
}
DEMO
A: Please refer this fiddle I have corrected your code working
Html code
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<button class="addfields" ng-click="addNewChoice()">Add question</button>
<br>
<label class="control-label col-sm-2">name</label>
<input type="text" ng-model="data.name" name="" placeholder="Add name">
<br>
<br>
<label class="control-label col-sm-2">email</label>
<input type="text" ng-model="data.email" name="" placeholder="Add emalil">
<br>
<br>
<fieldset data-ng-repeat="choice in data.questions" ng-init="Index = $index">
<button class="addfields" ng-click="addNewoptions(Index)">Add options</button><br>
<label class="control-label col-sm-2">Add Question</label>
<input type="text" ng-model="choice.name" name="" placeholder="Add Question">
<br>
<br>
<label class="control-label col-sm-2">Question order</label>
<input type="text" ng-model="choice.order" name="" placeholder="Add Question order">
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button><br><br>
<div class="fields" data-ng-repeat="option in choice.options">
<br>
<label class="control-label col-sm-2">Add options</label>
<input type="text" ng-model="option.option" name="" placeholder="Add options">
<br>
<br>
<label class="control-label col-sm-2">options order</label>
<input type="text" ng-model="option.order" name="" placeholder="Add Question order">
<button class="remove" ng-show="$last" ng-click="removeOption(Index)">-</button>
</div>
</fieldset>
<br>
<br>
<button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>
<br>
<br>
<br>
<div id="choicesDisplay">
<!-- {{ data.questions }} -->
</div>
</div>
Controller
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.data = {
name: '',
email: '',
questions: [
{
id: 'choice1',
options : [{
optid:'option1'
}]
}]
};
$scope.addNewChoice = function() {
var newItemNo = $scope.data.questions.length + 1;
$scope.data.questions.push({
'id': 'choice' + newItemNo,
'options' : []
});
};
$scope.removeChoice = function() {
var lastItem = $scope.data.questions.length - 1;
$scope.data.questions.splice(lastItem);
};
$scope.OnSave = function() {
console.log($scope.data);
};
$scope.addNewoptions = function(quest) {
var newItemNo = $scope.data.questions[quest].options.length + 1;
$scope.data.questions[quest].options.push({
'optid': 'option' + newItemNo
});
};
$scope.removeOption = function(quest) {
var lastItem = $scope.data.questions[quest].options.length - 1;
$scope.data.questions[quest].options.splice(lastItem);
};
});
| |
doc_23526578
|
I made sure I have the most up to date unity and VisualStudio with all relevant plugins.
https://gist.github.com/EgoSphere001/288818beb7ad0d2db2bdda028508c76e
A: Please look at your script again
public class PlayerMovement : MonoBehaviour
{
public PlayerMovement()
{
}
}
public Rigidbody rb;
// Start is called before the first frame update
private void Start() => Debug.Log("Hello, World!");
// Update is called once per frame
private void Update()
{
}
You are closing the PlayerMovement class ... so where does rb and Update belong to?! You expression body for Start is ok-ish but I would suggest to stick with a normal method declaration.
Also MonoBehaviours can not be generated using a constructor so the public PlayerMovement(){ makes no sense either.
Your script should probably look like this
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
// Start is called before the first frame update
private void Start()
{
Debug.Log("Hello, World!");
}
// Update is called once per frame
private void Update()
{
}
}
Also note: You should remove any empty Unity messages like Update, Start etc .. because Unity calls them anyway causing unnecessary overhead.
| |
doc_23526579
|
CODE:
var synth = new SpeechSynthesizer();
foreach (var voice in SpeechSynthesizer.AllVoices)
{
synth.Voice = voice;
var text = "Hello World";
var stream = await synth.SynthesizeTextToStreamAsync(text);
var me = new MediaElement();
me.SetSource(stream, stream.ContentType);
me.Play();
await Task.Delay(3000);
}
A: You can change the Gender and age using StartVoice(VoiceGender gender, VoiceAge age)
Simple Example:
PromptBuilder pb = new PromptBuilder();
pb.StartVoice(VoiceGender.Male, VoiceAge.Child);
pb.AppendText("I like my toy car");
pb.EndVoice();
You might want to search for TTS's that support your desired picth.
Here is the link for all languages available: Languages
Cheers
| |
doc_23526580
|
db.collections.update({ id: uid }, { $unset: [ "<field1>", "<field2>", ... ] })
My question is this. How can we achieve this with Pymongo.?
A: Pymongo is generally similar to the mongodb shell commands, but it has to work within the constraints of the python syntax. Importantly, you must put the $ operators in quotes, so "$unset" as per below.
db.collections.update_one({ "id": uid }, { "$unset": [ "", "", ... ] })
If this doesn't work, post the error you are getting.
| |
doc_23526581
|
{{1,2}}
instead of
{frozenset({1,2})}
Input
t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]
t1 = set(frozenset(i) for i in t)
print(t1)
Output
{frozenset({1, 2}), frozenset({1, 2, 5}), frozenset({1, 2, 3, 4}), frozenset(), frozenset({1, 2, 3, 6}), frozenset({5})}
A: You can define your class that is inherited from frozenset like:
class myFrozen(frozenset):
def __repr__(self):
return set(self).__repr__()
def __str__(self):
return set(self).__str__()
t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]
t1 = set(myFrozen(i) for i in t)
print(t1)
Output:
{{1, 2}, {1, 2, 5}, {1, 2, 3, 4}, set(), {1, 2, 3, 6}, {5}}
Note that in this example, for __repr__() and __str__() functions, I am just using the default functions in set class. If you wish not showing the set() for empty sets, you can change the functions as you with to print. For instance:
class myFrozen(frozenset):
def __repr__(self):
return '{' + ",".join(str(x) for x in self) + '}'
def __str__(self):
return self.__repr__()
t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]
t1 = set(myFrozen(i) for i in t)
print(t1)
# {{1,2}, {1,2,5}, {1,2,3,4}, {}, {1,2,3,6}, {5}}
A: If all you need is less verbose output, I'd just use a quick list comprehension..
print([set(s) for s in t])
# Output: [{1, 2}, {1, 2, 5}, {1, 2, 3, 4}, set(), {1, 2, 3, 6}, {5}]
| |
doc_23526582
|
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">
<bean id="productServiceImpl" class="com.demo.ws.CustomerServiceImpl" />
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="cxf:bean:productServiceEndpoint" />
<bean ref="productServiceImpl" />
<!-- log input received -->
<to uri="log:output" />
</route>
</camelContext>
<cxf:cxfEndpoint id="productServiceEndpoint"
address="http://localhost:9001/productService" serviceClass="com.demo.ws.CustomerService" />
</beans>
The SEI and implementation classes I'm using are trivial:
@WebService(serviceName="customerService")
public interface CustomerService
{
public String getCustomerById(String customerId);
}
public class CustomerServiceImpl implements CustomerService
{
@Override
public String getCustomerById(String customerId)
{
System.out.println("Called with "+customerId);
return "Hello " +customerId;
}
}
When running the project, the Webservice the implementation class is called correctly, returning the String "Hello [name]", however the returned body from SOAPUI is empty:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body/>
</soap:Envelope>
Can you help me to produce the return value in the Response ?
Thank you
A: You should return a SOAP message :
SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();
QName payloadName = new QName("http://apache.org/hello_world_soap_http/types", "greetMeResponse", "ns1");
SOAPBodyElement payload = body.addBodyElement(payloadName);
SOAPElement message = payload.addChildElement("responseType");
message.addTextNode("Your custom message");
return soapMessage;
You can also take a look to the camel doc examples : http://camel.apache.org/cxf-example.html
| |
doc_23526583
|
I see questions that are saying that this package is not compatible with umbraco 4.7.1, but it is working fine for me... is the package compatible with umbraco 4.7.1 ?
When should I choose repetable custom content over creating nodes of a certain datatype ? Which option is better for performance ?
Is it possible to index/include repetable fields in examine search ?
Thanks.
Repetable Custom Content
A: Repeatable custom content is very useful if the number of fields you have is small and they are logically part of the content node you are editing. By this I mean a collection of content that is part of the page you are editing. An example of which may be a list of links with a description, name etc.
Child nodes make most sense if the content is related but not necessarily part of the same page. Or if the content in question has lots of data. The trade off with child nodes is that they are slightly slower to add.
Another benefit of child nodes is that they are selectable and sharable amongst nodes easily. For instance a content panel that can be shared amongst pages.
There is no right or wrong way to use either nodes or repeatable content, however the main thing to consider is the ease of editing experience. As from a developer perspective it doesn't make much difference.
In terms of compatibility if you know that the package is working in a version of Umbraco that is not listed as compatible on the Package page on our.umbraco.org, then you can click the Report Compatibility link to indicate which version of Umbraco you have tested it with. This will ensure that the information is up to date.
| |
doc_23526584
|
Have a look at the cartoon example below. It shows two flat color circles on a flat color background.
The local binary pattern (P=8 samples, Radius=1) output is:
(Image is color coded in jet colors). The gray color correctly represents 255. However, the blue color is 85 (binary 01010101).
So while the method correctly shows the background and the circle on the right as 255, it shows the left circle as 85. Apparently, the local binary pattern method in skimage thinks the region is completely noisy (hence the alternating binary pattern 01010101). This is not true, however, as I have double checked the individual pixels in the region shown in blue above and their values are identical (i.e. its flat color, just like the flat color background and other flat color circle).
Has anyone experienced a similar problem before?
Here is the code if you want to replicate this:
from skimage.feature import local_binary_pattern
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
img = plt.imread('circles.png')
img = rgb2gray(img)
lbp = local_binary_pattern(img, 8, 1, 'default')
plt.imshow(lbp, cmap='nipy_spectral')
plt.title('Standard lbp (8,1)')
A: I guess the issue is due to numeric errors. When the color image is read using
img = plt.imread('circles.png')
you get an array of type float32 and in the subsequent conversion to grayscale
img = skimage.color.rgb2gray(img)
the resulting image is of type float64.
I recommend you to avoid the intermediate step. You could read the image with double precision (i.e. float64) from the very beginning like this:
In [63]: from skimage.feature import local_binary_pattern
In [64]: from skimage import io
In [65]: img = io.imread('circles.png', as_grey=True)
In [66]: img.dtype
Out[66]: dtype('float64')
In [67]: lbp = local_binary_pattern(img, 8, 1, 'default')
In [68]: io.imshow(lbp/255., cmap='nipy_spectral')
Out[68]: <matplotlib.image.AxesImage at 0x10bdd780>
| |
doc_23526585
|
I use opencv 3.2 to read image to Mat, and I can get Mat data and use memcpy to copy the Mat.data then create a new image in local client. But when I send Mat.data to server, the first of characters in the Mat.data is '\0'. All the Mat.data don't send to server.
My MIDL core code(I have defined uuid and version) is
void Output(
[in, out, size_is(1048576), string] unsigned char szString[]
);
void Output1(
[in, string] unsigned char* szString1
);
My Client core code(It has include all require header) is
Mat I = imread("U:\\normal.jpg", IMREAD_ANYDEPTH);
if (I.empty())
{
std::cout << "!!! Failed imread(): image not found" << std::endl;
// don't let the execution continue, else imshow() will crash.
}
if (!I.data) {
std::cout << "can't open or find image" << std::endl;
//return -1;
}
Mat out;
I.convertTo(I, CV_32F);
I = (I.reshape(0, 1)); // to make it continuous
char tr[512*512*4];
memcpy_s(tr, 512 * 512 * 4, I.data, 512*512 * 4);
//snprintf(tr, 512*512*4,"%s", I.data);
out = Mat(512,512, CV_32F, &tr[0]);
namedWindow("Display window", CV_WINDOW_AUTOSIZE);// Create a window for display.
imshow("Display window", out);
waitKey(5000);
.....
RpcTryExcept
{
std::clog << "Calling Open" << std::endl;
output((unsigned char* )tr);
//output1((unsigned char* )tr);
}
Server side is pretty same with client, I use break point in server to debug, but server side can't get the unsigned char array. I think it's because my function in MIDL just can send the char array, which is end by a null terminated('\0') string? I tried set the array length or the size of the char pointer but still can't transmit '\0' unsigned char to server.
A: From the MSDN explanation, when you sending array to stub you need to specify length_is also in your midl code.
The [ size_is] attribute indicates the upper bound of the array while the [ length_is] attribute indicates the number of array elements to transmit. In addition to the array, the remote procedure prototype must include any variables representing length or size that determine the transmitted array elements (they can be separate parameters or bundled with the string in a structure). These attributes can be used with wide-character or single-byte character arrays just as they would be with arrays of other types.
And
As an [in] parameter, achInOut must point to valid storage on the client side. The developer allocates memory associated with the array on the client side before making the remote procedure call.
The stubs use the [size_is] parameter strsize to allocate memory on the server and then use the [length_is] parameter pcbSize to transmit the array elements into this memory. The developer must make sure the client code sets the [length_is] variable before calling the remote procedure.
Their example of character array sending:
#define STRSIZE 500 //maximum string length
void Analyze(
[in, out, length_is(*pcbSize), size_is(STRSIZE)] char achInOut[],
[in, out] long *pcbSize);
/* client */
char achInOut[STRSIZE];
long cbSize;
...
gets_s(achInOut, STRSIZE); // get patient input
cbSize = strlen(achInOut) + 1; // transmit '\0' too
Analyze(achInOut, &cbSize);
/* server */
Analyze(char * str, long * pcbSize)
{
...
*pcbSize = strlen(str) + 1; // transmit '\0' too
return;
}
I think, this msdn link will help you.
A: Do you have to use OpenCV to read image data? Since this post has not been closed, you can try this alternative way to open image file(it works for text file as well) in binary mode, then read/save data into a float array, send it to server. I wrote a simple demo. It works and avoid the null-terminator problem for string.
Sender:
//Open file
char filename[] = "demo1.jpg";
FILE *fp = fopen(filename,"rb");
//Get File size
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
//Read file to buffer
float *img = new float[size];
fread(img, 1, size, fp);
RpcTryExcept
{
//Call your function pre-defined in IDL here to send float arry
}
Receiver:
FILE *fp = fopen((char *)fileName, "wb");
int recvByte = fwrite(img, 1, size, fp);
| |
doc_23526586
|
typedef void func(unsigned char);
void test(unsigned char a);
int main()
{
unsigned char b=0U;
func *fp=&test;
while(1)
{
fp(b);
b++;
}
}
void test(unsigned char a)
{
printf("%d",a);
}
I don't get what is the the difference between using the function pointer syntax and this approach? Both seem to almost yield the same functionality.
A: The style
typedef void func_t (void);
...
funct_t* fp;
Is one of the clearest ways to declare function pointers. Clear because it is consistent with the rest of the pointer syntax of C.
It is equivalent to the slightly less readable
typedef void (*func_t)(void);
func_t fp;
Which in turn is equivalent to the much less readable
void (*fp)(void);
The advantage of the first style becomes obvious when you pass these as parameters to a function:
1) void sort (func_t* callback); // very clear and readable!
2) void sort (func_t callback); // hmm what is this? passing by value?
3) void sort (void(*callback)(void)); // unreadable mess
Generally, it is a bad idea to hide the pointer syntax behind typedefs. Function pointers are no exception.
A: You are creating a function pointer with the declaration i.e.
func *fp = &test; // fp is a function pointer!
The other way would be to typedef the pointer,
typedef void (*func)(unsigned char);
func fp = &test; // Notice, no '*' in the declaration?
A: If func were typedefed as function pointer then the statement
func *fp=&test;
would be
func fp=&test;
| |
doc_23526587
|
For example if one div has 5 lines of text in it, and the others all have 2, then they all need to stretch to match the height of the one with 5 lines.
How can I do this by the elements' classes?
A: var mh=0;
$(".some-class-name").each(function () {
if (mh < $(this).height()) {
mh=$(this).height()
}
})
$(".some-class-name").height(mh);
A: $(document).ready(function(){
var el = $('.one'),
elHeight = [];
el.each(function(){
elHeight.push($(this).height());
});
el.height(Math.max.apply(Math, elHeight));
});
http://jsbin.com/qovacanari/1/edit?html,js,console,output
| |
doc_23526588
|
I'm looking into using the PEMReader class from BouncyCastle, but I can't get past some errors. I'm running the Java client with the -Djavax.net.debug=all option and Apache web server with the debug LogLevel. I'm not sure what to look for though. The Apache error log indicates:
...
OpenSSL: Write: SSLv3 read client certificate B
OpenSSL: Exit: error in SSLv3 read client certificate B
Re-negotiation handshake failed: Not accepted by client!?
The Java client program indicates:
...
main, WRITE: TLSv1 Handshake, length = 48
main, waiting for close_notify or alert: state 3
main, Exception while waiting for close java.net.SocketException: Software caused connection abort: recv failed
main, handling exception: java.net.SocketException: Software caused connection abort: recv failed
%% Invalidated: [Session-3, TLS_RSA_WITH_AES_128_CBC_SHA]
main, SEND TLSv1 ALERT: fatal, description = unexpected_message
...
The client code :
public void testClientCertPEM() throws Exception {
String requestURL = "https://mydomain/authtest";
String pemPath = "C:/Users/myusername/Desktop/client.pem";
HttpsURLConnection con;
URL url = new URL(requestURL);
con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(getSocketFactoryFromPEM(pemPath));
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(false);
con.connect();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
con.disconnect();
}
public SSLSocketFactory getSocketFactoryFromPEM(String pemPath) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TLS");
PEMReader reader = new PEMReader(new FileReader(pemPath));
X509Certificate cert = (X509Certificate) reader.readObject();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("alias", cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, null);
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory();
}
I noticed the server is outputing SSLv3 in the log while the client is TLSv1. If I add the system property -Dhttps.protocols=SSLv3 then the client will use SSLv3 as well, but I get the same error message. I've also tried adding -Dsun.security.ssl.allowUnsafeRenegotiation=true with no change in outcome.
I've googled around and the usual answer for this question is to just use openssl and keytool first. In my case I need to read the PEM directly on the fly. I'm actually porting a C++ program that already does this, and frankly, I'm very surprised how difficult it is to do this in Java. The C++ code:
curlpp::Easy request;
...
request.setOpt(new Options::Url(myurl));
request.setOpt(new Options::SslVerifyPeer(false));
request.setOpt(new Options::SslCertType("PEM"));
request.setOpt(new Options::SslCert(cert));
request.perform();
A: I figured it out. The problem is that the X509Certificate by itself isn't sufficient. I needed to put the private key into the dynamically generated keystore as well. It doesn't seem that BouncyCastle PEMReader can handle a PEM file with both cert and private key all in one go, but it can handle each piece separately. I can read the PEM into memory myself and break it into two separate streams and then feed each one to a separate PEMReader. Since I know that the PEM files I'm dealing with will have the cert first and the private key second I can simplify the code at the cost of robustness. I also know that the END CERTIFICATE delimiter will always be surrounded with five hyphens. The implementation that works for me is:
protected static SSLSocketFactory getSocketFactoryPEM(String pemPath) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TLS");
byte[] certAndKey = fileToBytes(new File(pemPath));
String delimiter = "-----END CERTIFICATE-----";
String[] tokens = new String(certAndKey).split(delimiter);
byte[] certBytes = tokens[0].concat(delimiter).getBytes();
byte[] keyBytes = tokens[1].getBytes();
PEMReader reader;
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(certBytes)));
X509Certificate cert = (X509Certificate)reader.readObject();
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(keyBytes)));
PrivateKey key = (PrivateKey)reader.readObject();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, "changeit".toCharArray(), new Certificate[] {cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, "changeit".toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory();
}
Update: It seems this can be done without BouncyCastle:
byte[] certAndKey = fileToBytes(new File(pemPath));
byte[] certBytes = parseDERFromPEM(certAndKey, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(certAndKey, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);
...
protected static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) {
String data = new String(pem);
String[] tokens = data.split(beginDelimiter);
tokens = tokens[1].split(endDelimiter);
return DatatypeConverter.parseBase64Binary(tokens[0]);
}
protected static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey)factory.generatePrivate(spec);
}
protected static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));
}
A: Although the answer of Ryan works well I want to provide an alternative for other developers as I faced a similar challenge in the past where I also needed to handle encrypted private keys in pem format. I have created a library to simplify loading pem files and creating SSLSocketFactory or SSLContext out of it, see here: GitHub - SSLContext Kickstart I hope you like it :)
The pem files can be loaded with the following snippet:
var keyManager = PemUtils.loadIdentityMaterial("certificate-chain.pem", "private-key.pem");
var trustManager = PemUtils.loadTrustMaterial("some-trusted-certificate.pem");
var sslFactory = SSLFactory.builder()
.withIdentityMaterial(keyManager)
.withTrustMaterial(trustManager)
.build();
var sslContext = sslFactory.getSslContext();
var sslSocketFactory = sslFactory.getSslSocketFactory();
Coming back to your main question, with the above snippet it is not needed to create a keystore object from the pem files. It will take care of that under the covers and it will map it to a KeyManager instance.
| |
doc_23526589
|
In the index.html
<link rel="manifest" href="<%= htmlWebpackPlugin.files.publicPath %>static/manifest.json">
And in my main.js
if('serviceWorker' in navigator) {
const messaging = firebase.messaging()
navigator.serviceWorker.register('/static/sw.js').then((registration) => {
messaging.useServiceWorker(registration)
console.log('Service Worker registered')
}).catch((error) => {
console.log('Service Worker failed to register')
})
}
It looks like it works, but when I try to add the webapp to my homescreen using DevTools, it shows the following error:
"Site cannot be installed: no matching service worker detected. You may need to reload the page, or check that the service worker for the current page also controls the start URL from the manifest"
After doing some research I found people say place the sw.js and manifest.json in the root of the project. But when I do, it won't link the files (when I put them in the static folder, it will link them). By the way, I'm using the standard Vue.js template.
Any suggestions how to fix this?
A: The reason to the service worker failed to register could be 1 of these:
*
*You are not running your application through HTTPS.
*The path to your service worker file is not written correctly — it
needs to be written relative to the origin, not your app’s root directory.
Structure wise, it should be like this
/static/
/css/
/js/
/img/
manifest.json
index.html
service-worker.js
In the index file, you should register the service worker similar to this
<script type=text/javascript>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error:', error);
});
}
</script>
and connect manifest.json
<link rel=manifest href=/manifest.json>
Content of manifest.json can be
{
"name": "vue-vanilla-pwa",
"short_name": "vue-vanilla-pwa",
"icons": [
{
"src": "/static/img/icons/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/static/img/icons/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/index.html",
"display": "standalone",
"background_color": "#000000",
"theme_color": "#4DBA87"
}
sw-precache is designed specifically for the needs of precaching some critical static resources. So if you want to do something else with service worker when user is offline, you don't need it. Here is an example list of what you can do with service workers: https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker
| |
doc_23526590
|
So, I faced a question. The web page quotes some css/js files in header, but I saw that 'href' value is relative path. Then the page will not show correctly in WebView.
[Updated]
For example, I'm using HttpClient to request a URI (http://example.com), then I will get the whole html page string. I will do some operations on this html string. After that, I will use WebView.NavigateToString(htmlpage) method to show this page. But if you check its head tag, there will be some <link> tag, its href value is relative path(/style-a/1.css), not absolute path. Then you will find that the html page doesn't show correctly in WebView.
Could someone give me a solution/code sample?
@Pedro Lamas, rene, Barett, moi_meme, Shachaf.Gortler Please do not put my question on hold. I didn't break any SO rules. My question was very clear. I think you do this, it's because you do not know how to answer my question. That's ok. If you don't know, you could choose not to answer it, but please do not put it on hold.
A: You can set address of your Link or Scripts tag with ms-appx-web:// and put address after that with additional [ / ] .
for example in this case you can use :
<script src="ms-appx-web:///Assets/FolderName/test.js" type="text/javascript"></script>
and also for link can use :
<link rel="stylesheet" type="text/css" href="ms-appx-web:///style-a/1.css">
| |
doc_23526591
|
In pubspec.yaml, I set my transformers like this:
transformers:
- web_components:
entry_points:
- web/foo.html
- test/my_component_test.html
- reflectable:
entry_points:
- web/foo.dart
- test/pub_serve:
$include:
- test/**_test{.*,}.dart
my_component_test.html looks like this:
<!doctype html>
<html>
<head>
<title>Custom HTML Test</title>
<link rel="x-dart-test" href="my_component_test.dart">
<script src="packages/test/dart.js"></script>
</head>
<body><my-component id="abc"></my-component></body>
</html>
my_component_test.dart like this:
@TestOn("browser")
import "dart:html";
import "package:test/test.dart";
import 'package:polymer/polymer.dart';
import '../web/my_component.dart';
void main() {
MyComponent componentUnderTest;
setUpAll(() {
return initPolymer();
});
setUp(() {
componentUnderTest = document.body.querySelector("#abc");
});
test("my-component should be initialized correctly", () {
Element heading = componentUnderTest.shadowRoot.querySelector('h1');
expect(heading.text, equals('This is my component'));
});
}
If I try to run the tests using pub serve and pub run test:test --pub-serve=8081 -p firefox in two separate terminals, there are two different errors:
[Error from WebComponents on polymer_dart_example|test/my_component_test.html]:
Unable to import `polymer_dart_example/web/my_component.dart` from polymer_dart_example|test/my_component_test.bootstrap.initialize.dart.
[Error from WebComponents on polymer_dart_example|test/my_component_test.html]:
Can't import `polymer_dart_example|web/my_component.dart` from `polymer_dart_example|test/my_component_test.bootstrap.initialize.dart`
Build error:
Transform WebComponents on polymer_dart_example|test/my_component_test.html threw error: Could not format because the source could not be parsed:
line 16, column 1 of <unknown>: Directives must appear before any declarations
import 'package:polymer/src/common/polymer_register.dart' as i13;
while compiling and
NullError: receiver is undefined
package:web_components/src/init.dart 31:1 J.$asx
package:polymer/init.dart 28:22 <fn>
package:stack_trace init.<fn>.<fn>
package:polymer/init.dart 31:3 dart<._setUpPropertyChanged
package:path/src/style/windows.dart 95:71 dart<.initPolymer.<fn>
===== asynchronous gap ===========================
while testing (caused by initPolymer()).
I suspect there is something wrong with my configuration, but I can't figure out what the problem is. The component itself is working fine.
A: test/my_component_test.dart needs to be added to the reflectable transformer.
I'm also pretty sure await initPolymer(); needs to be outside the setUpAll() method, at least there is no reason to wrap it with setUpAll().
void main() async {
MyComponent componentUnderTest;
await return initPolymer();
...
test(...);
group(...);
}
Related issue https://github.com/dart-lang/polymer-dart/issues/649
| |
doc_23526592
|
I am getting an error when try to build to prod with ng build --prodinlike below:
Property 'loading$' does not exist on type 'MatTableDataSource'
Here is how I implement in a component:
public dataSource = new MatTableDataSource<Employee>();
ngOnInit(){
this.repository.getData(`employee/list`).subscribe(
res => {
this.dataSource.data = res as Employee[];
}
)
}
It throws this error in the template:
<div class="mat-table__bottom">
<!-- MATERIAL SPINNER | Url: 'https://material.angular.io/components/progress-spinner/overview' -->
<mat-spinner [diameter]="20" *ngIf="dataSource.loading$ | async"></mat-spinner>
<!-- MATERIAL PAGINATOR | Binded to dasources -->
<!-- See off.documentations 'https://material.angular.io/components/paginator/overview' -->
<mat-paginator [pageSize]="10" [pageSizeOptions]="[3, 5, 10]" [length]="dataSource.paginatorTotal$ | async"
[showFirstLastButtons]="true"></mat-paginator>
</div>
So how can ı fix this error?
Thanks
A: MatTableDataSource doesn't have loading$ property. To fix it you need to declare and handle loading$ subject in your component:
public dataSource = new MatTableDataSource<Employee>();
public loading$ = new Subject<boolean>();
Then emit values while loading data:
ngOnInit(){
this.loading$.next(true);
this.repository.getData(`employee/list`)
.pipe(finalize(() => this.loading$.next(false)))
.subscribe(
res => {
this.dataSource.data = res as Employee[];
}
)
}
And finally in template change dataSource.loading$ to loading$
Additional information:
When using ng build --prod there are perfomed additional type checks and you get error, while in normal ng serve your loading$ is always treated as undefined
| |
doc_23526593
|
The example I have just lists a static number, but I am intending it's use to also be used for aggregates as well in the future.
@NamedQuery(name = "findSchool",
query = "SELECT s, 9876 as num " +
"FROM School s " +
"WHERE s.id = :schoolId)
public class School implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false, nullable = false)
@JsonView(FindSchoolView.class)
private UUID id;
@Transient
@JsonView(FindSchoolView.class)
private String num;
}
I keep getting this message when I attempt to run the query:
"class [Ljava.lang.Object; cannot be cast to class com.School
([Ljava.lang.Object; is in module java.base of loader 'bootstrap';
com.School is in unnamed module of loader
'app')",
If I take out num as a member of the School entity, then there is no error.
So, how can one put a calculated value within a JPQL query to map into an entity?
A: I think you need to use a formula
@NamedQuery(name = "findSchool",
query = "SELECT s" +
"FROM School s " +
"WHERE s.id = :schoolId)
public class School implements Serializable {
@Formula(value = "'9876'")
@JsonView(FindSchoolView.class)
private String num;
Note that the value doesn't have to be a constant but you can use any native query (despite possibly losing a bit of portability).
If it's not generated by the SQL and you don't need to save it in the db,
then you can also do this:
@Transient
@JsonView(FindSchoolView.class)
private String num = "9876";
| |
doc_23526594
|
1) The page, when viewed in browser, is loading itself every second, with the interval of timer.
I do not want this as the application is going to be quite heavy and if final application keeps re-loading it like this, it will be a total failure.
2) The purpose of the timer is to check the time and date every second, when the right time approaches, it should send an email. This function is not working. I am using below code.
If DateTime.Now = DateTime.Parse("01.13.2014 20:34") Then
Call SendEmail()
Timer1.Enabled = False
End If
3) I want to set this time using DateTimePicker like control, that we use for Winforms. Is anything like that possible? When hosted on server, where shall the time be taken, as on local server, it is taking from my system.
Thanks
A: That is the default behaviour of the Timer Control; once given an Interval and set Enabled = true, it will repost the entire page every (Interval) milliseconds.
What you are doing - waiting until a specific time to send an email - is not really a task that is suited to a web application. You can do it but I would advise against it; create a Windows Service to do the job instead.
There other alternatives if this sounds too daunting: -
*
*a console application (running on the server)
*a winforms application (running on the server)
*a SQL scheduled task and SQL Mail (database server)
The Windows Service approach is the one I'd use though.
If you really want to do this using a web page, you should consider using either: -
*
*A JavaScript-based timer that calls a web service or HttpHandler, or
*Wrap the content required (if any) in an UpdatePanel, and place the timer inside the UpdatePanel
As I said - I wouldn't do it this way. Good luck.
| |
doc_23526595
|
lst = [0,1,2,3,4,5,6]
counter=0
for i in range(len(lst)):
print("counter:",counter,"(",i,")", end="\t")
counter+=1
print()
for i in range(len(lst)):
for j in range(i+1,len(lst),1):
print("counter:",counter,"(",i,",",j,")", end="\t")
counter+=1
print()
for i in range(len(lst)):
for j in range(i+1,len(lst),1):
for k in range(j+1,len(lst),1):
print("counter:",counter,"(",i,",",j,",",k,")", end="\t")
counter+=1
print()
Results:
counter: 0 ( 0 ) counter: 1 ( 1 ) counter: 2 ( 2 ) counter: 3 ( 3 ) counter: 4 ( 4 ) counter: 5 ( 5 ) counter: 6 ( 6 )
counter: 7 ( 0 , 1 ) counter: 8 ( 0 , 2 ) counter: 9 ( 0 , 3 ) counter: 10 ( 0 , 4 ) counter: 11 ( 0 , 5 ) counter: 12 ( 0 , 6 )
counter: 13 ( 1 , 2 ) counter: 14 ( 1 , 3 ) counter: 15 ( 1 , 4 ) counter: 16 ( 1 , 5 ) counter: 17 ( 1 , 6 )
counter: 18 ( 2 , 3 ) counter: 19 ( 2 , 4 ) counter: 20 ( 2 , 5 ) counter: 21 ( 2 , 6 )
counter: 22 ( 3 , 4 ) counter: 23 ( 3 , 5 ) counter: 24 ( 3 , 6 )
counter: 25 ( 4 , 5 ) counter: 26 ( 4 , 6 )
counter: 27 ( 5 , 6 )
counter: 28 ( 0 , 1 , 2 ) counter: 29 ( 0 , 1 , 3 ) counter: 30 ( 0 , 1 , 4 ) counter: 31 ( 0 , 1 , 5 ) counter: 32 ( 0 , 1 , 6 ) counter: 33 ( 0 , 2 , 3 ) counter: 34 ( 0 , 2 , 4 ) counter: 35 ( 0 , 2 , 5 ) counter: 36 ( 0 , 2 , 6 ) counter: 37 ( 0 , 3 , 4 ) counter: 38 ( 0 , 3 , 5 ) counter: 39 ( 0 , 3 , 6 ) counter: 40 ( 0 , 4 , 5 ) counter: 41 ( 0 , 4 , 6 ) counter: 42 ( 0 , 5 , 6 )
counter: 43 ( 1 , 2 , 3 ) counter: 44 ( 1 , 2 , 4 ) counter: 45 ( 1 , 2 , 5 ) counter: 46 ( 1 , 2 , 6 ) counter: 47 ( 1 , 3 , 4 ) counter: 48 ( 1 , 3 , 5 ) counter: 49 ( 1 , 3 , 6 ) counter: 50 ( 1 , 4 , 5 ) counter: 51 ( 1 , 4 , 6 ) counter: 52 ( 1 , 5 , 6 )
counter: 53 ( 2 , 3 , 4 ) counter: 54 ( 2 , 3 , 5 ) counter: 55 ( 2 , 3 , 6 ) counter: 56 ( 2 , 4 , 5 ) counter: 57 ( 2 , 4 , 6 ) counter: 58 ( 2 , 5 , 6 )
counter: 59 ( 3 , 4 , 5 ) counter: 60 ( 3 , 4 , 6 ) counter: 61 ( 3 , 5 , 6 )
counter: 62 ( 4 , 5 , 6 )
A: Consider this definition of the powerset function:
def compress(it, n):
for v in it:
if n & 1:
yield v
n >>= 1
def powerset(s):
return [compress(s, i) for i in range(1 << len(s))]
That enumerates the subsets in binary order.
A: I don't have the complete answer, but only some hints to guide your reasoning. You can consider your indices as a twisted numeration system, where you don't have all digits for each numeration place.
Let n = len(lst) then the number of 1-index subsets is n1 = n, the number of 2-index subsets is n2 = n*(n+1)//2 - n1 and the number of 3-index subsets is n3 = n*(n+1)*(n+2)//8 - n2 - n1 and so on... In your example, n1 = 7, n2 = 21 and n3 = 35, and of course n1+n2+n3 = 63
So I guess that performing some variants of Euclidian decomposition, using combined // and % operators on n1, n2 and n3 should provide the correct subset. But that's not totally trivial...
| |
doc_23526596
|
Possible Duplicate:
Using var outside of a method
class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?
In function/method, i can declare a var type variable,then why can't, i do it in class ?
Thanks.
A: If you really don't know the type of object your instance variable will hold, use object, not var. var doesn't mean "i don't know", it means "infer the type for me" - this is why it can never be used on class members.
A: Because C# doesn't support this level of type inferencing. Your alternatives are to use a language, such as F#, that does support this level of type inferencing or beg the C# team to implement the feature. I've got a pretty good guess which one you'll have more luck with...
A: var in C# is a implicitly typed local variable used to infer the type from the RHS of the given expression, which needs to be resolved at compile time. When you declare a var with no RHS value in the class definition, there is no way for the compiler to know the type that you are trying to assign to var.
C# doesn't support implicit typing for class variables.
A: // method variable
var X;
is never valid - even inside a method; you need immediate initialization to infer the type:
// method variable
var X = "abc"; // now a string
As for why this isn't available for fields with a field-initializer: simply, the spec says so. Now why the spec says so is another debate... I could check the annotated spec, but my suspicion would be simply that they are more necessary for method variables, where the logic is more complex (re LINQ etc). Also, they are often used with anonymous types (that being the necessity for their existence); but anonymous types can't be exposed on a public api... so you could have the very confusing:
private var foo = new { x = 123, y = "abc"}; // valid
public var bar = new { x = 123, y = "abc"}; // invalid
So all in all I'm happy with the current logic.
A: Because the actual type of a var is inferred from the context in which it is used. For fields (class member variables), there is no such context.
A: You can argue that the intent is quite obvious if you would write var _users = new List<User>() as a field declaration.
The problem is that not all field declarations contains an assignment which is required to infer the type. (You might want to initialize a field through the constructor)
Mixing both var and normal type declarations would look like a nasty soup. Therefore it's not possible.
(at least that's my guess)
A: Yes, the var keyword is only allowed for local variables.
It was introduced in the language to be able to handle an anonymous type, that only exists in a local scope. As the anonymous type is limited to the local scope, it makes sense to only allow the var keyword in a local scope.
Additionally, it never works to use the var keyword without specifying a value, as that is used to infer the data type:
var x = "asdf"; // works
var x; // doesn't work
The normal way of declaring a variable is using a specific data type. Use the var keyword when you can't specify a data type (e.g. when the type is anonymjous) or when the type is superflous (e.g. repeated literally in the value). Example:
var x = new { Key = 42, Name = "asdf" };
var y = new System.Text.StringBuilder();
A: It is all because of the Build order. You can declare var in only methods. Compiler builds everything but methods first and thats why the type of the object will be clear to the compiler if you use it inside of a method. Jon had a great answer about this but can't seem to find.
| |
doc_23526597
|
A: Yes, the visibleRoles field is not getting added when generating api.yaml using apictl init in APICTL 3.2.1 which is an issue. Thank you very much for informing this. Will look into that.
Can you kindly add visibleRoles fields to your generated api.yaml as a workaround and proceed until this is fixed in APICTL 3.2.1? (This is already fixed in APICTL 4.0.0-Alpha2.)
| |
doc_23526598
|
I'm reading data from a text file into three vectors: X, Y and Cluster.
I need to generate a graph for X and Y and to set the color of the point according to the cluster {0,1,2}.
Can you please advise how can I do that? From what I tried to do, it only gives me an option to draw a plot by X,Y with one color.
Thanks in advance,
Adi
A: It seems like you are trying to do a scatter plot
cmp = lines(3);
scatter( X, Y, 20, cmp(Cluster+1), 'filled');
note the +1 when indexing cmp - Matlab's first index is 1 and not 0!
| |
doc_23526599
|
See the image here
I have also installed and configured the WordFence Security plugin. I also checked the Sucuri Site check tool but none of the tools showed any type of virus alerts.
The site I need help with is : [Link Deleted by User]
Any help would be appreciated and thanks in advance.
A: You need to check the Google Search Console. Some of the URL indexed by Google is a 404 URL, so manually check for the URL from Google Search Console, remove the indexed URL which are a 404 URL.
https://search.google.com/search-console/about
A: *
*Install Yoast SEO plugin
*Add metadata with Yoast.
*Create a XML site map
*Submit your site map at google console
A: Have you uploaded/submitted a valid sitemap.xml to your google search console?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.