text
stringlengths
15
59.8k
meta
dict
Q: how to create a MySQL / PHP sub query to count the number of records matching a value? I am having trouble querying MySQL. I want to actually get the count of records with the value of the current parent_cat_id. So in this case we want a sub_query that will tell us 4 (because there are 4 id parent_cat_id cat_name 6 2 Carrot 8 2 Potatoes 7 2 Lettuce 13 2 Asparagus 4 1 Pears 3 1 Banannas 2 1 Apples the Main $query which produces what I posted and much more information which I will use.... $menu_query = "SELECT c.id AS id, parent_cat_id, cat_name FROM db.category c JOIN db.parent_category pc ON pc.id = c.parent_cat_id WHERE c.is_active = 1 AND c.is_menu = 1 ORDER BY pc.sort_order, c.sort_order;"; $menu_result = mysql_query($menu_query) or die(mysql_error()); while($menu_row = mysql_fetch_array($menu_result)){ $menu_name = $menu_row['cat_name']; $id = $menu_row['id']; $parent_cat_id = $menu_row['parent_cat_id']; #echo $parent_cat_id; #return from database the $count of records with the same ['parent_cat_id'] 's So I was hoping for a $sub_query of some sort so that I know in my php code to build the next menu's items. The first menu should have 4 and the second menu should have 3. Thanks. UPDATE FINAL WORKING SUB QUERY SELECT c.id AS category_id, c.parent_cat_id, cat_name, d.totalCount FROM category c INNER JOIN parent_category pc ON pc.id = c.parent_cat_id INNER JOIN( SELECT parent_cat_id, COUNT(*) totalCount FROM category WHERE is_menu = 1 AND parent_cat_id = 2 ORDER BY parent_cat_id ) d ON c.parent_cat_id = d.parent_cat_id WHERE c.is_active = 1 AND c.is_menu = 1 ORDER BY pc.sort_order, c.sort_order; Thanks again for your help!!! I just needed to throw in another WHERE clause in the sub query you taught me. A: you can have extra subquery to count the values for each parent_cat_id SELECT c.id AS id, pc.parent_cat_id, pc.cat_name, d.totalCount FROM db.category c INNER JOIN db.parent_category pc ON pc.id = c.parent_cat_id INNER JOIN ( SELECT parent_cat_id, COUNT(*) totalCount FROM db.parent_category GROUP BY parent_cat_id ) d ON c.parent_cat_id = d.parent_cat_id WHERE c.is_active = 1 AND c.is_menu = 1 ORDER BY pc.sort_order, c.sort_order
{ "language": "en", "url": "https://stackoverflow.com/questions/14149871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIDatePicker set minimum and maximum time I've got a UIDatePicker with the time only and I need a possibility to set the minimum and the maximum hour is showed. For example, I need it to start at 6 hours and finish at 15 hrs. Is it possible to perform this with UIDatePicker? A: 1) Use this function to retrieve the minimum and maximum date func getTimeIntervalForDate()->(min : Date, max : Date){ let calendar = Calendar.current var minDateComponent = calendar.dateComponents([.hour], from: Date()) minDateComponent.hour = 09 // Start time let formatter = DateFormatter() formatter.dateFormat = "h:mma" let minDate = calendar.date(from: minDateComponent) print(" min date : \(formatter.string(from: minDate!))") var maxDateComponent = calendar.dateComponents([.hour], from: date) maxDateComponent.hour = 17 //EndTime let maxDate = calendar.date(from: maxDateComponent) print(" max date : \(formatter.string(from: maxDate!))") return (minDate!,maxDate!) } 2) Assign these dated to your pickerview func createPickerView(textField : UITextField, pickerView : UIDatePicker){ pickerView.datePickerMode = .time textField.delegate = self textField.inputView = pickerView let dates = getTimeIntervalForDate() pickerView.minimumDate = dates.min pickerView.maximumDate = dates.max pickerView.minuteInterval = 30 pickerView.addTarget(self, action: #selector(self.datePickerValueChanged(_:)), for: UIControlEvents.valueChanged) } That's it :) A: Just use this: datePicker.maximumDate = myMaxDate; datePicker. minimumDate = myMinDate; Where myMaxDate and myMinDate are NSDate objects A: As for my problem, the answer with maximumDate and minimumDate isn't what I am looking for. Maybe my solution is not that clear and right, but it worked great for me. I have changed the UIDatePicker with UIPickerView, wrote a separate delegate for it: @interface CHMinutesPickerDelegate () <UIPickerViewDelegate, UIPickerViewDataSource> @property (nonatomic, strong) NSArray *minutesArray; @end @implementation CHMinutesPickerDelegate - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component { return [self.minutesArray count]; } - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 1; } - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [self.minutesArray objectAtIndex: row]; } - (NSArray *)minutesArray { if (!_minutesArray) { NSMutableArray *temporaryMinutesArray = [NSMutableArray array]; for (int i = 0; i < 6; i++) { for (int j = 0; j < 2; j++) { [temporaryMinutesArray addObject: [NSString stringWithFormat: @"%i%i", i, j * 5]]; } } _minutesArray = temporaryMinutesArray; } return _minutesArray; } The minutesArray returns array of: { "05", "10"... etc}. It is an example for custom minutes picker, you can write the same thing for hour or etc, choosing your own maximum and minimum value. This worked nice for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/19863040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect text source from accessibility service I'm using an accessibility service to receive text from a view of a specific app. The text can be inserted manually or via voice. Is there any way to check the source? I'd like to change my behavior if the text is inserted manually or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/30143573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Turning a command line app into a Cocoa GUI app on Mac OS X? Is there any tutorials or references, if such thing is possible, to make GUI applications out of command line apps? What I mean is, having a command line app, wrap it into an app bundle and create a Cocoa GUI app that would have a simple interface to execute the command line app with its flags and parameters. A: As a matter of fact there are. Here is the first hit for a Google search: * *Cocoa Dev Central: Wrapping UNIX Commands What you're looking for is the NSTask class. Check out the documentation for all the information you need. A: For very simple scripts, I recommend Platypus. For more complicated scenarios, you could try something like Pashua.
{ "language": "en", "url": "https://stackoverflow.com/questions/3134035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Divide one CSS column in 2 rows http://jsfiddle.net/9877/6E2pQ/2/ What I want do is have columncontent1 on the left and columncontent2 and columncontent3 stacked on the right side. see the jsfiddle. How do I fix the css? I am running out of ideas. Is the error in the css or the way the div placed in the body: <style type="text/css"> /*<![CDATA[*/ .columncontainer1{ width:1001px; position:relative; border:0px; background-color:#fffffa; overflow:hidden; } .columncontainer2{ float:left; position:relative; right:300px; border-right:1px solid #0a0a0a; background-color:#f5f5f5; } .columncontainer3{ float:left; position:relative; bottom: 10px border-right:1px solid #0a0a0a; background-color:#f5f5f5; } .columncontent1{ float:left; width:680px; position:relative; background-color:#933; border: 1px; left:300px; padding:10px; overflow:hidden; } .columncontent2{ float:left; width:280px; position:relative; background-color:#FFF; border: 2px; left:301px; padding:10px; overflow:hidden; } .columncontent3{ float:left; width:280px; position:relative; left:301px; border: 4px; background-color:#CC6; padding:10px; overflow:hidden; } /*]]>*/ </style> A: There's a lot going on there, I've simplified the HTML and CSS: CSS: .leftCol { float: left; width: 50%; background-color: #ccc; height: 60px; } .rightColContainer { float: left; width: 50%; } .rightCol1 { background-color: #333; height: 30px; } .rightCol2 { background-color: #777; height: 30px; } HTML: <body> <div class="leftCol">columncontent1</div> <div class="rightColContainer"> <div class="rightCol1">columncontent2</div> <div class="rightCol2">columncontent3</div> </div> </body> You only need to 'contain' the right hand column to stop the 'stacked column' flowing incorrectly. A: CSS3 actually allows you to make several columns automatically without having to have all those classes. Check out this generator: http://www.generatecss.com/css3/multi-column/ This is however only if you are trying to make your content have multiple columns like a newspaper.
{ "language": "en", "url": "https://stackoverflow.com/questions/20598741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pathos multiprocessing pool CPickle error When i tried to run the following code: from pathos.multiprocessing import ProcessingPool as Pool list1 = [1,2,3,4,5] list2 = [6,7,8,9,10] def function1(x,y): print x print y if __name__ == '__main__': pool = Pool(5) pool.map(function1, list1, list2) It gets the followwing error: Traceback (most recent call last): File "test.py", line 9, in <module> pool.map(function1, list1, list2) File "C:\Python27\lib\site-packages\pathos\multiprocessing.py", line 136, in map return _pool.map(star(f), zip(*args)) # chunksize File "C:\Python27\lib\site-packages\multiprocess\pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "C:\Python27\lib\site-packages\multiprocess\pool.py", line 567, in get raise self._value cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed Isn't pathos.multiprocessing is designed to solve this problem? A: I'm the pathos author. When I try your code, I don't get an error. However, if you are seeing a CPickle.PicklingError, I'm guessing you have an issue with your install of multiprocess. You are on windows, so do you have a C compiler? You need one for multiprocess to get a full install of multiprocess.
{ "language": "en", "url": "https://stackoverflow.com/questions/44094924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does slice not work directly on arguments? Tested it out on this fiddle after looking at underscore. This seems like a hack to call slice on arguments when it is not on the prototype chain. Why is it not on the prototype chain when it obviously works on arguments. var slice = Array.prototype.slice; function test () { return slice.call(arguments,1); // return arguments.slice(1) } var foo = test(1,2,3,4); _.each(foo, function(val){ console.log(val) }); A: >>> Object.prototype.toString.call(arguments) <<< "[object Arguments]" >>> Array.isArray(arguments) //is not an array <<< false >>> arguments instanceof Array //does not inherit from the Array prototype either <<< false arguments is not an Array object, that is, it does not inherit from the Array prototype. However, it contains an array-like structure (numeric keys and a length property), thus Array.prototype.slice can be applied to it. This is called duck typing. Oh and of course, Array.prototype.slice always returns an array, hence it can be used to convert array-like objects / collections to a new Array. (ref: MDN Array slice method - Array-like objects) A: arguments is not a "real" array. The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used. The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array. You could do: var args = Array.prototype.slice.call(arguments); A: Arguments is not an Array. It's an Arguments object. Fortunately, slice only requires an Array-like object, and since Arguments has length and numerically-indexed properties, slice.call(arguments) still works. It is a hack, but it's safe everywhere. A: Referring to MDN: »The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:« https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments In order to call slice, you have to get the slicefunction, from the Array-prototype.
{ "language": "en", "url": "https://stackoverflow.com/questions/16345747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create Watchkit notification programmatically I'm looking to push a notification to the Apple Watch at a specific time. I was able to display a static message on the simulator using an apns file, but I'd like to set the data and time of the notification in the controller. I heard I might not be able to do this on a simulator, but if I got a real phone and watch, how would it work? A: So, you want to do something in the watch app extension and based on the results, schedule a UILocalNotification that will be sent to the phone at some point? You cannot directly schedule a UILocalNotification from the watch because you don't have access to the UIApplication object. See Apple staff comment here. However, using Watch Connectivity, you could send a message from the watch to the phone and have the phone app create and schedule it in the background. The watch will display the notification iff the phone is locked at the trigger time. The watch's notification scene will be invoked in that case. A: Assuming you want to send the notification from the phone to the watch: You can use UILocalNotification to send a notification to the watch - but the watch must be locked to receive it. There's also no guarantee when the Watch OS will turn on the watch to run the code that receives your notification, so your notification may arrive minutes or hours after it's sent.
{ "language": "en", "url": "https://stackoverflow.com/questions/33759489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create an object in a class by passing a token to a constructor? What I am attempting to do is to take a .txt file that has multiple lines of people's information (Last name, First name, phone number, email) and display the information into a listbox so that a user could select a name in the listbox and display all of the selected person's information in a second form. The instructions for my assignment say that the next thing I should do is Create your object by passing these tokens to your constructor. (Don’t pass the array but rather each element individually.) I have created a class called PersonEntry that constructs 4 strings containing the 4 pieces of information that's included in the .txt file. Here is where I'm at(the first one is my form1.cs code and the second is my PersonEntry.cs class code) and I don't know what to do next. Any help would be much appreciated! namespace ChalabiMichaelProgram10 { public partial class chalabiMichaelProgram10 : Form { List<PersonEntry> personsList = new List<PersonEntry>; public chalabiMichaelProgram10() { InitializeComponent(); } private void chalabiMichaelProgram10_Load(object sender, EventArgs e) { try { StreamReader inputfile; string line; int count; inputfile = File.OpenText("contacts.txt"); while (!inputfile.EndOfStream) { line = inputfile.ReadLine(); char[] delimiters = { ',' }; string[] tokens; tokens = line.Split(delimiters); for( count = 0; count < 4; count++) { tokens[count] = tokens[count].Trim(); } } } } } } namespace ChalabiMichaelProgram10 { class PersonEntry { //Constructor. public PersonEntry() { lastName = ""; firstName = ""; phoneNumber = ""; email = ""; } public string lastName { get; set; } public string firstName { get; set; } public string phoneNumber { get; set; } public string email { get; set; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/62768590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: array used the same memory space? i have an array in the main program like this: (i am using C# to program in asp.net) double[][] example= new double[][]; for this example lets imagine is an array of 10*2. so next thing i will do is send this array to another function like this: usedarray(example); public double[][] usedarray(double[][]examplearray) { } i know that a double array in each space has only 64 bit floating point number, so the array will have a 1280 bits for this example used memory, but when is send to the function it used the same space of memory? or it use a complete new set of memory space? A: Arrays are reference types, not value types. That means that the variable, examplearray doesn't actually contain 1280 bits of data, it just contains a reference (sometimes also referred to as a pointer) to the actual data, which is stored elsewhere (for the purposes of this post, it doesn't matter where "elsewhere" actually is). Passing that variable to a method, as you have done there, is only copying that reference (which is 32 or 64 bits, depending on the system), not the underlying 1280 bits of data.
{ "language": "en", "url": "https://stackoverflow.com/questions/13074824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: onRestart() and onRefresh() Act Different with Same Code I have the exact same methods and calls in onRefresh() and onRestart(), but for some reason onRestart() does what I want exactly, yet onRefresh() acts differently. What I want to happen is for app to understand when the location is disabled while running. onRestart() does this: I start the app, get the Forecast data, disable location from status bar, press the home button and open the app again. As expected, onRestart() tries to check for GPS status(with gpsTracker.getIsGPSEnabled()), sees that location is disabled, and sends the according Toast message. onRefresh() does this: I start the app, get the Forecast data, disable location from status bar, even wait few seconds and then refresh the app. Unexpectedly, onRefresh() gives sends the "Data Refreshed" toast, even though it gets "null, null" as location latitude and longitude. I could provide other codes as well, but if there was a problem with the rest of the code, why would onRestart() act the way I want? I'm not getting any errors. Any help would be highly appreciated. Thanks. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); final GPSTracker gpsTracker = new GPSTracker(this); mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); if (gpsTracker.getIsGPSTrackingEnabled()) { gpsTracker.getLocation(); getForecast(gpsTracker); Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show(); } } }, 3000); } }); } @Override protected void onRestart() { super.onRestart(); final GPSTracker gpsTracker = new GPSTracker(this); new Handler().postDelayed (new Runnable () @Override public void run() { gpsTracker.getLocation(); if (gpsTracker.getIsGPSTrackingEnabled()) { getForecast(gpsTracker); Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show(); } } }, 3000); } A: onRestart you create a new instance of GPSTracker. try updating your GPSTracker handler in onRefresh. give it a try A: @Override public void onRefresh() { final GPSTracker gpsTracker = new GPSTracker(MainActivity.this); new Handler().postDelayed(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); if (gpsTracker.getIsGPSTrackingEnabled()) { gpsTracker.getLocation(); getForecast(gpsTracker); Toast.makeText(MainActivity.this, "Data Refreshed", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Location is not enabled", Toast.LENGTH_LONG).show(); } } }, 3000); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/34661858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use jdt.ast to resolve polymorphism I'm working to get the override method binding through eclipse-jdt-ast. Just like when we using eclipse, press Ctrl and click the method ,we can jump to the method implenmentation. Although it's dynamic binging in java, but the following works well: public class Father{ public void test(){} } And Son: public class Son extends Father{ @Override public void test(){} public static void main (String[] arg){ Father f=new Son(); f.test(); } } When we click the test in main, we can correctly jump to the Son.java And I'm wondering how to do it. I tried to see the sources but didn't find the location because the code is too many. And my code now is : public class Main { static String filep="example/Son.java"; static String[] src={"example/"}; static String[] classfile={"example/"}; public static void main(String[] args) throws IOException,Exception{ ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(Files.toString(new File(filep), Charsets.UTF_8).toCharArray()); // only setEnvironment can we get bindings from char[] parser.setEnvironment(classfile, src, null, true); parser.setUnitName(filep); parser.setResolveBindings(true); parser.setKind(ASTParser.K_COMPILATION_UNIT); CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null); if (compilationUnit.getAST().hasResolvedBindings()) { System.out.println("Binding activated."); } else { System.out.println("Binding is not activated."); } ASTNode node=compilationUnit.findDeclaringNode("f"); compilationUnit.accept(new Myvisitor(compilationUnit)); } } And my visitor is: public class Myvisitor extends ASTVisitor { int i=0; CompilationUnit compilationUnit; Myvisitor(CompilationUnit compilationUnit){ this.compilationUnit=compilationUnit; } @Override public boolean visit(MethodInvocation node) { i++; System.out.println(i); IMethodBinding binding=node.resolveMethodBinding(); ASTNode astNode=compilationUnit.findDeclaringNode(binding); System.out.println(astNode); return true; } } It's a little long but simple, hope u can read here. Personally I guess the findDeclaringNode method may do it. However, it returns null when I pass the binding. So do u have any ideas? Thanks a lot A: When looking for all implementations of a given super method, the AST is of little help, as even with its bindings it only has references from sub to super but not the opposite direction. Searching in the opposite direction uses the SearchEngine. If you look at JavaElementImplementationHyperlink the relevant code section can be found around line 218 (as of current HEAD) You will have to first find the IMethod representing the super method. Then you prepare a SearchRequestor, an IJavaSearchScope, and a SearchPattern before finally calling engine.search(..). Search results are collected in ArrayList<IJavaElement> links. A good tradition of Eclipse plug-in development is "monkey see, monkey do", so I hope looking at this code will get you started on your pursuit :)
{ "language": "en", "url": "https://stackoverflow.com/questions/41176592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Close a MSI file handle after being downloaded from a website I have a vsto add-in for outlook. There is a code where I download a MSI file from a website: Public Sub DownloadMsiFile() Try Dim url As String = "https://www.website.com/ol.msi" Dim wc As New WebClient() wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;") If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then System.IO.File.Delete(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") End If wc.DownloadFile(url, My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") wc.Dispose() Catch ex As Exception MessageBox.Show("File couldn't be downloaded: " & ex.Message) End Try End Sub And then I get the MSI version using the following function: Function GetMsiVersion() As String Try Dim oInstaller As WindowsInstaller.Installer Dim oDb As WindowsInstaller.Database Dim oView As WindowsInstaller.View Dim oRecord As WindowsInstaller.Record Dim sSQL As String oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer) DownloadMsiFile() If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0) sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'" oView = oDb.OpenView(sSQL) oView.Execute() oRecord = oView.Fetch Return oRecord.StringData(1).ToString() Else Return Nothing End If Catch ex As Exception MessageBox.Show("File couldn't be accessed: " & ex.Message) End Try End Function And then I do the comparison with the current dll version to see if there is a need to download a newer version or not: Public Sub CheckOLUpdates() Dim remoteVersion As String = GetMsiVersion() Dim installedVersion As String = Assembly.GetExecutingAssembly().GetName().Version.ToString If Not String.IsNullOrEmpty(remoteVersion) Then Try If String.Compare(installedVersion, remoteVersion) < 0 Then Dim Result As DialogResult = MessageBox.Show("A newer version is available for download, do you want to download it now?", "OL", System.Windows.Forms.MessageBoxButtons.OKCancel, MessageBoxIcon.Question) If Result = 1 Then System.Diagnostics.Process.Start("http://www.website.com/update") Else Exit Sub End If Else MessageBox.Show("You have the latest version installed!", "OL", MessageBoxButtons.OK, MessageBoxIcon.Information) End If Catch ex As Exception End Try End If End Sub This works pretty well if this ran once. However if I try again to check for update, I would get the following error which happens while trying to delete the file in DownloadMsiFile() : The process cannot access the file %temp%\ol.msi because it is being used by another process If I use the sysinternals handle.exe utility to check the handles on this file I get the outlook process having a handle lock on this file: handle.exe %temp%\ol.msi Nthandle v4.30 - Handle viewer Copyright (C) 1997-2021 Mark Russinovich Sysinternals - www.sysinternals.com OUTLOOK.EXE pid: 25964 type: File 4FC8: %temp%\ol.msi I was wondering how can I close the handle to avoid this error? Any help is really appreciated A: So here is what I have to do to close the handle. I have added the following lines after opening the MSI file: Marshal.FinalReleaseComObject(oRecord) oView.Close() Marshal.FinalReleaseComObject(oView) Marshal.FinalReleaseComObject(oDb) oRecord = Nothing oView = Nothing oDb = Nothing So my final code looked like the following: Function GetMsiVersion() As String Try Dim oInstaller As WindowsInstaller.Installer Dim oDb As WindowsInstaller.Database Dim oView As WindowsInstaller.View Dim oRecord As WindowsInstaller.Record Dim sSQL As String Dim Version As String oInstaller = CType(CreateObject("WindowsInstaller.Installer"), WindowsInstaller.Installer) DownloadMsiFile() If File.Exists(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi") Then oDb = oInstaller.OpenDatabase(My.Computer.FileSystem.SpecialDirectories.Temp & "\ol.msi", 0) sSQL = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'" oView = oDb.OpenView(sSQL) oView.Execute() oRecord = oView.Fetch Version = oRecord.StringData(1).ToString() Marshal.FinalReleaseComObject(oRecord) oView.Close() Marshal.FinalReleaseComObject(oView) Marshal.FinalReleaseComObject(oDb) oRecord = Nothing oView = Nothing oDb = Nothing Else Version = Nothing End If Return Version Catch ex As Exception MessageBox.Show("File couldn't be accessed: " & ex.Message) End Try End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/67393101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does this line of code means in javascript? function delay(n){ n = n || 2000 //other stuff } what does the first line do? Thanks. A: It means that if n, the argument passed to the function, is falsey, 2000 will be assigned to it. Here, it's probably to allow callers to have the option of either passing an argument, or to not pass any at all and use 2000 as a default: function delay(n){ n = n || 2000 console.log(n); } delay(); delay(500); But it would be more suitable to use default parameter assignments in this case. function delay(n = 2000){ console.log(n); } delay(); delay(500);
{ "language": "en", "url": "https://stackoverflow.com/questions/65545634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting tensorflow rounding mode I am working with small numbers in tensorflow, which sometimes results in numerical instability. I would like to increase the precision of my results, or at the very least determine bounds on my result. The following code shows a specific example of numerical errors (it outputs nan instead of 0.0, because float64 is not precise enough to handle 1+eps/2): import numpy as np import tensorflow as tf # setup eps=np.finfo(np.float64).eps v=eps/2 x_init=np.array([v,1.0,-1.0],dtype=np.float64) x=tf.get_variable("x", initializer=tf.constant(x_init)) square=tf.reduce_sum(x) root=tf.sqrt(square-v) # run with tf.Session() as session: init = tf.global_variables_initializer() session.run(init) ret=session.run(root) print(ret) I am assuming there is no way to increase the precision of values in tensorflow. But maybe it is possible to set the rounding mode, as in C++ using std::fesetround(FE_UPWARD)? Then, I could force tensorflow to always round up, which would make sure that I am taking the square root of a non-negative number. What I tried: I tried to follow this question that outlines how to set the rounding mode for python/numpy. However, this does not seem to work, because the following code still prints nan: import numpy as np import tensorflow as tf import ctypes FE_TONEAREST = 0x0000 # these constants may be system-specific FE_DOWNWARD = 0x0400 FE_UPWARD = 0x0800 FE_TOWARDZERO = 0x0c00 libc = ctypes.CDLL('libm.so.6') # may need 'libc.dylib' on some systems libc.fesetround(FE_UPWARD) # setup eps=np.finfo(np.float64).eps v=eps/2 x_init=np.array([v,1.0,-1.0],dtype=np.float64) x=tf.get_variable("x", initializer=tf.constant(x_init)) square=tf.reduce_sum(x) root=tf.sqrt(square-v) # run with tf.Session() as session: init = tf.global_variables_initializer() session.run(init) ret=session.run(root) print(ret) A: Replace ret=session.run(root) with ret = tf.where(tf.is_nan(root), tf.zeros_like(root), root).eval() Refer tf.where
{ "language": "en", "url": "https://stackoverflow.com/questions/48344974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Getting "Error: Invalid or corrupt jarfile corda.jar" while bootstrapping the Corda netwrok While trying to bootstrap the Corda network getting below error. Error: Invalid or corrupt jarfile corda.jar Please find more details below. root@domestic-lc:/home/POC_DomesticLC# java -jar corda-tools-network-bootstrapper-4.0.jar --dir build/nodes Bootstrapping local test network in /home/POC_DomesticLC/build/nodes Using corda.jar in root directory Generating node directory for PartyB Generating node directory for BankB Generating node directory for Notary Generating node directory for BankA Generating node directory for PartyA Nodes found in the following sub-directories: [PartyA, PartyB, BankB, BankA, Notary] Found the following CorDapps: [] Not copying CorDapp JARs as --copy-cordapps is set to FirstRunOnly, and it looks like this network has already been bootstrapped. Waiting for all nodes to generate their node-info files... #### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyA/logs #### Error: Invalid or corrupt jarfile corda.jar #### Error while generating node info file /home/POC_DomesticLC/build/nodes/PartyB/logs #### Error: Invalid or corrupt jarfile corda.jar #### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankA/logs #### Error: Invalid or corrupt jarfile corda.jar #### Error while generating node info file /home/POC_DomesticLC/build/nodes/BankB/logs #### Error: Invalid or corrupt jarfile corda.jar #### Error while generating node info file /home/POC_DomesticLC/build/nodes/Notary/logs #### Error: Invalid or corrupt jarfile corda.jar Error while generating node info file. Please check the logs in /home/POC_DomesticLC/build/nodes/PartyA/logs. A: Did you get over this issue? I've tried with bootstrap 4.0 but I didn't see any issue, so my suggestions are: * *check your java version, make sure it is 1.8.171+ *make sure the corda.jar (in your build /nodes/notary/corda.jar) is correct because bad network may cause the incomplete corda.jar downloaded *make sure you've got the tools from official website instead of copying from other way where the bootstrap jar file might be broken *last, as always, please try to use the latest version bootstrap: 4.3, to utilise the best Corda: https://software.r3.com/artifactory/corda-releases/net/corda/corda-tools-network-bootstrapper/4.3/ A: I had a similar problem (not with that particular JAR file, but I'm using that file's name in my examples). Here's how I worked out what was wrong. These troubleshooting steps may help others who find this issue (but not the OP as the dates show it can't be this issue). I started by trying to validate the JAR file by inspecting its contents: $ jar -tf corda.jar This showed me that it was indeed invalid. In my case, I saw: java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.<init>(ZipFile.java:225) at java.util.zip.ZipFile.<init>(ZipFile.java:155) at java.util.zip.ZipFile.<init>(ZipFile.java:126) at sun.tools.jar.Main.list(Main.java:1115) at sun.tools.jar.Main.run(Main.java:293) at sun.tools.jar.Main.main(Main.java:1288) I then looked at the size of the file: $ ls -alh corda.jar In my case, it was 133 bytes, which seems a bit small for a JAR file, so I cated it and saw this: $ cat corda.jar 501 HTTPS Required. Use https://repo1.maven.org/maven2/ More information at https://links.sonatype.com/central/501-https-required It turned out that my script (a Dockerfile in fact) was downloading the file with curl -o but from a URL which was no longer supported. As https://links.sonatype.com/central/501-https-required says: Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS. If you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts: Replace http://repo1.maven.org/maven2/ with https://repo1.maven.org/maven2/ Replace http://repo.maven.apache.org/maven2/ with https://repo.maven.apache.org/maven2/ If for any reason your environment cannot support HTTPS, you have the option of using our dedicated insecure endpoint at http://insecure.repo1.maven.org/maven2/ For further context around the move to HTTPS, please see https://blog.sonatype.com/central-repository-moving-to-https. This is fairly specific, but may help someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/59247439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to add facebook comment to single page application? i have website news (single page application ) this code woks well in aspx page <div id="fb-root"> </div> <script language="javascript" type="text/javascript"> (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=1403512256546141"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="fb-comments" style="width: 670px; float: left;" data-href="http://www.facebook.com/share.php?u=http://www.game11.com/%23/newsdetail/24" data-width="670" data-num-posts="10" dir="rtl" lang="aa"> </div> but how to do in View in SPA which doesn't contain html or body tags just div i use durandal in single page application A: Late answer, but maybe it will help someone. For me the key to getting unique fb comments to render on a single page application was FB.XFBML.parse(); Each time I want to render unique comments: * *Change the url, each fb comments thread is assigned to the specific url So I might have www.someurl.com/#123, www.someurl.com/#456, www.someurl.com/#789, each with its own fb comment thread. In AngularJs this can be done with $location.hash('123'); *Create a new fb-comments div, where 'number' equals '123', '456' or '789' <div class="fb-comments" data-href="http://someurl.com/#{{number}}" data-numposts="5" data-width="100%" data-colorscheme="light"> </div> *Call a function that executes the fb SDK function FBfun(path) { setTimeout(function() { // I'm executing this just slightly after step 2 completes window.fbAsyncInit = function() { FB.init({ appId : '123456789123', xfbml : true, version : 'v2.2' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); FB.XFBML.parse(); // This is key for all this to work! }, 100); } A: i added the script to app.js like initializeFB: function () { if (!isFBInitialized.isInitialized) { FB.init({ appId: 'xxxxxxxxxxxx', appSecret: 'xxxxxxxxxxxxxxx', // App ID from the app dashboard channelUrl: '//mysite//channel.html', // Channel file for x-domain comms status: true, // Check Facebook Login status cookie: true, // enable cookies to allow the server to access the session xfbml: true // Look for social XFBML plugins on the page to be parsed }); (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired // for any auth related change, such as login, logout or session refresh. This means that // whenever someone who was previously logged out tries to log in again, the correct case below // will be handled. FB.Event.subscribe('auth.authResponseChange', function (response) { // Here we specify what we do with the response anytime this event occurs. if (response.status === 'connected') { // The response object is returned with a status field that lets the app know the current // login status of the person. In this case, we're handling the situation where they // have logged in to the app. testFBAPI(); } else if (response.status === 'not_authorized') { // In this case, the person is logged into Facebook, but not into the app, so we call // FB.login() to prompt them to do so. // In real-life usage, you wouldn't want to immediately prompt someone to login // like this, for two reasons: // (1) JavaScript created popup windows are blocked by most browsers unless they // result from direct user interaction (such as a mouse click) // (2) it is a bad experience to be continually prompted to login upon page load. FB.login(); } else { // In this case, the person is not logged into Facebook, so we call the login() // function to prompt them to do so. Note that at this stage there is no indication // of whether they are logged into the app. If they aren't then they'll see the Login // dialog right after they log in to Facebook. // The same caveats as above apply to the FB.login() call here. FB.login(); } }); isFBInitialized.isInitialized = true; } }, and call it in viewattached as app.initializeFB(); then it works well A: Step 3 for my React app become (more linter friendly): componentDidMount() { window.fbAsyncInit = () => { window.FB.init({ appId: '572831199822299', xfbml: true, version: 'v4.0', }); }; (function (d, s, id) { const fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } const js = d.createElement(s); js.id = id; js.src = '//connect.facebook.net/ru_RU/sdk.js'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); setTimeout(() => { window.FB.XFBML.parse(); }, 100); }
{ "language": "en", "url": "https://stackoverflow.com/questions/19975902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Variable "Name" is not readable, how can I fix it? I was inserting some code to make a registration form, but iIfound this class User { private String Nama; private String Kelas; private int NIM; public String getNama{ return Nama; } public String setNama{ } } The error message was all "variable is never read". Can someone explain why there is a message on this, and how I can fix it? A: Though it is not clear where you use your codes, but the following is a java model class, with setter and getter method. Even it is not the direct answer of you question, but I have used this types of model class in my projects, one can find the idea of setter and getter from the following user class. For using in various purposes You can create your User class as follows with constructors and setter and getter methods : public class User { private String Nama; private String Kelas; private int NIM; public User() { } public User(String nama, String kelas, int NIM) { Nama = nama; Kelas = kelas; this.NIM = NIM; } public String getNama() { return Nama; } public void setNama(String nama) { Nama = nama; } public String getKelas() { return Kelas; } public void setKelas(String kelas) { Kelas = kelas; } public int getNIM() { return NIM; } public void setNIM(int NIM) { this.NIM = NIM; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/71616728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run a javascript on regex pattern match url (Blogger) I'm trying to load a javascript on several pages but I only on pages which the url matches with a specific pattern. The following code works for specific pages but it doesn't accept any wildcard or regex <b:if cond='data:blog.url == &quot;https://mywebsite.com/yyyy/mm/article.html&quot;'> <script src='https://javascritp.js'/> </b:if> The closest thing I found is described here but since my website is running on Blogger I don't know how to use that code. Any suggestion or help please? A: Blogger conditional statements don't provide pattern matching capability. It would be easier to implement what you require via JavaScript directly in the Blogger template - An example code would look like - if(window.location.href.match(/Regex-Condition/){ var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'URL-Of-The-Script-You-Want-To-Load';script.async=true; var insertScript = document.getElementsByTagName('script')[0]; insertScript.parentNode.insertBefore(script, insertScript); } Other than this, you can also take a look at Lambda expressions (Refer to How to use Google Blogger Lambda Operators ) A: Hi and thank you for your feedback! While I was waiting for some reply I realized I've to use JavaScript as you said. I was testing this code but it looks something is wrong: <script type='text/javascript'> var pattern = new RegExp(&#39;mywebsite\.com\/(200[8-9]|201[0-6])\/&#39;); if (pattern.test(document.location.href)) { } </script> I've two main concerns: * *if the regex is correct *between the brackets I've to execute some code which includes Blogger conditional statements, div and plain JavaScript. Does this code need some special attention? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/42323018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split string using SUBSTR or SPLIT? I'm at a loss and hoping to find help here. What I'm trying to accomplish is the following: I have a .csv file with 8 columns. The third column contains phone numbers formatted like so: +45 23455678 +45 12314425 +45 43631678 +45 12345678 (goes on for a while) What I want is: +45 2345 5678 +45 1231 4425 +45 4363 1678 +45 1234 5678 (etc) So just a whitespace after the 8th position (inc the + and whitespace). I've tried various things but it's not working. First I tried it with substr but couldn't get it to work. Then looked at the split function. And then I got confused! I'm new to perl so I'm not sure what I'm looking for but I've tried everything. There's 1 condition, all the numbers begin with (let's say) +45 and then a whitespace and a block of numbers. But not all the numbers have the same length, some have more than 10 digits. What I want it to do is take the first bit "+45 1234" (/+43\s{1}\d{4}/) and then the second part no matter how many digits it has. I figured setting LIMIT to 1 so it just adds the last bit no matter if its 4 digits or 8 long. I've read http://www.perlmonks.org/?node_id=591988, but the part "Using split versus Regular Expressions" got me confused. I've been trying for 3 days now and not getting anywhere. I guess it should be simple but I'm just now getting to know the basics of perl. I do have an understanding of regular expression but I don't know what statement to use for a certain task. This is my code: @ARGV or die "Usage: $0 input-file output-file\n"; $inputfile=$ARGV[0]; $outputfile=$ARGV[1]; open(INFILE,$inputfile) || die "Bestand niet gevonden :$!\n"; open(OUTFILE,">$outputfile") || die "Bestand niet gevonden :$!\n"; $i = 0; @infile=<INFILE>; foreach ( @infile ) { $infile[$i] =~ s/"//g; @elements = split(/;/,$infile[$i]); @split = split(/\+43\s{1}\d{4}/, $elements[2], 1); @split = join ??? @elements = join(";",@elements); # Add ';' to all elements print OUTFILE "@elements"; $i = $i+1; } close(INFILE); close(OUTFILE); A: There are several issues with your code, but to address your question on how to add a space after the 8th position in a string, I'm going to assume you have stored your phone numbers in an array @phone_numbers. This is a task well suited for a regex: #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; my @phone_numbers = ( '+45 23455678', '+45 12314425', '+45 43631678', '+45 12345678' ); s/^(.{8})/$1 / for @phone_numbers; print Dumper \@phone_numbers; Output: $VAR1 = [ '+45 2345 5678', '+45 1231 4425', '+45 4363 1678', '+45 1234 5678' ]; To apply the pattern to your script, just add: $elements[2] =~ s/^(.{8})/$1 /; or alternatively my @chars = split//, $elements[2]; splice @chars, 8, 0, ' '; $elements[2] = join"", @chars; to alter phone numbers within your foreach loop. A: Here is a more idiomatic version of your program. use strict; use warnings; my $inputfile = shift || die "Need input and output file names!\n"; my $outputfile = shift || die "Need an output file name!\n"; open my $INFILE, '<', $inputfile or die "Bestand niet gevonden :$!\n"; open my $OUTFILE, '>', $outputfile or die "Bestand niet gevonden :$!\n"; my $i = 0; while (<$INFILE>) { # print; # for debugging s/"//g; my @elements = split /;/, $_; print join "%", @elements; $elements[2] =~ s/^(.{8})/$1 /; my $output_line = join(";", @elements); print $OUTFILE $output_line; $i = $i+1; } close $INFILE; close $OUTFILE; exit 0; A: use substr on left hand side: use strict; use warnings; while (<DATA>) { my @elements = split /;/, $_; substr($elements[2], 8, 0) = ' '; print join(";", @elements); } __DATA__ col1;col2;+45 23455678 col1;col2;+45 12314425 col1;col2;+45 43631678 col1;col2;+45 12345678 output: col1;col2;+45 2345 5678 col1;col2;+45 1231 4425 col1;col2;+45 4363 1678 col1;col2;+45 1234 5678 A: Perl one liner which you can use for multiple .csv files also. perl -0777 -i -F/;/ -a -pe "s/(\+45\s\d{4})(\d+.*?)/$1 $2/ for @F;$_=join ';',@F;" s_infile.csv A: This is the basic gist of how its done. The "prefix" to the numeric string is \+45, which is hard coded, and you may change it as needed. \pN means numbers, {4} means exactly 4. use strict; use warnings; while (<DATA>) { s/^\+45 \pN{4}\K/ /; print; } __DATA__ +45 234556780 +45 12314425 +45 436316781 +45 12345678 Your code has numerous other problems: You do not use use strict; use warnings;. This is a huge mistake. It's like riding a motorcycle and protecting your head by putting on a blindfold instead of a helmet. Often, it is an easy piece of advice to overlook, because it is explained very briefly, so I am being more verbose than I have to in order to make a point: This is the most important thing wrong. If you miss all the rest of your errors, it's better than if you miss this part. Your open statements are two-argument, and you do not verify your arguments in any way. This is very dangerous, because it allows people to perform arbitrary commands. Use the three-argument open with a lexical file handle and explicit MODE for open: open my $in, "<", $inputfile or die $!; You slurp the file into an array: @infile=<INFILE> The idiomatic way to read a file is: while (<$in>) { # read line by line ... } What's even worse, you loop with foreach (@infile), but refer to $infile[$i] and keep a variable counting upwards in the loop. This is mixing two styles of loops, and even though it "works", it certainly looks bad. Looping over an array is done either: for my $line ( @infile ) { # foreach style $line =~ s/"//g; ... } for my $index ( 0 .. $#infile ) { # array index style $infile[$index] =~ .... } But neither of these two loops are what you should use, since the while loop above is much preferred. Also, you don't actually have to use this method at all. The *nix way is to supply your input file name or STDIN, and redirect STDOUT if needed: perl script.pl inputfile > outputfile or, using STDIN some_command | perl script.pl > outputfile To achieve this, just remove all open commands and use while (<>) { # diamond operator, open STDIN or ARGV as needed ... } However, in this case, since you are using CSV data, you should be using a CSV module to parse your file: use strict; use warnings; use ARGV::readonly; # safer usage of @ARGV file reading use Text::CSV; my $csv = Text::CSV->new({ sep_char => ";", eol => $/, binary => 1, }); while (my $row = $csv->getline(*DATA)) { # read input line by line if (defined $row->[1]) { # don't process empty rows $row->[1] =~ s/^\+45 *\pN{4}\K/ /; } $csv->print(*STDOUT, $row); } __DATA__ fooo;+45 234556780;bar 1231;+45 12314425; oh captain, my captain;+45 436316781;zssdasd "foo;bar;baz";+45 12345678;barbarbar In the above script, you can replace the DATA file handle (which uses inline data) with ARGV, which will use all script argument as input file names. For this purpose, I added ARGV::readonly, which will force your script to only open files in a safe way. As you can see, my sample script contains quoted semi-colons, something split would be hard pressed to handle. The specific print statement will enforce some CSV rules to your output, such as adding quotes. See the documentation for more info. A: To add a space after the eighth character of a string you can use the fourth parameter of substr. substr $string, 8, 0, ' '; replaces a zero-length substring starting at offset 8 with a single space. You may think it's safer to use regular expressions so that only data in the expected format is changed $string =~ s/^(\+\d{2} \d{4})/$1 /; or $str =~ s/^\+\d{2} \d{4}\K/ /; will achieve the same thing, but will do nothing if the number doesn't look as it should beforehand. Here is a reworking of your program. Most importantly you should use strict and use warnings at the start of your program, and declare variables with my at the point of their first use. Also use the three-paramaeter form of open and lexical filehandles. Lastly it is best to avoid reading an entire file into an array when a while loop will let you process it a line at a time. use strict; use warnings; @ARGV == 2 or die "Usage: $0 input-file output-file\n"; my ($inputfile, $outputfile) = @ARGV; open my $in, '<', $inputfile or die "Bestand niet gevonden: $!"; open my $out, '>', $outputfile or die "Bestand niet gevonden: $!"; while (<$in>) { tr/"//d; my @elements = split /;/; substr $elements[2], 8, 0, ' '; print $out join ';', @elements; }
{ "language": "en", "url": "https://stackoverflow.com/questions/11099174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DOM reload after ajax form injection Ive tried similar questions to no avail. My question is simply how to reload the DOM after an ajax request has been made? Its not a question regarding event delegation, rather one concerning jquery selectors. sample: editUser : function(){ var editItem = $("a.edit"); editItem.on('click', function(e){ e.preventDefault(); //click the users tab & the edit tab var usersjq = $("li#users-jq"); usersjq.find("a").eq(0).click(); $("ul.tabs").find("a").eq(2).click(); var uid = $(this).attr('id').split('_')[1]; $(".three #users-edit").empty(); $(".three #users-edit").load(BASE_PATH + 'users/admin/users/edit/' + uid, function(){ //loads a form with id of #form-users-edit }, 'html'); }); }, formEditUsers : function(){ //#form-users-edit is not selectable //all of these just return jQuery ( ) console.log($(".three #users-edit").find("#form-users-edit")); console.log($(document.forms)); console.log($("form#form-users-edit")); } Regards. A: Passing formEditUsers() into the ajax success callback seems to work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/9270403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not full binding in knockout Knockout doesn't work as expected, im my interface. I suppose my mistake. But I cannot understand it. I have an album with genres included tracks with genres: var initialData = [{ title: 'Danny', genres: [ {id: 21, title: 'Noise'}, {id: 22, title: 'EBM'}], tracks: [ {title: 'Pony', genres: [ {id: 21, title: 'Noise'}, {id: 22, title: 'EBM'}]}, {title: 'Hungry', genres: [ {id: 21, title: 'Noise'}, {id: 22, title: 'EBM'}]} ] }]; I want to create 1-way sync between album genres to tracks genres: * *If i add genre to album, this genre would be added to all tracks. *If i delete genre from album, this genre would be deleted from all tracks. *If i add genre to track, this genre would be added only to this track. *If i delete genre from track, this genre would be deleted only from this track. My sync works fine (except one case) with this functions: self.addGenre = function(album) { var id = rand(), item = { id: id, title: ' genre #' + id }; album.genres.push(item); if (album.tracks()) { $.each(album.tracks(), function (index, track) { track.genres.push(item); }); } }; self.removeGenre = function(genre) { $.each(self.albums(), function() { this.genres.remove(genre); if (this.tracks()) { $.each(this.tracks(), function (index, track) { track.genres.remove(genre); }); } }); }; Exception is if I want to delete default (Noise, EBM, see initialData above ) genre from albums. it doesn't work. I created an jsFiddle to show this case and include in it a lot of console.log() to debug A: The problem is that when you use ko-mapping, it turns every property into an observable. The new genres you create are not the same kind of object as the initial objects, because they are just standard vanilla objects. So the genre you are trying to remove from the track is not the same one you removed from the album. A simple way to fix your issue is to alter the remove function, as in this fiddle. $.each(this.tracks(), function(index, track) { var toRemove = ko.utils.arrayFirst(track.genres(), function(item) { return ko.utils.unwrapObservable(genre.id) == ko.utils.unwrapObservable(item.id); }); track.genres.remove(toRemove); }); A better way would be to be a little more thorough in generating your initial viewmodel, the new genres, or both. This won't be easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/13171144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transitioning Between Index Paths in a DetailViewController? Swift So using the code below, I've segued my CollectionViewCell indexPath into the new DetailViewController. now each `DetailViewController displays what is contained in the array of the indexPath selected. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let animal: Animal! let anims: [Animal] = dataSource.anims animal = anims.filter{ $0.isDefault }[indexPath.row] DispatchQueue.main.async { self.performSegue(withIdentifier: "DetailVC", sender: animal) } } So that means the new DetailVCwill be able to pull the data from the array that corresponds with the selected indexPath.row, which it does. Now here's the issue. Once I'm in the DetailVC, I want to make a button that lets me switch the displayed data to the previous or next indexPath.row. To explain it better, below is some Pseudo-Code that explains what I'm trying to do @IBAction func nextIndex(_ sender: Any) { self.view.indexPath.row = self.view.indexPath.row +1 or self.datasource = next datasource index } Now what would I need to do to transition between these indexPaths from inside the DetailViewController? Such as a "go to next" or "go to previous" or "go to [selected path]" button? I feel there may be a simple answer to this that I'm not getting. A: Easy solution: You can implement singleton, manager that will be responsible for this. e.g. class AnimalManager: NSObject { static let shared = AnimalManager() private var animals = [Animal]() private var currentIndex: Int? ..... } Now you can implement such methods like: current animal, next animal, revious, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/41434270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Colour newly added bar in bar chart automatically when new data is received Following code basically put a colour in my bar graph based on cell D112 value. Now is there a way to automatically put colour as new data is available and new bar is added to my bar chart? For example, Cell D112 is the value for the month of Jan, now when i get value in cell D113 for the month of Feb, how do i colour the bar of that month automatically? I'm guessing there has to be some kind of a loop here right? Sub ColorGraphs() Dim ChrtObj As ChartObject Dim Ser As Series Dim SerPoint As Point Set ChrtObj = ActiveSheet.ChartObjects("Chart 18") Set Ser = ChrtObj.Chart.SeriesCollection(1) Set SerPoint = Ser.Points(3) With SerPoint.Format.Fill .Visible = msoTrue .Transparency = 0 .Solid End With Select Case Range("D112").Value Case Is < 0.96 SerPoint.Format.Fill.ForeColor.RGB = RGB(204, 0, 51) Range("P8").Interior.Color = RGB(204, 0, 51) Case 0.96 To 0.98 SerPoint.Format.Fill.ForeColor.RGB = RGB(255, 102, 0) Range("P8").Interior.Color = RGB(255, 102, 0) Case Else ' larger than 0.98 SerPoint.Format.Fill.ForeColor.RGB = RGB(0, 153, 102) Range("P8").Interior.Color = RGB(0, 153, 102) End Select End Sub A: Try putting your code in Private Sub Worksheet_Change(ByVal Target as Range). This Sub runs te code every time a cell is changed.
{ "language": "en", "url": "https://stackoverflow.com/questions/49498952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a data structure for a list ordered by value? I've got a JTable which shows the top 10 scores of a game. The data structure looks like the following: // {Position, Name, Score} Object[][] data = { {1, "-", 0}, {2, "-", 0}, {3, "-", 0}, {4, "-", 0}, {5, "-", 0}, {6, "-", 0}, {7, "-", 0}, {8, "-", 0}, {9, "-", 0}, {10, "-", 0} }; I want to be able to add a new score to this array in the correct order (so if it was the 3rd highest, it would be put at index 2). I'll then truncate this list down to the top 10 again and update the table. I know this is trivial to do by looping through and checking, but I'd like to know if there is an appropriate data structure that is better suited for data ordered by a value? Or is the simple two-dimensional array the only/best? A: Use a TreeSet with a custom comparator. Also, you should not work with Multi-dimensional arrays, use Maps (Name -> Score) or custom Objects A: Hey, if your array is sorted, u can use the Collections.binarySearch() or Arrays.binarySearch() method to guide u at what index to make the insertion. The way these method work is to make a binary search after an existing element, and if the element cannot be found in the collection it will return a value related to the insertion point. More info here Collections.binarySearch
{ "language": "en", "url": "https://stackoverflow.com/questions/5384093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to validate status code in robot framework i about to make a validation status code in robot framework. i create value in json with wrong password and i want to make validation code 400 bad request with this code. login_negative_user ${json} Load JSON From File ${CURDIR}/../json/negativeuser.json # Set Test Variable ${JSON_SCHEMA} ${json} ${resp}= POST ${base_url}/horde/v1/auth/login json=${json} ${data} Convert To String ${resp.json()} Status Should Be 400 ${resp} Should Be Equal As Strings ${resp.status_code} 400 ${jsondata} evaluate ${data} ${poselang}= Set Variable ${jsondata['data']['token']} Set Global Variable ${poselang} log to console Get poselang token But my log is this login negativeuser | FAIL | HTTPError: 400 Client Error: Bad Request for url: {secret api} am i wrong to make validation with that code? sorry i cant tell the api because it is secret
{ "language": "en", "url": "https://stackoverflow.com/questions/72373112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to rename a similarly named column from two tables when performing a join? I have two tables that I am joining with the following query... select * from Partners p inner join OrganizationMembers om on p.ParID = om.OrganizationId where om.EmailAddress = 'my_email@address.com' and om.deleted = 0 Which works great but some of the columns from Partners I want to be replaced with similarly named columns from OrganizationMembers. The number of columns I want to replace in the joined table are very few, shouldn't be more than 3. It is possible to get the result I want by selectively choosing the columns I want in the resulting join like so... select om.MemberID, p.ParID, p.Levelz, p.encryptedSecureToken, p.PartnerGroupName, om.EmailAddress, om.FirstName, om.LastName from Partners p inner join OrganizationMembers om on p.ParID = om.OrganizationId where om.EmailAddress = 'my_email@address.com' and om.deleted = 0 But this creates a very long sequence of select p.a, p.b, p.c, p.d, ... etc ... which I am trying to avoid. In summary I am trying to get several columns from the Partners table and up to 3 columns from the OrganizationMembers table without having a long column specification sequence at the beginning of the query. Is it possible or am I just dreaming? A: select om.MemberID as mem Use th AS keyword. This is called aliasing. A: Try this: p.*, om.EmailAddress, om.FirstName, om.LastName You should never use * though. Always specifying the columns you actually need makes it easier to find out what happens. A: You are dreaming in your implementation. Also, as a best practice, select * is something that is typically frowned upon by DBA's. If you want to limit the results or change anything you must explicitly name the results, as a potential "stop gap you could do something like this. SELECT p.*, om.MemberId, etc.. But this ONLY works if you want ALL columns from the first table, and then selected items. A: But this creates a very long sequence of select p.a, p.b, p.c, p.d, ... etc ... which I am trying to avoid. Don't avoid it. Embrace it! There are lots of reasons why it's best practice to explicity list the desired columns. * *It's easier to do searches for where a particular column is being used. *The behavior of the query is more obvious to someone who is trying to maintain it. *Adding a column to the table won't automatically change the behavior of your query. *Removing a column from the table will break your query earlier, making bugs appear closer to the source, and easier to find and fix. And anything that uses the query is going to have to list all the columns anyway, so there's no point being lazy about it!
{ "language": "en", "url": "https://stackoverflow.com/questions/2418528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: can not read some string from struts.properties I have define variable error in struts.properties as follows: error=this is an error Now I can call this error as follows: ErrorMsg = "<s:property value='getText(\"error\")'/>"; and it works, the result is: ErrorMsg=this is an error How to get the text of variable instead of string? I tried the following: var m="error"; error1 = "<s:property value='getText(m)'/>"; error2 = "<s:property value='getText(\"m\")'/>"; I use firebug debugger and error1 and error2 are displyed as follows: error1="" error2="" Any Idea? thank you in advance A: You appear to be mixing server side and client side code. The s:property tags will be evaluated first on the server side, long before any value of m is valid, as that is client side JavaScript code. If you post what you're trying to achieve then I or someone else may be able to help further. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/10020352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'boost/multi_array.hpp' file not found error while building on Mac I am trying to build using Cmake on macOS Big Sur. Following is the makefile. CMAKE_MINIMUM_REQUIRED(VERSION 3.5) #------------------------------------------------------------------------------# # Compiler setup #------------------------------------------------------------------------------# IF(CMAKE_SYSTEM_NAME=Windows) SET(ADDITIONAL_FLAGS "-DWIN32") ENDIF(CMAKE_SYSTEM_NAME=Windows) SET(CMAKE_CXX_COMPILER "g++") SET(CMAKE_CXX_FLAGS "-std=c++17 -g -Wall -Wno-uninitialized") SET(CMAKE_CXX_FLAGS_DEBUGALL "${CMAKE_CXX_FLAGS} -fsanitize=address,undefined -pthread" ) SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -O3 -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} ) SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} -O3 -DNDEBUG -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} ) SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS} -O3 -g -DNDEBUG -DOPTIMIZE -pthread" ${ADDITIONAL_FLAGS} ) #SET(CMAKE_BUILD_TYPE Debug) IF(NOT CMAKE_BUILD_TYPE) SET(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build: Debug Release RelWithDebInfo" FORCE) ENDIF(NOT CMAKE_BUILD_TYPE) #------------------------------------------------------------------------------# # Required libraries #------------------------------------------------------------------------------# SET(Boost_DEBUG "ON") SET(Boost_USE_STATIC_LIBS "ON") SET(HOME_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE INTERNAL "") SET(CMAKE_MODULE_PATH ${HOME_DIR}/CMake) FIND_PACKAGE(Boost COMPONENTS filesystem program_options timer chrono REQUIRED) SET(EXTERNAL_INCLUDES ${Boost_INCLUDES}) SET(EXTERNAL_LIBRARIES ${Boost_LIBRARIES}) FIND_PACKAGE(Eigen3 3.3.4) INCLUDE_DIRECTORIES(${EIGEN3_INCLUDE_DIRS}) #------------------------------------------------------------------------------# # Directories for compiled libraries #------------------------------------------------------------------------------# INCLUDE_DIRECTORIES(src/Mesh) INCLUDE_DIRECTORIES(src/Quadrature) INCLUDE_DIRECTORIES(src/Common) INCLUDE_DIRECTORIES(src/HybridCore) INCLUDE_DIRECTORIES(src/Plot) INCLUDE_DIRECTORIES(src/DDRCore) ADD_SUBDIRECTORY(src/Mesh) ADD_SUBDIRECTORY(src/Quadrature) ADD_SUBDIRECTORY(src/Common) ADD_SUBDIRECTORY(src/HybridCore) ADD_SUBDIRECTORY(src/Plot) ADD_SUBDIRECTORY(src/DDRCore) #------------------------------------------------------------------------------# # Directories for schemes #------------------------------------------------------------------------------# INCLUDE_DIRECTORIES(Schemes) ADD_SUBDIRECTORY(Schemes) While running make command I am getting fatal error: 'boost/multi_array.hpp' file not found #include <boost/multi_array.hpp> I have boost installed with the help of brew. I also tried this https://stackoverflow.com/a/32929012/8499104 to verify my path is correct. Still not able to figure out why this is not able to find this library.
{ "language": "en", "url": "https://stackoverflow.com/questions/69711110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redirecting in react-router-dom v6 in a non-JSX context I'm trying to redirect a user from the route they are currently looking at to another route programatically. In my case, I am not in a JSX environment, and cannot use any kind of React hooks. How would I go about this? I tried to use the code block below to redirect (tried using JSX), only to realize that it wouldn't work as it isn't in the context of the root router. ReactDOM.render(<div> <Navigate to="/" /> </div>, document.getElementById("redirect")); I also want to try and redirect without using window.location.href = as that would cause the whole page to refresh, something I don't want to happen. EDIT: As requested, I am trying to redirect to a page from an event that is emitted by Tauri and is handled by some TypeScript code on the front end. Using window.location.href isn't an issue in any case. Here is an example of what I'm trying to do: /** * Sets up event listeners. */ export async function setupListeners() { console.log("Setting up link event listeners..."); await listen("deeplink", onLinked); } /** * Invoked when a deep link call is received. * @param event The event. */ async function onLinked(event: Event<string>) { const { payload } = event; if (payload == "test:") // redirect("/testPage"); } A: See redirect: import { redirect } from "react-router-dom"; const loader = async () => { const user = await getUser(); if (!user) { return redirect("/login"); } }; (from the docs)
{ "language": "en", "url": "https://stackoverflow.com/questions/75024625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does Doctrine generate:entities create getters and setter in symfony I have class User likr this class user implements UserInterface { protected id , protected username; Then i have class student extends user { protected id , protected rollno; Now when i run this php app/console doctrine:generate:entities myBundle Then propery username gets inserted in class student. I want to know that is this ok or its error. Because then whats the use of extending from base class if my lass is going to be populated with all stuff A: This isn't an error. Symfony threats all classes as entities and if you're "mapping" them with doctrine you'll create the corrisponding tables onto database. Now inheritance have to be taken into account: every "field" (property) into parent classe, will be extended or inherited by child. So is perfectly clear that the corresponding parent field will be created into database. To me the best way for solve this is to create a parent class and to migrate all commons (fields,methods and so on...) into it. Then, you'll extend that new parent calss into user with specific fields (in that case username) aswell into student with student's specific fields. A: Yeah, that's probably not an error, although I agree it can be annoying. To see how exactly are they generated you can look into the command class.
{ "language": "en", "url": "https://stackoverflow.com/questions/11464227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Double buffering with C# has negative effect I have written the following simple program, which draws lines on the screen every 100 milliseconds (triggered by timer1). I noticed that the drawing flickers a bit (that is, the window is not always completely blue, but some gray shines through). So my idea was to use double-buffering. But when I did that, it made things even worse. Now the screen was almost always gray, and only occasionally did the blue color come through (demonstrated by timer2, switching the DoubleBuffered property every 2000 milliseconds). What could be an explanation for this? using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = CreateGraphics(); Pen pen = new Pen(Color.Blue, 1.0f); Random rnd = new Random(); for (int i = 0; i < Height; i++) g.DrawLine(pen, 0, i, Width, i); } // every 100 ms private void timer1_Tick(object sender, EventArgs e) { Invalidate(); } // every 2000 ms private void timer2_Tick(object sender, EventArgs e) { DoubleBuffered = !DoubleBuffered; this.Text = DoubleBuffered ? "yes" : "no"; } } } A: I would just draw all of your items to your own buffer, then copy it all in at once. I've used this for graphics in many applications, and it has always worked very well for me: public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { Invalidate();// every 100 ms } private void Form1_Load(object sender, EventArgs e) { DoubleBuffered = true; } private void Form1_Paint(object sender, PaintEventArgs e) { Bitmap buffer = new Bitmap(Width, Height); Graphics g = Graphics.FromImage(buffer); Pen pen = new Pen(Color.Blue, 1.0f); //Random rnd = new Random(); for (int i = 0; i < Height; i++) g.DrawLine(pen, 0, i, Width, i); BackgroundImage = buffer; } EDIT: After further investigation, it looks like your problem is what you're setting your Graphics object to: Graphics g = CreateGraphics(); needs to be: Graphics g = e.Graphics(); So your problem can be solved by either creating a manual buffer like I did above, or simply changing you Graphics object. I've tested both and they both work. A: Try setting the double buffered property to true just once in the constructor while you're testing. You need to make use of the back buffer. Try this: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace DoubleBufferTest { public partial class Form1 : Form { private BufferedGraphicsContext context; private BufferedGraphics grafx; public Form1() { InitializeComponent(); this.Resize += new EventHandler(this.OnResize); DoubleBuffered = true; // Retrieves the BufferedGraphicsContext for the // current application domain. context = BufferedGraphicsManager.Current; UpdateBuffer(); } private void timer1_Tick(object sender, EventArgs e) { this.Refresh(); } private void OnResize(object sender, EventArgs e) { UpdateBuffer(); this.Refresh(); } private void UpdateBuffer() { // Sets the maximum size for the primary graphics buffer // of the buffered graphics context for the application // domain. Any allocation requests for a buffer larger // than this will create a temporary buffered graphics // context to host the graphics buffer. context.MaximumBuffer = new Size(this.Width + 1, this.Height + 1); // Allocates a graphics buffer the size of this form // using the pixel format of the Graphics created by // the Form.CreateGraphics() method, which returns a // Graphics object that matches the pixel format of the form. grafx = context.Allocate(this.CreateGraphics(), new Rectangle(0, 0, this.Width, this.Height)); // Draw the first frame to the buffer. DrawToBuffer(grafx.Graphics); } protected override void OnPaint(PaintEventArgs e) { grafx.Render(e.Graphics); } private void DrawToBuffer(Graphics g) { //Graphics g = grafx.Graphics; Pen pen = new Pen(Color.Blue, 1.0f); //Random rnd = new Random(); for (int i = 0; i < Height; i++) g.DrawLine(pen, 0, i, Width, i); } } } It's a slightly hacked around version of a double buffering example on MSDN. A: No need to use multiple buffers or Bitmap objects or anything. Why don't you use the Graphics object provided by the Paint event? Like this: private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Pen pen = new Pen(Color.Blue, 1.0f); Random rnd = new Random(); for (int i = 0; i < Height; i++) g.DrawLine(pen, 0, i, Width, i); }
{ "language": "en", "url": "https://stackoverflow.com/questions/2566126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OnNotifyPropertyChanged not firing get I have a class which has an ObservableCollection called Items. That list should fill up a RadGridView. Even though the OC contains data, the list stays empty, and after a bit of debuggingg I noticed it has some odd behavior. I have a breakpoint in the Get and Set of the property. First it hits the Get. Then the Set, but it never hits the Get again. Shouldn't the NotifyChanged also trigger the get after that then, so it updates the list in the view? Here is the code below of the class I am talking about: public class PagedCollection<TEntity> where TEntity : class, INotifyPropertyChanged { internal WorkflowEntities Context; internal DbSet<TEntity> DbSet; private ObservableCollection<TEntity> _items; public ObservableCollection<TEntity> Items { get { return _items; } set { SetField(ref _items, value, nameof(Items)); } } public PagedCollection() { Context = new WorkflowEntities(); DbSet = Context.Set<TEntity>(); } public virtual IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IQueryable<TEntity>> query = null, string includeProperties = "") { IQueryable<TEntity> value = DbSet; if (filter != null) { value = value.Where(filter); } value = includeProperties.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Aggregate(value, (current, includeProperty) => current.Include(includeProperty)); return query?.Invoke(value).ToList() != null ? query(value).ToList() : value.ToList(); } // boiler-plate public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetField<T>(ref T field, T value, string propertyName) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } } The public virtual IEnumerable<TEntity> Get(...) is being triggered by another class, which fills up the Items. Like this: PagedCollection.Items = PagedCollection.Get();. This in turn fires the get, set, but not a get anymore, so my list stays empty in the view, even though there is data in PagedCollection.Items A: Your class, PagedCollection, doesn't implement INotifyPropertyChanged. public class PagedCollection<TEntity> where TEntity : class, INotifyPropertyChanged What this says is that TEntity must be a class and implement INotifyPropertyChanged. Try this instead: public class PagedCollection<TEntity> : INotifyPropertyChanged where TEntity : class, INotifyPropertyChanged A: You can't call PagedCollection.Get(); like that you have to instantiate something. A: A change in a property of an object within a regular ObservableCollection does not trigger the CollectionChanged event. Maybe you could use the TrulyObservableCollection class, derived from the former: ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged) A: One thing is the ObservableCollection property itself. When you run the program, it is get once when the view is loaded, and it is set once when you first initialize that property. After that, when you populate the list, it's not the PropertyChanged event that is fired, since it would be fired only if you assign the whole OC property to another value (usually via Items = new ObservableCollection<TEntity>()); Thus, the event you should be watching is CollectionChanged, which is fired every time you add, remove, swap or replace elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/41855741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I color a graph (vertices and edges) with excel data? I'm have an excel file with mostly 0's and 1's and I want to use this information to color the vertices and edges of a graph. So like if a cell is 0, color the edge gray, but if the cell is 1, color it blue. And similarly for vertices. Can anyone give me a suggestion for how to go about this? What should I use to make the graph? And how do I tell it how to color it? THANKS! A: Try using D3 graph. Visit https://d3js.org/ D3 uses javascript language. You can refer to multiple graphs. Even you can take input data from excel file to create dynamic graphs. You can refer to D3 network graph to understand how to change colour of vertex and edges of graph from given data http://christophergandrud.github.io/d3Network/ A: If you have the x and y values you can plot them directly on a worksheet. The following is an example that randomly generates x and y coordinates for 5 points. A small filled circle is drawn at each point. A line is drawn between the previous and the next point forming a closed loop. To demonstrate how you can select the line colors I alternately color them gray and blue to give you an idea of how to selectively color them based on some other criteria. vbBlue is one of a preset color pallet (see this link) which is why it doesn't have to be declared - unlike vbGray. Option Explicit Sub drawALine(xFrm As Double, yFrm As Double, xTo As Double, yTo As Double, c As Long) With ActiveSheet.Shapes.AddLine(xFrm, yFrm, xTo, yTo).Line .DashStyle = msoLineDashDotDot .ForeColor.RGB = c End With End Sub Sub drawNode(r As Double, x As Double, y As Double, c As Long) With ActiveSheet.Shapes.AddShape(msoShapeOval, x - r / 2, y - r / 2, r, r) .Fill.ForeColor.RGB = c End With End Sub Sub ConnectedOverLappingLoop() Dim xMax As Double, yMax As Double, x1 As Double, y1 As Double Dim xFrm As Double, yFrm As Double, xTo As Double, yTo As Double Dim radius As Double Dim vbGray As Long, clr As Long xMax = 200 yMax = 200 radius = 5 vbGray = RGB(150, 150, 150) xFrm = Rnd() * xMax yFrm = Rnd() * yMax x1 = xFrm y1 = yFrm clr = vbBlue drawNode radius, x1, y1, vbBlue Dim i As Integer For i = 1 To 5: xTo = Rnd() * xMax yTo = Rnd() * yMax drawNode radius, xTo, yTo, vbBlue drawALine xFrm, yFrm, xTo, yTo, clr xFrm = xTo yFrm = yTo If clr = vbBlue Then clr = vbGray Else clr = vbBlue End If Next drawALine xFrm, yFrm, x1, y1, clr End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/43160006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP sanitization question I was wondering how would you sanitize the $_SERVER['REQUEST_URI'], $_POST['email'] and $url code in the code snippets below using PHP. I'm using PHP Version 5.2.14 Code Snippets. <form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>"> </form> $email = $_POST['email']; //Grabs the email address $page_url = $url; //Grabs the pages url address. A: Use filter_var functions. // url filter_var($url, FILTER_VALIDATE_URL) // email filter_var('me@example.com', FILTER_VALIDATE_EMAIL) A: Except in some very particular cases you should never 'sanitize' input - only ever validate it. (Except in the very particular cases) the only time you change the representation of data is where it leaves your PHP - and the method should be appropriate to where the data is going (e.g. htmlentities(), urlencode(), mysql_real_escape_string()....). (the filter functions referenced in other posts validate input - they don't change its representation)
{ "language": "en", "url": "https://stackoverflow.com/questions/4343825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does Nutch's plug-in system work? I am new to Nutch, but I know Nutch uses Lucene for indexing, which only understands text format. Nutch has many plug-ins that are used for crawling documents with a particular format. My doubt is: how does actually the Nutch plug-in system? I seen the Team wiki page for nutch I'd like some information like how actually Nutch works with Lucene. A: All Lucene does is provide a way for "Documents" to be added into a structured index and for queries to be executed against that index. The Nutch crawler (I assume that's what you mean by nutch) just provides an easy way to get unstructured data (ie a website) to get pushed into the index. Just like you can use Solr to easily push xml data into a lucene index. Nutch plugins simply provide a hook were you can put customer logic. For instance the "parse-pdf" can convert a binary PDF file into one of these "lucene Documents". Basically all it does is use an API that can read PDF documents (pdfbox) to extract the text (this is similar to what "parse-html" does since html has a lot of parts that isn't text, for example all html tags). So regarding your concern about binary formats, its not difficult to parse, just difficult to get something useful. For instance we can write a "parse-image" plugin that could extract a lot of info about the image (ie name, format, size), it's just that parsing the "face" or the "dog" in the picture is difficult.
{ "language": "en", "url": "https://stackoverflow.com/questions/1448329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert Raw png data to a usable img src in javascipt Getting raw png data from an api I am using, from the docs it is supposedly base64 png but it does not look like it to me. The data comes back in either of 2 forms PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00�%00%00%00�%08%06%00%00%00=�%062%00%00%00%09pHYs%00%00%0E�%00%00%0E�%01�+%0E%1B%00%00 %00IDATx%01%00��q~%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00 or like PNG IHDR��=�2 pHYs���+ IDATx��q~J@7J@7�ɭ� IDATJ@72.*D2.*D������'$ �2-($J@7����.)&j��������6 6��n����J@7����(%!R���M���H� ���$�������N�����>�0����J����M+(���������J@7����/*&���< ���"������ ����������� ��� ����"�D#!-����2- could someone help me identify what this is being returned, and how can I decode it to be used as a img src?
{ "language": "en", "url": "https://stackoverflow.com/questions/71025374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to delete file and its folder if there is one, in shell? I have a shell script that is copying some files for a S3 bucket (aws) on local, then it is copying it to another place (it cannot do it directly, because of some authorization), but the idea is that the image may be in some folder and the shell is creating it locally, but it is deleting just the image and I found that after execution I have some empty folders. So my question is how to delete the folder too, if it is present in the name? My shell part that copies and deletes: aws s3 cp s3://$SRC_BUCKET/$PHOTO_NAME $PHOTO_NAME --profile $SRC_PROFILE # copy to other place rm $PHOTO_NAME # here PHOTO_NAME may have the parent folder in it (a.jpg, # or b/a.jpg) and I would like to delete the b folder too I have updated my code, based on the answer below, but it seems not to do what expected: the temporary directory is created, but all is done outside of it... My code looks like this: dir="$(mktemp aws-sync-XXXXX)" pushd "$dir" COUNT=1 until [ $COUNT -gt $MAX_COUNT ]; do aws s3 cp s3://$SRC_BUCKET/$PHOTO_NAME $PHOTO_NAME --profile $SRC_PROFILE # copy to other place rm $PHOTO_NAME (( MESSAGES_COUNT+=1 )) fi done popd rm -rf "$dir" A: fundamentally, you're setting yourself up for some race conditions (what if the folder already existed, &c). A better way to do this is creating a fresh folder before you run this script, then run it inside there. So: dir="$(mktemp aws-sync-XXXXX)" pushd "$dir" # do stuff popd rm -rf "$dir" That will ensure you delete everything your temporary command created, and nothing more.
{ "language": "en", "url": "https://stackoverflow.com/questions/32780888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I authenticate using MSXML2.XMLHTTP and VBA? I need to authenticate on the endpoint https://graph.microsoft.com/v1.0/me/drive/root/children using MSXML2.XMLHTTP and VBA. I have the access token already but I am struggling to find out the string to be used on: setRequestHeader method. Thank you, A: After searching I found the solution: setRequestHeader "Authorization", "Bearer " + accessToken
{ "language": "en", "url": "https://stackoverflow.com/questions/55767687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rapid json, c++, json, modify empty json array I have a json file, which contains two object. The first object is an array of objects. Each of these objects has an element "key" and empty array. I need to fill the array with 4 numbers and I need to save back the json. I am checking the tutorial, but probably I am missing something. May somebody help me please? Here is my code, that doesn't work: void BimObjectsToProjection::modifyViewBoxForProjection(std::string projectionName, long long minX, long long minY, long long Xlen, long long Ylen) { Value& projections = md_FilesJsonDocument["ProjectionImages"]; for (Value::ValueIterator projectionsIterator = projections.Begin(); projectionsIterator != projections.End(); ++projectionsIterator) { rapidjson::Value& projectionJson = *projectionsIterator; string name = projectionJson["Name"].GetString(); if (projectionName == name) { Document::AllocatorType& allocator = md_FilesJsonDocument.GetAllocator(); rapidjson::Value& viewBox = (*projectionsIterator)["BB"]; viewBox.PushBack((int)minX, allocator); viewBox.PushBack((int)minY, allocator); viewBox.PushBack((int)Xlen, allocator); viewBox.PushBack((int)Ylen, allocator); rapidjson::StringBuffer strbuf; rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); md_FilesJsonDocument.Accept(writer); break; } } } The json looks like this: { "ProjectionImages": [ { "Id": "33c75d31-7ccd-4daf-814a-56250cdee42f", "Name": "Projection_Image_Architectural_First Floor_Zone 1.png", "Discipline": "Architectural", "LevelName": "First Floor", "BB": [], "SheetFileName": null, "ProjectionLineFileId": "36bb6683-c6d3-43c2-bbdc-aedf3203ea86", "ProjectionLineFileName": "Projection_Image_Architectural_First Floor_Zone 1.pdf", "ZoneName": "Zone 1" }, ... Even if I try to add new array member, this code doesn't work. Is it because of my writing approch? void BimObjectsToProjection::modifyViewBoxForProjection(std::string projectionName, long long minX, long long minY, long long Xlen, long long Ylen) { Value& projections = md_FilesJsonDocument["ProjectionImages"]; for (Value::ValueIterator projectionsIterator = projections.Begin(); projectionsIterator != projections.End(); ++projectionsIterator) { rapidjson::Value& projectionJson = *projectionsIterator; string name = projectionJson["Name"].GetString(); if (projectionName == name) { Document::AllocatorType& allocator = md_FilesJsonDocument.GetAllocator(); Value a(kArrayType); a.PushBack((int)minX, allocator); a.PushBack((int)minY, allocator); a.PushBack((int)Xlen, allocator); a.PushBack((int)Ylen, allocator); (*projectionsIterator).AddMember("AA", a, allocator); rapidjson::StringBuffer strbuf; rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); md_FilesJsonDocument.Accept(writer); break; } } } A: This part of the code doesn't do anything: rapidjson::StringBuffer strbuf; rapidjson::Writer<rapidjson::StringBuffer> writer(strbuf); md_FilesJsonDocument.Accept(writer); strbuf contains the json string but it is discarded. I would move this into a separate function and print the conents with std::cout << strbuf;. To write directly to a file: std::ofstream ofs("out.json", std::ios::out); if (ofs.is_open()) { rapidjson::OStreamWrapper osw(ofs); rapidjson::Writer<rapidjson::OStreamWrapper> writer(osw); md_FilesJsonDocument.Accept(writer); }
{ "language": "en", "url": "https://stackoverflow.com/questions/65024226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jpegoptim: error creating temp file: mkstemps() failed jpegoptim gives me this error: error creating temp file: mkstemps() failed jpegoptim -o *.jpg image1.jpg 2000x1333 24bit P JFIF [OK] 442829 --> 451511 bytes (-1.96%), skipped. image2.jpg 1500x1124 24bit P Exif XMP IPTC ICC JFIF [OK] 582748 --> 583528 bytes (-0.13%), skipped. image3.jpg 2000x1501 24bit P Exif XMP IPTC ICC JFIF [OK] 630262 --> 634146 bytes (-0.62%), skipped. image4.jpg 1620x846 24bit P JFIF [OK] 316664 --> 319702 bytes (-0.96%), skipped. image5.jpg 1280x855 24bit N Exif XMP Adobe [OK] 66306 --> 66279 bytes (0.04%), optimized. jpegoptim: error creating temp file: mkstemps() failed A: If you haven't figured out the issue yet, it's likely that you don't have write permissions to the directory the image is in.
{ "language": "en", "url": "https://stackoverflow.com/questions/42972084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: speeding up (rewriting?) a not in sub select query From a table I'm trying to get a) users who fulfil certain criteria which is held in a key/value combination in a table OR b) users who do not have that key/value combination at all So, for example, to try and find users who live in France or who have not yet added their location, I'm using this (simplified) query: SELECT * FROM current_users JOIN current_users um_location ON current_users.id = um_location.id WHERE ( ( um_location.meta_key = 'location' AND um_location.meta_value = 'France' ) OR ( current_users.id NOT IN (SELECT current_users.id FROM current_users WHERE current_users.meta_key = 'location' ) ) ) The problem is, of course, that running the OR sub-select query (if that's what it's called) is slowing down the query hugely. And since the full query has about 5 or 6 of these sub-selects, it's slowing things down far too much. Is there another way of doing this perhaps? A faster way? A: Change your OR condition as a UNION query instead of OR SELECT * FROM current_users JOIN current_users um_location ON current_users.id = um_location.id WHERE um_location.meta_key = 'location' AND um_location.meta_value = 'France' UNION SELECT * FROM current_users JOIN current_users um_location ON current_users.id = um_location.id WHERE current_users.id NOT IN (SELECT current_users.id FROM current_users WHERE current_users.meta_key='location' ) A: This should be the most succinct possible: SELECT * FROM current_users LEFT JOIN current_users AS um_location ON current_users.id = um_location.id AND um_location.meta_key = 'location' WHERE um_location.meta_value = 'France' OR um_location.meta_value IS NULL ; ...but as isaace answer hints, MySQL does not handle OR conditions ideally. So, this might perform better. SELECT * FROM current_users LEFT JOIN current_users AS um_location ON current_users.id = um_location.id AND um_location.meta_key = 'location' WHERE um_location.meta_value = 'France' UNION SELECT * FROM current_users LEFT JOIN current_users AS um_location ON current_users.id = um_location.id AND um_location.meta_key = 'location' WHERE um_location.meta_value IS NULL ; ..but it will probably only make a difference if you have meta_value indexed; as the issue is that MySQL tends to ignore indexes when presented with OR. Edit: Due to the type of schema design begin used, there might be some weird issues with these queries using "location" entries as rows on the left side of the join; try this instead. SELECT * FROM current_users AS non_location LEFT JOIN current_users AS um_location ON current_users.id = um_location.id AND um_location.meta_key = 'location' WHERE non_location.meta_key != 'location' AND (um_location.meta_value = 'France' OR um_location.meta_value IS NULL ) ; A: First off, thank you both for your suggestions. Unfortunately I couldn't get them to work as the join LEFT JOIN current_users AS um_location ON current_users.id = um_location.id AND um_location.meta_key = 'location' did not return the records of those users who hadn't yet entered their location. However, after a lot of work I managed to solve the issue. It's not elegant but it works: * *Create a temporary table with a subset of the users who fulfil some basic criteria. *Do a simple INSERT IGNORE INTO ... SELECT DISTINCT ... FROM current_users adding in the missing 'location' with dummy information. Then the final query includes this: um_location.meta_value = 'France' or um_location.meta_value = 'dummyinfo' It's not blisteringly fast but since this is a process which acts in the back end for admin users only they can afford to wait... ;) Again, thanks for your help!
{ "language": "en", "url": "https://stackoverflow.com/questions/46060494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to generate a QR code and a downloadable link in php I would like to create a program that generates a QR code based on a URL (data from a database). The QR code will not be stored or saved, but only downloadable via a link on the page displaying the QR code. All in PHP :) Could someone help me ? I haven't found my answer for the downloadable link :) A: This works for me in creating the QR code use API:- https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl={data} In place of data use the data which you want to convert into a QR code. Code:- <div id="data_id"> <div class="col"> <?php echo '<img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl={data}">'; ?> </div> </div> <button id="downloadid" class="btn btn-small btn-primary">Download</button> Script For the Downloading the QR code image:- <script> var d = document.getElementById("downloadid"); d.addEventListener("click", function(e) { var div = document.getElementById("data_id"); var opt = { margin: [20, 20, 20, 20], filename: `filname.pdf`, image: { type: 'jpg', quality: 0.98 }, html2canvas: { scale: 2, useCORS: true }, jsPDF: { unit: 'mm', format: 'letter', orientation: 'portrait' } }; html2pdf().from(div).set(opt).save(); }); </script>`enter code here`
{ "language": "en", "url": "https://stackoverflow.com/questions/67456506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create a circuit based on this truth table? So this is the truth table In_1 In_2 In_3 Out 0 0 0 0 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 0 I would like to create a circuit based on this truth table. This is what I have tried, but failed A: A Karnaugh map as suggested by paddy, will give you a set of minterms which fulfil the expression. That is the classical way to tackle such problems. By inspection of the truth-table you can convince yourself, that the output is true whenever In_1 is unequal In_3 or In_1 is unequal In_2: f = (In_1 xor In_2) or (In_1 xor In_3)
{ "language": "en", "url": "https://stackoverflow.com/questions/74844748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Woocommerce - Remove Only one Unit of a product from cart I am working on this woocommerce search function that uses AJAX to fetch products on every keystroke and that gives the possibility to add or remove units of a certain product to cart right from the instant search results modal. In each search result there is this group of two buttons that allow the client to add 1 or remove 1 product from cart at a time. I managed to make the add to cart button work but can't seem to find a good solution to remove just one single unit from cart instead of all of them at once. I have tried this: function remove_product_from_cart_programmatically() {    if ( is_admin() ) return;    $product_id = 282;    $product_cart_id = WC()->cart->generate_cart_id( $product_id );    $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );    if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key ); } but it removes all products with that ID at once. I want to be able to remove unit by unit in case there are items in cart with that ID. This is the code I have right now for the remove from cart button: add_action('wp_ajax_search_remove_from_cart', 'search_remove_from_cart'); add_action('wp_ajax_nopriv_search_remove_from_cart', 'search_remove_from_cart'); // handle the ajax request function search_remove_from_cart() { $product_id = $_REQUEST['product_id']; WC()->cart->remove_cart_item($product_id); $products_in_cart = WC()->cart->get_cart_item_quantities($product_id); $updated_qty = $products_in_cart[$product_id]; // in the end, returns success json data wp_send_json_success(["Product removed from cart Successfuly!", $updated_qty]); // or, on error, return error json data wp_send_json_error(["Could not remove the product from cart"]); } Is there any function to remove only one unit of a certain product from cart? Thank you all ! A: You have to change the quantity instead of removing the product. Number of product units in the cart = quantity. Try something like this: function remove_from_cart(){ $product_id = 47; $cart = WC()->cart; $product_cart_id = $cart->generate_cart_id( $product_id ); $cart_item_key = $cart->find_product_in_cart( $product_cart_id ); if ( $cart_item_key ){ $quantity = $cart->get_cart_item($cart_item_key)['quantity'] - 1; $cart->set_quantity($cart_item_key, $quantity); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/74874720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing a C++ calling convention in ASM x86 I've written a simple program that obfuscates a string using ASM x86. User must input their desired string, and then choose a key (Ekey) for the string to be obfuscated. (I know you can emulate left and right bit rotations with shift operators or table lookups, I'm just trying to familiarize myself with ASM) I'm trying to alter the program so that it adopts an accepted C++ standard calling procedure such as Cdecl for passing parameters (EKey & tempChar) into the sub-routine obfuscate. Despite numerous hours of research I've been unsuccessful so I have come here in hope that somebody with a little more experience would be kind enough to offer some guidance. Here's the relevant function: void obfusc_chars (int length, char EKey) { char tempChar; // char temporary store for (int i = 0; i < length; i++) // encrypt characters one at a time { tempChar = OChars [i]; // __asm { // push eax // save register values on stack to be safe push ecx // pushes first string on stack // movzx ecx,tempChar // set up registers (Nb this isn't StdCall or Cdecl) lea eax,EKey // call obfuscate // obfuscate the character mov tempChar,al // // pop ecx // restore original register values from stack pop eax // } EChars [i] = tempChar; // Store encrypted char in the encrypted chars array } return; And the obfuscate subroutine: // Inputs: register EAX = 32-bit address of Ekey, // ECX = the character to be encrypted (in the low 8-bit field, CL). // Output: register EAX = the encrypted value of the source character (in the low 8-bit field, AL). __asm { obfuscate: push esi push ecx mov esi, eax and dword ptr [esi], 0xFF ror byte ptr [esi], 1 ror byte ptr [esi], 1 add byte ptr [esi], 0x01 mov ecx, [esi] pop edx x17:ror dl, 1 dec ecx jnz x17 mov eax, edx add eax, 0x20 xor eax, 0xAA pop esi ret } Thanks in advance for taking the time to read.
{ "language": "en", "url": "https://stackoverflow.com/questions/29729208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: not getting radiobutton 'value' from other function(def) in tkinter, how to achieve this without using class? Not getting radiobutton 'value' from other function(def) in tkinter, how to achieve this without using class? In this case a=a1.get() is not taking value from command (of sub1 button) in ques1() function. from tkinter import * global root root=Tk() root.geometry("500x500") a1=StringVar() ans1=StringVar() def ans1(): a=a1.get() #not getting it from ques1() print(a) def ques1(): root.destroy() global window1 window1=Tk() window1.geometry("500x500") question1=Label(window1, text="How many Planets are there in Solar System").grid() q1r1=Radiobutton(window1, text='op 1', variable=a1, value="correct").grid() q1r2=Radiobutton(window1, text='op 2', variable=a1, value="incorrect").grid() sub1=Button(window1, text="Submit", command=ans1).grid() next1But=Button(window1, text="Next Question", command=ques2).grid() def ques2(): window1.destroy() window2=Tk() window2.geometry("500x500") question2=Label(window2, text="How many Planets are there in Solar System").grid() next2But=Button(window2, text="Next Question") button=Button(root,text="Start Test", command=ques1).grid() A: This is a side effect from using Tk more than once in a program. Basically, "a1" is tied to the "root" window, and when you destroy "root", "a1" will no longer work. You have a couple options: * *Keep the same window open all the time, and swap out the Frames instead. *Use Toplevel() to make new windows instead of Tk. Option 1 seems the best for you. Here it is: from tkinter import * root=Tk() root.geometry("500x500") a1=StringVar(value='hippidy') ans1=StringVar() def ans1(): a=a1.get() #not getting it from ques1() print(repr(a)) def ques1(): global frame frame.destroy() # destroy old frame frame = Frame(root) # make a new frame frame.pack() question1=Label(frame, text="How many Planets are there in Solar System").grid() q1r1=Radiobutton(frame, text='op 1', variable=a1, value="correct").grid() q1r2=Radiobutton(frame, text='op 2', variable=a1, value="incorrect").grid() sub1=Button(frame, text="Submit", command=ans1).grid() next1But=Button(frame, text="Next Question", command=ques2).grid() def ques2(): global frame frame.destroy() # destroy old frame frame = Frame(root) # make a new frame frame.pack() question2=Label(frame, text="How many Planets are there in Solar System").grid() next2But=Button(frame, text="Next Question") frame = Frame(root) # make a new frame frame.pack() button=Button(frame,text="Start Test", command=ques1).grid() root.mainloop() Also, don't be scared of classes. They are great. Also, the way you have a widget initialization and layout on the same line is known to cause bugs. Use 2 lines always. So instead of this button=Button(frame,text="Start Test", command=ques1).grid() Use this: button=Button(frame,text="Start Test", command=ques1) button.grid() A: You need to use a single instance of Tk. Variables and widgets created in one cannot be accessed from another. A: Your code has some common mistakes. You are creating a new window on each question. It is not a good idea. You can use Toplevel but I will suggest you to use the root. You can destroy all of your previous widgets and place new ones. When the first question, both radiobuttons are unchecked and return 0 when none is selected. You are creating the buttons in Window1 so you will have to tie it with your var. from tkinter import * global root root=Tk() root.geometry("500x500") a1=StringVar(root) a1.set(0) #unchecking all radiobuttons ans1=StringVar() def ans1(): a=a1.get() print(a) def ques1(): for widget in root.winfo_children(): widget.destroy() #destroying all widgets question1=Label(root, text="How many Planets are there in Solar System").grid() q1r1=Radiobutton(root, text='op 1', variable=a1, value="correct").grid() q1r2=Radiobutton(root, text='op 2', variable=a1, value="incorrect").grid() sub1=Button(root, text="Submit", command=ans1).grid() next1But=Button(root, text="Next Question", command=ques2).grid() def ques2(): for widget in root.winfo_children(): widget.destroy() question2=Label(root, text="How many Planets are there in Solar System").grid() next2But=Button(root, text="Next Question") button=Button(root,text="Start Test", command=ques1) button.grid()
{ "language": "en", "url": "https://stackoverflow.com/questions/49904137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nhibernate entity with multiple Many-To-Many lists of the same type? Does anybody know how I would map an entity with two many-to-many collections of the same child type. My database structure is this.... The "normal" relationship will be.... tbl_Parent col_Parent_ID tbl_Parent_Child_Xref col_Parent_ID col_Child_ID tbl_Child col_Child_ID The alternative relationship is... tbl_Parent col_Parent_ID tbl_Include_ParentChild_Xref col_Parent_ID col_Child_ID tbl_Child col_Child_ID The entity and mapping look like this... public partial class ParentEntity : AuditableDataEntity<ParentEntity> { public virtual IList<ChildEntity> Children { get; set; } public virtual IList<ChildEntity> IncludedChildren { get; set; } } public partial class ParentMap : IAutoMappingOverride<ParentEntity> { public void Override(AutoMapping<ParentEntity> mapping) { mapping.Table("tbl_Parent"); mapping.HasManyToMany(x => x.Children) .Table("tbl_Parent_Child_Xref") .ParentKeyColumn("col_Parent_ID") .ChildKeyColumn("col_Child_ID") .Inverse() .Cascade.All(); mapping.HasManyToMany(x => x.IncludedChildren) .Table("tbl_Include_ParentChild_Xref") .ParentKeyColumn("col_Parent_ID") .ChildKeyColumn("col_Child_ID") .Inverse() .Cascade.All(); } } The error that I'm getting is "System.NotSupportedException: Can't figure out what the other side of the many-to-many property 'Children' should be." I'm using NHibernate 2.1.2, FluentNhibernate 1.0. A: It seems FNH is confused because you seem to map the same object (ChildEntity) to two different tables, if I'm not mistaken. If you don't really need the two lists to get separated, perhaps using a discriminating value for each of your lists would solve the problem. Your first ChildEntity list would bind to the discriminationg value A, and you sesond to the discriminating value B, for instance. Otherwise, I would perhaps opt for a derived class of your ChildEntity, just not to have the same name of ChildEntity. IList<ChildEntity> ChildEntities IList<IncludedChildEntity> IncludedChildEntities And both your objects classes would be identitical. If you say it works with NH, then it might be a bug as already stated. However, you may mix both XML mappings and AutoMapping with FNH. So, if it does work in NH, this would perhaps be my preference. But think this workaround should do it. A: You know I'm just shooting in the dark here, but it almost sounds like your ChildEntity class isn't known by Hibernate .. that's typically where I've seen that sort of message. Hibernate inspects your class and sees this referenced class (ChildEntity in this case) that id doesn't know about. Maybe you've moved on and found the issue at this point, but thought I'd see anyway. A: Fluent is confused because you are referencing the same parent column twice. That is a no-no. And as far as I can tell from the activity i have seen, a fix is not coming any time soon. You would have to write some custom extensions to get that working, if it is possible. A: To my great pity, NHibernate cannot do that. Consider using another ORM.
{ "language": "en", "url": "https://stackoverflow.com/questions/1915947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Wrap input with submit tag in one div Let's say I have these fields generated by simple_form_for: = f.input :amount, label: false, required: true = f.submit "✓", class: "btn btn-primary" I want to wrap them in one div and none of them should be nested inside any other div. (it should look like this): <form> <div class="inputFields"> <input name="amount"> <!-- f.input --> <input name="commit"> <!-- f.submit --> </div> </form> now it looks like this: <form> <div class="fieldcontainer"> <input name="amount"> <!-- f.input --> </div> <input name="commit"> <!-- f.submit --> </form> How to achieve this? A: According to the Simple Form documentation, you can skip use of the wrapper html tags by using input_field instead of input. So, if this is just a one-off case then you could define your own wrapper div tag and turn off the auto-generated wrapper: .inputFields = f.input_field :amount, label: false, required: true = f.submit "✓", class: "btn btn-primary" Or, if this is not a one-off case and is a common thing, you could create your own wrapper... See the custom wrapper documentation for help.
{ "language": "en", "url": "https://stackoverflow.com/questions/25247120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cordova websocket plugin showing error code 1006 and angular websocket plugin showing isTrusted true error Angular websocket plugin is working in the browser. But after generating apk in the mobile it is not working, it is showing error. Cordova websocket plugin also not working, it is showing error code 1006. Can any one help me. I am new to ionic. document.addEventListener('deviceready', function () { var ws = new WebSocket('ws://197.164.1.12:8080/example/2'); ws.onopen = function () { alert('open'); this.send('hello'); }; ws.onmessage = function (event) { alert(event.data); this.close(); }; ws.onerror = function (event) { alert('error occurred!'+JSON.stringify(event)); }; ws.onclose = function (event) { alert('onclose code=' + event.code); }; ws.close = function (event) { alert('close code=' + JSON.stringify(event)); alert('onclose code=' + event.code); }; }, false); A: Your browser is not allow CORS Origin api access. So you can add the plugin CORS Plugin for chrome
{ "language": "en", "url": "https://stackoverflow.com/questions/41181539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP / JpGraph - Memory not freed on completion of function My application needs to generate a pdf file with a bunch of graphs in it. The situation: I'm using FPDF for pdf generation and JpGraph for the graphs. My code gets the graph data from a database and iterates through, calling a function for each graph that contains all the JpGraph code for setting up, styling the graph and caching it as a png file in a cache folder on the server. FPDF then places these images in the pdf, which is served to browser. The problem: I'm getting PHP out of memory errors when the number of graphs exceeds a certain number. AFAICT this is not an FPDF problem: in trying to diagnose the problem I have generated much larger documents with many more (pre-generated) graphs and images of equivalent size. The problem seems to be that the memory used to render the graph in the graph rendering function is not freed when the function is completed. This is based on the fact that if I call memory_get_peak_usage in the function I get a bunch of increasing numbers, one from each time the function is called, up to the limit of 64MB where it stops. My graph generation script looks something like this: function barChart($filename, $ydata, $xdata){ // Create the graph. These two calls are always required $graph = new Graph(900,500); $graph->SetScale('textlin'); //(bunch of styling stuff) // Create the bar plot $bplot=new BarPlot($ydata); // Add the plot to the graph $graph->Add($bplot); //(more styling stuff) // Display the graph $graph->Stroke($filename); $graph = null; $bplot = null; unset($graph); unset($bplot); echo "<br><br>".(memory_get_peak_usage(true)/1048576)."<br><br>"; } As you can see, I've tried unsetting and nullifying the graph and bplot objects, although my understanding is that this shouldn't be necessary. Shouldn't all the memory used by the Graph and Bplot instances be freed up when the function finishes? Or is this perhaps a JpGraph memory leak? (I've searched high and low and can't find anyone else complaining about this). This is my first remotely resource-heavy PHP project, so I could be missing something obvious. A: I had the same problem and found the solution after just an hour or so. The issue is that jpgraph loads a default set of font files each time a Graph is created. I couldn't find a way to unload a font, so I made a slight change so that it only loads the fonts one time. To make the fix for your installation, edit "gd_image.inc.php" as follows: Add the following somewhere near the beginning of the file (just before the CLASS Image): // load fonts only once, and define a constant for them define("GD_FF_FONT0", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT0.gdf")); define("GD_FF_FONT1", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1.gdf")); define("GD_FF_FONT2", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2.gdf")); define("GD_FF_FONT1_BOLD", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1-Bold.gdf")); define("GD_FF_FONT2_BOLD", imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2-Bold.gdf")); then at the end of the Image class constructor (lines 91-95), replace this: $this->ff_font0 = imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT0.gdf"); $this->ff_font1 = imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1.gdf"); $this->ff_font2 = imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2.gdf"); $this->ff_font1_bold = imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1-Bold.gdf"); $this->ff_font2_bold = imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2-Bold.gdf"); with this: $this->ff_font0 = GD_FF_FONT0; $this->ff_font1 = GD_FF_FONT1; $this->ff_font2 = GD_FF_FONT2; $this->ff_font1_bold = GD_FF_FONT1_BOLD; $this->ff_font2_bold = GD_FF_FONT2_BOLD; I didn't test this with multiple versions of php or jpgraph, but it should work fine. ymmv. A: You could try using PHP >= 5.3 Garbage collection gc_enable() + gc_collect_cycles() http://php.net/manual/en/features.gc.php A: @bobD's answer is right on the money and helped solved my same question. However there is also one other potential memory leak source for those still looking for an answer to this very old problem. If you are creating multiple charts with the same background image, each load of the background image causes an increase in memory with each chart creation. Similar to bobD's answer to the font loading issue, this can be solved by making the background image(s) global variables instead of loading them each time. EDIT: It looks like there is a very small memory leak when using MGraph() as well. Specifically the function Add(). Perhaps it also loads a font library or something similar with each recursive call.
{ "language": "en", "url": "https://stackoverflow.com/questions/13253185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In bash/sed, how do you match on a lowercase letter followed by the SAME letter in uppercase? I want to delete all instances of "aA", "bB" ... "zZ" from an input string. e.g. echo "foObar" | sed -Ee 's/([a-z])\U\1//' should output "fbar" But the \U syntax works in the latter half (replacement part) of the sed expression - it fails to resolve in the matching clause. I'm having difficulty converting the matched character to upper case to reuse in the matching clause. If anyone could suggest a working regex which can be used in sed (or awk) that would be great. Scripting solutions in pure shell are ok too (I'm trying to think of solving the problem this way). Working PCRE (Perl-compatible regular expressions) are ok too but I have no idea how they work so it might be nice if you could provide an explanation to go with your answer. Unfortunately, I don't have perl or python installed on the machine that I am working with. A: You may use the following perl solution: echo "foObar" | perl -pe 's/([a-z])(?!\1)(?i:\1)//g' See the online demo. Details * *([a-z]) - Group 1: a lowercase ASCII letter *(?!\1) - a negative lookahead that fails the match if the next char is the same as captured with Group 1 *(?i:\1) - the same char as captured with Group 1 but in the different case (due to the lookahead before it). The -e option allows you to define Perl code to be executed by the compiler and the -p option always prints the contents of $_ each time around the loop. See more here. A: This might work for you (GNU sed): sed -r 's/aA|bB|cC|dD|eE|fF|gG|hH|iI|jJ|kK|lL|mM|nN|oO|pP|qQ|rR|sS|tT|uU|vV|wW|xX|yY|zZ//g' file A programmatic solution: sed 's/[[:lower:]][[:upper:]]/\n&/g;s/\n\(.\)\1//ig;s/\n//g' file This marks all pairs of lower-case characters followed by an upper-case character with a preceding newline. Then remove altogether such marker and pairs that match by a back reference irrespective of case. Any other newlines are removed thus leaving pairs untouched that are not the same. A: Here is a verbose awk solution as OP doesn't have perl or python available: echo "foObar" | awk -v ORS= -v FS='' '{ for (i=2; i<=NF; i++) { if ($(i-1) == tolower($i) && $i ~ /[A-Z]/ && $(i-1) ~ /[a-z]/) { i++ continue } print $(i-1) } print $(i-1) }' fbar A: Note: This solution is (unsurprisingly) slow, based on OP's feedback: "Unfortunately, due to the multiple passes - it makes it rather slow. " If there is a character sequence¹ that you know won't ever appear in the input,you could use a 3-stage replacement to accomplish this with sed: echo 'foObar foobAr' | sed -E -e 's/([a-z])([A-Z])/KEYWORD\1\l\2/g' -e 's/KEYWORD(.)\1//g' -e 's/KEYWORD(.)(.)/\1\u\2/g' gives you: fbar foobAr Replacement stages explained: * *Look for lowercase letters followed by ANY uppercase letter and replace them with both letters as lowercase with the KEYWORD in front of them foObar foobAr -> fKEYWORDoobar fooKEYWORDbar *Remove KEYWORD followed by two identical characters (both are lowercase now, so the back-reference works) fKEYWORDoobar fooKEYWORDbar -> fbar fooKEYWORDbar *Strip remaining² KEYWORD from the output and convert the second character after it back to it's original, uppercase version fbar fooKEYWORDbar -> fbar foobAr ¹ In this example I used KEYWORD for demonstration purposes. A single character or at least shorter character sequence would be better/faster. Just make sure to pick something that cannot possibly ever be in the input. ² The remaining occurances are those where the lowercase-versions of the letters were not identical, so we have to revert them back to their original state A: There's an easy lex for this, %option main 8bit #include <ctype.h> %% [[:lower:]][[:upper:]] if ( toupper(yytext[0]) != yytext[1] ) ECHO; (that's a tab before the #include, markdown loses those). Just put that in e.g. that.l and then make that. Easy-peasy lex's are a nice addition to your toolkit.
{ "language": "en", "url": "https://stackoverflow.com/questions/53729122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: EPPlus next row I am using Epplus to write out a collection into an excel file. Currently I am incrementing rows by manually manipulating the cell number.(ws is an instance of ExcelWorkSheet) int i = 1; foreach (var item in items) { ws.Cells["A"+i.ToString()].Value =item.Text; i++; } Instead of adding number to cell name is there a better way to handle this? Something like int i = 1; foreach (var item in items) { ws.Row[i].Cells[0]=item.Text; i++; } A: There's an [int Row, int Col] indexer on Cells (type ExcelRange), so you can use ws.Cells[i, 0]. int i = 1; foreach (var item in items) { ws.Cells[i, 0].Value =item.Text; i++; }
{ "language": "en", "url": "https://stackoverflow.com/questions/18744135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine current status of web video (playing | stopped) How can I determine when a user starts or stops playing a video on a web page? For instance, the video on this page: http://www.novamov.com/video/exm71hcwt1aly I need to be able to determine this from a separate .NET application running on the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/11038894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create HTML in angular? I have been working on React for a year. Now, I am writing angular. How can I create a piece of html code in ts.file? In react, I do it that way: const example = (item: string): React.ReactNode => { return <p> something.... {item} </p> } I want to do same thing in Angular8+ I know some way to do it. For example: const example2= (name: string): string => { return ` <div> <p>heyyy ${name}</p> </div> `; }; Are there any other ways to do it? A: In Angular, there are a couple of ways to do this. If you need to generate HTML in the typescript and then interpolate it into the template, you can use a combination of the DomSanitizer and the innerHTML attribute into other elements (for example a span). Below would be an example of what I suggested above: hello-world.component.ts: @Component({ selector: "hello-world", templateUrl: "./hello-world.component.html", styleUrls: ["./hello-world.component.scss"] }) export class HelloWorld { innerHTML: string = `<p>Hello, world!</p>`; } sanitze.pipe.ts: @Pipe({ name='sanitize' }) export class SanitizePipe { constructor(private sanitizer: DomSanitizer) { } transform(value: string): SafeHtml { return this.sanitizer.bypassSecurityTrustHtml(value); } } hello-world.component.html: <div [innerHTML]="innerHTML | sanitize"</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/68712302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javassist - How to add line number to method I am a newbie to java bytecode and javassist. I created a new class file with using javassist. Although I added fields and methods, I couldn't achieve to add line number to method. Result of my research, I understand that I need to add linenumberattribute to codeattribute of method info. Moreover, linenumberattribute consists of linenumbertable. I don't know how can I create a new linenumberattribute with javassist. A: I am writing a compiler that produces JVM code. I need line numbers in the output. I do it this way. I build up a list of objects similar to this: public class MyLineNum { public final short pc; public final short lineNum; } Then I add the line number table: final ClassFile classFile = ...; final ConstPool constPool = classFile.getConstPool(); final MethodInfo minfo = new MethodInfo( ... ); final Bytecode code = new Bytecode( constPool ); ... code that writes to 'code' final List<MyLineNum> lineNums = new ArrayList<>(); ... code that adds to 'lineNums' final CodeAttribute codeAttr = code.toCodeAttribute(); if ( !lineNums.isEmpty() ) { // JVM spec describes method line number table thus: // u2 line_number_table_length; // { u2 start_pc; // u2 line_number; // } line_number_table[ line_number_table_length ]; final int numLineNums = lineNums.size(); final byte[] lineNumTbl = new byte[ ( numLineNums * 4 ) + 2 ]; // Write line_number_table_length. int byteIx = 0; ByteArray.write16bit( numLineNums, lineNumTbl, byteIx ); byteIx += 2; // Write the individual line number entries. for ( final MyLineNum ln : lineNums) { // start_pc ByteArray.write16bit( ln.pc, lineNumTbl, byteIx ); byteIx += 2; // line_number ByteArray.write16bit( ln.lineNum, lineNumTbl, byteIx ); byteIx += 2; } // Add the line number table to the CodeAttribute. @SuppressWarnings("unchecked") final List<AttributeInfo> codeAttrAttrs = codeAttr.getAttributes(); codeAttrAttrs.removeIf( ( ai ) -> ai.getName().equals( "LineNumberTable" ) ); // remove if already present codeAttrAttrs.add( new AttributeInfo( constPool, "LineNumberTable", lineNumTbl ) ); } // Attach the CodeAttribute to the MethodInfo. minfo.setCodeAttribute( codeAttr ); // Attach the MethodInfo to the ClassFile. try { classFile.addMethod( minfo ); } catch ( final DuplicateMemberException ex ) { throw new AssertionError( "Caught " + ex, ex ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/21164289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is a function return necessary to be called a Closure Hey i came across this video on youtube http://www.youtube.com/watch?v=KRm-h6vcpxs which basically explains IIFEs and closures. But what I am not understanding is whether i need to return a function in order to call it a closure. E.x. function a() { var i = 10; function b() { alert(i); } } in this case can i call it a closure as it is accessing the 'i' variable from the outer function's scope or do i need to return the function like this return function b(){alert(i);} A: A closure is simply a function which holds its lexical environment and doesn't let it go until it itself dies. Think of a closure as Uncle Scrooge: Uncle Scrooge is a miser. He will never let go of his money. Similarly a closure is also a miser. It will not let go of its variables until it dies itself. For example: function getCounter() { var count = 0; return function counter() { return ++count; }; } var counter = getCounter(); See that function counter? The one returned by the getCounter function? That function is a miser. It will not let go of the count variable even though the count variable belongs to the getCounter function call and that function call has ended. Hence we call counter a closure. See every function call may create variables. For example a call to the getCounter function creates a variable count. Now this variable count usually dies when the getCounter function ends. However the counter function (which can access the count variable) doesn't allow it to die when the call to getCounter ends. This is because the counter function needs count. Hence it will only allow count to die after it dies itself. Now the really interesting thing to notice here is that counter is born inside the call to getCounter. Hence even counter should die when the call to getCounter ends - but it doesn't. It lives on even after the call to getCounter ends because it escapes the scope (lifetime) of getCounter. There are many ways in which counter can escape the scope of getCounter. The most common way is for getCounter to simply return counter. However there are many more ways. For example: var counter; function setCounter() { var count = 0; counter = function counter() { return ++count; }; } setCounter(); Here the sister function of getCounter (which is aptly called setCounter) assigns a new counter function to the global counter variable. Hence the inner counter function escapes the scope of setCounter to become a closure. Actually in JavaScript every function is a closure. However we don't realize this until we deal with functions which escape the scope of a parent function and keep some variable belonging to the parent function alive even after the call to the parent function ends. For more information read this answer: https://stackoverflow.com/a/12931785/783743 A: Returning the function changes nothing, what's important is creating it and calling it. That makes the closure, that is a link from the internal function to the scope where it was created (you can see it, in practice, as a pointer. It has the same effect of preventing the garbaging of the outer scope, for example). A: By definition of closure, the link from the function to its containing scope is enough. So basically creating the function makes it a closure, since that is where the link is created in JavaScript :-) Yet, for utilizing this feature we do call the function from a different scope than what it was defined in - that's what the term "use a closure" in practise refers to. This can both be a lower or a higher scope - and the function does not necessarily need to be returned from the function where it was defined in. Some examples: var x = null; function a() { var i = "from a"; function b() { alert(i); // reference to variable from a's scope } function c() { var i = "c"; // use from lower scope b(); // "from a" - not "c" } c(); // export by argument passing [0].forEach(b); // "from a"; // export by assigning to variable in higher scope x = b; // export by returning return b; } var y = a(); x(); // "from a" y(); // "from a" A: The actual closure is a container for variables, so that a function can use variables from the scope where it is created. Returning a function is one way of using it in a different scope from where it is created, but a more common use is when it's a callback from an asynchronous call. Any situation where a function uses variables from one scope, and the function is used in a different scope uses a closure. Example: var globalF; // a global variable function x() { // just to have a local scope var local; // a local variable in the scope var f = function(){ alert(local); // use the variable from the scope }; globalF = f; // copy a reference to the function to the global variable } x(); // create the function globalF(); // call the function (This is only a demonstration of a closure, having a function set a global variable which is then used is not a good way to write actual code.) A: a collection of explanations of closure below. to me, the one from "tiger book" satisfies me most...metaphoric ones also help a lot, but only after encounterred this one... * *closure: in set theory, a closure is a (smallest) set, on which some operations yields results also belongs to the set, so it's sort of "smallest closed society under certain operations". a) sicp: in abstract algebra, where a set of elements is said to be closed under an operation if applying the operation to elements in the set produces an element that is again an element of the set. The Lisp community also (unfortunately) uses the word "closure" to describe a totally unrelated concept: a closure is an implementation technique for representing procedures with free variables. b) wiki: a closure is a first class function which captures the lexical bindings of free variables in its defining environment. Once it has captured the lexical bindings the function becomes a closure because it "closes over" those variables.” c) tiger book: a data structure on heap (instead of on stack) that contains both function pointer (MC) and environment pointer (EP), representing a function variable; d) on lisp: a combination of a function and a set of variable bindings is called a closure; closures are functions with local state; e) google i/o video: similar to a instance of a class, in which the data (instance obj) encapsulates code (vtab), where in case of closure, the code (function variable) encapsulates data. f) the encapsulated data is private to the function variable, implying closure can be used for data hiding. g) closure in non-functional programming languages: callback with cookie in C is a similar construct, also the glib "closure": a glib closure is a data structure encapsulating similar things: a signal callback pointer, a cookie the private data, and a destructor of the closure (as there is no GC in C). h) tiger book: "higher-order function" and "nested function scope" together require a solution to the case that a dad function returns a kid function which refers to variables in the scope of its dad implying that even dad returns the variables in its scope cannot be "popup" from the stack...the solution is to allocate closures in heap. i) Greg Michaelson ($10.15): (in lisp implementation), closure is a way to identify the relationship betw free variables and lexical bound variables, when it's necessary (as often needed) to return a function value with free variables frozen to values from the defining scope. j) histroy and etymology: Peter J. Landin defined the term closure in 1964 as having an environment part and a control part as used by his SECD machine for evaluating expressions. Joel Moses credits Landin with introducing the term closure to refer to a lambda expression whose open bindings (free variables) have been closed by (or bound in) the lexical environment, resulting in a closed expression, or closure. This usage was subsequently adopted by Sussman and Steele when they defined Scheme in 1975, and became widespread.
{ "language": "en", "url": "https://stackoverflow.com/questions/16586950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: C# change the first 32bit Int of a GUID I have a GUID which I created with GUID.NewGUID(). Now I want to replace the first 32 bit of it with a specific 32-bit Integer while keeping the rest as they are. Is there a function to do this? A: You can use ToByteArray() function and then the Guid constructor. byte[] buffer = Guid.NewGuid().ToByteArray(); buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 0; Guid guid = new Guid(buffer); A: Since the Guid struct has a constructor that takes a byte array and can return its current bytes, it's actually quite easy: //Create a random, new guid Guid guid = Guid.NewGuid(); Console.WriteLine(guid); //The original bytes byte[] guidBytes = guid.ToByteArray(); //Your custom bytes byte[] first4Bytes = BitConverter.GetBytes((UInt32) 0815); //Overwrite the first 4 Bytes Array.Copy(first4Bytes, guidBytes, 4); //Create new guid based on current values Guid guid2 = new Guid(guidBytes); Console.WriteLine(guid2); Fiddle Keep in mind however, that the order of bytes returned from BitConverter depends on your processor architecture (BitConverter.IsLittleEndian) and that your Guid's entropy decreases by 232 if you use the same number every time (which, depending on your application might not be as bad as it sounds, since you have 2128 to begin with). A: The question is about replacing bits, but if someone wants to replace first characters of guid directly, this can be done by converting it to string, replacing characters in string and converting back. Note that replaced characters should be valid in hex, i.e. numbers 0 - 9 or letters a - f. var uniqueGuid = Guid.NewGuid(); var uniqueGuidStr = "1234" + uniqueGuid.ToString().Substring(4); var modifiedUniqueGuid = Guid.Parse(uniqueGuidStr);
{ "language": "en", "url": "https://stackoverflow.com/questions/42527016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: BeautifulSoup doesn't seem to parse anything I've been trying to learn BeautifulSoup by making myself a proxy scraper and I've encountered a problem. BeautifulSoup seems unable to find anything and when printing what it parses, It shows me this : <html> <head> </head> <body> <bound 0x7f977c9121d0="" <http.client.httpresponse="" at="" httpresponse.read="" method="" object="" of=""> &gt; </bound> </body> </html> I have tried changing the website I parsed and the parser itself (lxml, html.parser, html5lib) but nothing seems to change, no matter what I do I get the exact same result. Here's my code, can anyone explain what's wrong ? from bs4 import BeautifulSoup import urllib import html5lib class Websites: def __init__(self): self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"} def free_proxy_list(self): print("Connecting to free-proxy-list.net ...") url = "https://free-proxy-list.net" req = urllib.request.Request(url, None, self.header) content = urllib.request.urlopen(req).read soup = BeautifulSoup(str(content), "html5lib") print("Connected. Loading the page ...") print("Print page") print("") print(soup.prettify()) A: You are calling urllib.request.urlopen(req).read, correct syntax is: urllib.request.urlopen(req).read() also you are not closing the connection, fixed that for you. A better way to open connections is using the with urllib.request.urlopen(url) as req: syntax as this closes the connection for you. from bs4 import BeautifulSoup import urllib import html5lib class Websites: def __init__(self): self.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"} def free_proxy_list(self): print("Connecting to free-proxy-list.net ...") url = "https://free-proxy-list.net" req = urllib.request.Request(url, None, self.header) content = urllib.request.urlopen(req) html = content.read() soup = BeautifulSoup(str(html), "html5lib") print("Connected. Loading the page ...") print("Print page") print("") print(soup.prettify()) content.close() # Important to close the connection For more info see: https://docs.python.org/3.0/library/urllib.request.html#examples
{ "language": "en", "url": "https://stackoverflow.com/questions/47336456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to import a react component without using 'import' statement I'm new to React. Just trying out things. So far I have been using CDNs for React, React-DOM, and React-Bootstrap. I had no trouble using components of React-Bootstrap using the example code below: var Alert = ReactBootstrap.Alert; Now my problem is I want to use a component that is not provided by React-Bootstrap so I tried to look for components available in Github. I found a lot of the components that I am looking for but all of them are available for installation via npm which I am avoiding since I'm using React thru CDN. I know it is recommended to use npm or create-react app, but that's not how I started my application. So is there a way to import components like how I did in React-Bootstrap components? For example: var Select = React.Select; // import Select from 'react-select';
{ "language": "en", "url": "https://stackoverflow.com/questions/59854647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: Send Longitude and Latitude after 60 seconds to the localhost server(WAMP) I want to send the Longitude, Latitude, TimeStamp and the stonest wifi access point as JSON format to the server (WAMP- localhost) after every 60 seconds what is the best approach to do that? I would use AsyncTask but AsyncTasks should ideally be used for short operations (a few seconds at the most.) can someone give short example for sending this data with another approach than AsyncTask? A: start with these tutorials http://www.tutorialspoint.com/android/android_php_mysql.htm http://www.tutorialspoint.com/android/android_php_mysql.htm after that here is how to repeate every 60 seconds boolean run=true; Handler mHandler = new Handler();//sorry forgot to add this ... ... public void timer() { new Thread(new Runnable() { @Override public void run() { while (run) { try { Thread.sleep(60000);//60000 milliseconds which is 60 seconds mHandler.post(new Runnable() { @Override public void run() { //here you send data to server } }); } catch (Exception e) { } } } }).start();} call it like this to start it timer() and to stop it just do run=false;
{ "language": "en", "url": "https://stackoverflow.com/questions/29804032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "error_description": "Invalid Value" for token google sign in every time using flutter I am new in flutter trying to access auth token from google for my backend server but every time token is invalid. i am using FirebaseUser user await user.getIdToken() I give me a token but when I am trying to validate that token using my backend server as well as https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=mytoken and https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=mytoken this link it gives me "error_description": "Invalid Value". I am not sure await user.getIdToken() this method is right for getting token. Other think everything ok I am getting all user information except right token. please let me know if any other way. Below is my code: class LoginScreen extends StatefulWidget { @override _LoginScreenState createState() => new _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { final FirebaseAuth auth = FirebaseAuth.instance; final GoogleSignIn googleSignIn = new GoogleSignIn(); Future<http.Response> socailLogin(String authToken) async { var url = "http://api.ourdomain.com/user/social/login/google"; final response = await http.post(url, body: json.encode({"auth_token": authToken}), headers: {HttpHeaders.CONTENT_TYPE: "application/json"}); return response; } Future<FirebaseUser> googleSignin() async { final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn(); final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final FirebaseUser firebaseUser = await auth.signInWithGoogle( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken); return firebaseUser; } @override Widget build(BuildContext context) { final logo = Hero( tag: 'hero', child: CircleAvatar( backgroundColor: Colors.transparent, radius: 48.0, child: Image.asset('assets/logo.png'), ), ); final googleloginButton = Padding( padding: EdgeInsets.symmetric(vertical: 5.0), child: Material( borderRadius: BorderRadius.circular(30.0), // shadowColor: Colors.lightBlueAccent.shade100, // elevation: 5.0, child: MaterialButton( minWidth: 200.0, height: 42.0, onPressed: () async { FirebaseUser user = await googleSignin(); String idToken = await user.getIdToken(); if (idToken != null) { final http.Response response = await socailLogin(idToken); if (response.statusCode == 200) { var authToken = json.decode(response.body)['token']; if (authToken != null) { storedToken(authToken); } } else { print("Response status: " + response.statusCode.toString()); print("Response body: " + response.body); print("errror while request"); } } else { print("in else part not get token id from google"); } Navigator.push( context, MaterialPageRoute( builder: (context) => HomeScreen(), ), ); }, color: Colors.red, child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.bug_report, color: Colors.white, ), Text('Connect with Google', style: TextStyle(color: Colors.white)), ], ), ), ), ); return Scaffold( backgroundColor: Colors.white, appBar: new AppBar( centerTitle: true, title: new Text("Login"), ), body: Center( child: ListView( shrinkWrap: true, padding: EdgeInsets.only(left: 24.0, right: 24.0), children: <Widget>[ // logo, googleloginButton, facebookloginButton, ], ), ), ); } } Pleases help me. A: For backend server-side validation, you must use verifiable ID tokens to securely get the user IDs of signed-in users on the server side. ref. : https://developers.google.com/identity/sign-in/web/backend-auth Seems that the current flutter google sign in plugin does not support getting AuthCode for backend server-side OAuth validation. ref. : https://github.com/flutter/flutter/issues/16613 I think the firebaseUser.getIdToken() cannot be used for Google API. For https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=mytoken , you may need to pass the googleSignInAuthentication.idToken For https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=mytoken , you may need to pass the googleSignInAuthentication.accessToken Getting user information like user id and pass it to backend server-side is vulnerable to hackers. You should verify the idToken in backend server-side by Google API Client Libraries. A: I recently had a similar problem. this was my code: Future<void> googleLogin() async { final googleUser = await googleSignIn.signIn(); if (googleUser == null) { print('no google user??'); return; } _user = googleUser; final googleAuth = await googleUser.authentication; final credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken); try { await FirebaseAuth.instance.signInWithCredential(credential); } catch (e) { print('could not sign in with goodle creds, and heres why: \n $e'); } } I was not providing all the information in the credential variable. So all I had to do was to add the accessTokenId there. So replace the: final credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken); with: final credential = GoogleAuthProvider.credential( idToken: googleAuth.idToken, accessToken: googleAuth.accessToken); and when that got passed to FirebaseAuth.instance, it worked! How this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/51320271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using SmtpAppender to only send emails when logging an error or fatal I'm using log4net to log different types of messages. I have added the SmtpAppender to email specific user when logging messages. However, what I would like to achieve is to be able to only send emails if an error or fatal is logged. Accroding to my current configuration in the web.config file, I get two emails, one for the error and another one for the rest of the logs. Global.asax.cs: logger.Info("Info"); logger.Warn("Warning"); logger.Fatal("Fatal"); logger.Error("exception"); web.config: <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender"> <to value="bla@bla.com" /> <from value="bla@bla.com" /> <subject value="test logging message" /> <smtpHost value="*******" /> <bufferSize value="512" /> <lossy value="true" /> <evaluator type="log4net.Core.LevelEvaluator"> <threshold value="WARN"/> </evaluator> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%newline%date [%thread] %-5level %logger- %message%newline%newline%newline" /> </layout> </appender> A: I have found the solution, I should just add this tag to the SmtpAppender: <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="ERROR" /> <levelMax value="FATAL" /> </filter> A: Try using: <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender"> ... <threshold value="WARN"/> ... </appender> (or threshold value="ERROR" since you say you want to limit to Error and Fatallevels) rather than: <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender"> ... <evaluator type="log4net.Core.LevelEvaluator"> <threshold value="WARN"/> </evaluator> ... </appender> The log4net documentation or this message in the log4net user mailing list explains the difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/41564833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android make a dialog scrollable I'm showing a dialog when the user clicks a button. When the dialog appears and you click an EditText to enter some text, you can't see the bottom buttons (and the lowest EditText) anymore. So you have to click the keyboard down, then select the button or EditText. I searched for the answer for a while now, but i can't find it. So: How do i make my dialog scrollable? Apparently my code doesnt do the trick: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="16dp" android:paddingRight="16dp" android:orientation="vertical" android:scrollbars="vertical" android:scrollbarAlwaysDrawVerticalTrack="true"> <EditText android:id="@+id/addKlantNaam" android:textSize="20sp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/klantNaam" /> <EditText android:id="@+id/addKlantLocatie" android:textSize="20sp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/klantLocatie" /> <TextView android:id="@+id/scheidenDoorKomma" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="16sp" android:text="@string/scheidenDoorKomma"/> <EditText android:id="@+id/addFabrieken" android:textSize="20sp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/fabrieken" /> <EditText android:id="@+id/addMachines" android:textSize="20sp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/machines" /> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" > <Button android:id="@+id/dialogAnnuleren" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/annuleren" android:textSize="22sp" /> <Button android:id="@+id/dialogToevoegen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/dialogAnnuleren" android:textSize="22sp" android:text="@string/toevoegen"/> </RelativeLayout> </LinearLayout> This is how i call for the dialog: btnAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // custom dialog dialog = new Dialog(context); dialog.setContentView(R.layout.addklant_layout); dialog.setTitle("Klant toevoegen"); Button BTNannuleren = (Button) dialog.findViewById(R.id.dialogAnnuleren); // if button is clicked, close the custom dialog BTNannuleren.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); Button BTNtoevoegen = (Button) dialog.findViewById(R.id.dialogToevoegen); // if button is clicked, close the custom dialog BTNtoevoegen.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { StoreKlantInDatabase task = new StoreKlantInDatabase(); task.execute(urlInsertKlant); dialog.dismiss(); } }); dialog.show(); } }); anyone can help me out here? A: GeertG... now im emotionally involved :) try the link i found... it might do the trick as far as using a scrollview with more than a single child...I dont know if it solves your issue but... If ScrollView only supports one direct child, how am I supposed to make a whole layout scrollable? or how to add multiple child in horizontal scroll view in android Those solutions should work as creating a scrollview with more than 1 child... will it solve your problem? IDK... also look in to How to hide soft keyboard on android after clicking outside EditText? but having the keyboard closed and re-opened seems kinda reasonable to me... dont linger on it for too long:) A: The guidelines for what you are asking are can be found here. As you can see. there are a number of ways to achieve what you are asking. Further to this, you could consider changing default action of the 'Enter' button on the keyboard to select the next EditText and finally to submit the form when you are done (read up about it here): android:imeOptions="actionDone" A: Use LinearLayout Height match_parent. And try if its working or not. <LinearLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingRight="16dp" android:orientation="vertical" android:scrollbars="vertical" android:scrollbarAlwaysDrawVerticalTrack="true">
{ "language": "en", "url": "https://stackoverflow.com/questions/19109576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Hbase Pagination Filter returning more keys I am using Hbase pagination Filter to iterate over all the rows in table using following code Scan scan=new Scan(Bytes.toBytes(key)) Filter filter=new PageFilter(10000); scan.setFilter(pageFilter); scan.setCaching(100000);// 1lakh i know it should be 10K but this should not be the reson for scanner to return more keys as i commented out the line still getting more keys ResultScanner resultScanner=htable.getScanner(scan); But i am getting more than 10000 value for a specific key in most of the cases it is working fine and returning 10000 keys that is equal to pagination factor but in a specific case it returns more than 10000 key. Any point in the direction to understand this behavior will be of a great help A: OK,It is clear from HBase Api Pagination doc that the pagination filter does not guarantee to give rows <= pagination factor since the filter is applied for each region server
{ "language": "en", "url": "https://stackoverflow.com/questions/26562014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to overwrite User model I don't like models.User, but I like Admin view, and I will keep admin view in my application. How to overwirte models.User ? Make it just look like following: from django.contrib.auth.models import User class ShugeUser(User) username = EmailField(uniqute=True, verbose_name='EMail as your username', ...) email = CharField(verbose_name='Nickname, ...) User = ShugeUser A: That isn't possible right now. If all you want is to use the email address as the username, you could write a custom auth backend that checks if the email/password combination is correct instead of the username/password combination (here's an example from djangosnippets.org). If you want more, you'll have to hack up Django pretty badly, or wait until Django better supports subclassing of the User model (according to this conversation on the django-users mailing list, it could happen as soon as Django 1.2, but don't count on it). A: The answer above is good and we use it on several sites successfully. I want to also point out though that many times people want to change the User model they are adding more information fields. This can be accommodated with the built in user profile support in the the contrib admin module. You access the profile by utilizing the get_profile() method of a User object. Related documentation is available here.
{ "language": "en", "url": "https://stackoverflow.com/questions/1231943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change Bool value within a function in javascript? Based on this tutorial: link Here is my example code: function modifyVar(obj, val) { obj.valueOf = obj.toSource = obj.toString = function(){ return val; }; } function setToFalse(boolVar) { modifyVar(boolVar, 'false'); } var isOpen = true; setToFalse(isOpen); console.log('isOpen ' + isOpen); How can I change the bool variable value within a function? Is it possible to pass the bool value by reference? thanks in advance A: We can use that. var myBoolean = { value: false } //get myBoolean.value; //set myBoolean.value = true; A: Several problems there: * *'false' is not false. *Variables are passed by value in JavaScript. Always. So there is no connection whatsoever between the boolVar in setToFalse and the isOpen you're passing into it. setToFalse(isOpen) is processed like this: * *The value of isOpen is determined *That value (completely disconnected from isOpen) is passed into setToFalse *JavaScript has some interesting handling around primitive types: If you try to use them like object types (var a = 42; a.toFixed(2); for instance), the value gets promoted to a temporary object, that object is used, and then the object is discarded. So if obj is false, obj.anything = "whatever" ends up being a no-op, because the object that temporarily exists ends up getting released as soon as the line finishes. You could do something like what you're doing by promoting isOpen to an object via new Boolean, but beware that it will then act like an object, not a boolean: function modifyVar(obj, val) { obj.valueOf = obj.toSource = obj.toString = function(){ return val; }; } function setToFalse(boolVar) { modifyVar(boolVar, false); } var isOpen = new Boolean(true); // An object setToFalse(isOpen); snippet.log('isOpen ' + isOpen); <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> That works because the value in isOpen is a reference to an object. So when that value is passed into setToFalse as boolVar, boolVar's value is a copy of that reference, and so refers to the same object. So that sorts out issue #2 above. Issue #3 is solved by creating an object explicitly, rather than relying on the implicit behavior. But, remember my warning above about how it will act like an object (because it is one), not like a boolean? Here's an example: function modifyVar(obj, val) { obj.valueOf = obj.toSource = obj.toString = function(){ return val; }; } function setToFalse(boolVar) { modifyVar(boolVar, false); } var isOpen = new Boolean(true); // An object setToFalse(isOpen); snippet.log('isOpen ' + isOpen); if (isOpen) { snippet.log("isOpen is truthy, what the...?!"); } else { snippet.log("isOpen is falsey"); } <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> We see: isOpen false isOpen is truthy, what the...?! ...because isOpen contains a non-null object reference, and non-null object references are always truthy. A: You are passing boolean primitive variable isObject. For primitive types it doesn't make sense to try to set toString method, because it's not needed (and used), since in ECMAScript spec there are already defined rules for to String conversion. If you really want to use modifyVar function like you are trying, you can work with Boolean object instead of primitive: function modifyVar(obj, val) { obj.valueOf = obj.toSource = obj.toString = function(){ return val; }; } function setToFalse(boolVar) { modifyVar(boolVar, 'false'); } var isOpen = new Boolean(true); setToFalse(isOpen); console.log('isOpen ' + isOpen); So the answer: use new Boolean(true) or Object(true). A: I am not sure but you are assigning false in single quote, value withing single/double quotes will be considered as string. Just use modifyVar(boolVar, false); and try.
{ "language": "en", "url": "https://stackoverflow.com/questions/26829207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to use correctly isalnum function in C? I tried to check if a character of a string is alnum and then if the string contains only alnum characters to print the string. When I run the program nothing happens. I have another program with whom I read from the input the text I want and I send it with FIFO. If i don;t include in the program the "check" function it works, after that it doesn't. void put_alphanum(char *str) { while (*str) { if (*str >= '0' && *str <= '9') write(1, str, 1); else if (*str >= 'A' && *str <= 'Z') write(1, str, 1); else if (*str >= 'a' && *str <= 'z') write(1, str, 1); str++; } write(1,"\n",1); } This is the function I used to print the string. If I don't put it together with the check function the program works. int check(char *str) { while(*str) { if(isalnum(*str)==0) return 0; str++; } return 1; } This is the function I use to check if a string contains just alnum characters. But if I don;t include this function in my program, the program works. I think here is the problem. And the main function() int main() { int fd; int len; char buf[BUFF_SIZE + 1]; mkfifo(FIFO_LOC, 0666); fd = open(FIFO_LOC, O_RDONLY); while(1) { while((len = read(fd, buf, BUFF_SIZE))) { buf[len] = '\0'; if(check(buf)==1) put_alphanum(buf); } } return (0); } A: The Input text contains '\n' and that means that the string is not an alphanumeric string. When I read I push the enter button and that means one more character in the string.
{ "language": "en", "url": "https://stackoverflow.com/questions/44017907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Are there any web based email clients written in python? I need to integrate a email client in my current python web app. Anything available? L.E.: I'm building my app on top of CherryPy A: For others who might find this thread, check out Mailpile. I haven't used it yet, it is a python-based mail client, and I am sure it could be modified to work as a webmail app as well. A: You could try Quotient. It's a somewhat unusual webmail system, and it definitely won't fit into the same process as CherryPy - but it is in Python ;). A: You can build one, using email for generating and parsing mail, imaplib for reading (and managing) incoming mail from your mail server, and smtplib for sending mail to the world. A: Looking up webmail on pypi gives Posterity. There is very probably some way to build a webmail with very little work using Zope3 components, or some other CMS. I guess if you are writing a webapp, you are probably using one of the popular frameworks. We would need to know which one to give a more specific answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/236205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Fast tcp server availability check I want to make an Unity3D app that has a tcp/ip client. It should check regularly if there is an available server, and if there is one, tries to connect to it. I tried this as following _client = new TcpClient(_tcpAddress, _tcpPort); if (!_client.Connected) { return false; } But every time it calls the constructor, it lags badly. Is there any faster method that checks if there is a server at the specified port? A: Looking at the specific constructor you're using it states (emphasis mine): This constructor creates a new TcpClient and makes a synchronous connection attempt to the provided host name and port number. The underlying service provider will assign the most appropriate local IP address and port number. TcpClient will block until it either connects or fails. This constructor allows you to initialize, resolve the DNS host name, and connect in one convenient step. Your code isn't "lagging", it's actively waiting for the connection to succeed or fail. I would suggest instead using the default constructor and either call the BeginConnect and corresponding EndConnect methods, or if you can use the async/await pattern in Unity, perhaps try using ConnectAsync. Although in Unity, I think a simpler method might be to just use a coroutine (I'm not a Unity programmer so this might not be 100% right): StartCoroutine(TestConnectionMethod()); private IEnumerator TestConnectionMethod() { _client = new TcpClient(_tcpAddress, _tcpPort); yield return _client.Connected; }
{ "language": "en", "url": "https://stackoverflow.com/questions/62143387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to use AWS Cognito's adaptive authentication security heuristics in custom auth lambda trigger? I’m using AWS Cognito Custom Authentication flow. I do not rely on Cognito for MFA. I want to make use of the adaptive authentication security heuristics in Cognito’s advanced security features. Unfortunately, the event in trigger does not include this information. Is it possible to have different set of custom challenges based on the risk level from adaptive authentication? A: Here is a workaround until Cognito includes this information in the event passed to trigger. 
Configure different rules for advanced security features based on the app client id. For App client id 1, configure adaptive authentication to block users from login on detection of risk. And for App client id 2, configure to always allow login. In the custom auth trigger lambda, decide the challenges based on the app client id. So when app client is 1, use normal login challenges. And when app client id is 2, send extra challenges to client.

 The client should log in with app client id 1, and if it fails to login with the reason Unable to login because of security reasons, then log in using app client id 2. Unfortunately, Cognito does not have separate error codes, so had to look for error string in response. This approach does require that client whose request is deemed risky, to make a second cognito request. This will take longer time for that client, but atleast most users will not see slower logins. 
One option that was explored and dropped was to use Cognito admin api from lambda. There are two issues with this. First, every login would be slowed down by this additional http request to Cognito. Secondly, You can get last n events, but there is no way to ensure we request the right event. In case of simultaneous logins attempts, 1 no risk and 1 high risk, and admin api returns the no risk as last event, then both logins would pass through as no risk.
{ "language": "en", "url": "https://stackoverflow.com/questions/59919373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Equivalent of Nashorn's importPackage in graal.js script engine I am migrating old code from JDK 8 to JDK 12. In the process, I have noticed importPackage does not exist when using the "graal.js" script engine. It exists when using "javascript" for the script engine. Is there any way to achieve the same functionality with "graal.js"? The Nashorn migration doc on the GraalJS repository does not cover this. A: importPackage is originally from Rhino. Even Nashorn supports it when Rhino/Mozilla compatibility is requested explicitly using load("nashorn:mozilla_compat.js"); only, see Rhino Migration Guide in the documentation of Nashorn. Graal.js has Nashorn compatibility mode and it supports load("nashorn:mozilla_compat.js"); in this mode. So, you can use something like System.setProperty("polyglot.js.nashorn-compat", "true"); ScriptEngine engine = new ScriptEngineManager().getEngineByName("graal.js"); System.out.println(engine.eval("load('nashorn:mozilla_compat.js'); importPackage('java.awt'); new Point();")); (it prints java.awt.Point[x=0,y=0] which shows that the package java.awt was imported successfully).
{ "language": "en", "url": "https://stackoverflow.com/questions/57456476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if product available in Shopify using javascript I have a javascript that handles the product listing on the collection page. Is there a way to ensure that the product is available and not out of stock. I need something similar to {% if product.available %}. But I don't want to change the .liquid file. I need it in Javascript. A: You can get the JSON representation of an arbitrary product in your store by fetching data from /products/<some-product-handle>.js. When using the .js endpoint, the product object will include a number of aggregate parameters, including product.available which will be true if at least 1 variant in the product is available. Note that Shopify has 2* different product representations, one at the /products/<some-product-handle>.js endpoint and one at the /products/<some-product-handle.json endpoint. These two objects are surprisingly different, and one of those differences is that the .json endpoint does not have the aggregate product.available value - you would have to determine that yourself by checking the availability of all the variants within if using this endpoint. This is one of the reasons why I generally recommend using the .js endpoint for all your Javascript needs. * Strictly speaking, there's actually 3 different product representations: the output from a {{ product | json }} drop from Liquid is slightly different from both endpoints but largely the same as the .js endpoint, with the exception being how the product.options array is structured A: You have four options for getting data into javascript in Shopify: * *If the javascript is included as an inline script tag / a snippet in the liquid file then you’d be writing javascript liquid and you can interpolate directly e.g. var product = "{{ product | json}}". *You can update the liquid document to include e.g. attributes with the required data, e.g ‘data-‘ attributes, and then read those with javascript from the document. You’ve said this is not an option. *Re-fetch some data about entities on the current page using a Shopify API: e.g Ajax / Storefront / Shopify Buy SDK. *Add an alternative liquid page for an existing theme page that formats the data you need to json (e.g. {{ product | json }}) but name it e.g. product.ajax.liquid - this will make it into a custom view. Then you can fetch this pages url with the query parameter ?view=ajax and returned document will include the rendered json. This effectively creates a custom API for you. Those are the options.
{ "language": "en", "url": "https://stackoverflow.com/questions/59714654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to know the status of a systemctl process running in the host from a docker container(base image python:3.9)? I am trying to get the status of a systemctl service which is in the host from the docker container. I tried to volume mount the necessary unit files and made the docker work in privileged mode. But still i get an error saying the status of the service is inactive while the status in the host is in active. docker run --privileged -d -v /etc/systemd/system/:/etc/systemd/system/ -v /sys/fs/cgroup:/sys/fs/cgroup:ro -v /usr/lib/systemd/system/:/usr/lib/systemd/system/ test-docker:latest Is there a way to achieve this or any equivalent way of doing this ? A: The way systemctl communicates with systemd to get service status is through a d-bus socket. The socket is hosted in /run/systemd. So we can try this: docker run --privileged -v /run/systemd:/run/systemd -v /sys/fs/cgroup:/sys/fs/cgroup test-docker:latest But when we run systemctl status inside the container, we get: [root@1ed9d836a142 /]# systemctl status Failed to connect to bus: No data available It turns out that for this to work, systemctl expects systemd to be pid 1, but inside the container, pid 1 is something else. We can resolve this by running the container in the host PID namespace: docker run --privileged -v /run/systemd:/run/systemd --pid=host test-docker:latest And now we're able to successfully communicate with systemd: [root@7dccc711a471 /]# systemctl status | head ● 7dccc711a471 State: degraded Jobs: 0 queued Failed: 2 units Since: Sun 2022-06-26 03:11:44 UTC; 5 days ago CGroup: / ├─kubepods │ ├─burstable │ │ ├─pod23889a3e-0bc3-4862-b07c-d5fc9ea1626c │ │ │ ├─1b9508f0ab454e2d39cdc32ef3e35d25feb201923d78ba5f9bc2a2176ddd448a ...
{ "language": "en", "url": "https://stackoverflow.com/questions/72829097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular 6.1.2 PWA not working I tried all the solutions on the internet on how to add PWA to an Angular project, but still in Chrome Dev Tools, there are no service worker registered. I did run ng add @angular/pwa, with ng build --prod and http-server -o and still no service worker registered. It also does not add a @angular/service-worker package and also no Manifest.json file like it should as indicated all over the internet. I also tried creating a new project with PWA pre-installed with ng new myProject --service-worker, also not working. I even tried registering the service working like below: if ( 'serviceWorker' in navigator ) { window.addEventListener('load', function() { navigator.serviceWorker.register('/service-worker.js'); }); A side note: When I run ng add @angular/pwa I get a message "Path '/ngsw-config.json' already exist", so I found out that file is under @schematics package. The script only adds a @angular/pwa package, which does not corrolate with the Angular PWA docs. Here is my environment : Angular 6.1.2 Angular CLI: 6.1.3 Node 8.11.3 NPM 5.6.0 What do I need to do to get a plain PWA Angular project? A: It is the new version of @angular/pwa package that has a few bugs. So running ng add @angular/pwa@0.6.8 worked perfectly for me. To test the service worker locally: If you have Firebase added to your project (hosting), you can run ng build --prod and then firebase serve. When you don't have Firebase, you can run ng build --prod, cd into the dist folder (depending on your config) and then run http-server -o. If you don't have http-server module, install it by running npm i -g http-server A: Try using the Angular Console: https://angularconsole.com/ It abstracts away many of the need to know logic that the cli has. It's in beta but it should help you create the base for your PWA. Give it a try it's build from the Nrwl Team that also builds Nx which is an enhancement to the angular/cli using schematics A: I had the same issue. The problem was than this command: ng add @angular/pwa didn't add module @angular/pwa to package.json dependencies. I decided it so. First I run ng add @angular/pwa Then I did: npm install @angular/pwa And it all works!
{ "language": "en", "url": "https://stackoverflow.com/questions/51867392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Count Total Bar codes of Specific Color by fetching values from various fields when they match in SQL I have a situation where I have 4 color columns(Color1, Color2, Color3, Color4) I need to add the values of bar codes present in all color columns when they match. Its bit complicated, I have the graphical representation here: Color1 Color2 Color3 Color4 Barcodes Red 1 Red 3 Red 4 Red 2 Expected Result: Total Barcodes where Color is Red=10 I am using SQL Server Any Assistance in this would be really helpful. EDIT: there are 320 colors in the table A: I would unpivot and aggregate: select sum(Barcodes) from t cross apply (values (color1), (color2), (color3), (color4)) v(color) where color = 'Red'; If you want this for each color: select color, sum(Barcodes) from t cross apply (values (color1), (color2), (color3), (color4)) v(color) group by color;
{ "language": "en", "url": "https://stackoverflow.com/questions/51108435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: R - faster alternative to hist(XX, plot=FALSE)$count I am on the lookout for a faster alternative to R's hist(x, breaks=XXX, plot=FALSE)$count function as I don't need any of the other output that is produced (as I want to use it in an sapply call, requiring 1 million iterations in which this function would be called), e.g. x = runif(100000000, 2.5, 2.6) bincounts = hist(x, breaks=seq(0,3,length.out=100), plot=FALSE)$count Any thoughts? A: A first attempt using table and cut: table(cut(x, breaks=seq(0,3,length.out=100))) It avoids the extra output, but takes about 34 seconds on my computer: system.time(table(cut(x, breaks=seq(0,3,length.out=100)))) user system elapsed 34.148 0.532 34.696 compared to 3.5 seconds for hist: system.time(hist(x, breaks=seq(0,3,length.out=100), plot=FALSE)$count) user system elapsed 3.448 0.156 3.605 Using tabulate and .bincode runs a little bit faster than hist: tabulate(.bincode(x, breaks=seq(0,3,length.out=100)), nbins=100) system.time(tabulate(.bincode(x, breaks=seq(0,3,length.out=100))), nbins=100) user system elapsed 3.084 0.024 3.107 Using tablulate and findInterval provides a significant performance boost relative to table and cut and has an OK improvement relative to hist: tabulate(findInterval(x, vec=seq(0,3,length.out=100)), nbins=100) system.time(tabulate(findInterval(x, vec=seq(0,3,length.out=100))), nbins=100) user system elapsed 2.044 0.012 2.055 A: Seems your best bet is to just cut out all the overhead of hist.default. nB1 <- 99 delt <- 3/nB1 fuzz <- 1e-7 * c(-delt, rep.int(delt, nB1)) breaks <- seq(0, 3, by = delt) + fuzz .Call(graphics:::C_BinCount, x, breaks, TRUE, TRUE) I pared down to this by running debugonce(hist.default) to get a feel for exactly how hist works (and testing with a smaller vector -- n = 100 instead of 1000000). Comparing: x = runif(100, 2.5, 2.6) y1 <- .Call(graphics:::C_BinCount, x, breaks + fuzz, TRUE, TRUE) y2 <- hist(x, breaks=seq(0,3,length.out=100), plot=FALSE)$count identical(y1, y2) # [1] TRUE
{ "language": "en", "url": "https://stackoverflow.com/questions/38437350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Delphi FMX: HTTPClient asynchronous Post works in Windows, Fails in Android I'm using THTTPClient in Delphi 10.3 to perform a POST operation and bring data from a server. Parameters are JSON. Problem is: * *When compiled as a Win32 application, it works perfectly for both when performing a asynchronous call or not. *When compiled as an Android app, it fails in the async call and works fine in the normal way. The failure error indicates that somehow the request is not passing the json parameters (that only happens in async mode). For example: if the remote server requires to pass two parameters (say, name and age) I'll get the remote error that "name is a mandatory field". My code is based on a Delphi download sample. Is there something I should change for this to work in Android? Thanks! Here is the relevant code: //the content of mmoParams.Text is a JSON string: //{"name":"somebody","salary":"1000","age":"51"} Params := TStringStream.Create(mmoParams.Text, TEncoding.UTF8); Params.Position := 0; // prepare the request HTTPClient.ContentType := 'application/json'; HTTPClient.Accept := 'application/json'; if chkAsync.IsChecked then begin // prepare the request HTTPClient.ContentType := 'application/json'; HTTPClient.Accept := 'application/json'; // make the request and handle in the callback HTTPResult:= HTTPClient.BeginPost(DoEndPost,edtURL.Text,Params); end else begin // make the request HTTPResponse := HTTPClient.Post(edtURL.Text,Params); // handle response lblStatusCode.Text := HTTPResponse.StatusCode.ToString; mmoResult.Text := HTTPResponse.ContentAsString(TEncoding.UTF8); end; and here's the callback procedure for when the async call (BeginPost) is made. procedure TMainForm.DoEndPost(const AsyncResult: IAsyncResult); begin try HTTPResponse := THTTPClient.EndAsyncHTTP(AsyncResult); TThread.Synchronize(nil, procedure begin // handle result lblStatusCode.Text := HTTPResponse.StatusCode.ToString; mmoResult.Text := HTTPResponse.ContentAsString(TEncoding.UTF8); end); finally end; end; A: As suggested by @DaveNottage, an anonymous thread with standard Post was my best solution so far. This is the function I've been using quite succesfully so far. I call it from the main program with the destination url, the params that will be sent as JSON and a Callback Procedure that will handle the HTTPResponse received. procedure HTTPPostAsync(HTTPClient: TNetHTTPClient; url, params: string; CallBack: HTTPClientProc); var Thread: TThread; begin // define the thread Thread := TThread.CreateAnonymousThread ( procedure var HTTPResponse: IHTTPResponse; JSon : TStringStream; begin Json := TStringStream.Create(Params, TEncoding.UTF8); Json.Position := 0; HTTPClient.ContentType := 'application/json'; HTTPClient.Accept := 'application/json'; HTTPClient.ConnectionTimeout := 20000; HTTPClient.ResponseTimeout := 20000; try HTTPResponse:= HTTPClient.Post(url,Json); TThread.Synchronize (TThread.CurrentThread, procedure begin Callback(HTTPResponse); end ); finally Json.Free; end; end ); // let it roll Thread.start; end; A: Just copy files from {$BDS}/source/rtl/net from 10.2.3 into your project directory and cut non-exist function GetEncodingMIMEName into 'utf-8' everywhere. This fix works fine, but it will better if Embarcadero will stop make stupid bugs with every release
{ "language": "en", "url": "https://stackoverflow.com/questions/54846698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Weird behavior of JFormattedTextField with NumberFormatter and DecimalFormat I'm new here (I've read a lot, nut never posted before). I'm encountering a weird problem on a JFormattedTextField. I'm trying to limit the input to numbers ranging from 9999.9 to -9999.9, but I can't seem to find a working solution. I tried using a DecimalFormat and a NumberFormatter, but it doesn't work as expected. I looked all over the net, but I can't seem to find an explanation of what I'm seeing (maybe I'm not searching for the right thing?). Here is a small code that shows the problem: import java.awt.*; import javax.swing.*; import javax.swing.text.*; import java.text.*; public class testwindow extends JPanel { private JFormattedTextField field1; private JFormattedTextField field2; public testwindow() { try { //format text input fields (only numbers, dots and minus; overwrite; don't allow invalid chars) DecimalFormat decimalFormat = new DecimalFormat("#0.0;-#0.0"); decimalFormat.setNegativePrefix("-"); decimalFormat.setMinimumIntegerDigits(1); decimalFormat.setMaximumIntegerDigits(4); decimalFormat.setMinimumFractionDigits(1); decimalFormat.setMaximumFractionDigits(1); NumberFormatter realFormatter = new NumberFormatter(decimalFormat); realFormatter.setOverwriteMode(true); realFormatter.setAllowsInvalid(false); field1 = new JFormattedTextField(realFormatter); field1.setValue(0F); field2 = new JFormattedTextField(decimalFormat); field2.setValue(0F); setPreferredSize (new Dimension (215, 60)); setLayout(new GridLayout(2,1)); add (field1); add (field2); } catch (Exception ex) { ex.printStackTrace(); } } public static void main (String[] args) { JFrame frame = new JFrame ("MyPanel"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add (new testwindow()); frame.pack(); frame.setVisible (true); } } Basically, I type 123456, and I'd expect the result to be 1234.5. However: * *field1, with NumberFormatter applied, shows 4050.6 immediately *field2 shows 1234560.0 while typing, and changes to 4560.0 after focus is moved Also, when pressing minus on field1, the sign changes correctly between positive and negative. In field2, unless the minus is written as first character, it disappears. Last but not least, typing 9 as last char on field1 multiple times just causes the number to increase of 0.1 each time, making all the behavior really puzzling. I like much more the field1 behavior regarding the number of digits enforcement, but I wonder whether there is a correct/better way to obtain what I need, that is (as example) "1234.5" and the number not increasing by typing anything else as last char?
{ "language": "en", "url": "https://stackoverflow.com/questions/75319177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF Serialization not as expected I have a c# class like this as a return for my WCF method: [Serializable] [XmlRoot("OutputItem")] public class MyItem { [XmlElement("ItemName")] public string NodeName { get; set; } [XmlArray("Fields"), XmlArrayItem(ElementName = "Field", Type = typeof(MyItemField))] public List<MyItemField> Fields { get; set; } } My WCF method is as such: public MyItem GetItemXML(string id) { MyItem mi = new MyItem(); //do some stuff to populate mi return mi; } I expect the XML output of this to be something like this: <xml version="1.0" encoding="utf-16"?> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <GetItemXMLResponse xmlns="http://www.here.com/XML/ItemService.xsd"> <GetItemXMLResult> <OutputItem> <ItemName>FR</ItemName> <Fields> ...... </Fields> </OutputItem> </GetItemXMLResult> </GetItemXMLResponse> </s:Body> </s:Envelope> However, the output that is coming out is as follows - without the <OutputItem> directive at the top: <xml version="1.0" encoding="utf-16"?> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <GetItemXMLResponse xmlns="http://www.here.com/XML/ItemService.xsd"> <GetItemXMLResult> <ItemName>FR</ItemName> <Fields> ...... </Fields> </GetItemXMLResult> </GetItemXMLResponse> </s:Body> </s:Envelope> What am I missing? A: If I recall correctly it all depends on how your [OperationContract] is defined. you may have to use Message Contracts to get your desired behavior. Take a look at http://msdn.microsoft.com/en-us/library/ms730255.aspx A: // The Model Object [Serializable] [XmlRoot("OutputItem")] [DataContractAttribute] public class MyObject { [XmlElement("ItemName")] [DataMemberAttribute] public string Name { get; set; } [XmlArray("DummyItems")] [XmlArrayItem("DummyItem", typeof(MyItemField))] public List<Fields> DummyItem { get; set; } } // The Class that implement the contract [DataContract] public class ConsumptionService : IAnyContract { public MyObject GetItemXML(string id) { MyObject mo = new MyObject(); //do some stuff to populate mi MyObject mo; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/12504046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: generic type XMLexception in catel I try to use the properties CATEL who generic type. And I have XmlException in Model attribute. [Serializable] public class TDS : SavableModelBase<TDS> { public TestType<bool> Tds { get { return GetValue<TestType<bool>>(TdsProperty); } set { SetValue(TdsProperty, value); } } public static readonly PropertyData TdsProperty = RegisterProperty("Tds", typeof(TestType<bool>)); public TDS(TestType<bool> tds) { Tds = tds; } } ViewModel when i use catel prop public class MainWindowViewModel : ViewModelBase { [Model] public TDS Xxx //when assigning XMLException The '`' character, hexadecimal value 0x60, cannot be included in a name. { get { return GetValue<TDS>(XxxProperty); } set { SetValue(XxxProperty, value); } } public static readonly PropertyData XxxProperty = RegisterProperty("Xxx", typeof(TDS)); } class modelBase in main struct, where catel prop [Serializable] public class TestType<T> : ModelBase { public TestType(ushort val) { Val = val; } public ushort Val { get { return GetValue<ushort>(ValProperty); } set { SetValue(ValProperty, value); } } public static readonly PropertyData ValProperty = RegisterProperty("Val", typeof(ushort)); } I think that the problem, in a generic catel prop Help me!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/28711367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recursion for matrix in JavaScript I'm using recursion for finding neighbors of neighbors in a matrix (in a minesweeper game). Right now my function is finding and marking neighbors only from left till bottom right. What am I doing wrong? Javascript: function openAllZeroCount(elcell, i, j) { for (var idxi = i - 1; idxi <= i + 1; idxi++) { for (var idxj = j - 1; idxj <= j + 1; idxj++) { if (idxi < 0 || idxi >= gSize || idxj < 0 || idxj >= gSize) continue; if (gBoard[idxi][idxj].isMine === false && gBoard[idxi][idxj].minesAroundCount === 1) { var elCountZero = document.getElementById('cell-' + idxi + '-' + idxj) elCountZero.style.opacity = '0.8' elCountZero.innerText = gBoard[idxi][idxj].minesAroundCount } if (gBoard[idxi][idxj].isMine === false && gBoard[idxi][idxj].minesAroundCount === 0) { var elCountZero = document.getElementById('cell-' + idxi + '-' + idxj) elCountZero.style.opacity = '0.8' } } } if (idxi < 0 || idxi >= gSize || idxj < 0 || idxj >= gSize) return; if (gBoard[idxi][idxj].isMine === false) { console.log('gboard i j:', gBoard[idxi][idxj]) openAllZeroCount(null, idxi, idxj) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/52539935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I size my Spinner Image Size in Android app for different screen size/resolutions? I'm trying to develop my first app for the play store which should resize for different screen sizes/resolutions. For some reason the spinner images are showing up extremely small for mdpi virtual device & huawei 9 on firebase. Please see attached file. The other images are very large currently because I removed the ldpi, mdpi, hdpi, xhdpi, xxhdpi and xxhdpi folders to see how it would appear with just xxhdpi images. I have spinner widths in the layout xml files at 40dp, 50dp, 80dp and 180dp for small, normal, large and xtra large screens respectively.Screenshot of low res mdpi virtual devise Any ideas why the images would appear so tiny! A: In case anyone has sizing/layout issues with Android apps for different screen sizes/display dpis - I highly recommend this sdk https://github.com/intuit/sdp/commits?author=elhanan-mishraky which solved my problem above!
{ "language": "en", "url": "https://stackoverflow.com/questions/58942110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What causes inhibited conditional statements? There are three options that the user can input in this program. He can choose to login, create an account, or restore an account using his email. if user_ == 1: loginf.main() if user_ == 2: createnewaccount.main() if user_ == 3: restoreaccount.main() Each option calls a function from a different module. And then returns back to main when the user is done. For example, my code in the loginf module: def login_information(): login = input("Enter your username: \n") password = input("Enter your password: \n") if os.path.isfile('accountinfo.txt'): # Checking to see if accountinfo text file is created. pass # If not, then called back to mainf module. else: print("You don't have an account on file.") import mainf mainf.main() chobi = open('accountinfo.txt') particular_text = chobi.read().strip().split() if login and password not in particular_text: login_error() else: print("You've logged into your account.") chobi.close() return_back_to_main() def main(): while True: login_information() I've used a similar set-up for my other two modules. However, this is my output: C:\Users\raamis\PycharmProjects\TicTacToe\venv\Scripts\python.exe C:/Users/raamis/PycharmProjects/scratchProject/mainf.py ------------------------ LOGIN - 1 CREATE NEW ACCOUNT - 2 RESTORE ACCOUNT - 3 ------------------------ Select an option 1-3: 1 Enter your username: Luke Enter your password: RoboCop123! You've logged into your account. ------------------------ LOGIN - 1 CREATE NEW ACCOUNT - 2 RESTORE ACCOUNT - 3 ------------------------ Select an option 1-3: 1 Enter your username: Luke Enter your password: RoboCop123! You've logged into your account. ------------------------ LOGIN - 1 CREATE NEW ACCOUNT - 2 RESTORE ACCOUNT - 3 ------------------------ Select an option 1-3: 2 Enter your username: The functions are appropriately called for the first 2 iterations. But then when an option is selected on the third iteration, the program still refers back to the loginf module. I've also had to import locally to avoid circular imports.
{ "language": "en", "url": "https://stackoverflow.com/questions/59938511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cleaning an older swift application project using storyboards I have been assigned a "new" old app project from my company, where there is a mix of older swift code and newer swift code. I am slowly getting comfortable with deleting and refactoring parts of the code, trying to remove the Xcode warnings and making the code safer in general... But since I am new to swift (especially storyboards), I am not sure when an @IBOutlet or @IBAction can be removed. I have some @IBOutlets and @IBActions, where there are no 'dots' next to them: the circles to the left-side of the outlets don't have a dot Does this mean it is safe to change these from outlets to "regular" views? and is this also true for @IBActions? Is this simply straight forward, no dot = No @IBOutlet/@IBAction needed? Or is it trial and error: Try and remove, build & run, see if broken, redo...? Or are there smarter ways to check these things?
{ "language": "en", "url": "https://stackoverflow.com/questions/73611885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Complex data.table subset and manipulation I am trying to combine a lot of data.table manipulations into a some faster code. I am creating an example with a smaller data.table and I hopeful someone has a better solution than the clunky (embarrassing) code I developed. For each group, I want to: 1) Verify there is both a TRUE and FALSE in column w, and if there is: 2) Subtract the value of x corresponding to the highest value of v from each value of x in the same group and put that that number in a new column So in group 3, if the highest v value is 10, and in the same row x is 0.212, I would subtract 0.212 from every x value corresponding to group 3 and put that number in a new column 3) Remove all rows corresponding to groups without both a TRUE and a FALSE in column w. set.seed(1) test <- data.table(v=1:12, w=runif(12)<0.5, x=runif(12), y=sample(2,12,replace=TRUE), z=sample(letters[1:3],12,replace=TRUE) ) setkey(test,y,z) test[,group:=.GRP,by=key(test)] A: A chained version can look like this without needing to set a table key: result <- test[ # First, identify groups to remove and store in 'rowselect' , rowselect := (0 < sum(w) & sum(w) < .N) , by = .(y,z)][ # Select only the rows that we need rowselect == TRUE][ # get rid of the temp column , rowselect := NULL][ # create a new column 'u' to store the values , u := x - x[max(v) == v] , by = .(y,z)] The result looks like this: > result v w x y z u 1: 1 TRUE 0.6870228 1 c 0.4748803 2: 3 FALSE 0.7698414 1 c 0.5576989 3: 7 FALSE 0.3800352 1 c 0.1678927 4: 10 TRUE 0.2121425 1 c 0.0000000 5: 8 FALSE 0.7774452 2 b 0.6518901 6: 12 TRUE 0.1255551 2 b 0.0000000
{ "language": "en", "url": "https://stackoverflow.com/questions/34957130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add second data source to xslt / dataview in SharePoint? I'm trying to create a bar chart using dataview formated using xsl. The list to chart contains data about number of hours spend on certain project. The project column is of type lookup, which points to a list on the other subsite (simpler: cross site lookup column). The fist data source that I connected to dataview points to the first list. How to add second datasource? (I know it's maybe not the best explanaition so here's some code) <xsl:template name="dvt_1.footer"> <xsl:param name="ParentPath" /> <xsl:param name="Rows" /> <xsl:variable name="Time" select="count(/dsQueryResponse/Rows/Row)" /> <xsl:variable name="Projects" select="/NEED/DATA/SOURCE" /> <table width="100%" cellspacing="0" cellpadding="2" style="border-right: 1 solid #C0C0C0; border-bottom: 1 solid #C0C0C0; border-left-style: solid; border-left-width: 1; border-top-style: solid; border-top-width: 1;"> <xsl:for-each select="$Projects"> <xsl:call-template name="showBar"> <xsl:with-param name="TimeCount" select="$Time" /> <xsl:with-param name="ColumnTitle" select="ProjectName" /> <xsl:with-param name="ItemCount" select="count(/dsQueryResponse/Rows/Row[normalize-space(@Project) = 'ProjectName'])" /> </xsl:call-template> </xsl:for-each> </table> </xsl:template> So I need to: * *somehow populate Projects variable *figure out how to use fore-each variable from new datasource in xl:with-param :P I'm completely new to xsl so it's possible there are obvious mistakes in code. Any constructive input is highly appreciated. A: Use the document() function to load and leverage an external XML file within your XSLT. <xsl:variable name="Projects" select="document('http://some.url.to/file.xml')/DATA" />
{ "language": "en", "url": "https://stackoverflow.com/questions/1721813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why return from child is getting undefined in Parent in my Vue application I am building an Vue Application. In my child component I have a function say getName() and I am returning name but when I try to access this function in my parent I am not able to use that getting undefined. But when I emit name in the parent and Use the emit obj it is working. Can Anyone knows why I am facing this problem. Parent.vue export default defineComponent({ name: 'App', components: { HelloWorld }, mixins: [HelloWorld], data() : { let value !: string return { value} } methods: { fetchval(){ let x = this.value.getVal(); console.log(x); } } }); </script> Child.vue export default defineComponent({ name: 'HelloWorld', dat(){ let val!: string; return{ val, } }, computed: { value: { get() { return this.val as string; }, set(newval) { val = newval; } } }, methods: { getVal(){ return this.value as string; } } }); </script> When I try to console.log x I am getting undefined but when i emit this.value and use it in parent working fine. What am i missing? A: The "fetchval" method in your parent is not referencing your child but the "value" property in your data function. "this" refers to your parent component. Basically, you are trying to call a "getVal" function on a string in your parent. If you want to call a function on your child component, you need a reference to the child and call that function on that reference. You need to add a ref to your child component. If you're not familiar with refs, I suggest starting here: Template Refs
{ "language": "en", "url": "https://stackoverflow.com/questions/73148608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Internal Exception: java.sql.SQLSyntaxErrorException: 'EMAIL' is not a column in table I am running a JAVA EE Application using Maven and Netbeans Apparently my column "email" is not getting detected? what I am doing wrong? This is in my Entity class Customers package com.mycompany.carsales; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.*; @Entity public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id ; private String firstName; private String lastName; private String email; //email address private String phone; //phone number @JoinColumn(name="order_of") @OneToMany (cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) private List<CustomerTransaction> customerT; public List<CustomerTransaction> getCustomerT() { return customerT; } public void setCustomerT(List<CustomerTransaction> customerT) { this.customerT = customerT; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public String toString() { return "com.mycompany.carsales.Customer[ id=" + id + " ]"; } } This is in my Main package com.mycompany.carsales; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import com.mycompany.carsales.Customer; import java.util.ArrayList; import java.util.Date; import javax.persistence.*; /** * * @author carlos */ public class Main { public static void main (String[] args){ // Gets an entity manager and a transaction Cars car = new Cars(); //creating Games object and passing values to all it car.setBrand("Toyota"); car.setDescription("Manual, Red color"); car.setType("Truck"); car.setcYear("2014"); Automobile auto = new Automobile(); auto.setPrice(20000); auto.setPlate("88PLATE"); CustomerTransaction transaction1 = new CustomerTransaction(); //first CustomerOrder object with Games object passed in transaction1.setCarPlate(auto.getPlate()); transaction1.setCarPrice(auto.getPrice()); transaction1.setTransactionID(auto.getId()); transaction1.setBuyDate(new Date()); CustomerTransaction transaction2 = new CustomerTransaction(); //first CustomerOrder object with Games object passed in transaction2.setCarPlate(auto.getPlate()); transaction2.setCarPrice(auto.getPrice()); transaction2.setTransactionID(auto.getId()); transaction2.setBuyDate(new Date()); ArrayList<CustomerTransaction> tList = new ArrayList(); //The arrayList is created tList.add(transaction1); //here the previous orders are added one by one tList.add(transaction2); Customer customer = new Customer(); customer.setFirstName("Homer"); customer.setLastName("Simpson"); customer.setEmail("Homer.Simpson@fakeemail.com"); customer.setPhone("0404944165"); customer.setCustomerT(tList); EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPU"); EntityManager em = emf.createEntityManager(); //creation of Entity manager EntityTransaction tx = em.getTransaction(); //beginning the Entity Transaction tx.begin(); //persistence performed em.persist(auto); em.persist(customer); //commiting transaction and closing Manager tx.commit(); em.close(); emf.close(); System.out.println("Persistance is successfull"); } } My persistence xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="MyPU" transaction-type="RESOURCE_LOCAL"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <class>com.mycompany.carsales.Customer</class> <class>com.mycompany.carsales.Cars</class> <class>com.mycompany.carsales.Automobile</class> <class>com.mycompany.carsales.CustomerTransaction</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/Cars;create=true"/> <property name="javax.persistence.jdbc.password" value="app"/> <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/> <property name="javax.persistence.jdbc.user" value="app"/> <property name="eclipselink.ddl-generation" value="create-tables"/> </properties> </persistence-unit> </persistence>
{ "language": "en", "url": "https://stackoverflow.com/questions/38957506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does this typedef statement do? I was going through some code and am not able to understand the following piece of code. What does it do? What does it mean? typedef void*(*fun)[2]; fun new_array; A: Following the clockwise/spiral rule, fun is a pointer to an array of two pointers to void. A: OK, basically, this is how typedef works: first imagine that the typedef isn't there. What remains should declare one or more variables. What the typedef does is to make it so that if you would declare a variable x of type T, instead it declares x to be an alias for the type T. So consider: void*(*fun)[2]; This declares a pointer to an array of void* of size 2. Therefore, typedef void*(*fun)[2]; declares fun to be the type "pointer to array of void* of size 2". And fun new_array declares new_array to be of this type.
{ "language": "en", "url": "https://stackoverflow.com/questions/25499612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to install laravel using composer I installed composer successfully. Now i am trying to install laravel using this command composer global require "laravel/installer" in command prompt but i can't able to install laravel. This show me something like below image. When i use composer create-project --prefer-dist laravel/laravel blog in command prompt then it will show me something like below image. What should i do? any suggestion? A: This problem is caused due to many possible reasons, like: * *You are behind the firewall and firewall block it. *Your internet is too slow. (Hope it is not the case) *You are using VPN or PROXY. (Not all VPN causes this error.) *You have both ipv4 and ipv6 enabled (Not sure about this case.) I cannot confirm about the main reason that is caused for you to not being able to create project from composer but you could try some methods like: * *Changing to different ISP. *Try running composer -vvv: This helps to check what actually is doing behind the scene and helps in further more debug. *Try updating composer to latest version. *Try creating some older version of Laravel or any other packages composer create-project laravel/laravel blog "5.1.*" *Try using some VPN. This is only for testing and doesn't have fully confirmed solution. If there is any other reason we could edit this solution. A: If are installing the composer make sure that,you must have to set environment variable for PHP. If your using xampp control panel ->go to xampp installed path->PHP. Then copy location and set in the environment location.Then try to install composer.
{ "language": "en", "url": "https://stackoverflow.com/questions/43316695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding html table row with jquery can not set as marked I wrote a HTML file with a table. This table has about 7 entries (rows with data) by default. When the user clicks on one of these row the background color changes and it becomes marked, I did it with the jquery toggle function. I also have a button which adds further rows in this table, also with jquery. My problem: When I (user) add some rows with that button and click on those new added rows the background color doesn't change but the background color of default rows change. <!DOCTYPE html> <html> <head> <title>My Page</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(".row").click(function(){ $(this).toggleClass("activeRow"); }); $(document).on('click', '#addButton', function(){ $(".myTable tbody").append(" <tr class=&quot;row&quot;> <td>New</td> <td>This</td> <td>is</td> <td>great</td> </tr>"); }); }); </script> <style> .activeRow{ background-color:#B0BED9; } .myTable { border-collapse: collapse; width: 80%; clear:both; margin-top: 0; border-spacing: 0; table-layout: fixed; border-bottom: 1px solid #000000; } .myTable tbody, .myTable thead{ display: block; width: 100%; } .myTable tbody{ overflow: auto; height: 300px; } .myTable th, td{ width: 450px; } </style <table class="myTable"> <thead> <tr id="headRow"> <th>alo</th> <th>salam</th> <th>kissa</th> <th>chissa</th> </tr> </thead> <tbody class="bodyRows"> <tr class="row" > <td>Microsoft</td> <td>Saber</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Google</td> <td>50.2</td> <td>40.63</td> <td>45.23</td> </tr> <tr class="row"> <td>Apple</td> <td>25.4</td> <td>30.2</td> <td>33.3</td> </tr> <tr class="row"> <td>IBM</td> <td>20.4</td> <td>15.6</td> <td>22.3</td> </tr> </tbody> </table> <button id="addButton" class="tableButton">Add Row</button> A: You need to bind the row click events with .on method as well. $(document).ready(function() { $(document).on("click", ".myTable .row", function() { $(this).toggleClass("activeRow"); }); $(document).on('click', '#addButton', function() { $(".myTable tbody").append(" <tr class='row'> <td>New</td> <td>This</td> <td>is</td> <td>great</td> </tr>"); }); }); .activeRow { background-color: #B0BED9; } .myTable { border-collapse: collapse; width: 80%; clear: both; margin-top: 0; border-spacing: 0; table-layout: fixed; border-bottom: 1px solid #000000; } .myTable tbody, .myTable thead { display: block; width: 100%; } .myTable tbody { overflow: auto; height: 300px; } .myTable th, td { width: 450px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="myTable"> <thead> <tr id="headRow"> <th>alo</th> <th>salam</th> <th>kissa</th> <th>chissa</th> </tr> </thead> <tbody class="bodyRows"> <tr class="row"> <td>Microsoft</td> <td>Saber</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Google</td> <td>50.2</td> <td>40.63</td> <td>45.23</td> </tr> <tr class="row"> <td>Apple</td> <td>25.4</td> <td>30.2</td> <td>33.3</td> </tr> <tr class="row"> <td>IBM</td> <td>20.4</td> <td>15.6</td> <td>22.3</td> </tr> </tbody> </table> <button id="addButton" class="tableButton">Add Row</button> A: You're adding the toggleClass behaviour to the existing rows, not the newly created ones. You need to add the event when you create new rows: $(document).ready(function () { $(".row").on('click', function (ev) { $(this).toggleClass("activeRow"); }); $('#addButton').on('click', function (ev) { $(".myTable tbody").append(' <tr class="row"> <td>New</td> <td>This</td> <td>is</td> <td>great</td> </tr>'); $(".row").off('click').on('click', function (ev) { // off, to avoid overloading listeners on click event $(this).toggleClass("activeRow"); }); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/40579286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pre-populating a form field with HTML I would like to pre-populate this form: https://npo1.networkforgood.org/Donate/Donate.aspx?npoSubscriptionId=1006493 Specifically one field. <input name="ctl00$ctl00$body$formControl$stateControl$question_1241326" type="text" maxlength="100" id="ctl00_ctl00_body_formControl_stateControl_question_1241326" style="width:150px;"> (That's the "specific fund" box all the way at the bottom.) I want that field to be populated with the name of my charity, but I can't figure out how to make a link that will populate that field with the name when the link is clicked, or if that's even possible. I don't have access to the scripting of the target site, but I do have access to my site (where the link will be), it's a Wordpress site, if there is a Javascript, PHP, or other solution. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/16619739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dataframe supported method for transformation I have pandas pandas dataframe like this +-------+-----------+ | Name | Attribute | +-------+-----------+ | James | Tall | | James | Bald | | Lily | Fat | | Lily | Tall | +-------+-----------+ and my expect output is +------+------+------+-----+ | Name | Tall | Bald | Fat | +------+------+------+-----+ | James| 1 | 1 | 0 | | Lily | 1 | 0 | 1 | +------+------+------+-----+ My data contains several hundred attributes. Does anyone have experience with this kind of transformation?
{ "language": "en", "url": "https://stackoverflow.com/questions/61492761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make New Relic Track only one JBoss web app I currently have 3 web apps running on a single JBoss 7.1 container. I've successfully installed newrelic but it's currently monitoring all 3 web apps. Is there a way to make newrelic only monitor one web app? A: There's a good deal of customization available to control what app names traffic is reported to and whether particular transactions are reported to New Relic. But if you're currently seeing three different app names appearing under the 'Applications' menu, the easiest thing to do is just click the gear icon and select 'hide app' Beyond that, an API call can cause any selected transactions to be ignored by the agent. https://newrelic.com/docs/java/java-agent-api And if that doesn't have it resolved, you'll need to open a ticket at support.newrelic.com so we can take a look at your dashboard/setup.
{ "language": "en", "url": "https://stackoverflow.com/questions/19171648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I compare two lists in python and return matches I want to take two lists and find the values that appear in both. a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) would return [5], for instance. A: I prefer the set based answers, but here's one that works anyway [x for x in a if x in b] A: Not the most efficient one, but by far the most obvious way to do it is: >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) {5} if order is significant you can do it with list comprehensions like this: >>> [i for i, j in zip(a, b) if i == j] [5] (only works for equal-sized lists, which order-significance implies). A: Use set.intersection(), it's fast and readable. >>> set(a).intersection(b) set([5]) A: Can use itertools.product too. >>> common_elements=[] >>> for i in list(itertools.product(a,b)): ... if i[0] == i[1]: ... common_elements.append(i[0]) A: You can use def returnMatches(a,b): return list(set(a) & set(b)) A: You can use: a = [1, 3, 4, 5, 9, 6, 7, 8] b = [1, 7, 0, 9] same_values = set(a) & set(b) print same_values Output: set([1, 7, 9]) A: One more way to find common values: a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] matches = [i for i in a if i in b] A: If you want a boolean value: >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b) False >>> a = [3,1,2] >>> b = [1,2,3] >>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b) True A: a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] lista =set(a) listb =set(b) print listb.intersection(lista) returnMatches = set(['5']) #output print " ".join(str(return) for return in returnMatches ) # remove the set() 5 #final output A: Quick way: list(set(a).intersection(set(b))) A: The easiest way to do that is to use sets: >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) set([5]) A: >>> s = ['a','b','c'] >>> f = ['a','b','d','c'] >>> ss= set(s) >>> fs =set(f) >>> print ss.intersection(fs) **set(['a', 'c', 'b'])** >>> print ss.union(fs) **set(['a', 'c', 'b', 'd'])** >>> print ss.union(fs) - ss.intersection(fs) **set(['d'])** A: Also you can try this,by keeping common elements in a new list. new_list = [] for element in a: if element in b: new_list.append(element) A: A quick performance test showing Lutz's solution is the best: import time def speed_test(func): def wrapper(*args, **kwargs): t1 = time.time() for x in xrange(5000): results = func(*args, **kwargs) t2 = time.time() print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0) return results return wrapper @speed_test def compare_bitwise(x, y): set_x = frozenset(x) set_y = frozenset(y) return set_x & set_y @speed_test def compare_listcomp(x, y): return [i for i, j in zip(x, y) if i == j] @speed_test def compare_intersect(x, y): return frozenset(x).intersection(y) # Comparing short lists a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] compare_bitwise(a, b) compare_listcomp(a, b) compare_intersect(a, b) # Comparing longer lists import random a = random.sample(xrange(100000), 10000) b = random.sample(xrange(100000), 10000) compare_bitwise(a, b) compare_listcomp(a, b) compare_intersect(a, b) These are the results on my machine: # Short list: compare_bitwise took 10.145 ms compare_listcomp took 11.157 ms compare_intersect took 7.461 ms # Long list: compare_bitwise took 11203.709 ms compare_listcomp took 17361.736 ms compare_intersect took 6833.768 ms Obviously, any artificial performance test should be taken with a grain of salt, but since the set().intersection() answer is at least as fast as the other solutions, and also the most readable, it should be the standard solution for this common problem. A: Do you want duplicates? If not maybe you should use sets instead: >>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5])) set([5]) A: another a bit more functional way to check list equality for list 1 (lst1) and list 2 (lst2) where objects have depth one and which keeps the order is: all(i == j for i, j in zip(lst1, lst2)) A: Using __and__ attribute method also works. >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a).__and__(set(b)) set([5]) or simply >>> set([1, 2, 3, 4, 5]).__and__(set([9, 8, 7, 6, 5])) set([5]) >>> A: The following solution works for any order of list items and also supports both lists to be different length. import numpy as np def getMatches(a, b): matches = [] unique_a = np.unique(a) unique_b = np.unique(b) for a in unique_a: for b in unique_b: if a == b: matches.append(a) return matches print(getMatches([1, 2, 3, 4, 5], [9, 8, 7, 6, 5, 9])) # displays [5] print(getMatches([1, 2, 3], [3, 4, 5, 1])) # displays [1, 3] A: you can | for set union and & for set intersection. for example: set1={1,2,3} set2={3,4,5} print(set1&set2) output=3 set1={1,2,3} set2={3,4,5} print(set1|set2) output=1,2,3,4,5 curly braces in the answer. A: I just used the following and it worked for me: group1 = [1, 2, 3, 4, 5] group2 = [9, 8, 7, 6, 5] for k in group1: for v in group2: if k == v: print(k) this would then print 5 in your case. Probably not great performance wise though. A: This is for someone who might what to return a certain string or output, here is the code, hope it helps: lis =[] #convert to list a = list(data) b = list(data) def make_list(): c = "greater than" d = "less_than" e = "equal" for first, first_te in zip(a, b): if first < first_te: lis.append(d) elif first > first_te: lis.append(c) else: lis.append(e) return lis make_list()
{ "language": "en", "url": "https://stackoverflow.com/questions/1388818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "516" }
Q: Can I serialize an object if I didn't write the class used to instantiate that object? I've a simple class [Serializable] public class MyClass { public String FirstName { get; set: } public String LastName { get; set: } //Bellow is what I would like to do //But, it's not working //I get an exception ContactDataContext db = new ContactDataContext(); public void Save() { Contact contact = new Contact(); contact.FirstName = FirstName; contact.LastName = LastName; db.Contacts.InsertOnSubmit(contact); db.SubmitChanges(); } } I wanted to attach a Save method to the class so that I could call it on each object. When I introduced the above statement which contains ContactDataContext, I got the following error "In assembly ... PublicKeyToken=null' is not marked as serializable" It's clear that the DataContext class is generated by the framework (). I checked and did not see where that class was marked serialize. What can I do to overcome that? What's the rule when I'm not the author of a class? Just go ahead and mark the DataContext class as serializable, and pretend that everything will work? Thanks for helping A: It might be worth taking a step back and seeing if what you want to achieve is really valid. Generally, a serializable class is used for data transport between two layers. It is more likely to be a simple class that only holds data. It seems a little out of place for it to hold the ability to persist to a database. It is not likely that both ends of the pipe actually have access to the database, and it seems very unlikely that they would both have the ability to persist data. I wonder if it's worth factoring the save out to a repository. So have a repository class that will accept the data transfer object, construct the database object and save it. This will simplify your code and completely avoid the problem you're having. It will also greatly enhance testability. A: The problem is that the db field gets serialized, while clearly it doesn't need to be serialized (it's instantiated once the object is created). Therefore, you should decorate it with the NonSerialized attribute: [NonSerialized] ContactDataContext db = new ContactDataContext(); [Update] To make sure the db field is accesable after object initialization, you should use a lazy loading property and use this property instead of the field: [NonSerialized] ContactDataContext db = null; [NonSerialized] private ContactDataContext { get { if (db == null) { db = new ContactDataContext(); } return db; } set { db = value; } } public void Save() { Contact contact = new Contact(); contact.FirstName = FirstName; contact.LastName = LastName; Db.Contacts.InsertOnSubmit(contact); Db.SubmitChanges(); } [Update2] You can serialize most objects, as long as it has a public parameterless constructor (or no constructor at all) and no properties/fields that cannot be serialized but require serializing. If the class itself is not marked as [Serializable], then you can do this yourself using a partial class. If the class has properties/fields that cannot be serialized, then you might achieve this by inheriting the class and overriding these properties/fields to decorate them as [NonSerialized]. A: You can create a surrogate that knows how to serialize the dodgy classes - see here for an example A: I think you do need to decorate the base class, however, the DataContext auto generated classes are marked as partial. Have you tried doing something like: [Serializable] public partial class ContactDataContext { } Not sure if it would work but its worth a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/2646065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C how to handle malloc returning NULL? exit() or abort() When malloc() fails, which would be the best way to handle the error? If it fails, I want to immediately exit the program, which I would normally do with using exit(). But in this special case, I'm not quite sure if exit() would be the way to go here. A: If malloc() returns NULL it means that the allocation was unsuccessful. It's up to you to deal with this error case. I personally find it excessive to exit your entire process because of a failed allocation. Deal with it some other way. A: In library code, it's absolutely unacceptable to call exit or abort under any circumstances except when the caller broke the contact of your library's documented interface. If you're writing library code, you should gracefully handle any allocation failures, freeing any memory or other resources acquired in the attempted operation and returning an error condition to the caller. The calling program may then decide to exit, abort, reject whatever command the user gave which required excessive memory, free some unneeded data and try again, or whatever makes sense for the application. In all cases, if your application is holding data which has not been synchronized to disk and which has some potential value to the user, you should make every effort to ensure that you don't throw away this data on allocation failures. The user will almost surely be very angry. It's best to design your applications so that the "save" function does not require any allocations, but if you can't do that in general, you might instead want to perform frequent auto-save-to-temp-file operations or provide a way of dumping the memory contents to disk in a form that's not the standard file format (which might for example require ugly XML and ZIP libraries, each with their own allocation needs, to write) but instead a more "raw dump" which you application can read and recover from on the next startup. A: Use Both? It depends on whether the core file will be useful. If no one is going to analyze it, then you may as well simply _exit(2) or exit(3). If the program will sometimes be used locally and you intend to analyze any core files produced, then that's an argument for using abort(3). You could always choose conditionally, so, with --debug use abort(3) and without it use exit.
{ "language": "en", "url": "https://stackoverflow.com/questions/4287964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHP readdir while loop don't work cleanly I wrote a short php code that displays an image and the titke to every file in a directory. The problem is that if i run the code many files get the a instead of an image. So for example a .zip file is in front of a .txt file. Now it will display the of the txt file instead of the .zip image. The code: $file_dir = "upload/demofiles"; if ($handle = opendir($file_dir)) { $i = 1; while (false !== ($entry = readdir($handle))) { $format = pathinfo($entry, PATHINFO_EXTENSION); $file_path = $file_dir.'/'.$entry; if($format == "txt"){ $myfile = fopen($file_path, "r") or die("Unable to open file!"); $file_element = '<iframe src="'.$file_path.'" width="80px" style="height:80px" scrolling="no"></iframe>'; } if($format == "png"){ $myfile = fopen($file_path, "r") or die("Unable to open file!"); $file_element = '<img src="'.$file_path.'" />'; } if($format == "zip"){ $myfile = fopen($file_path, "r") or die("Unable to open file!"); $file_element = '<img width="64px" class="img" src="icons/zip.png" />'; fclose($myfile); } if($format == "pdf"){ $file_element = '<embed src="'.$file_path.'" width="80px" scrolling="no" style="height:80px">'; } if(!isset($file_element)){ $file_element = '<img class="img" width="64px" src="icons/file.png">'; } if ($entry != "." && $entry != "..") { echo '<label style="display:inline-block; border:solid 1px;"> <div>'.$file_element.'</div> <div>'.$entry.'</div> </label>'; } $i++; } } why does this happend? I think the variables should be cleared after on loop run. Thank you! A: Try this code: $file_dir = "upload/demofiles"; if ($handle = opendir($file_dir)) { $i = 1; while (false !== ($entry = readdir($handle))) { $format = pathinfo($entry, PATHINFO_EXTENSION); $file_path = $file_dir.'/'.$entry; switch($format){ case "txt": $myfile = fopen($file_path, "r") or die("Unable to open file!"); $file_element = '<iframe src="'.$file_path.'" width="80px" style="height:80px" scrolling="no"></iframe>'; break; case "png": $myfile = fopen($file_path, "r") or die("Unable to open file!"); $file_element = '<img src="'.$file_path.'" />'; break; case "zip": $myfile = fopen($file_path, "r") or die("Unable to open file!"); $file_element = '<img width="64px" class="img" src="icons/zip.png" />'; fclose($myfile); break; case "pdf": $file_element = '<embed src="'.$file_path.'" width="80px" scrolling="no" style="height:80px">'; break; default: $file_element = '<img class="img" width="64px" src="icons/file.png">'; break; } if ($entry != "." && $entry != "..") { echo '<label style="display:inline-block; border:solid 1px;"> <div>'.$file_element.'</div> <div>'.$entry.'</div> </label>'; } $i++; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/32280494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Use config file in App\Libraries Laravel i have one non-laravel library at the App\Libraries and there i have file providers.php <?php return [ 'slsp'=> [ 'SLSP_SPOROPAY_PU_PREDCISLO'=> '000000', 'SLSP_SPOROPAY_PU_CISLO'=> '0013662162', 'SLSP_SPOROPAY_PU_KBANKY'=> '0900', 'SLSP_SPOROPAY_SHAREDSECRET'=> 'Z3qY08EpvLlAAoMZdnyUdQ==', 'SLSP_SPOROPAY_REDIRECTURLBASE'=> 'http://epaymentsimulator.monogram.sk/SLSP_SporoPay.aspx', ], 'paypal'=>[ 'PAYPAL_USERNAME'=>'xxx', 'PAYPAL_PASSWORD'=>'xxx', 'PAYPAL_SIGNATURE'=>'xxxx', 'PAYPAL_CONNECTIONTIMEOUT'=>'3333', 'PAYPAL_RETRY'=>'true', 'PAYPAL_OGENABLED'=>'true', 'PAYPAL_FILENAME'=>'foo/bar', 'PAYPAL_LOGLEVEL'=>'5', ] ]; and than i would like get and set this value like Config::get('providers.paypal.username'); Config::set('providers.paypal.username', 'someName'); What i must do when i want using it? Thank you A: Better approach would be to create a laravel provider and register the provider in app providers. For Example: In your case php artisan make:provider EPaymentProvider It will create a provider file EPaymentProvider.php in providers directory. Now modify your Library/EPayment.php file like this <?php class EPayment { private static $_instance = 'null'; public $credentials = [ 'PAYPAL_USERNAME'=>'xxx', 'PAYPAL_PASSWORD'=>'xxx', 'PAYPAL_SIGNATURE'=>'xxxx', 'PAYPAL_CONNECTIONTIMEOUT'=>'3333', 'PAYPAL_RETRY'=>'true', 'PAYPAL_OGENABLED'=>'true', 'PAYPAL_FILENAME'=>'foo/bar', 'PAYPAL_LOGLEVEL'=>'5', ]; /** * @param array $array */ public function setPayPalCredential(array $array){ $this->credentials = $array; } /** * @return EPayment|string */ public static function PayPal(){ if(self::$_instance === 'null') self::$_instance = new self; return self::$_instance; } /** * @param $key * @return mixed */ public function getPayPalCredential($key){ return $this->credentials[$key]; } } and in register method of EPaymentProvider.php add Libraries/EPayment.php <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class HelperServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { require base_path().'/app/Libraries/EPayment.php'; } } Now add EPaymentProvider in config/app.php Provider array Now you can use Epayment::PayPal()->setPayPalCredential(['PAYPAL_USERNAME' => 'New Username']); and Epayment::PayPal()->getPayPalCredential('PAYPAL_USERNAME') let me know if it worked. A: First the file is outside the config folder so it wont be possible to set or get using the Config facade. To still use the providers file move it to the config directory and everything will work for you. A: To retrieve config values using dot notation, you can do the following in providers.php: $paypalArray = ['paypal' => [ 'PAYPAL_USERNAME'=>'xxx', 'PAYPAL_PASSWORD'=>'xxx', 'PAYPAL_SIGNATURE'=>'xxxx', 'PAYPAL_CONNECTIONTIMEOUT'=>'3333', 'PAYPAL_RETRY'=>'true', 'PAYPAL_OGENABLED'=>'true', 'PAYPAL_FILENAME'=>'foo/bar', 'PAYPAL_LOGLEVEL'=>'5'] ]; config($paypalArray); Now you can retrieve values like config('paypal.PAYPAL_USERNAME').
{ "language": "en", "url": "https://stackoverflow.com/questions/35420115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }