text
stringlengths
15
59.8k
meta
dict
Q: Datagridview mask values in column How can I "mask" the values of a datagridview in a windows forms application? In example, how can I limit the value in a column datagridviewtextboxcolumn so that is not bigger than a given number? (i.e. cell value in that column < 9.6) I build my datagridview programmatically at runtime. A: You can just use if() on CellEndEdit event handler A: The easiest way to do this, if possible, is to validate the value at the entity level. For instance, say we have the following simplified Foo entity; public class Foo { private readonly int id; private int type; private string name; public Foo(int id, int type, string name) { this.id = id; this.type = type; this.name = name; } public int Id { get { return this.id; } } public int Type { get { return this.type; } set { if (this.type != value) { if (value >= 0 && value <= 5) //Validation rule { this.type = value; } } } } public string Name { get { return this.name; } set { if (this.name != value) { this.name = value; } } } } Now we can bind to our DataGridView a List<Foo> foos and we will be effectively masking any input in the "Type" DataGridViewColumn. If this isn't a valid path, then simply handle the CellEndEdit event and validate the input.
{ "language": "en", "url": "https://stackoverflow.com/questions/6411511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replacing file for specific program The list of things I have: * *Windows 8. *A program ("foo") that executes another program ("bar"). *A "bar". *A replacement ("baz") for "bar". Now the "foo" executes the "bar", but I need it to execute the "baz", which will execute "bar" and do things with stdout. I guess I need to create a VFS, but I dunno how. This VFS should not work on child processes. What should I do? No, I can't replace "bar" with "baz" system-wide because the "bar" is WMI client.
{ "language": "en", "url": "https://stackoverflow.com/questions/31643101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UICollectionView self-sizing-cell on iOS 8 will crash with UIDynamic flowLayout and repeating call to _updateVisibleCellsNow I am trying to use the so called "self sizing cell" which means: * *set estimatedItemSize on flowLayout *overide preferredLayoutAttributesFittingAttributes in cell class Such as this: UICollectionView Self Sizing Cells with Auto Layout And I need dynamic effect like this:http://www.teehanlax.com/blog/implementing-a-bouncy-uicollectionviewlayout-with-uikit-dynamics/ It works fine without UIDynamic, but I need UIDynamic. As what I see, it will call the prepareLayout and layoutAttributesForElementsInRect until die, there will be too many _updateVisibleCellsNow waiting in line. I have no idea how to solve that, please help me in case u see. Or, if I am using those technologies in wrong way, please let me know. A: Two things worked for me: * *Make sure your collection view itself has layout constraints defined for placement within its superview. *I got this crash when the estimated size was larger than the final size. If I set the estimated size to a smaller value the crash stopped. A: If any size or frame position changed, it will trigger all cells' preferredLayoutAttributesFittingAttributes until all cells' frames did not change. The behavior flow is as the following: 1. Before self-sizing cell 2. Validated self-sizing cell again after other cells recalculated. 3. Did changed self-sizing cell If second steps can't get stable all cells' position and size, it will become infinite loop. Please reference my post here: UICollectionView Self Sizing Cells with Auto Layout
{ "language": "en", "url": "https://stackoverflow.com/questions/31025762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Swift 3: Handle Errors in URLSession Delegates I need to know how to catch errors (interruptions, primarily) in a URLsession with delegates. I have the following Swift function within a custom class, which downloads a small file to test download speeds: func testSpeed() { Globals.shared.dlStartTime = Date() Globals.shared.DownComplete = false let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) let task = session.downloadTask(with: url!) if Globals.shared.currentSSID == "" { Globals.shared.bandwidth = 0 Globals.shared.DownComplete = true session.invalidateAndCancel() NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil) } else { print("Running Task") task.resume() } } This class uses URLSessionDelegate and URLSessionDownloadDelegate. Here are the current delegates it calls: public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8) / 1000 let progress = (Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) * 100.0 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessUpdating"), object: nil, userInfo: ["progress" : progress]) } ^ That one monitors download progress and uses NotificationCenter to send the progress back to the view controller. public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("Done") if Globals.shared.DownComplete == false { let elapsed = Double( Date().timeIntervalSince(Globals.shared.dlStartTime)) Globals.shared.bandwidth = Int(Globals.shared.dlFileSize / elapsed) Globals.shared.DownComplete = true Globals.shared.dataUse! += (Globals.shared.dlFileSize! / 8000) } session.invalidateAndCancel() NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil) } ^ That one just calculates the speed once the download is finished, and sends the result to a global variable in another class. Unimportant. As of now, when I test my application, interrupting the download just hangs the app, because it keeps waiting for the processFinished NC call, which obviously never comes. Is there another delegate I should add to catch that interruption, or am I missing something more obvious? A: You can use urlSession:task:didCompleteWithError delegate method
{ "language": "en", "url": "https://stackoverflow.com/questions/43173259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trouble Replacing Fonts in PowerPoint Presentation I cannot change (i.e., "replace") two of the fonts used in a presentation I inherited that are giving issues to our users. I have the presentation set to embed fonts, but as I do not have the one in question, I can't fix it like I normally would (i.e., usually having the font in question and opening the file and closing it again embeds the fonts and there are no more issues.) The font in question in this case is called "Times" (not "Times New Roman", just "Times"), which I believe is an ancient PostScript font, if I'm not mistaken, which would be an issue since, from what I understand, PowerPoint does not support PostScript fonts. At any rate, I want to replace the font with "Arial", which I know is usually easily accomplished with Replace > Replace Font . . . however, it's not taking for some reason in this file. I'll tell PowerPoint to replace it, it seems to do something, and then . . . no change. SO. . . I headed to Google and tried a few things (One possibly mentioned by PPTools was converting the file to HTML and back, which is said to fix (i.e., "remove") some Asian and other unsupported fonts from presentations. But as I couldn't figure out how to save a presentation as a Web Page in O365 offline (PowerPoint 2019), it was a no go (there appears to be no option that I can find to either "Save As" or "Export" HTML or a Web Page, as was recommended. I therefore started looking VBA. My first try was this, as I found was originally used to change Far East Fonts to Arial: Sub ChgFarEastFontsToArial() Dim oSh As Shape Dim oSl As Slide For Each oSl In ActivePresentation.Slides For Each oSh In oSl.Shapes If oSh.HasTextFrame Then oSh.TextFrame.TextRange.Font.NameFarEast = "Arial" End If Next Next For Each oSh In ActivePresentation.SlideMaster.Shapes If oSh.HasTextFrame Then oSh.TextFrame.TextRange.Font.NameFarEast = "Arial" End If Next If ActivePresentation.HasTitleMaster Then For Each oSh In ActivePresentation.TitleMaster.Shapes If oSh.HasTextFrame Then oSh.TextFrame.TextRange.Font.NameFarEast = "Arial" End If Next End If End Sub It runs without error when I don't change anything, but since I wasn't actually looking to change Far East fonts, it didn't help me. My next try was this: Sub ReplaceFontToArial() Dim objSingleWord As Range Dim objDoc As Presentation Set objDoc = ActivePresentation With objDoc For Each objSingleWord In .Words If objSingleWord.Font.Name = "Times" Then objSingleWord.Font.Name = "Arial" End If Next End With End Sub But, it errors out highlighting ObjSingleWord As Range and stating, Compile error: User-defined type not defined. Then, upon a suggestion from the Microsoft VBA reference docs, I tried: Sub ReplaceFontToArial() With Application.ActivePresentation .Fonts.Replace Original:="Times", Replacement:="Arial" End With End Sub But this errors out with a Run-time error '424': Object required. I'm about out of thoughts to fix this problem. Any thoughts on how I can change out this crazy font would be amazing!! (Also advice on why my scripts above are not working would also be helpful.) FYI, in case it helps, fonts that will not be replaced are: Times Unsupported font file format (AAT), Times Bold Unsupported font file format (AAT), Times Italic Unsupported font file format (AAT), Times Bold Italic Unsupported font file format (AAT), and Noto Sans Symbols. A: Times is a Mac font (AAT is Apple Advanced Typography). My preferred technique with stubborn fonts is to change the file ending to .zip, unzip the file to OOXML, then use a text editor like NotePad++ to run a find and replace on all files. Find: typeface="Times" Replace: typeface="Arial" Then rezip and rename back to .pptx. Make a copy of the file to experiment. This method also works great on changing PowerPoint language settings. A: Both 'Replace font' and 'OOOXML transfer' didn't work for me. For people with Mac OS: open the pptx file with Keynote. A dialog asks to replace missing fonts. Simply replace the ones causing trouble. Then export to Powerpoint. It should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/57618249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with Github Pages - deleted remote and re-uploaded from local I deleted from remote and re-uploaded the code for my github webpage (branch gh-pages) i was hosting my site on with the following: git push origin :gh-pages git push origin gh-pages I am now getting a 404 error. My repo is about 920MB (under the 1GB Github Page limit). Anyone have an idea on what could be going wrong? A: Note that you could change your repo settings to pick up your pages from a docs folder in the master branch: that could be easier to maintain. But regarding gh-pages, check if one of the answers mentioned in "How to fix page 404 on Github Page?" applies, in particular regarding the case of the files (lower/upercase)
{ "language": "en", "url": "https://stackoverflow.com/questions/43356163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: RecyclerView OnClicklistener is unresponsive Firstly I know there are hundreds of these questions but the answers have not solved my problem. I suspect it's something small I'm missing, basically I've added a RecyclerView and need to start a new activity when a card is clicked. I've been following this tutorial and it's been smooth sailing up until this point. https://guides.codepath.com/android/using-the-recyclerview This is the Recycler <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/bgImg" android:scaleType="centerCrop"/> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/RV" /> </FrameLayout> This is the card <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="wrap_content" card_view:cardCornerRadius="4dp" android:layout_margin="5dp" android:clickable="true" android:background="?android:attr/selectableItemBackground"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/vendor_image2" android:layout_width="fill_parent" android:layout_height="240dp" android:padding="5dp" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/vendor_image2" > <TextView android:id="@+id/vendor_name2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:textStyle="bold" android:layout_marginLeft="10dp" android:layout_marginTop="5dp" android:paddingBottom="5dp"/> <TextView android:id="@+id/vendor_content2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="7dp" android:layout_toEndOf="@+id/vendor_name2" android:textColor="@color/text_col" android:paddingBottom="5dp" /> <TextView android:id="@+id/vendor_suburb2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="italic" android:textColor="@color/text_col" android:layout_below="@+id/vendor_name2" android:layout_marginLeft="10dp" /> <RatingBar android:id="@+id/MyRating2" style="?android:attr/ratingBarStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/vendor_suburb2" android:layout_marginLeft="10dp" android:isIndicator="true" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:numStars="5" android:textColor="@android:color/black" android:rating="3.5" android:stepSize="0.1" /> </RelativeLayout> </LinearLayout> </android.support.v7.widget.CardView> And finally the Adapter and Handler import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.iconiccode.android.guestloc8tor.SQL.DatabaseHandler; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import org.json.JSONException; import org.json.JSONObject; import java.util.List; public class VendorRecycleAdapter extends RecyclerView.Adapter<VendorRecycleAdapter.VendorHolder> { public List<Vendor> vendorList; private DatabaseHandler dbHandler = new DatabaseHandler(MyApp.getContext()); private Vendor currentVendor; int cate; Activity thiscontext; public VendorRecycleAdapter(Activity context, int Cate) { this.cate=Cate; this.thiscontext=context; } @Override public VendorHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(thiscontext); //View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2, parent, false); View view = inflater.inflate(R.layout.vendor_list_cards,parent,false); return new VendorHolder(view); } @Override public void onBindViewHolder(VendorHolder holder, int position) { vendorList = dbHandler.getVendorData(cate); currentVendor = vendorList.get(position); // Get the image string from the Vendor object String vendorImage = currentVendor.getImage(); Log.e("Vendor Adapter Image", vendorImage); // Get the name string from the Vendor object String vendorName = currentVendor.getCompanyName(); Log.e("Vendor Adapter Name", vendorName); // Get the content string from the Vendor object String vendorContent = currentVendor.getContent(); // Get the location string from the Vendor object String vendorSuburb = currentVendor.getSuburb(); Log.e("Vendor Adapter Suburb", vendorSuburb); // Find the TextView with view ID vendor_name // Display the name of the current vendor in that TextView holder.Vvendor_name.setText(vendorName); holder.Vvendor_image.setImageResource(R.drawable.loading); ImageLoader imageLoader; DisplayImageOptions options; imageLoader = ImageLoader.getInstance(); String url = vendorImage; imageLoader.init(ImageLoaderConfiguration.createDefault(MyApp.getContext())); options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.drawable.loading) .showImageOnFail(R.drawable.b4f29385) .resetViewBeforeLoading(true).cacheOnDisk(true) .imageScaleType(ImageScaleType.EXACTLY) .bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true) .displayer(new FadeInBitmapDisplayer(300)).build(); imageLoader.displayImage(url, holder.Vvendor_image); // Find the TextView with view ID vendor_content holder.Vvendor_content.setText(vendorContent); holder.Vvendor_suburb.setText(vendorSuburb); } @Override public int getItemCount() { vendorList = dbHandler.getVendorData(cate); return vendorList.size(); } public class VendorHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public ImageView Vvendor_image; public TextView Vvendor_name,Vvendor_content,Vvendor_suburb; public RatingBar Vrating; public VendorHolder(View itemView) { //These pull as null super(itemView); Vvendor_image = (ImageView)itemView.findViewById(R.id.vendor_image2); Vvendor_name = (TextView)itemView.findViewById(R.id.vendor_name2); Vvendor_content =(TextView)itemView.findViewById(R.id.vendor_content2); Vvendor_suburb = (TextView)itemView.findViewById(R.id.vendor_suburb2); Vrating = (RatingBar) itemView.findViewById(R.id.MyRating2); } @Override public void onClick(View v) { // int position = getAdapterPosition(); // currentVendor = vendorList.get(position); Intent intent = new Intent(thiscontext,VendorDetailsActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); String Category = Integer.toString(cate); JSONObject message = currentVendor.getAllData(); try { intent.putExtra("IMAGE", message.getString("IMAGE")); intent.putExtra("URL", message.getString("URL")); intent.putExtra("CONTENT", message.getString("CONTENT")); intent.putExtra("COMPANY_NAME", message.getString("COMPANY_NAME")); intent.putExtra("TEL", message.getString("TEL")); intent.putExtra("BOOKING_URL", message.getString("BOOKING_URL")); intent.putExtra("LAT", message.getString("LAT")); intent.putExtra("LON", message.getString("LON")); intent.putExtra("STREET", message.getString("STREET")); intent.putExtra("SUBURB", message.getString("SUBURB")); intent.putExtra("PROVINCE", message.getString("PROVINCE")); intent.putExtra("CITY", message.getString("CITY")); intent.putExtra("CAT",Category); } catch (JSONException json) { Log.e("ERROR", json.getMessage()); } thiscontext.startActivity(intent); } } } Any help would be greatly appreciated. Thanks A: I think you just forgot to set the onClickListener in your ViewHolder constructor: public VendorHolder(View itemView) { //These pull as null super(itemView); Vvendor_image = (ImageView)itemView.findViewById(R.id.vendor_image2); Vvendor_name = (TextView)itemView.findViewById(R.id.vendor_name2); Vvendor_content =(TextView)itemView.findViewById(R.id.vendor_content2); Vvendor_suburb = (TextView)itemView.findViewById(R.id.vendor_suburb2); Vrating = (RatingBar) itemView.findViewById(R.id.MyRating2); // If it should be triggered only when clicking on a specific view, replace itemView with the view you want. itemView.setOnClickListener(this); }
{ "language": "en", "url": "https://stackoverflow.com/questions/42448803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get Django to recognize a custom template tag? My project directory looks like this. settings_value.py has a template tag, named 'settings_value' in it. In my settings.py I added 'itslogical.templatetags' to INSTALLED_APPS. I try to use it in logicalhp/home.html, but it says the tag doesn't exist. I'm using code from this answer (I changed the name from 'value_from_settings' to 'settings_value'). . ├── internetparse │   └── ... ├── itslogical │   ├── settings.py │   ├── templates │   │   └── itslogical │   │   └── base.html │   └─── templatetags │      ├── __init__.py │      └── settings_value.py ├── logicalhp │   ├── templates │   │   └── logicalhp │   │   └── home.html │   └── views.py └── manage.py Let me know if you need anything else. What am I missing here? Edit: added code and updated error. This is based on @Dan's answer. 500 ERROR: 'settings_value' is not a valid tag library: Template library settings_value not found Template library settings_value not found, tried django.templatetags.settings_value ... #!/usr/bin/env python from django import template from django.conf import settings # Include settings from here in templates register = template.Library() # settings value @register.tag def settings_value(parser, token): try: # split_contents() knows not to split quoted strings. tag_name, var = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0] return ValueFromSettings(var) class ValueFromSettings(template.Node): def __init__(self, var): self.arg = template.Variable(var) def render(self, context): return settings.__getattr__(str(self.arg)) A: You shouldn't add the templatetags directory to installed apps. You should put the templatetags directory inside an existing app, and add that to installed apps. A: Try to move templatetags folder to logicalhp A: Part of the problem was a typo in my settings.py (wrote the 'logicalhp.templatetags' when it was in 'itslogical'). The larger problem was that it was trying to get the attribute "STATIC_URL" from my settings. It included the quotes, so it was effectively settings.__getattr__('"STATIC_URL"'). To fix it, I added a strip. return settings.__getattr__(str(self.arg)) #before return settings.__getattr__(str(self.arg).strip('"')) #after (By the way, it's not like you can omit the quotes in the template; else it think's its a variable. )
{ "language": "en", "url": "https://stackoverflow.com/questions/14113957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Express, fetching data from pons API I am new to express and I try to fetch data from Pons API: https://en.pons.com/p/files/uploads/pons/api/api-documentation.pdf here is my file: const express = require("express"); const fetch = require("node-fetch"); const app = express(); app.get("/", async (req, res, next) => { const answer = await fetch( "https://api.pons.com/v1/dictionary?q=dom&l=depl", { method: "get", headers: { "X-Secret": "XXX", }, } ) .then((res) => res.json()) .then((json) => console.log(json)) .catch((err) => console.log(err)); }); app.listen(5000); In my console I only see this: [ { lang: 'pl', hits: [ [Object], [Object] ] }, { lang: 'de', hits: [ [Object] ] } ] I would like to get translations in german for the word "dom". Can somebody please tell me what do I have wrong? A: You are not doing anything wrong. You just need some additional code to access the Objects in the response, which is a regular JavaScript object, but console.log() is just not printing it all. The translation you are looking for is contained somewhere in there. Just be aware that there can be multiple responses as the same word can have different meanings or can be of different word classes (noun, verb, adjective, etc.) What you can do to get a better understanding of the objects is to use JSON.stringify() to print the whole structure. For example: .then((json) => console.log(JSON.stringify(json, null, 2))) Note: The third paramter 2 means that an indentation of 2 spaces will be used. A: My approach to the Pons Api on the server const utils = require('./lib/utils') app.get("/dic/:word", (req, res, next) => { utils.getLastLine('api_key', 1).then(key => { key = key.split('=')[1] var word = req.params.word var translate = 'dees' return fetch( `https://api.pons.com/v1/dictionary?q=${word}&l=${translate}`,{ headers: { "X-Secret": key }} ) .then(res => res.json()).then(json => { var base = json[0].hits[0].roms[0] var wclass = base.wordclass var arab = base.arabs[0] var trans = arab.translations var firsttrans = trans[0].target var nrtrans = arab.translations.length res.json({ firsttrans, wclass, nrtrans, trans }) }) }); }); Requirements: * *Get a Pons Api Key *Be familiar with fetch Api - recommended server-side Further/Limits: * *It is a nested fetch *See a live example *Code example is for development, not for production: * *no server error catching in case of * *no input *non-existing word *not all Api results are considered, just the first hit
{ "language": "en", "url": "https://stackoverflow.com/questions/64101625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: angularjs: add show less button logic - fiddle included I found a fiddle that show how to add a button to show more records using a angularJS, it is pretty neat. I am trying to add a show less button, but I am not getting right the formula. I added and opposite of what the show more code does, but I am missing a pieces. I would like to get help in learning how to accomplish this. fiddle: demo code snippet: //show more functionality var pagesShown = 1; var pageSize = 3; $scope.paginationLimit = function(data) { return pageSize * pagesShown; }; $scope.hasMoreItemsToShow = function() { return pagesShown < ($scope.datalists.length / pageSize); }; $scope.showMoreItems = function() { pagesShown = pagesShown + 1; }; $scope.hasLessItemsToShow = function() { return pagesShown >= ($scope.datalists.length / pageSize); }; $scope.showLessItems = function() { pagesShown = pagesShown - 1; }; Thank you very much. A: The code for show less should probably (depending on your requirement) be a lot simpler. $scope.hasLessItemsToShow = function() { return pagesShown > 1; }; So, as long as you are showing more than one page of data, you can "go back", or show less.
{ "language": "en", "url": "https://stackoverflow.com/questions/32762193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Record video raw from Tango with Tango Ros Streamer? I want to record data from Tango with Tango Ros Streamer and save them into a bag by command: rosbag record -a When i visualize sequence of image in this bag, i realize the frame rate is extremely slow. Do you have any idea to modify or fix frame rate with this application? A: The theoretical wifi bandwidth is 11 megabits. * *One 1280x720 YUV image: 1280*720*1.5 = 1.3824 megabits *One 24fps stream of these images: 24*1.3824 megabits = 33.18 megabits So you cannot transmit the native stream of RGB images over WiFi. That is why in the source code of the Tango Ros Streamer app you will see constexpr double COLOR_IMAGE_RATE = 8.; // in Hz. You can either modify the code of this app to decrease the size of the images and increase the COLOR_IMAGE_RATE, either you want the full resolution and you can create an application which saves all the images on the device.
{ "language": "en", "url": "https://stackoverflow.com/questions/45037488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encoding error in Pandas DataFrame In pandas dataframe, when writing to csv you can encode a file easily by adding a argument encoding='utf-8' However there is an issue with this. If you are getting data directly from a database and placing it directly into a dataframe, when writing the csv, even with encoding you get an error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-25: ordinal not in range(128) So really some decoding/encoding needs to happen prior to placing the data into a datframe. Does anyone have a simple solution to this? A: If you are creating a DataFrame from a database, you can use read_sql: df = pd.read_sql('SELECT * FROM foo', con) Here con is a connection object, e.g. created using sqlite3 or mysqldb.
{ "language": "en", "url": "https://stackoverflow.com/questions/21485212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UITableViewCell dequeue. Cancel async sqlite call On a tableview, i'm loading (async) data from a sqlite DB(using fmdb). (in cellforrow...) My problem are that if the user scroll very fast, I get a lot of query pending\not cancelled. how can I cancel the query when dequeue cell? Thanks for your help
{ "language": "en", "url": "https://stackoverflow.com/questions/32014962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why python hash_ring is so slow? well,I found hash_ring.MemcacheRing's so slow that rate test cant beat directly db access while,I replace it with memcache.Client,rate test's back to normal rps is tested in multithreaded environment memcache.Client rps2500 hash_ring.MemcacheRing rps 600 directly db access:rps960 I use hotshot to track hash_ring.MemcacheRing,I found there's definitely something wrong with hash_ring,u can find that hash_ring cost too much cpu as expected in the following profile data collected hotshot profile data's collected in single threaded environment ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.066 0.000 8.297 0.001 Memcached.py:16(__getitem__) 10000 0.262 0.000 6.544 0.001 build/bdist.linux-x86_64/egg/memcache.py:818(_unsafe_get) 1 0.000 0.000 0.000 0.000 /usr/local/Python-2.6.4/lib/python2.6/socket.py:180(__init__) 20000 0.064 0.000 0.064 0.000 build/bdist.linux-x86_64/egg/memcache.py:310(_statlog) 80000 0.118 0.000 0.118 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:148() 10000 0.148 0.000 8.168 0.001 build/bdist.linux-x86_64/egg/memcache.py:812(_get) 20000 0.086 0.000 0.157 0.000 build/bdist.linux-x86_64/egg/memcache.py:1086(_get_socket) 30000 10.539 0.000 10.539 0.000 build/bdist.linux-x86_64/egg/memcache.py:1118(readline) 10000 0.102 0.000 0.102 0.000 build/bdist.linux-x86_64/egg/memcache.py:1142(recv) 20000 0.243 0.000 0.243 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:156(_hash_digest) 20000 0.103 0.000 0.103 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:124(distinct_filter) 10000 0.167 0.000 0.269 0.000 build/bdist.linux-x86_64/egg/memcache.py:965(_recv_value) 1 0.148 0.148 15.701 15.701 Memcached.py:25(foo) 10000 0.236 0.000 5.409 0.001 build/bdist.linux-x86_64/egg/memcache.py:953(_expectvalue) 20002 0.336 0.000 0.336 0.000 :1(settimeout) 10000 0.061 0.000 7.207 0.001 build/bdist.linux-x86_64/egg/memcache.py:541(set) 20000 0.116 0.000 0.606 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:141(gen_key) 20000 0.279 0.000 1.680 0.000 build/bdist.linux-x86_64/egg/hash_ring/memcache_ring.py:20(_get_server) 40000 0.346 0.000 1.236 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:111(iterate_nodes) 10000 0.144 0.000 7.146 0.001 build/bdist.linux-x86_64/egg/memcache.py:771(_set) 20000 0.129 0.000 0.247 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:150(_hash_val) 20000 0.098 0.000 0.433 0.000 build/bdist.linux-x86_64/egg/memcache.py:1111(send_cmd) 10000 0.063 0.000 8.231 0.001 build/bdist.linux-x86_64/egg/memcache.py:857(get) 10000 0.049 0.000 7.256 0.001 Memcached.py:13(__setitem__) 20000 0.144 0.000 5.510 0.000 build/bdist.linux-x86_64/egg/memcache.py:1135(expect) 20000 0.181 0.000 0.787 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:92(get_node_pos) 20000 0.070 0.000 0.070 0.000 build/bdist.linux-x86_64/egg/memcache.py:1070(_check_dead) 10000 0.084 0.000 0.084 0.000 build/bdist.linux-x86_64/egg/memcache.py:725(_val_to_store_info) 20000 0.068 0.000 0.225 0.000 build/bdist.linux-x86_64/egg/memcache.py:1076(connect) 20000 1.036 0.000 1.036 0.000 build/bdist.linux-x86_64/egg/memcache.py:1000(check_key) 10000 0.216 0.000 5.702 0.001 build/bdist.linux-x86_64/egg/memcache.py:777(_unsafe_set) 0 0.000 0.000 profile:0(profiler) and the following is memcache.Client's profile data ncalls tottime percall cumtime percall filename:lineno(function) 10000 0.064 0.000 8.022 0.001 Memcached.py:16(__getitem__) 10000 0.263 0.000 6.885 0.001 build/bdist.linux-x86_64/egg/memcache.py:818(_unsafe_get) 1 0.000 0.000 0.000 0.000 /usr/local/Python-2.6.4/lib/python2.6/socket.py:180(__init__) 20000 0.069 0.000 0.069 0.000 build/bdist.linux-x86_64/egg/memcache.py:310(_statlog) 10000 0.127 0.000 7.897 0.001 build/bdist.linux-x86_64/egg/memcache.py:812(_get) 20000 0.091 0.000 0.164 0.000 build/bdist.linux-x86_64/egg/memcache.py:1086(_get_socket) 30000 11.074 0.000 11.074 0.000 build/bdist.linux-x86_64/egg/memcache.py:1118(readline) 10000 0.098 0.000 0.098 0.000 build/bdist.linux-x86_64/egg/memcache.py:1142(recv) 20000 0.259 0.000 0.568 0.000 build/bdist.linux-x86_64/egg/memcache.py:329(_get_server) 1 0.149 0.149 15.036 15.036 Memcached.py:25(foo) 10000 0.236 0.000 5.645 0.001 build/bdist.linux-x86_64/egg/memcache.py:953(_expectvalue) 20002 0.351 0.000 0.351 0.000 :1(settimeout) 10000 0.064 0.000 6.814 0.001 build/bdist.linux-x86_64/egg/memcache.py:541(set) 10000 0.124 0.000 6.751 0.001 build/bdist.linux-x86_64/egg/memcache.py:771(_set) 20000 1.039 0.000 1.039 0.000 build/bdist.linux-x86_64/egg/memcache.py:1000(check_key) 20000 0.092 0.000 0.442 0.000 build/bdist.linux-x86_64/egg/memcache.py:1111(send_cmd) 10000 0.061 0.000 7.958 0.001 build/bdist.linux-x86_64/egg/memcache.py:857(get) 10000 0.050 0.000 6.864 0.001 Memcached.py:13(__setitem__) 20000 0.148 0.000 5.812 0.000 build/bdist.linux-x86_64/egg/memcache.py:1135(expect) 20000 0.073 0.000 0.073 0.000 build/bdist.linux-x86_64/egg/memcache.py:1070(_check_dead) 10000 0.087 0.000 0.087 0.000 build/bdist.linux-x86_64/egg/memcache.py:725(_val_to_store_info) 20000 0.072 0.000 0.236 0.000 build/bdist.linux-x86_64/egg/memcache.py:1076(connect) 20000 0.072 0.000 0.072 0.000 build/bdist.linux-x86_64/egg/memcache.py:57(cmemcache_hash) 10000 0.218 0.000 5.905 0.001 build/bdist.linux-x86_64/egg/memcache.py:777(_unsafe_set) 0 0.000 0.000 profile:0(profiler) 10000 0.156 0.000 0.255 0.000 build/bdist.linux-x86_64/egg/memcache.py:965(_recv_value) and profile data's following ncalls tottime percall cumtime percall filename:lineno(function) 20000 2.278 0.000 4.260 0.000 build/bdist.linux-x86_64/egg/memcache.py:1000(check_key) 640000 1.624 0.000 1.624 0.000 :0(ord) 20000 0.658 0.000 1.445 0.000 build/bdist.linux-x86_64/egg/memcache.py:329(_get_server) 100010 0.477 0.000 0.477 0.000 :0(len) 30000 0.460 0.000 0.827 0.000 build/bdist.linux-x86_64/egg/memcache.py:1118(readline) 110000 0.414 0.000 0.414 0.000 :0(isinstance) 20000 0.412 0.000 0.412 0.000 :0(sendall) 10000 0.349 0.000 1.974 0.000 build/bdist.linux-x86_64/egg/memcache.py:818(_unsafe_get) 10000 0.344 0.000 0.633 0.000 build/bdist.linux-x86_64/egg/memcache.py:725(_val_to_store_info) 10000 0.344 0.000 2.006 0.000 build/bdist.linux-x86_64/egg/memcache.py:777(_unsafe_set) 10000 0.325 0.000 0.624 0.000 build/bdist.linux-x86_64/egg/memcache.py:965(_recv_value) 50000 0.233 0.000 0.233 0.000 :0(find) 20000 0.200 0.000 0.808 0.000 build/bdist.linux-x86_64/egg/memcache.py:1135(expect) 10000 0.194 0.000 5.292 0.001 build/bdist.linux-x86_64/egg/memcache.py:812(_get) 20000 0.190 0.000 0.357 0.000 build/bdist.linux-x86_64/egg/memcache.py:1076(connect) 10000 0.185 0.000 4.771 0.000 build/bdist.linux-x86_64/egg/memcache.py:771(_set) 10000 0.173 0.000 0.187 0.000 build/bdist.linux-x86_64/egg/memcache.py:1142(recv) 10000 0.163 0.000 0.400 0.000 build/bdist.linux-x86_64/egg/memcache.py:953(_expectvalue) 20000 0.152 0.000 0.564 0.000 :1(sendall) 20000 0.147 0.000 0.711 0.000 build/bdist.linux-x86_64/egg/memcache.py:1111(send_cmd) 20000 0.142 0.000 0.232 0.000 build/bdist.linux-x86_64/egg/memcache.py:57(cmemcache_hash) ncalls tottime percall cumtime percall filename:lineno(function) 20000 2.679 0.000 4.921 0.000 build/bdist.linux-x86_64/egg/memcache.py:1000(check_key) 640000 2.125 0.000 2.125 0.000 :0(ord) 20000 0.636 0.000 2.887 0.000 build/bdist.linux-x86_64/egg/hash_ring/memcache_ring.py:20(_get_server) 20000 0.582 0.000 1.673 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:92(get_node_pos) 30000 0.565 0.000 0.979 0.000 build/bdist.linux-x86_64/egg/memcache.py:1118(readline) 20000 0.345 0.000 0.630 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:156(_hash_digest) 40000 0.328 0.000 2.065 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:111(iterate_nodes) 20003 0.294 0.000 0.294 0.000 :0(recv) 10000 0.287 0.000 1.119 0.000 build/bdist.linux-x86_64/egg/memcache.py:953(_expectvalue) 10000 0.176 0.000 4.437 0.000 build/bdist.linux-x86_64/egg/memcache.py:771(_set) 10000 0.175 0.000 1.697 0.000 build/bdist.linux-x86_64/egg/memcache.py:818(_unsafe_get) 10000 0.160 0.000 5.899 0.001 build/bdist.linux-x86_64/egg/memcache.py:812(_get) 20000 0.157 0.000 1.051 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:141(gen_key) 10000 0.148 0.000 0.251 0.000 build/bdist.linux-x86_64/egg/memcache.py:965(_recv_value) 20000 0.144 0.000 0.264 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:150(_hash_val) 90000 0.122 0.000 0.122 0.000 :0(isinstance) 50000 0.120 0.000 0.120 0.000 :0(find) 80000 0.120 0.000 0.120 0.000 build/bdist.linux-x86_64/egg/hash_ring/hash_ring.py:148()
{ "language": "en", "url": "https://stackoverflow.com/questions/10361902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I estimate gaussian (mixture) density from a set of weighted samples? Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm. Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem? A: I've just had the same problem. Even though the post is older, it might be interesting to someone else. honk's answer is in principle correct, it's just not immediate to see how it affects the implementation of the algorithm. From the Wikipedia article for Expectation Maximization and a very nice Tutorial, the changes can be derived easily. If $v_i$ is the weight of the i-th sample, the algorithm from the tutorial (see end of Section 6.2.) changes so that the $gamma_{ij}$ is multiplied by that weighting factor. For the calculation of the new weights $w_j$, $n_j$ has to be divided by the sum of the weights $\sum_{i=1}^{n} v_i$ instead of just n. That's it... A: You can calculate a weighted log-Likelihood function; just multiply the every point with it's weight. Note that you need to use the log-Likelihood function for this. So your problem reduces to minimizing $-\ln L = \sum_i w_i \ln f(x_i|q)$ (see the Wikipedia article for the original form). A: Just a suggestion as no other answers are sent. You could use the normal EM with GMM (OpenCV for ex. has many wrappers for many languages) and put some points twice in the cluster you want to have "more weight". That way the EM would consider those points more important. You can remove the extra points later if it does matter. Otherwise I think this goes quite extreme mathematics unless you have strong background in advanced statistics. A: I was looking for a similar solution related to gaussian kernel estimation (instead of a gaussian mixture) of the distribution. The standard gaussian_kde does not allow that but I found a python implementation of a modified version here http://mail.scipy.org/pipermail/scipy-user/2013-May/034580.html A: I think this analysis can be possibly be done via the pomegranate (see Pomegranate docs page) that supports a weighted Gaussian Mixture Modeling. According to their doc: weights : array-like, shape (n_samples,), optional The initial weights of each sample in the matrix. If nothing is passed in then each sample is assumed to be the same weight. Default is None. Here is a Python snippet I wrote that can possibly help you do a weighted GMM: from pomegranate import * import numpy as np # Generate some data N = 200 X_vals= np.random.normal(-17, 0.9, N).reshape(-1,1) # Needs to be in Nx1 shape X_weights = w_function(X_vals) # Needs to be in 1xN shape or alternatively just feed in the weight data you have pmg_model = GeneralMixtureModel.from_samples([NormalDistribution], 2, X_vals, weights=X_weights.T[0]) [Figure] Observed versus weighted distribution of the data we are analyzing [Figure] GMM of the weighted data
{ "language": "en", "url": "https://stackoverflow.com/questions/2492674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Get the XY coordinates of a `img` element I have an icon <img src="res/img/b_drop.png" id="drop_1" />. When this icon is clicked, I need a prompt to appear at some coordinates that I will calculate by the S and Y points of my #drop_. What can I do to calculate these two points using jQuery? A: offset could be what you want $('#drop_1').on('click', function(){ var offset = $(this).offset(); alert('top - ' + offset.top + "\n left - " + offset.left); }); This will alert the position of the element from the top and left of the document jQuery offset() Here is a Demo A: Relatively parent element: $('#drop_1').position().left // x coord $('#drop_1').position().top // y coord Relatively page: $('#drop_1').offset().left // x coord $('#drop_1').offset().top // y coord
{ "language": "en", "url": "https://stackoverflow.com/questions/17858423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read text file from Native code in Android project I searched for the similar information and can't find a clear solution. So I make inquiry here. I like to read a text file from my native code. I have two approaches. (1)First file path is taken in Java and pass to native code as In Java File cascadeDir = getDir("cascade", Context.MODE_PRIVATE); String att = "attr.names"; String tree = "face.tree"; File mAttClass = new File(cascadeDir, att); File mTree = new File(cascadeDir, tree); mNativeDetector.CreateNativeObject_Tree(mAttClass.getAbsolutePath(), mTree.getAbsolutePath()); mAttClass.delete(); mTree.delete(); In Native C void GetNames(char *Fn) /* --------- */ { LOGD("Enter getnames \n"); FILE *Nf, *fopen(); char Buffer[1000]; DiscrValue v; int AttCeiling=100, ClassCeiling=100, ValCeiling; /* Open names file */ if ( ! ( Nf = fopen(Fn, "r") ) ) Error(0, Fn, ""); } This method make error as "Can't open file from /data/data/com.test.pck/app_cascade/attr.names". (2) The second method is , the file (attr.names) is located in the same folder as source file in JNI folder. Then load using if ( ! ( Nf = fopen(Fn, "r") ) ) Error(0, Fn, ""); The error is "Can't open file from attr.names". How can I read that text file from my native C code. EDIT 1: As discussions below. I need to use openRawResources() to get a file descriptor, offset, and size. I tried to implement as follow. int rID = resources.getIdentifier("com.test.pkg:raw/"+attr.names, null, null); InputStream is = resources.openRawResource(rID); File cascadeDir = getDir("cascade", Context.MODE_PRIVATE); String temp; File mCascadeFile = null; temp = xmlarray[l] + ".xml"; mCascadeFile = new File(cascadeDir, temp); FileOutputStream os = new FileOutputStream(mCascadeFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); os.close(); Now it works. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/26478203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do i nest another cmdlet in foreach loop in powershell For each userID I want to get the date created for that user. This is what I use for single user and this works. (Get-AzureADUserExtension -ObjectId "00444a60-3468-48e7-97d7-69f08aac346d").Get_Item("createdDateTime") But I want a loop. I tried below Get-AzureADUser -All:$true | ForEach-Object{ $_.ObjectId $_.UserPrincipalName $_ | Add-Member -MemberType NoteProperty -Name "CreatedDateTime" -Value (Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime") } But then I'm asked to put a value (which I don't want) and when I do so I get an error -Value : The term '-Value' is not recognized as the name of a cmdlet[...] I also tried this Get-AzureADUser -All:$true | ForEach-Object { $UserObjectID = $_ ForEach-Object{ [PSCustomObject]@{ UserObjectID = $_.ObjectId UserUserPrincipalName = $_.UserPrincipalName UserDisplayName = $_.DisplayName createdDateTime = $_.createdDateTime } } } But here in result last column is empty which is understandable, because this command is not part of Get-AzureADUser cmdlet. I tried some more but also without a success. After I get this I also want to add +60 days to the createdDateTime but here I have no clue even how to start. Please advise how to correct the script and add 60 days to the result. EDIT: I tried now this Get-AzureADUser -All:$true | ForEach-Object { $UserObjectID = $_ ForEach-Object{ [PSCustomObject]@{ UserObjectID = $_.ObjectId UserUserPrincipalName = $_.UserPrincipalName UserDisplayName = $_.DisplayName DateCreated = $_ | Add-Member -MemberType NoteProperty -Name "CreatedDateTime" -Value (Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime") } } } But the DateCreated column is still empty A: You don't really need a loop construct here, you can get the desired output with Select-Object: Get-AzureADUser -All |Select ObjectId,UserPrincipalName,@{Name='CreationDate'; Expression={(Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime")}}
{ "language": "en", "url": "https://stackoverflow.com/questions/67786019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to generate multiple Images This is a game where 5 more images is to be added every time when a user click on last node of left side div. If he clicks on some other node alert 'game over' should be displayed. Issues: * *TypeError: leftside.lastChild is null *How would I delete all nodes of both the right and left hand side div before calling the generateface function to generate new set of faces. Matching Game click on the extra smiling face on the left .smile {position:absolute} div {position:absolute; width:500px;height: 500px} #rightside {left:500px;border-left: 1px solid black} var numberOfFaces = 5; var leftside = document.getElementById("leftside"); var rightside = document.getElementById("rightside"); function generatefaces() { for (i=0;ievent.stopPropagation(); numberOfFaces += 5; generateFaces(); }; theBody.onclick = function gameOver() { theBody.onclick = null; alert("Game Over!"); }; A: You forgot to add px to the top and left style property. Change the code as below ismile.style.top = topran + 'px'; ismile.style.left = leftran + 'px'; var numberOfFaces = 5; var leftside = document.getElementById("leftside"); function generatefaces() { for (i=0;i<=numberOfFaces;i++) { ismile = document.createElement("img"); ismile.src = "http://orig00.deviantart.net/449c/f/2009/061/5/7/smiley_icon_by_emopunk23.jpg"; ismile.className = "smile"; var topran = Math.random() * 400; topran = Math.floor(topran); var leftran = Math.random() *400; leftran = Math.floor(leftran); ismile.style.top = topran + 'px'; ismile.style.left = leftran + 'px'; leftside.appendChild(ismile); } } .smile {position:absolute} div {position:absolute; width:500px;height: 500px} #rightside {left:500px;border-left: 1px solid black} <body onload="generatefaces()"> <h1> Matching Game </h1> <p> click on the extra smiling face on the left </p> <div id="leftside"></div> <div id="rightside"></div> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/39290970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FF vs Chrome: cant figure out why my select looks different This is what it looks like in chrome: This is what it looks like in FF: This is the css I have applied to this element: .styled-select5 { margin-left: 20px; height: 12px; border: 1px solid #cccccc; overflow: hidden; width: 104px; z-index: 1; background: url(/images/registration/triangle.png) no-repeat right white; display: block; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .styled-select5 select { padding-right: 42px; background: none repeat scroll 0 0 transparent; -webkit-appearance: none; -moz-appearance: none; text-indent: .01px; text-overflow: ''; border: none !important; width: 110% !important; overflow: hidden; z-index: 5; height: 14px; display: block; padding-left: 3px;} .styled-select5 select::-ms-expand{ display: none;} .styled-select5 select option { height: 20px; width: 400px; } .styled-select5.hidden { display: none; } I have been trying to figure this out for a while. In order for them to look similar I have to change the padding in FF to get the text to show properly. I am not sure why this is happening. Is there some difference in the way chrome and FF do this? A: Each browser (on every OS) displays the HTML elements differently. The amount of styling that can override the defaults is also decided by the browser. You cannot edit beyond what's permitted. If you happen to use selects for Safari, it'll look far more different and you cannot customize much there as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/19592880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between "Git" in general and Github? I know that Github is the most common site programmers use to save and make changes to code, but is this the only software out there? What are other relevant sites that utilize "Git" or version control that I could use? A: Git is a distributed version control system. More simpler description: it is tool that helps to manage repo with sources. Wiht purpose to share your repo with other project participants you need a public server where will be hosted your git repo. GitHub it is web service that provide to you an opportunity to host your repo. You can host it like public or private repo. Also GitHub provide a lot of other helpful features (convenient code-review tool, edit files, manage team, graphs, wiki, gist, etc...). A: "Git" is version control system that can use different hosts as server. Many companies use local "Git" servers. Github is one of many public "Git" servers, but it is most popular one.
{ "language": "en", "url": "https://stackoverflow.com/questions/37064812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: where is tensorflow:Assets file location? I recently created a prototype model in tensorflow, I'm asking if where is the saved model saved in my pc, its file location. saving my file outputted this info: INFO:tensorflow:Assets written to: m_translator\assets and I don't know what clearly this is hope there's someone who can explain this to me A: From the info you have given, it says that the files are written to m_translator. Once check in your PC in the same directory where you are running your code if there is any folder named m_translator or check in the filepath you have provided while saving the model. Thank You.
{ "language": "en", "url": "https://stackoverflow.com/questions/72155066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Rails, where do I put code responsible for periodically saving data from an external source? The app I’m developing needs to get some data from a third-party REST API every few minutes and save it to a database. I’m not sure where this fits in the MVC architecture. My best guess would be to put it in the corresponding models, but seems like I'd be mixing responsibilities. Any suggestions? A: A common approach is to use custom rake tasks and schedule them using whenever. There is even a nice Railscast, although it is a bit old.
{ "language": "en", "url": "https://stackoverflow.com/questions/21841497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to draw a line graph with data in MySQL using chart Js in php I want to draw a line graph using the following data in MySQL table. date - dec 10 , dec 11, dec 12, dec 13, dec 14, dec 15, dec 16, dec17, dec,18,dec 19, dec 20 attendance - 65, 58, 56, 78, 51, 54, 69, 35, 68, 43, 52 I made two queries extracting the data and stored in 2 arrays namely $data1 and $data2 using the code below $con = new mysqli($servername, $username, $password, $db); $myquery1 = "select date from Table_attendance"; $query1 = mysqli_query($con, $myquery1); if ( ! $query1 ) { echo mysqli_error(); die; } for ($x = 0; $x < mysqli_num_rows($query1); $x++) { $data1[] = mysqli_fetch_assoc($query1); } $my1 = "select attendance from Table_attendance"; $qu1 = mysqli_query($con, $my1); if ( ! $qu1 ) { echo mysqli_error(); die; } for ($x = 0; $x < mysqli_num_rows($qu1); $x++) { $data2[] = mysqli_fetch_assoc($qu1); } I then encoded the two arrays $data1 and $data2 into json format using the following code. $encod = json_encode($data1); $encod2 = json_encode($data2); The output of the arrays were as follows. [{"date":"2021-12- 10"},{"date":"2021-12-11"},{"date":"2021-12-12"},{"date":"2021-12-13"},{"date":"2021-12-14"},{"date":"2021-12-15"},{"date":"2021-12-16"},{"date":"2021-12-17"},{"date":"2021-12-18"},{"date":"2021-12-19"},{"date":"2021-12-20"}] [{"attendance ":"65"},{"attendance ":" 58 "},{"attendance ":" 56"},{"attendance":" 78 "},{"attendance ":" 51 "},{"attendance ":" 54"}{"attendance ":"69 "},{"attendance ":"35"},{"attendance":"68"},{"attendance":"43"},{"attendance ":"52"}] Finally I tried passing the encoded values as follows to plot into a line graph but it didn't work. <script src="//code.jquery.com/jquery-1.9.1.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <canvas id="myChart" style="width:100%;max-width:600px"></canvas> <script> var xValues = <?php echo $encod?>; var yValues = <?php echo $encod2?>; new Chart("myChart", { type: "line", data: { labels: xValues, datasets: [{ fill: false, lineTension: 0, backgroundColor: "rgba(0,0,255,1.0)", borderColor: "rgba(0,0,255,0.1)", data: yValues }] }, options: { title: {display: true, text: 'Custom Chart Title'}, legend: {display: false}, scales: { yAxes: [{ticks: {min: 6, max:16}}], } } }); </script> Please help me with this assessment. If there is another better code than mine please be kind enough to share. A: You didn't pass the data in the Chart Object correctly. You can transform the object in php or js. Example in js below. const ctx = document.getElementById("myChart").getContext("2d"); const xValues = [ { date: "2021-12-10" }, { date: "2021-12-11" }, { date: "2021-12-12" }, { date: "2021-12-13" }, { date: "2021-12-14" }, { date: "2021-12-15" }, { date: "2021-12-16" }, { date: "2021-12-17" }, { date: "2021-12-18" }, { date: "2021-12-19" }, { date: "2021-12-20" }, ]; const yValues = [ { attendance: "65" }, { attendance: "58" }, { attendance: "56" }, { attendance: "78" }, { attendance: "51" }, { attendance: "54" }, { attendance: "69" }, { attendance: "35" }, { attendance: "68" }, { attendance: "43" }, { attendance: "52" }, ]; const x = xValues.map(item => item.date); const y = yValues.map(item => item.attendance); new Chart(ctx, { type: "line", data: { labels: x, datasets: [ { label: "Dataset 1", backgroundColor: "rgba(0,0,255,1.0)", borderColor: "rgba(0,0,255,0.1)", data: y, }, ], }, options: { responsive: true, plugins: { legend: { position: "top", }, title: { display: true, text: "Chart.js Line Chart", }, }, }, }); <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <canvas id="myChart" width="400" height="400"></canvas> EDIT Full php example <?php $con = new mysqli($servername, $username, $password, $db); $myquery1 = "select date from Table_attendance"; $result1 = mysqli_query($con, $myquery1); $rowsDate = mysqli_fetch_all($result1, MYSQLI_ASSOC); $xValues = array_map(function ($item) { return $item['date']; }, $rowsDate); $myquery2 = "select attendance from Table_attendance"; $result2 = mysqli_query($con, $myquery2); $rowsAtd = mysqli_fetch_all($result2, MYSQLI_ASSOC); $yValues = array_map(function ($item) { return $item['attendance']; }, $rowsAtd); ?> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <canvas id="myChart" width="400" height="400"></canvas> <script> const x = <?php echo json_encode($xValues) ?>; const y = <?php echo json_encode($yValues) ?>; new Chart(ctx, { type: "line", data: { labels: x, datasets: [{ label: "Dataset 1", backgroundColor: "rgba(0,0,255,1.0)", borderColor: "rgba(0,0,255,0.1)", data: y, }, ], }, options: { responsive: true, plugins: { legend: { position: "top", }, title: { display: true, text: "Chart.js Line Chart", }, }, }, }); </script> A: As mentioned in an answer the problem was in encoding. In fact the array that should be passed should be in the var xValues = [1,2,3,4,5,6] format. But what I got was in var xValues = [{1},{2},{3},{4},{5},{6}] format. Anyhow I will post my whole code if in case will be needed for someone in the future. Thank you very much for those who tried to help me. The full code is as follows $con = new mysqli($servername, $username, $password, $db); // getting date column from Table_attendance table $myquery1 = "select date from Table_attendance"; $query1 = mysqli_query($con, $myquery1); if ( ! $query1 ) { echo mysqli_error(); die; } $a1 =""; for ($x = 0; $x < mysqli_num_rows($query1); $x++) { $data1 = mysqli_fetch_assoc($query1); if($a1 != ""){ $a1 = $a1.",'".$data1['date']."'"; } else { $a1 = "'".$data1['date']."'"; } } // getting attendance column from Table_attendance table $my1 = "select attendance from Table_attendance"; $qu1 = mysqli_query($con, $my1); if ( ! $qu1 ) { echo mysqli_error(); die; } $a2 =""; for ($x = 0; $x < mysqli_num_rows($qu1); $x++) { $data2 = mysqli_fetch_assoc($qu1); if($a2 != ""){ $a2 = $a2.",".$data2['attendance']; } else { $a2 = $data2['attendance']; } } ?> <?php //ploting the graph ?> <script src="//code.jquery.com/jquery-1.9.1.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <canvas id="myChart" style="width:100%;max-width:600px"></canvas> <script> var xValues = <?php echo '['.$a1.']'; ?>; var yValues = <?php echo '['.$a2.']'; ?>; new Chart("myChart", { type: "line", data: { labels: xValues, datasets: [{ fill: false, lineTension: 0, backgroundColor: "rgba(0,0,255,1.0)", borderColor: "rgba(0,0,255,0.1)", data: yValues }] }, options: { title: {display: true, text: 'Total attendance'}, legend: {display: false}, scales: { yAxes: [{ticks: {min: 10, max:100}}], } } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/70800161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: vhs vimeo ViewHelper on my Site the User can insert a Vimeo URL, something like this: https://vimeo.com/181873015 I want to extract only the last Part: 181873015 cause this is the one i need for the v:media.vimeo ViewHelper. So i thought i could do it like this: <v:format.replace substring="https://vimeo.com/" content="{data.tx_extend_ttcontent_vimeo}" replacement="''" count="1"> </v:format.replace> But i don`t know how the get the Result. Something like this: <v:format.replace substring="https://vimeo.com/" content="{data.vimeo}" replacement="''" count="1" as="videoID"> </v:format.replace> Does not work. Then i thought maybe the inline Notation is the right one. So i tried this: <v:media.vimeo videoId="{v:format.replace(substring: \'https://vimeo.com/\', content: \'{data.tx_extend_ttcontent_vimeo}\', replacement: '\'\'', count: 1)}" width="123" height="123" title="1" byline="1" portrait="1" color="'00adef'" autoplay="1" loop="1" api="1" playerId="NULL"> </v:media.vimeo> The Result is: <iframe src="//player.vimeo.com/video/{v:format.replace(substring: \'https://vimeo.com/\', content: \' https://vimeo.com/181873015\', replacement: '\'\'', count: 1)}?title=1&byline=1&portrait=1&color='00adef'&autoplay=1&loop=1&api=1&player_id=NULL" webkitallowfullscreen="webkitAllowFullScreen" mozallowfullscreen="mozAllowFullScreen" allowfullscreen="allowFullScreen" width="123" height="123" frameborder="0"> So does anyone know what is the right inline Notation or how can i use the Tag Version??? Thanks Bernd
{ "language": "en", "url": "https://stackoverflow.com/questions/40675884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I validate form client-side with this naming convention I have a form that has some simple javascript to validate a simple questionnaire. It used the name attribute on inputs in the form but now the page is integrated with the clients CMS it needs to use a particular naming convention which I can't get to work. The old form had inputs like this: <input type="text" name="firstName" /> but with the cms all fields require "fields[firstName]", e.g.: <input name="fields[first-name]"> How do I get this to work. Exisiting JS below: function validate_form ( ) { valid = true; if ( ( document.register.question[0].checked == false ) && ( document.register.question[1].checked == false ) && ( document.register.question[2].checked == false ) ) { alert ( "Please choose an answer" ); valid = false; } else if ( document.register.form_title.value == "" ) { alert ( "Please fill in the 'Title' box." ); valid = false; } else if ( document.register.fName.value == "" ) { alert ( "Please add your First Name" ); valid = false; } else if ( document.register.lName.value == "" ) { alert ( "Please add your Last Name" ); valid = false; } else if ( document.register.email.value == "" ) { alert ( "Please add a valid email address" ); valid = false; } else if ( document.register.country.selectedIndex == 0 ) { alert ( "Please select your Country" ); valid = false; } else if ( document.register.dob1.selectedIndex == 0 ) { alert ( "Please ensure your date of birth is complete" ); valid = false; } else if ( document.register.dob2.selectedIndex == 0 ) { alert ( "Please ensure your date of birth is complete" ); valid = false; } else if ( document.register.dob3.selectedIndex == 0 ) { alert ( "Please ensure your date of birth is complete" ); valid = false; } else if ( document.register.terms.checked == false ) { alert ( "Please check the Terms & Conditions box." ); valid = false; } return valid; } A: you can use jquery with something like this: $("input[name=fields\\[first-name\\]]").val()
{ "language": "en", "url": "https://stackoverflow.com/questions/19824296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sound Issues With Javascript I am writing a front end to a game engine in Javascript. The engine runs on the server and sends pictures and sounds to the web browser through 'SignalR'. I am using the React framework. As the game runs the server sends small sound samples in WAVE format, passed into this component through the AudioPlayerProps. I am having two main issues with the sound. The first is that the sound sounds 'disjointed'. And the second is that after a time the sound just stops playing. I can see sound being queued in the audio queue, but the 'playNextAudioTrack' method is not being called. There are no errors in the console to explain this. If this is not the best way to provide sound for a game front end, please let me know. Also if you want to see any more code please let me know. This is a huge multi tiered project so I am only showing what I think you need to see. Right now I am testing in Chrome. At this stage I need to turn on the DEV tools to get past the 'user didn't interact with page so you can't play any sound issue'. I will sort that issue out in due course. import * as React from "react"; import { useEffect, useState } from "react"; export interface AudioPlayerProps { data: string; } export const AudioPlayer = function (props: AudioPlayerProps): JSX.Element { const [audioQueue, setAudioQueue] = useState<string[]>([]) useEffect( () => { if (props.data != undefined) { audioQueue.push(props.data); } }, [props.data]); const playNextAudioTrack = () => { if (audioQueue.length > 0) { const audioBase64 = audioQueue.pop(); const newAudio = new Audio(`data:audio/wav;base64,${audioBase64}`) newAudio.play().then(playNextAudioTrack).catch( (error) => { setTimeout(playNextAudioTrack, 10); } ) } else { setTimeout(playNextAudioTrack, 10); } } useEffect(playNextAudioTrack, []); return null; } A: I solved my own problem. Here is the typescript class I wrote to handle chunked audio in JavaScript. I am not a JavaScript expert and therefore there may be faults. EDIT: After running it in 15 minute lots several times, it failed a couple of times at about the 10 minute mark. Still needs some work. // mostly from https://gist.github.com/revolunet/e620e2c532b7144c62768a36b8b96da2 // Modified to play chunked audio for games import { setInterval } from "timers"; // const MaxScheduled = 10; const MaxQueueLength = 2000; const MinScheduledToStopDraining = 5; export class WebAudioStreamer { constructor() { this.isDraining = false; this.isWorking = false; this.audioStack = []; this.nextTime = 0; this.numberScheduled = 0; setInterval(() => { if (this.audioStack.length && !this.isWorking) { this.scheduleBuffers(this); } }, 0); } context: AudioContext; audioStack: AudioBuffer[]; nextTime: number; numberScheduled: number; isDraining: boolean; isWorking: boolean; pushOntoAudioStack(encodedBytes: number[]) { if (this.context == undefined) { this.context = new (window.AudioContext)(); } const encodedBuffer = new Uint8ClampedArray(encodedBytes).buffer; const streamer: WebAudioStreamer = this; if (this.audioStack.length > MaxQueueLength) { this.audioStack = []; } streamer.context.decodeAudioData(encodedBuffer, function (decodedBuffer) { streamer.audioStack.push(decodedBuffer); } ); } scheduleBuffers(streamer: WebAudioStreamer) { streamer.isWorking = true; if (streamer.context == undefined) { streamer.context = new (window.AudioContext)(); } if (streamer.isDraining && streamer.numberScheduled <= MinScheduledToStopDraining) { streamer.isDraining = false; } while (streamer.audioStack.length && !streamer.isDraining) { var buffer = streamer.audioStack.shift(); var source = streamer.context.createBufferSource(); source.buffer = buffer; source.connect(streamer.context.destination); if (streamer.nextTime == 0) streamer.nextTime = streamer.context.currentTime + 0.01; /// add 50ms latency to work well across systems - tune this if you like source.start(streamer.nextTime); streamer.nextTime += source.buffer.duration; // Make the next buffer wait the length of the last buffer before being played streamer.numberScheduled++; source.onended = function () { streamer.numberScheduled--; } if (streamer.numberScheduled == MaxScheduled) { streamer.isDraining = true; } }; streamer.isWorking = false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/61284881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Angular UIBootstrap popover error Getting an example from http://angular-ui.github.io/bootstrap/ and following instructions I did : <button popover="I appeared on mouse enter!" popover-trigger="mouseenter" class="btn btn-default">Mouseenter</button> and when I moved mouse over button I got: * *Uncaught TypeError: Cannot read property 'split' of undefined ui-bootstrap-tpls-0.11.2.min.js:8 *positionElementsui-bootstrap-tpls-0.11.2.min.js:8 *zui-bootstrap-tpls-0.11.2.min.js:9 *pui-bootstrap-tpls-0.11.2.min.js:9 *kui-bootstrap-tpls-0.11.2.min.js:9 *b.event.special.(anonymous function).handlejquery.min.js:4 *b.event.dispatchjquery.min.js:3 *v.handlejquery.min.js:3 There I found an instruction : "The popover directives require the $position service." But have no idea what does it mean. I am a beginner so please help me. Maybe some initialization needs? I cannot find it on official website A: Specifying popover-placement fixed the problem for me. Example: <input type="number" popover-placement="top" popover="This is some text that explains something" popover-trigger="focus"> A: There seems to be a problem with placement/position of tooltips, and popovers. It has something to do with the changes to angular.isDefined which works differently in AngularJS 1.2 & 1.3 Here are a few directives to patch the issues by setting defaults // Bootstrap UI fixes after upgrading to Angular 1.3 .directive('tooltip', function() { return { restrict: 'EA', link: function(scope, element, attrs) { attrs.tooltipPlacement = attrs.tooltipPlacement || 'top'; attrs.tooltipAnimation = attrs.tooltipAnimation || true; attrs.tooltipPopupDelay = attrs.tooltipPopupDelay || 0; attrs.tooltipTrigger = attrs.tooltipTrigger || 'mouseenter'; attrs.tooltipAppendToBody = attrs.tooltipAppendToBody || false; } } }) .directive('popover', function() { return { restrict: 'EA', link: function(scope, element, attrs) { attrs.popoverPlacement = attrs.popoverPlacement || 'top'; attrs.popoverAnimation = attrs.popoverAnimation || true; attrs.popoverPopupDelay = attrs.popoverPopupDelay || 0; attrs.popoverTrigger = attrs.popoverTrigger || 'mouseenter'; attrs.popoverAppendToBody = attrs.popoverAppendToBody || false; } } }) A: Perhaps you are using angular 1.3.1 that breaks popover, angular 1.3.0 works
{ "language": "en", "url": "https://stackoverflow.com/questions/26751579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rails get records after a certain ID In my app because records get created frequently I don't want to use a standard pagination mechanism because records wouldn't always be on the same page (records on page 2 today, might be on page 3 tomorrow). Instead what I want to do is request records after a certain ID. So let's say I have 100 records in my posts table ranging from IDs 1-100, and I show 10 records at a time. What I want to do is using params[:after] is request posts after that ID. So if I have params[:after] == 10 I want to get records 11-21 (though 21 may not exist, so it's really 10 records in the table created_at ordered desc from the ID onwards. In my controller I have something like: if params[:after].present? start_id = params[:after] end_id = start_id+10 @posts = Post.where(:id => start_id..end_id).order('created_at desc').limit(10) else @posts = Post.order('created_at desc').limit(10) end The problem I have is that the end_id will return the start_id+10 but in the DB the next 10 records IDs might not be that, so I'd end up with incorrect IDs coming back. So ideally I need to know what the ID of the 10th post from this one is. How can I do this? A: In case params[:after] is given I would do the following: Post.where('table_name.id > ?', start).order('id desc').limit(10) If you don't cheat on created_at column, the order on created_at and id columns should be the same, and ordering is much faster in id column (it has an index of numbers and that stuff) Including the table name in the start condition is optional, but will help you avoid ambiguous SQL in case you want to join several tables. A: You can try this Post.where('id > ?', start_id).order('created_at').limit(10) Hope this will work for you
{ "language": "en", "url": "https://stackoverflow.com/questions/41743464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJS - $resource with :id in the middle of url I need to get this resource inside a factory: Content: $resource("http://localhost:3000/matches/:id/content") But when I try to access it with: Content.get({id: $scope.match.id}, function(){}); I got an error because it is trying to reach "/matches/content" instead "/matches/123/content" (supposing the id is 123). GET http://localhost:3000/matches/content 404 (Not Found) How can I solve this? A: Should work fine here is fiddle that tests it out. Could you be calling it too early? http://jsfiddle.net/mbkq12wu/1/ angular.module('userApp', ['ngResource']) .factory('Content', function($resource) { return $resource("http://localhost:3000/matches/:id/content"); }); describe('SO Content Test resource calls matches/1/content', function () { it('Calls GET – api/:id/content', function() { $httpBackend .expectGET('http://localhost:3000/matches/1/content').respond(200); Content.get({id: 1}, function(){}); $httpBackend.flush(); }); A: Your code is fine. The problem is that $scope.match.id resolves to undefined and which results into resource URL with omitted :id part (and duplicated / also removed). To verify that resource is all right check Content.get({id: 123}, function(){}); and also console.log($scope.match.id).
{ "language": "en", "url": "https://stackoverflow.com/questions/30539461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Lint: How to suppress all warnings associated with support library? I am trying to use Android Lint to keep my code running smoothly but since I'm using support-v7-appcompat, Lint returns an enormous, overflowing list of warnings. How can I suppress all of them so I can only see issues with my own app? In the Lint Overflow menu, there are options for "Check all Projects", "check android-support-v7-appcompat", and "check [myapp]" - but clicking [myapp] also shows a vast amount of errors regarding abc_ (support library) and trying to suppress them by selecting them and pressing "ignore in this project" doesn't work! As soon as I click "check [myapp]" again, the same lint errors show up. I can only assume this isn't intended behavior of lint! What can I do to improve this? Regards, A: You can find the option in the android lint menu: Once "Skip Library Project Dependencies" is checked, that should skip appcompat lint warnings when you are checking your project
{ "language": "en", "url": "https://stackoverflow.com/questions/20176427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: socket binding won't return an int A snippet of my code looks as follows: int descriptor = socket(AF_INET, SOCK_STREAM, 0); if(descriptor < 0){ cerr << "Error establishing socket connection." << endl; return -1; } int port = 3400; struct sockaddr_in address; char buffer[140]; address.sin_family = AF_INET; address.sin_addr.s_addr = htons(INADDR_ANY); address.sin_port = htons(port); int size = sizeof(address); if(bind(descriptor,(struct sockaddr*)&address,size) < 0){ cerr << "Error binding socket." << endl; } cout << "Waiting for connection on " << INADDR_ANY << " on port " << port << ends; whenever I try compiling this, I get the following error: error: invalid operands to binary expression ('__bind<int &, sockaddr *, int &>' and 'int') if(bind(descriptor,(struct sockaddr*)&address,size) < 0){ Does anybody know what this could mean? bind() is supposed to return an integer or so I thought. My imports look like this: #include <iostream> #include <string.h> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> using namespace std; Thanks! A: using namespace std; combined with too much header inclusions is likely the culprit here - there's a reason why it has been repeated over and over again here on SO not to use it. By doing that, the compiler sees bind and thinks you mean std::bind from <functional>, not ::bind for sockets. So either do the right thing and review if you really need to include all those headers and get rid of that using declaration, or use ::bind (edit: or both - it's not bad to use :: to indicate you want to use some standard API function from the global namespace)
{ "language": "en", "url": "https://stackoverflow.com/questions/39423474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET Core VS2015 upgrade issue How to get this project.json working in vs2015. I've downloaded the latest runtime and sdk but trying to update the packages but can't get it to work to get the correct packages. After trying several configs, reinstalling packages I don't know which number combinations 1.0 1.1.0 1.0.3 1.1.0-preview etc.. I should try to get the packages working... { "buildOptions": { "emitEntryPoint": true, "preserveCompilationContext": true, "debugType": "portable" }, "dependencies": { "BundlerMinifier.Core": "2.4.337", "Microsoft.AspNetCore.Diagnostics": "1.1.1", "Microsoft.AspNetCore.Mvc": "1.1.2", "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.2", "Microsoft.AspNetCore.Razor.Tools": "1.1.0-preview4-final", "Microsoft.AspNetCore.Routing": "1.1.1", "Microsoft.AspNetCore.Server.IISIntegration": "1.1.1", "Microsoft.AspNetCore.Server.Kestrel": "1.1.1", "Microsoft.AspNetCore.StaticFiles": "1.1.1", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.1", "Microsoft.Extensions.Configuration.Json": "1.1.1", "Microsoft.Extensions.Configuration.UserSecrets": "1.1.1", "Microsoft.Extensions.Logging": "1.1.1", "Microsoft.Extensions.Logging.Console": "1.1.1", "Microsoft.Extensions.Logging.Debug": "1.1.1", "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.1", "Microsoft.NETCore.App": "1.1.1", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.1.0" }, "frameworks": { "netcoreapp1.1": { "imports": [ "dotnet5.6", "portable-net45+win8" ] } }, "publishOptions": { "include": [ "wwwroot", "**/*.cshtml", "appsettings.json", "web.config" ] }, "runtimeOptions": { "configProperties": { "System.GC.Server": true } }, "runtimes": { "win10-x64": {} }, "scripts": { "prepublish": [ "bower install", "dotnet bundle" ], "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] }, "tools": { "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0", "Microsoft.VisualStudio.Web.CodeGeneration.Tools": { "version": "1.1.0-preview4-final", "imports": [ "portable-net45+win8+dnxcore50", "portable-net45+win8" ] }, "Microsoft.AspNetCore.Razor.Tools": "1.1.1" }, "userSecretsId": ":-)" }
{ "language": "en", "url": "https://stackoverflow.com/questions/43717111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i get div-height? How do I calculate div2.offsetHeight within for loop after each added child before the append of the whole div? var children = store.children; for (var i = 0; i < children.length; i++) { var child = children[i]; div1.innerHTML += child.outerHTML; } div2.appendChild(div1); console.log(div2.offsetHeight);
{ "language": "en", "url": "https://stackoverflow.com/questions/58039213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp.Net 2005 "Could not load type" Although I have seen dozens of forum questions relating to "Could not load type", none of the advice in them seemed to apply to my situation. I wrote a new web application using aspx.net VB 2005. It is tiny, with just 2 pages, 1 of which has no code-behind. It runs aok in the IDE but when I installed it on my pc (and also when installed on the production server), and tried to run it this error came up: Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not load type 'EMTTrainingDatabase.pageMain'. Source Error: Line 1: <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="pageMain.aspx.vb" Inherits="EMTTrainingDatabase.pageMain" %> Line 2: Line 3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Source File: /EMTTrainingDatabase/pageMain.aspx Line: 1 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082 I checked the web site properties in IIS and the correct ASP.net version is specified: 2.0.50727. I checked the virtual path and it looks correct too: /EMTTrainingDatabase pageMain source code header looks like: <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="pageMain.aspx.vb" Inherits="EMTTrainingDatabase.pageMain" %> Some posters suggest that the bin is in the wrong folder or the bin doesn't contain the rigt contents. I don't have enough knowledge to evaulate this. Can someone help? Thank you. A: I was able to find the answer to my problem: When I added content to the deployment project, the dll was not in the bin. When I dragged it into the bin, the program worked. A: For the benefit of others who might have had the same error, it can also come due to the ASP.NET runtime being unable to locate the /bin folder. For this, make sure you have marked the virtual directory containing your application as a web application root. e.g. In godaddy web hosting you should mark Set Application Root to the folder/sub-folder containing your application. (Making it a virtual directory is not enough). Hope it will help someone. A: Just replace the CodeBehind attribute with CodeFile
{ "language": "en", "url": "https://stackoverflow.com/questions/2773707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I cannot connect by jupyter notebook to my database Here is the code I initiate inside my notebook using VS Code. The output is always, NameError: name 'sql' is not defined. Note: I already do the, pip install mysql and pip install mysql-connector-python db_connect = sql.connect(host = '127.0.0.1', database = 'ml_database', user = 'root', password = '1234') A: You should import the mysql.connector package. I think you might find this tutorial helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/70772812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Drupal 7 - Selecting individual images for auto-cropped image styles Let's say I have a content type X that has an image for an attribute. I know I can specify different styles for that image (e.g. medium, large, thumbnail), so that crops are automatically made. But can I select/upload a particular image to use? E.g. "I'm not happy with the autocrop for this thumbnail image. I'll just upload my own." Are there modules that allow this? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7843213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery validator, add method doesn't accept an array as parameter I have an array called series that has elements, but when I print the array as the parameter in function notEqualSeries, it shows an empty array. I have to do that in this way cause I want to use that function with other arrays, so only I would to write the name of the array $.validator.addMethod('notEqualSerie', function (value,element,params) { var igual = 0; console.log(params) params.forEach(function (item) { if(value == item){ igual++; } }); return igual < 2; }, 'Serie por ingresar repetida'); validacion = $('#formAddEquipos').validate({ rules: { serie: { AZ09_: true, required: true, nowhitespace: true, remote: { url : base_url + 'menu/serieExiste', async: false, }, notEqualSerie: series } } A: Use a function to insert the variable... notEqualSerie: function() { return series; }
{ "language": "en", "url": "https://stackoverflow.com/questions/42662641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Swift-fatal error: Array index out of range How can I fix this code so I no longer get an error. The error I get is fatal error: Array index out of range. The code checks how many "x" and "o" there are in a string var input = "xxxoxoooxoxo" var inputString = Array(input.characters) var XString = "" var OString = "" for var i = 0; i <= inputString.count; ++i { if inputString[i] == "x" { XString.append(inputString[i]) } else if inputString[i] == "o" { OString.append(inputString[i]) } } if XString.characters.count == OString.characters.count { print("equal") } else { print("Not Equal") } Thanks for the help. A: Replace this for var i = 0; i <= inputString.count; ++i with this: for var i = 0; i < inputString.count; ++i Arrays are zero indexed. That means the first element has the index 0. The second element has index 1. ... . The last element has the index array.count-1. A: @dasdom is correct. but here is a more Swift-y way to do it: // input string var input = "ooooxxxxxxxoxoooxoxo" // difference between number of x's and number of o's var diff = 0 // perform this function for each character in `input.characters`: input.characters.forEach { switch $0 // $0 is the argument to our function (unnamed) { case "x": diff += 1 // x's are +1 case "o": diff -= 1 // o's are -1 default: fatalError() // we expect only 'x' or 'o'... if we get something else, just crash } } // use the ternary (?:) operator to print the answer. // (<result> = <condition> ? <if-true value> : <if-false value>) print( diff == 0 ? "equal" : "not equal" ) A shorter version, inspired by @Eendje's answer :) print( input.characters.reduce(0) { $0 + [ "x":1, "o":-1 ][ $1 ]! } != 0 ? "not" : "", "equal" ) A: While everyone is giving you an alternative, I thought this would be a nice addition as well: var input = "xxxxxoxoooxoxo" You can get the count by using filter: let xCount = input.characters.filter { $0 == "x" }.count let oCount = input.characters.filter { $0 == "o" }.count print( xCount == oCount ? "equal" : "not equal" ) In your case, using reduce would be more efficient and it's shorter: let result = input.characters.reduce(0) { $0 + ($1 == "x" ? 1 : -1) } print(result == 0 ? "equal" : "not equal") // not equal This is only if you're sure input only contains x and o. If not, then you'll have to change the evaluation to: { $0 + ($1 == "x" ? 1 : $1 == "o" ? -1 : 0) } A: You are enumerating pass the range of the array. Use this instead. for var i = 0; i < inputString.count; ++i { Or you can use this more idiomatic code: var input = "xxxoxoooxoxo" var xString = 0 var oString = 0 for c in input.characters { if c == "x" { xString++ } else if c == "o" { oString++ } } if oString == xString { print("equal") } else { print("Not Equal") }
{ "language": "en", "url": "https://stackoverflow.com/questions/36111004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Permissions Request user Something Went Wrong error I'm having some issues with allowing users to connect their accounts to my app. Most users can do it fine, but some just comes back saying "Sorry, something went wrong." and this is for the same users all the time. I have two Facebook accounts, to test this, and one account is absolutely fine connecting, but another not really used account I use for testing, always fails. For example, if Firefox is logged in to Facebook as User A, and IE is logged in to Facebook as User B, then copying the below link (obviously changing to the correct App id and the correct redirect_uri) works in Firefox, but in IE I get the "Something went wrong error" http://www.facebook.com/dialog/permissions.request?_path=permissions.request&app_id=[MYAppID]&redirect_uri=[TheRedirectURL]&display=page&response_type=code&fbconnect=1&perms=publish_stream&from_login=1 Logging both out, and logging in each user into the other browser, the same user that worked before will work. So it's deffo not a browser issue, but down to the user surely, but no idea what. Anyone got any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7909658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cs50 Speller Uninitialised value was created by a heap allocation error I have some code that is supposed to take a dictionary file, read each word and add it to trie data structure setting a bool to true on the final node of the word. It runs but when i check words against the dictionary later in the check() function it was always saying false. Valgrind is throwing this error; ==20700== ==20700== Conditional jump or move depends on uninitialised value(s) ==20700== at 0x40116F: load (dictionary.c:114) ==20700== by 0x400834: main (speller.c:40) ==20700== Uninitialised value was created by a heap allocation ==20700== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==20700== by 0x401180: load (dictionary.c:116) ==20700== by 0x400834: main (speller.c:40) ==20700== Killed I had a look around and added the loops that itterate through children[] and initialise to NULL after creating a new node, but still seem to have the issue. // Represents a node in a trie typedef struct node { bool is_word; struct node *children[N]; } node; // Represents a trie node *root; // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { // Initialize trie root = malloc(sizeof(node)); if (root == NULL) { return false; } root->is_word = false; for (int i = 0; i < N; i++) { root->children[i] = NULL; } // Open dictionary FILE *file = fopen(dictionary, "r"); if (file == NULL) { unload(); return false; } //declare pointer to store adress of current node node *ptr = root; // Buffer for a word char word[LENGTH + 1]; for (int i = 0; i < LENGTH + 1; i++) { word[i] = 0; } int size = 0; // Insert words into trie while (fscanf(file, "%s", word) != EOF) { // make pointer to current place in trie structure and intitialise to root ptr = root; // make variable to store chaacter as int representing position in alphabet int alphaindex; // iterate over letters in word for (int i =0; i < LENGTH; i++) { // if word i == to ' character check ptr children and make new node if necesary if ((int)&word[i] == '\'') { alphaindex = 26; if (ptr-> children[alphaindex] == NULL) { node *n = malloc(sizeof(node)); if (n == NULL) { return 1; } root->is_word = false; for (int j = 0; j < N; j++) { root->children[j] = NULL; } // set 27th element of children to new node ptr -> children[alphaindex] = n; } // set ptr to ptr[26] ptr = ptr -> children[alphaindex]; } else { // adjust alphainex alphaindex = islower((int) word[i]) ? (int) word[i] - 97 : (int) word[i] - 65; //check location for NULL and make new index if necessary if (ptr -> children[alphaindex] == NULL) { node *n = malloc(sizeof(node)); if (n == NULL) { return 1; } root->is_word = false; for (int k = 0; k < N; k++) { root->children[k] = NULL; } // set children[alphaindex] to new node ptr -> children[alphaindex] = n; //set ptr to new alphaindex element of array which its self points to the new node ptr = ptr -> children[alphaindex]; } else { //set ptr to new alphaindex element of array which its self points to the new node ptr = ptr -> children[alphaindex]; } } // if the character is 0 word is over, set is_word and return to while loop if((char) word[i + 1] == 0) { ptr -> is_word = true; size ++; break; } } } printf("Size of dictionary = %i\n", size); // Close dictionary fclose(file); // Indicate success return true; } Im fairly sure that as the conditional with this error is where I evaluate weather or not to make a new node that this will be causing the errors when i try to test words against it later. Thanks in advance for your help Alex A: Several immediate problems: If word contains an apostrophe, all pointers in root are set to NULL here: for (int j = 0; j < N; j++) { root->children[j] = NULL; } Typo? That will make them "unfreeable" (not to mention, check will never find them). Same problem in the else branch: for (int k = 0; k < N; k++) { root->children[k] = NULL; } The apostrophe check needs to be discrete. It also looks like program doesn't "save" enough pointers, but you won't be able to work through that until these big structural problems are corrected.
{ "language": "en", "url": "https://stackoverflow.com/questions/59544257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simpler c++ template compile error output When working with templates in C++ any errors cause the compiler to emit a lot of output. In most cases when I am working on something most of that information is noise and I have to scroll around looking for the info I am interested in, for example: * *Every template candidate is listed. I rarely have use for this long list and it just clutters the output. *Aliases for template specializations are expanded, e.g. std::string is written as std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, or expanded typedefs / alias declarations. I would prefer to have them unexpanded for easier reading. Is it possible in either g++ or clang to reduce any of this for shorter/simpler output? Obviously the information can be important, but then I would prefer to compile again with more verbosity and keep it short and simple by default. A: Unfortunately there's no way to deal with this currently. C++20 solves this problem by introducing concepts, where templates can have abstract definitions that are restricted with everything except for their binary layout. Violating these definitions will provide simple errors. Currently, I dig into these lines and I got used to it. I'm currently dealing with a program with 5 template parameters at places. It's all about getting used to it and training your eyes to parse the content. However, if you're really stuck, one solution I may suggest is that you copy all the relevant error output to some editor, and do a find-and-replace to simplify individual expressions, making them smaller and smaller with every replace until it becomes readable for you. Good skills in regex may help as well. In Notepad++ (or Notepadqq on linux), you can find regular expressions and use capture groups in the replacement with \1 for first capture group, \2 for second, etc. So, bottom line: Until C++20, there's no clean solution for this except what you invent yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/53687794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Fast way to strip_tags in whole document Our website is currently under attack by some scriptkiddies that are adding HTML code to their motto's and other database tables (they have access too) and we would like to use strip_tags to filter the HTML out of it, we use a lot of queries on our website so I was wondering if there was a way to apply these rules to a whole document. Some of our queries look like this: <?php echo $users->UserInfo($username, 'motto'); ?> While others look like: <div class="title">'.$campaign['caption'].'</div> A plug-in for PHP would be good to, we use Windows Server 2008 R2 SP1 with IIS. A: The easiest way would be to create a wrapper object around the actual db abstraction object(s). For example, if there is an object of type "db" that provides you some convienance functions such as "select" and "update", you could write a class that extends "db" and overrides the "select function". It might look something like this (its an example as you have not provided enough info on your specific implementation). class db2 extends db { public function select($tableName, $whereClause) { $result = parent::select($tableName, $whereClause); return strip_tags($result); } } Then you would replace your object that instantiated "db" and instead instantiate "db2". $db = new db($connectionParams); should be replaced with $db = new db2($connectionParams); Now all your existing queries should use the new function which removes the tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/20585042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lua5.2 embedded in C++ I'm trying for the first time to have Lua embedded in C++. I've been searching for 2 days now, but most of internet tutos use lua5.1, which is incompatible with lua5.2. So I read a bit of lua documentation, example source code, and I end up with this : main.cpp : #include "luainc.h" #include <iostream> int main(){ int iErr = 0; lua_State *lua = luaL_newstate (); // Open Lua luaopen_io (lua); // Load io library if ((iErr = luaL_loadfile (lua, "hw.lua")) == 0) { std::cout<<"step1"<<std::endl; if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0) { std::cout<<"step2"<<std::endl; lua_getglobal (lua, "helloWorld"); // Push the function name onto the stack if (lua_type(lua, lua_gettop(lua)) == LUA_TNIL) { // if the global variable does not exist then we will bail out with an error. std::cout<<"global variable not found : helloworld"<<std::endl; /* error so we will just clear the Lua virtual stack and then return if we do not clear the Lua stack, we leave garbage that will cause problems with later function calls from the application. we do this rather than use lua_error() because this function is called from the application and not through Lua. */ lua_settop (lua, 0); return -1; } // Function is located in the Global Table /* lua_gettable (lua, LUA_GLOBALSINDEX); */ //lua5.1 lua_pcall (lua, 0, 0, 0); } } lua_close (lua); return 0; } hw.lua : -- Lua Hello World (hw.lua) function helloWorld () io.write ("hello World") end luainc.h : #ifndef __LUA_INC_H__ #define __LUA_INC_H__ extern "C" { #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lua.h> #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lauxlib.h> #include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lualib.h> } #endif // __LUA_INC_H__ I have no error, the output is : step1 step2 which should mean that my "helloworld" function has been found. But as I can not see "Hello World" in the output, I suspect that the function has not been called. What am I doing wrong ? This is how I compile my program : g++ main.cpp -L/usr/local/include -I/usr/local/include -llua A: First, why not #include "lua.hpp", which comes with Lua and does mostly what your luainc.hdoes? There are two problems with your code: * *You don't emit any error message when luadL_loadfile fails. *You use lua_pcall to call helloWorld but does not test its return value. When you change lua_pcall to lua_call you get this error message: attempt to index global 'io' (a nil value) This means that you forgot to set the global io after calling luaopen_io. Just add lua_setglobal(lua,"io")and it works. Unlike Lua 5.1, Lua 5.2 does not set globals automatically when you open libraries, unless the library itself does it, which is discouraged. You'll probably be better off calling luaL_openlibs to open all standard Lua libraries with no surprises. You may as well use luaL_dofile instead of luaL_loadfile and save the first lua_pcall. You still have to check the return value.
{ "language": "en", "url": "https://stackoverflow.com/questions/19315192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create composite index which contains the (latitude,longitude) and other datatype column in PostgreSQL? DDL: CREATE TABLE test ( longid bigint NOT NULL DEFAULT nextval('test_longid_seq'::regclass), longitude double precision, latitude double precision, create_ts_long bigint, CONSTRAINT test_pkey PRIMARY KEY (longid) ) We can use this to create the gist index : CREATE INDEX ll_idx ON test USING gist (ll_to_earth(latitude ::double precision, longitude ::double precision)) TABLESPACE pg_default; But there is a scenario that I want to find the nearest records of the specific time(create_ts_long). So how to create such composite index? Thanks in advance! A: Install the btree_gist contrib module. Then you have a gist_int8_ops operator class that you can use to create a GiST index on a bigint column.
{ "language": "en", "url": "https://stackoverflow.com/questions/39239938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: On Mouse Over doesn't fire triggers in ContentTemplate I have some textboxes and I want to change some of their properties when I put the mouse over them. In this case, I want to change the BorderBrush and BorderThickness. This is my XAML ControlTemplate, it's inside a Window.Resource tag: <Style TargetType="{x:Type TextBox}"> <Setter Property="SnapsToDevicePixels" Value="True"/> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="AllowDrop" Value="true"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBoxBase}"> <Border Name="Border" Padding="4" BorderBrush="#ccc" BorderThickness="1"> <ScrollViewer Margin="0" x:Name="PART_ContentHost"/> <Border.Background> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <GradientStop Color="#FFC4C4C4" Offset="0.0" /> <GradientStop Color="#FFF8F8F8" Offset="0.10" /> </LinearGradientBrush> </Border.Background> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver"> <Setter Property="BorderThickness" Value="1"></Setter> <Setter Property="BorderBrush" Value="Orange"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> This piece of code should set the properties I wrote inside the Trigger tag when the mouse cursor is over the textbox: <ControlTemplate.Triggers> <Trigger Property="IsMouseOver"> <Setter Property="BorderThickness" Value="1"></Setter> <Setter Property="BorderBrush" Value="Orange"></Setter> </Trigger> </ControlTemplate.Triggers> But this trigger simply don't get fired. Nothing happens. Why? And how can I achieve this? A: You could try this, add the Value property to your trigger and set it to true. Also need to add the target name to tell it to change the properties of border which is in your control template. <Trigger Property="IsMouseOver" Value="true" > <Setter Property="BorderThickness" TargetName="Border" Value="1"></Setter> <Setter Property="BorderBrush" TargetName="Border" Value="Orange"></Setter> </Trigger> A: I think you need to specify border element name <Trigger Property="IsMouseOver" Value="true" > <Setter TargetName="Border" Property="BorderThickness" Value="1"></Setter> <Setter TargetName="Border" Property="BorderBrush" Value="Orange"></Setter> </Trigger>
{ "language": "en", "url": "https://stackoverflow.com/questions/16220765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the relationship between ethereum and solidity? I am new to the blockchain. As I study solidity language, I can not figure out how it makes a blockchain in the end. I can map a contract to a class; but is it that every instance is a chain or what? A: The relationship between Solidity and Ethereum is something like the relationship between Objective-C and iPhones. The former is a programming language used to write code that runs on the latter. The actual implementation of the blockchain (the data structure, consensus protocols, etc.) is implemented in other languages (Go in the case of geth, Rust in the case of Parity). A: As I study solidity language, I can not figure out how it makes a blockchain in the end The Solidity programming language serves the sole purpose of allowing for the development of smart contracts on an Ethereum-based blockchain network. These smart contracts are simply the logic (code) that is triggered by internal or external actors (respectively users or other code) within the blockchain network and interpreted and executed by the Ethereum Virtual Machine (EVM). Solidity is not used to create the Ethereum blockchain network. The blockchain network must already be in existence for the smart contract logic to be deployed to the network. An Ethereum blockchain network can be created by any of the multiple Ethereum clients due to the unambiguous nature of the Ethereum protocols. I can map a contract to a class; but is it that every instance is a chain or what? Mappings in Solidity are a basic key/value data structure akin to a hash map. You can map keys of data type X to a value of data type Y. There is no explicit relation between Solidity mappings and the blockchain network itself. Whenever a smart contract function is called, a transaction is subsequently created on the blockchain network that is representative of the executed function as well as the caller of that function. This transaction is persisted on the blockchain and serves as immutable proof that an action has taken place.
{ "language": "en", "url": "https://stackoverflow.com/questions/54281072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting arguments in a kernel in OpenCL causes error I am a beginner in OpenCL and thus writing a simple program to double the elements of an array. The kernel code is:- __kernel void dataParallel(__global int* A, __global int* B) { int base = get_local_id(0); B[base]=A[base]+A[base]; } The local_work_size=32 as I am squaring 32 elements. In my program I have declared an integer array which holds the elements to be squared. int *A; A=(int*)malloc(sizeof(int)*64); for (i=0; i < 32; i++) { A[i] = i; } platforms[i] stores the platform id, devices[j] stores the corresponding device id. Their types: cl_platform_id* platforms; cl_device_id* devices; Creating context cl_context context=clCreateContext(NULL,1,&devices[j],NULL,NULL,NULL); Next comes the command queue cl_command_queue cmdqueue=cmdqueue=clCreateCommandQueue(context,devices[j],NULL,&err); Next I created 2 memory buffers, one to hold the input data and the other to hold the result. cl_mem Abuffer,Bbuffer; Abuffer=clCreateBuffer(context, CL_MEM_READ_WRITE ,32*sizeof(int),NULL,&err); Bbuffer=clCreateBuffer(context, CL_MEM_READ_WRITE ,32*sizeof(int),NULL,&err); Then I copied the data of array A to Abuffer ret=clEnqueueWriteBuffer(cmdqueue, Abuffer, CL_TRUE, 0, 32*sizeof(int), A, 0, NULL, NULL); printf("%d",ret);//output is 0 thus data written successfully into the buffer The kernel code was then read into a character string source_str and the program was created. kernelprgrm=clCreateProgramWithSource(context,1,(const char **)&source_str,(const size_t *)&source_size,&err); if(!err) { printf("\nKernel program created successfully\n"); }//Outputs -Kernel program created successfully I then built the program using: ret=clBuildProgram(kernelprgrm,1,&devices[j],NULL,NULL,NULL);//returns CL_SUCCESS Getting buildinfo next ret=clGetProgramBuildInfo(kernelprgrm,devices[j], CL_PROGRAM_BUILD_STATUS ,0,NULL,&size);//Returns success Creating kernel kernel = clCreateKernel(kernelprgrm, "dataParallel", &ret); printf("\nReturn kernel program=%d",ret); if(!ret) { printf("\nProgram created successfully!\n"); } //Outputs -Program created successfully! Now comes the devil:- ret=clSetKernelArg(kernel,0,sizeof(cl_mem),(void *) Abuffer); printf("\nKernel argument 1 ret=%d",ret); ret=clSetKernelArg(kernel,1,sizeof(cl_mem),(void *) Bbuffer); printf("\nKernel argument 2 ret=%d",ret); Both return -38 meaning CL_INVALID_MEM_OBJECT. P.S.:As per the errors pointed out i.e. use &Abuffer instead of Abuffer in the argument and after making the necessary changes, both return 0 size_t global_item_size = 32; size_t local_item_size = 32; Also ret = clEnqueueNDRangeKernel(cmdqueue, kernel, 1, NULL,&global_item_size, &local_item_size, 0, NULL, NULL); returns 0. Trying to get the result ret = clEnqueueReadBuffer(cmdqueue, Bbuffer, CL_TRUE, 0, 32*sizeof(int), B, 0, NULL, NULL);` printf("\nB:-\n"); for (t=0; t < 32; t++) { printf("%d\t ", B[t]); } This returns buildstatus=0 with core getting dumped for my AMD GPU (running AMD Accelerated Parallel Processing platform) and NVIDIA GPU whereas it works perfectly fine if the selected device is CPU using Intel(R) OpenCL platform. Also I tried getting the build log using: cl_build_status *status=(cl_build_status *)malloc(sizeof(cl_build_status )*size); clGetProgramBuildInfo(kernelprgrm,devices[j], CL_PROGRAM_BUILD_STATUS ,size,status,NULL); printf("\nBuild status=%d\n",*status); //Getting build info if not successful clGetProgramBuildInfo(kernelprgrm,devices[i], CL_PROGRAM_BUILD_LOG ,0,NULL,&size); char *buildlog=(char*)malloc(size); clGetProgramBuildInfo(kernelprgrm,devices[i], CL_PROGRAM_BUILD_LOG ,size,buildlog,NULL); printf("\n!!!!!!!!!!!!!!!!!!!!!Program ended!!!!!!!!!!!\n"); printf("\n\nBuildlog: %s\n\n",buildlog); But it returns Buildlog: Compilation started Compilation done Linking started Linking done Device build started Device build done Kernel <dataParallel> was successfully vectorized (4) Done. A: Here's what the OpenCL 1.2 spec has to say about setting buffers as kernel arguments: If the argument is a memory object (buffer, image or image array), the arg_value entry will be a pointer to the appropriate buffer, image or image array object. So, you need to pass a pointer to the cl_mem objects: ret=clSetKernelArg(kernel,0,sizeof(cl_mem),(void *) &Abuffer); A: Why are you using clEnqueueTask? I think you should use clEnqueueNDRangeKernel if you have parallel work to do. Also, just set the global work size; pass NULL for the local work group size. 32x32 is larger than some devices can do.
{ "language": "en", "url": "https://stackoverflow.com/questions/31159492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unity Singleton Pattern Its just a question that bugs me on Unity. We often use Singleton objects like game managers and so and there are two ways to go for this. One is to use a Singleton.cs c sharp class as follows: using System; using System.Linq; using UnityEngine; public class Singleton<T> : MonoBehaviour where T : MonoBehaviour { static T instance; DateTime BirthTime; public static T Instance { get { if (instance == null) Initialize(); return instance; } } private void Awake() { BirthTime = DateTime.Now; } public static void Initialize() { if (instance == null) instance = FindObjectOfType<T>(); } } And then derive our GameManager As GamaManager : Singleton<GameManager> In popular opinion, this method is CPU consuming, particularly on mobile as Unity has to iterate through hierarchy of so many objects for using the Initialize method mentioned in singleton. A simpler approach is to create private instance and initialize it in Start or Awake as: GameManager : MonoBehaviour { public static GameManager Instance { get; private set; } void Start() { Instance = this; } } But I think, its like writing same code again and again. Can anybody suggest a cleaner approach to this? A: I'm not sure what you want exactly, but in singleton pattern I prefer make a main class like GameManager and set it as a singleton class by using this piece of code: static GameManager _instance; public static GameManager instance { get { if (!_instance) { _instance = FindObjectOfType<GameManager>(); } return _instance; } } Or the piece of code that you wrote, after that define variables according to other sub managers type and access to them by GameManagersingleton. For example: public BulletManager myBulletManager; and use it like this: GameManager.instance.myBulletManager.Fire();
{ "language": "en", "url": "https://stackoverflow.com/questions/46286996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving response message from WebService In NetBeans I have to use the following code: public String launchRequest(String paramString) { URL localURL = new URL(paramString); Object localObject1 = new Socket(localURL.getHost(), localURL.getPort()); Object localObject2 = "GET " + paramString + " HTTP/1.0"; localObject2 = (String)localObject2 + "\r\nAccept value: */*\r\n"; localObject2 = (String)localObject2 + "Host value: " + localURL.getHost() + ":" + localURL.getPort() + "\r\n"; Object localObject3 = new PrintWriter(((Socket)localObject1).getOutputStream(), true); ((PrintWriter)localObject3).println((String)localObject2); ((PrintWriter)localObject3).close(); ((Socket)localObject1).close(); return "OK";} This code is supposed to call a webService created in C# that makes an insert operation in an Oracle Database. The url that is passed looks like this: http://192.168.88.29:443/RaduPestrea/Services/Ort.asmx/ORTRequest?callBackDisabled=true&siren=328812656&capId=1325369 The problem is that the webService is not called. The getOutputStream() retuns an OutputStream that has no message from the WebService. This is a part of the webService: namespace Services { /// /// Summary description for Service1. /// public class Ort : System.Web.Services.WebService { [WebMethod] public string ORTRequest(bool callBackDisabled, int siren, int capId) { Try{ ....... return "Success ReqId :" + reqNum; Catch(Exception ex) { return ex.ToString(); } } } The problem is I cannot modify this code. I hope the problem is from the URL I sent. Any help is appreciated. Thank you. Edit: Agreed it is not the most beautiful code. The task is, the Java code needs to call the WebService from that URL link. That link is supposed to make an insert in a database. There is no new record in database. I use the return statements from the WebService to make sure it is called but nothing is returned. I may be doing it wrong, is there anyway to check that the WebService has been called successfully ? If I use the following code, the web service is called and a new record is inserted in the database. <code> localURL = new URL(paramString); localObject1 = ""; localObject2 = localURL.openStream(); localObject3 = new InputStreamReader((InputStream)localObject2); BufferedReader localBufferedReader = new BufferedReader((Reader)localObject3); String str1; while ((str1 = localBufferedReader.readLine()) != null) { String str2 = ""; localObject1 = (String)localObject1 + str2; } return (String)localObject1; </code> A: First of all, it is a bad idea to use a Socket to make HTTP requests. It is better to use an existing library class / method; for example: new URL("https://example.com/foo/bar?param=xxx").openConnection(); This gives you some subclass of URLConnnection that you can use to form the request and get the reply from the server There are alternative libraries for making HTTP / HTTPS requests. For example, the Apache HttpComponents libraries can be a good choice, if your requirements are complicated. However, I suspect that the real reason that you are getting nothing back from your request, is that you are trying to talk to an "https" server (port 443) without using an SSL / TLS connection. That ain't going to work. The server is likely to just close the socket. While it is possible to establish an SSL / TLS connection over a plain Socket (in theory) or use an SSLSocket, it is simpler to use a properly formed "https://..." URL and (for example) URL.openConnection() as above. Moving past that, the header lines in your supposed request look syntactically invalid. Both Accept value: ... and Host value: .... are wrong. If really want to implement the HTTP message handling yourself, you need to read the HTTP 1.1 specification, and implement it to the letter. And finally (as @EJP points out) your code isn't even reading the response. Writing to an OutputStream is not going to "return" anything. You need to read the response from an InputStream ... even if only to check that the request was accepted. A: The problem is that the webService is not called. You haven't provided any evidence to that effect, and it is impossible to tell from the code you've posted. The getOutputStream() retuns an OutputStream that has no message from the WebService. This is meaningless. OutputStreams don't contain messages from the peer. They are used to send messages to the peer. This statement and your title are completely nonsensical. Is there anyway to check that the WebService has been called successfully? Yes. Read the response, and return it, instead of hardwiring "OK". And you've just posted code that does exactly that. Agreed it is not the most beautiful code. It isn't even correct code. The HTTP headers are invalid, and it makes no attempt to read a response. It's just incompetent. Use the HttpURLConnection code you posted.
{ "language": "en", "url": "https://stackoverflow.com/questions/31268967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I set duration of a video in ExoPlayer? I need to set duration of a video for a thumbnail to 5 seconds and loop it. I got the loop part, but I can't find documentation for setting specific duration I tried exoPlayer.seek(duration) but that didn't work A: You may use ClippingMediaSource: ClippingMediaSource​(MediaSource mediaSource, long startPositionUs, long endPositionUs) Creates a new clipping source that wraps the specified source and provides samples between the specified start and end position. You can convert to have a new media source and set this new media source for your ExoPlayer: // Create a new media source with your specified period val newMediaSource = ClippingMediaSource(mediaSource, 0, 5_000_000)
{ "language": "en", "url": "https://stackoverflow.com/questions/75279362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Entry to search through a number of entries in a Listbox (tkinter) I want to use a search function which searches through a list of program names (chrome, thunderbird, adobe reader etc.) I have a Listbox and then a load of program names added into the Listbox, I want the search feature, entry_1, to search through all of these names and then highlight the one which was searched for. Is this possible? Here is my code: from tkinter import * #definitions root = Tk() var_1 = StringVar(root) label_1 = Label(root, text="Search:") label_2 = Label(root, text="Subject specific programs below") label_3 = Label(root, text="Subject:") entry_1 = Entry(root) #this should search through the strings listed under listbox_2 configs button_1 = Button(root, text="Install") scrollbar_1 = Scrollbar(root) listbox_2 = Listbox(root, yscrollcommand=scrollbar_1.set) optionmenu_1 = OptionMenu(root, var_1, "Computing", "Engineering", "Physics") string_1 = StringVar(root, name="Google Chrome") string_2 = StringVar(root, name="Thunderbird") string_3 = StringVar(root, name="Adobe Reader X") string_4 = StringVar(root, name="WinRAR") string_5 = StringVar(root, name="OpenOffice") string_6 = StringVar(root, name="Program 1") string_7 = StringVar(root, name="Program 2") string_8 = StringVar(root, name="Program 3") string_9 = StringVar(root, name="Program 4") string_10 = StringVar(root, name="Program 5") string_11 = StringVar(root, name="Program 6") #configuration root.title("Network Installation") listbox_2.insert(1, string_1) listbox_2.insert(2, string_2) listbox_2.insert(3, string_3) listbox_2.insert(4, string_4) listbox_2.insert(5, string_5) listbox_2.insert(6, string_6) listbox_2.insert(7, string_7) listbox_2.insert(8, string_8) listbox_2.insert(9, string_9) listbox_2.insert(10, string_10) listbox_2.insert(11, string_11) optionmenu_1.config(width=15) scrollbar_1.config(command=listbox_2.yview) #grid additions label_1.grid(row=0, column=5) label_2.grid(columnspan=6, row=1, column=0, sticky=E) entry_1.grid(row=0, column=6) button_1.grid(columnspan=2, row=7, column=5) listbox_2.grid(rowspan=6, columnspan=6, row=2, column=0) scrollbar_1.grid(rowspan=6, row=2, column=4, sticky=N+S) optionmenu_1.grid(columnspan=3, row=0, column=1) label_3.grid(row=0, column=0) root.mainloop() A: I know this was asked a long time ago but here's how to highlight the listbox items using a search entry box in Tkinter. Explanation: * *all_listbox_items is the most important part. When the program first populates the listbox, it's important to capture those initial values and use the search entry box as a way to query these initial entries. *add a textvariable to entry_1 and name it search_var. *put a trace on search_var so if the values in the entry_1 change, we can trigger a function named highlight_searched. *The function highlight_searched basically enumerates all the listbox items and checks to see if the searched text in entry_1 is in any of the items from the listbox. Where this is true, you use selection_set(i) (where i is short-hand for index) to select each item. I'm not particularly happy with using enumerate. It's just easy. There surely is a better way to return the index of an item in a for loop. I'd love to hear a better solution to my enumeration suggestion. Code: from tkinter import * #definitions root = Tk() var_1 = StringVar(root) label_1 = Label(root, text="Search:") label_2 = Label(root, text="Subject specific programs below") label_3 = Label(root, text="Subject:") def highlight_searched(*args): search = search_var.get() for i,item in enumerate(all_listbox_items): if search.lower() in item.lower(): listbox_2.selection_set(i) else: listbox_2.selection_clear(i) if search == '': listbox_2.selection_clear(0, END) search_var = StringVar() search_var.trace('w', highlight_searched) entry_1 = Entry(root, textvariable=search_var) #this should search through the strings listed under listbox_2 configs button_1 = Button(root, text="Install") scrollbar_1 = Scrollbar(root) listbox_2 = Listbox(root, yscrollcommand=scrollbar_1.set) optionmenu_1 = OptionMenu(root, var_1, "Computing", "Engineering", "Physics") string_1 = StringVar(root, name="Google Chrome") string_2 = StringVar(root, name="Thunderbird") string_3 = StringVar(root, name="Adobe Reader X") string_4 = StringVar(root, name="WinRAR") string_5 = StringVar(root, name="OpenOffice") string_6 = StringVar(root, name="Program 1") string_7 = StringVar(root, name="Program 2") string_8 = StringVar(root, name="Program 3") string_9 = StringVar(root, name="Program 4") string_10 = StringVar(root, name="Program 5") string_11 = StringVar(root, name="Program 6") #configuration root.title("Network Installation") listbox_2.insert(1, string_1) listbox_2.insert(2, string_2) listbox_2.insert(3, string_3) listbox_2.insert(4, string_4) listbox_2.insert(5, string_5) listbox_2.insert(6, string_6) listbox_2.insert(7, string_7) listbox_2.insert(8, string_8) listbox_2.insert(9, string_9) listbox_2.insert(10, string_10) listbox_2.insert(11, string_11) optionmenu_1.config(width=15) scrollbar_1.config(command=listbox_2.yview) #grid additions label_1.grid(row=0, column=5) label_2.grid(columnspan=6, row=1, column=0, sticky=E) entry_1.grid(row=0, column=6) button_1.grid(columnspan=2, row=7, column=5) listbox_2.grid(rowspan=6, columnspan=6, row=2, column=0) scrollbar_1.grid(rowspan=6, row=2, column=4, sticky=N+S) optionmenu_1.grid(columnspan=3, row=0, column=1) label_3.grid(row=0, column=0) all_listbox_items = listbox_2.get(0, END) root.mainloop() And anyone showing up to this question that might be looking for a search box that filters the listbox (as opposed to highlighting them like this question is asking) to show only the relevant items pertaining to the search, you can use this: import tkinter as tk root = tk.Tk() def update_listbox(*args): search_term = search_var.get() listbox.delete(0, tk.END) for item in all_items: if search_term.lower() in item.lower(): listbox.insert(tk.END, item) search_var = tk.StringVar() search_var.trace('w', update_listbox) searchbox = tk.Entry(root, textvariable=search_var) searchbox.pack(fill=tk.X, expand=False) listbox = tk.Listbox(root) for i in ['Adam', 'Lucy', 'Barry', 'Bob']: listbox.insert(tk.END, i) listbox.pack() all_items = listbox.get(0, tk.END) root.mainloop()
{ "language": "en", "url": "https://stackoverflow.com/questions/27281397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parallelize with numba's prange and passing along a tuple I tried to parallelize as follows, closely following the documented example: @numba.jit(nopython=True) def foo(uIdx, grids): return uIdx @numba.jit(nopython=True, parallel=True) def bar(grid, grids): LIdxGrid = np.zeros(len(grid)) for uIdx in numba.prange(len(grid)): LIdxGrid[uIdx] = foo(uIdx, grids) return LIdxGrid if __name__ == '__main__': import numpy as np grid = np.arange(12) grids = (grid, grid) bar(grid, grids) But it appears not to work. The issue seems to stem from passing along grids (without even using it in the final foo function). If I remove that reference in foo and bar, it works: bar(grid, 0) Out[47]: array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.]) How do I work fix/around this issue? The full traceback is Traceback (most recent call last): File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/errors.py", line 491, in new_error_context yield File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 216, in lower_block self.lower_inst(inst) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 365, in lower_inst func(self, inst) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/parfor.py", line 119, in _lower_parfor_parallel index_var_typ) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/parfor.py", line 691, in call_parallel_gufunc sout, {}) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/parallel.py", line 251, in build_gufunc_wrapper cache=cache) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 460, in build_gufunc_wrapper return wrapcls(py_func, cres, sin, sout, cache).build() File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 411, in build self._build_wrapper(wrapperlib, wrapper_name) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 372, in _build_wrapper arg_steps, i, step_offset, typ, sym, sym_dim) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/npyufunc/wrappers.py", line 614, in __init__ "argument #{1}".format(typ, i + 1)) TypeError: scalar type tuple(array(int64, 1d, C) x 2) given for non scalar argument #2 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-46-b6a12a1ce616>", line 3, in <module> bar(grid, grids) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 360, in _compile_for_args raise e File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 311, in _compile_for_args return self.compile(tuple(argtypes)) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 618, in compile cres = self._compiler.compile(args, return_type) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/dispatcher.py", line 83, in compile pipeline_class=self.pipeline_class) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 871, in compile_extra return pipeline.compile_extra(func) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 365, in compile_extra return self._compile_bytecode() File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 802, in _compile_bytecode return self._compile_core() File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 789, in _compile_core res = pm.run(self.status) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 251, in run raise patched_exception File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 243, in run stage() File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 676, in stage_nopython_backend self._backend(lowerfn, objectmode=False) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 626, in _backend lowered = lowerfn() File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 613, in backend_nopython_mode self.flags) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/compiler.py", line 990, in native_lowering_stage lower.lower() File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 135, in lower self.lower_normal_function(self.fndesc) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 176, in lower_normal_function entry_block_tail = self.lower_function_body() File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 201, in lower_function_body self.lower_block(block) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/lowering.py", line 216, in lower_block self.lower_inst(inst) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/contextlib.py", line 99, in __exit__ self.gen.throw(type, value, traceback) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/errors.py", line 499, in new_error_context six.reraise(type(newerr), newerr, tb) File "/home/foo/anaconda3/envs/myenv3/lib/python3.6/site-packages/numba/six.py", line 659, in reraise raise value numba.errors.LoweringError: Failed at nopython (nopython mode backend) scalar type tuple(array(int64, 1d, C) x 2) given for non scalar argument #2 File "<ipython-input-44-ec97cbf0b87b>", line 9: def bar(grid, grids): <source elided> LIdxGrid = np.zeros(len(grid)) ^ [1] During: lowering "id=7[LoopNest(index_variable = parfor_index.317, range = (0, grid_size0.315, 1))]{51: <ir.Block at <ipython-input-44-ec97cbf0b87b> (9)>}Var(parfor_index.317, <ipython-input-44-ec97cbf0b87b> (9))" at <ipython-input-44-ec97cbf0b87b> (9) ------------------------------------------------------------------------------- This should not have happened, a problem has occurred in Numba's internals. A: The support for reference counted items (like np.ndarrays) is quite new (since numba 0.39) and I am not sure if working with tuples of ref. counted items already works. Afaik tuples of ref. counted items are not yet supported. So to make sure your code works, you must replace the tuple with a list: if __name__ == '__main__': import numpy as np grid = np.arange(12) grids = [grid, grid] bar(grid, grids) AND make sure you have numba version 0.39 installed! Otherwise this won't work as well. Of course a list is not a tuple, so this is only a workaround. But there is no other way to solve this problem, as long as tuples of ref. counted items are not fully supported.
{ "language": "en", "url": "https://stackoverflow.com/questions/51537589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: isDst in Time Zone in C language I am trying to figure out on making a time from the values i choose (dynamically) I tried giving a date of 31st march 03:10pm and trying to go back a month with 03:10Pm which is 28th Feb 03:10Pm. But i am getting a value as 04:10Pm. I set the isdst = -1 to do this bit; but still it fails. Any ideas. Tm->tm_mon = ReportMonth; Tm->tm_mday = ReportEndDay; Tm->tm_hour = TimeOfDay/60; Tm->tm_min = TimeOfDay%60; Tm->tm_sec = 59; Tm->tm_isdst = -1;
{ "language": "en", "url": "https://stackoverflow.com/questions/15789783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does not contain a definition for GetDataFromNumber But i have it defined? public void button2_Click(object sender, System.EventArgs e) { string text = textBox1.Text; Mainform = this; this.Hide(); GetSchedule myScheduleFinder = new GetSchedule(); string result = myScheduleFinder.GetDataFromNumber(text);// says there is no definition if (!string.IsNullOrEmpty(result)) { MessageBox.Show(result); } else { MessageBox.Show("Enter A Valid ID Number!"); } } says it does not contain definition for it but on my GetSchedule .cs file i have it defined public string GetDataFromNumber(string ID)//defined here { foreach (IDnumber IDCandidateMatch in IDnumbers) { if (IDCandidateMatch.ID == ID) { StringBuilder myData = new StringBuilder(); myData.AppendLine(IDCandidateMatch.Name); myData.AppendLine(": "); myData.AppendLine(IDCandidateMatch.ID); myData.AppendLine(IDCandidateMatch.year); myData.AppendLine(IDCandidateMatch.class1); myData.AppendLine(IDCandidateMatch.class2); myData.AppendLine(IDCandidateMatch.class3); myData.AppendLine(IDCandidateMatch.class4); //return myData; return myData.ToString(); } } return ""; } GetSchedule Class public class GetSchedule { public GetSchedule() { IDnumber[] IDnumbers = new IDnumber[3]; IDnumbers[0] = new IDnumber() { Name = "Joshua Banks", ID = "900456317", year = "Senior", class1 = "TEET 4090", class2 = "TEET 3020", class3 = "TEET 3090", class4 = "TEET 4290" }; IDnumbers[1] = new IDnumber() { Name = "Sean Ward", ID = "900456318", year = "Junior", class1 = "ENGNR 4090", class2 = "ENGNR 3020", class3 = "ENGNR 3090", class4 = "ENGNR 4290" }; IDnumbers[2] = new IDnumber() { Name = "Terrell Johnson", ID = "900456319", year = "Sophomore", class1 = "BUS 4090", class2 = "BUS 3020", class3 = "BUS 3090", class4 = "BUS 4290" }; } public class IDnumber { public string Name { get; set; } public string ID { get; set; } public string year { get; set; } public string class1 { get; set; } public string class2 { get; set; } public string class3 { get; set; } public string class4 { get; set; } public static void ProcessNumber(IDnumber myNum) { StringBuilder myData = new StringBuilder(); myData.AppendLine(myNum.Name); myData.AppendLine(": "); myData.AppendLine(myNum.ID); myData.AppendLine(myNum.year); myData.AppendLine(myNum.class1); myData.AppendLine(myNum.class2); myData.AppendLine(myNum.class3); myData.AppendLine(myNum.class4); MessageBox.Show(myData.ToString()); } public string GetDataFromNumber(string ID) { IDnumber[] IDnumbers = new IDnumber[3]; foreach (IDnumber IDCandidateMatch in IDnumbers) { if (IDCandidateMatch.ID == ID) { StringBuilder myData = new StringBuilder(); myData.AppendLine(IDCandidateMatch.Name); myData.AppendLine(": "); myData.AppendLine(IDCandidateMatch.ID); myData.AppendLine(IDCandidateMatch.year); myData.AppendLine(IDCandidateMatch.class1); myData.AppendLine(IDCandidateMatch.class2); myData.AppendLine(IDCandidateMatch.class3); myData.AppendLine(IDCandidateMatch.class4); //return myData; return myData.ToString(); } } return ""; } } } } A: Did you make sure GetDataFromNumber is inside the class definition, and not after the closing brace? A: Check that the GetSchedule class is in the same namespace that you are trying to call it from, or that it is referenced. It looks from your updated post like your function GetDataFromNumber is in a class called IDNumber - is this the problem? Try: IDnumber myNumber = new IDnumber(); myNumber.GetDataFromNumber(text); A: The problem is because you are creating web forms and copying the code from one page to another. When you do this you have to be careful and make sure that you don't change the first directive in the page. It tells the web for what behind the code page it should look for where it should find the definitions and behind code logic. The reason you are having this problem is cause when you copied and pasted from one page to another it brought the directive for the other page which more than likely you do not have the functions you are calling within your page defined. So just make sure you changed the first line in your web page to point to the right .cs file and class from which it inherits.
{ "language": "en", "url": "https://stackoverflow.com/questions/2725289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: fwrite function not working I am trying to write a simple program that opens the content of a binary file into a buffer and the searches that buffer for the occurrence of string which is '+' characters. It seems like to does find these characters even though my algorithm is a little flaky. Once it finds them it changes the character to some other character. Then it writes the same buffer back to file. It does not work as I tried opening the file in a hex editor and could not find the new string with the new characters. The file that gets modified prints out the string that I am trying to modify using fread and fwrite. Here is the code: #include <iostream> #include <stdio.h> #include <stdlib.h> #include <windows.h> using namespace std; char XyZ[] = "++++++++++++++++++++++++++"; //26 count int main() { int error = 0; FILE * pFile; unsigned int lSize; char * buffer; size_t result; int i = 0, j = 0; bool bfound = false; int count = 0; int startLocation = 0; pFile = fopen ( "E:\\DEVS\\Projects\\JustTesting\\FOpen\\Release\\Test.exe", "rb+" ); if (pFile==NULL) { cout << "Unable to open Test.exe" << endl; cout << GetLastError() << endl; } else { cout << "Successfully opened the file" << endl; // obtain file size: fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); cout << "Number of file size is " << lSize << endl; // allocate memory to contain the whole file: buffer = (char*) malloc (sizeof(char)*lSize); if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);} // copy the file into the buffer: result = fread (buffer,1,lSize,pFile); cout << "Total bytes read into our buffer is " << result << endl; if (result != lSize) { cout << "Error in reading the file" << endl; } else { for(i = 0; i < lSize; i++) { if(buffer[i] == '+') // '+' { //cout << "Found first one" << endl; startLocation = i; //j = i + 1; //cout << "Found the next one" << endl; while(buffer[++i] == '+') { buffer[i] = '@'; cout << "Found the next one" << endl; count++; } } } cout << "Found our string with count " << count << endl; } //for(int k = startLocation; k < startLocation + 5; k++) // buffer[k] = '@'; int value = fwrite (buffer , 1 , lSize , pFile ); cout << "bytes written to file is :" << value << endl; fclose (pFile); free (buffer); } return 0; } A: The first problem is your while: while(buffer[++i] == '+') So you've found your +, but in the while you first increase the position and then test whether the value is still +. That fails if you only have one + (and if you have several, the first is not overwritten). Instead, replace it with: for ( ; (buffer[i] == '+') && (i < lSize) ; i++) The next problem is that after fread, the file position is at the end. Your call to fwrite will thus append the modified buffer. To actually overwrite the file you first need to call rewind(pFile); again. A final note on fread/fwrite: you read and write lSize items, each 1 byte in size. That's pretty slow (try it with a one megabyte file). Instead you likely want the opposite: result = fread(buffer, lSize, 1, pFile); Note that result will then merely have 1 on success. The same applies for fwrite. A: Note that you would be trying to write the modified contents at the end of the file. Besides, switching between read and write operations need certain function calls in between to switch the operation mode. Try adding fseek( pFile, 0, SEEK_SET ); right before doing fwrite. Note that there may still be something wrong A: You open the file in rb (for reading), then write to it... I am not sure it will do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Questions about CoreData and pre-populated models To pre-populate CoreData in my app upon first launch, I have included a PreModel.sqlite file that was previously created by the app from data that it downloaded from a web service, which includes images. To populate the model, I do this: - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSLog(@"creating new store"); NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"PreModel.sqlite"]; if(![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]]) { NSString *sqlitePath = [[NSBundle mainBundle] pathForResource:@"PreModel" ofType:@"sqlite"]; if (sqlitePath) { NSError *error = nil; [[NSFileManager defaultManager] copyItemAtPath:sqlitePath toPath:[storeURL path] error:&error]; if (error) { NSLog(@"Error copying sqlite database: %@", [error localizedDescription]); } } } NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; } It seems to work. But I have 2 questions: * *If the sqlite file is just a database file and does not actually contain any images, how is the app finding and loading the images on first launch? *Even on subsequent runs of the app I see "creating new store" logged every time. Why is _persistentStoreCoordinator always nil? I am clearly setting it in the code. A: * *It's possible to store images in a database file, usually as binary blobs (which look like instances of NSData in Core Data). If you can provide more info about your model or the code that stores/loads the images, we can be more specific. *"Creating new store" is expected to get logged every time the app is launched in this instance. Even though the SQLite file is persistent on disk, you can't expect data structures in your code to stick around when your app is terminated - you need to create a new persistent store object for your program every time it launches. Think of it like assigning NSInteger x = 10, then expecting to be able to quit and relaunch your program while maintaining that x has the value 10. That's not how programs work - you'd need to reassign x = 10 before you can expect to read x and get 10 back. The variable _persistentStoreCoordinator works the same way here.
{ "language": "en", "url": "https://stackoverflow.com/questions/12322371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jupyter Notebook gets killed when using MaxPool layers I am training a neural-net model using Keras-CPU. It works fine when I don't add any MaxPool layers, but my jupyter kernel dies whenever I use a MaxPool layer. My whole data size is around 480 MB. My system has 128GB of memory, and it doesn't take more than 5-10 GB of memory when ran without MaxPool layers. My batch size is also small (32), and there is no significant increase in memory usage when I run the training. CPU usage goes up for a few seconds and then it drops back. There is an attached metric regarding the info of a single epoch; it just prints the start of the epochs: Epoch 1/2 and after that, my kernel dies. Here is the architecture of the network: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 382) 0 _________________________________________________________________ embedding_1 (Embedding) (None, 382, 100) 490600 _________________________________________________________________ conv1d_1 (Conv1D) (None, 382, 64) 12864 _________________________________________________________________ max_pooling1d_1 (MaxPooling1 (None, 191, 64) 0 _________________________________________________________________ conv1d_2 (Conv1D) (None, 191, 128) 16512 _________________________________________________________________ max_pooling1d_2 (MaxPooling1 (None, 95, 128) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 12160) 0 _________________________________________________________________ dense_1 (Dense) (None, 64) 778304 _________________________________________________________________ dropout_1 (Dropout) (None, 64) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 8320 _________________________________________________________________ dense_3 (Dense) (None, 1) 129 ================================================================= Total params: 1,306,729 Trainable params: 1,306,729 Non-trainable params: 0 Here is the method where I train my neural network: def get_nnn(train_data_shape, max_val, emb_shape, drop_out, pre_batch_size, pre_batch_epoch,\ final_batch_size, final_batch_epoch, ls_start, lr_end,class_weight, lr_decay_pat,\ lr_decay_rat,num_conv,conv_kernels,conv_neurons,train_data, train_lbl,test_data,test_lbl,loss_type='binary_crossentropy',\ act='sigmoid',use_emb=True,use_max_pool=True,custom_methods=[]): #A lot of params nnet = Input(shape=(train_data_shape,)) inp = nnet if use_emb: nnet = Embedding(max_val+1, emb_shape)(nnet) for i in range(num_conv): nnet = Conv1D(conv_neurons[i],conv_kernels[i], padding='same',activation='relu')(nnet) if use_max_pool: #Adding MaxPool here nnet = MaxPooling1D(pool_size=2)(nnet) nnet = Flatten()(nnet) nnet = Dense(64, activation='relu')(nnet) nnet = Dropout(drop_out)(nnet) nnet = Dense(128, activation='relu')(nnet) batch_size = final_batch_size epochs = final_batch_epoch lentrain = train_data.shape[0] exp_decay = lambda init, fin, steps: (init/fin)**(1/(steps-1)) - 1 steps = int(lentrain / batch_size) * epochs lr_init, lr_fin = ls_start, lr_end lr_decay = exp_decay(lr_init, lr_fin, steps) output = Dense(1, activation=act)(nnet) model = Model(inputs=inp, outputs=output) model.compile(loss=loss_type, optimizer=Adam(lr=ls_start, decay=lr_decay), metrics=['accuracy',precisioned,recalled,f1]+custom_methods) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=lr_decay_rat, patience=lr_decay_pat, min_lr=lr_end) print(model.summary()) model.fit(train_data, train_lbl, epochs=pre_batch_epoch, batch_size=pre_batch_size, class_weight=class_weight, validation_data=(test_data, test_lbl), callbacks=[reduce_lr]) model.fit(train_data, train_lbl, epochs=epochs, batch_size=batch_size, class_weight=class_weight, validation_data=(test_data, test_lbl), callbacks=[reduce_lr]) return model
{ "language": "en", "url": "https://stackoverflow.com/questions/50985792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mongodb - Multiple LET and AS assignments to use within the same pipeline How to perform multiple let and as and use them within the same pipeline. I have the following query but assignment defaults to userTo. Both userFrom and userTo are from users collection { $lookup: { from: "users", let: { userFrom: "$from", }, as: "userFrom", let: { userTo: "$to", }, as: "userTo", pipeline: [ { $match: { $expr: { $or: [ { $eq: [ "$$userFrom", "$_id" ] }, { $eq: [ "$$userTo", "$_id" ] } ] } } }, A: You are not using them correctly. as specifies the name of the output array of the $lookup. There is only 1 result set per lookup so only 1 as would be needed. let specifies the variables you want to use in the sub-pipeline. You can put them in an object if you want to use multiple variables. Your code should look like this: db.collection.aggregate([ { $lookup: { from: "users", let: { userFrom: "$from", userTo: "$to" }, pipeline: [ { $match: { $expr: { $or: [ { $eq: [ "$$userFrom", "$_id" ] }, { $eq: [ "$$userTo", "$_id" ] } ] } } } ], as: "userLookup" } } ])
{ "language": "en", "url": "https://stackoverflow.com/questions/75196553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Triggering method from a started jar File which was loaded via Runtime...exec("..") in a java file this is what I want to do: I need to start two jar Files from out of a java file and i want to call a method from the firstly started jar file, when i read a specific status from the second jar file. I figured out how to read the outsputstream from that jar files. (I also know, that its not the jar file who's printing out, but the classes inside the jar file. I just fomulated the question in this way to clearly explain that I use a java file in which I start two jar files) long l = System.currentTimeMillis(); Process theProcess1 = Runtime.getRuntime().exec("java -jar \"C:/test.jar\""); inStream = new BufferedReader(new InputStreamReader( theProcess1.getInputStream() )); ... I can now read the jar file's output. On a special keyword I want the firstly started jar to run a certain method (non static). e.g.: if(theProcess2 output a certain statuscode) { start a certain Method from executed jar file "in" theProcess1 } I think it could be possible by using the theProcess1 output, but I don't know how to read this stream in the jar File. (The jar file doesn't know that it was started via the java file. Any Ideas? A: You can't access another java process classloader class definitions. See this question for how to load a jar properly : How to load a jar file at runtime Once your jar is loaded, you can use Class.forName to access the second jar desired class EDIT : Here is a little snippet to help you read process standard output. //open a buffered reader on process std output InputStreamReader ir = new InputStreamReader(theProcess1.getInputStream()); BufferedReader in = new BufferedReader(ir); //read it line per line String line; while ((line = in.readLine()) != null) { System.out.println(line); }
{ "language": "en", "url": "https://stackoverflow.com/questions/15790842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vbs open, loop through message, close application I have solved a few of these issues with the code below. The part where I'm getting stuck is looping back through the message popup. If the answer is Yes, I want it to loop back to the top; if the answer is No, I want it to exit the loop and close the program; if the message box times out, I want it to exit the loop and close the program as well. Please see my code below. Thank you in advance for your help. Dim PromptTime, DelayTime, StrAppPath, AppExec, MsgTxt, intAnswer, intRet Set objShell = CreateObject("WScript.Shell") PromptTime = 5 DelayTime = 4 StrAppPath = "C:Windows\" AppExec = "Notepad.exe" MsgTxt = "Are you still using Notepad?" intMsgTimeout = 5 Set WshShell= CreateObject("WScript.Shell") objShell.Run chr(34) & StrAppPath & AppExec & chr(34), 1, "False" Do WScript.Sleep (1000 * 1 * PromptTime) 'intAnswer = MsgTxt(MsgTxt, vbYesNo, "Please select Yes or No") intResult = WshShell.Popup(MsgTxt, intMsgTimeout, "Warning!", vbYesNo) Select Case WshShell Case vbYes If intResult = vbYes Then Do Case vbNo If intResult = vbNo Then Exit Do 'Case Else If intResult = Else Then Exit Do End Select Loop taskKill = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & taskKill & "\root\cimv2") Set processlistFull= objWMIService.ExecQuery _ ("Select * from Win32_Process Where name = 'Notepad.exe'") For Each killPro In processlistFull killPro.Terminate() Next Set objShell = Nothing Set objWmi = Nothing Set objQResult = Nothing A: I discovered a method of doing this through 'Loop While' and removing the Select Case: Do WScript.Sleep (1000 * 1 * PromptTime) Loop While WshShell.Popup("Are you still using Syteline?", 5, "Please select yes or no", vbYesNo) = vbYes
{ "language": "en", "url": "https://stackoverflow.com/questions/53191306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MIPS32 Stackframe broken? So here the code as wished: PROGRAM 1 .text .globl main main: li $t0, 10 mtc1 $t0, $f12 cvt.s.w $f12, $f12 # 10.0 as single in $f12 jal printFloat li $v0, 4001 #sys_exit syscall printFloat: addi $sp, $sp, -4 #opens the stack frame sw $ra, 0($sp) #saves the return adress cvt.d.s $f12, $f12 #converts the single to double la $a0, strDouble #arguments needed for printf ("%f" in $a0, upper 32 bit of the float in $a2, lower ones in $a1) mfc1 $a1, $f12 mfc1 $a2, $f13 jal printf jal fflush la $a1, strBreakLine #arguments needed for printf (Adress of String in $a1, "%s" in $a0) la $a0, strStringOut jal printf jal fflush lw $ra, 0($sp) #restores the return adress addi $sp, $sp, 4 #pops the stack frame jr $ra .data strDouble: .asciiz "%f" strStringOut: .asciiz "%s" strBreakLine: .asciiz "\n" phm15fix@ci20:~$ gcc -o test -g test1.s phm15fix@ci20:~$ ./test 10.000000 PROGRAM 2 .text .globl main main: li $t0, 10 mtc1 $t0, $f12 cvt.s.w $f12, $f12 # 10.0 as single in $f12 jal printFloat li $v0, 4001 #sys_exit syscall printFloat: addi $sp, $sp, -4 #opens the stack frame sw $ra, 0($sp) #saves the return adress cvt.d.s $f12, $f12 #converts the single to double la $a0, strDouble #arguments needed for printf ("%f" in $a0, upper 32 bit of the float in $a2, lower ones in $a1) mfc1 $a1, $f12 mfc1 $a2, $f13 jal printf jal fflush jal printNewLine lw $ra, 0($sp) #restores the return adress addi $sp, $sp, 4 #pops the stack frame jr $ra printNewLine: addi $sp, $sp, -4 #opens the stack frame sw $ra, 0($sp) #saves the return adress la $a1, strBreakLine #arguments needed for printf (Adress of String in $a1, "%s" in $a0) la $a0, strStringOut jal printf jal fflush lw $ra, 0($sp) #restores the return adress addi $sp, $sp, 4 #pops the stack frame jr $ra .data strDouble: .asciiz "%f" strStringOut: .asciiz "%s" strBreakLine: .asciiz "\n" phm15fix@ci20:~$ gcc -o test -g test1.s phm15fix@ci20:~$ ./test 10.000000 Bus error PROGRAM 3 .text .globl main main: li $t0, 10 mtc1 $t0, $f12 cvt.s.w $f12, $f12 # 10.0 as single in $f12 jal function li $v0, 4001 #sys_exit syscall function: addi $sp, $sp, -4 #opens the stack frame sw $ra, 0($sp) #saves the return adress jal printFloat lw $ra, 0($sp) #restores the return adress addi $sp, $sp, 4 #pops the stack frame jr $ra printFloat: addi $sp, $sp, -4 #opens the stack frame sw $ra, 0($sp) #saves the return adress cvt.d.s $f12, $f12 #converts the single to double la $a0, strDouble #arguments needed for printf ("%f" in $a0, upper 32 bit of the float in $a2, lower ones in $a1) mfc1 $a1, $f12 mfc1 $a2, $f13 jal printf jal fflush jal printNewLine lw $ra, 0($sp) #restores the return adress addi $sp, $sp, 4 #pops the stack frame jr $ra printNewLine: addi $sp, $sp, -4 #opens the stack frame sw $ra, 0($sp) #saves the return adress la $a1, strBreakLine #arguments needed for printf (Adress of String in $a1, "%s" in $a0) la $a0, strStringOut jal printf jal fflush lw $ra, 0($sp) #restores the return adress addi $sp, $sp, 4 #pops the stack frame jr $ra .data strDouble: .asciiz "%f" strStringOut: .asciiz "%s" strBreakLine: .asciiz "\n" At the end of every program is the specific output. The first program works fine. In the second program I made an extra function for printing a new line. If I run this I get a "bus error". And in the third program I made a dummy function to simulate another stacklevel. There is also a "bus error" and the number i want to print is not printing. I think there are some problem with our stack. I used the debugger and if I load my return-address from stack I have the wrong address in my $ra and i dont know why. If it jumps to this address i get the "bus error". Here are the functions: PRINT_DOUBLE: addi $sp, $sp, -4 sw $ra, 0($sp) la $a0, strDouble mfc1 $a1, $f12 mfc1 $a2, $f13 jal printf nop # lw $a0, stdout # jal fflush jal BREAK_LINE lw $ra, 0($sp) addi $sp, $sp, 4 jr $ra BREAK_LINE: addi $sp, $sp, -4 sw $ra, 0($sp) la $a0, strBreakLine jal PRINT_STRING lw $ra, 0($sp) addi $sp, $sp, 4 nop jr $ra PRINT_STRING: addi $sp, $sp, -4 sw $ra, 0($sp) add $a1, $a0, $zero la $a0, strStringOut jal printf la $a0, stdout lw $a0, 0($a0) jal fflush lw $ra, 0($sp) addi $sp, $sp, 4 nop jr $ra A: I've looked over your program and most of it looks fine. I think your stack save/restore is fine. But, I see at least one other problem. After every jal printf, you're doing an immediate jal fflush, so fflush will get printf's first argument [which is a string pointer] instead of a file descriptor pointer (e.g. stdout). Under the mips ABI, the $a0-$a3 registers may be modified/destroyed by the callee. So, after printf returns $a0 can be anything. All three programs seem to have this problem. IMO, if program 1 is working, it's just the luck of the draw (i.e.) whatever ends up in $a0 is harmless enough. That is, whatever is in it, points to a memory location that isn't a file descriptor but fflush tries to interpret it as one and lucks out. Also, for fflush, $a0 should point to an address that is word [4 byte] aligned. If it's not, that could be the source of the bus error. To fix this, change all fflush calls to: lw $a0,stdout jal fflush That should probably work, but, depending on what the gcc assembler does, you may have to do: la $a0,stdout lw $a0,0($a0) jal fflush I've seen that the buserror appears if I try to jump back from a function For example I jump to PRINT_DOUBLE, there I jump to BREAK_LINE and there I jump to PRINT_STRING If I jump then back to BREAK_LINE all is fine, but back from BREAK_LINE to PRINT_DOUBLE I get the buserror I've desk checked your code and [once again] seems fine. One way to debug this is to [using gdb] is to single step [with stepi] within your functions and put breakpoints after the the jal printf [or jal fflush]. Before and after each jal, note the $sp value. It must be the same. Do this for all your functions. Also, when returning from a function, note the $sp value, then the value from the lw [which goes into $ra]. They should all match the "expected" Further, $sp must be 4 byte aligned at all times. Actually, according to a mips ABI document I've seen [possibly dated], it says that stack frames must be 8 byte aligned. That may be overkill at this point, but I mention it. If you do lw from unaligned, that's an alignment exception, which will probably show up as SIGBUS. Further, check the $ra value [before doing the jr $ra]. It also must be the "expected" value and be 4 byte aligned. In other words, exactly which instruction produces the exception? Another thing you can do is to comment out some function calls. Start with the jal fflush. Then, comment out jal printf [in your sub-functions]. I note that you do a "naked" printf call at the outset, which seems fine. Keep doing this until the program stops faulting. This ought to help localize the area/call. You didn't state whether you were running this in a simulator like spim or mars or real H/W [possibly running linux]. I suspect real H/W. But, you could verify your logic by running under a simulator [I prefer mars] and provide dummy functions for printf and fflush that just do jr $ra. Note that neither spim nor mars can link to .o files. They work purely from source, so you can only use your .s If you're running on real H/W, gdb ought to be able to provide detailed information on the source of the exception. If not, create a C function that sets up a signal handler for SIGBUS using sigaction [see the manpage]. Then, put a breakpoint on the signal handler. One of the arguments to the signal handler is a pointer to a siginfo_t struct that has additional information. Note that for SIGBUS, the si_code field will have a BUS_* value that may have more information.The third argument, although void * is a pointer to something that can give you the register values at the time of the exception. In another answer I gave: mips recursion how to correctly store return address for a function another OP had a similar problem. My answer added some special stack alignment and check code that may give you some ideas.
{ "language": "en", "url": "https://stackoverflow.com/questions/37271004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: override form method from dll class i want to build dll file that deals with system.windows.forms.form how can i override any form method from dll class such as (WndProc)? public partial class MyDll { public MyDll(System.Windows.Forms.Form form) { // i want to override WinProc form from my dll file. } } my project is a "ClassLibrary" not a "WindowsFormsApplication" A: You can easily override the method in this way: protected override void WndProc(ref Message m){...} Here you can find some examples: http://msdn.microsoft.com/library/system.windows.forms.control.wndproc%28v=vs.110%29.aspx A: If you pass the form as a parameter you have the instance of the class, not the definition. You have to create your own Form, override the method as mentioned before and then pass this new Form to your MyDll constructor. for example: Create a new class library project. Add two files: - MyDllClass.cs - MyForm (add new->Window Form) public partial class MyForm : Form { protected override void WndProc(ref Message m) { //your code here base.WndProc(ref m); } } Then in MyDllClass.cs you will have public MyDllClass(Form your_form_here) { //your code here }
{ "language": "en", "url": "https://stackoverflow.com/questions/22562617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring boot one to one with foreign key I am want to store room details and room types in my db. I have created an entity for Room as follows. @Data @Entity public class Room { @Id private String room_id; private Boolean status; private Double price; private Long type; private Long occupancy; @OneToOne(fetch = FetchType.LAZY, optional = true) @JoinColumn(name = "type_id", nullable = false) private RoomType roomType; } I have create a RoomType entity as follows: @Data @Entity public class RoomType { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String type; } To save a Room Entity in my DB, the following is the request body format need to be given { "room_id": "string", "status": true, "price": 0, "roomType": { "id": 1, "type": "string" } } I want to have the request body as follows { "room_id": "string", "status": true, "price": 0, "roomType": 1 # This the roomType foreign key } I want to have one to one relationship, so when retrieving the Room details, I will get the roomType values also in the following format. { "room_id": "string", "status": true, "price": 0, "roomType": { "id": 0, "type": "string" } } Or Is there any better way to handle this type of problem in spring boot?? A: I think there are two different concepts in here: * *The inner representation of a Room in your service (The classes you use and their relations) *The outer representation (The one exposed by your API) If you want those two representation to be the same, you could just serialize/deserialize data using the Room class directly (which I assume is what you are currently doing). For example: @Controller class MyController { @PostMapping @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Room createRoom(@RequestBody Room room) { // Here room will be automatically deserialized from the request body // Do stuff with the received room in here // ... // Here the returned room will be automatically serialized to // the response body return createdRoom; } } However, if you don't want the inner and outer representations to be the same, you can use the DTO pattern (Data Transfer Object). Example in Spring here. Now, you would have three different classes, Room and it's DTOs: public class RoomRequestDTO { private String room_id; private Boolean status; private Double price; private Long type; private Long occupancy; private Integer roomType; // This is now an Integer // Setters and Getters ... } public class RoomResponseDTO { private String room_id; private Boolean status; private Double price; private Long type; private Long occupancy; private RoomType roomType; // This is a RoomType instance // Setters and Getters ... } Now, your controller would receive RoomRequestDTOs and send RoomResponseDTOs: @Controller class MyController { @PostMapping @ResponseStatus(HttpStatus.CREATED) @ResponseBody public RoomResponseDTO createRoom(@RequestBody RoomRequestDTO roomReqDTO) { Room room = ... // Convert from DTO to Room // Do stuff with the received room in here RoomResponseDTO roomRespDTO = ... // Convert to the DTO return roomRespDTO; } } This approach also has the advantage that you can now change the inner representaion of Room without afecting the API. This is, you could decide to merge the Room and RoomType classes in one, without affecting the outer representation. Note: In the example I have linked, they use the ModelMapper library. If you do not desire to introduce that dependecy, you could simple add a contructor and a method to the DTOs as such public RoomResponseDTO(Room room) { // Manually asign the desired fields in here this.id = room.getId(); // ... } public Room toRoom() { Room room = new Room(); // Manually asing the desired field in here room.setId(this.id); // ... return room; } However, this approach would make you have to change these methods whenever you want to change the representations of Room. The ModeMapper library does this for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/65759715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mocha: Can't stub function in file that was already required in another test file I'm using Mocha to run a test suite on fileToTest.js with requires greeting.js // --fileToTest.js-- const { greeting } = require('./greeting'); module.exports = () => greeting(); // --greeting.js-- module.exports.greeting = () => 'hi!'; By itself, this test file successfully stubs greeting. // --test2.js-- let parent; const sinon = require('sinon'); const chai = require('chai'); const greeting = require('../../greeting.js'); const { expect } = chai; describe('stubbed /hi', () => { before(async () => { sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!'); parent = require('../../parent.js'); }); after(async () => { greeting.greeting.restore(); }); it('should say bye', async function () { expect(parent()).to.be.equal('bye!'); }); }); However if I run a test suite and have another test file that requires fileToTest.js, like test1.js below, the first test above (test2.js) won't stub greeting. // --test1.js-- const chai = require('chai'); const fileToTest = require('../../fileToTest.js'); const { expect } = chai; describe('not stubbed /hi', () => { it('should say hi', () => { expect(fileToTest()).to.be.equal('hi!'); }); }); It seems once test1.js requires fileToTest, mocha doesn't reload the fileToTest on the test2.js's require. So fileToTest is stuck with the old greeting function. Whats the proper way to stub a function in this situation? Repo A: This answer worked. I had to delete the cache. before(async () => { delete require.cache[require.resolve('../../fileToTest.js')]; // <------ sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!'); fileToTest = require('../../fileToTest.js'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/66809269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: I get "Incorrect argument" error when i try to run a simple test on couchbase nodejs server var couchbase = require("couchbase"); var cluster = new couchbase.Cluster('127.0.0.1:8091'); var bucket = cluster.openBucket('beer-sample', function(err) { if (err) { throw err; } bucket.get('aass_brewery-juleol', function(err, result) { if (err) { throw err; } var doc = result.value; console.log(doc.name + ', ABV: ' + doc.abv); doc.comment = "Random beer from Norway"; bucket.replace('aass_brewery-juleol', doc, function(err, result) { if (err) { throw err; } console.log(result); process.exit(0); }); }); }); Here is my file. It's the example from here : http://docs.couchbase.com/developer/node-2.0/hello-couchbase.html So when i try to run the server with "nodejs test1.js" i get "Incorrect argument" error. At bucket.js, module.js and in cluster.js into node_modules/couchbase/lib/ I have installed couchbase and i have full nodejs installed. I'm new in this and i cant understand where is my mistake. Maybe something with the versions of the couchbase or the node version i dunno. Here is my full error which i get into the terminal: Error: Incorrect argument at New Bucket (home/anton/node_modules/couchbase/lib/bucket.js:213:16) at Object<anonymus> (home/anton/PhpstormProjects/couchbase/test1.js:6:22) at Cluster.openBucket (home/anton/node_modules/couchbase/lib/cluster.js:37:10) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:902:3 A: The "Canonical" format for connecting to a cluster is couchbase://host where host in your case is localhost. Depending on the version you're using, newer enhancements may have been added to allow for the common host:8091 antipattern, but would still be incorrect. Chances are your code can still work if you upgrade to a newer version - but you should still use the couchbase:// variant (without the port).
{ "language": "en", "url": "https://stackoverflow.com/questions/28027413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return previous row when using boolean indexing Question How do I return the previous row, as well as the row meeting a condition, when using boolean indexing? Example: sodf = pd.Series([9,10,10,9,10,11]) sodf 0 9 1 10 2 10 3 9 4 10 5 11 dtype: int64 Boolean condition: sodf[sodf == 11] 5 11 Desired output: 4 10 5 11 A: You can get the index of sodf==11 and then get the loc value -1 onwards. Here's how to do it. import pandas as pd sodf = pd.Series([9,10,10,9,10,11]) x = sodf[sodf == 11].index[0] print (sodf.loc[x-1:]) Output will be: 4 10 5 11 If you just want the value of the previous row, then you can also give print (sodf.loc[x-1]) The output will be just the value as this is a pd.Series with one column: 10 A: Try something like this: i = sodf[(sodf == 9)].index i = i.union(i-1) i = i[i>=0] sodf[i] Output 0 9 2 10 3 9 dtype: int64
{ "language": "en", "url": "https://stackoverflow.com/questions/66825503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Something changed: no longer able to SSH to home: xFinity I need some help understanding the current situation that I am having with my home network. My home network is very simple: My ISP is xFinity with a Dynamic IP that doesn't change very frequently. Last IP change occured 6 months ago. It comes into an Arris SB6183 modem that I own. From the Arris, it goes into a Linksys E8540 WiFi 6 Router (or a Netgear R6250 DD-WRT due to troubleshooting). From here, I only have 2 computers: one Linux Desktop, and one personal Windows laptop that I use for web-browsing. The Linux Desktop machine (LAN IP is 192.168.1.200) has SSHD Service on Port 22. The Router port forwards incoming SSH 22 connection from Internet to Port 22 on 192.168.1.200. Router firewall (SPI) is disabled. Everything stopped working about 2 weeks ago. I am not able to SSH from outside into my Linux Desktop machine. If I am on the internal LAN, then SSH works just fine. Using CanYouSeeMe.org shows me that Port 22 cannot connect: "Reason: connection timed out" Here is what I tried: * *Removed the Router and Laptop and plugged in the Linux Desktop straight into the Arris modem. SSH attempts still shows "Request timed out" *Made sure that UFW Firewall on Linux is off. No Fail2Ban. *Replaced the Linksys E8450 with Netgear R6250 DD-WRT. No change. *Called xFinity Customer Support and asked "Is Comcast blocking external incoming IPs to Port 22 ?" they responded "We don't block Port 22" *Contacted Comcast Customer Security Assurance and Abuse and asked them to verify if my profile has some Security Profile/Screen in place or some sort of flag. They responded NO. Then, finally I put a Port Forwarding rule on the router: incoming connection on port 2222 go to SSH 22 on Linux Desktop. And this works!! If I initiate external SSH connection attemps on port 2222 I do indeed connect to my Linux desktop. In a related news, my Reolink Security APP on my Android Samsung phone no longer connects to my Home Camera over Cellular Data. It connects fine if my Phone connets to the Lan over WiFi. What are your thoughts ? Does it look like my ISP is blocking incoming connections ? Any help greatly appreciated!
{ "language": "en", "url": "https://stackoverflow.com/questions/75501076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading from file line by line known structure but length is unknown I'm sorry to ask this question, because I found similar answered questions, but I'm having difficulty to understand how to read lines of unknown length but the structure is the same. Each line is structured by the following: name:id:buyingPrice:sellingPrice:profit:quantity The names and IDs are strings while the rest are doubles. My problem is I don't know how to setup a while that reads and stores each field, would it be possible to get a detailed explanation on how to accomplish this? Here's my read of the file(just with strings) : file = fopen("fileData.txt", "rt"); if(file != NULL){ char lineSize[128] = ""; while(fgets(line, 128, file) != NULL){ fscanf("%s:%s:%s:%s:%s:%s", string1, string2, string3, string4, string5, string6); } fclose(file); A: Have you thought about using strtok to parse the tokens after the fgets? A: What I would use is the 'a' modifier for the scanf-format: Simply say 'fscanf("%as:%as:...", ...)', pass in the addresses of unallocated pointers and let fscanf malloc them for you. This originated as a gnu extension, but AFAIK, it has made it into the C11 standart.
{ "language": "en", "url": "https://stackoverflow.com/questions/16882633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I use the new HTML5 semantic elements? I'm in the process of upgrading my website, and this involves the decision of using the new HTML5 semantic elements <nav> <header> <footer> <aside> <section> over regular old <div> elements. I do plan on supporting IE7 and IE8, but I know that these versions don't support the above semantic elements. I've read up about 'plugins' like Modernizr, Initializr and HTML5shiv, and I know that older browsers will then support the new elements IF JavaScript is enabled, but what am I supposed to do if it's not? By default, the <html> tag is given the class of no-js and if JavaScript is enabled, Modernizr/Initializr replaces this class with js. That's all well and good, but there are some things I'm uncertain about. So far, what is covered? Sorted * *IF JavaScript is enabled, IE7 and IE8 are supported by Modernizr/Initializr. *With a reset.css file, other older browsers support these new tags. *Modern browsers are all fine. Problems * *IF JavaScript is disabled, what am I supposed to do about IE8 and below? The no-js class is added to the <html> tag, so what exactly can I do with that? *How can I use <noscript> to my advantage here? I don't want to make pages too large with coding. So, aside from those questions, I also want to ask if it's really worth using these tags, when I can just use good ol' <div> tags which would both support older browsers and also keep file sizes down by eliminating the required coding to make the new tags work in older browsers? Thank you, Dylan. A: It's good practice to use both, for example <nav> <div> <ul> <!-- etc --> </ul> </div> </nav> If you need to support those obsolete browsers, I wouldn't do anything more than that. The benefits, such as they are, are not worth the extra effort. A: I do plan on supporting IE7 and IE8, but I know that these versions don't support the above semantic elements. I've read up about 'plugins' like Modernizr, Initializr and HTML5shiv, and I know that older browsers will then support the new elements IF JavaScript is enabled, but what am I supposed to do if it's not? If JavaScript is not enabled, then while the content of the new elements will be shown, CSS will not be correctly applied to them. While in theory you could use a noscript element to trigger a redirect to a version of the page not using the new elements (via a meta refresh tag within the noscript), then you'd be maintaining two versions of your site. For example, given this page: Live Copy <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>HTML5 Elements</title> <style> nav { color: green; } </style> </head> <body> <nav><ul><li>This text should be green</li></ul></nav> </body> </html> ...early versions of IE will show the text in the default color. Adding the HTML5 shiv prior to the style element: <script src="http://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6.2/html5shiv.js"></script> ...which as you know requires JavaScript, makes the text green: Live Copy A: It's not necessary to follow the new semantic. New semantic is developed mostly for search engines, not for site functionality. If you really want to support IE, do it for IE. If you really consider no-script cases and CSS is not enough for you, than all you can do is PHP/ASP magic. One my friend works exclusively in Flash, because no js, totally client side, no cares about browsers... Who knows... A: Should I use the new HTML5 semantic elements? Yes. IF JavaScript is disabled, what am I supposed to do about IE8 and below? The no-js class is added to the tag, so what exactly can I do with that? You can do something like this, HTML <div id='wrapper'> // Whole website coding here </div> <div id='old-browsers'> Use an upgraded browser </div> CSS .no-js #wrapper { display: none; } #old-browsers { display: none; } .no-js #old-browsers { display:block; } How can I use to my advantage here? I don't want to make pages too large with coding. IE Consideration: IE7 is 7 years old and most developers today do not support it. IE7 / IE8 users with js disabled is pretty low and you shouldnt develop for those exceptions. Instead you should give them a suggestion to upgrade with above method. You can use the noscript tag for the same usecase. A: What you could do (and what a lot of big website's do) is to display a notice when javascript is disabled (optionally when the browser is IE7 or IE8 but you'll need a serverside check for that), that the website would not be displayed the way it is supposed to. See "How to detect if JavaScript is disabled?" on how to do so. Only 5.3% (source) of internet users are using Internet Explorer < 8 and 0.25% to 2% (source) of the total users have Javascript disabled. You could spend a lot of time making a smooth solution for max 5% x 2% = 0,01% of your visitors or you could spend 5 minutes building the notice system I described.
{ "language": "en", "url": "https://stackoverflow.com/questions/19744045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why Doesn't CreateProcess() Work? I have a program that attempts to restart Explorer in Windows 7; it first ends the process, then starts it again. Simple? So it looks -- it indeed seems to work. However, I noticed something funny: When I try to start a program (say, XP's Power Calculator powertoy) under compatibility mode, it no longer works! Nothing happens -- the process is created and immediately quits. If I run Explorer through the Run dialog of Task Manager, the program runs fine. What's going on?! #include <windows.h> int main() { PROCESS_INFORMATION pi; STARTUPINFO si = {sizeof(si)}; TCHAR path[] = TEXT("explorer"); DWORD f = 0; //I tried a variety of these flags; didn't work return CreateProcess(NULL, path, NULL, NULL, FALSE, f, NULL, NULL, &si, &pi); } Edit 1: * *The fact that it was 32-bit with WOW64 redirection disabled made no difference. I made it 64-bit and the issue was the same. *I tried ShellExecute but it didn't work either. Edit 2: The same exact code just worked for me a couple of times, and then stopped working again... huh? A: This isn't really an answer to the "why", but I managed to find out how to fix it myself: Instead of copying environmental variables from the current process, if I copy them with CreateEnvironmentBlock, then it works. I still haven't figured out what's causing it, though...
{ "language": "en", "url": "https://stackoverflow.com/questions/6411866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flicker in Gradient panel I have inherited a control from TPanel and in the Paint event handler, I have drawn the entire client rect using a gradient. This works perfectly fine until the user resizes. When the panel is resized, the panel component flickers too much. How can i avoid this flicker. I saw the gradients in MS office 2007, even if we resize the client area, there will not be a flicker. Please enlighten me on this. Thanks in anticipation A: You may want to look at this question How to eliminate the flicker on the right edge of TPaintBox (for example when resizing) Good overview of options to avoid flicker and also for TPanel. Edit : I made a quick test in my Delphi XE version on windows 7. With this code I cannot reproduce any flicker. The inherited Paint is removed and the Paint routine is quite fast. If you still can see flicker, the proposal from Simon can be implemented, but better keep the bitmap created for the lifetime of the component itself. unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TGradientPanel = class(TPanel) protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; end; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); private { Private declarations } sPanel : TGradientPanel; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} Uses Math; procedure GradVertical(Canvas:TCanvas; Rect:TRect; FromColor, ToColor:TColor) ; var Y:integer; dr,dg,db:Extended; C1,C2:TColor; r1,r2,g1,g2,b1,b2:Byte; R,G,B:Byte; cnt:Integer; begin C1 := FromColor; R1 := GetRValue(C1) ; G1 := GetGValue(C1) ; B1 := GetBValue(C1) ; C2 := ToColor; R2 := GetRValue(C2) ; G2 := GetGValue(C2) ; B2 := GetBValue(C2) ; dr := (R2-R1) / Rect.Bottom-Rect.Top; dg := (G2-G1) / Rect.Bottom-Rect.Top; db := (B2-B1) / Rect.Bottom-Rect.Top; cnt := 0; for Y := Rect.Top to Rect.Bottom-1 do begin R := R1+Ceil(dr*cnt) ; G := G1+Ceil(dg*cnt) ; B := B1+Ceil(db*cnt) ; Canvas.Pen.Color := RGB(R,G,B) ; Canvas.MoveTo(Rect.Left,Y) ; Canvas.LineTo(Rect.Right,Y) ; Inc(cnt) ; end; end; constructor TGradientPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); Self.ParentBackground := FALSE; end; procedure TGradientPanel.Paint; var rect : TRect; begin //inherited; // Avoid any inherited paint actions as they may clear the panel background rect := GetClientRect; GradVertical( Self.Canvas, rect, clBlue, clRed); end; procedure TForm1.FormCreate(Sender: TObject); begin sPanel := TGradientPanel.Create( Self); sPanel.Parent := Self; sPanel.Top := 10; sPanel.Left := 10; sPanel.Width := 300; sPanel.Height := 300; sPanel.Anchors := [akLeft,akRight,akTop,akBottom]; sPanel.Enabled := TRUE; sPanel.Visible := TRUE; end; end. A: A way to reduce flicker is to draw the gradient to a temporary bitmap the draw the entire contents of the bitmap to the panel. This method assumes you have an OnPaint method and a canvas to draw on in your inherited panel. So something like this (untested) var bmp : Tbitmap; procedure AfterConstruction; begin bmp := TBitmap.Create; end; procedure Destroy() begin if Assigned(bmp) then FreeandNil(bmp); end; //redraw you bmp gradient procedure Panel1.OnResize(); begin if Assigned(bmp) then //ensure the bmp s created in your constructor begin try bmp.SetBounds(Panel1.Clientrect); //ensure the bmp is the same size as the panel //draw your gradient on the bmp Panel1.OnPaint();//repaint the tpanel finally bmp.Free; end; end; //paint to the panel procedure Panel1.OnPaint() begin Panel1.Canvas.Draw(0,0,bmp); //use the OnPaint method to draw to the canvas end; end; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7196192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jsf cascading list How do I cascade the lists so if user changes selection in selectedCategory list it should update the selectedTo list. Here is my snippet: <h:selectOneMenu id="selectedCategory" value="#{converterBean.selectedCategory}"> <f:ajax execute="selectedCategory" render="selectedFrom"/> <f:selectItems value="#{converterBean.categories}"/> </h:selectOneMenu> <h:selectOneListbox id="selectedFrom" value="#{converterBean.selectedFrom}" size="5"> <f:selectItems value="#{converterBean.fromList}"/> <f:ajax execute="selectedCategory selectedFrom" render="selectedTo"/> </h:selectOneListbox> <h:selectOneListbox id="selectedTo" value="#{converterBean.selectedTo}" size="5"> <f:selectItems value="#{converterBean.toList}"/> </h:selectOneListbox> I notice that it updates the selectedFrom list but does not cascade further to selectTo list. As per suggestion to try render both selectedFrom and selectedTo for category selection the request posted from the page is: POST http://localhost:8081/converter_web/faces/converter.xhtml HTTP/1.1 Accept: */* Faces-Request: partial/ajax Content-Type: application/x-www-form-urlencoded;charset=UTF-8 Referer: http://localhost:8081/converter_web/ Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) Host: localhost:8081 Content-Length: 1253 Connection: Keep-Alive Pragma: no-cache Cookie: JSESSIONID=DDDEA598A60CC468763C36B536513B41 converter_form=converter_form&converter_form%3AselectedCategory=temperature&converter_form%3AselectedFrom=mm&converter_form%3AselectedTo=cm&converter_form%3Avalue=0.0&javax.faces.ViewState=b%2BArKl5NJujWibUQzHf3dUG2JlT%2Bnq7KygA2%2FXpXXscCouBr5xT9Br%2BmoP78%2FvuPAYG%2Bi7Q0jFEKGqJpFgRo%2BDU4ZV251yac84pu3bZ71V9j%2BHvRPMkWw82S8q0v2p1jmn3msPXxvKrQQ1oVpr7pGBPXc2faQGXHW55Md%2BKSkspIgCxXx3x3T6NDaJ1%2BGTEFkyb1DE%2BdoQHQ4EjqV3jEC5mq56OlsHgEmkQ8TVCQM%2FPmAfUBWiQEHqBYzohXNfFpO3kfdrKjeTrq648UtGPYU88VJ9mtIOptYEfwFKN9y%2FG9MOBKEfRZ9XlJz2bPt1zmATIg3iRT1W7YVtmHq7e9g%2FUxsM82duMxFUWhoFPHfrFk4tt48LFH29Hk60y3eeFxqtg7g1JxPD1aQrLN9sxBduS53nFWObCms1YU40uvMT2yjX0kp4wM8YwqT2jTFDtLHcVBide1RGTnzFGzjOrbCJ8rIEmWfPa1yUMkXRBBsgpKWFIl0ueBQiCT%2BDoD9UXlNOQGS%2F5tIdP%2BVTO%2FkWiBo5X99SpKwKY8%2B2pqzJKDrPRXIwci52Wi%2Fo%2Fw%2B0TkpnVrtDaDl7w2eYjmq7bYZFRDjWy3Jtgc5V1DUF%2BhX3Bfiq7l%2Fq5YL4DYx0NBI2esfJ0LTFCqXu8aCk%2BWOPOWnOCSGA5Y9EGUXgzV6q%2Fp%2FFWa8Kj8E%2FeoB380eFwXAEiyyRGv&javax.faces.source=converter_form%3AselectedCategory&javax.faces.partial.event=change&javax.faces.partial.execute=converter_form%3AselectedCategory&javax.faces.partial.render=converter_form%3AselectedFrom%20converter_form%3AselectedTo&javax.faces.behavior.event=valueChange&javax.faces.partial.ajax=true We would expect only selectedCategory be send but its sending all form fields in ajax call. It though calls getCategories(), getFromList(), getToList() but when it calls getToList it uses category=temperature and from=mm. from=mm is what is passed in POST request as selectedFrom=mm. Regards, Miten. A: Change this: <f:ajax execute="selectedCategory" render="selectedFrom"/> To this: <f:ajax execute="selectedCategory" render="selectedFrom selectedTo"/> A: I added ajax listener as below so indicate that category change is being invoked so that getFromList will set selectedFrom to new item from its list instead of one being posted. Then getToList will find correct category and from unit to query its to list. <f:ajax execute="selectedCategory" render="selectedFrom"></f:ajax> to <f:ajax listener="#{converterBean.categoryChanged}" execute="selectedCategory" render="selectedFrom selectedTo"></f:ajax>
{ "language": "en", "url": "https://stackoverflow.com/questions/12163944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find xpath for with no class or unique identifier <p> <span>Welcome<span> Hello welcome. <p> <p> <span>Welcome!!!<span> Good morning <p> A: You can just use the FirePath plugin that mozilla has. Or if not then for the following code <html> <body> <p> <span>Welcome<span> Hello welcome. <p> <p> <span>Welcome!!!<span> Good morning <p> </body> </html> The xpath for second p element will be : html/body/p[2] For the span within it: html/body/p[2]/span A: Use // slash to find all the elements present on the DOM with start with p tag //p will return you all element present on the DOM in p tag Hope it will help you :)
{ "language": "en", "url": "https://stackoverflow.com/questions/34986557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: With "azure-iot-sdk-java"; What is the expected lifetime of a DeviceClient instance I am developing a long-running program that sends data periodically to an Azure IoT Hub. I am using the com.microsoft.azure.sdk.iot.device/DeviceClient Java class to accomplish this. It's basically working, which is nice, but I have some questions about the lifetime of the DeviceClient instance. Should I instantiate exactly one DeviceClient instance at program startup, and then repeatedly call .sendEventAsync any time I have data to send? Or should I instantiate a new DeviceClient instance fresh from the connection string each time I want to send data? Or something in-between (e.g., send no more than 100 messages with a given DeviceClient instance, or let no DeviceClient instance live more than 72 hours)? As I said, it's basically working, we've successfully sent many many events, but we have also seen some funny behavior. For example, after a few weeks the client silently stops sending (oof), or after some time the client claims send SUCCESS_OK, but the events don't arrive in the IoT hub for several hours (up to 16 (!)). I can definitely imagine these occurrences steming from my misuse of the library, so any hints about how to use it correctly would be much appreciated. Thanks in advance for your time and consideration. A: You should only have one long-living DeviceClient instance. Especially if you are using MQTT or AMQP as transport protocol, the DeviceClient will open the connection - and keep it open. Over that open connection it will send the messages. And also the for cloud-to-device messages / twin updates, the same channel is used. Also, the client usually handles any connection-retry logic so you don't have to deal with that manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/57616420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run a rails migration as sql file My database admins do not want to control access to any drop/alter/create commands. Is there anyway to emulate what rails is doing to the schema migrations table and convert the migrations themselves in a reliable way to fake rails out into thinking it has been ran and also handle rollbacks? They want to run this from their end of course. I have seen a few suggestions, but no wholistic approach. Perhaps the answer is it really shouldn't be done, which is what I think right now as I believe it will just cause headaches and unreliability down the road.
{ "language": "en", "url": "https://stackoverflow.com/questions/42472000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I combine large csv files in python? I have 18 csv files, each is approximately 1.6Gb and each contain approximately 12 million rows. Each file represents one years' worth of data. I need to combine all of these files, extract data for certain geographies, and then analyse the time series. What is the best way to do this? I have tired using pd.read_csv but i hit a memory limit. I have tried including a chunk size argument but this gives me a TextFileReader object and I don't know how to combine these to make a dataframe. I have also tried pd.concat but this does not work either. A: The memory limit is hit because you are trying to load the whole csv in memory. An easy solution would be to read the files line by line (assuming your files all have the same structure), control it, then write it to the target file: filenames = ["file1.csv", "file2.csv", "file3.csv"] sep = ";" def check_data(data): # ... your tests return True # << True if data should be written into target file, else False with open("/path/to/dir/result.csv", "a+") as targetfile: for filename in filenames : with open("/path/to/dir/"+filename, "r") as f: next(f) # << only if the first line contains headers for line in f: data = line.split(sep) if check_data(data): targetfile.write(line) Update: An example of the check_data method, following your comments: def check_data(data): return data[n] == 'USA' # < where n is the column holding the country A: Here is the elegant way of using pandas to combine a very large csv files. The technique is to load number of rows (defined as CHUNK_SIZE) to memory per iteration until completed. These rows will be appended to output file in "append" mode. import pandas as pd CHUNK_SIZE = 50000 csv_file_list = ["file1.csv", "file2.csv", "file3.csv"] output_file = "./result_merge/output.csv" for csv_file_name in csv_file_list: chunk_container = pd.read_csv(csv_file_name, chunksize=CHUNK_SIZE) for chunk in chunk_container: chunk.to_csv(output_file, mode="a", index=False) But If your files contain headers than it makes sense to skip the header in the upcoming files except the first one. As repeating header is unexpected. In this case the solution is as the following: import pandas as pd CHUNK_SIZE = 50000 csv_file_list = ["file1.csv", "file2.csv", "file3.csv"] output_file = "./result_merge/output.csv" first_one = True for csv_file_name in csv_file_list: if not first_one: # if it is not the first csv file then skip the header row (row 0) of that file skip_row = [0] else: skip_row = [] chunk_container = pd.read_csv(csv_file_name, chunksize=CHUNK_SIZE, skiprows = skip_row) for chunk in chunk_container: chunk.to_csv(output_file, mode="a", index=False) first_one = False A: You can convert the TextFileReader object using pd.DataFrame like so: df = pd.DataFrame(chunk), where chunk is of type TextFileReader. You can then use pd.concat to concatenate the individual dataframes.
{ "language": "en", "url": "https://stackoverflow.com/questions/56494140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: In Java or Scala, is there a way to add a callback to an exception so that when the exception is caught, the callback is invoked? Problem statement: I have an RPC client lib 1 that is used by many services with all code in a mono repo. This RPC client lib 1 throws a set of runtime exceptions (S1). Now there is another RPC client lib 2 that I try to migrate all services from using lib 1 to lib 2. However, RPC client lib 2 throws a different set of runtime exceptions (S2). I am trying to get a list of services that are going to be affected if the RPC client exception semantics change from S1 to S2. Approach 1: read through code of all services that currently use RPC client lib 1. Obviously this approach is not scalable because there are many services and exception handling logic could be complex and not straightforward. Approach 2: static analysis. However, I am not sure if any static analysis can detect the situation where an exception thrown by the RPC lib is caught at many levels above in the call stack. Approach 3: explore if there is a way to register a callback to an exception and expect the callback to be invoked when the exception is caught. Ideally when the callback is invoked, it is provided with the information about where the exception is caught. A: Sounds like AspectJ pointcut "after catching" (not exising). Existing is "after throwing" https://coderanch.com/t/498256/frameworks/AOP-pointcut-CATCH-block https://www.eclipse.org/aspectj/doc/next/progguide/printable.html#the-handler-join-point How to intercept method which handles its own exceptions using AspectJ Spring AOP - Invoking advice from catch block Maybe java agents/bytecode manipulation can be helpful Using Instrumentation to record unhandled exception You can consider to instrument catch blocks throughout the codebase with Scalameta (or Scalafix) import scala.meta._ val transformer = new Transformer { override def apply(tree: Tree): Tree = tree match { case q"try $expr catch { ..case $cases } finally $expropt" => val cases1 = cases.map { case p"case $pat if $expropt => $expr" => pat match { case p"${pat: Pat.Var}: $tpe" => p"""case $pat: $tpe if $expropt => println("Exception " + ${pat.name} + " is caught") $expr """ case p"$pat" => p"""case $pat if $expropt => println("Exception " + ${pat.toString} + " is caught") $expr """ } } q"try $expr catch { ..case $cases1 } finally $expropt" case _ => super.apply(tree) } } transformer(q""" try { 1 / 0 } catch { case e: RuntimeException => println(e) throw e } """) //try { // 1 / 0 //} catch { // case e: RuntimeException => // println("Exception " + e + " is caught") // { // println(e) // throw e // } //} transformer(q""" try { 1 / 0 } catch { case _ => println("swallowed") } """) //try { // 1 / 0 //} catch { // case _ => // println("Exception " + "_" + " is caught") // println("swallowed") //} transformer(q""" try { 1 / 0 } finally { case _ => println("not catching") } """) //try { // 1 / 0 //} finally { // case _ => // println("not catching") //} https://scalameta.org/ https://www.scala-sbt.org/1.x/docs/Howto-Generating-Files.html Scala conditional compilation Macro annotation to override toString of Scala function How to merge multiple imports in scala? https://scalacenter.github.io/scalafix For Java sources Spoon (https://spoon.gforge.inria.fr) can be a replacement for Scalameta. A: Solution 1 can work. If you are only worried about different semantics then it is sufficient to search in client code for occurrences of the exceptions defined by lib1. If client code catches a more generic exception (e.g. Exception or Throwable) then the precise semantics don't matter and you can leave that code alone. Assumptions: * *Lib1's exceptions are specific and are not thrown by other code (e.g. not RuntimeException but Lib1Exception is okay). *Lib1 and lib2 throw different exceptions but for the same reasons: if lib1 would throw an exception, lib2 would as well (and vice versa). A: "Approach 3" is a "nogo". I would go with "approach 4": write a wrapper client library (L3?) that throws the exceptions you want. It may look like somewhat more work initially, but will definitely pay for itself when you change your mind and want to go back to L1, or when there are L4, L5 and L6 you want to try. It is also probably going to be a lot easier to unit-test.
{ "language": "en", "url": "https://stackoverflow.com/questions/74709820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Save Data from internet in asset folder I want to save data from internet in asset folder in Android. I used Eclipse IDE to develop the android application. How i can achieve this ? Thanks. A: The assets directory is readonly. It's defined and initialized at compile time, you cannot add or edit its contents. Source (note it doesn't mention anything about writing to files...only reading them.) Use the SDCard for such operations. A: slote is right . use internal file storage/SD Card or sqLite database to save image
{ "language": "en", "url": "https://stackoverflow.com/questions/8557661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reading wave audio file into an array in android i am a newbie in android but i have tried to the best of my ability, i want to read a wave audio file into an array of shorts, bytes, floats to be able to manipulate it. With Java you can use JavaSound and you good but android is giving me headache
{ "language": "en", "url": "https://stackoverflow.com/questions/9628311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby on Rails - Track API calls made to 3rd party service I have a 3rd party API service that I am interacting with, via my Rails app, and they have quite low daily limits. Wondering what the best way to track API calls is? * *Database *Redis *In memory *Other I have a service object that makes all the calls. Just need a good way to track each call made and not go over the daily limit.
{ "language": "en", "url": "https://stackoverflow.com/questions/73582651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Refresh Dataframe created by writing to Parquet files in append mode Is there a way that I can refresh a dataframe that is being created by appending to the parquets in pyspark? Basically I am writing to parquet in append mode, data that I get daily. If I want to check the parquet file created I load it up in pyspark and do a count of the data. However if new data is appended to the parquet and I try a count again on the dataframe without reloading the dataframe I do not get the updated count. Basically, I have to create a new dataframe everytime there are any changes to my parquet file. Is there a way in Spark, where the changes are automatically loaded once my parquet is updated?
{ "language": "en", "url": "https://stackoverflow.com/questions/47938705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery click function is not attaching click event to anchor HTML Inside <div id='foo-bar-baz'> I have a series of image links with unique ids as below <a href=''><img id='12341234' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a> <a href=''><img id='56785678' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a> Javascript / JQuery The above div is created by a $.get() to a webservice which returns a chunk of HTML in variable response. On success, the $.get() calls the below function: var thumbnailsDiv = function (response) { var json = $.parseJSON(response); $('#foo-bar-baz').html(json.html); alert("Setting click functions on thumbnails"); $('.foo-bar-thumbnail-image').unbind().click(function () { alert("I am thumbnail " + $(this).id); }, false); }; As you can see above, I'm trying to bind a click function to each of the image links. However this is not working (with or without the unbind()). After the above code has run, if I inspect the image links in the Dev Tools, I can see that there are two click event attached already to the thumbnails. Neither of these is my function above. The paths for both of them are from other applications libraries embedded on the page: one is labelled 'jQuery' and the other is labelled 'Bubbling' and 'DOM2'. I'm guessing that it is these attached events that mean I can't add my event above, but I don't know enough about jQuery or javascript to know if this is true (I am a server-side developer normally, I don't know front-end stuff at all.) Any suggestions as to how I get an on-click event working for these elements would be much appreciated, so that I can replace the demo code above with the code I need to run. A: You just need to bind the click event to the parent element which already exists on the page. $('#foo-bar-baz').on('click', '.foo-bar-thumbnail-image', function(){ // what you want to happen when click // occurs on elements that match '.foo-bar-thumbnail-image' // within '#foo-bar-baz' alert("I am thumbnail " + $(this).id); }); A: You should be using $(document).on('click','.foo-bar-thumbnail-image',function() ... instead of $.click(function()... since the event handler is on elements that were rendered on the page via JS. That's a "delegated" event handler - you can read more about that here https://learn.jquery.com/events/event-delegation/
{ "language": "en", "url": "https://stackoverflow.com/questions/41904640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ValueError: only 1-dimensional arrays can be used import scipy from matplotlib.pyplot import specgram sample_rate,X = scipy.io.wavfile.read("a3.wav") print(X.shape) specgram(X,Fs=sample_rate,xextend=(0,30)) i am new to python . and first time use python for audio processing . and have struct on following problem . please help . i want to plot the spectrogram for a wave file. In above code sample of python I got following Output: (528038, 2) ValueError: only 1-dimensional arrays can be used
{ "language": "en", "url": "https://stackoverflow.com/questions/44558906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does the -> operator do in Objective-C Sorry if this question has been asked before but there were literally no results when i typed it into google. As the title states, I would like to know what the -> operator does. I see it everywhere: [self processTorrent:alert->handle]; but don't know what it does A: It's the structure dereference ("member b of object pointed to by a") in C. Objective-C is a strict superset of C. The the usual way to access a member a is as s.a which, given the pointer, is expressed as (*p).a or can instead be accessed by the shorthand: p->a using the structure dereference operator. struct point { int* x; int* y; }; structure point* struct1; As with any pointer. To change the address it points to: struct1->x = &varX; To change the value at the address to which it points: *(struct1->x) = varX;
{ "language": "en", "url": "https://stackoverflow.com/questions/33975155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I calling JavaScript in WebView from Android? I am beginner in Android development and want to create Android app with JavaScript. I can run my page in WebView. I can run JavaScript in WebView. I can call Android Toast message (or Dailog alert ) from JavaScript to Android. But I can NOT run JavaScript function from Android ! Can you help me to fix my code [ Download an android studio project ] http://r7eq.weebly.com Code of MainActivity.java package com.example.adnroid_script; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.JavascriptInterface; import android.widget.Toast; public class MainActivity extends Activity { public static WebView myWebView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myWebView=(WebView) findViewById(R.id.webview); myWebView.getSettings().setJavaScriptEnabled(true); myWebView.addJavascriptInterface(new jsInterface(), "FromJS"); myWebView.loadUrl("file:///android_asset/index.html"); } public class jsInterface{ @JavascriptInterface public void ToAndroid(String jsMessage){ Toast toast = Toast.makeText(getApplicationContext(),"I sent javascript code to myWebView", Toast.LENGTH_LONG); toast.show(); WebView myWebView = (WebView) findViewById(R.id.webview); // ### The bug is here ### // myWebView.loadUrl("javascript:document.write('<div>Android say : It is working now !</div>');"); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/30427291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring boot lazy initialisation is causing issue for datasource I am trying to implement lazy-initialization in my spring boot microservice. My application is using below items. * *Flyway (I have disabled it from yml) *postgresql *Kafka Whenever I deploy this microservice on Jenkins my sping boot application is failing on startup. The reason is that on my Jenkins i have nothing installed (kakfa, postgresql or flyway) What i am adivised is we should use lazy loading, I.e Our application should start without this dependencies and my /health endpoint should be UP. I have made lazy-initialization: true and flyway: enable: false This is starting my application like a charm! Now whenever i am trying to call /health endpoint, I am getting below error. Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalArgumentException: URL must start with 'jdbc' Looking into the logs, It seems spring is trying to connect to database when we are calling /health endpoint. Is there a way to tell spring that check only app is running or not using /health and doesn't check other stuff? Please let me know if I am missing something to provide if you need it. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/62483427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use jQuery to lift element value then return item from array and update another element I have a select element... <select name="tour" id="tour"> <optgroup label="tour"> <option value="0" selected="selected">Please Select Tour</option> <option value="Tour1">Tour1</option> <option value="Tour2">Tour2</option> </optgroup> </select> I have an array... <?php $array = array(Tour1=>100,Tour2=>200); ?> I have a field element... <input type="text" size="5" id="distance" readonly="readonly" name="distance" value="" class="value" /> I'm looking to set up a jQuery script that looks for a change in the value in the select element 'tour', searches for it in my array, returns the associative value, and writes it to the value of my input field 'distance'. Desired output: When Tour1 is selected, text input field 'distance' will show 100. A: 1st Pass the PHP array to JavaScript using json_encode: var phpArray = <?php echo json_encode($array); ?>; 2nd Bind to the change event of that <select>: $('#tour').on('change', /* see below */); 3rd Update the value: function (event) { $('#distance').val(phpArray[$(this).val()]); } A: what you want to do is not possible. PHP is a server side script. What you could do in order to make your scripts working is to pass the php Array to Javascript when loading the page. That way Javascipt is able to read it and to change the input. Option would be to use AJAX or define a JS array with the php Array's data: var js_array = <? echo json_encode($you_array); ?>; For this solution you need to add a in your HTML page's if you're pointing to your JS script external. For a longer explanation why using your php Array in Javascript that easy is not possible, see here: Difference between Javascript and PHP
{ "language": "en", "url": "https://stackoverflow.com/questions/22418459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring boot SUM(column) with specification I have an entity, says: class MyEntity { Long id; String attr1; String attr2; String attr3; String attr4; Double attr5; } I use Specification to query the result filtered by attributes like: class MySpecification implements Specification<MyEntity> { private String attr1; private String attr2; private String attr3; private String attr4; @Override public Predicate toPredicate(Root<MyEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { List<Predicate> restriction = new ArrayList<>(); if (!StringUtils.isEmpty(attr1)) { restriction.add(criteriaBuilder.equal(root.get("attr1"), attr1)); } if (!StringUtils.isEmpty(attr2)) { restriction.add(criteriaBuilder.equal(root.get("attr2"), attr2)); } // And so on Predicate predicate = criteriaBuilder.disjunction(); predicate.getExpressions().add(criteriaBuilder.and(restriction.toArray(new Predicate[restriction.size()]))); return predicate; } } Now I want to get sum of attr5 by the Specification, how can I do that ? Thank you in advanced. A: After some research, here is solution: Create an interface: interface MyRepositoryCustom { <S extends Number> S sum(Specification<MyEntity> spec, Class<S> resultType, String fieldName); } Implementation: @Repository class MyRepositoryCustomImpl implements MyRepositoryCustom { @Autowired private EntityManager entityManager; @Override public <S extends Number> S sum(Specification<MyEntity> spec, Class<S> resultType, String fieldName) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<S> query = builder.createQuery(resultType); Root<MyEntity> root = applySpecificationToCriteria(spec, query); query.select(builder.sum(root.get(fieldName).as(resultType))); TypedQuery<S> typedQuery = entityManager.createQuery(query); return typedQuery.getSingleResult(); } protected <S> Root<MyEntity> applySpecificationToCriteria(Specification<MyEntity> spec, CriteriaQuery<S> query) { Root<MyEntity> root = query.from(MyEntity.class); if (spec == null) { return root; } CriteriaBuilder builder = entityManager.getCriteriaBuilder(); Predicate predicate = spec.toPredicate(root, query, builder); if (predicate != null) { query.where(predicate); } return root; } } Main repository should extend both JpaRepository and MyRepositoryCustom: @Repository interface MyEntityRepository extends JpaRepository<MyEntity, Long>, MyRepositoryCustom { }
{ "language": "en", "url": "https://stackoverflow.com/questions/64039786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need help understanding RESTful apis in PHP For a few weeks, I've been trying to gather as much information on implementation of RESTful apis in PHP as I can but in vain. All the information that is given online only explain the most basic concepts but never did I come across a very real example with complete code on how RESTapi actually works. For Example, POST is used create a new resource. But how? How is it implemented in real life? How do I do this in cURL? I am aware of the complete basics but am unable to find any concrete and complete example that explains everything. Most of the tutorials simply name the functions they've used but did not bother explaining what is happening exactly, what the flow of the program is, etc. If someone can help with a complete example (say, a library registration and database) I'll really appreciate it. I'm really confused. A: I will describe POST method in REST. Client send HTTP request via POST method with JSON data. For example, client send some data to create a word "nice". POST http://localhost/word/1 JSON content { "data": { "type": "word", "attributes": { "word": "nice" } } } In PHP you need get a response and convert to array and insert ot DB. Why insert? Because request method is POST.
{ "language": "en", "url": "https://stackoverflow.com/questions/38119089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Slider AutoplayJquery doesn't work How can I add autoplay in this slider? https://codepen.io/mikun/pen/YWgqEX $('.slide-nav').on('click', function(e) { e.preventDefault(); // get current slide var current = $('.flex--active').data('slide'), // get button data-slide next = $(this).data('slide'); $('.slide-nav').removeClass('active'); $(this).addClass('active'); if (current === next) { return false; } else { $('.slider__warpper').find('.flex__container[data-slide=' + next + ']').addClass('flex--preStart'); $('.flex--active').addClass('animate--end'); setTimeout(function() { $('.flex--preStart').removeClass('animate--start flex--preStart').addClass('flex--active'); $('.animate--end').addClass('animate--start').removeClass('animate--end flex--active'); }, 1200); } }); It's working good, but without an autoplay.
{ "language": "en", "url": "https://stackoverflow.com/questions/45109512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Notice unserialize error in CakePHP via Redis Update: Per suggestion from the accepted answer below, I tested reading a negative number: $negativeInt = -1; Cache::write('my-test-count', $negativeInt, 'short'); $readVal = Cache::read('my-test-count', 'short'); debug($readVal); exit; The unseralize error reproduces consistently when trying to read any negative number. It's now an accepted bug, which I assume will be resolved by 2.8.1 Original Question: I keep getting this error, but can't figure out why or even how to further troubleshoot. The line that throws the error should only get hit if Cache::read() returns false. But, that line would throw an unserialize error itself if I didn't put the @ before it. Question: How can I reliably use Redis for counts without getting unserialize Notices on a regular basis? If the data in the key is "bad", how can I know that without getting the Notice just from doing a ::read. I've tried making sure my data is (int) (see below), but that doesn't seem to help. Notice (8): unserialize(): Error at offset 0 of 2 bytes [APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Engine/RedisEngine.php, line 136] Upon inspection of the error: > unserialize - [internal], line ?? > RedisEngine::read() - APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Engine/RedisEngine.php, line 136 > Cache::read() - APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Cache.php, line 358 > Cache::remember() - APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Cache.php, line 567 > Item::getCount() - APP/Model/Item.php, line 812 It appears to be coming from this function: public function getCount($id) { $model = $this; // here is where the Cache::read() and debug are in the update below return Cache::remember('item' . $id. '_count', function() use ($model, $id) { $count = $model->find('count', array( 'conditions' => array( $model->alias . '.status' => 1, $model->alias . '.id' => $id ) )); return ($count === false) ? 0 : (int)$count; }, 'my_counts'); // THIS IS LINE 812 } public function decrementCount($id, $offset = 1) { if(empty($id)) return false; $count = @Cache::read('item' . $id . '_count', 'my_counts'); if($count === false) { $this->getCount($id); } else { Cache::decrement('item' . $id . '_count', $offset, 'my_counts'); } } public function incrementCount($id, $offset = 1) { if(empty($id)) return false; $count = @Cache::read('item' . $id. '_count', 'my_counts'); if($count === false) { $this->getCount($id); } else { Cache::increment('item' . $id. '_count', $offset, 'my_counts'); } } UPDATE: This function gets run in a loop (through 1-20 items). When I add the following before the Cache::remember(...: $toReturn = Cache::read('item' . $id. '_count', 'my_counts'); debug($toReturn); It gives this: * *debug: (int) 0 *debug: (int) 0 *Notice (8): unserialize(): Error at... (from the Cache::read) *debug: false *Notice (8): unserialize(): Error at... (from the Cache::remember *debug: (int) 0 *Notice (8): unserialize(): Error at... (from the Cache::read) *debug: false *Notice (8): unserialize(): Error at... (from the Cache::remember *0 *3 *1 *1 ... A: It seems to be a core bug. I might be able to answer to why this issue occurs. I am guessing that this issue is caused by int(-1). When writing data, RedisEngine doesn't serialize the data if it is an integer. Therefore, int(-1) will be saved without calling serialize(). public function write($key, $value, $duration) { if (!is_int($value)) { $value = serialize($value); } ... } But when reading data, the implementation seems asymmetric. I don't know Redis well, but I am guessing that Redis stores int(-1) as string(-1). As ctype_digit("-1") returns false, string(-1) would be unserialized wrongly. public function read($key) { $value = $this->_Redis->get($key); if (ctype_digit($value)) { // ctype_digit("-1") === false $value = (int)$value; } if ($value !== false && is_string($value)) { // is_string("-1") === true $value = unserialize($value); } ... } Thus, you will see "Notice (8): unserialize(): Error at offset 0 of 2 bytes". The size of string(-1) is 2 bytes. What about opening an issue on github, if you could reproduce that writing int(-1) and reading it throws a notice. Aside from that, a workaround would be stop using Cache::decrement(). On race conditions, the method will store int(-1). You may use Cache::write() instead if it is not an important data. For example: $count = Cache::read('item' . $id. '_count', 'my_counts'); if ($count === false || 0 > $count - $offset) { $this->getCount($id); } else { Cache::write('item' . $id. '_count', $count - $offset, 'my_counts'); } But if it is an important data, then you may need to implement exclusive lock/unlock. Thank you for reading this to the end and sorry if I am wrong. A: Solution: return ($count === false) ? 0 : (int)$count; Long version: You shouldn't increment/decrement serialized value. Cache::remember does something like this: $key = 'key'; $value = 10; $serialized = serialize($value); // $serialized = 'i:10;' $redis->set($key, $serialized); Cache::read does something like this: $key = 'key'; $serialized = $redis->get($key); // $serialized = 'i:10;' $value = unserialize($serialized); // $value = (int) 10 return $value; But Cache::decrement does something like this: $key = 'key'; $count = 1; $redis->decrby($key, $count); // Error, decrby expects plain value, "10", not "i:10;" ( http://redis.io/commands/decrby ) Also, if you decrement successfully, then you will have plain value in redis, so result will be: $key = 'key'; $serialized = $redis->get($key); // $serialized = '10' $value = unserialize($serialized); // error, cannot unserialize '10' EDIT: After checking source: https://github.com/cakephp/cakephp/blob/master/src/Cache/Engine/RedisEngine.php I see that Cake does checks: if (!is_int($value)) { $value = serialize($value); } So all you need to do to avoid serialization is to make sure that you are storing (int). A: Just remove third parameter, it should be work return Cache::remember('item' . $id. '_count', function() use ($model, $id) { $count = $model->find('count', array( 'conditions' => array( $model->alias . '.status' => 1, $model->alias . '.id' => $id ) )); return ($count === false) ? 0 : (int)$count; });
{ "language": "en", "url": "https://stackoverflow.com/questions/34936268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Recommendations for keeping a build server updated As a guy who frequently switches between QA, build and operations, I keep running into the issue of what to do about operating system updates on the build server. The dichotomy is the same on Windows, Linux, MacOS or any other o/s that can update itself via the internet: * *The QA team wants to keep the build server exactly as it is from the beginning of the product release cycle to the end, since installing updates could destabilize the server and means that successive builds aren't made against the same baseline. *The ops team wants the software to be deployed on a system with all the latest security patches; this can mean that the software isn't deployed on exactly the same version of the o/s that it was built on. I usually mitigate this by taking release candidate builds and installing them on a test server that has a completely up-to-date o/s, repeating the automated tests that are run on the build server and doing some additional system level testing to make sure everything looks good before deployment. However, this seems inefficient to me; does anyone have a better way ? A: Personally i don't think you have much of an issue here - just apply the latest updates to the build server. The main reasons i say this are: * *it is highly unlikely that your code or any of the dependencies on the build server are so tightly coupled to the OS version that installing regular updates is going to affect anything, let alone break it. There can be minor differences between window messages etc between Windows versions, but those are few and far between, and are usually quite well documented out there on teh interweb. If you are using managed technology stacks like WPF/Silverlight or ASP.Net and even mostly Winforms then you will be isolated from these changes - they should only affect you if you are doing hardcore stuff using the WinAPI directly to create your windows or draw your buttons. *it is a good practice to always engineer your product against the latest version of the OS, because you need to encourage your customer to implement those updates too - IOW you should not be in a position where you have to say to your client to not install update xyz because your application will not run against it - especially if that update is a critical security update *testing for differences between OS versions should be done by the QA team and should independant of what is on the build server *you do not want your build server to get in to such a state that it has been so isolated from the company update process that when you finally do apply them all it barfs and spits molten silicon everywhere. IOW, the longer you wait to update, the higher the risk of something going wrong and doing so catastrophically. Small and frequent/incremental updates are lower risk than mass updates once per decade :) The build server updates that you do have to be cautious about are third party controls or library updates - they can frequently contain breaking changes or considerably altered behavior. They really should be scheduled, and followed up by a round of testing looking for any changes. A: Virtualize! Using stuff like VMWare Server you can script the launch and suspend of virtual machines. So you can script VM resume, SSH to launch build, copy, VM suspend, repeat. (I say this, but I abandoned my work on this. Still, I was making progress at the time.) Also, you can trust your OS vendors. Can't you? They have an interest in compatibility. If you build on Windows XP it is almost certain to work on XP SP3 and Vista and Windows 7. If you build on RedHat Enterprise 5, it had better work on 5.1, 5.2, 5.3, 5.4, etc. In my experience this has worked out OK so far for me and I recommend building on your lowest patch OS versions. With the Linux stuff in particular I have found newer releases linking to more recent libraries not available on older versions. Of course it doesn't hurt to test your code on a copy of the deployment server. It all depends on how certain you want to be. A: Take the build server off the network, that way you do not need to worry about installing security updates. Only load the source from CD, thumb drive or whatever other means. Plug it back in at the end of your release cycle and then let all the updates take place. A: Well, for the most stable process, I would have two build servers, "Build with Initial config, Build with update config", and two autotest test servers with similar differences. Use virtualization to do this effectively and scriptably.
{ "language": "en", "url": "https://stackoverflow.com/questions/2777645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jsTree select Node which is not in DOM yet I have an jsTree, data comes from HTML $("#tree_container").jstree(); Now I want to implement deep linking on the tree elements. I am getting the class and data-id from URL parameters and now I want to select the correspondent node. var id=$("#tree_container").find("li."+get_class+"[data-id='"+get_id+"']").attr("id"); if(id!=undefined && id!=0) { treeElem.jstree(true).select_node(id); } This only works if the node is already in the DOM Tree. (sub-Trees are getting inserted in if the parent node is clicked) If the node I want is not in the tree ... id is undefined and the select fails. Thing is, if I put in the id (like "#j1_6") in directly the node is found even if it is not in the DOM tree. It only work with the Id in that format, I try putting other selectors in or even elements ($(".class[data-id='1']"), nothing worked. My problem is that I do not know how to get the id of the node if it is not in the DOM Tree yet. I did not find a api function or anything to do that. ====== UPDATE ====== I found a workaround ... When building the HTML tree I now combine the class and data-id to make up the html id of the element (li). So I have controll over the ids and know them and just do: treeElem.jstree(true).select_node("#"+get_type+"_"+get_id); so yeah, as I said for me it is just a workaround...
{ "language": "en", "url": "https://stackoverflow.com/questions/35311488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Store a custom Array List in Shared Preference I want to store a Custom Array List in a Shared Preference , so that I can read the List when I open my app the next time. I looked at many tutorials and answers but I could not really understand it. list_addr.java public class list_addr { public String title; public String detail; public list_addr( String title, String detail) { super(); this.title = title; this.detail=detail; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } @Override public String toString() { return title + "\n" ; } } list_adapter.java enterpublic class list_addr_adapter extends ArrayAdapter<list_addr> { Context context; int layoutResourceId; public list_addr_adapter(Context context, int layoutResourceId, List<list_addr> items) { super(context, layoutResourceId, items); this.layoutResourceId = layoutResourceId; this.context = context; // this.listener=callback; } /*private view holder class*/ private class ViewHolder { TextView txtTitle; TextView txtDetail; ImageView imageview; CheckBox checkbox; } ViewHolder holder = null; public View getView(final int position, View convertView, ViewGroup parent) { final list_addr lists = getItem(position); final int pos=position; LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = mInflater.inflate(R.layout.items_sav_addr2, null); holder = new ViewHolder(); holder.txtTitle = (TextView) convertView.findViewById(R.id.textTitle); holder.txtDetail = (TextView) convertView.findViewById(R.id.detail); holder.imageview = (ImageView) convertView.findViewById(R.id.imageview); holder.checkbox=(CheckBox)convertView.findViewById(R.id.chkitem); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); holder.txtTitle.setText(lists.getTitle()); holder.txtDetail.setText(lists.getDetail()); return convertView; } } This is how I inflate the list view - listView1 = (ListView) findViewById(R.id.listView); list_adapter_invoice adapter = new list_adapter_invoice(this, R.layout.items_row, MyAdaptertwo.rowitems); listView1.setAdapter(adapter); A: You can only save primitive types in shared preference . If you need to save an ArrayList then you can save it as a String which is Comma seperated . At the time of fetching this use split(",") on this String And you will get a String [] of it . And if you want to save a list of Object then i Suggest to use a Singleton Class for it . Here is example of Singelton Class .Try this it you want . public class ReferenceWrapper { private Context context; private static ReferenceWrapper wrapper; private ArrayList<Object> list; private ReferenceWrapper(Context context) { this.context = context; } public static ReferenceWrapper getInstance(Activity activity) { if (wrapper == null) { wrapper = new ReferenceWrapper(activity); } return wrapper; } public ArrayList<Object> getList() { return list; } public void setList(ArrayList<Object> list) { this.list = list; } } And use it like this ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this); wrapper.setList(yourArrarlist); And get It in any activity ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this); ArrarList<Object> list= wrapper.getList(yourArrarlist); It will return the same ArrayList list you saved recently . Because its only one object is Created .Let me know if it helps A: Answer is about write object in File instead of SharedPreference. Hope this may help try { ArrayList<List_addr> addrList = new ArrayList<>(); addrList.add(new List_addr("Bangalore", "Its a City")); addrList.add(new List_addr("Delhi", "Its also a City")); //write object into a file FileOutputStream fos = openFileOutput("addrList", Context.MODE_PRIVATE); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(addrList); oos.close(); //read object from the file FileInputStream fis = openFileInput("addrList"); ObjectInputStream ois = new ObjectInputStream(fis); ArrayList<List_addr> readAddrList = (ArrayList<List_addr>) ois.readObject(); ois.close(); for (List_addr address : readAddrList) { Log.i("TAG", "Name " + address.getTitle() + " City " + address.getDetail()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } Important : Please mind @MeetTitan answer comments. A: Step 1: Put string array set into the shared preference. pref.putStringSet(String key, Set<String> values); Step 2: Convert array list of pojo into set. Set<String> set = new HashSet<String>(list); Set 3: Retrive using the getStringSet. A: To save arraylist in shared preferences do the following // Create List of address that you want to save ArrayList addressList = new ArrayList(); addressList.add(new list_addr()); addressList.add(new list_addr()); SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE); //save the user list to preference Editor editor = prefs.edit(); try { editor.putString("addressList", ObjectSerializer.serialize(addressList)); } catch (IOException e) { e.printStackTrace(); } editor.commit(); and then to retrieve arraylist use this ArrayList addressList = new ArrayList(); // Load address List from preferences SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE); try { addressList = (ArrayList) ObjectSerializer.deserialize(prefs.getString("addressList", ObjectSerializer.serialize(new ArrayList()))); } catch (IOException e) { e.printStackTrace(); } And this is the link for objectSerializer class Object Serializer
{ "language": "en", "url": "https://stackoverflow.com/questions/34626551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to keep a user signed in on an Electron app using Auth0? There seem to be no complete explanations of how to do this, or even enough fragments for me to piece together what I have to do. After about 16 hours of studying, I am at wit's end. It seems like I can't use SSO, and I also can't use PKCE because there is no working example anywhere on the web. There is a github repo with an example implementation, but it does not function and after 2 hours playing with it I cannot determine what I need to do to move forward this way. Thanks for any help. A: You can add offline_access to your scope (e.g. "scope": "offline_access openid something:else",) and this will yield you a refresh_token. Auth0 currently supports unlimited refresh_token usage, so when your access_token expires (you either can track expiration time manually using "expires_in": 86400 value in respones or react on 401 response from api) - you can send your refresh token to OAuth2 api endpoint and receive new access token back. They have few descent articles about this matter and what you need to configure for your clients and API as well as what not to do (depending on your client security assumptions). Take a note - you must secure refresh_token properly - store it in some reliable store and prevent any external scripts from accessing it. I assume with electron app you can do it more reliable than with a public website.
{ "language": "en", "url": "https://stackoverflow.com/questions/42889805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to check if checkbox is checked in gridviewrow I need help with this code where I check every row in GridView if the CheckBox is checked or not. But there is still false. Can you help me, please? <asp:GridView ID="GridView1" CssClass="tabulka" runat="server" AutoGenerateColumns="false" /> <Columns> <asp:TemplateField HeaderText="Placení"> <ItemTemplate> <asp:CheckBox ID="Poslano" runat="server" Text="Vyřešeno" /> <asp:HiddenField ID="id" runat="server" Value='<%# Eval("id").ToString() %>' /> </ItemTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#CCCCCC" /> <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /> </asp:GridView> protected void Button1_Click(object sender, EventArgs e) { foreach (GridViewRow gvRow in GridView1.Rows) { if (((CheckBox)gvRow.FindControl("Poslano")).Checked) // here is a problem - still false { Tabor tab = new Tabor(); tab.Id = Convert.ToInt32(((HiddenField)gvRow.FindControl("id")).Value); // here is good value } } } A: Pleae check with below code foreach(var gvItem in GridView1.Items) { CheckBox chkItem = (CheckBox) gvItem.FindControl("Poslano"); if (chkItem.Checked) { //Do stuff } }
{ "language": "en", "url": "https://stackoverflow.com/questions/56963931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: calculate a rolling median on a dataframe that has a non-unique date index I have the following dataframe, which has a non-unique index using dates: column 2019-01-07 NaN 2019-01-08 NaN 2019-01-08 0.02 2019-01-09 31.45 2019-01-10 NaN 2019-01-10 71.87 2019-01-10 90.18 2019-01-11 NaN 2019-01-12 12.67 2019-01-12 5.68 2019-01-12 11.23 2019-01-12 21.67 2019-01-12 14.77 2019-01-12 5.18 2019-01-13 14.38 2019-01-13 NaN 2019-01-13 71.13 2019-01-13 20.02 2019-01-13 103.10 2019-01-14 NaN 2019-01-15 32.48 2019-01-16 37.37 2019-01-16 31.05 2019-01-16 7.00 2019-01-17 NaN 2019-01-17 39.65 2019-01-18 23.68 2019-01-18 0.08 2019-01-18 41.35 2019-01-19 NaN 2019-01-19 45.85 2019-01-19 3.98 2019-01-19 4.60 2019-01-19 NaN 2019-01-19 NaN 2019-01-20 3.60 2019-01-20 5.03 2019-01-20 15.70 My aim is to calculate a 7 day rolling median using all the values for each date, but ignoring the NaN values. The resulting dataframe should have a unique date index with the rolling median as a column value for that date, similar to the following: column 2019-01-13 17.40 2019-01-14 17.40 2019-01-15 20.85 2019-01-16 20.85 2019-01-17 20.02 2019-01-18 20.85 2019-01-19 31.05 2019-01-20 19.69 I am not sure how to easily achieve this using pandas, so if anyone can provide an answer or point me in the right direction, it will be very much appreciated. EDIT To make things clearer, I will explain how the median needs to be calculated for a single date. Using the date of 2019-01-13, the rolling median will need to use all the values, excluding the NaN values, from the 7 days up to the 13th. This means that the values that need to be included in the median calculation for the 13th are 0.02, 31.45, 71.87, 90.18, 12.67, 5.68, 11.23, 21.67, 14.77, 5.18, 14.38, 71.13, 20.02, 103.10. The resulting median for the 13th would be 17.4. Hope that helps. A: A rolling object is iterable, which allows for a solution like this: # drop NAs and group by date into lists of values df_per_date = df.dropna().groupby('date').apply(lambda g: g.value.to_list()) # compute medians across windows ('sum' concatenates multiple lists into one list) medians = [np.median(window.agg(sum)) for window in df_per_date.rolling(5)] # result medians = pd.Series(index=df_per_date.index, data=medians) medians By the way, I loaded the data like this: # load the data df = pd.read_csv(pd.io.common.StringIO(""" 2019-01-07 NaN 2019-01-08 NaN 2019-01-08 0.02 2019-01-09 31.45 2019-01-10 NaN 2019-01-10 71.87 2019-01-10 90.18 2019-01-11 NaN 2019-01-12 12.67 2019-01-12 5.68 2019-01-12 11.23 2019-01-12 21.67 2019-01-12 14.77 2019-01-12 5.18 2019-01-13 14.38 2019-01-13 NaN 2019-01-13 71.13 2019-01-13 20.02 2019-01-13 103.10 2019-01-14 NaN 2019-01-15 32.48 2019-01-16 37.37 2019-01-16 31.05 2019-01-16 7.00 2019-01-17 NaN 2019-01-17 39.65 2019-01-18 23.68 2019-01-18 0.08 2019-01-18 41.35 2019-01-19 NaN 2019-01-19 45.85 2019-01-19 3.98 2019-01-19 4.60 2019-01-19 NaN 2019-01-19 NaN 2019-01-20 3.60 2019-01-20 5.03 2019-01-20 15.70 """.strip()), sep='\s+', names=['date', 'value'], parse_dates=['date']) A: If the data is not too long, cross merge can work: df['key'] = 1 df = df.reset_index() (df.merge(df, on='key', suffixes=['','_']) .loc[lambda x: x['index'].ge(x['index_']) & x['index'].sub(x['index_']).le('7D')] .groupby('index')['column_'].median() ) Output: index 2019-01-07 NaN 2019-01-08 0.020 2019-01-09 15.735 2019-01-10 51.660 2019-01-11 51.660 2019-01-12 13.720 2019-01-13 17.395 2019-01-14 17.395 2019-01-15 20.020 2019-01-16 21.670 2019-01-17 21.670 2019-01-18 20.845 2019-01-19 20.020 2019-01-20 21.850 Name: column_, dtype: float64
{ "language": "en", "url": "https://stackoverflow.com/questions/65929683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error LNK1104 when upgrade from VS2008 to VS2010 My project make C dll deployment in Matlab. After upgrade from VS C++ 2008 to VS C++ 2010 project, I got this error: LINK : fatal error LNK1104: cannot open file 'mfc90d.lib' After searching for solution, I think it should reference to 'mfc100d.lib'. But I don't know HOW to reference. I tried to reference 'mfc90d.lib', and 'mfc100d.lib'. After that, the error gone, and the other replaced. LINK : fatal error LNK1104: cannot open file 'mfcs90d.lib' Even when I put 'mfcs90d.lib' in library paths, nothing happen. The error still there. Does anyone meet that problem? And how you solve that? Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/24771053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: returning and passing 2 one dimensional arrays from a function to another in c++ I have around 5 functions which exchange data among each other, each fuction has to return an array and around two integers. I went through "tuple" but we cant club integers and arrays together and im not very comfortable with "struts". If i could please be guided of ways of doing the same or passing and returning two arrays ( the integers can be put in an array). Thank You A: returning and passing 2 one dimensional arrays In C++, you can only return a single value. You cannot return multiple values, and the value that you return cannot be an array. im not very comfortable with "struts" [sic] I assume you mean structs. Well, now is the time to become comfortable, because a struct (also known as class) is great way to combine multiple values - even arrays - into a single object that can be returned. Another option is to pass the function multiple references (or iterators or pointers) to objects that the function can modify instead of returning them.
{ "language": "en", "url": "https://stackoverflow.com/questions/40910420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }