text
stringlengths
15
59.8k
meta
dict
Q: Cocoapods Error - Trouble in installing MapboxNavigation podfile -Mapboxnavigation sdk In order to implement MapbocNavigation podfile according to mapboxnavigationsdk official documentation.adding Mapbox-iOS-SDK and MapboxNavigation through Cocoapods, always get error, shown bellow.enter image description here Also tried: Generate access token and use secret key from Mapbox account and also configure .nertc file with secret key, follow all the steps of .nertc file configuration and research more about this error and implement all the possible ways but yet I am facing this error... A: First, please remove already created .netrc files with this command. sed -i '' '/^machine api.mydomain.com$/{N;N;d;}' ~/.netrc Then Try To create new .netrc file with this steps: To create .netrc file do next Fire up Terminal cd ~ (go to the home directory) touch .netrc (create file) open .netrc (open .netrc) Set required data. Save .netrc file should be like this machine api.mapbox.com login mapbox password <secret_key_created_from_your_mapbox_account> May be it will help to you. If Its Help then please upvote to my answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/74640597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could be in Optional really anything I found implemented this code (method where this part of code is used is returning Optional<File>, this part of code had to be added for verification if values are correct and case can be saved): if (!CaseChecker.checkValues(case)) { return Optional.of(new File("FALSE")); } When I asked the person, why he is returning something like this. The answer was "Optional can contain any value". To be honest I don't agree with this, because type of Optional is for some reason. So I wanted to confirm if Optional can be really anything and if yes, then what's the reason to write Optional type. A: The whole point of Optional is to avoid the situation where you return a bogus value (like null, or like returning -1 from String.indexOf in order to indicate it didn't find anything), putting the responsibility on the caller to know what is bogus and to know to check for it. Returning Optional lets the caller know it needs to check whether a valid result came back, and it takes away the burden of the caller code needing to know what return values aren't valid. Optional was never meant as a wrapper for a bogus value. And yes you can return anything. The api doesn't stop you from doing nonsensical things. Also consider that flatMap doesn't know what to do with this weird thing, it will treat the contents as nonempty. So now how you can use this value is limited. You have a multistage validation process where it might be something you can handle with operations chained together using flatMap, but this fake file has made that harder. It's limited your options. Return Optional.empty() if you don't have a valid value to return.
{ "language": "en", "url": "https://stackoverflow.com/questions/73474951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fast query and deletion of documents of a large collection in MongoDB I have a collection (let say CollOne) with several million documents. They have the common field "id" {...,"id":1} {...,"id":2} I need to delete some documents in CollOne by id. Those ids stored in a document in another collection (CollTwo). This ids_to_delete document has the structure as follows {"action_type":"toDelete","ids":[4,8,9,....]} As CollOne is quite large, finding and deleting one document will take quite a long time. Is there any way to speed up the process? A: Like you can't really avoid a deletion operation in the database if you want to delete anything. If you're having performance issue I would just recommend to make sure you have an index built on the id field otherwise Mongo will use a COLLSCAN to satisfy the query which means it will over iterate the entire colLOne collection which is I guess where you feel the pain. Once you make sure an index is built there is no "more" efficient way than using deleteMany. db.collOne.deleteMany({id: {$in: [4, 8, 9, .... ]}) * *In case you don't have an index and wonder how to build one, you should use createIndex like so: (Prior to version 4.2 building an index lock the entire database, in large scale this could take up to several hours if not more, to avoid this use the background option) db.collOne.createIndex({id: 1}) ---- EDIT ---- In Mongo shell: Mongo shell is javascript based, so you just have to to execute the same logic with js syntax, here's how I would do it: let toDelete = db.collTwo.findOne({ ... }) db.collOne.deleteMany({id: {$in: toDelete.ids}})
{ "language": "en", "url": "https://stackoverflow.com/questions/64045758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django ModuleNotFoundError: No module named 'EmailIngestionDemo.EmailIngestionDemo' Im trying to write a django web that will retrieve data from postgresql and display on it. But whenever I run my application it show me: from EmailIngestionDemo.EmailIngestionDemo.models import EmailData ModuleNotFoundError: No module named 'EmailIngestionDemo.EmailIngestionDemo' On my views.py I import my EmailData from EmailIngestionDemo.EmailIngestionDemo.models: Views.py from django.shortcuts import render from EmailIngestionDemo.EmailIngestionDemo.models import EmailData def showdata(request): results = EmailData.obj.all() return render(request, 'index.html',{"data":results}) This is my path: settings: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'EmailIngestionDemo' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'EmailIngestionDemo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'EmailIngestionDemo.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':"EmailData", 'USER':"postgres", 'PASSWORD':"xxx", 'HOST':"localhost", 'PORT':'5432' } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' A: Try from .models import EmailData A: * *get rid of the __init__.py adjacent to your manage.py - the level with manage.py should not be a Python package *use EmailIngestionDemo.models instead
{ "language": "en", "url": "https://stackoverflow.com/questions/68800369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails ActiveRecord using recently saved record id in after_save callback I want to use recently stored record ID in after_save callback, is that possible if yes how? after_save :create_children def create_children  self.id end Update: Sorry there was something going wrong with my save function, my bad, sorry to waste your time Thanks A: I just tried it with this: class Thing < ActiveRecord::Base after_save :test_me def test_me puts self.id end end and in the console: $ rails c Loading development environment (Rails 3.0.4) >> x=Thing.new => #<Thing id: nil, name: nil, created_at: nil, updated_at: nil> >> x.save 2 => true >> y=Thing.create 3 => #<Thing id: 3, name: nil, created_at: "2011-04-27 15:57:03", updated_at: "2011-04-27 15:57:03"> What else is going on in your model? A: if you call reload() after saving the object, the self.id will be populated
{ "language": "en", "url": "https://stackoverflow.com/questions/5805319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select records from a table with the latest 3 consecutive status as failed I am needing to select Phone Numbers that have the latest 3 consecutive status as Failed or Send_Failed. Let me explain further with an example (Microsoft SQL Server) My table: | Phone Number Attempted | Date Sent | SMS Return Code | |*456 | 2020-11-17| SEND_FAILED*| |*456 | 2020-11-16| SEND_FAILED*| |*456 | 2020-11-15| FAILED* | | 456 | 2020-11-14| DELIVERED | |*457 | 2020-11-17| SEND_FAILED*| |*457 | 2020-11-16| SEND_FAILED*| |*457 | 2020-11-15| SEND_FAILED*| | 457 | 2020-11-14| SEND_FAILED | | 455 | 2020-11-17| DELIVERED | | 455 | 2020-11-16| FAILED | | 455 | 2020-11-15| DELIVERED | | 455 | 2020-11-14| DELIVERED | | 454 | 2020-11-17| DELIVERED | | 454 | 2020-11-16| DELIVERED | | 454 | 2020-11-15| DELIVERED | | 454 | 2020-11-14| DELIVERED | | 453 | 2020-11-17| SEND_FAILED | | 453 | 2020-11-16| SEND_FAILED | | 452 | 2020-11-17| SEND_FAILED | | 452 | 2020-11-16| SEND_FAILED | | 452 | 2020-11-15| DELIVERED |> Expected result: 456 457 While below query it gets results very close to what I need, it fails since it also select record 452. Apparently my query fails to set the condition that the three more recent status must be a failed each of them. select i.[Phone Number Attempted], [SMS Return Code] from (select [Phone Number Attempted], [Date Sent] from [MyTable]) i cross apply (select top 3 * from [MyTable] ti where i.[Phone Number Attempted] = ti.[Phone Number Attempted] and ti.[SMS Return Code] != 'DELIVERED') C group by i.[Phone Number Attempted], [SMS Return Code], C.[Date Sent] having MIN(C.[SMS Return Code]) !='DELIVERED' and MAX(C.[SMS Return Code]) !='DELIVERED' and count (*) >= 3 and C.[Date Sent] = MAX(i.[Date Sent]) A: You can use lag(): select distinct phone from (select t.*, lag(status) over (partition by phone order by date) as prev_status, lag(status, 2) over (partition by phone order by date) as prev2_status, from t ) t where status in ('Failed', 'Send_Failed') and prev_status in ('Failed', 'Send_Failed') and prev2_status in ('Failed', 'Send_Failed') ; A: Below query gave me the right results for my own question select distinct A.[Phone Number Attempted] from ( Select distinct [Phone Number Attempted], [SMS Return Code], [Date Sent] ,LAG([SMS Return Code]) over (partition by [Phone Number Attempted] order by [Sent Date]) as prev_status ,lag([SMS Return Code], 2) over (partition by [Phone Number Attempted] order by [Sent Date]) as prev2_status from [MyTable] ) A where prev_status in ('FAILED', 'SEND_FAILED') and prev2_status in ('FAILED', 'SEND_FAILED') and [SMS Return Code] in ('FAILED', 'SEND_FAILED') and not exists (Select 1 from [MyTable] B where A.[Phone Number Attempted] =B.[Phone Number Attempted] and B.[Sent Date] > A.[Sent Date])
{ "language": "en", "url": "https://stackoverflow.com/questions/64886548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selenium webdriver stops executing test in Firefox Whenever I run a test script in firefox sometimes it continues to load/keep on loading the page even after 5 mins and at the same time I observed on the left side bottom of the page 'Transferring data from a.rfihub.com...'I had to abort the test run and execute it again. I don't know what this rfihub.com means and why it interferes or delays or stops loading the page. What can I do to prevent this? Need help. Thanks in advance A: I solved this issue by enabling DO Not Track option in Firefox. Menu -> Options-> Privacy-> click manage your Do Not Track Settings and uncheck the box. Restart the Firefox. Hope this helps someone facing similar issue in future.
{ "language": "en", "url": "https://stackoverflow.com/questions/36896869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .PivotTables function not recognized in VBA VBA seems to ignore the .PivotTables function in the code below. Does anybody have any possible explanation for this? Could there be a necessary but inactive reference library? Thanks in advance. ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:= _"Raw!" & Sheets("Raw").Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1), Version:=6).CreatePivotTable _ tabledestination:="PivotTable!" & Sheets("PivotTable").Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 3).Address _ (ReferenceStyle:=R1C1), TableName:="MFTPiv1", defaultversion:=6 With ActiveSheet.pivottables("MFTPiv1").PivotFields("Wholesaler") .Orientation = xlRowField .Position = 1 End With A: If your sheet isn't active it can't be found by "ActiveSheet". Make your sheet "PivotTable" active: Sheets("PivotTable").Select With ActiveSheet.pivottables("MFTPiv1").PivotFields("Wholesaler") .Orientation = xlRowField .Position = 1 End With Or not: With Sheets("PivotTable").pivottables("MFTPiv1").PivotFields("Wholesaler") .Orientation = xlRowField .Position = 1 End With Additionally, I've never used that "xlConsolidation" source type. I tried it on a bit of data I have here and it created a pivot table that is not conducive to what you're trying to accomplish. A "standard" pivot cache uses SourceType:=xlDatabase. Maybe try that.
{ "language": "en", "url": "https://stackoverflow.com/questions/45723189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Three.js list of random points Beginner question: I create some random points in java script. How can I later "call" each single one of them? I believe it was called an Object (the list of all points), where I can manipulate their position in the list or "pull" the ones I need. How do I do that in js? what is the line: var dots = []; for? The comment after that was added from another person and I don't get it. How can I make a line between two points (let's say the first and second from the list - the 0 and the 1) in Three.js? More complicated question: I create here X (in this case 20) random points in java script. I am trying to figure out a way to randomly create faces using groups of 3 points and form a mesh. Well, not so randomly, because I need a result, where all faces bind together in a continuous mesh. The result should look like a terrain poly-surface made out of the many vertex points. What rules should be applied? var numpoints = 20; var dots = []; //If you want to use for other task for (var i = 0 ; i < numpoints ; i++) { var x = Math.random() * (80 - 1) + 1 //Math.random() * (max - min) + min var y = Math.random() * (80 - 1) + 1 var z = Math.random() * (10 - 1) + 1 var dotGeometry = new THREE.Geometry(); dots.push(dotGeometry); dotGeometry.vertices.push(new THREE.Vector3(x, y, z)); var dotMaterial = new THREE.PointCloudMaterial( { size: 3, sizeAttenuation: false, color: 0xFF0000 }); var dot = new THREE.PointCloud( dotGeometry, dotMaterial); scene.add(dot); } A: To get a random element from array: function randChoice(array){ return array[Math.floor(Math.random()*array.length)]; }; There are 2 method to generate a mesh from random points that I know of: convex hull and alpha shape. Creating a mesh by repeating picking 3 random points would almost surely result in spaghetti. If you just want to generate terrain like in the picture, there is terrain generation from heightmap.
{ "language": "en", "url": "https://stackoverflow.com/questions/37793750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel to Access, change data types as part of a button's on click action I have 2 reports I run in SAP (I only have user level permissions) twice daily that need to end up in Access. The current process looks something like this: (1) Run report one, select the fields I need, export to Excel. (2) Run a saved import within Access to get the table. (3) Switch that table to design view so I can edit the data types to sync with the table I intend to update. (4) Run an append query. (5) Rinse and repeat for report 2. Since I'm looking to delegate this task to a user I'd like a button that changes the process to: (1) Run report one, select the fields I need, export to Excel. (2) Click the "import, change data type and append" button. (3) Rinse and repeat for report 2. The Excel document's formatting looks like this: txtField1 txtField2 txtField3 txtField4 txtField5 DateAndTimeField1 It also uses different naming conventions than Access. Access needs: TxtField1 txtField2 NumberField1 NumberField2 NumberField3 DateAndTimeField1 I can get the Excel document into Access using a macro then just add an append query to the button's actions. But I can't append it to the table I want unless the data types sync. How do I switch the data types and (if using vba) column headings on the imported document as part of the button's on click action? A: Maybe try Range("A1").NumberFormat Or, Range("D2").Value = Val(Range("C2").Value) The Val() function.
{ "language": "en", "url": "https://stackoverflow.com/questions/31456910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: try to extract one tweet's id information after creating an API object I'm still new in python and i was trying to extract one tweet's id information after creating an API object. so the code was : import tweepy consumer_key = 'hidden' consumer_secret = 'hidden' access_token = 'hidden' access_secret = 'hidden' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) # to test it exp_tweet = api.get_status(archive.tweet_id[1000], tweet_mode = 'extended') content = exp_tweet._json Content the output is : NameError: name 'archive' is not defined [enter image description here][1] A: If I take this tweet, I can find it's id in the URL witch is "1294917318405836802" You can update your code and try to retrieve it id_ = "1294917318405836802" exp_tweet = api.get_status(id_, tweet_mode = 'extended') content = exp_tweet._json
{ "language": "en", "url": "https://stackoverflow.com/questions/63923652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: cart.discount.enabled returns "true" in advanced demo, "false" on published page. I am wondering why cart.discount.enabled returns different values. I get it as "true" when I'm using the advanced editor on my admin page, but when I save and view the actual page (both in and out of maintenance mode) I get a "false" response. Why is this? I have discounts set up and active right now. Any idea why this is coming back false? I hope there's not some easy thing like a "turn on discounts" checkbox, I've combed through all the settings and not seen one. ' Thanks everyone! A: It sounds like you have seamless checkout with Stripe set as your store's Checkout option - which moves all of the shipping and discount calculations to the separate Checkout page. Unfortunately the design editor hasn't been updated to reflect these new changes with the seamless checkout, so those variables will still return "true" (as if you're using PayPal's checkout) when previewing your store.
{ "language": "en", "url": "https://stackoverflow.com/questions/24728344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search Keyword and rename entire file using VBS I spent a quite a bit looking around. I did find one method that was extremely close to what I was looking for but it replaces keywords. Dim sName Dim fso Dim fol ' create the filesystem object Set fso = WScript.CreateObject("Scripting.FileSystemObject") ' get current folder Set fol = fso.GetFolder("F:\Downloads") ' go thru each files in the folder For Each fil In fol.Files ' check if the file name contains underscore If InStr(1, fil.Name, "[wizardry] tv show bob - 13") <> 0 Then ' replace underscore with space sName = Replace(fil.Name, "[wizardry] tv show bob - 13", "tv show bob S03E13") ' rename the file fil.Name = sName End If Next ' echo the job is completed WScript.Echo "Completed!" But as I said, the only issue is that it repalces the keywords. I want it to replace the ENTIRE file name with what I want. Most of the files will have a group tag before hand like this: [wizardy] tv show bob - 13 I want to make sure the group tag is gone so I can actually copy the file over. Unless there is a way to pull the file name of the current file I renamed. Any help is appreciated, thanks. A: Instead of replace, you need to generate a new name with the original extension, I think? If not, please give us more detail. Dim sName Dim fso Dim fol Dim fil Dim ext Set fso = WScript.CreateObject("Scripting.FileSystemObject") Set fol = fso.GetFolder("F:\Downloads") For Each fil In fol.Files 'may need to specify a comparison If InStr(1, fil.Name, "[wizardry] tv show bob - 13", vbTextCompare) <> 0 Then ext = fso.GetExtensionName(fil) If Len(ext) > 0 Then ext = "." & ext sName = "tv show bob S03E13" & ext fil.Name = sName End If Next WScript.Echo "Completed!"
{ "language": "en", "url": "https://stackoverflow.com/questions/29177398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to put a link to the php set message I'm quite new in php and I'm editing code in the cake php. I would like to add a link to the help page after a error message: existing code: if (count($results) > 0) { $this->set("message", "Sorry, that data already exists."); return; } something like this: if (count($results) > 0) { $this->set("message", "Sorry, that data already exists.") <a href="http://www.example.com/">; return; } should I use echo within a php code - it just does not work for me. Thank you A: try to use this code if (count($results) > 0) { $this->set("message", "Sorry, that data already exists. <a href=\"http://www.example.com/\">Need help?</a>"); return; } A: $this->set("message", 'Sorry, that data already exists.<a href="http://www.example.com/">'); Doing this will get the anchor in as part of the string, and if you need to echo it, it should be generated as HTML. A: it's simply: if (count($results) > 0) { $this->set("message", 'Sorry, that data already exists. <a href="http://www.example.com/">'); return; } Better use single quotes ' and you don't need to escape " in tags attributes. Or store link in variable: if (count($results) > 0) { $link = '<a href="http://www.example.com/">'; $this->set("message", "Sorry, that data already exists. $link"); return; }
{ "language": "en", "url": "https://stackoverflow.com/questions/21582844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF REST - How can i test WebCache I'm trying to test my REST service with WebCache attribute [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public partial class MyContract : IMyContract { [OperationContract()] [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "items/{code}" [WebCache(CacheProfileName = "NoCacheProfile")] public ItemDTO GetItem(string code) when i try to open the host WebServiceHost host = new WebServiceHost2(typeof(MyContract), true, new Uri("http://localhost:7777/MySvc")); host.Open(); i get the following exception [System.NotSupportedException] = {"WebCacheAttribute is supported only in AspNetCompatibility mode."} A: If WebCacheAttribute is supported only in AspNetCompatibility mode, you may need to declare AspNetCompatibilityRequirementsMode = Required in "AspNetCompatibilityRequirements" attribute and check the service configuration in Web.config to ensure it is enabled: <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> </system.serviceModel> For more information, please visit: http://msdn.microsoft.com/en-us/library/aa702682.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/3071875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Weird LD_PRELOAD trick + gcc destructor behavior I have recently learned the LD_PRELOAD trick (What is the LD_PRELOAD trick?), which can be used to debug or patch the program. I wanted to see if I could combine this trick and GCC destructor (https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html) to debug a variable, and created an extremely simple case to hone my understanding. I have test.c as provided below: #include <stdio.h> int a = 1; void __attribute__((destructor)) run_last() { printf("Destructor: %d\n", a); } and test_2.c as provided below: #include <stdio.h> #include "test.c" int main() { extern int a; printf("main: %d\n", a++); } I compile test.c using the command gcc -Wall -O3 -fPIC -shared test.c -o test.so to generate the shared object, and compile test_2.c using the command gcc test_2.c -o test_2 Now, what I'm hoping to see is an output of: main: 1 Destructor: 2 The reason for this expectation is because I have post-incremented the variable a after I printed the statement, and as I am using extern int a, as far as I understand, I am incrementing the variable a that was declared in the test_2.c, which contains the destructor function run_last() that will use the most updated value of a. However, instead, I get an output such as this: Why is there a Destructor: 1 here? From my understanding, shouldn't the destructor only be called once? My guess at the moment is that when I #include "test.c" in the test_2.c, there is a behavior that I don't understand at the moment. Thank you for any suggestions or guidance,
{ "language": "en", "url": "https://stackoverflow.com/questions/66648308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binding the validator for one control to another control's value in Angular Reactive Forms I'm quite familiar with Angular 1.6, just starting to learn Angular 5 and looking at reactive forms so apologies if this is a bit of a newbie question. Our applications have lots of complex validation rules and I can see how in most cases they would be easier to implement with reactive forms. I have some scenario which seems a lot harder, specifically when the input to a validator is the value from another control. Here are two obvious examples: * *"From" and "to" date fields, where the "to" field must be a later date than the "from" field *"Confirm password" field must have the same value as the "password" field. In Angular 1 land, I would have done something like this: <input ng-model="vm.from" /> <input ng-model="vm.to" must-be-later-than="vm.from" /> <input ng-model="vm.password" /> <input ng-model="vm.confirmPassword" must-be-identical="vm.password" /> I'd have written custom validator directives for mustBeLaterThan and mustBeIdentical, but I'd have got automatic binding between the fields and the directives would only need to be written once. In Angular 2/4/5 reactive forms, it seems like I would create validator factory function, but I'm not clear on what I would pass into it as parameters other than the related FormControl, which seems dirty. I could obviously observe changes in one field and repeatedly destroy and recreate validators in the other, but that seems inefficient and convoluted. Is there a better convention that gets used in scenarios like this? A: I discovered the convention (couldn't find it the way I was Googling it because of my assumptions about the solution). You put both fields in a FormGroup and add a validator to the group.
{ "language": "en", "url": "https://stackoverflow.com/questions/48870539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: make image from several uiviews with imageview How can I make one image of several uiviews that have an imageview on it, with the scale and everything, I already found some code to put one image to another: - (UIImage *)addImage:(UIImage *)imageView toImage:(UIImage *)Birdie { UIGraphicsBeginImageContext(imageView.size); // Draw image1 [imageView drawInRect:CGRectMake(0, 0, imageView.size.width, imageView.size.height)]; // Draw image2 [Birdie drawInRect:CGRectMake(0, 0, Birdie.size.width, Birdie.size.height)]; UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultingImage; } This code make one image with two images at the point 0,0, I need to merge several images with the actual zoom to one image, I have one background image and several objects on it that I can zoom in and out and i want to make a final image with all the objects at their places and with their zoom, like photoshop, where you have several objects and you can merge them into one. A: You can do it as follows: Simply take the top-level view where all of the sub-views have been composited, and then: + (UIImage *) imageWithView:(UIView *)view { UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0); if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) { //This only works on iOS7 [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES]; } else { //For iOS before version 7, use the following instead [view.layer renderInContext:UIGraphicsGetCurrentContext()]; } UIImage * img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; }
{ "language": "en", "url": "https://stackoverflow.com/questions/19767815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Specifying desired crs format of Geopandas object I use geopandas's to_file() method to read a shapefile into a geopandas object. The shapefile has a valid .prj file with a ESRI WKT style projection information: PROJCS["Slovenia_1996_Slovene_National_Grid",GEOGCS["GCS_Slovenia 1996",DATUM["D_Slovenia_Geodetic_Datum_1996",SPHEROID["GRS_1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",15],PARAMETER["scale_factor",0.9999],PARAMETER["false_easting",500000],PARAMETER["false_northing",-5000000],UNIT["Meter",1]] With this, a created geodataframe has a crs attribute set as a dictionary, which I find it hard to work with, compared to proj4 string or epsg codes: {u'lon_0': 15, u'k': 0.9999, u'ellps': u'GRS80', u'y_0': -5000000, u'no_defs': True, u'proj': u'tmerc', u'x_0': 500000, u'units': u'm', u'lat_0': 0} Geopandas projection docs make it clear that .crs method accepts many different forms of crs information (epsg codes, dictionaries, proj4 strings,...), but it seems that there there is no control about the desired format when writing geopandas to shapefile. Question: Is there any way to specifiy the desired crs formatting or any built-in method to switch between the diffent formattings of crs attribute? A: Not sure if I'm missing something here, but have you tried just setting the crs in the dataframe before doing to_file() like below: gdf = geopandas.GeoDataFrame(df, geometry='geometry') gdf.crs = {'init' :'epsg:4326'} # or whatever A: Is there any way to specifiy the desired crs formatting The shapefile prj file has to be in the WKT format. See: https://gis.stackexchange.com/questions/114835/is-there-a-standard-for-the-specification-of-prj-files#114851 any built-in method to switch between the diffent formattings of crs attribute? Geopandas uses pyproj as a dependency. If you use pyproj 2+, you can use the pyproj.CRS class to convert formats. See: https://pyproj4.github.io/pyproj/stable/examples.html Additionally, you can use the pyproj.CRS class directly to check for equality of different CRS inputs.
{ "language": "en", "url": "https://stackoverflow.com/questions/42161889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: IQueryable doesn't allow ThenBy I'm trying to sort an IQueryable by multiple columns and many StackOverflow answers seem to indicate I should be able to do an OrderBy for the Primary sort and then a ThenBy for additional sorts. The OrderBy is fine but it's not allowing me to use ThenBy. It doesn't compile. I don't get why... IQueryable<vMyView> contacts = db.vMyView; var orderExpressions = new Dictionary<string, Expression<Func<vCRMAllContact, object>>>() { {"LastName", x => x.LastName}, {"FirstName", x => x.FirstName}, {"Email", x => x.Email}, {"Telephone1", x => x.Telephone1} }; contacts = contacts.OrderBy(orderExpressions[sortExpression], ascending).ThenBy(orderExpressions["FirstName"]).Skip(pageIndex * pageSize).Take(pageSize); A: Your first example is correct and absolutely should work: var contacts = db.vMyView.OrderBy(c => c.LastName).ThenBy(c => c.FirstName); // not sure why you need to reorder. Which could distort previous sorting contacts = contacts.OrderBy(orderExpressions[sortExpression]).ThenBy(orderExpressions["FirstName"]); Something looks off in your second example. OrderBy and ThenBy are already ascending there's no need for the additional parameter. There are alternatives for descending which are suffixed appropriately: OrderByDescending and ThenByDescending.
{ "language": "en", "url": "https://stackoverflow.com/questions/50182628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Exposing Just a Single Property Value from the Code I want to bind a single property from my datacontext and diplay on UI. How can I display the property Address in a texblock? public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } public class Person : INotifyPropertyChanged { private string fullname; public string FullName { get { return fullname; } set { fullname = value; OnPropertChanged("FullName"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } A: If you want to bind the Property to a textblock first in public partial class MainWindow : Window { private Person _myWindowModel = new Person() public MainWindow() { InitializeComponent(); DataContext = _myWindowModel; } } and after that in your Window in WPF go to the TextBlock and add: Text="{Binding FullName}"
{ "language": "en", "url": "https://stackoverflow.com/questions/30095192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my function getting "character(0)" as output when it works step by step in the console My function returns "character(0)" and I can't work out why. If I do it step by step in the console the result is right but not when I execute the function. The assigment I've got is the following: Write a function called best that take two arguments: the 2-character name of a state and an outcome. The function returns the name of the hospital that has the lowest mortality rate for the specified outcome (mortality rate) in that state. The outcomes can be one of “heart attack”, “heart failure”, or “pneumonia”. Hospitals that do not have data on a particular outcome should be excluded from the set of hospitals when deciding the rankings. The code I've got is the following: best <- function(state, outcome) { ## Read outcome data data <- read.csv("outcome-of-care-measures.csv", colClasses = "character", na.strings = "Not Available") data <- data[c(2, 7, 11, 17, 23)] names(data)[c(3:5)] <- c("heart attack", "heart failure", "pneumonia") ## Check that state and outcome are valid if (!state %in% unique(data$State)){ stop("Invalid State") } if (!outcome %in% c("heart attack", "heart failure", "pneumonia")) { stop("Invalid outcome") } ## Return hospital name in that state with lowest 30-day death hospital_data <- data[data$State == state, ] min <- which.min(hospital_data$outcome) hospital_name <- hospital_data[min, 1] print(hospital_name) } A: The issue is min <- which.min(hospital_data$outcome) and 'outcome' is passed as a string, but it is just literally using 'outcome' instead of the value passed in the function. It looks for the column 'outcome' in the data.frame and couldn't find it. df1 <- data.frame(col1 = 1:5) outcome <- 'col1' df1$outcome #NULL df1[[outcome]] Use [[ instead of $ min <- which.min(hospital_data[[outcome]])
{ "language": "en", "url": "https://stackoverflow.com/questions/58104460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing the link for the ModelAdmin list view in Django to apply a default filter? I want to apply a default filter value on a field ModelAdmin in django. I have a Model admin for the User model, which displays users. The user has a m2m to an Account model, so I am adding in the ModelAdmin: class CustomUserAdmin(UserAdmin): list_filters = ('accounts') In the filter I want it to give a default selected value, if nothing is selected. However I still want to give the user the option to revert to the default All option. So far all the solutions that I found, prevent reverting to the All option. For example this answer. I am thinking, that maybe chaining the link on the side menu to include the desired filter option in the query parameters. Is this doable? I can see in the source code for admin/app_list.html (source code), that the URL comes from model.admin_link, but I cant find any documentation for changing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/67070494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get an element in a list at a specified index I need to write a program that return an element from a list, using a specified index. We have a list of the English alphabet X = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] Starting at 0, I have to return, for example, the number with index 13, so the letter 'n', how do you return an element from a list with a specified index? Here's what I have worked in, but still doesn't run properly. position(0, 0, [], a). position(X, I, [H1|T1], _):- position(X, I1, T1, H1), I = I1 + 1. A: It's just a matter of iterating over the list and counting as you go. Try something like this: select( [X|_] , 0 , X ) . select( [_,Xs] , N , C ) :- N > 0 , N1 is N-1, select(Xs,N1,C). or select( Xs , N , C ) :- select(Xs,0,N,C) . select( [X|_] , N , N , X ) . select( [_|Xs] , V , N , C ) :- V1 is V+1, select(Xs,V1,N,C). The latter will work in a more Prolog-like way, bi-directionally. It doesn't care if you specified an index or not: * *select( [a,b,c,d] , N , C ) successively succeeds with * *N=0, C=a *N=1, C=b *N=2, C=c *N=3, C=d *select( [a,b,c,d] , 2 , C ) succeeds with just * *C=c *select( [a,b,c,d] , N , d ) succeeds with just * *N=3 A: My approach is also "count the number down and match the thing from the front when it reaches zero": :- use_module(library(clpfd)). position(0, [Elem|_], Elem). position(Pos, [_|T], Elem) :- Pos #= Pos_ + 1, position(Pos_, T, Elem). Your request "a program that return an element from a list, using a specified index" is an imperative request like you might use in Python; taking a single index and returning a single element. Changing to a Prolog relational way of thinking brings you to Nicholas Carey's comment: will work bi-directionally. It doesn't care if you specified an index or not So you can give an element and get an index. As well as that, they can check whether an element is at an index; this confirms 'dog' is in position 3, and says 'cow' is not in position 3: ?- position(3, [apple,box,cat,dog], dog). true ?- position(3, [apple,box,cat,dog], cow). false On backtracking, find all positions of an element, this finds 'box' in two places: ?- position(Pos, [apple,box,cat,dog,box], box). Pos = 1 ; Pos = 4 Which means compared to Python this code overlaps with x = items[i] and i = items.index(x) and enumerate(items) and items[i] == x.
{ "language": "en", "url": "https://stackoverflow.com/questions/72294298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS a:hover image borders I have a bunch of linked images in a table, with some padding. When I try to add an img:hover or a:hover border attribute, when the border appears, everything moves over by the amount of pixels that the border is thick. Is there a way to stop this behavior? A: img { border: solid 10px transparent; } img:hover { border-color: green; } A: img:hover { border: solid 2px red; margin: -2px; } Seems to work for me (Safari 6.0.5). No added space since the border is drawn on the 'inside' of the img. A: The problem is that you're adding a border to the element that takes up space - the other elements on the page have to move to make room for it. The solution is to add a border that matches the background, and then just change the color or styling on hover. Another possibility is to make the box larger than you originally intended, and then resize it to fit the border you're adding.
{ "language": "en", "url": "https://stackoverflow.com/questions/4191651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I track incoming search keywords Does anyone know how I could track what search terms people are using to arrive at my site. For instance, someone searchs google for 'giant inflatable house' and clicks through to my site. I want to be able to capture those keywords and which search engine they came from. A: You must parse the referer. For exemple a google search query will contains: http://www.google.be/search?q=oostende+taxi&ie=UTF-8&oe=UTF-8&hl=en&client=safari It's a real life query, yes I'm in Oostebde right now :) See the query string. You can determine pretty easily what I was looking for. Not all search engines are seo friendly, must major players are. How to get the referer ? It depends on the script language you use. A: You should use a tool like Google analytics. A: Besides the Google Analytics, Google Webmaster Tools is also very useful. It can report a detail analysis of the search queries' impressions, clicks, CTR, position etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/3469893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Simple sql solution needed SELECT distinct denomination, (SELECT count(com) from security where denomination = 200), (SELECT count(com) from security where denomination = 50), (SELECT count(com) from security where denomination = 1000), (SELECT count(com) from security where denomination = 100) from security; denomination | ?column? | ?column? | ?column? | ?column? --------------+----------+----------+----------+---------- 200 | 1 | 2 | 1 | 2 50 | 1 | 2 | 1 | 2 100 | 1 | 2 | 1 | 2 1000 | 1 | 2 | 1 | 2 The above code prints the above result. Thats not what i want. How do i write so the count of com for every denomination value so it would appear in separate column near respective number of denomination? i want it to look like this: denomination | ?column? | --------------+----------+ 200 | 1 | 50 | 2 | 100 | 2 | 1000 | 1 | Im sure the answer is simple, i just cant make my mind around it. A: SELECT denomination, count(com) FROM security WHERE denomination IN (200, 50, 1000, 100) GROUP BY denomination;
{ "language": "en", "url": "https://stackoverflow.com/questions/20607581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to link Android Developer merchant account to an existing Google merchant checkout account I would like to know how can I link an Android Developer merchant account with an existing Google checkout account. During the creation of the Android Developer merchant account, I only see the option to create a new google checkout account - I don't see a way to link to an existing google check out account. Does anyone know if this is possible? If so, can you tell me how to do it? The google developer documentation doesn't explicitly say it's not possible. A: In order to Link your Adsense account to your Developer account you MUST create first a Google Checkout Account. After creating one, you will see on your developer console a new request to link between your account to your adsense (by entering your pub-xxxxxxxxxxx id).
{ "language": "en", "url": "https://stackoverflow.com/questions/6296943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Make the cursor disappear I have a fullscreen c# application and I want that the cursor won't be visible while the user is in the application. (Controlling the application is solely with the keyboard) Any one knows how to do such a thing? PS : I prefer that the cursor will be completely unusable rather than "invisible" or "transparent" A: I think the only option you'll have is to hide the cursor from what I can remember in the past Cursor.Hide() I had to do something similar to this in a touchscreen app in the past A: If you prefer the cursor to be completely unusable, then Cursor.Hide() won't fulfill your requirements, because the cursor is only hidden but still clickable. You'll need to add something like this to disable clicking as well. A: vb.net: Me.Cursor = Cursors.No c:.net: this.Cursor = Cursors.No
{ "language": "en", "url": "https://stackoverflow.com/questions/9433187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: UIRefreshControl not working inside Container View I've got ViewController, that has ContainerView with another ViewController and UITableView. I am adding UIRefreshControl to tableView (inside Container) like this: refreshControl.addTarget(self, action: #selector(SomeViewController.reloadData), for: .valueChanged) tableView.addSubview(refreshControl) And it does not work. SomeViewController.reloadData is never called. Now when I do the same thing, except without container, everything works. Should I set some delegates or something to main/top ViewController, that has Container? A: Have you tried setting the refreshControl to the corresponding property on your tableView instead of adding it as a subview? tableView.refreshControl = refreshControl That should do it. edit: If you support any iOS earlier than 10, you will not be able to add it to the tableView directly but will instead need to add it to your UITableViewController, assuming you are using one. self.refreshControl = refreshControl
{ "language": "en", "url": "https://stackoverflow.com/questions/42398546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rollup.js - have PostCSS process whole bundle.css instead of individual files from rollup-plugin-svelte I've tried several guides and many configurations, but can't get my rollup, postcss, and svelte bundle process to work quite right. Right now the svelte plugin is extracting the css from my .svelte files and emitting it to the posctcss plugin, but it's doing it one file at a time instead of the entire bundle. This makes it so some functions in the purgecss and nanocss postcss plugins don't completely work because they need the entire bundle to do things like remove duplicate/redundant/unused css rules. // rollup.config.js import svelte from 'rollup-plugin-svelte' import resolve from 'rollup-plugin-node-resolve' import commonjs from 'rollup-plugin-commonjs' import livereload from 'rollup-plugin-livereload' import { terser } from 'rollup-plugin-terser' import rollup_start_dev from './rollup_start_dev' import builtins from 'rollup-plugin-node-builtins' import postcss from 'rollup-plugin-postcss' const production = !process.env.ROLLUP_WATCH export default { input: 'src/main.js', output: { sourcemap: true, format: 'iife', name: 'app', file: 'public/bundle.js', }, plugins: [ svelte({ dev: !production, emitCss: true, }), postcss({ extract: true, sourceMap: true, }), builtins(), resolve({ browser: true, dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/'), }), commonjs(), !production && rollup_start_dev, !production && livereload('public'), production && terser(), ], watch: { clearScreen: false, }, } // postcss.config.js const production = !process.env.ROLLUP_WATCH const purgecss = require('@fullhuman/postcss-purgecss') module.exports = { plugins: [ require('postcss-import')(), require('tailwindcss'), require('autoprefixer'), production && purgecss({ content: ['./src/**/*.svelte', './src/**/*.html', './public/**/*.html'], css: ['./src/**/*.css'], whitelistPatterns: [/svelte-/], defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [], }), production && require('cssnano')({ preset: 'default', }), ], } How can I have rollup pass the entire bundle.css to postcss instead of one "file" at a time? A: I had the same problem, preprocess goes file by file, so I had to actually include all my mixins and vars in every file, which is absolutely not a good solution. So for me the first solution was to remove postcss from sveltePreprocess, not emit the css file and to use postcss on the css bundle, that you get in the css function from svelte. You can then or (1) use postcss directly in the css function of svelte, and then emit the resulting css file in your dist directory, or (2) you can emit this file in a CSS directory, and have postcss-cli watch this directory and bundle everything Solution 1 // rollup.config.js // rollup.config.js import svelte from 'rollup-plugin-svelte'; import resolve from 'rollup-plugin-node-resolve'; import postcss from 'postcss'; import postcssConfig from './postcss.config.js'; const postcssPlugins = postcssConfig({}); const postcssProcessor = postcss(postcssPlugins); export default { input: 'src/main.js', output: { file: 'public/bundle.js', format: 'iife', }, plugins: [ svelte({ emitCss: false, css: async (css) => { const result = await postcssProcessor.process(css.code); css.code = result.css; css.write('public/bundle.css'); }, }), resolve(), ], }; and my postcss.config.js which returns a function that return an array of plugins: export default (options) => { const plugins = [ require('postcss-preset-env')() ]; if (options.isProd) { plugins.push(require('cssnano')({ autoprefixer: false })); } return plugins; }; Solution 2 // rollup.config.js import svelte from 'rollup-plugin-svelte'; import resolve from 'rollup-plugin-node-resolve'; export default { input: 'src/main.js', output: { file: 'public/bundle.js', format: 'iife', }, plugins: [ svelte({ emitCss: false, css: async (css) => { css.write('css/svelte-bundle.css'); }, }), resolve(), ], }; // package.json { //... "scripts": { "dev": "npm-run-all --parallel js:watch css:watch", "js:watch": "rollup -c -w", "css:watch": "postcss css/app.css --dir dist/ --watch", }, } /* css/app.css */ @import 'vars.css'; @import 'mixins.css'; /* all other code ... */ /* and svelte-bundle, which will trigger a bundling with postcss everytime it is emitted */ @import 'svelte-bundle.css'; Conclusion All in all, I don't like this methods, for exemple because I can't use nesting, as svelte throws an error if the css is not valid. I would prefer being able to use rollup-plugin-postcss after rollup-plugin-svelte, with emitCss set to false and the possibility to use rollup's this.emitFile in svelte css function, because since once the bundled file is emitted, we should be able to process it. It seems there are some issues talking about using emitfile, let's hope it will happen sooner than later https://github.com/sveltejs/rollup-plugin-svelte/issues/71 A: Can't say for sure, but when i compare your setup with mine the most striking difference is that i have: css: css => { css.write('public/build/bundle.css'); } in the svelte options additionally. My whole svelte option looks like this: svelte({ preprocess: sveltePreprocess({ postcss: true }), dev: !production, css: css => { css.write('public/build/bundle.css'); } }) Note, i'm using sveltePreprocess which would make your postcss superfluous, but i don't think that is causing your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/59792844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to send multple requests in an loop? I'm trying to make an automate project like send requests -> parse data - > connect to DB -> make a report via pandas. I was almost done, but recently discovered a bug that my loop sends only the 1st method. As you can see, I'm reading an .xml file and sending it as a body for request. My version is that 2nd .xml is way too big, like 900 strings and about 8Kb, meanwhile the first .xml is about 20 string and 1kb. Is there a way to fix it? cargoType = input('Enter a cargo type (CargoRedirection): ') cargoGuid = input('Enter a cargoGuid: ') methods = ['method1', 'method2'] # methods here are coming from filenames in a folder ./methods for method in methods: with open('./methods/' + str(cargoType) + '/' + str(method) + '.xml', 'rb') as methodBody: headers = { 'Content-Type': 'application/xml', 'Queue': 'Queue1', 'Message-Type': str(method), 'Branch': 'Branch1' } print(method) r = requests.post('url', data=methodBody, headers=headers) print(str(method) + 'was sent') A: You should send the file content, not the file handle. Your example is missing .read() Try: r = requests.post('url', data=methodBody.read(), headers=headers)
{ "language": "en", "url": "https://stackoverflow.com/questions/64914493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Marshaling structure with reference-type and value-type members inside a union bellow code is the marshling of a native win32 code. but i get an error message type load exception, can not load from assembly because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field there is a structure S1 with both value-type member and reference-type.. this structure is a member of union which has to have fieldOffset, but all S1 members can not start from fieldOffset 0 they are a mixture of reference and value type...how can I handle that?? [StructLayout(LayoutKind.Sequential)] public struct S1 { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeMsgid + 1)]//Reference Type public String MsgId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeTime + 1)]//Reference Type public String SendTime; public UInt32 SubsSeq;//Value Type public UInt32 ServTime;//Value Type [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Const.FieldSizeFillerA1 + 1)]//Reference Type public String Filler; } [StructLayout(LayoutKind.Explicit)] public struct AdminData { [FieldOffset(0)] public S1 S11;// get an error because the S1 has both reference type member and value type member [FieldOffset(0)] public S2 S22; [FieldOffset(0)] public S3 S33; } I know I have to break the S1 into 2 structures, one with value-type members and the other for reference-type members..but I do not know how to do it and how to reference them in AdminData which is a union. EDIT: here is the c++ code typedef struct S1 { char MsgId [Const.FieldSizeMsgid + 1];//Reference Type char SendTime[Const.FieldSizeTime + 1];//Reference Type int SubsSeq;//Value Type int ServTime;//Value Type char Filler[Const.FieldSizeFillerA1 + 1];//Reference Type } union AdminData { S1 S11;//has both value type member and reference type member S2 S22;//has both value type member and reference type member S3 S33;//has both value type member and reference type member } typedef struct MMTPMsg { int Length; short Type; AdminData Data; //the union long long TimeStamp; } A: As you have discovered you cannot overlay reference types on top of value types. So to implement your union, you need to use either one or the other. Your structures must contain value types and so we conclude that you must use value types exclusively. So, how do you implement your character arrays as value types? By using a fixed size buffer. unsafe public struct S1 { fixed byte MsgId[Const.FieldSizeTime + 1]; .... }
{ "language": "en", "url": "https://stackoverflow.com/questions/20951452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EXCEL: Search column for multiple strings, and give cell(s) of mismatch(es) I want to search into an entire column for mismatches (type-errors I made) compared to the available types I've defined. And in case there are any mismatches I want to have the cell of that mismatch displayed in the cell below. So this is what I have (I replaced the actual types with synonyms for privacy reasons, obviously they aren't named type# irl): Column E : E * *type1 (E1) *type5 (E2) *type3 (E3) *type3 (E4) *type7 (E5) *tipe2 (E6) *type9 (E7) *(E8) *type3 (E9) Column K2 : K10 * *type1 (K2) *type2 (K3) *type3 (K4) *type4 (K5) *type5 (K6) *type6 (K7) *type7 (K8) *type8 (K9) *type9 (K10) For example puposes I made the type-error "tipe2" in cell E6 and also added an empty row in cell E8. Now I want a formula which displays "Error" when something in column E:E does not match one of the types in column K2:K10, and else print either nothing or "no error found". And at the same time I want in a seperate cell the coordinates (in this case E6) of the mismatching cell. I've already got the part to get the mismatching cell, where my_string should be replaced with the mismatching string that has been found: ="E"&MATCH("my_string",E:E,FALSE)+IF(COUNTIF(E:E,"my_string")=1,0,COUNTIF(E:E,"my_string")-1) PS: I don't want a VBA script! I just want formulas inside two cells. One to see wether or not I made a mismatch, and incase I did made a mismatch I want the Cell's coordinates (or the last Cell's when multiple mismatches are found). A: You can use a so-called array formula to achieve this. As an illustration, I simulated your situation in this image: The important cell is H1, which contains the index of the offending cell in column E. For the sake of simplicity, I introduced two named ranges items, containing cells E1:E9 and lookup containing cells K2:K10. The formula in H1 is =MAX(IF(ISBLANK(items),0,IF(ISERROR(MATCH(items,lookup,0)),ROW(INDIRECT("1:"&ROWS(items))),0))) This is an array formula, which means that you have to confirm with Ctrl-Shift-Enter. If you did that right, the formula will show curly brackets around it -- you do not type those yourself. This formula goes over all cells in the range called items, creates an array with the value 0 for all cells that are blank or that have a match in the range called lookup. For the remaining cells, the value inserted is equal to the row number. Then the maximum is taken over that. As a result, H1 will contain the index of the last offending item. If all items are OK, then the value 0 is displayed. Cell G1 shows Error if any offending item has been found, and OK otherwise. The formula is =IF(H1=0,"OK","Error") Finally, I1 displays the actual offending item via =IF(H1>0,INDEX(items,H1),"") If you do not want to use the named ranges, then replace items with $E$1:$E$9 and lookup with $K$2:$K$10. If the offending cell is an empty cell, then I1 will contain the value 0. I think the value in H1 is useful for analysis, but if you do not want it, you can hide it. Or you can fold that formula in the ones used in G1 and I1, but the formulas become pretty complicated. A workbook containing this answer is uploaded here As a note on the side: are you aware that you can use Excel's data validation feature with a drop-down list to avoid these kinds of typos you are looking at. That might be useful for you. An example is given in the article Drop-Down Using Data Validation in Microsoft Excel A: The Easiest way to do this is; to use the filter "Does not contain" Excel 2010 solution, similar for 2003 * *Select the whole column *Select Data *Select Filter *Select filter option (triangle at top of column) *Select text filters *Select Does not contain *Enter type *Modify and rerun as needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/15311123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to decrease colorbar WIDTH in matplotlib? I have a plot I made in ipython notebook using two imported datasets & an array I made for the x-axis, but the colorbar is a bit thick for my liking. Is there any way to make it slimmer? #import packages import numpy as np #for importing u array import matplotlib.pyplot as plt #for plotting %matplotlib inline th = np.loadtxt("MT3_th.dat") #imports data file- theta pert. pi = np.loadtxt("MT3_pi.dat") #imports data file- pressure pert. k = np.loadtxt("MT3_z.dat") #imports data file- height i = np.linspace(-16.,16.,81) #x-axis array x, z = np.meshgrid(i, k) th[th == 0.0] = np.nan #makes zero values for th white clevels = [0.5, 1, 1.5, 2, 2.5, 3.] fig = plt.figure(figsize=(12,12)) thplot = plt.contourf(x, z, th, clevels, cmap=plt.cm.Reds, vmin=0., vmax=3.) ax2 = fig.add_subplot(111) piplot = ax2.contour(x, z, pi, 6, colors='k') plt.axis([-16.,16, 0, 16.]) plt.xticks(np.arange(-16,16.001,4)) plt.yticks(np.arange(0,16.001,2)) plt.colorbar(pad=0.05, orientation="horizontal") plt.xlabel("x (km)", size=15) plt.ylabel("z (km)", size=15) plt.title("Initial temp. & pres. perturbations (K, Pa)", size=20) plt.grid() plt.show() A: I was able to manually fix it using add_axes. (Thank goodness for colleagues!) cbar_ax = fig.add_axes([0.09, 0.06, 0.84, 0.02]) fig.colorbar(thplot, cax=cbar_ax, orientation="horizontal") A: Looking for the same answer I think I found something easier to work with compatible with the current version of Matplotlib to decrease the width of the colorbar. One can use the "ratio" option of the matplolib.figure function (see http://matplotlib.org/api/figure_api.html). And here is an example : import numpy as np from matplotlib import pyplot as plt # generate data x = np.random.normal(0.5, 0.1, 1000) y = np.random.normal(0.1, 0.5, 1000) hist = plt.hist2d(x,y, bins=100) plt.colorbar(aspect=20) plt.colorbar(aspect=50) A: I was able to use a combination of fraction and aspect parameters to get the desired width of the colorbar while it still stretched across the plot.
{ "language": "en", "url": "https://stackoverflow.com/questions/33443334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Passing date to request param in Spring MVC I am new to Spring MVC - and I am trying to pass a date from my javascript as a request Param My controller looks something like - public @ResponseBody List<RecordDisplay> getRecords( @RequestParam(value="userID") Long userID, @RequestParam(value="fromDate") Date fromDate, @RequestParam(value="toDate") Date toDate) { The question I have is how do I make the call from javascript - as in what should the URL look like for eg. - /getRecords?userID=1&fromDate=06022013&toDate=08022013' Do I need a way to parse the date so Spring can recognize it? A: This is now @DateTimeFormat as well which supports some common ISO formats A: Use @DateTimeFormat(pattern="yyyy-MM-dd") where yyyy is year, MM is month and dd is date public @ResponseBody List<Student> loadStudents(@DateTimeFormat(pattern="yyyy-MM-dd") Date birthDay) { ... } A: Use @DateTimeFormat("MMddyyyy") public @ResponseBody List<RecordDisplay> getRecords( @RequestParam(value="userID") Long userID, @RequestParam(value="fromDate") @DateTimeFormat(pattern="MMddyyyy") Date fromDate, @RequestParam(value="toDate") @DateTimeFormat(pattern="MMddyyyy") Date toDate) { A: You should use your application.properties (or any other project properties) and set the environment variable spring.mvc.format.date.
{ "language": "en", "url": "https://stackoverflow.com/questions/14766818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: Use ScriptBlock as determination for Mandatory I was hoping that I could setup a cmdlet so that it would use an environment variable for a parameter value if it exists, or otherwise prompt. function Test-Mandatory { [CmdletBinding()] param( [Parameter(Mandatory = { [string]::IsNullOrEmpty($Env:TEST_PARAM) })] [string] $foo = $Env:TEST_PARAM ) Write-Host $foo } Unfortunately, it seems that regardless of whether or not I have a $Env:TEST_PARAM set, the cmdlet always prompts for $foo. I could rework the validation to use [ValidateScript({ #snip #}), but then I wouldn't get Powershell prompting for the required value anymore, should $Env:TEST_PARAM not exist. I would simply get a validation error. So 2 questions here * *Why can I even assign a scriptblock to Mandatory if it doesn't appear to be honored? *Is there a simple way to get the default PS prompting behavior given the criteria I specified? A: FYI, here's what Microsoft had to say about it: "It’s not really a bug. Script blocks are valid attribute arguments – e.g. ValidateScriptBlock wouldn’t work very well otherwise. Attribute arguments are always converted to the parameter type. In the case of Mandatory – it takes a bool, and any time you convert a ScriptBlock to bool, you’ll get the value $true. You never invoke a script block to do a conversion." A: For the second question, you can always validate the value within the script. Just set the value to the environment variable as the default value. When I tried the validation with ($foo -eq $null) it didn't work, so I switched it to ($foo -eq ""). Here is a sample I tested to get what you were asking for: function Test-Mandatory { [CmdletBinding()] param( [string] $foo = $Env:TEST_PARAM ) begin { if ($foo -eq "") { $foo = Read-Host "Please enter foo: " } } #end begin process { Write-Host $foo } #end process } #end function As for the mandatory question, I believe if you assign a default value (even if it is empty), it will satisfy the mandatory assignment. When it goes to check if the value is present, since it was assigned a value, the mandatory checks true, allowing it to move on. A: Of note, this doesn't work as you would expect... I would expect $foo to be marked as mandatory only if $Env:TEST_PARAM does not exist. However, even when $Env:TEST_PARAM exists, the shell prompts :( function Test-Mandatory { [CmdletBinding()] param( [Parameter(Mandatory = { [string]::IsNullOrEmpty($Env:TEST_PARAM) })] [string] $foo ) if (!$PsBoundParameters.foo) { $foo = $Env:TEST_PARAM } Write-Host $foo }
{ "language": "en", "url": "https://stackoverflow.com/questions/12623749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Custom Excel Ribbon background colors (like design with tables) I have used CustomUIEditor to make many excel ribbons. I haven't been able to figure out how to change the background color of custom tabs I make. I'd like to change the background color of my tabs so they are noticeable as custom. I'm thinking of the same method excel uses when you click on a table and the color behind the design tab presents. Like this: A: While VBA can create and modify ribbons (and even add images) it can't change the overall color of the ribbon as seen when the ribbon is not selected. To change the ribbon color, you need a COM add-in. COM add-ins are different than regular add-ins. Instead of using VBA (which at first glance looks like Visual Basic and is similar to an outdated version of VB), COM add-ins utilize modern Visual Basic or Visual C++. How to write a COM add-in for Excel is beyond the scope of the question but here are some resources to get you started from Microsoft and Chuck Pearson: About Excel COM Add-ins Creating a COM Add-in Customizing Ribbon Colors
{ "language": "en", "url": "https://stackoverflow.com/questions/34909870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Inserting rows into a table with a predefined identity I am transfering data from an old database to a new one, and I need to keep the ID from the old database when inserting them into the new database. However, it's not working. This is my Query: SET IDENTITY_INSERT RentalEase.dbo.tblTenant ON INSERT INTO RentalEase.dbo.tblTenant SELECT [ID] ,1 ,[PropertyID] ,0 ,[UnitID] ,[TenantName] ,[Sex] ,[BirthDate] ,[SSNO] ,[CoTenant1] ,[CoTenant1Sex] ,[CoTenant1BirthDate] ,[CoTenant1SSNO] ,[CoTenant2] ,[CoTenant2Sex] ,[CoTenant2BirthDate] ,[CoTenant2SSNO] ,[CoTenant3] ,[CoTenant3Sex] ,[CoTenant3BirthDate] ,[CoTenant3SSNO] ,[CarColor] ,[CarModel] ,[CarYear] ,[CarState] ,[CarPlateNumber] ,[Memo] ,[Address1] ,[Address2] ,[Address3] ,[Address4] ,[Phone] ,[ReferBy] ,[BeginDate] ,[NoticeGiven] ,[LeaseMonth2Month] ,[LeaseEnds] ,[DepositPaid] ,[DepositRefundable] ,[RefundMemo] ,[RentDueDay] ,[Charge1] ,[Charge1Amount] ,[Charge2] ,[Charge2Amount] ,[Charge3] ,[Charge3Amount] ,[Charge4] ,[Charge4Amount] ,[ContractText] ,[BalanceDue] FROM [oldTables].[dbo].[tblCurrentTenant] SET IDENTITY_INSERT RentalEase.dbo.tblTenant OFF SQL Server complains that "An explicit value for the identity column in table RentalEase.dbo.tblTenant' can only be specified when a column list is used and IDENTITY_INSERT is ON." What do I need to do to get it to work? A: "An explicit value for the identity column in table RentalEase.dbo.tblTenant' can only be specified when a column list is used and IDENTITY_INSERT is ON." So use a column list, as the message states: SET IDENTITY_INSERT RentalEase.dbo.tblTenant ON INSERT INTO RentalEase.dbo.tblTenant ([ID], [fieldname], [fieldname], ...) SELECT [ID], ...
{ "language": "en", "url": "https://stackoverflow.com/questions/1435536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get absolute path from FileDialog? I'm creating FileDialog and trying to get a FilePath for FileDialog object. FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD); fd.setVisible(true); String path = ?; File f = new File(path); In this codes, I need to get a absolute FilePath for using with File object. How can I get filepath in this situation? A: Check out File.getAbsolutePath(): String path = new File(fd.getFile()).getAbsolutePath(); A: You can combine FileDialog.getDirectory() with FileDialog.getFile() to get a full path. String path = fd.getDirectory() + fd.getFile(); File f = new File(path); I needed to use the above instead of a call to File.getAbsolutePath() since getAbsolutePath() was returning the path of the current working directory and not the path of the file chosen in the FileDialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/40674007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Why is it bad practice to ask for full name in a form? In many many forms you see separate inputs for first and last name. I assume that asking for a users full name in one input is bad practice because you cannot rely on simply splitting the string by spaces to get the first and last names. Now I think about it i'm not sure if this would be a problem, can anyone shed any light on whether this is good or bad practice and if it is bad to ask for full name in a single input, why is it bad. Thanks A: As soon as you need to address a customer by Last Name, First Name you're screwed. Sorting becomes a problem, etc. It's very little extra effort to ask for each separately even if you don't think it's useful now. But to go back and do it is very problematic. Data atomization is important.
{ "language": "en", "url": "https://stackoverflow.com/questions/45045018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Best way to add base class values to derived class? I have a reference file (dll) containing a class, which i use as my base class: public class Group { public Group(); public int Id { get; set; } public int League_Id { get; set; } public string Name { get; set; } public string Nationality { get; set; } } (Please note that the Group class contains about 30 entities, i have only displayed some) Since i use Entity Framework the ID needs to be unique. i get this data from a API call and noticed that the ID is not unique, i have added my own class. public class modGroup : APICall.Group { public modGroup() { modID = 0; } [Key] public int modID { get; set; } } This setup works, EF is creating the database. What i'd like to do is get the data from the API (Which is structured as the Group class), create a new modGroup() and set all data from the API call, without referencing each individual object. What i would like to do is transfer data without setting each individual entity. List<APICall.Group> groupData= _ApiRequester.GetGroup(); using (var a = new databaseModel()) { foreach (APICall.Group x in groupData) { var modGroup = new Models.modGroup(); modGroup.modID = 0; // fill modgroup with rest of variables without doing: // modGroup.League_iD = a.League_iD; // modGroup.Name = a.Name; // etc } } A: I would use Automapper to map the two classes together in one call. This type of situation is what it was designed for. All you would need to do is create a mapping configuration and then map the two classes. It's a very simple but powerful tool. e.g. Something like this: var config = new MapperConfiguration(cfg => cfg.CreateMap<APICall.Group, modGroup>() .ForMember(dest => dest.modID, s=>s.MapFrom(s=>s.Id)); // etc create more mappings here ); var mapper = config.CreateMapper(); List<modGroup> modGroupList = mapper.Map<List<modGroup>>(groupData);
{ "language": "en", "url": "https://stackoverflow.com/questions/36132679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to compile this project into ARM architecture for iOS I am using this project as a library to develop iOS programs: http://github.com/chili-epfl/chilitags After compiling this project by CMake, the architecture of this file is x86. However, iPhone requires ARM architecture and this library cannot be run in real devices. I know I need to modify this project's CMake files into cross-compiling but I have no idea how to do it. I know I should use CMAKE_TOOLCHAIN_FILE and something like that but there is no good tutorial when I search. So, how to cross compile this project into ARM architecture? Please be specific. Thanks in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/47159110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android emulator no toolbar I'm using Android Studio 2.2.2 but whenever I launch an emulator there's no toolbar and I can't resize it. I want to be able to resize and show the toolbar like the image below: How do I do this? A: I think it is a unexpected problem, try new device to fix . But you can set scale type with 'AUTO' in emulator profile setting. you can drag border of emulator to scale it.
{ "language": "en", "url": "https://stackoverflow.com/questions/40904029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL: list users with their phone numbers and email addresses I want to make a query in PostgreSQL which lists my users and their email addresses and phone numbers (separated by commas), like this: | user1 | [email protected], [email protected] | +3612123123, +3623234234 | The tables are: user - stores the user's data user_email - stores the user's email addresses user_phone - stores the user's phone numbers I tried the obvius: SELECT user.id, user.name ( SELECT array_agg(user_email.email) FROM user_email WHERE user_email.user_id = user.id ) AS EmailAddresses, ( SELECT array_agg(user_phone.phone) FROM user_phone WHERE user_phone.user_id = user.id ) AS PhoneNumbers FROM user ORDER BY user.id But this lead to ridiculous query times (34sec). Than I tried: SELECT user.id, user.name, array_agg(user_email.email), array_agg(user_phone.phone) FROM user LEFT JOIN user_email ON user_email.user_id = user.id LEFT JOIN user_phone ON user_phone.user_id = user.id GROUP BY user.id ORDER BY user.id This results very good query times (around 100ms). But this way it's lists every combination of phone numbers and email addresses. So if I have 3 email address and 3 phone number, then it lists 9 email address (triples every single address) and 9 phone numbers too. Is there an efficient way to do what I want? A: DISTINCT can be used within aggregate expressions too: SELECT "user".id, name, array_agg(DISTINCT email) emails, array_agg(DISTINCT phone) phones FROM "user" LEFT JOIN user_email ON user_email.user_id = "user".id LEFT JOIN user_phone ON user_phone.user_id = "user".id GROUP BY "user".id ORDER BY "user".id; Note: if you only need comma separated lists, you may want to use string_agg() instead of array_agg(). SQLFiddle A: Either DISTINCT SELECT DISTINCT user.id, user.name, array_agg(user_email.email), array_agg(user_phone.phone) FROM user LEFT JOIN user_email ON user_email.user_id = user.id LEFT JOIN user_phone ON user_phone.user_id = user.id GROUP BY user.id ORDER BY user.id Or INNER Joins SELECT user.id, user.name, array_agg(user_email.email), array_agg(user_phone.phone) FROM user INNER JOIN user_email ON user_email.user_id = user.id INNER JOIN user_phone ON user_phone.user_id = user.id GROUP BY user.id ORDER BY user.id Or both SELECT DISTINCT user.id, user.name, array_agg(user_email.email), array_agg(user_phone.phone) FROM user INNER JOIN user_email ON user_email.user_id = user.id INNER JOIN user_phone ON user_phone.user_id = user.id GROUP BY user.id ORDER BY user.id
{ "language": "en", "url": "https://stackoverflow.com/questions/27859644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Process finished with exit code 133 (interrupted by signal 5: SIGTRAP) When I tried to run the last line of the code block, the IDE returns Process finished with exit code 133 (interrupted by signal 5: SIGTRAP). Any idea? When I tried to load library(dplyr), it gives me the same error. A: In case you installed R through home-brew. This seems to be a known issue. youtrack. I faced the same thing. Using the install from their website resolved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/74325059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DJANGO, NGINX and WINDOWS SERVER I have deployed a django application using nginx. These are the nginx configurations I configured. **c:/nginx/sites-available/project_nginx.conf & c:/nginx/sites-enabled/project_nginx.conf ** server { listen 80; server_name 192.168.xxx.xx; location /static { alias D:/project/apps/media; } location /media/ { alias D:/project/apps/media; } location / { proxy_pass http://localhost:8000; } } **c:/nginx/conf/nginx.conf ** events { worker_connections 1024; } http { include. mime.types; default_type application/octet-stream; include C:/nginx/conf/sites-enabled/project_nginx.conf ... I have successfully deployed it and it is running without any problem on the server but, NB: The server is a windows server the problem is that, I cannot access the software on other PCs which are on the same network. What is a possible solution to this problem? I need the application to be accessible with other PCs on the intranet.
{ "language": "en", "url": "https://stackoverflow.com/questions/75590917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to add support for HLS in desktop Chrome/HTML5 player? Desktop Chrome and FF do not support HLS. I know there is a plugin available to add HLS support to flash. Is there such plugin or technique available to enhance HTML5 on browsers which dont have HLS support yet? A: Not only it is possible, but it's been done numerous times. There are several open and closed source solutions available. A quick github search gave me this one. https://github.com/RReverser/mpegts EDIT: New/better option just released http://engineering.dailymotion.com/introducing-hls-js/
{ "language": "en", "url": "https://stackoverflow.com/questions/32289662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Jquery International Telephone number input I am trying to follow jquery tutorial on http://www.jqueryscript.net/form/jQuery-International-Telephone-Input-With-Flags-Dial-Codes.html to create input type number with country code in a form. However, in my case though flag is appearing to change, the country code is not added inside the input field as they show in the demo. Following is the code they have provided: <head> <meta charset="utf-8"> <title>International Telephone Input</title> <link rel="stylesheet" href="build/css/intlTelInput.css"> <link rel="stylesheet" href="build/css/demo.css"> </head> <body> <form> <input id="mobile-number" type="tel"> <button type="submit">Submit</button> </form> <!-- Load jQuery from CDN so can run demo immediately --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="build/js/intlTelInput.js"></script> <script> $("#mobile-number").intlTelInput({ //allowExtensions: true, //autoFormat: false, //autoHideDialCode: false, //autoPlaceholder: false, //defaultCountry: "auto", //ipinfoToken: "yolo", //nationalMode: false, //numberType: "MOBILE", //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'], //preferredCountries: ['cn', 'jp'], //preventInvalidNumbers: true, utilsScript: "lib/libphonenumber/build/utils.js" }); </script> Here is the link where I am trying to implement it: https://www.easyaccom.com/mobile/verifynumber.html I have tried changing the commented out options in script but it doesn't help. A: Ok I solved this problem. So basically here are the option fields that must be true and we need to place the below script before </head> tag. Script: <script> $(function() { $("#mobile-number").intlTelInput({ allowExtensions: true, autoFormat: false, autoHideDialCode: false, autoPlaceholder: false, defaultCountry: "auto", ipinfoToken: "yolo", nationalMode: false, numberType: "MOBILE", //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'], //preferredCountries: ['cn', 'jp'], preventInvalidNumbers: true, utilsScript: "lib/libphonenumber/build/utils.js" }); }); </script> Place it before closing head tag and remember to call $("#mobile-number").intlTelInput(); as it is important. A: You just forget to put your jquery code inside de document.ready. see below: $(document).ready(function(){ $("#mobile-number").intlTelInput({ //allowExtensions: true, //autoFormat: false, //autoHideDialCode: false, //autoPlaceholder: false, //defaultCountry: "auto", //ipinfoToken: "yolo", //nationalMode: false, //numberType: "MOBILE", //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'], //preferredCountries: ['cn', 'jp'], //preventInvalidNumbers: true, utilsScript: "lib/libphonenumber/build/utils.js" }); }); A: Country code will always be in input field with this code $("#mobile-number").on("blur keyup change", function() { if($(this).val() == '') { var getCode = $("#mobile-number").intlTelInput('getSelectedCountryData').dialCode; $(this).val('+'+getCode); }}); $(document).on("click",".country",function(){ if($("#phone").val() == '') { var getCode = $("#mobile-number").intlTelInput('getSelectedCountryData').dialCode; $("#mobile-number").val('+'+getCode); }}); A: $(function() { $("#mobile-number").intlTelInput({ autoHideDialCode: false, autoPlaceholder: false, nationalMode: false }); }); A: Why country flag and country code are not stable on page post back. Here is what I have tried so far: <script> $(document).ready(function () { $("#Phone").intlTelInput({ allowDropdown: true, // autoHideDialCode: false, // autoPlaceholder: "off", // dropdownContainer: "body", // excludeCountries: ["us"], defaultCountry: "auto", // formatOnDisplay: false, //geoIpLookup: function (callback) { // $.get("http://ipinfo.io", function () { }, "jsonp").always(function (resp) { // var countryCode = (resp && resp.country) ? resp.country : ""; // callback(countryCode); // }); //}, //initialCountry: "auto", // nationalMode: false, // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'], // placeholderNumberType: "MOBILE", // preferredCountries: ['in','pk', 'np','bd', 'us','bt','sg','lk','ny','jp','hk','cn'], // separateDialCode: true, utilsScript: "build/js/utils.js" }); $("#Phone").on("countrychange", function (e, countryData) { $("#hdnPhone").val(countryData.dialCode); }); }); </script> <script> $(document).ready(function () { $("#Phone").val(''); var HdnVal = $("#hdnPhone").val(); if (HdnVal != '') { var countryData = $("#Phone").intlTelInput("getSelectedCountryData"); $("#hdnPhone").val(countryData.dialCode); } }); </script> A: try this code $("#mobile-number").intlTelInput({ // allowExtensions: true, //autoFormat: false, autoHideDialCode: false, // autoPlaceholder: false, // defaultCountry: "auto", //ipinfoToken: "yolo", nationalMode: false, // numberType: "MOBILE", // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'], //preferredCountries: ['cn', 'jp'], //preventInvalidNumbers: true, utilsScript: "lib/libphonenumber/build/utils.js" }); }); A: //if you want to get coutry code value in input box then set false nationalMode: false, separateDialCode: false, Pease set this two lines in your function property it will run
{ "language": "en", "url": "https://stackoverflow.com/questions/28882944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Flickr: How to use flickr.photos.geo.getLocation in python or any language? I used the following code to get Latitude and Longitude in python in pycharm environment as import flickr api_key = u'xxxxx' secret_api_key = u'xxxxxx' photoID=8636126004 for photo in flickr.photos.geo.getLocation(api_key=api_key,photo_id=photoID,extras="geo"): print (photo.attrib['id']) print (photo.attrib['latitude']) print (photo.attrib['longitude']) But I get the below error as for photo in flickr.geo.getLocation(api_key=api_key,photo_id=photoID, extras="geo"): AttributeError: module 'flickr' has no attribute 'photos' Guide me to resolve this error and to get Latitude and Longitude in python. If the suggestion maybe in java or php etc. also helps me. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/54994378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic sorting with nullable column I am writing dynamic sorting with lambda expression as below: string sortColumn = imageFilterType == 1 ? "CreatedDate" : "AbuseCount"; var paramExp = Expression.Parameter(typeof(Items), typeof(Items).ToString()); Expression propConvExp = Expression.Convert(Expression.Property(paramExp, sortColumn), typeof(object)); var sortExp = Expression.Lambda<Func<Items, object>>(propConvExp, paramExp); Above I am creating dynamic sort column and I am applying this sortexpression in bellow query: var items = _db.Items.AsQueryable() .AsExpandable() .OrderByDescending(sortExp) .Where(predicate) .Select(x => x) .Join(_db.Users, i => i.UserId, u => u.UserID, (i, u) => new { i, FullName = u.UserType == 1 ? u.FirstName + " " + u.LastName : u.CompanyName, u.UserType, u.UserName }) .ToList() .Skip(pageIndex) .Take(pageSize); I have 2 columns in input by which I have to sort data one is CreatedDate and another is Abusecount. I have to apply sorting with one column among both of them. but as I am trying to run above code I am getting error: "Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types." Since in my database both column is of nullable type thatswhy I am getting this problem. Is anyone have solution of this problem? I don't want to change in DB. I have to solve it from fron end only. A: Try this, it's much simplier: var items = _db.Items.AsQueryable() .AsExpandable(); if (imageFilterType == 1) items=items.OrderByDescending(a=>a.CreatedDate); else items=items.OrderByDescending(a=>a.AbuseCount); items=items.Where(predicate) .Select(x => x) .Join(_db.Users, i => i.UserId, u => u.UserID, (i, u) => new { i, FullName = u.UserType == 1 ? u.FirstName + " " + u.LastName : u.CompanyName, u.UserType, u.UserName }) .Skip(pageIndex) .Take(pageSize) .ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/23211213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extremely slow WordPress user import on XAMPP I'm posting this question here because I'm not sure it's a WordPress issue. I'm running XAMPP on my local system, with 512MB max headroom and a 2.5-hour php timeout. I'm importing about 11,000 records into the WordPress wp_user and wp_usermeta tables via a custom script. The only unknown quantity (performance-wise) on the WordPress end is the wp_insert_user and update_user_meta calls. Otherwise it's a straight CSV import. The process to import 11,000 users and create 180,000 usermeta entries took over 2 hours to complete. It was importing about 120 records a minute. That seems awfully slow. Are there known performance issues importing user data into WordPress? A quick Google search was unproductive (for me). Are there settings I should be tweaking beyond the timeout in XAMPP? Is its mySQL implementation notoriously slow? I've read something about virus software dramatically slowing down XAMPP. Is this a myth? A: yes, there are few issues with local vs. hosted. One of the important things to remember is the max_execution time for php script. You may need to reset the timer once a while during the data upload. I suppose you have some loop which takes the data row by row from CSV file for example and uses SQL query to insert it into WP database. I usually put this simple snippet into my loop so it will keep the PHP max_exec_time reset: $counter = 1; // some upload query if (($handle = fopen("some-file.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { mysql_query..... blablabla.... // snippet if($counter == '20') // this count 20 loops and resets the counter { set_time_limit(0); $counter = 0; } $counter = $counter + 1; } //end of the loop .. also BTW 512MB room is not much if the database is big. Count how much resources is taking your OS and all running apps. I have ove 2Gb WO database and my MySql needs a lot of RAM to run fast. (depends on the query you are using as well)
{ "language": "en", "url": "https://stackoverflow.com/questions/11113481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: designing virtual methods I wonder under what circumstances you would choose the first or the second design : First design : the child method have to call the base method public abstract class Base { public virtual void Enable() { IsEnable = true; } public virtual void Disable() { IsEnable = false; } public bool IsEnable { get; private set; } } public class Child : Base { public override void Enable() { /* do stuffs */ base.Enable(); } public override void Disable() { /* do stuffs */ base.Disable(); } } Second design : a virtual method is used to be sure the child do not forget to call the base public abstract class Base { public void Enable() { IsEnable = true; OnEnable(); } public void Disable() { IsEnable = false; OnDisable(); } public bool IsEnable { get; private set; } public virtual void OnEnable() {} public virtual void OnDisable() {} } public class Child : Base { override void OnEnable() { /* do stuffs */ } override void OnDisable() { /* do stuffs */ } } Thanks A: It depends if you really want to make sure IsEnable gets set or not. If you can imagine scenarios in which the user doesn't want to set it, then I suppose you leave it up to them to call the base method. Otherwise, do it for them. A: The second, template-based approach is better in my opinion. It allows you to ensure that some base functionality is always called, and gives you room to add some if none is present at first without the risk of breaking any subclass. A: As soon as you make a method virtual, you are giving a derived class a chance to break your class. A responsible deriver will always ask himself "should I call the base implementation?" Guidance for this should always come from documentation. MSDN uses standard verbiage: Notes to Inheritors: When overriding Xxxxx in a derived class, be sure to call the base class's Xxxx method so that blablah happens. The C# language makes that easy with the "base" keyword. Working from the assumption that this documentation is not available or unclear, your second example would strongly discourage a deriver to call the other base class method. After all, s/he wouldn't use the standard pattern. Use this pattern only if you want to discourage the inheritor from calling a base class method. A: In the first one, where the overring class could prevent Enable from being set, I reckon Enable and Disable could potentially be misleading method names. Something like TryEnable and TryDisable would probably be more accurate implying that there are situations where you cannot enable. A third possible situation could be catered for if you took example 2 and changed it so the base class calls OnEnable before setting the flag: public void Enable() { OnEnable(); // Exceptions raised from here prevent the flag being set. IsEnable = true; } Then overriding classes could prevent the setting of the flag by raising an exception if an error were to occur. Thus error situations would prevent the flag from being changed. Just food for thought.
{ "language": "en", "url": "https://stackoverflow.com/questions/2124934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the need or benefit to use an instance variable/function attribute to implement memoization vs passing down the memo in each call? In a lot of examples of memoization, I see it most commonly that people favor making a wrapper or decorator (or some language-dependent variation of this, such as using a higher-order function to close over a memo object) to store the results of previous function calls in an almost 'state-like' fashion. Such an example can be seen below: class Memoize(object): def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): if args in self.cache: return self.cache[args] ret = self.func(*args) self.cache[args] = ret return ret @Memoize def fib(n): if n < 2: return 1 return fib(n-2) + fib(n-1) What is the difference / tradefoff between doing things this way, vs simply passing down a memo in the arguments of your function? For example, like so: def fib(n, memo = {}): if (n < 2): return 1 if (n in memo): return memo[n] memo[n] = fib(n - 1) + fib(n - 2) return memo[n] A: Separation of concerns: you don't want to muddy your nice clean implementation of fib with all the bookkeeping required to make it more efficient. Let fib compute Fibonacci numbers, and let Memoize worry about memoizing fib (or any other function).
{ "language": "en", "url": "https://stackoverflow.com/questions/49328260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Trigger python script on raspberry pi from a rails application I have a rails application, and when there is an update to one of the rows in my database, I want to run a python script which is on a raspberry pi (example: lights up a LED when a user is created). I'm using PostgreSQL and have looked into NOTIFY/LISTEN channels, but can't quite figure that out. Is there an easy way to do this? The raspberry pi will not be on the same network as the rails application. A: There are many "easy" ways, depending on your skills. Maybe: "Write triggers, which are sending the notify on insert/update" is the hint you need?
{ "language": "en", "url": "https://stackoverflow.com/questions/32170818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Closing/tabbing between windows using Javascript or HTML I have a small query. Is it possible to switch between open windows using HTML or JavaScript, for example; IE open with Intranet. Intranet has a button which when clicked it opens an already running application in this case Citrix Receiver. Basically minimizing the web browser or tabbing across.
{ "language": "en", "url": "https://stackoverflow.com/questions/39727636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error with base logout after extending LogoutListener class My target is to perform a logout from a controller being able to have base logout mechanism correctly performing. After googling and stack-overflowing on some similar questions I have tried to implement an extension of class LogoutListener as suggested in the answer here How to log user out of Symfony 2 application using it's internal handlers I have created the class and I've added the parameter "security.logout_listener.class" in parameters.yml which is imported from config.yml. Exactly my new class is # MyBundle/MyLogoutListener.php namespace MyBundle; use Symfony\Component\Security\Http\Firewall\LogoutListener; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\Request; class MyLogoutListener extends LogoutListener{ /** * Whether this request is asking for logout. * * @param Request $request * * @return Boolean */ protected function requiresLogout(Request $request) { if ($request->hasSession()) if ( $request->getSession->get('logout') ) { return true; } } return parent::requiresLogout($request); } } And the row I've added in parameters.yml is security.logout_listener.class: MyBundle\MyLogoutListener Whit this things I have a well working logout functionality activable in the login of a controller but if I try to use the base logout functionality of Symfony2 I receive this error : Runtime Notice: Declaration of MyBundle\MyLogoutListener::requiresLogout() should be compatible with Symfony\Component\Security\Http\Firewall\LogoutListener::requiresLogout(Symfony\Component\HttpFoundation\Request $request) For base logout functionality I mean the configuration in the firewall with : … logout: path: /logout target: /someaction … Please can somebody explain where is the problem ? Do I need to define a service with MyLogoutListener ?
{ "language": "en", "url": "https://stackoverflow.com/questions/30700770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zend storing data in session I'm new in Zend and php. For a project, i need to gather 3 ajax Zend Forms together. I know i need to use session to do that but i can't find any information about how to do that. Can someone help me ? EDIT : public function formResAction(){ $form = new Front_Form_ResPhone(); $bdd_Reservation = new Front_Model_DbTable_Reservation(); if($this->getRequest()->isPost()){ if($form->isValid($this->getRequest()->getPost())){ // Données non valides $session = new Zend_Session_Namespace('forms'); $formData = $form->getValues(); $session->form1 = $formData; print_r ($session->form1); echo $this->view->bloc11Fid($formData); exit; } else{ // Données non valides // echo "non valide"; } } else{ // Appel en GET // echo "GET"; } echo $form; exit; } public function formFidAction(){ $form = new Front_Form_FidForm(); $bdd_Reservation = new Front_Model_DbTable_Reservation(); if($this->getRequest()->isPost()){ if($form->isValid($this->getRequest()->getPost())){ // Données non valides $session = new Zend_Session_Namespace('forms'); $formData = $form->getValues(); $session->form2 = $formData; print_r ($session->form2); echo $this->view->bloc11Fid2($formData); exit; } else{ // Données non valides // echo "non valide"; } } else{ // Appel en GET // echo "GET"; } echo $form; exit; } public function formFid2Action(){ $form = new Front_Form_FidForm2(); $bdd_Reservation = new Front_Model_DbTable_Reservation(); if($this->getRequest()->isPost()){ if($form->isValid($this->getRequest()->getPost())){ // Données non valides $session = new Zend_Session_Namespace('forms'); $formData = $form->getValues(); $session->form3 = $formData; print_r ($session->form3); echo $this->view->bloc11Res($formData); exit; } else{ // Données non valides // echo "non valide"; } } else{ // Appel en GET // echo "GET"; } echo $form; exit; } public function resFormAction(){ $form = new Front_Form_ResForm(); $bdd_Reservation = new Front_Model_DbTable_Reservation(); if($this->getRequest()->isPost()){ if($form->isValid($this->getRequest()->getPost())){ // Données non valides $session = new Zend_Session_Namespace('forms'); $formData = $form->getValues(); $session->form4 = $formData; print_r ($session); $bdd_Reservation->insert($forms); echo $this->view->bloc11Fel($formData); exit; exit; } else{ // Données non valides // echo "non valide"; } } else{ // Appel en GET // echo "GET"; } echo $form; exit; } A: Check this: //create a session namespace $session = new Zend_Session_Namespace('myapp'); $session->somevar = 'somevalue'; echo $session->somevar; //somevalue Zend_Session_Namespace has magic getter and setter. So, if a attribute of the session object is not set, it will be NULL by default. http://framework.zend.com/manual/1.12/en/zend.session.basic_usage.html
{ "language": "en", "url": "https://stackoverflow.com/questions/23611355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Directx Texture interface to existing memory I'm writing a rendering app that communicates with an image processor as a sort of virtual camera, and I'm trying to figure out the fastest way to write the texture data from one process to the awaiting image buffer in the other. Theoretically I think it should be possible with 1 DirectX copy from VRAM directly to the area of memory I want it in, but I can't figure out how to specify a region of memory for a texture to occupy, and thus must perform an additional memcpy. DX9 or DX11 solutions would be welcome. So far, the docs here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb174363(v=vs.85).aspx have held the most promise. "In Windows Vista CreateTexture can create a texture from a system memory pointer allowing the application more flexibility over the use, allocation and deletion of the system memory" I'm running on Windows 7 with the June 2010 Directx SDK, However, whenever I try and use the function in the way it specifies, I the function fails with an invalid arguments error code. Here is the call I tried as a test: static char s_TextureBuffer[640*480*4]; //larger than needed void* p = (void*)s_TextureBuffer; HRESULT res = g_D3D9Device->CreateTexture(640,480,1,0, D3DFORMAT::D3DFMT_L8, D3DPOOL::D3DPOOL_SYSTEMMEM, &g_ReadTexture, (void**)p); I tried with several different texture formats, but with no luck. I've begun looking into DX11 solutions, it's going slowly since I'm used to DX9. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/15375692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python detect 'key up' event from the terminal I'm trying to write a python program to emulate a musical instrument. While the button is pressed down the note plays, when you take your finger off the button the sound automatically stops: while buttonUp: noteSilent() if buttonDown: notePlay() From what I understand the two main ways of doing this are with pygame and through curses. Pygame seems simpler but it seems to be aimed at making graphical apps whereas I'm quite content running this program purely from the command line. I've been trying to get it to work with curses but it's not really having the desired effect. This is what I currently have: while key != ord('q'): key = stdscr.getch() curses.echo() stdscr.addch(20, 25, key) stdscr.refresh() NoteSilent(2) if key == ord('a'): print "hello" NotePlay(2) This doesn't seem to have the desired effect and so any advice on how to tackle this would be much appreciated. A: curses doesn't provide separate events for key presses and releases, so you'd probably be better off with pygame if you want it to work that way. (Weird quasi-exception: ncurses and PDCurses can provide separate press and release events for mouse buttons, if you wanted to go that way. This isn't quite standard curses, and I don't know if the Python interface supports it.)
{ "language": "en", "url": "https://stackoverflow.com/questions/43187643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ol3 geometryFunction interaction.Draw add GPS point In a project i'm developing we are using the ol.interaction.Draw functionality to draw geometry. The geometryFunction we are using to add a GPS point to the geometry (linestring or polygon). This is accomplished by setting a boolean to add this GPS point. This boolean is set by a button some were in the HTML. Al works well but the sketch isn't updated untill we move the cursor over the map again. Is there a way to trigger the geometryFunction without moving the cursor over the map? // Interaction $scope.interactions.draw = new ol.interaction.Draw({ source: $scope.vector.getSource(), type: (function () { var type = 'Point'; if ($scope.layer.TypeName == 'LineStyle') type = 'LineString'; if ($scope.layer.TypeName == 'PolygonStyle') type = 'Polygon'; return type; })(), geometryFunction: function (coordinates, geometry) { if (!_.isUndefined(geometry)) { // Is move to GPS position selected? if ($scope.moveToGpsPosition_) { // GPS position var pos = _geolocation.geolocation.getPosition(); // Line if ($scope.layer.TypeName == 'LineStyle') coordinates.splice(coordinates.length - 1, 0, pos); // Polygon if ($scope.layer.TypeName == 'PolygonStyle') coordinates[0].splice(coordinates.length - 2, 0, pos); // Stop move to GPS position $scope.moveToGpsPosition_ = false; } geometry.setCoordinates(coordinates); } else { // Detect geometry type if ($scope.layer.TypeName == 'PointStyle') geometry = new ol.geom.Point(coordinates); if ($scope.layer.TypeName == 'LineStyle') geometry = new ol.geom.LineString(coordinates); if ($scope.layer.TypeName == 'PolygonStyle') geometry = new ol.geom.Polygon(coordinates); } return geometry; } }); A: I'm having a difficult time replicating your problem but I suspect you can solve it by added one of the following after your geometry.setCoordinates(coordinates); line: map.updateSize(); or map.render();
{ "language": "en", "url": "https://stackoverflow.com/questions/43871651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: tomcat to send SSL client certificate I am trying to do a https rest API call with a SSL certificate(PFX file) which have a password. I tested the connection from my desktop with SOAP UI and it is working fine. I have a web application which is running on tomcat and I need my tomcat to send this certificate for all the http/https call which it will make. I am not a tomcat person so i am stuck with this now. I can find in online about how to set up a keystore & server.xml so that my web app can use Client Authentication against things connecting to it, not for when it needs to connect out to some other server(outgoing call). my tomcat version is : 9.0.22 connector settings on my server.xml file
{ "language": "en", "url": "https://stackoverflow.com/questions/64837270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error messages on Java code that has me make 2 calculator objects and perform operations on them Here's the main Java file: class Main { public static void main(String[] args) { Calculator One = new Calculator(100,50,"Addition"); One.calculateNums(); One.showResults(); Calculator Two = new Calculator(100,50,"Subtraction"); Two.changeNumOne("200"); Two.calculateNums(); Two.showResults(); } } And here's the calculator java code: public class Calculator { // instance variables - first number, second number, operation private int firstNum; private int secondNum; private String operation; // static field to keep track of number of Calculator objects public static int Calculatorobjects = 0; // default constructor public Calculator(){ int firstNum = 0; int secondNum = 0; operation = "Addition"; } // initializing constructor public Calculator(int firstNum, int secondNum, int NumOperation){ NumOne = firstNum; NumTwo = secondNum; NumOperation = operation; } // getters for all 3 instance variables public int one(){ return firstNum; } public int two(){ return secondNum; } public String three(){ return operation; } // setters to be able to change any of the 3 instance variables after creating them public void changeNumOne(int NewNumOne){ firstNum = NewNumOne; } public void changeNumOne(int NewNumTwo){ SecondNum = NewNumTwo; } public void changeNumOne(String NewNumOperation){ operation = NewNumOperation; } // instance method to perform operation public void calculateNums(int result){ if(operation == "Addition"){ result = firstNum + secondNum; } if(operation == "Subtraction"){ result = firstNum - secondNum; } } // instance method to display results public void showResults(){ System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result); } } I'm getting the following error messages: exit status 1 Calculator.java:35: error: method changeNumOne(int) is already defined in class Calculator public void changeNumOne(int NewNumTwo){ ^ Calculator.java:36: error: cannot find symbol SecondNum = NewNumTwo; ^ symbol: variable SecondNum location: class Calculator Calculator.java:52: error: cannot find symbol System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result); ^ symbol: variable result location: class Calculator Main.java:4: error: method calculateNums in class Calculator cannot be applied to given types; One.calculateNums(); ^ required: int found: no arguments reason: actual and formal argument lists differ in length Main.java:8: error: method calculateNums in class Calculator cannot be applied to given types; Two.calculateNums(); ^ required: int found: no arguments reason: actual and formal argument lists differ in length 5 errors I've tried a bunch of random things while trying to fix it and all of them have either done nothing or made even more errors. I'm an amateur at Java so I definitely did a lot of things wrong but if someone could point them out and send the right code that would be great. A: 1.) At least you need to fix: public void changeNumOne(int NewNumOne){ firstNum = NewNumOne; } // Error: Same name as above public void changeNumOne(int NewNumTwo){ // Error: Capital SecondName SecondNum = NewNumTwo; } To: public void changeNumOne(int firstNum){ this.firstNum = firstNum; } public void changeNumTwo(int secondNum){ this.secondNum = secondNum; } 2.) And here you would like to print result, but your class does not have such a variable (also check, if your function calculateNums makes sense): public void showResults(){ System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result); } 3.) This should also fail: public Calculator(int firstNum, int secondNum, int NumOperation){ NumOne = firstNum; NumTwo = secondNum; NumOperation = operation; } Should be: public Calculator(int firstNum, int secondNum, string operation){ this.firstNum = firstNum; this.secondNum = secondNum; this.operation = operation; } 4.) Here you do not assign the values: public Calculator(){ int firstNum = 0; int secondNum = 0; operation = "Addition"; } Should be: public Calculator(){ this.firstNum = 0; this.secondNum = 0; this.operation = "Addition"; } Overall: There might be other errors. You need to check all your variables names. They are quite inconsistent. Though, read your error messages carefully and try to understand them for the future. A: There are many errors. I solved with this code, acting with Calculator class. I commented on the code where there were errors. class Calculator { // instance variables - first number, second number, operation private int firstNum; private int secondNum; private int result; //I declare the result variable so I can print it private String operation; // static field to keep track of number of Calculator objects public static int Calculatorobjects = 0; // default constructor public Calculator(){ this.firstNum = 0; //useless because uninitialized int are already 0 this.secondNum = 0; //same this.operation = "Addition"; } // initializing constructor public Calculator(int firstNum, int secondNum, String NumOperation){ //NumOperation is a String, not an int this.firstNum = firstNum; //I'm setting the global variables as the local variables that you pass to the constructor this.secondNum = secondNum; this.operation = NumOperation; } // getters for all 3 instance variables public int one(){ return firstNum; } public int two(){ return secondNum; } public String three(){ return operation; } // setters to be able to change any of the 3 instance variables after creating them public void changeNumOne(int NewNumOne){ firstNum = NewNumOne; } public void changeNumTwo(int NewNumTwo){. //changed method name secondNum = NewNumTwo; } public void changeNumOne(String NewNumOperation){ operation = NewNumOperation; } // instance method to perform operation public void calculateNums(){ if(operation.equals("Addition")){ //equals is used to compare strings result = firstNum + secondNum; } if(operation.equals("Subtraction")){ result = firstNum - secondNum; } } // instance method to display results public void showResults(){ System.out.println(firstNum + " " + operation + " " + secondNum + " = " + result); }
{ "language": "en", "url": "https://stackoverflow.com/questions/64739036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Navigation Bar Title Font Size I need to change the size of the Navigation Bar title text for one view controller in my iPhone app. I'm using iOS5, and tried the following code: if ([self.tabBarItem respondsToSelector:@selector(setTitleTextAttributes:)]) { NSLog(@"*** Support method(iOS 5): setTitleTextAttributes:"); [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, [UIColor blackColor], UITextAttributeTextColor, [UIColor grayColor], UITextAttributeTextShadowColor, [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)], UITextAttributeTextShadowOffset, nil]]; } However this only applies to the tabBarItem. A: Swift 2.0: func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName: UIFont(name: "DINNextLTW04-Regular", size: 20)! ] return true } Or override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = false self.title = "SAMPLE" //Set Color let attributes: AnyObject = [ NSForegroundColorAttributeName: UIColor.redColor()] self.navigationController!.navigationBar.titleTextAttributes = attributes as? [String : AnyObject] //Set Font Size self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Arial", size: 37.0)!]; } A: You got it already,but you can also use following attributes methods. For Color, NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor RedColor],UITextAttributeTextColor, nil]; self.navigationController.navigationBar.titleTextAttributes = attributes; For Size, NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],UITextAttributeFont, nil]; self.navigationController.navigationBar.titleTextAttributes = size; Thanks. For iOS 7 and above For Size: NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],NSFontAttributeName, nil]; self.navigationController.navigationBar.titleTextAttributes = size; A: You need to grab the navigation bar property and the use @property(nonatomic, copy) NSDictionary *titleTextAttributes. For further info see UINavigationBar Class Reference and Customizing UINavigationBar section. To understand better your question: What type of controller do you have? EDIT [self.navigationController.navigationBar setTitleTextAttributes:...]; if you access the navigationController within a pushed controller. [navigationController.navigationBar setTitleTextAttributes:...]; if navigationController is your current UINavigationController. This could be used when for example if you have the following code: UINavigationController* navigationController = ...; [navigationController.navigationBar setTitleTextAttributes:...]; A: Since iOS7, I always do like following: [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica-Bold" size:18.0],NSFontAttributeName, nil]]; The Keyword UITextAttributeFont has been depressed from iOS7, you'd supposed to replace with NSFontAttributeName. You can use [self.navigationController.navigationBar setTitleTextAttributes:]to set someone navigationController's appearence, while [UINavigationBar appearance] setTitleTextAttributes:] works for your whole App directly.(Of course you need to put it in a property position.) A: My example guard let sansLightFont = UIFont(name: "OpenSans", size: 20) else { return } navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : sansLightFont]
{ "language": "en", "url": "https://stackoverflow.com/questions/9621455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Set of bytes, what are the values of a and b program Project1; var a,b:set of byte; c:set of byte; i:integer; begin a:=[3]; b:=[2]; c:=(a+b)*(a-b); FOR i:= 0 TO 5 DO IF i IN c THEN write(i:2); readln; end. Can someone please explain to me what is going on in this code. I know that c=3 but dont understand how, what are the values of a and b ? Tried writeln(a,b); but gives me an error ... A: Ok, I'll explain what you probably could find out by debugging, or by simply reading a textbook on Pascal as well: The line: c := (a+b)*(a-b); does the following: a + b is the union of the two sets, i.e. all elements that are in a or in b or in both, so here, that is [2, 3]; a - b is the difference of the two sets, i.e. it is a minus the elements of a that happen to be in b too. In this case, no common elements to be removed, so the result is the same as a, i.e. [3] x * y is the intersection of the two sets, i.e. elements that are in x as well as in y (i.e. a set with the elements both have in common). Say, x := a + b; y := a - b;, then it can be disected as: x := a + b; // [3] + [2] --> [2, 3] y := a - b; // [3] - [2] --> [3] c := x * y; // [2, 3] * [3] --> [3]
{ "language": "en", "url": "https://stackoverflow.com/questions/48272735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Silverstripe migration, index and other pages not found. Why? I recently migrated a silverstripe website from a server with apache2 to a new server with nginx. I followed these instructions: http://doc.silverstripe.org/framework/en/installation/nginx . I am using php5-fpm with tcp port (127.0.0.1:9000). The problem is that i am facing "file not found." as soon as i try to reach the website from the browser. I would appreciate any help. Thanks. A: * *Which SilverStripe version? *Is there anything in the logs (both nginx and PHP)? My slightly tuned nginx configuration for SilverStripe 3 looks like this: https://gist.github.com/xeraa/eab6bc9914e4b75009b8 — this might get you started
{ "language": "en", "url": "https://stackoverflow.com/questions/27178291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running Code View (assembly debugger) on Win7 x64 I am using Win7 x64. In my class, we use Win XP x32 and write program in standard MS-DOS editor, and debug our programs with Code View. But my problem is that I can't set it up home, because I can't run Code View on x64. I two solutions. One is to change my OS to winXP x32 or install Virtual Machine and use winXP x32 on it. Is there maybe some other emulator/program that can do same as Code View ? any good tutorials about that? A: Late answer but hopefully someone will find it useful. One way to run it is to download DOSBox, it is an emulator of old-timer DOS. Since you are mentioning Code View, I am guessing that you are using MASM as well so short instructions how to run it would be as follows: * *Run DOSBox *In the console, write something like 'mount D C:/masm' where 'masm' is a folder where you have stored your compiler and Code View (cv.exe) *Next is command 'D:' which will make you inside your 'masm' folder *Compile it - 'masm myfile.asm' *Link it - 'link myfile' *Finally, debug in the Code View 'cv myfile.exe'
{ "language": "en", "url": "https://stackoverflow.com/questions/13534957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA refresh form I have a simple progress bar. I want to fill it when I make iteration through my loop, but I only see my form with 0 and 100 progress value, so it doesn't refresh during the loop. How can I achieve the runtime refreshment? Thank you! Sub test() UserForm1.Show (False) DoEvents For i = 1 To 700 For j = 1 To 5000 UserForm1.Label1.Caption = 100 * i / 700 & "% Completed" UserForm1.Bar.Width = 200 * i / 700 '200 - width of the bar Next j Next i End Sub A: You just have the DoEvents in the wrong place. Try it like this. Sub test() UserForm1.Show vbModeless For i = 1 To 700 For j = 1 To 5000 UserForm1.Label1.Caption = 100 * i / 700 & "% Completed" UserForm1.Bar.Width = 200 * i / 700 '200 - width of the bar DoEvents Next Next End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/62574964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are we seeing parquet write errors after switching to EMRFS consistent view? we have a large ETL process running on an EMR cluster that reads and writes large number of parquet files to into S3 buckets Here is the code: a = spark.read.parquet(path1) a.registerTempTable('a') b = spark.read.parquet(path2) b.registerTempTable('b') c = spark.read.parquet(path3) c.registerTempTable('c') sql = ''' select a.col1, a.col2, b.col1, b.col2, c.col1, c.col2, a.dt from a join b on a.dt = b.dt join c on a.dt = c.dt '''' df_out = spark.sql(sql) df_out.repartition('dt').write.parquet( path_out, partitionBy='dt', mode='overwrite') We recently had to switch to transient clusters and thus had to start using consistent view. I am positing our ERMFS site setup below: { "fs.s3.enableServerSideEncryption": "true", "fs.s3.consistent": "false", "fs.s3.consistent.retryPeriodSeconds": "10", "fs.s3.serverSideEncryption.kms.keyId": "xxxxxx", "fs.s3.consistent.retryCount": "5", "fs.s3.consistent.metadata.tableName": "xxxxx", "fs.s3.consistent.throwExceptionOnInconsistency": "true" } Running the same code wit the same spark configuration - that works on the permanent cluster - on the transient cluster with consistent view enabled results in an error. ... 19/02/25 23:01:23 DEBUG S3NativeFileSystem: getFileStatus could not find key 'xxxxxREDACTEDxxxx' 19/02/25 23:01:23 DEBUG S3NativeFileSystem: Delete called for 'xxxxxREDACTEDxxxx' but file does not exist, so returning false 19/02/25 23:01:23 DEBUG DFSClient: DFSClient writeChunk allocating new packet seqno=465, src=/var/log/spark/apps/application_1551126537652_0003.inprogress, packetSize=65016, chunksPerPacket=126, bytesCurBlock=25074688 19/02/25 23:01:23 DEBUG DFSClient: DFSClient flush(): bytesCurBlock=25081892 lastFlushOffset=25075161 createNewBlock=false 19/02/25 23:01:23 DEBUG DFSClient: Queued packet 465 19/02/25 23:01:23 DEBUG DFSClient: Waiting for ack for: 465 19/02/25 23:01:23 DEBUG DFSClient: DataStreamer block BP-75703405-10.13.32.237-1551126523840:blk_1073741876_1052 sending packet packet seqno: 465 offsetInBlock: 25074688 lastPacketInBlock: false lastByteOffsetInBlock: 25081892 19/02/25 23:01:23 DEBUG DFSClient: DFSClient seqno: 465 reply: SUCCESS downstreamAckTimeNanos: 0 flag: 0 Traceback (most recent call last): File "xxxxxREDACTEDxxxx", line 112, in <module> main() File "xxxxxREDACTEDxxxx", line xxxxxREDACTEDxxxx, in main xxxxxREDACTEDxxxx File "xxxxxREDACTEDxxxx", line 70, in main partitionBy='dt', mode='overwrite') File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py", line 691, in parquet File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__ File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 63, in deco File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o232.parquet. : org.apache.spark.SparkException: Job aborted. at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply$mcV$sp(FileFormatWriter.scala:215) at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:173) at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:173) at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65) at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:173) I suspect that the error is due to the setup of EMRFS but I was not able to find any EMRFS setting that would work. The only thing that results in this error not being thrown while I am running the code above is increasing the number of node to double the normal number. The error also isn't thrown if I decrease the amount of data. Changing the output commuter and spark speculation does not help either. Thanks a lot. I will be great full for any ideas / suggestions. A: "fs.s3.consistent": "false" should be true for emrfs consistent view to work
{ "language": "en", "url": "https://stackoverflow.com/questions/54887932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Shidoku solver matlab code I'm trying to write a Shidoku ( smaller and easier 4x4 variant of Sudoku) solver code in MATLAB. I have found some soduko solver (9x9) but i could't revise them to be suitable for my problem. For example: % Solving Sudoku Using Recursive Backtracking function X = sudoku(X) % SUDOKU Solve Sudoku using recursive backtracking. % sudoku(X), expects a 9-by-9 array X. % Fill in all “singletons”. % C is a cell array of candidate vectors for each cell. % s is the first cell, if any, with one candidate. % e is the first cell, if any, with no candidates. [C,s,e] = candidates(X); while ~isempty(s) && isempty(e) X(s) = C{s}; [C,s,e] = candidates(X); end % Return for impossible puzzles. if ~isempty(e) return end % Recursive backtracking. if any(X(:) == 0) Y = X; z = find(X(:) == 0,1); % The first unfilled cell. for r = [C{z}] % Iterate over candidates. X = Y; X(z) = r; % Insert a tentative value. X = sudoku(X); % Recursive call. if all(X(:) > 0) % Found a solution. return end end end % ------------------------------ function [C,s,e] = candidates(X) C = cell(9,9); tri = @(k) 3*ceil(k/3-1) + (1:3); for j = 1:9 for i = 1:9 if X(i,j)==0 z = 1:9; z(nonzeros(X(i,:))) = 0; z(nonzeros(X(:,j))) = 0; z(nonzeros(X(tri(i),tri(j)))) = 0; C{i,j} = nonzeros(z)'; end end end L = cellfun(@length,C); % Number of candidates. s = find(X==0 & L==1,1); e = find(X==0 & L==0,1); end % candidates end % sudoku Any help will be helpful. A: Just reduce the problem dimensionality from 3 to 2 (I know now that it is said "9x9" instead of "3x3", but the important dimensional number for the puzzle is N=3): % SHIDOKU Solve Shidoku using recursive backtracking. % shidoku(X), expects a 4-by-4 array X. function X = shidoku(X) [C,s,e] = candidates(X); while ~isempty(s) && isempty(e) X(s) = C{s}; [C,s,e] = candidates(X); end; if ~isempty(e) return end; if any(X(:) == 0) Y = X; z = find(X(:) == 0,1); for r = [C{z}] X = Y; X(z) = r; X = shidoku(X); if all(X(:) > 0) return; end; end; end; % ------------------------------ function [C,s,e] = candidates(X) C = cell(4,4); bi = @(k) 2*ceil(k/2-1) + (1:2); for j = 1:4 for i = 1:4 if X(i,j)==0 z = 1:4; z(nonzeros(X(i,:))) = 0; z(nonzeros(X(:,j))) = 0; z(nonzeros(X(bi(i),bi(j)))) = 0; C{i,j} = transpose(nonzeros(z)); end; end; end; L = cellfun(@length,C); % Number of candidates. s = find(X==0 & L==1,1); e = find(X==0 & L==0,1); end % candidates end % shidoku
{ "language": "en", "url": "https://stackoverflow.com/questions/24016968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: printing a div using jQuery How do I just print the article on my web page using jQuery, article is inside a div window.print() will print the entire window. So little confused with that...! A: Don't use jQuery ... use css and media=print. Here is an article for reference, and here. Basically, create a new stylesheet for what you want to show when you print, and set the media to print: <link rel="stylesheet" type"text/css" href="print.css" media="print"> A: You could probably put the content in an iframe and call print() on that window. A quick google gave me http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=449 which mentions you must focus() before you print(). Note that that page is a few years old. Also see How do I print an IFrame from javascript in Safari/Chrome. A: Styling html for printing is commonly achieved using a different style sheet, e.g. in your head element: <head> ... <link rel="stylesheet" type="text/css" media="screen" href="style.css"> <link rel="stylesheet" type="text/css" media="print" href="print.css"> ... </head> The style sheet style.css is used to style your html on screen, while print.css is used to style your html for print. By providing the appropriate styling in print.css you can easily show or hide html elements to achieve the output you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/5352081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keras LSTM + TensorFlow and a number sequence (improve loss) first of all, I'm running with the following setup: * *Running on windows 10 *Python 3.6.2 *TensorFlow 1.8.0 *Keras 2.1.6 I'm trying to predict, or at least guesstimate the following number sequence: https://codepen.io/anon/pen/RJRPPx (limited to 20,000 for testing), the full sequence contains about one million records. And here is the code (run.py) import lstm import time import matplotlib.pyplot as plt def plot_results(predicted_data, true_data): fig = plt.figure(facecolor='white') ax = fig.add_subplot(111) ax.plot(true_data, label='True Data') plt.plot(predicted_data, label='Prediction') plt.legend() plt.show() def plot_results_multiple(predicted_data, true_data, prediction_len): fig = plt.figure(facecolor='white') ax = fig.add_subplot(111) ax.plot(true_data, label='True Data') #Pad the list of predictions to shift it in the graph to it's correct start for i, data in enumerate(predicted_data): padding = [None for p in range(i * prediction_len)] plt.plot(padding + data, label='Prediction') plt.legend() plt.show() #Main Run Thread if __name__=='__main__': global_start_time = time.time() epochs = 10 seq_len = 50 print('> Loading data... ') X_train, y_train, X_test, y_test = lstm.load_data('dice_amplified/primeros_20_mil.csv', seq_len, True) print('> Data Loaded. Compiling...') model = lstm.build_model([1, 50, 100, 1]) model.fit( X_train, y_train, batch_size = 512, nb_epoch=epochs, validation_split=0.05) predictions = lstm.predict_sequences_multiple(model, X_test, seq_len, 50) #predicted = lstm.predict_sequence_full(model, X_test, seq_len) #predicted = lstm.predict_point_by_point(model, X_test) print('Training duration (s) : ', time.time() - global_start_time) plot_results_multiple(predictions, y_test, 50) I have tried to: * *increase and decrease epochs. *increase and decrease batch size. *amplify the data. The following plot represents: * *epochs = 10 *batch_size = 512 *validation_split = 0.05 As well, as far as I understand, the loss should be decreasing with more epochs? Which doesn't seem to be happening! Using TensorFlow backend. > Loading data... > Data Loaded. Compiling... > Compilation Time : 0.03000473976135254 Train on 17056 samples, validate on 898 samples Epoch 1/10 17056/17056 [==============================] - 31s 2ms/step - loss: 29927.0164 - val_loss: 289.8873 Epoch 2/10 17056/17056 [==============================] - 29s 2ms/step - loss: 29920.3513 - val_loss: 290.1069 Epoch 3/10 17056/17056 [==============================] - 29s 2ms/step - loss: 29920.4602 - val_loss: 292.7868 Epoch 4/10 17056/17056 [==============================] - 27s 2ms/step - loss: 29915.0955 - val_loss: 286.7317 Epoch 5/10 17056/17056 [==============================] - 26s 2ms/step - loss: 29913.6961 - val_loss: 298.7889 Epoch 6/10 17056/17056 [==============================] - 26s 2ms/step - loss: 29920.2068 - val_loss: 287.5138 Epoch 7/10 17056/17056 [==============================] - 28s 2ms/step - loss: 29914.0650 - val_loss: 295.2230 Epoch 8/10 17056/17056 [==============================] - 25s 1ms/step - loss: 29912.8860 - val_loss: 295.0592 Epoch 9/10 17056/17056 [==============================] - 28s 2ms/step - loss: 29907.4067 - val_loss: 286.9338 Epoch 10/10 17056/17056 [==============================] - 46s 3ms/step - loss: 29914.6869 - val_loss: 289.3236 Any recommendations? How could I improve it? Thanks! Lstm.py contents: import os import time import warnings import numpy as np from numpy import newaxis from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' #Hide messy TensorFlow warnings warnings.filterwarnings("ignore") #Hide messy Numpy warnings def load_data(filename, seq_len, normalise_window): f = open(filename, 'rb').read() data = f.decode().split('\n') sequence_length = seq_len + 1 result = [] for index in range(len(data) - sequence_length): result.append(data[index: index + sequence_length]) if normalise_window: result = normalise_windows(result) result = np.array(result) row = round(0.9 * result.shape[0]) train = result[:int(row), :] np.random.shuffle(train) x_train = train[:, :-1] y_train = train[:, -1] x_test = result[int(row):, :-1] y_test = result[int(row):, -1] x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) return [x_train, y_train, x_test, y_test] def normalise_windows(window_data): normalised_data = [] for window in window_data: normalised_window = [((float(p) / float(window[0])) - 1) for p in window] normalised_data.append(normalised_window) return normalised_data def build_model(layers): model = Sequential() model.add(LSTM( input_shape=(layers[1], layers[0]), output_dim=layers[1], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM( layers[2], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense( output_dim=layers[3])) model.add(Activation("linear")) start = time.time() model.compile(loss="mse", optimizer="rmsprop") print("> Compilation Time : ", time.time() - start) return model def predict_point_by_point(model, data): #Predict each timestep given the last sequence of true data, in effect only predicting 1 step ahead each time predicted = model.predict(data) predicted = np.reshape(predicted, (predicted.size,)) return predicted def predict_sequence_full(model, data, window_size): #Shift the window by 1 new prediction each time, re-run predictions on new window curr_frame = data[0] predicted = [] for i in range(len(data)): predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0]) curr_frame = curr_frame[1:] curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0) return predicted def predict_sequences_multiple(model, data, window_size, prediction_len): #Predict sequence of 50 steps before shifting prediction run forward by 50 steps prediction_seqs = [] for i in range(int(len(data)/prediction_len)): curr_frame = data[i*prediction_len] predicted = [] for j in range(prediction_len): predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0]) curr_frame = curr_frame[1:] curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0) prediction_seqs.append(predicted) return prediction_seqs Addendum: At nuric suggestion I modified the model as following: def build_model(layers): model = Sequential() model.add(LSTM(input_shape=(layers[1], layers[0]), output_dim=layers[1], return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(layers[2], return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense(output_dim=layers[3])) model.add(Activation("linear")) model.add(Dense(64, input_dim=50, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(1)) start = time.time() model.compile(loss="mse", optimizer="rmsprop") print("> Compilation Time : ", time.time() - start) return model Still a bit lost on this one... A: Even though you normalise the input, you don't normalise the output. The LSTM by default has a tanh output which means you will have a limited feature space, ie the dense layer won't be able to regress to large numbers. You have a fixed length numerical input (50,), directly pass that to Dense layers with relu activation and will perform better on regression tasks, something simple like: model = Sequential() model.add(Dense(64, input_dim=50, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(1)) For regression it is also preferable to use l2 regularizers instead of Dropout because you are not really feature extracting for classification etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/50707501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: angular2 / RxJS - how to retry from inside subscribe() this is my code: this._api.getCompanies().subscribe( res => this.companies = JSON.parse(res), exception => {if(this._api.responseErrorProcess(exception)) { // in case this retured TRUE then I need to retry() } } ) in case an exception happened, it will be sent to a function in the API then return true if the problem is fixed (like token refreshed for example) and it just needs to retry again after its fixed I could not figure out how to make it retry. A: In your .getCompanies() call right after the .map add a .retryWhen: .retryWhen((errors) => { return errors.scan((errorCount, err) => errorCount + 1, 0) .takeWhile((errorCount) => errorCount < 2); }); In this example, the observable completes after 2 failures (errorCount < 2). A: You mean something like this? this._api.getCompanies().subscribe(this.updateCompanies.bind(this)) updateCompanies(companies, exception) { companies => this.companies = JSON.parse(companies), exception => { if(this._api.responseErrorProcess(exception)) { // in case this retured TRUE then I need to retry() this.updateCompanies(companies, exception) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/40175255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: generic casting from object-boxed type Why does this work: decimal dec = new Decimal(33); double dd = (double) dec; Console.WriteLine(dd); But not this: decimal dec = new Decimal(33); object o = (object)dec; double dd = (double) o; Console.WriteLine(dd); The second example throws: System.InvalidCastException: Specified cast is not valid. This question comes from a situation where I have a generic method public T GetValue(string q) That gets values from a datasource. The types of these values are unknown, but the method assumes that it can cast the value to T. Sometimes the value will be object{decimal} and T will be double, in which case the InvalidCastException will be thrown. But in principle this should not be an issue since the value is a decimal (albeit boxed by an object) which can be cast to double. How do I handle this generically? A: The latter doesn't work because the decimal value is boxed into an object. That means to get the value back you have to unbox first using the same syntax of casting, so you have to do it in 2 steps like this: double dd = (double) (decimal) o; Note that the first (decimal) is unboxing, the (double) is casting. A: This can be done with Convert.ChangeType: class Program { static void Main(string[] args) { decimal dec = new Decimal(33); object o = (object)dec; double dd = GetValue<double>(o); Console.WriteLine(dd); } static T GetValue<T>(object val) { return (T)Convert.ChangeType(val, typeof(T)); } } The reason your code doesn't work has been well explained by others on this post. A: You can only cast boxed value types back to the exact type that was boxed in. It doesn't matter if there is an implicit or explicit conversion from the boxed type to the one you are casting to -- you still have to cast to the boxed type (in order to unbox) and then take it from there. In the example, this means two consecutive casts: double dd = (double) (decimal) o; Or, using the Convert methods: double dd = Convert.ToDouble(o); Of course this won't do for your real use case because you cannot immediately go from a generic type parameter to ToDouble. But as long as the target type is IConvertible, you can do this: double dd = (double)Convert.ChangeType(o, typeof(double)); where the generic type parameter T can be substituted for double.
{ "language": "en", "url": "https://stackoverflow.com/questions/20146235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: extracting words from a sentence using indexOf and substring and storing them in an array in java Here is what I have so far for this part of my program; String text = JOptionPane.showInputDialog("enter a sentence"); String newWord = ""; char space = '_'; int count = 0; for(int i = 0; i < text.length(); i++) { int found = text.indexOf(space, i); int start = found + 1; // start location of substring after a space int end = text.indexOf(space, start); // end of word count = end + 1; } while(count < text.length()) { newWord[count] = text.substring(start, end); count++; } System.out.println(newWord[count]); A: to split a sentence, use String's .split() method String [] splitter = text.split(" "); this will break the sentence based on spaces. Then you can do whatever you need to the array A: String text = JOptionPane.showInputDialog("Enter a sentence"); int count = 0; char space = ' '; int index = 0; do { ++ count; ++ index; index = text.indexOf(space, index); } while (index != -1); String[] array = new String[count]; index = 0; int endIndex = 0; for(int i = 0; i < count; i++) { endIndex = text.indexOf(space, index); if(endIndex == -1) { array[i] = text.substring(index); }else{ array[i] = text.substring(index, endIndex); } index = endIndex + 1; } for(String s : array) { System.out.println(s); }
{ "language": "en", "url": "https://stackoverflow.com/questions/11461699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: IBM MQ transmission queue exclusive lock I have a WebSphere MQ Queue Manager with transmission queue defined and I'm using API to get some information about the queue. When trying to inquire the queue (using .NET interface, but I believe this is not important here), I always receive an exception with reason 2042: MQRC_OBJECT_IN_USE - according to the documentation, this means that there's an exclusive lock at the queue. By some further investigation I can see that the process holding the lock is runmqchl - part of MQ Server. * *Is the exclusive lock typical for transmission queues? *Or this means that there's something wrong with the queue or the transmission? *Even better, maybe there is a way to do some inquiries (read-only) to that locked queue (i.e. to get its depth or browse the messages) using API? A: The SDR or SVR channel will always open the transmission queue for exclusive use. If the .Net client is getting an error because of this then it is asking for input rights as well as inquire. You can verify this by using WMQ Explorer to inquire on the queue and you will see that it has no problem getting queue attributes, depths, etc. So open for inquire but not browse or get and you should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/4216165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: React change state of one component from another I need to change the state of my sidebar component from another component. My code: Sidebar.tsx > const SideBar: React.FC = () => { const [open, setOpen] = useState<boolean>(false); function switchSidebar() { setOpen(!open); } const bar = useMemo(() => <Menu open={open} sidebar={true} />, [open]) return ( <> <SidebarButton /> { bar } </> } SidebarButton.tsx > export const SidebarButton:React.FC = () => { return( <svg xmlns="http://www.w3.org/2000/svg" onMouseDown={/* ? */}> <path stroke="currentColor" strokeWidth={3} d="M0 1.5h28M0 10.5h28M8 19.5h20"/> </svg> ) } Menu.tsx > const Menu: React.FC = ({sidebar, open, data = HeaderData}) => { return ( <ul> <SidebarButton /> { /* Other things to render */ } </ul> ) } How you can see I need a method to change the state that is contained in Sidebar from SidebarButton. A: You can pass the setOpen function as a prop to the SidebarButton component and then simply call the setOpen function to change the value. <SidebarButton setOpen={setOpen} /> If you would like to also call it from the menu component then you may need to move the declaration of open to a higher component that is common between Sidebar and Menu since props can only be passed downwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/68182599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to animate (resize) a Linear layout loaded into listview on item click in android Hi i need to animate (resize height and width) a linear layout added into a Listview through adapter in android. A: I'm not entirely sure as to what you want to do here. If im correct what your looking for is an expanded listview. You can achieve this using the following library it takes two layouts one for the listview item and the second the layout which needs to be expanded when the listview item is clicked https://github.com/tjerkw/Android-SlideExpandableListView
{ "language": "en", "url": "https://stackoverflow.com/questions/38694890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to translate whole words into morse-code with a dictionary? I'm writing a program that translates normal text to Morse code and I've written the core program that translates single letters to Morse code I still can't figure out how to translate whole words and text. more clarification: i can translate single letters but i cant translate whole words Here's the code: from tkinter import * #key down function def click(): entered_text=textentry.get() #this wil collect the text from the text entry box outpout.delete(0.0, END) try: definition = my_dictionary[entered_text] except: definition= "sorry an error occured" outpout.insert(END, definition) #### main window = Tk() window.title("THIS IS A SIMPLE TITLE") window.configure(background="yellow") #create label Label (window,text="Enter a text here.", bg="YELLOW", fg="BLACK", font="arial 30 bold italic" ) .grid(row=1, column=0, sticky=W) #create a text entry box textentry= Entry(window, width=20, bg="WHITE") textentry.grid(row=2, column=0, sticky=W) #add a submit button Button(window, text="SUBMIT", width=6, command=click) .grid(row=3 ,column=0, sticky=W) #create another label Label (window,text="THE ENCRYPTED TEXT IS:", bg="YELLOW", fg="BLACK", font="arial 10 bold" ) .grid(row=4, column=0, sticky=W) #create a text box outpout = Text(window, width=75, height=6, wrap=WORD, bg="WHITE") outpout.grid(row=5, column=0, columnspan=2, sticky=W) #the dictionary my_dictionary = { "A" : ".-", "B" : "-...", "C" : "-.-.", "D" : "-..", "E" : ".", "F" : "..-.", "G" : "--.", "H" : "....", "I" : "..", "J" : ".---", "K" : "-.-", "L" : ".-..", "M" : "--", "N" : "-.", "O" : "---", "P" : ".--.", "Q" : "--.-", "R" : ".-.", "S" : "...", "T" : "-", "U" : "..-", "V" : "...-", "W" : ".--", "X" : "-..-", "Y" : "-.--", "Z" : "--..", " " : "/" } #run the main loop window.mainloop() A: I think the issue is that you are trying to use the entire text as the key to the dictionary. So, if the text "A" is entered into the text input then it works as "A" is a key in my_dictionary. If the text "AS" is entered into the text box, this will fail as there is no key "AS" in my_dictionary. What you will want to do, therefore, is loop over each of the characters in the entered string and add the Morse value of that letter to your definition string. You will also want to make sure that the letter is uppercase (unless it is guaranteed that the input will be upper case). This is done using the string .upper() method in the following example. Something like the following should do what you want. definition = str() # Create a blank string to add the Morse code to # Go through each letter and add the Morse definition of the letter to definition for letter in entered_text: definition += my_dict[letter.upper()] # The upper makes sure the letter is a capital so that there will be a match in my_dict
{ "language": "en", "url": "https://stackoverflow.com/questions/48592334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Does Flask trim items? Within Flask and using Jinja2, I'm calling a datalist but for some reason any option with a space is trimmed so "tomato sauce" becomes "tomato". Is this something Flask is doing or have I messed up the templating? <!-- HOMEPAGE --> <form type="text" id="homeForm" class="centered" method="post" onsubmit="return false;"> {{ form.hidden_tag() }} <input type="text" id="homeInput" autocomplete=off list="topps" placeholder="Input here"> <datalist id="topps"> {% for top in topps %} <option value={{ top }}> {% endfor %} </datalist> <button type="submit" id="homeSubmit">Submit</button> </form> # ROUTES.PY # @app.route('/', methods=['GET', 'POST']) @app.route('/index', methods=['GET', 'POST']) def index(): form = ToppingsForm() topps = ["tomato sauce", "chilli flakes","something else"] return render_template('index.html', title='Home', form=form, topps=topps) A: Your problem is here: <option value={{ top }}> add quotes outside of {{top}} <option value="{{ top }}" />
{ "language": "en", "url": "https://stackoverflow.com/questions/62242154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ProxySQL between master/slave replication on flaky connection I have two MySQL servers with master/slave replication between them. The connection between them is ADSL. It is not reliable at all. I decided to add another ADSL connection from another ISP with its own IP address. The problem is that when when one ADSL connection goes down, the other one is useless because the slave is using the first connection's IP address which is down now. I want to know if is it possible to put a proxysql node between and give its IP to the slave. Is it possible for proxysql to do fail-over connection handling for the same node? Proxysql must choose the second IP address when the first one is not available. A: ADSL is generally not a fixed IP, which means that the server does not recognize it. As I understand it, you want to balance the load. Analyzing your doubt. I leave my case study. 1 - How each server is separate. Place a fixed IPv4 from there, create a fixed DNS and point to the corresponding fixed IP. Also place a domain and add the DNS configuration. If you have IPv6 (AAA), add it for even more answers. And prioritize cryptography. If you need a secure proxy, use CloudFlaure to manage your settings. It helps the configuration become more practical. 2 - Pointing the DNS to fixed IP, create NS for both servers. example: ns1.server.com //// ns2.server.com I recommend creating 4 NS for each server. 3 - The same procedure is used on the slave. but do not use ns, switch to another silga, for example: (tl1.server.com). This facilitates orientation. So, for each server. An IPv4 An Ipv6 Four NS Two DNS Therefore, when the first server goes down, the other server takes over. Be on IPV4 or IPV6. And the DNS and the DNS are congested or are not recognized for some reason, promptly the other takes over. So, without loss. If there is a problem with your hosting, create IP or domains. Due to fees. There are some free ones and, that work 90%, cloudflare itself has this service. If I was able to understand your demand, I recommend the services later. It works for me. Submit questions and follow the case. A: My Idea. You use dynamic dns to know always, which IP Address is valid, to reach the site with the spotty connection. A fail over Router like the one in the comment, has the advantage, that it always knows which connection is the better one, and actualizes the dyndns serverip. For the rest, i would see that both sites build a vpn. Most router can be VPN server as also client and with the dynamic Ip, establishing the connection is no problems, as long any connection actually work. For your replication it is the same network, with a fixed ip. If you have already a ssl server,all is the same, only you need to bridge the port, so that packet will enter the network. For all that, you should get some help, because the are many points that can be tweaked, to fit the situation on side.
{ "language": "en", "url": "https://stackoverflow.com/questions/57436729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Aframe + Meteor - Add a conditional custom component to an entity <a-gltf-model id='playerone' {{#if myplayer playerone}}entitymove{{/if}} src="#myMixBun"> </a-gltf-model> Using Aframe in Meteor, I want to add the custom component “entitymove” if the value of myplayer is “playerone”. The value of {{myplayer}} is “playerone” in main.html, so the variable is set correctly. But I get the Meteor error “A template tag of type BLOCKOPEN is not allowed here”. If “entitymove” was a “class”, for instance, I think I could solve this with the following: <a-gltf-model id='playerone' class={{#if myplayer playerone}}entitymove{{/if}} src="#myMixBun"> </a-gltf-model> But since it’s a component, I am at a loss as to how to fix the syntax. A: Assuming that this uses Meteor-Blaze templates you need to include the conditionals for DOM element attributes inside quotes/double quotes: <a-gltf-model id='playerone' class="{{#if myplayer playerone}}entitymove{{/if}}" src="#myMixBun"> </a-gltf-model> Readings: http://blazejs.org/guide/spacebars.html A: SOLVED This is my original, which doesn’t work. In main.js: player = "player not active"; Template.hello.helpers( counter() {...... // if player one player = "playerone"; // if player two player = "playertwo"; return { myplayer: player }; } In main.html: // This statement works {{counter.myplayer}}.... <a-gltf-model id='playerone' class="{{#if counter.myplayer playerone}}entitymove{{/if}}" src="#myMixBun"> </a-gltf-model> <a-gltf-model id='playertwo' class="{{#if counter.myplayer playertwo}}entitymove{{/if}}" src="#myMixBun"> </a-gltf-model> I think there are 2 problems with this: 1) spacebars doesn’t seem to like the if statement with a comparison?: {{#if counter.myplayer playertwo}} It only allows true or false if statements?, such as: {{#if counter.player1}} 2) My aframe custom component isn’t actually a class, so I can’t put the meteor #if statement inside the entity. I changed the code to the following and it now works: Changed main.js to: playerone =""; playertwo =""; // if player one playerone = "true"; playertwo = ""; // if player two playerone = ""; playertwo = "true"; return { player1: playerone, player2: playertwo}; } Changed main.html to: // These statements work {{#if counter.player1}}player1 is true{{/if}} {{#if counter.player2}}player2 is true{{/if}}.... {{#if counter.player1}} <a-gltf-model id='playerone' entitymove src="#myMixBun" ></a-gltf-model> <a-gltf-model id='playertwo' src="#myMixBun" ></a-gltf-model> {{/if}} {{#if counter.player2}} <a-gltf-model id='playerone' src="#myMixBun" ></a-gltf-model> <a-gltf-model id='playertwo' entitymove src="#myMixBun" ></a-gltf-model> {{/if}}
{ "language": "en", "url": "https://stackoverflow.com/questions/56049613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: count frequency group by pandas I am trying to add a new column to a data below, in which columns Algorithm1,2 & 3 are derived from Text column. I want to count each element in the 3 columns and create new column to only have elements which have count > 1 df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'], 'Algorithm1': ['AX','AB','AAB'], 'Algorithm2' : ['BX','AAX','AB'], 'Algorithm3' : ['AX','AB','AAX']}) This is how the final output should look like with columns values AB, AX & AAX as they have frequency > 1 df2 = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'], 'Algorithm1': ['AX','AB','AAB'], 'Algorithm2' : ['BX','AAX','AB'], 'Algorithm3' : ['AX','AB','AAX'], 'Majority': ['AB','AX','AAX']}) A: IIUC count values in Algorithm columns and filter if greater like 1: df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'], 'Algorithm1': ['AX','AB','AAB'], 'Algorithm2' : ['BX','AAX','AB'], 'Algorithm3' : ['AX','AB','AAX']}) s = df.filter(like='Algorithm').stack().value_counts() m = s.gt(1) print (s) AB 3 AX 2 AAX 2 AAB 1 BX 1 dtype: int64 df['new'] = pd.Series(s.index[m])[:m.sum()] print (df) T Algorithm1 Algorithm2 Algorithm3 new 0 AAABBX AX BX AX AB 1 AAABBX AB AAX AB AX 2 AAABBX AAB AB AAX AAX If number of values is greater like length of DataFrame: df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'], 'Algorithm1': ['AX','AB','AAB'], 'Algorithm2' : ['AAX','AAX','AB'], 'Algorithm3' : ['AX','AB','AAB']}) s = df.filter(like='Algorithm').stack().value_counts() m = s.gt(1) print (s) AB 3 AAB 2 AX 2 AAX 2 dtype: int64 df['new'] = pd.Series(s.index[m])[:m.sum()] print (df) T Algorithm1 Algorithm2 Algorithm3 new 0 AAABBX AX AAX AX AB 1 AAABBX AB AAX AB AAB 2 AAABBX AAB AB AAB AX If number of values is less like length of DataFrame: df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'], 'Algorithm1': ['AX','AB','AX'], 'Algorithm2' : ['AA','AAX','AB'], 'Algorithm3' : ['AX','AB','AX']}) s = df.filter(like='Algorithm').stack().value_counts() m = s.gt(1) print (s) AX 4 AB 3 AAX 1 AA 1 dtype: int64 df['new'] = pd.Series(s.index[m])[:m.sum()] print (df) T Algorithm1 Algorithm2 Algorithm3 new 0 AAABBX AX AA AX AX 1 AAABBX AB AAX AB AB 2 AAABBX AX AB AX NaN
{ "language": "en", "url": "https://stackoverflow.com/questions/73702026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to strip a txt file of multiple things? I am creating a function which reads data of a txt file, the text file is set up as one sentence per line. I have 6 requirements to strip the file of to make it usable later on in my program: 1. Make everything lowercase 2. Split the line into words 3. Remove all punctuation, such as “,”, “.”, “!”, etc. 4. Remove apostrophes and hyphens, e.g. transform “can’t” into “cant” and “first-born” into “firstborn” 5. Remove the words that are not all alphabetic characters (do not remove “can’t” because you have transformed it to “cant”, similarly for “firstborn”). 6. Remove the words with less than 2 characters, like “a”. Here's what I have so far... def read_data(fp): file_dict={} fp=fp.lower fp=fp.strip(string.punctuation) lines=fp.readlines() I am a little stuck, so how do I strip this file of these 6 items? A: This can be accomplished via a series of regex checks and then a loop to remove all items with less than 2 characters: Code import re with open("text.txt", "r") as fi: lowerFile = re.sub("[^\w ]", "", fi.read().lower()) lowerFile = re.sub("(^| )[^ ]*[^a-z ][^ ]*(?=$| )", "", lowerFile) words = [word for word in lowerFile.split() if len(word) >= 2] print(words) Input I li6ke to swim, dance, and Run r8un88. Output ['to', 'swim', 'dance', 'and', 'run']
{ "language": "en", "url": "https://stackoverflow.com/questions/43309008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Use imagemin in Cloud Functions for Firebase I've got a cloud function for Firebase that triggers on a storage bucket write: exports.convertToWebP = functions.storage.object().onChange(async event => { const path = event.data.name; const [pictureSlug, fileName] = path.split('/'); const [fileSlug, fileType] = fileName.split('.'); // Download the file const tmpFilePath = `/tmp/${fileSlug}.${fileType}`; const file = bucket.file(path); await file.download({ destination: tmpFilePath }); await imagemin( [`tmp/${fileSlug}.${fileType}`], '/tmp', { use: [ imageminWebp({quality: 50})] }); const destination = `${pictureSlug}.webp`; await bucket.upload(tmpFilePath, { destination }); The issue I'm having is that when I call the .download method on the storage object, it goes to the /tmp/ folder, but I can't for the life of me figure out how to get imagemin to grab the file. It could have something to do with the way I'm constructing the path, or it could be something else like Cloud Functions not supporting imagemin. The reason I'm doing this to being with is because the local instance of ImageMagick doesn't support webp. Also: This file is a .ts file and I'm using the typescript compiler to create a js file of it. It compiles to an ES5 version. A: In this bit of code: await imagemin( [`tmp/${fileSlug}.${fileType}`], '/tmp', { use: [ imageminWebp({quality: 50})] }); It looks like you're building a different string to the tmp file than you did when you built tmpFilePath. It's missing the leading slash. Any reason why you wouldn't use this instead? await imagemin( [tmpFilePath], '/tmp', { use: [ imageminWebp({quality: 50})] });
{ "language": "en", "url": "https://stackoverflow.com/questions/44318605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: chart.js / angular-chart line outside style issue I have a strange issue with angular-chart.js (which use chart.js). If I set and block the min and max values for yAxis, when the line goes out of the limits the style is strange. Do you have an idea about what occurs ? Here is the configuration for each 3 chart : ChartJsProvider.setOptions({ responsive: true, animation: false, pointDot: false, colours: [{ // blue fillColor: 'rgba(0,0,0,0)', strokeColor: 'rgba(51,87,205,1)', pointColor: 'rgba(51,87,205,1)', pointStrokeColor: 'rgba(51,87,205,1)', pointHighlightFill: 'rgba(0,0,0,0)', bezierCurve: true, pointHitDetectionRadius: 20, datasetStroke: false, }, { // blue fillColor: 'rgba(0,0,0,0)', strokeColor: '#FB3333', pointColor: '#FB3333', pointStrokeColor: '#FB3333', pointHighlightFill: 'rgba(0,0,0,0)', }], maintainAspectRatio: false, showXLabels: 10, showTooltips: true, multiTooltipTemplate: function(label) { return label.datasetLabel + " : " + label.value.toFixed(1); } }); And for each chart I applied an other configuration : $scope.optionsG1 = { scaleStartValue: -2, scaleStepWidth: 1, scaleOverride: true, scaleSteps: 4 }; Thanks for your help A: Set bezierCurve: false for the charts where you are having this problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/33911876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get Current Path of Page in Middleman Layout File Is it possible to retrieve the current path of a page in a middleman file? For instance, if I have a layout file layout.erb with something like the following: <%= page.path %> <%= yield %> and a test file index.html: Testing then when Middleman rendered the page I would get something like: /index.html Testing A: Middleman also provides the current_page variable. current_page.path is the source path of this resource (relative to the source directory, without template extensions) and current_page.url is the path without the directory index (so foo/index.html becomes just foo). <%= current_page.path %> # -> index.html <%= current_page.url %> # -> / Details from Middleman's Middleman::Sitemap::Resource rubydoc. http://rubydoc.info/github/middleman/middleman/Middleman/Sitemap/Resource A: The solution is: <%= request.path %>
{ "language": "en", "url": "https://stackoverflow.com/questions/10680971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Calculate average value between two cell phone recharges I have a cell phone recharge table which is as below. In that at UserId,Date level I have particular user's Balance amount, the amount which he consumed at a particular day for voice communication and amount that was consumed for data (internet) usage. Whenever the user recharges his account the Balance increases. So I want a query which could help me to find the average Voice and Data amount/balance between two recharges for each user. Recharge Table +--------+-----------+---------+-------+------+ | Userid | Date | Balance | Voice | Data | +--------+-----------+---------+-------+------+ | 1 | 4/5/2018 | 100 | 10 | 15 | //Recharge of 100 | 1 | 4/6/2018 | 75 | 5 | 10 | | 1 | 4/7/2018 | 60 | 10 | 10 | | 1 | 4/8/2018 | 90 | 10 | 20 | //Recharge of 50 | 1 | 4/9/2018 | 60 | 10 | 20 | | 1 | 4/10/2018 | 50 | 20 | 30 |// Recharge of 20 | 2 | 4/1/2018 | 200 | 50 | 40 |// Recharge of 200 | 2 | 4/2/2018 | 110 | 20 | 20 | | 2 | 4/3/2018 | 70 | 20 | 10 | | 2 | 4/4/2018 | 55 | 10 | 40 |// Recharge of 15 | 2 | 4/5/2018 | 5 | 2 | 2 | +--------+-----------+---------+-------+------+ In the above table A given day's Balance = Previous Day's (Balance - SUM(Voice + Data)) As you can see for UserId 1 100 gets reduced to 75 (100 - (10 + 15)). But in the third row(Date = 4/8/2018) he recharges by an amount of 50 due to which his balance becomes 90 instead of 40. So I want to find the average Voice and Data column between 100 and 90 for UserId = 1 Below is the output I want +--------+-------------+-----------+----------+ | UserID | RechageDate | Avg_Voice | Avg_Data | +--------+-------------+-----------+----------+ | 1 | 4/8/2018 | 8.33 | 11.66 | | 1 | 4/10/2018 | 10 | 20 | | 2 | 4/4/2018 | 27.5 | 25 | +--------+-------------+-----------+----------+ I know the question is difficult to understand but I have tried my best to explain it. Please feel free to ask in case of any ambiguity. A: I have Added two new column to determine the recharge information: I think you have recharge information in another table, if you can put that information like i did this query will work. DECLARE @tbl table( Userid int, Date datetime, Balance int, Voice int, Data int, Recharge int, RechargeSN int ) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(1,'4/5/2018' , 100 , 10 , 15,100,3) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(1,'4/6/2018' , 75 , 5 , 10,0,3) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(1,'4/7/2018' , 60 , 10 , 10,0,3) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(1,'4/8/2018' , 90 , 10 , 20,50,2) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(1,'4/9/2018' , 60 , 10 , 20,0,2) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(1,'4/10/2018' , 50 , 20 , 30,20,1) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(2,'4/1/2018' , 200 , 50 , 40,200,2) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(2,'4/2/2018' , 110 , 20 , 20,0,2) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(2,'4/3/2018' , 70 , 20 , 10,0,2) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(2,'4/4/2018' , 55 , 10 , 40,15,1) INSERT INTO @tbl( Userid, [Date], Balance, Voice, Data,Recharge,RechargeSN) VALUES(2,'4/5/2018' , 5 , 2 , 2,0,1) --SELECT * FROM @tbl t SELECT userid, RechageDate = max(date), Avg_Voice = (cast(SUM(voice) AS numeric) / Count(voice)) , Avg_Data = cast(SUM(Data) AS numeric) / Count(Data) *1.00 --, t.RechargeSN FROM @tbl t GROUP BY t.Userid, t.RechargeSN ORDER BY t.Userid A: Since you haven't posted any attempt to solve this, but have shown an understanding of the data, I assume you just need to be given a broad strategy to begin following, and you can handle the coding from there. Using LAG() partitioned by UserID, you can join each row to the previous row. You already have stated that you understand that (Balance - SUM(Voice + Data)), so in any CASE where that is not true, then you know that you have found a row where a recharge was done. You can create an artificial column (eg HasRecharge) in a CTE that uses a CASE expression to test this and return 1 for the rows that have a recharge, and 0 for the rows that don't. Then you can do a 2nd CTE where you SELECT from the first CTE WHERE HasRecharge=1 and WHERE there EXISTS() a previous row that also HasRecharge=1. And calculate two additional columns: A SUM of Voice + Data between this recharge and the last recharge (again using LAG() but this time WHERE HasRecharge=1) A COUNT of rows between this recharge and the last. Your final SELECT from the 2nd CTE would get the average simply by dividing the SUM column by the COUNT column. A: This problem becomes simpler when you have a flat table containing the day's charge, and the previous day's charge. Note that this will only work if your data set has a contiguous range of dates. The following queries will need to be edited of course: Select currentday.Date, currentday.user, currentday.balance - prevday.balance - (currentday.voice+currentday.data) as charge, currentDay.voice, currentDay.data, --The above column will tell you what the difference --is between the expected balance, and should --resolve to the charge for the day GETDATE() as nextCharge --leave this empty, use GETDATE() to force it to be a datetime into ##ChargeTable from [RechargeTable] currentday left join [RechargeTable] prevday on DATEADD(d,1,prevday.Date) = currentday.Date AND prevday.user = currentday.user Now, we know when the user has charged. The charge column will be positive. Select user, date into ##uniquedates from ##charge where charge>0 Now that we have the dates, we need to go back to the first temp table and update it with the next dates. (not sure on the syntax on aliasing updates). update ##ChargeTable up set nextCharge = ( select date from ##uniquedates where up.user == user AND date > up.date ) Now we can do some sub selects back on the table to get the data we need. select user, (select avg(voice) from ##ChargeTable where user = ct.user and date>=ct.date and date<=ct.nextCharge) as AvgVoice, (select avg(data) from ##ChargeTable where user = ct.user and date>=ct.date and date<=ct.nextCharge) as AvgData from ##ChargeTable ct where nextCharge is not null and charge>0
{ "language": "en", "url": "https://stackoverflow.com/questions/55541810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to detect a scroll / wheel event only once in a certain period of time? Let's say I have a scroll/wheel event like this: container.addEventListener("wheel", (e) => { const isScrollingDown = Math.sign(e.wheelDeltaY); // call some function once, don't listen for wheel event anymore // then listen for event again when done } Based on deltaY, I detect whether a user is scrolling down, or up. How would I call a function only once when I detect this (which is immediatly), remove the event listener, and then listen for it again when my function is complete? I can't remove the event listener from inside my event listener right? Thanks in advance. A: You can use removeEventListener() function. documentation example: let wheelHandler = function(e) { toggleListener(wheelHandler, false) const isScrollingDown = Math.sign(e.wheelDeltaY); // call some function once, don't listen for wheel event anymore // then listen for event again when done toggleListener(wheelHandler, true) }; let toggleListener = function(listener, add) { if (add) { container.addEventListener("wheel", wheelHandler) } else { container.removeEventListener("wheel", wheelHandler) } } toggleListener(wheelHandler, true); A: wait 1 second after first wheel: function handleWheel(e){ console.log(Math.random()) document.getElementById("container").removeEventListener("wheel", handleWheel) setTimeout(()=>{ document.getElementById("container").addEventListener("wheel", handleWheel); },1000); // return event after 1 second } document.getElementById("container").addEventListener("wheel", handleWheel) <div id="container" >wheel</div> A: you can define loading variable and check each time before run function var loading = false container.addEventListener("wheel", (e) => { const isScrollingDown = Math.sign(e.wheelDeltaY); if(!loading){ loading = true; // call some function once, don't listen for wheel event anymore // then listen for event again when done // after done loading = false } }
{ "language": "en", "url": "https://stackoverflow.com/questions/54052374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: insert in select in MySQL with JDBC I would like to have a value from a row inserted into an other row here is my code: static void addVipMonth(String name) throws SQLException { Connection conn = (Connection) DriverManager.getConnection(url, user, pass); PreparedStatement queryStatement = (PreparedStatement) conn.prepareStatement("INSERT INTO vips(memberId, gotten, expires) " + "VALUES (SELECT name FROM members WHERE id = ?, NOW(), DATEADD(month, 1, NOW()))"); //Put your query in the quotes queryStatement.setString(1, name); queryStatement.executeUpdate(); //Executes the query queryStatement.close(); //Closes the query conn.close(); //Closes the connection } This code is not valid. How do I correct it? A: I get an error 17:28:46 [SEVERE] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MyS QL server version for the right syntax to use near ' NOW(), DATE_ADD( now(), INT ERVAL 1 MONTH )' at line 1 – sanchixx It was due to error in SELECT .. statement. Modified statement is: INSERT INTO vips( memberId, gotten, expires ) SELECT name, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH ) FROM members WHERE id = ? * *You don't require VALUES key word when inserting with a select. *You used a wrong DATEADD function syntax. Correct syntax is Date_add( date_expr_or_col, INTERVAL number unit_on_interval). You can try your insert statement as corrected below: INSERT INTO vips( memberId, gotten, expires ) SELECT name FROM members WHERE id = ?, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH ) Refer to: * *INSERT ... SELECT Syntax *DATE_ADD(date,INTERVAL expr unit)
{ "language": "en", "url": "https://stackoverflow.com/questions/20922966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Movable parameters in std::thread constructor (Visual C++ 2012) I run into problem with rvalue references in MSVC 2012. #include <thread> #include <string> #include <future> void foo(std::promise<std::string> &&prms) { /* some code */ } int main() { std::promise<std::string> prms; // std::future<std::string> ftr = prms.get_future(); std::thread th(&foo, std::move(prms)); // some other code } Compiler says: error C2664: 'void (std::promise<_Ty> &&)' : cannot convert parameter 1 from 'std::promise<_Ty>' to 'std::promise<_Ty> &&' Is there my mistake (then how to fix it) or compiler issue (then I'd like to know origin of such behaviour)? A: This is a known issue in the Visual C++ 2012 implementation of std::thread. See the following bug on Microsoft Connect: std::thread constructor doesn't handle movable object The response to that bug states: We attempted to fix this during VC11's development, but it exploded horribly and we had to revert the change. As it turns out, std::thread can't be powered by bind(), because thread needs to move its arguments, and bind() is forbidden from doing so (since bound functors should be repeatedly invokable, without their bound arguments being moved-from). So we'll need to reimplement std::thread's ctor to avoid using bind().
{ "language": "en", "url": "https://stackoverflow.com/questions/14444638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TFS access issue when check in files I have a problem in TFS. Actually, last time when we are working on ROM (my project name). We (john & me ) both had created a controller with same name ROController.cs and we noticed this problem (same files Confilct), when we are checking files to TFS. So, i deleted my file , and let john to check in his file. Now ,the problem is that when i try to get lastest or even access that ROController and its View. i got errors like "you do not have permissoin to access this file." also in the team explorer , my file is shown as deleted, user name (me) These are the files properly defining the error status. This is the Error Shown
{ "language": "en", "url": "https://stackoverflow.com/questions/27939489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Node Outside of openshift cluster can't access pods inside cluster Note I have three nodes (A, B, C) whose ips are 172.18.143.115, 172.18.143.117, 172.18.143.124. A and B are a openshift cluster using ovs-sdn as its network pulgin, pod network is 10.130.0.0/16, service ip range is 172.30.0.0/16. there is a pod P(10.130.3.249:8002) in node B, and a corresponding service S(172.30.148.77:8002). I can curl S in node A or B, but can't do it in node C So I add a route like if dst_ip is P then goto node A or B. Then strange things happen, if the route points to B, I can curl S, otherwise if the route points to A, I can't curl S. Through tcpdump, i find pod P return a TCP ACK packet to node C through its veth, then this packet is output to tun0 according to flows in OVS, according to route it should be send by ens192(network interface) since its dst_ip is node C, but i can't catch it on ens192 with tcpdump, it seems like that this packet is droped. Why did this happen? A: Traffic is only routed within the cluster by default, so if the application on C is not part of the cluster, then ingress and egress won't be possible between the A/B nodes and C. This is all controlled by application's service configuration. To route ingress and egress traffic from/to outside the cluster, you'll need to configure the service of your application. One of the easier ways to do this is to use the type LoadBalancer service. You can also use the type NodePort service, which will expose the service on a mapped port in the range of 30000 - 32767 across all nodes. Lastly, you can assign an External IP to the service to allow outside traffic into the cluster. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/53735536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to perform a Join using Icriteria nhibernate I am developing an application in MVC3 using nhibernate to fire queries on database. I have Two Models. HobbyMasters HObbyDetail HobbyMaster class Contains: HobbyId and other details HobbyDetail Class Contains: HobbyDetaild HobbyMasters hobbymaster other detals Now i want to perform a jon between two tables using Icrteria: ICriteria criteria = session.CreateCriteria<HobbyDetail>() .CreateAlias("HobbyMasters", "HobbyMasters") .Add(Restrictions.EqProperty("HobbyMasters.HobbyId", "HobbyDetail.hobbymaster.HobbyId")); Also this: HobbyDetail = session.CreateCriteria(typeof(HobbyDetail)) .CreateAlias("HobbyMasters", "HobbyMasters", NHibernate.SqlCommand.JoinType.InnerJoin) .Add(Restrictions.EqProperty("HobbyMasters.hobbymaster.HobbyId", "HobbyDetail.HobbyId")) But i get an error saying Couldnot Resolve Property HobbyMaster of HobbyDetail Class Please Help me A: You can use QueryOver, it's a wrapper on ICriteria with Lambda Expressions: session.QueryOver<HobbyDetail>() .Fetch(hobbyDetail => hobbyDetail.HobbyMasters).Eager .TransformUsing(Transformers.DistinctRootEntity) .List();
{ "language": "en", "url": "https://stackoverflow.com/questions/10285856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extend the context object of a GraphQL call? I'm having the following GraphQL server call in a standard module: export default () => { return graphqlHTTP({ schema: schema, graphiql: true, pretty: true, formatError: error => ({ message: error.message, locations: error.locations, stack: error.stack, path: error.path }) }); }; That is used together with passport: app.use( "/graphql", passport.authenticate("jwt", { session: false }), appGraphQL() ); Everything is working file. Passport extends my req to get a logged user object that is used on my GraphQL calls to queries or mutations: ... resolve(source, args, context) { console.log("CURRENT USER OBJECT") console.log(context.user) ... All fine. Now I need to extend my context to add some custom resolvers, so my first try is: export default () => { return graphqlHTTP({ schema: schema, graphiql: true, pretty: true, context: resolvers, formatError: error => ({ message: error.message, locations: error.locations, stack: error.stack, path: error.path }) }); }; As GraphQL docs says, this overrides the original req context and my context.user on queries and mutations stops working. How can I properly extend the current context to add some more fields, instead of overriding it? Another unsuccessfull try: export default (req) => { return graphqlHTTP({ schema: schema, graphiql: true, pretty: true, context: { user: req.user, resolvers: resolvers }, formatError: error => ({ message: error.message, locations: error.locations, stack: error.stack, path: error.path }) }); }; This approach is not working... I'm getting the following error: user: req.user, ^ TypeError: Cannot read property 'user' of undefined [edit] My latest try is from my example on Apollo Docs: export default () => { return graphqlHTTP({ schema: schema, graphiql: true, pretty: true, context: ({ req }) => ({ user: req.user }), formatError: error => ({ message: error.message, locations: error.locations, stack: error.stack, path: error.path }) }); }; Now my context is a function in my resolver: console.log(context) console.log(context.user) Returns: [Function: context] undefined Getting crazy with this simple thing... A: Assuming you're using express-graphql, graphqlHTTP is a function that takes some configuration parameters and returns an express middleware function. Normally, it's used like this: app.use( '/graphql', graphqlHTTP({ ... }) ) However, instead of an object, graphqlHTTP can also take a function that returns an object as shown in the docs. app.use( '/graphql', graphqlHTTP((req, res, graphQLParams) => { return { ... } }) ) In this way, you can utilize the req, res or graphQLParams parameters inside your configuration object. app.use( '/graphql', graphqlHTTP((req, res, graphQLParams) => { return { schema, // other options context: { user: req.user, // whatever else you want } } }) )
{ "language": "en", "url": "https://stackoverflow.com/questions/57914065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Dataframe from complex data structure Say I need to have data stored as follows: [[[{}][{}]]] or a list of lists of two lists of dictionaries where: {}: dictionaries containing data from individual frames observing an event. (There are two observers/stations, hence two dictionaries.) [{}][{}]: two lists of all the individual frames related to a single event, one from each observer/station. [[{}][{}]]: list of all events on a single night of observation. [[[{}][{}]]]: list of all nights. Hopefully that's clear. What I want to do is create two pandas dataframes where all dictionaries from station_1 are stored in one, and all dictionaries from station_2 are stored in the other. My current method is as follows (where data is the above data structure): for night in range(len(data)): station_1 = pd.DataFrame(data[night][0]) station_2 = pd.DataFrame(data[night][1]) all_station_1.append(station_1) all_station_2.append(station_2) all_station_1 = pd.concat(all_station_1) all_station_2 = pd.concat(all_station_2) My understanding though is that the for loop must be horribly inefficient since I will be scaling the application of this script way up from my sample dataset this cost could easily become unmanageable. So, any advice for a smarter way of proceeding would be appreciated! I feel like pandas is so user friendly there's gotta be an efficient way of dealing with any kind of data structure but I haven't been able to find it on my own yet. Thanks! A: I don't think you can really avoid using a loop here, unless you want to invoke jq via sh. See this answer Anyways, using your full sample, I managed to parse it into a multiindexed dataframe, which I assume is what you want. import datetime import re import json data=None with open('datasample.txt', 'r') as f: data=f.readlines() # There's only one line data=data[0] # Replace single quotes to double quotes: I did that in the .txt file itself, you could do it using re # Fix the datetime problem cleaned_data = re.sub(r'(datetime.datetime\(.*?\))', lambda x: '"'+ str(eval(x.group(0)).isoformat())+'"', data) Now that the string from the file is valid json, we can load it: json_data = json.loads(cleaned_data) And we can process it into a dataframe: # List to store the dfs before concat all_ = [] for n, night in enumerate(json_data): for s, station in enumerate(night): events = pd.DataFrame(station) # Set index to the event number events = events.set_index('###') # Prepend night number and station number to index events.index = pd.MultiIndex.from_tuples([(n, s, x) for x in events.index]) all_.append(events) df_all = pd.concat(all_) # Rename the index levels df_all.index.names = ['Night','Station','Event'] # Convert to datetime df_all.DateTime = pd.to_datetime(df_all.DateTime) df_all (Truncated) Result:
{ "language": "en", "url": "https://stackoverflow.com/questions/40650913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Lock Cell based on the value of the another cell and perform data validation I am very new to VBA code. Now I was assigned to make a task that validate the data in an excel sheets. For Example in my Column A, I have a drop down menu that enable the user to make a selection between "Yes" or "No" only. * *If user selected "Yes", cells in Column B and Column C will be marked as Mandatory and cannot be blank. I want to put a validation error on this. **Example 1: If A1 and A30 == YES** * *B1 and C1, B30 and C30 are mandatory *Will fill a color to the mandatory cells and remove the fill color when the cells have value already *Throw a validation error when these cells are blank and if exceeds the number of characters required. Example 2: If A99 == NO *B99 will be locked and the user will not be allowed to enter a data on this cell. Possible that we can add a cell value as "NA" to avoid confusion I was able to capture this using the data validation and conditional formatting. However, I cannot perform the locked functionality since as per research, I need a VBA code for this one. A: Something like this should work. Put it into the code module for the sheet you want to apply it to. Private Sub worksheet_change(ByVal target As Range) ''''' CHECK IF THE CHANGED CELL IS IN RANGE A1:A99 (OR ANY OTHER RANGE YOU DEFINE) If Not Intersect(target, Range("A1:A99")) Is Nothing Then ''''' UNPROTECT THE SHEET ActiveSheet.Unprotect ''''' IF THE CELL CHANGED IS NOW 'YES' If target = "Yes" Then ''''' WE DEFINE HOW MANY COLUMNS TO MOVE ACROSS FROM THE CELL THAT CHANGED AND DO THE ACTIONS IN THE CODE BELOW ''''' SO IN THIS EXAMPLE WE'RE MOVING ACROSS 1 CELL TO B1 AND THEN 2 CELLS TO C1 ''''' SO TO GET TO AA1 AND AB2 WE'D DO i = 26 to 27 ''''' IF WE WANTED TO ACCESS AA1 ALL THE WAY THROUGH TO AZ1 WE'D DO i = 26 to 51 For i = 1 To 2 ''''' MOVE ACROSS i NUMBER OF CELLS FROM THE CELL THAT CHANGED With target.Offset(0, i) ''''' UNLOCK THE CELL .Locked = False '''''SET THE CONDITIONAL FORMATTING .FormatConditions.Add Type:=xlExpression, Formula1:="=ISBLANK(" & target.Offset(0, i).Address & ")" With .FormatConditions(.FormatConditions.Count) .SetFirstPriority .Interior.ColorIndex = 37 End With End With ''''' INCREASE i BY 1 AND LOOP TO AFFECT THE NEXT CELL Next i ''''' IF THE CELL CHANGED IS NOW 'NO' ElseIf target = "No" Then ''''' WE DEFINE HOW MANY COLUMNS TO MOVE ACROSS FROM THE CELL THAT CHANGED AND DO THE ACTIONS IN THE CODE BELOW For i = 1 To 2 ''''' MOVE ACROSS i NUMBER OF CELLS FROM THE CELL THAT CHANGED With target.Offset(0, i) ''''' SET THE CELL VALUE TO BLANK .Value = "" ''''' LOCK THE CELL .Locked = True ''''' REMOVE THE CONDITIONAL FORMATTING .FormatConditions.Delete ''''' ADD NEW CONDITIONAL FORMATTING HERE IF REQUIRED End With ''''' INCREASE i BY 1 AND LOOP TO AFFECT THE NEXT CELL Next i End If '''''PROTECT THE SHEET ActiveSheet.Protect End If End Sub Be sure to set locked to false in your A column where the drop down lists are or users won't be able to change the drop down value while the sheet is locked.
{ "language": "en", "url": "https://stackoverflow.com/questions/38142752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coding a guessing game in Jython Environment for Students ( JES ) I am trying to code a guessing game in JES using the pseudo code below: Generate a random single digit number Have the user guess the number If the user does not guess correctly give them a clue – indicate whether the number is even or odd and ask the user to guess again. If the user does not guess correctly, give another clue – indicate whether the number is a multiple of 3 and ask the user to guess again. If the user does not guess correctly, give another clue – indicate whether the number is less than or greater than 5 and ask the user to guess again. If the user does not guess correctly, display a box indicating the correct answer and the number of guesses the user made. If the user has guessed correctly, display a box indicating their guess is correct and how many guesses were required Show the amount of time the user played the guessing game. There are so many conditions I have no clue how to have the program ask each question, analyze the answer, and if the condition isn't met, to move on to the next one. When I run this code, it is just stuck in the loop of asking the user to guess and does not move through the if statements to give the user hints if they are incorrect. Below is my current code which obviously is incorrect. I am also aware there may be indenting issues in this post. from random import * from time import * def main(): a= randrange( 0, 11 ) start= clock() numberOfGuesses= 0 userGuess= requestInteger( " Please guess a single digit number " ) while userGuess != a: userGuess= requestInteger( " Please guess a single digit number " ) if userGuess % 2 == 0: showInformation( " Incorrect! Please try again. Hint: The number is even " ) if userGuess % 2 != 0: showInformation( " Incorrect! Please try again. Hint: The number is odd " ) if userGuess % 3 != 0: showInformation( " Incorrect! Please try again. Hint: The number is not a multiple of 3 " ) if userGuess > 5: showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " ) if userGuess < 5: showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " ) else: showInformation( " Correct " ) REVISED AND WORKING CODE from random import* from time import* def main (): a= randrange( 0, 10 ) start= clock() numberOfGuesses= 0 userGuess= requestNumber( " Please guess a single digit number " ) end= clock() elapsedTime= end - start if userGuess != a and userGuess % 2 == 0: showInformation( " Incorrect! Please try again. Hint: The number is even " ) userGuess= requestNumber( " Please guess a single digit number " ) numberOfGuesses= numberOfGuesses + 1 elif userGuess != a and a % 2 != 0: showInformation( " Incorrect! Please try again. Hint: The number is odd " ) userGuess= requestNumber( " Please guess a single digit number " ) numberOfGuesses= numberOfGuesses + 1 if userGuess != a and a % 3 != 0: showInformation( " Incorrect! Please try again. Hint: The number IS NOT a multiple of 3 " ) userGuess= requestNumber( " Please guess a single digit number " ) numberOfGuesses= numberOfGuesses + 1 if userGuess != a and a > 5: showInformation( " Incorrect! Please try again. Hint: The number is greater than 5 " ) userGuess= requestNumber( " Please guess a single digit number " ) numberOfGuesses= numberOfGuesses + 1 if userGuess != a and a < 5: showInformation( " Incorrect! Please try again. Hint: The number is less than 5 " ) userGuess= requestNumber( " Please guess a single digit number " ) numberOfGuesses= numberOfGuesses + 1 if userGuess == a: showInformation( " Correct! " ) showInformation( " The correct answer was" + " " + str(a) + " It took you " + str(elapsedTime) + " " + " seconds to complete this game " ) elif userGuess != a : showInformation( " Incorrect! " + " " + " The correct answer was" + " " + str(a) + " It took you " + str(elapsedTime) + " " + " seconds to complete this game " ) A: its stuck in the loop because user cant guess the same num that randnum genertes "while userguess !=a " it'll never be true
{ "language": "en", "url": "https://stackoverflow.com/questions/39676166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix SSL error in Perl LWP? #!/usr/bin/perl use strict; use warnings; use LWP::UserAgent; my $ua = LWP::UserAgent->new( agent => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4', ssl_opts => { verify_hostname => 0 } ); my $response = $ua->get('https://www.themoviedb.org'); gives an error message: Can't connect to www.themoviedb.org:443 SSL connect attempt failed error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure at /Library/Perl/5.18/LWP/Protocol/http.pm line 46. I use macOS Sierra LWP->VERSION 6.26 IO::Socket::SSL->VERSION 2.049 Net::SSLeay->VERSION 1.72 Net::SSLeay::OPENSSL_VERSION_NUMBER() 0x009081df LWP::UserAgent->VERSION 6.26 LWP::Protocol::https->VERSION 6.04 how to fix it? A: Net::SSLeay::OPENSSL_VERSION_NUMBER() 0x009081df This is OpenSSL 0.9.8, at least 7 years old, not supporting TLS 1.1 and TLS 1.2 and not supporting any ECDHE ciphers. Also, no support for SNI within IO::Socket::SSL for this old version of OpenSSL. Looking at the SSLLabs report for www.themoviedb.org you'll see: This site works only in browsers with SNI support. Thus, you'll need to upgrade your version of OpenSSL. Note that you also need to recompile Net::SSLeay afterwards and link it to the newer OpenSSL version.
{ "language": "en", "url": "https://stackoverflow.com/questions/45552150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Keras LSTM layer output and the output of a numpy LSTM implementation are similar but not same with the same weights and Input I modeled a two layered LSTM Keras model then I compared the output of the first LSTM layer with my simple python implementation of the LSTM layer by feeding in the same weights and Inputs. The results for the first sequence of a batch are similar but not same and from the second sequence the results deviates too far. Below is my keras model: For comparison of the Keras model I first created an intermediate layer where the intermediate layer outputs the result of the first layer with print(intermediate_output[0,0])for the first sequence and print(intermediate_output[0][1]) for the second sequence of the same batch then print(intermediate_output[0][127]) for the last sequence. inputs = Input(shape=(128,9)) f1=LSTM((n_hidden),return_sequences=True,name='lstm1')(inputs) f2=LSTM((n_hidden), return_sequences=False,name='lstm2')(f1) fc=Dense(6,activation='softmax',kernel_regularizer=regularizers.l2(lambda_loss_amount),name='fc')(f2) model2 = Model(inputs=inputs, outputs=fc) layer_name = 'lstm1' intermediate_layer_model = Model(inputs=model2.input, outputs=model2.get_layer(layer_name).output) intermediate_output = intermediate_layer_model.predict(X_single_sequence[0,:,:]) print(intermediate_output[0,0]) # takes input[0][9] print(intermediate_output[0][1]) # takes input[1][9] and hidden layer output of intermediate_output[0,0] print(intermediate_output[0][127]) Re-Implemented first layer of the same model: I defined LSTMlayer function where it does the same computation....after that weightLSTM loads the saved weights and x_t the same input sequence and later on h_t contains outputs for the next sequence. intermediate_out is a function corresponding to that of LSTM layer. def sigmoid(x): return(1.0/(1.0+np.exp(-x))) def LSTMlayer(warr,uarr, barr,x_t,h_tm1,c_tm1): ''' c_tm1 = np.array([0,0]).reshape(1,2) h_tm1 = np.array([0,0]).reshape(1,2) x_t = np.array([1]).reshape(1,1) warr.shape = (nfeature,hunits*4) uarr.shape = (hunits,hunits*4) barr.shape = (hunits*4,) ''' s_t = (x_t.dot(warr) + h_tm1.dot(uarr) + barr) hunit = uarr.shape[0] i = sigmoid(s_t[:,:hunit]) f = sigmoid(s_t[:,1*hunit:2*hunit]) _c = np.tanh(s_t[:,2*hunit:3*hunit]) o = sigmoid(s_t[:,3*hunit:]) c_t = i*_c + f*c_tm1 h_t = o*np.tanh(c_t) return(h_t,c_t) weightLSTM = model2.layers[1].get_weights() warr,uarr, barr = weightLSTM warr.shape,uarr.shape,barr.shape def intermediate_out(n,warr,uarr,barr,X_test): for i in range(0, n+1): if i==0: c_tm1 = np.array([0]*hunits, dtype=np.float32).reshape(1,32) h_tm1 = np.array([0]*hunits, dtype=np.float32).reshape(1,32) h_t,ct = LSTMlayer(warr,uarr, barr,X_test[0][0:1][0:9],h_tm1,c_tm1) else: h_t,ct = LSTMlayer(warr,uarr, barr,X_test[0][i:i+1][0:9],h_t,ct) return h_t # 1st sequence ht0 = intermediate_out(0,warr,uarr,barr,X_test) # 2nd sequence ht1 = intermediate_out(1,warr,uarr,barr,X_test) # 128th sequence ht127 = intermediate_out(127,warr,uarr,barr,X_test) The outputs of the keras LSTM layer from print(intermediate_output[0,0]) are as follows: array([-0.05616369, -0.02299516, -0.00801201, 0.03872827, 0.07286803, -0.0081161 , 0.05235862, -0.02240333, 0.0533984 , -0.08501752, -0.04866522, 0.00254417, -0.05269946, 0.05809477, -0.08961852, 0.03975506, 0.00334282, -0.02813114, 0.01677909, -0.04411673, -0.06751891, -0.02771493, -0.03293832, 0.04311397, -0.09430656, -0.00269871, -0.07775293, -0.11201388, -0.08271968, -0.07464679, -0.03533605, -0.0112953 ], dtype=float32) and the outputs of my implementation from print(ht0) are: array([[-0.05591469, -0.02280132, -0.00797964, 0.03681555, 0.06771626, -0.00855897, 0.05160453, -0.02309707, 0.05746563, -0.08988875, -0.05093143, 0.00264367, -0.05087904, 0.06033305, -0.0944235 , 0.04066657, 0.00344291, -0.02881387, 0.01696692, -0.04101779, -0.06718517, -0.02798996, -0.0346873 , 0.04402719, -0.10021093, -0.00276826, -0.08390114, -0.1111543 , -0.08879325, -0.07953986, -0.03261982, -0.01175724]], dtype=float32) The outputs from print(intermediate_output[0][1]): array([-0.13193817, -0.03231169, -0.02096735, 0.07571879, 0.12657365, 0.00067896, 0.09008797, -0.05597101, 0.09581321, -0.1696091 , -0.08893952, -0.0352162 , -0.07936387, 0.11100324, -0.19354928, 0.09691346, -0.0057206 , -0.03619875, 0.05680932, -0.08598096, -0.13047703, -0.06360915, -0.05707538, 0.09686109, -0.18573627, 0.00711019, -0.1934243 , -0.21811798, -0.15629804, -0.17204499, -0.07108577, 0.01727455], dtype=float32) print(ht1): array([[-1.34333193e-01, -3.36792655e-02, -2.06091907e-02, 7.15097040e-02, 1.18231244e-01, 7.98894180e-05, 9.03479978e-02, -5.85013032e-02, 1.06357656e-01, -1.82848617e-01, -9.50253978e-02, -3.67032290e-02, -7.70251378e-02, 1.16113290e-01, -2.08772928e-01, 9.89214852e-02, -5.82863577e-03, -3.79538871e-02, 6.01535551e-02, -7.99121782e-02, -1.31876275e-01, -6.66067824e-02, -6.15542643e-02, 9.91254672e-02, -2.00229391e-01, 7.51443207e-03, -2.13641390e-01, -2.18286291e-01, -1.70858681e-01, -1.88928470e-01, -6.49823472e-02, 1.72227081e-02]], dtype=float32) print(intermediate_output[0][127]): array([-0.46212202, 0.280646 , 0.514289 , -0.21109435, 0.53513926, 0.20116206, 0.24579187, 0.10773794, -0.6350403 , -0.0052841 , -0.15971565, 0.00309152, 0.04909453, 0.29789132, 0.24909772, 0.12323025, 0.15282209, 0.34281147, -0.2948742 , 0.03674917, -0.22213924, 0.17646286, -0.12948939, 0.06568322, 0.04172657, -0.28638166, -0.29086435, -0.6872528 , -0.12620741, 0.63395363, -0.37212485, -0.6649531 ], dtype=float32) print(ht127): array([[-0.47431907, 0.29702517, 0.5428258 , -0.21381126, 0.6053808 , 0.22849198, 0.25656056, 0.10378123, -0.6960949 , -0.09966939, -0.20533416, -0.01677105, 0.02512029, 0.37508538, 0.35703233, 0.14703275, 0.24901289, 0.35873395, -0.32249793, 0.04093777, -0.20691746, 0.20096642, -0.11741923, 0.06169611, 0.01019177, -0.33316574, -0.08499744, -0.6748463 , -0.06659956, 0.71961826, -0.4071832 , -0.6804066 ]], dtype=float32) The outputs from (print(intermediate_output[0,0]), print(h_t[0])) and (print(intermediate_output[0][1]), print(h_t1)) are similar...but the output from print(intermediate_output[0][127]) and print(h_t127) not same and both the algorithms are implemented on the same gpu... I saw the keras documentation and to me it seems that I am not doing anything wrong....Please comment on this and let me know that what else am I missing here ??
{ "language": "en", "url": "https://stackoverflow.com/questions/52026823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }