text
stringlengths
64
89.7k
meta
dict
Q: How to Tell If an Object Has Been Garbage Collected How I can know to tell if an Object has been garbage collected or not? A: According to this: You normally can’t tell whether an object has been garbage collected by using some reference to the object–because once you have a reference to the object, it won’t be garbage collected. You can instead create a weak reference to an object using the WeakReference object. The weak reference is one that won’t be counted as a reference, for purposes of garbage collection. In the code below, we check before and after garbage collection to show that a Dog object is garbage collected. Dog dog = new Dog("Bowser"); WeakReference dogRef = new WeakReference(dog); Console.WriteLine(dogRef.IsAlive); dog = null; GC.Collect(); Console.WriteLine(dogRef.IsAlive);
{ "pile_set_name": "StackExchange" }
Q: Navigation bar influence UITableViewController I have a UITableViewController connected with a UINavigationController in my storyboard. when I scroll down my table I can see the rows going to the back side to the "navigation bar". Making a brief check, I realized that the navigation bar are not influencing the table size (It appears that the navigation bar is in front of my table). Since when I select the table size: -(CGFloat)tableView:(UITableView *)tableViews heightForRowAtIndexPath:(NSIndexPath *)indexPath{ CGFloat value = tableViews.frame.size.height; NSLog(@"Table size -> %f",value); return value/2; } He returns the same size os my window... what I could do to make the "navigation bar" to influence the size of my table? A: You have a few options. Try one of the following: Subtract the height of the nav bar and status bar from the table view frame height. CGFloat value = tableViews.frame.size.height - CGRectGetMaxY(self.navigationController.navigationBar.frame); Don't put the table view behind the navigation bar. Fix this by adding the following line to your table view controller's viewDidLoad: self.edgesForExtendedLayout = UIRectEdgeLeft | UIRectEdgeRight; This prevents the table view from going under the nav bar or toolbar. One more note. If you want all rows to have the same height, don't implement the heightForRowAtIndexPath method. Instead, simply set the table view's rowHeight property.
{ "pile_set_name": "StackExchange" }
Q: Apscheduler runs once then throws TypeError I'm trying to add a list of someone's soundcloud followers to a database every hour. I have the code working to pull their list of followers and add them to a db, but I run into errors when I use it with apscheduler. Here's an example of the error: Traceback (most recent call last): File "desktop/SoundcloudProject/artistdailyfollowers.py", line 59, in <module> scheduler.add_job(inserttodaysdata(), 'interval', hours=1) File "//anaconda/lib/python3.5/site-packages/apscheduler/schedulers/base.py", line 425, in add_job job = Job(self, **job_kwargs) File "//anaconda/lib/python3.5/site-packages/apscheduler/job.py", line 44, in __init__ self._modify(id=id or uuid4().hex, **kwargs) File "//anaconda/lib/python3.5/site-packages/apscheduler/job.py", line 165, in _modify raise TypeError('func must be a callable or a textual reference to one') TypeError: func must be a callable or a textual reference to one Here's the code: import soundcloud import sqlite3 import datetime import time from apscheduler.schedulers.blocking import BlockingScheduler client = soundcloud.Client(client_id='f3b669e6e4509690939aed943c56dc99') conn = sqlite3.connect('desktop/SoundcloudProject/RageLogic.db') c = conn.cursor() writenow = datetime.datetime.now() print("If this is printing that means it's running") print("The time is now: \n" +str(writenow)) page ='https://soundcloud.com/ragelogic' page_size = 200 def create_table(): c.execute('CREATE TABLE IF NOT EXISTS RageLogicFollowersByDay(day TEXT, list_of_followers TEXT)') #add todays date and a list of followers to the db def inserttodaysdata(): global page full = False user = client.get('/resolve', url=page) ufollowing = [] ufirstfollowing = client.get('/users/'+str(user.id)+'/followers', order='id',limit=page_size, linked_partitioning=1) for user in ufirstfollowing.collection: ufollowing.append(user.id) if hasattr(ufirstfollowing, "next_href"): #print("MANYFOLLOWING") newlink = ufirstfollowing.next_href try: while full == False: newlist = client.get(newlink) for user in newlist.collection: ufollowing.append(user.id) print(len(ufollowing)) if newlist.next_href == None: print("full") full = True else: newlink = newlist.next_href except AttributeError: None #print(len(ufollowing)) wtl = [] wtl = repr(ufollowing) writenow = datetime.datetime.now() c.execute("INSERT INTO RageLogicFollowersByDay (day, list_of_followers) VALUES (?, ?)",(str(writenow), wtl)) conn.commit() #create_table() scheduler = BlockingScheduler() scheduler.add_job(inserttodaysdata(), 'interval', hours=1) scheduler.start() I'm really new to this whole thing and any help anyone could give would be awesome, thanks! A: See this line: scheduler.add_job(inserttodaysdata(), 'interval', hours=1) and it should be scheduler.add_job(inserttodaysdata, 'interval', hours=1) You're calling inserttodaysdata() and passing its return value to add_job(). Don't do that. Pass the function itself, not its call result.
{ "pile_set_name": "StackExchange" }
Q: Extending Django templates with a form I have a simple note taking part of my application that I want to combine into one html page. One page has the form to submit the notes, while the other displays the results. I'd like to have both the form and results on the same page. I'm attempting to use Django's template inheritance to achieve this, but the results aren't working as planned. When using it the way (obviously improperly) I have, the results do not show up and only the "submit" button from the form is displayed; not the actual form. This should be fairly simple but I've tried several variations and researched potential solutions and template documentation for hours with no success. If there's anyone who can illustrate what I'm doing incorrectly, it would be very appreciated. Here's the code with the basic form template: {% extends 'base.html' %} {% block page_title %}Notebook{% endblock %} {% block headline %}Notebook{% endblock %} {% block content %} <h2>Headline</h2> <div class="row"> <div class="span8"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary" value="Submit" /> </form> </div> </div> {% endblock %} And here's the attemtped extended form that would ideally contain both the form and the results: {% extends 'report/write_note.html' %} {% block extendscontent %} <div class="span4 offset8"> {% if notes %} {% for note in user.notes.all reversed %} <h3>{{ note.title }}</h3> <p>{{ note.date }}</p> <p>{{ note.copy }}</p> {% endfor %} {% else %} <p>You have no notes stored.</p> {% endif %} </div> {% endblock extendscontent %} And here are the views: @login_required def submit_note(request): if request.method == 'POST': notes_form = NotesForm(request.POST, request.FILES) if notes_form.is_valid(): new_note = notes_form.save(commit=False) new_note.author = request.user new_note.save() return HttpResponseRedirect( "" ) else: notes_form = NotesForm() return render_to_response("report/write_note.html", {'form': notes_form}, context_instance=RequestContext(request)) @login_required def all_notes(request): all_notes = Notes.objects.all().order_by('-date') paginate = paginated_stories(request, all_notes) return render_to_response("report/notes.html", {'notes': paginate}, context_instance=RequestContext(request)) A: I think you can have both form and notes on a same page by combining your views. ie something like - @login_required def notes_view(request): all_notes = Notes.objects.all().order_by('-date') paginate = paginated_stories(request, all_notes) # form processing and other code # ------------------------------- # return both form and notes to your template context return render_to_response("report/notes.html",{ 'notes': paginate, 'form': notes_form, },context_instance=RequestContext(request)) Or you can create a custom templatetag either for rendering notes or notes_form
{ "pile_set_name": "StackExchange" }
Q: SQL query with optional parameters in a related table I have a schema similar to this: Person ---------------- Id (PK) Name EventRegistration ---------------- EventId (PK, FK) PersonId (PK, FK) DateRegistered -- EDIT: Note that a single person can registered for multiple events. I need to write a query that searches for names of all people who registered for any events that occurred within a provided date range (i.e. DateRegistered should fall within DateRangeStart and DateRangeEnd). The trick is, the input parameters are optional. So you could define both, only start date, only end date, or neither. These would be interpreted, respectively, as "everything within this range," "everything on/after this date," "everything on/before this date," and "all people regardless of any event registrations." So I came up with something that works, but I was wondering if I could get some help improving this: -- Assume parameters @DateRangeStart and @DateRangeEnd (both date) are provided by user input SELECT p.Name FROM Person p WHERE (@DateRangeStart IS NULL OR EXISTS ( SELECT TOP 1 PersonId FROM EventRegistration WHERE PersonId = p.Id AND DateRegistered >= @DateRangeStart AND (@DateRangeEnd IS NULL OR DateRegistered <= @DateRangeEnd) ) ) AND (@DateRangeEnd IS NULL OR EXISTS ( SELECT TOP 1 PersonId FROM EventRegistration WHERE PersonId = p.Id AND (@DateRangeStart IS NULL OR DateRegistered >= @DateRangeStart) AND DateRegistered <= @DateRangeEnd ) ) A: Something like this should work: SELECT DISTINCT p.Name FROM Person p LEFT JOIN EventRegistration e ON p.Id = e.PersonId WHERE (@DateRangeStart IS NULL OR DateRegistered >= @DateRangeStart) AND (@DateRangeEnd IS NULL OR DateRegistered <= @DateRangeEnd)
{ "pile_set_name": "StackExchange" }
Q: R - extract georeferenced raster pixel color I would like to extract the color values for each pixel of a georeferenced raster image using R. I need those pixel colors later to plot a tif (or geotif) as mentioned in a previous question (see R - original colours of georeferenced raster image using ggplot2- and raster-packages). Due to the fact that raster images with data-band cannot implicitly use the band-values to assign colors to them (not able to represent pattern fills), I defenitely need those pixel colors. I already know how to access the colortable where all possible 256 colors are listed in a vector. However, they are not mapped in this form. Here is the code which I use to load the raster image and extract the unmapped colortable: raster1 <- raster(paste( workingDir, "/HUEK200_Durchlaessigkeit001_proj001.tif", sep="", collapse="")) raster1.pts <- rasterToPoints(raster1) raster1.df <- data.frame(raster1.pts) colTab <- attr(raster1, "legend")@colortable Thank you for your help! A: I have posted an answer under the question which I have cited in my question here. The solution applies to both question-threads, so I don't repeat it here completely: R - original colours of georeferenced raster image using ggplot2- and raster-packages It turned out, that the first data-band of my spatial raster image object exactly reflected the colors. I used a vector of with all unique possible values in the raster to reference to the respective colors in colTab. This is not directly possible because values starting from 0 which is not a valid index in R. I simply introduced named indices to cope with it. Now, only colors with indices listed in valTab will be passed as colours-parameter for the scaled fill and the plotted result is the georeferenced raster image with its original colors.
{ "pile_set_name": "StackExchange" }
Q: How can I increase my reputation? Am I being penalized for asking about an obscure programming language? I don't care so much about my reputation, it's just I cannot vote for people who had helped me. So what can I do to increase my reputation? A: You ask a lot of questions, but you never answer anything. Good answers will gain you rep a lot faster than asking questions. A: Here is how to gain reputation. For example you might start accepting answers, they will earn you 2 points: How does "Reputation" work? A: I feel your pain. I'm using a relatively unused programming language too. You can answer general questions. It doesn't matter what language you're using for questions about preferred software, algorithms, etc. It's harder work to get points on these questions, (as they're applicable to everyone, tend to go to community status, and encourage bikeshedding), but it can be done. You can push stackoverflow to other members of your community. Your particular programming language will have places on the web where users hang out, and you can tell those users to come over here. You can do what the R guys did, and organise a [your language] flash mob. This is encouraged behaviour, and can help move a community over from wherever to this site. http://en.oreilly.com/oscon2009/public/schedule/detail/10432 For me - I'm pretty certain I can't get the questions and answers for my language moved from the forum they use over here. In this situation, you may have to accept that stackoverflow is not for you.
{ "pile_set_name": "StackExchange" }
Q: Remove trailing numbers from string js regexp I am trying to remove the trailing numbers from the string using JavaScript RegExp. Here is the example. Input output ------------------------- string33 => string string_34 => string_ str_33_ing44 => str_33_ing string => string Hope above example clears what I am looking for! A: You could use this regex to match all the trailing numbers. \d+$ Then remove the matched digits with an empty string. \d+ matches one or more digits. $ asserts that we are at the end of a line. string.replace(/\d+$/, "") A: Use .replace(): "string".replace(/\d+$/, '') A simple demo jsfiddle: http://jsfiddle.net/v8xvrze0/
{ "pile_set_name": "StackExchange" }
Q: Does HttpRuntime.Cache Compress Objects in Cache? I need to store several large strings and objects with large string properties in the HttpRuntime.Cache Does the HttpRuntime.Cache compress objects it stores? A: No it does not, The objects that are stored in the cache aren't serialized so it can't really compress them. See What is the default serialization used by the ASP.net HttpRuntime.Cache.
{ "pile_set_name": "StackExchange" }
Q: Puppeteer saved PNG is NOT transparent I am using Puppeteer to screen capture an HTML element with ID name. The HTML element is with border-radius: 50px and I set Puppeteer with omitBackground: true. The Saved PNG result gave me is a WHITE background, looks like it captured the BODY WHITE background. puppeteer: v1.13.0 Any ideas? A: If the page has a background color you want to remove that, and then use the omitBackground: true option of page.screenshot: await page.evaluate(() => document.body.style.background = 'transparent'); await page.screenshot({ path: 'example.png', omitBackground: true, });
{ "pile_set_name": "StackExchange" }
Q: Changing Component Background color dynamically with wait() I'm trying to do a funny JFrame so when mouse leaves the window, it changes the Panel Background color to some random colors (To gain user attention): wnd.addMouseListener(new MouseAdapter(){ @Override public synchronized void mouseExited(MouseEvent e){ cond = true; while(cond){ try{ wnd.getContentPane().setBackground(Color.getHSBColor((cont+=0.05), 1, 1)); wnd.setTitle("Num: "+cont); wnd.getContentPane().repaint(); //With or without it doesn't work either wait(100); } catch(InterruptedException ex){ Thread.currentThread().interrupt(); } } } }); The problem is that Background color doesn't change... It shows me the values of cont in the window title but color doesn't change. If I remove the cycle and just move the mouse inside and outside the panel, it changes... But I want to make it that when mouse leaves the window, it keeps changing the colors automatically until mouse gets back to it. Some kind of epilepsy (?) I don't know why if I cycle it and make a delay with wait() it doesn't work. A: Swing is a single threaded framework, this means that anything to blocks the Event Dispatching Thread, will prevent it from processing the Event Queue (including repaint requests) and cause the application to appear as it has hung, cause it has. You should never perform long running or blocking operations from within the context of the EDT. Instead, in this case, you should use a Swing Timer to schedule a regular callback. The benefit of this is that the callback is executed from within the context of the EDT, making it safe to use to update the UI (as Swing is also not thread safe). import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class Test { public static void main(String[] args) { new Test(); } public Test() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private Timer updateTimer; public TestPane() { updateTimer = new Timer(100, new ActionListener() { private float cont = 0; @Override public void actionPerformed(ActionEvent e) { setBackground(Color.getHSBColor((cont += 0.05), 1, 1)); } }); addMouseListener(new MouseAdapter() { @Override public void mouseExited(MouseEvent e) { updateTimer.start(); } @Override public void mouseEntered(MouseEvent e) { updateTimer.stop(); } }); } @Override public Dimension getPreferredSize() { return new Dimension(200, 200); } } } Take a look at Concurrency in Swing and How to use Swing Timers for more details
{ "pile_set_name": "StackExchange" }
Q: Installing R from cmd Can I configure the R installation from Windows cmd? C:\R-3.3.1-win.exe /silent Gives me a standard silent install, but: C:\R-3.3.1-win.exe /help gives me no information. Also /? says nothing. A: Solution, first determine the configurations for the installer: C:\R-3.3.1-win.exe /SAVEINF=config This will save those configurations in a file named config. To load those configurations on the installer use: R-3.3.2-win.exe /SILENT /LOADINF=config
{ "pile_set_name": "StackExchange" }
Q: How to extract words from the string in python? I have strings of the form sent="Software Development = 1831". I want to extract only words from the string i.e. "Software Development". How I can extract this in Python. A: You can try split : >>> sent="Software Development = 1831" >>> sent.split("=")[0] 'Software Development '
{ "pile_set_name": "StackExchange" }
Q: Why elem_match is returning 0 elements? I am trying to get one record result from a collection of objects, but after following the Mongoid documentation I don't know what more to try. I have this single element: > contacts => #<Contact _id: 55ace6bc6xx, device_fields: {"app_id"=>"55ace6bc65195efc8200xxxx"}, created_at: 2015-07-20 12:17:00 UTC, updated_at: 2015-07-20 12:17:00 UTC, name_first: "Kory", name_last: "Funk", ...> this list of matchers: > apps = [] > apps << App.where(id: "55ace6bc65195efc8200xxxx").first.id => ["55ace6bc65195efc8200xxxx"] And this code trying to get the elements that match: > contacts.elem_match(device_fields: {:app_id.in => apps }).to_a => [] > contacts.elem_match(device_fields: { "app_id": "55ace6bc65195efc8200xxxx"}).to_a => [] Why is it returning an empty array it there is one that matches? A: According to official mongodb manual The $elemMatch operator matches documents that contain an array field And you are trying to use it with the hash field so you basically misunderstood this selection. So there is no object that matches. Instead of it you should do: contacts.where(:'device_fields.app_id'.in => apps).to_a
{ "pile_set_name": "StackExchange" }
Q: Serilog destructuring operator - does it destructure ahead of log level check I am trying to understand the performance impact of serilog destructuring operator, specifically to verify that destructure is not performed before the logger checks if the intended message can even be logged. For example, the following code: var sensorInput = new { Latitude = 25, Longitude = 134 }; Log.Debug("Processing {@SensorInput}", sensorInput); should not result in something like: var tmp = destructure(sensorInput); readonly bool _isDebug = Log.IsEnabled(LogEventLevel.Debug); if (_isDebug) Log.Debug("Processing {var1}", tmp); I did check the Serilog source code but I haven't found anything which would confirm the above is not happening - perhaps someone knows the relevant code? A: Serilog will only apply destructuring if the event is enabled. Debug() calls Write(), which does a level check before any more work is performed.
{ "pile_set_name": "StackExchange" }
Q: How to setup a Bar Button with a value of firebase? I want to check if the user is a admin or not. If the user is a admin, I want to show a bar button. If not, the bar button should be hidden. I call the following code in viewDidLoad: @IBOutlet weak var beitraegeMelden: UIBarButtonItem! var admin = false func setupBarButton() { observeAdmin() if admin == true { self.beitraegeMelden.isEnabled = true self.navigationItem.rightBarButtonItem = self.beitraegeMelden } else { self.beitraegeMelden.isEnabled = false self.navigationItem.rightBarButtonItem = nil } } func observeAdmin() { guard let currentUserUid = UserApi.shared.CURRENT_USER_ID else { return } let REF_ADMIN = Database.database().reference().child("users").child(currentUserUid).child("admin") REF_ADMIN.observeSingleEvent(of: .value) { (admin) in let adminRecht = admin.value as? Bool if adminRecht == true { self.admin = true } else { self.admin = false } } } Here my database structure of the actually logged in user: users currentUid admin: true The admin value never gets true. Thanks in advance for your help! A: You need a completion as the call to firebase is asynchronous func observeAdmin(completion:@escaping((Bool) -> () )) { guard let currentUserUid = UserApi.shared.CURRENT_USER_ID else { return } let REF_ADMIN = Database.database().reference().child("users").child(currentUserUid).child("admin") REF_ADMIN.observeSingleEvent(of: .value) { (admin) in completion( (admin.value as? Bool) ?? false ) } } Call observeAdmin { (res) in self.beitraegeMelden.isEnabled = res self.navigationItem.rightBarButtonItem = res ? self.beitraegeMelden : nil }
{ "pile_set_name": "StackExchange" }
Q: What does "->" mean in objective-c? Well, I'm sorry I can't find any useful results when I search "->" on Google, and this is the first time I've seen anything like this. I've found the following line in one of Ray Wenderlich's game center tutorials: Message *message = (Message *)[data bytes]; if (message->messageType == kMessageTypeRandomNumber) { ... } Message here is a predefined struct: typedef struct { MessageType messageType; } Message; From http://www.raywenderlich.com/3325/game-center-tutorial-for-ios-how-to-make-a-simple-multiplayer-game-part-22. A: This means the same thing as it does in C and C++, basically you are accessing the data of a pointer. If you were using an object: you might say message.messageType Since you are dealing with a pointer: you use message->messageType to get the messageType data from the pointer message This syntax saves you from having to dereference a variable before you access its data. Here is a link to another StackOverFlow question which was asked from a programmer learning C. The same content/principles apply here. Arrow Operator Here is another link explaining the Difference Between . and ->
{ "pile_set_name": "StackExchange" }
Q: How can I retrieve a full list of account activities with the Dynamics CRM Views? Using the CRM views, is there a way to retrieve a list of all of the activities linked to a specific account? I want it to retrieve not only those associated with the account directly, but also those associated with the account's contacts, cases, etc. I am trying to replicate the list generated when you click the Activities option from within an account. So far I have retrieved the contacts for the account and their activities. I also noticed that CRM doesn't seem to always return what I expect. Sometimes activities related to contacts of the account are not displayed. Other times, emails / appointments that are logically related to the account but have nothing in their regardingobjectid field are shown. I am hoping this doesn't mean creating the mother of all joins or querying each activity type separately. Particularly because I need all of the related case activities, opportunity activities, etc. A: I've used something like this. Effectively I build a table var with all the guids of the items I want to search (in my case accounts and contacts) then I query AcitivtyParty for all activities where they are a party on the activity - then over to Activity to get the details. Declare @account_guid varchar(200) Select @account_guid = 'insert some guid here' Declare @GUIDS as Table(id varchar(200), fullname varchar(200), objecttype char(2)) Declare @ActivityIds as Table(id varchar(200)) --grab all guids we need activities for Insert Into @GUIDS Select contactid, fullname, 'C' From FilteredContact Where accountid = @account_guid UNION ALL Select accountid, [name], 'A' From FilteredAccount Where accountid = @account_guid --find all activities where the account/contact are referred to Insert Into @ActivityIds Select activityid From FilteredActivityParty fap Join @GUIDS g on g.id=fap.partyid Group By activityid Select * From FilteredActivityPointer fap Join @ActivityIds a on fap.activityid = a.id Where statecode<>2 --hide canceled items
{ "pile_set_name": "StackExchange" }
Q: Rango decimales Sql server Hola buen dia quiero saber como puedo hacer una condicion tengo este problema cuando en una consulta resto campo1-campo2 en la condicion debo traer solo cuando hay diferencias, sin embargo existe que la diferencia a veces me sale de 0.01 o -0.01 quiero que si sale eso como resultado lo ignore tengo la consulta de la siguiente forma: SELECT CAMPO1-CAMPO2 FROM RESTA WHERE (CAMPO1-CAMPO2)>0 quiero la consulta que me traiga si la renta hubo diferencia de 0 pero si hay entre un rango de 0.01 o negativo yo ignorarlo en la consulta, lo hice usando cast para trabajar con enteros pero no me sirver SELECT CAST((CAMPO1-CAMPO2) AS INT) FROM RESTA WHERE CAST((CAMPO1-CAMPO2) AS INT)>0 alguien que me ayude con otra forma de hacerlo A: Utiliza el valor absoluto ABS de la diferencia para filtrar y CAST para descartar los decimales SELECT CAST(CAMPO1 - CAMPO2 AS INT) FROM RESTA WHERE ABS(CAMPO1 - CAMPO2) > 0.01
{ "pile_set_name": "StackExchange" }
Q: Can't change the name of the downloaded file in DownloadManager class dynamically i'm using the Download Manager class to download Mp3 files . DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE); //dls is an arraylist that holds the download links Uri uri=Uri.parse(dls.get(0)); DownloadManager.Request request= new DownloadManager.Request(uri); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"file.mp3"); downloadManager.enqueue(request); the setDestinationInExternalPublicDir method requires a second parameter that will change the name of the downloaded file . I want the file to have its default name . If i dont use the method the file will have its default name but it wont be located in the Download directory . How can i achieve both , locate the file in the Download directory and leave the name of the file as it is ? thanks for help. A: Can you try this: public static String getFileNameFromURL(String url) { if (url == null) { return ""; } try { URL resource = new URL(url); String host = resource.getHost(); if (host.length() > 0 && url.endsWith(host)) { // handle ...example.com return ""; } } catch(MalformedURLException e) { return ""; } int startIndex = url.lastIndexOf('/') + 1; int length = url.length(); // find end index for ? int lastQMPos = url.lastIndexOf('?'); if (lastQMPos == -1) { lastQMPos = length; } // find end index for # int lastHashPos = url.lastIndexOf('#'); if (lastHashPos == -1) { lastHashPos = length; } // calculate the end index int endIndex = Math.min(lastQMPos, lastHashPos); return url.substring(startIndex, endIndex); } This method can handle these type of input: Input: "null" Output: "" Input: "" Output: "" Input: "file:///home/user/test.html" Output: "test.html" Input: "file:///home/user/test.html?id=902" Output: "test.html" Input: "file:///home/user/test.html#footer" Output: "test.html" Input: "http://example.com" Output: "" Input: "http://www.example.com" Output: "" Input: "http://www.example.txt" Output: "" Input: "http://example.com/" Output: "" Input: "http://example.com/a/b/c/test.html" Output: "test.html" Input: "http://example.com/a/b/c/test.html?param=value" Output: "test.html" Input: "http://example.com/a/b/c/test.html#anchor" Output: "test.html" Input: "http://example.com/a/b/c/test.html#anchor?param=value" Output: "test.html" You can find the whole source code here: https://ideone.com/uFWxTL
{ "pile_set_name": "StackExchange" }
Q: Is it possible to verify empty input from the user in spring boot? I'm writing a spring boot application and I'm having some troubles in verifying empty input from the user. Is there a way to validate an empty input from the user? For example: @PostMapping("/new_post/{id}") public int addNewPost(@PathVariable("id") Integer id, @RequestBody Post post) { return postService.addNewPost(id, post); }` Here I want to add a new post only if the user exists in the database but when I send this post request I am getting the regular 404 error message and I am not able to provide my own exception although in my code I validate if the id equals to null. http://localhost:8080/new_post/ Any idea what can I do? Thanks A: You can do something like this @PostMapping(value = {"/new_post/{id}", "/new_post"}) public int addNewPost(@PathVariable(required = false, name="id") Integer id, @RequestBody Post post) { return postService.addNewPost(id, post); } But the ideal way to handle this is using @RequestParam. @RequestParam is meant exactly for this purpose.
{ "pile_set_name": "StackExchange" }
Q: How to add new column name in existing table Currently I am trying to send email with csv file which includes data from a table, in csv file (not in the actual table database) I want add new column "cop" with some calculated value. I am able to add new data but I can not add column name to that column. I tried to use "AS" is not working .. SELECT $table_row, $cop_configure AS cop FROM data_to_use WHERE device_key = '$device_key' here pic of csv file what I am getting currently thanks... A: You have to Alter your exiting table and then add a new column ALTER TABLE `tablename` ADD cop VARCHAR(60);
{ "pile_set_name": "StackExchange" }
Q: using strtok in C to assign value to a structure i am receiving a default char array (first/last) in guest_init (and i need to initialize the values such that guest have default values ) is my following code correct? as when i run this g->first_name is always being assigned garbage. need some help. struct guest { char last_name[30]; char first_name[30]; }; struct auditorium_seating { struct guest **seating; }; void guest_init_default(struct guest *g) { *g->first_name = "???"; *g->last_name = "???"; } void guest_init(struct guest *g, char *info) { strcpy(g->first_name, strtok(info, "/")); strcpy(g->last_name, strtok(NULL, "\0")); } void auditorium_seating_init(int rowNum, int columnNum, struct auditorium_seating *a) { a->seating=malloc((sizeof(a->seating[rowNum][columnNum]))); char string_arr[30]="aaa/bbb"; for (int i = 0; i<rowNum; i++) { for (int j = 0; j<columnNum; j++) { //guest_init_default(a->seating); guest_init(a->seating,string_arr); } } } auditorium_seating_init being called from main. void main() { struct auditorium_seating auditorium_seating; struct guest temp_guest; int row, col, rowNum, columnNum; char guest_info[30]; printf("Please enter a number of rows for an auditorium seating."); scanf_s("%d", &rowNum); printf("Please enter a number of columns for an auditorium seating."); scanf_s("%d", &columnNum); auditorium_seating_init(rowNum, columnNum, &auditorium_seating); printf("Please enter a guest information or enter \"Q\" to quit."); } A: Enable your compiler warnings: *g->first_name = "???"; is wrong. And strtok(NULL, "\0")); is wrong too. You probably want this: #include <string.h> #include <stdio.h> struct guest { char last_name[30]; char first_name[30]; }; void guest_init(struct guest *g, char *info) { strcpy(g->first_name, strtok(info, "/")); strcpy(g->last_name, strtok(NULL, "/")); } int main() { struct guest g; char info[] = "Foo/Bar"; guest_init(&g, info); printf("Last Name = %s\n", g.last_name); printf("First Name = %s\n", g.first_name); } There may be more errors related to struct auditorium_seating *a, but you didn't post that code.
{ "pile_set_name": "StackExchange" }
Q: Modal view controller not in the window hierarchy The App I'm trying to do has a tabbar controller. When the App starts, I'm getting the user location in the AppDelegate and when I've got the accuracy I need the AppDelegate sends an NSNotification to my App's starting page (index 0 of the tab bar controller). Upon receiving the notification, this view tries to send an email with the user coordinates and other data, but as soon as the MFMailComposeViewController is presented I get the following error: Warning: Attempt to present <MFMailComposeViewController: 0x98a0270> on <UITabBarController: 0x988c630> whose view is not in the window hierarchy! What am I missing? Thanks. EDIT: adding some code... This is what I've got in my AppDelegate.m: - (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults]; NSDate *eventDate = newLocation.timestamp; NSTimeInterval howRecent = [eventDate timeIntervalSinceNow]; if (abs(howRecent) < 10.0) { [self locationUpdate:newLocation]; smsLoc = newLocation; if ([[phoneNumbers objectForKey:@"sendSMS"] isEqualToString:@"yes"]) { [[NSNotificationCenter defaultCenter] postNotificationName:@"sendSMS" object:nil]; } else if ([[phoneNumbers objectForKey:@"sendEmail"] isEqualToString:@"yes"]) { [[NSNotificationCenter defaultCenter] postNotificationName:@"sendEmail" object:nil]; } } } Then, in my first view controller I have: - (void)viewDidLoad { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendSMS:) name:@"sendSMS" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendEmail:) name:@"sendEmail" object:nil]; } And at the end, the selector for "sendSMS" (the other is pretty similar): - (void)sendSMS: (NSNotification *)notification { NSUserDefaults *phoneNumbers = [NSUserDefaults standardUserDefaults]; if ([phoneNumbers objectForKey:@"first"] || [phoneNumbers objectForKey:@"second"]) { MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init]; if ([MFMessageComposeViewController canSendText]) { AppDelegate *deleg = (AppDelegate *)[[UIApplication sharedApplication] delegate]; controller.body = [NSString stringWithFormat:@"some message with coordinates %.4f - %.4f", [deleg currentLocation].coordinate.latitude, [deleg currentLocation].coordinate.longitude]; controller.recipients = [NSArray arrayWithObjects:[phoneNumbers objectForKey:@"first"], [phoneNumbers objectForKey:@"second"], nil]; controller.messageComposeDelegate = self; [self presentModalViewController:controller animated:YES]; } } } } Second edit: adding some more code. UITabBarController *tabBarController = [[UITabBarController alloc] init]; tabBarController.delegate = self; tabBarController.selectedIndex = 0; [[tabBarController.tabBar.items objectAtIndex:0] setTitle:NSLocalizedString(@"Home", nil)]; [[tabBarController.tabBar.items objectAtIndex:1] setTitle:NSLocalizedString(@"Requests", nil)]; [[tabBarController.tabBar.items objectAtIndex:2] setTitle:NSLocalizedString(@"Account", nil)]; [[tabBarController.tabBar.items objectAtIndex:3] setTitle:NSLocalizedString(@"Settings", nil)]; //some other controls from DB [[tabBarController.tabBar.items objectAtIndex:1] setBadgeValue:[NSString stringWithFormat:@"%d",number]]; The tabbarController has been made via IB, but I've added the code above in my AppDelegate because I need to localize the tab bar items and to add a badge to one of them. Am I doing something wrong here? A: I'm not sure if you have solve this issue. The error message means the viewcontroller you use to present another modal viewcontroller is not visible on the window. This can happen for e.g: [VC1 presentModalViewController:VC2]; // Error here, since VC1 is no longer visible on the window [VC1 presentModalViewController:VC3]; If your issue is like above, you can fix it like: if (self.modalViewController != nil) { [self.modalViewController presentModalViewController:VC3 animated:YES]; } else { [self.tabBarController presentModalViewController:VC3 animated:YES]; } If that doesn't fix your issue, maybe you can try to present using self.tabBarController instead of self. Again just suggestion, not sure if it works though.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between phrase prosody and sentence prosody? What is the difference between phrase prosody and sentence prosody? I know that prosody is a phonological suprasegmental--its components, such as intonation, are more than one phoneme long. I know that possible components of prosody in a given language such as pitch, intonation contour, stress, and tempo can be modulated to convey lexical, syntactic, and pragmatic information. In English, for example, rising intonation is a prosodic cue that marks a lot of questions. I know that prosody can vary quite a bit across languages. For example, some languages don't have word stress, a fact mentioned in this paper: http://www.let.leidenuniv.nl/pdf/lucl/lwpl/1.1/roosman.pdf Note this definition of prosody: http://www.glottopedia.org/index.php/Prosody I've run across a reference to distinct phrase and sentence prosody in this conlang, http://yiklamu.ludiware.com/grammar.html But I can find darned little introductory information on natural language prosody on the Internet, let alone any typological information about it. Do any natural languages distinguish phrase and sentence prosody? Do most natural languages do so? Does this distinction occur in English? If so, what are some English examples? Also, where can I find more information about prosody on the Internet or in a still-available book? A: It is standard to talk about the prosodic hierarchy, which is a theoretical construct that divides utterances into smaller, phonologically relevant constituents called phrases, which are in turn divided into smaller constituents called prosodic words, and so on. There is not an absolute consensus as to what the exact levels of the prosodic hierarchy are or even how many there are, and (as with many theoretical constructs in linguistics) slightly different models lend themselves to different languages. For example, the mora is a prosodic unit that is more motivated in some languages than in others. Here is a (non-exhaustive) list of levels in the hierarchy: Utterance Phrase (some distinguish a major phrase and a minor phrase) Word Foot Syllable Mora Generally, each presumed level in the prosodic hierarchy is motivated by the observation that certain phonological processes (some may be prosodic in nature and others may be segmental) are associated with that constituent. For example, in standard Japanese there is a prosodic constituent called the accentual phrase, in which only one accented syllable may occur. If multiple words that are lexically accented are combined into a single accentual phrase, all but one of the accents gets deleted. Often, presumed prosodic constituents are motivated by more phonetic-y phenomena. For example, in English it is common to observe the lengthening of word-final, phrase-final, and utterance-final syllables. In many languages there is also a pitch reset (where the downward trend of the overall pitch range—sometimes called declination—stops and starts again at a higher pitch) at phrase boundaries. The usage of the term prosody in the conlang grammar you linked to is a bit confusing and seems to conflate prosody and intonation. It's not really that languages "distinguish" between "sentence" and "phrase" prosody; rather, as described above, different phonological and phonetic processes are observed to occur at different prosodic levels (i.e. over different prosodic constituents). Often-cited references for the prosodic hierarchy include those by Selkirk, Pierrehumbert and Beckman, and Hayes. I'm not sure how technical you want to get, but if you search for "prosodic hierarchy" online, you'll find links to online course materials that are relevant for your question.
{ "pile_set_name": "StackExchange" }
Q: How to handle scenario of same city with multiple names Ok, I have a list with some contacts on it filled by respective persons. But persons living in same city might write different names of cities(that I don't have any control on sice the names of cities may change with changing government). For example: NAME CITY John Banaglore Amit Bengaluru Here both the Bangalore and the Bengaluru refer to the same city. How can I make sure(my be programatically) that my system does not consider as two different cities but one, while traversing the list. One solution I could think of is to have a notion of unique ids attached to each city, but that requires recreating the list and also I have to train the my contacts about the unique id notion. Any thoughts are appreciated. Please feel free to route this post to any other stackexchange.com site if you think it does not belong here or update the tags. A: I would recommend creating a table alias_table which maps city aliases to a single common name: +------------+-----------+ | city_alias | city_name | +------------+-----------+ | Banaglore | Bangalore | | Bengaluru | Bangalore | | Bangalore | Bangalore | | Mumbai | Bombay | | Bombay | Bombay | +------------+-----------+ When you want do any manipulation of the table in your OP, you can join the CITY column to the city_alias column above as follows: SELECT * FROM name_table nt INNER JOIN alias_table at ON nt.CITY = at.city_alias
{ "pile_set_name": "StackExchange" }
Q: Найти математическое ожидание Знаю как находить из плотности, а тут что-то не понятно. Как тут найти ? A: Вектор (ξ, η) имеет дискретное распределение, поэтому через плотность посчитать не получится (плотность есть только у случайных величин, имеющих абсолютно непрерывное распределение). В дискретном случае математическое ожидание считается тоже просто, а именно, если случайная величина ξ принимает значения a_1, ..., a_n с вероятностями p_1, ..., p_n, то её математическое ожидание равно сумме величин a_i * p_i. Например, посчитаем Eη. η принимает значение -1/2 с вероятностью 1/12 + 0 + 1/12 = 1/6, и значение 1/2 с вероятностью 1/4 + 1/2 + 1/12 = 5/6. Таким образом, Eη = (-1/2) * (1/6) + (1/2) * (5/6) = 1/3.
{ "pile_set_name": "StackExchange" }
Q: AngularJS Showing Busy icon when loading data i have created a small example which would show spinner when data will be loading. create directive for this because i can reuse it. problem is spinner loading all the time which is not right. see the code and tell me where i made the mistake ? angular.module('myApp', []) .directive('loading', ['$http' ,function ($http) { return { restrict: 'A', template: '<div class="loading-spiner"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" /> </div>', link: function (scope, elm, attrs) { scope.isLoading = function () { return $http.pendingRequests.length > 0; }; scope.$watch(scope.isLoading, function (v) { if(v){ elm.show(); }else{ elm.hide(); } }); } }; }]) .controller('myController', function($scope, $http) { $scope.loadData = function() { $scope.students = []; $http.get('https://api.myjson.com/bins/x1rqt.json') .success(function(data) { $scope.students = data[0].students; }); } }); jsfiddle link https://jsfiddle.net/tridip/6L6p0bgd/ A: angular.module('myApp', []) .controller('myController', function($scope, $http) { $scope.loadData = function() { $scope.students = []; $scope.loading=true; $http.get('https://api.myjson.com/bins/x1rqt.json') .success(function(data) { $scope.students = data[0].students; $scope.loading=false; }); } }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="myApp" ng-controller="myController"> <h1>Loading spinner</h1> <div class="loading-spiner" ng-show="loading"> <img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" /> </div> <div> <ul ng-repeat="student in students"> <li>{{student.name}}</li> </ul> </div> <button ng-click="loadData()" class="btn btn-primary">Click for Load data</button> </body> Hope it will help othrewise use isolation in your derective with = scope.
{ "pile_set_name": "StackExchange" }
Q: Iterate view controllers of navigation controller swift I want to iterate through view controllers of navigation controller in swift. For that I wrote a for loop like this for navController in tabBarController?.viewControllers { //some process } tabBarController is a UITabBarController. But I am getting error like '$T4??' does not have a member named 'Generator' Whats wrong with the code? A: Optional chaining results in optional array of view controllers. Optional arrays do not conform to those protocols for be iterated with for..in loop. Try: if let viewControllers = tabBarController?.viewControllers { for viewController in viewControllers { // some process } }
{ "pile_set_name": "StackExchange" }
Q: Children attending a parent's wedding Recently a relative of mine who is a widow got engaged. The children were told that the Minhag is that children do not attend a wedding of their parents. What is the source of this Minhag? What is the reason? A: Per Ohr.edu in the name of Rabbi Yosef Shalom Elyashiv Shlita, Children have a Chiyuv to respect their parents even after the parents have passed away. Attending the marriage of a surviving parent would be disrespectful to the deceased parent. See Hirhurim for more reasons. A: I know of a family where the mother passed away at a young age, leaving her husband and 5 or 6 children, the youngest of whom was around three. I suppose because of this the husband re-married before a year had passed. Before the wedding one of the sons told me that he and his siblings would attend the wedding out of kavod for their father. And this while they were still in mourning. He said his father had told him this from Rav Moshe Feinstein. If someone could find a source I would be grateful.
{ "pile_set_name": "StackExchange" }
Q: Why are LIB files beasts of such a duplicitous nature? I'm trying to understand this LIB file business on Microsoft Windows, and I've just made a discovery that will - I hope - dispel the confusion that hitherto has prevented me from getting a clear grasp of the issue. To wit, LIB files are not the one kind of file that their file extension suggests they are. :: cd "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib" :: lib /nologo /list Ad1.Lib obj\i386\activdbgid.obj obj\i386\activscpid.obj obj\i386\ad1exid.obj obj\i386\dbgpropid.obj obj\i386\dispexid.obj :: lib /nologo /list oledb.lib o:\winmain.obj.x86fre\enduser\…\oledb\uuid\objfre\i386\oledbiid.obj o:\winmain.obj.x86fre\enduser\…\oledb\uuid\objfre\i386\oledbnewiid.obj o:\winmain.obj.x86fre\enduser\…\oledb\uuid\objfre\i386\cmdtreeiid.obj o:\winmain.obj.x86fre\enduser\…\oledb\uuid\objfre\i386\oledbdepiid.obj :: lib /nologo /list AdvAPI32.Lib | sort | uniq -c 731 ADVAPI32.dll The first two examples contain object files (appearing as relative or absolute paths when displayed by the lib.exe utility). The third example, however, only contains 731 references to a DLL. (I guess lib.exe isn't designed to display more useful information for this kind of file.) Some contain object files, and they are static libraries. Others contain symbols, and they are import libraries. (There's a short explanation here.) So static libraries appear to be the equivalents of .a files on Linux, and DLLs appear to map to .so files on Linux. (By the way, how would import libraries fit into this Windows/Linux equivalence picture?) Now I'm wondering why this is so? Why did Microsoft decide to give import libraries the same file extension as static libraries? (I understand that historically, static libraries were first, like primitive forms of life preceded more complex forms.) Why wouldn't they say, okay, here's these new kind of libraries, they shall be referred to as import libraries, and they shall bear the file extension .ILB (or whatever)? A: Because they are libraries. Why invent a whole new vendor-specific extension for what is exactly the same thing as their already-vendor-specific libraries?
{ "pile_set_name": "StackExchange" }
Q: Can you copy linker/additional dependancies etc to other projects I consistently have to add directx lib files etc to all of my projects, dependencies, linker stuff etc... Is there a file I can copy across that has all that stuff.. and I just copy it to every project that needs it? A: Yes. You have the option of creating a property sheet that can be added to new or existing projects. Here are the basic steps. Open the Property Manager (View menu). Right click on a project and select "Add New Property Sheet" Once the property sheet has been created/added right click on it and add your common configuration settings (the same way you do in a project's properties). Once you've created the property sheet you can add it to new or existing projects in much the same way. Open the Property Manager. right click on the project you want to add the property sheet to and click "Add Existing Property Sheet". I don't recommend copying into each project or solution directory but rather keep in in a central place much like you would a third party library (i.e. Boost).
{ "pile_set_name": "StackExchange" }
Q: How to use Raspberry Pi Clock Count for performance measurement I make performance measurements on the Raspberry Pi and would like to have higher resolution then just clock_gettime(). Therefor I need to enable the CPU register PMUSERENR. According to /proc/cpuinfo on my Raspberry Pi I have an "ARMv7 Processor rev 5 (v7l)". So I downloaded the architecture reference manual and found that I have to use: CRn = c9, opc1 = 0, CRm = c14, opc2 = 0 asm ("MCR p15, 0, %0, C9, C14, 0\n\t" :: "r"(1)); But when using this code in a kernel module, I get following oops: Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.604846] Internal error: Oops: 5 [#1] SMP ARM Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.715199] Process insmod (pid: 2944, stack limit = 0xac80e210) Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.722399] Stack: (0xac80fe90 to 0xac810000) Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.727920] fe80: 7f1ba0f8 00007fff 80098128 ac80fea8 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.738472] fea0: 80578128 0000002d 00000000 7f1ba0f8 7f1ba0f8 7f1ba26c 7f1ba264 7f1ba134 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.749092] fec0: ac80e000 8057608c ac80feec ac80fed8 8057608c 00000000 00000000 00000000 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.759724] fee0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 pi@raspberrypi ~/projects/timer $ Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.770389] ff00: 00000000 00000000 00000000 00000000 76f5e948 00007390 00000000 76f7b390 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.781147] ff20: 76f5e948 b91a2390 ac80e000 00000000 ac80ffa4 ac80ff40 8009b6c4 80099714 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.792000] ff40: b919b000 00007390 b91a0598 b91a0457 b91a22c8 0000026c 000002ac 00000000 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.802930] ff60: 00000000 00000000 0000001f 00000020 0000000c 0000000a 00000009 00000000 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.813947] ff80: 7ea4371c 00000000 55afc028 00000080 8000fc28 ac80e000 00000000 ac80ffa8 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.825056] ffa0: 8000fa20 8009b5f0 7ea4371c 00000000 76f74000 00007390 76f5e948 76f74000 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.836170] ffc0: 7ea4371c 00000000 55afc028 00000080 55afbf78 00007390 76f5e948 00000000 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.847338] ffe0: 00000000 7ea436c4 76f55fb4 76ec0534 60000010 76f74000 00000000 00000000 Message from syslogd@raspberrypi at Apr 29 20:58:12 ... kernel:[ 84.880715] Code: e51b3084 e1530005 e2455008 0a000009 (e5953014) I am new to kernel modules, so I do not know which direction I should go. Is there a good way to debug such things? A: Linux kernel comes with a PMU driver. You could just leverage that. I would write a tutorial for you, but why reinvent the wheel when this guy explains it so well: http://www.carbondesignsystems.com/virtual-prototype-blog/using-the-arm-performance-monitor-unit-pmu-linux-driver
{ "pile_set_name": "StackExchange" }
Q: Kill vertical scrolling when a link is clicked? I have a js popup. It pops up when a link is clicked. I want to disable (vertical) scrolling on the page when that link is clicked, and then reactivate scrolling when the popup is closed. Is there any way to do this? jQuery, Javascript? A: you can set overflow hidden to disable the scrolling. $('#yourDiv').css('overflow','hidden'); and to set scrol $('#yourDiv').css('overflow','scroll')
{ "pile_set_name": "StackExchange" }
Q: jQuery find() returning an empty string in Google Chrome I'm using jQuery to setup an Ajax request that grabs an XML feed from a PHP script and then parses some information out of the feed and inserts it into the DOM. It works fine in Firefox; however, in Chrome, I am getting an empty string for the title element. Here's the basic setup of the Ajax request: $.get('feed.php', function(oXmlDoc) { $(oXmlDoc).find('entry').each(function() { $(this).find('title').text(); $(this).find('id').text(); // do other work... }); }); For what it's worth, here's the PHP script that's grabbing data from the feed. I'm using cURL because I'm making the request across domains (and because it was a quick and dirty solution for the problem at hand). $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $str_feed_url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $xml = curl_exec($curl); curl_close($curl); echo $xml; The XML data is being returned correctly and I can see the values of the sibling nodes in Chrome (such as ID), but, for whatever reason, I continue to get an empty string for the title node. Edit: As requested, here's a fragment of the relevant XML: <entry> <id>http://TheAddress.com/feed/01</id> <title type="text">The Title of the Post</title> <author><name>Tom</name></author> <published>2009-11-05T13:46:44Z</published> <updated>2009-11-05T14:02:19Z</updated> <summary type="html">...</summary> </entry> A: I haven't tried it, but make sure that the xml is returned with the correct content type (text/xml). You can also set the dataType to xml at the jQuery.ajax(options).
{ "pile_set_name": "StackExchange" }
Q: Eclipse Jobs stay in the Progress View after returning an OK status I have a an Eclipse Job class similar to the following: public class MyCustomJob extends Job { @Override protected IStatus run(IProgressMonitor monitor) { MyObject.blockingMethod(); return Status.OK_STATUS; } } When I execute this job and it exits correctly, the bottom-right where the progress is listed while it is running still shows the name of the now completed job, but without any progress bar. If I double click in the region where the name of the job still is, the Progress View opens as expected, but shows that the job has finished. If I click the "x" to clear the job, it disappears from the view, but if I close the view and reopen it, it comes right back. How can I remove the name of the job from the bottom-right of the display and guarantee that if I clear the Finished job from the Progress View that is actually being dismissed? A: Check the return path for any async UI execs that could affect status. Changing from: Platform.getDefault().asyncExec(runnable) to Platform.getDefault().syncExec(runnable) fixed this issue
{ "pile_set_name": "StackExchange" }
Q: Elif me this piece of code from Exploring ES6 Help me wrap my head around this example: function* genFuncWithReturn() { yield 'a'; yield 'b'; return 'The result'; } function* logReturned(genObj) { const result = yield* genObj; console.log(result); // (A) } Results in: > [...logReturned(genFuncWithReturn())] The result [ 'a', 'b' ] So, my question is why and how result of return statement is produced first and recursive generator statement second? A: [...logReturned(...)] produces a new array after logReturned terminated. And just before logReturned terminates, it calls console.log(result). Maybe this ASCII art helps understand the flow: ┌──────────────────────┐ ┌──────────────────────┐ ┌─────────────────────┐ │[...logReturned(...)] │ │ logReturned │ │ genFuncWithReturn │ └──────────────────────┘ └──────────────────────┘ └─────────────────────┘ │ │ │ │ │ │ │ get next from iterator │ │ │ ─────────────────────────▶ │ get next from iterator │ │ │ ─────────────────────────▶ │ │ │ │ │ │ yield 'a' │ │ yield 'a' │ ◀───────────────────────── │ │ ◀───────────────────────── │ │ │ │ │ (remembers 'a') │ │ │ │ │ │ get next from iterator │ │ │ ─────────────────────────▶ │ get next from iterator │ │ │ ─────────────────────────▶ │ │ │ │ │ │ yield 'b' │ │ yield 'b' │ ◀───────────────────────── │ │ ◀───────────────────────── │ │ │ │ │ (remembers 'b') │ │ │ │ │ │ get next from iterator │ │ │ ─────────────────────────▶ │ get next from iterator │ │ │ ─────────────────────────▶ │ │ │ │ │ │ done, return 'The result' │ │ │ ◀───────────────────────── │ │ │ │ │ console.log(result) (terminates) │ │ │ done │ return │ ◀───────────────────────── │ ['a', 'b'] │ │ ◀───────────│ (terminates) │
{ "pile_set_name": "StackExchange" }
Q: CSS vertical align center in circles I am trying to vertical center text in anchor. I used line-height and it works, but when the text wraps, the text in the second line gets the line-height... How can I center the text in the anchor without fails like that? Run this code snippet and click on the circle to reveal the other circles and you'll see what I mean. (function($) { $.path = {}; $.path.arc = function(params) { for (var i in params) { this[i] = params[i] } this.dir = this.dir || 1; while (this.start > this.end && this.dir > 0) { this.start -= 360 } while (this.start < this.end && this.dir < 0) { this.start += 360 } this.css = function(p) { var a = this.start * (p) + this.end * (1 - (p)); a = a * 3.1415927 / 180; var x = Math.sin(a) * this.radius + this.center[0]; var y = -Math.cos(a) * this.radius + this.center[1]; return { top: y + "px", left: x + "px" } } }; $.fx.step.path = function(fx) { var css = fx.end.css(1 - fx.pos); for (var i in css) { fx.elem.style[i] = css[i] } } })(jQuery); $(function() { var clicked = false, allowAnimate = true; $('.MainCircle').click(function() { var list = $(this).siblings('ul').children('li'), noli = list.size(); if ((!clicked) && (allowAnimate)) { allowAnimate = false; list.each(function(i) { var li = $(this); var liw = li.width(); if (i == 0) { li.animate({ top: (liw * -2.3) + "px" }, 250); } else { li.delay(250).animate({ path: new $.path.arc({ center: [0, 0], radius: liw * 2.3, start: 0, end: 360 / noli * i, dir: 1 }) }, 500, function() { if (i + 1 == noli) { clicked = !clicked; allowAnimate = true; } }); } }); } else if ((clicked) && (allowAnimate)) { allowAnimate = false; list.each(function(i) { var li = $(this); li.animate({ top: 0, left: 0 }, 500, function() { if (i + 1 == noli) { clicked = !clicked; allowAnimate = true; } }); }); } }); }); body { font-family: verdana; font-size: 12px } ul { list-style: none; margin: 0; padding: 0 } a { color: #000; text-decoration: none } #CircledMenu li { position: absolute } .MainCircle { background: red; border-radius: 100px; display: block; height: 200px; line-height: 200px; position: absolute; text-align: center; width: 200px; z-index: 1 } .SubMenu li { margin: 50px } .SubMenu a { background: red; border-radius: 50px; display: block; height: 100px; line-height: 100px; text-align: center; width: 100px } <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> </head> <body> <ul style="margin:200px;" id="CircledMenu"> <li> <a href="#" class="MainCircle">Products</a> <ul class="SubMenu"> <li><a href="#">Kitchen</a></li> <li><a href="#">Bedroom</a></li> <li><a href="#">Car</a></li> <li><a href="#">DIY/Storage</a></li> <li><a href="#">Bathroom</a></li> <li><a href="#">Footwear</a></li> <li><a href="#">Garden/Outdoor/Travel</a></li> <li><a href="#">Health</a></li> <li><a href="#">Gifts</a></li> <li><a href="#">Pet</a></li> <li><a href="#">Living Solutions</a></li> <li><a href="#">Clock/Lighting</a></li> <li><a href="#">Personal Care</a></li> <li><a href="#">Practial Solutions</a></li> </ul> </li> </ul> </body> </html> I would like to support as much as possible browsers. if you add extra properties to support more browsers, please say which line is for which browser by adding comment. A: You can use display:table property for this. Write it like this: .SubMenu li { margin:50px; background:red; border-radius:50px; height:100px; width:100px; display:table; } .SubMenu a { height:100px; width:100px; display:table-cell; text-align: center; vertical-align: middle; } Check this JSFiddle.
{ "pile_set_name": "StackExchange" }
Q: How to show images from path in new window in python tk After browsing path of image i wanna show image on next window in python using Tk library but image is not showing in next window. please take a look on my code below and give answer Thanks. import tkinter as tk from tkinter import filedialog as fd a="" str1 = "e" class Browse(tk.Frame): """ Creates a frame that contains a button when clicked lets the user to select a file and put its filepath into an entry. """ def __init__(self, master, initialdir='', filetypes=()): super().__init__(master) self.filepath = tk.StringVar() self._initaldir = initialdir self._filetypes = filetypes self._create_widgets() self._display_widgets() def _create_widgets(self): self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10)) a=self._entry self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse) self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify) self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14)) def _display_widgets(self): self._label.pack(fill='y') self._entry.pack(fill='x', expand=True) self._button.pack(fill='y') self._classify.pack(fill='y') def retrieve_input(self): #str1 = self._entry.get() #a=a.replace('/','//') print (str1) def classify(self): newwin = tk.Toplevel(root) newwin.geometry("500x500") label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14)) label.pack() canvas = tk.Canvas(newwin, height=300, width=300) canvas.pack() my_image = tk.PhotoImage(file=a, master=root) canvas.create_image(150, 150, image=my_image) newwin.mainloop() def browse(self): """ Browses a .png file or all files and then puts it on the entry. """ self.filepath.set(fd.askopenfilename(initialdir=self._initaldir, filetypes=self._filetypes)) if __name__ == '__main__': root = tk.Tk() labelfont = ('times', 10, 'bold') root.geometry("500x500") filetypes = ( ('Portable Network Graphics', '*.png'), ("All files", "*.*") ) file_browser = Browse(root, initialdir=r"C:\Users", filetypes=filetypes) file_browser.pack(fill='y') root.mainloop() A: Your global variable a which stores the path of the image is not getting updated. You need to explicitly do it. Below is the code that works. Have a look at the browse() function. import tkinter as tk from tkinter import filedialog as fd a="" str1 = "e" class Browse(tk.Frame): """ Creates a frame that contains a button when clicked lets the user to select a file and put its filepath into an entry. """ def __init__(self, master, initialdir='', filetypes=()): super().__init__(master) self.filepath = tk.StringVar() self._initaldir = initialdir self._filetypes = filetypes self._create_widgets() self._display_widgets() def _create_widgets(self): self._entry = tk.Entry(self, textvariable=self.filepath, font=("bold", 10)) a = self._entry self._button = tk.Button(self, text="Browse...",bg="red",fg="white", command=self.browse) self._classify=tk.Button(self,text="Classify",bg="red",fg="white", command=self.classify) self._label=tk.Label(self, text="IMAGE CLASSIFICATION USING DEEP LERAINING.", bg="blue", fg="white",height=3, font=("bold", 14)) def _display_widgets(self): self._label.pack(fill='y') self._entry.pack(fill='x', expand=True) self._button.pack(fill='y') self._classify.pack(fill='y') def retrieve_input(self): #str1 = self._entry.get() #a=a.replace('/','//') print (str1) def classify(self): global a newwin = tk.Toplevel(root) newwin.geometry("500x500") label = tk.Label(newwin, text="Classification", bg="blue", fg="white",height=3, font=("bold", 14)) label.pack() canvas = tk.Canvas(newwin, height=300, width=300) canvas.pack() my_image = tk.PhotoImage(file=a, master=root) canvas.create_image(150, 150, image=my_image) newwin.mainloop() def browse(self): """ Browses a .png file or all files and then puts it on the entry. """ global a a = fd.askopenfilename(initialdir=self._initaldir, filetypes=self._filetypes) self.filepath.set(a) if __name__ == '__main__': root = tk.Tk() labelfont = ('times', 10, 'bold') root.geometry("500x500") filetypes = ( ('Portable Network Graphics', '*.png'), ("All files", "*.*") ) file_browser = Browse(root, initialdir=r"~/Desktop", filetypes=filetypes) file_browser.pack(fill='y') root.mainloop() P.S. Do change your initialdir. I changed it as I am not on Windows.
{ "pile_set_name": "StackExchange" }
Q: user control that other developers can add controls to it and "inherit" the behavior of all controls on my control hi all and sorry for the confusing title... can't find the right words yet. just out of curiosity, I am playing with c# user control, I created a control that is built from a panel, a textbox that is being used as a filter, and some labels / buttons/ etc... that are being filtered. when ever you change the text of the textbox, all the controls on the panel are visible / invisible depending if their Text property contains the Text of the textbox. very simple. but I want this user control to be such that the user that uses it can drop more labels or controls to it and they will behave the same, I can't figure out how to do that.. when I am editing the control (adding controls to it), it works as expected and the new controls behave as the old ones without code modifications, but only when I am editing the user control and not when using it. when I am dragging the user control to a form, I can not add controls to it... when I try to add a label to the control - it is just added to the form and not to the control and therefore the text box is not influencing the added label. what should I do if I want to be able to add the control to a form and then add some controls to the control? I will be happy for some pointers. here is the relevant code: private void textBox1_TextChanged(object sender, EventArgs e) { foreach (Control c in panel1.Controls) { if (c.Text.Contains(textBox1.Text)) { c.Visible = true; } else { c.Visible = false; } } } edit - pictures added. as you can see - i typed 1 in the filter text box and all the controls except button1 are now invisible - and of course the bad behaving label. Thanks, Jim. A: You describe one of the reasons why I almost never use UserControls. Anything that isn't done to the original UC must be done in code.. You can instead make it a class that is not a UserControl, ie make it a simple subclass of Panel (or FlowLayoutPanel as I do here merely for convenience, while dropping stuff on it during my tests). class FilterPanel : FlowLayoutPanel { TextBox tb_filterBox { get; set; } Label st_filterLabel { get; set; } public FilterPanel() { st_filterLabel = new Label(); st_filterLabel.Text = "Filter:"; this.Controls.Add(st_filterLabel); tb_filterBox = new TextBox(); this.Controls.Add(tb_filterBox); // st_filterLabel.Location = new Point(10, 10); // not needed for a FLP // tb_filterBox.Location = new Point(100, 10); // use it for a Panel! tb_filterBox.TextChanged += tb_filterBox_TextChanged; } void tb_filterBox_TextChanged(object sender, EventArgs e) { foreach(Control ctl in this.Controls) { if (ctl != tb_filterBox && ctl != st_filterLabel) ctl.Visible = ctl.Text.Contains(tb_filterBox.Text); } } } Now after placing it on a form (or whatever) you (or whoever) can drop Controls onto it in the designer and they'll be part of its Controls collection, just like you want it and will behave as expected.. Two notes on subclassing Controls: If you break one during developement, the Form(s) using it will be broken, too, until you fix the problem. So take a little extra care! For the Designer to display the Control it always needs to have one parameterless constructor, like the one above. Even if you prefer to have the ability to hand in parameters, one parameterless constructor must still be there or the designer will get into trouble!
{ "pile_set_name": "StackExchange" }
Q: Analytic function on convergent sequence Let $f:U\to\mathbb{C}$ analytic function, where $U$ is a region. $x_n \to x_0 \in U$ is a real convergent sequence, it is known that $f(x_n)$ is real for all $n$. Is it true $f^{(n)}(x_0)$ is real for all $n$? It is obvious that it is true for $n=0$ and $n=1$, but I could not get further. A: Let $g(z)=\overline{f(\bar z)}$. It is a holomorphic function and $f(x_n)=g(x_n)$ for all $n$. This however means that $f=g$ (both $f$ and $g$ being holomorphic), hence $f(z)$ is real for real $z$, hence all the derivatives of $f$ are real on the real axis.
{ "pile_set_name": "StackExchange" }
Q: Safari iframe's service worker loops infinitely and iframe is a white screen (not in other browsers, not in a new tab) I have 2 webapplications build in vue. One application is some sort of wrapper for all the applications a company has and it loads several projects via an iframe (And one of them is the other web-application build in vue). Both projects have the vue-pwa plugin installed. When opening the wrapper project in the safari browser on a mac and browsing to the iframe with the other vue application the screen is blank and i'm seeing that there are an unlimited count of console.logs: Service worker has been registered. from the register hook in the registerServiceWorker.js The moment i open the contents of that iframe in a seccond tab of safari, these console.logs stop and the page is normally loaded and functioning. Does anyone have an idea for a solution, or how to debug what the issue is? A: The issue was that i needed to set the header X-Frame-Options: ALLOW-FROM https://example.com/ Weird thing is that the code was executed, it was just not visible. And other browsers don't seem to bother that since there was no X-Frame-Options that blocked it.
{ "pile_set_name": "StackExchange" }
Q: Rationalising a fraction with a surd The given fraction is: $$\frac{2}{1+\sqrt5}$$ Can someone explain to me how to rationalise this (in steps - GCSE Level)? My only idea is to mutliply the top and bottom by $1+\sqrt5$ ?? TIA. A: $$ \frac 2 {1+ \sqrt 5} = \frac {2 (1-\sqrt 5)}{(1+\sqrt 5)(1 - \sqrt 5)} = \frac{2(1-\sqrt 5)}{1 - 5} = \frac{2(1-\sqrt 5)}{-4} = \frac{-(1-\sqrt 5)}{2} = \frac{\sqrt 5 - 1} 2. $$
{ "pile_set_name": "StackExchange" }
Q: Website failover across internet connections Requirement For a network having 4 static IP internet leased line connections linked to hosting a website. What are the current strategies one can apply to ensure high availability in case of internet failure of one of the connections ? If this is possible, How ? nslookup sampleWebsite.com Server: sampleWebsite.com Address: 111.111.111.11 Non-authoritative answer: Name: sampleWebsite.com Addresses:111.111.111.11 222.222.222.22 333.333.333.33 444.444.444.44 Setup Server - Windows Server 2012 Internet connection - Standard Fibre-optic 4Mbps connection Firewall - Commercial firewall appliance Note Tried ServerFault & WebMasters, but couldn't find a similar question Similar, but are they the solution ? Why is DNS failover not recommended? How browsers handle multiple IPs A: You can only reliably have the DNS point at one IP, as you will know from reading about DNS failover. You need to either have your ISP implement a routing protocol to distribute the incoming connections to an active line (such as with BGP) or use an external service which decides which is an active connection (such as load balancing or dynamic DNS) My suggestions would be Amazon Route 53 (http://aws.amazon.com/route53/) for DNS based on health-checks or something like CloudFlare (https://www.cloudflare.com/overview) which adds a layer between your users and your site
{ "pile_set_name": "StackExchange" }
Q: PHP: How to make "Latest visit" count nicer I have "Your latest 5 visits" at the home page of the user when he logs on. It works great without any problem. But then i want to change it. I dont know how i should do this, but someway somehow only count the user 1 time at the time, and not e.g 10 times if he visits/refresh your profile. So should i do this with a time checker? And for how long should it only count 1? When should second count? I need some idea for this, as I dont know if i should make it count 1 time per 10 minutes or 1 time per 1 minute.. So a good solution/giving a good realistic minute tip will answer the question. A: There are a number of tutorials about 'Your Last Visit' http://www.tizag.com/phpT/phpcookies.php
{ "pile_set_name": "StackExchange" }
Q: How to rotate object to look mouse point in three js? How to calculate object rotation.y in three js to look mouse pointer? When i move mouse pointer from 1 to 2, arrow should turn to point 2. How do i calculate rotation.y? A: As an option, you can use THREE.Raycaster() with THREE.Plane() and use .lookAt() of your arrow to point it at the point of intersection of the raycaster's ray and plane. Let's create our arrow object: var coneGeom = new THREE.ConeGeometry(0.125, 1, 4); coneGeom.translate(0, .5, 0); coneGeom.rotateX(Math.PI / 2); // var coneMat = new THREE.MeshNormalMaterial(); var cone = new THREE.Mesh(coneGeom, coneMat); cone.lookAt(new THREE.Vector3(0, 1, 0)); scene.add(cone); then we'll add an event listener for mousemove: window.addEventListener("mousemove", onmousemove, false); and then our onmousemove function will be like this: var plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0); // it's up to you how you will create THREE.Plane(), there are several methods var raycaster = new THREE.Raycaster(); //for reuse var mouse = new THREE.Vector2(); //for reuse var intersectPoint = new THREE.Vector3();//for reuse function onmousemove(event) { //get mouse coordinates mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; raycaster.setFromCamera(mouse, camera);//set raycaster raycaster.ray.intersectPlane(plane, intersectPoint); // find the point of intersection cone.lookAt(intersectPoint); // face our arrow to this point } jsfiddle example r86
{ "pile_set_name": "StackExchange" }
Q: How to change CSS properties in Meteor Templates? I have been trying to fix this problem for days without finding a solution. I am working on a web application that aims at retrieving information from a db. I am using Meteor and blaze. As a matter of fact, i would like to change css properties in a template event wether it deals with the css proporties of the click target element or any DOM element in the same template. Here is my template code tag : <button type="button" class="buttonsValue" value="{{value}}"> <div class="CheckButtonsLed"></div> </button> Here is my template event code : Template.devicesConfiguration.events({ 'click .buttonsValue':function(e, template){ //works well on the parent of the target of the click event : $(e.target.parentElement).css('background-color', 'chartreuse'); //works well on the target of the click event : e.target.style.backgroundColor="#ffcccc"; //does the same thing but with a different syntax : $(e.currentTarget).css('background-color', '#ffcccc'); // Does not work ... var CheckButtonsLed = template.find('.CheckButtonsLed'); CheckButtonsLed.style.marginLeft = '2 em'; } }); It seems that it does not like the margin proporties while it works for the background property. my class element is my template devicesConfiguration. I thought first it was because the target of the margin property is not the target of my click event but i tried to change the margin of the target of the event (.buttonsvalue) without results... does someone have an idea ? thanks a lot ! :) A: Well it works now. it deals with a matter of syntax : i wrote simpleInput.style.padding = '2 em'; instead of ... simpleInput.style.padding = '2em'; to put in a nutshell, to change CSS Property of a DOM element (which is not the target of the event)in a meteor template : Template.devicesConfiguration.events({ 'click .buttonsValue':function(e, template){ var simpleInput = template.find('#simpleInput'); simpleInput.style.padding = '2em'; } }); and don't put a div element in a button tag ... Bye !
{ "pile_set_name": "StackExchange" }
Q: Intervention Image rounded corners upload I'm trying to upload my files as circles, but I can't make it work. I've seen some topics about applying a mask to the image, but when I apply the mask it takes way to long and the server shuts the request down. I'm using the Intervention Image library for Laravel My code is as follows: $identifier = "{$this->loggedUser->id}" . str_random(9) . ".{$file->getClientOriginalExtension()}"; $mask = $this->createCircleMask(200, 200); $thumbMask = $this->createCircleMask(40, 40); Image::make($file->getRealPath())->mask($mask)->save(public_path("images/profile/{$identifier}")); Image::make($file->getRealPath())->mask($thumbMask)->save(public_path("images/profile/thumbs/{$identifier}")); The createCircleMask method looks like this: public function createCircleMask($width, $height) { $circle = Image::canvas($width, $height, '#000000'); return $circle->circle($width - 1, $width / 2, $height / 2); } A: Here is a function that works in my case. But ONLY if I use the imagick driver. The standard gd library is very very slow, at least on my test computer. You can have a look at vendor\intervention\image\src\Intervention\Image\Gd\Commands\MaskCommand.php to find out why. public function upload() { $path = storage_path('app')."/"; $image = \Image::make(\Input::file('image')); $image->encode('png'); /* if you want to have a perfect and complete circle using the whole width and height the image must be shaped as as square. If your images are not guaranteed to be a square maybe you could use Intervention's fit() function */ // $image->fit(300,300); // create empty canvas $width = $image->getWidth(); $height = $image->getHeight(); $mask = \Image::canvas($width, $height); // draw a white circle $mask->circle($width, $width/2, $height/2, function ($draw) { $draw->background('#fff'); }); $image->mask($mask, false); $image->save($path."circled.png"); }
{ "pile_set_name": "StackExchange" }
Q: Usage of SearchBuilder in NEST ElasticSearch client I was wondering if anyone had any tips or examples for using the SearchBuilder API in NEST. The docs are still kinda sparse. I am looking to dynamically construct queries/filters based on criteria sent in URL parameters. An example: www.mydomain.com/things/search?prop1=3&prop2=foo&prop3=bar And once I extract those I want to build an exact-match query based on the criteria that are present. A: Using the DSL query syntax you can now simply do this: var results = client.Search(s=>s .Fields(new string[0]) .Query(q=> q.Term(ESFields.City, city) && q.Term(ESFields.State, state) ) ); Which relies on the conditionless query support added in 0.9.10.0. This will only render the city query if city holds a value and only the state term query if state is not null or empty. If both are valid it will do a bool query If only one is valid it will do just the one term query If neither is valid it will fall back to a match_all query.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to make program which will stop Java from promoting integer into long Scanner num=new Scanner(System.in); System.out.println("Enter number in range from 1 to 20"); int n=num.nextInt(); int product=1; for(int i=1;i<=n;i++){ product*=i; if(product>Integer.MAX_VALUE || product<Integer.MIN_VALUE){ System.err.println("Out od Integer boundary"); } else System.out.println("Product of numbers between 1 and "+n+" is "+product); } } } I'm working on same basic tasks and this particular one is: Compute the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and decide if the results are correct. and then Hints: Product of 1 to 13 (=6227020800) is outside the range of int [-2147483648, 2147483647], but within the range of long. Take note that computer programs may not produce the correct answer even though everything seems correct! So if i understand correct Java will automatically transcend int value into long value, but i was thinking to make program which will not allow that. Is is possible? Also feel free to explain anything what is incorrect in code or my thinking.Thanks. p.s Sorry for bad English. A: If I understand the question correctly, the simple solution would be to use Math.multiplyExact (which appeared in Java 8): import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner num = new Scanner(System.in); System.out.println("Enter number in range from 1 to 20"); int n = num.nextInt(); int product = 1; try { for (int i = 1; i <= n; i++) { product = Math.multiplyExact(product, i); } System.out.println("Product of numbers between 1 and " + n + " is " + product); } catch (ArithmeticException e) { System.err.println("Out of Integer boundary"); } } } The multiplyExact method ensures that your multiplication result does not overflow. If it does, an AriphmeticException is thrown which could be catched and handled.
{ "pile_set_name": "StackExchange" }
Q: I heard professional chessplayers must train physically as well as mentally. Why is that? I heard that both Fischer and Karpov felt that physical training was extremely important to their success and that the Russian coaches also felt a certain amount of physical training was necessary. Why is that? How is it supposed to help? What sort of exercise is supposed to help. A: You've heard it right. Physical training is as important as mental training in chess. Thinking is an energy intensive activity and often has a direct effect on the physical body. Quoting this scientific american article by By Ferris Jabr on July 18, 2012, brain weighs about 1.4 kilograms, only 2 percent of total body weight, it demands 20 percent of our resting metabolic rate (RMR)—the total amount of energy our bodies expend in one very lazy day of no activity. Karpov had lost 10kg (22lb) over the course of 1984-85 Kasparov-Karpov world championship match. Quoting Kasparov from this interview, I pay a lot of attention to my physical condition; to be fit under the terrible pressure of big competitions. Obviously this is becoming more important with age. From a study by Speakman JR et. al , being physically fit improves resting metabolic rate (RMR) which is a major contributor to daily energy reserve and thus any increases in RMR in response to exercise interventions are potentially of great importance. Chess, as you know is a brain intensive activity and thus RMR plays an important important role. Therefore from the 1st and the 3rd paragraphs, it is clear that physical fitness improves mental fitness and therefore beneficial to chess.
{ "pile_set_name": "StackExchange" }
Q: Как сохранить значения, введенные в поля поиска? Допустим, на веб-странице имеется расширенный поиск недвижимости. Пользователь может выбрать чекбоксы или же ввести текст в input поля. После отправки формы, значения, введенные в поля, сбрасываются. Какие удобные механизмы для их сохранения существуют? Слышал, что можно хранить в localstore браузера, кто об этом слышал? A: Если отправляешь форму AJAXом, то данные и так сохранятся. Если отправляешь стандартно, то в чем проблема подставить уже полученные сервером переменные в качестве значений полей формы и тем самым сохранить ввод для посетителя? Все равно ведь страницу перегружать, а пришедшие данные все равно на сервере проверять. Про LocalStorage вот здесь все понятно написано: http://webknowledge.ru/ispolzovanie-localstorage-dlya-nuzhd-javascript/
{ "pile_set_name": "StackExchange" }
Q: Setting up a local SVN repository with encrypted passwords with TortoiseSVN I am planning on using a local repository, using only TortoiseSVN's "create repository here" feature. The repo is created and I can read and write to it just fine. The problem is that I can't get authentication to work. I thought I wanted Windows authentication, but I actually want the simple text-file based authentication so I can force the current system user (i.e. any person can be using the same Windows account and I want to differentiate between them) to provide their name and password. I haven't found any information on how to do this without svnserve running. So far, I have modified svnserve.conf like this: anon-access = read auth-access = write password-db = passwd realm = LocalOnly I didn't mess with the [sasl] section. I also modified passwd: [users] harry = teH0wLIpW0gyQ I am trying to use encrypted passwords created with a simple perl script. However, regardless of what I do with the repo (i.e. including writing to the repo), I am never prompted for a password. I tried clearing TortoiseSVN's authentication cache since I do connect to a remote repo, but this didn't matter at all. Has anyone tried this and succeeded? Or is it not possible without svnserve? A: Try Subversion Edge. you can edit the file you are mentioning using the GUI provided by the tool. It uses its own http server(not svnserve or IIS).
{ "pile_set_name": "StackExchange" }
Q: Neatest way to remove linebreaks in Perl I'm maintaining a script that can get its input from various sources, and works on it per line. Depending on the actual source used, linebreaks might be Unix-style, Windows-style or even, for some aggregated input, mixed(!). When reading from a file it goes something like this: @lines = <IN>; process(\@lines); ... sub process { @lines = shift; foreach my $line (@{$lines}) { chomp $line; #Handle line by line } } So, what I need to do is replace the chomp with something that removes either Unix-style or Windows-style linebreaks. I'm coming up with way too many ways of solving this, one of the usual drawbacks of Perl :) What's your opinion on the neatest way to chomp off generic linebreaks? What would be the most efficient? Edit: A small clarification - the method 'process' gets a list of lines from somewhere, not nessecarily read from a file. Each line might have No trailing linebreaks Unix-style linebreaks Windows-style linebreaks Just Carriage-Return (when original data has Windows-style linebreaks and is read with $/ = '\n') An aggregated set where lines have different styles A: After digging a bit through the perlre docs a bit, I'll present my best suggestion so far that seems to work pretty good. Perl 5.10 added the \R character class as a generalized linebreak: $line =~ s/\R//g; It's the same as: (?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}]) I'll keep this question open a while yet, just to see if there's more nifty ways waiting to be suggested. A: Whenever I go through input and want to remove or replace characters I run it through little subroutines like this one. sub clean { my $text = shift; $text =~ s/\n//g; $text =~ s/\r//g; return $text; } It may not be fancy but this method has been working flawless for me for years. A: Reading perlport I'd suggest something like $line =~ s/\015?\012?$//; to be safe for whatever platform you're on and whatever linefeed style you may be processing because what's in \r and \n may differ through different Perl flavours.
{ "pile_set_name": "StackExchange" }
Q: UIView removeFromSuperView animation delay I have a method which animates one of the subviews of UIWindow and then removes it from UIWindow using removeFromSuperview. But when I put removeFromSuperview after animation block, the animation never shows, because removeFromSuperview removes the UIView from UIWindow before the animation plays :-( How can I delay removeFromSuperview so the animation plays first, and then subview is removed? I tried [NSThread sleepForTimeInterval:1]; after animation block but that didn't have desired effect, because animation sleeps too for some reason. My code for this method: - (void) animateAndRemove { NSObject *mainWindow = [[UIApplication sharedApplication] keyWindow]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.8]; UIView *theView = nil; for (UIView *currentView in [mainWindow subviews]) { if (currentView.tag == 666) { currentView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.0]; theView = currentView; } } [UIView setAnimationTransition: UIViewAnimationTransitionNone forView:theView cache:YES]; [UIView commitAnimations]; //[NSThread sleepForTimeInterval:1]; [theView removeFromSuperview]; } A: You should use the delegation mechanism in animation blocks to decide what to do when the animation ends. For your case, use [UIView beginAnimations:nil context:nil]; [UIView setAnimationDelegate:theView]; [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)]; .... This ensures [theView removeFromSuperview] will be called after the animation is completed. A: If you're targetting iOS 4.0 upwards you can use animation blocks: [UIView animateWithDuration:0.2 animations:^{view.alpha = 0.0;} completion:^(BOOL finished){ [view removeFromSuperview]; }]; (above code comes from Apple's UIView documentation)
{ "pile_set_name": "StackExchange" }
Q: What does the rpart "Error in as.character(x) : cannot coerce type 'builtin' to vector of type 'character' " message mean? I've been banging my head against rpart for a few days now (trying to make classification trees for this dataset that I have), and I think it's time to ask a lifeline at this point :-) I'm sure it's something silly that I'm not seeing, but here's what I've been doing: EuropeWater <- read.csv(file=paste("/Users/artessaniccola/Documents/", "Magic Briefcase/CityTypology/Europe_water.csv",sep="")) library(rpart) attach(EuropeWater) names(EuropeWater) [1] "City" "waterpercapita_m3" "water_class" "population" [5] "GDPpercapita" "area_km2" "populationdensity" "climate" EuropeWater$water_class <- factor(EuropeWater$water_class, levels=1:3, labels=c("Low", "Medium", "High")) EuropeWater$climate <- factor(EuropeWater$climate, levels=2:4, labels=c("Arid", "Warm temperate", "Snow")) EuropeWater_tree <- rpart(EuropeWater$water_class ~ population+GDPpercapita + area_km2 + populationdensity + EuropeWater$climate, data=EuropeWater, method=class) Error in as.character(x) : cannot coerce type 'builtin' to vector of type 'character' and for the life of me, I can't figure out what the Error is about. A: Does this work? EuropeWater_tree <- rpart(EuropeWater$water_class ~ population+GDPpercapita + area_km2 + populationdensity + EuropeWater$climate, data=EuropeWater, method="class") I think you should quote method type. When you use class instead of "class" then R is trying convert to character themself: as.character(class) Error in as.character(class) : cannot coerce type 'builtin' to vector of type 'character' Cause class is a function with type buildin: typeof(class) [1] "builtin" A: I would start by fixing the formula: remove the redundant EuropeWater as you already supply the data= argument: res <- rpart(water_class ~ population + GDPpercapita + area_km2 + populationdensity + climate, data=EuropeWater, method="class") Also, make sure that all columns of your data.frame are of the appropriate type. Maybe some of the data read from the csv file was mistakenly read as a factor? A quick summary(EuropeWater) may reveal this.
{ "pile_set_name": "StackExchange" }
Q: visual studio 2010 web projects This is just taking too long. Cannot install visual studio, i have a msdn subscription, but after installing the grand total of available web projects is 3. mvc won't install. sp1 won't install. any ideas? win xp. this is driving me nuts. why can't it "just work"? since it won't let me invent tags, i'll include them here: i-give-up wtf-microsoft A: problem with backslashes. http://forums.asp.net/t/1661809.aspx/1 . Hope this will help someone else
{ "pile_set_name": "StackExchange" }
Q: How to compute GCD with a MILP? How would one formulate a linear optimisation program that computes the Greatest Common Divisor (GCD) of a set of $n$ numbers $\{a_1,...,a_n \}$? I can only think of a non linear formulation : $$ \max\; \{ p \} $$ subject to \begin{align*} a_i &= p \cdot q_i \quad &\forall i=1,...,n\\ q_i &\in \mathbb{N} \quad &\forall i=1,...,n\\ p &\in \mathbb{N} \end{align*} One could linearize the product, but I am wondering if there is a better way to this (with an optimization program). A: Let $m = \min_{i \in \{1,\dots,n\}} a_i$. For $p\in\{1,\dots,m\}$, let binary variable $z_p$ indicate whether $p$ is the GCD. The problem is to maximize $\sum_{p=1}^m p\ z_p$ subject to \begin{align} \sum_{p=1}^m z_p &= 1 \\ (a_i-p\ a_i)(1 - z_p) \le a_i - p\ q_i &\le a_i (1 - z_p) &&\text{for $i \in \{1,\dots,n\}$} \\ q_i &\in [0,a_i] \cap \mathbb{N} &&\text{for $i \in \{1,\dots,n\}$}\\ z_p &\in \{0,1\} &&\text{for $p \in \{1,\dots,m\}$}\\ \end{align}
{ "pile_set_name": "StackExchange" }
Q: How can i get a checkbox value? I want to use a checkbox and I fails to check the status (full or empty). I want to send a mail if the checkbox is full. <input type="checkbox" name="checkAddress" onclick="checkAddress(this)" /> function checkAddress(checkbox) { if (checkbox.checked == true) { status==1; } } function secSendMailFunction(){ for(var i=1; i<4; i++){ if(status==i){ var ref = firebase.database().ref(); ref.on("value", function(snapshot){ mail=snapshot.child(i).child("Mail").val(); }) } } A: Firstly you are doing wrong assignment - status==1; this is not correct, == / === is an conditional statement. You want to assign a value to status not compare it. Use = I suggest you to choose onchange instead onclick. Checkbox is a type of input which possibly have only two values either true/ false. Triggering event will be good in this case const input = document.querySelector('input') input.onchange = function(el) { if(el.srcElement.checked){ alert('do my job') } } <input type="checkbox" />
{ "pile_set_name": "StackExchange" }
Q: Transpose column into rows without summing I have the following table: id name year month value code 1 George 1991 1 675 1234 2 George 1991 2 675 1234 3 George 1991 2 675 1234 5 George 1991 3 675 1234 ... ... ... ... ... ... but I have to show it like this, so I can have months in a row with one id: id year name code jan feb mar apr ... dec 1 1991 George 1234 675 675 675 0 0 2 1991 George 1234 0 675 0 0 0 ... ... ... ... ... ... ... ... ... ... the thing is: There can be more than 1 value in the same month, and I couldn't create that structure without summing the values (in this example, february), and I don't want that. Is there any way to do this using a pivot or something?? A: If you have multiple values for each month that you want to keep unique, then you should consider applying a row_number() prior to using the PIVOT: select name, year, code, coalesce([1], 0) as jan, coalesce([2], 0) as feb, coalesce([3], 0) as mar from ( select name, year, month, value, code, row_number() over(partition by name, year, month order by year, month) rn from yourtable ) src pivot ( max(value) for month in ([1], [2], [3]) ) piv See SQL Fiddle with Demo The result is: | NAME | YEAR | CODE | JAN | FEB | MAR | ------------------------------------------ | George | 1991 | 1234 | 675 | 675 | 675 | | George | 1991 | 1234 | 0 | 675 | 0 |
{ "pile_set_name": "StackExchange" }
Q: Is there any reason for using if(1 || !Foo())? I read some legacy code: if ( 1 || !Foo() ) Is there any seen reason why not to write: if ( !Foo() ) A: The two are not the same. The first will never evaluate Foo() because the 1 short-circuits the ||. Why it's done - probably someone wanted to force entry in the then branch for debugging purposes and left it there. It could also be that this was written before source control, so they didn't want the code to be lost, rather just bypassed for now. A: if (1 || !Foo() ) will be always satisfied. !Foo() will not even be reached because of short-circuits evaluation. This happens when you want to make sure that the code below the if will be executed, but you don't want to remove the real condition in it, probably for debug purposes. Additional information that might help you: if(a && b) - if a is false, b won't be checked. if(a && b) - if a is true, b will be checked, because if it's false, the expression will be false. if(a || b) - if a is true, b won't be checked, because this is true anyway. if(a || b) - if a is false, b will be checked, because if b is true then it'll be true. It's highly recommended to have a macro for this purpose, say DEBUG_ON 1, that will make it easier to understand what the programmer means, and not to have magic numbers in the code (Thanks @grigeshchauhan). A: 1 || condition is always true, regardless whether the condition is true or not. In this case, the condition is never even being evaluated. The following code: int c = 5; if (1 || c++){} printf("%d", c); outputs 5 since c is never incremented, however if you changed 1 to 0, the c++ would be actually called, making the output 6. A usual practical usage of this is in the situation when you want to test some piece of code that is being invoked when the condition that evaluates to true only seldom is met: if (1 || condition ) { // code I want to test } This way condition will never be evaluated and therefore // code I want to test always invoked. However it is definitely not the same as: if (condition) { ... which is a statement where condition will actually be evaluated (and in your case Foo will be called)
{ "pile_set_name": "StackExchange" }
Q: Find intersecting point of three circles programmatically As the title says, I have 3 Circle. Each one have different radius. I know the radius of each circles. Also know the center points of each circle. Now I need to know how I can calculate the intersecting point of three circles programmatically, is there is any formula or something? It may look like below image A: You could get help from this C code. Porting it to JAVA should not be challenging. Explanation is here. Search for/scroll to: intersection of two circles Using this method, find the intersection of any two circles.. lets say (x,y). Now the third circle will intersect at point x,y only if distance between its center and point x,y is equal to r. case 1) If distance(center,point) == r, then x,y is the intersection point. case 2) If distance(center,point) != r, then no such point exists. Code (ported from [here! all credits to original author): private boolean calculateThreeCircleIntersection(double x0, double y0, double r0, double x1, double y1, double r1, double x2, double y2, double r2) { double a, dx, dy, d, h, rx, ry; double point2_x, point2_y; /* dx and dy are the vertical and horizontal distances between * the circle centers. */ dx = x1 - x0; dy = y1 - y0; /* Determine the straight-line distance between the centers. */ d = Math.sqrt((dy*dy) + (dx*dx)); /* Check for solvability. */ if (d > (r0 + r1)) { /* no solution. circles do not intersect. */ return false; } if (d < Math.abs(r0 - r1)) { /* no solution. one circle is contained in the other */ return false; } /* 'point 2' is the point where the line through the circle * intersection points crosses the line between the circle * centers. */ /* Determine the distance from point 0 to point 2. */ a = ((r0*r0) - (r1*r1) + (d*d)) / (2.0 * d) ; /* Determine the coordinates of point 2. */ point2_x = x0 + (dx * a/d); point2_y = y0 + (dy * a/d); /* Determine the distance from point 2 to either of the * intersection points. */ h = Math.sqrt((r0*r0) - (a*a)); /* Now determine the offsets of the intersection points from * point 2. */ rx = -dy * (h/d); ry = dx * (h/d); /* Determine the absolute intersection points. */ double intersectionPoint1_x = point2_x + rx; double intersectionPoint2_x = point2_x - rx; double intersectionPoint1_y = point2_y + ry; double intersectionPoint2_y = point2_y - ry; Log.d("INTERSECTION Circle1 AND Circle2:", "(" + intersectionPoint1_x + "," + intersectionPoint1_y + ")" + " AND (" + intersectionPoint2_x + "," + intersectionPoint2_y + ")"); /* Lets determine if circle 3 intersects at either of the above intersection points. */ dx = intersectionPoint1_x - x2; dy = intersectionPoint1_y - y2; double d1 = Math.sqrt((dy*dy) + (dx*dx)); dx = intersectionPoint2_x - x2; dy = intersectionPoint2_y - y2; double d2 = Math.sqrt((dy*dy) + (dx*dx)); if(Math.abs(d1 - r2) < EPSILON) { Log.d("INTERSECTION Circle1 AND Circle2 AND Circle3:", "(" + intersectionPoint1_x + "," + intersectionPoint1_y + ")"); } else if(Math.abs(d2 - r2) < EPSILON) { Log.d("INTERSECTION Circle1 AND Circle2 AND Circle3:", "(" + intersectionPoint2_x + "," + intersectionPoint2_y + ")"); //here was an error } else { Log.d("INTERSECTION Circle1 AND Circle2 AND Circle3:", "NONE"); } return true; } Call this method as follows: calculateThreeCircleIntersection(-2.0, 0.0, 2.0, // circle 1 (center_x, center_y, radius) 1.0, 0.0, 1.0, // circle 2 (center_x, center_y, radius) 0.0, 4.0, 4.0);// circle 3 (center_x, center_y, radius) Also, define EPSILON to a small value that is acceptable for your application requirements private static final double EPSILON = 0.000001; Note: Maybe some one should test and verify if the results are correct. I can't find any easy way to do so..works for the basic cases that I have tried A: You can use the following condition: (x - x0) ^ 2 + (y - y0) ^ 2 <= R ^ 2 where x and y - coordinates of your point , x0 and y0 - coordinates of the center of the circle , R - radius of the circle , ^ 2 - squaring . If the condition is satisfied, the point is inside (or on the circumference in the case of equality of the left and right parts). If not satisfied, the point is outside the circle . / / Point, which hit the circle is necessary to determine PointF p = ...; / / Center of the circle PointF center = new PointF (10, 10); / / The radius of the circle float r = 5F; / / "Normalize" the situation relative to the center point of the circle float dx = p.x - center.x; float dy = p.y - center.y; / / Compare the distance from the point to the center of a circle to its radius boolean result = ((r * r) <= (dx * dx + dy * dy))) ? true : false;
{ "pile_set_name": "StackExchange" }
Q: Laravel 5.6 session timeout exception when using spatie permissions I have been trying to redirect the user after session timeout, but when using spatie permissions package i cant get the TokenMismatchException for the session timeout, i always get UnauthorizedException. Here is my Exceptions/Handler.php file: public function render($request, Exception $exception) { if ($exception instanceof TokenMismatchException){ session()->flash('warning','Session timeout. Please login again.'); return redirect()->guest(route('login')); } if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException){ return redirect('/restricted'); } return parent::render($request, $exception); } How to catch the session timeout exception and make a custom redirect in this case? A: Sounds like the package's RoleMiddleware is being evaluated before VerifyCsrfToken in the pipeline. From their source, you can see it throws an UnauthorizedException immediately if the user is not logged in: namespace Spatie\Permission\Middlewares; use Closure; use Illuminate\Support\Facades\Auth; use Spatie\Permission\Exceptions\UnauthorizedException; class RoleMiddleware { public function handle($request, Closure $next, $role) { if (Auth::guest()) { throw UnauthorizedException::notLoggedIn(); } $roles = is_array($role) ? $role : explode('|', $role); if (! Auth::user()->hasAnyRole($roles)) { throw UnauthorizedException::forRoles($roles); } return $next($request); } } You can modify the order of middleware by setting the $middlewarePriority property in the kernel, however, be aware this can lead to unintended side effects: protected $middlewarePriority = [ \App\Http\Middleware\MyMiddleware::class, ]; Look at the order of middleware defined in Illuminate\Foundation\Http\Kernel and work off that.
{ "pile_set_name": "StackExchange" }
Q: Is must conditional or biconditional? To use the wireless network in the airport you must pay the daily fee unless you are a subscriber to the service. Express your answer in terms of w: “You can use the wireless network in the airport,” d: “You pay the daily fee,” and s: “You are a subscriber to the service.” So here it should be w -> (d v s) (If must is considered the same as necessary (conditional)) However, Is it? Is must the same as conditional or is it comparable to if and only if? A: It is only conditional; i.e. to use the network, it is necessary to pay the fee or subscribe. However, this may not be sufficient as one might also need to set up some sort of account or whatever the case may be.
{ "pile_set_name": "StackExchange" }
Q: why to use redux saga or thunk at all I am really confused by redux saga. So whatever article I look at they explain that it is there to fix the side effect of redux and asynchronous calls and even they give explanation on the difference of saga and thunk but all of them are confusing. They lack the explanation of why I should use saga at all? what is wrong if I make the async call wait for it and then update the redux state. What i need is a simple and clear explanation on why and in what occasion we need to use redux saga or thunk? Am I right to say if I do not use saga then if I click 1000 times my code will run the async code and wait for result 1000 times but with saga I have a way to control over it either run all in parallel(fork) or just run the last one? A: so for whatever action that needs to change the redux store (not the component state) and is asynchronous we better to use thunk or saga but we do not have to and if not using it still it is valid. right? First and foremost, redux-saga or redux-thunk are libraries built on top of Redux's middleware, which is used to handle concerns unrelated to the main data flow of redux, e.g. API calls, logging, routing. You can obviously write your own middlewares to handle async flow instead of using those libraries, which might lighten your app size a lot. However, redux-thunk and especially redux-saga have many syntax-sugar APIs to deal with complex usage of async flows, such as racing, sequencing API calls, cancelling API call based on condition and so on, which reduce a lot of working implementing equivalent logics by yourself. Also when we say redux is syncronous flow by nature still we can swait for the call and then proceed. So how is that different from saga or thunk? It's more personal opinion, but I think the main reason of using those libraries is separation of concerns. With middleware implementation to handle all async flows, we can have 3 logical parts in a react/redux app: redux part consisting of pure functions for synchrounous data flow, redux middleware part (can be redux-thunk or redux-saga) which deals with all API calls and side-effects from redux and react part to handle user interaction and communication with redux store. This way the code will be more manageable and easier for unit testing. Am I right to say if I do not use saga then if I click 1000 times my code will rin the asnc code and wait for result 1000 times but with saga I have a way to control over it either run all in parallel(fork) or just run the last one? Again, a self-implemented redux middleware can be use to throttle all but the last call. However, redux-saga already has an API for this case, and many more for other common async problems.
{ "pile_set_name": "StackExchange" }
Q: Android, GUI design w/ Eclipse, Layout->View->Layout I'm trying to find my way into Android development. I'm using Eclipse Helios. The GUI design software seems to make it impossible to design certain element hierarchies. For example: <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <ScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="110px"> <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="30px" android:orientation="vertical"> </LinearLayout> </ScrollView> </LinearLayout> I have not been able to design this structure in the GUI designer. I drag a LinearLayout to the design frame, drag a ScrollView over it, then drag a LinearLayout on top. Always, this will be inserted as a child of the first LinearLayout, not of the ScrollView. However, in this example for ScrollViews, this seems to be right. Am I doing something wrong? How would I design this structure using the GUI designer? Or is this only possible by direct XML manipulation? Thanks. A: The Wysiwyg editor for android is badly broken. They just released one in the new sdk version and from their own saying : "It is a complete rewrite and is far from really usable but this new version is on par with the old one so we released it" Use the Wysiwyg up to where you can't get it to do what you want then switch to xml is the best advice I can give you. Most senior developers don't even trust wysiwyg in the first place and would advise you to just go xml...You write what you want and get it the way you want.
{ "pile_set_name": "StackExchange" }
Q: Escape code 50 in xterm My coworker has the following in the ~/.bash_profile of many of our servers: echo -e "\033]50;SetProfile=Production\a" The text doesn't seem to matter, since this also works: echo -e "\033]50;ANY_TEXT\a" But no text doesn't work; the \a is also required. This causes his terminal in OSX to change profiles (different colours, etc.); but in my xterm, it changes the font to huge; which I can't seem to reset. I have tried to reset this with: Setting VT fonts with shift+right click Do "soft reset" and "full reset" with shift+middle click Sending of various escape codes & commands: $ echo -e "\033c" # Reset terminal, no effect $ echo -e "\033[0;m" # Reset attributes, no effect $ tput sgr0 # No effect $ tput reset # No effect My questions: Why does this work on xterm & what exactly does it do? Code 50 is listed as "Reserved"? How do I reset this? Screenshot: A: Looking at the list of xterm escape codes reveals that (esc)]50;name(bel) sets the xterm's font to the font name, or to an entry in the font menu if the first character of name is a #. The simplest way to reset it is to use the xterm's font menu (Ctrl + right mouse click) and select an entry other than Default. Alternatively, you can find out which font the xterm uses on startup, and set that with the escape sequence. In the font menu you'll also find an option Allow Font Ops; if you uncheck that, you cannot any more change the font using escape sequences.
{ "pile_set_name": "StackExchange" }
Q: Super simple jQuery tabs - without UI - collapse on page load I'd like all tabs to be collapsed on page load. Right now the first one is open by default: $(document).ready(function($) { $('#forms').find('.forms-toggle').click(function(){ //Expand or collapse this panel $(this).next().slideToggle('fast'); //Hide the other panels $(".forms-content").not($(this).next()).slideUp('fast'); }); }); HTML and CSS are here: https://jsfiddle.net/re8x8cx3/ A: Place this inside dom ready, $(".forms-content").hide(); Then the code will be, $(document).ready(function($) { $(".forms-content").hide(); $('#forms').find('.forms-toggle').click(function() { //Expand or collapse this panel $(this).next().slideToggle('fast'); //Hide the other panels $(".forms-content").not($(this).next()).slideUp('fast'); }); }); Fiddle
{ "pile_set_name": "StackExchange" }
Q: PHP bindParam variable error In my web service I have a problem with bindParams. Here is my code: $stmt = $this->db->prepare("SELECT data FROM sless WHERE ST_CONTAINS(data.area, Point(:query))"); $stmt->bindParam(':query', $queryText, PDO::PARAM_STR); but :query variable isnt correctly adapted this code. When I echo $queryText it gives 29.029087,40.990361 perfectly. But in the code it's not working. By the way when I write 29.029087,40.990361 latitude and longitude instead of the variable :query my code working perfectly. Here is the code: $stmt = $this->db->prepare("SELECT data FROM sless WHERE ST_CONTAINS(data.area, Point(29.029087,40.990361))"); How can I solve the problem? A: Try both coordinate separately list($lat, $lng) = split(',', $queryText); $stmt = $this->db->prepare("SELECT data FROM sless WHERE ST_CONTAINS(data.area, Point(:lat,:lng))"); $stmt->bindParam(':lat', $lat, PDO::PARAM_STR); $stmt->bindParam(':lng', $lng, PDO::PARAM_STR);
{ "pile_set_name": "StackExchange" }
Q: Can one source code be deployed to Openshift, Heroku and Google App Engine at once? As subject, is is possible with just one source code, we can deploy our code to Openshift or Google App Engine? Heroku is not necessarily in my case. My application is using Python Flask + PostgreSQL 9.1. I love the easiness in Openshift when I configure my technology stack, but is the case will be same with GAE? Thanks! A: I work on Openshift and at this time I'm not aware of anything that will deploy your code to GAE and Openshift at the same time. You might be able to write your own script for it.
{ "pile_set_name": "StackExchange" }
Q: How to change the title icon of a Windows Forms application How do I change the title icon of a Windows Forms application? A: Set it in two places: The Icon: dropdown in Project properties -> Application The Icon property of the main form (startup form).
{ "pile_set_name": "StackExchange" }
Q: Passed value from binding as key in dictionary I tried to make a ListView of ListViews using dictionary in xaml, but i cant figure out how to. I have a dictionary: public Dictionary<string, float> dictionary {get;set;} And ObservableCollection<string> Parameters{get; set;} containing names of key values in said dictionary. I have a ListView with itemsSource = "{Binding Parameters}" And an ListViews as DataTemplate with itemsSource that would be like: itemsSource= "{Binding dictionary[Passed_Value]}" I cant manualy create ListViews with only selected values of Dictionary as user may choose which to display, and there are 10s of them. A: Your question is quite a challenge to understand. So, I thought I would just demonstrate creating a list of lists. Starting with this code-behind. public class Level1 { public int Key { get; set; } public string Name { get; set; } public IEnumerable<Level2> Items { get; set; } } public class Level2 { public int Key { get; set; } public string Name { get; set; } } public IEnumerable<Level1> Items { get { return Enumerable.Range(1, 10) .Select(x => new Level1 { Key = x, Name = $"Level 1 Item {x}", Items = Enumerable.Range(1, 10) .Select(y => new Level2 { Key = y, Name = $"Level 2 Item {y}", }) }); } } And this XAML: <ListView ItemsSource="{x:Bind Items}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" /> <ItemsControl ItemsSource="{Binding Items}" Margin="12,0,0,0"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> Looks like this: Please note that I changed the nested ListView and made it an ItemsCOntrol because the nesting controls that each have a SELECTED behavior can cause you a real nightmare. Other than that, this does it. Not sure you need a Dictionary at all, but binding to a dictionary is certainly possible - just a little clunky. Best of luck.
{ "pile_set_name": "StackExchange" }
Q: Aggregation Conditional Count on Present Fields I am trying to write an aggregation that counts how many documents have certain fields (ie only count them if they are present). The objects look something like this: { "_id" : ObjectId("5617731fe65e0b19101c7039"), "dateCreated" : ISODate("2015-10-09T07:56:15.068Z"), "dateSent" : ISODate("2015-10-09T07:56:16.682Z"), "dateAttempted" : ISODate("2015-10-09T07:56:16.682Z") }, { "_id" : ObjectId("561e37bb537d381bb0ef0ae2"), "dateCreated" : ISODate("2015-10-14T11:08:43.306Z"), "dateSent" : ISODate("2015-10-14T11:09:51.618Z"), "dateAttempted" : ISODate("2015-10-14T11:09:51.618Z"), "dateViewed" : ISODate("2015-10-15T10:09:50.618Z"), "dateOpened" : ISODate("2015-10-15T10:10:01.618Z") } I want to iterate over all documents, counting where the field exists. Desired output: { "total" : 1000, "created" : 1000, "sent" : 990, "attempted" : 995 "viewed" : 800, "opened" : 750 } Bonus points if this output can be grouped per day! I would prefer not to perform a new aggregation for each date in the range. Here's what I have so far, which doesn't work; it returns zeros for each field [ { "$group": { "_id": { "$dayOfMonth": "$dateCreated" }, "total": { "$sum": 1 }, "sent": { "$sum": "$dateSent" }, "attempted": { "$sum": "$dateAttempted" }, "viewed": { "$sum": "$dateViewed" }, "clicked": { "$sum": "$dateClicked" } } } ] A: The $cond and $ifNull operators are the helpers here: [ { "$group": { "_id": { "$dayOfMonth": "$dateCreated" }, "total": { "$sum": 1 }, "sent": { "$sum": { "$cond": [ { "$ifNull": [ "$dateSent", false ] }, 1, 0 ] } }, "attempted": { "$sum": { "$cond": [ { "$ifNull": [ "$dateAttempted", false ] }, 1, 0 ] } }, "viewed": { "$sum": { "$cond": [ { "$ifNull": [ "$dateViewed", false ] }, 1, 0 ] } }, "clicked": { "$sum": { "$cond": [ { "$ifNull": [ "$dateClicked", false ] }, 1, 0 ] } } } } ] $ifNull will return either the field where present ( a logical true ) or the alternate value false. And the $cond looks at this condition and returns either 1 where true or 0 where false to provide the conditional count.
{ "pile_set_name": "StackExchange" }
Q: What is the best way to use Source File switches with CMake I would like to build a shared library. The lib has a source directory and some sub directories. source core.c sub1 featrue1.c sub2 feature2.c sub3 feature3.c So I would like to add the lib to a project an would like to build and link the lib only with feature 1. And for an other build I would like to build it with feature1.c and feature2.c and so on ... Which mechanism can I use for that in cmake. In Eclipse CDT it is something like Resource Configuration => Remove or Add to build. Many thanks Mathias A: I would suggest to use object libraries: # first solution add_library(feature1 OBJECT sub1/feature1.c) add_library(feature2 OBJECT sub1/feature2.c) add_library(feature3 OBJECT sub1/feature3.c) if(conditions) add_library(my_shared_library SHARED $<TARGET_OBJECTS:feature1>) elseif(other_condition) # other version endif() # second solution add_library(my_shared_lib SHARED common.c $<$<BOOL:${WITH_FEATURE1}>:sub1/feature1.c> $<$<BOOL:${WITH_FEATURE2}>:sub2/feature2.c> )
{ "pile_set_name": "StackExchange" }
Q: Is a function less than a decreasing function also decreasing? Two families of functions, $f_\alpha(x)$ and $g_\alpha(x)$, where $0\leq\alpha, x\leq 1$. It is known that $f_\alpha(0)=g_\alpha(0)=1$ and $f_\alpha(1)=g_\alpha(1)=0$ for any $\alpha$. Also, $f_0(x)=g_0(x)\leq 1$ and $f_1(x)=g_1(x)=1$ for any $x\in[0, 1]$. Knowing that $g_\alpha(x)$ decreases in $x$ for any $\alpha$, can we say the same for $f_\alpha$? A: Here we have $f\le g$ and $g$ is decreasing but, as you can see from the picture, nothing can be deduced regarding if $f$ is increasing or decreasing.
{ "pile_set_name": "StackExchange" }
Q: Having two Windows excluded in a IfWinNotActive in AutoHotKey I am mapping Alt+F4 to ESC so that I can close windows just by pressing escape. However there are two windows that I need to actually use ESC in. So, when either of these two windows are active I want to be able to press ESC without closing the window. What is the easiest way to accomplish this? I have my script working when I just am excluding one active window but I need to work when either of the two windows are active. Here is my attempted code: GroupAdd, ESC, Untitled - Notepad GroupAdd, ESC, #IfWinNotActive, ahk_group, ESC Escape::!F4 Return This is the code that works properly with just one window: ;#IfWinNotActive, Untitled - Notepad ;Escape::!F4 ;Return UPDATE: Should this work? SetTitleMatchMode, 2 SetTitleMatchMode, 2 #IfWinNotActive, Untitled - Notepad #IfWinNotActive, Document 1 - Microsoft Word Escape::!F4 Return A: You have an extra comma in your #IfWinNotActive line after ahk_group Try the following: GroupAdd, ESC, Untitled - Notepad ; Add more windows to the group if necessary #IfWinNotActive, ahk_group ESC Escape::!F4 Return
{ "pile_set_name": "StackExchange" }
Q: What's wrong with my stove? We've got burners that flop between partially-lit states, mainly by starting like after being on a while, switching to sometimes some of them do this, and then we stop using them What's going on? A: Electric coils that are that uneven I would replace, sooner rather than later. I have personally experienced the end of an oven element when one of the "hot spots" burnt through and it was happily arcing away. Fortunately I was in the kitchen and noticed it right away so I could shut things down, as it did not trip the breaker. I have read of the same thing on a stovetop coil burning a hole through the bottom of a pot. Fortunately they are generally quite inexpensive. I would replace the whole set, myself.
{ "pile_set_name": "StackExchange" }
Q: Does GCC STL have a trait that gets the primitive type from typedef aliases? I can't find a metafunction which returns the primitive type from its typedef aliases, like in that possible example: typedef int ivar; typedef ivar signIvar; ... // true std::cout << std::is_same< int, std::get_primitive<signIvar>::type >::value; It may exist, but I cannot find it. Implementation is possible in principle, but I can only make it expensive for compile time. A: There is conceptually no such thing as "get primitive type from its typedef alias". An alias of a type is simply a name for the same type. As such, you can do: std::cout << std::is_same_v<int, signIvar>; // output: 1
{ "pile_set_name": "StackExchange" }
Q: Delete product custom option value I want to remove one custom value from the product custom option, I've following code for it but it's not working $obj = Mage::getModel('catalog/product'); $product_id = $obj->getIdBySku("mysku"); $product = $obj->load($product_id); foreach ($product->getOptions() as $o) { $values = $o->getValues(); foreach ($values as $v) { if($v->getData('default_title') == "Something"){ $optionValue=Mage::getModel('catalog/product_option_value')->load($v->getData('option_id')); $optionValue->delete(); } } } A: Well, I've resolved by myself, By following $obj = Mage::getModel('catalog/product'); $product_id = $obj->getIdBySku("mysku"); $product = $obj->load($product_id); foreach ($product->getOptions() as $o) { $values = $o->getValues(); foreach ($values as $v) { if($v->getData('default_title') == "Something"){ $product->setCanSaveCustomOptions(true); $v->delete(); } } }
{ "pile_set_name": "StackExchange" }
Q: How to read Headers Parameter on server side "RESTLET" [I am trying to send parameter with GET request on RESTLET Netsuite !! but i am continuously facing issue 403 forbidden when i am trying to concatenate parameter with URL , without parameter Request is working good and getting response but i want to send parameter so now i am trying to send parameter through Header but not able to read on server side !! please help me out .how to read request header values/parameters on Netsuite RESTLET. 1-first i tried concatenate with +"&name=asd" and then Uri builder throws error 403 forbidden 2-Now i am sending parameters through request.header.add("name":"asd") working good This is my client side request code in which i am attaching parameters in request header HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.ContentType = "application/json"; request.Method = "GET"; request.Headers.Add(header); request.Headers.Add("email", "[email protected]"); request.Headers.Add("password", "123-4567"); WebResponse response = request.GetResponse();///here i got 403 on concatination //// function getCustomer(context) { var request =https.request.headers;///headers function not defined // var email =request.email; //var password = request.password; } Want to get header values on server side][1] [1]: https://i.stack.imgur.com/SEB68.png A: In RESTlet you don't have access to request-headers, instead you get all the arguments passed to RESTlet in scriptContext(function argument to RESTlet entry point, get in current case). Check this out on how to use RESTlet and how you can pass arguments. Note: Add { "Content-Type": "application/json" } header since you want to pass data to RESTlet.
{ "pile_set_name": "StackExchange" }
Q: @Html.EditorFor(model => model.ID) can't display the right value I have a model contain the file XSID(Guid) and ID(nvarchar), Now I want to edit the ID value with @Html.EditorFor(model => model.ID) but it could not get the right value ,it also get the value of XSID .But the @Html.DisplayFor(model => model.ID) could get the right value. I don't konw why? @using Student.Resource; @using M = Student.Model; @model M.Stu_XS <ul class="cur"> <li class="line"> <label> @Stu_XS.ID: </label> <span> @Html.HiddenFor(model => model.XSID) @Html.DisplayFor(model => model.ID) @Html.EditorFor(model => model.ID) @Html.ValidationMessageFor(model => model.ID) </span> </li> </ul> A: If you have an ID in your route, that value will be used and not the one in your model. For example let's suppose that you have the following model: public class Stu_XS { public int ID { get; set; } public Guid XSID { get; set; } } and the following controller action: public ActionResult SomeAction(int id) { var model = new Stu_XS(); model.ID = 123; return View(model); } which you would request like this: /somecontroller/someaction/456 The Html.EditorFor will display 456 which is coming from the route and not 123 from the model. That's by design. If you want to change this behavior you will have to remove the ID from the ModelState so that the value from your model is used: public ActionResult SomeAction(int id) { var model = new Stu_XS(); model.ID = 123; ModelState.Remove("id"); return View(model); }
{ "pile_set_name": "StackExchange" }
Q: JavaScript .replace doesn't work I have the following JavaScript code, and I like to replace some strings, but I can't $new_slide = '<div class="slide">' + '<table>' + '<tr>' + '<td class="pictureContainer">' + '<img src="/img/admin/slide-placeholder.svg" />' + '<input type="hidden" name="slides[0][picture][id]" data-value="picture_id" />' + '<input type="hidden" name="slides[0][picture][thumbnail]" data-value="picture_thumbnail" />' + '<input type="hidden" name="slides[0][picture][original]" data-value="picture_original" />' + '</td>' + '<td class="fieldsContainer">' + '<p>' + '<label for="masthead_0">Masthead</label>' + '<input type="text" data-value="masthead" name="slides[0][masthead]" id="masthead_0" />' + '</p>' + '<p>' + '<label for="first_heading_0">Heading #1</label>' + '<input type="text" data-value="first_heading" name="slides[0][first_heading]" id="first_heading_0" />' + '</p>' + '<p>' + '<label for="second_heading_0">Heading #2</label>' + '<input type="text" data-value="second_heading" name="slides[0][second_heading]" id="second_heading_0" />' + '</p>' + '<p>' + '<label for="link_title_0">Link title</label>' + '<input type="text" data-value="link_title" name="slides[0][link][title]" id="link_title_0" />' + '</p>' + '<p>' + '<label for="link_url_0">Link URL</label>' + '<input type="text" data-value="link_url" name="slides[0][link][url]" id="link_url_0" />' + '</p>' + '</p>' + '<label for="target_0">Link Target</label>' + '<select id="target_0" data-value="link_target" name="slides[0][link][target]">' + '<option value="_self">' + z.self + '</option>' + '<option value="_blank">' + z.blank + '</option>' + '</select>' + '</p>' + '</td>' + '</tr>' + '</table>' + '</div>'; var slide = { "picture_id" : "45", "picture_thumbnail" : "/thumbnail.jpg", "picture_original" : "/original.jpg", "masthead" : "Mast Head #1", "first_heading" : "First Heading", "second_heading" : "", "link_title" : "Link Title #1", "link_url" : "Link URL #1", "link_target" : "Link target #1" } for(field in slide) { $new_slide.replace('data-value="' + field + '"', 'value="' + slide[field] + '"'); } More spesific, I like by iterating the slide variable to replace the "key" values in the $new_slide variable with the value in slide variables. In turn, the sting <input type="hidden" name="slides[0][picture][id]" data-value="picture_id" /> I like to be converted in <input type="hidden" name="slides[0][picture][id]" data-value="45" /> as well the field <input type="text" data-value="second_heading" name="slides[0][second_heading]" id="second_heading_0" /> I like to be converted in <input type="text" data-value="" name="slides[0][second_heading]" id="second_heading_0" /> But my code seems that not working. Can somebody to help me ? A: You have to change it like: $new_slide = $new_slide.replace('data-value="' + field + '"', 'value="' + slide[field] + '"'); because replace function doesn't change the $new_slide value, it just returns the new modified string.
{ "pile_set_name": "StackExchange" }
Q: Styling of SVG circle doesn´t work in Firefox, browser removes radius property I'm trying to create a kind of progress ring with an SVG and CSS, which worked so far in Chrome. However, Firefox (61.0.1 (64-bit)) causes me problems and doesn't show my circle. I have already tried to use the method from this question, but without success. Is there a way to style the ring to display correctly in both Chrome and Firefox (both in the latest version)? Is it problematic, that I add styles with [ngStyles] during runtime? this is needed to calculate the space and the shown progress I have a running example on code sandbox for you, which also just is working for chrome, but not for Firefox. HTML <div class="my-progress-ring"> <svg> <circle class="progress" [ngStyle]="getCircleStyles()"/> </svg> </div> CSS div.my-progress-ring { width: 50px; height: 50px; } svg { height: 100%; min-height: 100%; width: 100%; min-width: 100%; } circle.progress { stroke: red; stroke-width: 4px; stroke-linecap: round; transform: rotate(-90deg); transform-origin: 50% 50%; cx: 50%; cy: 50%; fill: transparent; } Typescript public getCircleStyles(): any { return { 'r': 21, 'stroke-dasharray': 131.947, 'stroke-dashoffset': 32.987 }; } EDIT: The numbers for the getCircleStyles are hardcoded in this example. In my app i´m using a function to calculate the numbers depending on the size of the progress ring and the current progress. EDIT 2: It seems that Firefox doesn't like some properties of values of my stlying. The r property is missing A: Seems like you found an inconsistent implementation of the SVG 2.0 spec in Firefox. Or, maybe Firefox does not fully support SVG 2.0 yet. The specification states that: Some styling properties can be specified not only in style sheets and ‘style’ attributes, but also in presentation attributes. So, both style sheets and attributes should work. The quick fix is to add r, cxand cy presentation attributes to your circle element (as suggested here): <circle _ngcontent-c1="" class="progress" style="stroke-dasharray: 131.947; stroke-dashoffset: 32.987;" cx="50%" cy="50%" r="21" fill="transparent" ng-reflect-ng-style="[object Object]"></circle>
{ "pile_set_name": "StackExchange" }
Q: Reference type fields are null in IParameterInspector .BeforeCall I implement IParameterInspector interface. When I call methods which have primitive type parameters Beforecall works fine! But something goes wrong when I pass a custom reference type object. When I pass reference type parameter all the fields of the object get default values. object IParameterInspector.BeforeCall(string operationName, object[] inputs) { var argument = (MyCustomType)inputs[0]; if (argument != null) { // All the fields are null, e.g.argument.ID is null } } A: Sorry, Solved!! DataMember attribute was missing on the fields :)
{ "pile_set_name": "StackExchange" }
Q: Opening a table in Microsoft Access with VBA in Excel I'm trying to load a table from Microsoft Access and paste it into Excel cells with VBA. My path is correctly finding my .accdb file and does error until the first Cells(row x).Value = statement. The "OpenRecordset" method not referencing a table, makes me feel like I shouldn't be passing in the name of the table- or using a different method altogether. I get an error: "Run-time error '3265' Application-defined or object-defined error Here is my code below: Sub ImportAccessButton() Dim row As Integer Dim dbPassengerCarMileage As Database Dim rstPassengerCarMileage As Recordset row = 3 Set dbPassengerCarMileage = OpenDatabase(ThisWorkbook.Path & "\Cars.accdb") Set rstPassengerCarMileage = dbPassengerCarMileage.OpenRecordset("Amber") If Not rstPassengerCarMileage.BOF Then Do Until rstPassengerCarMileage.EOF Cells(row, 1).Value = rstPassengerCarMileage!MAKE Cells(row, 2).Value = rstPassengerCarMileage!Model Cells(row, 3).Value = rstPassengerCarMileage!VOL Cells(row, 4).Value = rstPassengerCarMileage!HP Cells(row, 5).Value = rstPassengerCarMileage!MPG Cells(row, 6).Value = rstPassengerCarMileage!SP Cells(row, 7).Value = rstPassengerCarMileage!WT row = row + 1 rstPassengerCarMileage.MoveNext Loop End If 'Close database and Cleanup objects rstPassengerCarMileage.Close dbPassengerCarMileage.Close Set rstPassengerCarMileage = Nothing Set dbPassengerCarMileage = Nothing End Sub A: It uses ADODB. The CopyFromRecordset command speeds up. Sub ImportAccessButton() Dim Rs As Object Dim strConn As String Dim i As Integer Dim Ws As Worksheet Dim strSQL As String set Ws = ActiveSheet strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ "Data Source=" & ThisWorkbook.Path & "\Cars.accdb" & ";" strSQL = "SELECT * FROM Amber" Set Rs = CreateObject("ADODB.Recordset") Rs.Open strSQL, strConn If Not Rs.EOF Then With Ws .Range("a2").CurrentRegion.ClearContents For i = 0 To Rs.Fields.Count - 1 .Cells(2, i + 1).Value = Rs.Fields(i).Name Next .Range("a" & 3).CopyFromRecordset Rs End With End If Rs.Close Set Rs = Nothing End Sub
{ "pile_set_name": "StackExchange" }
Q: Simple Android Scrolling Text Ticker I want to create a scrolling text ticker for a simple android app. I have a large list of quotes stored in an array, and I would like to randomly populate my ticker with the quotes: one quote scrolls all the way through, then another is randomly chosen and scrolls its way through, and so on. The ticker should chug along regardless of what's been focused on or hovered over... 1) How do I create a text ticker for these purposes? 2) How do I populate the ticker with a steady stream of random quotes selected from my array? Thanks A: If I'm understand what you're trying to do properly you want to look at the ellipsize and marqueeRepeatLimit properties of TextView. Via the API: http://developer.android.com/reference/android/widget/TextView.html#attr_android:ellipsize http://developer.android.com/reference/android/widget/TextView.html#attr_android:marqueeRepeatLimit Also, look at this question for an implementation. From what I remember when I had to implement something like this is that the XML properties can be tricky. They interfere with one another and prevent the text from scrolling across the screen so it may take some toying with to get it right. From there, populating it with different quotes is as simple as calling setText() on the TextView with the random quote that I assume you'll have stored in an array or database at the proper time.
{ "pile_set_name": "StackExchange" }
Q: use regex to replace long string I want to replace the string ID12345678_S3_MPRAGE_ADNI_32Ch_2_98_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg with ID12345678 How can I replace this via regex? I tried this - it didn't work. import re re.sub(r'_\w+_\d_\d+_\w+','') Thank you A: You can use re.sub with pattern [^_]* that match any sub-string from your text that not contain _ and as re.sub replace the pattern for first match you can use it in this case : >>> s="ID12345678_S3_MPRAGE_ADNI_32Ch_2_98_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg" >>> import re >>> re.sub(r'([^_]*).*',r'\1',s) 'ID12345678' But if it could be appear any where in your string you can use re.search as following : >>> re.search(r'ID\d+',s).group(0) 'ID12345678' >>> s="_S3_MPRAGE_ADNI_ID12345678_32Ch_2_98_clone_transform_clone_reg_N3Corrected1_mask_cp_strip_durastripped_N3Corrected_clone_lToads_lesions_seg" >>> re.search(r'ID\d+',s).group(0) 'ID12345678' But without regex simply you can use split() : >>> s.split('_',1)[0] 'ID12345678'
{ "pile_set_name": "StackExchange" }
Q: Run a VBA macro in Spotfire using Ironpython So I would try ask over in this thread IronPython - Run an Excel Macro but I don't have enough reputation. So roughly following the code given in the link I created some code which would save a file to a specific location, then open a workbook that exists there, calling the macro's within it, which would perform a small amount of manipulation on the data which I downloaded to .xls, to make it more presentable. Now I've isolated the problem to this particular part of the code (below). Spotfire normally is not that informative but it gives me very little to go on here. It seems to be something .NET related but that's about all I can tell. The Error Message Traceback (most recent call last): File "Spotfire.Dxp.Application.ScriptSupport", line unknown, in ExecuteForDebugging File "", line unknown, in StandardError: Exception has been thrown by the target of an invocation. The Script from Spotfire.Dxp.Data.Export import DataWriterTypeIdentifiers from System.IO import File, Directory import clr clr.AddReference("Microsoft.Office.Interop.Excel") import Microsoft.Office.Interop.Excel as Excel excel = Excel.ApplicationClass() excel.Visible = True excel.DisplayAlerts = False workbook = ex.Workbooks.Open('myfilelocation') excel.Run('OpenUp') excel.Run('ActiveWorkbook') excel.Run('DoStuff') excel.Quit() A: Right, so I'm answering my own question here but I hope it helps somebody. So the above code, as far as I'm aware was perfectly fine but didn't play well with the way my spotfire environment is configured. However, after going for a much more macro heavy approach I was able to find a solution. On the spotfire end I've two input fields, one which gives the file path, the other the file name. Then there's a button to run the below script. These are joined together in the script but are crucially separate, as the file name needs to be inputted into a separate file, to be called by the main macro so that it can find the file location of the file. Fundamentally I created three xml's to achieve this solution. The first was the main one which contained all of the main vba stuff. This would look into a folder in another xml which this script populates to find the save location of the file specified in an input field in spotfire. Finding the most recent file using a custom made function, it would run a simple series of conditional colour operations on the cell values in question. This script populates two xml files and tells the main macro to run, the code in that macro automatically closing excel after it is done. The third xml is for a series of colour rules, so user can custom define them depending on their dashboard. This gives it some flexibility for customisation. Not necessary but a potential request by some user so I decided to beat them to the punch. Anyway, code is below. from Spotfire.Dxp.Data.Export import DataWriterTypeIdentifiers from System.IO import File, Directory import clr clr.AddReference("Microsoft.Office.Interop.Excel") import Microsoft.Office.Interop.Excel as Excel from Spotfire.Dxp.Data.Export import * from Spotfire.Dxp.Application.Visuals import * from System.IO import * from System.Diagnostics import Process # Input field which takes the name of the file you want to save name = Document.Properties['NameOfDocument'] # Document property that takes the path location = Document.Properties['FileLocation'] # just to debug to make sure it parses correctly. Declaring this in the script # parameters section will mean that the escape characters of "\" will render in a # unusable way whereas doing it here doesn't. Took me a long time to figure that out. print(location) # Gives the file the correct extension. # Couldn't risk leaving it up to the user. newname = name + ".xls" #Join the two strings together into a single file path finalProduct = location + "\\" + newname #initialises the writer and filtering schema writer = Document.Data.CreateDataWriter(DataWriterTypeIdentifiers.ExcelXlsDataWriter) filtering = Document.ActiveFilteringSelectionReference.GetSelection(table).AsIndexSet() # Writes to file stream = File.OpenWrite(finalProduct) # Here I created a seperate xls which would hold the file path. This # file path would then be used by the invoked macro to find the correct folder. names = [] for col in table.Columns: names.append(col.Name) writer.Write(stream, table, filtering, names) stream.Close() # Location of the macro. As this will be stored centrally # it will not change so it's okay to hardcode it in. runMacro = "File location\macro name.xls" # uses System.Diagnostics to run the macro I declared. This will look in the folder I # declared above in the second xls, auto run a function in vba to find the most # up to date file p = Process() p.StartInfo.FileName = runMacro p.Start() Long story short: To run excel macro's from spotfire one solution is to use the system.dianostics method I use above and simply have your macro set to auto run.
{ "pile_set_name": "StackExchange" }
Q: Fallo al recoger string desde urlopen() Cuando la función recibe una variable que contiene un string escrito a mano, la función de reemplazar los caracteres funciona, pero cuando recibe la variable desde urlopen(), no funciona. Los dos strings son de tipo str. #!/usr/bin/python # -*- coding: utf_8 -*- import re from urllib import request from re import findall, UNICODE from unidecode import unidecode import sys import re from unicodedata import normalize response = str(request.urlopen("https://www.amazon.es/Spigen-042CS20927-Carcasa-Protecci%C3%B3n-h%C3%ADbrida/dp/B01M0USRWG/ref=pd_sim_107_5?_encoding=UTF8&pd_rd_i=B01M0USRWG&pd_rd_r=dee5b20b-0f7b-11e9-b36a-dd935edf15f1&pd_rd_w=fXXgN&pd_rd_wg=Sc7jG&pf_rd_p=cc1fdbc2-a24a-4df6-8bce-e68491d548ae&pf_rd_r=20G8D05BQ984RRGRR8SS&psc=1&refRID=20G8D05BQ984RRGRR8SS").readlines()) Descripcion = re.findall('<title>.*?Amazon', response) DescripcionA = Descripcion[0].replace('<title>', "") original = DescripcionA.replace('Amazon', "") def normalize(s): replacements = ( ("\xc2\xa1", "¡"), ("\xc2\xbf", "¿"), ("\xc3\x81", "Á"), ("\xc3\x89", "É"), ("\xc3\x8d", "Í"), ("\xc3\x91", "Ñ"), ("\xc3\x93", "Ó"), ("\xc3\x9a", "Ú"), ("\xc3\x9c", "Ü"), ("\xc3\xa1", "á"), ("\xc3\xa9", "é"), ("\xc3\xad", "í"), ("\xc3\xb1", "ñ"), ("\xc3\xb3", "ó"), ("\xc3\xba", "ú"), ("\xc3\xbc", "ü") ) for a, b in replacements: s = s.replace(a, b).replace(a.upper(), b.upper()) return s #Cuando escribo el string a mano, funciona: text2= "spigen Funda iPhone 7/8, Ultra Hybrid 2 Tecnolog\xc3\xada de amortiguaci\xc3\xb3n de Aire y protecci\xc3\xb3n h\xc3\xadbrida contra ca\xc3\xaddas:" text2 = normalize(text2) #Cuando uso la variable que contiene un str No funciona: text = normalize(original) print(text) print(text2) A: Las direcciones de request normalmente vienen codificadas, puedes decodificarla utilizando la función decode: request.urlopen(tu_direccion).read().decode('utf8')
{ "pile_set_name": "StackExchange" }
Q: Reset variable value every 60 seconds in infinite loop I am doing a project which requires resetting a variable every 1 Minute without pausing an infinite loop. For example: int temp = 0; while(true){ temp ++; //After 60 Seconds call_to_a_function(temp); temp = 0; } How can I achieve this in C++? Your help is appreciated! A: atomic_int temp; std::thread t( [&temp]() { while( temp!= -1){ std::this_thread::sleep_for(std::chrono::seconds(60)); temp=0; } }); while ( true ) { temp < INT_MAX ? temp++ : 0; cout << temp << endl; } // do some stuff // when program needs to exit, do this to avoid a crash temp = -1; // t will exit the loop t.join(); // wait until t finishes running While loops with sleep might get optimized away.
{ "pile_set_name": "StackExchange" }
Q: MySQL - ignore insert error: duplicate entry I am working in PHP. Please what's the proper way of inserting new records into the DB, which has unique field. I am inserting lot of records in a batch and I just want the new ones to be inserted and I don't want any error for the duplicate entry. Is there only way to first make a SELECT and to see if the entry is already there before the INSERT - and to INSERT only when SELECT returns no records? I hope not. I would like to somehow tell MySQL to ignore these inserts without any error. Thank you A: You can use INSERT... IGNORE syntax if you want to take no action when there's a duplicate record. You can use REPLACE INTO syntax if you want to overwrite an old record with a new one with the same key. Or, you can use INSERT... ON DUPLICATE KEY UPDATE syntax if you want to perform an update to the record instead when you encounter a duplicate. Edit: Thought I'd add some examples. Examples Say you have a table named tbl with two columns, id and value. There is one entry, id=1 and value=1. If you run the following statements: REPLACE INTO tbl VALUES(1,50); You still have one record, with id=1 value=50. Note that the whole record was DELETED first however, and then re-inserted. Then: INSERT IGNORE INTO tbl VALUES (1,10); The operation executes successfully, but nothing is inserted. You still have id=1 and value=50. Finally: INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200; You now have a single record with id=1 and value=200.
{ "pile_set_name": "StackExchange" }
Q: Should [cascade] be used for CSS? Or better retag to [css-cascade]? I saw that some questions use the tags css and cascade. However, the description says cascade should only be used for something about relational databases. In fact, among the more than 900 questions in cascade, only twenty-something had the css tag too. This made me think these questions are wrongly tagged. Therefore, I decided to create the css-cascade tag, and retag the csscascade questions. I didn't ask it in meta at first because there were so few questions. My fault, I should had. While doing the retagging, I saw that some of these cascade tags in css questions were added by BoltClock ♦. I guess a moderator knows more than me, so now I'm not sure whether I was doing something wrong? A: That was so long ago I don't even remember adding that tag to those questions. Looking at it now I don't think I would be comfortable having that tag around because it is ambiguous. The wiki that was added serves to reinforce the ambiguity. I think your decision to create a more specific css-cascade tag was good. If nothing else it corresponds to the css-cascade specification. I will retag the rest of the CSS questions. As there are 900 other questions with the cascade tag I'm not going to touch the rest. (In the next episode: should css-cascade and css-specificity be merged? Many, many questions conflate the two terms when in reality they mean completely different things, but is keeping them separate useful?)
{ "pile_set_name": "StackExchange" }
Q: Is all DOM nodes inherit from DOM Node interface? I'm confusing about this point since almost all DOM nodes are some sub-interface of the Node interface, but I can't find the precise definition that can prove this. Is there anybody know more about this? thanks. A: Yes, all nodes inherit from the DOM Node interface: The following interfaces all inherit from Node’s methods and properties: Document, Element, CharacterData (which Text, Comment, and CDATASection inherit), ProcessingInstruction, DocumentFragment, DocumentType, Notation, Entity, EntityReference And also, according to W3: The Node interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. While all objects implementing the Node interface expose methods for dealing with children, not all objects implementing the Node interface may have children. For example, Text nodes may not have children, and adding children to such nodes results in a DOMException being raised.
{ "pile_set_name": "StackExchange" }
Q: How to get webpack4 chunkhash value to use in script src inside the html automatically? How can I get the chunkhash value generated by webpack4 so that I can use it inside my index.html to set properly the script src? Brief context: Hope it not to be a stupid question because I am completely newcomer in webpack, started to learn today. I know how to config, extract js, css, minify them, and maybe all the very basic operations. This is my webpack.config.js: const path = require('path') const webpack = require('webpack') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const OptmizerCssAssetsPlugin = require('optimize-css-assets-webpack-plugin') const TerserPlugin = require('terser-webpack-plugin') module.exports = { entry: './src/index.js', output: { path: path.resolve('dist'), filename: '[chunkhash].bundle.js' // <<<<<< }, mode: 'development', optimization: { minimizer: [ new TerserPlugin({}), new OptmizerCssAssetsPlugin({}) ], splitChunks: { chunks: 'all' } }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { cacheDirectory: true } } }, { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader }, 'css-loader' ] } ] }, plugins: [ new webpack.ProvidePlugin({ cowsay: 'cowsay-browser' }), new MiniCssExtractPlugin({ filename: 'css/[name].css' }) ] } The relevant part is in filename: '[chunkhash].bundle.js' that will produce a filename like 6f9e5dd33686783a5ff8.bundle.js. I can use that name in my html like <script src="dist/6f9e5dd33686783a5ff8.bundle.js"></script> but I would have to change it everytime the code was updated/regenerated. I was able to use filename: '[name].bundle.js' instead of the chunkhash but it is not good for caching porpouses. So, is there any way I can get the chunkhash value and use it to set my script src filename in my index.html automatically everytime I build the project? Any valid advice will be wellcome! A: Ok, I found a way. I used the plugin below because it let me use my html as a template file. I just had to remove link and script tags and let it insert them in final html that it will generate. This is how I done: 1 - Install html-webpack-plugin npm i -D html-webpack-plugin 2 - Move my /index.html as /src/main.html Because my configs will generate a file named index.html. Rename template as main.html avoids possible confusions 3 - Add it to plugins secion of webpack.config.js // ... other imports here ... // const HtmlPlugin = require('html-webpack-plugin') module.exports = { entry: './src/index.js', output: { path: path.resolve('dist'), filename: '[chunkhash].bundle.js' // **** using chunkhash }, mode: 'development', optimization: { minimizer: [ new TerserPlugin({}), new OptmizerCssAssetsPlugin({}) ], splitChunks: { chunks: 'all' // **** config the WebPack SplitChunksPlugin } }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { cacheDirectory: true } } }, { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader }, 'css-loader' ] } ] }, plugins: [ new webpack.ProvidePlugin({ cowsay: 'cowsay-browser' }), new MiniCssExtractPlugin({ filename: 'css/[contenthash].css' // **** using contenthash }), // **** new config: new HtmlPlugin({ filename: 'index.html', template: path.resolve('src', 'main.html') }) ] } 4 - That is all! Now, when I build my project, my /src/main.html is parsed, all css link tags and script js tags are inserted automatically in a new /dist/index.html file (see below): <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Vacapack</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- LOOK THIS: //--> <link href="css/7358f9abc5c8cea68707.css" rel="stylesheet"></head> <body> <pre id="caixa"></pre> <!-- AND THESE: //--> <script type="text/javascript" src="b6183f7997b49195d1f8.bundle.js"></script> <script type="text/javascript" src="0e374d6ca9b34e89e18f.bundle.js"></script></body> </html> Hope it can help some one else!
{ "pile_set_name": "StackExchange" }
Q: AS3/Flex Override function in imported swf I'm using a flex component that use a to load a .swf file. The loaded .swf - is passed to me as is and I can't edit - it has some as3 functions in it Is it possible in the "parent" application (the one with ) to override functions included in the "child" swf (the imported one)? And if it's possible, how? Thanks A: I don't completely understand what you're asking. It sounds to me like you're loading a SWF at runtime, and want to extend / override methods in that SWF at runtime. As far as I know there is no way to do that. You'll have to extend the SWF code in the SWF at compile time. Without the code I Do not believe it is possible. If you can get the source code, or get the code as a SWC then you can override and extend the code easily. IF you share some source code, it may help solidify your request.
{ "pile_set_name": "StackExchange" }
Q: owin Error on first run after installing a customers site umbraco 7 site I get this error on a 7.3 umbraco build: The following errors occurred while attempting to load the app. - The OwinStartupAttribute.FriendlyName value 'UmbracoDefaultOwinStartup' does not match the given value '' in Assembly 'umbraco, Version=1.0.5750.18164, Culture=neutral, PublicKeyToken=null'. - No assembly found containing a Startup or [AssemblyName].Startup class. To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config. To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config. Any ideas? I've even removed owin.dll from the bin folder and the reference from the solution, also added to the web.config <add key="owin:AutomaticAppStartup" value="false" /> and still get the same error? Thanks A: If you insert the following web.config appSettings, it should spring to life: <add key="owin:AutomaticAppStartup" value="true" /> <add key="owin:appStartup" value="UmbracoDefaultOwinStartup" /> I received this error after upgrading 7.2.8 -> 7.4.1. After performing the above, Umbraco claimed it could not find System.Object. This was resolved by adding the following to the assemblies section: <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> Furthermore; if you receive any dependency mismatches (I received a message that 'umbraco' was attempting to use Microsoft.Owin 2.1.0, despite the latest Umbraco NuGet shipping with 3.0.1.0), you may need to add the following to the assemblyBinding section: <dependentAssembly> <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> </dependentAssembly>
{ "pile_set_name": "StackExchange" }
Q: Ajax to ActionResult, getting Model I have an action (Index) that return a View with a concrete model. Inside that view (Is a calendar) I have two buttons to change months. When I click one of those I call back Index action to that will return the same view with a modified model. $("#right").live("click", function () { $.post($(this).attr("href"), function (response) { $("#wrapper").replaceWith($(response).filter("div#wrapper")); }); return false; }); So, I click #right and it call /Home/Index and Index return something like: return View(new DateViewModel(dt, _bDays.GetDaysFromMonth(dt))); So as you see, I replace div#wrapper with the new one. Perfect but... Is there a way to get the model of the response? I mean, that action return a view with a model and apart from getting the concrete div I want the model. Any idea? A: I don't know why you would need the model in the AJAX callback, and thus there is probably a better solution than the one I am about to propose. So you could have your controller action render the partial view into a string and then return a JSON object containing both the HTML and the model: [HttpPost] public ActionResult MyAction() { MyViewModel model = new DateViewModel(dt, _bDays.GetDaysFromMonth(dt)); string html = RenderPartialToString("partialName", model); return Json(new { Model = model, Html = html }); } and in your AJAX callback: $.post($(this).attr("href"), function (response) { var model = response.Model; var html = response.Html; $("#wrapper").replaceWith($(html).filter("div#wrapper")); });
{ "pile_set_name": "StackExchange" }
Q: collision & touch + shoot methods for Android I really need help. I am making a game app for my final year project. It is a simple game where you have to shoot a ball into a target by rebounding of walls or angled blocks. However i need help in 2 areas: the shooting mechanism is similar to that of stupid zombies. There is a crosshairs where you touch on the screen to indicate which direction you want the ball to be shot at. On release the ball should move into that direction and hopefully gets into the target and if not gravity and friction causes it to come to a stop. The problem is how do I code something like this? I need the ball to rebound of the walls and I will have some blocks angled so that the ball has to hit a certain part to get to the target. The ball will eventually come to a stop if the target is not reached. How can I make a method to create the collisions of the wall and blocks? I have spent the last weeks trying to find tutorials to help me make the game but have not found much specific to the type of game I am making. It would be great if sample code or template could be provided as this is my first android app and it is for my final year project and i do not have much time left. Thank you in advance akkki A: Your question is too generic for stack overflow no one is going to do your project for you. Assuming you have basic programming experience if not get books and learn that first. Assuming you already chose Android because of your tag, and assuming 2d game as it is easier. Pre requests: Install java+eclipse+android sdk if you havent already. Create a new project and use the lunar landar example, make sure it runs on your phone or emulator. Starting sample: The lunar landar has a game loop a seperate thread which constantly redraws the whole screen, it does this by constantly calling the doDraw function. You are then supposed to use the canvas to draw lines, circles, boxes, colours and bitmaps to resemble your game. (canvas.draw....) Lunar landar does not use openGL so its slower but much easier to use. Stripping the sample: You probably don't want keyevents or the lunar spaceship! Delete everything in the onDraw function Delete the onKeyUp, onKeyDown Delete any errors what happen Create a new @Override public boolean onTouchEvent(MotionEvent event){ return false; } Run it you should get a blank screen, this is your canvas to start making your game... You mentioned balls, break it down to what a ball is: A position and direction, create variables for the balls x,y direction_x and direction_y the touch event will want to change the balls direction, the draw event will want to move the ball (adding the direction x,y to the ball x,y) and draw the ball (canvas.drawCircle(x,y,radius,new Paint())) want more balls search and read about arrays. Most importantly start simple and experiment. 2 collisions Collisions can be done in the dodraw function and broken down to: moving an object, checking if that object has passed where it is supposed to go and if so move it back before anyone notices.... There are many differently techniques of collision detection: If your walls are all horizontal and vertical (easiest) then box collisions checks the balls new x,y+-radius against a walls x,y,width and height its one big if statement and google has billions of examples. If your walls are angled then your need line collision detection, you basically have a line (vector) of where your ball is heading a vector of your wall create a function to check where two lines collide and check if that point is both on the wall and within the radius of your ball (google line intersection functions) or you can use colour picking, you draw the scene knowing all your walls are red for example, then check if the dot where the new ball x,y is, is red and know you hit Good luck, hope this helped a little, keep it simple and trial and error hopefully this gets you started and your next questions can be more specific.
{ "pile_set_name": "StackExchange" }
Q: OWASP | ZAP | SQL Injection | Scan Report When SQL injection is executed through FUZZ along with the inbuilt payload. The scan result shows multiple column along Code, Reason, State, and Payloads. How do i analyse this columns (Code, Reason, State, and Payloads) for the posted request A: Any fuzzing activity requires manual review and confirmation by the user. Without much much more detail as to the app, functionality, and output we can't tell you how to go about analyzing fuzzer results. Essentially you'd have to review the fuzz results in contrast to the original (known good) request/response. Here are some resources that might help you: https://www.owasp.org/index.php/SQL_Injection https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OTG-INPVAL-005) https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.md If you aren't sure how HTTP communication, various attack techniques, etc work then it might be best (from multiple perspectives: time, budget/cost, effectiveness, sanity, etc) to engage your security team or contract the assessment work out to a third party.
{ "pile_set_name": "StackExchange" }
Q: C unable to read from array of strings out of function I wrote a function that scans a directory and copies all file names in it to a char** that I pass as a parameter, I'm using dirent.h to get the files in the directory, here is my main & the function: int main(void) { char** files = 0; int size = 0, i = 0; size = scanDir(files, "C:\\Users\\user\\test"); for (i = 0; i < size; i++) { puts(files[i]); free(files[i]); } free(files); getchar(); return 0; } int scanDir(char** files, char* path) { int size = 0, i = 0; DIR* dp = 0; struct dirent* ep = 0; files = (char**)malloc(sizeof(char*) * size); dp = opendir(path); if (dp != NULL) { while (ep = readdir(dp)) { files = realloc(files, sizeof(char*) * ++size); files[i] = (char*)malloc(sizeof(char) * (strlen(ep->d_name) + 1)); strcpy(files[i], ep->d_name); i++; } (void)closedir(dp); } return size; } I'm using visual studio and during debugging files[i] within scanDir does contain the correct filename in each iteration of the while loop but in the for loop, it crashes and in the variable watch it says the it is "unable to read memory" under files Why is that happening? A: files is passed by value, and so when scanDir assigns to it and returns, the change doesn't propagate back to the caller. I am afraid you need another level of indirection (char***). int main(void) { char** files = 0; size = scanDir(&files, "C:\\Users\\user\\test"); ... } int scanDir(char*** files, char* path) { ... *files = (char**)malloc(sizeof(char*) * size); ... } Alternatively, you could change the scanDir signature to return the newly allocated char** pointer along with the size.
{ "pile_set_name": "StackExchange" }