id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23529700
std::vector<int> v{0,1,2,3,4,5}; std::copy_n(v.begin(), 3, std::ostream_iterator<int>(std::cout, ":")); I can use the new C++20 ranges to take several ints from a vector putting them to standard output with | operator in a for loop, one value at a time using <<. for(int n : std::views::all(v) | std::views::take(3)) { std::cout << n << '/'; } How can I put the results of std::views::all(v) | std::views::take(3) to standard output w/o explicitly looping through values? Something like: std::views::all(v) | std::views::take(4) | std::ostream_iterator<int>(std::cout, " "); or std::cout << (std::views::all(v) | std::views::take(4)); A: The specific thing you're looking for is using the new ranges algorithms: std::ranges::copy(v | std::views::take(4), std::ostream_iterator<int>(std::cout, " ")); You don't need to use views::all directly, the above is sufficient. You can also use fmtlib, either directly: // with <fmt/ranges.h> // this prints {0, 1, 2, 3} fmt::print("{}\n", v | std::views::take(4)); or using fmt::join to get more control (this lets you apply a format string to each element in addition to specifying the delimiter): // this prints [00:01:02:03] fmt::print("[{:02x}]\n", fmt::join(v | std::views::take(4), ":"));
doc_23529701
What is the best way to persist that ArrayList? onSaveInstanceState only seems to support primitives and I've been unable to set up a case where onRetainNonConfigurationInstance actually gets called. So in onCreate, the XML data is loaded from the server ever time I switch to that Activity. I have made the models that are in the ArrayList implement Parcelable, so could use that in some way? A: What is the best way to persist that ArrayList? I don't see where your problem has anything to do with multiple activities. What happens if the user presses HOME (gasp!), for example? Your app will eventually be closed. Do you want to reload the data from the server? If the answer is "yes", then you don't need to "persist" anything, and onSaveInstanceState() may suffice (see below). If the answer is "no", then you need to rethink your approach to your data model, so you arrange to keep the data in a database, synchronizing with your Web service periodically, and probably dumping the ArrayList and replacing it with a Cursor. onSaveInstanceState only seems to support primitives If the answer to my HOME question is "yes", then you can just hold onto the data in a data member of your activity, and, if it is modestly sized, also stash it in the Bundle in onSaveInstanceState(). A Bundle can hold an ArrayList of Parcelable. However, if the data set is large (say, 100KB or more), you probably don't want to go this route and should consider the "no" path I described above. I've been unable to set up a case where onRetainNonConfigurationInstance actually gets called. Rotate the screen. There are other scenarios, but orientation changes are the easiest ones to trigger it. However, it has nothing to do with your problem. A: "onSaveInstanceState only seems to support primitives" onSaveInstanceState supports objects, as long as they are declared serializable. // ON_SAVE_INSTANCE_STATE // save instance data (5) on soft kill such as user changing phone orientation protected void onSaveInstanceState(Bundle outState){ password= editTextPassword.getText().toString(); try { ConfuseTextStateBuilder b= ConfuseTextState.getBuilder(); b.setIsShowCharCount(isShowCharCount); b.setTimeExpire(timeExpire); b.setTimeoutType(timeoutType); b.setIsValidKey(isValidKey); b.setPassword(password); state= b.build(); // may throw } catch(InvalidParameterException e){ Log.d(TAG,"FailedToSaveState",e); // will be stripped out of runtime } outState.putSerializable("jalcomputing.confusetext.ConfuseTextState", state); // save non view state super.onSaveInstanceState(outState); // save view state //Log.d(TAG,"onSaveInstance"); }
doc_23529702
this is the method I'm using register(BuildContext context) { http .post(Uri.parse('http://reqres.in/api/register'), body: _user) .then((value) { var valJson = json.decode(value.body); ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text("$valJson"))); if (valJson['error'] != null) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text("ERROR: ${valJson['error']}"))); } else { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text("Registered successfully"))); } }); } the error in this line: var valJson = json.decode(value.body); it shows that the body is empty! according to reqres.in this information should return no error { "email": "eve.holt@reqres.in", "password": "pistol" } and in my case, it should show Snackbar with a success message, but it the Snackbar is not showing up at all! I'm using this method inside a Form() widget Map<String, String> _user = {}; ... return Form( key: _formKey, child: Column( children: [ TextFormField( validator: (value) { _user['email'] = value.trim(); }, ), TextFormField( validator: (value) { _user['password'] = value.trim(); }, ), ElevatedButton( onPressed: () { _user['email'] = nameValue; _user['password'] = passValue; register(context); }, ) ], ), ); please help, thank you
doc_23529703
This is my code const app = require('./app'); const config = require('./config/config'); const logger = require('./config/logger'); let server; server = app.listen(config.port, config.host, () => { logger.info(`Listening to port ${config.port} on host ${config.host}`); }); app.get('/:sid/:ui', (req, res, next) => { console.log('OK') }) app.get('/url', (req, res, next) => { console.log('inside') res.append(config.host+":"+config.port+"/:sid/:ui") }) I am looking for result to be as http://127.0.0.1:3005/sid/ui When I hit the 2 url http://127.0.0.1:3005/url I get the following error TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["127.0.0.1:3005/:sid/:ui"] at ServerResponse.setHeader (node:_http_outgoing:578:3) at ServerResponse.header (C:\Users\wgupta\node_modules\express\lib\response.js:794:10) at ServerResponse.append (C:\Users\wgupta\node_modules\express\lib\response.js:755:15) at C:\Backend\temp1\src\index.js:14:7 A: Use res.send() instead of res.append() A: Syntax issue solved it using res.send(config.host+":"+config.port+"/sid/ui")
doc_23529704
I'd like to know how I can map my search response directly to my ViewModel class without any transforming in C#. I have an ElasticIndex called "PublicLegislationResult", and a ViewModel called "ViewEntities.PublicLegislationDetail" with a subset of the properties that exist in the ElasticSearch index. The properties in the ViewModel class are not necessarily the same as the ones in the main index. Ex: "ItemSubCategory"(index) => "SubCategory" (ViewModel) This search query works: ISearchResponse<PublicLegislationResult> searchResults; searchResults = await this.Client .SearchAsync<PublicLegislationResult>(s => this.GetPublicSearchDescriptor(s) .Query(q => q .Bool(b => b .Must(m => m.Match(mt => mt.Field(f => f.CalendarYear).Query(searchCriteria)))))); return searchResults; But I have to additionally transform the results to my ViewModel as such List<PublicLegislationResult> publiclegislationHitList = publicLegislationResult.Hits?.Select(t => t.Source).ToList(); fileDetailList = publiclegislationHitList?.Select(t => new ViewEntities.PublicLegislationDetail(){ ... }.ToList(); I have tried this: ISearchResponse<ViewEntities.PublicLegislationDetail> searchResults; searchResults = await this.Client .SearchAsync<ViewEntities.PublicLegislationDetail>(s => this.GetPublicSearchDescriptor(s) .Query(q => q .Bool(b => b .Must(m => m.Match(mt => mt.Field(f => f.CalendarYear).Query(searchCriteria)))))); return searchResults; This partially works (surprisingly) because the ViewModel object closely matches the index and NEST is able to map the properties with exact matching names, the rest are returned as NULL Hence my question: If NEST is able to do this much out-of-the-box, is there a way to explicitly map the properties of the index to my view model so that I can skip the transformation step completely? Any help figuring this out would be greatly appreciated, thanks! A: You can deserialize _source JSON documents in Elasticsearch to any POCO type to which the JSON property names and types map to POCO properties. NEST serializes POCO property names to camel case JSON properties by default, and attempts to match JSON properties to POCO properties by camel casing the POCO property names; if there's a match on name, it will attempt to assign the JSON value to the POCO property by using a registered JsonFormatter to deserialize the JSON type to a CLR type. If a property name will not match by convention, you can use attributes such as PropertyNameAttribute on the POCO property to indicate the name in JSON, or use fluent mapping to indicate the names.
doc_23529705
How do I go from here? g.append('g') .attr('class', 'axis') .attr('transform', 'translate(0,' + height + ')') .call(d3.axisBottom(x)); A: Put this is the CSS: .axis path, .axis line { fill: none; stroke: none; } Here is a demo: var svg = d3.select("svg"); var x = d3.scaleLinear().domain([1, 10]).range([10, 390]) svg.append('g') .attr('class', 'axis') .attr('transform', 'translate(0,50)') .call(d3.axisBottom(x)); .axis path, .axis line { fill: none; stroke: none; } <script src="https://d3js.org/d3.v4.min.js"></script> <svg width="400" height="80"></svg>
doc_23529706
module SomeStuff class Widget < ActiveRecord::Base; end end class WidgetsController < ApplicationController def create w = Widget.create(params) location = url_for w render :json => w, :location => location end end The problem is Rails wants a "some_stuff_widget_path" to exist and it doesn't because the controller is not namespaced. I tried the solutions given in another post (http://stackoverflow.com/questions/4404440/rails-url-for-and-namespaced-models) but they didn't seem to work. My models are technically in a separate gem which is namespaced and then my Rails app includes that gem and provides controllers. Without changing that setup, is there a way to get "url_for" to work? A: As mentioned in one of your comments above, you have resources :widgets in your config/routes.rb. In the location you're trying to set above with the url_for, you're trying to match the following route widget GET /widgets/:id(.:format) widgets#show But as you said, url_for w is instead causing rails to guess you're looking for the (non-existent) some_stuff_widget_path route. Instead change that line to location = url_for widget_path(w)
doc_23529707
I have created several branches which each branch have a new feature. -> Master -> Feature 1 -> Feature 2 ... -> Feature 80 I have an idea to create a simple web-page where the users can choose which features they want to include. Then I want to merge all selected features (branches) into the master and create a new repository on Github that the user can access. Does anybody have any ideas if this is possible using Github's features, have any other approach on this matter or do I have to code this manually myself? A: Your webapp could create a PR (Pull Request) through an GitHub API call, one PR per selected branch. Then the "enable auto-merge for PR" feature from GitHub would automatically merge each of those PR, provided there is no conflict. Or you can use the merge-pull-requests-automerge-action GitHub action.
doc_23529708
SELECT item, [2018-05]=CEILING(SUM(CASE WHEN New_Date = '2018-05' THEN Qty Else NULL END)), [2018-06]=CEILING(SUM(CASE WHEN New_Date = '2018-06' THEN Qty Else NULL END)), [2018-07]=CEILING(SUM(CASE WHEN New_Date = '2018-07' THEN Qty Else NULL END)), [2018-08]=CEILING(SUM(CASE WHEN New_Date = '2018-08' THEN Qty Else NULL END)), [2018-09]=CEILING(SUM(CASE WHEN New_Date = '2018-09' THEN Qty Else NULL END)), [2018-10]=CEILING(SUM(CASE WHEN New_Date = '2018-10' THEN Qty Else NULL END)), [2018-11]=CEILING(SUM(CASE WHEN New_Date = '2018-11' THEN Qty Else NULL END)), [2018-12]=CEILING(SUM(CASE WHEN New_Date = '2018-12' THEN Qty Else NULL END)), [2019-01]=CEILING(SUM(CASE WHEN New_Date = '2019-01' THEN Qty Else NULL END)), [2019-02]=CEILING(SUM(CASE WHEN New_Date = '2019-02' THEN Qty Else NULL END)), [2019-03]=CEILING(SUM(CASE WHEN New_Date = '2019-03' THEN Qty Else NULL END)), [2019-04]=CEILING(SUM(CASE WHEN New_Date = '2019-04' THEN Qty Else NULL END)), [2019-05]=CEILING(SUM(CASE WHEN New_Date = '2019-05' THEN Qty Else NULL END)), [2019-06]=CEILING(SUM(CASE WHEN New_Date = '2019-06' THEN Qty Else NULL END)), [2019-07]=CEILING(SUM(CASE WHEN New_Date = '2019-07' THEN Qty Else NULL END)), [2019-08]=CEILING(SUM(CASE WHEN New_Date = '2019-08' THEN Qty Else NULL END)), [2019-09]=CEILING(SUM(CASE WHEN New_Date = '2019-09' THEN Qty Else NULL END)), [2019-10]=CEILING(SUM(CASE WHEN New_Date = '2019-10' THEN Qty Else NULL END)), [2019-11]=CEILING(SUM(CASE WHEN New_Date = '2019-11' THEN Qty Else NULL END)), [2019-12]=CEILING(SUM(CASE WHEN New_Date = '2019-12' THEN Qty Else NULL END)), [2020-01]=CEILING(SUM(CASE WHEN New_Date = '2020-01' THEN Qty Else NULL END)), [2020-02]=CEILING(SUM(CASE WHEN New_Date = '2020-02' THEN Qty Else NULL END)) FROM dbo.A GROUP BY item ORDER BY item; However, as there are too many Year-Month columns, I'd like to make it dynamic uisng a variable similar to the following code and get all distinct year-month values from "New_Date" col and assign them to the variable "piv_col": DECLARE @piv_col NVARCHAR (250) SELECT DISTINCT @piv_col= New_Date FROM dbo.A However, the @piv_col only takes the last value of the col. Could you please help me how I can assign all distinct values to the variable and use that variable instead of year-month columns ([2018-05], [2018-06], etc.) to make the query work dynamically? I appreciate all your help!
doc_23529709
Hello, I'm working on a project in which the main part of the data has a complex structure as you can see in the above picture. Now, the object, in reality, is much complex than that but what I showed it servers the purpose. Because in DB they are linked together in tables relationship the first time when the website is launched, after log in, a list of projects will come together with some small details of technology and dataObjects. I created separated action and effects files but everything is handled by a single reducer. What I mean is at the start, the list of projects will be saved on a state, than any other actions like Create a project, technology, data object, edit, delete has to perform actions over the same state "projects-state". For example besides technologyAPIS will be another 3-4 technologies, inside each technology object will be another list of objects. The issue here is that the reducer file is getting bigger and bigger when it handles all kinds of actions that will perform actions over the specific data from the state. It is important that the chain of Objects stay together. My question is, is this a bad approach? it can be handled in a different way? I know I can create a reducer for each entity (project, technology, data app) but I will lose that relationship between them, where one belongs to the other? Thank you so much for your feature response A: I've only been doing reactive/NGRX for a few months now, but from my understanding, thats defiantly a bad approach. It should still work, but may be a hassle to debug/maintain. Ngrx seems to be promoting 'Normalising' data, just like the usual Relational Database concept. You could break down your project-state into smaller states, with relational keys in them. Example Projects state (not to be confused with project-state) * *id:number *projectDescription:string *createdBy:string *techAPIs:number[] //where the content here is the id of the TechApi TechApi state * *id:number *otherInfo:any And then when you need to access the TechApi state for a project, you retrieve it and filter/map it in a selector. This is a some what General Example if my explanation is not understandable.
doc_23529710
I've got the following code: // Bank Interest $res = $db->query(" SELECT uid, id, rm_days, bank FROM sys_users LEFT JOIN sys_users_stats ON sys_users.id = sys_users_stats.uid ") or die($db->error); while ($row = $res->fetch_object()) { $multiply = ($row->rm_days >= 1) ? 0.04 : 0.02; $interest = ($row->bank >= 15000000) ? ceil(15000000 * $multiply) : ceil($row->bank * $multiply); $res = $db->query("UPDATE sys_users_stats SET bank = bank + $interest"); $rjdRPG->addEvent($row->uid, "You have gained $$interest bank interest."); } Everything works ok, it even does send me the event in the game: You have gained $24 bank interest. 01 Dec 2015 09:20 PM Only SSH/Crontab is returning an error if I run it manually, (testing purposes) It's returning: PHP Fatal error: Call to a member function fetch_object() on a non-object in /home/RJDGaming/tm/crons/daily.php on line 22 But it is updating the bank column to the correct amount. And sends out a notification, so all seems ok, but i'm not sure how I should solve that PHP Fatal Error as everything is working fine. $db->error doesn't return anything, so i'm a bit lost here. A finger pointing in the right direction would be greatly appreciated. A: The problem is that you update $res in the loop: $res! while($row = $res->fetch_object()) { $multiply = ($row->rm_days >= 1) ? 0.04 : 0.02; $interest = ($row->bank >= 15000000) ? ceil(15000000 * $multiply) : ceil($row->bank * $multiply); $res! $res = $db->query("UPDATE sys_users_stats SET bank = bank + $interest"); $rjdRPG->addEvent($row->uid, "You have gained $$interest bank interest."); }
doc_23529711
I want result like: required - binary name, doc test name optional - doc name1, doc name2, doc name3 <?xml version="1.0" encoding="UTF-8"?> <test> <required> <item type="binary"> <name>binary name</name> <url visibility="restricted">test.exe</url> </item> <item type="document" subtype="mytype"> <name>doc test name</name> <url visiblity="visible">my.pdf</url> </item> </required> <optional> <item type="document"> <name>doc name1</name> <url visiblity="visible">user_guide1.pdf</url> </item> <item type="document2"> <name>doc name2</name> <url visiblity="visible">user_guide2.pdf</url> </item> <item type="document3"> <name>doc name3</name> <url visiblity="visible">user_guide3.pdf</url> </item> </optional> <dependencies> <dependency> <url>test4.xml</url> </dependency> </dependencies> </test> A: You can use the XML Parser or SimpleXML. $xml = new SimpleXMLElement($yourXml); A: SimpleXML with XPath: http://www.php.net/manual/en/simplexmlelement.xpath.php $xmlSrc =<<<XML <test> <required> <item type="binary"> <name>binary name</name> <url visibility="restricted">test.exe</url> </item> <item type="document" subtype="mytype"> <name>doc test name</name> <url visiblity="visible">my.pdf</url> </item> </required> <optional> <item type="document"> <name>doc name1</name> <url visiblity="visible">user_guide1.pdf</url> </item> <item type="document2"> <name>doc name2</name> <url visiblity="visible">user_guide2.pdf</url> </item> <item type="document3"> <name>doc name3</name> <url visiblity="visible">user_guide3.pdf</url> </item> </optional> <dependencies> <dependency> <url>test4.xml</url> </dependency> </dependencies> </test> XML; $xml = new SimpleXMLElement($xmlSrc); $required_names = $xml->xpath('/test/required/item/name'); $optional_names = $xml->xpath('/test/optional/item/name'); print_r($required_names); print_r($optional_names);
doc_23529712
I need to replace "\n\s*(\n)" with "$1". It seems that is not possible with short regex. So I wonder is it possible to write such macros? A: Netbeans macros cannot handle regex. Your regex/replace works for me so I would use replace in files for this operation. I suggest to use format source feature (ALT + SHIFT + F). It can simply solve your problem for java/javascript/json (and maybe other) source. You can define blank line policy via menu Tools -> Options -> Editor -> Formatting.
doc_23529713
Thank you so much
doc_23529714
A: You can start by reading: http://www.gpwiki.org/index.php/SDL:Tutorials:Using_SDL_with_OpenGL You will use SDL to create an OpenGL context within which you will do all of your OpenGL based rendering. By events do you mean user input? If so, then simply at the end of each frame/loop make use of SDL to check for input like so: int main( ) { ... while( running ) { ... update( ); draw( ); ... handleKeys( ); } return 0; } void handleKeys( ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYDOWN: //Check for event and act accordingly break; case SDL_KEYUP: //Check for event and act accordingly break; case SDL_MOUSEBUTTONDOWN: //Check for event and act accordingly break; default: break; } } } Obviously there are much more elegant and effective means of getting input but just wanted to show a simple example.
doc_23529715
I have tryed so many things now without success. I really hope some of you can help me out or maybe point me to a simular example. For example, if I put in four names in the textarea and then presses "Generate Notes", it should generate three notes where the first note should show up empty in both fields and the names will be put into the last two notes in random order. Like this: Textarea; name1 name2 name3 name4 The output will be like this: * *[empty,empty] *[name2,name3] [name1,name4] If I put in six names: name1 name2 name3 name4 name5 name6 The output would be like this: * *[empty,empty] *[empty,empty] [empty,empty] *[name2,name5] [name3,name1] [name4,name6] [empty,empty] The following fiddle has a none-functioning textarea added. It does has a "Generate Notes" button that right now manually adds notes. One session per click. It doesnt generate anything. Please take a look at this fiddle: jsfiddle.net/VJ94U/1140/ Any help or directions you are able to give me are much appreciated! Thank you in advance. A: Alright so you're looking for an algorithm that solve this situation. Here is a working example, now you need to adapt that to Angular thingies, let us know if you have problem with that. function graph(nbNames) { var nbLines = 0; while (Math.pow(2, nbLines) < nbNames) { nbLines ++; } for (var i=0; i<nbLines; i++) { var t = ''; for (var j=0; j<Math.pow(2, i); j++) { t += '[ '; for (var k=0; k<2; k++) { if (i === nbLines-1 && (j*2+k) < nbNames) { t += ' x '; } else { t += ' - '; } } t += " ]"; } console.log(t); } } And the output: graph(4) >> [ - - ] [ x x ][ x x ] graph(6) >> [ - - ] [ - - ][ - - ] [ x x ][ x x ][ x x ][ - - ] EDIT: And you can get your array of names from the textarea this way: var names = $(yourTextArea).val().split('\n'); var numberNames = names.length;
doc_23529716
What I want to be able to do is to remove the circled horizontal bars from the graph axes. Does anyone know how to do this? My current code is as below var p = new ExcelPackage(new FileInfo(fileName)); var openSheet = p.Workbook.Worksheets.First(); var scatterChart = openSheet.Drawings.AddChart("Worm Calc", eChartType.XYScatter); scatterChart.Series.Add(openSheet.Cells["E3:E103"], openSheet.Cells["F3:F103"]); scatterChart.Legend.Remove(); scatterChart.XAxis.LogBase = 10; scatterChart.YAxis.LogBase = 10; scatterChart.XAxis.RemoveGridlines(true, true); //does not help scatterChart.XAxis.RemoveGridlines(); //does not help scatterChart.Title.Text = "Worm Calc"; scatterChart.SetPosition(2, 0, 7, 0); scatterChart.SetSize(350, 350); p.SaveAs(new FileInfo(fileName)); A: The method RemoveGridLines() will not do it as it was designed to remove the horizontal and vertical lines of the chart (I know, I wrote it :) ). You are looking to remove the Tick Marks. You only circled some of them on each axis but I assume you actually want to remove ALL of them. To do that: scatterChart.XAxis.MajorTickMark = eAxisTickMark.None; scatterChart.XAxis.MinorTickMark = eAxisTickMark.None; scatterChart.YAxis.MajorTickMark = eAxisTickMark.None; scatterChart.YAxis.MinorTickMark = eAxisTickMark.None; If you are looking to remove ONLY those that are circled, AFAIK, excel (nothing to do with EPPlus) cannot do that. It is all or nothing.
doc_23529717
julia> using HTTP, XLSX, DataFrames, GZip julia> file = HTTP.get("http://www.tsetmc.com/tsev2/excel/IntraDayPrice.aspx?i=35425587644337450&m=30") julia> write("c:/users/shayan/desktop/file.xlsx.gz", file.body); julia> df = GZip.open("c:/users/shayan/desktop/file.xlsx.gz", "r") do io XLSX.readxlsx(io) end But this throws a MethodError: ERROR: MethodError: no method matching readxlsx(::GZipStream) Closest candidates are: readxlsx(::AbstractString) at C:\Users\Shayan\.julia\packages\XLSX\FFzH0\src\read.jl:37 Stacktrace: [1] (::var"#23#24")(io::GZipStream) @ Main c:\Users\Shayan\Documents\Python Scripts\test.jl:15 [2] gzopen(::var"#23#24", ::String, ::String) @ GZip C:\Users\Shayan\.julia\packages\GZip\JNmGn\src\GZip.jl:269 [3] open(::Function, ::Vararg{Any}) @ GZip C:\Users\Shayan\.julia\packages\GZip\JNmGn\src\GZip.jl:265 [4] top-level scope @ c:\Users\Shayan\Documents\Python Scripts\test.jl:14 A: XLSX.jl does not work on streams. So you would need to ungzip the file to some temporary location and then read it. tname = tempname() * ".xlsx" GZip.open("c://temp//journals.xlsx.gz", "r") do io open(tname, "w") do out write(out, read(io)) end end df = XLSX.readxlsx(tname)
doc_23529718
I need sth like this: COL1-(PK) | COL2-(some int value) | COL3-max(COL2) 1 0 3 1 3 3 1 2 3 2 10 15 2 7 15 2 15 15 A: select col1, col2, (select max(col2) from tablename t2 where t1.col1 = t2.col1) from tablename t1 A correlated sub-select is used to get each col1's max col2 value. A: Use window functions: select col1, col2, max(col2) over (partition by col1) as col3 from table t; This is what these functions are designed for. By the way, your code seems to suggest that col1 is a primary key. Primary keys are not duplicated, so this is not a primary key. A: GROUP BY SELECT COL1, MAX(COL2) AS MAX FROM table GROUP BY COL1
doc_23529719
I have a UIPageViewController and I want to test it with Calabash. I've tried using Then I swipe right which didn't work with UIScrollView or PageView. Then I found this which worked with UIScrollView but still nothing with PageView. Then /^I swipe pageView to the (left|right|up|down)$/ do |direction| scrollViews = query("scrollView") scroll("scrollView index:0", direction) sleep(STEP_PAUSE) # optional end Then I swipe to the right I can't figure out how to get this working for UIPageViewController. If anybody has any insight to this it would be great! Thanks for the help! A: Apparently this is an apple bug. this is the workaround Then do right scroll("scrollView index:0", right) sleep(STEP_PAUSE) end however swiping only works now in portrait orientation in ios 7 (another bug) A: Use this code : scroll("tableView", :right) or If you are not sure about view then just use : scroll("*", :right) Or the easiest way to use is swipe : swipe "right" At last give a try to : You could try using performAction('drag',x1,x2,y1,y2,speed) Where x1 is the horizontal percentage of the screen you want to start at, x2 is the horizontal percentage of the screen you want to end at, y1 is the vertical percentage of the screen you want to start at, y2 is the vertical percentage of the screen you want to end at, and speed is the speed of the drag. The smaller the number, the faster the drag. For your purposes, for example, swiping left to go to the next screen would be something like performAction('drag',99,1,50,50,5) If still you face the issue , comment below
doc_23529720
scp username@host.com:/dir/of/file.txt \local\dir\ It looks like it was successful, but it only ends up creating a new folder labeled 'localdir' in the remote directory /dir/of/. How can I copy the file to my local computer over SSH? A: Make sure the scp command is available on both sides - both on the client and on the server. BOTH Server and Client, otherwise you will encounter this kind of (weird)error message on your client: scp: command not found or something similar even though though you have it all configured locally. A: Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r. So here in your case it'd be something like local> scp -r username@host.com:/path/to/dir local/path If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files. A: It depends on what your local OS is. If your local OS is Unix-like, then try: scp username@remoteHost:/remote/dir/file.txt /local/dir/ If your local OS is Windows ,then you should use pscp.exe utility. For example, below command will download file.txt from remote to D: disk of local machine. pscp.exe username@remoteHost:/remote/dir/file.txt d:\ It seems your Local OS is Unix, so try the former one. For those who don't know what pscp.exe is and don't know where it is, you can always go to putty official website to download it. And then open a CMD prompt, go to the pscp.exe directory where you put it. Then execute the command as provided above EDIT if you are using Windows OS above Windows 10, then you can use scp directly from its terminal, just like how Unix-like OS does. Thanks to @gijswijs @jaunt @icanfathom A: You need to name the file in both directory paths. scp username@host.com:/dir/of/file.txt \local\dir\file.txt A: that scp command must be issued on the local command-line, for putty the command is pscp. C:\something> pscp username@host.com:/dir/of/file.txt \local\dir\
doc_23529721
How would I go about colouring the black lines individually, or adding floating labels? Cheers! vpspec=frq1.*spectrumb; figure(4) semilogx(frq1,vpspec); xlim([frq1(1),0.5]); hold on; top=max(get(gca,'ylim')); semilogx([K1 inertial, M2;K1 inertial,M2],[0 top],'color','k','LineStyle','-'); grid on hold off; legend xlabel("Frequency (Cycles/Hour)"); ylabel("Spectral Power"); title("Variance Preserving Spectra from windowed time series"); print -dpng variance_preserving_deception_spectra Averaged spectra for windowed time series, with lines depicting the K1 and M2 tide respectively. I tried adding legend("K1","M2"), but to no avail. I can edit the legend for the wave form, but it's the two black lines that I need to distinguish. All attempts to modify the semilogx line return an error.
doc_23529722
Example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When I call registerReceiver() for that action with a null BroadcastReceiver — I get the Intent that was last Broadcast for that action. Whenever I find the last value by: //In Activity val batteryIntent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)); //sticky val level = batteryIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); val scale = batteryIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1); This Intent: AudioManager.ACTION_HEADSET_PLUG works too, but some Intents don't work: LocationManager.MODE_CHANGED_ACTION, Intent.ACTION_POWER_CONNECTED BluetoothDevice.ACTION_ACL_CONNECTED, ... I know, some don't make sense, but result of these Intents are always null, even if there has been a change, why? For ACTION_BATTERY_CHANGED there is information: "This is a sticky broadcast ..." in doc, but for ACTION_HEADSET_PLUG no. Is exist any restriction or split to sticky / non-sticky or list which Intents work as sticky? Why do some Intents work and others don't? Thank you. A: Where can I find information which Intent/Broadcast can be sticky? Look at the source code for the Android version of interest, searching for sendStickyBroadcast(). Is exist any restriction or split to sticky / non-sticky or list which Intents work as sticky? Sticky broadcasts are sent using sendStickyBroadcast(). Technically, it is not tied to a specific Intent.
doc_23529723
this is my code below for getting the images. $sql = $conn->prepare("SELECT * FROM ewsc_picture_gallery WHERE ewsc_picture_gallery_folder = '".$_GET['gallery']."'"); $sql->execute(); $result = $sql->get_result(); $numrows = $result->num_rows; if ($numrows==1){ while($show = mysqli_fetch_array($result)){ $ewsc_picture_gallery_id = $show['ewsc_picture_gallery_id']; $ewsc_picture_gallery_title = $show['ewsc_picture_gallery_title']; $ewsc_picture_gallery_folder = $show['ewsc_picture_gallery_folder']; } } else { $error = "<div class=\"label label-danger\">FATAL ERROR!! This page will restart your machine. Please close this page.</div>"; } $sql->close(); $conn->close(); the below code is for displaying the images in a gallery on the web page. <div id="HomeSlider"> <!-- #region Jssor Slider Begin --> <!-- Generated by Jssor Slider Maker. --> <!-- This demo works without jquery library. --> <script type="text/javascript" src="../../homeslider/jssor.slider.min.js"></script> <!-- use jssor.slider.debug.js instead for debug --> <script type="application/javascript" src="../../homeslider/jssorslider.js"> </script> <div id="jssor_1" class="SliderContainer"> <div data-u="slides" class="TheSlides"><!-- BEGINNING OF SLIDES --> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/1.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/1.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/2.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/2.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/3.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/3.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/4.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/4.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/5.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/5.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/6.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/6.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/7.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/7.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/8.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/8.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/9.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/9.jpg" /></a> </div> <div data-p="225.00" style="display: none;"> <a href="<?php echo $ewsc_picture_gallery_folder;?>/10.jpg" target="_blank"><img data-u="image" src="<?php echo $ewsc_picture_gallery_folder;?>/10.jpg" /></a> </div> </div><!-- END OF SLIDES --> <!-- Bullet Navigator --> <div data-u="navigator" class="jssorb05" style="bottom:60px;right:16px;" data-autocenter="1"> <!-- bullet navigator item prototype --> <div data-u="prototype" style="width:16px;height:16px;"></div> </div> </div> <script> jssor_1_slider_init(); </script> <!-- #endregion Jssor Slider End --> </div>
doc_23529724
server: windows 10 PC client: Android 7.1 linux version 4.4.63 testing in 5 ghz network... Is there any options left over to try. timers below added shows that more time is consumed in kernel_recvmsg. even perf tool calls shows more time is consumed in kenrel_recvmsg. t_usb.rx_rcv_start = ktime_get(); while (total_rcvd < length && total_rcvd >= 0 && !kthread_should_stop()) { kvec.iov_base = tcp_recv_buf+data_rcvd; kvec.iov_len = length-data_rcvd; data_rcvd = kernel_recvmsg(tcp_socket->socket, msg, &kvec, 1, length - total_rcvd, MSG_WAITALL); if (data_rcvd > 0) { total_rcvd += data_rcvd; } else { vfree(tcp_recv_buf); return data_rcvd; } } t_usb.rx_start = t_usb.rx_rcv_end=ktime_get();
doc_23529725
A sample string is: info = "name: joe", "name: jerry", "name: kate" Here is what I'm doing: import re string = 'info = "name: joe", "name: jerry", "name: kate"' array = re.findall(r'"(.*?)"', string) for x in array: x = x.replace(" ","") #remove spaces because there might be space before colon occasionally print(x.split("name:")[1]) The output prints: joe jerry kate I am just wondering if there is any easier way to do this and return the same output than what I did. A: Try: res=list(re.findall(r'\"name: ([^\"]+)"', string)) print(res) 2 important things - you extract only a group, hence the square brackets, and you define a name as set of one or more characters, that aren't double quotes ", since regex is on default greedy (i.e. matches the longest match only). Outputs: ['joe', 'jerry', 'kate'] A: You can embed the name: pattern in the regex, account for the occasional space before the colon via \s* and also match one or more spaces after colon and the actual name (where you are splitting from): re.findall(r'"name\s*:\s+(.*?)"', string) # ['joe', 'jerry', 'kate']
doc_23529726
public static class Database { public static bool HasAccess(string userId, string documentId) { return true; } } Now it's quite easy to have someone key documentId instead of userId and vice versa. One could prevent that by abstracting the data type of the arguments: public class UserId { public string Value { get; internal set; } public static implicit operator string(UserId id) { return id.Value; } } public class DocumentId { public string Value { get; internal set; } public static implicit operator string(DocumentId id) { return id.Value; } } public static class Database { public static bool HasAccess(UserId userId, DocumentId documentId) { return true; } } This way you get a nice compiler warning if you type in arguments out of order: UserId e = new UserId() { Value = "a" }; DocumentId d = new DocumentId() { Value = "b" }; Database.HasAccess(d, e); You also get the ability to change abstracted type in without affecting the rest of the system but that's not very likely. Would abstracting type be a good idea to get more type safety? The question relates to C# solutions but short descriptions in other languages is welcome. EDIT: Removed the implicit cast from string and pointing finger at the C# tag. A: I think you answered your own question - better data integrity and validation, better system A: Interesting, but I suspect that in many cases (particularly seialization / RPC APIs) this will only add confustion/overhead. Also - a minor implementation detail, but given this approach I'd make the wrappers fully immutable, not just "internal set" immutable. TBH - I'd probably rather use unit tests for most of this... sometimes simple is beautiful. The other problem is that since you have implicit operators, it won't stop you doing the much more likely: string user = "fred"; SomeMethodThatWantsADocument(user); That should compile; the implicit operator undoes all your good work... A: This is where typedef becomes useful in C++. You can have UserID and DocumentID as typedeffed types and thus are not interchangable without a cast, but don't require anything more than a quick note to the compiler saying 'this should be a separate type distinct from other types even though it is really just type X'. A: In this case, it doesn't look worth it to me. You've added 12 lines, spread across two extra-classes. In some languages you're looking at having to manage two new files for that. (Not sure in C#). You've introduced a lot of extra cognitive load. Those classes appear whenever you navigate your class-list; they appear in your automatically generated documentation; they're there as something that newcomers to your codebase see whenever they're trying to learn their way around, they're in the dependency graph of the compiler etc. Programmers have to know the types and create two new objects whenever they call HasAccess. And for what? To prevent you accidentally mixing up the username and document id when checking if someone has a right to access the database. That check should probably be written two, maybe three times in a normal system. (If you're writing it a lot you probably haven't got enough reuse in your database access code) So, I'd say that this is excess astronautics. My rule of thumb is that classes or types should encapsulate variant behaviour, not variant use of passive data. A: Yes, it is sometimes a good idea. But if you get too obsessed with this you become an architecture astronaut. As regards the type safety argument - it does increase type safety but lots of languages manage fine without it. In my opinion the best way to go is leave it as a String to start with, and then when you find yourself reusing the interface, make the refactoring to a more abstract type at that point. Predicting the future is too hard to waste time trying. A: Seems to be a lot of overhead for something your unit tests ought to prevent anyway, at least in this case. A: What you don't ask and don't answer are the questions that best determine if the new types are important: * *What is the projected, realistic lifetime of this system? If the answer is 2+ years, you should have at least one level of abstraction for the database and for the user id. In other words, your database should be abstract and your user and credentials should be abstract. Then you implement your database and userid in terms of the abstract definition. That way, if the needs should change your changes will be local to the places that need it most. *What are the gains and losses from having a userid data type? This question should be answered in terms of usability, expressiveness, and type safety. The number of created classes or extra lines are largely immaterial if there are clear gains in usability and expressiveness - hooray, you win. Let me give you an example of a clear loss - I worked with a class hierarchy that contained an abstract base class with several concrete children types. Rather than provide constructors for the child classes and appropriate accessors, they made a factory method that took an XML string or stream as an argument and constructed the appropriate concrete class from that. It was such a loss in usability that it made this library painful - even their sample code reeked of lose. While I could construct everything they offered, it felt heinous and generated runtime instead of compile time errors for typical issues. A: While at the end of the day, you may not care, the more abstraction the harder the maintenance (especially for other people). If in six months you have to start digging through this code to find or fix a bug, or even add a new feature, it will take you that much longer to remember what you did and why. If someone else is doing it, multiply that time. Elegant code is always nice when you're writing new code, but I always like to weigh that with the needs of maintainers down the road. A: This feels like a YAGNI issue to me. If you're just doing it because it MIGHT be useful, that's usually not a good enough reason for the extra complexity. Also, as others have noted, this is the sort of thing that unit tests should catch. Another thing I try to keep in mind is whether an abstraction is meant to protect programmers from themselves. Yes, it is theoretically easy to flip-flop two string arguments. But in all seriousness, paying attention to argument ordering has been a fundamental aspect of programming in most languages for decades. It's not something that should happen often, and it's certainly something that tests should be catching. If this type of thing is a common problem in your organization, I'd say you have bigger problems to worry about.
doc_23529727
I want to replace \n with an HTML break and want to display it as below: I recommended Garden Solutions for this Tender Contracting on the basis of 1)Top Scorer for tender 2)Professional Experience in Building Services 3)Approved Service Providers I am using JavaScript's replace function var val = recommend.replace("\n","<br>"); But it's not working. A: Use a regular expression (RegExp) literal and the "global" (g) modifier: var val = recommend.replace(/\n/g, "<br />"); Or use a RegExp directly: var val = recommend.replace(RegExp("\n","g"), "<br>"); A: By using the RegExp "\n" you just replace the first occurrence. To replace all occurrences you need to add RegExp the modifier g. So use the following, instead, to replace all occurrences: var val = recommend.replace( new RegExp( "\n", "g" ),"<br>"); Demo fiddle here.
doc_23529728
auth_method: odbc ## MySQL server: odbc_type: mysql odbc_server: "localhost" odbc_database: "chat" odbc_username: "admin" odbc_password: "admin" ## If you want to specify the port: odbc_port: 3306 modules ... mod_mam: db_type: odbc Full ejabberd.yml ### ###' ejabberd configuration file ### ### ### The parameters used in this configuration file are explained in more detail ### in the ejabberd Installation and Operation Guide. ### Please consult the Guide in case of doubts, it is included with ### your copy of ejabberd, and is also available online at ### http://www.process-one.net/en/ejabberd/docs/ ### The configuration file is written in YAML. ### Refer to http://en.wikipedia.org/wiki/YAML for the brief description. ### However, ejabberd treats different literals as different types: ### ### - unquoted or single-quoted strings. They are called "atoms". ### Example: dog, 'Jupiter', '3.14159', YELLOW ### ### - numeric literals. Example: 3, -45.0, .0 ### ### - quoted or folded strings. ### Examples of quoted string: "Lizzard", "orange". ### Example of folded string: ### > Art thou not Romeo, ### and a Montague? ###. ======= ###' LOGGING ## ## loglevel: Verbosity of log files generated by ejabberd. ## 0: No ejabberd log at all (not recommended) ## 1: Critical ## 2: Error ## 3: Warning ## 4: Info ## 5: Debug ## loglevel: 4 ## ## rotation: Describe how to rotate logs. Either size and/or date can trigger ## log rotation. Setting count to N keeps N rotated logs. Setting count to 0 ## does not disable rotation, it instead rotates the file and keeps no previous ## versions around. Setting size to X rotate log when it reaches X bytes. ## To disable rotation set the size to 0 and the date to "" ## Date syntax is taken from the syntax newsyslog uses in newsyslog.conf. ## Some examples: ## $D0 rotate every night at midnight ## $D23 rotate every day at 23:00 hr ## $W0D23 rotate every week on Sunday at 23:00 hr ## $W5D16 rotate every week on Friday at 16:00 hr ## $M1D0 rotate on the first day of every month at midnight ## $M5D6 rotate on every 5th day of the month at 6:00 hr ## log_rotate_size: 10485760 log_rotate_date: "" log_rotate_count: 1 ## ## overload protection: If you want to limit the number of messages per second ## allowed from error_logger, which is a good idea if you want to avoid a flood ## of messages when system is overloaded, you can set a limit. ## 100 is ejabberd's default. log_rate_limit: 100 ## ## watchdog_admins: Only useful for developers: if an ejabberd process ## consumes a lot of memory, send live notifications to these XMPP ## accounts. ## ## watchdog_admins: ## - "admin@jabber.local" ###. =============== ###' NODE PARAMETERS ## ## net_ticktime: Specifies net_kernel tick time in seconds. This options must have ## identical value on all nodes, and in most cases shouldn't be changed at all from ## default value. ## ## net_ticktime: 60 ###. ================ ###' SERVED HOSTNAMES ## ## hosts: Domains served by ejabberd. ## You can define one or several, for example: ## hosts: ## - "example.net" ## - "example.com" ## - "example.org" ## hosts: - "jabber.local" ## ## route_subdomains: Delegate subdomains to other XMPP servers. ## For example, if this ejabberd serves example.org and you want ## to allow communication with an XMPP server called im.example.org. ## ## route_subdomains: s2s ###. =============== ###' LISTENING PORTS ## ## listen: The ports ejabberd will listen on, which service each is handled ## by and what options to start it with. ## listen: - port: 5222 module: ejabberd_c2s certfile: "/home/administrador/ejabberd/conf/server.pem" starttls: true ## To enforce TLS encryption for client connections, ## use this instead of the "starttls" option: ## starttls_required: true ## ## Custom OpenSSL options ## protocol_options: - "no_sslv3" ## - "no_tlsv1" max_stanza_size: 65536 shaper: c2s_shaper access: c2s - port: 5269 module: ejabberd_s2s_in max_stanza_size: 131072 shaper: s2s_shaper ## ## ejabberd_service: Interact with external components (transports, ...) ## ## - ## port: 8888 ## module: ejabberd_service ## access: all ## shaper_rule: fast ## ip: "127.0.0.1" ## hosts: ## "icq.example.org": ## password: "secret" ## "sms.example.org": ## password: "secret" ## ## ejabberd_stun: Handles STUN Binding requests ## ## - ## port: 3478 ## transport: udp ## module: ejabberd_stun ## ## To handle XML-RPC requests that provide admin credentials: ## ## - ## port: 4560 ## module: ejabberd_xmlrpc ## maxsessions: 10 ## timeout: 5000 ## access_commands: ## admin: ## commands: all ## options: [] - port: 5280 module: ejabberd_http request_handlers: "/websocket": ejabberd_http_ws ## "/pub/archive": mod_http_fileserver web_admin: true http_bind: true register: true captcha: false ###. ================== ###' S2S GLOBAL OPTIONS ## ## s2s_use_starttls: Enable STARTTLS + Dialback for S2S connections. ## Allowed values are: false optional required required_trusted ## You must specify a certificate file. ## ## s2s_use_starttls: optional ## ## s2s_certfile: Specify a certificate file. ## ## s2s_certfile: "/home/administrador/ejabberd/conf/server.pem" ## Custom OpenSSL options ## ## s2s_protocol_options: ## - "no_sslv3" ## - "no_tlsv1" ## ## domain_certfile: Specify a different certificate for each served hostname. ## ## host_config: ## "example.org": ## domain_certfile: "/home/administrador/ejabberd/conf/example_org.pem" ## "example.com": ## domain_certfile: "/home/administrador/ejabberd/conf/example_com.pem" ## ## S2S whitelist or blacklist ## ## Default s2s policy for undefined hosts. ## ## s2s_access: s2s ## ## Outgoing S2S options ## ## Preferred address families (which to try first) and connect timeout ## in milliseconds. ## ## outgoing_s2s_families: ## - ipv4 ## - ipv6 ## outgoing_s2s_timeout: 10000 ###. ============== ###' AUTHENTICATION ## ## auth_method: Method used to authenticate the users. ## The default method is the internal. ## If you want to use a different method, ## comment this line and enable the correct ones. ## auth_method: internal ## ## Store the plain passwords or hashed for SCRAM: ## auth_password_format: plain ## auth_password_format: scram ## ## Define the FQDN if ejabberd doesn't detect it: ## fqdn: "server3.example.com" ## ## Authentication using external script ## Make sure the script is executable by ejabberd. ## ## auth_method: external ## extauth_program: "/path/to/authentication/script" ## ## Authentication using ODBC ## Remember to setup a database in the next section. ## ## auth_method: odbc ## ## Authentication using PAM ## ## auth_method: pam ## pam_service: "pamservicename" ## ## Authentication using LDAP ## ## auth_method: ldap ## ## List of LDAP servers: ## ldap_servers: ## - "localhost" ## ## Encryption of connection to LDAP servers: ## ldap_encrypt: none ## ldap_encrypt: tls ## ## Port to connect to on LDAP servers: ## ldap_port: 389 ## ldap_port: 636 ## ## LDAP manager: ## ldap_rootdn: "dc=example,dc=com" ## ## Password of LDAP manager: ## ldap_password: "******" ## ## Search base of LDAP directory: ## ldap_base: "dc=example,dc=com" ## ## LDAP attribute that holds user ID: ## ldap_uids: ## - "mail": "%u@mail.example.org" ## ## LDAP filter: ## ldap_filter: "(objectClass=shadowAccount)" ## ## Anonymous login support: ## auth_method: anonymous ## anonymous_protocol: sasl_anon | login_anon | both ## allow_multiple_connections: true | false ## ## host_config: ## "public.example.org": ## auth_method: anonymous ## allow_multiple_connections: false ## anonymous_protocol: sasl_anon ## ## To use both anonymous and internal authentication: ## ## host_config: ## "public.example.org": ## auth_method: ## - internal ## - anonymous ###. ============== ###' DATABASE SETUP ## ejabberd by default uses the internal Mnesia database, ## so you do not necessarily need this section. ## This section provides configuration examples in case ## you want to use other database backends. ## Please consult the ejabberd Guide for details on database creation. ## MySQL server: odbc_type: mysql odbc_server: "localhost" odbc_database: "chat" odbc_username: "admin" odbc_password: "admin" ## If you want to specify the port: odbc_port: 3306 ## ## PostgreSQL server: ## ## odbc_type: pgsql ## odbc_server: "server" ## odbc_database: "database" ## odbc_username: "username" ## odbc_password: "password" ## ## If you want to specify the port: ## odbc_port: 1234 ## ## If you use PostgreSQL, have a large database, and need a ## faster but inexact replacement for "select count(*) from users" ## ## pgsql_users_number_estimate: true ## ## SQLite: ## ## odbc_type: sqlite ## odbc_database: "/home/administrador/ejabberd/database/ejabberd.db" ## ## ODBC compatible or MSSQL server: ## ## odbc_type: odbc ## odbc_server: "DSN=ejabberd;UID=ejabberd;PWD=ejabberd" ## ## Number of connections to open to the database for each virtual host ## ## odbc_pool_size: 10 ## ## Interval to make a dummy SQL request to keep the connections to the ## database alive. Specify in seconds: for example 28800 means 8 hours ## ## odbc_keepalive_interval: undefined ###. =============== ###' TRAFFIC SHAPERS shaper: ## ## The "normal" shaper limits traffic speed to 1000 B/s ## normal: 1000 ## ## The "fast" shaper limits traffic speed to 50000 B/s ## fast: 50000 ## ## This option specifies the maximum number of elements in the queue ## of the FSM. Refer to the documentation for details. ## max_fsm_queue: 1000 ###. ==================== ###' ACCESS CONTROL LISTS acl: ## ## The 'admin' ACL grants administrative privileges to XMPP accounts. ## You can put here as many accounts as you want. ## admin: user: - "admin": "jabber.local" ## ## Blocked users ## ## blocked: ## user: ## - "baduser": "example.org" ## - "test" ## Local users: don't modify this. ## local: user_regexp: "" ## ## More examples of ACLs ## ## jabberorg: ## server: ## - "jabber.org" ## aleksey: ## user: ## - "aleksey": "jabber.ru" ## test: ## user_regexp: "^test" ## user_glob: "test*" ## ## Loopback network ## loopback: ip: - "127.0.0.0/8" ## ## Bad XMPP servers ## ## bad_servers: ## server: ## - "xmpp.zombie.org" ## - "xmpp.spam.com" ## ## Define specific ACLs in a virtual host. ## ## host_config: ## "localhost": ## acl: ## admin: ## user: ## - "bob-local": "localhost" ###. ============ ###' ACCESS RULES access: ## Maximum number of simultaneous sessions allowed for a single user: max_user_sessions: all: 10 ## Maximum number of offline messages that users can have: max_user_offline_messages: admin: 5000 all: 1000 ## This rule allows access only for local users: local: local: allow ## Only non-blocked users can use c2s connections: c2s: blocked: deny all: allow ## For C2S connections, all users except admins use the "normal" shaper c2s_shaper: admin: none all: normal ## All S2S connections use the "fast" shaper s2s_shaper: all: fast ## Only admins can send announcement messages: announce: admin: allow ## Only admins can use the configuration interface: configure: admin: allow ## Admins of this server are also admins of the MUC service: muc_admin: admin: allow ## Only accounts of the local ejabberd server can create rooms: muc_create: local: allow ## All users are allowed to use the MUC service: muc: all: allow ## Only accounts on the local ejabberd server can create Pubsub nodes: pubsub_createnode: local: allow ## In-band registration allows registration of any possible username. ## To disable in-band registration, replace 'allow' with 'deny'. register: all: allow ## Only allow to register from localhost trusted_network: loopback: allow ## Do not establish S2S connections with bad servers ## s2s: ## bad_servers: deny ## all: allow ## By default the frequency of account registrations from the same IP ## is limited to 1 account every 10 minutes. To disable, specify: infinity ## registration_timeout: 600 ## ## Define specific Access Rules in a virtual host. ## ## host_config: ## "localhost": ## access: ## c2s: ## admin: allow ## all: deny ## register: ## all: deny ###. ================ ###' DEFAULT LANGUAGE ## ## language: Default language used for server messages. ## language: "en" ## ## Set a different default language in a virtual host. ## ## host_config: ## "localhost": ## language: "ru" ###. ======= ###' CAPTCHA ## ## Full path to a script that generates the image. ## ## captcha_cmd: "/home/administrador/ejabberd/lib/ejabberd-16.04/priv/bin/captcha.sh" ## ## Host for the URL and port where ejabberd listens for CAPTCHA requests. ## ## captcha_host: "jabber.local:5280" ## ## Limit CAPTCHA calls per minute for JID/IP to avoid DoS. ## ## captcha_limit: 5 ###. ======= ###' MODULES ## ## Modules enabled in all ejabberd virtual hosts. ## modules: mod_adhoc: {} mod_admin_extra: {} mod_announce: # recommends mod_adhoc access: announce mod_blocking: {} # requires mod_privacy mod_caps: {} mod_carboncopy: {} mod_client_state: {} mod_configure: {} # requires mod_adhoc mod_disco: {} ## mod_echo: {} ## mod_irc: {} mod_http_bind: {} ## mod_http_fileserver: ## docroot: "/var/www" ## accesslog: "/home/administrador/ejabberd/logs/access.log" mod_last: {} mod_mam: db_type: odbc mod_muc: ## host: "conference.@HOST@" access: muc access_create: muc_create access_persistent: muc_create access_admin: muc_admin mod_muc_admin: {} ## mod_muc_log: {} ## mod_multicast: {} mod_offline_odbc: access_max_user_messages: max_user_offline_messages mod_ping: {} ## mod_pres_counter: ## count: 5 ## interval: 60 mod_privacy: {} mod_private: {} ## mod_proxy65: {} mod_pubsub: access_createnode: pubsub_createnode ## reduces resource comsumption, but XEP incompliant ignore_pep_from_offline: true ## XEP compliant, but increases resource comsumption ## ignore_pep_from_offline: false last_item_cache: false plugins: - "flat" - "hometree" - "pep" # pep requires mod_caps mod_register: ## ## Protect In-Band account registrations with CAPTCHA. ## ## captcha_protected: true ## ## Set the minimum informational entropy for passwords. ## ## password_strength: 32 ## ## After successful registration, the user receives ## a message with this subject and body. ## welcome_message: subject: "Welcome!" body: |- Hi. Welcome to this XMPP server. ## ## When a user registers, send a notification to ## these XMPP accounts. ## ## registration_watchers: ## - "admin1@example.org" ## ## Only clients in the server machine can register accounts ## ip_access: trusted_network ## ## Local c2s or remote s2s users cannot register accounts ## ## access_from: register access: register mod_roster_odbc: {} mod_shared_roster: {} ## mod_stats: {} ## mod_time: {} mod_vcard: {} mod_version: {} ## ## Enable modules with custom options in a specific virtual host ## ## host_config: ## "localhost": ## modules: ## mod_echo: ## host: "mirror.localhost" ## ## Enable modules management via ejabberdctl for installation and ## uninstallation of public/private contributed modules ## (enabled by default) ## allow_contrib_modules: true ###. ###' ### Local Variables: ### mode: yaml ### End: ### vim: set filetype=yaml tabstop=8 foldmarker=###',###. foldmethod=marker: Latest entries of ejabberd.log 2016-05-06 10:26:31.546 [info] <0.7.0> Application lager started on node ejabberd@localhost 2016-05-06 10:26:31.576 [info] <0.7.0> Application crypto started on node ejabberd@localhost 2016-05-06 10:26:31.606 [info] <0.7.0> Application sasl started on node ejabberd@localhost 2016-05-06 10:26:31.631 [info] <0.7.0> Application asn1 started on node ejabberd@localhost 2016-05-06 10:26:31.632 [info] <0.7.0> Application public_key started on node ejabberd@localhost 2016-05-06 10:26:31.654 [info] <0.7.0> Application ssl started on node ejabberd@localhost 2016-05-06 10:26:31.679 [info] <0.7.0> Application fast_yaml started on node ejabberd@localhost 2016-05-06 10:26:31.711 [info] <0.7.0> Application fast_tls started on node ejabberd@localhost 2016-05-06 10:26:31.736 [info] <0.7.0> Application fast_xml started on node ejabberd@localhost 2016-05-06 10:26:31.746 [info] <0.7.0> Application stringprep started on node ejabberd@localhost 2016-05-06 10:26:31.766 [info] <0.7.0> Application cache_tab started on node ejabberd@localhost 2016-05-06 10:26:32.099 [info] <0.7.0> Application mnesia started on node ejabberd@localhost 2016-05-06 10:26:33.919 [info] <0.7.0> Application inets started on node ejabberd@localhost 2016-05-06 10:26:34.287 [warning] <0.39.0>@ejabberd_config:emit_deprecation_warning:1294 Module mod_roster_odbc is deprecated, use mod_roster with 'db_type: sql' instead 2016-05-06 10:26:35.975 [info] <0.7.0> Application p1_mysql started on node ejabberd@localhost 2016-05-06 10:26:36.006 [info] <0.39.0>@cyrsasl_digest:start:60 FQDN used to check DIGEST-MD5 SASL authentication: oficina24 2016-05-06 10:26:36.202 [info] <0.510.0>@ejabberd_listener:listen_tcp:189 Reusing listening port for {5222,{0,0,0,0},tcp} 2016-05-06 10:26:36.202 [info] <0.511.0>@ejabberd_listener:listen_tcp:189 Reusing listening port for {5269,{0,0,0,0},tcp} 2016-05-06 10:26:36.203 [info] <0.513.0>@ejabberd_listener:listen_tcp:189 Reusing listening port for {5280,{0,0,0,0},tcp} 2016-05-06 10:26:36.203 [info] <0.39.0>@ejabberd_app:start:76 ejabberd 16.04 is started in the node ejabberd@localhost 2016-05-06 10:26:36.203 [info] <0.7.0> Application ejabberd started on node ejabberd@localhost I've executed mysql.sql script on phpmyadmin and the database is correctly setted up. The problem is that I'm not able to link ejabberd with mysql because when I register a user with ejabberd web admin it doesn't store it in sql database. Since I can't store the user I'm not able to check for the messaging storage neither. Am I missing something? Regards! EDIT: user on .yml admin: user: - "admin": "jabber.local" - "admin": "localhost" ejabberd.log 2016-05-06 11:28:40.055 [warning] <0.525.0>@ejabberd_web_admin:process:239 Access of <<"admin@localhost">> from <<"127.0.0.1">> failed with error: <<"inexistent-account">> 2016-05-06 11:28:43.813 [error] <0.525.0>@ejabberd_sql:check_error:991 SQL query 'Q9525209' at {sql_queries,145} failed: <<"Unknown Host">> 2016-05-06 11:28:43.813 [error] <0.525.0>@ejabberd_sql:check_error:991 SQL query 'Q9525209' at {sql_queries,145} failed: <<"Unknown Host">> 2016-05-06 11:28:43.813 [error] <0.525.0>@ejabberd_auth:is_user_exists:316 The authentication module ejabberd_auth_sql returned an error when checking user <<"admin">> in server <<"localhost">> Error message: <<"Unknown Host">> A: You have an issue with your database configuration. ejabberd cannot connect to it, as stated in error message: Failed connecting to "localhost":3306 : {error,econnrefused} You are saying that it stores users in SQL db, but you are likely mistaken as ejabberd cannot connect to the database. I think it should be actually storing data in Mnesia. This is confirmed by your config (auth_method: internal)
doc_23529729
#include <iostream> using namespace std; int main() { int gt1, gt2; cout << "Hello World!" << endl; return 0; } Just for 0.5 sec a black box shows up and it closes. Is there anything I can do to prevent this? A: Set a breakpoint in your code, such that you can debug it. Just click on the bar on the left side of the source. A: Your function completes and returns the control to the debugger. That's why you see the screen close. This behavior (debugging) is different than running your program from Visual (where you see the line "press any key..." in the end. For debugging purposes you can add the following two lines just before "return": char ch; cin.get(&ch); This will wait for any key being pressed before termination. A: Add cin.get(); to end of code before return 0.
doc_23529730
Is it possible to use jQuery (or otherwise) to 1- detect if an iframe with class="iframe1" appears on a given page and 2- if it does exist, to remove the primary navigation bar with id="main-header" ? I'm currently using this custom CSS to hide the navigation globally: #main-header { display:none !important; } and then using this (for example) to replace it on individual pages: .page-id-1350 #main-header { display:block !important; } Obviously this is not ideal, and I very much like to automate this process. Thanks very much in advance, Chris A: You can use the following jQuery code to do just that: if($(".iframe1").length > 0) // If .iframe1 exists $("#main-header").hide(); // Hide #main-header Or, go the opposite way, keep your CSS that hides #main-header and then show it when .frame1 is not present on the page: if($(".iframe1").length == 0) // If .iframe1 does not exists $("#main-header").show(); // Show #main-header A: You could do this with JavaScript, with code like this: <script> // Place this at the end of the body window.addEventListener("load", function(){ var iframeTest = document.querySelectorAll("iframe.iframe1"); var navBar = document.getElementById("main-header"); if (iframeTest.length > 0) { navBar.setAttribute("style","display:none"); } }); </script>
doc_23529731
However, two days ago, the checkout layout got changed automatically from the classic one to the mobile-responsive version. Previously when I had the callback for instant update defined it automatically used to switch from the mobile-friendly version to the classic version. Now that is no longer the case and the instant update features don't seem to work at all with the mobile-friendly checkout. Is there anything I can do about it or has PayPal stopped supporting instant update just when I finished my plugin? A: I have the same problem.. UPDATE.. After emailing PayPal tech support they finally replied.. Unsupported features In-Context Express Checkout does not support: * *Parallel payments or multi-seller payments *Callback / Instant Update API operations *Billing agreements that use the deprecated SetCustomerBillingAgreement API operation *Seamless checkout for a Log in with PayPal integration So yes, they stopped supporting instant update with Express Checkout, though they haven't removed the documentation as of yet.
doc_23529732
The function will be called from a nested loop, requesting the vector (and processing it's elements) million times, so unnecessary (re)allocations should be avoided. Bjarne Stroustrup recommends returning collections by value, due to C++11 move semantics. However it seems to me that the second approach (doStuff2) is better in my case, since it supports vector reuse. Any suggestions? template <typename T> class A { typedef std::vector<T> TVec; std::vector<TVec> m_items; public: size_t getIndex(size_t i, size_t j); std::vector<TVec*> doStuff(float x, float y) { // calculate n, i0, i1, j0, j1 (by x and y) // ... std::vector<TVec*> vec; vec.reserve(n); for (size_t i = i0; i<i1; i++) for (size_t j = j0; j<j1; j++) vec.push_back(&m_items[getIndex(i, j)]); return vec; } void doStuff2(float x, float y, std::vector<TVec*> &vec) { // calculate n, i0, i1, j0, j1 (by x and y) // ... vec.clear(); vec.reserve(n); for (size_t i = i0; i<i1; i++) for (size_t j = j0; j<j1; j++) vec.push_back(&m_items[getIndex(i, j)]); } }; A: However it seems to me that the second approach (doStuff2) is better in my case, since it supports vector reuse. Any suggestions? The second option (doStuff2) is better than the first, because it avoids reallocating the vector. That said, you should (probably) consider using a visitor pattern: Your code (if I understood you correctly): // "function will be called from a nested loop, requesting the vector // (and processing it's elements) million times, so unnecessary // (re)allocations should be avoided." void yourCientCode() { std::vector<TVec*> vec; for(auto x: ???) for(auto y: ???) // nested loop (a million(?) times) { A::doStuff2(x, y, vec); performClientComputation(vec); } } Alternative code: // "function will be called from a nested loop, requesting the vector // (and processing it's elements) million times, so unnecessary // (re)allocations should be avoided." void yourCientCode() { for(auto x: ???) for(auto y: ???) // nested loop { A::doStuff3(x, y, performClientComputation); // computation function should // be injected as a visitor } } This way, no vector is returned. Client code doesn't have to "get vector then apply computation", but "apply computation on elements satisfying whatever conditions" (see Demeter's Law). Having a vector (or not) becomes an internal implementation detail (as far as client code is concerned) and can be optimized later, without altering client code at all).
doc_23529733
if firstoption = go and second = true I want MASK in value "A" if firstoption = stop and second = true MASK = "B" etc It's possible using without managebean set inputbox and can change value in inputbox? <composite:interface> <composite:attribute name="value" type="java.lang.String" /> <composite:attribute name="firstoption" type="java.lang.String"/> <composite:attribute name="secondoption" d type="java.lang.Boolean" /> </composite:interface> <composite:implementation> <h:panelGrid> <p:selectOneMenu id="first" value="#{cc.attrs.firstoption}" > <p:ajax update="action"/> <f:selectItem itemValue="GO" /> <f:selectItem itemValue="STOP"/> </p:selectOneMenu> <p:selectOneMenu id="second" value="#{cc.attrs.secondoption}" > <p:ajax update="action"/> <f:selectItem itemValue="#{true}" /> <f:selectItem itemValue="#{false}"/> </p:selectOneMenu> <p:inputText id="action" value="#{cc.attrs.value}" <h:panelGrid> </composite:implementation> Maybe something like this with button ? <f:setPropertyActionListener target="#{cc.attrs.value}" value="A" /> but can't use that to inputtext/selectonemenu
doc_23529734
When I run my program, it creates a CSV file in my Netbeans project folder. However, when I open the CSV file - it is blank. In my main method, I show the user the array and then call the writeCSV method as shown below: //show the user the sorted array System.out.println( "The sorted array is: "); for ( int i=0; i<24; i++) System.out.println( "\t" + course2[i].toString() ); //write the data from the duplicate array to a CSV file System.out.println("\nWriting data from Course array to CSV File."); writeCSV(course2, count); The writeCSV method is pasted below: //write from duplicate array of courses to a CSV file public static void writeCSV(Course[] courseArray, int count) throws Exception { //create a File class object and give the file the name employees.csv java.io.File courseCSV = new java.io.File("courses.csv"); //Create a Printwriter text output stream and link it to the CSV File java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV); //Iterate the elements actually being used for (int i=0; i < count ; i++) { outfile.write(courseArray[i].toCSVString()); }//end for outfile.close(); } //end writeCSV() The writeCSV method above calls the toCSVString method which is defined in a class I created named Course. I pasted this method below: // method to return properties as a CSV string on one line //public String toCSVString(Course c){ public String toCSVString() { String record = campus + "," + course + "," + section + "," + crn + "," + credits + "," + time + "," + days + "\n"; return record; } //end toCSVString() My code runs flawlessly up until I have to write the array to a CSV file. This is when it creates the blank CSV file. This makes me believe I have an error within my toCSVString method or the writeCSV method I believe. Any tips or help would be greatly appreciated. Thanks. A: For those who just tuned in... Change your writeCSV method to this: //write from duplicate array of courses to a CSV file public static void writeCSV(Course[] courseArray) throws Exception { //create a File class object and give the file the name employees.csv java.io.File courseCSV = new java.io.File("courses.csv"); //Create a Printwriter text output stream and link it to the CSV File java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV); //Iterate the elements actually being used for (int i=0; i < courseArray.length ; i++) { outfile.write(courseArray[i].toCSVString()); }//end for outfile.close(); } //end writeCSV() * *Remove the count argument from this function, unless you actually intend to write a different number of elements into the CSV file. Judging from your main method, this isn't the case. *Change count in your for-loop to courseArray.length Then, in your main method, change the call to: writeCSV(course2); Always be sure to initialize your variables, and when in doubt, make use of your debugger. That could have helped you spot this. Hope this helps.
doc_23529735
<html> <head> <meta http-equiv="X-UA-Compatible" content="IE=6" /> </head> <body bgcolor="#ffffff" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> <SCRIPT LANGUAGE="JavaScript"> <!-- Begin function BuildActivityTypeSubTypeDropDown(ActivityTypeId) { var ActivitySubTypeId = 0 var arrActivityTypeId = new Array(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,35,36,37,38,39,40,41,42,45,46,47,48); var arrActivityTypeName = new Array('Adventure','Sport','Culture','Personal Development','Fitness','Wellbeing','Ski','Cycling','Surfing','Tennis','Fishing','Golf','Walking','Languages','Music','Poker','Bridge','Football','Photography','Cooking','Painting','Airborne','Wine','Cricket','Scrabble','Chess','Mountains','Diving','Kayaking','Windsurfing','Sailing','Riding','Singing','Farming','Creative Writing','Croquet','Drama','Bowls','Motorcycle','Wildlife','Incentive','Spice','Comedy','Boot Camp'); var arrActivitySubTypeId = new Array(190,16,77,12,32,30,99,104,14,112,18,28,34,98,89,97,15,17,170,78,35,74,196,13,109,6,108,68,21,207,95,37,11,110,191,111,90,40,63,43,85,59,65,69,120,169,200,189,202,173,172,216,175,178,136,199,198,176,171,195,197,179,192,168,194,177,205,180,100,181,103,101,162,102,114,119,115,118,116,117,121,122,124,123,186,125,187,126,152,153,131,127,128,130,129,135,133,201,183,132,134,137,138,140,182,139,141,142,144,164,145,143,146,147,148,149,150,151,154,155,156,209,157,213,208,214,211,212,210,158,184,159,160,167,161,163,165,166,203,204,215,193); var arrActivitySubTypeName = new Array('Canyoning','Multi-Activity','Golf','Archaeology','Cooking','Sightseeing','Wine','Outdoor Survival skills','Public Speaking','Aerobics','Bachata','Belrobics','Bollywood Fitness','Booiaka','Boot Camp','Boxfit','Drums Alive','Fitness','Ginastica Natural','Insanity','Kettlebell Workout','Masala Bhangra','Parkour','Personal Training','Pilates','Retreat','Running','Spa','Step Aerobics','Weight Loss','Yoga','Zumba','Nutrition','Pilates','Spa','Weight-Loss','Yoga','Alpine and Downhill','Cross-Country','Snowboarding','Cycle Touring','Mountain Biking','Road Cycling','Surfing','Tennis','Big Game','Carp','Fly','Salmon','Trout','Golf','Hiking','Rambling','Walking','French','German','Italian','Spanish','Classical Concerts','Groups - live concerts','Learn to play','stud','Texas Hold \'em','Bridge','Football','Photography','Baking','Breadmaking','Cooking','Painting','Ballooning','Gliding','Hang-Gliding','Light Aircraft','Para-Gliding','Wine','Cricket','Scrabble','Chess','Climbing and mountaineering','Hiking','Diving','Kayaking','Windsurfing','Bareboat Charter','Big Boat','Cabin Charter','Dinghy','Expedition Adventure Sailing','Flotilla Sailing Holidays','RYA Training Holidays','Skippered Charter','Horseriding','Choral','Urban Farming','Writing','Croquet','Acting and Drama','Bowls','Track days','Birdwatching','Various','Various','Carry on Comedy','Boot Camp'); var arrActivitySubTypeActivityTypeId = new Array(2,2,3,4,4,4,4,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,8,8,8,9,9,9,10,11,12,12,12,12,12,13,14,14,14,15,15,15,15,16,16,16,17,17,18,19,20,21,21,21,22,23,23,23,23,23,24,25,26,27,28,28,29,30,31,32,32,32,32,32,32,32,32,33,35,36,37,38,39,40,41,42,45,46,47,48); var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeId') var ActivitySubTypeDropDownOption ActivitySubTypeDropDown.options.length = 0; ActivitySubTypeDropDownOption = document.createElement("OPTION"); ActivitySubTypeDropDownOption.value = ''; ActivitySubTypeDropDownOption.text = ''; ActivitySubTypeDropDown.add(ActivitySubTypeDropDownOption); for(var i = 0; i < arrActivitySubTypeId.length; ++i) { if (arrActivitySubTypeActivityTypeId[i] == ActivityTypeId) { ActivitySubTypeDropDownOption = document.createElement("OPTION"); ActivitySubTypeDropDownOption.value = arrActivitySubTypeId[i]; ActivitySubTypeDropDownOption.text = arrActivitySubTypeName[i]; ActivitySubTypeDropDown.add(ActivitySubTypeDropDownOption); if (arrActivitySubTypeId[i] == ActivitySubTypeId) { ActivitySubTypeDropDownOption.selected = true; } } } } // End --> </script> <center> <form name="frmBookings"> Activity Category<br> <select id="ActivityTypeDropDown" name="ActivityTypeId" style="width: 100px" OnChange="BuildActivityTypeSubTypeDropDown(this.value)"> <option value="">Select All</option> <option value=""></option> <option value="2" >Adventure</option> <option value="23" >Airborne</option> <option value="48" >Boot Camp</option> <option value="40" >Bowls</option> <option value="18" >Bridge</option> <option value="27" >Chess</option> <option value="47" >Comedy</option> <option value="21" >Cooking</option> <option value="37" >Creative Writing</option> <option value="25" >Cricket</option> <option value="38" >Croquet</option> <option value="4" >Culture</option> <option value="9" >Cycling</option> <option value="29" >Diving</option> <option value="39" >Drama</option> <option value="36" >Farming</option> <option value="12" >Fishing</option> <option value="6" >Fitness</option> <option value="19" >Football</option> <option value="13" >Golf</option> <option value="45" >Incentive</option> <option value="30" >Kayaking</option> <option value="15" >Languages</option> <option value="41" >Motorcycle</option> <option value="28" >Mountains</option> <option value="16" >Music</option> <option value="22" >Painting</option> <option value="5" >Personal Development</option> <option value="20" >Photography</option> <option value="17" >Poker</option> <option value="33" >Riding</option> <option value="32" >Sailing</option> <option value="26" >Scrabble</option> <option value="35" >Singing</option> <option value="8" selected>Ski</option> <option value="46" >Spice</option> <option value="3" >Sport</option> <option value="10" >Surfing</option> <option value="11" >Tennis</option> <option value="14" >Walking</option> <option value="7" >Wellbeing</option> <option value="42" >Wildlife</option> <option value="31" >Windsurfing</option> <option value="24" >Wine</option> </select> <br><br> Activity Type<br> <select id="ActivitySubTypeDropDown" name="ActivitySubTypeId" style="width: 100px"> </select> <SCRIPT LANGUAGE="JavaScript"> <!-- Begin BuildActivityTypeSubTypeDropDown(8); // End --> </script> <br><br> <input type="submit" value="Search Bookings" class="button"> </form> </body> </html> I'm looking for the most minimal changes necessary to get it to work in current desktop versions of Edge, Firefox and Chrome. I should add that this is HTML output. The contents of the arrays on lines 11 to 15 are pulled from a database with server side code, so if possible I'm looking for an answer which continues to use these arrays. When I remove the compatibility meta tag I get the following error alert for line 20: "Unable to get property "options" of undefined or null reference". Can anyone help? A: There is no element with ID ActivitySubTypeId. You should change var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeId') to var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeDropDown') A: Adding more information to @Titus' answer: From MS documentation you can see that In IE7 Standards mode and previous modes, this method performs a case-insensitive match on both the ID and NAME attributes, which might produce unexpected results. For more information, see Defining Document Compatibility. So forcing the compatibility mode that code works because of the name attribute, but any modern browser checks just the id attribute's value, as expected. A: You should need to change this, it will also give the error in other browsers var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeId') to var ActivitySubTypeDropDown = document.getElementById('ActivitySubTypeDropDown');
doc_23529736
I have some little problem. I need add project to some user profile page. For example: User has to go to the pages of projects, and use button "add to profile". It should add the project to the User Profile. But when I use "add" ActiveRecord::RecordNotFound (Couldn't find Profile with 'id'=): app/controllers/projects_controller.rb:15:in `add' I have three models: class ProjectList < ActiveRecord::Base belongs_to :profile belongs_to :project end class Project < ActiveRecord::Base has_many :project_lists has_many :profiles, through: :project_lists has_many :charts end class Profile < ActiveRecord::Base belongs_to :user has_many :project_lists has_many :projects, through: :project_lists has_attached_file :avatar, styles: { thumb: ["64x64#", :jpg, :png] } validates_attachment :avatar, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] } end My controllers: class ProjectsController < ApplicationController before_action :find_project, only: [:show, :edit, :update, :destroy] def index @projects = Project.all.paginate(page: params[:page], per_page: 5) end def new @project = Project.new end def add @profile = Profile.find(params[:profile_id]) @profile.projects << project end def edit end def update if @project.update(project_params) redirect_to projects_path else render 'edit' end end def create @project = Project.new(project_params) #@project.profiles.build(params[:profile_id]) if @project.save flash[:create] = 'Project created' redirect_to projects_path else render 'new' end end def show end def destroy @project.destroy flash[:destroy] = 'Delete project' redirect_to projects_path end private def project_params params.require(:project).permit(:project_name, :project_id, :description) end def find_project @project = Project.find(params[:id]) end end profile controller: class ProfilesController < ApplicationController #before_action :authenticate_user!, except: [:index] before_action :find_profile, only: [ :show, :edit, :update, :destroy] def index @profiles = Profile.all.paginate(page: params[:page], per_page: 5) end def show end def new @profile = Profile.new end def add end def edit end def create end def update respond_to do |format| if @profile.update(profile_params) format.json { head :no_content } format.js format.html do redirect_to '/' end else format.json { render json: @profile.errors.full_messages, status: :unprocessable_entity } end end end def destroy @profile.destroy respond_to do |format| format.js format.html { redirect_to profiles_url } format.json { head :no_content } end end private def profile_params params.require(:profile).permit(:name, :birthday, :biography, :user_id, :avatar, :profile_id) end def find_profile @profile = Profile.find(params[:id]) end end In my views a use helper: <%= link_to 'Add', add_to_profile_path(@project), :class => 'btn btn-sm btn-info' %> My routes: Rails.application.routes.draw do devise_for :users # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". resources :profiles resources :charts get '/projects/add_project/:project_id', to: 'projects#add', as: 'add_to_profile' resources :projects root 'profiles#index' end In console: Started GET "/projects/add_project/2" for 127.0.0.1 at 2017-02-17 17:12:55 +0200 Processing by ProjectsController#add as HTML Parameters: {"project_id"=>"2"} Profile Load (0.1ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" = ? LIMIT 1 [["id", nil]] Completed 404 Not Found in 4ms (ActiveRecord: 0.1ms) ActiveRecord::RecordNotFound (Couldn't find Profile with 'id'=): app/controllers/projects_controller.rb:15:in `add' I be grateful for any help. A: I found the solution. First I changed model name project_list to profiles_projects. Create ProfilesProjects controller for my model class ProfilesProjectsController < ApplicationController def create @profiles_projects = _current_profile.profiles_projects.new(:project_id => params[:project_id]) if @profiles_projects.save render status: 201, json: @profiles_projects end end private def _current_profile @current_profile = current_user.profile end end and it's working for me. Now I can add projects to Profile. maybe it will help someone
doc_23529737
If something like "Foobar Café" is entered, it is stored in the MySQL database as "Foobar Café". Why is it doing that? Both the HTML page and database table are set to UTF-8 encoding (the "business_name" field has a collation of "utf8_unicode_ci"). Shouldn't that take care of everything? What exactly could be causing the special character "é" (&etilde;) to be stored in the database as "é"? It makes no sense. A: Your database connection is probably not set to UTF-8. At the start of your connection, issue the following query: SET NAMES 'utf8'; That will set the connection character set to utf8 which will match the encoding and collation of your tables, code and client page. A: I'm guessing it is from the form not mysql since the email comes from there. Look into that. Maybe you have a ”pre processor” of some sort. Just wondering, why do you store html chars when you will be displaying that info to users? That's a recipe for disaster. XSS. A quick fix, try using htmlentites on the data with uft-8 turned on. Send the email as html and you should be fine. However, try to find the cause of the issue. Edit. echo htmlentities($str, ENT_QUOTES, "UTF-8"); That should solve your issue. Charset for utf 8 must be defined A: Check the settings for the respective db table or db, set it to to utf-8
doc_23529738
If the requested type is image/jpeg, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality; if the second argument is anything else, the default value for image quality is used. Other arguments are ignored. But on practice I get: Security error" code: "1000. Is it something that is not yet supported? Or why it might be happening? Any insightful advice or explanation might be helpful. UPDATE: I use newest File API to load local image file into memory first, scale it with the canvas and then export - with custom quality. A: It's a known bug.
doc_23529739
I am passing ReviewFormViewModel I want to pass the ListAdhoc to the partial controller and add items to it then pass it back to the view. public class ReviewFormViewModel { ...// other fields public List<AdhocViewModel> ListAdhoc { get; set; } } public class AdhocViewModel { public int? ReviewId { get; set; } public String AdhocQuestion { get; set; } //free form public int? SelectedAnswer { get; set; } // for binding int? for optional public String Comments { get; set; } public List<AdhocOptionsVM> ListAdhocOptions { get; set; } } public class AdhocOptionsVM { public int AnswerId { get; set; } public String RatingName { get; set; } public Decimal Rating { get; set; } public String ActiveFl { get; set; } } controller for partial view public PartialViewResult Adhoc() { //pass model object on button click and add each item to the model everytime var AdhocObj = new AdhocViewModel(); AdhocObj.ListAdhocOptions = new List<AdhocOptionsVM>(); var query = db.dbQuestionOptions.Where(qo => qo.ActiveFl == "Y").OrderByDescending(qo => qo.Rating).ToList(); foreach (var item in query) { var AdhocAnsOptionsVMObj = new AdhocOptionsVM(); AdhocAnsOptionsVMObj.AnswerId = item.AnswerId; AdhocAnsOptionsVMObj.RatingName = item.RatingName; AdhocAnsOptionsVMObj.Rating = item.Rating; AdhocAnsOptionsVMObj.ActiveFl = item.ActiveFl; AdhocObj.ListAdhocOptions.Add(AdhocAnsOptionsVMObj); } return PartialView("Adhoc", AdhocObj); } and partial view that is using the ReviewFormViewModel aswell: <div class="adhoc"> @using (Html.BeginCollectionItem("adhoc")) { <div class="panel panel-success"> <div class="panel-heading"> @Html.HiddenFor(m => m.ReviewId) @Html.HiddenFor(m => m.AdhocId) @Html.TextAreaFor(m => m.AdhocQuestion, htmlAttributes: new { @style = "width:650px", @placeholder = "Enter Adhoc Question here" })<br /> </div> <div class="panel-body"> @foreach (var optAnswer in Model.ListAdhocOptions) { <div class="radio"> <responselabel>@Html.RadioButtonFor(m => m.SelectedAnswer, optAnswer.AnswerId, new { id = optAnswer.AnswerId }) @optAnswer.RatingName</responselabel><br /> </div> } <div>@Html.ValidationMessageFor(m => m.SelectedAnswer)</div><br /> @Html.TextAreaFor(m => m.Comments, htmlAttributes: new { @style = "width:650px", @placeholder = "Comments" })<br /><br /> </div> <button type="button" class="delete">Delete</button> </div> } main view @model CustomerFeedback.Areas.ProjectManagers.Models.ReviewFormViewModel @{ ViewBag.Title = "CreateFormsIndex"; } <h4 align="center">Project Review Form</h4> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="text-center"> <h4> @Html.DisplayName(Model.ProjectId) @Html.DisplayName(Model.ProjectName) </h4> <h4> PM: @Html.DisplayName(Model.FullName) </h4> </div> </div> </div> </div> <div class="container"> <br /> <div class="panel-group"> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.ProjectId) @Html.HiddenFor(m => m.AccountId) @Html.HiddenFor(m => m.ReviewDate) <div class="panel panel-default"> <div class="panel-body"> <div class="panel-group"> <div class="panel-heading"> <h4 class="panel-title"> Required Questions </h4> </div> @for (int i = 0; i < Model.ListReqQuestions.Count; i++) { <div class="panel panel-success"> <div class="panel-heading"> @Html.HiddenFor(m => m.ListReqQuestions[i].QuestionId) @Html.DisplayFor(m => m.ListReqQuestions[i].QuestionText) </div> <div class="panel-body"> @foreach (var optAnswer in Model.ListReqQuestions[i].ListQuestionOptions) { <div class="radio"> <responselabel>@Html.RadioButtonFor(m => m.ListReqQuestions[i].SelectedAnswer, optAnswer.AnswerId, new { id = optAnswer.AnswerId }) @optAnswer.RatingName</responselabel><br /> </div> } <div>@Html.ValidationMessageFor(m => m.ListReqQuestions[i].SelectedAnswer)</div><br /> @Html.TextAreaFor(m => m.ListReqQuestions[i].Comments, htmlAttributes: new { @style = "width:650px", @placeholder = "Comments" })<br /><br /> </div> </div> } <div class="panel-heading"> <h4 class="panel-title"> Optional Questions </h4> </div> @for (int i = 0; i < Model.ListOpQuestions.Count; i++) { <div class="panel panel-success"> <div class="panel-heading"> @Html.HiddenFor(m => m.ListOpQuestions[i].QuestionId) @Html.DisplayFor(m => m.ListOpQuestions[i].QuestionText) </div> <div class="panel-body"> @foreach (var optAnswer in Model.ListOpQuestions[i].ListQuestionOptions) { <div class="radio"> <responselabel>@Html.RadioButtonFor(m => m.ListOpQuestions[i].SelectedAnswer, optAnswer.AnswerId, new { id = optAnswer.AnswerId }) @optAnswer.RatingName</responselabel><br /> </div> } <div>@Html.ValidationMessageFor(m => m.ListOpQuestions[i].SelectedAnswer)</div><br /> @Html.TextAreaFor(m => m.ListOpQuestions[i].Comments, htmlAttributes: new { @style = "width:650px", @placeholder = "Comments" })<br /><br /> </div> </div> } @*on click (new adhoc question) add a new freeform question with list of answers*@ <div class="panel panel-success" id="adhoc"> @* renders partial adhoc view *@ </div> <br /> <div class="center"> <input type="button" value="New Adhoc Question" class="btnAdhoc btn-success" /> </div> <br /> <div class="center"> <input type="submit" value="Save" name="Command" class="btn btn-success" /> <input type="submit" value="Submit" name="Command" class="btn btn-success" /> <input type="submit" value="Cancel" name="Command" class="btn btn-success" /> <input type="submit" value="Attach" name="Command" class="btn btn-success" /> </div> </div> </div> </div> } </div> </div> <script> $(function () { $('.btnAdhoc').click(function (event) { event.preventDefault(); $.ajax({ url: '/ProjectManagers/Forms/Adhoc', //data: JSON.stringify(model), type: 'get', success: function (result) { $('#adhoc').append(result); } }); }); }) </script> UPDATE: I've added the AdhocViewModel. Ive added the view model for those properties. I have a form with a set of questions and responses to be answered. Those are from the database. I have a button, on click will generate the partial view and append to the form (can be many). The partial view consists of a text area (for any question entered), set of responses (from database) and a comment box. I am not sure how to handle this on post (submit). My attempt is to pass the model from the view to the partial controller, add items to it and pass it back to the view for processing. I am not have any success on passing model data UPDATE 2 Updated code with using BeginCollectionItem helper. Added main view A: The reason that the collection does not bind is because the parameter in BeginCollectionItem() must match the name of you property. Change it to @using (Html.BeginCollectionItem("ListAdhoc")) // binds to List<AdhocViewModel> ListAdhoc In addition you also need a loop in the main view to render existing AdhocViewModel in the collection. Even if none exist initially, it is still required in case you need to return the view because ModelState is invalid. In the main view include <div class="panel panel-success" id="adhoc"> @foreach(var item in Model.ListAdhoc) { @Html.Partial("Adhoc", item) } </div>
doc_23529740
Please suggest what to do? A: If your website is not on intranet, add it to compatibility view. This way, the responsexml object returned will be of type IXMLDOMDocement2 which will have methods to select nodes. For us also, we were firing ajax request for which the output was XML string. After obtaining response, the responsexml object returned was of type IXMLDOMDocement2 when the application was running on intranet (as intranet websites are automatically added to compatibility view by IE). However, during production, when the website moved to internet, the responsexml object returned was of type XMLDocument which does not have the method selectNodes. However, after adding the website to compatibility view, the issue got resolved. The returned responsexml object was automatically converted to IXMLDOMDocement2.
doc_23529741
PLEASE, I'm not talking about Firebase Cloud Storage. A: To delete a file, first create a reference to that file. Then call the delete() method on that reference, which returns a Promise that resolves, or an error if the Promise rejects. import { getStorage, ref, deleteObject } from "firebase/storage"; const storage = getStorage(); // Create a reference to the file to delete const desertRef = ref(storage, 'images/desert.jpg'); // Delete the file deleteObject(desertRef).then(() => { // File deleted successfully }).catch((error) => { // Uh-oh, an error occurred! });
doc_23529742
@Controller @SessionAttributes({ WebKeys.OBJECT_SIX, WebKeys.DSP_LOGIC, WebKeys.NEW_CARD_FORM }) In each of my API, I am calling the function: @RequestMapping(value = "/apiA.do", method = RequestMethod.POST) public String doAPIa(Model model) { setInfo(model); } @RequestMapping(value = "/apiB.do", method = RequestMethod.POST) public String doAPIb(Model model) { setInfo(model); } In my setInfo(), I am trying to access the session attribute and add value back to the model: private void setInfo(Model model) throws Exception{ String populationId = // need to get from WebKeys.OBJECT_SIX session attribute if(populationId!=null && (populationId.equals(Constants.POP_TYPE_ID))){ DisplayHelperTO helper = (DisplayHelperTO) // need to get from WebKeys.DSP_LOGIC; NewCardNewBasicForm newCardForm = (NewCardNewBasicForm ) // need to get from WebKeys.NEW_CARD_FORM); model.addAttribute("newCardForm", newCardForm); model.addAttribute("dspLogic", helper); } } I tried to declare in such way: private void setInfo(Model model, @SessionAttribute(WebKeys.OBJECT_SIX) String populationId) throws Exception{ } However, if I am declaring the function in this way, the part to call the setInfo() in both doAPIa and doAPIb will be highlighted in syntax error. Any ideas on how to access the session attributes in function? Thanks!
doc_23529743
I want to add two items in Headers tab in SOAP screenshot. A: The problem's been solved. Since the wsdl address was created as https, it was fixed as http in the stub file and the header was added with the following method. ServiceClient serviceClient = stub._getServiceClient(); List headers = (List) serviceClient.getOptions().getProperty(HTTPConstants.HTTP_HEADERS); if (headers == null){ headers = new ArrayList(); } headers.add(new Header("username", username)); headers.add(new Header("password", password)); serviceClient.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);
doc_23529744
A: By design interceptors work only for public, protected and package-private (default visibility) methods. During Quarkus deployment any interceptor on private methods is just ignored but should leads to a a failed build if this property is setted. Quarkus allows interception of non-private static method
doc_23529745
I am pulling the version in from the package.json and storing it in the jwt/session to have for comparison of which version the user authenticated from and what version is now running. // pages/api/auth/[nextauth].ts const version = require('../../../package.json').version import NextAuth from 'next-auth' import { signOut } from 'next-auth/react' export default NextAuth({ providers: [ /*...*/ ], session: { strategy: 'jwt' }, callbacks: { async jwt(props) { const { token, user, account } = props const isSignIn = user?.username ? true :false if(isSignIn) { token.version = version // ... } if (token?.version !== version) { await signOut() return {} } return token }, // ... } }) This works, but it is throwing an error https://next-auth.js.org/errors#jwt_session_error window is not defined { message: 'window is not defined', stack: ... name: 'ReferenceError } I know the error is throwing because I am calling the signOut function on the server side when it is meant to be a browser side function hence the error for window is not defined. How else can I call the signOut function without it trying to use the browser side call including the reference to window? A: You can't use signOut on sever side from what I gathered, but here is a trick I used in my case. Instead trying signOut from the server side return an error code. const version = require('../../../package.json').version import NextAuth from 'next-auth' import { signOut } from 'next-auth/react' export default NextAuth({ providers: [ /*...*/ ], session: { strategy: 'jwt' }, callbacks: { async jwt(props) { const { token, user, account } = props const isSignIn = user?.username ? true :false if(isSignIn) { token.version = version // ... } if (token?.version !== version) { return { // You can ignore this if you don't need the previous data ...token, // Return an error code error: "invalid-version", } } return token }, // ... } }) Create a wrapper around the secured routes. you can do this in a common layout too. export const Auth = ({children}) => { const { data: sessionData } = useSession(); const router = useRouter(); useEffect(() => { // check if the error has occurred if (sessionData?.user.error === "invalid-version") { // Sign out here signOut(); } }, [sessionData?.user.error, router]); return ( <>{children}</> ) }
doc_23529746
I want the box to be shown without having to click the marker first. I thought i could solve this by imitating a click after the website has loaded, but i can't find out how to address that specific marker to click. Could anyone hint me to a solution? I couldn't solve this without breaking the whole Map :/.. Thanks a lot. This problem concerns the following website: http://prusiklackierbetrieb.de/neu/black/indexnewimages.html I have found the location where the infowindow is created. However, when i change the event from "click" to "load" or "domready" it does not fire. i think it is because the script is loaded after these events fire. How can I still open the window by default? Code Snippet: !function(a) { "use strict"; var t = { cntClass: "map", mapClass: "map_model", locationsClass: "map_locations", marker: { basic: "images/gmap_marker.png", active: "images/gmap_marker_active.png" }, styles: [], onInit: !1 } , o = { map: { x: -73.9924068, y: 40.646197, zoom: 14 }, locations: [] } , n = function(t, o) { var n = t.parent().find("." + o.locationsClass).find("li") , e = []; return n.length > 0 && n.each(function(t) { var n = a(this); n.data("x") && n.data("y") && (e[t] = { x: n.data("x"), y: n.data("y"), basic: n.data("basic") ? n.data("basic") : o.marker.basic, active: n.data("active") ? n.data("active") : o.marker.active }, a.trim(n.html()) ? e[t].content = '<div class="iw-content">' + n.html() + "</div>" : e[t].content = !1) }), e }; a.fn.googleMap = function(e) { e = a.extend(!0, {}, t, e), a(this).each(function() { var t = a(this) , s = a.extend(!0, {}, o, { map: { x: t.data("x"), y: t.data("y"), zoom: t.data("zoom") }, locations: n(t, e) }) , i = new google.maps.Map(this,{ center: new google.maps.LatLng(parseFloat(s.map.y),parseFloat(s.map.x)), styles: e.styles, zoom: s.map.zoom, scrollwheel: !1 }); e.onInit && e.onInit.call(this, i); var c = new google.maps.InfoWindow , l = []; for (var r in s.locations) l[r] = new google.maps.Marker({ position: new google.maps.LatLng(parseFloat(s.locations[r].y),parseFloat(s.locations[r].x)), map: i, icon: s.locations[r].basic, index: r }), s.locations[r].content && (google.maps.event.addListener(l[r], "DOMContentLoaded", function() { for (var t in l) l[t].setIcon(s.locations[t].basic); c.setContent(s.locations[this.index].content), c.open(i, this), a(".gm-style-iw").parent().parent().addClass("gm-wrapper"), this.setIcon(s.locations[this.index].active) }), google.maps.event.addListener(c, "closeclick", function() { for (var a in l) l[a].setIcon(s.locations[a].basic) })); google.maps.event.addDomListener(window, "resize", function() { i.setCenter(new google.maps.LatLng(parseFloat(s.map.y),parseFloat(s.map.x))) }) }) }}(jQuery); A: When you crate the infowindow just call open infowindow.open(map, marker); You can look an example here https://www.ibeernalia.com/#dorigen . A: The map is loaded in an IFRAME so you cannot simulate click on an element in the IFRAME. What you can do it to use the Google Maps API for that More Info: * *https://developers.google.com/maps/documentation/javascript/infowindows
doc_23529747
When I write the package name it shows me this error I checked 3 months ago so there was no such problem.
doc_23529748
* *I need to see Bahasa Malaysia language translation on a spinner in android *How to call another program; say Google hangouts into the app? I already got the translations in values-ms Please I really need this thanks A: i found the answer String[] language= { "English", "Chinese (Simplified)", "Bahasa Malaysia"}; ArrayAdapter<String> adapter = new ArrayAdapter<String (this,android.R.layout.simple_spinner_item,language); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Configuration config = new Configuration(); Locale applang = new Locale ("ms"); switch (arg2){ case 0: config.locale = Locale.ENGLISH; break; case 1: config.locale = Locale.SIMPLIFIED_CHINESE; break; case 2: config.locale = applang; break; default: config.locale = Locale.ENGLISH; break; } getResources().updateConfiguration(config, null); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } });
doc_23529749
but The parent page is (php). I found article about that; http://kerneltrap.org/node/65367. I have now HTML file and .JS file that hide the location bar after signed it. But there is a php file, php's file that call the html to do what i need. I found jar protocol can call html without any problem; but Jar can't call php file, is there a solution for that, or jar is not support php. advise me please A: just rename your html file to php and use a include or require to call the php file. As a php file anything not inside a <? yourcodehere ?> or <?php yourcodehre ?> is interpretted as html.
doc_23529750
I have a html form with some checkboxes say A,B,C,D & E and I am posting the form through ajax to one of the controllers. I would like to distinctly identify if each check boxes are checked from the controller and perform some action based on the selected checkbox value. I would like to know the best practise to acheive this. P.S: I will be passing the selected checkbox value to the underlying DAL. A: You can do it in many ways. Here i'm giving a sample idea- Using a model object Lets assume, you have a model "CheckBoxValues" in server side with the fields public class CheckBoxValues { public Boolean A { get; set; } public Boolean B { get; set; } } On your html page, use the code to get values from the checkboxes on a button click handler- var values= {}; var StateOfCheckBoxA = $('#CheckBoxA').is(':checked'); values.A= StateOfCheckBoxA ; var StateOfCheckBoxB = $('#CheckBoxB').is(':checked'); values.B= StateOfCheckBoxB; var SubmitURL = YourController/ActionMethod/ $.ajax({ type: "POST", url: SubmitURL, data: values, dataType: 'json', beforeSend: function () { }, success: function (result) { }, error: function (request, status, error) { }, complete: function () { } }); Now your actionmethod public JsonResult Create(CheckBoxValues values) { Boolean checkboxA=values.A; Boolean checkboxB=values.B; } Hope this will help you.
doc_23529751
ImgList: ["904u3jg8orut390jgg","09re8im09mj3895gh","509tgj390h359"]. I tried and googled the errors each and every one of them, but I could not find a solution. I have even tried to enable longpath in Windows, but it did not work for me. If someone could help me, I would be very grateful. Here is my code. EDIT: I think that the problem is with the splitting and replacing the characters. When I add the string to the list, I am getting an extra quotes and backslash, wrapped in like this "\"... \"". I have tried to trim, to replace the characters but nothing successful. I have tried to change the imgList = imgList.Select(s => s.Replace("\"", string.Empty)).ToList(); with imgList = imgList.Select(s => s.Replace("\\b\"", string.Empty)).ToList(); but it did not work. Any help? //getting data from database string strList = dt.Rows[0]["imgList"].ToString(); List<string> imgList = new List<string>(strList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); imgList = imgList.Select(s => s.Replace("\"", string.Empty)).ToList(); imgList = imgList.Select(s => s.Replace("[", string.Empty)).ToList(); imgList = imgList.Select(s => s.Replace("]", string.Empty)).ToList(); //assign the value pdf.ImageList = imgList; //using iTextSharp foreach (var item in pdf.ImageList) { if (item.Count() >= 1) { Image image = Image.GetInstance(item); } } A: In a comment you mentioned: those images are uploaded, HttpPostedFile in byte[] from Binary Reader and converted ToBase64String the byte[] So those images are base64-encoded... consequentially you have to base64-decode the database contents again to get the image byte arrays. Then you can feed those image byte arrays into Image.GetInstance.
doc_23529752
view function: def blog(request): posts = Post.objects.all().order_by('-date_posted') paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts, 'page_obj': page_obj, 'title': 'Blog', 'banner_page_title': 'Blog', 'page_location': 'Home / Blog' } return render(request, 'blog/blog.html', context) html rendering <nav class="blog-pagination justify-content-center d-flex"> <ul class="pagination"> {% if is_paginated %} {% if page_obj.has_previous %} <li class="page-item"> <a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous"> <span aria-hidden="true"> <span class="ti-arrow-left"></span> </span> </a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item active"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next"> <span aria-hidden="true"> <span class="ti-arrow-right"></span> </span> </a> </li> {% endif %} {% endif %} </ul> </nav> the url route path('blog/', blog, name='blog'), A: Remove the {% if is_paginated %} as it isn't returning any value and that is why you don't see any of the numbers (don't forget to remove the closer if {% endif %}) You can access your paginated objects from the page_obj {% for post in page_obj %} {{ post }} {% endfor %} Here is the HTML with the changes {% for post in page_obj %} {{ post.text }}<br> {% endfor %} <nav class="blog-pagination justify-content-center d-flex"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"> <a href="?page={{ page_obj.previous_page_number }}" class="page-link" aria-label="Previous"> <span aria-hidden="true"> <span class="ti-arrow-left"></span> </span> </a> </li> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <li class="page-item active"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <li class="page-item"> <a href="?page={{ num }}" class="page-link">{{ num }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next"> <span aria-hidden="true"> <span class="ti-arrow-right"></span> </span> </a> </li> {% endif %} </ul> </nav>
doc_23529753
void computeFPS() { numberOfFramesSinceLastComputation++; currentTime = glutGet(GLUT_ELAPSED_TIME); if(currentTime - timeSinceLastFPSComputation > 1000) { char fps[256]; sprintf(fps, "FPS: %.2f", numberOfFramesSinceLastFPSComputation * 1000.0 / (currentTime . timeSinceLastFPSComputation)); glutSetWindowTitle(fps); timeSinceLastFPSComputation = currentTime; numberOfFramesSinceLastComputation = 0; } } My question is, how is the value that is calculated in the sprint call stored in the fps array, since I don't really assign it. A: This is not a question about OpenGL, but the C standard library. Reading the reference documentation of s(n)printf helps: man s(n)printf: http://linux.die.net/man/3/sprintf In short snprintf takes a pointer to a user supplied buffer and a format string and fills the buffer according to the format string and the values given in the additional parameters. Here's my suggestion: If you have to ask about things like that, don't tackle OpenGL yet. You need to be fluent in the use of pointers and buffers when it comes to supplying buffer object data and shader sources. If you plan on using C for this, get a book on C and thoroughly learn that first. And unlike C++ you can actually learn C to some good degree over the course of a few months. A: This function is supposedly called at every redraw of your main loop (for every frame). So what it's doing is increasing a counter of frames and getting the current time this frame is being displayed. And once per second (1000ms), it's checking that counter and reseting it to 0. So when getting the counter value at each second, it's getting its value and displaying it as the title of the window. /** * This function has to be called at every frame redraw. * It will update the window title once per second (or more) with the fps value. */ void computeFPS() { //increase the number of frames numberOfFramesSinceLastComputation++; //get the current time in order to check if it has been one second currentTime = glutGet(GLUT_ELAPSED_TIME); //the code in this if will be executed just once per second (1000ms) if(currentTime - timeSinceLastFPSComputation > 1000) { //create a char string with the integer value of numberOfFramesSinceLastComputation and assign it to fps char fps[256]; sprintf(fps, "FPS: %.2f", numberOfFramesSinceLastFPSComputation * 1000.0 / (currentTime . timeSinceLastFPSComputation)); //use fps to set the window title glutSetWindowTitle(fps); //saves the current time in order to know when the next second will occur timeSinceLastFPSComputation = currentTime; //resets the number of frames per second. numberOfFramesSinceLastComputation = 0; } }
doc_23529754
[LuisIntent("bookConfRoom")] public async Task BookConferenceRoom(IDialogContext context, LuisResult result) { IDialog<RoomBooking> roomBookingDialog = MakeRootDialog(); context.Call(roomBookingDialog, RoomBookingComplete); } MakeRootDialog() builds the FormFlow form: internal static IDialog<RoomBooking> MakeRootDialog() { return Chain.From(() => FormDialog.FromForm(RoomBooking.BuildForm, options: FormOptions.PromptInStart)); } And RoomBooking looks like this: [Serializable] public class RoomBooking { public LocationOptions MeetingLocation; public DateTime MeetingTime; public double NumberOfHours; public int NumberOfAttendees; public List<AmenitiesOptions> Amenities; public static IForm<RoomBooking> BuildForm() { return new FormBuilder<RoomBooking>().Build(); } } When that intent is hit the resume after function RoomBookingComplete runs immediately without the FormFlow appearing. However if I remove FormOptions.PromptInStart then the FormFlow does run, but you have to send another message to the bot before it starts, which is what I thought PromptInStart would fix? I think I'm getting confused with the order of the Dialog stack and/or which dialog context I'm in. Any help will be appreciated. A: You should remove the Chain.From internal static IDialog<RoomBooking> MakeRootDialog() { return FormDialog.FromForm(RoomBooking.BuildForm, options: FormOptions.PromptInStart)); }
doc_23529755
My problem is no matter what I do this firebase query seems to think there are documents in my DB that do not exist. Every time I go to accept the service it displays the toast. Meaning there is a collection "services" where a document has the field "serviceCompleted" which is equal to "false" but in my DB there is no collection "services" under employees My database showing no collection "services" exist underneath "employees" and here is my Kotlin code fun setButton(serviceID: String, eID: String){ val btnAcceptService = view.findViewById<Button>(R.id.btnAcceptService) btnAcceptService.setOnClickListener { val queryEmpServices = database.collection("employees").document(eID).collection("services").whereEqualTo("serviceComplete", false) queryEmpServices.get().addOnSuccessListener { documents -> if (documents != null){ Toast.makeText(applicationContext,"You already have a service active!", Toast.LENGTH_SHORT).show() }else { database.collection("services").document(serviceID).update("saccept", true).addOnSuccessListener { database.collection("services").document(serviceID).get().addOnSuccessListener { document -> if (document != null) { val Location = document.get("ulocation").toString() val serviceType = document.get("serviceType").toString() val uComment = document.get("ucomment").toString() val uID = document.get("uid").toString() if (document.getBoolean("saccept") == true) { database.collection("users").document(document.get("uid").toString()).collection("services").document(serviceID).update("saccept", true).addOnSuccessListener { database.collection("employees").document(mAuth.currentUser!!.uid).get().addOnSuccessListener { document -> if (document != null) { val calendar = Calendar.getInstance() val simpleDateFormat = SimpleDateFormat("dd-MM-yyyy HH:mm:ss") val acceptDate = simpleDateFormat.format(calendar.time) val eFullName = document.get("ename").toString() + " " + document.get("esurname").toString() val eCompany = document.get("ecompany").toString() database.collection("users").document(uID).get().addOnSuccessListener { document -> val uName = document.get("name").toString() val uPhonenumber = document.get("phonenumber").toString() val serviceAccept = EmployeeServiceAccept(acceptDate, serviceID, Location, serviceType, uComment, uName, uPhonenumber, false) database.collection("employees").document(mAuth.currentUser!!.uid).collection("acceptedservices").document(serviceID).set(serviceAccept) database.collection("services").document(serviceID).update("acceptedby", eFullName + ", " + eCompany) database.collection("users").document(uID).collection("services").document(serviceID).update("acceptedby", eFullName + ", " + eCompany) Toast.makeText(applicationContext, "Service Accepted", Toast.LENGTH_SHORT).show() } } } } } } else { Toast.makeText(applicationContext, "Failed to accept service", Toast.LENGTH_SHORT).show() } A: When you are using the Task.addOnSuccessListener(OnSuccessListener) method on a Query object, the result that you get can be a success or a failure, never both and never null. It will always be one, or the other. That being said, you should never check the documents object against nullity because it can never be null. What you should do instead, is to check the "documents" object, which is of type QuerySnapshot to see if isEmpty() or not: if (!documents.isEmpty){ Toast.makeText(applicationContext,"You already have a service active!", Toast.LENGTH_SHORT).show() } else { Toast.makeText(applicationContext,"You don't have a service active!", Toast.LENGTH_SHORT).show() } Where indeed the Toast message from the "else" part of the statement will be displayed, as there are no documents present in the QuerySnapshot object: "You don't have a service active!"
doc_23529756
-code is same in both environments -.NET 4.0 web application deployed to IIS -log4net.config is same in both environments -logs to text file on same drive as application that runs it -logger is instantiated in static class, used through whole application. -global.asax application_start configures logger by building FileInfo object that points to log4net.config and doing this log4net.Config.XmlConfigurator.ConfigureAndWatch(file); Does anyone have any advice? I'm sorry if this question is vague or needs more information. I'm unsure where to begin with troubleshooting this. I'll add any requested information. A: The user from your application pool needs to have write rights to the logging directory, check is the rights on both environments are the same.
doc_23529757
So the obvious thing here is that tile of size d x d could tile the floor of size a x b if gcd(a, b) mod d = 0. So the simplest way would be: * *go over all sizes of floors *for each size of floor: a. calculate gcd(a, b) b. go over all tiles and check how many of them divides by gcd(a,b) But this seems to be too slow - I got 2/3 tests passed on the task. The complexity seems to be O(m*n*log(size)). Any idea how to do that better (faster)?
doc_23529758
const { useRef } = React const Main = props => { const textInput = useRef() const EN = useRef() const move = useRef() var randomize = Math.floor(Math.random() * 1320) const [change, setchange] = React.useState(1) const cursors = { pointerEvents: "none", borderRadius: "50%", width: "20PX", height: "20PX", backgroundColor: "red", position: "fixed", transform:"translate3d(-10px,-10px,15px)", }; const enemy = { zIndex: "-1", borderRadius: "20%", width: "30PX", height: "30PX", backgroundColor: "green", position: "absolute", left: "${change}px", }; const borders = { width: "1300px", height: "620px", backgroud: "#ccc", border: "4px solid #333", position: "absolute", right: "500px" } const testi = { background: "steelblue", color: "white", padding: "1.5rem" } function enem() { setchange(change + Math.floor(Math.random() * 1320)) EN.current.style.left = randomize + "px" console.log("FSDF") } React.useEffect(() => { document.addEventListener("mousemove", (event) =>{ textInput.current.style.top = event.clientY + 'px' textInput.current.style.bottom = event.clientX + 'px' textInput.current.style.left = event.clientX + 'px' textInput.current.style.right = event.clientY + 'px' console.log(event.clientY) if(textInput.current.style.right == "1320px"){ console.log("help") } }) console.log(textInput.current.style.left) }); return ( <div style={borders} > <div ref={textInput} style={cursors}></div> <div style={enemy} ref={EN}></div> <div className={"pe"} ref={move}></div> <button onClick={enem}>Move randomly</button> </div>) } ReactDOM.render(<Main />, document.getElementById("root")); A: Without looking deeply into this, it looks like your useEffect is continually adding event listeners and never removing them on cleanup. This looks like a memory leak to me. This may help: https://www.roundthecode.com/front-end-development/react/how-to-use-onclick-onmouseover-async-events-react
doc_23529759
So, using this guide I created python server that listens for webhooks and exposed it via NGROK service. from flask import json from flask import request import requests from flask import Flask, request, url_for, redirect, render_template app = Flask(__name__) @app.route('/') def api_root(): return "WEBHOOK" @app.route('/*MyHtmlVerificationFile*') def admin(): return render_template('*MyHtmlVerificationFile*') @app.route('/notif', methods=['POST']) def api_gd_message(): data = request.get_data() header = request.headers print(data) print(header) return '' if __name__ == '__main__': app.run(debug=True) Then, according to this example I've verified ownership of the URL domain and registered it, got credential and wrote script to track changes. from oauth2client.service_account import ServiceAccountCredentials from oauth2client.client import OAuth2Credentials from pygdrive3 import service import uuid import requests import json channel_id = str(uuid.uuid4()) JSON_KEY_FILE = "creds.json" SCOPES = ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, SCOPES) access_token_info = credentials.get_access_token() token = access_token_info.access_token header = { 'Authorization': f'Bearer ' + token, 'Content-Type': 'application/json', } body = { "id": channel_id, "type": "web_hook", "address": "https://*MyDomain*/notif" } r = requests.post(url='https://www.googleapis.com/drive/v3/changes/watch?pageToken=101', data=json.dumps(body), headers=header) print(r.content) Which result is: b'{\n "kind": "api#channel",\n "id": "MyId",\n "resourceId": "*MyResourceId*",\n "resourceUri": "*MyRsourceUri*",\n "expiration": "1612820606000"\n }\n' Process finished with exit code 0 And there is server's message when Webhook launched. 127.0.0.1 - - [08/Feb/2021 21:43:20] "POST /notif HTTP/1.1" 200 - b'' Host: *MyDomain* User-Agent: APIs-Google; (+https://developers.google.com/webmasters/APIs-Google.html) Content-Length: 0 Accept: */* Accept-Encoding: gzip,deflate,br X-Forwarded-For: 66.249.88.84 X-Forwarded-Proto: https X-Goog-Channel-Expiration: Mon, 08 Feb 2021 21:43:26 GMT X-Goog-Channel-Id: *MyChannelId* X-Goog-Message-Number: 1 X-Goog-Resource-Id: *MyResourcelId* X-Goog-Resource-State: sync X-Goog-Resource-Uri: *MyResourcelUri* Problem is there are no messages when I do something (edit, delete, rename, etc.) with files on the Gdrive.
doc_23529760
In other words, I wanted #page-content to have a width that is equal to the width of all the images inside it. This is because i would like the page-content div to be wider than the browser window, so that the user can scroll from left to right. the code I had was as follows: <div id="page-content"> <div id="gallery"> <div> <a href="#" class="shutterset"> <img src="images/pic1.jpg"/> </a> <a href="#" class="shutterset" > <img src="images/pic2.jpg" /> </a> <a href="#" class="shutterset" > <img src="images/pic3.jpg" /> </a> <a href="#" class="shutterset" > <img src="images/pic4.jpg" /> </a> <a href="#" class="shutterset" > <img src="images/pic5.jpg" /> </a> <a href="#" class="shutterset" > <img src="images/pic6.jpg" /> </a> <a href="#" class="shutterset" > <img src="images/pic7.jpg" /> </a> <a href="#" class="shutterset" > <img src="images/pic8.jpg" /> </a> </div> <div class="clear"> </div> <p>hi</p> </div> </div> And the jQuery I tried out was: $(document).ready(function() { $("p").html($("#gallery img:first").width()); }); I'd done this to test to see if the width was being calculated, but it doesnt seems to be. The result is always 0, as opposed to the width of the image. Would appreciate any help Seedorf A: I suggest adding a class to the images as you have the links, i.e. <img class="shutterimg" and trying this in a $(window).load function to be sure they have loaded: var totalwidth = 0; $('img.shutterimg').each(function() { totalwidth += $(this).width(); }); $('#gallery').width(totalwidth); A: Image widths are not calculated until the image is downloaded, unless the width attribute is specified. Your handler executes on $(document).ready() -- this is when the whole DOM has loaded but will almost certainly be before the images have loaded. Wait for the $(window).load() event instead: this is triggered when all the content (images, stylesheets and scripts) has loaded. $(window).load(function() { $("p").html($("#gallery img:first").width()); });
doc_23529761
The official website prints out the requirement of 3.1.0 but at the same time it provides the wrong package 3.0.0. https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html#protobuf-library-related-issues A: I just changed 3.0.0 to 3.1.0 in the URL, so https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.1.0-cp27-none-linux_x86_64.whl instead of https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.0.0-cp27-none-linux_x86_64.whl Seems to work just fine! A: pip uninstall protobuf pip install -U protobuf worked for me. A: If you are using poetry you can update protobuf with the right versions poetry add "probuf@>=3.9.2,<3.20" and then poetry add tensorflow. The same with pip, upgrade protobuf to the specified version and then run pip install tensorflow. A: One solution is to use pip install protobuf. One can also download the whl package from https://pypi.python.org/pypi/protobuf/3.1.0 and run pip install protobuf-3.1.0-py2.py3-none-any.whl
doc_23529762
char item_availablity[16]; I can encode it with 2 bytes where every bit is mapped with one item id where 1 represents available and 0 represents unavailable For ex 0000100010001000 This number has information that Items with id 4,8,12 are available I need to encode this information by using less than 2 Bytes. Is this possible? If so, how? A: To put it simply: No, you cannot. It's simply impossible to store 1 bit of information about 16 separate things in less than 16 bits. That is, in the general case. An exception is if there are some restrictions. For instance, let's call the items i_1, i_2 ... i_16. If you know that i_1 is available if and only if i_2 also is available, then you can encode the availability about these two items in just one bit. A more complicated example is that i_1 is available iff i_2 or i_3 is available. Then you could store the availability for these three items in two bits. But for the general case, nope, it's completely impossible. A: Trying to think out of the box here - If some items are more rare than others, you could use a variable length encoding so that, on average, it would take less than 16 bits to store the information. However, there will be combinations of availabilities where it would take more than 16 bits.
doc_23529763
For reference the Web API GET controller method that creates the cookie looks like ... HttpResponseMessage resp = new HttpResponseMessage() { Content = new JsonContent(results) }; if (results.Token != null) { var cookie = new CookieHeaderValue("XSRF-TOKEN", results.Token); cookie.Expires = DateTimeOffset.Now.AddDays(365); cookie.Domain = Request.RequestUri.Host; cookie.Path = "/"; cookie.HttpOnly = false; resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); } return resp; ... Using Fiddler I can see the cookie in the response. Now I'm expecting 2 things * *all subsequent API calls to that same domain should include this cookie in the request header *Angular should be adding the X-XSRF-TOKEN header I mentioned earlier Neither one is happening (I'm checking with Fiddler). I've tried with the site and API in the same domain (like localhost) and in different domains. Some sources I've checked: * *https://docs.angularjs.org/api/ng/service/$http *https://stormpath.com/blog/angular-xsrf I also tried adding $httpProvider.xsrfWhitelistedOrigins = [webServicesPath]; where webServicesPath is a variable I use for the API path but it makes no difference. A: You should use something like following public void Configure(IApplicationBuilder app, IAntiforgery antiforgery) { context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false }); } public void ConfigureServices(IServiceCollection services) { // Angular's default header name for sending the XSRF token. services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); }
doc_23529764
I've added if statement to sort by select statement like this: I've tried to add an if statement to sort manually by selecting but, no results changing. Am I missing something or how do I fix it? public function search(Request $request){ $cityKey = $request->cityKey; $key = $request->key; $doctors = Doctor_list::where('speciality_title', 'LIKE', '%' . $key . '%')-> where('location', 'LIKE', '%' . $cityKey . '%')-> orWhere('doctors_name', 'LIKE', '%' . $key . '%')-> where('location', 'LIKE', '%' . $cityKey . '%')-> orWhere('speciality_type', 'LIKE', '%' . $key . '%')-> where('location', 'LIKE', '%' . $cityKey . '%')->get(); If ($request->get('sortBy') === 'rate'){ dd($doctors->orderBy('rate', 'desc')); } return view('healthflex.search', compact('doctors')); } <select name="sortBy" class="select"> //THIS IS SELECT STATEMENT <option>choose</option> <option class="sorting" value="rate}">rate</option> <option class="sorting">Popular</option> <option class="sorting">Ohirgi</option> A: Try this $doctors = Doctor_list::where('speciality_title', 'LIKE', '%' . $key . '%')-> where('location', 'LIKE', '%' . $cityKey . '%')-> orWhere('doctors_name', 'LIKE', '%' . $key . '%')-> where('location', 'LIKE', '%' . $cityKey . '%')-> orWhere('speciality_type', 'LIKE', '%' . $key . '%')-> where('location', 'LIKE', '%' . $cityKey . '%') ->orderBy($request->input('sortBy', 'id'), 'desc'); if you don't even apply the sort if the sortBy value is not passed in request you may do instead ->where('location', 'LIKE', '%' . $cityKey . '%') ->when($sortBy = $request->input('sortBy'), function($query) use($sortBy){ $query->orderBy($sortBy , 'desc'); }); Now you can return the result return view('healthflex.search', compact('doctors'));
doc_23529765
All i want is an <img src="" /> in a <a> tag. The A has a given width, height and overflow:hidden; Now how can I show only center part of img without knowing the image size? Here is a fiddle and this is the code I've got: <a href=""> <img class="center" src="http://images2.fanpop.com/images/photos/7000000/Nature-Around-the-World-national-geographic-7018209-1440-900.jpg" /> </a> <a href=""> <img class="center" src="http://naturalgeographic.net/wp/wp-content/uploads/2013/05/rock-climbing.jpg" /> </a> <style type="text/css"> a { position:relative; display:inline-block; width:300px; height:300px; overflow:hidden; border:solid 5px orange; } img.center { position:absolute; display:inline-block; top:-50%; left:-50%; } </style> If not possible with only those elements I can add whatever needed. BUT would like a only html/css solution no javascript. Thanks for helping. A: I would suggest to use a background image instead of an img tag. This way you can display just the center part of an image by: background:url('http://naturalgeographic.net/wp/wp-content/uploads/2013/05/rock-climbing.jpg') no-repeat center center; Here is the dirty updated JSFiddle. A: You need to manipulate img width and height, without it you will not be able to put the picture relative to it's parent container. Something like this: position: absolute; display: inline-block; top: -50%; left: -50%; width: 200%; height: 200%; Here's your fiddle: http://jsfiddle.net/9JmQe/
doc_23529766
error: invalid use of non-static data member Here's the code sample: Player.h: #ifndef _PLAYER_H_ #define _PLAYER_H_ #include "Segment/Dynamic_Segment.h" class Attributes_P; class Player; class Attributes_P : public Attributes_DS{ protected: Player *rel; int inv_mcols, inv_mrows; public: Attributes_P(); void controls( int MKEY_UP, int MKEY_RIGHT, int MKEY_DOWN, int MKEY_LEFT ); void inventory( int inv_mcols, int inv_mrows ); }; class Player : public Dynamic_Segment{ protected: int **inv; public: int MKEY_UP, MKEY_RIGHT, MKEY_DOWN, MKEY_LEFT; public: Player(); Attributes_P set; friend class Core; friend class Attributes_P; }; #endif Player.cpp: #include "Segment/Player.h" Attributes_P::Attributes_P(){}; Player::Player() : Dynamic_Segment(){ set.inv_mcols = 0; set.inv_mrows = 0; } void Attributes_P::inventory( int inv_mcols, int inv_mrows ) { this->inv_mcols = inv_mcols; this->inv_mrows = inv_mrows; &rel.inv = new int*[this->inv_mcols]; for( int i = 0; i < this->inv_mrows; i++ ) { &rel.inv[i] = new int[this->inv_mcols]; } } void Attributes_P::controls( int MKEY_UP, int MKEY_RIGHT, int MKEY_DOWN, int MKEY_LEFT ) { &rel.MKEY_UP = MKEY_UP; &rel.MKEY_RIGHT = MKEY_RIGHT; &rel.MKEY_DOWN = MKEY_DOWN; &rel.MKEY_LEFT = MKEY_LEFT; } Have been banging my head against a wall for some time now... Any ideas would be appreciated! A: Now I see. I think it's &rel. should be rel-> i.e. rel->MKEY_UP = MKEY_UP; Did you mean (*rel).MKEY_UP? This also works.
doc_23529767
response-code: 400 details: name: DPRP_DISABLED message: DPRP is disabled for this merchant. details: null debug-id: *********** information-link: https://developer.paypal.com/webapps/developer/docs/api/#DPRP_DISABLED at com.paypal.base.rest.PayPalRESTException.createFromHttpErrorException(PayPalRESTException.java:72) at com.paypal.base.rest.PayPalResource.execute(PayPalResource.java:431) at com.paypal.base.rest.PayPalResource.configureAndExecute(PayPalResource.java:295) at com.paypal.base.rest.PayPalResource.configureAndExecute(PayPalResource.java:228) at com.paypal.api.payments.Agreement.create(Agreement.java:145) I know I need to upgrade my sandbox account to pro but in contrary as stated in the sandbox account documentation: On the Profile page of the Business account, click the Account type: Upgrade to Pro link. there is no such thing to click: So how can I activate DPRP? A: Please kindly reach the PayPal MTS team to help you enable the DPRP access for your sandbox account.
doc_23529768
Recently, my ISP was giving me lots of trouble and then I decided to change to a VPS to have more control of the system. I have installed on this VPS everything my App needs to work (MySQL, php, apache, phpmyadmin) everything is working fine. I started to move the databases and PHP files to the VPS and made the necessary changes to the PHP files to access the new DBs, user, password, etc... Using the PHP files, I managed to read and write on the DBs, but I could not COPY data between two DBs or DELETE data. When I give the copy and delete commands thru PHPMyAdmin's console it is working, but when I do the same thing via PHP it does not. This exact code is working perfectly on the older server... what can be wrong? This is my code: <?php ini_set('default_charset','UTF-8'); $con=mysqli_connect("url","user","pass","db_name"); mysqli_set_charset($con,"utf8"); if (mysqli_connect_errno($con)) { echo '{"query_result":"ERROR"}'; } $emp_id = $_GET['id']; $result = mysqli_query($con,"INSERT INTO publiagenda SELECT * FROM moderagenda WHERE id = $emp_id DELETE * FROM moderagenda WHERE id = $emp_id"); if($result == true) { echo <<<HTML <br><center>Dados Publicados no app e apagados da tabela de moderacao</center></big HTML; echo <<<HTML <br><center><big><a href="http://appdacidade.net.br/app/agenda/publish_agenda.php">Voltar</a></center></big HTML; } else { echo '{"query_result":"FAILURE"}'; } mysqli_close($con); ?> With the valuable help of the members of this community, my code is now working, following is the corrected code: <?php ini_set('default_charset','UTF-8'); $con=mysqli_connect("url","user","pass","db_name"); mysqli_set_charset($con,"utf8"); if (mysqli_connect_errno($con)) { echo '{"query_result":"ERROR"}'; } $emp_id = $_GET['id']; $result = mysqli_query($con,"INSERT INTO publiagenda SELECT * FROM moderagenda WHERE id = $emp_id"); if($result == true) { header("Location: ./dados_publicados.html"); } else { echo '{"query_result":"FAILURE"}' . mysqli_error($con); } mysqli_close($con); ?>
doc_23529769
<input type="text" value="Enter Password" class="password" /> ... onclick/onfocus, I'd like to change the input type to 'password' and value removed, like so: <input type="password" value="" class="password" /> This doesn't seem to work: $('input.password').click(function () { $(this).attr('type', 'password'); }); (See this question for why I want to do this) This works, but just one problem, I need to click twice to be able to type in the pass field: var passField = $("input.password"); var passFieldNew = passField.clone(); $('input.password').click(function () { passFieldNew.attr("type", "password"); passFieldNew.attr("value", ""); passFieldNew.insertBefore(passField); passField.remove(); }); how do I fix that problem? Thanks! A: You cannot change the type attr while the element is in the DOM, but if you remove it first you can. The following should work (tested, but only in firebug). The password class will be kept since it's the same element you insert again. var $pwd = $('input.password').remove(); // Note, might be better to select on ID $pwd.attr('type', 'password'); $pwd.val(''); $('#ABC').after($pwd); // Insert it somewhere in the DOM again A: What if you had a hidden password field that you swap in for the text field when it get the focus? Something like this (untested): <style type="text/css" media="screen"> #password { display: none; } </style> <script type="text/javascript"> $(document).ready(function() { $('#text').focus(function() { $(this).hide(); $('#password').show().focus(); }); }); </script> <input type="text" value="Enter Password" class="password" id="text" /> <input type="password" value="" class="password" id="password" /> When the text field receives focus, it hides itself, shows the password field, and sets the focus to the password field. If you styled the text field and password field to look the same, it should be seamless. A: You can't change the type of the input field at runtime, but you can do a crafty switch by replacing it with a new one: <script type="text/javascript"> $(function() { var password = $("#myPassword").val(); $("#myPassword").remove(); $("#form").append('<input id="myPassword" type="text" class="password" />'); $("#myPassword").val(password); }); </script> <div id="form"> <input id="myPassword" type="password" value="Enter Password" class="password" /> </div>
doc_23529770
In my development machine, it is building by Visual Studio 2013 successfully. But when I try to build same sources on Linux Mono environment with xbuild, it is failing. Here is the output: root@jannes:/home/hitly/hitly/src/Hitly.Service# xbuild XBuild Engine Version 12.0 Mono, Version 3.2.8.0 Copyright (C) 2005-2013 Various Mono authors Build started 3/31/2014 2:11:49 PM. __________________________________________________ Project "/home/hitly/hitly/src/Hitly.Service/Hitly.Service.csproj" (default target(s)): Target RestorePackages: Executing: mono --runtime=v4.0.30319 ../.nuget/NuGet.exe install "" -source "" -RequireConsent -solutionDir "../" The specified path is not of a legal form (empty). /home/hitly/hitly/src/.nuget/NuGet.targets: error : Command 'mono --runtime=v4.0.30319 ../.nuget/NuGet.exe install "" -source "" -RequireConsent -solutionDir "../"' exited with code: 1. Task "Exec" execution -- FAILED Done building target "RestorePackages" in project "/home/hitly/hitly/src/Hitly.Service/Hitly.Service.csproj".-- FAILED Done building project "/home/hitly/hitly/src/Hitly.Service/Hitly.Service.csproj".-- FAILED Build FAILED. Errors: /home/hitly/hitly/src/Hitly.Service/Hitly.Service.csproj (default targets) -> /home/hitly/hitly/src/.nuget/NuGet.targets (RestorePackages target) -> /home/hitly/hitly/src/.nuget/NuGet.targets: error : Command 'mono --runtime=v4.0.30319 ../.nuget/NuGet.exe install "" -source "" -RequireConsent -solutionDir "../"' exited with code: 1. 0 Warning(s) 1 Error(s) Time Elapsed 00:00:00.7254640 I couldn't understand reason of the error. How can I build these sources on Linux? A: Fixed! I simply added PackagesConfig element to .nuget/NuGet.targets: <PropertyGroup Condition=" '$(OS)' != 'Windows_NT'"> <!-- We need to launch nuget.exe with the mono command if we're not on windows --> <NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath> ++++<PackagesConfig>packages.config</PackagesConfig> </PropertyGroup> A: NuGet.targets is a key file for NuGet package restore, but its versions are not well managed by NuGet guys. The issue you met simply indicates that the version you use is not Mono friendly. Your edit might work, but I recommend you keep an eye on NuGet Git repository to grab the latest, such as http://nuget.codeplex.com/SourceControl/latest#src/Build/NuGet.targets. Hope NuGet guys can do more testing on Mono as that can prevent similar issues in the long run. (Please forget about this answer. NuGet latest console can run on latest Mono and the restore mechanism is also changed to get rid of this targets file.)
doc_23529771
I want to be able to call this API from another server server2. This server calls the API of server1 without any user interaction (for backup purposes, amongst other things). What would be the best way to authenticate server2 when calling the server1 API ? I could create a specific technical user which has the role 'ROLE_SUPERVISOR', but I read that the client credential grant type might suit this case better (server to server authentication). I would then only have to create a new client application and register it in the authorization server. However, how do I add the role 'ROLE_SUPERVISOR' to a client application ? Thanks. A: I think that there are some terms being using the comments and in the question that are confusing the issue a bit. So I need server2 to have the 'ROLE_SUPERVISOR' in order to access this API. With OAuth 2.0, servers aren't the things with roles. A token has claims and those claims can be interpreted by an application. As mentioned in the question, you can obtain a token in a number of ways, one of them being the client credentials grant. However, how do I add the role 'ROLE_SUPERVISOR' to a client application It's also not entirely correct to say that clients have roles. I believe the OP wants server2 to pass an OAuth 2.0 token to server1, and that the given token should have the appropriate claims in it such that server1 will grant the corresponding request with a ROLE_SUPERVISOR granted authority. To get such a token with the client credentials grant, you'll need to configure a client in the authorization server: @Override protected void configure(ClientDetailsServiceConfigurer clients) { clients.inMemory() .withClient("id") .authorizedGrantType("client_credentials") .authorities("ROLE_SUPERVISOR") .secret("{noop}secret") } Then, server2 can use the client id and secret configured to obtain a token. As already stated, Spring Security ships with filters for negotiating with authorization servers and adding the appropriate Authorization header to the call to server1.
doc_23529772
See code below <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script> </script> <script type= "text/javascript"> var geocoder; var map; var count=0; //Store points in array var points = []; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 3, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"),myOptions); } function codeAddress() { var address = document.getElementById("address").value; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { alert("Geocode was not successful for the following reason: " + status); } }); } function plusCount(){ if (count==2){ count=0; } else{ count=count +1; } } function drawCircle() { var address=document.getElementById("address").value; var radius=document.getElementById("radius").value; var latitude=40; var longitude=0; geocoder.geocode( { 'address': address}, function(results, status){ if (status==google.maps.GeocoderStatus.OK){ latlng=(results[0].geometry.location); latitude=latlng.lat(); longitude=latlng.lng(); alert(latitude); alert(longitude); alert (radius); } else{ alert("Geocode was not successful for the following reason: " + status); } }); //Degrees to radians var d2r = Math.PI / 180; alert("calc d2r " + d2r); // Radians to degrees var r2d = 180 / Math.PI; alert("calc r2d " + r2d); // Earth radius is 3,963 miles var cLat = (radius / 3963) * r2d; alert("calc cLat " + cLat); var cLng = cLat / Math.cos(latitude * d2r); alert("calc cLng " + cLng); // Calculate the points // Work around 360 points on circle for (var i=0; i < 360; i++) { var theta = Math.PI * (i/16); // Calculate next X point circleY = longitude + (cLng * Math.cos(theta)); // Calculate next Y point circleX = latitude + (cLat * Math.sin(theta)); // Add point to array points.push(new google.maps.LatLng(circleX, circleY)); }; alert("completed loop"); var colors=["#CD0000","#2E6444","#003F87" ]; var Polyline_Path = new google.maps.Polyline({ path: points, strokeColor: colors[count], // color of the outline of the polyline strokeOpacity: 1, // between 0.0 and 1.0 strokeWeight: 1, // The stroke width in pixels fillColor: colors[count], fillOpacity: .5 }); Polyline_Path.setMap(map); } function clearMap(){ if(points){ for( i in points){ points[i].setMap(null); } points.length=0; }} </script> </head> <body onload="initialize()"> <div id="map_canvas" style="width:500px; height:460px; -moz-outline-radius:20px; -moz-box-sizing:padding-box; -moz-outline- style:solid ;-moz-outline-color:#9FB6CD; - moz-outline-width:10px;"></div> <div> Zip Code: <input id="address" type="textbox" value=""> Radius:<input id="radius" type="textbox" value=""> <input type="button" value="Find" onclick="codeAddress() "> <input type="button" value="Draw Radius" onclick= "drawCircle() ; plusCount()"> <input type="button" value="Reset" onclick= "clearMap()"> </div> </body> A: It looks like you are drawing the circle manually, but you could use the google.maps.Circle which works for me and fills the circle entirely. Here is a snippet I use in my application, which works also in maximum zoom level: var circ = new google.maps.Circle({ 'center':lc, 'clickable':false, 'fillColor':"#00FFFF", 'fillOpacity':0.2, 'map':currentmap, 'radius':75, 'strokeColor':'#0000A0', 'strokeOpacity':'0.5' }); lc is my center point, currentmap is the map div A: This method works for me var options = { strokeColor: #CD0000, strokeOpacity: 0.8, strokeWeight: 2, fillColor: #2E6444, fillOpacity: 0.5, map: map, center: latlng, radius: parseInt(radius) }; var circle = new google.maps.Circle(options); A: var drawInnerZone= { strokeColor: "#61A0A8", strokeOpacity: 0.2, strokeWeight: 1, fillColor: "#61A0A8", fillOpacity: 0.8, map: map, center: NearMatches['InnerZone'].center, //Latlng radius: NearMatches['InnerZone'].Distance //radius }; MatchZone1 = new google.maps.Circle(drawInnerZone); it works for me.. A: the answer for richie work correctly on my project function searchLocations() { var image='image/male.png' var a = document.getElementById("radiusSelect").value; var address = document.getElementById("addressInput").value; var geocoder = new google.maps.Geocoder(); geocoder.geocode({'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, icon: image }); var circle = new google.maps.Circle({ map: map, radius: parseInt(a), // 10 miles in metres fillColor: '#AA0000' }); circle.bindTo('center', marker, 'position'); searchLocationsNear(results[0].geometry.location); } else { alert(address + ' not found'); } }); }
doc_23529773
I'm looking for any suggestions about how to scrape the web page. The only option I see right now is finding the chrome process, triggering the inspector, clicking inside, then running the Javascript. Needless to say, this sounds fragile. I also haven't been able to find anything on capturing the Ajax calls from selenium so I can make them and capture the JSON. When tried copy / paste from the chrome network tab into selenium I got a missing application block message. Does anyone have any other advice? Since I can replicate the issue in the chrome debugger, I don't see posting code as useful. It looks like a design decision. Ralph A: Sadly, I wasn't able to do things in a straightforward way. Instead, I used Selenium to do the login and navigate to the page, then use windows API calls to click inside the window send ^a^c to copy the data and an absolute location to click on the button to go to the next page. The site is set up so that ^a^c copies the raw data for this site. I don't know if that's standard for Angular or not. Fragile, but it works.
doc_23529774
mongo mydb myscript.js --eval "parameter = 'value'" However, I want the script to still work without requiring the --eval. If this were browser-based JS, I'd just do a var internalParameter = window.parameter || null sort of thing to get around the ReferenceError thrown by checking for an undefined variable, but mongo doesn't have window. Is it possible to access variables through the global object in Mongo scripting, or do I just have to wrap this in a try/catch? A: Now that I've learned a little more about common JavaScript idioms, I know you can also do: var internalParameter = typeof parameter == "undefined" ? null : parameter A: In myscript.js you can do: var parameter = parameter || null; If parameter is passed in via the --eval it will have that value, otherwise it will be null. UPDATE To do it without defining the input variable you can use the fact that this refers to the global object in the shell and do: var internalParameter = this.parameter || null; A: Yes. Your script could set a default like this: var parameter = parameter || 'default'; print('parameter = ' + parameter); And then it would be possible to pass parameters or leave the default: % mongo script.js MongoDB shell version: 2.0.7 connecting to: localhost:27017/test parameter = default % mongo script.js --eval "var parameter = 'something else';" MongoDB shell version: 2.0.7 connecting to: localhost:27017/test parameter = something else A: I did the following to solve a similar problem: function set_param(name, default_val) { if (typeof this[name] === "undefined") this[name] = default_val; } set_param("DAYS_BACK", 180); set_param("BATCH_SIZE", 1000); Now if either of the parameters is given with an --eval argument, MongoDB shell will use what was provided. Otherwise it will use the default supplied by the second argument to set_param(). The variables whose names were given as the first argument to set_param() are safe to use once set_param() is executed regardless of the use of --eval.
doc_23529775
class Foo { std::vector<Thing>things; void bar(); } I need to modify the Thing's stored in things in bar: void bar(){ //How do I read a Thing stored in the vector, without making a copy? Thing thing = things[0]; // Doesn't this make a copy ? //..... } How do I read a Thing stored in the vector, without making a copy? If I do: Thing &thing = things[0]; the members of thing are not initialized. A: The second snippet is spot-on: the line below does not make a copy. Thing &thing = things[0]; Something else is wrong with your code, probably a copy constructor. Since thing variable is a reference to the object inside the vector, if you see thing partially initialized, the object inside the vector is partially initialized as well. To fix this problem, make sure that your code has a proper copy constructor, and follows the rule of three. But why do I need a copy constructor if I am using a reference? Since your vector contains objects, not pointers, copy constructor gets invoked when your object is inserted into vector<Thing>. If the copy constructor is required because your constructor allocates resources, but is not provided, your object may end up partially initialized when the destructor of the object that has been inserted into the vector is invoked. A: You can use pointers. Thing *thing = &things[0]; thing->pong(); If this is not initialized either, your vector is not ready. A: You can use iterator: vector<Thing>::iterator iter = things.begin(); //then use iter as a pointer; *iter = Thing();
doc_23529776
If using command prompt-say user press -r and then enter key, then the license header is removed from all the files and if user presses -a then license is added to all the files and replaces the previous one. I tried license maven plugin but it was not removing the headers and on adding header it automatically adds one after the other everytime. Requirement is now to develop a java code for such thing now. Is there any way you could help. Thanks
doc_23529777
You can edit the task by just clicking on it. At the first attempt, it works properly and the localStorage is updated. But, when we try to edit the same item again, its reading it as undefined. And hence an error is thrown: Cannot read property 'toLowerCase' of undefined Its at this line: if($("#new_data").val().toLowerCase() === item[0].toLowerCase()){ // line # 263 One of these two ^ have the value as undefined for some reason. What am I missing? jsFiddle EDIT: Recreating the issue: Add a new item > edit it to something else > click somewhere else so it saves > now edit it again to something else and click somewhere else again > There should be an error in the console. I am using Chrome v35. A: You seem to be attaching a new delegated event handler to "focusout enter" for #new_data every time you call editItem(). The first event handler will work fine, but the second (or possibly third, fourth, etc.) will always throw the undefined exception, since the first handler will have already destroyed the #new_data element with this line: $(element).find('textarea') .replaceWith("<p class='item_content'>"+$("#new_data").val()+"</p>"); There's a couple of ways you can tackle this: A) Pull the whole event binding out of the editItem function, and only ever call it once: function editItem() { /* do stuff */ } $(document).on("focusout enter", "#new_data", function(){ /* do stuff */ }); B) Name the event handler and call .off before you bind a new one: function focusOutHandler(){ /* do stuff */ } $(document).off("focusout enter", "#new_data", focusOutHandler) .on("focusout enter", "#new_data", focusOutHandler); And C) My personal favourite -- don't delegate it $(element).find('textarea').on("focusout enter", function() { /* do stuff */ }); e.g. http://jsfiddle.net/5Z67W/
doc_23529778
E.g. When the values of data 1 is the same of values in data 2, there's an confirmation box will pop up and open new tab. But when data 1 and 2 are both different values there's a two confirmation box will pop up, first is for data 1 and open new tab. Second, for data 2 and open new tab again (for data 2) Please help me. I'm a newbie in JavaScript. Thank you Here's the link of complete updated code of comparing values and open new tab // When both addresses have same values if (data 1=== data 2) { if (confirm("Do you want to proceed on Google Maps and search for Contact Address?") == true) { gmaps = tabCreate("http://maps.google.com/maps?q=" + encodeURIComponent(response.data.data1)); } else { gmaps = ""; } } // When both addresses have different values if (data1!= data2) { if (confirm("Do you want to proceed on Google Maps and search for Permanent Address?") == true) { gmaps = tabCreate("http://maps.google.com/maps?q=" + encodeURIComponent(response.data.data2)); } else { gmaps = ""; } } Here's the code link of two data 1 and 2 A: In your code: function scanLapVerification() { try { try with no catch indicates that at least there is no point in the try. Remove it. //check if the page is activity where address check is done var page_title = "Prelim checks - CB BAP"; var el = getElement(document, "class", "view-operator-verification-title", ""); What does getElement do? What does it return? if (!el || el.length == 0) return; if (el[0].innerText != page_title) return; var page_title = ''; page_title is used once, the its value is changed and it's not used again. The line above doesn't seem to do anything useful. var el = getElement(document, "class", "workflowActivityDetailPanel", ""); if (el && el.length > 0) { Without knowing what getElement returns, or how it works, it's impossible to tell if that test is suitable or not. var eltr = getElement(el[0], "tag", "tr", ""); I'll guess that eltr is an Array of tr elements (I might be wrong though…). if (eltr && eltr.length > 0) { //Read Contact and Permanent address var addresses = { D1: { province: null, municipality: null, barangay: null, zip: null, street: null, snumber: null } ,D2: { province: null, municipality: null, barangay: null, zip: null, street: null, bnumber: null } }; var address_type = null; There is rarely a need to initialise a variable to null, they are initialised to undefined by default which suits most purposes. for (var i = 0; i < eltr.length; i++) { tr_text = eltr[i].innerText; Not all browsers support innerText, you may need a function with some feature detection that uses textContent or innerText depending on which is supported. if (tr_text.substr(0, "Data 1".length) == "Data 1") address_type = "D1"; if (tr_text.substr(0, "Data 2".length) == "Data 2") address_type = "D2"; That can be: if (/^Data 1/.test(tr_text)) address_type = 'D1'; if (/^Data 2/.test(tr_text)) address_type = 'D2'; . if (address_type && tr_text.substr(0, "Province".length) == "Province") { addresses[address_type].province = tr_text.substr("Province".length + 1, tr_text.length - "Province".length - 1); That can be: if (address_type && /^Province/.test(tr_text) { addresses[address_type].province = tr_text.replace(/^Province/,''); } and so on. [...] //Comparing of two objects var data1 = addresses.D1.street + '' + addresses.D1.barangay + '' + addresses.D1.province + '' + addresses.D1.zip; data1 = data1 .replace(/\s+/g, ' ').trim(); var permanent_address = data1 ; alert(data1 === data2); //true alert(data1 != data2); //false return { content: "address_check", data1 : data1 , data2: data2}; It seems you want to compare two objects to see if they have the same own properties and same–named properties have the same values. Something like the following may suit: function haveSamePropsAndValues(a, b) { // Get the own properties of each object var aKeys = Object.keys(a); var bKeys = Object.keys(b); // Compare properties and values // If different number of properties, not the same if (aKeys.length != bKeys.length) return false; // If have same number of properties, compare their names and values for (var i=0, iLen=aKeys.length; i<iLen; i++) { // Check property names if (aKeys[i] != bKeys[i]) return false; // Check property values if (a[aKeys[i]] != b[bKeys[i]]) return false; } return true; } The above function returns true if the two objects have the same number of properties with the same names and same values. Otherwise it returns false. It only checks own properties, not inherited. Note that it will return true for two empty objects too. This only works if the values being compared are identical, so you might want to trim leading and trailing white space and reduce any internal whitespace to single. Also perhaps convert to lower case before comparing so that ' Fred ' == 'fred' returns true. A very quick and dirty version is: function haveSamePropsAndValues(a, b){ return JSON.stringify(a).toLowerCase() == JSON.stringify(b).toLowerCase(); }
doc_23529779
With the scripting options (part of SMO) I'm able to choose which parts of script should be included, like Foreign indexes, constraints, etc. $opcionesscript = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions $opcionesscript.DriAll = $true However, the property 'ScriptBatchTerminator' which refers to 'GO' statements is not working when set true $opcionesscript.ScriptBatchTerminator = $true This the same result true or false: $mydb.Tables["CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS"].Script($opcionesscript) SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON CREATE TABLE [dbo].[CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS]( [IDRELACION] [int] IDENTITY(1,1) NOT NULL, [IDLOCALIDAD] [int] NOT NULL, [COD_ART] [nvarchar](16) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [FECHA] [datetime] NOT NULL, CONSTRAINT [PK_CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS] PRIMARY KEY CLUSTERED ( [IDRELACION] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GRANT SELECT ON [dbo].[CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS] TO [someuser] AS [dbo] ALTER TABLE [dbo].[CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS] WITH CHECK ADD CONSTRAINT [FK_CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS_CAT_LOCALIDADES_INVENTARIO] FOREIGN KEY([IDLOCALIDAD]) REFERENCES [dbo].[CAT_LOCALIDADES_INVENTARIO] ([IDLOCALIDAD]) ALTER TABLE [dbo].[CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS] CHECK CONSTRAINT [FK_CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS_CAT_LOCALIDADES_INVENTARIO] ALTER TABLE [dbo].[CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS] WITH CHECK ADD CONSTRAINT [FK_CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS_CATARTI] FOREIGN KEY([COD_ART]) REFERENCES [dbo].[CATARTI] ([COD_ART]) ALTER TABLE [dbo].[CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS] CHECK CONSTRAINT [FK_CAT_LOCALIDADES_INVENTARIOS_RELACION_ARTICULOS_CATARTI] Why is not including 'GO' statements? Is there a bug or there is something that I'm missing? I'm creating a single batch .sql file to include those create table with its foreign keys, so those 'GO' are required. A: For some reason SMO doesn't provide the GO statements in the script, I just found a way to workaround this issue by manually adding the GO statement after every script generated like this: >$mydb.Tables["my_table"].Script($opcionesscript)| out-file c:\Tables.txt –append; “GO” | out-file c:\Tables.txt -append }
doc_23529780
So i've got to the point where i want to replace stupid mesh generation with culling. View of a terrain with no between-chunks culling: View inside a terrain: It worked fine but when i try to also cull those blocks between chunks, things go weird. View of a terrain when added between-chunks culling: Here is the code of mesh generating: void Chunk::CreateMesh() { for (int x = 0; x < CHUNK_SIZE; x++) { for (int y = 0; y < CHUNK_SIZE; y++) { for (int z = 0; z < CHUNK_SIZE; z++) { BlockType currentBlock = blocks[x][y][z]; BlockChunkPosition currentPos(x, y, z); if (currentBlock != BlockType::AIR) { // Right face if (GetBlock(x + 1, y, z) == BlockType::AIR || GetBlock(x + 1, y, z) == BlockType::LEAVES) { mesh.AddFace(RIGHT_FACE, currentBlock, currentPos); } // Left face if (GetBlock(x - 1, y, z) == BlockType::AIR || GetBlock(x - 1, y, z) == BlockType::LEAVES) { mesh.AddFace(LEFT_FACE, currentBlock, currentPos); } // Top face if (GetBlock(x, y + 1, z) == BlockType::AIR || GetBlock(x, y + 1, z) == BlockType::LEAVES) { mesh.AddFace(TOP_FACE, currentBlock, currentPos); } // Bottom face if (GetBlock(x, y - 1, z) == BlockType::AIR || GetBlock(x, y - 1, z) == BlockType::LEAVES) { mesh.AddFace(BOTTOM_FACE, currentBlock, currentPos); } // Front face if (GetBlock(x, y, z + 1) == BlockType::AIR || GetBlock(x, y, z + 1) == BlockType::LEAVES) { mesh.AddFace(FRONT_FACE, currentBlock, currentPos); } // Back face if (GetBlock(x, y, z - 1) == BlockType::AIR || GetBlock(x, y, z - 1) == BlockType::LEAVES) { mesh.AddFace(BACK_FACE, currentBlock, currentPos); } } } } } } BlockType Chunk::GetBlock(int x, int y, int z) { try { return blocks.at(x).at(y).at(z); } catch (std::out_of_range &) { BlockWorldPosition pos = ToWorldCoordinates(position, BlockChunkPosition(x, y, z)); return terrain->GetBlock(pos); } } BlockType Terrain::GetBlock(BlockWorldPosition pos) { ChunkPosition chunkPos; chunkPos = GetChunkPos(pos); BlockChunkPosition blockPos; blockPos = GetBlockLocalPos(pos); ChunkTable::iterator currentChunk; if(((currentChunk = chunks.find(chunkPos)) != chunks.end())) { return currentChunk->second->GetBlock(blockPos.x, blockPos.y, blockPos.z); } return BlockType::AIR; } When I use the debugger, it works strangely in try-catch block. Is there anything wrong there? What can cause such problem? A: Finally I found the problem. This issue occured because I bound vertex and index buffer a few extra times when it wasn't needed. The vetrex array alredy had the buffers bound to it. void ChunkMesh::GenerateMesh() { ibo.Bind(); vbo.Bind(); vao.Bind(); vbo.GenerateBuffer(sizeof(float) * mesh.size(), &mesh[0]); ibo.GenerateBuffer(indices.size(), &indices[0]); vao.AddBuffer(vbo, layout); } replaced with void ChunkMesh::GenerateMesh() { vao.Bind(); vbo.GenerateBuffer(sizeof(float) * mesh.size(), &mesh[0]); ibo.GenerateBuffer(indices.size(), &indices[0]); vao.AddBuffer(vbo, layout); } And void ChunkMesh::Render()const { ibo.Bind(); vao.Bind(); shader.Bind(); GLCall(glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0)); } I replaced with void ChunkMesh::Render()const { vao.Bind(); shader.Bind(); GLCall(glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0)); } Although, I still don`t completely understand why this happened.
doc_23529781
I'm only targeting modern browsers. But I also appreciate answers that target older browsers. A: This seems to work. Not tested it that well though. <textarea></textarea> <script> var textarea = document.querySelector('textarea'); textarea.addEventListener('input', function() { textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px'; }); </script>
doc_23529782
Under a project, in the node "References" you now see ".NET Framework 4.5.1" and ".NET Platform 5.4". Now, I'm working on an application which is being hosted on Mongo and when installing that through Nuget, the reference only gets added to .NET Framework 4.5.1 When I'm building my application, I see a lot of errors regarding MongoDB namespace not found, despite they are colored and useable in the source code (I dohave intellisense). Anyone who can explain me what's wrong? A: That is because your code is built both for the "classical CLR" and for .NET core (this is the default in file->new Project when you created the project in Visual Studio). As it looks the MongoDB nuget package is only available for the "classical CLR", so your code cannot be built for the core CLR. One option is to drop the CoreCLR support: you can do this by removing that from the "frameworks" part in the project.json file. Now I don't know anything about the MongoDb nuget package... maybe there is a CoreCLR version... if this is the case then you need to add that dependency for CoreCLR (Maybe someone knows whether there is support for CoreCLR at all and can extend my answer..)
doc_23529783
#import "Custom.h" @interface Custom () @property (nonatomic, retain) UILabel *label; @end @implementation Custom @synthesize label; - (void) dealloc { [label release]; [super dealloc]; } @end A: I like to do this to create private interfaces. If a property is only used in your implementation, not in collaboration with other objects, it should not pollute the header (which defines the public interface). You can also hide private protocol implementations this way: @interface YourClass () <UIAlertViewDelegate> This way the users of your class don’t have to know that you have an UIAlertView buried somewhere in your implementation. What could be considered a downside is that your subclasses can no longer access the “private” properties. You have to either move their declaration to the header file (making them public), or create a special “protected” header. Another option worth mentioning in this context is declaring private variables in the @implementation directive: @implementation YourClass { NSString *foo; NSUInteger bar; } These are not statics, they are regular instance variables. A: The idea behind this is that all properties you declare in your header file, are visible and accesible for everyone outside that class. To respect the encapsulation principle of OOP, you want to make the scope of certain members of your class as private as possible. So all those members that only your class will use, should be hidden to "the outside world". This can be done by declaring a special type of category called "extension" (it can't have a name, it's declared as @interface Class () ), and the properties inside that extension (along with private method declaration if you want as well) As to the question whether it's a good practice, that may be discussed among different developers. To me, it is since it's good OOP practice, and also because it helps keeping your header file as clean as possible (and so making it easier for other developers to see what "services" your class provides) A: You would want to define label in your header for later use through out other methods in your @implementations. For example, create that label in your viewDidLoad, and you can change it throughout the other methods..
doc_23529784
Dim WS_Count As Integer Dim I As Integer WS_Count = ActiveWorkbook.Worksheets.Count For I = 1 To WS_Count Dim strSQL As String strSQL = "select * from ActiveWorkbook.Worksheets where ActiveWorkbook.Worksheets(I).Name = VLANs and VLAN = 2" Debug.Print strSQL Next I ActiveWorkbook.Close SaveChanges:=False I need to be able to query all worksheets on specific columns I have to query different columns on one worksheet I might have to make a query based on the vlan column and on the other one the query might be based on the ip column. My code compiles and gives no errors.
doc_23529785
Class Client Class Project Class Ticket Class Reply Clients have a sub collection of projects, projects have a sub collection of tickets and tickets have a sub collection of replies. var data = ctx.Set<Ticket>().Include(p => p.Client). Select(p => new { Ticket = p, LastReplyDate = p.Replies.Max(q => q.DateCreated)}); Doesn't work. Neither project nor client are loaded when selecting data this way. I know how to make it work. My question is why doesn't it work like this? A: Because Include works only if you select entities directly. Once you do the projection Include is ignored. I will not tell you why but it simply works this way. A: Another possibility is to use StriplingWarrior's solution but then cleanse the intermediate data from the final result: var data = ctx.Set<Ticket>() .Select(p => new { Ticket = p, Clients = p.Client, LastReplyDate = p.Replies.Max(q => q.DateCreated) }) .AsEnumerable() .Select(p => new { Ticket = p.Ticket, LastReplyDate = p.LastReplyDate }); A: As Ladislav mentioned, Include only works if you select the Ticket entity directly. Since you're projecting other information out, the Include gets ignored. This should provide a good work-around: var data = ctx.Set<Ticket>() .Select(p => new { Ticket = p, Clients = p.Client, LastReplyDate = p.Replies.Max(q => q.DateCreated) }); First of all, each Ticket's Clients will be accessible directly from the Clients property on the anonymous type. Furthermore, Entity Framework should be smart enough to recognize that you have pulled out the entire Client collection for each Ticket, so calling .Ticket.Client should work as well.
doc_23529786
If the updated_at from database is > fetched_at return a response indicating that the record has been updated since it was fetched for edit and prompt the user for a refresh. In this case the user will refresh the record and redo the editing desired. Is there a better way to approach this? I mean is it possible to lock the record making it unavailable/readonly for all other users when any user is currently editing/updating the record? A: If I get it correctly then what you require is that when a user is about to update a record he should review the latest updated value before sending his update. The fetched_at and updated_at use-case should work. Locking the record I do not think its a good idea. You will have to go through another process of unlocking the record. Like what if a user fetches the record and takes awfully lot of time to update it back or worse still if the user pulls up the record and leaves is desk to go for another errand or if for some reason the session of the user gets cut-off due to some error or internet issues etc. You could try another way that keep polling the database and compare if at any point an update has happened to the record when a user has fetched for editing. If an update has happened then display a label message saying the record has recently been updated. Vuejs + ajax or Vuejs + axios does provide innovate ways to do the polling. This post here shows a method to do polling. new Vue({ el: '#app', data: { items: [], interval: null, }, methods: { loadData: function () { $.get('/api/data', function (response) { this.items = response.items; }.bind(this)); } }, ready: function () { this.loadData(); this.interval = setInterval(function () { this.loadData(); }.bind(this), 30000); }, beforeDestroy: function(){ clearInterval(this.interval); } }); <div id="app"> <div v-for="item in items">{{ item.prop }}</div> </div> In the comments they do talk about pusher which is something similar to nodejs broadcast.
doc_23529787
Since I ran low on ideas, I used an old article from ReignDesign.com to tweak the database file a bit. I also happen to be using a 2016 version of SQLDroid, which does appear to work fine. The file is in " ~/assets/database/test.db ". Here is the basic code I am using: public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); copyDatabaseFromAssets( this, "test.db", true ); } /** * Copy database file from assets folder inside the apk to the system database path. * @param context Context * @param databaseName Database file name inside assets folder * @param overwrite True to rewrite on the database if exists * @return True if the database have copied successfully or if the database already exists without overwrite, false otherwise. */ private boolean copyDatabaseFromAssets( Context context, String databaseName, boolean overwrite ) { File outputFile = context.getDatabasePath( databaseName ); if ( outputFile.exists() && !overwrite ) { return true; } outputFile = context.getDatabasePath( databaseName + ".temp" ); outputFile.getParentFile().mkdirs(); try { InputStream inputStream = context.getAssets().open( databaseName ); OutputStream outputStream = new FileOutputStream( outputFile ); // transfer bytes from the input stream into the output stream byte[] buffer = new byte[ 1024 ]; int length; while ( ( length = inputStream.read( buffer ) ) > 0 ) { outputStream.write( buffer, 0, length ); } // Close the streams outputStream.flush(); outputStream.close(); inputStream.close(); outputFile.renameTo( context.getDatabasePath( databaseName ) ); } catch ( IOException e ) { if ( outputFile.exists() ) { outputFile.delete(); } return false; } return true; } } Thank you. A: Your db file located at inside sub-folder, better way to get file from sub-folder just change this line InputStream inputStream = context.getAssets().open( databaseName ); To: InputStream inputStream = context.getAssets().open("database/" + databaseName); Hope it will help you!
doc_23529788
I've used an text document. Only becaue of the sd card i wanne achieve an connecting between the two scripts Reading part: #loops for Barcode_Data def Create_File(): file = open("Barcode_data.txt", "w") file.write(" // ") file.close() empty = '' def Barcode_Read(): Barcode_Data= input("Input: ",) print(Barcode_Data) file = open("Barcode_data.txt", "a") file.write(Barcode_Data) file.write(" // ") file.close() #Loop that will only run once Create_File() #Loop that will run continuesly while True: Barcode_Read() TCP Server: #TCP server def TCP_Connect(socket): socket.listen() conn, addr = socket.accept() with conn: data = conn.recv(1024) if data == b'Barcode_Data': tcp_file = open("Barcode_data.txt", "r") Barcode_Data = tcp_file.read() tcp_file.close() conn.sendall(Barcode_Data.encode('utf-8')) elif data == b'Clear Barcode_Data': tcp_file = open("Barcode_data.txt", "w") tcp_file.write(" // ") tcp_file.close() #TCP Socket setup HOST = '' # Standard loopback interface address (localhost) PORT = 1025 # Port to listen on (non-privileged ports are > 1023) import socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) #Loop that wil run continuesly while True: TCP_Connect(s) A: You can use the code from this question as is: Interprocess communication in Python Server process: from multiprocessing.connection import Listener address = ('localhost', 6000) # family is deduced to be 'AF_INET' listener = Listener(address, authkey='secret password') conn = listener.accept() print 'connection accepted from', listener.last_accepted while True: msg = conn.recv() # do something with msg if msg == 'close': conn.close() break listener.close() Client process: from multiprocessing.connection import Client address = ('localhost', 6000) conn = Client(address, authkey='secret password') conn.send('close') # can also send arbitrary objects: # conn.send(['a', 2.5, None, int, sum]) conn.close() Documentation is available here: https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing-listeners-clients
doc_23529789
from selenium import webdriver driver = webdriver.Chrome('/path/to/chromedriver) A: Download driver and give the path according to where it saved https://chromedriver.chromium.org/downloads webdriver.Chrome(executable_path="your path")
doc_23529790
Here's the MATLAB code: xm_row = -(Nx-1)/2.0+0.5:(Nx-1)/2.0-0.5; xm = xm_row(ones(Ny-1, 1), :); ym_col = (-(Ny-1)/2.0+0.5:(Ny-1)/2.0-0.5)'; ym = ym_col(:,ones(Nx-1,1)); And here is my very rough attempt at trying to do the same thing in python: for x in range (L-1): for y in range (L-1): xm_row = x[((x-1)/2.0+0.5):((x-1)/2.0-.5)] xm = xm_row[(ones(y-1,1)),:] ym_column = transposey[(-(y-1)/2.0+0.5):((y-1)/2.0-.5)] ym = ym_column[:,ones(x-1,1)] In my python code, L is the size of the array I am looping across. When I try to run it in python, I get there error: 'int' object has no attribute '__getitem__' at the line: xm_row = x[((x-1)/2.0+0.5):((x-1)/2.0-.5)] Any help is appreciated! A: In MATLAB, you can implement that in a simpler way with meshgrid, like so - Nx = 5; Ny = 7; xm_row = -(Nx-1)/2.0+0.5:(Nx-1)/2.0-0.5; ym_col = (-(Ny-1)/2.0+0.5:(Ny-1)/2.0-0.5)'; [xm_out,ym_out] = meshgrid(xm_row,ym_col) Let's compare this meshgrid version with the original code for verification - >> Nx = 5; >> Ny = 7; >> xm_row = -(Nx-1)/2.0+0.5:(Nx-1)/2.0-0.5; >> ym_col = (-(Ny-1)/2.0+0.5:(Ny-1)/2.0-0.5)'; >> xm = xm_row(ones(Ny-1, 1), :) xm = -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 >> ym = ym_col(:,ones(Nx-1,1)) ym = -2.5 -2.5 -2.5 -2.5 -1.5 -1.5 -1.5 -1.5 -0.5 -0.5 -0.5 -0.5 0.5 0.5 0.5 0.5 1.5 1.5 1.5 1.5 2.5 2.5 2.5 2.5 >> [xm_out,ym_out] = meshgrid(xm_row,ym_col) xm_out = -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 -1.5 -0.5 0.5 1.5 ym_out = -2.5 -2.5 -2.5 -2.5 -1.5 -1.5 -1.5 -1.5 -0.5 -0.5 -0.5 -0.5 0.5 0.5 0.5 0.5 1.5 1.5 1.5 1.5 2.5 2.5 2.5 2.5 Now, transitioning from MATLAB to Python has a simpler medium in NumPy, as it hosts many counterparts from MATLAB for use in a Python environment. For our case, we have a NumPy version of meshgrid and that makes it just a straight-forward porting as listed below - import numpy as np # Import NumPy module Nx = 5; Ny = 7; # Use np.arange that is a colon counterpart in NumPy/Python xm_row = np.arange(-(Nx-1)/2.0+0.5,(Nx-1)/2.0-0.5+1) ym_col = np.arange(-(Ny-1)/2.0+0.5,(Ny-1)/2.0-0.5+1) # Use meshgrid just like in MATLAB xm,ym = np.meshgrid(xm_row,ym_col) Output - In [28]: xm Out[28]: array([[-1.5, -0.5, 0.5, 1.5], [-1.5, -0.5, 0.5, 1.5], [-1.5, -0.5, 0.5, 1.5], [-1.5, -0.5, 0.5, 1.5], [-1.5, -0.5, 0.5, 1.5], [-1.5, -0.5, 0.5, 1.5]]) In [29]: ym Out[29]: array([[-2.5, -2.5, -2.5, -2.5], [-1.5, -1.5, -1.5, -1.5], [-0.5, -0.5, -0.5, -0.5], [ 0.5, 0.5, 0.5, 0.5], [ 1.5, 1.5, 1.5, 1.5], [ 2.5, 2.5, 2.5, 2.5]]) Also, please notice that +1 was being added at the end of the second argument to np.arange in both cases, as np.arange excludes the second argument element when creating the range of elements. As an example, if we want to create a range of elements from 3 to 10, we would be required to do np.arange(3,10+1) as shown below - In [32]: np.arange(3,10+1) Out[32]: array([ 3, 4, 5, 6, 7, 8, 9, 10])
doc_23529791
In my case I have tested for collinearity prior to modelling, e.g. using VIF, and everything checks out. However, the ranking (using IC) of different models makes me uncertain whether it truly can separate between the predictors. Any ideas? ps! Can someone with higher rep than I add a more relevant tag such as collinearity? A: There are some solutions listed at this blog post. They use some code to create a function that will calculate VIFs for lmer and lme model objects from the lmer and nlme R packages, respectively. I have copied the code for the function below. vif.lme <- function (fit) { ## adapted from rms::vif v <- vcov(fit) nam <- names(fixef(fit)) ## exclude intercepts ns <- sum(1 * (nam == "Intercept" | nam == "(Intercept)")) if (ns > 0) { v <- v[-(1:ns), -(1:ns), drop = FALSE] nam <- nam[-(1:ns)] } d <- diag(v)^0.5 v <- diag(solve(v/(d %o% d))) names(v) <- nam v } Once you run that code once, you will be able to execute a new function, vif.lme within the R environment. I give an example below using a random data set, and an uninformative random effect. I use an uninformative random effect so that the results of lme within nlme will generate the same parameter values for predictors as lm in base R. Then, I use the above code to calculate variance inflation factors, as well as the vif functino from the car package used to calculate VIFs for linear models, to show that they give the same output. #make 4 vectors- c is used as an uninformative random effect for the lme model a<-c(1:10) b1<-c(2,4,6,8,10,100,14,16,18,20) b2<-c(1,9,2,4,5,6,4,3,2,-1) c<-c(1,1,1,1,1,1,1,1,1,1) test<-data.frame(a,b1,b2,c) #model a as a function of b1 and b2, and c as a random effect require(nlme) fit<-lme(a~b1+b2, random=~1|c,data=test) #see how the model fits summary(fit) #check variance inflation factors vif.lme(fit) #create a new regular linear regression model and check VIF using the car package. #answers should be the same, as our random effect above was totally uninformative require(car) fit2<- lm(a~b1+b2,data=test) #check to see that parameter fits are the same. summary(fit2) #check to see that variance inflation factors are the same vif(fit2)
doc_23529792
My gopath is apparently C:/Users/me/go as it should be. *Edit Except if I run cd $GOPATH/src, it says C:\src doesnt exist, it looks in C: not C:/Users Method 1. (running go get -u golang.org/x/blog) I open Powershell and run that in my Users/me/go/src directory and it says: can't load package: package golang.org: no Go files in C:\Users\me\go\src\golang.org But it does download the source files. So its basically this step? 'u can manually git clone the repository to $GOPATH/src/golang.org/x/blog.' Then I dont know where to run go build or what to run. I tried go build -o blog.exe ./blog and it says can't load package: package blog: cannot find package "blog" in any of: C:\Go\src\blog (from $GOROOT) C:\Users\me\go\src\blog (from $GOPATH) I tried running the same command in different directories of the project and doesnt work. A: I'll try to answer your questions. (Note that I am a Linux user, so there may be some discrepancies with the Windows commands below. You may want to follow these directions: http://www.wadewegner.com/2014/12/easy-go-programming-setup-for-windows/ to setup the GOROOT environment variable.) * *For method 1, the -u flag tells go to update the source code. Since you haven't downloaded it before, it lets you know with the error you see. What you want to run is go get golang.org/x/blog. *To build the package, you first want to change the directory (cd) to the package root, so cd %GOPATH%\src\golang.org\x\blog or cd C:\Users\me\go\src\golang.org\x\blog. Next, you want to run go build. Then, you can run the output file, which should automatically be named blog.exe. Hopefully this helps! :)
doc_23529793
pnp.sp.web.lists.ensure("listName").then((ler : ListEnsureResult) => { listEnsureResults = ler; if (!ler.created) { resolve(ler.list); return Promise.reject(LIST_EXISTS); } return ler.list.fields.addText("Field1"); }) i want to add multiple columns but i am always getting an error in adding multiple fields. A: You can add multiple fields to list as below in SPFx: public addFieldsToList(listname: string): Promise<any> { return Promise.all([ pnp.sp.web.lists.getByTitle(listname).fields.addText("MyField1"), pnp.sp.web.lists.getByTitle(listname).fields.addText("MyField2"), pnp.sp.web.lists.getByTitle(listname).fields.addText("MyField3"), pnp.sp.web.lists.getByTitle(listname).fields.addText("MyField4"), ]).then((response) => { return response; }, (error: any) => { return error; }).catch((error: any) => { return error; }); } You just need to call this method and pass your list name.
doc_23529794
I've got enums UNDEFINED(-1), FIS(0), MANUELL(1) defined as public enum Ausloesungsart { UNDEFINED( -1), FIS( 0), MANUELL( 1); } however at runtime i'm adding another enum if it's not contained in the list as UNDEFINED with the parsed code, as in 123. Here is how I take the Enum: public static Ausloesungsart fromIdentifier(Integer code) { if (enumsByIdentifier.containsKey(code)) { return enumsByIdentifier.get(code); } else { enumsByIdentifier.put(code, Ausloesungsart.UNDEFINED); return enumsByIdentifier.get(code); } } by now the list should contain UNDEFINED(-1), FIS(0), MANUELL(1), UNDEFINED(123) when parsing the file it obviously sets the value 88 and searches for it. However it returns -1 in the end on the frontend. Notice It never even jumps into the else clausel, somehow it's already in? Any idea what I'm missing? Edit: Where the parsing happens: Ausloesung ausloesung = new Ausloesung(Ausloesungsart.fromIdentifier(header.getReleaseType())); at this point, releaseType is 123 but in the end there is -1 = Undefined instead of 123 = Undefined in the database and frontend. Usecase: Any Status not in the enumeration should be displayed in the frontend as in <CODE> = Undefined Currently the message is built with a property attribute: my.properties: Ausloesungsart.UNDEFINED= {0} \= Unbekannt Ausloesungsart.FIS=0 \= FIS Ausloesungsart.MANUELL=1 \= Manuell A: however at runtime i'm adding another enum if it's not contained in the list as UNDEFINED with the parsed code, as in 123. Enums are designed to represent immutable things. You cannot add a new enum value at runtime and you should not try to modify the actual either. However it returns -1 in the end on the frontend. Associating an integer value to an enum value in a map will not modify the state of the enum itself. If multiple integer values may be associated to UNDEFINED enum value and that these integer values are not specified at compile time, you should probably not use the enum field to set this information. It doesn't mean that the UNDEFINED enum could not be associated to multiple numeric values. But this should not done directly in the state itself of the enum values. You could use a custom class that provides the two information : the String placeholder and the numeric code. You could introduce a static method in Ausloesungsart that returns it. public static getAusloesungsartWithValue(Integer code){ for (Ausloesungsart current : values()){ if (current.numericValue.equals(code)){ return new AusloesungsartWithValue(current, code); } } return new AusloesungsartWithValue(UNDEFINED, code); } Then call it : AusloesungsartWithValue value = Ausloesungsart.getAusloesungsartWithValue(123); // UNDEFINED AusloesungsartWithValue otherValue = Ausloesungsart.getAusloesungsartWithValue(0); // FIS A: What do you mean "it returns -1 in the end on the frontend". You probably implemented it is like this: enum Ausloesungsart { UNDEFINED(-1), FIS(0), MANUELL(1); private int value; public void getValue() { return value; } } Now you can put these enum items into maps all you want, its value will never change. To display the list you mention in your comment to this answer, do for (int value : yourList) { Ausloesungsart art = Arrays.stream(Ausloesungsart.values()) .filter(a -> a.getValue() == value) .findFirst().orElse(Ausloesungsart.UNDEFINED); System.out.println(String.format("<%d>: %s", value, art.toString()); } A: your are putting values in the map and that is working... what you will never get to work is that you return a enum with that integer attribute... your method is doing insertiong in a Map so you can at the end have something like UNDEFINED(-1), FIS(0), MANUELL(1), UNDEFINED(123), UNDEFINED(1231), UNDEFINED(12311), UNDEFINED(1233123), but all those calues are still the same enum: Ausloesungsart.UNDEFINED no matter how much the map changes, you have at the end the same enum public enum Ausloesungsart { UNDEFINED( -1), FIS( 0), MANUELL( 1); }
doc_23529795
I created a form where the user can insert his email and if the email is in database, it will automatically send an email with a link for password reset. This link has a specific token that is created for each user when they click on the button for receiving the email. This token is inserted in the database and also the timestamp for when it is created. I'm trying to delete the token from the database if it reached a limit time of 5 minutes but it doesn't work. Is there any way to do this? Thank you. My table: CREATE TABLE user ( id bigint identity NOT NULL, username varchar(50) NOT NULL, email varchar(50) NOT NULL, password varchar(50) NOT NULL, attempts int DEFAULT 3, state varchar(50) DEFAULT 'Active’, reset_token uuid, time_token TIMESTAMP, PRIMARY KEY (id) ); The tokengenerator: public class TokenGenerator { public static String UniqueToken() { String token = UUID.randomUUID().toString(); return token; }} My class ForgotPasswordHandler.java: public class ForgotPasswordHandler { private static PreparedStatement ps = null; private static ResultSet rs = null; private static Connection con = DBConnectionManager.getConnection(); //Creates a token for the user when it clicks on submit for forgot password public static void CreateToken (String email) { try { if (con == null){ System.out.println("Failed connection"); }else{ String token = TokenGenerator.UniqueToken(); PreparedStatement ps = con.prepareStatement( "UPDATE user SET reset_token = ?, time_token = ? WHERE email = ?"); ps.setString(1,token); ps.setTimestamp(2,new Timestamp(new Date().getTime())); ps.setString(3, email); ps.executeUpdate(); ps.close(); }} catch (Exception e) { e.printStackTrace(System.out); } } //This is where I'm having trouble to delete the actual token after 5 minutes. public static void DeleteToken() { try { if (con == null){ System.out.println("Failed Connection"); }else{ PreparedStatement ps = con.prepareStatement( "UPDATE user SET reset_token = NULL WHERE time_token < NOW() - INTERVAL 5 MINUTE"); ps.executeUpdate(); ps.close(); }} catch (Exception e) { e.printStackTrace(System.out); } } } My Servlet ForgotPassword.java: public class ForgotPassword extends HttpServlet { private static final long serialVersionUID = 1L; private String host; private String port; private String email; private String name; private String pass; public void init() { // reads SMTP server setting from web.xml file ServletContext context = getServletContext(); host = context.getInitParameter("host"); port = context.getInitParameter("port"); email = context.getInitParameter("email"); name = context.getInitParameter("name"); pass = context.getInitParameter("pass"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //verify if emails exists in db String email = request.getParameter("email"); if(!UserReset.EmailCheck(email)) { String message = "This email isn't in our database"; request.setAttribute("message", message); request.getRequestDispatcher("reset.jsp").forward(request, response); } else { String recipient = request.getParameter("email"); String subject = "Your Password has been reset"; String token = TokenGenerator.UniqueToken(); ForgotPasswordHandler.CreateToken(email); ForgotPasswordHandler.DeleteToken(); String url = "http://localhost:8080/login/reset-password.jsp?token=" + token; UserReset.RefreshState(email); //Builds email message and sends it String content = "Hello, please change your password in this link:" + url; content += "\nObrigado!"; String message = ""; try { EmailSender.sendEmail(host, port, email, name, pass, recipient, subject, content); message = "Please verify your email."; } catch (Exception ex) { ex.printStackTrace(); message = "Ops, an error occured: " + ex.getMessage(); } finally { request.setAttribute("message", message); request.getRequestDispatcher("reset.jsp").forward(request, response); } } } } A: You probably shouldn't be deleting the token actively. Just record the time the token was issued, and then when the new query comes in, get the create time and check that it is within 5 minutes.
doc_23529796
There doesn't seem to be adequate documentation yet on WinRT. Also, if it's not possible with SDL can I achieve this (a simple arcade-style game) with some other graphics library/game engine ? A: XAML support for SDL/WinRT is planned, but not yet implemented beyond a barely-functional (and largely non-functional), proof-of-concept phase. Much of the work on SDL/WinRT has, so far, been geared towards getting non-XAML/Direct3D apps running well. Initial support for XAML will, to note, probably be geared around SwapChainPanel and/or SwapChainBackgroundPanel, as the APIs for these map a bit more closely to SDL's own APIs. (At least, these are my own plans, development-wise.)
doc_23529797
I am trying the following code: Jersey: @GET @Path("/get-zip") @Produces("application/zip") @Consumes(MediaType.APPLICATION_JSON) public Response getZip() throws IOException{ File fileObj = new File('myfile.zip'); return Response.ok((Object)fileObj) .header("Content-Disposition", "attachment; filename=\"" + fileObj.getName() + "\"") .build(); } cURL Code: $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 1); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1); $file = curl_exec($curl); $file_array = explode("\n\r", $file, 2); $header_array = explode("\n", $file_array[0]); foreach($header_array as $header_value) { $header_pieces = explode(':', $header_value); if(count($header_pieces) == 2) { $headers[$header_pieces[0]] = trim($header_pieces[1]); } } header('Content-type: ' . $headers['Content-Type']); header('Content-Disposition: ' . $headers['Content-Disposition']); echo $file_array[1]; Anything I am missing? A: MediaStreamer streamer = new MediaStreamer(fileObj.getInputStream()); return Response.ok() .header(HttpHeaders.CONTENT_LENGTH, fileObj.getContentLength()) .header(HttpHeaders.CONTENT_DISPOSITION, fileObj.getContentDisposition()) .entity(streamer) .type(fileObj.getContentType()) .build(); and MediaStreamer look like this import com.google.common.io.ByteStreams; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.StreamingOutput; import java.io.*; public class MediaStreamer implements StreamingOutput { private InputStream is; public MediaStreamer(InputStream is) { this.is = is; } @Override public void write(OutputStream os) throws IOException, WebApplicationException { Writer writer = new BufferedWriter(new OutputStreamWriter(os)); ByteStreams.copy(is, os); writer.flush(); } }
doc_23529798
option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "waifu_database.settings" PYTHONPATH: "/opt/python/current/app/waifu_database:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: waifu_database.wsgi:application However, I still have the React portion to deploy. I know that it would probably be easier to separate the two, but is there a way I can install all the packages using npm and deploy it with the Django backend? I've already tried this but it just gave me a "Failed to deploy application" error. Here is my file directory: waifu_database |- .ebextensions |- .elasticbeanstalk |- api |- frontend |- node_modules/ |- src/ |- static/ |- templates/ |- package.json |- waifu_database |- asgi.py |- settings.py |- urls.py |- wsgi.py |- manage.py |- requirements.txt Here is my package.json file: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode production --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.19.3", "@babel/preset-env": "^7.19.3", "@babel/preset-react": "^7.18.6", "babel-loader": "^8.2.5", "react": "^18.2.0", "react-dom": "^18.2.0", "webpack": "^5.74.0", "webpack-cli": "^4.10.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.18.6", "react-router-dom": "^6.4.2" } }
doc_23529799
Insert, Delete, Update, Search and Select. All the functionalities work well except for update. Following is the code for update: stmt_update = conn_update.createStatement(); stmt_update.executeUpdate("UPDATE Conference SET C_NAME = '" + confname + "', C_YEAR = " + yr + ", START_DATE = to_timestamp('" +stdate +"','yyyy-mm-dd HH24:MI:ss.FF1'), END_DATE = to_timestamp('" +enddate +"','yyyy-mm-dd HH24:MI:ss.FF1')," + "COUNTRY = '"+country_update+"', CITY = '"+city_update+"', VENUE = '"+venue_update+"'," + ", CONTACT_EMAIL = '"+c_email_update+"' where conference_id = '" + confid + "'"); Table structure is: ( Conference_ID varchar(10) NOT NULL, C_Name varchar(20), C_Year numeric(4,0), Start_Date date, End_Date date, Country varchar(10), City varchar(10), Venue varchar(10), Contact_Email varchar(10), PRIMARY KEY(Conference_ID) ); Error is: ORA-01747: invalid user.table.column, table.column, or column specification I thought there was something to do with the date inputs. Any suggestions would help greatly. Thanks. -----Update-------------- Tried using prepare Statement stmt_update = conn_update.prepareStatement("UPDATE Conference SET C_NAME = '" + confname + "', C_YEAR = " + yr + ", START_DATE = to_timestamp('" +stdate +"','yyyy-mm-dd HH24:MI:ss.FF1'), END_DATE = to_timestamp('" +enddate +"','yyyy-mm-dd HH24:MI:ss.FF1')," + "COUNTRY = '"+country_update+"', CITY = '"+city_update+"', VENUE = '"+venue_update+"'," + ", CONTACT_EMAIL = '"+c_email_update+"' where conference_id = '" + confid + "'"); stmt_update.executeUpdate("UPDATE Conference SET C_NAME = '" + confname + "', C_YEAR = " + yr + ", START_DATE = to_timestamp('" +stdate +"','yyyy-mm-dd HH24:MI:ss.FF1'), END_DATE = to_timestamp('" +enddate +"','yyyy-mm-dd HH24:MI:ss.FF1')," + "COUNTRY = '"+country_update+"', CITY = '"+city_update+"', VENUE = '"+venue_update+"'," + ", CONTACT_EMAIL = '"+c_email_update+"' where conference_id = '" + confid + "'"); Still getting the same error. Error: ORA-01747: invalid user.table.column, table.column, or column specification A: stmt_update = conn_update.createStatement(); stmt_update.executeUpdate("UPDATE Conference SET C_NAME = '" + confname + "', C_YEAR = " + yr + ", START_DATE = to_timestamp('" +stdate +"','yyyy-mm-dd HH24:MI:ss.FF1'), END_DATE = to_timestamp('" +enddate +"','yyyy-mm-dd HH24:MI:ss.FF1')," + "COUNTRY = '"+country_update+"', CITY = '"+city_update+"', VENUE = '"+venue_update+"'," + ", CONTACT_EMAIL = '"+c_email_update+"' where conference_id = '" + confid + "'"); __ Here one extra comma is exist. Those two commas causing the error. So your code should be: stmt_update = conn_update.createStatement(); stmt_update.executeUpdate("UPDATE Conference SET C_NAME = '" + confname + "', C_YEAR = " + yr + ", " + "START_DATE = to_timestamp('" + stdate + "','yyyy-mm-dd HH24:MI:ss.FF1'), END_DATE = to_timestamp('" + enddate + "','yyyy-mm-dd HH24:MI:ss.FF1'), " + "COUNTRY = '" + country_update + "', CITY = '"+city_update+"', VENUE = '"+ venue_update + "', " + "CONTACT_EMAIL = '" + c_email_update + "' WHERE conference_id = '" + confid + "'"); A: this to much use this : java.sql.PreparedStatement stm=your_conn_variable.prepareStatement("UPDATE table_name set field_name=?,seconde_field=? "); // stm.setString(1,your_value); stm.setString(2,your_seconde_value); stm.executeUpdate(); //will not have to write all this lines and forget all ' , ; here is an example like your case : stmt_update = conn_update..prepareStatement( "UPDATE Conference SET C_NAME = ?") stmt_update.setString(1,confname); stmt_update.executeUpdate();