text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Sorting list with searched input string I am working on a Parse/Android application in which I am getting array list of objects from the server, for example Apple, Banana, Carrot, Dino etc which I am displaying in my Adapter.
Now I want to make a search thing on my list, if I press any alphabet it will show the items according to those characters, for example: if I press "A" so it will show me : Apple, Apricot etc and do not show any other.
My code is given below:
// mItems is my arraylist of objects with "title" object.
mItems = (ArrayList<ParseObject>) objects;
mAdapter = new GenericAdapter<ParseObject>(getApplicationContext(),
mItems,R.layout.listview_dical_assist,mNotificationsBinder);
mListView.setAdapter(mAdapter);
My autoComplete editField where I want to make that sorting list thing.
autoComplete.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// I need to put that search query here user press any character
adapter.notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33186044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: BigQuery Regex to extract string between two substrings From this example string:
{&q;somerandomtext&q;:{&q;Product&q;:{&q;TileID&q;:0,&q;Stockcode&q;:1234,&q;variant&q;:&q;genomics&q;,&q;available&q;:0"}
I'm trying to extract the Stockcode only.
REGEXP_REPLACE(col, r".*,&q;Stockcode&q;:/([^/$]*)\,&q;.*", r"\1")
So the result should be
1234
however my Regex still returns the entire contents.
A: use regexp_extract(col, r"&q;Stockcode&q;:([^/$]*?),&q;.*")
if applied to sample data in your question - output is
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70283253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: cannot get opengraph to scape url I know this is a pretty common problem but any of the solutions I have tried (thats a lot) haven't worked.
I am trying to scrape http://residencyradio.com/ using https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fresidencyradio.com%2F
The site itself is getting a complete overhaul, this will be revealed next week and I want the relevant images, title and info to appear if someone links to the site, but instead at the moment these properties are being shown as they were the very first time the site was cached on FB (nearly a year ago).
As far as I can see, I have included all the relevant meta tags etc how they should be, I even tried implementing a like button on the site, but to no avail. I have followed what has been set out on: http://ogp.me/ and can't see anything wrong.
Here is a sippet of the page from !DOCTYPE to </head>:
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns#">
<head>
<meta charset=utf-8>
<title>The Residency</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
<link href="css/reset.css" rel="stylesheet" type="text/css" />
<link href="css/stylesheet.css" rel="stylesheet" type="text/css" />
<link rel="icon" type="image/png" href="images/favicon.png" />
<!--Meta Data-->
<meta name="keywords" content="The Residency, M. Budden, Neal McClelland, Michael Budden, Radio, Residency Radio,
Residency, Global, House, Electro, Progressive, Tech, Techno, DnB, Drum and Base, Dubstep, iTunes, Belfast,
Northern Ireland, UK" />
<meta name="description" content="Brought to you by Neal McClelland and M. Budden, The Residency is a weekly global underground dance show" />
<meta property="og:title" content="The Residency A global underground dance show" />
<meta property="og:type" content="musician" />
<meta property="og:url" content="https://www.facebook.com/theresidency" />
<meta property="og:image" content="https://www.residencyradio.com/images/Residency_logo_circle.png" />
<meta property="og:site_name" content="The Residency" />
<meta property="fb:admins" content="1324839758" />
Any help would be greatly appreciated, as I've been scratching my head for a few days trying to figure it out!
Thanks in advance!
A: This is a guess, but your html is not valid and maybe because of that the facebook scraper fail to parse and extract the data from it.
I haven't went through all of it, but you don't seem to close all tags.
For example the description and keywords meta tags don't end with "/>" or ">".
Edit
Screen capture of what the debugger shows when I load your html from my server:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10509034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a nice way to tell jQuery to not eval scripts on ajax requests that are HTML I'm using jQuery to make an ajax request, and everything is working as expected. But it's evaluating the scripts in the wrong context.
I have an iframe (same domain, no worries here), and I'm trying to get the scripts to eval in the context of the iframe, instead of where the ajax request was made -- eg. a different frame.
I figured I could tell ajax not to eval the scripts, and I would do the work myself to eval them in the right context. Any ideas, or ways to disabled the automatic eval?
Edit
So, I was somewhat wrong about the initial question.. The scripts are not evaluated when loaded, but rather when the content is being placed in the document. You can see this by testing the example:
$('#some_element').html('<span>content</span><script>alert(window)</script>');
Now, when doing this from a different frame, the evaluation happens in the scope of where you're calling, not the element you're inserting content into.
I ended up setting the content without using jQuery, and then finding/evaling any script tags:
element.get(0).innerHTML = data;
element.find('script').each(function() {
otherWindow.eval(this.innerText);
});
Final Update
I ended up tracking it down to the source, and overriding it from there.. the following is coffeescript, but you can get the idea. I chose to override it because for my usage, this should never happen in the top window, but is expected in the iframe content.
$.globalEval = (data) -> (iframeWindow.execScript || (data) -> iframeWindow["eval"].call(iframeWindow, data))(data) if (data && /\S/.test(data))
A: This questions shows how to do custom eval of the scripts:
jQuery: Evaluate script in ajax response
In the following piece of code... ** this code is from the answer of the other question ** just got it as a snippet:
$("body").append($(xml).find("html-to-insert").eq(0));
eval($(xml).find("script").text());
eval itself is bound to a window, that you can define to be the context:
windowObject.eval - when calling just eval('...'), it supposes you are calling just like this: window.eval('...')
Now you need to get the window that corresponds to the frame you want to execute the eval in and do something like this:
myIFrameWindow.eval('...')
When you do this, it is execute in the context of that window. It is just a matter of finding the window associated with the iframe that you want now.
To find the window of a given frame, take a look at this post:
Getting IFRAME Window (And Then Document) References With contentWindow
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6394135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Ignore adapter creation when adaptee already of correct type I have the following setup:
class Target(Base):
def __init__(name: str):
self.name = name
class Adapter(Target):
def __init__(self, adaptee: Base, name: str):
super().__init__(name=name)
self.adaptee = adaptee
def as_target(adaptee: Base, name: str):
if isinstance(adaptee, Target):
return adaptee
else:
return Adapter(adaptee, name)
I am wondering if I could get rid of as_target function and instead handle the logic on adapter creation.
Semantically, it would have the following meaning:
class Adapter(Target):
def __init__(self, adaptee: Base, name: str):
if isinstance(adaptee, Target):
self = adaptee
else:
super().__init__(name=name)
self.adaptee = adaptee
I've tried playing around with overriding __new__ but I wasn't able to make it work.
A: class Base:
pass
class Target(Base):
def __init__(self, name: str):
self.name = name
def __repr__(self):
return "{}({})".format(type(self).__name__, repr(self.name))
class Adapter(Target):
def __new__(cls, adaptee: Base, name: str):
if isinstance(adaptee, Target):
return adaptee
else:
return super().__new__(cls)
def __init__(self, adaptee: Base, name: str):
super().__init__(name=name)
self.adaptee = adaptee
print(Adapter(Base(), "a")) # Adapter('a')
print(Adapter(Target("b"), "c")) # Target('b')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61784499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Generate Permutations - Swap Function I'm going thru the EPI book and adapting the solutions in Go. I don't understand the solution for "generating permutations". Below is my implementation in Go (which works correctly):
func permutations(A []int) [][]int {
result := [][]int{}
var directedPermutations func(i int)
directedPermutations = func(i int) {
if i == len(A)-1 {
B := make([]int, len(A))
copy(B, A)
result = append(result, B)
return
}
for j := i; j < len(A); j++ {
A[i], A[j] = A[j], A[i]
directedPermutations(i + 1)
A[i], A[j] = A[j], A[i]
}
}
directedPermutations(0)
return result
}
Below is the result:
16.3_generate_permutations$ go run main.go
input: [1 2 3]
[[1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 2 1] [3 1 2]]
Specifically, I'm confused as to why the values are swapped before and after the recursive case. I've stepped thru with a debugger and see that for each successive call values are swapped to generate the permutation.
Is the swap before recursive case and swap back afterwards a common pattern?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59142060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Only insert new rows in SQLIte with pandas to_sql() I've got a dataframe in Pandas and I want to export the dataframe to sqlite with the pandas function to_sql(), the problem I've got is that function only admit remplace or append values, and I can not export just by inserting new rows.
to_sql() function:
if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’
How to behave if the table already exists.
fail: Raise a ValueError.
replace: Drop the table before inserting new values.
append: Insert new values to the existing table.
Is there an option to do that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52907930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Update React [Native] View on Day Change I'm working on a React Native component that should update itself when the day changes, even when the user hasn't interacted with the view.
Is setInterval the only way to deal with this? If I call setTimeout in viewDidLoad specifying the number of ms until the next day, won't the interval be inaccurate if the app gets paused? Alternatively, I could run a periodic timer, but I'd need to give it a short interval so that there's not an apparent delay when the day changes -- seems pretty inefficient.
Am I missing something?
A: I suppose this is more of a general app architectural concern. The simplest answer is you should take the current time in seconds (new Date().getTime()), determine how many seconds there are until the next day, and set a timer for that number.
However, as you mentioned, once the app is killed, that timer will no longer be accurate.
You should use AppStateIOS to listen for when the app is backgrounded and foregrounded. Upon being sent to the background, clear the timer. Upon being brought to the foreground, run the original calculation again and generate a new timer.
Unfortunately there is no equivalent functionality on Android as of yet.
A: You can use react-native-midnight which subscribes to native APIs and fires event listeners when the day has changed from either a timezone change or crossing the midnight threshold.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34430704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Error messages are not displayed using jQuery Validate I have the following jQuery script.
function updateItem(form) {
var validator = $("#add-experience-form").validate({
debug: true,
rules: {
eventTitle: {
required: true
}
},
messages: {
eventTitle: {
required: "Please, enter a title."
}
}
});
if (!validator.valid()) {
return;
}
}
Here's the HTML:
<form action="/User/AddExperience" id="add-experience-form" method="post" novalidate="novalidate">
<p>
<label>Experience Title<span class="required">*</span></label>
<input id="eventTitle" name="eventTitle" required="required" style="width: 350px;" type="text" value="">
<span class="field-validation-valid" data-valmsg-for="eventTitle" data-valmsg-replace="true"></span>
<br>
<label> </label><span class="tip">50 character maximum</span>
</p>
{
Experience Title
@*@
50 character maximum
For some reason error message doesn't display for the above form even though validator.valid() evaluates to false.
If it helps, I put this form inside jQuery UI dialog, but I don't think it really matters.
Any ideas?
A: To validate html forms , the simplest way is to combine two open source powerful frameworks twitter bootstrap ( to get nice form ) and jquery.validate.js plugin ( for validation ).
Bootstrap framework : http://getbootstrap.com/getting-started/ .
Jquery validation plugin : http://jqueryvalidation.org/
So your html code and your script may appear like this
Html code :
First add this link
<link href="bootstrap/bootstrap.min.css" rel="stylesheet" media="screen">
Then
<form method="post" action="/User/AddExperience" id="add-experience-form" class="form-horizontal">
<fieldset>
<h4 class="text-primary">fields required * </h4>
<div class="form-group">
<div class="control-group">
<label class="control-label col-xs-3" for="experienceTitle">Experience Title<span class="req">*</span></label>
<div class="col-xs-9">
<input type="text" class="form-control" id="eventTitle" name="eventTitle">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-9">
<div class="form-actions">
<input type="submit" class="btn btn-primary" name="newsubmit" id="newsubmit" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</div>
</fieldset>
</form>
Jquery script : put it in a js file called validate.js
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
});
$('#add-experience-form').validate({
rules: {
eventTitle: {
minlength: 2,
lettersonly:true,
required: true
}
},
messages: {
eventTitle: {
required:"blablabla",
minlenght:"blablabla",
maxlenght:"50 character maximum",
lettersonly: "Letters only please"
}
},
highlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('error').addClass('success');
},
success: function (label) {
$(label).closest('form').find('.valid').removeClass("invalid");
},
errorPlacement: function (error, element) {
element.closest('.control-group').find('.help-block').html(error.text());
}
}).cancelSubmit=true; // to block the submit of this plugin and call submit to php file
});
You can put all these scripts in one folder called js then add them in your code
<script src="//code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/docs.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/validate.js"></script>
For more details you can refer to the documentation http://jqueryvalidation.org/documentation/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23584049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to redirect from one servlet to another by using tricky redirection? If I have two servlets:
@WebServlet (urlPatterns = {"/s1"})
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 100);
map.put("B", 200);
map.put("C", 300);
req.setAttribute("map", map);
getServletContext().getRequestDispatcher("Servlet2").forward(req, resp);
}
}
public class Servlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map map = (Map) req.getAttribute("map");
for (Object o : map.values()) {
System.out.println(o);
}
}
}
How can I make redirect between them? And which path I need to use in my getRequestDispatcher method? And one more condition - Servlet2 must be without any mapping in annotations or in web.xml.
A:
Servlet2 must be without any mapping in annotations or in web.xml.
Then you cannot use HttpServletRequest#getRequestDispatcher(String), which is a container managed method that checks those mappings.
That condition is ridiculous and makes no sense. If you aren't going to use the Servlet container, don't make a Servlet. Make a service class that performs the actions you need. You don't need to make everything a Servlet.
Your only (ridiculous) alternative is to instantiate Servlet2 and explicitly invoke its doGet method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20958755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Move factory method from AppModule to AppComponent in Angular 7 I use ngx-translate-multi-http-loader loader to create specific translations. The documentation requires that this factory has to be created within the app.module.ts:
export function multiTranslateHttpLoaderFactory(http: HttpClient) {
return new MultiTranslateHttpLoader(http, [
{prefix: './assets/i18n/default/', suffix: '.json'},
{prefix: './assets/i18n/bc/', suffix: '.json'}
]);
}
This factory is configured inside the import arrays in this way:
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: multiTranslateHttpLoaderFactory,
deps: [HttpClient]
}
}),
I need a way to put the factory into my app.component.ts, because I still have to program some logic and do not want to do that within my app.module.ts.
But if I move the method into my app.component.ts and make all the necessary import statements on top of the file, angular doesn't compile and returns this error message:
ERROR in src / app / app.module.ts (55,21): error TS2304: Can not find
name 'multiTranslateHttpLoaderFactory'.
Is there a possibility or do I really have to define the factory within app.module.ts ???
A: It really should not matter where you define your factory, or any other function for that matter. Just be sure to import it correctly, somewhere in the top of app.module.ts
import {multiTranslateHttpLoaderFactory} from 'path/to/your/component'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55023607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: super priviliege not set for master user in aws rds mysql I have created an AWS RDS instance, I have created my master user with master password, and it is working/connecting fine.
But when I am going to create a function on that instance, it shows me the following error:
ERROR 1418: This function has none of DETERMINISTIC, NO SQL,
or READS SQL DATA in its declaration and binary logging is enabled
(you might want to use the less safe log_bin_trust_function_creator variable).
In my instance the variable log_bin_trust_function_creators shows OFF, and if I try to change the variable using SET GLOBAL log_bin_trust_function_creators = 1;, it gives me another error "Error Code: 1227. Access denied; you need (at least one of) the SUPER privilege(s) for this operation"
A: Set log_bin_trust_function_creators = 1 for Parameter group of the RDS instance.
Note: Default Parameter-Group is not editable. Create a new Parameter-Group and assign it to the RDS instance by modifying it from UI (AWS Admin Console) OR maybe using commands
DELIMITER $$
CREATE DEFINER=`DB_USERNAME_HERE`@`%` FUNCTION `GetDistance`(coordinate1 VARCHAR(120), coordinate2 VARCHAR(120)) RETURNS decimal(12,8)
READS SQL DATA
BEGIN
DECLARE distance DECIMAL(12,8);
/*Business logic goes here for the function*/
RETURN distance;
END $$
DELIMITER ;
Here, you have to replace DB_USERNAME_HERE with you RDS database username and function names according to you need.
Important thing is: DEFINER=`DB_USERNAME_HERE`@`%`
This was the problem I was facing after setting log_bin_trust_function_creators = 1 in parameter group. And it worked like a charm.
A: A better way is to apply your own parameter group, with log_bin_trust_function_creators set to true. (its false by default)
A: This happens when you try to create a procedure/function/view with a DEFINER that is not the current user.
To solve this remove or update the DEFINER clause.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15088831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to call a function when pressing the default react native picker in react native I'm using react-native picker in dialog mode. Now I want to call a function whenever the dialog opens. How can I achieve that because there is no onPress prop? Any help will be appreciated. Please don't recommend any other packages because I want to use the default one.
A: You can achieve it without using Picker, use TouchableOpacity to call a function, and in the same function just open a Modal for showing the list of items of Picker and close the Modal when selecting any item from the list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68410062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WMS/WFS server: am I crazy to write my own? I'm a "do it yourself" kind of guy, but I want to make sure I'm not going to do myself in by trying to bite off more than I can chew.
I am writing a browser-based mapping application that needs to have the option to run standalone (no internet connection) on the end-user's machine. That is, the application is some kind of server that will, in many cases, get installed on the end user's machine and the browser will point to some localhost URL to access it.
I will be using MapLayers on the client side, and the server side will have a bunch of custom logic specific to the application, such as handling click events on the map in certain custom ways, creating various custom objects on the map at certain times, and so on.
For the "business logic" part of the server, I'm happy using paste/webob with python. It's a simple infrastructure that lets me put all this custom logic in easily.
I had been thinking that the client would communicate with two servers: this paste/webob business logic server, and a server just for serving WMS and WFS map elements. So I was looking at MapServer and GeoServer to handle the map parts and ... I'm not happy.
I'm not happy because I don't want to have to install and worry about a "beast" on the client machines. For MapServer, I don't really want to install a full-blown web server like Apache, and have to deal with CGI and PHP and MapScript. For GeoServer, there's (potentially) installing Java, and dealing with various complexities of the GeoServer setup and administration.
Part of this is simply a learning curve issue. If I can avoid it, I'm not especially interested in learning the intricacies of either MapServer or GeoServer. I installed GeoServer, pointed it to some of my data, and was able to use the MapLayers preview built into GeoServer's nice web admin to view my data. But when I tried to serve the data for real using my own MapLayers web page pointed at GeoServer, I crashed GeoServer. That I could crash the server just be sending some presumably malformed requests from the client was quite surprising to me. And I could dig into the GeoServer logs to try to figure out what I did wrong, but ... I don't really want to spend a lot of time on that.
So, I am considering implementing parts of the WMS and WFS interface myself just using the paste/webob server I already have. It may in fact be that I only need the WMS, since I might handle vector objects through a simple custom protocol that I make to pass data to the client, which can then create and manipulate the objects directly using OpenLayers.
I've looked at the specs and example messages for WMS (and a bit less at WFS). It seems not so difficult just to implement this protocol myself, especially because I have full control of the client in this case -- it's not like I need to be able to act as a generic WMS or WFS server; I just have to make my own OpenLayers client happy.
The two main abilities that I need the WMS server to have are:
*
*Serve tiles from a store of prerendered tiles that I've created ahead of time (I'll prerender the tiles using OpenStreetMap data and mapnik as the redering engine; and I'll store and access them using the normal Google Maps style tile naming scheme that OpenLayers expects)
*Have the ability to server modified versions of these tiles where certain data that I store locally is drawn on top of the tiles. For instance, I might have, say, 10000 points on one "layer" and 10000 polygons on another layer, and when the user activates these layers I will serve my same base tiles, but as I'm serving these tiles I'll render these additional features on top of them, and probably I'll implement a simple caching scheme to keep these over-rendered tiles around for some amount of time.
So my question is: Even though I know there are existing tools that do these things (MapServer, GeoServer, TileCache, and others), I'm actually feeling like it's less work for me to just to respond to some simple WMS messages, and do this additional over-drawing on my tiles myself in python, making sure everything is projected correctly, etc. I don't need to draw fancy wide streets or anything for these over-layers, just simple lines, icons, and perhaps labels. It sure sounds nice and simple to have a python-only solution.
I figure if I ever need to expand into supporting more of the WMS/WFS protocol, or doing fancier overdrawing, I can just insert MapServer/GeoServer at that time.
Are there pitfalls here I'm not considering?
A: Mapserver is very easy to setup and learn. Implementing any kind of rendering by yourself is going to require much more effort, and you will probably find a lots of unexpected traps.
mapserver cgi should be enough for your needs. If you require some very specific tweak, then mapscript can be useful.
I think it could be interesting if you could make a pure JavaScript application, and save yourself from installing a web server (and a map server). If you just needed browsing a tile mosaic, may be you could do it just with JavaScript (generate an html table with a cell for each tile). You can render points or polygons, with JavaScript, using a canvas and doing some basic coordinate conversion to translate geographic points to pixels. Openlayers have this functionality, I think.
EDIT: I just checked and with Openlayers you can browse local tiles, and you can render kml and some other vect data. So, I think you should give Openlayers a try.
A: No need to have a wms/wfs. What you need is a tile implementation. Basically you should have some sort of central service, or desktop service that generates the tiles. Once these tiles are generated, you can simply transform them to your "no-real-webserver-architecture" filesystem. You can create a directory structure that conforms to /{x}/{y}/{z}.png and call it from javascript.
An example of how openstreetmap does this can be found here: http://wiki.openstreetmap.org/wiki/OpenLayers_Simple_Example
A: You may like featureserver: http://featureserver.org/.
It has its own WFS. I am using it right now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5334378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Oracle APEX: Text wrapping issue with a display-only page item I have a display-only page item on an inline dialog region. The value of the item is set via hidden page item that retrieves the value from the database using PL/SQL.
The issue is that the text is rather long, so instead of text wrapping, it extends beyond the width of the inline dialog causing a horizontal scroll bar to appear. How can I set the width of the page item to be no wider than the inline dialog default width and make the page item text wrap around?
A: Did you try to
*
*set display only item's template to "optional" (instead of e.g. "optional - floating"), and then
*set its "custom attributes" property (which is in the "Advanced" set of properties) to e.g. style="width:300px"
Illustration:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74494751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SharePoint Visual Studio Build - error : '.', hexadecimal value 0x00 When I deploy my SharePoint project I receive the following error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\SharePointTools\Microsoft.VisualStudio.SharePoint.targets(375,5): error : '.', hexadecimal value 0x00, is an invalid character. Line 1, position 1.
The line number relates to the following in the build XML:
<CreateSharePointProjectService Configuration="$(Configuration)"
Platform="$(Platform)"
ProjectFile="$(MSBuildProjectFile)"
ProjectReferences="@(SharePointProjectReference)"
OutDir="$(TargetDir)">
<Output PropertyName="ProjectService" TaskParameter="ProjectService" />
</CreateSharePointProjectService>
Furthermore I've managed to whittle down the problem (or at least seemingly) to the following property:
ProjectFile="$(MSBuildProjectFile)"
i.e. if I remove this property then I no longer get the same error message (but I get others as a consequence).
I'm not sure what's going on here as I know nothing about MSBuild. Obviously this always used to work before so I don't know what's changed to cause it to no longer work. Any suggestions will be greatly appreciated as I've wasted a lot of time on this already. BTW, this problem occurs in both Visual Studio 2010 and 2012.
Thanks
A: OK, problem sorted. It turns out that the error message actually referred to an XML file referenced by the solution (containing some deployment files). This XML had somehow become corrupted which does fit the message '.', hexadecimal value 0x00. After removing this feature (which didn't need deploying anyway) the problem disappeared so the world can go on being a happy place again (or at least my manager is!)
A: I just ran into this after downloading an msbuild file from the internet. Opening the newly downloaded file in a hex editor showed me what the problem was pretty quickly. The file was downloaded with 2 byte characters, and every other byte was a 0. I think Notepad++ said the encoding was UCS-2. In any case, the fix was pretty simple. Notepad++ has an Encoding menu option that I used to rewrite the file as UTF-8. Changing the file back to UTF-8 immediately fixed the problem.
Hope this helps people in the future.
--Addendum - I might have tried to muck with the file using PowerShell before its encoding changed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13679605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How is arctangent [function a()] implemented in bc? I wanted to see and possibly modify how the arctangent function a() was implemented in bc (the arbitrary precision calculator language) but was unable to find it. I even found a git repo of the project https://github.com/gavinhoward/bc, however was unable to locate the implementation code for it. This should be part of the matlib library for bc.
Please share link, location of the directory or source code below.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72898893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using mapply to plot I'm trying to iteratively plot scatterplots ONLY using mapply.
Let's say I have the iris dataset:
> names(iris)
[1] "Sepal.Length" "Sepal.Width" "Petal.Length"
[4] "Petal.Width" "Species"
I would like to use mapply() and only mapply() to plot Sepal.Width, Petal.Length, and Petal.Width against Sepal.Length
I have this starter code:
mapply(function(ii){plot(x = iris[["Sepal.Length"]],
y = ii, ylab = paste(names(ii)), xlab = "Sepal Length")},
ii = iris[c(2,3,4)])
Everything works fine here EXCEPT the y axis labels. I want it to display the column names of the y-axis values, but this does not work.
A: Neither mapply nor lapply pass the names of the items in their data objects to the "working functions". What you see after the function completion is that they add back the names to the results. Even if you use the deparse(substitute)) strategy you end up with a useless name like "dots[[1L]][[1L]]". So you are condemned to either index by the names themselves or by a numeric index into the names(dataframe) values.
A: Consider passing column names to fit your column assignment and ylab character requirement. And as @alistaire comments, you are only passing one vector into your function. Mapply (informally as multivariate apply) is designed to iterate elementwise through more than one equal-length or multiple-length vectors. This would be akin to passing in Sepal.Length 1 or 3 times:
plotfct <- function(ii, jj)
plot(x = iris[[ii]], y = iris[[jj]],
xlab = paste(ii), ylab = paste(ii))
mapply(plotfct, c("Sepal.Length", "Sepal.Length", "Sepal.Length"),
c("Sepal.Width", "Petal.Length", "Petal.Width"))
But since Sepal.Length does not change, repeating its value to meet the length of longer is redundant. Simply use lapply or its simplified wrapper, sapply:
plotfct <- function(ii)
plot(x = iris[["Sepal.Length"]], y = iris[[ii]],
xlab = "Sepal Length", ylab = paste(ii))
lapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct)
# EQUIVALENTLY:
# sapply(c("Sepal.Width", "Petal.Length", "Petal.Width"), plotfct)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48848147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: paginated calls on a service method without changing signature of original method I have a use case where I need to add pagination inputs (viz. page number and page size) to existing service calls (that returns a list of results) without changing the existing signature (because it will break existing clients). One way of achieving this is that we set the inputs in a threadlocal and have the implementation read the threadlocal and do its pagination logic. From a code point of view, it would look something like:
try {
PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
List<SpecialObject> results = specialService.getSpecialObjs(); //results count will be equal to pageSize value
} finally {
PaginationKit.clearPaginationInput(); // Clear threadlocal
}
From a client's point of view, this is not at all elegant and I wanted to wrap this functionality into some better syntactic sugar. There were two approaches I had in mind and I wanted to know if this is a generic enough use case that has been solved as a pattern elsewhere. There are many such services and trying to put up a decorator for each of the services is not desirable.
Approach 1:
I like the mockito style of Mockito.when(methodCall).thenReturn(result) kind of sugar.
So the code may look like:
SpecialService specialService = PaginationDecorator.prepare(SpecialService.class); // Get a spy that is capable of forwarding calls to the actual instance
List<SpecialObject> results = PaginationDecorator.withPageSize(pageSize).onPage(pageNumber).get(specialService.getSpecialObjs()).get(); // The get() is added to clear the threadlocal
I tried to borrow code from Mockito to create the spy, but the OngoingStubbing<T> interface is quite intertwined in the subsequent call chaining/creation code and is smelling of something that I should avoid.
Approach 2:
Use java.util.Function to capture the method call and accept two additional parameters pageNumber and pageSize to play with the threadlocals. The code may look like
List<SpecialObject> results = PaginationDecorator.withPaging(specialService.getSpecialObjs(), pageSize, pageNumber);
PaginationDecorator.java:
public static List<T> withPaging(Function<U, List<T>> call, int pageSize, int pageNumber) {
try {
PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
return call.apply(); // Clearly, something is missing here!
} finally {
PaginationKit.clearPaginationInput(); // Clear threadlocal
}
}
I am not able to clearly formulate how to use call correctly here.
Can someone please tell me :
*
*which of these two is the better approach
*if this is available as a recipe elsewhere using a different approach
*suggest ways forward to implement approach 1 or 2. Personally #2 seems cleaner to me (if it works).
Feel free to critique the approach and thanks in advance for the read!
P.S.: I also liked the iterator recipe in this question, but the primary problem of syntactic sugar is still desired.
A: Your second variant does not work, because you are using the wrong interface (Function expects an input argument) and no syntax to create a function instance, but just an ordinary invocation expression.
You have several choices
*
*Use Supplier. This interface describes a function without parameters and returning a value.
public static <T> T withPaging(Supplier<T> call, int pageSize, int pageNumber) {
try {
PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
return call.get();
} finally {
PaginationKit.clearPaginationInput(); // Clear threadlocal
}
}
Instead of insisting on it to return List<T>, we simply allow any return type which raises its versatility. It includes the possibility to return a List of something.
Then, we may use either, a method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
specialService::getSpecialObjs, pageSize, pageNumber);
or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
() -> specialService.getSpecialObjs(), pageSize, pageNumber);
*Stay with Function, but allow the caller to pass the required argument
public static <T,R> R withPaging(
Function<T,R> call, T argument, int pageSize, int pageNumber) {
try {
PaginationKit.setPaginationInput(pageSize, pageNumber); // Set threadlocal
return call.apply(argument);
} finally {
PaginationKit.clearPaginationInput(); // Clear threadlocal
}
}
Now, the caller has to provide a function and a value. Since the intended method is an instance method, the receiver instance can be treated like a function argument
Then, the function might be again specified either, as a (now unbound) method reference
List<SpecialObject> results=PaginationDecorator.withPaging(
SpecialService::getSpecialObjs, specialService, pageSize, pageNumber);
or a lambda expression:
List<SpecialObject> results=PaginationDecorator.withPaging(
ss -> ss.getSpecialObjs(), specialService, pageSize, pageNumber);
*There is an alternative to both, resorting to AutoCloseable and try-with-resource, rather than try…finally. Define the helper class as:
interface Paging extends AutoCloseable {
void close();
static Paging withPaging(int pageSize, int pageNumber) {
PaginationKit.setPaginationInput(pageSize, pageNumber);
return ()->PaginationKit.clearPaginationInput();
}
}
and use it like
List<SpecialObject> results;
try(Paging pg=Paging.withPaging(pageSize, pageNumber)) {
results=specialService.getSpecialObjs();
}
The advantage is that this will not break the code flow regarding your intended action, i.e. unlike lambda expressions you may modify all local variables inside the guarded code. Recent IDEs will also warn you if you forget to put the result of withPaging inside a proper try(…) statement. Further, if an exception is thrown and another one occurs inside the cleanup (i.e. clearPaginationInput()), unlike finally, the secondary exception will not mask the primary one but get recorded via addSuppressed instead.
That’s what I would prefer here.
A: Your second approach seems cleaner and easier for this task. As for implementation you can just use Java's Proxy class. It seems easy enough. I don't know any libraries that somehow make it even more easier.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class PagingDecorator {
public static void setPaginationInput(int pageSize, int pageNumber) {
}
public static void clearPaginationInput() {
}
public static <T> T wrap(final Class<T> interfaceClass, final T object, final int pageSize, final int pageNumber) {
if (object == null) {
throw new IllegalArgumentException("argument shouldn't be null");
}
ClassLoader classLoader = object.getClass().getClassLoader();
return (T) Proxy.newProxyInstance(classLoader, new Class[]{interfaceClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
setPaginationInput(pageSize, pageNumber);
try {
return method.invoke(object, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw e;
} finally {
clearPaginationInput();
}
}
});
}
public static <T> T wrap(final T object, final int pageSize, final int pageNumber) {
if (object == null) {
throw new IllegalArgumentException("argument shouldn't be null");
}
Class<?>[] iFaces = object.getClass().getInterfaces();
//you can use all interfaces, when creating proxy, but it seems cleaner to only mock the concreate interface that you want..
//unfortunately, you can't just grab T as interface here, becuase of Java's generics' mechanic
if (iFaces.length != 1) {
throw new IllegalArgumentException("Object implements more than 1 interface - use wrap() with explicit interface argument.");
}
Class<T> iFace = (Class<T>) iFaces[0];
return wrap(iFace, object, pageSize, pageNumber);
}
public interface Some {
}
public static void main(String[] args) {
Some s = new Some() {};
Some wrapped1 = wrap(Some.class, s, 20, 20);
Some wrapped2 = wrap(s, 20, 20);
}
}
A: You are using Java 8, right? Maybe you can add a default method without any implementation (sounds a litte weird, I know) like this:
// Your current service interface
interface ServiceInterface <T> {
// Existing method
List<T> getObjects();
// New method with pagination atributes
default List<T> getObjects(int pageSize, int pageNumber) {
throw new UnsupportedOperationException();
}
}
The new services (with pagination suport) must override this method. In my opinion, this way You "keep it simple".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34913880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need Rally Burndown chart API implementation to show in our dashboard I am creating Dashboard(dashing.IO) in which i want to display the Rally Burn down chart.
A: You'll need to create your app in an html file and then embed it in an iframe element in a widget.
https://help.rallydev.com/apps/2.1/doc/#!/guide/embedding_apps
The burn down chart is accessible via the Standard Report component:
https://help.rallydev.com/apps/2.1/doc/#!/api/Rally.ui.report.StandardReport
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40628483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Vue.js - Data lost in karma/phantomjs tests I'm writting some unit tests for a Vue app. Everything is workign good when I try to test the DOM content, but I can't access the data of my components. In fact there is no data if I console.log my component $data property, it prints an empty object, no initially defined data or any other data. Just nothing.
Here is some code
some vue component
<template>
<form @submit.prevent="saveAccount">
<label for="accountType">Tipo de cuenta</label>
<select class="form-control" id="accountType" v-model="newAccount.type">
<option v-for="type in accountTypes" v-bind:value="type.value">
{{type.label}}
</option>
</select>
</form>
</template>
<script>
export default {
data () {
return {
accountTypes: [
{value: '1', label: 'Activo'},
{value: '2', label: 'Pasivo'},
{value: '3', label: 'Patrimonio'},
{value: '4', label: 'INTO'}
]
}
}
}
</script>
My tests
beforeAll(() => {
vm = new Vue({
template: '<div><account></account></div>',
components: { account }
}).$mount()
})
afterAll(() => {
vm.$destroy(true)
})
it('account type', () => {
// this pass
expect(vm.$el.querySelectorAll('#accountType option').length).toBe(4)
const options = vm.$el.querySelectorAll('#accountType option')
// here accountTypes is undefined
const accountValues = vm.accountTypes.map(type => {
return type.value
})
options.forEach(option => {
expect(accountValues.indexOf(option.value)).not.toBe(-1)
})
})
Some code is omitted. So, why is that my component data is empty but at the same time, properly rendered in the DOM?
A: After some try and error I found the answer and it's pretty obvious now. The thing is, that I was searching for data in the wrong place. The vmobject that I defined like this
vm = new Vue({
template: '<div><account></account></div>',
components: { account }
}).$mount()
Is a Vue instance that only have a component and a template option, the data I was searching for was in the child of that instance. So, I have to use this way to access data
const accountInstance = vm.$children[0]
This works, because to test I defined a single child easy to identify. I also tried before using const accountInstance = new account() but that throws an error because vue components ar not constructors
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36925863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any way to get a warning in eg. GCC or Clang about this strict aliasing violation? The rationale for this being a strict aliasing violation is that
the buffer has declared type char array and is being aliased by
a pointer to struct
#include<string.h>
#include<stdalign.h>
#include<stdio.h>
struct thing {
int a;
char x;
};
int main() {
char alignas(struct thing) buffer[128];
struct thing s = {10,'a'};
struct thing *ptr = memcpy(buffer,&s,sizeof(struct thing));
// violation at ptr->a
printf("%d\n",ptr->a);
return 0;
}
A: A compiler that warned about all constructs that violate the constraints in N1570 6.5p7 as written would generate a lot of warnings about constructs which all quality implementations would support without difficulty. The only way those parts of the Standard would make any sense would be if the authors expected quality implementations to extend the semantics of the language to support use cases which, even if they're not mandated by the Standard, they should have no reason not to support. The use case illustrated in the presented code is an example of this.
Although the Standard would not forbid implementations from using N1570 6.5p7 as an excuse to behave nonsensically even in situations where an object is only ever used as a single type of storage, the stated purpose of the rules is to describe situations where implementations would or would not be required to allow for the possibility of pointer aliasing. Forbidding the particular construct at issue even in cases where storage is only used as a single type would do nothing to further that aim. If code were to use the subscripting operator on buffer, in addition to accessing the storage via a struct thing*, a compiler might legitimately fail to recognize the possibility that accesses using the latter lvalue might interact with those using the former. In the presented code, however, the storage is only used as type struct thing or via memcpy, usage cases that there would have been no reason to prohibit. Writing the rules in such a way as to only forbid use of a char[] to hold data of some other type in situations where it was also subscripted would definitely add complexity, but would not have been expected to make compilers support any constructs they wouldn't have supported anyway.
If the Standard had been intended to characterize programs into those that were correct or incorrect, it would need to have been worthwhile to write more detailed rules. Since it made no attempt to distinguish constructs which are erroneous from those which are correct but "non-portable" (in the sense that there might exist some implementations which don't process them meaningfully), however, there was no need to try to explicitly identify and provide for all of the constructs which compilers would have no reason not to process meaningfully.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68687936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Overriding an external style sheet without access to I have a Ecommerce Host that does not allow access to the Header Tag or the External .CSS file.
I have to override using inline styles.
Problem is, I have to override Pseudo Class :active
Is there way to link an external style sheet from within an inline style so that I can style the pseudo classes?
Any simple alternatives? Without access?
A: You don't need to put your <link rel="stylesheet" href="blah-blah.css"> tag into head to make it work, but it's a bad practice, because it works slower and looks a bit bad, but I understand your situation :) Just put <link> at the end of the <body> and it'll work fine! For example:
File styles.css
p {
color: blue;
}
File index.html
<!DOCTYPE html>
<html>
<head>
<!-- Evil host holders didn't allow access this tag. Well, okay :D -->
</head>
<body>
<p>I am blue, da ba dee da ba dai!</p>
<link rel="stylesheet" href="styles.css"/>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69055438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C#: RunWorkerAsync() doesn't trigger DoWork() I am writing a small forms based application to connect to an LDAP server, and I wanted the "connect" button to work in the background. So I was following the information and discussion
here
but for whatever reason my code doesn't appear to be working right: I set a breakpoint at 'worker.RunWorkerAsync();' And it just steps right through it.
What am I doing wrong? I am working in Visual Studio 2010, in case it matters.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Threading;
namespace ldapconnect
{
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
}
public Form1()
{
InitializeComponent();
}
//server
public string lds;
//naming context
public string root;
public string username;
public string password;
BackgroundWorker worker = new BackgroundWorker();
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
worker = sender as BackgroundWorker;
foreach (string s in connect(worker, e, lds + "/" + root, txt_user.Text.ToString(), txt_pass.Text.ToString()))
{
rtb_results.Text += s + "\r\n";
}
}
private List<string> connect(BackgroundWorker worker, DoWorkEventArgs e, String serv, string usr, string pass)
{
//Directory search code taking server path and creds passed in from form
DirectoryEntry conn = new DirectoryEntry(serv, usr, pass);
DirectorySearcher ds = new DirectorySearcher(conn);
//I only want users
ds.Filter = "objectClass=user";
List<string> sendBack = new List<string>();
try
{
SearchResultCollection results = ds.FindAll();
foreach (SearchResult result in results)
{
sendBack.Add(result.ToString());
}
}
catch (Exception ex)
{
sendBack.Clear();
sendBack.Add(ex.ToString());
}
return sendBack;
}
//connect button start background worker
private void btn_connect_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
//Exit Button
private void btn_close_Click(object sender, EventArgs e)
{
this.Close();
}
//set server path
private void btn_server_Click(object sender, EventArgs e)
{
string serv = inputBox("ldap://", "IP or DNS Name of LDS Server", "");
lds = serv;
lbl_server.Text = lds;
}
//set default context
private void btn_context_Click(object sender, EventArgs e)
{
string cntx = inputBox("In CN=,DC=,DC= Form:", "Default Naming Context", "");
root = cntx;
lbl_cntx.Text = root;
}
//VB interaction box
private string inputBox(string a,string b,string c)
{
return Microsoft.VisualBasic.Interaction.InputBox(a, b, c);
}
private void btn_Defaults_Click(object sender, EventArgs e)
{
lds = "LDAP://127.0.0.1";
root = "DC=USERS,DC=TEST,DC=LOCAL";
txt_user.Text = "reader";
txt_pass.Text = "password";
lbl_server.Text = lds;
lbl_cntx.Text = root;
}
}
}
A: You have not set
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
before calling worker.RunAsync()
A: You are never wiring up the event.
public Form1()
{
InitializeComponent();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
}
A: RunWorkerAsync() starts the worker thread and immediately returns thus the debugger seems to "step through it". Set a breakpoint in the worker_DoWork() method.
A: If u still have event and is not working, try the following
Just call
System.Windows.Forms.Application.DoEvents();
before calling RunWorkerAsync()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14734517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Qt QInputDialog parameter list I am starting a Qt course this semester. Having looked at the official documentation as well as some on line examples I am confused by the parameter lists of the QInputDialog and QMessagebox classes.
Is there anywhere where one could find some decent info as to what to pass when creating the class / form?
Right now I have this by trial error
tempC = QInputDialog::getDouble(0, "Temperature Converter",
"Enter the temperature in Celsius to convert to Fahrenheit:", 1);
Looking at the official docs doesn't help a lot either (at least not for me yet) as it says this:
double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
tr("Amount:"), 37.56, -10000, 10000, 2, &ok);
as an example.
Any links will be much appreciated.
A: double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
tr("Amount:"), 37.56, -10000, 10000, 2, &ok);
*
*A dialog will popup with parent the widget in which you are using this function. (this)
*The dialog's title will be QInputDialog::getDouble() (tr is used in order to translate this string if you want using QtLinguist)
*Inside the dialog will be a double spibox and a label
*The label's string will be Amount:
*The default value of the spinbox (what you see when the dialog popups) will be 37.56
*The minimum value will be -10000 (you will not be able to set a value less than this)
*The maximum value will be 10000 (you will not be able to set a value greater than this)
*Two decimal point will be displayed, eg 3.478 will be displayed as 3.48.
*If the user presses the Ok button then the ok argument will be set to true, otherwise it will be set to false
Check the documentation which includes an example for more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8871013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Object of type Period is not JSON serializable in plotly I am trying to plot a line chart. Below is my code
CODE :
import plotly.offline as pyo
import plotly.graph_objects as go
flag = determineFlag('2020-03-01','2020-03-30')
df_r = getDataForTrend(df,'2020-03-01','2020-03-30','d')
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
data = [go.Scatter(x = df_r[df_r['S2PName-Category']==category]['S2BillDate'],
y = df_r[df_r['S2PName-Category']==category]['totSale'],
mode = 'lines',
name = category) for category in df_r['S2PName-Category'].unique()]
layout = {'title':'Category Trend',
'xaxis':{'title':'Time Frame'},
'yaxis':{'title':'Total Sales Amount','tickformat' : '.2f'}}
fig = go.Figure(data=data,layout=layout)
pyo.iplot(fig)
when I run the above code I get the below error:
ERROR:
TypeError: Object of type Period is not JSON serializable
While tying to debug, I try to execute the below code
DEBUG CODE :
df_r[df_r['S2PName-Category']==category]['S2BillDate']
OP :
3 2020-03-01
11 2020-03-02
21 2020-03-03
26 2020-03-04
41 2020-03-06
42 2020-03-05
46 2020-03-07
Name: S2BillDate, dtype: period[D]
How can I fix the type error ? Is there any tweaks to this ? Any help is much appreciated! Thanks !
A: AFAIK this is still an issue and plotly will fail in such situation. There is still an open issue at github: Support for Pandas Time spans as index col.
As proposed in the comments one of the solution is to use to_timestatmp conversion, see this.
*
*Create MWE (this is just for reproducibility since there is no data provided in the question)
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.offline as pyo
df = pd.DataFrame({"one": np.random.random(10)}, index=pd.period_range("2020-03-01", freq="M", periods=10))
# Out:
# one
# 2020-03 0.302359
# 2020-04 0.919923
# 2020-05 0.673808
# 2020-06 0.718974
# 2020-07 0.754675
# 2020-08 0.731673
# 2020-09 0.772382
# 2020-10 0.654555
# 2020-11 0.549314
# 2020-12 0.101696
data = [
go.Scatter(
x=df.index,
y=df["one"],
)
]
fig = go.Figure(data=data)
pyo.iplot(fig)
# -> will fail ("TypeError: Object of type Period is not JSON serializable")
*Use to_timestamp conversion (-> df.index.to_timestamp())
data = [
go.Scatter(
x=df.index.to_timestamp(), # period to datetime conversion
y=df["one"],
)
]
fig = go.Figure(data=data)
pyo.iplot(fig)
Or, if you do not need datetime format you can convert this to string as well:
data = [
go.Scatter(
x=df.index.strftime("%Y-%m"), # You can define your own format
y=df["one"],
)
]
fig = go.Figure(data=data)
pyo.iplot(fig)
You can of course do this conversion right on the original dataframe (so you do not need to do it iteratively inside go.Scatter), but this is just minor stuff. There might be also a way of using custom encoder instead of the default one, but I think it's not worthy of trying and afaik there is no better solution than using one of possible conversion from Period to datetime or string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61088783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Start Activity while Countdown is running I have a problem with my Android app at the moment. I use the Google Client Message Service to send messages to my Android App. If the user opens the app, he starts on the HomeActivity.
When the user now receives my message from the server and press on the push message, the app starts a new intent with the AlertActivity.
At this point, I pass the time (saved in the message) with putExtra to the new activity, where i use it for a CownDownTimer. Till this point everything is ok and the countdown works perfect.
The problem is now, when the user minimizes the app and open it again.
At this Point the user is not redirected to my AlertActivity again but to my HomeActivity.
After the CountDownTimer Ends the AlertSound is played, but he can't cancel it, because he can't show the activity again.
How can I redirect the User to the AlertActivity if he starts the app while the CountDown is running?
My AlertActivity
package com.prgguru.example;
public class AlertActivity extends Activity {
String str;
Boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert);
final TextView txttime = (TextView) findViewById(R.id.txtalert);
str = getIntent().getStringExtra("msg");
Integer time = Integer.parseInt(str);
time = time; //*60000;
txttime.setText(time+"");
CountDownTimer Count = new CountDownTimer(time, 1000) {
@Override
public void onTick(long millisUntilFinished) {
running = true;
txttime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
//txttime.setText(""+millisUntilFinished / 1000);
}
@Override
public void onFinish() {
txttime.setText("Finished");
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.alarm);
mp.start();
}
};
Count.start();
}
public boolean getRunning(){
return false;
}
}
GCMIntentService
public class GCMIntentService extends IntentService {
// Sets an ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification(extras.get(ApplicationConstants.MSG_KEY)+"");
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
Intent resultIntent = new Intent(this, AlertActivity.class);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Alert")
.setContentText("You've received new message.")
.setSmallIcon(R.drawable.ic_launcher);
// Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
//defaults = defaults | Notification.DEFAULT_LIGHTS;
//defaults = defaults | Notification.DEFAULT_VIBRATE;
// defaults = defaults | Notification.DEFAULT_SOUND;
Notification notification = mNotifyBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alarm);
notification.defaults |= Notification.DEFAULT_VIBRATE;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("New message from Server");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, notification);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30199487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Handle multiple login page for different type of user in asp.net core mvc 6 In asp.net core i need to manage two different types of user (administrator and normal user).
When user session is expired i want administrater to be redirected to baseurl/admistrator/login and for normal user redirect to baseurl/login
services.AddIdentity<User, Role>(op =>
{
op.SecurityStampValidationInterval = TimeSpan.FromSeconds(0);
op.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromMinutes(30);
op.Cookies.ApplicationCookie.SlidingExpiration = true;
//here how can i set multiple login path
//op.Cookies.ApplicationCookie.LoginPath = new Microsoft.AspNetCore.Http.PathString("/administrator/account/login");
//op.Cookies.ApplicationCookie.LoginPath = new Microsoft.AspNetCore.Http.PathString("/login");
Does anyone have idea how to do it ?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44039914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Drive API with Python from server(Backend) without browser autentication I'd like to save the files of my Saas Appication to my Google Drive Account, all the examples I've seen was with oauth2 autentication and needs the end user autenticate openning the browser, I need to upload files from my server without any user interation, sending files direct to my account!
I have try many tutorials I found on internet with no success, mainly the oficial
Google Drive API with Python
How can I autenticate programatically from my server and upload files and use API features such as share folders and others?
I'm using Python, the lib PyDrive uses the same aproach to autenticate
A: To add to andyhasit's answer, using a service account is the correct and easiest way to do this.
The problem with using the JSON key file is it becomes hard to deploy code anywhere else, because you don't want the file in version control. An easier solution is to use an environment variable like so:
https://benjames.io/2020/09/13/authorise-your-python-google-drive-api-the-easy-way/
A: You can do this, but need to use a Service Account, which is (or rather can be used as) an account for an application, and doesn't require a browser to open.
The documentation is here: https://developers.google.com/api-client-library/python/auth/service-accounts
And an example (without PyDrive, which is just a wrapper around all this, but makes service account a bit trickier):
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
scopes = ['https://www.googleapis.com/auth/drive.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('YourDownloadedFile-5ahjaosi2df2d.json', scopes)
http_auth = credentials.authorize(Http())
drive = build('drive', 'v3', http=http_auth)
request = drive.files().list().execute()
files = request.get('items', [])
for f in files:
print(f)
A: I know it's quite late for answer but this worked for me:
Use the same API you were using, this time in your computer, it will generate a Storage.json which using it along with your scripts will solve the issue (specially in read-ony platforms like heroku)
A: Checkout the Using OAuth 2.0 for Web Server Applications. It seems that's what you're looking for.
Any application that uses OAuth 2.0 to access Google APIs must have
authorization credentials that identify the application to Google's
OAuth 2.0 server. The following steps explain how to create
credentials for your project. Your applications can then use the
credentials to access APIs that you have enabled for that project.
Open the Credentials page in the API Console. Click Create credentials
OAuth client ID. Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP,
Java, Python, Ruby, and .NET must specify authorized redirect URIs.
The redirect URIs are the endpoints to which the OAuth 2.0 server can
send responses. For testing, you can specify URIs that refer to the
local machine, such as http://localhost:8080.
We recommend that you design your app's auth endpoints so that your
application does not expose authorization codes to other resources on
the page.
A: Might be a bit late but I've been working with gdrive over python, js and .net and here's one proposed solution (REST API) once you get the authorization code on authorization code
How to refresh token in .net google api v3?
Please let me know if you have any questions
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46457093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How can I delete the selected messages (with checkboxes) in jQuery? I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
if ($('#checkbox_' + id).is(':checked')) {
$('#' + id).addClass("selected");
}
else {
$('#' + id).removeClass("selected");
}
}
But, I don't know where to go from there.
Here is some example markup for one of the lines [generated by PHP] of the list of messages:
<div class="line" id="33" >
<span class="inbox_check_holder">
<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />
<span class="star_clicker" id="star_33" onclick="addStar(33)" title="Not starred">
<img id="starimg_33" class="not_starred" src="images/blank.gif">
</span>
</span>
<div class="line_inner" style="display: inline-block;" onclick="readMessage(33, 'Test')">
<span class="inbox_from">Nathan</span>
<span class="inbox_subject" id="subject_33">Test</span>
<span class="inbox_time" id="time_33" title="">[Time sent]</span>
</div>
</div>
As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {
}
else {
alertBox('No messages selected.'); //this is a custom function
}
});
I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!
A: How about this
$('#delete').click(function() {
var checked = $('.inbox_check:checked');
var ids = checked.map(function() {
return this.value; // why not store the message id in the value?
}).get().join(",");
if (ids) {
$.post(deleteUrl, {idsToDelete:ids}, function() {
checked.closest(".line").remove();
});
}
else {
alertBox('No messages selected.'); // this is a custom function
}
});
Edit: Just as a side comment, you don't need to be generating those incremental ids. You can eliminate a lot of that string parsing and leverage jQuery instead. First, store the message id in the value of the checkbox. Then, in any click handler for a given line:
var line = $(this).closest(".line"); // the current line
var isSelected = line.has(":checked"); // true if the checkbox is checked
var msgId = line.find(":checkbox").val(); // the message id
var starImg = line.find(".star_clicker img"); // the star image
A: Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
var result = null;
var scriptUrl = './databaseDelete.php';
$.ajax({
url: scriptUrl,
type: 'post',
async: false,
data: {id: reference_id},
success: function(response)
{
result = response;
}
)};
return result;
}
$('.inbox_check').each(function(){
if ($(this).is(':checked')){
var row = $(this).parent().parent();
var id = row.attr('id');
if (id == null)
{
alert('My selector needs updating');
return false;
}
var debug = 'Deleting ' + id + ' now...';
if (console) console.log(debug);
else alert(debug);
row.remove();
var response = removeDatabaseEntry(id);
// Tell the user something happened
$('#response_div').html(response);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8002068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting Error after implementing ROOM database in kotlin Gradle (Module) :
def room_ver = "2.2.5"
dependencies {
implementation "androidx.room:room-ktx:" + room_ver
kapt "androidx.room:room-compiler:" + room_ver
androidTestImplementation "androidx.room:room-testing:" + room_ver
}
Error :
Tried adding :
gradle (app level)
dependencies {
classpath "com.android.tools.build:gradle:3.1.3"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}
gradle : Module
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-kapt'
Dashboard.kt
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.view.inputmethod.EditorInfo
import android.widget.TextView.GONE
import android.widget.TextView.OnEditorActionListener
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.ddnsoftech.mrenvois.R
import com.ddnsoftech.mrenvois.common.APIService.Const
import com.ddnsoftech.mrenvois.common.APIService.IntentKeys
import com.ddnsoftech.mrenvois.common.`interface`.BackButtonClickIntefrace
import com.ddnsoftech.mrenvois.common.helpers.UserSession
import com.ddnsoftech.mrenvois.common.util.SnackNotify
import com.ddnsoftech.mrenvois.common.util.hideKeyboard
import com.ddnsoftech.mrenvois.model.Restaurant
import com.ddnsoftech.mrenvois.view.Activities.RestaurantsDetails.ResturantsDetailsActivity
import com.ddnsoftech.mrenvois.view.Adapter.CategoryAdapter
import com.ddnsoftech.mrenvois.view.Adapter.ResturantAdapter
import com.ddnsoftech.mrenvois.view.BaseActivity.BaseActivity
import com.ddnsoftech.mrenvois.view.ServiceNotAvailable.ServiceNotAvailableActivity
import kotlinx.android.synthetic.main.filer_search_view.*
import kotlinx.android.synthetic.main.fragment_dashboard.*
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [DashboardFragment.newInstance] factory method to
* create an instance of this fragment.
*/
private enum class DashboardListType {
FILTER_VIEW,HOME_VIEW
}
enum class FilterType {
popular,promo,location
}
class DashboardFragment : Fragment(), BackButtonClickIntefrace {
val viewModel = DashboardFragmentVM()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
// param1 = it.getString(ARG_PARAM1)
// param2 = it.getString(ARG_PARAM2)
}
hideKeyboard()
}
lateinit var popularRestaurantAdapter: ResturantAdapter
lateinit var nearRestaurantAdapter: ResturantAdapter
lateinit var categoryAdapter: CategoryAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_dashboard, container, false)
}
override fun onStart() {
super.onStart()
txtDeliveringTo.text = "${getString(R.string.delivering_to)} ${UserSession.shared.currentAddress?.address ?: ""}"
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initialSetup()
getHomePageData()
}
companion object {
@JvmStatic
fun newInstance() =
DashboardFragment().apply {
// arguments = Bundle().apply {
// putString(ARG_PARAM1, param1)
// putString(ARG_PARAM2, param2)
// }
}
}
@SuppressLint("ClickableViewAccessibility")
fun initialSetup() {
viewModel.clearFilter()
popularRestaurantAdapter = ResturantAdapter(viewModel.popular_restaurant,requireActivity())
nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
categoryAdapter = CategoryAdapter(viewModel.categories,requireContext())
popularRestaurantAdapter.onItemSelect = { restaurant ->
redirectToRestaurantDetails(restaurant)
}
nearRestaurantAdapter.onItemSelect = { restaurant ->
redirectToRestaurantDetails(restaurant)
}
categoryAdapter.onItemSelect = { index,value ->
viewModel.restaurants.clear()
viewModel.categories[index] = value
getHomePageData()
}
val manager1 = GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
recyclerViewMostPopular.layoutManager = manager1
val manager2 = GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
recyclerViewNearBy.layoutManager = manager2
val manager3 = LinearLayoutManager(requireActivity(),LinearLayoutManager.HORIZONTAL,false)
// GridLayoutManager(requireActivity(), 4, GridLayoutManager.HORIZONTAL, false)
recyclerViewCategory.layoutManager = manager3
recyclerViewMostPopular.adapter = popularRestaurantAdapter
recyclerViewNearBy.adapter = nearRestaurantAdapter
recyclerViewCategory.adapter = categoryAdapter
scrollView.viewTreeObserver
.addOnScrollChangedListener(OnScrollChangedListener {
if (scrollView != null) {
val bottom: Int =
scrollView.getChildAt(scrollView.childCount - 1)
.height - scrollView.height - scrollView.scrollY
// if (scrollView.scrollY === 0) {
// //top detected
// SnackNotify.showMessage("Reached to top",relyMain,SnackNotify.MSGType.SUCCESS)
// }
if (scrollView.scrollY == 120) {
hideKeyboard()
}
if (bottom == 0) {
//bottom detected
if (viewModel.isFilterApplied()) {
getHomePageData()
}
//SnackNotify.showMessage("Reached to Bottom",relyMain,SnackNotify.MSGType.SUCCESS)
}
}
})
swipeRefreshLayout.setOnRefreshListener {
viewModel.restaurants.clear()
getHomePageData()
}
/// Ser view handler
// etSearchView.
setupSearchView()
setUpFilerView()
reloadList()
}
fun redirectToRestaurantDetails(restaurant: Restaurant) {
var intent = Intent(requireActivity(), ResturantsDetailsActivity::class.java)
intent.putExtra(IntentKeys.RESTAURANT,restaurant)
activity?.startActivity(intent)
}
fun setUpFilerView() {
lnrPopular.setOnClickListener { view ->
onFilterButtonClick(view)
}
lnrPromos.setOnClickListener { view ->
onFilterButtonClick(view)
}
lnrLocation.setOnClickListener { view ->
onFilterButtonClick(view)
}
txtNearByViewAll.setOnClickListener {
onFilterButtonClick(lnrLocation)
}
txtPopularViewAll.setOnClickListener {
onFilterButtonClick(lnrPopular)
}
txtDeliveringTo.setOnClickListener {
(requireActivity() as? BaseActivity)?.openSetLocation()
}
}
fun setupSearchView() {
etSearchView.setOnTouchListener(View.OnTouchListener { _ , event ->
val DRAWABLE_RIGHT = 2
if (event.action == MotionEvent.ACTION_UP) {
if (event.rawX >= etSearchView.right - etSearchView.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
) {
viewModel.restaurants.clear()
getHomePageData()
true
}
}
false
})
etSearchView.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
viewModel.restaurants.clear()
getHomePageData()
true
} else false
})
// etSearchView.doOnTextChanged { text, start, before, count ->
// }
}
fun getHomePageData() {
hideKeyboard()
viewModel.search = etSearchView.text?.toString()
swipeRefreshLayout.isRefreshing = true
viewModel.getHomeData { success,errMsg ->
swipeRefreshLayout.isRefreshing = false
if (success) {
reloadList()
}else {
SnackNotify.showMessage(errMsg,relyMain, SnackNotify.MSGType.ERROR)
reloadList()
}
}
}
fun getSearchData() {
}
fun reloadList() {
if (viewModel.isFilterApplied()) {
if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.VERTICAL) {
val handler = nearRestaurantAdapter.onItemSelect
nearRestaurantAdapter = ResturantAdapter(viewModel.restaurants,requireActivity(), GridLayoutManager.VERTICAL)
nearRestaurantAdapter.onItemSelect = handler
val manager2 = GridLayoutManager(requireActivity(), 1, GridLayoutManager.VERTICAL, false)
recyclerViewNearBy.layoutManager = manager2
recyclerViewNearBy.adapter = nearRestaurantAdapter
}
lnrMostPopularContainer.visibility = View.GONE
lnrTopCategoryContainer.visibility =
if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE
lnrNearByContainer.visibility =
if (viewModel.restaurants.count() == 0) View.GONE else View.VISIBLE
viewNoRecordFound.visibility =
if (viewModel.restaurants.count() != 0) View.GONE else View.VISIBLE
//popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
nearRestaurantAdapter.updateList(viewModel.restaurants)
categoryAdapter.updateList(viewModel.categories)
txtNearByTitle.text = getString(R.string.restaurants)
txtNearByViewAll.visibility = View.GONE
reloadFilterTab(true)
}else{
if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.HORIZONTAL) {
nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
val manager2 = GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
recyclerViewNearBy.layoutManager = manager2
recyclerViewNearBy.adapter = nearRestaurantAdapter
}
txtNearByTitle.text = getString(R.string.near_by)
txtNearByViewAll.visibility = View.VISIBLE
viewNoRecordFound.visibility = if (viewModel.near_restaurants.count() == 0 && viewModel.popular_restaurant.count() == 0) View.VISIBLE else View.GONE
lnrMostPopularContainer.visibility =
if (viewModel.popular_restaurant.count() == 0) View.GONE else View.VISIBLE
lnrNearByContainer.visibility =
if (viewModel.near_restaurants.count() == 0) View.GONE else View.VISIBLE
lnrTopCategoryContainer.visibility =
if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE
popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
nearRestaurantAdapter.updateList(viewModel.near_restaurants)
categoryAdapter.updateList(viewModel.categories)
reloadFilterTab(false)
}
}
fun reloadFilterTab(filterApplied:Boolean) {
if (filterApplied && viewModel.filterType != null)
{
when (viewModel.filterType!!) {
FilterType.popular -> {
lnrPopular.background = resources.getDrawable(R.drawable.filter_active_border)
lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
}
FilterType.promo -> {
lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
lnrPromos.background = resources.getDrawable(R.drawable.filter_active_border)
lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
}
FilterType.location -> {
lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
lnrLocation.background = resources.getDrawable(R.drawable.filter_active_border)
}
}
}else{
lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
}
}
override fun onBackClicked(): Boolean{
// TODO("Not yet implemented")
if (viewModel.isFilterApplied())
{
viewModel.clearFilter()
getHomePageData()
return true
}
return false
}
fun onFilterButtonClick(v: View) {
when (v) {
lnrPopular -> {
viewModel.filterType = if( viewModel.filterType == FilterType.popular ) null else FilterType.popular
}
lnrPromos -> {
viewModel.filterType = if( viewModel.filterType == FilterType.promo ) null else FilterType.promo
}
lnrLocation -> {
viewModel.filterType = if( viewModel.filterType == FilterType.location ) null else FilterType.location
}
}
reloadFilterTab(viewModel.filterType != null)
viewModel.restaurants.clear()
getHomePageData()
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64625771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: modal does not load form data I have the data form and the data update views, when I'm not using the modal, it works perfectly, however when using modal, it loads the empty forms, and if I load without the modal, the data saved in the database appear .
I do not know where I'm going wrong.
I can change the user name and save, the problem is that let's say user1 and I want to change to the user2 name, when I click to change the name, the form field does not come with user1 filled in.
and if I do not use the modal, it comes with the user1 already filled in
views.py
class UserNameUpdate(LoginRequiredMixin, UpdateView):
model= User
fields = ['username']
template_name=' /change-username.html'
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset() # This should help to get current user
# Next, try looking up by primary key of Usario model.
queryset = queryset.filter(pk=self.request.user.usuario.pk)
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
raise Http404("No user matching this query")
return obj
def get_success_url(self):
return reverse('sistema_perfil')
change-username.html
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}
<div class="container">
<div class="card text-white bg-primary mb-3">
<div class="card-header"><small class="text">
<a href="{% url 'sistema_index' %}" class="text-white ">Home /</a>
<a href="{% url 'sistema_perfil' %}" class="text-white ">Perfil /</a>
<a class="text-white">Usúario</a>
</small></a></p> Alterar Nome do Usúario</div>
<div class="card bg-light text-center ">
<div class="card-body text-secondary text-center">
<form method="post" action="{% url 'sistema_change_username' %}" class="form-signin" enctype="multipart/form-data" id="form" name="form" validate>
{% csrf_token %}
<div class="form-row ">
<div class="form-group col-md-6 text-center">
{{ form.username| as_crispy_field}}
</div>
</div>
<input type="submit" class="btn btn-primary " >
</form>
<a class="btn btn-light float-left" href="sistema_perfil" role="button">Voltar</a>
</div>
</div>
</div>
</div>
{% endblock %}
menu_perfil.html
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% include 'profile/change-username.html' %}
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
A: Am I right that the with-modal and without-modal templates load from two different views? If so, the problem is how you are using Django's {% include %} template tag. Here are the docs:
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#include
Key line: "An included template is rendered within the context of the template that includes it."
It looks like menu_perfil.html is rendered from a different view, which doesn't pass the form object into its context. So menu_perfil.html doesn't know what {{ form }} is. Whereas change-username.html is rendered with your UsernameUpdate view with the form object. Try moving your modal HTML into change-username.html, around your form code, instead of including a separate snippet, and see if that solves the problem.
In general, inheriting from base templates using {% extends %} is preferable to using includes unless you really have to, because of limitations like this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55054888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: printing BST IN order I am trying to print out tree nodes IN order however all that it is coming out are the noes of the lowest depth! I'm not sure what is wrong with my logic so I was wondering if another set of eyes would help me or give me a hint thanks!!
Expected output:
1
2
3
4
6
8
10
my code:
class Node:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def BST_Insert(root, node): # root --> root of tree or subtree!
if root.value is None:
root = node # beginning of tree
else:
if root.value > node.value: # go to left
if root.left is None:
root.left = node
else:
BST_Insert(root.left, node)
if root.value < node.value: # go to right
if root.right is None:
root.right = node
else:
BST_Insert(root.right, node)
def inorder_print(root):
if root.left is not None:
inorder_print(root.left)
else:
print root.value
if root.right is not None:
inorder_print(root.right)
r = Node(4)
# left
a = Node(2)
b = Node(1)
c = Node(3)
# right
d = Node(8)
e = Node(6)
f = Node(10)
BST_Insert(r, a)
BST_Insert(r, b)
BST_Insert(r, c)
BST_Insert(r, d)
BST_Insert(r, e)
BST_Insert(r, f)
print "in order:"
inorder_print(r)
A: I don't think you need the else after the the first if statement.
Something like the following might work,
if left!=null:
inorder(left)
print(current_node.val)
if (right!=null):
inorder(right)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19177317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: htaccess [L] flag didn't work I have .htaccess file like this inside searchEngine folder inside htdocs of xampps
RewriteEngine On
RewriteRule ^\/?test$ view/index.php [NC,L]
RewriteRule ^(.*)$ http://google.com [NC,L]
then I type this in the address bar:
*
*localhost/searchEngine/test
Why this redirect to
*
*http://google.com
not
*
*view/index.php?
I thought this must be redirected to
*
*view/index.php
not
*
*http://google.com
A: It is because mod_rewrite runs in a loop. First rule is doing this:
Starting URL:
/searchEngine/test
Ending URL:
/searchEngine/view/index.php
Now L flag causes mod_rewrite to loop again. So now your starting URL becomes:
Starting URL:
/searchEngine/view/index.php
Now 1st rule' pattern ^test doesn't match but your 2nd rule is using .* as matching pattern hence redirects to google.
You can have your rules as follows to prevent this behavior:
RewriteEngine On
RewriteRule ^/?test$ view/index.php [NC,L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^ http://google.com [R,L]
2nd rule has this additional condition:
RewriteCond %{ENV:REDIRECT_STATUS} ^$
REDIRECT_STATUS is set to 200 after first rule's execution. So 2nd rule will redirect only if first rule hasn't executed first hence it will skip /test.
If you're using Apache 2.4+ then you can use END instead of L to end the execution:
RewriteEngine On
RewriteRule ^/?test$ view/index.php [NC,END]
RewriteRule ^ http://google.com [R,L]
A: This is happening because of the internal redirection, You can use the END flag instead of L to stop this behaviour :
RewriteEngine On
RewriteRule ^\/?test$ view/index.php [NC,END]
RewriteRule ^(.*)$ http://google.com [NC,L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37498484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to reduce duplication here? I am creating a prisoner's dilemma simulation and I have two functions that are counting cooperations and defections done by the two players and outputting them as a tuple. I see a lot of similarities and would like some guidance on how to consolidate the two functions into another function that the two can call upon so I am not reusing code. I am very new in OCaml so I am struggling to find a way to do this!
Here is the necessary information:
type action = bool ;;
type play = action * action ;;
type history = play list
let rec count_defections (history : history) : (int * int) =
match history with
| [] -> (0, 0)
| play :: rest ->
match play with
| (player1, player2) ->
match count_defections rest with
| (d1, d2) ->
if (player1, player2) = (false, false) then (d1 + 1, d2 + 1)
else if (player1, player2) = (false, true) then (d1 + 1, d2)
else if (player1, player2) = (true, false) then (d1, d2 + 1)
else (d1, d2) ;;
let rec count_cooperations (history : history) : (int * int) =
match history with
| [] -> (0, 0)
| play :: rest ->
match play with
| (player1, player2) ->
match count_cooperations rest with
| (d1, d2) ->
if (player1, player2) = (true, true) then (d1 + 1, d2 + 1)
else if (player1, player2) = (true, false) then (d1 + 1, d2)
else if (player1, player2) = (false, true) then (d1, d2 + 1)
else (d1, d2) ;;
My first thoughts were:
let count_common (history : history) : (int * int) =
match history with
| [] -> (0, 0)
| play :: rest ->
match play with
| (player1, player2) ->
match .....
But I don't really understand how to do the rest.
A: Here's a function that counts the two parts of a pair separately, counting elements that equal a given value.
let count_val_in_pairs value pairs =
List.fold_left
(fun (cta, ctb) (a, b) ->
((if a = value then cta + 1 else cta),
(if b = value then ctb + 1 else ctb)))
(0, 0)
pairs
Your count_defections is this:
let count_defections history =
count_val_in_pairs false history
Your count_cooperations is this:
let count_cooperations history =
count_val_in_pairs true history
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66149244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: taking input from file using scanner class in java I am trying store a list of cities in a class using two co-ordinates(x,y) in java
My class is as follows:
public class City {
int x;
int y;
// Constructs a city at chosen x, y location
public City(int x, int y){
this.x = x;
this.y = y;
}
}
I have made another class to store the cities in an ArrayList:
public class TourManager {
// Holds our cities
private static ArrayList destinationCities = new ArrayList<City>();
// Adds a destination city
public static void addCity(City city) {
destinationCities.add(city);
}
}
My main class is as follows:
public class Final {
public static void main(String[] args) {
// Create and add our cities
City city = new City(60, 200);
TourManager.addCity(city);
City city2 = new City(180, 200);
TourManager.addCity(city2);
City city3 = new City(80, 180);
TourManager.addCity(city3);
}
}
Here, I have stored three cities in the ArrayList inside the main function. But now I want to take the input from a file in the following format. I just want to take the co-ordinates ignoring all other lines.
NAME: sample.tsp
TYPE: TSP
COMMENT: Odyssey of Ulysses (Groetschel/Padberg)
DIMENSION: 3
EDGE_WEIGHT_TYPE: GEO
NODE_COORD_SECTION
1 60 200
2 180 200
3 80 180
I want to use the scanner class to take the input but getting confused in using it. i have made a partial code fragment to take input but it isn't working:
Scanner in = new Scanner(new File("sample.tsp"));
String line = "";
int n;
in.nextLine();
in.nextLine();
in.nextLine();
line = in.nextLine();
line = line.substring(11).trim();
n = Integer.parseInt(line);
in.nextLine();
in.nextLine();
But how will I take the coordinates using the City class object as I have done before from this file?
A: You need to skip the first few lines, which you don't need.
Then split the lines to get the various numbers. Index 0 contains the serial no., 1 and 2 contain the coordinates. Then parse them to int. eg:
in.nextLine();// multiple times.
//...
String cs = in.nextLine(); // get the line
City city = new City(Integer.parseInt(cs.split(" ")[1]), Integer.parseInt(cs.split(" ")[2]));
TourManager.addCity(city);
String cs2 = in.nextLine();
City city2 = new City(Integer.parseInt(cs2.split(" ")[1]), Integer.parseInt(cs2.split(" ")[2]));
TourManager.addCity(city2);
String cs3 = in.nextLine();
City city3 = new City(Integer.parseInt(cs3.split(" ")[1]), Integer.parseInt(cs3.split(" ")[2]));
TourManager.addCity(city3);
A: Whenever you use in.nextLine(), actually it takes the string that you entered. So try to assign it to some string variable. For example:
String s =in.nextLine();
Also, just using in.nextLine(); which you did in 2nd,3rd 4th,8th and 9th line is not needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36718469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sql query to fetch the third highest sale grouped by sales Fetch the third highest sale amount from the table (group by sale amount) in MySQL
select Top 3 * from t1 group by sale_Amnt
|Id|product_name|product_group |sale_Amnt(INR)
------------------------------------------------
1| p1 | Cosmetic |4485
2| p2 | Cosmetic |8525
3| p3 | Health |12589
4| p4 | Health |8525
5| p5 | Home Appliances|9858
6| p6 | Home Appliances|12589
Expected output
|Id|product_name|product_group |sale_Amnt(INR)
------------------------------------------------
2| p2 | Cosmetic |8525
4| p4 | Health |8525`
A: The proposed duplicate is a misunderstanding of the question. This question appears to be looking for the third highest value overall, but taking duplicates into account.
You can get the third row using offset/fetch in SQL Server:
select t.*
from t
where t.sale_amount = (select t2.sale_amount
from t t2
group by t2.sale_amount
order by t2.sale_amount desc
offset 2 fetch first 1 row only
);
In MySQL, that would be:
select t.*
from t
where t.sale_amount = (select t2.sale_amount
from t t2
group by t2.sale_amount
order by t2.sale_amount desc
limit 1 offset 2
);
A:
SELECT * FROM `sale_amnt` ORDER BY `sale_Amnt` DESC LIMIT 2,1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49732062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL divide by shifted value of other field I have a table that looks like this:
Where RETENTION is the division of N_CUSTOMERS by CUSTOMER_WHEN_0 for each PERIOD_NUMBER.
Now I need to get another new field that is the result of dividing each retention value of thar PERIOD_NUMBER by the retetion value of the previous PERIOUD_NUMBER. In the example of the image it's not appreciated, but I have all the consecutive values for PERIOD_NUMBER. When the PERIOD_NUMBER is 0, it doesn't matter that the division by its shifter value is NAN or similar, I will replace it later.
So, summarizing, my desired output is a ner field that shows the result of dividing the RETENTION value of the PERIOD_NUMBER of that row by the RETENTION value of the previous PERIOD_NUMBER. I'm using DBT and in case is useful I have the querys I used to get these fields and I have the code to do that process in Python, but I need to do it in SQL
first purchase of the user, ORDER_MONTH is the date of that purchase, and PERIOD_NUMBER is the date difference in months between COHORT and ORDER_MONTH. N_CUSTOMERS is the number of customers in each PERIOD_NUMBER in each COHORT, and CUSTOMER_WHEN_0 is the number of users in each cohort when the PERIOD_NUMBER is 0.
I had to use a window function in order to achive this last field.
A: Here is an example of how you can get the previous RETENTION using a subquery, assuming that the period numbers are all consecutive:
SELECT
N_CUSTOMERS,
PERIOD_NUMBER,
CUSTOMER_WHEN_0,
RETENTION,
(SELECT st_inner.RETENTION
FROM sourcetable st_inner
WHERE st_inner.PERIOD_NUMBER = st_outer.PERIOD_NUMBER - 1
) as PREVIOUS_RETENTION
FROM sourcetable st_outer
I left out the calculation for readability's sake, but I think it should be clear how to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68338485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AngularJS. Displaying custom popup on user's attempt to leave the page Is it possible to synchronously display bootstrap modal (instead of native confirm) when user tries:
*
*change route
*leave the page
(AngularJS)
A: You must separate your code into two different functions.
If you have this:
var txt;
var r = confirm("Press a button!");
if (r == true) {
// Put this in a function ...
txt = "You pressed OK!";
} else {
// ... and this in another function
txt = "You pressed Cancel!";
}
Would like this:
var onOkClick = function(){
txt = "You pressed OK!";
};
var onCancelClick = function(){
txt = "You pressed Cancel!";
};
And in the buttons of your modal:
<button type='button' class='btn btn-success' onclick="onOkClick()">OK</button>
<button type='button' class='btn btn-default' onclick="onCancelClick()">Cancel</button>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27510360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: This is a number guessing game the num_check function works just fine the first time but won't run any second attempts. Does anyone know why? import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
A: After getting input from console, you should create a loop which breaks when guessed number equal to input. For example:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
After revision, code seems like:
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
A: You should use while True:, because your guessing code runs only once without it
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 10)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
att = 1
num = num_gen()
while True:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
print('Your guess was HIGH! Please guess another number between 1 and 100: ')
att += 1
elif result == 'low':
print('Your guess was LOW! Please guess another number between 1 and 100: ')
att += 1
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
break
A: It's because python programs runs from top to bottom, and when it reaches the bottom it's done and stops running. To stop this order we have multiple different ways:
We can call a function, as you do in you're program.
Selection Control Structures: As if statements
Iteration Control Structures: As loops
The last one is the one you need in this solution. Wrap code in a while loop, with the correct condition, in you're example, this would be
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
The best way woul be to use a will loop as follow:
while guess != num:
A: how can you expect it to run more than 1 time if you have not used any loop in the program. For example in this case you should use a while loop, then only it will prompt the user again and again and will check for the conditions, set a game variable to be True. When the number is matched then simply set the game variable to be False and it will end the loop.
import random
# Set the game variable initially to be True
game = True
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while game:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
game = False
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70648761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use query string to find requesting page in ASP.NET? I have a page signup.aspx where user can register, how this page will find from which page request came from and how it will redirect user after registration to the requesting page. I want to do this using query string but don't know how
A: On any links to the register page put
<a href="Signup.aspx?ReturnUrl=<%=Request.Url.AbsolutePath%>">Register Here</a>
then on your register form when they have registered add:
if (!String.IsNullOrEmpty(Request["ReturnUrl"]))
Response.Redirect(Request["ReturnUrl"]);
else
Response.Redirect("~/Default.aspx");
A: if(Request.QueryString["foo"] == "bar"){
Response.Redirect("page.php", true);
}
This would get the information from http://www.example.com/registered.aspx?foo=bar
So Request.QueryString["QueryString"] is the value of anything after the ? and each variable after the &. so if you had http://www.example.com/registered.aspx?foo=bar&abc=def
Then you would have 2 querystrings, foo and abc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5211663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How Can I Implement Realtime Notification On My Php Page This Is My Home.Php ,I Need To Display Realtime Notification From Database
<html>
<body>
<label>Notifications <?php echo "(".$notification.")"; ?>)</label>
//$notification Contain no. of Notifications From Database
</body>
</html>
A: You need to use web socket for real time notification. You can try Ratchet or socket.io.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39388930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: How to sum the values of all the textboxes with same class which are generated using ajax? I want to sum of all the values of textboxes generated using ajax. I have the textboxes with classname adminhoursand these textboxes are generated using ajax. The sum should be displayed in another textbox on the change event of the textbox with class adminhours. The sum should be multiplied with the admin rate textbox. Please help me. Thanks in advance.
HTML
<form action="" method="post">
<div class="timecardstepcontainer">
<table class="widefat" style="width:100%" id="steponetable">
<thead>
<tr>
<th>Name</th>
<th>Email2(payment)</th>
<th>Class Rate</th>
<th>Admin Rate</th>
<th>Week</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="txtuser" id="txtuser">
<option>--select--</option>
<option value="2">nitinjohnson2000</option>
</select>
</td>
<td><input type="text" name="txtemail2" style="width:100%;" readonly=""></td>
<td width="5%"><input type="text" name="txtclassrate" style="width:80px;" readonly=""></td>
<td width="5%"><input type="text" name="txtadminrate" style="width:80px;" readonly=""></td>
<td><!--<input type="text" name="txtweek" id="txtweek" />-->
<select name="txtweek" id="txtweek">
<option>--select--</option>
<option>08-31-2015</option>
<option>09-07-2015</option>
<option>09-14-2015</option>
<option>09-21-2015</option>
<option>09-28-2015</option>
<option>10-05-2015</option>
<option>10-12-2015</option>
<option>10-19-2015</option>
</select>
</td>
<td><label id="txtstatus">Not Saved</label></td>
<td><textarea name="txtcomment"></textarea></td>
</tr>
</tbody>
</table>
</div>
<div class="timecardstepcontainer" id="steptwotable">
<table class="widefat" style="width:100%">
<thead>
<tr>
<th>Session</th>
<th>Day of week</th>
<th>Date</th>
<th>Pre-Assigned</th>
<th>Start Date</th>
<th>End Date</th>
<th>Present</th>
<th>Late Arrival</th>
<th>Expense</th>
<th>Admin Hours</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fall 2015 - Bethany Elementary Chess Program - Plano ISD</td>
<td>Wed</td>
<td>09-02-2015</td>
<td>Y</td>
<td>2015-09-09</td>
<td>2015-12-12</td>
<td><input type="checkbox" name="presentdays[]"></td>
<td><input type="checkbox" name="latedays[]"></td>
<td>5</td>
<td><input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;"></td>
<td><input type="text" name="item_comment" style="width:80px;"></td>
</tr>
<tr>
<td>Fall 2015 - Ashley Elementary Chess Program - Frisco ISD</td>
<td>Mon</td>
<td>08-31-2015</td>
<td>Y</td>
<td>2015-09-14</td>
<td>2015-12-12</td>
<td><input type="checkbox" name="presentdays[]"></td>
<td><input type="checkbox" name="latedays[]"></td>
<td>15</td><td><input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;"></td>
<td><input type="text" name="item_comment" style="width:80px;"></td>
</tr>
<tr>
<td>Fall 2015 - Bledsoe Elementary Chess Program - Frisco ISD</td>
<td>Wed</td>
<td>09-02-2015</td>
<td>Y</td>
<td>2015-09-16</td>
<td>2015-12-12</td>
<td><input type="checkbox" name="presentdays[]"></td>
<td><input type="checkbox" name="latedays[]"></td>
<td>15</td>
<td><input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;"></td>
<td><input type="text" name="item_comment" style="width:80px;"></td>
</tr>
<tr>
<td>Fall 2015 - Anderson Elementary Chess Program - Frisco ISD</td>
<td>Mon</td>
<td>08-31-2015</td>
<td>Y</td>
<td>2015-09-21</td>
<td>2015-12-12</td>
<td><input type="checkbox" name="presentdays[]"></td>
<td><input type="checkbox" name="latedays[]"></td>
<td>5</td>
<td><input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;"></td>
<td><input type="text" name="item_comment" style="width:80px;"></td>
</tr>
</tbody>
</table>
</div>
<div class="timecardstepcontainer">
<table class="widefat" style="width:100%" id="stepthreetable">
<thead>
<tr>
<th>Day</th>
<th>Classes $</th>
<th>Late $</th>
<th>Expense</th>
<th>Admin</th>
<th>Approved Adjustment</th>
<th>Approved Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="number_of_classes" value="4" style="width:50px;" readonly=""></td>
<td><input type="text" name="totalclasses" value="40" readonly=""></td>
<td><input type="text" value="" id="latecharges" readonly=""></td>
<td><input type="text" name="totalexpense" value="40" readonly=""></td>
<td><input type="text" name="totaladminrate" value="0" readonly=""></td>
<td><input type="text" name="approved_adjustment" id="approved_adjustment" style="width:50px;"></td>
<td><textarea name="approver_comment"></textarea></td>
</tr>
</tbody>
</table>
</div>
<div class="timecardstepcontainer">
<table class="widefat" style="width:100%">
<tbody><tr>
<td>Total</td>
<td><input type="text" name="finaltotal" id="finaltotal" readonly=""></td>
<td>Approved Total</td>
<td><input type="text" name="approvedtotal" id="approvedtotal" readonly=""></td>
</tr>
</tbody></table>
</div>
<input type="hidden" name="alldata" id="alldata" value="16,15,17,14">
<div class="timecardstepcontainer">
<table>
<tbody><tr>
<td><input type="submit" name="addtimecard" value="Save" class="button button-primary button-large"></td>
</tr>
</tbody></table>
</div>
</form>
Javascript
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("select[name='txtuser']").change(function(){
jQuery.ajax({
url:ajaxurl,
type:'post',
data:{action:'timecardapp_manage_timecard_stepone',user_id: jQuery("#txtuser").val()},
success: function(response){
var data=JSON.parse(response);
jQuery("input[name='txtemail2']").val(data.email2);
jQuery("input[name='txtclassrate']").val(data.class_rate);
jQuery("input[name='txtadminrate']").val(data.admin_rate);
}
});
});
jQuery("#txtweek").change(function(){
if(jQuery("select[name='txtuser'] option:selected").text()=='--select--'){
alert("Please select a user first to proceed");
return false;
} else {
jQuery.ajax({
url:ajaxurl,
type:'post',
data:{action:'timecardapp_manage_timecard_stepone',user_id: jQuery("#txtuser").val()},
success: function(response){
var data=JSON.parse(response);
var alldata = new Array();
var currentweek = jQuery("#txtweek option:selected").text();
var days_date = new Array();
function pad(str) {
return ("0"+str).slice(-2);
}
function getNextDay(str) {
var parts = str.split("-");
var mon_day = new Date(parts[2], parts[0] - 1, parseInt(parts[1], 10) + 0, 12, 0, 0, 0);
var tue_day = new Date(parts[2], parts[0] - 1, parseInt(parts[1], 10) + 1, 12, 0, 0, 0);
var wed_day = new Date(parts[2], parts[0] - 1, parseInt(parts[1], 10) + 2, 12, 0, 0, 0);
var thu_day = new Date(parts[2], parts[0] - 1, parseInt(parts[1], 10) + 3, 12, 0, 0, 0);
var fri_day = new Date(parts[2], parts[0] - 1, parseInt(parts[1], 10) + 4, 12, 0, 0, 0);
days_date[0] = ""+pad(mon_day.getMonth()+1)+"-"+ pad(mon_day.getDate())+"-"+mon_day.getFullYear();
days_date[1] = ""+pad(tue_day.getMonth()+1)+"-"+ pad(tue_day.getDate())+"-"+tue_day.getFullYear();
days_date[2] = ""+pad(wed_day.getMonth()+1)+"-"+ pad(wed_day.getDate())+"-"+wed_day.getFullYear();
days_date[3] = ""+pad(thu_day.getMonth()+1)+"-"+ pad(thu_day.getDate())+"-"+thu_day.getFullYear();
days_date[4] = ""+pad(fri_day.getMonth()+1)+"-"+ pad(fri_day.getDate())+"-"+fri_day.getFullYear();
}
var currentweek = jQuery("#txtweek option:selected").text(), // no values available
next_day = new Date(); // or some other default
if (currentweek && currentweek.indexOf("--") == -1) { // not the first
next_day=getNextDay(currentweek);
}
var trHTML = '';
var number_of_classes = 0;
var totalexpense = 0;
var totaladminhours = 0;
jQuery.each(data.final_data, function (i, item) {
if(item.event_title == 'Admin'){
//Monday
trHTML += '<tr>';
trHTML += '<td>'+item.event_title+'</td>';
trHTML += '<td>Mon</td>';
trHTML += '<td>'+days_date[0]+'</td>';
trHTML += '<td>Y</td>';
trHTML += '<td>'+item.start_date+'</td>';
trHTML += '<td>'+item.end_date+'</td>';
trHTML += '<td> </td>';
trHTML += '<td> </td>';
trHTML += '<td>'+item.expense_allowance_value+'</td>';
trHTML += '<td><input type="text" name="admin_hours[]" class="adminhours" value="'+item.hours_allowed+'" style="width:50px;" /></td>';
trHTML += '<td><input type="text" name="item_comment" style="width:80px;" /></td>';
trHTML += '</tr>';
//Tuesday
trHTML += '<tr>';
trHTML += '<td>'+item.event_title+'</td>';
trHTML += '<td>Tue</td>';
trHTML += '<td>'+days_date[1]+'</td>';
trHTML += '<td>Y</td>';
trHTML += '<td>'+item.start_date+'</td>';
trHTML += '<td>'+item.end_date+'</td>';
trHTML += '<td> </td>';
trHTML += '<td> </td>';
trHTML += '<td>'+item.expense_allowance_value+'</td>';
trHTML += '<td><input type="text" name="admin_hours[]" class="adminhours" value="'+item.hours_allowed+'" style="width:50px;" /></td>';
trHTML += '<td><input type="text" name="item_comment" style="width:80px;" /></td>';
trHTML += '</tr>';
//Wednesday
trHTML += '<tr>';
trHTML += '<td>'+item.event_title+'</td>';
trHTML += '<td>Wed</td>';
trHTML += '<td>'+days_date[2]+'</td>';
trHTML += '<td>Y</td>';
trHTML += '<td>'+item.start_date+'</td>';
trHTML += '<td>'+item.end_date+'</td>';
trHTML += '<td> </td>';
trHTML += '<td> </td>';
trHTML += '<td>'+item.expense_allowance_value+'</td>';
trHTML += '<td><input type="text" name="admin_hours[]" class="adminhours" value="'+item.hours_allowed+'" style="width:50px;" /></td>';
trHTML += '<td><input type="text" name="item_comment" style="width:80px;" /></td>';
trHTML += '</tr>';
//Thursday
trHTML += '<tr>';
trHTML += '<td>'+item.event_title+'</td>';
trHTML += '<td>Thu</td>';
trHTML += '<td>'+days_date[3]+'</td>';
trHTML += '<td>Y</td>';
trHTML += '<td>'+item.start_date+'</td>';
trHTML += '<td>'+item.end_date+'</td>';
trHTML += '<td> </td>';
trHTML += '<td> </td>';
trHTML += '<td>'+item.expense_allowance_value+'</td>';
trHTML += '<td><input type="text" name="admin_hours[]" class="adminhours" value="'+item.hours_allowed+'" style="width:50px;" /></td>';
trHTML += '<td><input type="text" name="item_comment" style="width:80px;" /></td>';
trHTML += '</tr>';
//Friday
trHTML += '<tr>';
trHTML += '<td>'+item.event_title+'</td>';
trHTML += '<td>Fri</td>';
trHTML += '<td>'+days_date[4]+'</td>';
trHTML += '<td>Y</td>';
trHTML += '<td>'+item.start_date+'</td>';
trHTML += '<td>'+item.end_date+'</td>';
trHTML += '<td> </td>';
trHTML += '<td> </td>';
trHTML += '<td>'+item.expense_allowance_value+'</td>';
trHTML += '<td><input type="text" name="admin_hours[]" class="adminhours" value="'+item.hours_allowed+'" style="width:50px;" /></td>';
trHTML += '<td><input type="text" name="item_comment" style="width:80px;" /></td>';
trHTML += '</tr>';
alldata.push(item.session_id);
} else {
trHTML += '<tr>';
trHTML += '<td>'+item.event_title+'</td>';
trHTML += '<td>'+item.day_of_week+'</td>';
if(item.day_of_week=='Mon'){
trHTML += '<td>'+days_date[0]+'</td>';
}
if(item.day_of_week=='Tue'){
trHTML += '<td>'+days_date[1]+'</td>';
}
if(item.day_of_week=='Wed'){
trHTML += '<td>'+days_date[2]+'</td>';
}
if(item.day_of_week=='Thu'){
trHTML += '<td>'+days_date[3]+'</td>';
}
if(item.day_of_week=='Fri'){
trHTML += '<td>'+days_date[4]+'</td>';
}
trHTML += '<td>Y</td>';
trHTML += '<td>'+item.start_date+'</td>';
trHTML += '<td>'+item.end_date+'</td>';
trHTML += '<td><input type="checkbox" name="presentdays[]" /></td>';
trHTML += '<td><input type="checkbox" name="latedays[]" /></td>';
trHTML += '<td>'+item.expense_allowance_value+'</td>';
trHTML += '<td><input type="text" name="admin_hours[]" class="adminhours" value="'+item.hours_allowed+'" style="width:50px;" /></td>';
trHTML += '<td><input type="text" name="item_comment" style="width:80px;" /></td>';
trHTML += '</tr>';
number_of_classes++;
totalexpense = +totalexpense + +item.expense_allowance_value;
totaladminhours = totaladminhours + item.hours_allowed;
}
alldata.push(item.session_id);
});
jQuery('#steptwotable').find('tbody').empty();
jQuery('#steptwotable').find('tbody').append(trHTML);
var totalclasses = number_of_classes * jQuery("input[name='txtclassrate']").val();
var totaladminrate = totaladminhours * jQuery("input[name='txtadminrate']").val();
var trHTML2 = '';
trHTML2 += '<tr>';
trHTML2 += '<td><input type="text" name="number_of_classes" value="'+number_of_classes+'" style="width:50px;" readonly /></td>';
trHTML2 += '<td><input type="text" name="totalclasses" value="'+totalclasses+'" readonly /></td>';
trHTML2 += '<td><input type="text" value="" id="latecharges" readonly /></td>';
trHTML2 += '<td><input type="text" name="totalexpense" value="'+totalexpense+'" readonly /></td>';
trHTML2 += '<td><input type="text" name="totaladminrate" value="'+totaladminrate+'" readonly /></td>';
trHTML2 += '<td><input type="text" name="approved_adjustment" id="approved_adjustment" style="width:50px;" /></td>';
trHTML2 += '<td><textarea name="approver_comment"></textarea></td>';
trHTML2 += '</tr>';
jQuery('#stepthreetable').find('tbody').empty();
jQuery('#stepthreetable').find('tbody').append(trHTML2);
jQuery("#alldata").val(alldata);
var the_final_total = +totalclasses + +totalexpense - jQuery("#latecharges").val() + +totaladminrate;
jQuery("#finaltotal").val(the_final_total);
}
});
}
});
});
jQuery(document).on("keyup change", ".adminhours", function() {
var latecharge;
var admincharge;
var adminhours=jQuery(".adminhours");
if(jQuery("#latecharges").val().length > 0){
latecharge=jQuery("#latecharges").val();
} else {
latecharge=0;
}
if(jQuery("input[name='totaladminrate']").val().length > 0){
admincharge=jQuery("input[name='totaladminrate']").val();
} else {
admincharge=0;
}
alert(adminhours.length);
if(jQuery(".adminhours").val().length > 0){
for(var i = 0; i < adminhours.length; i++){
adminhours= +adminhours+ + +jQuery(adminhours[i]).val();
}
} else {
adminhours=0;
}
var thefinaltotal = +admincharge + +jQuery("input[name='totalclasses']").val() + +jQuery("input[name='totalexpense']").val() - latecharge;
jQuery("input[name='totaladminrate']").val(adminhours*jQuery("input[name='txtadminrate']").val());
jQuery("input[name='finaltotal']").val(thefinaltotal);
});
</script>
A: The logic to get all elements with class .adminhours should not check with val in selector if(jQuery(".adminhours").val().length > 0). I have updated your code below :
var totalAdminhours = 0;
if(jQuery(".adminhours").length > 0){
jQuery(".adminhours").each(function () {
totalAdminhours += totalAdminhours + jQuery(this).val();
});
} else {
totalAdminhours = 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33396942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Overloading == operator A derives directly from Object class and neither A or Object overload == operator, so why doesn't next code cause an error:
class Program
{
static void Main(string[] args)
{
A a1 = new A();
A a2 = new A();
if (a1 == a2) ... ;
}
}
class A { }
thanx
A:
A derives directly from Object class and neither A or Object overload == operator, so why doesn't next code cause an error?
As with your other question, you seem to have some strange belief that whether an overloaded operator exists has any bearing on whether an operator can be meaningfully chosen. It does not.
Again, to resolve this situation overload resolution first attempts to determine if there is a user-defined operator defined on either of the operands. As you note, there is not.
Overload resolution then falls back on the built-in operators. As I mentioned in your other question, the built-in operators are the equality operators on int, uint, long, ulong, bool, char, float, double, decimal, object, string, all delegate types and all enum types, plus the lifted-to-nullable versions of all the value types.
Given those operators we must now determine the applicable ones. There is no implicit conversion from "A" to any of the value types, to any of the nullable value types, to string, or to any delegate type.
The only remaining applicable candidate is object.
If overload resolution chooses the equality operator that compares two objects, additional constraints must be met. In particular, both operands must either be null or a reference type, or a type parameter not constrained to be a value type. That constraint is met. Also, if the two sides have types then the operand types must have some sort of compatibility relationship; you can't do "myString == myException" because there is no relationship between string and Exception. There is a relationship between "A" and "A", namely, they are identical.
Therefore the reference equality operator is chosen, and the == means "compare these two object expressions by reference".
I am mystified as to why you believe having a user-defined == operator has anything to do with this, either in this question or your other question. The absence of such a method does not prevent the compiler from generating whatever code it likes for this expression. Can you explain?
A: Because by default, the == operator compares the references (memory locations) of the objects a1 and a2. And because they're different instances of class A, the expression a1 == a2 always evaluates to false in your example.
A: Objects have a default implementation of the == operator that checks if they refer to the same object (reference comparison). So there's no reason for it to be an error. The operator does have a meaning.
A: Because Object has a default implementation comparing references.
A: The base's == operator is called that why its not giving any error.
A:
By default, the operator == tests for
reference equality by determining if
two references indicate the same
object, so reference types do not need
to implement operator == in order to
gain this functionality.
From: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
The important bit concerning your question being:
reference types do not need to
implement operator == in order to gain
this functionality
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5915829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Are the UTC datetime formats acknowledged by W3C identical to those of ISO 8601? The W3C Date and Time note suggests that date and time 'official' formats are identical to, or a subset of ISO 8601. The note says "This document defines a profile of ISO 8601", and also "To reduce the scope for error and the complexity of software, it is useful to restrict the supported formats to a small number."
Is it safe to assume, that all W3C datetimes (such as those used in server logs) are therefore compatible with ISO 8601?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55899399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I change the Universal Login logo on auth0 dashboard? I'm currently stuck on the auth0 Universal Login page.
I want to change the logo by given an url but it keep telling me that the url is not valid.
I don't know what to do anymore because the exact same url is valid for the Application logo.
Screenshot of the error
A: it seems that you might get that error if you have an whitespace before or after the link too. Can you check whether or not you have that white space in there? maybe that's it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67057012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Positive lookahead assertion and .* sign in python I have the following regular expression:
passw = re.compile(r'^(?=.*\d)(?=.*[A-Z])(?=.*[\$|\?\!])[A-Za-z\d$!&]{8}$')
which I can interpret as string of length 8, which must contain at least one number, one big letter and one of characters($?!). And also consists only of numbers, letters and $?!.
?= - this symbol is known as lookahead assertion: For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
But how can we interpret .* sign? What does it mean in regex?
Can we avoid it in this situation?
A: In fact .* means zero or more occurrences of any character, and when it follows with a special pattern in a lookahead it means that the regex engine will assert that the regex can be matched. And when you use .* before your pattern you are telling the regex engine to match my pattern that precede by zero or more characters this means you want to be sure that your pattern is present in your string (from leading to trailing).
Here is an example with diagram:
(?=.*\d)[a-z]+
Debuggex Demo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38098915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Google Maps kml files If I use an embeded google map in my website, will the data contained in an kml displayed be publicly viewable?
Will it be possible for the user to access just the data displayed (i.e., not the user interface) or would I have to provide that separately?
A: If you load your KML through the API, with GGeoXml(), (V2), or KmlLayer(), (V3), then your data needs to be in a public server because it is parsed by Google's servers and they need to be able to get to it. If you load it with a third party extension then you can keep it private.
Third party extensions that can load and parse KML data are EGeoXml() by Mike Williams
http://econym.org.uk/gmap/extensions.htm#EGeoXml
and GeoXml() by Lance Dyas
http://www.dyasdesigns.com/geoxml/
but I believe that both of those are only available for the API V2 for now.
A: I just upgraded my Google Maps JavaScript API Application from v2 to v3, following these instructions.
My v2 application was using the EGeoXml extension referred to by @Marcelo in the accepted answer to locally parse KML data.
A substitution of geoxml3 in its place, as suggested by @geocodezip (a contributor to the project) in a comment, functioned immediately in my v3 application.
A: No, the data will not be public. I'm not sure about your other question though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3435566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: remove duplicate rows where one column equals a different column I have a df like this:
d = {'label':['A','B','G','O']
,'label2':['C','D','O','Z']}
df = pd.DataFrame(d)
print(df)
label label2
0 A C
1 B D
2 G O
3 O Z
What i want to do is to get rid of the duplicate rows that have label = label2 (keep only the first)
So i want to get something like this from the above df:
label label2
0 A C
1 B D
2 G O
I do this below, but it doesn't do the trick
df[~df[['label', 'label2']].apply(frozenset, axis=1).duplicated()]
Any idea on how to tackle this?
A: Try this, using .isin method for Seires:
mask = ~df['label'].isin(df['label2'])
df_output = df[mask]
print(df_output)
Output:
label label2
0 A C
1 B D
2 G O
A: You can use drop to remove duplicate label between 2 columns:
df.drop(df[df['label'].isin(df['label2'])].index, inplace=True)
print(df)
# Output:
label label2
0 A C
1 B D
2 G O
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69556208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: .Net Garbage Collection on LoH When the memory dump is being analyzed, it shows that this particular string variable which is holding the xml content is causing memory leak. I read on some of the articles that LoH goes to Gen 2. So,
*
*Will garbage collector gets invoked if Gen 0 and Gen 1 is not under pressure and Gen 2 is under pressure due to LoH ?
*Will it go to Gen 2 when it has released Gen 0 or Gen 1 memory ?
*If so what’s the better way to handle this ?
A: *
*No, it will not
*Only if there's enough memory pressure
However, if your application is doing allocations, it's pretty unlikely the string will survive for too long. And if there's not enough memory pressure, the GC has little reason to release the memory.
Do make sure the string is not referenced anymore, though. Count the references, check that it's not interned.
You can force a garbage collection, but it's great way to damage GC performance. It might be the best solution for your case if your application does the odd "allocate a huge string and then forget it" operation, and you care about memory available to the rest of the system (there's no benefit to your application). There's no point in trying that if you're doing a lot of allocations anyway, though - in that case, look for memory leaks on your side. WinDbg can help.
A: 1. Will garbage collector gets invoked if Gen 0 and Gen 1 is not under pressure ?
If there is enough space in Generation0 and Generation2, then Garbage Collector will not be invoked.
If there is enough space in Generation0 and Generation2, then it means that that there is enough space to create new objects and there is no reason to run Garabage Collection.
2. Will it go to Gen 2 when it has released Gen 0 or Gen 1 memory ?
If the object is survived after Garbage Collection in Generation1 and in the Generation1, then the object will be moved to Generation2.
3. If so what’s the better way to handle this ?
*
*To destroy an object from heap, you should just delete references of this string. Your string variable which has xml values should not be static to be garbage collected.(read more about roots)
*Try to use compact GCSettings.LargeObjectHeapCompactionMode:
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
This will compact the Large Object Heap when the next Full Garbage Collection is executed. With GC.Collect() call after the settings been applied, the GC gets compacted immediately.
*
*Try to use WeakReference:
WeakReference w = new WeakReference(MyLargeObject);
MyLargeObject = w.Target as MyLargeClass;
MyLargeClass MyLargeObject;
if ( (w == null) || ( (MyLargeObject=w.Target as MyLargeClass) == null) )
{
MyLargeObject = new MyLargeClass();
w = new WeakReference(MyLargeObject);
}
This article gives is very useful to you about Garbage Collection and the article is written in plain English.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36124936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Drawable Rotating around its Top Android I am getting strange results with the following code:
Animation a = new RotateAnimation(0.0f, 360.0f,
Animation.ZORDER_TOP, 0.5f, Animation.ZORDER_TOP,
0.5f);
a.setRepeatCount(-1);
a.setDuration(1000);
img.startAnimation(a);
Whats the right way to specify the axis point (top of the drawable)?
A: Try this one it will work "rotationY" means it will rotate Y Direction, "rotationX" means it will rotate X Direction
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, 360f);
animation.setDuration(600);
animation.setRepeatCount(ObjectAnimator.INFINITE);
animation.setInterpolator(new AccelerateDecelerateInterpolator());
animation.start();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43847810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: ^M characters when using Tramp (on Windows) to connect to Ubuntu Server I've set up Tramp on Emacs on my Windows 7 box (64 bit). For this test, this is the only thing in my emacs-config:
(setq tramp-default-method "plink")
Then I connect to my Ubuntu Server 9.10 running in a VM on my local network.
Connection goes fine, i can use dired to browse folders and open files. Yay!
However, git status shows up as:
Git:master^M
An when i open speedbar all folders and files ends with ^M, ie:
<+> conf/^M
Does anyone know how to prevent this line-ending collision from occurring?
A: don't know if this is it but I had a similar issue that I fixed with this.
(setq default-buffer-file-coding-system 'utf-8-unix)
there's a few people who have asked how to get tramp working on windows(I actually gave up) so if you felt like documenting how you did it, there would likely be legions of thankful windows users out there.
A: (prefer-coding-system 'utf-8) did the trick!
Thanks Tom for the clue... Getting Tramp to work on my windows machine was no trouble at all. I'm using this version of Emacs:
GNU Emacs 23.1.50.1 (i386-mingw-nt6.1.7600)
of 2009-10-15 on LENNART-69DE564
With this in my init.el:
(setq tramp-default-method "plink")
(prefer-coding-system 'utf-8)
Putty directory with plink-app is in my system path.
Then: C-X C-F /[email protected]: and Tab brings up password prompt then autocompletion on servers-files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2567600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hiding filter input box instead of disabling + tablesorter 2 I need a little assistance. I am using a fork of JQuery TableSorter 2 (http://mottie.github.com/tablesorter/) to work and filter my tables. If i dont want certain columns to be used as filter, I simply need to add "filter-false" as a class to the selected column header.
My main question is whether there is a way I can actually hide the filter boxes on the selected columns instead of just disabling them...
Thanks
Emmanuel
A: Here is the default css:
/* optional disabled input styling */
table.tablesorter thead tr.tablesorter-filter-row input.disabled {
opacity: 0.5;
filter: alpha(opacity=50);
}
As seen, a disabled class is applied to those disabled filters, so you can use css to either apply display:none or visibility:hidden to it:
tr.tablesorter-filter-row input.disabled {
display: none;
}
A: I recommend simply sticking with:
/* optional disabled input styling */
table.tablesorter thead tr.tablesorter-filter-row input.disabled {
opacity: 0.0;
filter: alpha(opacity=0);
}
As having that one hidden, removes also the table's inner border thus creating unpleasant visual effect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10387792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AlertDialog not showing when not onCreate I have an Activity that have to show an AlertDialog with a ListView for the user to choose one of the options. When I put the code of the AlertDialog in the onCreate method, it works. But when somewhere else, it doesn't. There are no errors on the console.
Here is where it's called (in the Activity):
@Override
public void onStateChanged(IntegratorState state) {
switch (state.getState()) {
case AWAITING_MENU_OPTION:
IntegratorHelper.showOptionsMenu(state, SitefMenuActivity.this).show();
break;
default:
Toast.makeText(getApplicationContext(), state.getState().name(),
Toast.LENGTH_LONG).show();
}
}
And here is where I create the Dialog (in another class):
public static AlertDialog showOptionsMenu(IntegratorState state, Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(state.getGatewayMessageExtra());
String[] strings;
strings = state.getGatewayMessage().split(";");
final List<String> options = Arrays.asList(strings);
builder.setAdapter(new MenuSaleAdapter(context,
android.R.layout.simple_list_item_1, options),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == options.size()-1) {
// Do a thing
} else {
// Do other thing
}
}
});
return builder.create();
}
private static class MenuSaleAdapter extends ArrayAdapter<String> {
public MenuSaleAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView,
parent);
view.setTextColor(Color.BLACK);
return view;
}
}
I tried to put all the code in the same Activity, but it still doesn't work. The application doesn't freeze or anything, it just don't show the Dialog. Any ideas? Thanks
A: Try changing first part to:
@Override
public void onStateChanged(IntegratorState state) {
switch (state.getState()) {
case AWAITING_MENU_OPTION:
IntegratorHelper.showOptionsMenu(state, SitefMenuActivity.this);
break;
default:
Toast.makeText(getApplicationContext(), state.getState().name(),
Toast.LENGTH_LONG).show();
}
}
and second part:
public static void showOptionsMenu(IntegratorState state, Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(state.getGatewayMessageExtra());
String[] strings;
strings = state.getGatewayMessage().split(";");
final List<String> options = Arrays.asList(strings);
builder.setAdapter(new MenuSaleAdapter(activity,
android.R.layout.simple_list_item_1, options),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == options.size()-1) {
// Do a thing
} else {
// Do other thing
}
}
});
builder.create().show();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31214239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use cronjobs to run a python script on a webserver thats on the cloud? I am currently trying to create a Discord bot (with Discord.py) that is able to search through Reddit every few hours to see if there is anything new that has been posted in a specific subreddit. Currently, I have a way to scrape Reddit for this information but it is activated through a Discord command. Ideally, I would like for the script to run automatically after a certain time interval instead of being activated through a command.
I am using asyncpraw and discord.py for my code, so it is all in Python.
Additionally, I am using Flask to create a webserver for the bot, and then using Repl.it to host the server for free. I also use cron-job.org to submit a request every five minutes to the webserver in order to keep it running.
I have my files set up as main.py, which contains all information for the Discord bot, commands, and code that activates when the command is entered into the chat, and then a keep_alive.py file that contains the starting of the web server and the thread (I'm not super knowledgeable about Flask so I'm not super clear on what everything does). At the end of main.py, before I enter the discord bot's token, I call a function from keep_alive.py.
So far, I have tried to use cron-job.org to set up a cronjob, but it hasn't worked thus far as I am not super clear on how to go about it. I have also tried using schedule.py or sched.py, but neither has worked.
To my understanding, I need to use a cronjob for the functionality that I want, but I would love some guidance on actually implementing it, especially as far as the organization of files goes and where to call functions for them to activate. Additionally, I would like to find out if there is a way to use cronjobs within Repl.it, because I don't think you can use them from within their console.
Please let me know if you need any more information or code or anything else!
I appreciate any and all help! Thanks!
A: I don't know if this helps you but the way I was able to automate python scripts on my web server was by using a windows 2016 server.
Then creating a .bat file that would run the script like this. Just make sure your file location is set correctly.
python C:\inetpub\wwwroot\top_10_week.py %*
Then use windows task scheduler to schedule the script to run after a certain time, I set mine to 3 hours but I'm sure you can do it every 5 minutes.
https://www.windowscentral.com/how-create-automated-task-using-task-scheduler-windows-10
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68566641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Incorrect prettier file pattern I'm using prettier to format an angular project but I'm having a little trouble figuring out the correct file pattern.
Using prettier --check src/**/* includes *.pdf files which causes errors.
Using prettier --check src/**/*.ts ignores *.component.ts files.
I could use prettier --check src/**/*(.component.ts|.service.ts|...) an so on but this pattern would be gigantic. I also have to do this for .html en .scss
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71952866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Missing Method when include require 'test_helper' i'm trying to test using minitest but when running this file with
bin/rails test test/controllers/api/v1/blogs_api_controller_test.rb
But it gives this error
.rvm/gems/ruby-2.3.1/gems/railties-5.1.1/lib/rails/railtie/configuration.rb:95:in
method_missing': undefined methodweb_console' for
(NoMethodError) Did you mean? console
require 'test_helper'
class BlogsApiControllerTest < ActiveSupport::TestCase
test 'Get all Blogs' do
assert false
end
end
Rails version 5.1.1 Ruby 2.3.1
Gem File
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
# Use Puma as the app server
gem 'puma', '~> 3.8.2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 3.2.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 4.1.1'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.6'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
gem 'kaminari', '~> 0.17.0'
gem 'bootsy', '~> 2.4'
gem 'searchkick', '~> 3.0.2'
gem 'devise', '~> 4.3.0'
gem 'omniauth-facebook', '~> 3.0.0'
gem 'omniauth-google-oauth2', '~> 0.4.1'
gem 'cancancan', '~> 1.15.0'
gem 'paperclip', '~> 5.0.0'
gem 'sitemap_generator', '~> 5.1.0'
gem 'jwt'
gem 'simple_command'
gem 'rack-cors', require: 'rack/cors'
# For admin panel ----------------
gem 'activeadmin', '~> 1.0.0'
# Below are for rails 5
# gem 'inherited_resources', github: 'activeadmin/inherited_resources'
# gem 'ransack', github: 'activerecord-hackery/ransack'
gem 'draper', '~> 3.0.1'
# ---------------------
group :development, :test do
gem 'pry'
# Use mysql as the database for Active Record
gem 'mysql2', '~> 0.4.6'
end
group :development do
gem 'wdm', '>= 0.1.0' if Gem.win_platform?
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console'
gem 'listen', '~> 3.0.8'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.1'
end
group :production do
gem 'pg', '~> 0.18.4'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
A: Please put gem 'web-console' into your Gemfile's test section. You can change the following lines
group :development, :test do
gem 'pry'
# Use mysql as the database for Active Record
gem 'mysql2', '~> 0.4.6'
end
with following
group :development, :test do
gem 'pry'
gem 'web-console'
# Use mysql as the database for Active Record
gem 'mysql2', '~> 0.4.6'
end
And remove web-console from following lines
group :development do
gem 'wdm', '>= 0.1.0' if Gem.win_platform?
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console' # remove this
Now run following command to update bundles
bundle install
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55016342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set color of alertdialog I display an alertdialog in my app but the left and right side of the title shows a different color. I have set my own background color in thems.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="ACCAppTheme" parent="android:Theme.Holo">
<!-- Change default text colour from dark grey to black -->
<!-- <item name="android:windowBackground">@drawable/ic_logo</item> -->
<item name="android:background">#140051</item>
<item name="android:textColor">#ffffff</item>
<item name="android:textColorHint">#c0c0c0</item>
<item name="android:actionBarStyle">@style/AppTheme.ActionBar</item>
</style>
<!-- <style name="OverFlow" parent="@android:style/Widget.Holo.ActionButton.Overflow">
<item name="android:textSize">18sp</item>
</style> -->
<style name="AppTheme.ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">#140051</item>
<item name="android:height">50dp</item>
<item name="android:titleTextStyle">@style/AppTheme.ActionBar.Text</item>
<item name="android:textColor">@android:color/white</item>
<item name="android:showDividers">beginning</item>
</style>
<style name="AppTheme.ActionBar.Text" parent="@android:style/TextAppearance">
<item name="android:textAllCaps">false</item>
<item name="android:textColor">@android:color/white</item>
</style>
</resources>
but what appears is like this
here's the code that creates the alert dialog
public class AppMessages {
public static final int MESSAGE_INFO = 1;
public static final int MESSAGE_CRITICAL = 2;
public interface AlertButtonClickListener {
public abstract void onButtonClicked(boolean value);
}
public static void showMessage(Context context,
String message,
String title,
int messageType,
final AlertButtonClickListener target) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setTitle(title)
.setIcon(R.drawable.ic_dialog_information)
.setCancelable(false)
.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (target != null) {
target.onButtonClicked(true);
}
}
});
switch (messageType) {
case AppMessages.MESSAGE_CRITICAL:
builder.setIcon(R.drawable.ic_dialog_exclamation);
break;
case AppMessages.MESSAGE_INFO:
builder.setIcon(R.drawable.ic_dialog_information);
break;
}
builder.show();
}
public static void yesNo(final Context mContext,
final String title,
final String msg,
final String positiveBtnCaption,
final String negativeBtnCaption,
final boolean isCancelable,
final AlertButtonClickListener target) {
((Activity) mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(title)
.setMessage(msg)
.setIcon(R.drawable.ic_dialog_question)
.setCancelable(false)
.setPositiveButton(positiveBtnCaption,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
target.onButtonClicked(true);
}
})
.setNegativeButton(negativeBtnCaption,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
target.onButtonClicked(false);
}
});
AlertDialog alert = builder.create();
alert.setCancelable(isCancelable);
alert.show();
if (isCancelable) {
alert.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
target.onButtonClicked(false);
}
});
}
}
});
}
}
here's how I call the it
AppMessages.showMessage(thisActivity,
"New update found. Click Ok to download it now.",
"New Update Found",
1,
new AppMessages.AlertButtonClickListener() {
@Override
public void onButtonClicked(boolean value) {
APKDownloader.downloadAPK(thisActivity);
}
});
A: Try this,
Customize AlertDialog Theme
Create a new Android XML resource file under res/values/
You'll want to create a new style that inherits from the default alertdialog theme:
<style name="CustomDialogTheme" parent="@android:style/Theme.Dialog">
<item name="android:bottomBright">@color/white</item>
<item name="android:bottomDark">@color/white</item>
<item name="android:bottomMedium">@color/white</item>
<item name="android:centerBright">@color/white</item>
<item name="android:centerDark">@color/white</item>
<item name="android:centerMedium">@color/white</item>
<item name="android:fullBright">@color/orange</item>
<item name="android:fullDark">@color/orange</item>
<item name="android:topBright">@color/blue</item>
<item name="android:topDark">@color/blue</item>
</style>
You can specify either colors or drawable for each section of the AlertDialog.
An AlertDialog will build it's display by combining 3 drawables/colors (top, center, bottom) or a single drawable/color (full).
In a theme of your own override the android:alertDialogStyle style (you can do this within the same XML file):
@style/CustomDialogTheme
Override your application's theme in the AndroidManifest within the application tag:
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@style/MyTheme">
Now that you've defined your application's theme, any attributes overridden in your theme will resonate throughout your app.
For example if you also wanted to change the color of your application's title bar:
You would first define a new style that inherits from the default attribute
@color/blue
and just add the new overridden item to your theme:
<style name="MyTheme">
<item name="android:windowTitleBackgroundStyle">@style/MyBackground</item>
<item name="android:alertDialogStyle">@style/CustomDialogTheme</item>
</style>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33337992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Embedding tab bar to top of screen iphone I want to design a page with tab bar on top of it.In some articles of this site.(i missed urls) i found that this is not a common way and the question gets some down rate.
The question is this: whethere having a design like this may cause that apple not approve the application on his store?
A: Even if it doesn't make Apple reject your app, think of the users not being used to the tab bar being at the top and how that is going to affect how well the app does in the Store.
Every platform has its own design patterns and there is a reason for that. If you stick to them there is a higher chance that the first-time users have an easier time using your app, which results in a higher chance that they keep using it. If they don't know how to use it or find it hard, they will move to another one.
Take a look at the Human Interface Guidelines and apply them. It will do good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15051173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Terraform: aws_lb_listener with multiple ports I am building an ALB on AWS using Terraform. The ALB should forward multiple ports to the instances, but the documentation specifies:
port - (Required) The port on which the load balancer is listening.
Do I have to add a separate ALB listener for each port, or is there a way to specify multiple ports per listener?
A: An ALB listener can only listen on a single port. You must define a listener for each port you want the load balancer to listen on. This isn't a limitation of Terraform, it's the way AWS load balancers are designed.
Additionally, since an ALB can only handle HTTP and HTTPS requests you usually don't setup more than two listeners on an ALB (ports 80 and 443), and the listener configuration would of necessity be different since one would have an SSL certificate configuration and one would not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47032187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use multiple checkbox selection while parsing JSON I'm trying to select multiple checkboxes in a custom listview while parsing JSON. Now I am able select a single checkbox. How can I select multiple checkbox values?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32423224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python - regex putting repeating patterns in a single group I'm trying to parse a string in regex and am 99% there.
my test string is
1
1234 1111 5555 88945
172.255.255.255 from 172.255.255.255 (1.1.1.1)
Origin IGP, localpref 300, valid, external, best
rx pathid: 0, tx pathid: 0x0
my current regex pattern is:
(?P<as_path>(\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>\S+,\s{0,4})
im using regex101 to test and have a link to the test here https://regex101.com/r/iGM8ye/1
So currently i have a group2 I don't want this group, could someone tell me why im getting this group and how to remove it?
and the second is, in the attributes I want to match the words, "valid, external, best" currently my pattern only matches "valid," I thought adding the repeat of within the group would of matched all three of those but it hasn't.
How would I achieve matching the repeat of "string, string, string," (string comma space) into one group?
Thanks
EDIT
Desired output
as_path : 1234 1111 5555 88945
peer_addr : 172.255.255.255
peer_rid : 1.1.1.1
local_pref : 300
attribs : valid, external, best
attiribs may also just be valid, external, or just external, or another entry in the format (stringcommaspace)
A: Try Regex: (?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>[\S]+,(?: [\S]+,?)*){0,4}
Demo
Regex in the question had a capturing group (Group 2) for (\d{4,10}\s). it is changed to a non capturing group now (?:\d{4,10}\s)
A: See regex in use here.
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}(?:\.\d{0,3}){3}).*\((?P<peer_rid>\d{0,3}(?:\.\d{0,3}){3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2})
*
*You were getting group 2 because your as_path group contained a group. I changed that to a non-capturing group.
*I changed attribs to \S+(?:,\s+\S+){2}
*
*This will match any non-space character one or more times \S+, followed by the following exactly twice:
*
*,\s+\S+ the comma character, followed by the space character one or more times, followed by any non-space character one or more times
*I changed peer_addr and peer_rid to \d{0,3}(?:\.\d{0,3}){3} instead of \d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}. This is a preference, but shortens the expression.
Without that last modification, you can use the following regex (it performs slightly better anyway (as seen here):
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2})
You can also improve the performance by using more specific tokens as the following suggests (notice I also added the x modifier to make it more legible) and as seen here:
(?P<as_path>\d{4,10}(?:\s\d{4,10}){0,19})\s+
(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})[^)]*
\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+
.*localpref\s(?P<local_pref>\d+),\s+
(?P<attribs>\w+(?:,\s+\w+){2})
A: You get that separate group because your are repeating a capturing group were the last iteration will be the capturing group, in this case 88945 You could make it non capturing instead (?:
For the second part you could use an alternation to exactly match one of the options (?:valid|external|best)
Your pattern might look like:
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>(?:valid|external|best)(?:,\s{0,4}(?:valid|external|best))+)
regex101 demo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55499712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why json_encode create new line after password_verify php and create error in android studio I'm new in php, now i want to create json_encode and use it as API to my android apps, but after i try it on android, the log say that
Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
and the postman shows one line after the json response. how to eliminate the new line (line two) which is not contain anything.
This is my response in postman:
1 {"kode":1,"pesan":"Login Berhasil"}
2
picture spoiler :
https://imgur.com/a/fKi0a72
thank you for all your response afterwards
i have tried to change code in php to fetch the password row several time but always produce second line.
$konek = new Mysqli($HostName, $HostUser, $HostPass, $DatabaseName) or die(Mysqli_errno());
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $_POST['email'];
$password = $_POST['password'];
$role = $_POST['role'];
$sql = "SELECT * FROM user WHERE email= '$email'";
$result = $konek->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if(password_verify($password, $row['password'])){
echo json_encode(array('kode' =>1, 'pesan' => 'Login Berhasil'));
} else {
echo json_encode(array('kode' =>2, 'pesan' => 'Login Gagal. Periksa Email atau password'));
}
}
}
}
else{
echo json_encode(array('kode' =>101, 'pesan' => 'Login Error '));
}
This is my response in postman:
1 {"kode":1,"pesan":"Login Berhasil"}
2
A: try to see output in json instead of html because in my Postman it is displayed correctly.
you should set Content type of Response of API to json to avoid any issues like this.
If doesn't help please comment with output as json in postman.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54264404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Rails ActiveRecord query using multiple joins involving polymorphic association I'm trying to figure out how I can replicate the following SQL query using AR given the model definitions below. The cast is necessary to perform the average. The result set should group foo by bar (which comes from the polymorphic association). Any help is appreciated.
SQL:
SELECT AVG(CAST(r.foo AS decimal)) "Average", s.bar
FROM rotation r INNER JOIN cogs c ON r.cog_id = c.id
INNER JOIN sprockets s ON s.id = c.crankable_id
INNER JOIN machinists m ON r.machinist_id = m.id
WHERE c.crankable_type = 'Sprocket' AND
r.machine_id = 123 AND
m.shop_id = 1
GROUP BY s.bar
ActiveRecord Models:
class Rotation < ActiveRecord::Base
belongs_to :cog
belongs_to :machinist
belongs_to :machine
end
class Cog < ActiveRecord::Base
belongs_to :crankable, :polymorphic => true
has_many :rotation
end
class Sprocket < ActiveRecord::Base
has_many :cogs, :as => :crankable
end
class Machinist < ActiveRecord::Base
belongs_to :shop
end
UPDATE
I've figured out a way to make it work, but it feels like cheating. Is there are a better way than this?
Sprocket.joins('INNER JOIN cogs c ON c.crankable_id = sprockets.id',
'INNER JOIN rotations r ON r.cog_id = c.id',
'INNER JOIN machinists m ON r.machinist_id = m.id')
.select('sprockets.bar', 'r.foo')
.where(:r => {:machine_id => 123}, :m => {:shop_id => 1})
.group('sprockets.bar')
.average('CAST(r.foo AS decimal)')
SOLUTION
Albin's answer didn't work as-is, but did lead me to a working solution. First, I had a typo in Cog and had to change the relation from:
has_many :rotation
to the plural form:
has_many :rotations
With that in place, I am able to use the following query
Sprocket.joins(cogs: {rotations: :machinist})
.where({ machinists: { shop_id: 1 }, rotations: { machine_id: 123}})
.group(:bar)
.average('CAST(rotations.foo AS decimal)')
The only real difference is that I had to separate the where clause since a machine does not belong to a machinist. Thanks Albin!
A: I think this code is a little simpler and taking more help from AR
Sprocket
.joins(cogs: {rotations: :machinist})
.where({ machinists: { machine_id: 123, shop_id: 1 } } )
.group(:bar)
.average('CAST(rotations.foo AS decimal)')
The select clause was unnecessary, you don't have to select values since you only need them internally in the query, AR helps you decide what you need afterwards.
I tested this out using a similar structure in one of my own projects but it is not the exact same models so there might be a typo or something in there if it does not run straight up. I ran:
Activity
.joins(locations: {participants: :stuff})
.where({ stuffs: { my_field: 1 } })
.group(:title)
.average('CAST(participants.date_of_birth as decimal)')
producing this query
SELECT AVG(CAST(participants.date_of_birth as decimal)) AS average_cast_participants_date_of_birth_as_decimal, title AS title
FROM `activities`
INNER JOIN `locations` ON `locations`.`activity_id` = `activities`.`id`
INNER JOIN `participants` ON `participants`.`location_id` = `locations`.`id`
INNER JOIN `stuffs` ON `stuffs`.`id` = `participants`.`stuff_id`
WHERE `stuffs`.`my_field` = 1
GROUP BY title
which AR makes in to a hash looking like this:
{"dummy title"=>#<BigDecimal:7fe9fe44d3c0,'0.19652273E4',18(18)>, "stats test"=>nil}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26746627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I am unable to get show different devices both audio and video available during stream I was just going through https://github.com/ScaleDrone/webrtc/blob/master/script.js but there is no way i could select from the devices and stream
navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
}).then(stream => {
// Display your local video in #localVideo element
localVideo.srcObject = stream;
// Add your stream to be sent to the conneting peer
stream.getTracks().forEach(track => pc.addTrack(track, stream));
}, onError);
how do i get all the device id shown for both video as well as audio source . please helpp me anyone
i just want that all device id should be shown and i can select any one from them.
I actually mean to say that when i use this on my phone it only selects my front camera . but what command should i insert here so that i can move to my rear camera or any other camera device attached and same is the case of audio, there are no audio devices to select from
A: I think you are looking for enumerateMediaDevices it seems to be implemented on all recent browsers (Not IE).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64367677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can you mix string and object outputs in SQL JSON? I'm trying to construct a JSON-serialized list of key/value pair items from my SQL database (compat level 140). The trick is that the values can be anything: numbers, strings, null, or other JSON objects.
It should be able to look something like this:
[{"key":"key1","value":"A String"},{"key":"key2","value":{"InnerKey":"InnerValue"}}]
However, SQL seems to be forcing me to select either a string or an object.
SELECT
[key] = kvp.[key],
[value] = CASE
WHEN ISJSON(kvp.[value]) = 1 THEN JSON_QUERY(kvp.[value])
ELSE '"' + kvp.[value] + '"' -- See note below
END
FROM (VALUES
('key1', 'This value is a string')
,('key2', '{"description":"This value is an object"}')
,('key3', '["This","value","is","an","array","of","strings"]')
,('key4', NULL)
-- Without these lines, the above 4 work fine; with either of them, even those 4 are broken
--,('key5', (SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
--,('key6', JSON_QUERY((SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)))
) AS kvp([key], [value])
FOR JSON PATH
Am I trying to do something that SQL can't support, or am I just missing the proper syntax for making this work?
*Note that the addition of the double-quotes seems like it shouldn't be necessary. But without those, SQL fails to wrap the string and generates bad JSON:
[{"key":"key1","value":This value is a string},...
A: If your query is modified to this, it works:
SELECT
[key] = kvp.[key],
[value] = ISNULL(
JSON_QUERY(CASE WHEN ISJSON(kvp.[value]) = 1 THEN kvp.[value] END),
'"' + STRING_ESCAPE(kvp.[value], 'json') + '"'
)
FROM (VALUES
('key1', 'This value is a "string"')
,('key2', '{"description":"This value is an object"}')
,('key3', '["This","value","is","an","array","of","strings"]')
,('key4', NULL)
-- These now work
,('key5', (SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
,('key6', JSON_QUERY((SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)))
) AS kvp([key], [value])
FOR JSON PATH, INCLUDE_NULL_VALUES
Of course, this wouldn't be sufficient if value was an int. Also, I can't really explain why yours doesn't work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47833621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: function that moves capitals to the front of a string and capitalizes lowercase letters? I'm trying to make a function that takes in a string as an input. It then moves the capital letters in the string to the front, and capitalizes lower-case letters. Lower-case letters and spaces should be kept in the same position relative to their location in the original string.
For example:
unravel_message(' neHAw moPPnthY')
should return 'HAPPY NEW MONTH' as the output.
and unravel_message('ALL CAPITALS')
should return 'ALLCAPITALS ' as the output.
(the space remains in the same location; only the capitals are moved back)
My Attempt:
def unravel_message(word):
return ''.join([i for i in word if i == i.upper()]) + ''.join([i.upper() for i in word if i == i.lower()])
for my function, unravel_message(' neHAw moPPnthY') outputs ' HA PPY NEW MONTH'. Which isn't quite right. I think this may be because of the ''.join(). I would like to revise this function to use a single list comprehension wihtout imports if possible. If the inputs are all lowercase, I would also like to include an assertion statement addressing an error but I'm not sure how to do this.
A: Timsort is stable, which means that you can get what you want with something like
>>> assert not message.islower()
>>> ''.join(sorted(message, key=lambda c: not c.isupper())).upper()
'HAPPY NEW MONTH'
The trick is that booleans are a subclass of integers in python. The key returns False == 0 for elements you want to move to the beginning, and True == 1 for elements that stay. You need to use lambda c: not c.isupper() because spaces and other characters will move back if you use str.islower as the key.
If you want the assertion to be more detailed, like checking if all the letter characters are lowercase, you can do it with something like
>>> assert any(c != c.lower() for c in message)
For more complex unicode code points, use c.casefold() instead of c.lower().
A: Here is a solution that uses a single list comprehension without imports. It is also linear in time with the length of the string unlike sorting solutions with have higher time complexity of O(n log n). It also has an assertion statement flagging strings with no uppercase letters (i.e., all alpha characters are lowercase).
def unravel_message(s):
assert any('A' <= c <= 'Z' for c in s)
return (duo := list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s]))))[0] + duo[1]
x = unravel_message(' neHAw moPPnthY')
print(x)
x = unravel_message(' no uppercase letters')
Output:
HAPPY NEW MONTH
Traceback (most recent call last):
File "C:\python\test.py", line 7, in <module>
x = unravel_message(' no uppercase letters')
File "C:\python\test.py", line 2, in unravel_message
assert any('A' <= c <= 'Z' for c in s)
AssertionError
Note that the solution uses the walrus operator := to make it a one-liner. If you are using Python earlier than version 3.8, you can do this instead:
def unravel_message(s):
assert any('A' <= c <= 'Z' for c in s)
duo = list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s])))
return duo[0] + duo[1]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71918801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Which one is better in terms of Speed and memory usage or simply best practice I have a function with a lot of constant variables inside. Would it be better to store these variables in a Hash-map (it would be a complicated one) (it would have hash-maps inside the Hash-map. Or several if, else if clauses. In terms of readability they're about the same. But What I'm worried about is the memory taken and the speed of the app. This is a extremely simplified version of the problem :
function myFunction(data) {
var a = 0, b = 0, c = 0, d = 0;
if(data == value1) {
a += 3;
if(value1Fetched) {
b += 6;
c +=2;
d +=1;
}
} else if (data == value2) {
a += 1;
if(value2Fetched) {
b += 4;
c +=9;
}
}
return a+b+c+d;
}
Obviously there are way more flags and values (and Data is a Hash-map too)
version 2 :
function myFunction(data) {
var a = 0, b = 0, c = 0, d = 0;
var myHash = {
value1: {
a: 3,
b: 6,
c: 2,
d: 1
},
value2: {
a: 1,
b: 4,
c: 9,
d: 0
}
};
a += myHash[data][a];
if(isFetched(data)){
b += myHash[data][b];
c += myHash[data][c];
d += myHash[data][d];
}
return a+b+c+d;
}
Sorry for the messy (pseudo)code, i tried to make it as readable as possible.
This has been haunting me for days and everyone at work has a different opinion.
A: I would say the extensibility of the second question far outweighs any possible (and unlikely) performance issues. You can even change that structure on the fly if needed, or have multiple instances for two environments where the mapping turns out different.
It might be slower for examples as small as the one you posted, but it sounds like the actual might have a great many entries, in which case using a map lookup has O(log(n)) complexity rather than O(n) (hope I have those terms correct! Been a while since college). Large JSON objects (string-maps) are not uncommon in JavaScript, in fact you often work with them for the libraries and browser features in common code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33552199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Apache httpd.conf file: How to add condition to check url is HTTPS or HTTP I want to set "SameSite" and "Secure" as follows in httpd.conf file, only if url is https only.
How can add condition to check if url is https or http
Header always edit Set-Cookie (.*) "$1; SameSite=None; Secure"
Header onsuccess edit Set-Cookie (.*) "$1; SameSite=None; Secure
I have tried following solutions but didn't help:
<If "reqenv('HTTPS') == 'on'">
SetEnvIf HTTPS "on" HAS_HTTPS
SetEnvIfExpr "tolower(req('HTTPS')) =='on'" HAS_HTTPS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72519421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Failed to call a dynamic method in a static context? These are created using Android Studio similar to How to modify dummy content in android master/detail activity?. I changed the static method under dummyContent into below:
public void fetchData() {
// Add some sample items.
for (int i = 1; i <= COUNT; i++) {
addItem(createDummyItem(i));
}
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
DummyContent.UNAME, DummyContent.PASSWORD.toCharArray());
}
});
try {
DummyContentRegistry registry = new XMLDummyContentParser(DummyContent.url).parse();
for (DummyContent.DummyItem t: registry.getTeachers()) {
DummyContent.addItem(t);
}
} catch (Exception e) {
fail("Exception should not have been thrown");
}
}
while above passed the test:
public class DummyContentRegistryTest {
@Before
public void buildRegistry() {}
@Test
public void testFetchData() {
Assert.assertEquals(0,DummyContent.ITEMS.size());
new DummyContent().fetchData();
Assert.assertEquals(27,DummyContent.ITEMS.size());// two more items are added through parsing xml on a website
}
}
However when I call the method under MainActivity.onCreate it failed "Exception should not have been thrown". Why? Here's an example of failing call
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DummyContent.ITEMS.isEmpty()) {
new DummyContent().fetchData();
}
......
}
I don't know if the problem is similar to calling non-static method in static method in Java but I've obviously tried the way most of them agreed.
[ 07-25 04:04:56.442 23983:24025 D/ ]
HostConnection::get() New Host Connection established 0x7f1b57910500, tid 24025
07-25 04:04:56.460 23983-24025/*****private*****.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
07-25 04:04:56.873 23983-23983/*****private*****.myapplication I/Choreographer: Skipped 32 frames! The application may be doing too much work on its main thread.
07-25 04:05:07.474 23983-23983/*****private*****.myapplication W/System.err: java.io.IOException: Couldn't open *****private*****
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at *****private*****.myapplication.dummy.XMLDummyContentParser.parse(XMLDummyContentParser.java:33)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at *****private*****.myapplication.dummy.DummyContent.fetchData(DummyContent.java:53)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:52)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.app.Activity.performCreate(Activity.java:6237)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.os.Looper.loop(Looper.java:148)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at java.lang.reflect.Method.invoke(Native Method)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: Caused by: android.os.NetworkOnMainThreadException
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err: ... 18 more
07-25 04:05:07.483 23983-23983/*****private*****.myapplication D/AndroidRuntime: Shutting down VM
07-25 04:05:07.484 23983-23983/*****private*****.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: ******private*******, PID: 23983
java.lang.RuntimeException: Unable to start activity ComponentInfo{******private*******.myapplication.MainActivity}: java.lang.IllegalStateException: Already attached
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Already attached
at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2126)
at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:313)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
A: The Exception e, which you catch may contain useful information on what exactly went wrong. Do e.printStackTrace(); inside your catch-block to print all available information to the standard output.
If that does not help you solve the problem post the stacktrace here.
A: You cannot manipulate UI thread from background thread thats why you are getting this error.
ClassName.this.runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
// enclose your UI manipulated code here in these braces.
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38565911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get the number of pages in a PDF file inside a Google Apps Script? The PDF files are in my Google Drive. I just got that I can get the number of pages of a PDF sending it as a job to Cloud Print, because Cloud Print will return a JSON object with "numberOfPages" attribute.
Is there any faster and easier way? Thanks in advance.
A: Well, I actually did like I said.
I take my file, then send it to CloudPrint via its JSON Api. I need to send it to a dummy printer, a printer I registered in CloudPrint but actually is never connected to Internet. Then, I get the number of pages of the PDF file in the value of response's "numberOfPages" attribute. Save this number in some var. Finally, I send a delete petition to JSON Api for my file in the dummy printer, indeed isn't necessary at all.
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16777507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bash script in raspbian runs manually, won't run in cron Trying to turn a small TV into a photo frame so to speak, so I have a Raspberry Pi and I have a bash script at /home/pi/scripts/script.sh:
#!/bin/sh
sudo /usr/bin/gpicview /home/pi/Downloads/test_5_25.png >> /home/pi/Downloads/test.log
My cron tab looks like this:
# m h dom mon dow command
* * * * * sh /home/pi/scripts/script.sh
My syslog shows that its running:
May 27 04:32:01 raspberrypi /USR/SBIN/CRON[2999]: (pi) CMD (sh /home/pi/scripts/script.sh
But gpicview is not opening like when I run the script manually, and in my error log it shows...
option parsing failed: Cannot open display:
I thought maybe permissions or something, but I've double checked those to the best of my ability and cannot figure it out. Any clues would be greatly appreciated!!
A: You probably need to set the display manually, i.e.:
* * * * * export DISPLAY=:0 && sh /home/pi/scripts/script.sh
As outlined in this article.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30473298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Out-Of-Browser Service Access problem using Silverlight 4 I have a Silverlight 4 application that access a couple of WCF Data Services.
There are no problems accessing the service through the browser.
I set the program to run out-of-browser with elevated trust. Then I can see the calls to the WCF Service via fiddler, but nothing ever comes back.
If I debug then I get the following error:
$exception {System.UnauthorizedAccessException: Invalid cross-thread access.
at MS.Internal.XcpImports.CheckThread()
at System.Windows.Controls.ItemCollection.GetValueInternal(DependencyProperty dp)
at System.Windows.PresentationFrameworkCollection`1.get_CountImpl()
at System.Windows.PresentationFrameworkCollection`1.get_Count()
at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.RemoveAll()
at System.Windows.Controls.ItemContainerGenerator.RemoveAll()
at System.Windows.Controls.ItemContainerGenerator.OnRefresh()
at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
at System.Windows.Controls.ItemCollection.NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)
at System.Windows.Controls.ItemCollection.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
at System.Collections.ObjectModel.ObservableCollection`1.ClearItems()
at System.Collections.ObjectModel.Collection`1.Clear()
at ClientFolderExplorer.ViewModels.DocumentExplorerViewModel.clientCatalog_ClientsLoadingComplete(Object sender, ClientLoadingEventArgs e)
at ClientFolderExplorer.Catalogs.ClientCatalog.<>c__DisplayClass3.<ExecuteClientQuery>b__2(IAsyncResult a)} System.Exception {System.UnauthorizedAccessException}
Not sure where to start troubleshooting. I have crossdomain.xml and clientaccesspolicy.xml files in place in the root of the webserver, but I cannot even see these files being requested (in fiddler).
Any Ideas?
A: Yes - you suppose the problem is related to cross-site access, while in reality it's related to cross-thread access (first line of error indicates this clearly).
I'm assuming you're trying to set some UI element's data bound (or not, doesn't matter) property directly from the callback handling the service call. (edit) Forgot to clarify - where the callback is running on a thread different from the UI thread. Silverlight like most other frameworks disallows modifying UI except from the UI thread.
If so, take a look at how to use Dispatcher in order to switch back to the UI thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4314774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Laravel much better of using if so most of time i do this
@if(!empty($variable)
@if($variable == "yes")
do something here
@endif
@endif
well as you can see it really not a beautiful way, maybe (i really hope there is) a much simpler way to just detect if the variable is exist and not throwing error when it is not exist beside that...?
it making my code so crowded and if by anychance i forgot to add those will got beautiful error (well i design a eye cathing error page by the way)
@if(!empty($variable))
or
@if(isempty($variable))
A: Combine the two checks into a single if statement:
@if (! empty($variable) && $variable == 'yes')
do something here
@endif
A: if you are searching for one line condition, it will work as expected,
{{!empty($variable) ? $variable == 'yes' ? 'do something' : 'do something else' : 'variable is empty'}}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34459880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C function macro to take NSString placeholders In my IOS-Project, I have a custom Logger-class (singleton) containing the function
- (void)log:(NSString *)domain logLevel:(int)level logMessage:(NSString *)message
which is globally available through the following preprocessor macro:
#define MyLog(domain, level, message) [[MyLogger sharedInstance] log:domain logLevel:level logMessage:message]
Now when I make the call:
MyLog(@"common", LL_ERROR, @"There was an error!");
Everything works fine. But in practice, the logMessage will sometimes contain string placeholders. So the big question is:
How can I make my macro accept calls like
MyLog(@"common", LL_ERROR, @"There was an error: %@", [error debugDescription]);
With the current solution, Xcode complains: "Too many arguments provided to function-like macro invocation".
A: First, you have to change your log method to take a "variable argument list",
for example like this:
- (void)log:(NSString *)domain logLevel:(int)level logMessage:(NSString *)message, ...
{
va_list argList;
va_start(argList, message);
NSString *fullMessage = [[NSString alloc] initWithFormat:message arguments:argList];
va_end(argList);
NSLog(@"domain:%@, level:%d: %@", domain, level, fullMessage);
}
Then you have to change your MyLog macro to work with a variable number of arguments.
This is a GNU feature (http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html), that works
with Clang as well:
#define MyLog(domain, level, message, ...) \
[[MyLogger sharedInstance] log:domain logLevel:level logMessage:message, ##__VA_ARGS__]
Now
MyLog(@"common", LL_ERROR, @"There was an error!");
MyLog(@"common", LL_ERROR, @"There was an error: %@", [error debugDescription]);
should both work without problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19313675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Requires API level 21 (current min is 16) I'm new in android development and programming. I'm working on android camera application. I'm new in this so I use the lectures of a youtuber who uses API level 21 and I'm using API level 16 for maximum users but our code is same which causes a problem.
call requires API level 21 (current min is 16):android.hardware.camera2.CameraDevice.StateCallback#StateCallback more...CTRL + f1)
Please help me to fix this. I don't want to change its API level to 21.
A: Use 'android.hardware.camera' instead of 'android.hardware.camera2' API and that allows you to use that API with API level 16.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39060745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best practices on upgrading cassandra I am getting errors from pyspark connecting to cassandra because it appears I am using a too old a cassandra:
[idf@node1 python]$ nodetool -h localhost version
ReleaseVersion: 2.0.17
[idf@node1 python]$
[idf@node1 cassandra]$ java --version
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
[idf@node1 cassandra]$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
[idf@node1 cassandra]$
I want to upgrade to the latest version. However, I have already collected quite a bit of data and I don't want to lose it. I am using CentOS 7.2 with a single cassandra node. My questions are,
*
*where is the cassandra data stored on the local file system
*is it correct to assume that I can compress this directory and move it?
Then once I have the data backed up, what is the correct way to upgrade cassandra? Is it
*
*remove old version completely
*install new version
*copy data back
What is the best practice to do this?
A: I'm guessing you are using OSS version. Default location for data is /var/lib/cassandra and you can backup it if you wan't.
Procedure for upgrade is simple:
*
*run nodetool drain
*stop cassandra
*save your cassandra.yaml
*remove old and install new version
*update new cassandra.yaml with your settings
*start cassandra
*run nodetool ugradesstables
This should leave you with your node running the new version of cassandra with all your schema and data in it.
Be careful if you are upgrading past 2.1 because 2.2 and up require java8. Everything else is the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37305158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cake php form containing file upload not adding enctype="multipart/form-data" attribute I have a controller Job and controller User
I want to send post data from the view of Job Controller to User controller
the form contains file upload option too
$this->Form->create('User',array('url'=>array('controller'=>'Users','action'=>'newUser')),array('type' =>'file','enctype'=>'multipart/form-data'))
it will give the out put
<form action="/User/newUser" id="UserViewForm" method="post" accept-charset="utf-8">
but it is not adding attribute of enctype="multipart/form-data"
to form
A: Try this
$this->Form->create('User',
array('type' => 'file', 'class' => 'classname', 'url'=>array('controller'=>'Users','action'=>'newUser') ) );
You don't need to create a separate array for the all options.
Docs: Form Options
A: <?php
echo $this->Form->create('User', array('url' => array('controller' => 'Users','action' =>'newUser'),'class'=>'classname','enctype'=>'multipart/form-data'));
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27731337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to schedule a notification using firebase messaging I am trying to push a schedule notification to a group of people using firebase messaging, but the only resources I found were for flutter_local_notifications with the scheduling feature. which, as far as I know, work only for the same device I work with and do not send the notification to other devices.
I tried to customize the local schedule notification to send notifications to other devices but I did not know where to add the tokens for other devices
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74919878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create waveform with pyaudio and matplotlib in real time I'm looking for a real time graph of an audio input (microphone) and show this data in a waveform graph using matplotlib. How can I show the data on Y axes and the time (seconds) in X axes ?
I don't know anything for audio processing so I learned a lot with docs and examples but I still don't know how to make the graph react in real time.
from scipy.io import wavfile
from matplotlib import pyplot as plt
import numpy as np
# Load the data and calculate the time of each sample
samplerate, data = wavfile.read('audio.wav')
print(samplerate, data)
times = np.arange(len(data))/float(samplerate)
# Make the plot
# You can tweak the figsize (width, height) in inches
plt.figure(figsize=(30, 4))
print(data[:,0])
plt.fill_between(times, data[:,0], data[:,1], color='k')
plt.xlim(times[0], times[-1])
plt.xlabel('time (s)')
plt.ylabel('amplitude')
# You can set the format by changing the extension
# like .pdf, .svg, .eps
plt.savefig('plot.png', dpi=100)
plt.show()
I expect a waveform looking like that but, using my microphone instead of wav file. I tested other things but it was no so concluding...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56886312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RegEx JavaScript: Match consecutive single line comments I am trying to write a RegEx to parse groups of single line comments.
Given this input:
//line 1
//line 2
//line 3
//line 4
//line 5
//line 6
I expect to have two matches: Lines 1-3 and 4-6. With my current RegEx (^\/\/[\S\s]+$) I have one match: Lines 1-6, although there is an empty line in between.
The problem is that \s matches any whitespace character, so the blank line is included. But at the same time, line break are part of the RegEx – but only when the line starts with //, so I am stuck.
How can I prevent the RegEx from matching the blank line?
A: You could try this one:
/(^\/\/[^\n]+$\n)+/gm
see here https://regex101.com/r/CrR9WU/1
This selects first the two / at the beginning of each line then anything that is not a newline and finally (at the end of the line) the newline character itself. There are two matches: rows 1 to 3 and rows 4 to 6. If you also allow "empty comment lines like // then this will do too:
/(^\/\/[^\n]*$\n)+/gm
Edit:
I know, it is a little late now, but Casimir's helpful comment got me on to this modified solution:
/(?:^\/\/.*\n?)+/gm
It solves the problem of the final \n, does not capture groups and is simpler. (And it is pretty similar to Jan's solution ;-) ...)
A: This is what modifiers are for:
(?:^\/{2}.+\n?)+
With MULTILINE mode, see a demo on regex101.com.
Broken apart, this says:
(?: # a non-capturing group
^ # start of the line
\/{2} # //
.+ # anything else in that line
\n? # a newline, eventually but greedy
)+ # repeat the group
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46383205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the cosine distance of something and itself? I'm playing with scipy's cosine distance. From what I've gathered, the closer a cosine distance is to 1, the more similar the vectors are. I got some unexpected results in a text mining project, so I decided to investigate the simplest case.
import numpy as np
import scipy.spatial
arr1 = np.array([1,1])
arr2 = np.array([1,1])
print scipy.spatial.distance.cosine(arr1, arr2)
My program prints 0.0.
Shouldn't the result be 1.0? Why or why not?
A: It is the cosine distance, not the cosine similarity. A basic requirement for a function d(u, v) to be a distance is that d(u, u) = 0.
See the definition of the formula in the docstring of scipy.spatial.distance.cosine, and notice that the formula begins 1 - (...). Your expectation of the function is probably based on the quantity in (...), but that expression is the cosine similarity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50960016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: django: Invalid filter I got an article app and trying to make a custom filter, I have a directory called templatetags in article app, and a tags.py within that directory, here is the directory structure.
-manage.py(f)
-settings.py(f)
-articles(d)
- templatetags(d)
- tags.py(f)
On the templates, the articles have its own directory, all article templates extend from a base.html template, here is the template structure.
-base.html(f)
-articles(d)
-index.html(f)
I load the tags in base.html {% load tags %} and use the custom filter in index.html and got the invalid filter error.
tags.py
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def space2Dash(s):
return s.replace(' ', '_');
I just can't figure out what I did wrong.
edit:
I changed the filter name to abcfilter.py and I have the article app loaded in my settings.py
articles/index.html
{% load abcfilter %}
{{ "foo bar"|space2dash }}
the error:
Request Method: GET
Request URL: http://localhost:8080/articles/
Django Version: 1.2.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid filter: 'space2dash'
Exception Location: ***/lib/python2.7/django/template/__init__.py in find_filter, line 363
Python Executable: /usr/local/bin/python
Python Version: 2.7.1
Server time: Sun, 10 Apr 2011 07:55:54 -0500
A: Just for reference, I solved the problem by moving
{% load ... %}
from the base template to the concrete template.
See also this post https://stackoverflow.com/a/10427321/3198502
A: To avoid loading the module in each template using {% load MODULE_NAME %}, you can add it as a 'builtin' in settings.py:
TEMPLATES = [
{
'OPTIONS': {
...
,
'builtins': [
...
'APP_NAME.templatetags.MODULE_NAME',
]
},
},
]
A: First off remove the semicolon after your replace.
Do you have a file called __init__.py (this is suppose to have 2 underscores before and after init, hard to format in editor.) under the templatetags directory?
Here is a good page with lots of info if you haven't looked yet.
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
A: I was nearly going nuts with this problem and none of the above answers helped.
If you have several apps, make sure that the file names containing your custom tags/filters are unique, prefereablyapp_name_filters.py. Otherwise Django will only load the custom filters from the app it finds matching first!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5604703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: LZ4 compression library in android app How do I use LZ4 compression library in my android application...
The main issue I'm facing is when i try to export a signed application package, the error which comes is
Warning: net.jpountz.util.UnsafeUtils: can't find referenced class sun.misc.Unsafe
When I directly run the application in my device, there is no issue, this error comes only when I try to export the application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26904752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Custom XPath rule raises violation in pmd but not in sonar I have a quite strange behavior.
I create a XPath rule for PMD 4.2.6 in a file named pmd-extensions.xml :
...
<rule name="AvoidPrintStackTrace-XPath"
message="Avoid to use printStackTrace - XPath"
class="net.sourceforge.pmd.rules.XPathRule">
<description>Avoid to use printStackTrace - XPath</description>
<properties>
<property name="xpath">
<value>
<![CDATA[
//Name[contains (@Image, "printStackTrace")]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
// don't do this!
myException.printStackTrace()
]]>
</example>
</rule>
...
I have an unit test validating this rule and working fine:
...
@Before
public void setUp() {
addRule("rulesets/pmd-extensions.xml", "AvoidPrintStackTrace-XPath");
}
...
But when I embed this rule in Sonar, the rule doesn't fire any violation while I expected one:
...
<rule key="AvoidPrintStackStrace-XPath" >
<name>AvoidPrintStackStrace-XPath</name>
<configKey>rulesets/pmd-extensions.xml/AvoidPrintStackTrace-XPath</configKey>
<category name="Usability"/>
<description>Avoid to use printStackTrace - XPath</description>
</rule>
...
And if I declare this rule directly in Sonar (with same XPath expression), the rule fire a violation as expected:
...
<rule key="AvoidPrintStackStrace-XPath-Sonar" priority="MAJOR">
<name><![CDATA[AvoidPrintStackStrace-XPath-Sonar]]></name>
<configKey><![CDATA[net.sourceforge.pmd.rules.XPathRule]]></configKey>
<category name="Maintainability"/>
<description>Avoid to use printStackTrace - XPath-Sonar</description>
<param key="xpath" type="s">
<description><![CDATA[XPath expressions.]]></description>
<defaultValue>//Name[contains (@Image, "printStackTrace")]</defaultValue>
</param>
<param key="message" type="s">
<description><![CDATA[Message to display when a violation occurs.]]></description>
<defaultValue>Prevent use of printStackTrace</defaultValue>
</param>
</rule>
...
What's wrong ?
Thanks.
A: You probably haven't added this new rule to the profile that you are using for your project.
The fact that you provided a "pmd-extensions.xml" file just means that you added this rule to the rule repository. But if you do not activate this rule on a single profile, it will remain inactive and will never get executed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11221618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XSLT, getting values not in order I have an XML like this
<row>
<col>1</col>
<col>name1</col>
<col>link1</col>
<col>junk1</col>
<col>value1</col>
</row>
<row>
<col>2</col>
<col>name2</col>
<col>link2</col>
<col>junk2</col>
<col>value2</col>
</row>
how do I write the XSLT to get this output? the third column in each row contains the link and the fourth value does not need to be printed in output
<tr>
<td>1<td>
<td><a href="link1">name1</a></td>
<td>value1<td>
</tr>
<tr>
<td>2<td>
<td><a href="link2">name2</a></td>
<td>value<td>
</tr>
A: Seeing your XSLT would help understand why you get unsorted output. But in any case, try <xsl:sort select="col/text()"/>.
A: The following XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/table">
<xsl:copy>
<xsl:apply-templates select="row">
<xsl:sort select="col[1]"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="row">
<tr>
<td>
<xsl:value-of select="col[1]"/>
</td>
<td>
<a href="{col[3]}">
<xsl:value-of select="col[2]"/>
</a>
</td>
<td>
<xsl:value-of select="col[5]"/>
</td>
</tr>
</xsl:template>
</xsl:stylesheet>
When applied to the following input XML
<table>
<row>
<col>1</col>
<col>name1</col>
<col>link1</col>
<col>junk1</col>
<col>value1</col>
</row>
<row>
<col>2</col>
<col>name2</col>
<col>link2</col>
<col>junk2</col>
<col>value2</col>
</row>
</table>
will produce the following output
<table>
<tr>
<td>1</td>
<td>
<a href="link1">name1</a>
</td>
<td>value1</td>
</tr>
<tr>
<td>2</td>
<td>
<a href="link2">name2</a>
</td>
<td>value2</td>
</tr>
</table>
Do note the use of Attribute Value Templates (AVT) to set the href attribute for the a tag:
<a href="{col[3]}">
You can also do away with the xsl:sort should you just wish the order of the rows in the output to be the same as the order in input XML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7757003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: STM32 DMA: bytes remaining in buffer, encoded? For quite a while now I've been struggling with DMA communication with two STM32 boards in some form or another. My current issue is as follows.
I have a host (a Raspberry Pi) running the following code, waiting for the board to initialise communication:
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
unsigned int usbdev;
unsigned char c;
system("stty -F /dev/ttyUSB0 921600 icanon raw");
usbdev = open("/dev/ttyUSB0", O_RDWR);
setbuf(stdout, NULL);
fprintf(stderr, "Waiting for signal..\n");
while (!read(usbdev, &c, 1));
unsigned char buf[] = "Defend at noon\r\n";
write(usbdev, buf, 16);
fprintf(stderr, "Written 16 bytes\r\n");
while (1) {
while (!read(usbdev, &c, 1));
printf("%c", c);
}
return 0;
}
Basically it waits for a single byte of data before it'll send "Defend at noon" to the board, after which it prints everything that is sent back.
The boards first send out a single byte, and then wait for all incoming data, replace a few bytes and send it back. See the code at the end of this post. The board can be either an STM32L100C or an STM32F407 (in practice, the discovery boards); I'm experiencing the same behaviour with both at this point.
The output I'm seeing (on a good day - on a bad day it hangs on Written 16 bytes) is the following:
Waiting for signal..
Written 16 bytes
^JDefend adawnon
As you can see, the data is sent and four bytes are replaced as expected, but there's an extra two characters in front (^J, or 0x5E and 0x4A). These turn out to be a direct consequence of the signal_host function. When I replace the character with something arbitrary (e.g. x), that is what's being output at that position. It is interesting to note that \n actually gets converted to its caret notation ^J somewhere along the road. It appears that this occurs in the communication to the board, because when I simply hardcode a string in the buffer and use dma_transmit to send that to an non-interactive host program, it gets printed just fine.
It looks like I've somehow miss-configured DMA in the sense that there's some buffer that is not being cleared properly. Additionally, I do not really trust the way the host-side program is using stty.. However, I've actually had communication working flawlessly in the past, using this exact code. I compared it to the code stored in my git history across several months, and I cannot find the difference/flaw.
Note that the code below uses libopencm3 and is based on examples from libopencm3-examples.
STM32L1 code:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/dma.h>
void clock_setup(void)
{
rcc_clock_setup_pll(&clock_config[CLOCK_VRANGE1_HSI_PLL_32MHZ]);
rcc_periph_clock_enable(RCC_GPIOA);
rcc_periph_clock_enable(RCC_USART2);
rcc_periph_clock_enable(RCC_DMA1);
}
void gpio_setup(void)
{
gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3);
gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3);
}
void usart_setup(int baud)
{
usart_set_baudrate(USART2, baud);
usart_set_databits(USART2, 8);
usart_set_stopbits(USART2, USART_STOPBITS_1);
usart_set_mode(USART2, USART_MODE_TX_RX);
usart_set_parity(USART2, USART_PARITY_NONE);
usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE);
usart_enable(USART2);
}
void dma_request_setup(void)
{
dma_channel_reset(DMA1, DMA_CHANNEL6);
nvic_enable_irq(NVIC_DMA1_CHANNEL6_IRQ);
dma_set_peripheral_address(DMA1, DMA_CHANNEL6, (uint32_t) &USART2_DR);
dma_set_read_from_peripheral(DMA1, DMA_CHANNEL6);
dma_set_peripheral_size(DMA1, DMA_CHANNEL6, DMA_CCR_PSIZE_8BIT);
dma_set_memory_size(DMA1, DMA_CHANNEL6, DMA_CCR_MSIZE_8BIT);
dma_set_priority(DMA1, DMA_CHANNEL6, DMA_CCR_PL_VERY_HIGH);
dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL6);
dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL6);
dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL6);
dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL6);
dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL6);
}
void dma_transmit_setup(void)
{
dma_channel_reset(DMA1, DMA_CHANNEL7);
nvic_enable_irq(NVIC_DMA1_CHANNEL7_IRQ);
dma_set_peripheral_address(DMA1, DMA_CHANNEL7, (uint32_t) &USART2_DR);
dma_set_read_from_memory(DMA1, DMA_CHANNEL7);
dma_set_peripheral_size(DMA1, DMA_CHANNEL7, DMA_CCR_PSIZE_8BIT);
dma_set_memory_size(DMA1, DMA_CHANNEL7, DMA_CCR_MSIZE_8BIT);
dma_set_priority(DMA1, DMA_CHANNEL7, DMA_CCR_PL_VERY_HIGH);
dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL7);
dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL7);
dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL7);
dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL7);
dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL7);
}
void dma_request(void* buffer, const int datasize)
{
dma_set_memory_address(DMA1, DMA_CHANNEL6, (uint32_t) buffer);
dma_set_number_of_data(DMA1, DMA_CHANNEL6, datasize);
dma_enable_channel(DMA1, DMA_CHANNEL6);
signal_host();
usart_enable_rx_dma(USART2);
}
void dma_transmit(const void* buffer, const int datasize)
{
dma_set_memory_address(DMA1, DMA_CHANNEL7, (uint32_t) buffer);
dma_set_number_of_data(DMA1, DMA_CHANNEL7, datasize);
dma_enable_channel(DMA1, DMA_CHANNEL7);
usart_enable_tx_dma(USART2);
}
int dma_done(void)
{
return !((DMA1_CCR6 | DMA1_CCR7) & 1);
}
void dma1_channel6_isr(void) {
usart_disable_rx_dma(USART2);
dma_clear_interrupt_flags(DMA1, DMA_CHANNEL6, DMA_TCIF);
dma_disable_channel(DMA1, DMA_CHANNEL6);
}
void dma1_channel7_isr(void) {
usart_disable_tx_dma(USART2);
dma_clear_interrupt_flags(DMA1, DMA_CHANNEL7, DMA_TCIF);
dma_disable_channel(DMA1, DMA_CHANNEL7);
}
void signal_host(void) {
usart_send_blocking(USART2, '\n');
}
int main(void)
{
clock_setup();
gpio_setup();
usart_setup(921600);
dma_transmit_setup();
dma_request_setup();
unsigned char buf[16];
dma_request(buf, 16); while (!dma_done());
buf[10] = 'd';
buf[11] = 'a';
buf[12] = 'w';
buf[13] = 'n';
dma_transmit(buf, 16); while (!dma_done());
while(1);
return 0;
}
STM32F4 code:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/dma.h>
void clock_setup(void)
{
rcc_clock_setup_hse_3v3(&hse_8mhz_3v3[CLOCK_3V3_168MHZ]);
rcc_periph_clock_enable(RCC_GPIOA);
rcc_periph_clock_enable(RCC_USART2);
rcc_periph_clock_enable(RCC_DMA1);
}
void gpio_setup(void)
{
gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3);
gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3);
}
void usart_setup(int baud)
{
usart_set_baudrate(USART2, baud);
usart_set_databits(USART2, 8);
usart_set_stopbits(USART2, USART_STOPBITS_1);
usart_set_mode(USART2, USART_MODE_TX_RX);
usart_set_parity(USART2, USART_PARITY_NONE);
usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE);
usart_enable(USART2);
}
void dma_request_setup(void)
{
dma_stream_reset(DMA1, DMA_STREAM5);
nvic_enable_irq(NVIC_DMA1_STREAM5_IRQ);
dma_set_peripheral_address(DMA1, DMA_STREAM5, (uint32_t) &USART2_DR);
dma_set_transfer_mode(DMA1, DMA_STREAM5, DMA_SxCR_DIR_PERIPHERAL_TO_MEM);
dma_set_peripheral_size(DMA1, DMA_STREAM5, DMA_SxCR_PSIZE_8BIT);
dma_set_memory_size(DMA1, DMA_STREAM5, DMA_SxCR_MSIZE_8BIT);
dma_set_priority(DMA1, DMA_STREAM5, DMA_SxCR_PL_VERY_HIGH);
dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4);
dma_enable_memory_increment_mode(DMA1, DMA_STREAM5);
dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM5);
dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM5);
dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM5);
dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM5);
dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM5);
}
void dma_transmit_setup(void)
{
dma_stream_reset(DMA1, DMA_STREAM6);
nvic_enable_irq(NVIC_DMA1_STREAM6_IRQ);
dma_set_peripheral_address(DMA1, DMA_STREAM6, (uint32_t) &USART2_DR);
dma_set_transfer_mode(DMA1, DMA_STREAM6, DMA_SxCR_DIR_MEM_TO_PERIPHERAL);
dma_set_peripheral_size(DMA1, DMA_STREAM6, DMA_SxCR_PSIZE_8BIT);
dma_set_memory_size(DMA1, DMA_STREAM6, DMA_SxCR_MSIZE_8BIT);
dma_set_priority(DMA1, DMA_STREAM6, DMA_SxCR_PL_VERY_HIGH);
dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4);
dma_enable_memory_increment_mode(DMA1, DMA_STREAM6);
dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM6);
dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM6);
dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM6);
dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM6);
dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM6);
}
void dma_request(void* buffer, const int datasize)
{
dma_set_memory_address(DMA1, DMA_STREAM5, (uint32_t) buffer);
dma_set_number_of_data(DMA1, DMA_STREAM5, datasize);
dma_channel_select(DMA1, DMA_STREAM5, DMA_SxCR_CHSEL_4);
dma_enable_stream(DMA1, DMA_STREAM5);
signal_host();
usart_enable_rx_dma(USART2);
}
void dma_transmit(const void* buffer, const int datasize)
{
dma_set_memory_address(DMA1, DMA_STREAM6, (uint32_t) buffer);
dma_set_number_of_data(DMA1, DMA_STREAM6, datasize);
dma_channel_select(DMA1, DMA_STREAM6, DMA_SxCR_CHSEL_4);
dma_enable_stream(DMA1, DMA_STREAM6);
usart_enable_tx_dma(USART2);
}
int dma_done(void)
{
return !((DMA1_S5CR | DMA1_S6CR) & 1);
}
void dma1_stream5_isr(void) {
usart_disable_rx_dma(USART2);
dma_clear_interrupt_flags(DMA1, DMA_STREAM5, DMA_TCIF);
dma_disable_stream(DMA1, DMA_STREAM5);
}
void dma1_stream6_isr(void) {
usart_disable_tx_dma(USART2);
dma_clear_interrupt_flags(DMA1, DMA_STREAM6, DMA_TCIF);
dma_disable_stream(DMA1, DMA_STREAM6);
}
void signal_host(void) {
usart_send_blocking(USART2, '\n');
}
int main(void)
{
clock_setup();
gpio_setup();
usart_setup(921600);
dma_transmit_setup();
dma_request_setup();
unsigned char buf[16];
dma_request(buf, 16); while (!dma_done());
buf[10] = 'd';
buf[11] = 'a';
buf[12] = 'w';
buf[13] = 'n';
dma_transmit(buf, 16); while (!dma_done());
while(1);
return 0;
}
A: Well, I can be brief about this one.
I recommend against using stty for this sort of thing. I realise I have probably not configured stty properly, and with some option-tweaking it is probably possible to get it right, but it's completely unclear. I ended up throwing it out the window and using pyserial instead. I should've done that weeks ago. The above STM32 code works fine and the required Python code is completely trivial.
#!/usr/bin/env python3
import serial
dev = serial.Serial("/dev/ttyUSB0", 921600)
dev.read(1) # wait for the signal
dev.write("Defend at noon\r\n".encode('utf-8'))
while True:
x = dev.read()
print(x.decode('utf-8'), end='', flush=True)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33544963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Dijit TabContainer tabs missing, serif fonts, all containers visible I have a small project I am doing, and am using Dojo for it. At the moment I can't get everything to load properly. I am trying to use the Tundra theme.
Essentially, the issue is that the TabContainer is missing tabs, has serif fonts instead of sans-serif, and shows all ContentPanes inside it instead of hiding ones in non-active tabs. The serif issue also applies to all other Dijit elements I try to create, however Dijit form elements seem to work a bit better (apart from font being incorrect, it has correct styling, and validation and other fancy stuff works fine).
The same issue appears when using the other Dijit themes, however the TabContainer border colour changes with each different theme which leads me to believe the Dijit theme may be loading correctly. Dojo seems to be correctly creating the Dijit elements though, looking at the Firebug output further below.
Complete copies of Dojo 1.3.2 dojo, dijit and dojox directories exist in js/dojo. All linked stylesheets and scripts are initially loading and the paths to them are correct (I've tested to confirm that with alert boxes in js and body colour changing in css).
index.html
<!DOCTYPE HTML>
<html>
<head>
<link href="js/dojo/dijit/themes/tundra/tundra.css" rel="stylesheet">
<script src="js/dojo/dojo/dojo.js"></script>
<script src="js/script.js"></script>
</head>
<body class="tundra">
<div id="xmldiv">
</div>
<script language="javascript">xmlEnableDiv('xmldiv');</script>
</body>
</html>
js/script.js
function xmlEnableDiv(div) {
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
var tc = new dijit.layout.TabContainer({
}, div);
var cp1 = new dijit.layout.ContentPane({
id: "xmleditor",
title: "Editor",
content: "This is where the editor will actually go"
});
tc.addChild(cp1);
var cp2 = new dijit.layout.ContentPane({
id: "xmltext",
title: "Source",
content: "This is where the source will actually go"
});
tc.addChild(cp2);
}
Checking Firebug, I see the following (which to my eyes looks like it should):
<body class="tundra">
<div id="xmldiv" class="dijitTabContainer dijitContainer dijitTabContainerTop dijitLayoutContainer" widgetid="xmldiv">
<div id="xmldiv_tablist" class="dijitTabContainerTop-tabs" dojoattachevent="onkeypress:onkeypress" wairole="tablist" role="tablist" widgetid="xmldiv_tablist"/>
<div class="dijitTabSpacer dijitTabContainerTop-spacer" dojoattachpoint="tablistSpacer"/>
<div class="dijitTabPaneWrapper dijitTabContainerTop-container" dojoattachpoint="containerNode" role="tabpanel">
<div id="xmleditor" class="dijitContentPane" title="" widgetid="xmleditor" role="group">This is where the editor will actually go</div>
<div id="xmltext" class="dijitContentPane" title="" widgetid="xmltext" role="group">This is where the source will actually go</div>
</div>
</div>
<script language="javascript">
xmlEnableDiv('xmldiv');
</script>
</body>
The actual output (in Firefox and Chrome) is a box (the TabContainer) with a themed border. There are no tabs on the TabContainer, and both of the ContentPanes are visible at the same time (both with serif fonts).
The things I've tried without avail:
*
*Doing a dojo.parser.parse() at the end of my init function
*Trying other Dijits. They act similarly in that they seem to partially load. Every Dijit has serif fonts instead of sans-serif, but form elements and dialog are both showing correctly apart from the incorrect font
Thanks in advance, this is driving me nuts.
A: The solution was to add startup after creating the TabContainer.
Thanks to this post: http://www.dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/tabcontainer-labels-not-rendering-when-created-programatically
tabContainer = new dijit.layout.TabContainer({
}, div);
tabContainer.startup();
A: Another possibility is that adding TabContainer to a hidden element can have missing tabs, as described above, even after calling startup. The solution to this is to ensure that the TabContainer receives the resize event. You can try this yourself by finding the ID of the tab container, and then executing this in the console:
dijit.byId('dijit_layout_TabContainer_0').resize();
If your tabs appear, then you have a resize problem. Ensure that the parent container handles/passes the resize event to the tab container child. For example:
resize: function() {
this.tabContainer.resize();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1269561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can not access contextVariables in decorator I have python decorator and I need pass contextVariable inside my decorator or as argument request_id in function
Step 1: Declare contextVariables and methods
_correlation_id_ctx_var: ContextVar[str] = ContextVar(CORRELATION_ID_CTX_KEY, default=None)
_request_id_ctx_var: ContextVar[str] = ContextVar(REQUEST_ID_CTX_KEY, default=None)
def get_correlation_id() -> str:
return _correlation_id_ctx_var.get()
def get_request_id() -> str:
return _request_id_ctx_var.get()
Step 2: The context Variable I declare inside middleware (use FastApi)
@app.middleware("http")
async def log_request(request: Request, call_next):
correlation_id = _correlation_id_ctx_var.set(request.headers.get('X-Correlation-ID', str(uuid4())))
request_id = _request_id_ctx_var.set(str(uuid4()))
Step3: I try to pass contextVariable to decorator - it always None
Try to pass as argument in function itself - it always None
What it the problem?
Why contextVars accessible in function body only and not in decorator or argument function?
Is there any solutions to have access to contextVar before function body?
@app.get('/test')
@decorator(request_id=get_request_id())
def test_purpose(request_id=get_request_id()):
print('get_correlation_id() start', get_request_id())
return 'ok'
Decorator:
def decorator(request_id=None, *args, **kwargs):
def logger(func, request_id=None, *args, **kwargs):
@wraps(func, *args, **kwargs)
def wrapper(*args, **kwargs):
try:
res = func()
print()
return res
except Exception:
pass
return wrapper
return logger
A: @decorator(request_id=get_request_id()) <- this line is executed when your module is imported. Which means your getter function is called only once, when the module is imported, not each time your decorated function is called.
To fix it, just pass the getter function, not its result, to the decorator, and make the call inside the wrapper function, inside the decorator. (For that, just leave the parentheses out):
def decorator(request_id_getter=None, *d_args, **d_kw):
def logger(func): # other arguments than the first positional arg here are not used at all.
@wraps(func, *d_args, **d_kw)
def wrapper(*args, **kwargs):
request_id = request_id_getter() # and here the value is retrieved when the function is actually called
try:
res = func()
print()
return res
except Exception:
pass
return wrapper
return logger
@app.get('/test')
@decorator(request_id=get_request_id) # <- here is the change - do not _call_ the function!
def test_purpose(request_id=get_request_id()):
print('get_correlation_id() start', get_request_id())
return 'ok'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70882688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sort simplexml object - without casting to array Is it possible to sort a simplexml object but keep the object as a simplexml object instead of casting to an array.
There doesnt appear to be a way to do this - and if casted to an array it seems very messy to transform the array(s) back to a simplexml object.
So -
Is it possible to sort a simplexml object by an attribute etc.
For example (sort by the position attribute node):
<test_nodes>
<node position="1"></node>
<node position="2"></node>
<node position="3"></node>
</test_nodes>
If not then what is the most painless and efficient way to cast an array to a simple xml object
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7470767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: redirect page with header with string My page cannot redirect to another page using header and below is the code
$v1 = "http://www.google.com";
header('Location: $v1');
instead it redirected to http://localhost/$v1
How can i achieve this type of syntax to redirect
A: Change single quote to double quotes. Note that variables inside the single quotes would not be parsed.
header("Location: $v1");
A: Wrong syntax. Try:
$url = "http://www.google.com/";
header("Location: $url");
// ^ ^
// You should use double quotes to expand variables.
A: This worked for me:
$v1 = "http://www.google.com";
header('Location:'. $v1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8654353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add Lodash debounce to react input? I have a simpel form:
https://codesandbox.io/s/distracted-poincare-2blfq?file=/src/App.js:357-552
<form>
<TextField
onChange={handleChange}
onBlur={clearInput}
value={inputValue}
placeholder="Do an api request"
/>
</form>
On the onChange I want to do an api request with the value of the input but I would like to add a debounce or throttle. Important is that when the input is blurred the text in the input should be removed and the placeholder should be visible.
A: Method 1.
Use React debounce input, simple method
https://www.npmjs.com/package/react-debounce-input
Method 2
Create timer and call API based on that, no external library needed. and i always suggest this
let timer = null
const handleChange = (e) => {
setInputValue(e.target.value)
if(timer) {
clearTimeout(timer)
}
timer = setTimeout(()=>yourApiCall(e.target.value), 700)
}
const yourApiCall = (val) => {
//call API here
}
<form>
<TextField
onChange={handleChange}
onBlur={clearInput}
value={inputValue}
placeholder="Do an api request"
/>
</form>
a working example
https://codesandbox.io/s/beautiful-goldberg-vyo2u?file=/src/App.js
Method 3
Use loadash debounce
check the answers from this link
Lodash debounce with React Input
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69756151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php variable in a echo string I'm customizing a wordpress for the first time so I'm pretty new with PHP langage and something is driving me crazy.
I wrote that function to transform my HTML5/CSS3/JQUERY layout into a CMS:
<?php $property = simple_fields_values("pillow_front");
foreach ($property as $value) {
echo "<div class='solo'>";
echo "<div class='box coussin'>";
echo "<div class='outImg'><img src='" . wp_get_attachment_url($value) . "'/></div>";
echo "</div>";
echo "</div>";
}
?>
But in the front-end it doesn't work and when I look at the code it appears that the img tag is not closed properly:
<div class="solo">
<div class="box coussin" style="width: 328px; height: 328px;">
<div class="outImg" style="opacity: 1;">
<img src="http://localhost:8888/wp-content/uploads/2014/01/021.jpg" style="width: 328px; height: 328px;">
</div>
</div>
</div>
I didn't really well understoud if the . in PHP was the exact equivalent of the + in javascript but I tried a lots of thing and I can get that tag to be properly closed !
Thank you
A: You can print in another system, something like this:
<?php
$property = simple_fields_values("pillow_front");
foreach ($property as $value) {
?>
<div class='solo'>
<div class='box coussin'>
<div class='outImg'><img src="<?php print wp_get_attachment_url($value);?>"/></div>
</div>
</div>
<?php
}
?>
Please note that i put the echo of the function only because i do not know how it works, it can be not necessary, use php only when needed.
A: Or just a bit more MVC-Pattern or in that case just MV? ;) Try this one without Wordpress.
<?php
//Init
$property = simple_fields_values("pillow_front");
$template = '<div class="solo">
<div class="box coussin">
<div class="outImg"><img src="{MARKER:FRONT}" /></div>
</div>
</div>';
foreach ($property as $value) {
echo str_replace(array('{MARKER:FRONT}'), array($value), $template);
}
?>
And as i know wordpress view, your code style is not confirm to WP-Styleguide. WP is using HTML/PHP Templating. In WP you view need to look like this.
<?php foreach(simple_fields_values("pillow_front") as $value): ?>
<div class='solo'>
<div class='box coussin'>
<div class='outImg'><img src="<?php echo htmlentities(value): ?>"/></div>
</div>
</div>
<?php endforeach; ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21021415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FTP username with | (pipe) in Windows batch file I'm trying to FTP files to a remote location. But here is the issue I'm facing.
When I use the below script, I'm able to login to the remote server but I'm not able to place any files over there, 550 access denied log prompt.
echo user domain/username> ftp.txt
echo password>> ftp.txt
echo cd remotepath>> ftp.txt
echo put FTPTest.txt>>ftp.txt
echo quit>> ftp.txt
ftp -n -s ftp.txt Servername>ftp_logs.txt
del ftp.txt
I tried to login via command prompt. I successfully Ftp'd, if the username is like Servername|domain/username.
I modified the script as below, script is not even executing.
echo user Servername|domain/username> ftp.txt
echo password>> ftp.txt
echo cd remotepath>> ftp.txt
echo put FTPTest.txt>>ftp.txt
echo quit>> ftp.txt
ftp -n -s ftp.txt Servername>ftp_logs.txt
del ftp.txt
Searching for clues...
A: You have to escape the |, as that has a special meaning in Windows:
echo user Servername^|domain/username> ftp.txt
The above will get you
user Servername|domain/username
in the ftp.exe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44133126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Binding a field to a reactive form does not show value If I hardcode the value to something like 'xxx' it is fine. But when I call a service and then try to bind the value nothing happens. I thought it was data bound so when the field is set it would show on the UI ?
<form [formGroup]="saveFileForm" (ngSubmit)="onExpSubmit()">
<div class="row" style="padding: 40px;">
<div class="col-md-6">
Notes:
</div>
<div class="col-md-6">
<input type="text" formControlName="Notes">
</div>
</div>
fileData: AttachmentVm = new AttachmentVm();
constructor(private service: AttachService,
private formBuilder: FormBuilder,
private router: Router,
public dialogRefSpinner: MatDialogRef<DialogRedirectToLandingSpinnerModule>,
public snackBar: MatSnackBar,
public dialog: MatDialog,
) { }
ngOnInit(): void {
this.saveFileForm = this.formBuilder.group({
PaymentDate: [''],
IsPaid: [false],
Notes: [this.fileData.GlobalNotes],
//Notes: ['xxx'],
FileDescription: ['']
});
if (this.formIdFromParent) {
this.service.getFiles(this.formIdFromParent).subscribe(result => {
this.fileData = result;
})
}
}
A: You need to update the form control value:
if (this.formIdFromParent) {
this.service.getFiles(this.formIdFromParent).subscribe(result => {
this.fileData = result;
this.formIdFromParent.controls['Notes'].setValue(this.fileData. GlobalNotes);
})
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64394470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: REDIS LIST MOVE recovery/rollback strategy I have the following scenario:
*
*Redis SENTINEL with one main REDIs and two replicas
*Redis Connection timeout configured to 30 seconds
*Lettuce's Java REDIS client
*Spring Data on top of Lettuce's REDIS client
I have a REDIS LIST which I am using as a QUEUE. As expected, each element on the queue must be processed by one and only one element processor. However, in some weird corner cases, I sometimes experience THIS:
-> BLMOVE A B 8
(*) I get a timeout here after 30 seconds
(this is, move from list A to list B and block for 8 seconds
The problem I have is that the ELEMENT actually moves from list A to list B and I still get the timeout, so after this exception the element gets lost in queue B and never gets processed. I understand that this might be a network issue with the REDIS CONNECTION.
My question is: What's the best way to handle cases like this? Is there a way to "recover" the unprocessed element and try again?
A: There are a few ways to solve this issue:
*
*Use a REDIS SENTINEL with failover capabilities. This way, if the primary REDIS instance goes down, the sentinel will automatically failover to the replica instance and your elements will not be lost.
*Use a REDIS CLUSTER. This will provide you with high availability and will ensure that your elements are not lost in the event of a failure.
*Use a REDIS Replication setup. This will provide you with a hot standby REDIS instance that can take over if the primary instance goes down.
*Use a REDIS Persistence setup. This will ensure that your elements are not lost in the event of a failure.
*Use a REDIS Backup setup. This will ensure that your elements are not lost in the event of a failure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72944310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: My own mini-framework is not compatible with some projects I failed to create a mini-library with some useful functions that I have found over the Internet, and I want to use them easily by just including a file to the HTML (like jQuery).
The problem is that some vars and functions share the same name and they are causing problems.
Is there a better solution to this instead of giving crazy names to the vars/funcs like "bbbb123" so the odds that someone is working with a "bbbb123" var is really low?
A: I would put all of your functions and variables into a single object for your library.
var MyLibrary = {
myFunc: function() {
//do stuff
},
myVar: "Foo"
}
There are a few different ways of defining 'classes' in JavaScript. Here is a nice page with 3 of them.
A: You should take one variable name in the global namespace that there are low odds of being used, and put everything else underneath it (in its own namespace).
For example, if I wanted to call my library AzureLib:
AzureLib = {
SortSomething: function(arr) {
// do some sorting
},
DoSomethingCool: function(item) {
// do something cool
}
};
// usage (in another JavaScript file or in an HTML <script> tag):
AzureLib.SortSomething(myArray);
A: You could put all of your library's functions inside of a single object. That way, as long as that object's name doesn't conflict, you will be good. Something like:
var yourLib = {};
yourLib.usefulFunction1 = function(){
..
};
yourLib.usefulFunction2 = function(){
..
};
A: Yes, you can create an object as a namespace. There are several ways to do this, syntax-wise, but the end result is approximately the same. Your object name should be the thing that no one else will have used.
var MyLibrary = {
myFunc: function() { /* stuff */ }
};
Just remember, it's object literal syntax, so you use label : value to put things inside it, and not var label = value;.
If you need to declare things first, use a wrapping function to enclose the environment and protect you from the global scope:
var MyLibrary = (function() {
var foo = 'bar';
return {
myFunc: function() { /* stuff */ }
};
})(); // execute this function right away to return your library object
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7957060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cordova: command not found after installing globally I try to install Cordova in macOS Mojave. I run the following command to install globally. It is installed successfully npm i -g cordova
but when I check the version using cordova --version , It gives me the error "cordova: command not found".
and also when I try to get the location using which cordova, It returns nothing.
A: Refer this great write up: http://blog.webbb.be/command-not-found-node-npm/
This can happen when npm is installing to a location that is not the standard and is not in your path.
To check where npm is installing, run: npm root -g
It SHOULD say /usr/local/lib/node_modules, If it doesn't then follow this:
Set it to the correct PATH:
*
*run: npm config set prefix /usr/local
*Then reinstall your npm package(s) with -g:
npm install -g cordova etc
If this doesn't work then try adding the global path of cordova(where it got installed) to your $PATH variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57881541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Regex to split the string into identical blocks I wanted to fetch the data an put it in the list from the below XML using regex in python as below
[['ip-address','1.1.1.1/16','protocol','ospf','ll',4],['ip-address','3.3.3.3/32','ip-addr','2.2.2.2','ip-addr','8.8.8.8','type',route]]
a=''' <att>
<rt>
<rts>
<ip-address>1.1.1.1/16</ip-address>
<bb>
<cc>
<protocol>ospf</protocol>
</cc>
</bb>
<ee>
<ff>
<ll>4</ll>
</ff>
</ee>
</rts>
<rts>
<ip-address>3.3.3.3/32</ip-address>
<bb>
<cc>
<ip-addr>2.2.2.2</ip-addr>
<ip-addr>8.8.8.8</ip-addr>
</cc>
</bb>
<ee>
<ff>
<type>route</type>
</ff>
</ee>
</rts>
<rt>
</att>'''
My approach was to divide the above single string into multiple string and then search, example
b= '''<rts>
<ip-address>1.1.1.1/16</ip-address>
<bb>
<cc>
<protocol>ospf</protocol>
</cc>
</bb>
<ee>
<ff>
<ll>4</ll>
</ff>
</ee>
</rts>'''
c= '''<rts>
<ip-address>3.3.3.3/32</ip-address>
<bb>
<cc>
<ip-addr>2.2.2.2</ip-addr>
<ip-addr>8.8.8.8</ip-addr>
</cc>
</bb>
<ee>
<ff>
<type>route</type>
</ff>
</ee>
</rts>'''
I used the following regex to create multiple string
regex = re.findall(r"<(rts)>.*<\ /rts)", a, re.S)
But it fetches all untill the end of string as below,
<rts>
<ip-address>1.1.1.1/16</ip-address>
<bb>
<cc>
<protocol>ospf</protocol>
</cc>
</bb>
<ee>
<ff>
<ll>4</ll>
</ff>
</ee>
</rts>
<rts>
<ip-address>3.3.3.3/32</ip-address>
<bb>
<cc>
<ip-addr>2.2.2.2</ip-addr>
<ip-addr>8.8.8.8</ip-addr>
</cc>
</bb>
<ee>
<ff>
<type>route</type>
</ff>
</ee>
</rts>
Is there a way I could be able to divide the string as "b" and "c" shown above?
A: With lxml and xpath you can parse xml much more easily than by rolling your own regex parser.
Here's an example:
import lxml
import StringIO
a =''' <att>
<rt>
<rts>
<ip-address>1.1.1.1/16</ip-address>
<bb>
<cc>
<protocol>ospf</protocol>
</cc>
</bb>
<ee>
<ff>
<ll>4</ll>
</ff>
</ee>
</rts>
<rts>
<ip-address>3.3.3.3/32</ip-address>
<bb>
<cc>
<ip-addr>2.2.2.2</ip-addr>
<ip-addr>8.8.8.8</ip-addr>
</cc>
</bb>
<ee>
<ff>
<type>route</type>
</ff>
</ee>
</rts>
</rt>
</att>'''
f = StringIO.StringIO(a)
tree = lxml.etree.parse(f)
rts = tree.xpath('//rts')
ipa = rts[0].xpath(".//ip-address")[0]
print ipa.text
This prints the first ip-address of the first rts tag, i.e. 1.1.1.1/16.
Note:
I needed to fix your xml, there was a / missing on the last rt tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40298671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: different screen.colorDepth value for firefox and opera/chrome I m testing a javascript in which i wrote this
document.write("\n\n\n\n"+screen.colorDepth);
switch(screen.colorDepth)
{
case 24: document.bgColor = "skyblue" ;
break;
case 32: document.bgColor = "yellow";
break;
default: document.bgColor = "white";
break;
}
but unfortunately Firefox 21.0 and IE9 is showing value 24 and thus background color is going skyblue
and opera( v12.01 Build 1532) and chrome(Version 27.0.1453.94 m) is showing 32 and thus the background is going yellow . I m using win 7 ultimate 32bit and my original color depth of screen is 32 bit. Can anyone plz explain why this is happening ?
A: I guess they are using different approaches interpreting the color precision. A 32-bit screen is in fact only 24-bit color (the 8 last bits is not part of the color space).
Mozilla defines it as:
Returns the color depth of the screen.
Chrome seem to read it directly from the system as-is, while FF and IE9 seem to correctly (based on that definition) identify the color precision (color depth) of the screen.
Please note that screen.colorDepth is not part of any standard and it's up to the implementers how it actually works.
The more correct way of checking color-precision in regards to color depth would therefor be:
case 16: document.bgColor = "..." ;
break;
case 24:
case 32: document.bgColor = "..."; //32 = 24 bit color depth + 8 bits alpha
break;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16930540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.