id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23530800
I have a variable defined in a lambda layer and when we have multiple calls to that code , the variable value from one execution is preserved and used by subsequent run. Is there any way to make each lambda execution to reset all variable and not to use any variable value from previous run. A: I suspect this is nothing to do with Lambda Layers and everything to do with container reuse (a performance feature of Lambda). Anything declared outside your handler function will persist across warm restarts. For more, see AWS Lambda Execution Context. One possible way to test for cold/warm startup, and reset an environment, is as follows: import json import logging cache = {} cold_start = True def handler(event, context): global cold_start if cold_start: print("Cold start") cold_start = False else: print("Warm start, reset cache") cache = {} # do work here cache['name'] = 'Jason' cache['age'] = 27
doc_23530801
I've found here several advices but none of them worked. So there is an "Upload Picture" button on the web page. When I click on this button (in Chrome), it doesn't show regular context menu (inspect element etc.) but Global settings and About Flash player so I suppose it has something to do with Flash. I've tried to find an upload tag id and send keys there, but it did not worked: self.driver.find_element_by_id('SWFUpload_0').send_keys('screen.png') I'm attaching a code of the wrapper in case it helps to solve the problem. <div class="swfupload-wrapper"> <object id="SWFUpload_0" type="application/x-shockwave-flash" data="/sites/all/libraries/swfupload/swfupload.swf?preventswfcaching=1448803178493" width="185" height="15" class="swfupload"><param name="wmode" value="transparent"><param name="movie" value="/sites/all/libraries/swfupload/swfupload.swf?preventswfcaching=1448803178493"><param name="quality" value="high"><param name="menu" value="false"><param name="allowScriptAccess" value="always"><param name="flashvars" value="movieName=SWFUpload_0&amp;uploadURL=%2Fswfupload&amp;useQueryString=false&amp;requeueOnError=false&amp;httpSuccess=&amp;assumeSuccessTimeout=0&amp;params=sid%3D38372a6537633265663131316238386535363966326461366632653538616538363535%26amp%3Bfile_path%3Dfiles%252Fcars%26amp%3Bop%3Dmove_uploaded_file%26amp%3Binstance%3D%257B%2522name%2522%253A%2522field_part_pictures%2522%257D%26amp%3Bwidget%3D%257B%2522file_extensions%2522%253A%2522jpg%2520jpeg%2520png%2520gif%2522%252C%2522file_path%2522%253A%2522cars%2522%252C%2522max_filesize_per_file%2522%253A%2522%2522%252C%2522max_filesize_per_node%2522%253A%2522%2522%252C%2522file_widgets%2522%253Anull%252C%2522max_resolution%2522%253A%25220%2522%252C%2522min_resolution%2522%253A%25220%2522%252C%2522alt%2522%253A%2522%2522%252C%2522custom_alt%2522%253A0%252C%2522title%2522%253A%2522%2522%252C%2522custom_title%2522%253A0%252C%2522progress_indicator%2522%253A%2522bar%2522%252C%2522title_type%2522%253A%2522textfield%2522%252C%2522use_default_image%2522%253A0%252C%2522label%2522%253A%2522Pictures%2522%252C%2522weight%2522%253A%2522-1%2522%252C%2522description%2522%253A%2522%2522%252C%2522type%2522%253A%2522swfupload_widget%2522%252C%2522module%2522%253A%2522swfupload%2522%252C%2522list_field%2522%253A%25220%2522%252C%2522list_default%2522%253A1%252C%2522description_field%2522%253A%25220%2522%257D&amp;filePostName=field_part_pictures&amp;fileTypes=*.jpg%3B*.jpeg%3B*.png%3B*.gif&amp;fileTypesDescription=&amp;fileSizeLimit=0&amp;fileUploadLimit=0&amp;fileQueueLimit=0&amp;debugEnabled=false&amp;buttonImageURL=%2Fnode%2F4182%2F&amp;buttonWidth=185&amp;buttonHeight=15&amp;buttonText=&amp;buttonTextTopPadding=0&amp;buttonTextLeftPadding=0&amp;buttonTextStyle=color%3A%20%23000000%3B%20font-size%3A%2016pt%3B&amp;buttonAction=-110&amp;buttonDisabled=false&amp;buttonCursor=-2"></object> </div> Do you have any advices? A: As I know, selenium doesn't work with flash. So you need to use some other additional tool. A: You can use sikuli with selenium to upload the file in flash objects.
doc_23530802
all my pods are running correctly. I am trying to mount a volume on my jupyterlab (pod) using hostpath. below is my config apiVersion: apps/v1 kind: Deployment metadata: name: jupyter labels: app: jupyter spec: replicas: 1 selector: matchLabels: app: jupyter template: metadata: labels: app: jupyter spec: containers: - name: jupyter image: jupyter:1.1 ports: - containerPort: 8888 securityContext: runAsNonRoot: true runAsUser: 1000 volumeMounts: - name: mydir mountPath: /notebooks volumes: - name: mydir hostPath: # directory location on host path: /home/<myuser>/data # this field is optional type: DirectoryOrCreate The pod starts without any issues. but i dont see the notbooks which i have kept in my hostpath onto my jupyter labs and vice versa( if i save a notebook in jupyter lab it does not get saved to my hostpath). i followed the tutorial on https://kubernetes.io/docs/concepts/storage/volumes/#hostpath i want to point out that i am using the @FROM jupyter/datascience-notebook:python-3.7.6" as my docker image. i tried mounting /home/jovyan/ but it was giving me access related errors while starting the pod. so i reverted back to "/notebooks" A: It looks like an issue with how the path is being written on Windows, I see the issue reported in the references below. Solution: * *If your file is in say C: drive, it should be converted to the below /host_mnt/c/path/to/my/folder * *If the above does not work you may want to remove the "type: DirectoryOrCreate" and retry. References: https://github.com/kubernetes/kubernetes/issues/59876#issuecomment-628955935 https://github.com/docker/for-win/issues/1703#issuecomment-366701358 . A: If you are using WSL based engine on windows, the path should be /run/desktop/mnt/host/c/<folder>
doc_23530803
Is there a way to search for "th" and "em" tags in the html table? If I can search for those in my table data during the filter when the user types in the search bar, I reason that I can include them with the filtered results, and thus achieve the goal. Advice is appreciated, I am very new to JavaScript. My relevant javascript code is as follows, currently it only displays the filtered results, and not headings or subheadings: function filterTable(event) { var filter = event.target.value.toUpperCase(); var rows = document.querySelector("#multicategoryTable").rows; for (var i = 0; i < rows.length; i++) { var Col0 = rows[i].cells[0].textContent.toUpperCase(); var Col1 = rows[i].cells[1].textContent.toUpperCase(); var Col2 = rows[i].cells[2].textContent.toUpperCase(); var Col3 = rows[i].cells[3].textContent.toUpperCase(); var Col4 = rows[i].cells[4].textContent.toUpperCase(); var Col5 = rows[i].cells[5].textContent.toUpperCase(); var Col6 = rows[i].cells[6].textContent.toUpperCase(); if (Col0.indexOf(filter) > -1 || Col1.indexOf(filter) > -1 || Col2.indexOf(filter) > -1 || Col3.indexOf(filter) > -1 || Col4.indexOf(filter) > -1 || Col5.indexOf(filter) > -1 || Col6.indexOf(filter) > -1) { rows[i].style.display = ""; } //else if ( else { rows[i].style.display = "none"; } } } document.querySelector('#myInput').addEventListener('keyup', filterTable, false);
doc_23530804
project.Forms.AddNew.DB.ItemsPOJO@5aa434 How can I get the actual countries names from the database instead of values like the above? The classes look as follows: The POJO class: @Entity(name = "InitialDBItems") public class InitialDBItemsPOJO implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int countriesListID; private String countriesList; public String getCountriesList() { return countriesList; } public void setCountriesList(String countriesList) { this.countriesList = countriesList; } public int getCountriesListID() { return countriesListID; } public void setCountriesListID(int countriesListID) { this.countriesListID = countriesListID; } } The countries array that gets persisted into the database: public class InitialDBItems { static InitialDBItemsPOJO initialDBItemsPOJO = new InitialDBItemsPOJO(); public static void persistCountries() { String[] countriesList = { "Afghanistan", "Albania", "Algeria", // More countries }; for (String c : countriesList) { initialDBItemsPOJO.setCountriesList(c); new ManageItems().addItems(initialDBItemsPOJO); System.out.println(c); } } How I get the countries from the database: public static ObservableList<InitialDBItemsPOJO> retrieveCountriesList() { ObservableList<InitialDBItemsPOJO> data; List countriesListListItems; String countriesListListItemsQuery = "from InitialDBItems"; data = FXCollections.observableArrayList(); countriesListListItems = new ManageItems().listItems(countriesListListItemsQuery); for (Iterator iterator = countriesListListItems.iterator(); iterator.hasNext();) { InitialDBItemsPOJO countriesListListItemsIt = (InitialDBItemsPOJO) iterator.next(); data.add(countriesListListItemsIt); } return data; } } Hope you can help. Thank you all in advance. A: project.Forms.AddNew.DB.ItemsPOJO@5aa434 is the value of the default toString(); of your entity InitialDBItemsPOJO an easy work around is to override it @Entity(name = "InitialDBItems") public class InitialDBItemsPOJO implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int countriesListID; private String countriesList; public String getCountriesList() { return countriesList; } public void setCountriesList(String countriesList) { this.countriesList = countriesList; } public int getCountriesListID() { return countriesListID; } public void setCountriesListID(int countriesListID) { this.countriesListID = countriesListID; } public String toString(){ return countriesList; } } or public static ObservableList retrieveCountriesList() { ObservableList<InitialDBItemsPOJO> data; List countriesListListItems; String countriesListListItemsQuery = "from InitialDBItems"; data = FXCollections.observableArrayList(); countriesListListItems = new ManageItems().listItems(countriesListListItemsQuery); for (Iterator iterator = countriesListListItems.iterator(); iterator.hasNext();) { InitialDBItemsPOJO countriesListListItemsIt = (InitialDBItemsPOJO) iterator.next(); data.add(countriesListListItemsIt.getCountriesList()); } return data; }
doc_23530805
For example, some psuedo code: ARRAY = [['1', '2'], ['3', '4']] USER_MADE_ARRAY = input('type in numbers.') #print(USER_MADE_ARRAY) #>>>['1', '3', '2'] #if USER_MADE_ARRAY == the value of any of the elements in ARRAY[row 0]: # USER_MADE_ARRAY[elements equal to the values in ARRAY[row 0]] = "Bob" #print(USER_MADE_ARRAY) #>>>['Bob', '3', 'Bob'] #And so on... I just don't understand this. A: I think you want a list comprehension like: user_made_array = ["Bob" if item in array[0] else item for item in user_made_array] (the uppercase was a bit wearing...) Without much more information it's hard to see how to generalise this; it's not at all clear what you're trying to achieve. However, you could do something like: replace = {'1': 'Bob', '2': 'Bob'} user_made_array = [replace.get(item, item) for item in user_made_array] If you have a list of words the same length as array, you can build replace with zip: names = ['Bob', 'Colin'] replace = {} for name, nums in zip(names, array): replace.update({num: name for num in nums}) But this is really just guessing, because you haven't included much information in your question.
doc_23530806
package com.zimperium.server.phishing.services; //all my imports @Slf4j @Service @ConditionalOnProperty(value="urlcache.enabled", matchIfMissing=true, havingValue="true") public class UrlCacheClient { private Cache<String, Boolean> cache; private String cache_name = "ReceivedUrls"; //Constructor: public UrlCacheClient() { // Begin implementing Cache CachingProvider mycachingProvider = Caching.getCachingProvider(); CacheManager mycacheManager = mycachingProvider.getCacheManager(); //configure the cache MutableConfiguration<String, Boolean> config = new MutableConfiguration<String, Boolean>() .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.HOURS, 72))) .setStatisticsEnabled(true) .setManagementEnabled(true) .setTypes(String.class, Boolean.class) ; // Get or Create: try { Iterable<String> existings_caches = mycacheManager.getCacheNames(); log.info("Existing Caches: {}", existings_caches); if (Iterables.contains(existings_caches, cache_name)) { cache = mycacheManager.getCache(cache_name); log.info("Cache: {} Fetched (Already Existed).", cache_name); } else { cache = mycacheManager.createCache(cache_name, config); log.info("Cache: {} Created!", cache_name); } } catch(CacheException e) { log.info("Cache not available. Error: {}", e); } }; //Methods: public Boolean isNewUrl(String url) { Boolean isnew = true; try { // If url exists: if (cache.containsKey(url)) { isnew = false; //if found in cache, not new xD this.datadog_client.Increment("CacheUrl.Hit"); } else { this.datadog_client.Increment("CacheUrl.Miss"); }; cache.put(url, true); //We store on Cache for next time } catch(Exception e) { this.datadog_client.Increment("CacheUrl.Exception"); log.warn("Cache Failed to check {}, Error: {}", url, e.getMessage()); }; return isnew; // If something wrong appends... keep going }; } I launch Hazelcast Like this: docker run --name=hazelcast -p 5701:5701 --detach hazelcast/hazelcast:latest --build BUT I have discover that after apron 45mb of keys I start losing data no matter if it was in less than 72hrs, I made this test to probe it: @Test public void CheckMaxSize() throws Exception { // Hash Generator String ORIGINAL_HASH = generateRandomPassword(50); this.urlcache.isNewUrl(ORIGINAL_HASH); // We put it on cache Integer counter = 0; Boolean still_incache = true; while (still_incache) { still_incache = !(this.urlcache.isNewUrl(ORIGINAL_HASH)); //Negation: not (isnew) // We add new Hash to increse: this.urlcache.isNewUrl(generateRandomPassword(25)); //We dont care the value // Some Feedback: counter += 1; if ((counter%250) == 0) { log.info("We succed loading: {} items on Cache...", counter); } } log.warn("We losted our Controller Hash after putting: {} new ones in cache", counter); } The generateRandomPassword Function: public static String generateRandomPassword(int len) { String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&"; Random rnd = new Random(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) sb.append(chars.charAt(rnd.nextInt(chars.length()))); return sb.toString(); } I have discover that after 16k keys the controller is lost, but when I Increase the size of the password size to 50... it only take 8k keys to lost controller... Test Log: com.zimperium.server.phishing.services.UrlCacheClientTest > CheckMaxSize STANDARD_OUT 2022-07-28 13:11:04.669 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 250 items on Cache... 2022-07-28 13:11:05.354 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 500 items on Cache... 2022-07-28 13:11:06.052 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 750 items on Cache... 2022-07-28 13:11:06.744 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 1000 items on Cache... 2022-07-28 13:11:07.391 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 1250 items on Cache... 2022-07-28 13:11:08.048 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 1500 items on Cache... 2022-07-28 13:11:08.667 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 1750 items on Cache... 2022-07-28 13:11:09.305 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 2000 items on Cache... 2022-07-28 13:11:09.960 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 2250 items on Cache... 2022-07-28 13:11:10.616 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 2500 items on Cache... 2022-07-28 13:11:11.275 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 2750 items on Cache... 2022-07-28 13:11:12.539 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 3000 items on Cache... 2022-07-28 13:11:14.879 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 3250 items on Cache... 2022-07-28 13:11:16.008 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 3500 items on Cache... 2022-07-28 13:11:16.865 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 3750 items on Cache... 2022-07-28 13:11:18.090 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 4000 items on Cache... 2022-07-28 13:11:18.833 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 4250 items on Cache... 2022-07-28 13:11:19.857 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 4500 items on Cache... 2022-07-28 13:11:20.693 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 4750 items on Cache... 2022-07-28 13:11:21.347 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 5000 items on Cache... 2022-07-28 13:11:21.996 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 5250 items on Cache... 2022-07-28 13:11:22.682 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 5500 items on Cache... 2022-07-28 13:11:23.426 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 5750 items on Cache... 2022-07-28 13:11:24.224 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 6000 items on Cache... 2022-07-28 13:11:25.079 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 6250 items on Cache... 2022-07-28 13:11:25.899 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 6500 items on Cache... 2022-07-28 13:11:26.493 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 6750 items on Cache... 2022-07-28 13:11:27.334 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 7000 items on Cache... 2022-07-28 13:11:28.320 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 7250 items on Cache... 2022-07-28 13:11:29.285 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 7500 items on Cache... 2022-07-28 13:11:30.310 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 7750 items on Cache... 2022-07-28 13:11:31.460 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 8000 items on Cache... 2022-07-28 13:11:32.317 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 8250 items on Cache... 2022-07-28 13:11:33.018 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 8500 items on Cache... 2022-07-28 13:11:33.675 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 8750 items on Cache... 2022-07-28 13:11:34.417 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 9000 items on Cache... 2022-07-28 13:11:35.062 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 9250 items on Cache... 2022-07-28 13:11:35.688 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 9500 items on Cache... 2022-07-28 13:11:36.294 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 9750 items on Cache... 2022-07-28 13:11:36.896 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 10000 items on Cache... 2022-07-28 13:11:37.485 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 10250 items on Cache... 2022-07-28 13:11:38.067 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 10500 items on Cache... 2022-07-28 13:11:38.728 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 10750 items on Cache... 2022-07-28 13:11:39.398 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 11000 items on Cache... 2022-07-28 13:11:40.076 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 11250 items on Cache... 2022-07-28 13:11:40.783 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 11500 items on Cache... 2022-07-28 13:11:41.457 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 11750 items on Cache... 2022-07-28 13:11:42.110 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 12000 items on Cache... 2022-07-28 13:11:42.789 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 12250 items on Cache... 2022-07-28 13:11:43.380 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 12500 items on Cache... 2022-07-28 13:11:44.053 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 12750 items on Cache... 2022-07-28 13:11:44.724 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 13000 items on Cache... 2022-07-28 13:11:45.327 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 13250 items on Cache... 2022-07-28 13:11:45.986 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 13500 items on Cache... 2022-07-28 13:11:46.661 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 13750 items on Cache... 2022-07-28 13:11:47.324 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 14000 items on Cache... 2022-07-28 13:11:47.979 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 14250 items on Cache... 2022-07-28 13:11:48.644 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 14500 items on Cache... 2022-07-28 13:11:49.221 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 14750 items on Cache... 2022-07-28 13:11:49.812 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 15000 items on Cache... 2022-07-28 13:11:50.446 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 15250 items on Cache... 2022-07-28 13:11:51.086 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 15500 items on Cache... 2022-07-28 13:11:51.722 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 15750 items on Cache... 2022-07-28 13:11:52.384 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 16000 items on Cache... 2022-07-28 13:11:53.081 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 16250 items on Cache... 2022-07-28 13:11:53.732 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 16500 items on Cache... 2022-07-28 13:11:54.441 INFO 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We succed loading: 16750 items on Cache... 2022-07-28 13:11:54.607 WARN 39907 --- [ Test worker] c.z.s.p.services.UrlCacheClientTest : We losted our Controller Hash after putting: 16812 new ones in cache How can I increase the size of my cache? I need at least 50k keys in memory on Hazelcast map to work... Thank you very much for you help in advance <3 A: You have two choices Run more Docker images is best. See this guide for a guide. Depending on your networking you may need hazelcast.local.publicAddress to make them find each other, as each will be separate Docker images. Note that a 2nd Docker image doesn't increase capacity if you have the default backup-count=1. You need at least a 3rd, but you can have hundreds. Or increase the heap size on the existing process, but this will hit a limit very quickly. Once Java heap size gets too big, GC will kill performance. 45Mb of data seems very little to run out of memory. Is it an OOM you get ?
doc_23530807
Is there a way to send to a mailing list instead of just an array of users on Sendgrid? The best I've seen is that you can make one API call to a mailing list to get the emails, but it caps you by returning a maximum of 50 users. I've also seen that you can specify lists in marketing campaigns, but apparently you can't use dynamic templates in those campaigns? So I'd have to manually extract the HTML. This leads me to believe I'll need to request the version of the template I want with test_data, grab the HTML content from that, and manually insert it into a new campaign with the mailing list ID I want? Any ideas? Is there a better way?
doc_23530808
* *1.I was building a ionic Mobile App in that i have a gallery and i was trying to view a image as pop-up from gallery, pop-up was working fine and it fetch the image path too but unable to see image on pop-up. here my app.js function galleryController($scope, $http, $rootScope, $location,$ionicModal, profile){ /*alert(0);*/ profile.galleries(window.localStorage['token']).success(function(data){ /*alert(JSON.stringify(data));*/ if(data.status == 200) { $scope.gallery = data.data.gellary; //alert(JSON.stringify(data)); } $ionicModal.fromTemplateUrl('partials/gallery.html', function(modal) { $scope.gridModal = modal; }, { scope: $scope, animation: 'slide-in-up' }); // open video modal $scope.openModal = function(selected) { $scope.data = selected; $scope.gridModal.show(); }; // close video modal $scope.closeModal = function() { $scope.gridModal.hide(); }; //Cleanup the video modal when we're done with it! $scope.$on('$destroy', function() { $scope.gridModal.remove(); }); }); }; kangaroo.directive('gridImage', function(){ alert("yyyyyyyyyyyyyyyyyyy"); return function($scope, element, attrs){ var url = attrs.gridImage; element.css({ 'background-image': 'url(' + url +')', }); }; }); *I was fetching image from s3 Amazon by using api , this is html code in my gallery.html where i get the data from my controller i can see the image in gallery and not able to see on pop-up don't know what was the problem. **gallery.html page** <ion-header class="bar bar-header bar-balanced"> <!-- <button class="button button-icon icon ion-navicon"></button> --> </ion-header> <div class="padding" > <div ng-controller="galleryController"> <ion-content class="content has-header ionic-pseudo" style="margin-top:19px"> <div ng-repeat="x in gallery" > <img ng-src="{{x.thumb_img}}" ng-click="openModal(x)" alt="" class="gallery_i" /> </div> </ion-content> <script id="partials/gallery.html" type="text/ng-template"> <div class="modal" ng-click="closeModal()"> <img ng-src="{{data.thumb_img}}" /> </div> </script> </div> </div> please help me out of this Thanks in advance.
doc_23530809
@interface Vehicle : NSObject @property (nonatomic) int wheels; - (id)initWithNumberOfWheels:(int)wheels; @end from there i create some subclasses for same "car" & "truck" which give more detail to the class. @interface Car : Vehicle @property (nonatomic) BOOL convertible; @property etc... @end and... @interface Truck : Vehicle @property (nonatomic) BOOL is4x4; @property (nonatomic) int numberOfDoors; @end so here is where it gets interesting. i want to create another class that allocates those objects but i want the "type" of vehicle to be determined in the init method but use the same @property variable. so for example (and again, this is all garbage code just to give a visual representation) Road.h #import "Car.h" #import "Truck.h" @interface Road : NSObject @property (strong, nonatomic) NotSureWhatToUseHereToMakeThisWork *myRide; // doesn't work: @property (strong, nonatomic) id myRide; // doesn't work: @property (strong, nonatomic) Vehicle *myRide; - (id)initWithCars; - (id)initWithTrucks; @end Road.m @implementation Road - (id)initWithCars { //standard init code... myRide = [[Car alloc] initWithNumberOfWheels:4]; myRide.convertable = NO; } - (id)initWithTrucks { //standard init code... myRide = [[Truck alloc] initWithNumberOfWheels:6]; //yes, some trucks have more than 4 wheels myRide.is4x4 = YES; } @end the bottom line is if i use the superclass in the @property it doesn't get the subclass properties obviously. basically i want to keep all this as generic and reusable as possible. it doesn't make since to make a special "road" class just for cars & one for trucks. a road is a road after all. is there anyway to do what i am after? is there a better way to do something like this? the primary purpose is to have objects that inherit specific properties for specific situations only. the reason i don't want to make extra @properties is i don't want those visible if they aren't applicable to the situation. edit: i added a couple extra snippets to show what i tried before even posting this question that didn't work. answer: the correct "answer" if anyone is curious is located in CRD's response in the "Addendum". the reason this works is the type "id" can only call methods and does not inherit properties. so rather the workaround (i say it that way, as i was researching this, came to the conclusion this is not good programming and should probably be avoid if possible) would be to use the accessor methods to get/set the property. id mySomethingObject = [[SomeClass alloc] init...]; [mySomethingObject setPropertyMethod]...; //sets value [mySomethingObject propertyMethod]...; //gets value rather than trying to use... mySomethingObject.property = ; //set mySomethingObject.property; //get as stated in the correct answer, if your class you allocated "id" to does not respond to that method your program will crash. A: You appear to be confusing a number of issues. First there is the type of an instance vs. the type of variables which hold references to instances. When an object is created is it of some specific type and that types does not change[*]. Variables also have a type, and that does not change either. Subtyping/inheritance allows you to store a reference to an object of some type, T, in a variable of some other type, S, provided S is a supertype of T. Second there is static vs. dynamic typing. While Objective-C uses dynamic typing, where the actual type of objects used in some operation is determined at run time, the compiler itself uses static typing, where types are determined during compilation, to aid in writing correct programs. Sometimes the compilers static checking will just produce warnings, but in other cases the compiler will refuse to compile something. In particular property references are compiled based on static typing. In your example this means you cannot directly reference a property of Car on an object referenced by a variable of type Vehicle *, even if you know the referenced object is a Car - as at compile time all that is known is that is it a Vehicle. The solution is to first test the actual type of the referenced object and then introduce a local variable of the more precise type, or use a lot of casts. For example: // (a) create an object of type Car (for a Reliant Robin ;-)) // (b) create a variable of type Car and store in it a reference to the created Car Car *myCar = [[Car alloc] initWithNumberOfWheels:3]; // Create a variable of type Vehicle and store in it the reference stored in myCar // The created instance is *still* a Car Vehicle *myRide = myCar; // See if myRide is a Car and then do something if ([myRide isKindOfClass:Car.class]) { // create a variable of type Car to avoid having to continually cast myRide Car *myCarRide = (Car *)myRide; // due to if above we know this cast is valid if (myCarRide.isConvertible) ... To do this without the intermediate variable you use a cast: ... // See if myRide is a Car and then do something if ([myRide isKindOfClass:Car.class]) { if (((Car *)myCarRide).isConvertible) ... Which shows why the intermediate variable approach is better! As a final example, you write your initWithTrucks method like this: - (id)initWithTrucks { //standard init code... Truck *myTruck = [[Truck alloc] initWithNumberOfWheels:6]; //yes, some trucks have more than 4 wheels myTruck.is4x4 = YES; // Store the reference to the created Truck in myRide myRide = myTruck; } HTH Addendum From your comments it seems you may be looking for dynamic typing and do not wish to the compiler to perform any static typing. This is (partially) supported, but not using the dot notation for properties - you must use the getter and setter methods directly. First, in Road you declare myRide to be type id: @interface Road : NSObject @property id myRide; The id type means two things (a) any object reference and (b) do not statically check a method exists on the object. However the compiler must know that a called method exists on some object, and it will still perform static type checks on the arguments to the method - so its not complete dynamic typing (however you could pass id typed expressions or declare your methods to take arguments of type id of course...). Second you make all references to properties use the getter or setter methods directly and do not use the dot notation (for non-property methods you just call them as usual). E.g.: - (id)initWithTrucks { //standard init code... myRide = [[Truck alloc] initWithNumberOfWheels:6]; //yes, some trucks have more than 4 wheels [myRide setIs4x4:YES]; } If you make a call such as [myRide setIs4x4:YES] and myRide is referencing a Car object then you will get a runtime error. The general recommendation is to stick as much as possible with the compiler's static typechecking. [*] We will ignore any runtime magic, there be dragons. In normal code objects never change type. A: You have to use the type "Vehicle" and then cast your object with "Truck" or "Car" to get the specific properties A: the most generic architecture would be to create a VehicleProtocol, that any class could implement. you still could have a Vehicle class that implements the protocol and subclass from it (similar to NSObject implementing the NSObject protocol), or let independent classes implement it. the road would have a property @property (strong) id<VehicleProtocol> myRide. A complete example of the later architecture: no vehicle super class, but all a VehicleProtocol #import <Foundation/Foundation.h> @protocol VehicleProtocol <NSObject> @property (nonatomic) NSUInteger wheels; @end @interface Car : NSObject <VehicleProtocol> @property (nonatomic) BOOL convertible; @property (nonatomic) NSUInteger wheels; -(id)initWithNumberOfWheels:(NSUInteger) numberOfWheels; @end @implementation Car -(id)initWithNumberOfWheels:(NSUInteger) numberOfWheels { if (self = [super init]) { _wheels = numberOfWheels; } return self; } @end @interface Truck : NSObject <VehicleProtocol> @property (nonatomic) BOOL is4x4; @property (nonatomic) int numberOfDoors; @property (nonatomic) NSUInteger wheels; -(id)initWithNumberOfWheels:(NSUInteger) numberOfWheels; @end @implementation Truck -(id)initWithNumberOfWheels:(NSUInteger) numberOfWheels { if (self = [super init]) { _wheels = numberOfWheels; } return self; } @end @interface Road : NSObject @property (strong) id<VehicleProtocol> myRide; @end @implementation Road @end int main(int argc, const char * argv[]) { @autoreleasepool { NSArray *vehicles = @[[[Car alloc] initWithNumberOfWheels:4], [[Car alloc] initWithNumberOfWheels:3], [[Truck alloc] initWithNumberOfWheels:10]] ; for (id v in vehicles) { if ([v isKindOfClass:[Truck class]]) { [v setIs4x4:YES]; } } Road *road = [[Road alloc] init]; road.myRide = vehicles[0]; NSLog(@"%@", road.myRide); road.myRide = vehicles[2]; NSLog(@"%@", road.myRide); NSObject *obj = [[NSObject alloc] init]; road.myRide = obj; // warning in this line NSLog(@"%@", road.myRide); } return 0; } Sure it might have more lines of codes than with "classical subclassing", but there are less dependencies. Instead the classes agree on a contract to fulfill. Here the contract only requires the objects to have any number of wheels. Note that I create a Road and assign first a car and than a truck (I also show how to identify cars and trucks via -isKindOfClass:), both works without any warning or error, as Car and Truck completely fulfill the contract. Than I assign a plain NSObject. Here the compiler warns, as he recognizes that NSObject does not implement the protocol. Though it is not an compiler error, as the compiler does not know, if you will use any protocol specific method on that object. In case of a plain NSObject assigned to myRide, this line NSLog(@"%@ %ld", road.myRide, (unsigned long)road.myRide.wheels); will lead to a runtime crash (as an NSObject instance does not respond to wheel) — but at compile time it will not even trigger a warning. A: Storing a Car in a variable of type Vehicle * does not remove the object's Car properties — the Car will still be able to access all of its state normally — it just means that you can't access the properties through that variable. But that's the basic idea here, isn't it? You want this class to be able to handle all Vehicles, and that's what it's doing — it's only showing you the functionality available to all Vehicles. So you can have the interface necessary for interaction with a generic Vehicle in the Vehicle class, and implement the methods in your subclasses to do the class-appropriate behavior when called, and everything will work. If the issue is specifically creating new instances of a specific class that you want to treat generically from that point on, you can use a statically typed local variable and assign to the generically typed variable once it's set up. For example, let's say we have a game where there are human players and AI players, and the human player can give himself an advantage by making AI players take more damage. We could do this: @interface Combatant : NSObject @property(nonatomic, strong) NSString *name; @property(nonatomic) int hitPoints; - (void)takeDamage:(int)damageAmount; @end @implementation Combatant - (void)takeDamage:(int)damageAmount { self.hitPoints -= damageAmount; } @end @interface HumanCombatant : Combatant @property(nonatomic, strong) UserID *userID; - (id)initWithUserID:(UserID *)theID; @end @implementation HumanCombatant - (id)initWithUserID:(UserID *)theID { if ((self = [super init])) { _userID = [theID retain]; } } - (void)takeDamage:(int)damageAmount { [super takeDamage: damageAmount]; NSLog(@"Human took %d damage, has %d health remaining", damageAmount, self.hitPoints); } @end @interface AICombatant : Combatant @property(nonatomic) double damageMultiplier; @end @implementation AICombatant - (void)takeDamage:(int)damageAmount { int modifiedDamage = damageAmount * self.damageMultiplier; [super takeDamage: modifiedDamage]; NSLog("AI took %d damage, has %d health remaining", modifiedDamage, self.hitPoints); } @end Then, in most of our game code, we can use a variable typed as a Combatant *, and when you send it takeDamage:, it will do the right thing for the type of combatant it is. Our external code that calls the object a Combatant * will not be able to directly access an AICombatant's damageMultiplier property, because the other code doesn't know whether the Combatant is an AICombatant, but the object will still have that property and will behave correctly for its class. A: Make it a Vehicle* and make each class implement type to return a constant indicating that class's type. @property (nonatomic, strong) Vehicle* yourRide; ... if (yourRide.type == VehicleConstant_Truck) { Truck* yourTruck = (Truck*) yourRide; NSLog(@"This truck %s a 4x4", yourTruck.is4x4 ? "is" : "isn't"); } To make @vikingosegundo happy, an alternative approach is to do: if ([yourRide isKindOfClass:[Truck class]]) { instead of the if statement above.
doc_23530810
Example : <?php echo '<div>' . $escaped . '</div>' ?> I already know htmlspecialchars PHP function & affiliates A: No, for the HTML body you will also need to encode the & character to prevent an attacker from potentially escaping the escape. Check out the XSS Experimental Minimal Encoding Rules:- HTML Body (up to HTML 4.01): * *HTML Entity encode < & *specify charset in metatag to avoid UTF7 XSS XHTML Body: * *HTML Entity encode < & > *limit input to charset http://www.w3.org/TR/2008/REC-xml-20081126/#charsets Note that if you want to enter stuff inside of an attribute value, then you need to properly encode all characters with special meaning. The XSS (Cross Site Scripting) Prevention Cheat Sheet mentions to encode the following characters:- &,<, >, ", ', / You must also quote the attribute value for the escaping to be effective. A: The answer is no, someone will find his way to exploit it, somehow. You are underestimating the number of techniques and the creativity of attackers. Read through the OWASP XSS Cheat Sheet https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet to have an idea of the number of ways this could happen. In your case, does it protect against an XSS into an onload attribute? Or into an input that becomes part of a CSS definition? In those situations you already are into an implicit tag, so you only need JS code to be added, no reason to use '<' or '>' Do output validation with XSS, it is the simplest thing and it will protect you everywhere, just do it every single time you write anything (no matter if it comes from the user or not) and pay attention to the context (escape/encode for an URL when you are writing a link, escape/encode for JS when you are writing directly into a JS script, escape/encode for CSS when you are writing part of a CSS definition, escape/encode JSON when you write JSON data, escape/encode HTML in any other case). In addition, even if it is unrelated, I usually point to this site to show how people like to be creative about JS http://www.jsfuck.com/ - this is meant to be obfuscation-only but I used it for evading anti-XSS controls, usually when made by a 3rd party.
doc_23530811
I have hundreds of documents inside a collection in a mongodb database. In every document I have an array called "hashes", in most documents this array contains a list of hashes (MD5, SHA1 etc...). I want to export all these hashes to a text file, or list them all in a GUI/terminal. I've included an image where what I want to export is highlighted in yellow. A: This command was derived from the documentation Lalit Agarwal provided. It does exactly what I wanted. ./mongoexport --port 27017 -db paste_db -collection pastes --fields hashes --csv > out.csv
doc_23530812
'Cannot interpret feed_dict key as Tensor: ' + e.args[0]) TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(7, 7, 3, 64), dtype=float32) is not an element of this graph. If I remove K.clear_session() at end, there is no error. Is there anyone who can explain why this error comes in second iteration? I tried other methods (for gpu release) but none of them worked and this is my last option. But it throws error. I have pasted an example code which can produce the error. Please NOTE that this is not the actual code, I just made an example to reproduce the error which I am facing in actual code. from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import tensorflow as tf import random seed_value= 0 import os import keras os.environ['PYTHONHASHSEED']=str(seed_value) random.seed(0) np.random.seed(0) from keras import backend as K from keras.datasets import cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() for i in range(3): base_model = tf.keras.applications.resnet50.ResNet50(weights='imagenet', input_shape=(32, 32, 3), include_top=False) x = base_model.output x = tf.keras.layers.GlobalAveragePooling2D()(x) output = tf.keras.layers.Dense(10, activation='softmax', kernel_initializer=tf.keras.initializers.RandomNormal(seed=4))(x) model = tf.keras.Model(inputs=base_model.input, outputs=output) y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) for layer in base_model.layers: layer.trainable = False optimizer = tf.train.AdamOptimizer(learning_rate=0.0001) model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) model.fit(x_train,y_train,batch_size=1024,epochs=1,verbose=1) K.clear_session() Traceback (most recent call last): File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1092, in _run subfeed, allow_tensor=True, allow_operation=False) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3490, in as_graph_element return self._as_graph_element_locked(obj, allow_tensor, allow_operation) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 3569, in _as_graph_element_locked raise ValueError("Tensor %s is not an element of this graph." % obj) ValueError: Tensor Tensor("Placeholder:0", shape=(7, 7, 3, 64), dtype=float32) is not an element of this graph. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:/codes/experiments-AL/breakhis/40X-M-B/codes-AL/error_debug.py", line 22, in <module> include_top=False) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\keras\applications\__init__.py", line 70, in wrapper return base_fun(*args, **kwargs) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\keras\applications\resnet50.py", line 32, in ResNet50 return resnet50.ResNet50(*args, **kwargs) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\keras_applications\resnet50.py", line 291, in ResNet50 model.load_weights(weights_path) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\keras\engine\network.py", line 1544, in load_weights saving.load_weights_from_hdf5_group(f, self.layers) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\keras\engine\saving.py", line 806, in load_weights_from_hdf5_group K.batch_set_value(weight_value_tuples) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\keras\backend.py", line 2784, in batch_set_value get_session().run(assign_ops, feed_dict=feed_dict) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 929, in run run_metadata_ptr) File "C:\Users\sirshad\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\client\session.py", line 1095, in _run 'Cannot interpret feed_dict key as Tensor: ' + e.args[0]) TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(7, 7, 3, 64), dtype=float32) is not an element of this graph. Process finished with exit code 1 A: I was able to overcome this issue by saving the imagenet pre-trained model to disk and then loading everytime in loop after I call tf.keras.backend.clear_session(). So saving the base model to file and then loading works. But I am still confused why it did not work before with base_model = tf.keras.applications.resnet50.ResNet50
doc_23530813
set.seed(20) x1=rnorm(100) x2=rnorm(100) x3=rnorm(100) t=data.frame(a=x1,b=x1+x2,c=x1+x2+x3) fun1=function(multi1,multi2) { v=t$c s=c() for (i in v) { if (i<0) { s[i]=i*multi1 } else if(i>0) { s[i]=i*multi2 } } return(s) } fun1(multi1=0.5,multi2=2) But it gave me just a few numbers. I felt I might made some stupid mistakes but I couldn't figure out. A: tl;dr This operation can be vectorized. You can use the following method, assuming you want to leave values that are 0 or NA alone. with(t, c * ifelse(c < 0, 0.5, ifelse(c > 0, 2, 1))) If you want to include them in one side (e.g. on the positive side), it's even more simple. with(t, c * ifelse(c < 0, 0.5, 2)) As far as your loop goes, you've got a few issues there. First, you were indexing s by decimal values, which would likely cause errors in the calculations. This is also the reason why your result vector was so short. When you indexed in the loop, the indices were moved to integer values and since some of them were repeated, s ended up being very short. The actual unique index length went something like this - length(unique(as.integer(t$c))) # [1] 9 And as a result you got, as a simple example, s[c(1, 2, 1, 1)] <- something Since 1 is repeated, only indices 1 and 2 were changed. This is what was happening in your loop. Further illustrated as x <- 1:5 x[1.2] # [1] 1 x[1.99] # [1] 1 Next, notice below that we have allocated the vector s. We can do that because we know the length of the resulting vector will be the same as v. This is the recommended, more efficient way rather than building the vector in the loop. Moving on, I changed for(i in v) to for(i in seq_along(v)) to correct this. Now we are indexing with a sequence for i. Then we also need to index v in the same manner. Finally, we can assign s[i] <- if(... instead of assigning to the same index inside the if() statement. Also note that you haven't accounted for 0 or any other values that may appear in v (like NA). I added a final else where we just leave those values alone. Change that as you see necessary. Furthermore, instead of going to the global environment to get t$c, we can pass it as an argument and make this function more general (credit to @ShawnMehan for that suggestion). Here's the revised version: fun1 <- function(vec, multi1, multi2) { s <- vector("numeric", length(vec)) for (i in seq_along(vec)) { s[i] <- if (vec[i] < 0) { vec[i] * multi1 } else if(vec[i] > 0) { vec[i] * multi2 } else { vec[i] } } return(s) } So now we have a length 100 result x <- fun1(t$c, 0.5, 2) str(x) # num [1:100] 2.657 -0.949 7.423 -0.749 5.664 ... I wrote this long explanation because I figure you are learning how to write a loop. In R though, we can vectorize this entire operation and put it into one line of code. The following line gives the same result as fun1(t$c, 0.5, 2). with(t, c * ifelse(c < 0, 0.5, ifelse(c > 0, 2, 1))) Thanks to @Frank for catching my calculation oversight. Hopefully this all makes sense. Sometimes I don't do well with explanations and technical jargon. If there are any questions, please comment.
doc_23530814
#include <QCoreApplication> #include <QMutex> #include <QSemaphore> #include <QThread> #include <cstdio> static const int N = 2000000; class Thread : public QThread { public: Thread(); void run(); private: static QMutex mutex; }; QMutex Thread::mutex; static int g_counter = 0; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); Thread A, B, C; A.run(); B.run(); C.run(); char c; scanf("%c", &c); printf("%d\n", g_counter); return app.exec(); } Thread::Thread() { } void Thread::run() { //QMutexLocker lock(&mutex); for (int i = 0; i < N; ++i) { ++g_counter; --g_counter; } } I expected to see g_counter jumping up and down as three threads are changing it at the same time. My problem was that I used run() so it executed as a simple function instead of start() to launch it as a thread. Anyway thanks. A: I'm not sure what you are trying to do here, but you need to start the thread by calling start(). You also need to lock the mutex, otherwise what's the point? #include <QCoreApplication> #include <QMutex> #include <QSemaphore> #include <QThread> #include <cstdio> static const int N = 2000000; class Thread : public QThread { public: Thread(int id); void run(); private: int id_; static QMutex mutex; }; QMutex Thread::mutex; static int g_counter = 0; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); Thread A(0), B(1), C(2); A.start(); B.start(); C.start(); char c; scanf("%c", &c); printf("%d\n", g_counter); return app.exec(); } Thread::Thread(int id) : id_(id){ } void Thread::run() { for (int i = 0; i < N; ++i) { mutex.lock(); ++g_counter; printf("g_counter: %d thread: %d\n", g_counter, id_); mutex.unlock(); mutex.lock(); --g_counter; printf("g_counter: %d thread: %d\n", g_counter, id_); mutex.unlock(); } }
doc_23530815
Product Name | Category | Product Group | Attributes -------------------------------------------------------------------------------------------- 1- Board Marker - Blue | Stationary | White Board Markers | Color = Blue, Type = Board 2- Board Marker - Green | Stationary | White Board Markers | Color = Green, Type = Board In the new indexed data I need to store the data as: Product Name | Category | Product Group | ----------------------------------------------------------------------------------------------------------------------------------------------- 1- Board Marker | Stationary | White Board Markers TL,DR: Find items which are at least 90% similar, on properties such as Product Name, Category , Product Group, (some)Attributes, and generate a new index to store them. I am new to ElasticSearch and a noob at this. PS. I asked a this question on the ElasticSearch forum but got no love. https://discuss.elastic.co/t/clustering-deduplicating-data-in-elasticsearch/96274
doc_23530816
The words are nested in a span with an unique id like id="one" oder id="two". Like: <p id="JShighlight"> <span id="one">Lorem </span><span id="two">Ipsum </span><span id="three">Dolores</span></p> To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray let childNodeArray = document.getElementById('JShighlight').children; Then I randomly chose an index: let i = Math.floor(Math.random() * childNodeArray.length); The variable name saves the randomly chosen ID. let name = childNodeArray[i].id; To this randomly chosen word /Id I want to add a certain style so that this word blinks one time. I tried: name.classList.add("blinking"); (.blinking is the css-class: .blinking { animation: blinkingText 0.6s 1; /* animation-iteration-count: 1; */ } ) But it does not work. What "works" is: document.getElementById(name).style.color = "red"; Why can I pass a variable as an argument in the latter case and not in the former case? How can I append a css class to an variable ID? A: In the first case, name is a string not an element. what you can do is: name = document.getElementById(name); name.classList.add("blinking"); A: use Array.from to convert children DOM list to array of DOM elements. Also remove the id attribute before storing the name refer variable. Please update the below lines. let childNodeArray = Array.from(document.getElementById('JShighlight').children); let i = Math.floor(Math.random() * childNodeArray.length); let name = childNodeArray[i]; name.classList.add("blinking"); A: Instead of let name = childNodeArray[i].id; try let name = childNodeArray[i]; Hope your issue will be resolved;
doc_23530817
It's a loop where the loop fills the printarea of the ws with information (page 1 f.e) --> prints the page 1 --> fills the the printarea of the ws with the next information (page 2 f.e.) --> prints the page 2 and on and on and on. I do have the option to tell the loop from which page it should start and when to end: * *InputBox("Auf welcher Seite soll der Ausdruck beginnen ?", MSGTitel) - On which page should the print start? *Ende = InputBox("Bis zu welcher Seite soll gedruckt werden ?", MSGTitel) - Until which page it should print? ** My goal is to have all the pages I want to be saved in one pdf - is that possible?** Here is the code: Private Sub CommandButton6_Click() Dim Start Dim Ende Dim X1 As Integer Dim ST1 As Integer Dim End1 As Integer X1 = 0 Start = InputBox("Auf welcher Seite soll der Ausdruck beginnen ?", MSGTitel) If Start <> "" Then If IsNumeric(Start) = True Then Ende = InputBox("Bis zu welcher Seite soll gedruckt werden ?", MSGTitel) If Ende <> "" Then If IsNumeric(Ende) = True Then If Start > Ende Then ST1 = Ende End1 = Start Else ST1 = Start End1 = Ende End If Do Until ST1 + X1 = End1 + 1 Tabelle6.Cells(11, 2).value = (Val(ST1 + X1) * 20) - 19 Label1.Caption = Val(ST1 + X1) Tabelle6.Cells(6, 31).value = Label1.Caption 'Debug.Print Label1.Caption Tabelle6.PrintOut X1 = X1 + 1 Loop End If End If End If End If End Sub Thanks for your help Tried to change the print method or instead of printing to save it as a pdf but I struggle with the loop as all my pdfs only have one page in it A: It is not possible with PrintOut method, if your sheet Tabelle6 contains only one page. Your problem cannot be simply solved with VBA. You can try other solution: Rewrite VBA-script so that your loop, instead of PrintOut method, copies contents of Tabelle6 on new sheet, one page after (below) previous page, and then prints the whole new sheet, after the loop is finished (you need to take care of page breaks on new sheet, so that print looks like what you expect)
doc_23530818
New-AzWebAppSSLBinding -ResourceGroupName $webappname -WebAppName $webappname -Thumbprint "$newthumbprint" -Name "$customdomain" When I Debug this the custom domain isn't found, But when I check the domain in microsoft azure under tls/ssl bindings, the domain is there with his old thumbprint. When im using the original domain of the webapp (.azurewebsites.net) then it would say that there is a conflict because in the new certificate is that domain not registered and thats good because I dont want that. Anyone know how I can change the thumbprint of customdomains in powershell instead of waste my time in microsoft azure application and doing it more then 100 times manually... A: For the error, "custom domain isn't found" or "Hostname 'www.exmaple.com' does not exist", here are possible reasons: * *You could check the certificate's subject name must match the domains used to access the Web App. * *You should find the existing certificate under TLS/SSL settings---Private Key Certificates. When you run the PowerShell commands, ensure that you type the correct Hostname and matched Thumbprint. The command is working well on my side. In addition, If you update an SSL certificate from a local machine to the Azure web app, you can use this command. New-AzWebAppSSLBinding -ResourceGroupName $webapprg -WebAppName $webappname -CertificateFilePath $PathToPfxFile -CertificatePassword $PlainTextPwd -Name $customdomain
doc_23530819
I want to be able to keep the exe inside the boundary of the actual form I create. A: This requires a bit of Windows API trickery. The technique is called "Subclassing a Window" and you can read more about it on MSDN - scroll down a bit to find the relevant section. Ryan looks like he got most of the way there in C# answering his own question, but states that he didn't solve it completely. I have done this very successfully using C code similar to that you see in the MSDN article. It is not explicitly stated in the MSDN article, but it is a best practice to reset WndProc back to it's orginal value when done (e.g. when your app exits). You'll see in Ryan's code that he does do this.
doc_23530820
[Vue warn]: Property or method "nombreUsuario" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property in my component i´m creating a modal and i thinked that i could pass this data to my modal, but i can´t. i´m traying declare one variable in export deafult of my component, but always returned me a error. i´m showing in internet very much examples that how to do this, but i can´t. I appreciate all help My actual code is: componentVUE <template> <div class="tabla-usuarios"> <table class="table table-hover table-striped"> <thead> <th>Id</th> <th>Nombre</th> <th>Email</th> <th>Dirección</th> <th>Editar</th> </thead> <tbody> <tr> <td>{{ datosUsuario.id }}</td> <td>{{ datosUsuario.nombre }}</td> <td>{{ datosUsuario.email }}</td> <td>{{ datosUsuario.direccion }}</td> <td><a href="#" class="btn btn-info" data-toggle="modal" data-target="#create">Editar</a></td> </tr> </tbody> </table> <div class="modal fade" id="create"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span>×</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label for="nombre">Nombre:</label> <input type="text" class="form-control" id="nombre" :nombreUsuario="nombreUsuario"> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email"> </div> <div class="form-group"> <label for="direccion">Direccion:</label> <input type="text" class="form-control" id="direccion"> </div> </div> <div class="modal-footer"> <input type="submit" class="btn btn-primary" value="Guardar"> </div> </div> </div> </div> </div> </template> <script> export default { data() { return { datosUsuario: [], isOpen: false, }; }, created: function () { this.cargar(); }, methods: { cargar: function () { let url = "/getDatosPersonales"; axios .get(url) .then((response) => { this.datosUsuario = response.data; }) .catch((error) => console.error(error)); }, }, }; </script> A: The easiest way to pass information to a modal is to pass it through a function and store it in a Vue property. First, in your loop, change your button to this: <td><a href="#" class="btn btn-info" data-toggle="modal" data-target="#create" @click="setSelectedItem(datosUsuario)">Editar</a></td> Then you want to add both the property and the method: <script> export default { data() { return { datosUsuario: [], isOpen: false, selectedItem: {} }; }, created: function () { this.cargar(); }, methods: { cargar: function () { let url = "/getDatosPersonales"; axios .get(url) .then((response) => { this.datosUsuario = response.data; }) .catch((error) => console.error(error)); }, setSelectedItem(item) { this.selectedItem = item; } }, }; </script> Then it's real easy to get that data back into your modal: <div class="form-group"> <label for="nombre">Nombre:</label> <input type="text" class="form-control" id="nombre" v-model="selectedItem.nombre"> </div> You can also use the selectedItem in other functions, such as when submitting it back to the server.
doc_23530821
'subject' : { 'name' :"...." 'facebookPosts':[ { date:"14/02/2017 20:20:03" , // it is a string text:"facebook post text here", other stuff here } ] } and I want to count the facebookPosts within a specific objects that their date field contains e.g "23/07/2016". Now, I do that by extracting all the documents and count in the client side (spring ) , But I think that's not efficient. A: You need to aggregate your results. final Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(Criteria.where("facebookPosts.date").regex(REGEX)), Aggregation.unwind("facebookPosts"), Aggregation.group().count().as("count")); Regex might not be the best solution, just an example. unwind will split array into separate elements you can then count. Create a class that will hold the count, something like: public class PostCount { private Long count; // getters, setters } And then execute it like this: AggregationResults<PostCount> postCount = mongoTemplate.aggregate(aggregation, Subject.class, PostCount.class); long count = postCount.getMappedResults().get(0).getCount();
doc_23530822
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="MyAssembly1" culture="neutral" publicKeyToken="4fa4847a62640ab8"/> <codeBase version="1.0.0.0" href="FILE:G:/DLL/MyAssembly1.dll"/> </dependentAssembly> </assemblyBinding> </runtime> This is the code i have use to redirect the compiler to get DLL from the custom location
doc_23530823
I am able to achieve this by nesting a for (transArray) inside and tableView (product). However I need to sort and format the tableView based on the results first. General Question: Can fetched results be used without tableViews? - (void)calculateAmounts { NSIndexPath *indexPath=0; for (Product *product in self.fetchedResultsController.fetchedObjects){ // All product records selectedProduct = [self.fetchedResultsController objectAtIndexPath:indexPath]; // >>>>>NSLog shows correct number of object, however selectedProduct @ Index Path Are NULL for (id product1 in transProductArray) { // An array of all of the trans for product if ((NSNull *)product1 == [NSNull null]) { } else if ([product1 isEqualToString:selectedProduct]) { float qty = [@"1" floatValue]; NSNumber *numQty=[NSNumber numberWithFloat:qty]; // Update quantity sold in product by 1 NSNumber *quantity = [NSNumber numberWithFloat:([selectedProduct.quantitySold floatValue] + [numQty floatValue])]; selectedProduct.quantitySold = quantity; [self.product.managedObjectContext save:nil]; } } // Next Trans } // Next Product } A: This is a good question. Not (clearly) knowing the implementation, I will bet it is possible to use fetched results outside a tableview. However, the Overview of NSFetchedResultsController documentation has this as the first line: You use a fetched results controller to efficiently manage the results returned from a Core Data fetch request to provide data for a UITableView object. While table views can be used in several ways, fetched results controllers are primarily intended to assist you with a master list view. This infers that the two objects are linked for efficiency and ease of use. Plus, there are monitors under-the-hood to watch for changes, etc. What you may be looking for is a 'plain-old' NSFetchRequest. A tutorial. A: Hi I am not to sure whether you still require an answer to this however I had the same issue myself. I overcame as described in my own question on the subject. Display multiple core data entities objects in 1 Non-Table View Controller I inserted a small tableview into my VC and set it to alpha and used the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath to enable displaying details in labels. This was the only way I could overcome it. Hope this helps. A: Thanks for the answer. Like a lot of things the answer was too easy! It's about the fetch, not the tableview. Just do a fetch into an array, then loop though the array to accumulate your values: Also useful for finding a specific object or output to a CSV. NSError *error; NSNumber *total=0; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"TransDetail" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; for (TransDetail *trans in fetchedObjects) { total = total + trans.amount; }
doc_23530824
ABC 318 XY2388 OR ABC 318 XY02388 and I want them to become "ABC 318/XY 2388". So if there is any leading zero after the second batch of letters then remove them. Using the following code I have managed to get the output as ABC 318/XY 2388 ABC 318/XY 02388 (Wrong!) $input = "ABC 318 XY2388"; $output = preg_replace("/([A-Z]*) (\d*) ([A-Z]*)(\d*)/","$1 $2/$3 $4", $input); echo $output; Can anyone please suggest a way that I can trim the 0(zero) out of there? So if I pass following: ABC 318 XY2388 OR ABC 318 XY02388 Final output should be ABC 318/XY 2388 A: * means "repeated 0 or more times", so you're making every single match optional. Your regex would even match the string [SPACE][SPACE] or A[SPACE][SPACE]A etc. The regex /([A-Z]+) ([0-9]+) ([A-Z]+)0?([0-9]+)/ would work much better. Here's a demo, and an autopsy: * *([A-Z]+) - A capturing group matching the letters between A-Z repeated 1 or more times (that's what + means) *[SPACE] - A literal space character *([0-9]+) - A capturing group matching the digits between 0 and 9 repeated 1 or more times *[SPACE] - A literal space character *([A-Z]+) - The same as the first. A capturing group matching A-Z repeated 1 or more times. *0? - A literal 0 character repeated 0 or 1 time (so it's optional). *([0-9]+) - A capturing group matching the digits between 0 and 9 repeated 1 or more times PHP Demo. PHP Code: <?php $input = "ABC 318 XY2388"; $output = preg_replace("/([A-Z]+) ([0-9]+) ([A-Z]+)0?([0-9]+)/", "$1 $2/$3 $4", $input); var_dump($output); //string(15) "ABC 318/XY 2388" $input = "ABC 318 XY02388"; $output = preg_replace("/([A-Z]+) ([0-9]+) ([A-Z]+)0?([0-9]+)/", "$1 $2/$3 $4", $input); var_dump($output); //Same as above, as 0 is optional: string(15) "ABC 318/XY 2388" ?> A: Just to add a simple suggestion: If what you need is to trim one or more in-the-middle 0s, maybe you can do: $input = "ABC 318 XY0002388"; $output = preg_replace("/([A-Z]+) ([0-9]+) ([A-Z]+)(0*)([0-9]+)/", "$1 $2/$3 $5", $input); var_dump($output); //should be "ABC 318/XY 2388" Please note that I am saving the "in-the-middle 0s" on $4, but $4 is not part of the output. I have not tested it, but it should work, maybe if you don't parenthesized the "(0*)", it works with "$1 $2/$3 $4" without saving the 0s. I hope this helps.
doc_23530825
Say the component/service must integrate with a few different external web services that all report back different errors, and must also do some database work on your side. There are many different things that can go wrong, both network/database-wise and business rule-wise. Would it be better to try to catch all types of errors within the component and report them back to the caller using an error-code scheme, or try to wrap all errors into various types of exceptions and throw them on to the caller. This seems to be a struggle, because it gets awkward to deal with the business rule checks using exceptions, and I've read in several places to avoid using exceptions to control "non-exceptional" or business-logic flows. I feel that "exceptional" is often a debatable term, and it gets sticky trying to keep different cases defined as "exceptional" vs. "non-exceptional." (e.g. if your business logic checks for spending limits, age limitations, etc.). At the same time, using an error-code scheme is also awkward, because the caller might choose to ignore the error codes. Any tips or references would be appreciated! A: I'd go for the error code scheme, because you said "many different things that can go wrong". You might want to have a scheme that returns a List of Error objects, where Error would encapsulate the code, explanation, original data, etc. An exception can only tell one thing that's wrong, and it should be of an "exceptional" nature, not a run-of-the-mill problem. Or perhaps a hybrid where you throw an exception that has a List of Error objects as a private data member and an access method that lets you iterate over the errors. A: Business related errors should not be exeptions. Exceptions are there if there is an event in the program that the program is not designed to handle or completly unforseen. To this end, if you anticipate a large number of different exceptions, by all means implement some useful numbering scheme. Here I would recommend a guid for the reason of component reuse. Every component should expose some interface to query the list of possible exception numbers (this can then be added to a data store for documentation). Also as you reuse components, error codes will not conflict. User or business data errors on the other hand almost warrant some numbering scheme. There is almost no way to anticipate all the silly things a user is capable of. However, I would strongly discourage formal language exceptions in favour of some custom error object. Language exceptions may incur significant overhead, or require specialized handling to prevent them from propogating up the call stack. A business error object may very well be a nice way to go. A: Services are borderline, especially if they have to be hit from various languages that may not handle SOAP exceptions properly. There are also security concerns if it's on the WWW. If it's not a service, is internal, and/or will be accessed by clients in known languages, use exceptions to handle failure conditions. Clients are not guaranteed to check error codes. See http://msdn.microsoft.com/en-us/library/ms229030.aspx for a great discussion of this. (It's also in the book Framework Design Guidelines.) A: There's absolutely nothing that could prevent you from making both business rules and technical rules violations exceptions. I'd use exceptions in two cases: * *Precondition violation. If your function's specification says "the amount spent should not exceed the limit for this type of account", and user, knowing this, specifies greater limit anyway, throw the exception right into him! *Postcondition violation. If all preconditions are met, but due to unexpected denial (database connection, for example; or completion of the transaction violates anti-monopoly law) you can't supply the correct result, do not supply it. Throw an exception. Since all business logic probably is within one component and doesn't rely on anything else, case 2 for business exceptions is quite rare. And what falls into case 1 should be checked for in the front-end application. This makes me think that the approach of not throwing business-logic exceptions is not that you "should not do", but likely "you mostly don't need to". Anyway, from the perspective of the language you're programming, it hardly notices the difference between "technical" and "business" exceptions, so it'll handle them all correctly. Second, exceptions are caught somewhere. I guess, that, from architector's point of view, business and technical exceptions will be caught in the different components. Of course, unless they're effectively uncaught, merely displaying error messages without programmatical handling falls into this category. So the use of the same mechanism won't make you mix these errors. So, my point is, that if you chose not to repulse exceptions as programming concept, you may use them for business logic as well.
doc_23530826
the indexed error is in the index.php at line 52 error to deploy my site on hostinger, I created a folder laravelblog which contains all my files except the public my hostinger domain and the files it contains then I modified the paths in the index.php
doc_23530827
I used SQLite Manager (a Firefox extension) to add the value directly to the sqlite file in my project. I can query the table and it shows that the 19th record has a "threatLevel" of 2. When I run my app in the simulator, the 19th record has a "threatLevel" of 1. I have tried cleaning my build, uninstalling the app from the simulator, even removing the sqlite database from my project and readding it. Nothing works. SQLite Manager says it has a value of 2, but when the program is run it gets a value of 1. The code to load it into the class from the DB is this: primaryKey = pk; database = db; // Compile the query for retrieving City data. if (init_statement == nil){ const char *sql = "SELECT * FROM myTable WHERE id=?"; if (sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL) != SQLITE_OK){ NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database)); } } sqlite3_bind_int(init_statement, 1, primaryKey); if (sqlite3_step(init_statement) == SQLITE_ROW){ LOAD THE FIRST 12 FIELDS HERE self.threat_level = sqlite3_column_int(init_statement, 13); } else { self.name = @"Nothing"; } EDIT I just tried deleting the sqlite database from the project, and I moved it to my desktop to back it up. I can still build and run my app. So it's looking at an older version of my database, but Spotlight says there are no other versions on my machine except for the one on my desktop. Any help here? A: You can use lsof to list the files open by a process, which can hopefully help you nail down which database is being used. Find the process ID of your application with Activity Monitor or the like, and run lsof -p <PID> in Terminal. A: I think instead of using SELECT * you may want to use explicit column names in the select string... A: Where is your sqlite in your project - eg. Is it in your app bundle or are you writing it to the Documents folder for your app? If you are writing it to the Documents folder for your app and running the simulator your file will be located in the Application Support folder for the iPhone Simulator ~/Library/Application Support/iPhone Simulator/User/Applications/<application id> Also I'll add a +1 to using Core Data in general - I just attended an Apple iPhone event and there are some significant efficiency and performance benefits to be gained by using Core Data over most of the other sqlite frameworks and especially over directly accessing the sqlite c api. A: It should be pretty easy to identify the name/path of the database that you are using as you're needing to provide the argument as part of sqlite3_open()? if (sqlite3_open([dataFilePath UTF8String], &database) == SQLITE_OK) { The database file is likely in the simulator. There is an option within the simulator to "Reset Content and Settings."
doc_23530828
class A { public: A() { cout << "A" << endl; } A(A &) { cout << "A&" << endl; } A(const A &) { cout << "const A&" << endl; } }; A fun() { class A a; return a; } int main() { class A a = fun(); // output: A } A: Short answer: compiler optimizations. * *First, the a object from your function is created directly in the scope of the main function, in order to avoid having to copy (or move in C++11) the local parameter out of the scope of the function via the function's return. This is return value optimization. *Then, in main, the statement becomes equivalent to class A a = A() and again the compiler is allowed to the create the a object in place, without copying from a temporary object. This is copy elision. This is allowed even if the copy constructor (which is bypassed entirely) has side-effects, like in your example.
doc_23530829
This is my code so far: classs Figure(QMainWindow): x1 = 0 #I made this variables to get the coordinates and use it in x2 = 0 # another methods too def __init__(self): #A lot of stuff in here to create the figure def right_click_press(self, event): if event.button == 3: #"3" is the right button print "you click the right button" print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%( event.button, event.x, event.y, event.xdata, event.ydata) #Get the coordinates of the mouse click Figure.x1 = event.xdata Figure.y1 = event.ydata #I create the action noteAction_2 = QAction(QIcon(""), "Insert note",self, triggered = self.openDialog) #I create the context menu self.popMenu = QMenu(self) self.popMenu.addAction(noteAction_2) cursor = QCursor() print cursor.pos() #self.connect(self.figure_canvas, SIGNAL("clicked()"), self.context_menu) #self.popMenu.exec_(self.mapToGlobal(event.globalPos())) self.popMenu.exec_() def context_menu(self): pass I tried globalPos , mapToGlobal, pos and trying to make another method (as you can see above) to get to open it where I make the click, but I do not get the result that I want. This is what I get: A: I already solved it replacing the line: self.popMenu.exec_() with this: #I create the context menu self.popMenu = QMenu(self) self.popMenu.addAction(noteAction_2) cursor = QCursor() self.popMenu.popup(cursor.pos()) By doing this, i discard using another method and i get the coordinates easily. Hope this help you.
doc_23530830
string encodedUrl = "videos/Sample.mp4" CloudBlockBlob encodedVideoBlob = blobClient.GetBlockBlobReference(encodedUrl); Log(string.Format("Got blob reference for {0}", encodedUrl), EventLogEntryType.Information); encodedVideoBlob.Properties.ContentType = contentType; encodedVideoBlob.Metadata[BlobProperty.Description] = description; encodedVideoBlob.UploadFile(localEncodedBlobPath); I see the "Got blob reference" message, so I assume the reference resolves correctly. Void Run() C:\Inter\Projects\PoC\WorkerRole\WorkerRole.cs (40) System.ArgumentNullException: Value cannot be null. Parameter name: value at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result() at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait() at Microsoft.WindowsAzure.StorageClient.CloudBlob.UploadFromStream(Stream source, BlobRequestOptions options) at Microsoft.WindowsAzure.StorageClient.CloudBlob.UploadFile(String fileName, BlobRequestOptions options) at EncoderWorkerRole.WorkerRole.ProcessJobOutput(IJob job, String videoBlobToEncodeUrl) in C:\Inter\Projects\PoC\WorkerRole\WorkerRole.cs:line 144 at EncoderWorkerRole.WorkerRole.Run() in C:\Inter\Projects\PoC\WorkerRole\WorkerRole.cs:line 40 Interestingly, I'm running that same snippet from an on-premises server i.e., outside of Azure and it works correctly. Ideas welcome, thanks! A: Found the culprit! Basically, problem was in this line encodedVideoBlob.Metadata[BlobProperty.Description] = description; There's a check well down that makes sure no null or empty metadata is being set. Found it by disassembling from Reflector and searching for ArgumentNullException ocurrences. Could be great to catch and re-throw a more meaningful exception up in the stack :-) Here are the interesting methods: internal static void AddMetadata(HttpWebRequest request, NameValueCollection metadata) { if (metadata != null) { foreach (string str in metadata.AllKeys) { AddMetadata(request, str, metadata[str]); } } } internal static void AddMetadata(HttpWebRequest request, string name, string value) { CommonUtils.AssertNotNullOrEmpty("value", value); request.Headers.Add("x-ms-meta-" + name, value); } internal static void AssertNotNullOrEmpty(string paramName, string value) { AssertNotNull(paramName, value); if (string.IsNullOrEmpty(value)) { throw new ArgumentException(Microsoft.WindowsAzure.SR.ArgumentEmptyError, paramName); } } internal static void AssertNotNull(string paramName, object value) { if (value == null) { throw new ArgumentNullException(paramName); } }
doc_23530831
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.3.2</version> </dependency>
doc_23530832
A: When you are in the directory of the deployer.phar file you can do php composer.phar --working-dir=../../ to specify the location of the composer.json file.
doc_23530833
I'm able to get the number of displays and their CGDirectDisplayID's like this: NSRect frame; NSScreen *screen; CGDirectDisplayID displays[4]; CGDisplayCount displayCount; screen = [window frame] frame = [screen frame]; err = CGGetDisplaysWithRect((CGRect){NSMinX(frame), NSMinY(frame), NSWidth(frame), NSHeight(frame)}, 4, displays, &displayCount); but I'm not able to force a window there unless I manually drag it over after it's been instantiated. Any ideas? I've seen applications that do this, but can't find any code examples or documentation. A: You can set child window's origin point. This code is not tested, but should work: NSArray *screens = [NSScreen screens]; NSPoint newFrameOriginPoint; if ([screens count]>1){ NSRect secondScreenRect = [[screens objectAtIndex:1] visibleRect]; newFrameOriginPoint = NSMakePoint(NSMinX(secondScreenRect), NSMinY(secondScreenRect)); [childWindow setFrameOrigin:newFrameOriginPoint]; } [childWindow makeKeyAndOrderFront:nil];
doc_23530834
USE ieee.std_logic_1164.ALL; USE ieee.std_logic_arith.ALL; USE ieee.std_logic_unsigned.ALL; USE ieee.numeric_std.ALL; ENTITY Lab3ALU IS PORT( opcode :IN STD_LOGIC_VECTOR(2 DOWNTO 0);--INPUT a :IN STD_LOGIC_VECTOR(31 DOWNTO 0);--INPUT b :IN STD_LOGIC_VECTOR(31 DOWNTO 0);--INPUT Cout :OUT STD_LOGIC; Zero :OUT STD_LOGIC; q :OUT STD_LOGIC_VECTOR(31 DOWNTO 0));--OUTPUT END Lab3ALU; ARCHITECTURE description of Lab3ALU IS SIGNAL Reg1, Reg2, Reg3, Result : STD_LOGIC_VECTOR(31 DOWNTO 0); SIGNAL Cin, Sum, Carry : STD_LOGIC; BEGIN -- Update the register output on the clock's rising edge process (a,b, opcode) begin Cin <= opcode(2); Reg1 <= a;--temporarirly store A in Reg1 local variable Reg2 <= b;--temporarily store B in Reg2 local variable Reg3 <= NOT b; case opcode is When "000" => Result <= Reg1 AND Reg2;--AND When "001" => Result <= Reg1 OR Reg2;--OR When "010" => addloop: for i in 0 to 31 loop Result(i) <= ((Reg1(i) XOR Reg2(i)) XOR Cin); Cin <= (((Reg1(i) XOR Reg2(i))AND Cin)OR (Reg1(i) AND Reg2(i))); end loop addloop; When "110" => subloop: for i in 0 to 31 loop Result(i) <= ((Reg1(i) XOR Reg3(i)) XOR Cin); Cin <= (((Reg1(i) XOR Reg3(i))AND Cin)OR (Reg1(i) AND Reg3(i))); end loop subloop; When "100" => Result(31 downto 1) <= reg1(30 downto 0); Result(0) <= '0'; Cin <= '0'; When "101" => Result(30 downto 0) <= reg1(31 downto 1); Result(31) <= '0'; Cin <= '0'; When others => Result <= "00000000000000000000000000000000"; end case; if Result = "00000000000000000000000000000000" then Zero <= '1'; else Zero <= '0'; end if; q<= Result; Cout<= Cin; end process; END description;```
doc_23530835
How do i get image on notification? This is what i get now1 How do i get this?2 A: Recently found out that @aws-amplify/push notification does not include images on notification for now. Image on notification have been added as a feature request.
doc_23530836
In fact, I cannot select any item of the list; I can do that only after selecting an option such as "add item" from the menu. Why ? A: I have just found out this bug: using the option android:animateLayoutChanges="true" in the layout of the ListView prevents you from selecting any item of the ListView; you can do that, only after doing something like adding a new item and returning to the ListView. I have experienced this bug using the SimpleCursorAdapter up-to-date and the one that comes with v4 support library. Hope it helps (I have wasted a lot of time !)
doc_23530837
above url contain a html table.I want to save this table value on XML and also want to save this table value on database MS2008. How to save html table values on database A: You could use HTML Agility pack like so: WebClient webClient = new WebClient(); const string strUrl = "http://www.myspace.com/centuryman"; // Setup proxy for internal stuff //System.Net.WebProxy pry = new System.Net.WebProxy("194.80.164.8", 80); //pry.Credentials = CredentialCache.DefaultCredentials; //WebRequest.DefaultWebProxy = pry; Stream s = webClient.OpenRead(strUrl); HtmlDocument doc = new HtmlDocument(); doc.Load(s); HtmlNode link = doc.DocumentNode.SelectNodes("//*[@id='profile_bandschedule']")[0]; This would return you a enumarable object which you could loop around and insert values of the html into the database. See another example: How to use HTML Agility pack A: Actually, on a typical dynamic HTML page, the table's values are loaded from the database. But, if you want, you can still parse the page's source, and save every row's values into your database. Is that what you want to do? A: You can parse the table with jQuery, create client side array or object and send it back to the server with an AJAX call or form post. HTML: <!DOCTYPE html> <html> <head> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <meta charset=utf-8 /> <title>JS Bin</title> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <table id="tableData"> <tr id="tableHeader"> <td>col1</td> <td>col2</td> </tr> <tr id="tableRow"> <td>data1row1</td> <td>data2row2</td> </tr> <tr id="tableRow"> <td>data1row2</td> <td>data2row3</td> </tr> </table> </body> </html> SCRIPT: $(document).ready(function() { //parse all the data $('#tableData tr').each(function() { if($(this).attr('id')=='tableHeader') { alert('this is the header row'); } $('td', this).each(function() { alert($(this).html()); }); }); //post the form or send data via AJAX }); A: If you use this algorithm, it is easy to pull HTML into a SQL Server database https://sourceforge.net/projects/sqldom/ I take those stored procedures and fire them in order to parse HTML and it provides REALLY beautiful parsing of HTML data into SQL Server, and it works in nearly any version of SQL Server Step 1: Download the file named 'SQLDOM_core_persist_927.sql' from the SourceForge link above Step 2: run this SQL to make a test database create database SQLDom_Test1 go use SQLDom_Test1 go Step 3: Open the script in SSMS. Go FIND/Replace and replace all '#' symbols with empty string ''. I prefer doing it this way, because I don't want to run temporary tables and temporary stored procedures. Step 4: Execute the script (note you might need to turn on Object (OLE) Automation/Scripting (the script from source forge gives you the command to do that, if necessary) Step 5: View the output, and I recommend looking at the example #3. I'd go ahead and run this code (it takes me 5 seconds, and it returns 196 rows of beautifully parsed HTML. See Step 6 (at the bottom) for further analysis --Example 3: Parse and re-render from a URL DECLARE @HTML varchar(MAX) EXEC sputilGetHTTP @URL = 'http://www.google.com', @ResponseText = @HTML OUTPUT, @SuppressResultset = 1 EXEC spactDOMLoad @HTML=@HTML EXEC spgetDOM EXEC spgetDOMHTML @PrettyWhitespace=1, @PrintHTML = 1 ----- FULL OUTPUT FROM THE SCRIPT INSTALLATION ----- (Again, if it is necessary to turn on OLE Automation, the script will inform you of that step) SQLDOM version .927 has been successfully loaded and is ready for use. In this version, stored procedures are standard persistent stored procedures that access temporary tables. Since the scope of the temporary tables needs to persist across all calls to the SQLDOM procedures on a database connection, the caller must explicitly create the temporary tables on the connection before calling SQLDOM. To obtain the SQL statement to create the temporary tables that needs to be called by the caller, do this: EXEC sdom.spgetInitSession This returns the needed SQL in three ways: in the @SQLToExecute parameter, in the SQLToExecute column in the resultset returned, and output via a PRINT statement. Execute this code on the connection before attempting to use SQLDOM. REMEMBER: you can NOT do this in a call like: EXEC(@SQLToExecute) because the scope of the temporary tables would be limited to the EXEC() statement--the temp tables would be immedately dropped after the EXEC() statement. You will likely need to copy-and-paste the SQLToExec code and manually execute that before you make calls to SQLDOM. (Temp tables HAVE been created on this connection: you can immediately try out SQLDOM here with no further initialization. But you will need to create the temp tables yourself on any new SQL connection.) Things to try: [pardon the fact that StackOverflow is butchering this mixed HTML/SQL script] --Example 1: Simple parse of string EXEC sdom.spactDOMLoad @HTML = 'Hello World.SQLDOM ROCKS!' EXEC sdom.spgetDOM --Example 2: Render HTML from DOM (that we parsed in Example 1 above) EXEC sdom.spgetDOMHTML @PrettyWhitespace=1, @PrintHTML = 1 --Example 3: Parse and re-render from a URL DECLARE @HTML varchar(MAX) EXEC sdom.sputilGetHTTP @URL = 'http://www.google.com', @ResponseText = @HTML OUTPUT, @SuppressResultset = 1 EXEC sdom.spactDOMLoad @HTML=@HTML EXEC sdom.spgetDOM EXEC sdom.spgetDOMHTML @PrettyWhitespace=1, @PrintHTML = 1 --Example 4: Parse from a string, modify the DOM, render resulting HTML EXEC sdom.spactDOMLoad @HTML = '<html><body>Hello World.<br /><div id="myContent">Future content goes here</div></body></html>' EXEC sdom.spactDOMLoad @HTML = '<div>Here is some neat stuff about <b>SQLDOM</b></div>', @Selector = '.myContent' EXEC sdom.spgetDOM EXEC sdom.spgetDOMHTML @PrettyWhitespace=1, @PrintHTML = 1 Step 6: --Show me all the hyperlinks (you will need to join this to tblDomAttribs to see the details) SELECT * FROM [dbo].[tblDOM] WHERE Tag = 'A' I'm pretty impressed that this script can chew through 50k HTML characters and it's simple to parse out whatever you are looking for. It's simple to join tblDom and tblDomAttribs, look at the tables, I believe that it is simply the DEID column you have to join on (to see the href of the A tags)
doc_23530838
Besides Bloom Filters, what other options do I have? If I could have something which mapped to a 64 bit value, it would be perfect, especially if it were algorithmic rather than a lookup table. A: If the list of events is constant and not dynamic, you could use a Minimal Perfect Hashing function. A: To guarantee zero collisions, use any standard dictionary/symbol table algorithm. That's what they do. For minimal collisions, there are all sorts of hash functions available. Bob Jenkins' lookup3.c is fairly popular. A question you then have to ask yourself is if you will be subject to maliciously chosen UUIDs. If so, you need a better hash function and a secure random salt. (If you can tolerate the speed, a keyed HMAC is the perfect way to go for this.)
doc_23530839
<?php while($row = $result->fetch_assoc()) { ?> <table border="1" width="702" height="149" align="center"> <tr> <td width="148"><img src='get.php' width='200' height='211' /> </td> </tr> </table> <?php } ?> the code in get.php <?php include ("config.php"); $image = mysql_query ("SELECT image.image FROM image JOIN products WHERE image.id = products.Image_ID"); $image = mysql_fetch_assoc ($image); $image = $image ['image']; header ("Content-type: image/jpeg"); echo $image; ?> but it gives me one image repeated in index.php.. How can I make the code take the Image_ID from the index.php to show all images in the same page? A: This is your index.php <?php while($row = $result->fetch_assoc()) { ?> <table border="1" width="702" height="149" align="center"> <tr> <td width="148"><img src='get.php?id='<?= $row['id'];?> width='200' height='211' /> </td> </tr> </table> <?php } ? And get.php <?php include ("config.php"); $image = mysql_query ("SELECT image.image FROM image JOIN products WHERE image.id = '".$_GET['id']."'"); $image = mysql_fetch_assoc ($image); $image = $image ['image']; header ("Content-type: image/jpeg"); echo $image; ?>
doc_23530840
A: Although it is a very interesting question, it is highly a matter of personal preferences and likings, so I'll answer as if you asked me personally. Note: My working system is Windows, so I'll focus on it. I can write cross-platform apps, of course, but I do that on a Windows machine. Indentation, White Spaces All indentation-related things are more or less annoying, especially if the indentation is made with multiple spaces, not tabs (yes yes, I know the whole "holy war" around it!). Python did teach me to indent code properly even in languages that don't require it, but it still hurts me to write proper Python because of these spaces. Why so? The answer is simple: my screen reader tells me the number of spaces, and the actual nesting level is four times less. Each such operation (20 spaces, aha, dividing by 4, it is fifth nesting level) brings some overhead to my mind and makes me spend my inner "CPU" resources that I could free for debugging or other fancy stuff. It is a wee little thing, you'd say, and you'd be right, but this overhead is on each and single line of my (or another person's!) code I must read or debug! This is quite a lot. Tabs are much better: 5 tabs, fifth nesting level, nice and well. Braille display here would be also a problem because, as you probably know, a Braille display (despite the name) is a single line of text, usually 14 to 40 characters long. I.e., imagine a tiny monitor with one single line of text that you pan (i.e., scroll), and nothing besides that. If 20 chars are spaces, you stay with only 20 chars left for the code. A bit more, if you read in Grade 2 Braille, but I don't know whether it would be appropriate for coding, I mostly use speech for it, except some cases. Yet more painful are some code styling standards where you have to align code in the line. For instance, this was the case with tests in moment.js. There the expected values and messages should match their line position so, for example, the opening quote would be in column 55 on every line (this is beautiful to see, I admit). I couldn't get my pull request accepted for more than a week until I finally understood what Iskren (thank him for his patience with me!), one of the main developers, was trying to tell me. As you can guess, this would be completely obvious for a sighted person. Block Endings A problem adjacent to the previous one: for me personally it is very nifty when I know that a particular code block ends. A right brace (as in C) or the word end (as in Ruby) are good, indentation level change (as in Python) is not: still some overhead on getting knowing that the nesting level has abruptly changed. IDEs Sorry to admit it, but there is virtually no comfortable IDE for the blind. The closest to such an IDE is Microsoft Visual Studio, especially the latest version (gods bless Jenny Lay-Flurrie!), Android Studio seems also moving towards accessibility starting with version 2. However, these are not as usable, nifty and comfortable as they are for the sighted users. So, for instance, I use text editors and command-line tools to write, compile and debug my code, as do many blind people around me. Ballad of the snake_case, or Another Holy War Yet another thing to blame Python about: camelCase is far more comfortable to deal with then snake_case or even PascalCase. Usually screen readers separate words written in camelCase as if they were separated with spaces, so I get no pain readingThisPartOfSentence. When you write code, you have to turn your punctuation on, otherwise you'll miss something really tiny and "unimportant", such as a quote, a semicolon or a parenthesis. Then, if your punctuation is on, and you read my_very_cool_descriptive_variable_name, you hear the following: "my underline very underline cool underline.... underline underline underline!!!" (bad language and swears censored). I tried even to replace underlines with sounds (yes, my screen reader gives such an opportunity), but the sounds can't be so well synchronized because of the higher speech rate I use. And it is quite a nightmare when dealing with methods and properties like __proto__ (aha, there are two underscores on both sides, not one, not three - well, got it right, I think!), __repr__ and so on, and so forth. Yes, you might say, I can replace the word "underline" with something really short like "un" (this is also possible), but some overhead is still here, as with white spaces and code nesting. PascalCase is far better but it implies a bit more concentration, also, since we need to remember putting the first capital letter (oh, I'm too fastidious now, let it be PascalCase, but not those under... oh well, you got it already). This was the reason I gave up with Rust, btw. Searching for Functions As I have already told you, IDEs are not good for us, so text editor is our best friend. and then, you need to search for functions and methods, as well as for classes and code blocks. In certain languages (not Python this time), there are no keyword that would start a function (see, for example, C or Java code). Searching for functions in these conditions becomes quite painful if, for example, you do know that you have a logical error somewhere in the third or fourth function in the file, but you don't exactly remember its name, or you skim through someone's code... well, you know, there are lots of reasons to do that. In this particular context, Python is good, C is not. Multiple Repeating and Alike Characters This is not a problem per se, but a circumstance that complicates debugging, for example, regular expressions or strongly nested operations like ((((a + ((b * c) - d) ** e) / f) + g) - h. this particular example is really synthetic, but you get what I mean: nested ternary operators (that I love, btw!), conditional blocks, and so on. And regular expressions, again. The Ideal Language The closest to the ideal blind-friendly language as for me is the D language. The only drawback it has is absence of the word function except for anonymous functions. PHP and Javascript are also good, but they have tons of other, blind-unrelated drawbacks, unfortunately. Update about Go In one of his talks Rob Pike, the main developer of the Go language said that no one likes the code style imposed by the Gofmt utility. Probably, no one — except me! I like it, I love it so much, every file in Go is so concise and good to read, I'm really excited about the language because of that. The only slightly annoying thing for a blind coder is when a function has several pairs of parentheses in its definition, like if it is actually a struct method. the <- channel operator still gives me moments to think about what I'm doing, sending or receiving, but I believe it's a matter of habit. Update about Visual Studio Code Believe it or not, when I was writing this answer and the first update to it, I wasn't working as a full-time developer — now I am. So many circumstances went favorably for accessibility and me in particular! Slack, that virtually every business uses, became accessible, and so became Microsoft Visual Studio Code (again, gods bless Jenny and her team!). Now I use it as my primary code editor. Yes, it's not an IDE per se, but it's sufficient for my needs. And yes, I had to rework my punctuation reading: now I have shorter and often artificial names for many punctuation signs. So, calling from end of January 2021, I definitely recommend Visual Studio Code as the coding editor for blind people and their colleagues. What is even more amazing is that LiveShare, their pair programming service, is also accessible! Yes, it does have some quirks (for now you can't tell what line in the file your colleague is editing if you're blind), but still it's an extremely huge step forward.
doc_23530841
A: You could check them before submitting form: window.URL = window.URL || window.webkitURL; $("form").submit( function( e ) { var form = this; e.preventDefault(); //Stop the submit for now //Replace with your selector to find the file input in your form var fileInput = $(this).find("input[type=file]")[0], file = fileInput.files && fileInput.files[0]; if( file ) { var img = new Image(); img.src = window.URL.createObjectURL( file ); img.onload = function() { var width = img.naturalWidth, height = img.naturalHeight; window.URL.revokeObjectURL( img.src ); if( width == 400 && height == 300 ) { form.submit(); } else { //fail } }; } else { //No file was input or browser doesn't support client side reading form.submit(); } });
doc_23530842
I am using an arduino ethernet. The devices I am trying to get data from include a GPS and an IMU both from sparkfun. I can get data from either devices using just on software serial port but as soon as I add the second software serial port, neither ports will work. I can't use the hardware serial port because that is being used byt another device. My code is exactly similar to the example: #include <SoftwareSerial.h> SoftwareSerial portOne(7,8); SoftwareSerial portTwo(5,6); void setup() { Serial.begin(9600); portOne.begin(9600); portTwo.begin(9600); } void loop() { portOne.listen(); while (portOne.available() > 0) { char inByte = portOne.read(); Serial.write(inByte); } delay(500); portTwo.listen(); while (portTwo.available() > 0) { char inByte = portTwo.read(); Serial.write(inByte); } Serial.println(); } Anyone with any ideas? A: This code will not work, or will work poorly if it works at all. SoftwareSerial only has one internal buffer. Yes, you can have multiple SoftwareSerial objects in existence, but only one of them controls the internal buffer. When any RX pin gets asserted, that generates an interrupt, but only the listen()ing RX pin gets checked for a start bit. What's really needed is the ability to check on multiple pins when an interrupt comes along from the start bit. Then you'd have to set up pointers to the appropriate data structures. It would be complicated, but possible. Or maybe just give up on interrupt-driven reception, and spin on checking both/all of the RX pins, and start the receive based on the pin you see. Be forwarned that this code has much hair, and you WILL need an oscilloscope to make it work. I'm having a similar problem, which is why I found your sensor. After talking it over with my co-workers, we've decided to read our sensors in rotating order. Our sensors report the current state of the sensor, and not specific events, so it's okay if we lose some reports. So we'll read from port 1, then read from port 2, then port 1, etc. Our sensors spit out lines of text, so we know when to switch to the next sensor. A: The referenced example only actively listens to one port at a time. The recommended solution would be to upgrade to an Arduino Mega (https://www.sparkfun.com/products/11061) which has 4 hardware serial ports. In order to simultaneously support two software serial ports is going to require a lot of the CPU resources. It also be a difficult design and excessive programming time far outweighing the cost of $58 + shipping. Looking at you code again it occurs to me that you are immediately checking for characters after your portOne.listen command. At 9600 baud it will take approximately 1ms for the first character to arrive, your while test will have been completed and the portTwo.listen command executed long before the first character arrives. For testing purposes try adding a 1-2 ms delay after the portOne.listen command and see if you get a character. As an example (untested and note, if port one is sending characters with no intercharacter gaps, the first while will never fail, preventing reading portTwo characters): void loop() { portOne.listen(); delay(2); while (portOne.available() > 0) { char inByte = portOne.read(); Serial.write(inByte); delay(1); } portTwo.listen(); delay(2); while (portTwo.available() > 0) { char inByte = portTwo.read(); Serial.write(inByte); delay(1); } Serial.println(); } A: Don't use while ...... Use: { portOne.listen(); if (PortOne.available() ) { ricevo = myPort1.read(); } // delay(2); // ridiculos waiting time // delay(1); // extra ridiculos waiting time Than 500 ms is a too big time for switching, no time.....
doc_23530843
self.navigationController?.navigationBar.shadowImage = UIImage() to remove the border of a navigationBar earlier in my app but now I'm not sure to add the border back on a later screen. A: To reset the navigationBar's shadowImage to the default shadowImage do the following: self.navigationController?.navigationBar.shadowImage = UINavigationBar().shadowImage
doc_23530844
Essentially what it then does, is the Raycast picks up what it collided with, and then opens the "NPC" script inside that object. I do this to differentiate the NPCs, as in the future I can change the code for different NPCs using Serialization. Okay, again this also works fine based on my debugging, my problem seems to be happening further ahead. This NPC script then activates a variable on another my "NPCMaster" script called "DialogueActive". According to my debugging this also works, the problem is, is that despite both my NPCs being pretty much exactly the same, and are both correctly activating this variable one of them will not activate the if statement checking if "DialogueActive" == true. The odd thing is, when I change their names, to both the same name, or change their names completely, or delete, and copy the prefab, the broken NPC changes. Yet once I place them, one NPC is broken and the other isn't, it is not depending on who I talk to first or anything. And I can talk to the non-broken NPC as many times as I want and it will always work. I have tried a bunch of things, I have tried changing how I activate the variable (despite it not being where the problem begins) I have tried deleting them both, duplicating them, making them have the same name, but then the broken NPC will just switch places. Like I said, I am new to C# unity, and pretty much coding in general so the problem likely results from my ignorance. //The if statement where the problem happens. void Update() { if (DialogueActive == true) { Debug.Log("Test2"); panelexist.enabled = true; maintext.text = dialogue; } else { panelexist.enabled = false; maintext.text = ""; } } //The variable which activates the "DialogueActive" variable. void Update() { if (Interacting == true) { Debug.Log("Test1"); obj.GetComponent<NPCMasterScr> ().DialogueActive = true; } else { obj.GetComponent<NPCMasterScr> ().DialogueActive = false; } if (Input.GetKeyUp("escape")) { Interacting = false; obj.GetComponent<NPCMasterScr> ().DialogueActive = false; } } I expected the if (DialogueActive == true) statement to activate the code below it, which it did in one case but not another. A: Seems like your scripts doing some conflicting things. This part: if (Interacting == true) { Debug.Log("Test1"); obj.GetComponent<NPCMasterScr> ().DialogueActive = true; } else { obj.GetComponent<NPCMasterScr> ().DialogueActive = false; } This will work correctly on the script that is higher in the hierarchy. When the second script trying to do something when if = true, the first script blocking this via its else. So, when the second script trying to obj.GetComponent<NPCMasterScr> ().DialogueActive = true;, the first script does obj.GetComponent<NPCMasterScr> ().DialogueActive = false;. Update 1: The following code may help to understand the problem. void Update() { if (Interacting == true) { Debug.Log("Test1"); obj.GetComponent<NPCMasterScr> ().DialogueActive = true; } if (Input.GetKeyDown("escape")) { Interacting = false; obj.GetComponent<NPCMasterScr> ().DialogueActive = false; } } HOW-TO-USE: * *Interact with the firs object *Stop interacting *Press Esc (interacting should be stopped before this step!) *Interact with the second object ... and control DialogueActive state for each step
doc_23530845
I'm doing something like this for the rotation: $("#container div").first().appendTo('#container').fadeOut(5000); $("#container div").first().fadeIn(5000); So I'm assuming it has something to do with the appended text after the font is applied. Or something. I'm fairly new to fontface, so this may be something I'm doing wrong. Relevant CSS: @font-face { font-family: 'OpenSansRegular'; src: url('fonts/OpenSans-Regular-webfont.eot'); src: url('fonts/OpenSans-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/OpenSans-Regular-webfont.woff') format('woff'), url('fonts/OpenSans-Regular-webfont.ttf') format('truetype'), url('fonts/OpenSans-Regular-webfont.svg#OpenSansRegular') format('svg'); font-weight: normal; font-style: normal; } #homecontainer span { float: right; display:block; font-family:OpenSansRegular,Ariel, Helvetica, sans-serif; } The text is showing up as Ariel. The rest of the text that uses this font works fine. Any ideas? A: Try: font-family:OpenSansRegular,Ariel, Helvetica, sans-serif; to font-family:'OpenSansRegular',Ariel, Helvetica, sans-serif; Also double check your CSS selection with something obnoxious font-size:50px;color:pink; to make sure you are actually applying that font to the proper region.
doc_23530846
int main(int argc, char** argv) { if (argc != 1) return -1; ofstream fTestFile; fTestFile.open("C:\\ABC\\ServiceTest.txt", ios::app); fTestFile << "argc=" << argc << endl; for (int i=0;i <argc;i++) fTestFile << "argv " << i << "=: " <<argv[i] << endl; for (int i=0; i<100000; i++) { fTestFile << i << ","; if (i % 50 == 0) fTestFile << "\n"; Sleep(10); } fTestFile << "\n"; return 0; } When I click "Start" via services.msc on this service, the service tries to start but fails with (1053 error Taking too long to respond). In the servicetest.txt file I see some data, like I see the debug statements and I see the numbers till 2663 or something. Is there a step that I am missing, any help greatly appreciated. Thank You A: Your service needs to communicate with the service manager (services.exe) to report and update it's current status. Read here http://msdn.microsoft.com/en-us/library/windows/desktop/ms687414%28v=vs.85%29.aspx
doc_23530847
I want send a signal starting in a child1, catch by parentprocess and, after that, send the same signal to child process 2. When child 2 receive the signal, i want to send another signal back to parent child, and then parent child kill both child processes. I have tried this: new_pid = fork(); sleep(3); switch(new_pid) { case -1: perror("fork failed"); exit(1); case 0: kill(getppid(), SIGUSR1); sleep(3); pause(); break; default: signal(SIGUSR1, trata_SIGSEGV); sleep(3); new_pid2 = fork(); sleep(3); kill(new_pid2, SIGUSR1); sleep(3); switch(new_pid2) { case -1: perror("fork failed"); case 0: signal(SIGUSR1, trata_SIGSEGV); kill(getppid(), SIGUSR2); sleep(3); pause(); break; default: signal(SIGUSR2, trata_SIGSEGV); kill(new_pid, SIGKILL); kill(new_pid2, SIGKILL); break; } break; Only parent child receive the signal, then nothing happens and go to program menu). void trata_SIGSEGV(int sig){ if (sig == SIGUSR1) { printf("Received"); } if (sig == SIGUSR2) { printf("Received"); } if (sig == SIGINT) { printf("Received"); } } A: There's several issues going on here. There may be more in trata_SIGSEGV. * *You give no time after forking for the processes to set up to be ready for processing. As you're sending default termination signals, it's likely they're killing the recipient before the recipient is listening for them. (Are you thinking signal waits for a signal? It doesn't; it merely configures what should be done if/when the signal happens.) *Line 19 is attempting to send the trata_SIGSEGV signal to process SIGUSR2. That's not going to work. *You end with the problem you start with - the main execution thread has no delays in its processing from forking off the processes to telling the scheduler to simply end them. On a modern computer, probably even a millisecond delay would be far more than enough time for the signal handlers to be set up. But if you want them to happen reliably, you need to give at least some delay for the other processes to get where they need to be. Alternatively, I think you could set up the signal handlers in the parent and then fork. Given your update, I'm wondering how you know which process got what signal. My suggestion for your signal handler: void trata_SIGSEGV(int sig) { printf("%d received signal %d\n", getpid(), sig); if (SIGINT == sig) exit(1); } Also, I'm noticing you're sending the first signal to process 2 before checking what the fork return is, so process 2 is signalling itself before it can possibly have the signal handlers set up. Set up the signal handlers before you do any forking, so there's no race there. I've verified in my own test of your code that the signal handlers are retained across fork.
doc_23530848
I'm wanting to create a library of iPhone apps that each will have the same User Logon screen. Therefore, I want to create the LogonScreen ViewController once and then share it amongst my projects. I tried adding the files as a 'link' like you do with files in Visual studio but that seemed to create a disjoint between the Login.cs and the Login.designer.cs ie the Login.Designer.cs does not appear underneath the Login.cs in the Solution explorer. The Login.cs has also lost the reference to the txtUsername textbox control I have in my xib. Any ideas on how to solve this problem? A: If I'm understanding your problem correctly this will get you on track: Dimitris Tavlikos Answer This will produce a custom class which you can abstract into a common library for your applications. -Nick A: Would advise you to add your shared views in a separated project (iOS Library Project) and add this project as a reference. You won't have the problems of linking separate files in each future project, which would get more and more complicated when you will have more shared views. The reason why you lost the reference to your textfield is because it 'lost' the designer.cs file, which has these references.
doc_23530849
const simulation = d3.forceSimulation(nodes) .force( 'charge', d3.forceManyBody() .distanceMax(200) .strength(-50) ) .force( 'link', d3.forceLink(links) .id((d) => d.id) .distance(30) ) .force( 'center', d3.forceCenter( $svg.innerWidth() / 2, $svg.innerHeight() / 2, ) ); this looks good with all nodes visible – but there will also be the possibility to filter/remove nodes, in which case I would want the graph to be way more compact than it actually is (see animation). this is probably due to the fact that there are no edges between the remaining nodes, and the fact that they are already spread out a lot when the new simulation starts. while I could simply reset all node positions to the center of the canvas, that would not look great transition-wise. ideally each node would move from its current position to its new position in a more compact layout. is there a way to achieve this? I thought maybe the forceManyBody strength could transition from a positive value (attraction) at first to a negative value (repulsion), but apparently this value is can only be set once for the run of the simulation. A: adding an attraction force (https://github.com/ericsoco/d3-force-attract) works well enough.
doc_23530850
typedef std::shared_ptr<MediaItem> MediaItemPtr; typedef std::shared_ptr<ImageMediaItem> ImageMediaItemPtr; class MediaItem { //stuff here } class ImageMediaItem : public MediaItem { //more stuff here } Internally, I pass everything around as a MediaItemPtr object, but when I try to cast to a ImageMediaItemPtr, nothing I try seems to work. For example: ImageMediaItemPtr item = std::dynamic_pointer_cast<ImageMediaItemPtr>(theItem); //theItem is MediaItemPtr Fails with error C2440: 'initializing' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'std::tr1::shared_ptr<_Ty>' Any thoughts of how this cast should actually work? I'm a bit new to shared_ptr A: Try: ImageMediaItemPtr item = std::dynamic_pointer_cast<ImageMediaItem>(theItem); A: The template argument to dynamic_pointer_cast should be the pointed-to type. In other words, it should be T and not shared_ptr<T>. In this case, it should be dynamic_pointer_cast<ImageMediaItem> and not dynamic_pointer_cast<ImageMediaItemPtr>.
doc_23530851
// I don't want this, because it breaks the rest of the application. I have // implemented zooming and landmark placement functionality, which no longer // work properly after scaling. ctx.save(); ctx.scale(-1, 1); ctx.drawImage(image, -image.width, 0, image.width, image.height); ctx.restore(); It seems to me that I should be able to do this with the CanvasRenderingContext2D.drawImage() method, since that page reads: sWidth: The width of the sub-rectangle of the source image to draw into the destination context. If not specified, the entire rectangle from the coordinates specified by sx and sy to the bottom-right corner of the image is used. If you specify a negative value, the image is flipped horizontally when drawn. This is how I draw the image: var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var image = document.getElementById('source'); ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, image.width, image.height); Working example here: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage#Using_the_drawImage_method But if I try to flip the image as per the description, I get the following error in Firefox: ctx.drawImage(image, 0, 0, -image.width, image.height, 0, 0, image.width, image.height); IndexSizeError: Index or size is negative or greater than the allowed amount I don't understand what I'm doing wrong here. How can I flip an image horizontally without scaling the canvas? A: A fairly simple solution would be to use a second canvas, draw the image there flipped only once, then draw that portion of the other canvas onto your main canvas. That would successfully create a flipped version of your image, cached, and you can draw it wherever you want. A: Negative region does not seem to be supported (yet?), or this line may affect how the implementation is done, ref. step 4: The image data must be processed in the original direction, even if the dimensions given are negative. In any case, we can't do much about it but to look at alternative ways - This leaves you with some options though - I assume you want to avoid using save/restore, and you can - Reset transformation This is the fastest method, but you need to be aware of that it will reset any transformation. And this may be OK in most cases, so: ctx.scale(-1, 1); ctx.drawImage(image, -image.width, 0); ctx.setTransform(1, 0, 0, 1, 0, 0); The last call is resetting the transformation matrix using an identity matrix. Reversing last transformation operation If you depend on other transformations, you can simply reverse the last transformation operation. This is the second fastest option (it need to do a matrix multiplication internally): ctx.scale(-1, 1); ctx.drawImage(image, -image.width, 0); ctx.scale(-1, 1); // revert scale only Using save/restore As you already know... but slow as it saves and restores the whole state of the canvas, not just the transformation. Flipping manually If there for some reason is a requirement not to use transformation at all, you can always flip it scanline by scanline. This is the second least efficient method but allows you to work without transformations, and it does allow you to do other things like displacing: for(var x = 0; x < width; x++) ctx.drawImage(img, x, 0, 1, height, width - x, 0, 1, height); (width and height being the image's width and height). Pixel manipulation And the last, just for the record, is of course to get the pixel data and loop through, switch places etc. This is the slowest method and it depends on CORS requirement, and is not recommended for this.
doc_23530852
use bs58; i = b"Hello"; // or i = [0,1,2,3]; // or i = vec![0,1,2,3]; let e = bs58::encode(i).with_check().into_string(); No matter what type I supply to bs58::encode(), it errors out saying that method with_check() not found. Coming from Python, it's really frustrating because I have to spend hours debugging simple stuff that should just work. A: If you look in the API documentation for bs58::encode, you see that it returns a EncodeBuilder. Looking at the documentation for that, you see that there is a with_check method but it has a note attached to it: This is supported on crate feature check only. Rust supports crates defining optional features - these features typically have extra dependancies that are not needed in all cases, so they are off by default. You can enable the extra features in your Cargo.toml file, like this: [dependancies] bs58 = { version="0.4.0", features=["check"] } See also the Features section of the Cargo book.
doc_23530853
A: You might be able to resolve your issue by increasing the maximum JVM Heap Size configured on your server. To change the JVM Heap Size, navigate to Servers > WebSphere Application Servers > [server_name] > Java and process management > Process definition > Java virtual machine. Adjust the minimum and maximum values for Heap Size and restart your server for the changes to take effect. Please be aware that tuning your JVM is a highly complex process. You can use the information at this IBM Documentation link as a starting point. To identify why your application is throwing an OOM error, you will have to perform some form of analysis. To do this, you need to simulate the expected production load on a different testing environment. Then you can collect PMI statistics, Javacores, Heap dumps, Core dumps and use them to identify why your applications encounter an OOM error.
doc_23530854
I create the splash screen here: public class MainActivity extends ReactActivity { @Override protected void onCreate(Bundle savedInstanceState) { SplashScreen.show(this, R.style.SplashTheme, true); super.onCreate(savedInstanceState); } ... } And I hide the splash screen here: const App = () => { changeNavigationBarColor('white', true, true); // HERE useEffect(() => { setTimeout(() => { SplashScreen.hide(); }, 3000); }, []); return ( ... ); } export default App; I'm following this video tutorial, that uses this library. A: There is no property like that in react-native-splash-screen. Simply you can't. But it supposes to fade out as I know. Maybe you can't see because of the emulator skipping some frames. A: You can make use of this library which has argument called fade when executing hide function. Simply do, RNBootSplash.hide({ fade: true }); // fade
doc_23530855
typedef Card* Cardptr; Does this mean that foo in the following declaration Cardptr foo; is the same as in this declaration?: struct Card{ } *foo; The appearance of the * symbol has me confused because it appears adjacent to Card in the statement that we're given and appears adjacent to foo in the statement with *foo A: Does this mean that foo in the following declaration ... is the same as in this declaration? ... Yes and no. I say yes because both declarations declare a pointer variable to the type named Card (in C++, for C to apply as well, it must be struct Card). But it's not exactly the same. The first declaration can introduce what is called an "opaque handle". The struct doesn't need to be fully defined at that point. You can pass pointers to it around, but you won't be able to access any members until the full definition is seen. The second declaration introduces the complete type and immediately creates a pointer to it. It's equivalent to the first case after the full structure definition is seen. The appearance of the * symbol has me confused because it appears adjacent to Card in the statement that we're given and appears adjacent to foo in the statement with *foo The adjacency of * is immaterial. Since it's applied the same regardless of where you write it. It modifies the newly declared entity, not the type. To illustrate: int *i, j; Will create only one pointer, named i, and a regular integer named j. Since typedef statements follow the same rules as variables declarations (the application of the typedef keyword just changes the meaning from introducing a new object, to introducing a new type name), the behavior of * is equivalent. Meaning that here: typedef int *i, j; The * again modifies only i. We end up with two aliases. The alias i which is a new type name for a pointer to an int, and j which is an alias for an int. In fact, we could have rewritten it as follows to get the same effect: typedef int j, *i; Again, because * modifies only i. A: [for C++] Yes: you can create a variable foo that's a Card* at the tail end of the struct Card definition as you've illustrated, and it's equivalent to the Cardptr foo above (assuming an earlier definition of Card) as in: struct Card { }; typedef Card* Cardptr; Cardptr foo; People sometimes do the trailing *foo thing for concision - it avoids having to repeat the type.
doc_23530856
I'm able to get a 'resampled to daily' result, but the type is ommitted. The code below should be a fully working example (well, working apart from the known error at the end!): import pandas as pd import datetime as dt df = pd.DataFrame({ 'Date': [dt.datetime(2021,1,1), dt.datetime(2021, 1, 3), dt.datetime(2020,1,2)], 'Type': ['A', 'A', 'B'], 'Value': [1,2,3] }) df.set_index('Date', inplace=True) # this loses the 'type' print(df.resample('1D').mean()) df = df.reset_index().set_index(['Date', 'Type']) # this raises an exception "TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'" print(df.resample('1D').mean()) Output I'm looking for is a row for every day / type combo: date type value 20210101 A 1 20210102 A NaN 20210103 A 2 20210101 B NaN 20210102 B 3 20210103 B NaN Any advice or pointers gratefully received. A: If need resample per groups is possible use Grouper for resample per days and then for add missing values is used Series.unstack with DataFrame.stack: df = (df.groupby(['Type', pd.Grouper(freq='1D', key='Date')])['Value'] .mean() .unstack() .stack(dropna=False) .reset_index(name='Value') ) print (df) Type Date Value 0 A 2021-01-01 1.0 1 A 2021-01-02 NaN 2 A 2021-01-03 2.0 3 B 2021-01-01 NaN 4 B 2021-01-02 3.0 5 B 2021-01-03 NaN If need only append missing datetimes per groups is used DataFrame.reindex: mux = pd.MultiIndex.from_product([df['Type'].unique(), pd.date_range(df['Date'].min(), df['Date'].max())], names=['Date','Type']) df = df.set_index(['Type','Date']).reindex(mux).reset_index() print (df) Date Type Value 0 A 2021-01-01 1.0 1 A 2021-01-02 NaN 2 A 2021-01-03 2.0 3 B 2021-01-01 NaN 4 B 2021-01-02 3.0 5 B 2021-01-03 NaN
doc_23530857
basically it is: (goalsScoredAtHome + goalsScoredAway) - (goalsConciededAtHome + goalsConciededAway) Everything is saved in one table: homeTeam | awayTeam | goalsHome | goalsAway USA | Poland | 2 | 0 Poland | USA | 3 | 1 this is what I have as 4 separate queries: (select sum(goalsHome) as GoalsScoredHome from game where home = 'USA' + select sum(goalsAway) as GoalsScoredAway from game where away = 'USA') - (select sum(goalsAway) as GoalsConciededHome from game where home = 'USA' + select sum(goalsHome) as GoalsConciededAway from game where away = 'USA') Is there any way to do it in one query? A: A direct translation of your query uses conditional aggregation: select (sum(case when home = 'USA' then goalsHome else 0 end) + sum(case when away = 'USA' then goalsAway else 0 end) ) - (sum(case when home = 'USA' then goalsAway else 0 end) + sum(case when away = 'USA' then goalsHome else 0 end) ) from game; You can simplify this to: select (sum(case when home = 'USA' then goalsHome - goalsAway else 0 end) + sum(case when away = 'USA' then goalsAway - goalsHome else 0 end) ) from game; A: You can do like the following select sum(gs-gs) as GoalScore from( select sum(GoalsScore1) as gs from ( select sum(goalsHome) as GoalsScore1 from game where homeTeam = 'USA' union all select sum(goalsAway) as GoalsScore1 from game where awayTeam = 'USA' )gs1 union all select sum(GoalsScore2) as gs from ( select sum(goalsHome) as GoalsScore2 from game where homeTeam = 'USA' union all select sum(goalsAway) as GoalsScore2 from game where awayTeam = 'USA' )gs2 )gs3
doc_23530858
I have went through the tutorial about the structure of swift, but what's really giving me headache now is the UI widgets * *keyboard covers up textfield. how can I make it so view would get pushed up if textfield is covered but does nothing when textfield is visible. the example I found here would push the view up or down to be exactly right above the keyboard, but pushing the view down isn't what I want. *how can I have the error icon on the right within the textfield like this? and also how to add an additional row of navigation right above the keyboard to allow user go backward/forward and Done *I found a Date Picker in Object library, but it takes a lot of space. What I want is like the screenshot below. it pushes the view up when user click on something then disappear when done. and also the same question on how to have the additional nav bar right on the top of keyboard *I don't know if it's going to be the same thing as Date Picker. I also want a list show up at the bottom when event is triggered. Can someone please please help me? or direct me to the right article. I found myself having really hard time on UI when coding in swift :( A: Quick fix: You can use this, which is a subclass of ViewController that won't let UITextFields be hidden by the keyboard. (more details on link) Hard way: Implement by yourself a method which respond when keyboard is show, get its height and textfield location, then move view of viewController. And another method to respond when keyboard is dismiss to restore view of viewController. Edit: For textFields, its better put image right of textfield, or maybe upon textField (but its ugly when there is text behind). That bar is a accessory view and you can use in any textField, even when you’re using DatePicker or PickerView. For Datepicker, here there is a simple way. For Accessory view: Swift code //TODO:First tag all textFields in your view, starting by 1. //In your viewController var textFields:[UITextField]? = nil //Class attribute var activeTextField:UITextField? = nil //Class attribute override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) textFields = [UITextField]() searchTextFields(self.view) setAccessoryView() } //MARK: Helper functions //Search for all textFields in your view (and subviews), if tag is greater than 0, connect delegate and append to ‘textFields’ array. func searchTextFields(_view: UIView) { for subView in _view.subviews { if subView.isKindOfClass(UITextField) { let textField = subView as UITextField if textField.tag > 0 { textField.delegate = self textFields?.append(subView as UITextField) } } else if subView.isKindOfClass(UIView) { searchTextFields(subView as UIView) } } } func setAccessoryView() { if textFields != nil { //Create buttons let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let ok = UIBarButtonItem(title: "OK", style: UIBarButtonItemStyle.Done, target: self, action: "okButtonAction") //TODO: Place your own images let next = UIBarButtonItem(image: UIImage(named: "setaDireita"), style: UIBarButtonItemStyle.Plain, target: self, action: "nextButton") let previous = UIBarButtonItem(image: UIImage(named: "setaEsquerda"), style: UIBarButtonItemStyle.Plain, target: self, action: "previousButton") //Order buttons let itensToolbar = NSMutableArray(array: [previous, next, space, ok]) //Create toolbar let toolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.width, 0)) toolbar.barStyle = UIBarStyle.Default toolbar.items = itensToolbar toolbar.sizeToFit() //Set toolbar for textField in textFields! { textField.inputAccessoryView = toolbar } } } //MARK: Actions AccessoryView func okButtonAction() { //You can do whatever you want self.activeTextField?.resignFirstResponder() } func nextButton() { if activeTextField?.tag != textFields?.last?.tag { textFields?[activeTextField!.tag].becomeFirstResponder() } } func previousButton() { if activeTextField?.tag != textFields?.first?.tag { textFields?[activeTextField!.tag - 2].becomeFirstResponder() } } //MARK: UITextFieldDelegate func textFieldDidBeginEditing(textField: UITextField) { self.activeTextField = textField let toolbar = textField.inputAccessoryView as UIToolbar if textField.tag == textFields?.first?.tag { (toolbar.items?[0] as UIBarButtonItem).enabled = false (toolbar.items?[1] as UIBarButtonItem).enabled = true } else if textField.tag == textFields?.last?.tag { (toolbar.items?[0] as UIBarButtonItem).enabled = true (toolbar.items?[1] as UIBarButtonItem).enabled = false } else { (toolbar.items?[0] as UIBarButtonItem).enabled = true (toolbar.items?[1] as UIBarButtonItem).enabled = true } } Hope helps you.
doc_23530859
The window reflect the full change set that would be updated for a document. As you can see in the Example which uses the default analyzer. We are only given the option to either update all classes in the document to be upper case or none of them. How can I register a change so that it creates an indiviual check box for each change that would be made to the document and not the full change set?
doc_23530860
q.items = [{ label: "1" }, { label: "2" }]; q.activeItems = [{ label: "2" }]; q.show(); Based on my understand of vscode extension api doc. /** * Active items. This can be read and updated by the extension. */ activeItems: readonly T[]; it should active "2" item when quickpick is showing. But I found activeItems will reset after show() method; I dont know why and cant find any same issue in the internet, A: it seems that a bug is impacting behavior here my solution was to set the active items after calling the show method. Also it seems the code does reference comparisons. So const q = vscode.window.createQuickPick(); const selectedItem = { label: "2" }; q.items = [{ label: "1" }, selectedItem]; q.show(); q.activeItems = [selectedItem];
doc_23530861
MainWindow: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Window1 window1 = new Window1(); if (sender.Equals(boton1)) { window1.info.Content = "You pressed button 1"; } else { window1.info.Content = "You pressed button 2"; } window1.Show(); this.Close(); } } Window1: public partial class Window1 : Window { public Window1() { InitializeComponent(); } MainWindow main; private void Button_Click(object sender, RoutedEventArgs e) { main = new MainWindow(); if (Convert.ToString(label.Content) == "You pressed button 1") { main.label1.Content = textBox.Text; } else { main.label2.Content = textBox.Text; } main.Show(); this.Close(); } } My complete project is a little different but larger. Sorry if you don't understand me, I'm not a native english speaker. A: As was said earlier you are creating a new MainWindow which is negating all of your previous changes, Try assigning the MainWindow as the Owner of Window1 that way you can reference back to the originating Window. Something like this: MainWindow: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Window1 window1 = new Window1(); if (sender.Equals(boton1)) { window1.info.Content = "You pressed button 1"; } else { window1.info.Content = "You pressed button 2"; } window1.Owner = this; //Note I am adding the Owner here window1.Show(); Hide(); // I also am hiding the MainWindow instead of closing it. } } Window1: public partial class Window1 : Window { MainWindow main; public Window1() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { main = (MainWindow)Owner; /Note I am using the owner not creating a new MainWindow if (Convert.ToString(label.Content) == "You pressed button 1") { main.label1.Content = textBox.Text; } else { main.label2.Content = textBox.Text; } main.Show(); this.Close(); } } A: Because u re-creating MainWindow. Every time when you open new Window, u are creating new instance of MainWindow in this class, thats why old textbox are cleared. Try something like this: MainWindow: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Window1 window1 = new Window1(); if (sender.Equals(boton1)) { window1.info.Content = "You pressed button 1"; } else { window1.info.Content = "You pressed button 2"; } window1.ShowDialog(); YourTexbox.Text = window1.YourText; } } Window1: public partial class Window1 : Window { public string YourText {get; set;} public Window1() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (Convert.ToString(label.Content) == "You pressed button 1") { YourText = textBox.Text; } else { YourText = textBox.Text; } this.Close(); } }
doc_23530862
A: * *Implement scrollView delegate's scrollViewDidScroll:. *In scrollViewDidScroll: implementation: Get the visible rect of the contentView of the scrollview. Here's how. *Check if the subview you want to animate is within the visible rect using CGRectContainsRect(). This is not tested but hope this help: - (void) scrollViewDidScroll:(UIScrollView *)scrollView { // get the scrollView's contentView visible rect // from here: https://stackoverflow.com/questions/868288/getting-the-visible-rect-of-an-uiscrollviews-content CGRect visibleRect; visibleRect.origin = scrollView.contentOffset; visibleRect.size = scrollView.contentSize; if( CGRectContainsRect(visibleRect, rectOfScrollViewSubviewYouWantToAnimate) ) { // NOTE: This will be called multiple times as the scrollview moves // do your animation here: } else { // rectOfScrollViewSubviewYouWantToAnimate is out of scrollView Visible area } } A: Please go to this page , This might help you . I tried it on one imageview. Similarly you can perform this for all imageview in your code. [blog] : http ://icodeguru.blogspot.in/2014/09/animated-imageview-stops-animating-when.html
doc_23530863
URL | Last_Updated | Reviewed | Date_Found | Crawl_Date URL.html | January 21, 2016 | April 11, 2016 | 2019-02-11T03:50:01Z/ | 2021-03-04 01:27:08 And secondly, I need to get a "max" field, but it has to prioritize the last_updated date field. I'm assuming it'll end up being some kind of if/then statement but I'm not sure how to proceed without a standardized date format for the 4 dates I have. Ultimately, I need to use this "max_date" to identify the number of days between the crawl_date and the last_updated date. So far, I have this - URLtoDate$date_diff <- as.Date(as.character(URLtoDate$crawl_date), format="%Y/%m/%d")- as.Date(as.character(URLtoDate$max.date), format="%Y/%m/%d") But, as my dates aren't in the same format, I'm getting NAs across the dataset. Any help is greatly appreciated.
doc_23530864
I've got a basic sorting system (by ID, ascending/descending) already which works fine on my end, but I also want to be able to filter the films by genre (e.g if film is marked as Action on database, make all non-action films hidden. This cannot be done by CSS alone as I'm not able to add classes to the content within the containers, the container for the film image is generated via JS. I'm assuming I need to create a new function such as function getFilmListByGenre(genreName) Or something along those lines, but I don't know how I'd make it work. Here is the current Javascript that I have, which creates the sort feature. let db = new PouchDB('films'); let radios = document.getElementsByName("sort"); radios[0].addEventListener("change", getFilmList); radios[1].addEventListener("change", getFilmList); getFilmList(); function getFilmList(){ db.allDocs({include_docs: true, descending: radios[0].checked}).then(function(films){ let listContents = ''; for(let i = 0; i < films.total_rows; i++) { let thisFilm = films.rows[i].doc; let image = '<a class="btn" href="viewFilm.html?id=' + thisFilm._id +'"><img class="filmImage" src="' + thisFilm.image +'"></a>'; listContents += '<div class="filmRow">'+ image + '</div>'; } document.getElementById('filmContainer').innerHTML = listContents; }) } I basically want to grab the value for genre (which can only be "Action", "Comedy", "Horror" or "Other") for each film from the database, then if the corresponding radio (named filter) is selected, all of the films which aren't labelled as that genre are hidden. @import url(https://fonts.googleapis.com/css?family=Raleway); body { margin: 0; font-family: 'Raleway', georgia, arial; background-color: #e0e0e0; text-align: center; } h1 { color: #aaaaaa; text-align: left; } .sortFilms { text-align: left; display: inline-block; background-color: #ff6699; width: 80%; padding: 20px; } header { text-align: center; display: inline-block; border-bottom: 5px; border-top: 0; border-left: 0; border-right: 0; border-style: solid; border-color: #aaaaaa; width: 80%; padding: 20px; background-color: #e0e0e0; } .newFilm { text-align: left; display: inline-block; background-color: #ff6699; width: 80%; padding: 20px; } label { font-size: 1em; padding: 6px; color: #fff; font-weight: 700; display: block; text-align: left; } .form { margin: auto; display: flex; text-align: center; flex-direction: column; } h2 { font-weight: 700; font-size: 2em; width: 50%; color: #B2365F; } #formTitle { margin-top: 0; margin-bottom: 0; } .row { margin-left: -20px; display: grid; grid-template-columns: 1fr 1fr; } .col { padding: 20px; } input, textarea, select { width: 100%; display: block; border-radius: 25px; background-color: #e0e0e0; padding: 10px; border: none; box-sizing:border-box; } } .tagline { margin: 0; color: #333333; font-size: 1em; font-weight: 700; } input::placeholder { color: #000; } textarea::placeholder { color: #000; } #modifyFilmButton { float: right; } @media only screen and (max-width: 700px) { .row { grid-template-columns: 1fr; } } @media screen and (max-width:800px) { table { border: 0; } table caption { font-size: 1.3em; } table thead { border: none; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } table tr { border: 2px solid #e0e0e0; background-color: #e0e0e0; display: block; margin-bottom: .625em; border-radius: 20px; } table td { display: block; font-weight: bold; font-size: 1.2em; text-align: left; padding: 15px; } table td::before { /* * aria-label has no advantage, it won't be read inside a table content: attr(aria-label); */ content: attr(data-label); float: left; font-weight: bold; text-transform: uppercase; } table td:last-child { border-bottom: 0; } } .oldFilm { border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; text-align: left; display: inline-block; background-color: #AAAAAA; width: 80%; padding: 20px; } #oldTitle { margin-top: 0; margin-bottom: 0; color: #ff6699; padding-bottom: 20px; } td { padding: 5px; font-weight: bold; } table { border-collapse: collapse; text-align: center; width: 100%; } thead { background: #ff6699; } .reviewImage { width: 200px; border-radius: 20px; } .filmRow img { width: 300px; height: 420px; margin: 10px; border-radius: 20px; } .filmRow { -webkit-flex-flow: row wrap; justify-content: space-around; } #filmContainer { width: 100%; margin-top: 10px; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-around; } #date { padding: 5px; text-align: left; width: 30%; } #date input { width: auto; } #date label { display: -webkit-inline-box; } #oldTitle2 { margin-top: 0; margin-bottom: 0; color: #ff6699; } .genre { padding: 5px; text-align: left; width: 60%; } .genre input { width:auto; } .genre label { display: -webkit-inline-box; } <div class="sortFilms"> <h2 id="formTitle">Latest reviews</h2> <div id='filmContainer'></div> </div> <div class="oldFilm"> <h2 id="oldTitle2">Sort by</h2> <div id="date"> <p><b>Age of review</b></p> <label>Newer<input type="radio" name="sort" checked/></label> <label>Older<input type="radio" name="sort"/></label> </div> <div class="genre"> <p><b>Genre</b></p> <label>Action<input type="radio" name="filter"/></label> <label>Comedy<input type="radio" name="filter"/></label> <label>Horror<input type="radio" name="filter"/></label> <label>Other<input type="radio" name="filter"/></label> </div> </div> A: You should seperate your display logic and your fetching logic, then you can just filter out the results that aren't the genre you wanted. I would do it something like this: var db = { allDocs: () => { return new Promise((resolve) => resolve([{genre: 'Horror', title: 'The Hills Have Eyes'}, {genre: 'Comedy', title: 'Dumb and Dumber'}])) } } function getFilmList() { return db.allDocs(); } function getFilmsByGenre(genre) { return getFilmList().then(films => films.filter(film => film.genre === genre)); } function displayFilms(films) { let listContents = ''; for(let i = 0; i < films.length; i++) { let thisFilm = films[i].title; listContents += '<div class="filmRow">'+ thisFilm + '</div>'; } document.getElementById('filmContainer').innerHTML = listContents; } document.getElementById('all').addEventListener('click', () => { getFilmList().then(displayFilms) }) document.querySelectorAll('[name="filter"]').forEach(radio => radio.addEventListener('change', (event) => { getFilmsByGenre(event.target.parentNode.textContent).then(displayFilms) })) <div id="filmContainer"></div> <button id="all">All</button> <label>Action<input type="radio" name="filter"/></label> <label>Comedy<input type="radio" name="filter"/></label> <label>Horror<input type="radio" name="filter"/></label> <label>Other<input type="radio" name="filter"/></label>
doc_23530865
public interface Human{ void talk(); } public class Ame implements Human{ public static void talk(){ System.out.println("Speak English"); } } public class Chin implements Human{ public static void talk(){ System.out.println("Speak Chinese"); } } public class test { public static void main(String[] args){ Chin c = new Chin(); c.talk(); Ame a = new Ame(); a.talk(); } } But it shows errors :Ame and Chin talk() cannot implement Human talk(). Methods is overridden as static . Please tell me why this heppened and how to fix this error. A: Static methods are part of Class and not Objects. Overriding is concept of polymorphism, ie, a method associated with an instance can have multiple behaviour. Static methods are not associated with instance and polymorphism cannot be applied. A: When you declare a method as static, it belongs to the class as a whole and not a specific instance. The methods of an interface cannot be static in Java. When you implement an interface, you are expected to provide an instance method for the abstract methods of the interface. When you use a static method, your static method tries to hide the instance method of the same name. But this would violate the rules to be followed while implementing an interface. Thus we cannot make the interface methods as static in the implementing class. A: You cannot reference a non-static interface from a static method this way. In essence, a static method is one that can be accessed directly without recreating a local duplicate object, but its values cannot be modified in the same way. Really, the solution to this problem is quite simple. Remove the static modifier from the overriding talk() methods
doc_23530866
How to draw this names on chart rather than tooltips? Is there need to change in data or options given to Google chart? You can check this plunker. var chart2 = {}; chart2.type = "ScatterChart"; chart2.cssStyle = "height:400px; width:500px;"; chart2.data = [ ['Age', 'Weight'], [ {'v':8,'f':'Name 1'}, -12], [ {'v':-4,'f':'Name 2'}, 5.5], [ {'v':11,'f':'Name 3'}, 14], [ {'v':-4,'f':'Name 4'}, -5], [ {'v':3,'f':'Name 5'}, 3.5], [ {'v':6.5,'f':'Name 6'}, -7] ]; chart2.options = { "title": "Age Vs Maturity", "isStacked": "true", "fill": 20, "hAxis": {"title": "Age", minValue: -15, maxValue: 15}, "vAxis": {"title": "Maturity", minValue: -15, maxValue: 15}, "legend": 'none' }; $scope.chart2 = chart2; A: you can use an annotation column to add labels to a scatter chart... see following example... google.charts.load('current', { callback: function () { var data = google.visualization.arrayToDataTable([ ['Age', 'Weight', {role: 'annotation'}], [ 8, 12, 'Point 1'], [ 1, 5.5, 'Point 2'], [ 11, 14, 'Point 3'], [ 4, 5, 'Point 4'], [ 3, 3.5, 'Point 5'], [ 6.5, 7, 'Point 6'] ]); var options = { title: 'Age vs. Weight comparison', hAxis: {title: 'Age', minValue: 0, maxValue: 15}, vAxis: {title: 'Weight', minValue: 0, maxValue: 15}, legend: 'none' }; var chart = new google.visualization.ScatterChart(document.getElementById('chart_div')); chart.draw(data, options); }, packages:['corechart'] }); <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div"></div>
doc_23530867
.switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside { top: 40px; } So I tried the following: $('.switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside').css('top', '20px'); But this does nothing, it also doesn't give an error. How can I set a line of CSS that looks like that? I know best practice is to use classes but can it be done in another way? A: How can I set a line of CSS that looks like that? jQuery's css function doesn't create CSS rules. The $ (jQuery) function you're passing the selector into looks for matching elements for that selector that exist in the DOM as of the moment you call that function. It returns a jQuery object (which is array-like, basically a set of elements). Then when you call css on it, it sets the inline style of each of those elements in the set to what you provide. If you're not seeing anything happen when you run that code, it means that as of when you ran that code, no elements matched the selector (or changing the top on the ones that did wasn't visually apparent). If you want to add a CSS rule so it applies to elements that exist now or ones added in the future, one way you can do that is to append a style element: $("head").append( $("<style/>").text( ".switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside {\n" + " top: 40px;\n" + "}" ) ); Live Example: setTimeout(() => { $("head").append( $("<style/>").text( ".switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside {\n" + " top: 40px;\n" + "}" ) ); }, 800); <div class="switch-vertical"> <input /> <input type="checkbox" checked /> <div class="toggle-outside"> <div class="toggle-inside" style="position: relative"> Lorem ipsum </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> (Note: I used Rory McCrossan's HTML in the above, adding position: relative to the targeted element so you could see it move when the CSS was added.) But this does nothing, it also doesn't give an error. Correct. jQuery is set-based. Doing operations on an empty set isn't an error, it just means nothing happens. :-)
doc_23530868
Cut a long story short I have need to order a result set by the order of the array used in the select. Which I believe could be done using the FIELD() function, however from my investigations it doesn't look like its possible using Doctrine. For example, I am stumped as how I can utilise FIELD() in a query like below (if its even possible): return $this ->createQueryBuilder('a') ->where('a.identifier IN (:identifiers)') ->setParameter('identifiers',$identifiers) ->getQuery() ->getResult(); A: I am using doctrine version 1.2.4 and using following query to order by specific values. $query->orderBy('FIELD(str,str1,str2,str3,...)'); A: I'm using doctrine v2.5.x. It does not support the FIELD function. I found and used this file. https://github.com/beberlei/DoctrineExtensions/blob/master/src/Query/Mysql/Field.php Or you can install the extension.
doc_23530869
Note: Build is working fine in internal testing. App Store Connect Dear Developer, We identified one or more issues with a recent submission for TestFlight review for your app, "XYZ" 1.0 (1.0.1). Please correct the following issues, then upload again. ITMS-90853: Invalid font - There was an error validating the font named '' at 'XYZ.app/NORMAN.TTF'. Font basic parsability. ITMS-90853: Invalid font - There was an error validating the font named '' at 'XYZ.app/FancyPants.ttf'. Font basic parsability. ITMS-90853: Invalid font - There was an error validating the font named '' at 'XYZ.app/Alakob.ttf'. Font basic parsability. ITMS-90853: Invalid font - There was an error validating the font named '' at 'XYZ.app/AlternateGothicEF-NoTwo_0.ttf'. Font basic parsability. ITMS-90853: Invalid font - There was an error validating the font at 'XYZ.app/GothamRounded-Bold.ttf'. Font not supported by platform. Best regards, The App Store Team I also found this apple forum thread but there is no solution provided. Anyone have the solution for this? A: This is font validation errors. But these are coming after the iOS 14 - Xcode 12 update! I have fixed the fonts by using following software as suggested in this article – Download and install CR8 Software Solutions free font editor for Mac called Type from here: Type light – Open your problem ttf or otf font in the editor (choose File then Open). – Choose Font then Rename Font then click RENAME button (without making any changes). – Save your font (choose File then Save As). – Done! Re-upload the iOS build after updating this font... A: After some research, it looks like iOS still only supports ttf/otf family of fonts and DOES NOT support woff family of fonts. Valid in June 2021 still. Even if you're shipping a Hybrid app (like Cordova / Capacitor / Ionic thing) and WKWebView perfectly supports woff2 since forever - you'll still get ITMS-90853: Invalid font errors from "App Store Connect" Cerberus.
doc_23530870
first tech_one ... tech_four etc mtc second ch0_b0 ch1_b0 ch2_b0 ... ch5 0 1.764052 0.400157 0.978738 ... 0.144044 1.454274 0.761038 1 0.121675 0.443863 0.333674 ... -0.742165 2.269755 -1.454366 2 0.045759 -0.187184 1.532779 ... 1.230291 1.202380 -0.387327 Into tech_one ... tech_four etc mtc ch0 ch1 ch2 ... ch5 _ _ b0 b0 b0 ... 0 1.764052 0.400157 0.978738 ... 0.144044 1.454274 0.761038 1 0.121675 0.443863 0.333674 ... -0.742165 2.269755 -1.454366 2 0.045759 -0.187184 1.532779 ... 1.230291 1.202380 -0.387327 The following code is drafted. import pandas as pd import numpy as np import re np.random.seed(0) arrays = [["tech_one", "tech_one", "tech_one", "tech_one", "tech_two", "tech_two", "tech_two", "tech_two",'tech_three','tech_three','tech_four','etc','mtc'], ["ch0_b0", "ch1_b0", "ch2_b0", "ch3_b0", "ch0", "ch1", "ch2", "ch3","ch1",'ch3','ch5','','']] index = pd.MultiIndex.from_tuples(list(zip(*arrays)), names=["first", "second"]) df = pd.DataFrame(np.random.randn(3, len(arrays[0])), columns=index) tup=[(e[0],*re.split('_',e[1])) for e in df.columns] remove_nan=[tuple('_' if x == '' else x for x in x) for x in tup] df.columns= pd.MultiIndex.from_tuples(remove_nan) which produced the folllowing tech_one ... tech_four etc mtc ch0 ch1 ch2 ... ch5 _ _ b0 b0 b0 ... NaN NaN NaN 0 1.764052 0.400157 0.978738 ... 0.144044 1.454274 0.761038 1 0.121675 0.443863 0.333674 ... -0.742165 2.269755 -1.454366 2 0.045759 -0.187184 1.532779 ... 1.230291 1.202380 -0.387327 As can be seen above, the NaN is still there despite being removed using the line remove_nan=[tuple('_' if x == '' else x for x in x) for x in tup] May I know to handle this issue? A: As I have mentioned in the comment, the reason for NaN is different length tuples, you can just create the list of tuples with equal length, taking the length of maximum length tuples from the list, and having empty string '' to enlarge the tuple. n = len(max(remove_nan, key=len)) remove_nan=[t+('',)*(n-len(t)) for t in remove_nan] df.columns= pd.MultiIndex.from_tuples(remove_nan) OUTPUT: tech_one ... tech_four etc mtc ch0 ch1 ch2 ... ch5 _ _ b0 b0 b0 ... 0 -0.969233 0.746873 0.253076 ... 0.087689 0.874305 0.380449 1 0.387685 -0.382714 -1.043338 ... -1.684973 1.346454 -0.437792 2 -1.300301 0.164648 -0.032736 ... 1.198207 1.608662 -0.818090 [3 rows x 13 columns]
doc_23530871
I tried these answers but they no longer work: Getting the Facebook like/share count for a given URL I found https://developers.facebook.com/docs/graph-api/reference/v10.0/link but there are no JavaScript - JSON examples. A: Thank you @CBroe. The documentations is here: developers.facebook.com/docs/graph-api/reference/v10.0/url The JavaScript and JSON: var url = "https://graph.facebook.com/?fields=engagement&access_token=ACCESS-TOKEN&id=WEBSITE-URL"; $.getJSON(url, function(json) { console.log(json); });
doc_23530872
A: The search function can be applied to a range using arrayformula wrapper: =arrayformula(search("str", C2:F9)) This returns a bunch of #value! errors where no match is found, or the position of substring when it's found. A more readable output is produced with =arrayformula(if(iserror(search("str", C2:F9)), , C2:F9)) This leaves non-matches blank, and returns the actual cell content where there is a match. Or you could put row(C2:F9) at the end to get the row numbers, etc. A: We can simply use vlookup or match formula to find a string from a specific range Vlookup example: =VLOOKUP(B2, $B$2:$B, 1, FALSE) Match example: =MATCH("Sunday",A2:A9,0) =MATCH(DATE(2012,1,1),A2:F2)
doc_23530873
app.get('title'); // => undefined app.set('title', 'My Site'); app.get('title'); // => "My Site" But I've seen things like log('Save configuration values in app %j', config); app.set('config', config); log('Setting port as %d', config.app.port); app.set('port', config.app.port); log('Setting view engine as %s', 'jade'); app.set('view engine', 'jade'); being set with that method. Which are definitely not as trivial. What exactly is happening here that isn't detailed in the official doc? A: Going straight to the source, there doesn't seem to be anything special about app.set at all. It just updates an internal settings property that is an object containing seemingly anything. For Balloons.IO: * *port to set the server port *config (also used in other places, but it's retrieved the same way) However, express does have some special settings that it uses internally in the express documentation here. Other libraries that use express may also have settings that they use internally.
doc_23530874
obj = { key1 : [ 1, 2, 3 ], key2 : [ 4, 5 ], key3 : [] } how can I skip, for example, the empty one. Because I want to join() the not empty arrays in that object, and filter them. If I join that empty array the filter looks for empty string and of course it doesn't find it, and everything brakes. var match = $('.widget'); for ( var i in obj ){ var joined = obj[i].join(); match = match.filter(joined); } I have tried to delete it: if ( obj[i].length == 0 ) { delete obj[i] }; but error occurs that obj[i] is undefined and can't join it. How can I just skip it. A: You need to pass the key to delete a property : for ( var i in obj ){ if ( obj[i].length == 0 ) { delete i } } A: Use loop control: for (var i in obj) { if (obj[i].length == 0) { continue; } ... }
doc_23530875
I have data like this in json : { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5007", "type": "Powdered Sugar" }, { "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5003", "type": "Chocolate" }, { "id": "5004", "type": "Maple" } ] } and data like that : { "id": "0001", "gloss": "donut", "test": "Cake", "ppu": 0.55, "batter": [ { "id": "1001", "name": "Regular" }, { "id": "1002", "name": "Chocolate" }, { "id": "1003", "name": "Blueberry" }, { "id": "1004", "name": "Devil's Food" } ] } In each case I want the data to be in a simple table but with different fields in columns. For example I want to get :id, type, topping.type in the first , and in the second : id, gloss, ppu, topping.type, name Is it possible to solve that kind of problem with a custom template or directive that can handle both case (and others?) to avoid doing multiple heavy similar templates? If you need more precision I can give you more details about it. Thanks. PS: Bonus, same question for angular 2 (even I actually need it in angular 1). Edit : Ok here we go : i need to get something like that : https://plnkr.co/edit/iBENCVpRdohwAtm4AA54 But i have absolutely no idea how can i acheive that, assuming that data1.json and data2.json are here only for example , data are comming from a webservice. but i'm searching the global solution to that kind of problems. A: Yes, you should create directive with field config like this: var config = [{ title: 'Column name', renderer: function valueRenderer(item){ return item.id} }]; and render it like <table> <thead> <th ng-repeat="column in config" ng-bind="column.title"> </thead> <tbody> <tr ng-repeat="item in data"> <td ng-repeat="column in config" ng-bind="column.renderer(item)"></td> </tr> </tbody> </table> and wrap it inside directive <my-dir config="ctrl.config" data="ctrl.data"></my-dir> directive: module.directive('myDir', function(){ return { restrict: 'E', scope: { data: '=', config: '=' }, template: '<table ....' }; });
doc_23530876
Probably a simple and a frequently asked question, but i didn't find an answer. A: What you seem to want is do an assignin in the current workspace. But this is trivial in MATLAB, because is the basic assignment: var = val; The other two accessible workspaces via the ws parameter are: * *'base', which is the base workspace (all the scripts will create their variables in it); *'caller', which is the workspace of the calling function (this workspace is created every time you enter a function, and destroyed when exiting the function), or the global workspace if called from a script. A: I used the following workaround: function main() ... assignhere(name,value) ... return function assignhere(varname,varvalue) assignin('caller',varname,varvalue); return although I would prefer to have access to the current workspace directly
doc_23530877
For the dropdown I'm using this Angularjs-dropdown-multiselect At the moment, after submitting the request, user will be directed to result page and the model content for dropdown and input text is preserved and that's how I want it to be. The problem is, I want to reset the model (back to empty) if user go to page other than the result page. HTML: <div class="col-sm-3"> <div class="dropdown" ng-dropdown-multiselect="" options="cats" selected-model="catModel" checkboxes="true" translation-texts="{buttonDefaultText: 'Categories'}"></div> </div> <div class="col-sm-3"> <div class="dropdown" ng-dropdown-multiselect="" options="ccs" selected-model="ccModel" checkboxes="true" translation-texts="{buttonDefaultText: 'Credit Cards'}"></div> </div> <div class="col-sm-6"> <form data-ng-submit="findValue(catModel, ccModel, keyword)" > <div class="input-group search-bar"> <input type="search" class="form-control" placeholder="Search for..." data-ng-model="keyword"> <span class="input-group-btn"> <button class="btn btn-search" type="button" data-ng-click="findValue(catModel, ccModel, keyword)"><img src="img/icon_search.png" alt="Search" /></button> </span> <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/> </div> </form> </div> JS: .controller('mainController', ['$scope', '$http', '$location', 'dataFactory', function ($scope, $http, $location, dataFactory){ dataFactory.getCategories().success(function (data){ $scope.cats = data; }); dataFactory.getCcs().success(function (data){ $scope.ccs = data; }); $scope.catModel = []; $scope.ccModel = []; $scope.findValue = function(catModel, ccModel, keyword) { var searchUrl = baseUrl; var catID = ''; if(catModel.length > 0) { searchUrl += 'categoryID='; angular.forEach(catModel, function(value, key) { if(key < catModel.length - 1) { searchUrl += value.id + ','; catID += value.id + ','; } else { searchUrl += value.id; catID += value.id; } }) if(ccModel.length > 0 | keyword != null) { searchUrl += '&'; } } if(ccModel.length > 0) { searchUrl += 'ccID='; angular.forEach(ccModel, function(value, key) { if(key < ccModel.length - 1) { searchUrl += value.id + ','; } else { searchUrl += value.id; } }) if(keyword != null) { searchUrl += '&'; } } if(keyword != null) { searchUrl += 'search_keyword=' + keyword; } $http.get(searchUrl).success(function (data) { $scope.results = data; $scope.pageTitle = 'Promotions search result'; $location.path('/promotion'); }) } } I'm putting the model and function inside mainController because the header is in every view. I'm quite new in AngularJS and programming so this code might not be proper, please let me know if there's a simpler and proper way. Any help is appreciated. Thank you A: You can subscribe to the following event $locationChangeSuccess that will be triggered on every location change. And inside you can reset your model. Just declare $rootScope.$on('$locationChangeSuccess', function() { //reset your model here });
doc_23530878
After I'm inserting information in data table if I refresh the page the query is executed again and if I refresh it again it will execute again. Is there any way to disable refresh or make the events unique to be executed only once when the event is raised without execution on refresh Thanks A: if I understand correctly. You have a web form with a button. You push the button which causes a post back and the event handler for the button press to execute. Then you hit refresh and the page has the button event handler execute again. The reason for this is your refreshing the last information sent to the server. Which is the button click information in the __doPostback. This is why you are seeing the event of the button fire again. ASP.NET doesn't provide a way to do it directly. Here is an Article talking about how to detect a refresh over a postback. and your issue is discussed here on other thread
doc_23530879
http://teamtreehouse.com/library The main thing I am trying to replicate is the links tooltip that slides out/fades in beside the icon. Looking at the source, I believe thats done through CSS? correct me if I'm wrong. Also, I noticed they have svg classes on the links, are they just for site responsiveness and not really related to the function of the links/tooltip? Thanks for any help on this and please let me know if I can provide any other info. A: For the bar itself simply have floated div extended to 100% height and set it's position to fixed. The tooltips that pop out can either be done with javascript or CSS. For javascript or jQuery, there are numerous tooltip libraries that will give you the same functionality. In CSS you can add a hover state that shows the div. Either one of these approaches will work. For the CSS solution see this related question: Using only CSS, show div on hover over <a> The SVG class on these from what I can tell is actually the icon itself. SVG is a neat format that lets you apply font styling to images. If you look at the bootstrap framework icons you'll see this is how they are displayed. I'm guessing that the same technique is being used here.
doc_23530880
Class "App\Http\Controllers\User" not found. Here is the controller and here is how I will print the data public function directory() { $dashboardTitle = "Directory"; $isCurrent = "Directory"; $users = User::all(); return view('dashboard.directory', [ 'dashboardTitle' => $dashboardTitle, 'isCurrent' => $isCurrent, 'users' => $users ]); } table to print at <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th> Picture </th> <th>Name</th> <th>Email</th> <th>User type</th> <th>Birthdate</th> <th>Contact number</th> <th>Created time</th> </tr> @foreach($users as $user) <tr> <td>{{ $user->profile_image }}</td> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->user_type }}</td> <td>{{ $user->bdate }}</td> <td>{{ $user->contact_no}}</td> <td>{{ $user->created_at }}</td> </tr> @endforeach </thead> <tfoot> </tbody> </table> A: At the top off your controller add Laravel 8+ use App\Models\User; Laravel <=7 use App\User;
doc_23530881
<div class="fieldWrap"> <label for="jobnamesurname">Name &amp; Surname</label> <input type="text" id="jobnamesurname" name="Name &amp; Surname"> </div> <div> <input type="reset" name="reset"> </div> </form> here is my fiddle link All works ok, just one thing - when you write something then click clear, it is ok, but after this when you try to write something label stays and both value and label are showing, I want to get rid of this issue.3. I can't use just placeholder attribute because it doesn't work on IE9. A: I think both problems can be solved using the Placeholders.js Plugin. It's lightweight, easy to use, and works just like the placeholder attribute except its suitable for IE6 and up. A: how about this jQuery(".clearField").click(function(){ var inputVal = jQuery(".fieldWrap input").val(); if(inputVal != ''){ jQuery(".fieldWrap input").val(''); jQuery(".fieldWrap").removeClass('placeholder-hide'); } }); A: well i've just upded your fiddle, seems to work jQuery(".clearField").click(function(){ var inputVal = jQuery(".fieldWrap input").val(); if(inputVal != ''){ jQuery(".fieldWrap input").val(''); //jQuery(".fieldWrap").addClass('showPlText'); jQuery(".fieldWrap input").blur(); } }); A: http://jsfiddle.net/BB3JK/951/ jQuery(".clearField").click(function(){ jQuery(".fieldWrap input").val(''); jQuery('.fieldWrap > input').blur(); }); A: $(function() { $("#input_1").focus(function() { $("#label_1").hide(0); }); $("#input_1").blur(function() { if (!$(this).val()) { $("#label_1").show(0); } }); $("#reset").click(function() { $("#input_1").val(""); $("#input_1").blur(); $("#label_1").show(0); }); }); /* style the input */ .input_text { position : absolute; left : 0; width : 150px; z-index : 1; background : transparent; outline: none; border: 1px solid #0b4b84; color: #666666; text-align: center; width: 100%; font-size: 16px; float: left; padding: 8px;border : solid 1px black; } /* style the label "placeholder" */ .label { position : absolute; left : 0; z-index : 0; width : 150px; width: 100%; margin-bottom: 5px; font-weight: normal; text-align: center; color: #666666; font-size: 15px; top: 0; bottom: 0; left: 0; right: 0; line-height: 38px; cursor: pointer; font-family:'Arial'; text-transform:uppercase; } /* style the parent container of label/input */ .parent { background : lightgrey; display : inline-block; position : relative; width : 600px; background : #FFF; /* move background here */ } /* style for reset button */ .button-reset { margin-top : 40px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="parent"> <input type="text" class="input_text" id="input_1" /> <label class="label" id="label_1">Name & Surname</label> <button id="reset" class="button-reset">Réinitialiser</button> </div> I think you were trying something similar. I used JQuery plain as it offers IE 6+ compatibility, and I used position : absolute; for both the <input type="text" /> and <label></label> to peform this trick.
doc_23530882
import java.util.Scanner; public class Creditcard { // Return true if the card number is valid public static boolean isValid(long number) { int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number); if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=13 ) && (getSize(number)<=16 )) { return true; } else { return false; } } public static int getDigit(int number) { if (number <= 9) { return number; } else { int firstDigit = number % 10; int secondDigit = (int) (number / 10); return firstDigit + secondDigit; } } public static int sumOfOddPlace(long number) { int result = 0; while (number > 0) { result += (int) (number % 10); number = number / 100; } return result; } public static int sumOfDoubleEvenPlace(long number) { int result = 0; long temp = 0; while (number > 0) { temp = number % 100; result += getDigit((int) (temp / 10) * 2); number = number / 100; } return result; } public static boolean prefixMatched(long number, int d) { String card; if ((getPrefix(number, d) == 4) || (getPrefix(number, d) == 5) || (getPrefix(number, d) == 6) || (getPrefix(number, d) == 37)) { if (getPrefix(number, d) == 4) { card = ("Visa "); } else if (getPrefix(number, d) == 5) { card = ("Master"); } else if (getPrefix(number, d) == 6) { card = ("Discover Card "); } else if (getPrefix(number, d) == 37) { card = ("American Express cards"); } return true; } else { return false; } } public static int getSize(long d) { int count = 0; while (d > 0) { d = d / 10; count++; } return count; } public static long getPrefix(long number, int k) { if (getSize(number) < k) { return number; } else { int size = (int) getSize(number); for (int i = 0; i < (size - k); i++) { number = number / 10; } return number; } } public static void main(String[] args) { long number; // Create scanner object Scanner input = new Scanner(System.in); System.out.print("Enter a credit card number: "); number=input.nextLong(); if (isValid(number)) { String card; long n=getPrefix(number,1); if (n == 4) card = "Visa "; else if (n == 5) card = "Master "; else if (n == 6) card = "Discovery "; else card = "American Express "; System.out.print("This is a valid "+card+"Card Number"); } else System.out.print("This is Invalid Credit Card Number"); } } the problem i am having is i couldn't get it to repeatedly ask for credit cards till i press -1 Write a program named Creditcard.java that prompts the user for a credit card number and determines whether it is valid or not. (Much of this assignment is taken from exercise 6.31 in the book) Credit card numbers follow certain patterns. A credit card number must have between 13 and 16 digits, and must start with: 4 for Visa cards 5 for Master cards 6 for Discover cards 37 for American Express cards The algorithm for determining whether a card number is entered correctly as developed by Hans Luhn of IBM in 1954. The Luhn check or Mod 10 check works as follows. Consider the card number 5842016792622547. Double every second digit from right to left. If the doubling of a digit results in a two-digit number, add up the digits to get a single-digit number. The digits are shown in bold and italic here: 5842016792622547 This gives us (from right to left): 4 * 2 = 8 2 * 2 = 4 6 * 2 = 12 → (1 + 2) = 3 9 * 2 = 18 → (1 + 8) = 9 6 * 2 = 12 → (1 + 2) = 3 0 * 2 = 0 4 * 2 = 8 5 * 2 = 10 → (1 + 0) = 1 Add up those numbers (8 + 4 + 3 + 9 + 3 + 0 + 8 + 1 = 36) Now add up all the digits in the odd positions from right to left: (7 + 5 + 2 + 2 + 7 + 1 + 2 + 8 = 34) Add those two numbers (36 + 34 = 70). If this sum is divisible by 10, the number is valid. If it is not divisible by 10, the number is not valid. Your program will prompt the user to enter a credit card number as a long integer and display whether the number is valid or not. Design your program to use the following methods: Return true if the card number is valid */ public static boolean isValid(long number) Return the sum of the doubled even-place digits */ public static int sumOfDoubleEvenPlace(long number) Return the given number if it is a single digit, otherwise return the sum of the two digits */ public static int getDigit(int n) Return the sum of the odd-place digits */ public static int sumOfOddPlace(long number) Return the number of digits in the given number */ public static int getSize(long number) Return the first length_prefix number of digits from number. If the number of digits in number is less than length_prefix, return number. */ public static long getPrefix(long number, int length_prefix) You may also implement this function if you feel it is useful for your solution: Return true if prefix is a prefix for number */ public static boolean prefixMatched(long number, int prefix) Here is the result of running the program a few times: Enter credit card number: 412345678 That is not a valid credit card number. Enter credit card number: 5842016792428358 That is a valid credit card number. Enter credit card number: 5782077482835719 That is not a valid credit card number. Extra Challenges Challenge 1: If the card is valid, display which type of card it is. For example: Enter credit card number: 5842016792428358 That is a valid Master card number. Challenge 2: Repeatedly ask for credit card numbers until the user enters -1. (Hint: while)
doc_23530883
Can the outputs be blocked or set to low? Or do I have to do this with the hardware? A: During reset all of the pins are set to inputs. You should be able to prevent the horn from sounding by adding a 10k resistor to ground. Edit: Assuming your horn is connected between an output pin and ground, you might also be able to change the horn to be between VCC and the output. When you make that change you will need to change the code to clear the bit when you want to activate the horn.
doc_23530884
How to force Stanford NLP's WordsToSentencesAnnotator to split sentences on dots? I tried adding -ssplit.boundaryMultiTokenRegex "//.", but it still fails to split on the . all the time. I use Stanford CoreNLP version 3.5.2 (2015-04-20) on Windows 7 SP1 x64 Ultimate with Java 1.8.0_25 x64. Example: I have a text that contains two sentences: D R E L I N. Okay. I use Stanford NLP's WordsToSentencesAnnotator to split the text into sentences through the command line interface: java -cp "*" -Xmx2g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit -file test.txt It returns just one sentence D R E L I N. Okay. instead of two sentences ['D R E L I N.', 'Okay.'], .i.e. looking at the output XML file, the node sentences had only one sentence child:
doc_23530885
<Application x:Class="MN.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MN" Startup="Application_Startup" DispatcherUnhandledException="Application_DispatcherUnhandledException"> <Application.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}" Color="#FFF" /> </Application.Resources> </Application> Instead of coming out white, the controls that use this color initially come out black. It remains black until I modify this particular XAML Color property in VS. Once I change it to any other value the value is respected, until I load the app again at which point it reverts to black. Most (if not all) other SystemColors.*Key values seem to work as expected. Whatever value I set seems to be in effect at app load time. I'm wondering if there is something I need to do to override the original defaults. Some kind of refresh/notify call I can make? Also considering building this Application.Resources after a delay? But looking for a better/cleaner solution. [EDIT 2023-01-16] So I tried a text block directly in my Window and this works as expected, however if I load a textblock via a page loaded into a frame, it does not. My Page: <Page x:Class="MN.TestPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MN" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800" Title="TestPage"> <DockPanel Margin="20" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"> <StackPanel DockPanel.Dock="Top" VerticalAlignment="Top" HorizontalAlignment="Stretch"> <TextBlock FontSize="36" Text="I expect this text to be not black in color."/> </StackPanel> </DockPanel> </Page> My Window: <Window x:Class="MN.TestWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:MN" mc:Ignorable="d" Title="TestWindow" Height="702" Width="1245" WindowState="Maximized" Loaded="Window_Loaded"> <DockPanel> <Frame x:Name="frame" /> </DockPanel> </Window> And in my window code-behind: private void Window_Loaded(object sender, RoutedEventArgs e) { frame.Source = new Uri("TestPage.xaml", UriKind.Relative); } As an aside I'm open to better ways to doing what I want to accomplish. I basically want my app to run in a dark mode, or even better respect the user's choice for dark or light mode. It sounds like this is something that is maybe supposed to "just work" but it doesn't seem to be for me, so my plan was to override the system colors to create a default scheme for most controls and then override any controls that are problematic from there. Most guides I've found have recommended this approach or seem to rely on some framework or other that I don't want to depend on. A: I recommend usercontrols instead of pages. When I try this with a usercontrol, it works ok. There are a number of downsides to frames and pages. Seems this behaviour is one I had not previously noticed. The Frame has a bunch of side effects isolating pages, retaining state and generally complicating things I usually don't find need complicating. Frame and pages are useful for "wizard" like scenarios where the user is inputting to a series of views and may want to go back and forth between them. In that scenario the features frame and page add are worth the overhead. But usercontrols. If I have a usercontrol: <Grid> <TextBlock FontSize="36" Text="I expect this text to be not black in color."/> </Grid> </UserControl> And instead do: private void Window_Loaded(object sender, RoutedEventArgs e) { this.Content = new UserControl1(); } That gives me red text. Think of usercontrols for all encapsulation of UI. Think of them before you consider another window. You only ever need two windows defined in a multi window wpf app. One is mainwindow. Another: EverythingElseWindow which just has a contentpresenter whose content is bound to datacontext. Template out it's content. https://social.technet.microsoft.com/wiki/contents/articles/52485.wpf-tips-and-tricks-using-contentcontrol-instead-of-frame-and-page-for-navigation.aspx This approach with system brushes is not how I would usually approach such things. If extensive re styling is necessary, I suggest you look at off the shelf themes. Over riding these system keys is unreliable. You will find that the ( sometimes surprisingly complicated ) templates for controls do not always use these system brushes. Error handlers: private void Application_Startup(object sender, StartupEventArgs e) { DispatcherUnhandledException += App_DispatcherUnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; // Get too many spurious errors when handling firstchanceexception // AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; You have to be super careful with your bindings and templates before you can use FirstchanceException in production code. It is, however, sometimes useful to have this set up to explore issues whilst developing. All those should log via some central injectable interface. Nlog if you are writing in house software. Consider web and application insights if it's external. Rather a sprawling post, even for me, hope this helps.
doc_23530886
Any suggestions on what may need to be set differently or changed on the server. All files have been uploaded and the mappings seem to be fine. Thank you for your help! A: When accessing the captcha image directly it shows this error: Fatal error: Call to undefined function imagecreate() in C:\inetpub\wwwroot\securimage\securimage.php on line 1418 It appears your server hasn't got the GD module installed, which is used to generate images on the fly.
doc_23530887
{"HYR":"[{\"LastUpdatedBy\":\"Bug 101510: VMukkanagoudar\",\"IATACountryCode\":\"US\",\"MetroCodeBool\":false,\"AirportName\":\"Sawyer County\",\"Latitude\":46,\"CityName\":\"Hayward\",\"MajorAirportBool\":false,\"Longitude\":-91,\"StatusCode\":\"A\",\"DisplayNameLocal\":\"Hayward, WI (HYR-Sawyer County)\",\"DisplayNameInternational\":\"Hayward, WI, United States (HYR-Sawyer County)\",\"UpdateDate\":\"2009-03-06 20:44:00.0\",\"AirportCode\":\"HYR\",\"AirportID\":5396808,\"RegionName\":\"Wisconsin\",\"IdenticalMetroCodeBool\":false,\"ExternalName\":\"HYR\",\"CountryCode\":\"USA\"}]", "VAA":"[{\"LastUpdatedBy\":\"fmoneo\",\"IATACountryCode\":\"FI\",\"MetroCodeBool\":false,\"AirportName\":\" \",\"Latitude\":63,\"CityName\":\"Vaasa\",\"MajorAirportBool\":true,\"Longitude\":22,\"StatusCode\":\"A\",\"DisplayNameLocal\":\"Vaasa (VAA)\",\"DisplayNameInternational\":\"Vaasa, Finland (VAA)\",\"UpdateDate\":\"2008-08-12 17:26:00.0\",\"AirportCode\":\"VAA\",\"AirportID\":4276566,\"RegionName\":\" \",\"IdenticalMetroCodeBool\":false,\"ExternalName\":\"VAA\",\"CountryCode\":\"FIN\"}]" ....(and so on)} The java object is as follows @JsonIgnoreProperties(ignoreUnknown = true) public class Config { @JsonProperty("AirportCode") String airportCode; @JsonProperty("AirportID") Integer airportId; @JsonProperty("MetroCodeBool") Boolean metroCodeBool; @JsonProperty("MajorAirportBool") Boolean majorAirportBool; @JsonProperty("IdenticalMetroCodeBool") Boolean identicalMetroCodeBool; @JsonProperty("StatusCode") Character statusCode; //Getters and setters } The code for conversion is String jsonStr = apiCall(); if(jsonStr != null) { ObjectMapper mapper = new ObjectMapper(); TypeReference<HashMap<String, ArrayList<Config>>> typeRef = new TypeReference<HashMap<String, ArrayList<Config>>>() {}; HashMap<String, ArrayList<AirConfig>> configMap = mapper.readValue(jsonStr, typeRef); } However, the error I get is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at [Source: java.io.StringReader@2b82d59e; line: 1, column: 2] (through reference chain: java.util.HashMap["HYR"]) I believe the TypeReference I have created is incorrect. Any solutions to how I should change it. A: This JSON is invalid in your case. See the part {"HYR":"[{\"LastUpdatedBy\":\"Bug 101510: There is a " that should not be there, so valid part would be like: {"HYR":[{\"LastUpdatedBy\":\"Bug 101510: In your case, you are require a value of HYR to be an array, but it is of String value (due to quotation). Removing quotation will indeed make valid JSON array. A: There are extra " in json at the start and end of Array "[ ]". You need to remove them. try { String jsonStr = "{\"HYR\":[{\"LastUpdatedBy\":\"Bug 101510: VMukkanagoudar\",\"IATACountryCode\":\"US\",\"MetroCodeBool\":false,\"AirportName\":\"Sawyer County\",\"Latitude\":46,\"CityName\":\"Hayward\",\"MajorAirportBool\":false,\"Longitude\":-91,\"StatusCode\":\"A\",\"DisplayNameLocal\":\"Hayward, WI (HYR-Sawyer County)\",\"DisplayNameInternational\":\"Hayward, WI, United States (HYR-Sawyer County)\",\"UpdateDate\":\"2009-03-06 20:44:00.0\",\"AirportCode\":\"HYR\",\"AirportID\":5396808,\"RegionName\":\"Wisconsin\",\"IdenticalMetroCodeBool\":false,\"ExternalName\":\"HYR\",\"CountryCode\":\"USA\"}]}"; if (jsonStr != null) { ObjectMapper mapper = new ObjectMapper(); TypeReference<HashMap<String, ArrayList<Config>>> typeRef = new TypeReference<HashMap<String, ArrayList<Config>>>() {}; HashMap<String, ArrayList<Config>> configMap = mapper.readValue(jsonStr, typeRef); ArrayList<Config> configList = configMap.get("HYR"); } } catch (IOException e) { e.printStackTrace(); } } A: using (with your Config with a proper toString): public static void main(String[] args) throws IOException { String jsonStr = "{\"HYR\":\"[{\\\"LastUpdatedBy\\\":\\\"Bug 101510: VMukkanagoudar\\\",\\\"IATACountryCode\\\":\\\"US\\\",\\\"MetroCodeBool\\\":false,\\\"AirportName\\\":\\\"Sawyer County\\\",\\\"Latitude\\\":46,\\\"CityName\\\":\\\"Hayward\\\",\\\"MajorAirportBool\\\":false,\\\"Longitude\\\":-91,\\\"StatusCode\\\":\\\"A\\\",\\\"DisplayNameLocal\\\":\\\"Hayward, WI (HYR-Sawyer County)\\\",\\\"DisplayNameInternational\\\":\\\"Hayward, WI, United States (HYR-Sawyer County)\\\",\\\"UpdateDate\\\":\\\"2009-03-06 20:44:00.0\\\",\\\"AirportCode\\\":\\\"HYR\\\",\\\"AirportID\\\":5396808,\\\"RegionName\\\":\\\"Wisconsin\\\",\\\"IdenticalMetroCodeBool\\\":false,\\\"ExternalName\\\":\\\"HYR\\\",\\\"CountryCode\\\":\\\"USA\\\"}]\"}"; ObjectMapper mapper = new ObjectMapper(); // step one: deserialize the map HashMap<String, String> configMap = mapper.readValue(jsonStr, new TypeReference<HashMap<String, String>>() {}); // step two, deserialize the value for HYR final String hyr = configMap.get("HYR"); List<Config> configs = mapper.readValue(hyr, new TypeReference<List<Config>>() {}); System.out.println(configs); } Works here (jackson-2.3.2) and outputs: [Foo.Config(airportCode=HYR, airportId=5396808, metroCodeBool=false, majorAirportBool=false, identicalMetroCodeBool=false, statusCode=A)]
doc_23530888
Here's my directory structure: /Maths /build / /CMakeLists.txt /maths.cpp /maths.h /Alpha /build / /CMakeLists.txt /main.cpp And here are the contents of those files: * CMakeLists.txt (for Maths) * cmake_minimum_required(VERSION 2.6) project(Maths) add_library(maths STATIC maths.cpp) * maths.cpp * int Double(int x) { int y = x * 2; return y; } * maths.h * int Double(int x); * CMakeLists.txt (for Alpha) * cmake_minimum_required(VERSION 2.8) project(Alpha) add_executable(alpha main.cpp ../Maths/maths.h) target_link_libraries(maths ../Maths/build/libmaths.a) * main.cpp * #include <iostream> #include "maths.h" using namespace std; int main() { int x = 5; int y = Triple(x); cout << "The answer = " << y << endl; return 0; } So, I enter the directory /Maths/build, and run cmake ... Then, I run make. This creates the library file libmaths.a in the directory /Maths/build. Then, I enter the directory /Alpha/build, and run cmake ... Then, I run make. However, this gives me the error message: /usr/bin/ld: cannot find -lmaths Why can make not find the library file that I just created? I also tried copyiing libmaths.a and maths.h into the directory /Alpha, and changing Alpha's CMakeLists.txt to: cmake_minimum_required(VERSION 2.8) project(Alpha) add_executable(alpha main.cpp maths.h) target_link_libraries(maths libmaths.a) But this gave the same error. A: The essential problem here is that libmaths.a is not placed in one of the default linker directories. The bigger problem is that you passed libmaths.a to target_link_libraries in the first place. This is bad for several reasons, but the most obvious is that it's completely non-portable. A different compiler toolchain might use a different ending than .a for static libraries, so you won't be able to build there. Also, should you ever decide to switch to dynamic linking in the future, it means refactoring your existing CMake scripts. The proper solution is to not pass hardcoded filenames to target_link_libraries. There are two roads that you can take to avoid this. * *Use a find script. Essentially, you call find_library(MY_MATHLIB maths [...]) and then do target_link_libraries(alpha ${MY_MATHLIB}) instead. This will determine the absolute path of the .a file in a portable way and pass that to the linker. The biggest disadvantage of this approach is that the .a file must already be there for the find call to succeed. So if you want to build maths after running the CMake for alpha or build it as part of alpha, this won't work. *Since both libraries are under your control, consider using CMake's packaging mechanism. This is by far the most convenient approach for building, but unfortunately also the most difficult to set up. If you are willing to spend some time digging through the CMake docs and experimenting with the build, I encourage you to give it a try, but if you just want something that works quickly, you might want to stick with option 1. A: Use a CMakeLists.txt in the root directory /CMakeLists.txt: CMAKE_MINIMUM_REQUIRED(VERSION 2.8) PROJECT( MyProject ) ADD_SUBDIRECTORY( Maths ) ADD_SUBDIRECTORY( Alpha ) in Alpha/CMakeLists.txt: TARGET_LINK_LIBRARIES( alpha maths ) Run CMake on the top-level CMakeLists.txt instead of the individual subdirectory ones
doc_23530889
For some reason it seems they are stacked on top of each other or something. I have no code to show because there's nothing implemented out of the norm, but you can see an example on on my live sandbox here: http://sandbox.tsdapps.com/account/register If you look at it in IE, int Newsletter section there two blank radio buttons. One of them is already selected but seems to be underneath the blank one in presentation. The same for the Terms checkbox, if you check it, you can see the underlying element get checked because the tip of the checkmark overlaps and is visible to the top right of the box. I've searched everywhere to try and solve this on my own and I can't find anything. And the github issues portal has like 100 open issues and seems to be pretty much dead, so here I am. Any help would be greatly appreciated. Thanks. -Vince A: Tried taking your style and script file, and used the default Uniform setup: http://jsfiddle.net/AKfN8/2/ Which works fine in IE... So it seems to be Modernizer breaking it, this is what happend when i added it: http://jsfiddle.net/AKfN8/11/ So my guess is that you are using the Modernizr HTML5 input tag extension which might break Uniform. Could you try to remove modernizr to test it? :) If it is, you might want to make a build without the input extension. A: The code does not work in IE8 well because IE8 (as well as IE9 as far as I know) does not support :after and :before pseudo css classes. But you could achieve desired behavior by adding a css and js files that will be IE specific and will be loaded only in IE browsers and add some extra code. First simply hide the checkbox from the user, to avoid the checkbox be on top of the uniform span. #some_holder_dom_node span>input[type='checkbox'] { visibility: hidden; } Once the checkbox is hidden we need to handle it's check/uncheck actions manually and trigger events with other element, for instance: (function(){ $(document).on('click', '#some_holder_dom_node div.checker>span', function(){ $(this).find('input:checkbox').trigger('click'); }); }()); I used simple JS and CSS, but you could use scss or sass to save some typing for css rules as well as CoffeeScript or something to handle JS stuff.
doc_23530890
To do that, I react to the MouseDown event. What I expect is the following: * *User touches screen with finger: MouseDown *User releases finger from screen: MouseClick, MouseUp However, in Windows 10 with Tablet Mode activated, this does not work. Instead, the sequence "MouseDown", "MouseClick", "MouseUp" is triggered only when the finger is lifted. How could I make it so that I get a notification about the finger touch? Sample code in VB.NET: Public Class Form1 Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown Me.ListBox1.Items.Add("mousedown") End Sub Private Sub Form1_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp Me.ListBox1.Items.Add("mouseup") End Sub Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick Me.ListBox1.Items.Add("mouseclick") End Sub End Class
doc_23530891
I can use a SOAP GUI client to connect and do some queries but how do I go about using the certificate, password and link above in powershell so I can send some queries? If anyone has used the Bloomberg Data License Web Services and can provide a complete example how to fetch some pricing data? A: Start with: curl --cert .\BloombergDLWS.p12:MyP@$$w0rd -H "Content-Type: text/xml;charset=utf-8" -H 'SOAPAction: \"submitGetDataRequest\"' -d "@submitGetDataRequest.xml" --request-target 'https://dlws.bloomberg.com/dlps' --url 'https://dlws.bloomberg.com/dlps' Three notes about the CURL command: * *The request-target flag is necessary. Otherwise it sends POST /dlps HTTP/1.1 instead of POST /dlps HTTP/1.1 and results in a 502 BAD GATEWAY error. *Escape the SOAPAction quotes, otherwise you get Failed to convert request to BAS: Failed to find action index for SOAP action 'submitGetDataRequest' when converting SOAP request for service ID 125322 *Read the SOAP envelope XML from a file. Inline XML, besides vastly inflating the command length, generated a ParseError even though I had copied it in carefully as one line. Where submitGetDataRequest.xml contains <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://services.bloomberg.com/datalicense/dlws/ps/20071001"> <soapenv:Header/> <soapenv:Body> <ns:submitGetDataRequest> <ns:headers> <ns:secmaster>true</ns:secmaster> </ns:headers> <ns:fields> <ns:field>NAME</ns:field> <ns:field>TICKER</ns:field> <ns:field>CPN</ns:field> <ns:field>MATURITY</ns:field> <ns:field>ID_BB_GLOBAL</ns:field> </ns:fields> <ns:instruments> <ns:instrument> <ns:id>912810CY2</ns:id> <ns:type>CUSIP</ns:type> </ns:instrument> </ns:instruments> </ns:submitGetDataRequest> </soapenv:Body> </soapenv:Envelope> This returns a response that doesn't contain the data you want, but it does include a responseId code to use in a second request. <?xml version="1.0" encoding="UTF-8" ?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <dlws:submitGetDataResponse xmlns='http://services.bloomberg.com/datalicense/dlws/ps/20071001' xmlns:dlws="http://services.bloomberg.com/datalicense/dlws/ps/20071001" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <dlws:statusCode> <dlws:code>0</dlws:code> <dlws:description>Success</dlws:description> </dlws:statusCode> <dlws:requestId>01234567-89AB-CDEF-0123-456789ABCDEF</dlws:requestId> <dlws:responseId>ABCDEF0123-4567890AB</dlws:responseId> </dlws:submitGetDataResponse> </soap:Body> </soap:Envelope> You must insert the responseId code into another request like so (saved as retrieveGetDataResponse.xml): <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://services.bloomberg.com/datalicense/dlws/ps/20071001"> <soapenv:Header/> <soapenv:Body> <ns:retrieveGetDataRequest> <ns:responseId>ABCDEF0123-4567890AB</ns:responseId> </ns:retrieveGetDataRequest> </soapenv:Body> </soapenv:Envelope> Wait a few minutes, then submit the final request, saving your data as DataResponse.xml: curl --cert .\BloombergDLWS.p12:MyP@$$w0rd -H "Content-Type: text/xml;charset=utf-8" -H 'SOAPAction: \"retrieveGetDataResponse\"' -d "@retrieveGetDataResponse.xml" --request-target 'https://dlws.bloomberg.com/dlps' --url 'https://dlws.bloomberg.com/dlps' -o DataResponse.xml Submitting this request too soon will return a result that basically says it's not ready, try again later.
doc_23530892
#include<stdio.h> #include <stdlib.h> #define LEN 2 int main(void) { char num1[LEN],num2[LEN]; //works fine with //char *num1= malloc(LEN), *num2= malloc(LEN); int number1,number2; int sum; printf("first integer to add = "); scanf("%s",num1); printf("second integer to add = "); scanf("%s",num2); //adds integers number1= atoi(num1); number2= atoi(num2); sum = number1 + number2; //prints sum printf("Sum of %d and %d = %d \n",number1, number2, sum); return 0; } Here is the output : first integer to add = 15 second integer to add = 12 Sum of 0 and 12 = 12 Why it is taking 0 instead of first variable 15 ? Could not understand why this is happening. It is working fine if I am using char *num1= malloc(LEN), *num2= malloc(LEN); instead of char num1[LEN],num2[LEN]; But it should work fine with this. Edited : Yes, it worked for LEN 3 but why it showed this undefined behaviour. I mean not working with the normal arrays and working with malloc. Now I got that it should not work with malloc also. But why it worked for me, please be specific so that I can debug more accurately ? Is there any issue with my system or compiler or IDE ? Please explain a bit more as it will be helpful or provide any links to resources. Because I don't want to be unlucky anymore. A: LEN is 2, which is enough to store both digits but not the required null terminating character. You are therefore overrunning the arrays (and the heap allocations, in that version of the code!) and this causes undefined behavior. The fact that one works and the other does not is simply a byproduct of how the undefined behavior plays out on your particular system; the malloc version could indeed crash on a different system or a different compiler. Correct results, incorrect results, crashing, or something completely different are all possibilities when you invoke undefined behavior. Change LEN to 3 and your example input would work fine. I would suggest indicating the size of your buffers in your scanf() line to avoid the undefined behavior. You may get incorrect results, but your program at least would not crash or have a security vulnerability: scanf("%2s", num1); Note that the number you use there must be one less than the size of the array -- in this example it assumes an array of size 3 (so you read a maximum of 2 characters, because you need the last character for the null terminating character). A: LEN is defined as 2. You left no room for a null terminator. In the array case you would overrun the array end and damage your stack. In the malloc case you would overrun your heap and potentially damage the malloc structures. Both are undefined behaviour. You are unlucky that your code works at all: if you were "lucky", your program would decide to crash in every case just to show you that you were triggering undefined behaviour. Unfortunately that's not how undefined behaviour works, so as a C programmer, you just have to be defensive and avoid entering into undefined behaviour situations. Why are you using strings, anyway? Just use scanf("%d", &number1) and you can avoid all of this. A: Your program does not "work fine" (and should not "work fine") with either explicitly declared arrays or malloc-ed arrays. Strings like 15 and 12 require char buffers of size 3 at least. You provided buffers of size 2. Your program overruns the buffer boundary in both cases, thus causing undefined behavior. It is just that the consequences of that undefined behavior manifest themselves differently in different versions of the code. The malloc version has a greater chance to produce illusion of "working" since sizes of dynamically allocated memory blocks are typically rounded to the nearest implementation-depended "round" boundary (like 8 or 16 bytes). That means that your malloc calls actually allocate more memory than you ask them to. This might temporarily hide the buffer overrun problems present in your code. This produces the illusion of your program "working fine". Meanwhile, the version with explicit arrays uses local arrays. Local arrays often have precise size (as declared) and also have a greater chance to end up located next to each other in memory. This means that buffer overrun in one array can easily destroy the contents of the other array. This is exactly what happened in your case. However, even in the malloc-based version I'd still expect a good debugging version of standard library implementation to catch the overrun problems. It is quite possible that if you attempt to actually free these malloc-ed memory blocks (something you apparently didn't bother to do), free will notice the problem and tell you that heap integrity has been violated at some point after malloc. P.S. Don't use atoi to convert strings to integers. Function that converts strings to integers is called strtol.
doc_23530893
What is the best way to solve this problem? function fish($bubbles) { extract(shortcode_atts(array( "fin" => get_option('pacific'), ), $bubbles)); $width = " width=\"".$fin['width']."\""; $height = " height=\"".$fin['height']."\""; $osorientation = " orientationMode=\"manual\""; $link = "https://pacific.local/item/1/A"; $path = parse_url($link, PHP_URL_PATH); $segments = explode('/', rtrim($path, '/')); wp_enqueue_script( 'some-pacific-js' ); $atlantic = "<fish-info fAdd=\"".$segments[2]."\" fId=\"".$segments[3]."\" network=\"".$network."\"></fish-info>"; return $atlantic; } add_filter('widget_text', 'do_shortcode'); add_shortcode('pacific', 'fish'); A: The preferred way is pass link as a parameter of the shortcode, then call the shortcode two times with specific link. First of all, change the fish function: function fish($atts) { // Pay attention, I removed "extract" so $fin is now a key inside $atts $atts = shortcode_atts( array( 'fin' => get_option('pacific'), 'item' => 'CHOOSE_A_DEFAULT' ), $atts ); $width = " width=\"".$atts['fin']['width']."\""; $height = " height=\"".$atts['fin']['height']."\""; $osorientation = " orientationMode=\"manual\""; $link = "https://pacific.local/item/" . $atts['item']; $path = parse_url($link, PHP_URL_PATH); $segments = explode('/', rtrim($path, '/')); wp_enqueue_script( 'some-pacific-js' ); $atlantic = "<fish-info fAdd=\"".$segments[2]."\" fId=\"".$segments[3]."\" network=\"".$network."\"></fish-info>"; return $atlantic; } In the widget where you are calling the short code, youhave probably something like this: [pacific] You have to change it into something like this: [pacific item="1/A"] [pacific item="2/B"]
doc_23530894
<style name="question_dialog" parent="@android:style/Theme.Holo.Dialog"> <item name="android:windowTitleStyle">@style/question_dialog_title</item> </style> <style name="question_dialog_title" parent="android:Widget.TextView"> <item name="android:background">#5cc5cc</item> <item name="android:textSize">21sp</item> <item name="android:textColor">#ffffff</item> </style> The java code is as follows : new AlertDialog.Builder(this, R.style.question_dialog).setTitle("Assam Quiz" ). setMessage("Hello world Hello world"). setPositiveButton("OK", (dialog, which) - > {dialog.dismisd(); }).show(); } The AlertDialog image is attached. A: out of the style - I think your dialog has some header layout set to it that prevents the title to be at the top, but if that is the case or not - you can easily set a custom title for the dialog header giving it the header layout only, and so you will have the full control for the dialog header: // creating the Dialog AlertDialog.Builder builder = new AlertDialog.Builder(context); // getting dialog context Context mContext = builder.getContext(); // building the inflater LayoutInflater mLayoutInflater = LayoutInflater.from(mContext); // inflate the dialog header layout View mView = mLayoutInflater.inflate(R.layout.simple_dialog_header, null); // get the TextView for the header (contained in the header layout) TextView mTextView = (TextView) mView.findViewById(R.id.title_text); // set the text for that TextView mTextView.setText(message); // set the custom header view for the dialog builder.setCustomTitle(mView); /* here you can set positive , negative ,neutral buttons or set the dialog message or any attribute you want */ // finally, show the dialog builder.show(); and for the header layout (R.layout.simple_dialog_header): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/primary" android:orientation="vertical" android:paddingBottom="15dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:paddingTop="15dp"> <TextView android:id="@+id/title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:maxLines="1" android:textAlignment="center" android:textColor="@color/primary" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout>
doc_23530895
I need a list to use for chartjs. last_records = TaskResult.objects.filter(task_name='scraper.tasks.send_game', date_created__day=20).order_by("-date_created")[:100] queryset = last_records.annotate(date=TruncMinute('date_created')).values("date_created").annotate(created_count=Count('id')) I made this query however its not returning the correct response. There are many records so thats why I limit it to last 100 records. In order to use chartjs correctly, I need a list of the date with the hour and how many records there are of it. I need something like this: [{'date_created': '2021-02-20 10:49'), 'count': 2}, ...] A: Solved it with this: five_minutes_ago = datetime.datetime.now() + datetime.timedelta(minutes=-120) last_records = TaskResult.objects.filter( task_name='scraper.tasks.send_game', date_done__gte=five_minutes_ago ).annotate(date=TruncMinute('date_done')).values("date").annotate( amount=Count('id') ).order_by("-date")
doc_23530896
That's what i've come up with, but it does not work. Any ideas ? #!/usr/bin/gawk -f BEGIN { OFS=FS=";"; IMGPATH="/var/xxx/imp/"; IMGimportPATH="http://xxx/img/imp/"; } NR > 1{ sub(/\r$/,""); fcount=sprintf("find %s -name %s* -print|awk 'END{printNR}'",IMGPATH,$1); fcount | getline fc; close (fcount); if (fc == 0) { print $1,$0,$(NF+1)=IMGimportPATH"brak.png" FS "197"; } else if(fc == 1) print $1,$0,$(NF+1)=IMGimportPATH$1".jpg" FS "197"; else if(fc > 1){ $(NF+1)=IMGimportPATH$1".jpg"; x=1; while (x < fc){ $(NF)=$(NF)","IMGimportPATH$1"_"x".jpg"; x=x+1; } print $1,$0 FS "197"; } #} } #awk -v RS="" '$3=="sn::"{"gzuncompress(base64_decode) -d<<< \""$4"\""|getline $4}{print $2,$4}' file
doc_23530897
Is the same thing also possible with webforms to create the pages and controls and pass them any dependencies? If yes, where do I have to plug it in? A: Yes you can, here's an example of how Spring.NET does it. A: Castle Windsor was the first major IoC container for ASP.NET. See this question discussing how it can be used with Web forms. A: Not directly, as Web Forms does not allow any code to take control of Page and Control instantiation. So something like a Page Factory is not feasible, and you can't do constructor injection. But there are work arounds/hacks that can buy you setter injection as others have mentioned. A: Another good approach would be using the Model-View-Presenter pattern and have your dependencies injected into the presenter's constructor. A: I know this question is very old but in the .NET Framework 4.7.2+ you can have constructor injection in ASP.NET WebForm pages and user controls. From this official blog post: Areas that Dependency Injection can be used There are many areas you can use Dependency Injection in WebForms applications now. Here is a complete list. * *Pages and controls WebForms page User control Custom control *IHttpHandler and IHttpHandlerFactory *IHttpModule Providers *BuildProvider *ResourceProviderFactory *Health monitoring provider *Any ProviderBase based provider created by System.Web.Configuration.ProvidersHelper.InstantiateProvider. e.g. custom session state provider
doc_23530898
Starting daemon threads in a Java EE server is a big no no Basically Smack's XMPPConnection starts one daemon thread to monitor incoming data & another to send outgoing data from/to the jabber server respectively. Is it reasonable to use daemon threads to listen for write/reads in this scenario ? A: Yes, XMPPConnection creates two threads--one for listening/reading and one for writing. But these only live as long as the XMPPConnection instance, which I assume is not forever. "Starting daemon threads in a Java EE server is a big no no" Are you writing spec compliant EJB? If so, then this applies. The spec says don't do it. EJB 2.1 specification: "The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups." Or is it just a webapp that happens to be running in Tomcat? If this is the case, then I do not see any fundamental problem. Without the threads, your Smack client would be unable to communicate with the server. A: I have used Smack API for client connections only which are stand alone programs. First you should revisit the choice (or purpose) of Smack API inside a J2EE container.
doc_23530899
I would be very gratefull for any suggestions on that.