text
stringlengths
15
59.8k
meta
dict
Q: Webrtc connection failed when microphone permission granted I'm trying to establish the webrtc connection between the browser and docker container with Janus gateway with the video room plugin. Everything works fine when I create the RTCPeerConnection from the browser with permissions to media not set or denied. However, I experience problems when I try to connect with Janus from the browser with media permissions already granted before the connection was created. In this case, the connection state is failed. I can see in the janus (in docker container) that the remote candidates are not present there. I can see in the webrtc console that for all pairs, there are STUN request setnt but no responses received
{ "language": "en", "url": "https://stackoverflow.com/questions/74503015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where would a sortedSet go in this UML diagram? I am self guiding myself through a Python Data Structures book and came across this problem for one of the exercises regarding the chapter regarding inheritance. I am very puzzled. The problem: A sorted set behaves just like a set, but allows the user to visit its items in ascending order with a for loop, and supports a logarithmic search for an item. Draw a class diagram that shows where you would place a new class for sorted sets in the collection framework shown in the figure below: I am confused on where a new class for a sorted set would go in this diagram. My gut tells me, it would be a be added as a third bag interface? For example LinkedBag, ArrayBag and a new SetBag point to bag interface and abstract bag, and SetSortedBag points to SetBag? Is this on the right track? I find this question sorta odd. A: Assuming that LinkedBag refers to the LinkedList data structure, then yes you are correct in that Set would be a third section, with SortedSet inheriting from it. However, I would not define it as an "interface". Interfaces are a type of class which is generally used as a blueprint for inheriting classes to follow, and does not implement their own class functions. Instead, they declare functions which their derivative classes will implement. For additional information, Abstract Classes are similar, except that they can implement their class functions. Neither Interfaces nor Abstract classes can (usually) be initialized as an object. This becomes a lot more blurry in Python which uses the general "Python Abstract Base Classes" and doesn't do Interfaces directly, but can be mocked through the abstract classes. However, as a term for general programming, the distinctions between normal classes, interfaces, and abstract classes can be important, especially since interfaces and abstract classes (usually) are not/ can not be initialized as objects. The exact rules of inheritance regarding Interfaces and Abstract Classes can differ between languages, for example in Java you can't inherit from more than one abstract class, so I won't directly address it here. Since a Set is a data structure on its own that can, and usually should, have functionality separate from a sorted set, you would not make the set an interface, but rather a normal class. You can still inherit from normal classes, which is what you would do with SortedSet inheriting from Set. A: A sorted set according to the narrative is a set, but with some variations in some behavior: A sorted set behaves just like a set, but allows the user to visit its items in ascending order with a for loop, and supports a logarithmic search for an item. This means that SortedSet would inherit from Set, just like SortedArrayBag inherits from ArrayBag. Inheritance should by the way shown in UML with a big hollow array head (small arrows like in your diagram mean a navigable association, which has nothing to do with inheritance). A set is however not a bag. A set contains an item at maximum once, whereas a bag may contain multiple times the same item. This could lead to a completely different interface (e.g. membership on an item is a boolean for a set, whereas it could be an integer for a bag). The safe approach would therefore be to insert an AbstractSet inheriting from AbstractCollection: A shortcut could be to deal with the set like a bag, and return a count of 1 for any item belonging to the set, ignoring multiple inserts. This would not be compliant with the Liskov Substitution Principle, since it would not respect all the invariants and weaken post-conditions. But if you'd nevertheless go this way, you should insert Set as extending AbstractBag, and SortedSet as a specialization of Set. In this case, your set (and sorted set) would also realise the BagInterface (even if it'd twist it). Shorn's answer analyses this situation very well.
{ "language": "en", "url": "https://stackoverflow.com/questions/75442773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: shell-write command problem - How to add a "key" to a plist file via terminal? (iphone,mobileterminal) I wanted to run this command in mobileterminal (iphone): write "/myPlist.plist" TestKey "TestStringForKey" but it says: 'write' command not found The plist EXISTS! What am I doing wrong? Is there any other way? EDIT: TestKey does not exist in the plist. I want to create it. EDIT: Some infos: iPod Touch with iOS 4.2.1 and with the newest mobileterminal from googlecode. EDIT: Now I installed "write". If I run the command i get this: usage: write user [tty] A: I think you want the defaults command: defaults write "myPlist.plist" TestKey "TestStringForKey" A: I use this to write to a plist file with iPhone terminal. Just make sure you have ericautilities installed from Cydia. plutil -key ShowedAlert -value nope /dir/ect/ory/to/playlist.plist A: /myPlist.plist means, that myPlist.plist is in your root directory. I think, it's in your current working directory, so just use write "myPlist.plist" TestKey "TestStringForKey"
{ "language": "en", "url": "https://stackoverflow.com/questions/5901180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Must I declare own wxFrame class? I'm creating simple c++ application with user interface. I have written own classes with needed mechanics, and now I must display some of its components using wxWidgets. MyApp contains objects of that classes, but they are also needed in MyFrame when handling events. It would be much more comfortable without passing pointers to that objects to MyFrame and implement everything in MyApp::OnInit function. Is that possible? // should contain informations about game state, players, gameboard, etc class MyApp : public wxApp { GameBoard gb; Player player; bool lightTheme; public: virtual bool OnInit(); }; // should contain only window layout, button events, etc class MyFrame : public wxFrame { GameBoard *gb; Player *player; bool *lightTheme; std::vector<wxStaticBitmap*> cardImages; // some events here void displayImages(wxGridSizer*); public: MyFrame(GameBoard*, Player*, bool*); }; A: To answer your title question, you don't have to declare MyFrame and can just create and directly use wxFrame and use Bind() to connect the different event handlers. In all but the simplest situations, it's typically convenient to have a MyFrame class centralizing the data and event handlers for the window, but it is not required by any means. If you decide to keep everything in MyApp instead, you may find wxGetApp() useful for accessing it from various places in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/55704151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "Shadowbox is not defined" error which suggests that Shadowbox.init(shadowbox_conf)? I am having a problem where i am getting the error "Shadowbox is not defined" and it suggests that Shadowbox.init(shadowbox_conf) is the problem. I believe that this issue started occurring when I updated from wordpress 3.3.0 to 3.3.1. I can't figure out why this has suddenly started to cause a problem. Unfortunately my javascript skills are lacking, so any help you could give me would be appreciated. You can view the page in question here. (note I am using shadowbox JS plugin to use the shadowbox lightbox, and I have also integrated this with the javascript plugin isotope, which is use for layout and filtering. http://www.imageworkshop.com/portfolio/ A: okay, i eventually tracked down the fix. I am using the Shadowbox JS plugin. Turns out that this plugin has been removed from the repository at wordpress, and i had missed out on the latest update which fixed the compatibility issues. Follow the link below to find out more and download teh latest version if you require. http://sivel.net/2011/12/shadowbox-js-plugin-pulled-from-the-wordpress-org-repository/
{ "language": "en", "url": "https://stackoverflow.com/questions/8781509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I filter data returned by the BigQuery connector for Spark? I have adapted the instructions at Use the BigQuery connector with Spark to extract data from a private BigQuery object using PySpark. I am running the code on Dataproc. The object in question is a view that has a cardinality >500million rows. When I issue this statement: table_data = spark.sparkContext.newAPIHadoopRDD( 'com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat', 'org.apache.hadoop.io.LongWritable', 'com.google.gson.JsonObject', conf=conf) in the job output I see: Bigquery connector version 0.10.7-hadoop2 Creating BigQuery from default credential. Creating BigQuery from given credential. Using working path: 'gs://dataproc-9e5dc592-1a35-42e6-9dd6-5f9dd9c8df87-europe-west1/hadoop/tmp/bigquery/pyspark_input20181108091647' Estimated number of shards < desired num maps (0 < 93); clipping to 0. Computed '2' shards for sharded BigQuery export. Table 'projectname:datasetname.viewname' to be exported has 0 rows and 0 bytes Estimated number of shards < desired num maps (0 < 93); clipping to 0. Computed '2' shards for sharded BigQuery export. Table 'projectname:datasetname.viewname' to be exported has 0 rows and 0 bytes (timestamp/message-level/namespace removed for readability) That was over 2 hours ago and the job is still running, there has been no more output in that time. I have looked in the mentioned gs location and can see that a directory called shard-0 has been located, but it is empty. Essentially there has been no visible activity for the past 2 hours. I'm worried that the bq connector is trying to extract the entirety of that view. Is there a way that I can issue a query to define what data to extract as opposed to extracting the entire view? UPDATE I was intrigued by this message in the output: Estimated number of shards < desired num maps (0 < 93); clipping to 0 It seems strange to me that estimated number of shards would be 0. I've taken a look at some of the code (ShardedExportToCloudStorage.java) that is getting executed here and the above message is logged from computeNumShards(). Given numShards=0 I'm assuming that numTableBytes=0 which means function call: tableToExport.getNumBytes(); (ShardedExportToCloudStorage.java#L97) is returning 0 and I assume that the reason for that is that the object I am accessing is a view, not a table. Am I onto something here or am I on a wild goose chase? UPDATE 2... To test out my theory (above) that the source object being a view is causing a problem I have done the following: Created a table in the same project as my dataproc cluster create table jt_test.jttable1 (col1 string) Inserted data into it insert into jt_test.jttable1 (col1) values ('foo') Submitted a dataproc job to read the table and output the number of rows Here's the code: conf = { # Input Parameters. 'mapred.bq.project.id': project ,'mapred.bq.gcs.bucket': bucket ,'mapred.bq.temp.gcs.path': input_directory ,'mapred.bq.input.project.id': 'myproject' ,'mapred.bq.input.dataset.id': 'jt_test' ,'mapred.bq.input.table.id': jttable1 } table_data = spark.sparkContext.newAPIHadoopRDD( 'com.google.cloud.hadoop.io.bigquery.JsonTextBigQueryInputFormat', 'org.apache.hadoop.io.LongWritable', 'com.google.gson.JsonObject', conf=conf) print ('got table_data') print (table_data.toDF().head(10)) print ('row tally={}'.format(table_data.toDF().count())) When I run the dataproc pyspark job, here's the output: 8/11/08 14:59:26 INFO <cut> Table 'myproject:jt_test.jttable1' to be exported has 1 rows and5 bytes got table_data [Row(_1=0, _2=u'{"col1":"foo"}')] row tally=1 Create a view over the table create view jt_test.v_jtview1 as select col1 from `myproject.jt_test.jttable1` Run the same job but this time consume the view instead of the table conf = { # Input Parameters. 'mapred.bq.project.id': project ,'mapred.bq.gcs.bucket': bucket ,'mapred.bq.temp.gcs.path': input_directory ,'mapred.bq.input.project.id': 'myproject' ,'mapred.bq.input.dataset.id': 'jt_test' ,'mapred.bq.input.table.id': v_jtview1 } When I run the dataproc pyspark job, here's the output: Table 'dh-data-dev-53702:jt_test.v_jtview1' to be exported has 0 rows and 0 bytes and that's it! There's no more output and the job is still running, exactly the same as I explained above. Its effectively hung. Seems to be a limitation of the BigQuery connector - I can't use it to consume from views. A: To close the loop here, jamiet@ confirmed in the comment that root cause is that BigQuery does not support export from Views, it supports export only from Tables.
{ "language": "en", "url": "https://stackoverflow.com/questions/53206807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Box-model seems to be broken in Chrome 15 (latest stable release) I thought the days of checking box-model issues between modern browsers were long gone... I have been having problems getting Chrom[e|ium] to display my website correctly, and I've managed to create this really simple example of what's going wrong: The HTML: <div class="block"> <div class="left">LEFT!</div> <div class="right"> RIGHT! 16px margins on everything.... What's that??? → → → </div> </div> The CSS: div.left { float: left; margin: 16px; padding: 16px; width: 256px; height: 256px; outline: 1px solid red; background: #fee; } div.right { margin: 16px; padding: 16px; overflow: hidden; outline: 1px solid blue; background: #eef; } A screenshot of the problem: A live demo: http://jsfiddle.net/g105b/BJuYR/ A: No other browser behaves like WebKit does here. Searching WebKit Bugzilla for "block formatting context margin" yields this very similar result: https://bugs.webkit.org/show_bug.cgi?id=19123 As a workaround, you can use the fix I proposed in a comment: removing the left margin on div.right sorts it out: http://jsfiddle.net/BJuYR/13/
{ "language": "en", "url": "https://stackoverflow.com/questions/8402548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to retry Django Celery task on Exception when Internal Server Error is raised? I am trying to use Celery to send anywhere from 1 to about 25 consecutive requests to a third-party API. The measure of success is whether I get a URL back in the response payload: response_json["data"]["url"]. Celery or not, sometimes I get the data I expect, and sometimes I don't. I decided to experiment with Celery to retry the API call while taking advantage of the built-in exponential backoff, which sounds perfectly suited to my needs, but I am struggling to implement. When the data I am expecting is not available in the response payload, I get a TypeError: 'type' object is not iterable (i.e., there is no such item in the response). But I am also getting an Internal Server Error, which I wonder whether I need to handle or whether I could use to trigger the retry. Here is a example of one of several similar approaches I have tried: @shared_task(autoretry_for=(Exception), retry_backoff=True, retry_backoff_max=120) def third_party_api_request(payload, api_url, headers): response = requests.request("POST", api_url, headers=headers, data=payload) response_json = response.json() return response_json["data"]["url"] # output: Internal Server Error: -- snip -- autoretry_for = tuple( TypeError: 'type' object is not iterable Another approach I have tried: @shared_task(bind=True) def third_party_api_request(self, payload, api_url, headers): try: response = requests.request("POST", api_url, headers=headers, data=payload) response_json = response.json() return response_json["data"]["url"] except TypeError as exc: logger.error("Error sending request to API: %s", exc) raise self.retry(exc=exc) # output: ERROR 2022-04-22 17:31:40,131 tasks 72780 123145528369152 Error sending request to API: 'NoneType' object is not subscriptable Internal Server Error: -- snip -- TypeError: 'NoneType' object is not subscriptable -- snip -- raise ret celery.exceptions.Retry: Retry in 180s: TypeError("'NoneType' object is not subscriptable") ERROR 2022-04-22 17:31:40,409 log 72780 123145528369152 Internal Server Error: -- snip -- TypeError: 'NoneType' object is not subscriptable -- snip -- raise ret celery.exceptions.Retry: Retry in 180s: TypeError("'NoneType' object is not subscriptable") And yet another approach, with similar results: @shared_task(autoretry_for=(TypeError), retry_backoff=True, retry_backoff_max=120) def send_http_request_to_proctoru_task(payload, api_url, headers): response = requests.request("POST", api_url, headers=headers, data=payload) response_json = response.json() try: return response_json["data"]["url"] except TypeError: logger.error("API response: %s", response_json) raise A: The issue was I had misplaced the return statement. I still have much fine-tuning to do, but the following code solves the issue in the question that I posed earlier today. I have been reading posts, documentation, and articles for days, and I wish I could everyone credit, but this is the blog post that ultimately helped me realize my error: https://testdriven.io/blog/retrying-failed-celery-tasks/. @shared_task(name="send_http_request_to_proctoru_task", bind=True, max_retries=6) def send_http_request_to_proctoru_task(self, api_url, headers, payload): try: response = requests.request("POST", api_url, headers=headers, data=payload) response_json = response.json() if response_json["response_code"] == 2: raise Exception() return response_json["data"]["url"] except Exception as exc: logger.warning("Exception raised. Executing retry %s" % self.request.retries) raise self.retry(exc=exc, countdown=2 ** self.request.retries)
{ "language": "en", "url": "https://stackoverflow.com/questions/71975002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Syntax Issue while Declaring select statement into a variable If I run the select statement its working fine but if I defined into a variable then I am getting syntax error. Declare @a varchar(2550) SET @a=' SELECT 'ALTER DATABASE ' + CAST(DB_NAME() AS VARCHAR(50)) + ' MODIFY FILE ( NAME = ' + QUOTENAME( df.name,'''') + ', NEWNAME = ''' + QUOTENAME( DB_NAME()) + + CASE WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN '.mdf'' )' WHEN df.type_desc = 'LOG' THEN '_log.ldf'' )' WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN '.ndf'' )' END FROM sys.database_files df' select @a Error: Msg 102, Level 15, State 1, Line 38 Incorrect syntax near ' + CAST(DB_NAME() AS VARCHAR(50)) + '. A: It's a combination of typing errors and wrong use of SET and/or SELECT. If I understand you correctly, you may try to use the following statement: DECLARE @a varchar(2550) SELECT @a = 'ALTER DATABASE ' + CAST(DB_NAME() AS VARCHAR(50)) + ' MODIFY FILE ( NAME = ' + QUOTENAME( df.name,'''') + ', NEWNAME = ''' + QUOTENAME( DB_NAME()) + CASE WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN '.mdf'' )' WHEN df.type_desc = 'LOG' THEN '_log.ldf'' )' WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN '.ndf'' )' END FROM sys.database_files df SELECT @a As an important note, when you use SELECT @local_variable and the SELECT statement returns more than one value, the variable is assigned the last value that is returned. So if you want to generate a complex statement for all database files, you need to concatenate the returned rows (using FOR XML PATH or STRING_AGG()). In this case, as @GordonLinoff commented, you may declare the @a variable as nvarchar(max): DECLARE @a nvarchar(max) = N'' SELECT @a = ( SELECT N'ALTER DATABASE ' + CAST(DB_NAME() AS VARCHAR(50)) + N' MODIFY FILE ( NAME = ' + QUOTENAME( df.name,'''') + N', NEWNAME = ''' + QUOTENAME( DB_NAME()) + CASE WHEN df.type_desc = 'ROWS' AND df.file_id = 1 THEN N'.mdf'' )' WHEN df.type_desc = 'LOG' THEN N'_log.ldf'' )' WHEN df.type_desc = 'ROWS' AND df.file_id != 1 THEN N'.ndf'' )' END + N';' FROM sys.database_files df FOR XML PATH('') ) SELECT @a A: I think you're looking for something like this declare @a nvarchar(max); with file_cte as ( select N'ALTER DATABASE ' + quotename(db_name()) + N' MODIFY FILE ( NAME = ' + quotename( df.name,'''') + N', NEWNAME = ''' + quotename(db_name()) + case when df.type_desc = N'ROWS' AND df.file_id = 1 then N'.mdf'' )' when df.type_desc = N'LOG' THEN N'_log.ldf'' )' when df.type_desc = N'ROWS' AND df.file_id != 1 then N'.ndf'' )' end string from sys.database_files df) select @a=concat(string_agg(string, ';'), ';') from file_cte; select @a;
{ "language": "en", "url": "https://stackoverflow.com/questions/64459391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically hide/show widgets? I want to dynamically hide/show widget like so: Default: |-------| | | | text | | editor| |-------| With webkit preview: |-------|-------| | | | | text | web | | editor| widget| |-------|-------| With okular preview: |-------|-------| | | | | text | okular| | editor| widget| |-------|-------| A: Just add all your widgets into the layout and use QWidget::hide(), QWidget::show() when needed. For more complex situations you can use The State Machine Framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/9306379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Summarize the data using two Python data Frames I have two data frames. I would like to do some analysis by using these two tables. I thought of using Joins but it didn't work. Hence reaching out for help. Let me elaborate the problem with the help of data. This data is not complete data, just for understanding purpose I have created these sample data. In reality, the data sizes are big. I have two inputs tables. Table1: Month Area State_Code State_Name Jan 101 TX01 Total_Country Feb 101 TX01 Total_Country Feb 101 TX04 South Jan 102 TX01 Total_Country Feb 102 TX01 Total_Country Feb 102 TX06 North Feb 102 TX12 Mumbai The point to be noted here is Area "101" is mapped to State_Name "Total_Country" twice because we have two Month - Jan and Feb. But Area "101" is mapped to State_Name "South" only once because it is active only from Month "Feb". Table2: Month Area Brand Price Sales Jan 101 Nestle 14 300 Jan 101 Unilever 15 380 Feb 101 Abc 10 320 Feb 101 Nestle 14 420 Feb 101 Unilever 15 500 Jan 102 Nestle 15 310 Jan 102 Unilever 16 390 Feb 102 Nestle 15 430 Feb 102 Unilever 16 510 This is the brand level data for every month in an individual area. Output Table: The output must contain Sum of(Price) and Sum of(Sales) at Month * State_Code * State_Name * Brand. Month State_Code State_Name Brand Price Sales Jan TX01 Total_Country Nestle 29 610 Jan TX01 Total_Country Unilever 31 770 Feb TX01 Total_Country Abc 10 320 Feb TX01 Total_Country Nestle 29 850 Feb TX01 Total_Country Unilever 31 1010 Feb TX04 South Abc 10 320 Feb TX04 South Nestle 14 420 Feb TX04 South Unilever 15 500 Feb TX06 North Nestle 15 430 Feb TX06 North Unilever 16 510 Feb TX12 Mumbai Nestle 15 430 Feb TX12 Mumbai Unilever 16 510 Thanks in advance for help..! A: Try merge then create the summary values via groupby sum: new_df = ( df1.merge(df2) .drop('Area', 1) .groupby(['Month', 'State_Code', 'State_Name', 'Brand'], as_index=False, sort=False) .sum() ) new_df: Month State_Code State_Name Brand Price Sales 0 Jan TX01 Total_Country Nestle 29 610 1 Jan TX01 Total_Country Unilever 31 770 2 Feb TX01 Total_Country Abc 10 320 3 Feb TX01 Total_Country Nestle 29 850 4 Feb TX01 Total_Country Unilever 31 1010 5 Feb TX04 South Abc 10 320 6 Feb TX04 South Nestle 14 420 7 Feb TX04 South Unilever 15 500 8 Feb TX06 North Nestle 15 430 9 Feb TX06 North Unilever 16 510 10 Feb TX12 Mumbai Nestle 15 430 11 Feb TX12 Mumbai Unilever 16 510 A: You can do a pd.merge() with multiple columns, so that it is a dual-key merge/join. edit: you will also need to drop() the 'area' column df3 = pd.merge(df1,df2,on=['Month','Area']).drop('Area',axis=1) output = df3.groupby(['Month','State_Code','State_Name','Brand'],as_index=False,sort=False).sum() df3 Month Area State_Code State_Name Brand Price Sales 0 Jan 101 TX01 Total_Country Nestle 14 300 1 Jan 101 TX01 Total_Country Unilever 15 380 2 Feb 101 TX01 Total_Country Abc 10 320 3 Feb 101 TX01 Total_Country Nestle 14 420 4 Feb 101 TX01 Total_Country Unilever 15 500 5 Feb 101 TX04 South Abc 10 320 6 Feb 101 TX04 South Nestle 14 420 7 Feb 101 TX04 South Unilever 15 500 8 Jan 102 TX01 Total_Country Nestle 15 310 9 Jan 102 TX01 Total_Country Unilever 16 390 10 Feb 102 TX01 Total_Country Nestle 15 430 11 Feb 102 TX01 Total_Country Unilever 16 510 12 Feb 102 TX06 North Nestle 15 430 13 Feb 102 TX06 North Unilever 16 510 14 Feb 102 TX12 Mumbai Nestle 15 430 15 Feb 102 TX12 Mumbai Unilever 16 510 output Month State_Code State_Name Brand Area Price Sales 0 Jan TX01 Total_Country Nestle 203 29 610 1 Jan TX01 Total_Country Unilever 203 31 770 2 Feb TX01 Total_Country Abc 101 10 320 3 Feb TX01 Total_Country Nestle 203 29 850 4 Feb TX01 Total_Country Unilever 203 31 1010 5 Feb TX04 South Abc 101 10 320 6 Feb TX04 South Nestle 101 14 420 7 Feb TX04 South Unilever 101 15 500 8 Feb TX06 North Nestle 102 15 430 9 Feb TX06 North Unilever 102 16 510 10 Feb TX12 Mumbai Nestle 102 15 430 11 Feb TX12 Mumbai Unilever 102 16 510
{ "language": "en", "url": "https://stackoverflow.com/questions/67837520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sort Multi-dimensional array by value dynamically with PHP This Stackoverflow answer is 95% of the way there: https://stackoverflow.com/a/10484863. I just need to pass another variable into the function which I believe uses closure. I want to pass the variable sort: $sort = get_category_name(); into: function compareByName($a, $b) { return strcmp($a["name"], $b["name"]); } usort($a, 'compareByName'); so its $a[$sort] and not defined by me as $a[key]. My array: Array( [0] => Array ( [id] => 7 [product_type_id] => 2 [category_en] => Prints [category_es] => Impresiones [category_ru] => Печати ) [1] => Array ( [id] => 8 [product_type_id] => 2 [category_en] => Drawings [category_es] => Dibujos [category_ru] => Рисунки ) [2] => Array ( [id] => 9 [product_type_id] => 2 [category_en] => Paintings [category_es] => Pinturas/Cuadros [category_ru] => Картины ) ) should allow me to sort the array by the category based on the users language which is set by get_category_name().
{ "language": "en", "url": "https://stackoverflow.com/questions/19352063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unexpected search results when querying for files based on mimeType - Google Drive API v3 + Javascript I am trying to search Google Drive for Excel files using the Javascript API (v3). Some Excel files seem to have a mime type of 'application/vnd.ms-excel' and some have a mime type of 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'. When I use mime type 'application/vnd.ms-excel', the files with that mime type are returned correctly. But, when I use the mime type 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' I get a ton of irrelevant results (with mime types like 'x-javascript', 'x-markdown', and even 'image/png'). Is this a bug or am I doing something wrong? Any help will be greatly appreciated! Thanks. Here's my code: function getItemsByQuery(query, callback) { var retrievePageOfFiles = function(request, result) { request.execute(function(resp) { result = result.concat(resp.files); var nextPageToken = resp.nextPageToken; if (nextPageToken) { request = gapi.client.drive.files.list({ 'pageToken': nextPageToken }); retrievePageOfFiles(request, result); } else { result.length > 0 ? callback(result) : callback([]); } }); }; var q = {'q': query }; var initialRequest = gapi.client.drive.files.list(q); retrievePageOfFiles(initialRequest, []); } getItemsByQuery("trashed=false and mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'", function(results) { // Handle results - lots of irrelevant files returned here. }); A: It looks like you forgot to add the q field when rebuilding the query with a pageToken field.
{ "language": "en", "url": "https://stackoverflow.com/questions/40283817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript primitives: same memory location, new memory location, or engine-dependent? 10 var x = 5; 11 x = 10; Does the memory location of the variable x change in line 11 from line 10 OR does the JavaScript engine just overwrites the memory space originally allocated to x in line 10 and place the value 10 there? Is this specified, or engine-dependent? A: According to Javascript documentation, assigning values means reading and writing to memory that is already allocated. When you assign a variable, memory is allocated. When you change its value, reading and writing is done on the same memory location.
{ "language": "en", "url": "https://stackoverflow.com/questions/36135871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PETSc C macro within struct In PETSc, a number of common-use structures such as Vec, Mat, IS, etc. are defined similarly, as in the 4 snippets below. Questions: * *when and how is PETSCHEADER expanded? I am writing the foreign interface from another language, and was wondering whether I have to wrap the macro in a function or whatnot *What's the scope of hdr and ops ? Thanks in advance petscvec.h typedef struct _p_Vec* Vec; vecimpl.h struct _p_Vec { PETSCHEADER(struct _VecOps); PetscLayout map; void *data; /* implementation-specific data */ ... petscimpl.h #define PETSCHEADER(ObjectOps) \ _p_PetscObject hdr; \ ObjectOps *ops vecimpl.h typedef struct _VecOps *VecOps; struct _VecOps { PetscErrorCode (*duplicate)(Vec,Vec*); /* get single vector */ PetscErrorCode (*duplicatevecs)(Vec,PetscInt,Vec**); /* get array of vectors */ ...
{ "language": "en", "url": "https://stackoverflow.com/questions/30243958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filter with jQuery by input range A few days ago, I asked on this forum about filter with jQuery. Some people helped me but now I need to do filter no by checkboxes, but with input type="range". Is it possible? My code looks like: JSFIDDLE My code. $(document).ready(function () { $('input.szukajnapraw').on('click', function () { var $checked = $('input.szukajnapraw:checked'), $trs = $('.results > tr'); $trs.toggle(!$checked.length); if ($checked.length) { $checked.each(function () { var text = $(this).attr('rel').trim().toLowerCase(); $trs.find('td:nth-child(1),td:nth-child(4),td:nth-child(7),td:nth-child(13)').filter(function(){ return text == $(this).text().trim().toLowerCase(); }).parent().show(); }) } }).last().change(); }); <div class="box col-md-10 items"> <label>Ilość dysków</label> <input type="range" min="1" max="24" /> </div> <div class="box col-md-10 items"> <label>Pojemność</label> <input type="range" id="range1" min="1" max="96" /> </div> <div class="box col-md-10 items"> <label>Wydajność</label> <input type="range" min="50" max="2000" /> </div> <table class="table table-striped table-bordered"> <thead> <tr> <th>Producent</th> <th>Produkt</th> <th>Foto</th> <th>Typ</th> <th>Cena netto</th> <th>Cena brutto</th> <th>Interface</th> <th>Ilość dysków</th> <th>Pojemność</th> <th>RAID</th> <th>Wydajność</th> <th>Opis</th> <th>Specyfikacja</th> <th>Zakup</th> </tr> </thead> <tbody class="results"> <tr> <td>Tiger Technology</td><td>Macierz 123 TEST</td><td><img src="admin/forms/temp/ff.jpg" style = "width:50px;height:50px;"/></td><td>NAS Network Attached Storage</td><td>69.00</td><td>124.00</td><td>Thunderbolt2</td><td>60</td><td>5tb</td><td>0 1</td><td>Duża</td><td>dsadsadasdawderwasfcagfae</td><td style='display:none;'>1</td><td><a href=http://www.google.pl target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='30' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>G-Tech</td><td>vcxv</td><td><img src="admin/forms/temp/" style = "width:50px;height:50px;"/></td><td>DAS Direct Attached Storage</td><td>50.00</td><td>70.00</td><td>USB 3.0</td><td>5</td><td>400</td><td>5*5*</td><td>500</td><td>dsadsad</td><td style='display:none;'>1</td><td><a href=http://www.o2.pl target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='34' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>Tiger Technology</td><td>das sad</td><td><img src="admin/forms/temp/IMG_20150504_074450.jpg" style = "width:50px;height:50px;"/></td><td>SAN Srorage Area Network</td><td>50.00</td><td>70.00</td><td>eSATA</td><td>6</td><td>400</td><td>5/8/8</td><td>500</td><td>dasdasdsa</td><td style='display:none;'>2</td><td><a href=http://www.nw.pl target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='35' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>LaCie</td><td>Macierz</td><td><img src="admin/forms/temp/depositphotos_12071772-Website-Development-PHP-HTML-Arrows.jpg" style = "width:50px;height:50px;"/></td><td>SAN Srorage Area Network</td><td>98.00</td><td>120.00</td><td>miniSAS</td><td>6</td><td>4 TB</td><td>5</td><td>Duża</td><td>Tu powinien być opis, ale testuje i go nie wpisuje! </td><td style='display:none;'>2</td><td><a href=http://www.google.pl target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='36' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>LaCie</td><td>dsad</td><td><img src="admin/forms/temp/IMG_20150504_074450.jpg" style = "width:50px;height:50px;"/></td><td>SAN Srorage Area Network</td><td>50.00</td><td>70.00</td><td>Thunderbolt</td><td>8</td><td>400</td><td>8/8/8</td><td>500</td><td>fasdf</td><td style='display:none;'>2</td><td><a href=http://fsdfsdf target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='37' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>mLogic</td><td>test</td><td><img src="admin/forms/temp/ff.jpg" style = "width:50px;height:50px;"/></td><td>DAS Direct Attached Storage</td><td>80.00</td><td>100.00</td><td>Thunderbolt</td><td>8</td><td>900</td><td>5/8/8</td><td>600</td><td>fsdfd</td><td style='display:none;'>1</td><td><a href=http://fsdfds target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='38' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>Promise</td><td>Zdjęcie</td><td><img src="admin/forms/temp/depositphotos_12071772-Website-Development-PHP-HTML-Arrows.jpg" style = "width:50px;height:50px;"/></td><td>DAS Direct Attached Storage</td><td>4564.00</td><td>999999.99</td><td>Thunderbolt</td><td>4</td><td>5</td><td>1</td><td>300</td><td>SPrawdzam czy działaja fotki .... .... .. .. .. .</td><td style='display:none;'>1</td><td><a href=http://feasd target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='39' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>Promise</td><td>g</td><td><img src="admin/forms/temp/rc.jpg" style = "width:50px;height:50px;"/></td><td>DAS Direct Attached Storage</td><td>45.00</td><td>5.00</td><td>Thunderbolt</td><td>12</td><td>1</td><td>1</td><td>l</td><td>l</td><td style='display:none;'>1</td><td><a href=http://l target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='40' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>Promise</td><td>jj</td><td><img src="admin/forms/temp/" style = "width:50px;height:50px;"/></td><td>DAS Direct Attached Storage</td><td>1.00</td><td>1.00</td><td>Thunderbolt</td><td>2</td><td>j</td><td>j</td><td>j</td><td>n</td><td style='display:none;'>1</td><td><a href=http://j target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='43' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr><tr> <td>Promise</td><td>jj</td><td><img src="admin/forms/temp/" style = "width:50px;height:50px;"/></td><td>DAS Direct Attached Storage</td><td>1.00</td><td>1.00</td><td>Thunderbolt</td><td>2</td><td>j</td><td>j</td><td>j</td><td>n</td><td style='display:none;'>1</td><td><a href=http://j target='_blank'>Specyfikacja producenta</a></td><td><form action='' method='POST'> <input type='hidden' name='id' value='44' /> <input class='btn btn-primary btn-sm' type='submit' name='koszykAdd' value='Dodaj do koszyka'/></form></td></tr> </tbody> </table> A: Try utilizing .each() , where i is index of element within collection , el is element , el.value is value of input type="range" current element within loop $("input[type=range]").each(function(i, el) { console.log(el.value); }); https://jsfiddle.net/f3x5jfjg/15/ A: Yes, that can be done. You would have to take advantage of the change event, not the click event though. As the ranges are wide, and it's hard to find a match I have set a match by default and used addClass() and removeClass() instead of hide() and show() just to demonstrate how to approach this. Pick any other match, if you can find one, and set your ranges to it. $(document).ready(function () { var ranges = $('div.box > input[type=range]'), table = $('table.table'), hrow = $('tr:has(th)', table), orow = $('tr:has(td)', table); ranges.on('change', function() { //init range object var orange = []; //determine value setting & index for each range ranges.each(function() { var thisrange = {}; thisrange.value = this.value; thisrange.label = $(this).prev('label').text().trim(); thisrange.column = $.inArray( thisrange.label, $('th',hrow).map(function(i,v) { return $(v).text().trim(); }) ); $(this).next('label').text( this.value ); orange.push( thisrange ); }); //hide [remove hightlight] all rows but header orow.removeClass('highlight'); //show [hightlight] rows with values orow.filter(function() { var result = true,that = this; $.each( orange, function(i,v) { result = result && $('td',that).eq(v.column).text().trim() == v.value; }); return result; }).addClass('highlight'); }).change(); }); DEMO NOTE: Some values in the filter columns are non-numeric and would never be set on the range! And some numeric values are out of range. Update Here is a version that will filter just by the changed range. When the page loads it filters by the value of the first range. $(document).ready(function () { var ranges = $('div.box > input[type=range]'), table = $('table.table'), hrow = $('tr:has(th)', table), orow = $('tr:has(td)', table); ranges.on('change', function() { var value = this.value, label = $(this).prev('label').text().trim(), column = $.inArray( label, $('th',hrow).map(function(i,v) { return $(v).text().trim(); }) ); //display the new value $(this).next('label').text( value ); //hide [remove hightlight] all rows but header orow.removeClass('highlight'); //show [hightlight] rows with values orow.filter(function() { return $('td',this).eq(column).text().trim() == value; }).addClass('highlight'); }).eq(0).change(); }); DEMO
{ "language": "en", "url": "https://stackoverflow.com/questions/30126765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't (Style)Application.Current.Resources["FrameBorder"] let me access a resource in my ResourceDirectory I created a resource in the file FrameRes.xaml like this: <ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Japanese.Resources.FrameRes"> <Style x:Key="FrameBorder" TargetType="Frame"> <Setter Property="CornerRadius" Value="2" /> <Setter Property="HasShadow" Value="false" /> <Setter Property="Margin" Value="10,0" /> <Setter Property="BorderColor" Value="{DynamicResource LineColor}" /> <Setter Property="Padding" Value="0" /> <Setter Property="VerticalOptions" Value="Start" /> </Style> </ResourceDictionary> and this is contained inside: <?xml version="1.0" encoding="utf-8"?> <Application xmlns:converters="clr-namespace:Japanese" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Japanese.App"> <Application.Resources> <ResourceDictionary Source="/Resources/FooterRes.xaml" /> <ResourceDictionary Source="/Resources/FrameRes.xaml" /> </Application.Resources> </Application> When I try to access this in C# like this then it fails and says there's no reference to FrameBorder: var fb2 = (Style)Application.Current.Resources["FrameBorder"]; When I try to access this in C# like this it works: Application.Current.Resources.TryGetValue("FrameBorder", out object frameBorder); var fb = (Style)frameBorder; Does anyone know why the first way doesn't work. It looks the same to me. A: The way you have it set up, you have a ResourceDictionary inside another ResourceDictionary with no key/name/reference. When you call Application.Current.Resources["FrameBorder"];, you are accessing the upper-most level of the dictionary and looking for "FrameBorder", not its sub-levels. However, calling TryGetValue goes through all levels of the Dictionary. Read through the Docs to understand how to access values from Dictionaries. Ok, so I have played around with the ResourceDictionary tags and files, and I can see where you're going wrong. According to the Xamarin Forms Docs on ResourceDictionary, you can add stand-alone ResourceDictionary XAML files to your App.xaml like so: <App ...> <App.Resources> <!-- Add more resources here --> <ResourceDictionary Source="MyResourceDictionary.xaml" /> <!-- Add more resources here --> </App.Resources> ... </App> You can replace App with ContentPage or ContentView, depending on your use. What does this do? Simply put, this creates a new ResourceDictionary object and merges other ResourceDictionary files into it. Let's go into a bit more detail. Let's start by looking at the Application.Current.Resources property, which is of type ResourceDictionary and implements ICollection, IDictionary, and IResourceDictionary. Given the interfaces it implements, you can obtain the values by numeric or string ID (ex: App.Current.Resources[0] or App.Current.Resources["LabelStyle"]). This accesses the top-level contents of the dictionary, so only those that have been created in the <[App/ContentPage/ContentView].Resources> tag. You also have a property called MergedDictionaries, which implements ICollection. This means that you can only access the list items by numeric ID (ex: MyMergedDictionary[0]). When you add a ResourceDictionary file like: <ResourceDictionary Source="MyResourceDictionary.xaml" /> You are actually merging this file with the current ResourceDictionary. To then access the contents of MyResourceDictionary you would call (in C#): App.Current.Resources.MergedDictionaries[0]["InternalKeyName"] This is probably better explained like so: <App ...> <App.Resources> <!-- Called using App.Current.Resources["PrimaryColor"] --> <Color x:Key="PrimaryColor">#2196F3</Color> <!-- Called using App.Current.Resources.MergedDictionaries[0]["InternalKeyName"] --> <ResourceDictionary Source="MyResourceDictionary.xaml" /> </App.Resources> ... </App> Your case In your case you have two dictionaries merged into your Application Resources: FooterRes and FrameRes. For better management, I would create an enum like: public enum MergedResourcesEnum { Footer, Frame } and use this enum when calling the resources in C# like so: Application .Current .Resources .MergedDictionaries[(int)MergedResourcesEnum.Frame]["FrameBorder"]; A: You can try to delete the outer ResourceDictionary tag and both of var fb2 = (Style)Application.Current.Resources["FrameBorder"]; and Application.Current.Resources.TryGetValue("FrameBorder", out object frameBorder); var fb = (Style)frameBorder; work right. So your xaml code is like this: (Please ignore the unrelated package name and FooterRes.xaml because I you didnot share your FooterRes.xaml file) <Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="App75.App"> <Application.Resources> <ResourceDictionary Source="/Resources/FooterRes.xaml" /> </Application.Resources> </Application>
{ "language": "en", "url": "https://stackoverflow.com/questions/53457854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Can anybody help explain what happens here with Java thread interruption? These are the 3 classes I have: public class ChildThread extends Thread { @Override public void run() { while (true) { System.out.println("Child thread is running."); if (Thread.currentThread().isInterrupted()) { System.out.println("Child thread is interrupted."); return; } } } } public class MainThread extends Thread{ public Thread childThread = new ChildThread(); @Override public void run() { childThread.start(); } } public class App { public static void main(String[] args) { MainThread mainThread = new MainThread(); mainThread.start(); mainThread.childThread.interrupt(); } } When I run this, the child thread doesn't seem to be ever interrupted. It keeps printing: "Child thread is running." However, if I put a debug breakpoint at mainThread.childThread.interrupt();, child thread will get interrupted. And also, if I change App class like the following: public class App { public static void main(String[] args) throws Exception{ ChildThread childThread = new ChildThread(); childThread.start(); Thread.sleep(3000); childThread.interrupt(); } } it works again. Child thread gets interrupted and stopped printing after 3 seconds. It seems that the behaviors are different interrupting from a thread that directly started a child thread, and from a thread that didn't directly start a child thread. And it's also different depending on whether there's a breakpoint or not. It's so weird to me. How could this work in a complex system? I don't think a complex system can guarantee all interruption signals are from the original starters of threads. Could anyone help explain this? I can't find anywhere that seem to have an answer. A: You need the Thread.sleep before interrupting otherwise, you are interrupting before the child thread even before it has gotten a chance to start running. As per the API specs "Interrupting a thread that is not alive need not have any effect.". So, in affect, the interrupt statement is being ignored as at the time the thread is not active. Without the sleep, the thread become active AFTER the interrupt - hence is never interrupted. public class App { public static void main(String[] args) throws InterruptedException { MainThread mainThread = new MainThread(); mainThread.start(); Thread.sleep(1); // <== This line is needed as otherwise, the next line will // interrupt the thread, even before it has started running! mainThread.childThread.interrupt(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/48848624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mutate F# [] Record This code shows how to make a function mutate its input - one of the things we come to F# to avoid. type Age = { mutable n : int } let printInside a = printfn "Inside = %d" a.n let inside a = a.n <- a.n + 1 a.n let a = {n = 1} printInside a //a = 1 inside a printInside a //a = 2 That being said, how do I do the same bad thing with [<Struct>] Records? I suspect that ref or byref may be involved but I just can't seem to get it to work. type [<Struct>] Age = { mutable n : int } let printInside a = printfn "Inside = %d" a.n let inside a = a.n <- a.n + 1 a.n let a = {n = 1} printInside a //a = 1 inside a printInside a //a = 2 A: The fundamental issue is that a mutable field can only be modified if the struct itself is mutable. As you noted, we need to use byref in the declaration of Age. We also need to make sure a is mutable and lastly we need to use the & operator when calling the function inside. The & is the way to call a function with a byref parameter. type [<Struct>] Age = { mutable n : int } let printInside a = printfn "Inside = %d" a.n let inside (a : Age byref) = a.n <- a.n + 1 a.n let mutable a = {n = 1} printInside a //a = 1 inside &a printInside a //a = 2 A: Now that I get the pattern, here is a simple example (just an int instead of a struct record) of how to mutate values passed into a function: let mutable a = 1 let mutate (a : byref<_>) = a <- a + 1 mutate &a a //a = 2
{ "language": "en", "url": "https://stackoverflow.com/questions/53235635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HTML input button with onclick with custom onStart function not working I have created a button with an onclick function which loads particular elements after clicking on the button. For some reason, suddenly the button cannot be clicked and the function has now become undefined. After running the same code on js fiddle, the correct output is executed however within the browser through xampp the code does not run function onStart() { //Start Button startBtn.style.display = "none"; } <input type="button" id="startBtn" value="START" onclick="onStart()">
{ "language": "en", "url": "https://stackoverflow.com/questions/47562990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to access model attributes in view through thymeleaf and spring boot I'm having hardtime to access model attribute values in the view using thymeleaf. <h4>Employees per Project</h4> <table class="table table-bordered table-striped"> <thead class="thead-dark"> <tr> <th> FirstName<span></span></th> <th> LastName</th> <th>Projects Count</th> </tr> </thead> <tbody> <tr th:each=" EmpPrjCnt : ${employeeProjectCount} "> <td th:text="${EmpPrjCnt.fName}"></td> <td th:text="${EmpPrjCnt.lname}"></td> <td th:text="${EmpPrjCnt.Pc}"></td> </tr> </tbody> </table> </div> Controller Code: List<projectEmployee> employeeProjectCount= empRep.employeeProjects(); //.employeeProjects(); System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount); System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getfName()); System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getlName()); System.out.println("FROM Home Controller :::::::::: "+employeeProjectCount.get(1).getPc()); model.addAttribute("employeeProjectCount", employeeProjectCount); I can access all the attributes in the controller through but not in the view. Let me know where im going wrong. Error: There was an unexpected error (type=Internal Server Error, status=500). An error happened during template parsing (template: "class path resource [templates/main/Home.html]") org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/main/Home.html]") at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241) at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100) at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1103) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1077) at org.thymeleaf.spring6.view.ThymeleafView.renderFragment(ThymeleafView.java:372) at org.thymeleaf.spring6.view.ThymeleafView.render(ThymeleafView.java:192) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1414) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1158) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1097) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1003) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:895) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:705) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:880) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:833) Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "EmpPrjCnt.fName" (template: "main/Home" - line 70, col 12) at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393) at org.attoparser.MarkupParser.parse(MarkupParser.java:257) at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230) ... 48 more Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "EmpPrjCnt.fName" (template: "main/Home" - line 70, col 12) at org.thymeleaf.spring6.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292) at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166) at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138) at org.thymeleaf.standard.processor.AbstractStandardExpressionAttributeTagProcessor.doProcess(AbstractStandardExpressionAttributeTagProcessor.java:144) at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314) at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205) at org.thymeleaf.engine.Model.process(Model.java:282) at org.thymeleaf.engine.Model.process(Model.java:290) at org.thymeleaf.engine.IteratedGatheringModelProcessable.processIterationModel(IteratedGatheringModelProcessable.java:368) at org.thymeleaf.engine.IteratedGatheringModelProcessable.process(IteratedGatheringModelProcessable.java:222) at org.thymeleaf.engine.ProcessorTemplateHandler.handleCloseElement(ProcessorTemplateHandler.java:1640) at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleCloseElementEnd(TemplateHandlerAdapterMarkupHandler.java:388) at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:322) at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleCloseElementEnd(OutputExpressionInlinePreProcessorHandler.java:220) at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleCloseElementEnd(InlinedOutputExpressionMarkupHandler.java:164) at org.attoparser.HtmlElement.handleCloseElementEnd(HtmlElement.java:169) at org.attoparser.HtmlMarkupHandler.handleCloseElementEnd(HtmlMarkupHandler.java:412) at org.attoparser.MarkupEventProcessorHandler.handleCloseElementEnd(MarkupEventProcessorHandler.java:473) at org.attoparser.ParsingElementMarkupUtil.parseCloseElement(ParsingElementMarkupUtil.java:201) at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:725) at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301) ... 50 more Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1021E: A problem occurred whilst attempting to access the property 'fName': 'Accessing member 'fName' is forbidden for type 'class jdk.proxy5.$Proxy124' in Thymeleaf expressions. Blocked classes are: [com.sun.*, jakarta.*, java.*, javax.*, jdk.*, org.ietf.jgss.*, org.omg.*, org.w3c.dom.*, org.xml.sax.*, sun.*]. Allowed classes are: [java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Enum, java.lang.Float, java.lang.Integer, java.lang.Iterable, java.lang.Long, java.lang.Math, java.lang.Number, java.lang.Short, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.math.RoundingMode, java.time.*, java.util.ArrayList, java.util.Calendar, java.util.Calendar, java.util.Collection, java.util.Date, java.util.Enumeration, java.util.HashMap, java.util.HashSet, java.util.Iterator, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.LinkedList, java.util.List, java.util.Locale, java.util.Map, java.util.Map$Entry, java.util.Optional, java.util.Properties, java.util.Set, java.util.stream.Stream].' at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:209) at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104) at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:405) at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:92) at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112) at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:338) at org.thymeleaf.spring6.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:265) ... 75 more Caused by: org.springframework.expression.EvaluationException: Accessing member 'fName' is forbidden for type 'class jdk.proxy5.$Proxy124' in Thymeleaf expressions. Blocked classes are: [com.sun.*, jakarta.*, java.*, javax.*, jdk.*, org.ietf.jgss.*, org.omg.*, org.w3c.dom.*, org.xml.sax.*, sun.*]. Allowed classes are: [java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Enum, java.lang.Float, java.lang.Integer, java.lang.Iterable, java.lang.Long, java.lang.Math, java.lang.Number, java.lang.Short, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.math.RoundingMode, java.time.*, java.util.ArrayList, java.util.Calendar, java.util.Calendar, java.util.Collection, java.util.Date, java.util.Enumeration, java.util.HashMap, java.util.HashSet, java.util.Iterator, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.LinkedList, java.util.List, java.util.Locale, java.util.Map, java.util.Map$Entry, java.util.Optional, java.util.Properties, java.util.Set, java.util.stream.Stream]. at org.thymeleaf.spring6.expression.ThymeleafEvaluationContext$ThymeleafEvaluationContextACLPropertyAccessor.canRead(ThymeleafEvaluationContext.java:237) at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:198) ... 81 more
{ "language": "en", "url": "https://stackoverflow.com/questions/74913894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call LostFocus event of another control from the other control Calling the LostFocus event of control from other control Example. : I want to call LostFocus event of Button1 button from the Gotfocus event of Button2 button. code is :- private void button2_GotFocus(object sender, RoutedEventArgs e) { button1.gotFocus // this line giving error. } A: Use following code: private void button2_GotFocus(object sender, RoutedEventArgs e) { button1.RaiseEvent(new RoutedEventArgs(LostFocusEvent, button1)); } private void button1_LostFocus(object sender, RoutedEventArgs e) { } If this doesn't solve your problem, post your code and state your problem and purpose clearly so that you can get better solution. A: you can just call event handler method of Button1's LostFocus event in button2_GotFocus : private void button2_GotFocus(object sender, RoutedEventArgs e) { button1_LostFocus(this.button1, null); } A: Try this private void button2_GotFocus(object sender, RoutedEventArgs e) { button1_LostFocus(sender,e) }
{ "language": "en", "url": "https://stackoverflow.com/questions/21301669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nav Bar not showing after camera image capture I have been updating an app that I had some else build for me. In the updating, I am instituting storyboard segues, among other things, and have got the app almost complete. One little niggling issue is when I take an picture with the camera and the image is presented in the TakenImageView, the NavBar is not visible. Yet, if I go from the gallery to the TakenImageView, the NavBar shows! Ugh. The image picker is presented from the HomeView, then moves to TakenImage after the user chooses camera or gallery. I have tried to change to a prepare and perform Segue, but the segue doesn't fire from the gallery when selecting an image or from the camera's UsePhoto. The only way I can get the image to the TakenImageView is to manually segue via instantiating the view in code. See below... - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info; { UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; TakenImageVC *takenVC = [storyboard instantiateViewControllerWithIdentifier:@"TakenImageVC"]; takenVC.takenimage = [info objectForKey:UIImagePickerControllerOriginalImage]; [picker pushViewController:takenVC animated:YES]; //_pickerImage = [info objectForKey:UIImagePickerControllerOriginalImage]; //[self performSegueWithIdentifier:@"TakenSegue" sender:self]; } The prepare for segue has only these three. The top two are modal and are linking from the buttons. The TakenSegue is linking from the controller. Of course, I have the destinationController commented out, as the segue doesn't fire when using perform as noted earlier. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"InfoSegue"]) { NSLog(@"Info Modal view"); } if ([segue.identifier isEqualToString:@"HelpSegue"]) { NSLog(@"Help Modal view"); } if ([segue.identifier isEqualToString:@"TakenSegue"]) { NSLog(@"Taken Segue"); //TakenImageVC *takenVC = segue.destinationViewController; //takenVC.takenimage = _pickerImage; } } In trying different methods, I have added a NavigationController between the HomeView and TakenImageView and have changed the class to UIImagePickerController in the attributes. Still, the NavBar doesn't show... but only after taking a photo with the camera! And, yes, I have the navigation bar set to not hide... in both the HomeView and TakenView. This is in the viewWillAppear of both controllers. Target is iOS7.1 and up. Running Xcode 7. I'd appreciate some help from anyone with a hint as to what is causing the nav bar to not show from the camera and, of course, a way to fix it! Thanks! A: I was unable to get the next view to show with a nav bar after the camera, even after trying numerous scenarios. So, after seeing a hint in a different post, I removed the nav controller between the home and taken view, changed the attributes to none for Simulated Metrics/Top Bar and inserted a toolbar in it's place in the TakenView and two following views. Yes, it required more work in Storyboard and I had to add a label where the title should go, but it is all functioning. And, I didn't have to add any more code, except for changing the back or cancel buttons into unwindSegues.
{ "language": "en", "url": "https://stackoverflow.com/questions/33144321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing Soap XML I have a XML like this: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <SampleResponse xmlns="http://tempuri.org/"> <SampleResult> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <NewDataSet xmlns=""> <Table diffgr:id="Table1" msdata:rowOrder="0"> <tag1>tag1 text</tag1> <tag2>tag2 text</tag2> </Table> <Table diffgr:id="Table2" msdata:rowOrder="1"> <tag1>tag1 text</tag1> <tag2>tag2 text</tag2> </Table> </NewDataSet> </diffgr:diffgram> </SampleResult> </SampleResponse> </soap:Body> </soap:Envelope> So i parsed above XML using Below Code: string XMLresponse = e.response; var XResult = XElement.Parse(XMLresponse); var result = XResult.Descendants("Table") .Select(t => new { tag1 = t.Descendants("tag1").First().Value, tag2 = t.Descendants("tag2").First().Value, }); foreach (var res in result) { string str = res.tag1; // here i am able get the response } listbox.ItemsSource = result; But i am not able bind it to ListBox. i have a ListBox like below: <ListBox x:Name="listbox"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical"> <TextBlock Text="Sample" ></TextBlock> <TextBlock Text="{Binding tag1}" ></TextBlock> <TextBlock Text="{Binding tag2}" ></TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> In the ListBox i have added a TextBlock, which is repeated twice. But the dynamical text blocks are not binding with data. A: The two dynamic values are represented as fields, not properties. And since you can only bind to properties in XAML, you'll need to create a strong-typed data structure with your two properties, and select the values into that. Something like: class V { public string tag1 { get; set; } public string tag2 { get; set; } } var result = XResult.Descendants("Table").Select(t => new V { tag1 = t.Descendants("tag1").First().Value, tag2 = t.Descendants("tag2").First().Value, });
{ "language": "en", "url": "https://stackoverflow.com/questions/8802109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery : XMLHttp Requests : Is this use of synchronous ajax bad? I know that in general the goal should be to avoid async: false. However, in this situation, I want to understand whether it's worth tying things together to make it work, or if it is okay: On my site's registration page, I have a JS/jQuery validation function on submission. It has two AJAX queries, one for the username (to make sure it hasn't already been taken), and one for the email (to make sure they didn't submit an email already claimed by another user). In the validation function, I check each of these, along with lots of other things (passwords matching, check not blank, etc.), and when either of these pop up, a warning message states the issue. Both of these ajax queries use async: false in order to ensure that the form doesn't submit before they are checked. My question is, how bad is this? And if it's bad bad, then why? I could put the work in to make a single function that checks both and has 4 return values for each of the different options, but that seems like a lot... I know this may not be a solid coding question, but I'm new to coding and want to make sure I understand what the difference here means. Thanks so much in advance. A: Synchronous HTTP requests halt execution of subsequent code while they are en route. While browsers may no longer block the UI during this time, we're relying on the user's available bandwidth, network reliability, and the server's current load for the performance of our code. This is generally not good practice. as i have found from this link may this will help you please look at this https://softwareengineering.stackexchange.com/questions/112551/should-we-still-consider-a-synced-xmlhttprequest-bad-practice you should also reffer to https://webtide.com/xmlhttprequest-bad-messaging-good/
{ "language": "en", "url": "https://stackoverflow.com/questions/14490770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Crystal Reports Record Selection and Summary Field conflict I am really new to Crystal Reports and I am looking for any suggestions on how to approach the following issue: I currently have a report that uses a record selection to limit the results by date. I would like to include in this same report a summary a total count of all the records (ignoring the record restriction). Unfortunately (although somewhat expected), the summary calculates the total after the record restriction is applied. Is there any way to get around this? In case my question is a bit unclear I've included a generic example below: * *I have a report that pulls info from a database with a total of 10 records. *I select a specific date range, and it only returns 3 records *I would like to include in the report footer that 3/10 records are getting returned. A: This is bit tricky to perform in crystal reports as record selection is compulsory applied. However you can overcome this by using sub report. Calculate the report footer using report. This will surely work
{ "language": "en", "url": "https://stackoverflow.com/questions/17958053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Logical constraints in CPLEX I am a beginner at using CPLEX and I have come across a problem with creating logical constraints (if ... then ...). I use IBM ILOG CPLEX Optimization Studio version 12.7. According to the the manual, it should be able to handle logical constraints by using "=>" (e.g., "if x>0 then y>=2" should become x>0 => y>=2). The problem consists of assigning a start and end of a shift to employees (or a 0 if they are not working today). I am trying to create a variable that functions like an indicator for whether they are working in order to use it for assigning costs later. I have boiled my code down to the following: using CP; tuple TimeSlot { key int day; key int slotNo; } {TimeSlot} TimeSlots = ...; {int} mondays = {t.slotNo|t in TimeSlots:t.day==1}; int monMax = max(t in mondays) t; range monRange = 0..monMax; range allEmployees = 1..10; dvar int monStart[allEmployees] in monRange; //Start of monday shift dvar int monEnd[allEmployees] in monRange; //End of monday shift dvar int monAtWork[allEmployees] in 0..1; //Binary //minimize ... subject to{ forall(t in allEmployees) {monStart[t] > 0 && monEnd[t]>0} => monAtWork[t] = 1; //Get error here } The error I get is syntax error, unexpected =. I have tried both splitting and flipping the constraint (e.g., monStart[t] == 0 => monAtWork[t] = 0;) to no avail. Am I missing something? A: Looking at the provided OPL examples (e.g. BasketballScheduling\acc.mod) I think that the 'then' part defining the constraint should have '==' rather than '='. It is not an assignment, but declaring that the two must be equal. A: using CP; tuple TimeSlot { key int day; key int slotNo; } {TimeSlot} TimeSlots = {<1,1>,<2,2>};; {int} mondays = {t.slotNo|t in TimeSlots:t.day==1}; int monMax = max(t in mondays) t; range monRange = 0..monMax; range allEmployees = 1..10; dvar int monStart[allEmployees] in monRange; //Start of monday shift dvar int monEnd[allEmployees] in monRange; //End of monday shift dvar int monAtWork[allEmployees] in 0..1; //Binary //minimize ... subject to{ forall(t in allEmployees) (monStart[t] > 0 && monEnd[t]>0) => monAtWork[t] == 1; //Get error here } works fine
{ "language": "en", "url": "https://stackoverflow.com/questions/43251134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a Flash Movieclip via a web interface? Forgive me if this is not the correct place to ask such a question. Basically, I am looking for a way to allow someone to easily (at least, easier then diving into Flash) create a basic Flash animation (movieclip) with some placed image assets and text, all via a web interface. I was thinking along the lines of using jQuery to allow drag and drop assets, of which you'd "record" the co-ordinates and relay that to Flash somehow to create the SWF file. Or would it be better to create a tool in Flash (surely making operations easier) and then have some kind of "save" button to render out the SWF? I'm totally open to suggestions. Thank you A: If you really need to produce a stand-alone SWF file (and not just a config file for you own "player"), I would probably do it like this; 1) Create your editor in whatever system you feel like (flash, jquery etc). 2) Build a config file in the client. This is used, together with all the resources the user added, to play back the animation. 3) Upload said assets and config file to your web server. 4) Use the flex compiler (on the server) to produce the resulting SWF, combining your player with generated AS3 which embeds the uploaded resources as needed, to make it available to the player. 5) Give the user a download link for the newly generated SWF file. A: I don't think there is any swf compiler available for Flash (actionescript). You may create a swf that allows users to create an animation, save it as a home-made vector format, and then replay it. But I don't believe you can create and independant swf file with only the created animation in it. Just think about a player in Flash, and a format that the player will read (xml, json, name it...). You can either generate the input with jQuery or Flash, and then feed it into your player to display it. You will eventually need two files. A: Apparently this library allows you to compile SWFs at runtime. I haven't used it myself (yet) and don't know how stable or flexible it is, but it appears to be what you're looking for. I'd recommend giving it a spin and seeing if it's sufficient. I'm not exactly sure how it saves the file, so you might run into security problems since it's a web application. Hopefully it should be OK though.
{ "language": "en", "url": "https://stackoverflow.com/questions/14258455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FCM messages are not delivered when the device is started and it has a password On android, the messages do not arrive after I restart my device and have a password, if he has no password he receives the message I would like to understand this situation, whether it is for security or really is a sdk failure
{ "language": "en", "url": "https://stackoverflow.com/questions/61322949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: need to add a col conditionally I have one table which I want to join with another. I would create a commmand in Crystal reports to get this output and change the names in the formulas easily. I need something like this: only I need the sum from the second tbl. Select * from rapklib.shpfrt a left outer join ralib.shpfrtc b where idord# a = idord# b the first is created as CREATE VIEW Ralib.shpfrt AS SELECT T01.IDORD#, T01.IDDOCD, T01.IDPRT#, T01.IDSFX#, T01.IDSHP#, T01.IDNTU$, T01.IDENT# , ( T01.IDNTU$ * T01.IDSHP# ) AS LINTOT , T02.IARCC3, T02.IAPRLC , T01.IDORDT, T01.IDHCD3 FROM STDTA.OEINDLID T01 INNER JOIN STDTA.ICPRTMIA T02 ON T01.IDPRT# = T02.IAPRT# WHERE t01.iddocd > 20131231 the second is the same as the first but only will contain rows when there is a value in idprt# = 'FRTCRDM' then the sum we get there means there was a credit given for shipping charge (freight). So I want to join them for use in a crystal report that will give me all the rows of the first but bring in the FRTCRDM amounts as well. Currently I am joining them when order# are = and thus only getting orders which have a FRTCRDM.
{ "language": "en", "url": "https://stackoverflow.com/questions/30201845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disqus Comment System [Wordpress] - Change the word "Comment" i have installed Disqus comment system on one of my wordpress blogs, but i want the comment numbers to show as 0 instead of 0 Comments or 12 instead of 12 Comments. Previously there used to be an Appearance section in Disqus admin that used to have an option to change this output as was suggested in answer to this question. But seems like the Appearance section has been taken off by Disqus. Is there any other way to achieve this (without messing with the plugin code, ofcourse.) ?? UPDATE: Well, looked into the plugin source as well but no use, seems like they are updating it using javascript. After enabling Reactions now it returns 0 comments and 0 Reactions. UPDATE#2: okie so i at last found where it is coming from ... the plugin basically includes a count.js files from yoursite.disqus.com\count.js?some wierd parameters, and the js file looks something like this: var DISQUSWIDGETS; if (typeof DISQUSWIDGETS != 'undefined') { DISQUSWIDGETS.displayCount({"showReactions": true, "text": {"and": "and", "reactions": {"zero": "0 Reactions", "multiple": "{num} Reactions", "one": "1 Reaction"}, "comments": {"zero": "0 Comments", "multiple": "{num} Comments", "one": "1 Comment"}}, "counts": [{"reactions": 0, "uid": 1, "comments": 0}, {"reactions": 0, "uid": 0, "comments": 0}, {"reactions": 0, "uid": 3, "comments": 0}, {"reactions": 0, "uid": 2, "comments": 0}, {"reactions": 0, "uid": 4, "comments": 0}]}); } the worst part is we can't even change the code in the js file as it is hosted on disqus itself. A: Alternatively you can "hack" the code of Disqus. I'll try to explain what I did step-by-step: * *Get the newest file of the main disqus function. It should be something similar to this: http://disqus.com/forums/(your-site-id)/count.js *Copy that script somewhere, you can "beautify it" to make it more readable. Than find and change the displayCount function to whatever you want to like this: c.displayCount = function (a) { for (var b, c, e, g, f = 0; f < a.counts.length; f++) if (b = a.counts[f], c = h[b.uid]) e = b.comments === 0 ? "0 drivels" : b.comments == 1 ? "1 drivel" : "{num} drivels", g = e.replace("{num}", b.comments), a.showReactions && (e = b.reactions === 0 ? a.text.reactions.zero : b.reactions == 1 ? a.text.reactions.one : a.text.reactions.multiple, e !== "" && (g += " " + a.text.and + " " + e.replace("{num}", b.reactions))), c.element.innerHTML = g }; (note the drivels ;) *Save (upload) the whole file somewhere on your server and remember the path *Use Wordpress administration to edit the Disqus plugin - file disqus-comment-system/disqus.php and find line that contains concatenated url withthe word count.js. It is in about 3/4 of the file. As of now the line looks like this but it might change in the future: s.src = '//' + '<?php echo DISQUS_DOMAIN; ?>/forums/' + disqus_shortname + '/count.js'; *Make this link point to your newly-uploaded file like this (I used relative URL): s.src = '/wp-include/custom/disqus-count.js'; *Save it and profit! It took me more than an hour to figure this out so I hope this actually helps someone (I needed to translate these messages into my native language). A great benefit of this approach is the fact that if your language uses different word forms for different numbers (other than 0, 1 and more), you can script it in. A: You should be able to hide it via JavaScript. Something along these lines: node = document.getElementsByClassName("dsq-comment-count")[0].childNodes[0] node.nodeValue = node.nodeValue.replace("Comments", "") A: The official answer is here: http://help.disqus.com/customer/portal/articles/565624#customizing-link-text * *Go to http://YOUR-SITE.disqus.com/admin/settings/?p=general *Edit Comment Count Link section as you need. *That's all!
{ "language": "en", "url": "https://stackoverflow.com/questions/12126869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble with for loops in Python 3: getting the index in string2 of an element from string1 I am trying to write a program that will take a file and encode it using the Viginère cipher. I've run into a little bump with indices. I've defined my strings text and alphabet like this: import string alphabet = string.ascii_lowercase ciphertext = open("black_hole.txt","r") ciphertext = ciphertext.read() text = "" for i in range(len(ciphertext)): if ciphertext[i].isalpha() == True: text = text + ciphertext[i] My trouble starts when I try to write this for loop: for i in range(len(text)): print(alphabet.index(text[i])) I get the ValueError "substring not found". I find this strange since text[i] is always a letter as well as a string. Please let me know if I haven't posed this question clearly enough! A: for i in range(len(text)): print(alphabet.index(text.lower()[i])) just add lower() and it will work A: As stated by Kevin in comments, you are probably missing uppercase. You can use alphabet[ord(text[i].lower()) - ord('a')] instead of index.
{ "language": "en", "url": "https://stackoverflow.com/questions/30627204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Count by ratio and then group by MSQL I have a table like ID Name 1 ABC 1 DEF 1 VVV 1 BBB 1 BCD 2 ZZZ 2 BAA 3 AAA 3 BBB 3 BBC I want to get the ratio of all the names that start with A to All the names that start with B group by ID. So the output should be ID Ratio 1 0.5 2 0 3 0.33 . SELECT (ID, (SELECT COUNT(*) FROM `table` WHERE name LIKE 'A%') / (SELECT COUNT(*) FROM `table` WHERE name LIKE 'B%')) AS `ratio` from table Group by ID does not give me the right answer. It takes the total ratio of A/B across all ID's into account and writes that number for all the ID's. A: I'd try: SELECT ID, CASE WHEN B = 0 THEN 0 ELSE A/B END AS Ratio FROM ( SELECT ID, SUM(CASE WHEN Name LIKE 'A%' THEN 1 ELSE 0 END) AS A, SUM(CASE WHEN Name LIKE 'B%' THEN 1 ELSE 0 END) AS B FROM my_table GROUP BY ID ) AS grouped; The inner SELECT gets the group IDs, and for every ID, the number of items beginning with A and those beginning with B. The outer SELECT (you can omit it if you're sure that there'll always be at least one B-row) checks that the ratio makes sense before attempting to calculate it. Or else: SELECT ID, COALESCE(SUM(CASE WHEN Name LIKE 'A%' THEN 1 ELSE 0 END) / SUM(CASE WHEN Name LIKE 'B%' THEN 1 ELSE 0 END), 0) FROM my_table GROUP BY ID; This takes advantage of the fact that, if the number of B-rows is zero, the division will yield NULL. The COALESCE transforms that NULL in a 0. A: This will do it: SELECT id, SUM(IF(name LIKE 'A%',1,0))/SUM(IF(name like 'B%',1,0)) FROM `table` GROUP BY ID
{ "language": "en", "url": "https://stackoverflow.com/questions/12082475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawer is not opening in react-native I am using drawer navigation in material top navigation. This is my drawer navigation code import { createDrawerNavigator, createStackNavigator } from "react-navigation"; import { UserProfileComponent } from "../components/standalone/userProfile/userProfile.component"; import { RecordMeetingComponent } from "../components/standalone/recordMeeting/recordMeeting.component"; import { ChatBotComponent } from "../components/standalone/chatBot/chatBot.component"; import DrawerScreen from "../components/shared/drawerToggler/drawerToggle.component"; import userDashBoardTabsStack from "./userDashBoardTabs"; const userDrawerNavigator = createDrawerNavigator({ Home:{ screen: userDashBoardTabsStack, navigationOptions:{ drawerLabel: "Home" } }, Record: { screen: RecordMeetingComponent, navigationOptions:{ drawerLabel: "Record" } }, Profile: { screen: UserProfileComponent, navigationOptions: { drawerLabel: "My Profile" } }, ChatBot: { screen: ChatBotComponent, navigationOptions: { drawerLabel: "Chat Bot" } }, },{ initialRouteName: "Record", contentComponent: DrawerScreen, drawerWidth: 300 } ) export default userDrawerNavigator; This is my tab navigation import { createMaterialTopTabNavigator } from "react-navigation"; import { UserDashboardTodayTab } from "../components/standalone/usersTabs/today/today.component"; import { UserDashboardWeekTab } from "../components/standalone/usersTabs/week/week.component"; import { UserDashboardMonthTab } from "../components/standalone/usersTabs/month/month.component"; const userDashBoardTabsStack = createMaterialTopTabNavigator({ today:{ screen: UserDashboardTodayTab, navigationOptions: (navigation)=>({ title: "TODAY" }), }, week: { screen: UserDashboardWeekTab, navigationOptions: (navigation)=>({ title: "WEEK" }), }, month:{ screen: UserDashboardMonthTab, navigationOptions: (navigation)=>({ title: "MONTH", headerTitle: "#000000" }) } },{ order: ["today", "week", "month"], tabBarOptions : { activeTintColor: "#000000", inactiveTintColor: "#ADB2BF", pressColor: "#25B7AF", indicatorStyle: { backgroundColor: "#25B7AF", }, activeBackgroundColor: "#25B7AF", style: { fontFamily: "nunito_regular", backgroundColor: "#ffffff" } }, swipeEnabled: true, animationEnabled: true, lazy: true, backBehavior: "initialRoute" }) export default userDashBoardTabsStack; I am calling these two in a createStacknavigator import { createStackNavigator } from "react-navigation"; import userDrawerNavigator from "./userDrawer"; import React from "react"; import { TouchableOpacity } from "react-native"; import Icon from "react-native-vector-icons/Feather"; const OnboardingStack = createStackNavigator({ userDrawerNavigator: { screen: userDrawerNavigator }, },{ navigationOptions: ({ navigation }) => ({ title: 'ReactNavigation', // Title to appear in status bar headerLeft: <TouchableOpacity onPress={ () => { navigation.dispatch(DrawerActions.toggleDrawer())} }> <MenuImage navigation={ navigation }/> </TouchableOpacity>, headerStyle: { backgroundColor: '#333', }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold', }, }) }, { initialRouteName: "userDrawerNavigator", headerLayoutPreset: "center", } ) const MenuImage = ({navigation}) => { if(!navigation.state.isDrawerOpen){ return <Icon name="menu" color="#000000"/> }else{ return <Icon name="arrow-left" color="#000000"/> } } export default OnboardingStack; And iterating these components in a switch navigator import { createSwitchNavigator, createAppContainer } from "react-navigation"; import { SplashComponent } from "../components/standalone/splash/splash.component"; import AuthStack from "./loggedOut"; import UserStack from "./loggedIn"; import OnboardingStack from "./freshInstall"; export const AppStack = createAppContainer(createSwitchNavigator( { Splash: SplashComponent, LoggedIn: UserStack, LoggedOut: AuthStack, Onboarding: OnboardingStack }, { initialRouteName: "Splash" } )) This is my custom component for drawer class DrawerScreen extends React.Component { navigateToScreen = (route) => () => { const navigateAction = NavigationActions.navigate({ routeName: route }); this.props.navigation.dispatch(navigateAction); this.props.navigation.dispatch(DrawerActions.closeDrawer()) } render () { return ( <View> <ScrollView> <View> <View > <Text onPress={this.navigateToScreen('RecordMeetingComponent')}> Record </Text> </View> <View> <Text onPress={this.navigateToScreen('UserProfileComponent')}> My Profile </Text> </View> <View > <Text onPress={this.navigateToScreen('ChatBotComponent')}> Chat Bot </Text> </View> </View> </ScrollView> </View> ); } } DrawerScreen.propTypes = { navigation: PropTypes.object }; export default DrawerScreen; But the drawer navigation is not appearing in the screen. What am I doing wrong here?
{ "language": "en", "url": "https://stackoverflow.com/questions/56770617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Launch PowerShell as administrator in current directory New to PowerShell. I need to launch PowerShell as Administrator in the current directory. From what I have heard about the amazing abilities of PowerShell, I expect I should be able to do this without a registry hack?
{ "language": "en", "url": "https://stackoverflow.com/questions/69649599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Glide for Android: How to include GIFs from Google Drive? I am trying to include GIFs in my android application. My GIFs are shared as a document on Google Drive with public access enabled. Currently, I'm trying to use Glide to include the GIFs. Glide.with(parent.getContext()) .asGif() .load("https://drive.google.com/uc?id=1-QKgZ76K3EZQlbXyY3wI57FA8k31JmrA") .into(imageView); However, although there is no error, the GIF does not display on my phone, even after a long time(internet issues shouldn't be the problem). It appears that this is only a problem for GIFs on google drive. Trying to show an internet GIF such as this one works on my Android phone. How can I show GIF files on Google Drive with Glide on my Android device? A: It should work. Because Glide trying to fetch image which type you specified. I just tried it and its work. it loads too late. If you wait a bit, you will see that it can be loaded. You can test it more easily if you upload a lower resolution gif file to Drive.
{ "language": "en", "url": "https://stackoverflow.com/questions/72863884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hadoop Name node recovery in CDH3 cluster I am using CDH3 Cloudera Pseudo distributed mode cluster.It was working fine before. but currently i am not able to do any hadoop commands,hive queries,pig scripts. Looks like the namenode gets corrupted. I tried sudo jps and found that namenode daemon is not running. It only shows DataNode Jps RunJar HMaster SecondaryNamenode What is the root cause here? How do i recover my name node?
{ "language": "en", "url": "https://stackoverflow.com/questions/24423916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recover simulated affine transformation for matched asift features (Morel's implementation) Has anyone tried to recover the simulated affine transformation for the ASIFT feature detector? (From the author's implementation). In the original paper the simulated affine is clearly recovered by the equation 2.2 but I cannot seem to find a clear point where this is performed. Has anyone tried before? The function compensate_affine_coor1 in compute_asift_keypoints.cpp seems to be what I'm looking for but the scale seems to be normalized plus, the center of coordinates to perform the transformation is not clear to me. A: It is performed in function you mentioned. Center coordinates are shifted because when you rotate image, top-left corner(origin) is moved, so they have to compensate it. And scale doesn`t change at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/13800578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to endian swap many structures in C++ I have a lot of C++ struct that look kind of like this: typedef struct { UINT32 foo : 5; UINT32 spare0 : 27; double bar; } data; or this typedef struct { double foo; double bar; } data2; I'm currently endian swapping all structures by each field individually in a single function call, but I was wondering if there was some more efficient way of doing this without manually swapping each individual field for each struct. Would the only way to do this is to create a function that requires the size for each field so the function would know how many bits to swap? Other methods are welcome as well. Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/42476816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql: Counting occurences in a table, return as a single row I have a table listing some organizations, and some details, as the country they are in. I need to count the number of organizations in each country, and I managed that with this query: SELECT COUNTRY, COUNT(*) AS ORGANIZATIONS FROM ORGANIZATION GROUP BY COUNTRY This gives me a result set like this: COUNTRY | ORGANIZATION --------+------------- UK | 12 FR | 7 NL | 9 This is good, but a better result I'm looking for is a single row result, like this: UK | FR | NL ---+----+--- 12 | 7 | 9 Any ideas on how to do that in MySQL alone? A: This can't really be done with a single SQL statement as it would require an unknown number of columns. I would be inclined to say that this is just formatting of the returned data, and hence probably better places in the calling script. However it is easy to do if you have a fixed number of countries that you are interested in. But with several sub queries it is not likely to be that efficient. What can be done is to dynamically build up the SQL, but that is messy. Alternative would to GROUP_CONCAT the countries details into a single row:- SELECT GROUP_CONCAT(CONCAT_WS('##', COUNTRY, ORGANIZATIONS )) FROM ( SELECT COUNTRY, COUNT(*) AS ORGANIZATIONS FROM ORGANIZATION GROUP BY COUNTRY ) sub0
{ "language": "en", "url": "https://stackoverflow.com/questions/24927773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Deleting file from internal storage in Android I was saving file to internal storage now I want to delete it. The problem is, I don't remember the name of that file so I can't use this myContext.deleteFile(fileName); approach. How to get the name of that file and delete it? A: When you use file methods from Context, Android saves that file into app's directory (and encrypt it, compared to File.()) method). So, you can just clear app data and that file will be removed
{ "language": "en", "url": "https://stackoverflow.com/questions/40786560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python 3 not rendering html on browser If I run this script on terminal, it outputs the html template. But on browser after serving it using python3 -m http.server 8000, it just display the exact script (not rendering). I've installed packages on requirements.txt and interpreter set to Python 3.x, am I missing something here? home.py #!/usr/bin/env python3 import os import sys from jinja2 import Environment, FileSystemLoader # Get current url try: url = os.environ['SCRIPT_NAME'] except KeyError: url = '' print('Content-type: text/html\n') env = Environment(loader=FileSystemLoader('templates')) template = env.get_template('home.html') print(template.render(url=url)) A: Your script could work as a CGI script, since it outputs a HTTP header, followed by the HTML content. python -m http.server, by default, does not run CGI scripts for security, but if you add the --cgi switch, it will, provided that the scripts are in the cgi-bin directory relative to the directory you start it from. In other words: * *create a cgi-bin directory *move home.py to cgi-bin/home.py *run python3 -m http.server --cgi 8000 *navigate to http://127.0.0.1:8000/cgi-bin/home.py When working with CGI scripts, you might want to enable the (soon-to-be-deprecated) cgitb handler too. Anything more intricate than that, and I would recommend looking at the Flask application framework instead, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/72985401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Register to GCM in background what I'm trying to do is run some scripts let say "in background" and display external page. I have my activity public class MyApp extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl(Config.getStartUrl()); //super.loadUrl("http://external.com/"); } } I'm able now only to load my internal page where scripts are included or load external url. What I want to do is public class MyApp extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // run my gcm script to register super.loadUrl("http://external.com/"); //load prepared page } } but I don't know if script should/can be run from java code. Or maybe this is wrong solution and I should load my external page from js? I'm using cordova 2.5 A: If you planning to support IOS (APNS) and Android (GCM), you can use PushPlugin https://github.com/bobeast/PushPlugin It is easy to setup, where you can register for GCM using javascript and having the same interface for Android and IOS.
{ "language": "en", "url": "https://stackoverflow.com/questions/15794825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot import python package installed with apt-get On ubuntu (specifically the python:3.7.3-stretch base dockerimage), I run: $ pip install pandas $ python -c 'import pandas' $ And that works fine. Then, I try to install the package pygrib (which isn't installable with pip), via apt-get, python3-grib. I try: $ apt-get update $ apt-get install python3-grib $ python -c 'import pygrib' Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'pygrib' (Omitting the output of the installs for brevity). Why can't I import pygrib? I am not inside a virtual environment. A: The first thing I would try, would be to double check that the python you're calling is the same that you've installed pygrib into * *$ which python *$ python -c "help("modules")" *$ python -c "help("modules pygrip")" (to inspect which python you're calling, and which packages are installed there). If that's not working, then there's something off with the ubuntu package - so I'd then try installing from source instead; From https://github.com/jswhit/pygrib Clone the github repository, or download a source release from https://pypi.python.org/pypi/pygrib. Copy setup.cfg.template to setup.cfg, open in text editor, follow instructions in comments for editing. If you are using the old grib_api library instead of the new eccodes library, be sure to uncomment the last line setup.cfg. Run 'python setup.py build' Run 'python setup.py install' (with sudo if necessary) Run 'python test.py' to test your pygrib installation.
{ "language": "en", "url": "https://stackoverflow.com/questions/59097045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete contents of textbox and automatically deleting another I have 2 input box fields, one linked to an autocomplete and the other is hidden I have an action on select that takes the id of the selected item into the hidden field. code: $('#id_emp_name').autocomplete({ source: '/mycompany/employees.json', minLength: 1, dataType: 'json', max: 12, select: function(event, ui) { $('#id_emp_id').val(ui.item.id); } }); I want to change it so that whenever I delete contents (even a single character) on the autcomplete textbox it would set the hidden textbox's to '' A: Would this work for you? $('#id_emp_name').autocomplete({ source: '/mycompany/employees.json', minLength: 1, dataType: 'json', max: 12, select: function(event, ui) { $('#id_emp_id').val(ui.item.id); } }).keyup(function(){ $('#id_emp_id').val(''); }); You may need to put some conditions on it of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to load configurations at Vue JS app start I want to load some configuration from an API call before any page load happens. For this I added my api call function in main.js but it returns promise and page get loaded before my global api completes. I want to load the global configuration first as my backend services URLs will keep on changing. my main.js import globalConfigLogic from '../appStarter/globalConfig-logic'; import globalConfigDetails from '../appStarter/app-starter.js'; // API Wrapper - Global Mixin Vue.mixin(apiWrapper) Vue.use(VeeValidate); Vue.config.productionTip = false; globalConfigLogic.getGlobalConfiguration( globalConfigDetails.globalConfigHost, globalConfigDetails.globalConfigHostPort, globalConfigDetails.globalConfigKeys ); new Vue({ router, store, render: h => h(App) }).$mount('#app') The functions is just making an API call and converting the result in hashmap and giving it back. A: If loading your configuration returns a promise, simply put the creation of the Vue instance in the .then() {} code.
{ "language": "en", "url": "https://stackoverflow.com/questions/51882640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I set up gulp to run identically in Visual Studio 2017 and msbuild without having to change my build scripts? I'm struggling to get set up with gulp in Visual Studio 2017. I'm not sure where I'm going wrong but there are a few things I'm confused about and I can't really find any online resources that are of any use. The build system I'm using is CruiseControl.NET and I would like gulp to work with it. This is what I've done so far: * *Installed Visual Studio 2017 with .NET Core cross-platform development and Node.js development selected (amongst other options). *Created a new project *Added a gulpfile.js file to the project *Right-click on the file and choose Task Runner Explorer In the Task Runner Explorer I get the error Failed to load. See output window (Ctl+Alt+O) for more information.. Then if I do the following: * *Open the Node.js Interactive Window *Run the command .npm install --global gulp-cli *Close Visual Studio and open it back up again In the Task Runner Explorer, I then get the message (No tasks found). First off, is this the correct way to set up Gulp in Visual Studio 2017? The reason I'm asking this is because I'm not sure why I need to prefix commands with a period character (ie .npm as opposed to npm). I'm also not sure where gulp was installed because I can't find it in the path C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Web\External\node_modules. Because of this I can't really set up CruiseControl.NET. A: The way I'm handling this is to first use the Web Essentials 2017 extension. This installs the Bundler & Minifier tool, which then adds a bundleconfig.json file to your project. Right-click on this file, go to the Bundler & Minifier menu item and you will see an option in there to Convert To Gulp. Selecting convert to gulp will create the necessary gulpfile.js and also install the npm packages required for using Gulp. Wait for all of the npm packages to install and you can then right click on gulpfile.js, select Task Runner Explorer and you should be ready to set up Gulp-based tasks. If you see gulpfile.js failed to load message, npm packages may still be installing (check the progress bar on the VS 2017 status bar). Hit the Refresh icon in Task Runner Explorer when all packages are installed and the error should vanish. There's probably a more manual way to add Gulp support but I find this more automated method ensures all the tooling is wired up to work properly and I don't miss anything. I gleaned all this information from the awesome Microsoft Docs site, specifically this page on Bundling & Minification. There's also a Using Gulp section in there that may provide additional details for your situation. https://learn.microsoft.com/en-us/aspnet/core/client-side/bundling-and-minification A: Microsoft have now added documentation on how to get gulp running: https://learn.microsoft.com/en-us/aspnet/core/client-side/using-gulp Make sure you update Visual Studio 2017 to the latest version as it now comes shipped with Node.js, NPM and Gulp (you don't need to pick "Node.js support" when installing Visual Studio for this to work). Create an npm Configuration File (package.json) in your project folder and edit it to reference gulp: { "version": "1.0.0", "name": "example", "private": true, "devDependencies": { "gulp": "3.9.1" }, "scripts": { "gulp": "gulp" } } In the project folder, create a Gulp Configuration File (gulpfile.js) to define the automated process. Add the following to the post-build event command line for each project requiring gulp support: cd $(ProjectDir) call dotnet restore npm run gulp To run the tasks in Visual Studio 2017, open the Task Runner Explorer (View > Other Windows > Task Runner Explorer). Then on the build server just install Node.js and ensure the path to node is added to the environmental path variable then when the build server builds the project gulp will run too! A: I found the solution here. More information on that part of VS from Mads himself. You have to force Visual Studio run with your Node.js version: Go to Tools > Options in Visual Studio 2017 Go to Projects and Solutions > External Web Tools Add the following path: C:\Program Files\nodejs
{ "language": "en", "url": "https://stackoverflow.com/questions/43188670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Clean up Array of words I have a function that strips html and places the words in an array and then uses array_count_values. Im trying to report the number of occurences of each word. The array outputed is very messy. I tried to clean it up, and I'm getting nowhere. I want to remove telephone numbers, and for some reason phrases are pushed together. Also the first array seems to be null, but isset() or empty() doesn't seem to unset it. $body = $this->get_response($domain); $body = preg_replace('/<body(.*?)>/i', '<body>', $body); $body = preg_replace('#</body>#i', '</body>', $body); $openTag = '<body>'; $start = strpos($body, $openTag); $start += strlen($openTag); $closeTag = '</body>'; $end = strpos($body, $closeTag); // Return if cannot cut-out the body if ($end <= $start || $start === false || $end === false) { $this->setValue(''); return; } $body = substr($body, $start, $end - $start); $body = preg_replace(array( '@<script[^>]*?>.*?</script>@si', // Strip out javascript '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly '@<![\s\S]*?--[ \t\n\r]*>@', // Strip multi-line comments including CDATA '/style=([\"\']??)([^\">]*?)\\1/siU',// Strip inline style attribute ), '', $body); $body = strip_tags($body); $body = array_filter(explode(' ', $body), create_function('$str', 'return strlen($str) > 2;')); $body = array_map('trim', $body); $words = $body; $i = 0; $words = array_count_values($words); foreach($words as $word){ if (empty($word)) unset($words[$i]); $i++; } echo "<pre>"; print_r($words); echo "</pre>"; outputs Array ( [] => 28 [333.444.5555] => 1 [facebook] => 2 [twitter] => 2 [linkedin] => 2 [youtube googleplus] => 1 [About History Our] => 1 [Mission Who] => 1 [This That Other] => 1 [Us English FA Football] => 1 [Media Pay] => 2 [Per] => 4 [Think Fast] => 2 [Marketing Design] => 1 [Consulting Case] => 2 A: I'm afraid explode(' ', $body) is not enough because space is not the only white space character. Try preg_split instead. $body = array_filter(preg_split('/\s+/', $body), create_function('$str', 'return strlen($str) > 2;'));
{ "language": "en", "url": "https://stackoverflow.com/questions/12516137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any form designer available for Google Android I am a new comer in Android development, I have downloaded and installed the Android SDK, but not find any GUI or Form designer, can any one know about some Form designer in for Android, Thanks in advance. A: As d. correctly mentioned the built-in designer does not truly represent your view. And if we keep in mind that even after 4 years of trying, Microsoft's equivalent for their XAML code still doesn't reach minimum usefulness level, I would strongly recommend to go manual. It's faster, much more difficult but equally rewarding. Once you get a hang of editing the XML files manually the development becomes much easier and WAY faster in my humble opinion. Regards A: This answer is very late to the game but each new release of the Eclipse Android plugin improves the layout GUI editor. The one released yesterday (9.0.0) is light years ahead of the original tools which were awful. A: The form designer is part of the Android Development Tools (ADT) Plugin for Eclipse which comes with the Android SDK. A: Google has not announced any plans for a wysiwyg designer for Android app development. However, there is a tool available for this. Check out this link http://www.designerandroid.com/?p=165
{ "language": "en", "url": "https://stackoverflow.com/questions/1755860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Python Calling Current Directrory I am using fasitai library and when ı tried the loading model ı want to take model from current directory. learn = load_learner('This arg. have to my current directory','model.pkl') I tried os.get_cwd() and ' ./ ' but they aren't worked. Thanks A: I found the solution learn = load_learner('','model.pkl') the first arg. had to be space '' .
{ "language": "en", "url": "https://stackoverflow.com/questions/56036119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: RoR NameError - Ruby on Rails MySQL NameError in GenresController#index uninitialized constant GenresController RAILS_ROOT: C:/Users/Will/Desktop/INSTAN~1/rails_apps/talewiki I've created a table called Genres and when I try to connect to it via local host I get the above error. Any ideas? A: With all the questions you're asking I believe you're an absolute beginner regarding ROR. Perhaps you should visit some tutorials to learn rails. I don't know what your genre model describes, but I think it will have a name. Basic steps for a basic genre model: * *Delete the table for your genres if created manually (with SQL code) DROP TABLE genres; *generate a complete scaffolding for genres: $ ruby script/generate genre name:string $ rake db:migrate *Now you have a complete controller for all CRUD actions for a simple genre model If I were you I would read some tutorial about RoR, because you make the impression that you don't understand RoR or the MVC principle behind it. A good start would be: http://storecrowd.com/blog/top-50-ruby-on-rails-tutorials/ A: You need to generate a controller to handle the index action when your browse your application on localhost ruby script/generate controller genres index run that from your console within your application and it will generate the GenresController with the action index (it will be an empty action but you shouldn't see an error when browsing http://localhost:3000/genres/) A: file C:/Users/Will/Desktop/INSTAN~1/rails_apps/talewiki/app/controllers/genres_controller.rb must be present
{ "language": "en", "url": "https://stackoverflow.com/questions/2913290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to intercept exe files launch from windows explorer? i want to be notified when when user trys to open a file from the explorer. How could this be done? I tired hooking some winapi in the explorer.exe with no hope. I also want to intercept this call and cancel it. A: You might want to have a look at a similar question: Intercept windows open file Also for the people asking why someone would want to do this or immediately jump to malware conclusions. There are a number of legitimate uses for this. Especially if you are creating a B2B product that deals with automation or control over a customer's PC environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/35542332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: React Typescript ESLint "extends" parsing error I have a react typescript code that looks like the following in Button.tsx: import * as React from 'react'; type ButtonOwnProps<E extends React.ElementType = React.ElementType> = { children?: React.ReactNode; variant?: 'contained' | 'outlined'; as?: E; }; I am getting the following eslint error: Parsing error: Unexpected token, expected "," 1 | import * as React from 'react'; 2 | > 3 | type ButtonOwnProps<E extends React.ElementType = React.ElementType> = { | ^ 4 | children?: React.ReactNode; eslint Can anyone help me understand where I did wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/68231145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to filter a RecyclerView using Kotlin? I just started to use kotlin and room database, in my fragment i have a RecyclerView and an EditText which i would use as search for the RecyclerView. The RecyclerView's adapter is inside my ViewModel observable and i've actually set a TextWatcher to my EditText but as the data of the RecyclerView comes from my room DataBase how should i set that filtering? When the EditText is empty i should return items from the LiveData observable.. Here is my Fragment code: private lateinit var recyclerView: RecyclerView private lateinit var txtSearch: EditText private val articoliViewModel: ArticoliViewModel get() = (activity as MainActivity).articoliViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView = view.findViewById(R.id.recyclerView) txtSearch = view.findViewById(R.id.txtSearch) val adapter = ArticoliListAdapter() recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(activity) articoliViewModel.articoli.observe(viewLifecycleOwner) { articoli -> // Update the cached copy of the words in the adapter. articoli.let { adapter.submitList(it) } } txtSearch.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) }
{ "language": "en", "url": "https://stackoverflow.com/questions/65805427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Injecting javascript into page via url I'm trying to run a javascript code via url to change values of the form in the page. Here is the content of the HTML page. <html> <body> <form method='post'> Name: <input type='text' id='name' value='' /><br /> Family: <input type='text' id='family' value='' /><br /> Email: <input type='text' id='email' value='' /><br /> <input type='submit' value='Submit' /><br /> </form> </body> </html> Now, I enter the following value in the URL section of chrome: javascript:document.getElementById('name').value = 'string1'; What happens is my whole page will go blank and only the value "string1" will be displayed in the page. However, running the following code works properly: javascript:document.getElementById('name').value = 1; It will change the value of the name field to 1. I'm wondering what is causing this problem. Note: The purpose of this work is to inject code into webview in android. Any advice is appreciated. A: Try this. javascript:document.getElementById('name').value = 'string1'; undefined; Tack on a 'undefined;' to any script that returns a string. A: That is because you are using single quotes after the attribute value value='' and you changing it's value in javascript using document.getElementById('name').value='string1'; so the html becomes <input type='text' id='name' value=''string1'' you can fix it using value="" or using document.getElementById('name').value="string1"; A: well i tried the following code <html> <body> <form method='post'> Name: <input type='text' id='name' value='' /><br /> Family: <input type='text' id='family' value='' /><br /> Email: <input type='text' id='email' value='' /><br /> <input type='submit' value='Submit' /><br /> </form> <button onclick="change()">Click me</button> <script> function change(){ var obj=document.getElementById('name'); obj.value="string1"; } </script> </body> </html> and it works just fine the problem is in your script do you created a function to change the value or just putted the code in a script tag like this <script>document.getElementById('name').value="String1";<script>
{ "language": "en", "url": "https://stackoverflow.com/questions/39674244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the advantage of dynamic memory control? For example, I want to make a stack. I can do it in that way, using the dynymic memory control, with new and delete opereations: #include <iostream> using namespace std; struct List { int x; List *Next,*Head; }; void Add(int x, List *&MyList) { List *temp=new List; temp->x=x; temp->Next=MyList->Head; MyList->Head=temp; } void Show(List *MyList) { List *temp=MyList->Head; while (temp!=NULL) { cout<<temp->x<<" "; temp=temp->Next; } } void ClearList(List *MyList) { while (MyList->Head!=NULL) { List *temp=MyList->Head->Next; delete MyList->Head; MyList->Head=temp; } } int main() { List *MyList=new List; MyList->Head=NULL; for (int i=0;i<10;i++) Add(i,MyList); Show(MyList); ClearList(MyList); delete MyList->Head; delete MyList; } And also I can just make a stack in that way and do anything with it: std::stack<int> MyStack; So, which one is better? What is the advantage of a stack with dynamic memory allocation? In what cases should I use first/second variants? A: The both stacks use dynamically allocated memory for their nodes (though for std::stack it depends on underlying container). Of course it is better to use standard class. It was already tested and written by qualified programmers and it is flexible enough: you can use several standard containers to implement the stack because standard stack is a container adapter. In fact you can write your own underlying container for std::stack as for example a wrapper around an array and in this case the whole stack will be placed in the stack memory though its size of course will be fixed.:) Nevertheless the standard stack also has many drawbacks. For example you can not use std::forward_list as the underlying container. I made a proposal to specialize standard class std::stack for std::forward_list. A: which one is better depends surely on the use case. But generally I would advise you to use the STL implementation of the stack, because it is heavily used and therefore tested perfectly. Furthermore, you'll get a perfect abstraction of a stack with the STL implementation. Second, the STL implementation is also using dynamic memory allocation, so from this point of view there is no difference to your implementation. A: Using dynamic memory gives the advantage of adding possible memory leaks and/or segmentation faults to your program. I only use dynamic memory when forced to. Forcing example: working with a library that uses c-strings for parameters and return values.
{ "language": "en", "url": "https://stackoverflow.com/questions/28915865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot open new project or old project in Visual Studio 2012 Recently I have installed VS 2012 and SQL Server Management Studio. When I try to open the New Project, I'm getting this error: Web application projects are currently configured to use IIS Express. To switch back to using the Visual Studio Development server, change the development server option under the Projects and Solutions/Web Projects category of the Tools/Options menu. Configuring IIS Express failed with the following error: Filename: redirection.config Error: Cannot read configuration file I was Search about that issue. But the given solution doesn't fix my problem. I have tried * *Control Panel -> Programs and Features -> Turn Windows Features on or off... inside that, we had to select Internet Information Services -> Web Management Tools -> IIS 6 Management Compatibility -> IIS Metabse and IIS 6 configuration compatibility." *true replace it with the string True. Could someone please help?
{ "language": "en", "url": "https://stackoverflow.com/questions/46326697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use for loop to calculate moving average with a window size of 10 using 5th column I have a data.csv file containing 5 columns. now I want to use for loop to calculate moving average with a window size of 10 using 5th column in R. for(i in 1: length[ , 5]-9) { data$Mean [i] <- mean (data[i,5]:data[(i+9),5]) } This means to calculate the mean of 10 consecutive rows and store them in the same data frame by creating a new column It is calculating wrong and I am getting the error as follows..... Error in data[i, 5]:data[(i + 9), 5] : NA/NaN argument A: You have made a couple of mistakes in the line that calculates the mean. The most significant one is that when you try to calculate the mean for the last 9 rows of your dataframe, you go out of bounds. ie, if your dataframe has 100 rows, by row 92 your are trying to get the mean of rows 92:101; of course, there is no row 101. It should be something like this: for(i in 1: length(data[ , 5]-9)) { data$Mean [i] <- mean(data[i:min(i+9, nrow(data)),5]) } Also, it's generally a bad idea to use data as a variable name, since there already is a data() function in base R. Simply choose a similar name, like "mydata" A reproducible example follows, that will get the mean of the next ten rows, OR the mean of the n next rows for the last 9 rows. mydata <- data.frame(col_1 = rnorm(100), col_2 = rnorm(100), col_3 = rnorm(100), col_4 = rnorm(100), col_5 = rnorm(100)) for(i in 1: length(mydata[ , 5]-9)) { mydata$Mean [i] <- mean(mydata[i:min(i+9, nrow(mydata)),5]) } head(mydata) If you dont' want to get the mean for the last ten rows, do this instead: for(i in 1: length(mydata[ , 5]-9)) { mydata$Mean [i] <- ifelse( i + 9 <= nrow(mydata), mean(mydata[i:min(i+9, nrow(mydata)),5]), NA) }
{ "language": "en", "url": "https://stackoverflow.com/questions/48368865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bluetooth Low Energy Android - Search in Background I would like to know whether it is possible to check in the background if someone enters or leaves the a beacon Region? In iOS for example you can use the methods didEnterRegion or didExitRegion to send notifications from the background. Is there any native possibility or has someone a workaround? A: Android doesn't have any "native" iBeacon capability at all, but you can see iBeacons using my company's open source Android iBeacon Library, which has APIs similar to those native to iOS 7. In the case of iOS, the CLLocationManagerDelegate gives you access to the didEnterRegion and didExitRegion callbacks that you describe. In the Android iBeacon Library, the equivalent is the MonitorNotifier interface that gives you the same callback methods. Making these callbacks successfully fire for apps that aren't in the foreground is a little tricky on both iOS and Android. On Android, you need to start a service of your own that runs when the Android device starts up, and bind to the IBeaconManager in that service. Setting this up isn't super easy, so we developed a Pro Android iBeacon Library that does all this automatically. Examples are here. EDIT: Both libraries above have been discontinued in favor of the free and open source Android Beacon Library which has all the feature of the pro library described above.
{ "language": "en", "url": "https://stackoverflow.com/questions/19638118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Data Clensing in SQL Server I've got a table in the following format: Name Address1 Address2 Address3 Joe NULL 1 A Road London Bob 2 A Lane NULL London I'd like to run an update to move all the values left where there are nulls so that I end up with: Name Address1 Address2 Address3 Joe 1 A Road London NULL Bob 2 A Lane London NULL Please help! Thanks, Josh A: BEGIN TRANSACTION update person set Address1 = Address2, Address2 = null where Address1 is null and Address2 is not null; update person set Address2 = Address3, Address3 = null where Address2 is null and Address3 is not null; update person set Address1 = Address2, Address2 = null where Address1 is null and Address2 is not null; select top 100 * from person ROLLBACK TRANSACTION This would get very ugly if you had lots of address fields, but for 3 is acceptable. Remember to test any script copy and pasted from the interwebs in a transaction that you rollback so you don't get your database wiped :) EDIT: With further info (6 address fields): You could do like above only repeat 5 times to move so in worst case you where still done Declare StoredProcedure OneRound BEGIN update person set Address1 = Address2, Address2 = null where Address1 is null and Address2 is not null; update person set Address2 = Address3, Address3 = null where Address2 is null and Address3 is not null; update person set Address3 = Address4, Address4 = null where Address3 is null and Address4 is not null; update person set Address4 = Address5, Address5 = null where Address4 is null and Address5 is not null; update person set Address5 = Address6, Address6 = null where Address5 is null and Address6 is not null; END Declare StoredProc FixAllAddresses BEGIN call OneRound call OneRound call OneRound call OneRound call OneRound END You could also use a cusor (warning psydo code) I have not looked up the syntax for T-SQL cursors and it has been a while so I will get the details wrong, check the syntax in the online help. Declare cursor @personCursor for select ID,Address1,Address2,... from person; OPEN @personCursor FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...) while(@@FETCH_STATUS) BEGIN IF @addr1 is null BEGIN IF @addr2 is not null BEGIN @addr1 = @addr2 @addr2 = null END ELSE IF @addr3 is not null @addr1 = @addr3 @addr3 = null BEGIN -- Boaring, ugly code goes here for addr4,addr5,addr6 END END IF @addr2 is null IF @addr3 is not null BEGIN @addr2 = @addr3 @addr3 = null END ELSE IF @addr4 is not null @addr2 = @addr4 @addr4 = null BEGIN -- Boaring, ugly code goes here for addr5, addr6 END BEGIN -- repeat for addr3, addr4, if @addr5 is null BEGIN IF addr6 is not null BEGIN @addr5 = @addr6 @addr6 = null END END END update person set address1 = @addr1, address2 = @addr2, ... where PersonId = @personId FETCH @personCursor into (@personID, @addr1, @addr2, @addr3...) END The Stored proc begin called 5 times makes for less code and may be less error prone, the cursor only iterates through your people once, but does not filter. I suspect the stored proc solution below will be faster but it will depend on your data. A: David's solution is the most efficient. One that might be more easily extend-able for greater numbers of columns is. ;WITH cte AS (SELECT *, MAX(CASE WHEN RN=1 THEN value END) OVER (PARTITION BY ContactId) AS new_Address1, MAX(CASE WHEN RN=2 THEN value END) OVER (PARTITION BY ContactId) AS new_Address2, MAX(CASE WHEN RN=3 THEN value END) OVER (PARTITION BY ContactId) AS new_Address3 FROM #Addresses OUTER APPLY (SELECT ROW_NUMBER() OVER (ORDER BY CASE WHEN value IS NULL THEN 1 ELSE 0 END, idx) AS RN, idx, value FROM (VALUES(1,Address1), (2,Address2), (3,Address3)) t (idx, value)) d) UPDATE cte SET Address1 = new_Address1, Address2 = new_Address2, Address3 = new_Address3
{ "language": "en", "url": "https://stackoverflow.com/questions/5565458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to filter out different classes into an array How will I take product with same category into a string or an array? <ul> <li class="product_cat-category-1"></li> <li class="product_cat-category-3"></li> <li class="product_cat-category-2"></li> <li class="product_cat-category-5"></li> <li class="product_cat-category-1"></li> <li class="product_cat-category-2"></li> <li class="product_cat-category-3"></li> <li class="product_cat-category-5"></li> <li class="product_cat-category-4"></li> <li class="product_cat-category-1"></li> <li class="product_cat-category-2"></li> <li class="product_cat-category-3"></li> <li class="product_cat-category-4"></li> </ul> What I want exactly is to filter them and append them into a new div to create a filterable animation using GSAP. This is actually a WordPress WooCommerce product page. Last time I created a popup using GSAP, and in that I used something called split() function: triggers.each(function(){ let listClassName = $(this).attr('class').split(' '); let revealClassName = String(listClassName[listClassName.indexOf(listClassName.find(element => element === 'dasrgsap__reveal-trigger')) + 1]); const sectionReveal = $('.dasrgsap__reveal-content.' + revealClassName); const colReveal = $('.dasrgsap__reveal-content.' + revealClassName + ' .et_pb_column'); }); The trigger was (dasrgsap__reveal-trigger sandra) and the popup content container was (dasrgsap__reveal-container sandra). Both were given two separate classes, which made it easier to split and access them. In this case, WooCommerce product list items are given too many classes, so the only class I can play with to get a specific category is the product_cat-'product-category'. I want to get a string or array of the same product category, and I want to split product_cat- and category-1 and get an array of that category, but I'm not able to do it. Is this even possible? A: This is only a guess but is this what you were after $("li").each(function() { var category = $.makeArray( $(this) .attr("class") .slice( $(this).attr("class").indexOf("-") + 1, $(this).attr("class").length ) ); // console.log(category); var product = $.makeArray($(this) .attr("class") .slice(0, $(this).attr("class").indexOf("-"))) // console.log(category); var completeList = $.merge(product, category); console.log(completeList) }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="product_cat-category-1"></li> <li class="product_cat-category-3"></li> <li class="product_cat-category-2"></li> <li class="product_cat-category-5"></li> <li class="product_cat-category-1"></li> <li class="product_cat-category-2"></li> <li class="product_cat-category-3"></li> <li class="product_cat-category-5"></li> <li class="product_cat-category-4"></li> <li class="product_cat-category-1"></li> <li class="product_cat-category-2"></li> <li class="product_cat-category-3"></li> <li class="product_cat-category-4"></li> </ul> https://jsfiddle.net/7xcpjr59/ I hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/72663844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: NLog structuring logging masking Suppose we are writing the following structured log message logger.Info("User's Password is {Password}", "1234567890"); I would like to mask a password property because it is a sensitive data. I found this issue but I think it is a very difficult way. For example, I have found the extension that resolves a similar task for serilog. It is very simple to use. But I didn't find any useful information for Nlog. How to achieve it with nlog library? I will appreciate any suggestions. A: You could use RegisterObjectTransformation, introduced in NLog 4.7. For example: LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation<object>(o => { var props = o.GetType().GetProperties(); var propsDict = props.ToDictionary(p => p.Name, p => p.GetValue(o)); propsDict.Remove("password"); return propsDict; })); Please note, in terms of performance you maybe need something like a reflection cache and smart optimizations. A: I suggest that you wrap the secret password in an object like this: public class SecretWrapper : IFormatable { private readonly string _secret; public SecretWrapper(string secret) { _secret = secret; } public string GetSecret() => _secret; // Not a property to avoid basic reflection public override string ToString() => "******" public string ToString (string format, IFormatProvider formatProvider) => ToString(); } NLog will never output the secret-value: logger.Info("User's Password is {Password}", new SecretWrapper("1234567890"));
{ "language": "en", "url": "https://stackoverflow.com/questions/61330333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wix installer creating registry entry based on user input So, basically what I have is Wix installer, which is modified and I am currently stuck at a problem with registry entry. During install the Installer has a custom dialogue, where user has to choose/insert second path. Which will be stored in the Registry. But instead of inserting what user entered, it inserts "[INSTALLFOLDER]", although it should look something like "C:\Program Files...". I did some research but, didn't find anything that could help me. All of the code are in the same file. Main parts of the code are here, first there's this property. Which later should be written into registry. <Property Id="CUSTOMPATH" Value="INSTALLFOLDER" Secure="yes" /> Later on there's the custom window. <!-- NetWork path --> <Dialog Id="CustomNETDirDlg" Width="370" Height="270" Title="Custom Folder"> <Control Id="Next" Type="PushButton" X="236" Y="243" Width="56" Height="17" Default="yes" Text="!(loc.WixUINext)" /> <Control Id="Back" Type="PushButton" X="180" Y="243" Width="56" Height="17" Text="!(loc.WixUIBack)" /> <Control Id="Cancel" Type="PushButton" X="304" Y="243" Width="56" Height="17" Cancel="yes" Text="!(loc.WixUICancel)"> <Publish Event="SpawnDialog" Value="CancelDlg">1</Publish> </Control> <Control Id="Description" Type="Text" X="25" Y="23" Width="280" Height="15" Transparent="yes" NoPrefix="yes" Text="Choose Network Path" /> <Control Id="Title" Type="Text" X="15" Y="6" Width="200" Height="15" Transparent="yes" NoPrefix="yes" Text="NetWork Path" /> <Control Id="BannerBitmap" Type="Bitmap" X="0" Y="0" Width="370" Height="44" TabSkip="no" Text="!(loc.InstallDirDlgBannerBitmap)" /> <Control Id="BannerLine" Type="Line" X="0" Y="44" Width="370" Height="0" /> <Control Id="BottomLine" Type="Line" X="0" Y="234" Width="370" Height="0" /> <Control Id="FolderLabel" Type="Text" X="20" Y="60" Width="290" Height="30" NoPrefix="yes" Text="Choose / Enter Path" /> <Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes"/> <Control Id="CustomChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" /> </Dialog> <!-- / NetWork path --> Little bit below that is this publish part... <Publish Dialog="CustomNETDirDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg">1</Publish> <Publish Dialog="CustomNETDirDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" Order="4">1</Publish> <Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Property="_BrowseProperty" Value="[CUSTOMPATH]" Order="1">1</Publish> <Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish> And this works for me. I replaced guid for "reasons". Registry path and everything else seems to be fine, just one thing which is not working,adding [CUSTOMPATH] property as registry value.I also tried without [] brackets, and so on... Even tried it with [Manufacturer], worked perfectly fine, inserted Manufacturer into registry. But this here is not working. <DirectoryRef Id="TARGETDIR"> <Component Id="RegistryEntries" Guid="{my guid}"> <RegistryValue Root='HKMU' Key='Software\[Manufacturer]\[ProductName]' Type='string' Value='[CUSTOMPATH]' KeyPath='yes' /> </Component> </DirectoryRef> A: Correct This is correct because you specify that the content of CUSTOMPATH is actually a reference a different Property (or Directory because a certain point Directory elements become available to be used like Property elements): <Property Id="CUSTOMPATH" Value="INSTALLFOLDER" Secure="yes" /> <Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes"/> The above will visualize the content of INSTALLFOLDER so that's ok. However, the actual value of CUSTOMPATH will never change. It should always remain a reference to another property because you use it with Indirect=Yes. Possible root cause of your problem In the next part you assign a value to CUSTOMPATH and that's where I think something goes wrong. I tried the following and it gave me the requested result ("C:\Program Files..." in the registry value). <Publish Dialog="CustomNETDirDlg" Control="CustomChangeFolder" Property="_BrowseProperty" Value="[INSTALLFOLDER]" Order="1">1</Publish> <RegistryValue Root='HKLM' Key='Software\Test\TestRegEntry1' Type='string' Value='[INSTALLFOLDER]' KeyPath='yes'/> If this doesn't work, could you provide me with the logfile? zzz.msi /lvoicewarmupx debug.log A: So basically what I did to fix this issue was that I created right beside INSTALLFOLDER another directory. Since I didn't add any files into it, that folder will not be created, but value as such remains. <Directory Id="INSTALLFOLDER2" Name="!(bind.property.ProductName)"></Directory> <Directory Id="INSTALLFOLDER" Name="!(bind.property.ProductName)"> <!-- Here are files I wanted to include --> </Directory> Registry entry now looks like this: <DirectoryRef Id="TARGETDIR"> <Component Id="RegistryEntries" Guid="here comes your guid"> <RegistryValue Root='HKMU' Key='Software\[Manufacturer]\[ProductName]' Type='string' Value="[INSTALLFOLDER2]" KeyPath='yes' /> </Component> </DirectoryRef> And Property like this: <Property Id="CUSTOMPATH" Value="INSTALLFOLDER2" Secure="yes" /> Folder selector controls look like this, so both typing and button (folder selector) work. Dialog that uses them is exactly like InstallDirDlg, but with a different name. <Control Id="NETFOLDER" Type="Edit" X="20" Y="100" Width="320" Height="18" Text="{200}" Property="CUSTOMPATH" Indirect="yes" /> <Control Id="CustomChangeFolder" Type="PushButton" X="20" Y="120" Width="56" Height="17" Text="!(loc.InstallDirDlgChange)" />
{ "language": "en", "url": "https://stackoverflow.com/questions/34291935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript - .length gives me 0 length Array is initialized var Collect = []; So I have a promise arguments so that I'll have a asynchronous in execution since retrieving data from firebase which then push in the array Collect takes a bit of time. Here's my code: function loadTables(){ var promise = getDataFirebase(); promise.then(function(){ console.log("firsst"); return ProcessOfData(); }).then(function(){ console.log(Collect); //when printed, it shows the elements collected from firebase so the array is not 0. console.log(Collect.length); // but when printeed here. it gives me 0. why? return EndProcessLog(); }).then(function(){ }); } Codes when retrieving data from firebase: function getDataFirebase(){ return new Promise (function(resolve,reject){ refReview.on("value", function(snap){ var data = snap.val(); for(var key in data){ //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT Collect.push({ "RevieweeName": data[key].revieweeID.firstname.concat(" ",data[key].revieweeID.lastname), "ReviewerName": data[key].reviewerID.firstname.concat(" ",data[key].reviewerID.lastname), rating:data[key].rating, content: data[key].content }) }//end of for loop }); //end of snap resolve(); }); } A: Why does it not work? Because you are resolving the promise before the asynchronous method runs. The reason why the object shows the value is the console lazy loading the object. What do you do? Move the resolve line after the for loop inside the callback. refReview.on("value", function(snap) { var data = snap.val(); for (var key in data) { //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT Collect.push({ "RevieweeName": data[key].revieweeID.firstname.concat(" ", data[key].revieweeID.lastname), "ReviewerName": data[key].reviewerID.firstname.concat(" ", data[key].reviewerID.lastname), rating: data[key].rating, content: data[key].content }) } //end of for loop resolve(); < --RIGHT }); //end of snap // resolve(); <-- WRONG Ideally with a promise you do not use global variables, you pass the value through the resolve. var myPromise = new Promise(function(resolve, reject) { var str = "Hello!"; resolve(str); }); myPromise.then(function(value) { console.log(value); });
{ "language": "en", "url": "https://stackoverflow.com/questions/48408665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to select specific substring length based on a filter I have multiple CSV files with different names, containing today's date, customer number, and then the extension. For example: 2019-01-23 XYZF-105.csv 2019-01-23 ABCD-205.csv 2019-01-23 Different nonstandard name.csv 2019-01-23 ##ABCD-305(Trial).csv I would like to get the part of the name where it contains the customer number only, like ABCD-305. Tried using a substring to select 8 characters right from the dot, but that doesn't work for those that have suffix like (Trial). Neither it work 11 characters from the beginning, as it will include the ##. Also, it has to avoid the nonstandard names. I used $allitems = Get-ChildItem -Path 'C:\Downloads\Customers\*.csv' $res = @() foreach ($item in $allitems){ $item = $item.Name.substring($item.Name.Length - 12,8) $res += $Item } This way, for the proper names I get good results, but only if the name of the CSV is like 2019-01-23 ABCD-205.csv. What should be the way to skip the date, skip the .csv extension and get only results with 8 characters, that have a dash after the 4th character? Thanks in advance A: Try the following (PSv3+ syntax): $res = (Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name | Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' | ForEach-Object { $_.Matches[0].Value } * *(Get-ChildItem -Path C:\Downloads\Customers\*.csv).Name outputs the file names of all CSV files in dir. C:\Downloads\Customers *Select-String -CaseSensitive '\b[A-Z]{4}-\d{3}\b' uses case-sensitive regex (regular-expression) matching to only select file names that contain 4 ({4}) uppercase chars. [A-Z], followed by -, followed by 3 digits (\d), on word boundaries (\b) *The ForEach-Object script block then outputs the part of each matching file name that matched the regex ($_.Matches[0].Value), so that only the relevant portions of matching file names are collected in $res, as an array. A: This would be a good time to use regex. See https://regex101.com/r/AH00n6/1 and understand the following regex: .*\s[#]*([A-Z]{4}-[0-9]{3}).*.csv This is a little extra to capture just the names, but gives more insight into how to control the regex.
{ "language": "en", "url": "https://stackoverflow.com/questions/54336573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why pl sql assignment operator throws error while reading from sql query? set serveroutput on; declare v_emp_first_name US_EMPLOYEES.FIRST_NAME%TYPE; BEGIN select us_employees.first_name into v_emp_first_name from us_employees where email = '[email protected]'; dbms_output.put_line('v_emp_first_name --> ' || v_emp_first_name); v_emp_first_name := select first_name from us_employees where email = '[email protected]'; dbms_output.put_line('v_emp_first_name --> ' || v_emp_first_name); END; When I compile above code the below statement throws error v_emp_first_name := select first_name from us_employees where email = '[email protected]'; Is it not possible to read a column value via a sql query and map that value using assignment operator ? If i have the below code alone then it compile and works fine select us_employees.first_name into v_emp_first_name from us_employees where email = '[email protected]'; A: You have issue with this code: v_emp_first_name := select first_name from us_employees where email = '[email protected]'; You can not use the assignment operator against the query as you have used. Replace this assignment := with INTO as follows: select first_name INTO v_emp_first_name from us_employees where email = '[email protected]'; A: The short answer is NO. You can't assign the output of a scalar query to a variable. The proper syntax for your "assignment" is the one you are already aware of. I am sure that you will then ask WHY. Why did Oracle choose that "weird" syntax for assignment, and not the simpler one you tried? The answer is that in more general cases a select statement may return multiple columns, not just one; and the values from multiple columns can be "assigned" to multiple variables (local to the PL/SQL block) simultaneously. Which, by the way, is the more common usage - people extract one "record" at a time, rather than a single value. So, how would you re-write the "select into" operation as an "assignment" (or multiple "assignments")? There is no natural way to do that. You may ask why Oracle doesn't allow "your" assignment syntax, in the case of a single column selected, in addition to the select into syntax (which is needed for multi-column rows anyway). The answer is that would be wasteful. We already have a syntax - that we need for more general cases anyway; we don't need one more. You might say that we could put all the receiving local variables into a record type, and do a single assignment (to a record) even for general "rows" returned by a select. Alas, SQL statements return rows, not records; rows are a SQL concept, and specifically they are not a data type. Perhaps Oracle could do further development along those lines (to add functionality that doesn't exist today), but why bother - they already have a perfectly fine syntax for what you need, and you already know what that syntax is - without needing to define a record type to hold all your local variables, then define a "record type" for rows coming from a SQL select statement, then .....
{ "language": "en", "url": "https://stackoverflow.com/questions/65591504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't run code in Android studio due to VT-x disabled When i try to run my code in android studio i got an error"Intel HAXM is required to run this AVD. VT-x is disabled in BIOS. Enable VT-x in your BIOS security settings (refer to documentation for your computer)." . I did every thing i could but i couldn't fix it . Can anybody tell me in detail how A: First make sure your processor supports virtualization technology Intel processors from i3 supports it. If your processor is above i3, then Go to BIOS and look for an option named VTx or virtualization and Enable it...save changes and exit Now open your web browser and search for HAxm drivers and install the latest one. You should be good P.S: if your processor is below i3, you cannot run avd A: If your computer does not support Virtualization, there are emulators that don't require it. I know one that many people use is Genymotion. Alternatively, of course, you can test on a physical device.
{ "language": "en", "url": "https://stackoverflow.com/questions/38538947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web Scraping w/Mechanize and/or BeautifulSoup4 on ASP pages Hello I am a programming n00b and am desperately trying to get some code to work. I can't really find any good tutorials on ASP scraping/filling in fields and submitting then working with the content. Here is my code so far: import mechanize import re url = 'http://www.cic.gc.ca/english/work/iec/index.asp' br = mechanize.Browser(factory=mechanize.RobustFactory()) br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.open(url) response = br.response().read() What I am trying to do: * *Load that URL *Fill out the 2 form fields *Submit *Print the div id stats into python *Run a loop on a 15 minute timer *Play a loud sound if anything in div stats changes when it loops Please advise me the best/fastest way of doing this with minimal programming experience. A: It's not that difficult once you understand why the second form isn't shown when page is loaded. There's nothing to do with ASP itself, it's rather due to CSS style set to "display: none;" and will only be active once the first Option Select has been filled. Here is a full sample of what you're after, implemented in Selenium, it's similar to machanize I believe. The basic flow should be: * *load the web browser and load the page *find the first Option Select and fill it in *trigger a change event (I chose to send a TAB key) and the second Option Select is shown *fill in the second Select and find the submit button and click it *assign a name to the content you get from the div id=stats text *compared if the text has changed from last fetch a) if YES, do your BEEP and close the driver page etc. b) if NO, set a scheduler (I use Python's Event's Scheduler, and run the crawling function again... That's it! Easy, ok code time -- I used United Kingdom + Working Holiday pair for test: import selenium.webdriver from selenium.webdriver.common.keys import Keys import sched, time driver = selenium.webdriver.Firefox() url = 'http://www.cic.gc.ca/english/work/iec/index.asp' driver.get(url) html_content = '' # construct a scheduler s = sched.scheduler(time.time, time.sleep) def crawl_me(): global html_content driver.refresh() time.sleep(5) # wait 5s for page to be loaded country_name = driver.find_element_by_name('country-name') country_name.send_keys('United Kingdom') # trick's here to send a TAB key to trigger the change event country_name.send_keys(Keys.TAB) # make sure the second Option Select is active (none not in style) assert "none" not in driver.find_element_by_id('category_dropdown').get_attribute('style') cateogory_name = driver.find_element_by_name('category-name') cateogory_name.send_keys('Working Holiday') btn_go = driver.find_element_by_id('submit') btn_go.send_keys(Keys.RETURN) # again, check if the content has been loaded assert "United Kingdom - Working Holiday" not in driver.page_source compared_content = driver.find_element_by_id('stats').text # here we will end this script if content has changed already if html_content != '' and html_content != compared_content: # do whatever you want to play the beep sound # at the end exit the loop driver.close() exit(-1) # if no changes are found, trigger the schedule_crawl() function, like recursively html_content = compared_content print html_content return schedule_crawl() def schedule_crawl(): # set your time interval here, 15*60 = 15 minutes s.enter(15*60, 1, crawl_me, ()) s.run() # and run it of course crawl_me() To be honest, this is quite easy and straight forward however it does require you fully understand how html/css/javascript (not javascript in this case, but you do need to know the basic) and all their elements how they work together. You do need to learn from the basic read => digest => code => experience => do it in cycles, Programming doesn't have a shortcut or the fastest way. Hope this helps (and I really hope you do not just copy & paste mine, but learn and implement your own in mechanize by the way). Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/27760424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the specific requirement to use Dagger2 in any android application? What are the actual benefits of using dagger2 in an android application? I read the dagger 2 documentation but still not able to find that in what condition I should use dagger2 in my application and what are the benefits of its implementation? A: 1.) to use Dagger2, you need to include it as a dependency in your project. annotationProcessor 'com.google.dagger:dagger-compiler:2.9' compile 'com.google.dagger:dagger:2.9' provided 'org.glassfish:javax.annotation:10.0-b28' Then you can use Dagger2. 2.) Whenever you have a class which is the dependency of another class. So if you have something like this: public int getNewRandomNumber() { return new Random().nextInt(5000); } Then you have an implicit dependency on Random and it is not mockable. So you might want to provide this as a dependency to the method instead: public int getNewRandomNumber(Random random) { return random.nextInt(5000); } But you might be using Random in a bunch of places, so you might want to provide it to the class itself: public class RandomGenerator { private final Random random; public RandomGenerator(Random random) { this.random = random; } } After which the question surfaces: if you need an instance of RandomGenerator, where are you getting Random from? Surely this is stupid: RandomGenerator gen = new RandomGenerator(new Random()); Wouldn't it be nicer to do either this: RandomGenerator randomGenerator = component.randomGenerator(); or @Inject RandomGenerator randomGenerator; Well apparently with Dagger it's pretty easy @Module public class RandomModule { @Provides @Singleton Random random() { return new Random(); } } @Singleton @Component(modules={RandomModule.class}) public interface SingletonComponent { Random random(); RandomGenerator randomGenerator(); } then @Singleton public class RandomGenerator { private final Random random; @Inject public RandomGenerator(Random random) { this.random = random; } } or @Singleton public class RandomGenerator { @Inject Random random; @Inject public RandomGenerator() { } } You can read more about dependency injection here
{ "language": "en", "url": "https://stackoverflow.com/questions/42179524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools? Yesterday I observed some really strange behaviour and wrote a looooong question on it. As @tacoshy correctly pointed out, the question lacked focus. I will therefore, in this post, focus on one single question: Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools? Preface The <head>-element contain the following viewport meta-tag <meta name="viewport" content="width=device-width, initial-scale=1" /> Before any video shown below, the following have both been performed in Chrome-devtools Settings > Preferences > Reset defaults and reload and The kebab-icon in the responsive view > Reset to defaults The application. The code can be found here. It's deployed and can be inspected here. A React-application with a state (windowWidth) that is updated to window.innerWidth when the resize-event triggers. I also have a container div with min-width set to windowWidth. In short, the container should always have the same min-width as window.innerWidth. The container contains a div with min-width statically set to 400px. The behaviour When I only open chrome developer tools and resize the visible window by changing the width of the developer tools, this is the observed behaviour: * *window.innerWidth corresponds to the size of the window. *The scale (from window.visualViewport.scale) remains at 1. Now we try in Chrome developer tools responsive mode: * *The width remains static (781px) *The entire scale of the viewport goes down. Further investigations * *window.visualViewport.width will produce nearly identical behaviour * *(apart from width sometime shifting to a decimal-point value) *window.screen.width will produce a different but also erroneous behaviour: * *The layout doesn't break until the screen becomes smaller than the cyan-coloured element (in the header with min-width: 400px). Then the container seem to shrink quicker and at this point we can also see how the scale starts to go down. *Setting windowWidth statically to 100vw produces exactly the same behaviour as above. Solution to the weird behaviour All of the examples above on the layout breaking have one thing in common: The scale starts to go down instead of the actual width of the viewport. So one could imagine that updating the viewport meta-tag to include minimum-scale=1 would solve the problem, and it does! Using <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" /> Produces the following behaviour: As you can see, the Scale remains at 1 and the layout doesn't break. In fact, adding minimum-scale=1 makes innerWidth, visualViewport.width and screen.width all produce the same expected behaviour in the responsive view of chrome developer tools. Unfortunately solving that was not the question, the question is and remains: Why does resizing the window behave differently from resizing the "responsive box" in chrome developer tools? Edit This strange scaling-behaviour is not mirrored when viewing the page in the Firefox developer tools responsive view. Edit2 Similar questions Does Mobile View in Chrome-Dev-Tools force scaling? Exactly the same problem, solved by adding the meta-tag: <meta name="viewport" content="width=device-width, initial-scale=1.0"> Which apparently did solve the problem in January 2020, but does not solve the problem today (as we cab see here). Resize Chrome responsive mode window without changing scale Also solved by adding: <meta name="viewport" content="width=device-width, initial-scale=1.0"> which is already present this time around. Why is Chrome shrinking the view in responsive mode? Exactly the same behaviour as this mine but the selected solution was a jQuery-hack. The poser also mentioned a similar scaling-problem when tilting your phone and then tilting it back again which I too have experienced (it goes away when adding minimum-width=1 to the viewport metatag). Summary It looks like this issue used to be solved by adding <meta name="viewport" content="width=device-width, initial-scale=1.0"> but now requires <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1"> my question in that case remains * *Why have they changed this? *What use is there for the developer to change the scale of the page when resizing the responsive window? *Is this a feature or a bug? Edit3 Edge on the other hand does seem to mirror this behaviour.
{ "language": "en", "url": "https://stackoverflow.com/questions/72706577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: "Lock on the Kernel Object" on windows can make the entire system unresponsive? There's this WIN32 process, which someone says: The servide takes a lock on the kernel object and does not release. After a while the machine becomes irresponsive and has to restarted. Restanting only the service won't fix the issue. According to my knowledge applications were not supposed to be able to crash the entire system in windows. Does anyone know if such an indecent behavior (taking a lock on the kernel object and not releasing it) can indeed crash the OS? If so why don't we see this more in malicious software? Some clarifications: This is not a device driver. Any amiguity left in the reponse is also ambiguous to me. Please elaborate on the cases you can think of. A: This doesn't mean anything. There is no "kernel object" in NT, and any lock you could possibly take would be released if the service were restarted. A: This depends on what type of application it is. Some applications install and use kernel drivers as part of their usage. A kernel driver has the most low level access possible in the system and is capable of crashing or hanging the system. If the process uses a kernel driver, and the description alludes to this, then yes it can crash / hang the system. I believe Windows Vista started limiting the amount of damage a kernel driver can accidentally do (graphics drivers especially). But intentionally, you can still cause lots of problems. A: Depending on which precise kernel object they mean, and which service, this may very well be true. See for instance Raymond Chen on Loader Lock, a kernel lock which applications can monopolize. Restarting the service will then become a problem because the very unload of that service will require the loader lock, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/1004637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Parsec with restrictions on parsed result I'm trying to come up with a clever way of parsing assembly code. For example, if the registers are numbered from 0 to 31, I want to accept $31 but not $32. I would like to do these while I parse the source code, because 1) I want to use the position information. 2) I like it simple. My best idea is to use a special parser to indicate failure. For example I could write import Text.Parsec hiding (label) import Text.Parsec.Token import Text.Parsec.Language (emptyDef) import Text.Parsec.String import Text.Parsec.Expr import Text.Parsec.Perm data Register = Register Integer deriving (Eq, Ord, Show) register :: Parser Register register = do char '$' n <- onlyWhen "Register number must be between 0 and 31" (\n -> n >= 0 && n <= 31) (decimal p) return $ Register n onlyWhen :: String -> (a -> Bool) -> Parser a -> Parser a onlyWhen mess pred pars = do r <- pars if pred r then return r else fail mess p = makeTokenParser emptyDef It works, but the error message contains traces of the parsing state, which is unfortunate. What would be the best way to do it? Is there some additional library for doing this kind of things? A: Try to extract Error messages getErrorMessage (ParseError p xs) = show p ++ concat $ map messageString xs
{ "language": "en", "url": "https://stackoverflow.com/questions/18080773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using a list of conditions to filter a DataFrame in Pandas I wish to have a function which takes a list of conditions, of any length, and places an ampersand between all the conditions. Example code below. df = pd.DataFrame(columns=['Sample', 'DP','GQ', 'AB'], data=[ ['HG_12_34', 200, 35, 0.4], ['HG_12_34_2', 50, 45, 0.9], ['KD_89_9', 76, 67, 0.7], ['KD_98_9_2', 4, 78, 0.02], ['LG_3_45', 90, 3, 0.8], ['LG_3_45_2', 15, 12, 0.9] ]) def some_func(df, cond_list): # wrap ampersand between multiple conditions all_conds = ? return df[all_conds] cond1 = df['DP'] > 40 cond2 = df['GQ'] > 40 cond3 = df['AB'] < 0.4 some_func(df, [cond1, cond2]) # should return df[cond1 & cond2] some_func(df, [cond1, cond3, cond2]) # should return df[cond1 & cond3 & cond2] I would appreciate any help with this. A: You can use functools.reduce for that: from functools import reduce def some_func(df, cond_list): return df[reduce(lambda x,y: x&y, cond_list)] Or, like @AryaMcCarthy says, you can use and_ from the operator package: from functools import reduce from operator import and_ def some_func(df, cond_list): return df[reduce(and_, cond_list)] or with numpy - like @ayhan says - which has also a logical and reduction: from numpy import logical_and def some_func(df, cond_list): return df[logical_and.reduce(cond_list)] All three versions produce - for your sample input - the following output: >>> some_func(df, [cond1, cond2]) Sample DP GQ AB 1 HG_12_34_2 50 45 0.9 2 KD_89_9 76 67 0.7 >>> some_func(df, [cond1, cond2, cond3]) Empty DataFrame Columns: [Sample, DP, GQ, AB] Index: []
{ "language": "en", "url": "https://stackoverflow.com/questions/43160733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SQL Datetime as time query I would like the below select statement to be show as time rather than datetime. I'm aware that a cast as solution is likely however given I am trying to Cast as a "grouped by time", I am not finding a solution. SELECT DATEADD(hour, DATEDIFF(hour, 0,dbo.tbReceiptLine.Time), 0) AS Hourly, DATEADD(minute, DATEDIFF(minute, 0, dbo.tbReceiptLine.Time) / 30 * 30, 0) AS [30 Mins] I would like to show this as time only. A: In SQL Server 2008 onwards you can cast to time datatype: SELECT CAST(dbo.tbReceiptLine.Time as time) See The ultimate guide to the datetime datatypes
{ "language": "en", "url": "https://stackoverflow.com/questions/18225487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Build asset folder empty : android Studio, using Gradle I have created a simple app in android studio, where I have placed a font under src/main/assets/fonts/fontName.ttf When running a build/clean etc. the asset folder in the build stays empty. (build/exploded-aar/com.android.support/appcompat-v7/19.1.0/assets) The application runs, no instances of the file are found on the device.
{ "language": "en", "url": "https://stackoverflow.com/questions/23216700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Amazon MWS (PHP) - How does the request work I am trying to pull a report in PHP for active listings. I've made progress, however, I cannot understand how this works and there is nothing out there that can explain it. For example, in the Samples provided from the PHP library, I see quite a few XML files. When you run the RequestReportResponse sample, does that generate the XML file, or does the XML file tell the RequestReportResponse what to do based on values and functions? I am asking because, with the MWS Scratchpad - I select all the necessary fields, submit it then refresh the Amazon Reports page of my seller central section and it shows a pending report. I'm just asking how the XML content affects the report or how the report can affect the XML. A: The answer to your question comes in two parts. Part 1 - Calling the Amazon API Most MWS requests do not require any file (be it plain text or XML) to be sent to Amazon. For example, all parameters needed to do send RequestReport can (and must) be sent as regular parameters. I'm not sure what Amazon would do if you did submit a file along with it as I've never tried. But then again... why would you? One of the calls that does require a file to be send is the SubmitFeed call where that file is the actual feed to be submitted. It depends on the type of feed you're submitting if Amazon expects it to be plain text or XML. Part 2 - Handling Amazon's API responses When you get information back from Amazon's API, it usually is in XML format (there are a few calls that may return plaintext instead). You will need to decode this data to get your information out. To make it a bit clearer, I'll outline a typical process for you: The process of getting all your listings from Amazon: * *Do a RequestReport call to Amazon. No XML attached *Decode the XML that you're getting back (it is a RequestReportResponse). If all went well, you'll get a RequestReportId as part of the response, and Amazon will start processing your request. Amazon may need a few minutes to actually create the report, in cases of very complex or large requests or during high activity hours it may actually take up to an hour or more. So we need to find out when the request we made is actually done. *Poke Amazon API with a GetReportRequestList call asking for the status of your request with ReportRequestIdList.Id.1={YourRequestIdHere}. This also does not need a XML attachment. *Decode the XML that you're getting back. (it is a GetReportRequestListResponse) If its ReportProcessingStatus is not _DONE_, wait for at least 45 seconds, then repeat from step 3. If the report is actually done, you'll see a valid GeneratedReportId in the response. If it is missing, you'll need to do an extra GetReportList call to find its ID. *Call GetReport to finally fetch your report with ReportId={YourGeneratedReportIdHere} *Decode whatever you're getting back. Depending on the type of report you requested, the response may be XML or plain text. This process is explained in detail (and with a pretty flow chart) in Amazon Marketplace Web Service Reports API Section Reference (Version 2009-01-01) To finally answer your question with respect to getting active listings from Amazon MWS: None of the three calls require you to send XML to Amazon. The data you receive from Amazon will be in XML format (with the possible exception step 6 if you requested a plain text report).
{ "language": "en", "url": "https://stackoverflow.com/questions/18346288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: clickhouse 1 node out of 3 not syncing I have a 3-node clickhouse cluster, almost identical to the setup in https://github.com/tetafro/clickhouse-cluster. I ran the CREATE TABLE statement on the 3 nodes, as follows: CREATE TABLE replica_test.hits_shard ( `WatchID` UInt64, `JavaEnable` UInt8, `Title` String, `GoodEvent` Int16, `EventTime` DateTime, `EventDate` Date, `CounterID` UInt32, `ClientIP` UInt32, `ClientIP6` FixedString(16), `RegionID` UInt32, `UserID` UInt64, `CounterClass` Int8, `OS` UInt8, `UserAgent` UInt8, `URL` String, `Referer` String, `URLDomain` String, `RefererDomain` String, `Refresh` UInt8, `IsRobot` UInt8, `RefererCategories` Array(UInt16), `URLCategories` Array(UInt16), `URLRegions` Array(UInt32), `RefererRegions` Array(UInt32), `ResolutionWidth` UInt16, `ResolutionHeight` UInt16, `ResolutionDepth` UInt8, `FlashMajor` UInt8, `FlashMinor` UInt8, `FlashMinor2` String, `NetMajor` UInt8, `NetMinor` UInt8, `UserAgentMajor` UInt16, `UserAgentMinor` FixedString(2), `CookieEnable` UInt8, `JavascriptEnable` UInt8, `IsMobile` UInt8, `MobilePhone` UInt8, `MobilePhoneModel` String, `Params` String, `IPNetworkID` UInt32, `TraficSourceID` Int8, `SearchEngineID` UInt16, `SearchPhrase` String, `AdvEngineID` UInt8, `IsArtifical` UInt8, `WindowClientWidth` UInt16, `WindowClientHeight` UInt16, `ClientTimeZone` Int16, `ClientEventTime` DateTime, `SilverlightVersion1` UInt8, `SilverlightVersion2` UInt8, `SilverlightVersion3` UInt32, `SilverlightVersion4` UInt16, `PageCharset` String, `CodeVersion` UInt32, `IsLink` UInt8, `IsDownload` UInt8, `IsNotBounce` UInt8, `FUniqID` UInt64, `HID` UInt32, `IsOldCounter` UInt8, `IsEvent` UInt8, `IsParameter` UInt8, `DontCountHits` UInt8, `WithHash` UInt8, `HitColor` FixedString(1), `UTCEventTime` DateTime, `Age` UInt8, `Sex` UInt8, `Income` UInt8, `Interests` UInt16, `Robotness` UInt8, `GeneralInterests` Array(UInt16), `RemoteIP` UInt32, `RemoteIP6` FixedString(16), `WindowName` Int32, `OpenerName` Int32, `HistoryLength` Int16, `BrowserLanguage` FixedString(2), `BrowserCountry` FixedString(2), `SocialNetwork` String, `SocialAction` String, `HTTPError` UInt16, `SendTiming` Int32, `DNSTiming` Int32, `ConnectTiming` Int32, `ResponseStartTiming` Int32, `ResponseEndTiming` Int32, `FetchTiming` Int32, `RedirectTiming` Int32, `DOMInteractiveTiming` Int32, `DOMContentLoadedTiming` Int32, `DOMCompleteTiming` Int32, `LoadEventStartTiming` Int32, `LoadEventEndTiming` Int32, `NSToDOMContentLoadedTiming` Int32, `FirstPaintTiming` Int32, `RedirectCount` Int8, `SocialSourceNetworkID` UInt8, `SocialSourcePage` String, `ParamPrice` Int64, `ParamOrderID` String, `ParamCurrency` FixedString(3), `ParamCurrencyID` UInt16, `GoalsReached` Array(UInt32), `OpenstatServiceName` String, `OpenstatCampaignID` String, `OpenstatAdID` String, `OpenstatSourceID` String, `UTMSource` String, `UTMMedium` String, `UTMCampaign` String, `UTMContent` String, `UTMTerm` String, `FromTag` String, `HasGCLID` UInt8, `RefererHash` UInt64, `URLHash` UInt64, `CLID` UInt32, `YCLID` UInt64, `ShareService` String, `ShareURL` String, `ShareTitle` String, `ParsedParams` Nested( Key1 String, Key2 String, Key3 String, Key4 String, Key5 String, ValueDouble Float64), `IslandID` FixedString(16), `RequestNum` UInt32, `RequestTry` UInt8 ) ENGINE=ReplicatedMergeTree('/clickhouse/tables/{shard}/tables/hits', '{replica}') PARTITION BY toYYYYMM(EventDate) ORDER BY (CounterID, EventDate, intHash32(UserID)) SAMPLE BY intHash32(UserID); CREATE TABLE replica_test.hits_distributed ( `WatchID` UInt64, `JavaEnable` UInt8, `Title` String, `GoodEvent` Int16, `EventTime` DateTime, `EventDate` Date, `CounterID` UInt32, `ClientIP` UInt32, `ClientIP6` FixedString(16), `RegionID` UInt32, `UserID` UInt64, `CounterClass` Int8, `OS` UInt8, `UserAgent` UInt8, `URL` String, `Referer` String, `URLDomain` String, `RefererDomain` String, `Refresh` UInt8, `IsRobot` UInt8, `RefererCategories` Array(UInt16), `URLCategories` Array(UInt16), `URLRegions` Array(UInt32), `RefererRegions` Array(UInt32), `ResolutionWidth` UInt16, `ResolutionHeight` UInt16, `ResolutionDepth` UInt8, `FlashMajor` UInt8, `FlashMinor` UInt8, `FlashMinor2` String, `NetMajor` UInt8, `NetMinor` UInt8, `UserAgentMajor` UInt16, `UserAgentMinor` FixedString(2), `CookieEnable` UInt8, `JavascriptEnable` UInt8, `IsMobile` UInt8, `MobilePhone` UInt8, `MobilePhoneModel` String, `Params` String, `IPNetworkID` UInt32, `TraficSourceID` Int8, `SearchEngineID` UInt16, `SearchPhrase` String, `AdvEngineID` UInt8, `IsArtifical` UInt8, `WindowClientWidth` UInt16, `WindowClientHeight` UInt16, `ClientTimeZone` Int16, `ClientEventTime` DateTime, `SilverlightVersion1` UInt8, `SilverlightVersion2` UInt8, `SilverlightVersion3` UInt32, `SilverlightVersion4` UInt16, `PageCharset` String, `CodeVersion` UInt32, `IsLink` UInt8, `IsDownload` UInt8, `IsNotBounce` UInt8, `FUniqID` UInt64, `HID` UInt32, `IsOldCounter` UInt8, `IsEvent` UInt8, `IsParameter` UInt8, `DontCountHits` UInt8, `WithHash` UInt8, `HitColor` FixedString(1), `UTCEventTime` DateTime, `Age` UInt8, `Sex` UInt8, `Income` UInt8, `Interests` UInt16, `Robotness` UInt8, `GeneralInterests` Array(UInt16), `RemoteIP` UInt32, `RemoteIP6` FixedString(16), `WindowName` Int32, `OpenerName` Int32, `HistoryLength` Int16, `BrowserLanguage` FixedString(2), `BrowserCountry` FixedString(2), `SocialNetwork` String, `SocialAction` String, `HTTPError` UInt16, `SendTiming` Int32, `DNSTiming` Int32, `ConnectTiming` Int32, `ResponseStartTiming` Int32, `ResponseEndTiming` Int32, `FetchTiming` Int32, `RedirectTiming` Int32, `DOMInteractiveTiming` Int32, `DOMContentLoadedTiming` Int32, `DOMCompleteTiming` Int32, `LoadEventStartTiming` Int32, `LoadEventEndTiming` Int32, `NSToDOMContentLoadedTiming` Int32, `FirstPaintTiming` Int32, `RedirectCount` Int8, `SocialSourceNetworkID` UInt8, `SocialSourcePage` String, `ParamPrice` Int64, `ParamOrderID` String, `ParamCurrency` FixedString(3), `ParamCurrencyID` UInt16, `GoalsReached` Array(UInt32), `OpenstatServiceName` String, `OpenstatCampaignID` String, `OpenstatAdID` String, `OpenstatSourceID` String, `UTMSource` String, `UTMMedium` String, `UTMCampaign` String, `UTMContent` String, `UTMTerm` String, `FromTag` String, `HasGCLID` UInt8, `RefererHash` UInt64, `URLHash` UInt64, `CLID` UInt32, `YCLID` UInt64, `ShareService` String, `ShareURL` String, `ShareTitle` String, `ParsedParams.Key1` Array(String), `ParsedParams.Key2` Array(String), `ParsedParams.Key3` Array(String), `ParsedParams.Key4` Array(String), `ParsedParams.Key5` Array(String), `ParsedParams.ValueDouble` Array(Float64), `IslandID` FixedString(16), `RequestNum` UInt32, `RequestTry` UInt8 ) ENGINE = Distributed('hivestack', replica_test, 'hits_shard', rand()); I have an out-of-sync issue with node-2 as follows: * *if i insert data to node-2, the data is only seen by node-2 * *insert ... into node2 => hits_shard then select count(*) fom node1 => hits_shard the result is 0 *if i insert data into node-1 or node-3, it's seen by all 3 nodes. SELECT * from system.replicas: replica_test,hits_shard,ReplicatedMergeTree,1,1,0,0,0,0,/clickhouse/tables/02/tables/hits,clickhouse02,/clickhouse/tables/02/tables/hits/replicas/clickhouse02,-1,0,0,0,0,1969-12-31 19:00:00,1969-12-31 19:00:00,1969-12-31 19:00:00,1969-12-31 19:00:00,"","","",0,0,1969-12-31 19:00:00,0,1,1,"","",{'clickhouse02':1} select * from system.replication_queue is empty clickhouse version: clickhouse/clickhouse-server:22.4.5.9 zookeeper version: bitnami/zookeeper:3.8.0 I verified that all 3 nodes can talk to each others via clickhouse-client and nc 9000 Would appreciate any tips on how to debug/fix this A: Are you sure you have the same zookeeper clickhouse settings on all 3 nodes? Do you insert into Distributed table or insert into ReplicatedMergeTree? For first case, check on node-2 SELECT * FROM system.distribution_queue FORMAT Vertical SELECT * FROM system.clusters FORMAT Vertical and compare <remote_servers> section in your config for all 3 nodes
{ "language": "en", "url": "https://stackoverflow.com/questions/72378864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure SQL Database DTU percentage Reach 100% on particular function My scenario is I have a button name(publish) at admin side use for publish agreement and after publish it visible to user-side. Recently I saw when I publish agreement DTU percent reach almost 100% and I tested rest of all functionality DTU not goes upto 5%. My database size is 250mb I upgraded the DTU to a higher tier(from B1 to B2,S1,S2,S3) but when publish agreement it reach 100% process took (3 minute maximum) when publish a large agreement I checked the Query that taking long time also not complicated (@EntityKeyValue1 bigint)SELECT [Extent1].[Revision] AS [Revision], [Extent1].[ClauseVersionId] AS [ClauseVersionId], [Extent1].[SourceClauseVersionId] AS [SourceClauseVersionId], [Extent1].[DisplayHeader] AS [DisplayHeader], [Extent1].[Body] AS [Body], [Extent1].[EndUserGuidanceNote] AS [EndUserGuidanceNote], [Extent1].[DocumentParty_DocumentPartyId] AS [DocumentParty_DocumentPartyId], [Extent1].[PublishedClause_ClauseId] AS [PublishedClause_ClauseId] FROM [dbo].[PublishedClauseVersion] AS [Extent1] WHERE ([Extent1].[PublishedClause_ClauseId] IS NOT NULL) AND ([Extent1].[PublishedClause_ClauseId] = @EntityKeyValue1) I saw many answer and article but I didn't get any proper solution for this issue. A: Check if the 2 sides of the comparison matches , Meaning the PublishedClause_ClauseId is also BigInt Data type as the parameter you are using "@EntityKeyValue1" , Mismatching them cause query optimizer to either scan or not use indexes, Match them then redeploy
{ "language": "en", "url": "https://stackoverflow.com/questions/41584085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: curl_multi_fdset returns always 1 What I want to do: download multiple files at the same time. Issue: curl_multi_fdset always return 1. Issue 2: I don't really understand how fd_set work. I am new to C and the doc is quite confusing. Sources: I used this example and this progress bar. My full .cpp: Github So the problem seems to be in the initializing method: static void initialize(CURLM *cm, int i, char* url[], std::string filepath) { CURL *eh = curl_easy_init(); FILE *fp; // added to the example fp = fopen(filepath.c_str(), "wb"); // added to the example curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, callback); curl_easy_setopt(eh, CURLOPT_WRITEDATA, fp); // added to the example curl_easy_setopt(eh, CURLOPT_NOPROGRESS, 0); // added to the example curl_easy_setopt(eh, CURLOPT_HEADER, 0L); curl_easy_setopt(eh, CURLOPT_URL, url[i]); curl_easy_setopt(eh, CURLOPT_PRIVATE, url[i]); curl_easy_setopt(eh, CURLOPT_VERBOSE, 0L); curl_easy_setopt(eh, CURLOPT_PROGRESSFUNCTION, progress_func); // added to the example curl_multi_add_handle(cm, eh); } However, it also won't work without these additional options. So it has to be something different but I didn't change anything regarding the fd_set. Any help is appreciated. Call of initialize: CURLM *cm = nullptr; CURLMsg *msg; long L; unsigned int C = 0; int M, Q, U = -1; fd_set R, W, E; struct timeval T; curl_global_init(CURL_GLOBAL_ALL); /* we can optionally limit the total amount of connections this multi handle uses */ curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, (long) MAX); if ((argc - 2) < MAX) { for (C = 0; C < argc - 2; ++C) { path = "test" + std::to_string(C) + ".html"; initialize(cm, C, urls, path); } } Call of the function which returns 1: FD_ZERO(&R); FD_ZERO(&W); FD_ZERO(&E); if (curl_multi_fdset(cm, &R, &W, &E, &M)) { fprintf(stderr, "E: curl_multi_fdset\n"); return EXIT_FAILURE; }
{ "language": "en", "url": "https://stackoverflow.com/questions/53836844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I move both files and folders to the specified directory? There is a code that moves files from one directory to another, but it doesn't move folders. import os,glob import shutil inpath = str5 outpath = str6 os.chdir(inpath) for file in glob.glob("*.*"): shutil.move(inpath+'/'+file,outpath) How to make it move both files and folders to the specified directory? A: *.* selects files that have an extension, so it omits sub-folders. Use * to select files and folders. Then you should see your desired result. for file in glob.glob("*"): shutil.move(inpath+'/'+file,outpath) A: You can use os.listdir to get all the files and folders in a directory. import os import shutil def move_file_and_folders(inpath, outpath): for filename in os.listdir(inpath): shutil.move(os.path.join(inpath, filename), os.path.join(outpath, filename)) In your case, inpath = <specify the source> outpath = <specify the destination> move_file_and_folders(inpath, outpath)
{ "language": "en", "url": "https://stackoverflow.com/questions/70505242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Applescript Finder Selection "Stuck" I've been using the code below for awhile to auto-magically scale images down through the various wallpaper sizes that I want. This morning, it ceased working and is giving some of the most bizarre behavior I've ever seen. If I reboot my box, the script works as expected the first time it runs. After that, the previous selection seems to be stuck in the Image Events memory. What I mean is the following: I have this directory structure: . |-- 11 | `-- Math.png |-- 1610 |-- 169 | `-- Math.png |-- 43 | `-- Math.png |-- Math.jpg `-- Math.png I run the script for the first time after rebooting with ./169/Math.png selected in the Finder and get the following results in Applescript Editor: tell application "Finder" get selection --> {document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk} get document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:Math.png" end tell tell application "Image Events" open alias "Paul:Users:tim:Downloads:test:169:Math.png" --> image "Math.png" get dimensions of image "Math.png" --> {2560, 1440} scale image "Math.png" to size 1920 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -1708 «event ascrgdut» --> error number -1708 offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/169/Math_1920x1080.png" as PNG --> file "Paul:Users:tim:Downloads:test:169:Math_1920x1080.png" scale image "Math.png" to size 1366 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/169/Math_1366x768.png" as PNG --> file "Paul:Users:tim:Downloads:test:169:Math_1366x768.png" end tell Result: file "Paul:Users:tim:Downloads:test:169:Math_1366x768.png" of application "Image Events" tell application "Finder" get selection --> {document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk} get document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:Math.png" end tell tell application "Image Events" open alias "Paul:Users:tim:Downloads:test:169:Math.png" --> image "Math.png" get dimensions of image "Math.png" --> {2560, 1440} scale image "Math.png" to size 1920 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -1708 «event ascrgdut» --> error number -1708 offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/169/Math_1920x1080.png" as PNG --> file "Paul:Users:tim:Downloads:test:169:Math_1920x1080.png" scale image "Math.png" to size 1366 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/169/Math_1366x768.png" as PNG --> file "Paul:Users:tim:Downloads:test:169:Math_1366x768.png" end tell Result: file "Paul:Users:tim:Downloads:test:169:Math_1366x768.png" of application "Image Events" tell application "Finder" get selection --> {document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk} get document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:Math.png" end tell tell application "Image Events" open alias "Paul:Users:tim:Downloads:test:169:Math.png" --> image "Math.png" get dimensions of image "Math.png" --> {2560, 1440} scale image "Math.png" to size 1920 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -1708 «event ascrgdut» --> error number -1708 offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/169/Math_1920x1080.png" as PNG --> file "Paul:Users:tim:Downloads:test:169:Math_1920x1080.png" scale image "Math.png" to size 1366 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -10004 end tell tell current application tell application "Finder" get selection --> {document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk} get document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:Math.png" end tell tell application "Image Events" open alias "Paul:Users:tim:Downloads:test:169:Math.png" --> image "Math.png" get dimensions of image "Math.png" --> {2560, 1440} scale image "Math.png" to size 1920 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -1708 «event ascrgdut» --> error number -1708 offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/169/Math_1920x1080.png" as PNG --> file "Paul:Users:tim:Downloads:test:169:Math_1920x1080.png" scale image "Math.png" to size 1366 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "169" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:169:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/169/Math_1366x768.png" as PNG --> file "Paul:Users:tim:Downloads:test:169:Math_1366x768.png" end tell Result: file "Paul:Users:tim:Downloads:test:169:Math_1366x768.png" of application "Image Events" I run the script again with ./Math.png selected in Finder: tell application "Finder" get selection --> {document file "Math.png" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk} get document file "Math.png" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:Math.png" end tell tell application "Image Events" open alias "Paul:Users:tim:Downloads:test:Math.png" --> image "Math.png" get dimensions of image "Math.png" --> {2560, 1440} scale image "Math.png" to size 1920 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/Math_1920x1080.png" as PNG --> file "Paul:Users:tim:Downloads:test:Math_1920x1080.png" scale image "Math.png" to size 1366 get name of image "Math.png" --> "Math.png" get name of image "Math.png" --> "Math.png" offset of "." in "Math.png" --> error number -10004 end tell tell current application offset of "." in "Math.png" --> 5 end tell tell application "Finder" get parent of document file "Math.png" of folder "test" of folder "Downloads" of folder "tim" of folder "Users" of startup disk --> alias "Paul:Users:tim:Downloads:test:" end tell tell application "Image Events" save image "Math.png" in "/Users/tim/Downloads/test/Math_1366x768.png" as PNG --> file "Paul:Users:tim:Downloads:test:Math_1366x768.png" end tell Result: file "Paul:Users:tim:Downloads:test:Math_1366x768.png" of application "Image Events" Notice that the previously selected ./169/Math.png is the one that gets open when I call open currentWallpaper as (alias), despite the fact that the correct wallpaper shows up in the Finder selection. In other words, it's not like Finder is stuck with the old selection, but that the wallpapers that I'm looping through get stuck on the old ones. Perhaps even more bizarre, is that if I move the old wallpaper, that I had selected, the currentWallpaper reference moves with it! In other words, even if I trash the old selection, the output from the script reports that it's opening the one in ./.Trashes. It does not seem to get confused as long as the names are different. The Script: tell application "Finder" to set wallpapers to selection set myDimensions to {w169:[{2560, 1440}, {1920, 1080}, {1366, 768}], w1610:[{2560, 1600}, {1920, 1200}, {1440, 900}, {1280, 800}], f43:[{1600, 1200}], s:[{1024, 1024}]} tell application "Image Events" repeat with currentWallpaper in wallpapers set theWallpaper to open (currentWallpaper as alias) tell theWallpaper set theWallpaperDimensions to dimensions of theWallpaper set currentAspects to {} if my aspectsEqual(16 / 10, theWallpaperDimensions) then set currentAspects to w1610 of myDimensions if my aspectsEqual(16 / 9, theWallpaperDimensions) then set currentAspects to w169 of myDimensions if my aspectsEqual(4 / 3, theWallpaperDimensions) then set currentAspects to f43 of myDimensions if my aspectsEqual(1, theWallpaperDimensions) then set currentAspects to s of myDimensions repeat with dim in currentAspects -- Scale and Crop to current dimensions if item 1 of theWallpaperDimensions is greater than item 1 of dim then scale to size (get item 1 of dim) -- Set up save target set namePrefix to text items 1 thru ((offset of "." in (get name)) - 1) of (get name) as string tell application "Finder" set _ to parent of currentWallpaper as alias set parentPath to POSIX path of _ end tell set saveTarget to parentPath & namePrefix & "_" & (get item 1 of dim) & "x" & (get item 2 of dim) & ".png" --save to target save in saveTarget as PNG end if end repeat end tell end repeat end tell on aspectsEqual(baseAspect, wallpaperDimensions) set wallpaperAspect to (item 1 of wallpaperDimensions) / (item 2 of wallpaperDimensions) set aspectDifference to baseAspect - wallpaperAspect if aspectDifference is less than 0 then set aspectDifference to aspectDifference * -1 return aspectDifference is less than 1.0E-3 end aspectsEqual A: The problem is caused by way "Image Events" returns references to opened images: open alias "Paul:Users:tim:Downloads:test:Math.png" --> image "Math.png" open alias "Paul:Users:tim:Downloads:test:169:Math.png" --> image "Math.png" The opened image is referenced by name. If you open another image with the same name, the returned reference may occasionally refer to a previously opened image of the same name. As a work-around add a close every image before you enter the loop that processes the selected images. Furthermore you need to close the opened image when you are done with it: tell application "Image Events" close every image repeat with currentWallpaper in wallpapers set theWallpaper to open (currentWallpaper as alias) tell theWallpaper ... end tell close theWallpaper end repeat end tell
{ "language": "en", "url": "https://stackoverflow.com/questions/6164731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Combining two datasets to match each - R I have two datasets like this: * *Population by country Country Population America value Argentina value Australia value Brazil value Japan value ... *Landmass by country Country Landmass Argentina value Mexico value Uruguay value Maldives value ... The number of rows and the number of country names are different from each set, is there a way to combine both data, (adding Landmass column to the respective country in the population set) it doesn't matter if that country isn't present in the population set, only combine to the ones that are there. A: I think what you're after is a left_join which from the docs: https://dplyr.tidyverse.org/reference/join.html returns all rows from x, and all columns from x and y. i.e. pops <- data.frame( "Country" = c("America", "Argentina", "Australia","Brazil", "Japan"), "Population" = seq(100, 200, 25) ) landmass <- data.frame( "Country" = c("Argentina", "Mexico", "Uruguay","Maldives"), "Landmass" = seq(1250, 2000, 250) ) dplyr::left_join(pops, landmass, by = c("Country"= "Country")) yields
{ "language": "en", "url": "https://stackoverflow.com/questions/68744939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Solve a system of equations depending on a set of parameters with Mathematica Using Mathematica, I want to solve a system of nonlinear equations like f(x,y;m)=0 g(x,y;m)=0 where m is an external parameter on which the equations depends on. As the equations are very hard, what I do is to explicitly fix m, above all, and then find a solution for that specific value of m (by FindRoot[]). But this is very slow and inefficient (and more specifically in my case, where indeed I have three parameters). What I would like is an automatic method that studies numerically the solution for a discrete set of values ​​for m, that fixes it without that I explicitly change it from time to time. So that I would get all together the solutions for those values ​​of m. It would be nice also that a similar procedure can be applied to the initial seeds for FindRoot [], since in my case I get several solutions changing the latter, and so there are different solutions for that value of m, and so similarly I would like to have all the solutions for a given set of initial seeds. Is it possible to do such a thing? How? Many thanks A: For the first part, assuming that you have a function solve[m] and a range of values for m={1,2,3,...}, you can use: Map[solve, m] I'm not sure what you mean by "fixing it", but this will give you an array, which you can investigate further.
{ "language": "en", "url": "https://stackoverflow.com/questions/15309473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use of jTDS to connect to SQL Server 2012 throws IOException; MS SQL Driver works The following code using jTDS driver (1.3.1): DriverManager.getConnection("jdbc:jtds:sqlserver://anIpAddress;databaseName=aDatabase", "user", "pass") results in: java.sql.SQLException: I/O Error: DB server closed connection. at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2481) at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:632) at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371) at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at com.example.crd.test.TestDb.main(TestDb.java:20) Caused by: java.io.IOException: DB server closed connection. at net.sourceforge.jtds.jdbc.SharedSocket.readPacket(SharedSocket.java:852) at net.sourceforge.jtds.jdbc.SharedSocket.getNetPacket(SharedSocket.java:731) at net.sourceforge.jtds.jdbc.ResponseStream.getPacket(ResponseStream.java:477) at net.sourceforge.jtds.jdbc.ResponseStream.read(ResponseStream.java:114) at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2368) However, this code using MS SQL driver (4.2) works without exception: DriverManager.getConnection("jdbc:sqlserver://anIpAddress;databaseName=aDatabase", "user", "pass") I'm trying to connect to a SQL Server 2012 database. Note: The user has read only access to the database. I do not have permission to change any configuration on SQL Server 2012. I have tried the same code to connect to a SQL Server 2005 database, and both the Microsoft and jTDS drivers work without exception in that case. How can I connect to the SQL Server 2012 database without exception using jTDS?
{ "language": "en", "url": "https://stackoverflow.com/questions/36726133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Integrate REST Web Services with Spring Integration I have implemented Restful web services using spring technologies. Now, I need to integrate these services to work together on the same context using spring integration. How To make web services methods as endpoints ? How can I realize the coreography of web services ? How It is possible to transform messages exchanged between web services ? A: The spring-integration tag has links to lots of resources.
{ "language": "en", "url": "https://stackoverflow.com/questions/31718634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Disable gridview controls using jquery in aspx form I have a form in which there is a CheckBox and a gridview. When I uncheck the CheckBox I want controls in my Gridview to be disabled. here is my gridview aspx: <div id="gridVersion" runat="server"> <ac:GridViewWithPager ID="gdvwAllowedVersion" runat="server" UseCustomPager="True" AllowPaging="True" AutoGenerateColumns="False" Width="50%"> <Columns> <asp:TemplateField ItemStyle-CssClass="centerdata"> <ItemTemplate> <asp:RadioButton ID="rdblSelectedVersionList" runat="server" AutoPostBack="true" Checked='<%#Eval("IsSelected") %>' EnableViewState="true" OnCheckedChanged="rdblSelectedVersionList_CheckedChanged" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" Width="2%"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="IDEAlliance Version" HeaderStyle-Width="11%" HeaderStyle-HorizontalAlign="Left"> <ItemTemplate> <asp:Label ID="lblVersion" runat="server" Text='<%# Eval("IdeAllianceVersion") %>' /> </ItemTemplate> <HeaderStyle HorizontalAlign="Left" Width="11%"></HeaderStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Restrict Import Of" ItemStyle-CssClass="centerdata" HeaderStyle-Width="2%" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="2%"> <ItemTemplate> <asp:CheckBox ID="chkCheckRestrictImport" runat="server" Checked='<%# Eval("RestrictedForImport")%>' /> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" Width="2%"></HeaderStyle> <ItemStyle HorizontalAlign="Center" Width="2%"></ItemStyle> </asp:TemplateField> <asp:TemplateField HeaderText="Restrict Upgrade To" ItemStyle-CssClass="centerdata" HeaderStyle-Width="2%" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="2%"> <ItemTemplate> <asp:CheckBox ID="chkCheckRestrictUpgrade" runat="server" Checked='<%# Eval("RestrictedForUpgrade")%>' /> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" Width="2%"></HeaderStyle> <ItemStyle HorizontalAlign="Center" Width="2%"></ItemStyle> </asp:TemplateField> </Columns> </ac:GridViewWithPager> </div> My CheckBox control is something like this: <asp:CheckBox ID="chkActivateSettings" runat="server" Text="Activate Restriction Settings."> </asp:CheckBox> I have already written a Jquery code that hides and shows this grid. But now what I want is to disable control in this grid upon unchecking the CheckBox. So I want to modify this code: $(document).ready(function () { if ($('#<%=chkActivateSettings.ClientID %>').is(":checked")) { //show the hidden div $('#<%=gridVersion.ClientID %>').show("fast"); } else { //otherwise, hide it $('#<%=gridVersion.ClientID %>').hide("fast"); } // Add onclick handler to checkbox w/id checkme $('#<%=chkActivateSettings.ClientID %>').click(function () { // If checked if ($('#<%=chkActivateSettings.ClientID %>').is(":checked")) { //show the hidden div $('#<%=gridVersion.ClientID %>').Ena("fast"); } else { //otherwise, hide it $('#<%=gridVersion.ClientID %>').hide("fast"); } }); }); Looking forward to your usual cooperation. A: Try this: 1) Add Enabled="True" to gridview markup: <ac:GridViewWithPager ID="gdvwAllowedVersion" runat="server" Enabled="True" UseCustomPager="True" AllowPaging="True" AutoGenerateColumns="False" Width="50%"> 2) Use Jquery's DOM manipulation method attr(key, value) to enable/disable gridview: $(document).ready(function () { // Add onclick handler to checkbox w/id checkme $('#<%=chkActivateSettings.ClientID %>').click(function () { // If checked if ($('#<%=chkActivateSettings.ClientID %>').is(":checked")) { //show the hidden div $('#<%=gdvwAllowedVersion.ClientID %>').attr("disabled", false); } else { //otherwise, hide it $('#<%=gdvwAllowedVersion.ClientID %>').attr("disabled", true); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/10203419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot deploy Next.js to Netlify. Deploy failed due to an error in @netlify/plugin-nextjs plugin I can run npm run build with no problems at all, but whenever I try and deploy my Next.js project to Netlify I get an odd error stating Deploy failed due to an error in @netlify/plugin-nextjs plugin After doing some research I found that I should install @netlify/plugin-nextjs into my package.json as a dev dependency, then add it to a netlify.toml in the root of my project which I have done. Here is the github repo which Netlify's support forums have led me to: https://github.com/netlify/netlify-plugin-nextjs I've followed the directions on their github repo above for the @netlify/plugin-nextjs plugin as well as searched for any relevant posts under their github issues and unfortunately I couldn’t find anything related nor useful in the github issues. I’ve tried clearing cache and deploy but it didn’t help. I am using Next.js version v11.1.2 Here is the build log with the error detailed: 11:58:50 PM: Started restoring cached go cache 11:58:50 PM: Finished restoring cached go cache 11:58:50 PM: go version go1.16.5 linux/amd64 11:58:50 PM: go version go1.16.5 linux/amd64 11:58:50 PM: Installing missing commands 11:58:50 PM: Verify run directory 11:58:52 PM: ​ 11:58:52 PM: ──────────────────────────────────────────────────────────────── 11:58:52 PM: Netlify Build 11:58:52 PM: ──────────────────────────────────────────────────────────────── 11:58:52 PM: ​ 11:58:52 PM: ❯ Version 11:58:52 PM: @netlify/build 18.21.2 11:58:52 PM: ​ 11:58:52 PM: ❯ Flags 11:58:52 PM: baseRelDir: true 11:58:52 PM: buildId: 618232a9499e9a000783387d 11:58:52 PM: deployId: 618232a9499e9a000783387f 11:58:52 PM: ​ 11:58:52 PM: ❯ Current directory 11:58:52 PM: /opt/build/repo 11:58:52 PM: ​ 11:58:52 PM: ❯ Config file 11:58:52 PM: /opt/build/repo/netlify.toml 11:58:52 PM: ​ 11:58:52 PM: ❯ Context 11:58:52 PM: production 11:58:52 PM: ​ 11:58:52 PM: ❯ Installing plugins 11:58:52 PM: - @netlify/[email protected] 11:59:02 PM: ​ 11:59:02 PM: ❯ Loading plugins 11:59:02 PM: - @netlify/[email protected] from netlify.toml 11:59:03 PM: ​ 11:59:03 PM: ──────────────────────────────────────────────────────────────── 11:59:03 PM: 1. @netlify/plugin-nextjs (onPreBuild event) 11:59:03 PM: ──────────────────────────────────────────────────────────────── 11:59:03 PM: ​ 11:59:03 PM: ​ 11:59:03 PM: ──────────────────────────────────────────────────────────────── 11:59:03 PM: Plugin "@netlify/plugin-nextjs" failed 11:59:03 PM: ──────────────────────────────────────────────────────────────── 11:59:03 PM: ​ 11:59:03 PM: Error message 11:59:03 PM: Error: This site does not seem to be using Next.js. Please run "npm install next" in the repository. 11:59:03 PM: If you are using a monorepo, please see the docs on configuring your site: https://ntl.fyi/next-monorepos 11:59:03 PM: ​ 11:59:03 PM: Plugin details 11:59:03 PM: Package: @netlify/plugin-nextjs 11:59:03 PM: Version: 3.9.2 11:59:03 PM: Repository: git+https://github.com/netlify/netlify-plugin-nextjs.git 11:59:03 PM: npm link: https://www.npmjs.com/package/@netlify/plugin-nextjs 11:59:03 PM: Report issues: https://github.com/netlify/netlify-plugin-nextjs/issues 11:59:03 PM: ​ 11:59:03 PM: Error location 11:59:03 PM: In "onPreBuild" event in "@netlify/plugin-nextjs" from netlify.toml 11:59:03 PM: at validateNextUsage (/.netlify/plugins/node_modules/@netlify/plugin-nextjs/helpers/validateNextUsage.js:15:12) 11:59:03 PM: at onPreBuild (/.netlify/plugins/node_modules/@netlify/plugin-nextjs/index.js:32:5) 11:59:03 PM: ​ 11:59:03 PM: Resolved config 11:59:03 PM: build: 11:59:03 PM: command: next build 11:59:03 PM: commandOrigin: config 11:59:03 PM: environment: 11:59:03 PM: - FACEBOOK_APP_ID 11:59:03 PM: - FACEBOOK_APP_SECRET 11:59:03 PM: - GATSBY_STRIPE_PK 11:59:03 PM: - NEXT_PUBLIC_FIREBASE_API_KEY 11:59:03 PM: - NEXT_PUBLIC_FIREBASE_APPID 11:59:03 PM: - NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN 11:59:03 PM: - NEXT_PUBLIC_FIREBASE_DATABASE_URL 11:59:03 PM: - NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID 11:59:03 PM: - NEXT_PUBLIC_FIREBASE_PROJECT_ID 11:59:03 PM: - NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET 11:59:03 PM: - NEXT_PUBLIC_STRAPI 11:59:03 PM: - NEXT_PUBLIC_STRAPI_DEV 11:59:03 PM: - NEXT_PUBLIC_STRAPI_FETCH 11:59:03 PM: - NEXT_PUBLIC_STRAPI_PROD 11:59:03 PM: - STRAPI_API 11:59:03 PM: - CYPRESS_CACHE_FOLDER 11:59:03 PM: ignore: git diff --quiet $CACHED_COMMIT_REF $COMMIT_REF . ../ 11:59:03 PM: publish: /opt/build/repo/.next 11:59:03 PM: publishOrigin: config 11:59:03 PM: plugins: 11:59:03 PM: - inputs: {} 11:59:03 PM: origin: config 11:59:03 PM: package: '@netlify/plugin-nextjs' 11:59:04 PM: Caching artifacts 11:59:04 PM: Started saving node modules 11:59:04 PM: Finished saving node modules 11:59:04 PM: Started saving build plugins 11:59:04 PM: Finished saving build plugins 11:59:04 PM: Started saving yarn cache 11:59:29 PM: Finished saving yarn cache 11:59:29 PM: Started saving pip cache 11:59:29 PM: Finished saving pip cache 11:59:29 PM: Started saving emacs cask dependencies 11:59:29 PM: Finished saving emacs cask dependencies Here is my package.json file: { "name": "@minimal/minimal-kit-react", "author": "minimals.cc", "version": "2.6.0", "private": true, "scripts": { "dev": "next dev -p 3222", "build": "next build", "start": "next start" }, "dependencies": { "@apollo/client": "^3.4.16", "@auth0/auth0-spa-js": "1.18", "@emotion/cache": "^11.4.0", "@emotion/react": "^11.4.1", "@emotion/server": "^11.4.0", "@emotion/styled": "^11.3.0", "@fontsource/alata": "^4.5.0", "@fontsource/barlow": "^4.5.0", "@fontsource/inter": "^4.5.0", "@fontsource/karla": "^4.5.0", "@fontsource/poppins": "^4.5.0", "@fontsource/public-sans": "^4.5.0", "@fontsource/raleway": "^4.5.0", "@fullcalendar/daygrid": "^5.9.0", "@fullcalendar/interaction": "^5.9.0", "@fullcalendar/list": "^5.9.0", "@fullcalendar/react": "^5.9.0", "@fullcalendar/timegrid": "^5.9.0", "@fullcalendar/timeline": "^5.9.0", "@hookform/devtools": "^4.0.1", "@hookform/resolvers": "^2.8.0", "@iconify/icons-ant-design": "^1.1.0", "@iconify/icons-eva": "^1.1.0", "@iconify/icons-ic": "^1.1.10", "@iconify/icons-simple-icons": "^1.1.46", "@material-ui/core": "^4.11.0", "@material-ui/data-grid": "^4.0.0-alpha.21", "@material-ui/icons": "^4.11.2", "@material-ui/lab": "^4.0.0-alpha.56", "@mui/icons-material": "^5.0.0", "@mui/lab": "^5.0.0-alpha.47", "@mui/material": "^5.0.0", "@mui/styles": "^5.0.0", "@mui/utils": "^5.0.0", "@mui/x-data-grid": "^5.0.0-beta.1", "@react-pdf/renderer": "^2.0.19", "@reduxjs/toolkit": "^1.6.1", "@stripe/react-stripe-js": "^1.5.0", "@stripe/stripe-js": "^1.18.0", "@testing-library/jest-dom": "^5.14.1", "@testing-library/react": "^12.1.0", "@testing-library/user-event": "^13.2.1", "@turf/bbox": "^6.5.0", "amazon-cognito-identity-js": "^5.1.0", "animejs": "^3.2.1", "apexcharts": "^3.28.3", "autosuggest-highlight": "^3.1.1", "axios": "^0.21.4", "axios-mock-adapter": "^1.20.0", "change-case": "^4.1.2", "d3-array": "^3.0.2", "d3-scale": "^4.0.0", "date-fns": "^2.24.0", "deck.gl": "^8.5.8", "dotenv": "^10.0.0", "draft-js": "^0.11.7", "draftjs-to-html": "^0.9.1", "emoji-mart": "^3.0.0", "firebase": "^8.10.0", "formik": "^2.2.9", "framer-motion": "^4.1.17", "fs": "^0.0.1-security", "graphql": "^15.7.1", "highlight.js": "^11.3.1", "history": "^5.0.1", "i18next": "^20.6.1", "i18next-browser-languagedetector": "^6.1.2", "immutable": "^4.0.0-rc.14", "jsonwebtoken": "^8.5.1", "jwt-decode": "^3.1.2", "lazysizes": "^5.3.2", "lodash": "^4.17.21", "lowlight": "^2.4.0", "madge": "^5.0.1", "mapbox-gl": "^2.4.1", "next": "^11.1.2", "notistack": "^1.0.6-next.3", "nprogress": "^0.2.0", "numeral": "^2.0.6", "pnp-webpack-plugin": "^1.7.0", "process": "^0.11.10", "prop-types": "^15.7.2", "react": "17.0.2", "react-apexcharts": "^1.3.9", "react-beautiful-dnd": "^13.1.0", "react-copy-to-clipboard": "^5.0.4", "react-dom": "17.0.2", "react-draft-wysiwyg": "^1.14.7", "react-dropzone": "^11.4.0", "react-helmet-async": "^1.1.2", "react-highlight": "^0.14.0", "react-hook-form": "^7.15.3", "react-i18next": "^11.12.0", "react-image-lightbox": "^5.1.4", "react-infinite-scroll-component": "^6.1.0", "react-intersection-observer": "^8.32.1", "react-lottie": "^1.2.3", "react-map-gl": "^6.1.17", "react-markdown": "^7.1.0", "react-quill": "^2.0.0-beta.4", "react-redux": "^7.2.5", "react-resize-aware": "^3.1.1", "react-scripts": "^4.0.1", "react-scroll": "^1.8.4", "react-slick": "^0.28.0", "react-spring": "^9.2.4", "redux": "^4.1.1", "redux-persist": "^6.0.0", "rehype-highlight": "^5.0.0", "rehype-raw": "^6.1.0", "simplebar": "^5.3.5", "simplebar-react": "^2.3.5", "slick-carousel": "^1.8.1", "stylis": "^4.0.10", "stylis-plugin-rtl": "^2.0.2", "typescript": "^4.3.5", "uuid": "^8.3.2", "worker-loader": "^3.0.8", "yup": "^0.32.9" }, "devDependencies": { "@babel/core": "^7.15.8", "@babel/eslint-parser": "^7.15.4", "@babel/preset-react": "^7.14.5", "@iconify/icons-fa-solid": "^1.1.1", "@iconify/react": "^3.0.1", "@netlify/plugin-nextjs": "^4.0.0-beta.5", "@types/node": "^16.7.13", "@typescript-eslint/eslint-plugin": "^4.31.0", "@typescript-eslint/parser": "^4.31.0", "eslint": "^7.32.0", "eslint-config-airbnb": "^18.2.1", "eslint-config-airbnb-typescript": "^14.0.0", "eslint-config-prettier": "^8.3.0", "eslint-config-wesbos": "2.1.0", "eslint-plugin-html": "^6.1.2", "eslint-plugin-import": "^2.24.2", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-prettier": "^4.0.0", "eslint-plugin-react": "^7.25.1", "eslint-plugin-react-hooks": "^4.2.0", "graphql": "latest", "prettier": "^2.3.2", "typescript": "^4.4.2" } } Here is my netlify.toml: [build] publish = ".next" [[plugins]] package = "@netlify/plugin-nextjs" A: I had this same issue. Removing the @netlify/plugin-nextjs from the plugins tab on Netlify fixed the issue for me. I removed the plugin and triggered a new deploy. A: I had the same issue and I resolved it by updating the plugin from the plugins tab in Netlify. A: In my case, the solution was to disable the plugin, and then re-enable it. Disabling the plugin broke my site temporarily because it's needed to run Next.js, but it was the only way I could get my deploy to succeed. Other things I tried that did not work: * *Re-building node_modules *Updating package-lock.json *Triggering a re-deploy without cache A: If you are using a monorepo to fix this issue go to the deploy settings of your site and under build settings change the publish directory to [subdir]/.next where [subdir] is the sub directory you have your next project in. After that clear change and deploy again A: I have faced the same issues. I tried adding the NETLIFY_NEXT_PLUGIN_SKIP= "TRUE"to the environment variables and it worked for me A: 1st in your project folder cmd or git bash run (yarn build) then go to the netlify build setting and change (Build command: next build) this process is work for me A: remove the netlify.toml file and let netlify build it with the default npm run build A: I also faced the same issue. There is something wrong in @netlify/plugin-nextjs plugin latest version 4.0 Try doing this and this worked for me. In netlify, under your project, do this. Site Settings -> Plugins -> Next.js Runtime -> click Change version and select version 3. NextJs plugin version change screenshot And redeploy the site.
{ "language": "en", "url": "https://stackoverflow.com/questions/69831067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Change NSTabViewController NSSegmentedControl In 10.10 Apple introduced some updates on AppKit with Storyboards and a few classes. One of those is NSTabViewController. In the WWDC Session 212 the presenter showed some properties of the class. Supposedly, the default NSSegmentedControl could be modified, or, setting tabStyle to NSTabViewControllerTabStyleUnspecified could enable us to modify the tabs style. The problem is that segmentedControl doesn't appear to be an available property on the SDK. Maybe it didn't made it to release? How can we change the style without it? My goal was to implement something like the Xcode 6 left tab. A: The way to do this is to create a tabless tab view and a custom segmented control whose action changes tabs inyour tab view. You can fill a duplicate bug report at bugreport.apple.com: * *rdar://34206798 NSTabViewController.h documentation is outdated *rdar://34206839 NSTabViewController should provide a way to customise its NSSegmentedControl
{ "language": "en", "url": "https://stackoverflow.com/questions/26790657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to build and Install TAGLIB in Codeblocks I am struggling to create a program which embeds song lyrics in *.mp3 files using C++ programming for my ongoing project. After searching, I found a library named "TAGLIB" that can process ID3v2.3 standard metadata. According to the LIBTAG installation guide, I ran CMAKE and configured liked this image and this image and build with mingw C:\Desktop\taglib> mingw32-make and C:\Desktop\taglib> mingw32-make install I got this folder C:\Program Files (x86)\taglib having contents inside it, including, bin\libtag.dll bin\libtag_c.dll bin\libtag_c.dll include\*.h files lib\pkgconfig\taglib.pc lib\pkgconfig\taglib_c.pc lib\libtag.a lib\libtag.dll.a lib\libtag_c.dll.a In Codeblocks, I linked libtag.a, libtag.dll.a and libtag_c.dll.a and configured search directories to C:\Program Files (x86)\taglib and did same to the current project. But compiler gives this type of error for]many times undefined reference to _imp___ZN6TagLib6StringC1EPKcNS0_4TypeE'| when I tried to compile example codes provided with library. Then I used GCC to compile code. But this time no luck.. C:\Program Files (x86)\taglib>gcc -o f.exe framelist.cpp -L"C:/Program Files (x86)/taglib/lib/" -libta.a -I"C:/Program Files (x86)/taglib/include/taglib" Getting this error: ` framelist.cpp:32:10: error: #include expects "FILENAME" or <FILENAME> #include C:/Program Files (x86)/taglib/include/taglib/id3v2tag.h> ^ framelist.cpp: In function 'int main(int, char**)': framelist.cpp:59:23: error: invalid use of incomplete type 'class TagLib::ID3v2: :Tag' << id3v2tag->header()->majorVersion() ^ In file included from framelist.cpp:30:0: C:/Program Files (x86)/taglib/include/taglib/mpegfile.h:37:27: note: forward dec laration of 'class TagLib::ID3v2::Tag' namespace ID3v2 { class Tag; class FrameFactory; } ^ framelist.cpp:61:23: error: invalid use of incomplete type 'class TagLib::ID3v2: :Tag' << id3v2tag->header()->revisionNumber() ^ In file included from framelist.cpp:30:0: C:/Program Files (x86)/taglib/include/taglib/mpegfile.h:37:27: note: forward dec laration of 'class TagLib::ID3v2::Tag' namespace ID3v2 { class Tag; class FrameFactory; } ^ framelist.cpp:63:23: error: invalid use of incomplete type 'class TagLib::ID3v2: :Tag' << id3v2tag->header()->tagSize() ^ In file included from framelist.cpp:30:0: C:/Program Files (x86)/taglib/include/taglib/mpegfile.h:37:27: note: forward dec laration of 'class TagLib::ID3v2::Tag' namespace ID3v2 { class Tag; class FrameFactory; } ^ framelist.cpp:67:14: error: 'TagLib::ID3v2::FrameList' has not been declared ID3v2::FrameList::ConstIterator it = id3v2tag->frameList().begin(); ^ framelist.cpp:68:13: error: 'it' was not declared in this scope for(; it != id3v2tag->frameList().end(); it++) ^ framelist.cpp:68:27: error: invalid use of incomplete type 'class TagLib::ID3v2: :Tag' for(; it != id3v2tag->frameList().end(); it++) ^ In file included from framelist.cpp:30:0: C:/Program Files (x86)/taglib/include/taglib/mpegfile.h:37:27: note: forward dec laration of 'class TagLib::ID3v2::Tag' namespace ID3v2 { class Tag; class FrameFactory; } ^ ` As you can understand, I'm fairly new to adding external library, help me figuring out, How can I properly install "LIBTAG" to start coding in Codeblocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/52026669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove c__DisplayClass from code coverage I'm getting c__DisplayClass files appearing in my code coverage analysis that appear to be auto generated code from closures (see this link). My question is, HOW do you remove this auto generated code from code coverage results? A: After some research, I've discovered you can make use of a .runsettings file (documentation). You can customize your code coverage results within this file like so: <CodeCoverage> <ModulePaths> <Exclude></Exclude> </ModulePaths> <Functions> <Exclude> <Function>.*c__DisplayClass.*</Function> </Exclude> </Functions> </CodeCoverage> This gave me the results I wanted. All auto generated c__DisplayClass functions are excluded from the results. A: Just to add to Anthony's excellent answer, I had lots of auto generated rubbish which can be hidden neatly with the following .runsettings file: <CodeCoverage> <ModulePaths> <Exclude></Exclude> </ModulePaths> <Functions> <Exclude> <Function>.*&lt;*&gt;.*</Function> </Exclude> </Functions> </CodeCoverage> Note that &lt; and &gt; are the triangular brackets < and > so this should (in my experience) cover all automatically generated code in the coverage results.
{ "language": "en", "url": "https://stackoverflow.com/questions/31568270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: calling non exported functions from dll using c++ console app i have a dll with COM METHOD functions i want to call i know the prototype and parameters of each fun. and also return type can anyone help me in calling these functions in details please because i am a beginner in this part i use vs2010 thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/5998884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP to WebService I want to connect to a webservice. I have the following code to test connecting to the service; $soapURL = 'http://xxx.xxx.xx.xx4/wsdl/wsdl' ; $soapParameters = Array('login' => "xxx", 'password' => "1234") ; $client = new SoapClient($soapURL, $soapParameters); var_dump($client->__getFunctions()); Which works fine and give me back the following; array(6) { [0]=> string(35) "CallResponse Call(Call $parameters)" [1]=> string(59) "FieldManagerResponse FieldManager(FieldManager $parameters)" [2]=> string(56) "FixScheduleResponse FixSchedule(FixSchedule $parameters)" [3]=> string(44) "GeocodeResponse Geocode(Geocode $parameters)" [4]=> string(59) "ShowCallInfoResponse ShowCallInfo(ShowCallInfo $parameters)" [5]=> string(59) "WorkScheduleResponse WorkSchedule(WorkSchedule $parameters)" } I want to call the ShowCallinfo function which has 2 parameters, an integer 0, and a string 'CA12345' - and should return a set of data; Latest combination I have tried (immediately after the other code) are; $result = $client->ShowCallInfo(0,'CA212345'); Which results in a SoapFault exception: [HTTP] Not Found in A: The SoapFault you're facing is not due to the parameters but due to the fact that the SoapAction address is not reachable from your network or is simply invalid. * *You should first check the url in <soap:address location="{url}" /> in the WSDL and ensure that it is reachable, *You should then use a WSDL to php generator that will ease you the task of sending the request. Indeed you won't have to wonder about soap as you'll only deal with objects or at least you'll know exactly how to send the parameters. I can only advise you to try the PackageGenerator as it's mine but you can find other project of this type out there
{ "language": "en", "url": "https://stackoverflow.com/questions/35204569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.2 force_ssl except on landing page I want to enforce SSL on all routes except my landing page. I tried setting force_ssl in all my controllers, and for the controller that contains root, I did: force_ssl :except => :index However, after I deployed this to my staging app on Heroku, my app is still enforcing ssl on the home page. Is there something else that needs to be done to disable ssl on that specific route? A: rack-ssl-enforcer gem will help you
{ "language": "en", "url": "https://stackoverflow.com/questions/10877976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamically load coordinates to google map from database as I go through with my studies on web dev and ajax; i came across with this template that has a map(google map) on it. the script for loading the map is placed on an external .js file here is the code. function LoadMapProperty() { var locations = new Array( [14.4718329, 121.0086019], [14.530026, 120.996063], [14.4737421, 121.0032217], [14.5075023, 120.993699], [14.5075023, 120.993699], [14.471466, 121.0277539], [14.4779355, 120.99883], [14.4731542, 121.0037827], [14.4966062, 120.9884816], [14.4926289, 120.98628], [14.4779355, 120.99883], [14.4663681, 121.0085009], [14.4965154, 120.9895496], [14.527833, 120.996831], [14.4849982, 120.9869173], [14.5016121, 120.9960593], [14.4745177, 120.9987967], [14.4745177, 120.9987967], [14.5292715, 120.9960647], [14.4798793, 120.9983465], [14.530001, 120.995553], [14.4745177, 120.9987967], [14.4745177, 120.9987967], [14.5292715, 120.9960647], [14.4901257, 120.9883528], [14.4799374, 120.9978811], [14.4678564, 120.9801271], [14.4745177, 120.9987967], [14.503642, 120.994828], [14.5002999, 120.9973589], [14.5292715, 120.9960647], [14.51565, 120.9960106] ); var markers = new Array(); var mapOptions = { center: new google.maps.LatLng(14.4718329, 121.0086019), zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false }; var map = new google.maps.Map(document.getElementById('property-map'), mapOptions); $.each(locations, function(index, location) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(location[0], location[1]), map: map, icon: 'http://html.realia.byaviators.com/assets/img/marker-transparent.png' }); var myOptions = { content: '<div class="infobox"><div class="image"><img src="http://html.realia.byaviators.com/assets/img/tmp/property-tiny-1.png" alt=""></div><div class="title"><a href="detail.html">1041 Fife Ave</a></div><div class="area"><span class="key">Area:</span><span class="value">200m<sup>2</sup></span></div><div class="price">€450 000.00</div><div class="link"><a href="detail.html">View more</a></div></div>', disableAutoPan: false, maxWidth: 0, pixelOffset: new google.maps.Size(-146, -190), zIndex: null, closeBoxURL: "", infoBoxClearance: new google.maps.Size(1, 1), position: new google.maps.LatLng(location[0], location[1]), isHidden: false, pane: "floatPane", enableEventPropagation: false }; marker.infobox = new InfoBox(myOptions); marker.infobox.isOpen = false; var myOptions = { draggable: true, content: '<div class="marker"><div class="marker-inner"></div></div>', disableAutoPan: true, pixelOffset: new google.maps.Size(-21, -58), position: new google.maps.LatLng(location[0], location[1]), closeBoxURL: "", isHidden: false, // pane: "mapPane", enableEventPropagation: true }; marker.marker = new InfoBox(myOptions); marker.marker.open(map, marker); markers.push(marker); google.maps.event.addListener(marker, "click", function (e) { var curMarker = this; $.each(markers, function (index, marker) { // if marker is not the clicked marker, close the marker if (marker !== curMarker) { marker.infobox.close(); marker.infobox.isOpen = false; } }); if(curMarker.infobox.isOpen === false) { curMarker.infobox.open(map, this); curMarker.infobox.isOpen = true; map.panTo(curMarker.getPosition()); } else { curMarker.infobox.close(); curMarker.infobox.isOpen = false; } }); }); } function LoadMap() { var locations = new Array( [14.4718329, 121.0086019], [14.530026, 120.996063], [14.4737421, 121.0032217], [14.5075023, 120.993699], [14.5075023, 120.993699], [14.471466, 121.0277539], [14.4779355, 120.99883], [14.4731542, 121.0037827], [14.4966062, 120.9884816], [14.4926289, 120.98628], [14.4779355, 120.99883], [14.4663681, 121.0085009], [14.4965154, 120.9895496], [14.527833, 120.996831], [14.4849982, 120.9869173], [14.5016121, 120.9960593], [14.4745177, 120.9987967], [14.4745177, 120.9987967], [14.5292715, 120.9960647], [14.4798793, 120.9983465], [14.530001, 120.995553], [14.4745177, 120.9987967], [14.4745177, 120.9987967], [14.5292715, 120.9960647], [14.4901257, 120.9883528], [14.4799374, 120.9978811], [14.4678564, 120.9801271], [14.4745177, 120.9987967], [14.503642, 120.994828], [14.5002999, 120.9973589], [14.5292715, 120.9960647], [14.51565, 120.9960106] ); var markers = new Array(); var mapOptions = { center: new google.maps.LatLng(14.4718329, 121.0086019), zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); $.each(locations, function(index, location) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(location[0], location[1]), map: map, icon: 'http://html.realia.byaviators.com/assets/img/marker-transparent.png' }); var myOptions = { content: '<div class="infobox"><div class="image"><img src="http://html.realia.byaviators.com/assets/img/tmp/property-tiny-1.png" alt=""></div><div class="title"><a href="detail.html">1041 Fife Ave</a></div><div class="area"><span class="key">Area:</span><span class="value">200m<sup>2</sup></span></div><div class="price">€450 000.00</div><div class="link"><a href="detail.html">View more</a></div></div>', disableAutoPan: false, maxWidth: 0, pixelOffset: new google.maps.Size(-146, -190), zIndex: null, closeBoxURL: "", infoBoxClearance: new google.maps.Size(1, 1), position: new google.maps.LatLng(location[0], location[1]), isHidden: false, pane: "floatPane", enableEventPropagation: false }; marker.infobox = new InfoBox(myOptions); marker.infobox.isOpen = false; var myOptions = { draggable: true, content: '<div class="marker"><div class="marker-inner"></div></div>', disableAutoPan: true, pixelOffset: new google.maps.Size(-21, -58), position: new google.maps.LatLng(location[0], location[1]), closeBoxURL: "", isHidden: false, // pane: "mapPane", enableEventPropagation: true }; marker.marker = new InfoBox(myOptions); marker.marker.open(map, marker); markers.push(marker); google.maps.event.addListener(marker, "click", function (e) { var curMarker = this; $.each(markers, function (index, marker) { // if marker is not the clicked marker, close the marker if (marker !== curMarker) { marker.infobox.close(); marker.infobox.isOpen = false; } }); if(curMarker.infobox.isOpen === false) { curMarker.infobox.open(map, this); curMarker.infobox.isOpen = true; map.panTo(curMarker.getPosition()); } else { curMarker.infobox.close(); curMarker.infobox.isOpen = false; } }); }); } function InitMap() { google.maps.event.addDomListener(window, 'load', LoadMap); google.maps.event.addDomListener(window, 'load', LoadMapProperty); } I am new with this ajax thing and as i said just trying to learn things. as with the code you'll notice that the coordinates are bundled in an array. so my question is, Is there a way where in I can fetch some coordinates from my database and put them in this .js script? any links on other website, suggestions or hint is much appreciated. Thank you for your time. A: Here's some code that should help you get started. function addMarkers(map, locations) { $.each(locations, function(index, location) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(location[0], location[1]), map: map, icon: 'http://html.realia.byaviators.com/assets/img/marker-transparent.png' }); var myOptions = { content: '<div class="infobox"><div class="image"><img src="http://html.realia.byaviators.com/assets/img/tmp/property-tiny-1.png" alt=""></div><div class="title"><a href="detail.html">1041 Fife Ave</a></div><div class="area"><span class="key">Area:</span><span class="value">200m<sup>2</sup></span></div><div class="price">€450 000.00</div><div class="link"><a href="detail.html">View more</a></div></div>', disableAutoPan: false, maxWidth: 0, pixelOffset: new google.maps.Size(-146, -190), zIndex: null, closeBoxURL: "", infoBoxClearance: new google.maps.Size(1, 1), position: new google.maps.LatLng(location[0], location[1]), isHidden: false, pane: "floatPane", enableEventPropagation: false }; marker.infobox = new InfoBox(myOptions); marker.infobox.isOpen = false; var myOptions = { draggable: true, content: '<div class="marker"><div class="marker-inner"></div></div>', disableAutoPan: true, pixelOffset: new google.maps.Size(-21, -58), position: new google.maps.LatLng(location[0], location[1]), closeBoxURL: "", isHidden: false, // pane: "mapPane", enableEventPropagation: true }; marker.marker = new InfoBox(myOptions); marker.marker.open(map, marker); markers.push(marker); google.maps.event.addListener(marker, "click", function(e) { var curMarker = this; $.each(markers, function(index, marker) { // if marker is not the clicked marker, close the marker if (marker !== curMarker) { marker.infobox.close(); marker.infobox.isOpen = false; } }); if (curMarker.infobox.isOpen === false) { curMarker.infobox.open(map, this); curMarker.infobox.isOpen = true; map.panTo(curMarker.getPosition()); } else { curMarker.infobox.close(); curMarker.infobox.isOpen = false; } }); }); } // Assign handlers immediately after making the request, // and remember the jqXHR object for this request var jqxhr = $.ajax( "getlocations.php" ).done(function() { addMarkers(map, locations) }); Basically, the code fetches data from the script on getlocations.php and calls addMarkers using the data (it must be returned in JSON form) in "locations". You can add parameters to the AJAX to make it more flexible, like this: $.ajax( { type: "GET", url: "getlocations.php", data: { city: "Boston", page: 1 } // or whatever parameters you need to send in the URL }).done(function() { addMarkers(map, locations) });
{ "language": "en", "url": "https://stackoverflow.com/questions/28801991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Hibernate,Primary key consist from auto generated id and foreign key as pk Welecome, i pretty new in hibernate and i have problem. Above I insert code example. Order should consist 2 primary keys id(own.auto generated pk) and other pk(also as fk from Client table) id of client whose make order. Everything work fine except that when I have added @GeneratedValue(strategy=GenerationType.AUTO) I am geting above errrors: org.hibernate.PropertyAccessException: could not set a field value by reflection setter of pl.pb.intern.test.model.Order.id at org.hibernate.property.DirectPropertyAccessor$DirectSetter.set(DirectPropertyAccessor.java:151) at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:423) at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121) at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90) at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:735) at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:727) at org.hibernate.engine.spi.CascadingAction$5.cascade(CascadingAction.java:258) at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:388) at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:331) at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:209) at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:418) at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:358) at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:334) at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:209) at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:166) at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:132) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.cascadeOnUpdate(DefaultSaveOrUpdateEventListener.java:364) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:338) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:241) at org.hibernate.event.internal.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:55) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90) at org.hibernate.internal.SessionImpl.fireUpdate(SessionImpl.java:786) at org.hibernate.internal.SessionImpl.update(SessionImpl.java:778) at org.hibernate.internal.SessionImpl.update(SessionImpl.java:774) at pl.pb.intern.test.dao.HibernateClientDAO.updateClient(HibernateClientDAO.java:34) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) Caused by: java.lang.IllegalArgumentException: Can not set long field pl.pb.intern.test.model.Order.id to org.hibernate.id.IdentifierGeneratorHelper$2 at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source) at sun.reflect.UnsafeLongFieldAccessorImpl.set(Unknown Source) at java.lang.reflect.Field.set(Unknown Source) at org.hibernate.property.DirectPropertyAccessor$DirectSetter.set(DirectPropertyAccessor.java:139) ... 67 more My entities: @Entity public class Client { @Id @GeneratedValue(strategy=GenerationType.AUTO) int id; @OnetoMany(mappedBy="client", cascade=CascadeType.ALL , fetch=FetchType.EAGER,orphanRemoval=true) List<Order> orders //other fields } @Enitity public classs Order { @Id @GeneratedValue(strategy=GenerationType.AUTO) int id; @Id @ManyToOne @JoinColumn( name="order_client_id",insertable=false, updatable=false) Client client; public void setId(long id) { this.id=id } public login getId() { return this.id; } } } I have reviewed hibernate docs and i did't find any contraindications against connection auto generated primary key and foreign key as pk. What am doing wrong in this example?? A: On the composite primary key issue, see JPA composite primary key From the exception stack trace, it seems the method signatures of your Order.getId()/Order.setId() have the wrong signatures. According to JavaBean conventions, since Order.id is an int, setId() should take an int parameter and getId() should return an int accordingly. Or, you can change the type of Order.id to long since getId()/setId() already make use of long. Also, you may wish to edit your code to fix the following typos and syntax errors: Client.java: - @OnetoMany supposed to be @OneToMany - Missing end-of-line semicolon on List<Order> orders Order.java - Missing end-of-line semicolon on this.id = id in Order.setId
{ "language": "en", "url": "https://stackoverflow.com/questions/19072137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I was working on my application but suddenly i got table does not exist in all my tables Hey guy i was working on my app but suddenly i got an error says table does not exist in engine. When i went to see in my database i found out that all my tables are not working for w/e reason but as you can see (in the picture below) it says it does exist, i already checked if i have ibdata1 under C:/xampp/mysql/data/ and i found it. Please if there is any solution i can do because i have like 10 tables i cant just re-create them, it's to much work... The error is table does not exist in engine
{ "language": "en", "url": "https://stackoverflow.com/questions/59011578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIDocumentInteractionController change file name for Sharing iam using the following code to show the sharing options for PDF self.documentController = UIDocumentInteractionController(url: url) self.documentController.name = "Test name" // not working self.documentController.presentOptionsMenu(from: self.shareButton, animated: true) the problem is that I save the PDF file name with datestamp to avoid having two files with the same name, but when the share options is being shown the actual file name appears, is there is a way to show custom name instead of the actual filename (I don't want to copy the file to other place and rename it, waste of time and performance) A: In such a situation, we can create a temporary folder which can contain the same file with lastPathExtension will be document.fileExtension and we can pass this newly file path to UIDocumentInteractionController.init(url: newFileUrl) For Example: func openUnsupportedFileWithPath(documentName : String, fileurl : URL, fileExtension : String, aDocument: SILDocumentDB? = nil, sourceView: UIView? = nil) -> Void { // Create new temporary path let paths: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] var newFileUrl: String = paths.appending("/Downloads/TemporaryFolder)") newFileUrl = newFileUrl.appendingFormat("%@","\(documentName)") let destinationPathUrl : URL do { // Move newly filePath with new fileName and fileExtension destinationPathUrl = URL(fileURLWithPath: destinanewFileUrltionPath) try FileManager.default.moveItem(at: fileurl, to: destinationPathUrl) } catch { print(error) } //Pass newly filePath to UIDocumentInteractionController documentInteractionController = UIDocumentInteractionController.init(url: newFileUrl) documentInteractionController?.name = documentName documentInteractionController?.delegate = self let canPreview = documentInteractionController?.presentPreview(animated: true) if (canPreview == false) { let activityViewController = UIActivityViewController.init(activityItems: [fileurl], applicationActivities: nil) activityViewController.setValue(documentName, forKey: "subject") if ISIPAD { activityViewController.popoverPresentationController?.sourceView = sourceView ?? self.view } self.present(activityViewController, animated: true, completion: nil) } } And UIDocumentInteractionController get dismiss, remove the temporary filePath on documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) method. public func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) { documentInteractionController = nil let paths: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let filePath: String = paths.appending("/Downloads/TemporaryFolder)") let _fileManager : FileManager = FileManager.default if filePath.length > 0 { if _fileManager.fileExists(atPath: filePath) { do{ try _fileManager.removeItem(atPath: filePath) }catch let error as NSError{ print("\(error.localizedDescription)") } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/60320294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Last month's last date using Javascript I have a textbox in which I show only month and year. So when I have June 2013, and when I look for First half, then I want the previous month's date to 14th of June. So in Javascript I was simply using var currentmonth=doucument.getElementbyId("textbox"); var currentdate="01-"+currentmonth;// as earlier I had 1st to 15 of month. I want to get the last months' last date that too in a format, like "31-May-2013". I am trying to change like: currentdate= new Date(currentdate).get...//but not working A: Create date object: var currentdate = new Date("01-"+currentmonth) Set last day of month using setFullYear, getFullYear and getMonth methods: currentdate.setFullYear(test.getFullYear(), test.getMonth()+1, 0)
{ "language": "en", "url": "https://stackoverflow.com/questions/16917289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Discrepancy in the user roles(authorities) in the access token obtained from grant_type=password and grant_type=refresh_token I have a situation: Step 1: Obtained access token (grant_type=password) (A1) and also a refresh token.(RT1) Step 2: Accessed resource (R) using the token (A1) - Success Step 3:Revoked user access role for Resource R. Step 4: Obtained access token (grant_type=password) (A2) and also a refresh token.(RT2) Step 5: Accessed resource (R) using the token (A2) - Failed till here all fine.now comes the unexpected part. Step 6: Obtained new access token (grant_type=refresh_token) using RT2. Unexpectedly using this access token i was able to access resource R. During this whole flow none of the token was expired one. I see two issues here:- User roles aren't getting updated for refresh token on grant_type=password and for grant_type=refresh_token. Although access token has changed (Step 4) but refresh token remains same RT1 == RT2. hence any further usage of RT gives access token with previous roles. How do i tell spring (oauth2) to update user roles (for the newly created token's) while obtaining the access token using refresh token and also while updating RT with new roles (step4), to resolve this discrepancy. Below is the Authorization server configuration: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2" xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> <property name="userDetailsService"> <bean class="com.dummy.mc.security.service.UserDetailsServiceImpl"> <property name="userRepository" ref="userRepository" /> <property name="grantedAuthorityRepository" ref="grantedAuthorityRepository" /> </bean> </property> <property name="passwordEncoder"> <bean class="com.dummy.mc.security.password.McpmPasswordEncoder"> <property name="encodeHashAsBase64" value="true" /> </bean> </property> <property name="saltSource"> <bean class="org.springframework.security.authentication.dao.ReflectionSaltSource"> <property name="userPropertyToUse" value="salt" /> </bean> </property> </bean> <!--https://stackoverflow.com/questions/49761597/spring-oauth2-clientid-passed-in-as-username-for-password-grant-type--> <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore"> <constructor-arg ref="dataSource" /> </bean> <bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"> <property name="tokenStore" ref="tokenStore" /> <property name="supportRefreshToken" value="true" /> <property name="clientDetailsService" ref="clientDetailsService" /> <property name="reuseRefreshToken" value="false"/> </bean> <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /> <bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"> <property name="authenticationManager" ref="clientDetailAuthenticationManager" /> </bean> <!-- Authentication manager for client (not resource-owner) authentication required to protect the token endpoint URL --> <security:authentication-manager id="clientDetailAuthenticationManager"> <security:authentication-provider user-service-ref="clientDetailsUserService"/> </security:authentication-manager> <bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"> <constructor-arg ref="clientDetailsService"/> </bean> <bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="test/client" /> <property name="typeName" value="Basic" /> </bean> <security:http pattern="/oauth/token" create-session="stateless" use-expressions="true" authentication-manager-ref="authenticationManager"> <security:intercept-url pattern="/oauth/token" access="isAuthenticated()" /> <security:anonymous enabled="false" /> <security:http-basic entry-point-ref="clientAuthenticationEntryPoint" /> <!-- include this only if you need to authenticate clients via request parameters --> <security:custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <authorization-server client-details-service-ref="clientDetailsService" xmlns="http://www.springframework.org/schema/security/oauth2" token-services-ref="tokenServices" > <authorization-code /> <implicit /> <refresh-token /> <client-credentials /> <password authentication-manager-ref="authenticationManager" /> </authorization-server> <!-- <oauth:resource-server id="resourceFilter" token-services-ref="tokenServices" authentication-manager-ref="authenticationManager" /> --> <security:authentication-manager id="authenticationManager"> <security:authentication-provider ref="daoAuthenticationProvider"> </security:authentication-provider> </security:authentication-manager> <oauth:client-details-service id="clientDetailsService"> <oauth:client client-id="core-api" secret="secret" authorized-grant-types="password,client_credentials,refresh_token" scope="read" resource-ids="api-core" access-token-validity="36000" authorities="ROLE_CLIENT,ROLE_TRUSTED_CLIENT" /> </oauth:client-details-service> </beans> Resource Server Configuration: <mvc:default-servlet-handler /> <mvc:annotation-driven/> <security:global-method-security pre-post-annotations="enabled"/> <!-- TODO: make an access denied view that tells me something useful --> <security:http use-expressions="true" entry-point-ref="oauthAuthenticationEntryPoint"> <security:intercept-url pattern="/**" access="isFullyAuthenticated() and hasRole('api.core')" /> <security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> <security:anonymous /> </security:http> <!-- It's just a "feature" of the Spring Security that an authentication manager is mandatory. so install an empty one because it isn't used at run time --> <security:authentication-manager/> <oauth:resource-server id="resourceServerFilter" token-services-ref="tokenServices" resource-id="api-core"/> <bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices" > <property name="tokenStore" ref="tokenStore" /> </bean> <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore"> <constructor-arg ref="dataSource" /> </bean> <bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="test/client" /> <property name="typeName" value="Basic" /> </bean> <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /> A: Authorities are loaded when access token its required. Using jdbc store, authorities are saved to OAUTH_ACCESS_TOKEN table, AUTHENTICATION column. When refresh token its required, authorities are loaded from database. If authorities changed after access token was required, you will have to implement custom token store. Take a look to org.springframework.security.oauth2.provider.token.store.JdbcTokenStore, and extend from it.
{ "language": "en", "url": "https://stackoverflow.com/questions/52073349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: useEffect hook not firing on orientation change I am trying to change the height of a container, when in mobile landscape mode only. I am playing around in the developer tools to swap the orientation of a mobile device but it only works on the first render. I am new to react hooks so not sure if I am implementing it right. The idea is that I am testing that once in landscape, if it's on mobile the height should be less than 450px (which is the check I am doing for the if statement) Could someone point me in the right direction, please? Thanks! const bikeImageHeight = () => { const windowViewportHeight = window.innerHeight; const isLandscape = window.orientation === 90 || window.orientation === -90; let bikeImgHeight = 0; if (windowViewportHeight <= 450 && isLandscape) { bikeImgHeight = windowViewportHeight - 50; } return bikeImgHeight; }; useEffect(() => { bikeImageHeight(); window.addEventListener("resize", bikeImageHeight); return () => { window.removeEventListener("resize", bikeImageHeight); }; }, []); A: The useEffect hook is not expected to fire on orientation change. It defines a callback that will fire when the component re-renders. The question then is how to trigger a re-render when the screen orientation changes. A re-render occurs when there are changes to a components props or state. Lets make use of another related stackoverflow answer to build a useWindowDimensions hook. This allows us to hook into the windows size as component state so any changes will cause a re-render. useWindowDimensions.js import { useState, useEffect } from 'react'; function getWindowDimensions() { const { innerWidth: width, innerHeight: height } = window; return { width, height }; } export default function useWindowDimensions() { const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions()); useEffect(() => { function handleResize() { setWindowDimensions(getWindowDimensions()); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); return windowDimensions; } You can then use that hook in your component. Something like: BikeImage.js import React from 'react' import useWindowDimensions from './useWindowDimensions' export default () => { const windowDimensions = useWindowDimensions(); // Define these helper functions as you like const width = getImageWidth(windowDimensions.width) const height = getImageHeight(windowDimensions.height) // AppImage is a component defined elsewhere which takes // at least width, height and src props return <AppImage width={width} height={height} src="..." .../> } A: Here is a custom hook that fires on orientation change, import React, {useState, useEffect} from 'react'; // Example usage export default () => { const orientation = useScreenOrientation(); return <p>{orientation}</p>; } function useScreenOrientation() { const [orientation, setOrientation] = useState(window.screen.orientation.type); useEffect(() => { const handleOrientationChange= () => setOrientation(window.screen.orientation.type); window.addEventListener('orientationchange', handleOrientationChange); return () => window.removeEventListener('orientationchange', handleOrientationChange); }, []); return orientation; } Hope this takes you to the right direction. A: You need to trigger a re-render, which can be done by setting state inside of your bikeImageHeight. const [viewSize, setViewSize] = useState(0) const bikeImageHeight = () => { const windowViewportHeight = window.innerHeight; const isLandscape = window.orientation === 90 || window.orientation === -90; let bikeImgHeight = 0; if (windowViewportHeight <= 450 && isLandscape) { bikeImgHeight = windowViewportHeight - 50; } setViewSize(bikeImgHeight) return bikeImgHeight; }; And per the comments conversation, here's how you'd use debounce: function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; const YourComponent = () => { const bikeImageHeight = () => { const windowViewportHeight = window.innerHeight; const isLandscape = window.orientation === 90 || window.orientation === -90; let bikeImgHeight = 0; if (windowViewportHeight <= 450 && isLandscape) { bikeImgHeight = windowViewportHeight - 50; } setViewSize(bikeImgHeight) return bikeImgHeight; }; const debouncedBikeHeight = debounce(bikeImageHeight, 200) useEffect(() => { bikeImageHeight(); window.addEventListener("resize", debouncedBikeHeight); return () => { window.removeEventListener("resize", debouncedBikeHeight); }; }, []); return <div>some jsx</div> } Example debounce taken from here: https://davidwalsh.name/javascript-debounce-function
{ "language": "en", "url": "https://stackoverflow.com/questions/58398109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }