text
stringlengths
64
89.7k
meta
dict
Q: How to compress file and take a backup in centos i have a dedicated server running centos. i want to know, how to take a backup of my files in [ var/www ] , file size is very big, it can be around 100GB+ , so i want to compress it using zip, or tar.gz anything will work. can anyone please provide the centos command line for it, how to download all files from var/www by compressing to make the size smaller. A: Issue the Command: # tar cvzf backup.tar.gz /var/www Where: c - create backup v - verbose output z - compress in gzip f - backup file name The backup will be created in your current working directory. Use ls command to list it
{ "pile_set_name": "StackExchange" }
Q: What's 8BITMIME? what's 8bitmime? waht's the defference of 7bit and 8bit? How to understand them? A: SMTP was originally specified using the pure ASCII character set. What a lot of people forget (or never get taught) is that the original ASCII is a 7-bit character set. With much of the computing world using octets (8-bit bytes) or multiples thereof, some applications started, very unwisely, using the 8th bit for internal use, and so SMTP never got the chance to easily move to an 8-bit character set. 8BITMIME, which you can read about in excruciating detail in RFC 1652, or in a decent summary at wikipedia, is a way for SMTP servers that support it to transmit email using 8-bit character sets in a standards-compliant way that won't break old servers. In practice, most of the concerns that led to this sort of thing are obsolete, and a lot of SMTP servers will even happily send/receive 8-bit character sets in "plain" SMTP mode (though that's not exactly the wisest decision in the world, either), but we're left with this legacy because, well, "if it ain't broke" (for very strict definitions of "broke")...
{ "pile_set_name": "StackExchange" }
Q: Sublime Text shows "NUL" characters in build output I've coded a simple Red "Hello world" program in Sublime Text 3: Red [] print "Hello world!" I've also created a build system that I'm trying to use to compile and run the program, where G:\Red Programming Language\redlang.exe is the Red programming language compiler that I downloaded from the Windows link here: { "shell_cmd": "\"G:\\Red Programming Language\\redlang\" \"$file\"" } The problem is that whenever I use my build system on a saved program, a strange NUL character appears between each character of the build output: This doesn't happen with any other build system I have installed. The output appears fine if I run the redlang.exe from the Command Prompt, so it's probably an issue with my Sublime Text setup; I'm using Sublime Text Build 3083 and Windows 10. How can I get rid of those NUL characters? A: The output of Red programs on Windows is using the native UTF-16LE encoding, which is the cause of the NUL characters you are seeing, as Sublime's output capturing defaults to UTF-8. You need to change it in your build system using the encoding command as described in the Sublime build system documentation. So you might try something like: { "shell_cmd": "\"G:\\Red Programming Language\\redlang\" \"$file\"", "encoding": "UTF-16LE" } See the supported encodings list here. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: How can I increase the size of numbers which appear above the Bar Chart I am using Bar chart component from https://code.google.com/p/achartengine/ and I want just to increase the text size of labels which appear above the chart I mean I want to make numbers (4,5) bigger that now I tried the following code : renderer.setAxisTitleTextSize(24); renderer.setChartTitleTextSize(24); renderer.setLabelsTextSize(24); renderer.setLegendTextSize(24); but I didn't get any difference What should I do to achieve that ? A: This line r.setChartValuesTextSize(24); solve the problem The complete code : protected XYMultipleSeriesRenderer buildBarRenderer(int[] colors) { XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(); renderer.setAxisTitleTextSize(24); renderer.setChartTitleTextSize(24); renderer.setLabelsTextSize(24); renderer.setLegendTextSize(24); int length = colors.length; for (int i = 0; i < length; i++) { XYSeriesRenderer r = new XYSeriesRenderer(); r.setLineWidth(24); r.setColor(colors[i]); // here is the magic r.setChartValuesTextSize(24); renderer.addSeriesRenderer(r); } return renderer; }
{ "pile_set_name": "StackExchange" }
Q: What is the difference between "Topic" and "Focus" What is the difference between grammatical categories "Topic" and "Focus"? They are both optional, and they succeed "Force" and they both seem to stress a part of text. Rizzi places them in the following order: ... Force ... (Topic) ... (Focus) ... fin IP But the difference between them is not clear to me. One of the things I found is that Topic allows known information to be fronted, whereas Focus introduces new information. Though that can't be all, right? I mean, I think it would be strange to solely base such a theory on Information Structure. A: I am slightly puzzled by the fact that you seem to know Rizzi's work but not the answer to this question, but anyway. This answer entirely presupposes the framework in which L.Rizzi is working. Rizzi's aim is to describe the articulation of what he calls the complementizer layer CP of a sentence. He remarks that this part of the sentence (typically found at the left periphery of the clause, and universally so if one believes in R.Kayne's antisymmetry principle) may contain several projections which typically differ in syntactical properties and semantic interpretation. Among them, the one he calls Topic hosts topicalized elements (for the moment, by definition). In Romance, a characteristic property of an element in that position is that it is left-dislocated and replaced by a coreferential clitic pronoun. Le livre que tu m'as conseillé, je l'ai adoré. (The book that you me recommended, I it have adored) Focus hosts elements in focus (again, for the moment, by definition) and is distinguished in Romance from Topic by a number of properties: most saliently focal stress, the necessity for the sentence to be contrastive and the fact that there may be only one Focus position. L.Rizzi also gives a number of much more subtle diagnosis (weak cross over, quantificational properties...) For instance (focal stress in bold): Ton livre, je l'ai adoré. Pas celui de Nolan. (Your book, I it have adored. Not Nolan's). Now part of the difficulty is that even though these two functional projections are usually easily distinguished in Romance, hence my stress on this family of languages above, the distinction might be quite mysterious or elusive in other languages. For instance, the topic position in Finnish seems to be the normal subject position and as such entirely unmarked. At the other side of the spectrum, some languages mark theses positions overtly, as does the post-position も in Japanese with Focus (but note that Japanese tolerates multiple Focus positions, contrary to Romance). As usual with syntax anyway, more subtle characterizations will depend on what you intend to do with these categories. References: L.Rizzi The fine structure of the left periphery in Elements of grammar: Handbook in generative syntax. S.Miyagawa Why agree? Why move? Linguistics Inquiry Monograph 54. UPDATE: I can't believe I forgot to cite the following truly wonderful poem. I can't see how anyone could wonder about Topic and Focus ever after. On functional structure
{ "pile_set_name": "StackExchange" }
Q: Shared primary key but want to manage/save entities separately? Note : I am a hibernate newbie. I am currently trying to model 2 entities in spring that have the same primary key and a OneToOne relationship. Table 1 : CREATE TABLE person ( id uuid NOT NULL, name varchar(10000), CONSTRAINT pk_person_id PRIMARY KEY (id) ) Table 2 : CREATE TABLE nickname ( id uuid NOT NULL, nick varchar(10000), CONSTRAINT pk_nickname_id PRIMARY KEY (id), CONSTRAINT fk_person_id FOREIGN KEY (id) REFERENCES person(id) ON DELETE CASCADE ) Java classes: @Getter @Setter @NoArgsConstructor @Entity @ToString @Table(name = "Person") public class Person { @Id private UUID id; @Column(name = "name") private String name; } @Getter @Setter @NoArgsConstructor @Entity @ToString @Table(name = "person") public class NickName { @Id private UUID id; @Column(name = "nick") private String nick; @MapsId @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id") private Person person; } 1) The behavior I want is to allow saving objects of Person class separately ie not save them as part of the call to save Nickname. 2) For a subset of Persons, I may wish to create a Nickname. Each person in this hypothetical example can only have one nickname. 3) When saving nicknames, I don't want the person object to also be saved. It may be that the person may exist beforehand and the nickname is added later. I currently get an exception regarding the entity already existing when trying to save Nickname object via NicknameRepository.save(nickname) where nickname object is initialized with nick and person objects, in the case that the person already exists. 4) I do want the primary key ids to be the same, and the id being a foreign key from Nickname --> Person 5) I don't want to save or add the nickname when saving the person object either. 6) When adding a nickname for an existing person, i would rather pass just the id of the Person instead of the entire object. Currently, I am forced to pass the Person object in its entirety. Would be great if somebody could help! A: I went ahead with the following which served my requirements. @Getter @Setter @NoArgsConstructor @Entity @ToString @Table(name = "Person") public class Person { @Id private UUID id; @Column(name = "name") private String name; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.DETACH) @PrimaryKeyJoinColumn @Fetch(FetchMode.JOIN) private NickName nickName; } @Getter @Setter @NoArgsConstructor @Entity @ToString @Table(name = "nickname") public class NickName { @Id private UUID id; @Column(name = "nick") private String nick; }
{ "pile_set_name": "StackExchange" }
Q: Grep / awk greater than date I'm sure this is an easy one for the Gurus. I'm working on my get things done and todo system. At the moment I've simply got a markdown file which I edit in VI and set tags against my things to do. It looks like this # My project | @home - Do this this | @home I think sync this file across my devices and use tasker / grep on android to show me the todo based on where I am. I've now got to the stage where I want to add things to do in the future so I was thinking of something like - Do this thing in the future | @home @2014-02-01 How could I exclude that line until the date is 2014-02-01? My current command for just extract @home todos is grep -e "@home" myfile | cut -d '|' -f1 I'm convinced there's a way of doing this, but google / stackoverflow hasn't lead me the right direction yet! Help appreciated, Thanks Alan A: Using Perl perl -MTime::Piece -ne ' BEGIN {$now = localtime} print unless /@(\d{4}-\d\d-\d\d)/ and $now < Time::Piece->strptime($1, "%Y-%m-%d") ' <<END # My project | @home - Do this this | @home - Do this thing in the future | @home @2014-02-01 END # My project | @home - Do this this | @home Also, GNU awk gawk ' BEGIN {now = systime()} match($0,/@([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])/, m) { time = mktime(m[1] " " m[2] " " m[3] " 0 0 0") if (time > now) next } 1 ' A: Using awk: DAT=$(date +%Y%m%d) # get today's date, for example 20140117 awk 'NF>3{gsub(/-/,"",$NF);if ($NF>d) next}{print $1}' FS="[|@]" d=$DAT file # My project - Do this this
{ "pile_set_name": "StackExchange" }
Q: Isotope URL Hash not working when called on page load I've got an issue with Isotope where I've switched to the URL Hash method of filtering because I need to be able to send visitors to the page with a filter already active. When I use the filter normally - i.e. page load is unfiltered and clicking a button activates a filter, everything works as expected. When arriving from another page with the hash in the URL, it does activate the filtering, but it doesn't properly hide the remaining items - instead they're all bunched up at 0,0 absolute and not hidden. Only the filtered items are laid out properly, like so (properly filtered items have been blurred for a level of privacy): This is the code I already have: <script> (function( $ ){ function getHashFilter() { var hash = location.hash; // get filter=filterName var matches = location.hash.match( /filter=([^&]+)/i ); var hashFilter = matches && matches[1]; return hashFilter && decodeURIComponent( hashFilter ); } $( function() { var $container = $('.blogGrid'); // bind filter button click var $filters = $('.filter-button-group').on( 'click', 'button', function() { var filterAttr = $( this ).attr('data-filter'); // set filter in hash location.hash = 'filter=' + encodeURIComponent( filterAttr ); }); var isIsotopeInit = false; function onHashchange() { var hashFilter = getHashFilter(); if ( !hashFilter && isIsotopeInit ) { return; } isIsotopeInit = true; // filter isotope $container.isotope({ itemSelector: '.blogItem', percentPosition: true, layoutMode: 'fitRows', filter: hashFilter }); // set selected class on button if ( hashFilter ) { $filters.find('.is-checked').removeClass('is-checked'); $filters.find('[data-filter="' + hashFilter + '"]').addClass('is-checked'); } } $(window).on( 'hashchange', onHashchange ); // trigger event handler to init Isotope onHashchange(); }); })( jQuery ); </script> I'm in Joomla, so I also have the ability to send variables by user session - but I couldn't see an Isotope method that would work that way? A: It turns out that the filtering was occurring before layout was complete, so there was no final arranging of filtered items. I just added $(document).ready(function(){ $container.isotope(); }); To the bottom of the script to trigger a re-arrangement after the document finished loading. That seems to have sorted it.
{ "pile_set_name": "StackExchange" }
Q: Get JSON text from WKWebView I want to get the contents of http://www.devpowerapi.com/fingerprint from a WKWebView evaluateJavaScript("document.documentElement.innerHTML") returns <head></head><body></body> instead of the actual JSON Is it possible to get the contents with a WKWebView? A: Simplest way to do this (works for this specific case): webView.evaluateJavaScript("document.getElementsByTagName('pre')[0].innerHTML", completionHandler: { (res, error) in if let fingerprint = res { // Fingerprint will be a string of JSON. Parse here... print(fingerprint) } }) Possibly better way to do this: So .innerHTML returns HTML, not a JSON header. JSON headers are notoriously difficult to grab with WKWebView, but you could try this method for that. First set: webView.navigationDelegate = self And then in the WKNavigationDelegate method: public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { let res = navigationResponse.response as! HTTPURLResponse let header = res.allHeaderFields print(header) }
{ "pile_set_name": "StackExchange" }
Q: How to get starting date in a Week based on week number using vb.net? I need help on getting the starting date of a week from a given week number in vb.net. I have combobox binded with items 1-53 as week numbers. What I want to do is whenever I select a specific week number, it will return the first date of that selected week number. For instance I have selected week Number 46, it must return November 11, 2013 as first date of week number 46. I have tried the following codes and it returns only the first date of a week from a current week number. DateAdd("d", -Weekday(Now, FirstDayOfWeek.Monday) + 1, Now) Is there any possible way that can return my expected output? Please help me. Thanks in advance. A: You could try something like this: Private Sub TestDateAdd() Dim weekStart As DateTime = GetWeekStartDate(46, 2013) Console.WriteLine(weekStart) End Sub Private Function GetWeekStartDate(weekNumber As Integer, year As Integer) As Date Dim startDate As New DateTime(year, 1, 1) Dim weekDate As DateTime = DateAdd(DateInterval.WeekOfYear, weekNumber - 1, startDate) Return DateAdd(DateInterval.Day, (-weekDate.DayOfWeek) + 1, weekDate) End Function Disclaimer: I only really tested this with the one input, you probably want to make sure that it works as expected for different years, etc..
{ "pile_set_name": "StackExchange" }
Q: How to extend the timeout of a SQL query This is not a connection timeout as a connection to the database is made fine. The problem is that the stored procedure that I'm calling takes longer than, say, 30 seconds and causes a timeout. The code of the function looks something like this: SqlDatabase db = new SqlDatabase(connectionManager.SqlConnection.ConnectionString); return db.ExecuteScalar(Enum.GetName(typeof(StoredProcs), storedProc), parameterValues); The ExecuteScalar call is timing out. How can I extend the timeout period of this function? For quick stored procedures, it works fine. But, one of the functions takes a while and the call fails. I can't seem to find any way to extend the timeout period when the ExecuteScalar function is called this way. A: If you are using the EnterpriseLibrary (and it looks like you are) try this: Microsoft.Practices.EnterpriseLibrary.Data.Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("ConnectionString"); System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName"); cmd.CommandTimeout = 600; db.AddInParameter(cmd, "ParameterName", DbType.String, "Value"); // Added to handle paramValues array conversion foreach (System.Data.SqlClient.SqlParameter param in parameterValues) { db.AddInParameter(cmd, param.ParameterName, param.SqlDbType, param.Value); } return cmd.ExecuteScalar(); Edited to handle the paramValues array directly based on the comments. I also included your ConnectionString value: Microsoft.Practices.EnterpriseLibrary.Data.Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase(connectionManager.SqlConnection.ConnectionString); System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName", parameterValues); cmd.CommandTimeout = 600; return cmd.ExecuteScalar(); A: you do this by setting the SqlCommand.CommandTimeout property A: I think this might be a better way to do this (as of Enterprise Library 6.0): SqlDatabase db = new SqlDatabase(connectionManager.SqlConnection.ConnectionString); System.Data.Common.DbCommand cmd = db.GetStoredProcCommand(storedProc, parameterValues); cmd.CommandTimeout = 600; return db.ExecuteScalar(cmd);
{ "pile_set_name": "StackExchange" }
Q: Is it possible to apply changes to all objects in Array without using "for each" or "for" in Swift 3? for example var imageViewArray:UIImageView = [imageView1,imageView2,imageView3] I want to chage sameimageView.image = img or imageView.isUserInteractionEnabled = false to all Image View inside the array A: 1. It's an array First of all it's not var imageViewArray:UIImageView but var imageViewArray:[UIImageView] because you want an array of UIImageView right? 2. Naming conventions Secondly is Swift we don't name a variable after it's type so imageViewArray becomes imageViews. 3. map Now if you really hate the for in and the foreach your can write imageViews = imageViews.map { imageView in imageView.isUserInteractionEnabled = true return imageView } or as suggested by Bohdan Ivanov in the comments imageViews.map { $0.isUserInteractionEnabled = true } 4. Wrap up This answer shows you how to use the wrong construct (map) to do something that should be made with the right construct (for in). That's the point of having several constructs, everything could be made with an IF THEN and a GOTO. But a good code uses the construct that best fits that specific scenario. So, the best solution for this scenario is absolutely the for in or the for each imageViews.forEach { $0.isUserInteractionEnabled = true }
{ "pile_set_name": "StackExchange" }
Q: Error after upgrading Angular 5 to 6 , VSTS build After upgrading from Angular 5 to 6 i have got it up and running locally. It runns in builds and build --prod . I do have it in an .NET MVC application. However when the build on VSTS goes through it pops up some errors. It says. node_modules\@angular\compiler\src\output\output_ast.d.ts(602,15): Error TS2474: Build:In 'const' enum declarations member initializer must be constant expression. node_modules\@angular\core\src\render3\interfaces\container.d.ts(35,5): Error TS1169: Build:A computed property name in an interface must directly refer to a built-in symbol. node_modules\@angular\core\src\sanitization\bypass.d.ts(55,14): Error TS2535: Build:Enum type 'BypassType' has members with initializers that are not literals. It is only the build on VSTS that fails and it comes in the process of CompileTypeScriptWithTSConfig: I do run typescript version 2.7.2 and i have set the csproj Typescript version to 2.7 . As Visual studio doesnt have support for 2.9.2 and Angular 6.1.4 doesnt support version 3.0.0 A: Your VSTS build must be using a version of TypeScript older than 2.7, because the error message A computed property name in an interface must directly refer to a built-in symbol. does not exist in 2.7 and newer. It looks like you'll need to use at least 2.7 to compile those type declaration files. I don't know what controls the TypeScript version of your VSTS build; if you provide more information, I may be able to help more.
{ "pile_set_name": "StackExchange" }
Q: SOLR df and qf explanation I cannot find an adequeate explanation of how these query params interact I am getting suprising (to me) results that if I specify qf=title^20 description^10 then I get no results however if I then add df=description I do get results df is set to text in solrconfig.xml - which will change - but my question is this - does the df setting somehow override the qf setting? this seems odd A: df is the default field and will only take effect if the qf is not defined. I guess you are not using dismax parser and using the default settings in solrconfig.xml qf then won't take effect anyways and the df field which is text would not return values. df=description searches on the field and hence returns values. Try passing defType=edismax as parameter.
{ "pile_set_name": "StackExchange" }
Q: How to have photos received in an email automatically published to website? I email myself many photos that I post to my website. It is possible to have photos that are sent to an email of your own domain [email protected] automatically uploaded to a directory in your FTP server? Possibly with PHP? Any advice is appreciated A: Yes but it will be pretty complex. If you are using cPanel you can pipe emails to a PHP script. Otherwise you could use a cron job that runs a PHP script that connects to the email inbox to achieve the same purpose. On the PHP script you would need to break up the email into its components including the attachment. You can then use that information to write it to the server and whatever else you need to do with the data.
{ "pile_set_name": "StackExchange" }
Q: Rhythmbox: How to edit track order of playlist? I've looked around for quite a while and was surprised to not have found any information on this: How is it possible to change the track order of a playlist I've created in Rhythmbox 3.02? Simple drag-and-drop does not work and there seems to be no other obvious way. A: It depends on the kind of playlist you created. Automatic Playlist If you created an "Automatic" playlist (i.e. one that has rules for including/excluding various kinds of files), you can change the order only by changing the sort criterion in the playlist edit box. Here's what the Edit Automatic Playlist dialog looks like: To change your sort order: Click the checkbox beside "Limit to:" This will enable the "When sorted by:" controls on the next line. Choose the field by which you want your tracks sorted (Album, Artist, etc). You can also choose whether to sort in ascending or descending order. If you don't want to limit the number of tracks in your playlist, uncheck the checkbox you enabled in step 1. Click the Close button and you're done! Static Playlist RhythmBox refers to playlists where you've explicitly added specific songs as Static. When you populate static playlists, RhythmBox always adds new tracks to the end, so you could change the order of this list by removing and adding tracks until they're in the order you want. Bleah. Fortunately, there is a somewhat easier way. Rhythmbox stores the content for the static playlists, along with the rules for the Automatic ones, in a human-readable XML file. In order to change the order, you have to edit that file. The file's (default) path is: ~/.local/share/rhythmbox/playlists.xml. To change the order of a manually-created playlist: (NOTE: these instructions, while pretty basic, assume a certain amount of familiarity with Linux operations, like copying and editing files. If you don't know how to do these things, you'll need to look them up first.) Close RhythmBox, lest it overwrite the file you are about to edit. Navigate to the directory containing the playlist file. (~/.local/share/rhythmbox/) (Optional but HIGHLY RECOMMENDED!) Copy the playlists.xml file to a backup file, in case you screw up. (To do so in a terminal, enter something like this command: cp playlists.xml playlists-backup.xml .) Open the file (the original, not the backup) with your favourite text editor. Find the particular playlist you want to edit. Each playlist is a playlist element, consisting of: an opening <playlist> tag a location element for each track comprising the playlist, specifying the file path (Note that the file specifiers are URL-encoded, so – for instance – what would normally be a space in the file name will appear as %20. Take that into account if you are using your editor's search functionality to find a specific file!) a closing <playlist> tag Each playlist element has a name attribute (among others), so if the playlist you want to edit is called Main, you can search for name="Main". Move a song: (Note: These are very basic directions, aimed at beginners. Experienced users of text editors will not need these.) Find the file you want to move. highlight the entire line containing the location element of each track you want to move cut out the selected text (usually Ctrl+X will do this) place your cursor in the new location and paste the text you cut in the previous step (usually Ctrl+V) Repeat the previous step for each track you want to move. Save the file. (!) If you've done everything correctly, when you open RhythmBox, the songs should be in the order you want. If you haven't done everything correctly, RhythmBox may not be able to read the playlists file at all. It's a good thing you backed it up when you started all this, huh? You should be able to use the backup to figure out what you did wrong. This procedure is certainly nowhere near as nice as being able to drag and drop the songs from the RhythmBox GUI itself, but it's better than not being able to change the order at all.
{ "pile_set_name": "StackExchange" }
Q: Concatenating strings using foreach I'm trying to make a generated random characters. I'm concatenating the values of $char_type using foreach loop but it doesn't show anything. Here's my code: public function randomizer($range, $type) { $strtester = ''; $char_type = array('alp_sm' => 'abcdefghijklmnopqrstuvwxyz', 'alp_cs' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'num' => '0123456789', 'sp' => '!@#$%^&*()'); if(is_array($type)) { foreach($type as $row) { if(in_array($row, $char_type)) { $strtester .= $char_type[$row]; } } } print_r($strtester); exit(); $seed = str_split($strtester); shuffle($seed); $generated_string = ''; foreach (array_rand($seed, $range) as $k) $generated_string .= $seed[$k]; return $generated_string; } Update: What i want to get from $strtester is for example I want $char_type alp_sm and alp_cs then the $strtester will get abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ Thank you in advance A: Replace if(in_array($row, $char_type)) { to if(array_key_exists($row, $char_type)) { and then try function randomizer($range, $type) { $strtester = ''; $char_type = array('alp_sm' => 'abcdefghijklmnopqrstuvwxyz', 'alp_cs' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'num' => '0123456789', 'sp' => '!@#$%^&*()'); if(is_array($type)) { foreach($type as $row) { if(array_key_exists($row, $char_type)) { $strtester .= $char_type[$row]; } } } $seed = str_split($strtester); shuffle($seed); $generated_string = ''; foreach (array_rand($seed, $range) as $k) $generated_string .= $seed[$k]; return $generated_string; } $res = randomizer(5, array("alp_sm")); print_r($res);
{ "pile_set_name": "StackExchange" }
Q: Awk field separator behaviour Why this awk script: awk '{FS = "\t" ; print $1 " - " $2}' A.txt with this input file A.txt B A A1 C B A2 D A A3 outputs these results B - A C B - A2 D A - A3 Note that between first B and A there is a space and not a tab character. I double checked this A: I believe it's because FS is being set in the first action. Before the first action is invoked, the splitting of the first line is done already, and it uses the default FS (whitespace). So to get it consistent, you should invoke awk with -F option. A: The correct way is: BEGIN {FS = "\t"} { print $1 " - " $2} You are setting the FS too late (after the first line is splitted)
{ "pile_set_name": "StackExchange" }
Q: Has anyone migrated production machines from MySQL to MariaDB? I'm running MySQL for most of our DBs right now, and would like to get off the Oracle ship before it takes more of a turn. My understanding is that the transition from MySQL->MariaDB should be trivial, but going the other way is not so easy. Has anyone made this jump yet? Edit: Bonus points if you have anecdotal information on doing this with Debian/Ubuntu. A: I have migrated various servers from MySQL to MariaDB a few weeks ago without any problem. If you want the full list of what might not be compatible, you can have a look here: http://kb.askmonty.org/en/mariadb-versus-mysql-compatibility. If you're upgrading to a higher version of MariaDB than MySQL was, you just have to jsut the mysql_upgrade binary as stated on http://kb.askmonty.org/en/upgrading-to-mariadb-from-mysql. Moreover, with MariaDB 5.3 (released at the end of July), they now provide a proper repository, so there's no need to install by hand : http://downloads.askmonty.org/mariadb/repositories/
{ "pile_set_name": "StackExchange" }
Q: K8S Read config map via go API I’ve a config map which I need to read from K8S via api I Created a cluster role kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: zrole rules: - apiGroups: [""] resources: ["configmaps"] verbs: ["get", "list"] and cluster role binding kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: z-role-binding subjects: - kind: Group name: system:serviceaccounts apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: zrole Config Map apiVersion: v1 kind: ConfigMap metadata: name: z-config namespace: fdrs data: avr: client1 fuss: xurbz The code is used like clientSet.CoreV1().ConfigMaps(uNamespcae) when I run the code locally (and provide to the the GO api the kubeconfig) I was able to get the config map data, However when I run the code inside the cluster I got error: invalid token , any idea what am I missing here? A: Check automountServiceAccountToken in the pod spec. By default it's set to true, but maybe you have it disabled. Use the official GO client. It reads the correct configuration and tokens by default. https://github.com/kubernetes/client-go/blob/master/examples/in-cluster-client-configuration/main.go If you don't use it, then use the correct configuration: https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#directly-accessing-the-rest-api-1 Check the token in the pod: /var/run/secrets/kubernetes.io/serviceaccount/token and use the kubernetes service.
{ "pile_set_name": "StackExchange" }
Q: how to build a triangular slider? Good afternoon! I have a triangular slider design but no HTML: triangular slider design at the bottom How it functions: if you hover over a slide (a triagle) the slide grows a bit like this if you click on it a lightbox opens if you click on the gray next/prev arrows another set of 6 images appears I've tried to use CSS border-triangles+border-image rotating individual triangle images forth and their container back map tag for hover and click but no real solution. I appreciate anyone's help. A: what you want to do is possible via CSS3. It must be done thinking, that it will not be triangles for older browser. So, you start first building your slider in square shap. The second part is to rotate squares, hide half of it , and .... I copied one of my dabblet into liveweave.com, so you can open it in IE8 if you wish: http://liveweave.com/UU2oOZ it is not your solution, this menu is vertical), but it is an example that can help you to start someting.
{ "pile_set_name": "StackExchange" }
Q: Disable index temporarily in SQL server I have 1 table with more than 10 millions records of employee salary. I have created few indexes and testing on performance improvement based on that, But i am facing issue with disabling the index, as it says access to the table will not be available in case of disabling the index. So is there any way to disable the index and then check on trial error for the performance, in order to identify that improvement is due to index or not. Drop and re-create is a tedious process, and i want some alternative on the same. A: it can help ALTER INDEX indexName ON tableName DISABLE;
{ "pile_set_name": "StackExchange" }
Q: Python zero-values Are there any values other than False, None, 0, and 0.0 that will return False with bool(x) (in Python 3.X)? A: http://docs.python.org/py3k/library/stdtypes.html#truth-value-testing A: Any empty sequence or mapping object will also evaluate to False: >>> bool({}) False >>> bool([]) False >>> bool("") False >>> bool(()) False
{ "pile_set_name": "StackExchange" }
Q: Representation of -1 due to bit overflow? Hey I was trying to figure out why -1 << 4 (left) shift is FFF0 after looking and reading around web I came to know that "negative" numbers have a sign bit i.e 1. So just because "-1" would mean extra 1 bit ie (33) bits which isn't possible that's why we consider -1 as 1111 1111 1111 1111 1111 1111 1111 1111 For instance :- #include<stdio.h> void main() { printf("%x",-1<<4); } In this example we know that – Internal representation of -1 is all 1’s 1111 1111 1111 1111 1111 1111 1111 1111 in an 32 bit compiler. When we bitwise shift negative number by 4 bits to left least significant 4 bits are filled with 0’s Format specifier %x prints specified integer value as hexadecimal format After shifting 1111 1111 1111 1111 1111 1111 1111 0000 = FFFFFFF0 will be printed. Source for the above http://www.c4learn.com/c-programming/c-bitwise-shift-negative-number/ A: First, according to the C standard, the result of a left-shift on a signed variable with a negative value is undefined. So from a strict language-lawyer perspective, the answer to the question "why does -1 << 4 result in XYZ" is "because the standard does not specify what the result should be." What your particular compiler is really doing, though, is left-shifting the two's-complement representation of -1 as if that representation were an unsigned value. Since the 32-bit two's-complement representation of -1 is 0xFFFFFFFF (or 11111111 11111111 11111111 11111111 in binary), the result of shifting left 4 bits is 0xFFFFFFF0 or 11111111 11111111 11111111 11110000. This is the result that gets stored back in the (signed) variable, and this value is the two's-complement representation of -16. If you were to print the result as an integer (%d) you'd get -16. This is what most real-world compilers will do, but do not rely on it, because the C standard does not require it. A: First thing first, the tutorials use void main. The comp.lang.c frequently asked question 11.15 should be of interest when assessing the quality of the tutorial: Q: The book I've been using, C Programing for the Compleat Idiot, always uses void main(). A: Perhaps its author counts himself among the target audience. Many books unaccountably use void main() in examples, and assert that it's correct. They're wrong, or they're assuming that everyone writes code for systems where it happens to work. That said, the rest of the example is ill-advised. The C standard does not define the behaviour of signed left shift. However, a compiler implementation is allowed to define behaviour for those cases that the standard leaves purposefully open. For example GCC does define that all signed integers have two's-complement format << is well-defined on negative signed numbers and >> works as if by sign extension. Hence, -1 << 4 on GCC is guaranteed to result in -16; the bit representation of these numbers, given 32 bit int are 1111 1111 1111 1111 1111 1111 1111 1111 and 1111 1111 1111 1111 1111 1111 1111 0000 respectively. Now, there is another undefined behaviour here: %x expects an argument that is an unsigned int, however you're passing in a signed int, with a value that is not representable in an unsigned int. However, the behaviour on GCC / with common libc's most probably is that the bytes of the signed integer are interpreted as an unsigned integer, 1111 1111 1111 1111 1111 1111 1111 0000 in binary, which in hex is FFFFFFF0. However, a portable C program should really never assume two's complement representation - when the representation is of importance, use unsigned int or even uint32_t assume that the << or >> on negative numbers have a certain behaviour use %x with signed numbers write void main. A portable (C99, C11, C17) program for the same use case, with defined behaviour, would be #include <stdio.h> #include <inttypes.h> int main(void) { printf("%" PRIx32, (uint32_t)-1 << 4); }
{ "pile_set_name": "StackExchange" }
Q: Kill a blocker with an instant - is it still blocking? We are in the combat phase: I declared my attackers My opponent declared his blockers, stating which attackers he was blocking I cast an instant, which automatically kills his blocker. There is nothing blocking my attacker now Now we're in the damage phase. I said that my attacker now does damage and reduces my opponent's hit points. My opponent said that because my attacker was blocked no damage could be done. I pointed out that the blocker was destroyed before the damage phase, so therefore he wasn't blocking, but he wasn't having it. (My attacker does not have trample) Is this covered by a specific section in the rules? A: Your opponent was right. From the magic comprehensive rules (http://magic.wizards.com/en/gameinfo/gameplay/formats/comprehensiverules): 509.1h An attacking creature with one or more creatures declared as blockers for it becomes a blocked creature; one with no creatures declared as blockers for it becomes an unblocked creature. This remains unchanged until the creature is removed from combat, an effect says that it becomes blocked or unblocked, or the combat phase ends, whichever comes first. A creature remains blocked even if all the creatures blocking it are removed from combat. I bolded the relevant part.
{ "pile_set_name": "StackExchange" }
Q: Encrypt Sidekiq's connection to Redis We currently have Sidekiq setup with Azure Redis Cache and would like to encrypt the connection between them. After a little googling I came across a recently merged pull request that adds native encryption to Redis but this as of yet has not been released. I have seen people suggest Stunnel but I was wondering if there were any alternatives to this approach? A: Sidekiq uses the redis gem which has SSL/TLS support if you provide a connection URL using the rediss:// scheme (second 's' is not a typo). # https://github.com/redis/redis-rb/blob/1317ecb518c2d0d0263f1cfc49f104cea3ea24b3/lib/redis/cluster/option.rb#L29 class Redis class Cluster class Option DEFAULT_SCHEME = 'redis' SECURE_SCHEME = 'rediss' # ... def secure? @node_uris.any? { |uri| uri.scheme == SECURE_SCHEME } || @options[:ssl_params] || false end end end end I've used this with AWS ElastiCache which supports in-transit encryption. The Azure docs suggest Azure Cache has similar SSL capability.
{ "pile_set_name": "StackExchange" }
Q: How do I make CSS control my HTML table? I have a table similar to This one that looks like: <table class="DynaTable"> <tr class="DynaTableHead"> <th class="DynaTableHeadCell-1">col 1</th> <th class="DynaTableHeadCell-2">col 2</th> <th class="DynaTableHeadCell-3">col 3</th> <th class="DynaTableHeadCell-4">col 4</th> <th class="DynaTableHeadCell-5">col 5</th> </tr> <tr class="DynaTableRow"> <td class="DynaTableRowCell-1">cell 1-1</td> <td class="DynaTableRowCell-2">cell 1-2</td> <td class="DynaTableRowCell-3">cell 1-3</td> <td class="DynaTableRowCell-4">cell 1-4</td> <td class="DynaTableRowCell-5">cell 1-5</td> </tr> <tr class="DynaTableRow"> <td class="DynaTableRowCell-1">cell 2-1</td> <td class="DynaTableRowCell-2">cell 2-2</td> <td class="DynaTableRowCell-3">cell 2-3</td> <td class="DynaTableRowCell-4">cell 2-4</td> <td class="DynaTableRowCell-5">cell 2-5</td> </tr> <tr class="DynaTableRow"> <td class="DynaTableRowCell-1">cell 3-1</td> <td class="DynaTableRowCell-2">cell 3-2</td> <td class="DynaTableRowCell-3">cell 3-3</td> <td class="DynaTableRowCell-4">cell 3-4</td> <td class="DynaTableRowCell-5">cell 3-5</td> </tr> <tr class="DynaTableRow"> <td class="DynaTableRowCell-1">cell 4-1</td> <td class="DynaTableRowCell-2">cell 4-2</td> <td class="DynaTableRowCell-3">cell 4-3</td> <td class="DynaTableRowCell-4">cell 4-4</td> <td class="DynaTableRowCell-5">cell 4-5</td> </tr> </table> Want I want to do when the user loads the page on a mobile device, make it display like This one that looks like: <table class="DynaTable"> <tr class="DynaTableHead"> <th rowspan="2" class="DynaTableHeadCell-1">col 1</th> <th class="DynaTableHeadCell-2">col 2</th> <th class="DynaTableHeadCell-3">col 3</th> <th class="DynaTableHeadCell-4">col 4</th> <th class="DynaTableHeadCell-5">col 5</th> </tr> <tr class="DynaTableHead"> <th class="DynaTableHeadCell-X" colspan="3">col 3</th> </tr> <tr class="DynaTableRow"> <td rowspan="2" class="DynaTableRowCell-1">cell 1-1</td> <td class="DynaTableRowCell-2">cell 1-2</td> <td class="DynaTableRowCell-3">cell 1-3</td> <td class="DynaTableRowCell-4">cell 1-4</td> <td class="DynaTableRowCell-5">cell 1-5</td> </tr> <tr> <td class="DynaTableRowCell-X" colspan="3">cell 1-3</th> </tr> <tr class="DynaTableRow"> <td rowspan="2" class="DynaTableRowCell-1">cell 2-1</td> <td class="DynaTableRowCell-2">cell 2-2</td> <td class="DynaTableRowCell-3">cell 2-3</td> <td class="DynaTableRowCell-4">cell 2-4</td> <td class="DynaTableRowCell-5">cell 2-5</td> </tr> <tr> <td class="DynaTableRowCell-X" colspan="3">cell 2-3</th> </tr> <tr class="DynaTableRow"> <td rowspan="2" class="DynaTableRowCell-1">cell 3-1</td> <td class="DynaTableRowCell-2">cell 3-2</td> <td class="DynaTableRowCell-3">cell 3-3</td> <td class="DynaTableRowCell-4">cell 3-4</td> <td class="DynaTableRowCell-5">cell 3-5</td> </tr> <tr> <td class="DynaTableRowCell-X" colspan="4">cell 3-3</th> </tr> <tr class="DynaTableRow"> <td rowspan="2" class="DynaTableRowCell-1">cell 4-1</td> <td class="DynaTableRowCell-2">cell 4-2</td> <td class="DynaTableRowCell-3">cell 4-3</td> <td class="DynaTableRowCell-4">cell 4-4</td> <td class="DynaTableRowCell-5">cell 4-5</td> </tr> <tr> <td class="DynaTableRowCell-X" colspan="3">cell 4-3</th> </tr> </table> How can I make this work using only HTML and CSS? I "can" use JavaScript/jquery, but I would REALLY rather not. The output is what is important. I can go from the first output to the second output when mobile loads it, OR I can go from mobile version to desktop version -- doing the latter would make avoiding JavaScript less important. Does CSS offer rowspan/colspan options now (it didn't use to last time I tried, but that was 3-5 years ago)? A: 1- you can style your website by using the fluid method see this 2- you can do it by using media type in CSS see this
{ "pile_set_name": "StackExchange" }
Q: Three Column DIV - is nesting necessary? I have a general question regarding the three column DIV layout. From what I've read online, a common practice seems to be something like this: .container { .left { //content } .other { .center { //content } .right { //content } } } Basically, two columns are always nested within a second container. However, I have some code that looks like this, and it appears to work just fine. jsFiddle Demo HTML <div class="container"> <div class="left"> Left<br>Content<br>Section </div> <div class="center"> Center<br>Content<br>Center<br>Content<br>Center<br>Content </div> <div class="right"> Right<br>Content<br>Section </div> </div> CSS .container { display:inline-block; width:100%; max-width:800px; } .left { background-color:#FF6666; float:left; width:10%; } .center { background-color:#66FF66; float:left; width:70% } .right { background-color:#6666FF; float:right; width:20%; } So, my question is this: Is there a reason to need to nest every two DIV elements inside another container? And is there any downside to using the approach I'm using now? As far as I can tell... there is nothing wrong with it, but would like to hear what the community has to say, and am I going to experience some trouble down the line. A: I have to agree with the comment Niels Keurentjes provided, there is no reason why this isn't 'allowed'. It could be be useful for some (responsive) designs to wrap more divs in one. The code you provided can also be optimized, dropping the container div and use your body as the wrapper: HTML: <div class="left"> ... </div> <div class="center"> ... </div> <div class="right"> ... </div> CSS: /* delete the .container style */ body { width:100%; max-width:800px; } Also check this updated Fiddle.
{ "pile_set_name": "StackExchange" }
Q: IntelliJ IDEA 15 generate orm pojo of the table for hibernate I am a beginner to hibernate and want to generate orm pojo of the table for hibernate in Intellij idea 15. there is a good solution provided in IntelliJ IDEA 10 generate entity (POJO) from DB model. but I can't find where is Generate Persistence Mapping window in Intellij idea 15. this is my screenshot, where is Generate Persistence Mapping? Anyone can help me, thank you very much. A: On my IJ14 it's a pop-up menu item, as it also seems to be explained in the link where you've got the idea from. Try right-clicking the tutorial item in the tree from the Persistence tool window, then at the bottom (or somewhere) you should see Generate persistence mapping:
{ "pile_set_name": "StackExchange" }
Q: .net xml serializer not encoding some characters I a class containing multiple properties of type string. One of the values contains a character of hex value 96. If I serialize the class to xml, the xml serializer does not encode that character, and if I view the xml in various tools such as IE or SQLServer with OpenXML, it complains that the character is invalid in an xml document. Shouldn't the xml serializer be encoding this character? A: I was able to work around the error by changing the encoding to iso-8859-1. In my case, that code page included all the characters that my data consumed. I think theoretically it may be possible for the data to contain other characters but this is a suitable work around.
{ "pile_set_name": "StackExchange" }
Q: How to implement multi-level delegate in Objective-C I have 4 classes (views): A, B, C and D Class A calls B, B calls C, and C Calls D: A > B > C > D In class D I have implemented a delegate protocol and I want to catch the delegate event in class A. How can I achieve this? A: There are multiple ways how you could achieve this. What's best in your case depends on the situation. Here are some ideas: You could implement the delegate protocol in all of those classes and simply pass it down the line. You could add an ivar to access class D from A and pass it directly (danger of spaghetti code!) If it's possible you could change your implementation, so that you only implement the delegate in A and handle it right there. A last resort could be using NSNotifications (not to be confused with NSUserNotifications in Mountain Lion). In your class A you post a notification to the default notification center and in class D you register to this notification and handle it as you want. Only use this approach though if nothing else works, because this can result in even worse code.
{ "pile_set_name": "StackExchange" }
Q: Using Flow js, where do you keep your Type Aliases? I'm new to using Flow js, and find myself creating a lot of custom type aliases for the different API call responses and other functions. Currently I keep the type alias in the same file where I need it, and export it if I need it elsewhere in the program. But, I'm quickly finding this to become unwieldy / messy. Is there a certain recommended structure of how to organize all of the type aliases? Thanks. A: You can use flow-typed directory to define global types and modules like explained in documentation. Other way would be to make some index file on top of some folder structure where you would export all related to this directory types. In my project I have global redux types declared in flow-typed directory and other types exported from commons directory.
{ "pile_set_name": "StackExchange" }
Q: angularjs does not filter other pages I have a simple code which get employees from controller and I want to filter these records with pagination. When I filter on first page everything works fine but, when I want to filter from other page it does not filter and shows nothing. My code is as follow: -filter.js angular.module('MyApp', ['ui.bootstrap']).controller('MyController', function ($scope, EmployeesService) { $scope.Employees = null; $scope.currentPage = 1; $scope.pageSize = 2; $scope.maxSize = 100; EmployeesService.GetEmployees().then(function (d) { $scope.Employees = d.data; // Success }, function () { alert('Failed'); // Failed }) }) .service('EmployeesService', function ($http) { var service = {}; service.GetEmployees = function () { return $http.get('/Employees/GetEmployees'); } return service; }) .filter('start', function () { return function (input, start) { if (!input || !input.length) { return; } start = +start; return input.slice(start); }; }); -Index.cshtml <div ng-app="MyApp"> <div ng-controller="MyController"> <input type="text" ng-model="filterText" name="searchString" placeholder="Search for names.." class="form-control"><br /> <div ng-repeat="emp in Employees |orderBy: 'employeeName'| filter: filterText | start: (currentPage-1) * pageSize | limitTo: pageSize" class="alert alert-warning col-md-12"> <span ng-bind="emp.employeeName"></span> <b>:</b> <span ng-bind="emp.employeePhoneNumber"></span> </div> <pagination ng-model="currentPage" total-items="Employees.length" items-per-page="pageSize"></pagination> </div> </div> Thank you in advance. Sorry for delaying.Here is my working JSFiddle: https://jsfiddle.net/neslisahozdemir/khbbbe47/4/ A: As i understood your query i think you will find your solution by changing the sequence of filter . try using <tr ng-repeat="emp in Employees | filter: filterText|orderBy: 'employeeName' |start: (currentPage-1) * pageSize | limitTo: pageSize" class="alert alert-warning col-md-12"> For now filter is working page wise(mean if you type in "C" you will find data on page 1,2 one record each) After the change in sequence of filter you will get the data in same page(at 1st page 2 records) for filter text "C". Find updated fiddle Hope it will help you.
{ "pile_set_name": "StackExchange" }
Q: How do I remove the Title "Languages" from the Language Icon Module? I am trying to create a bilingual site from a Drupal 7 site that already exists in English. I have absolutely no programming background, yet have managed to make it quite far thanks to reading other individuals' questions and answers on Drupal Answers. Thanks guys! Now I have some questions of my own :) For these questions the page I am referring to is http://laidea.us/testingpage I would like to remove the title "Languages" or "Idiomas" (in Spanish) from the Language Switcher block. I tried seeing if I could do that in views, but couldn't find the Language Switcher block there. I would like to have my language icons be side by side, and without the list bullets next to them. I've noticed that it says what language the content is in, and there is a language switch below my text. How do I get rid of/ hide these fields? Thank you for your help! -Jane A: To remove the title 'Languages', configure the block, and set the title as <none> To have the icons side by side and remove the list bullets you need to specify some css in your theme: section.block .content .language-switcher-locale-url li { background: none; // in your case, you have background set display: inline-block; // to make them side by side list-style-type: none; // to get rid of listing bullets } A: previous answer is correct, you need CSS styling. The reason that I provide another answer is because you said you have no programming background, so I guess you don't know where to copy-paste the correct code. So here is what you can do: download the module css injector enable the module go to configuration -> development -> css injector (admin/config/development/css-injector) create a new rule and give a name to the rule: e.g. front-page styling Finally in this rule write your CSS. (here paste the code provided by Елин Й.) EDIT: if you can't find a way to remove the LANGUAGE title, there is a quick and dirty solution: add the following: #block-locale-language-content h2 {display: none;} If you want to style your website, you really need to study a bit CSS, which is very easy and not like difficult programming. You just target(select) the correct things, the styling of which you would like to change, and then apply some changes to them. It's really simple, don't be afraid of it! for example li { color: blue; background-color: red; } would select all the lists in a website (like the language lists) and make the color blue and the background color red :) To recap: study a bit CSS, official and good place to learn or for example here - a bit more fun install firebug in order to correctly select what you want to style
{ "pile_set_name": "StackExchange" }
Q: In the history of D&D were Demons and Devils the same thing at one point? I recently finished the book Passage to Dawn by R.A. Salvatore and in it a Balor warns a wizard of his Pit Fiend subordinates and a character uses an Imp to collect information from the Abyss. Now as far as I'm aware Demons and Devils don't cooperate and are from different planes of existence, Demons from the Abyss and Devils from the Nine Hells. I don't understand why an Imp and Pit Fiends would be in the Abyss unless they were at the time the book was published (1996) the same kind of creatures. A: No. I'm not going to dig through my old 0e stuff but demons and devils were separate in the D&D 1e Monster Manual (1977), and were in the 2e 1990s as well (though actually renamed baatezu and tanar'ri for a while to avoid the Satanic Panic). But you don't need that to understand why different critters are on a plane. When a wizard uses an invisible stalker to guard his tower do you wonder if they're the same kind of creature because they're on the same plane? Are all of the members of your PC party all the same alignment, because surely people of different alignments could never work together? Imps make good spies because they can turn invisible. So you import one. In those days there was the concept of the Blood War where all the lower planes were fighting each other - and you don't fight someone else without going to their plane to stab them some. A: They never were the same, ever, in the history of the game At least, not in official material. (In that respect, the first word in @mxyzplk's answer is all that is needed for your bolded question: No). Demons came first OD&D did not start with demons, but it got them in supplement three (Eldritch Wizardry) in Types I-VI, Orcus, and Demagorgon. No devils. Alignment at that point was Law, Neutrality, Chaos. Devils arrived with Two-axis alignment in AD&D, and the growing market AD&D 1e added Devils, and also added the two alignment axis1 (Law to Chaos, Good to Evil) as well as the basic structure of the planes that has more or less survived with a bit of tweaking into the current edition. (PHB. 1e pages 119-121) Devils were added before the PHB was published, in the Monster Manual for AD&D 1st edition; they were Lawful Evil. The Devil's particular planes of the evil were in a quadrant of the great wheel anchored by the 9 hells, while Demons were Chaotic Evil and resided in their series of planes, to include the Abyss, on their quadrant of the great wheel. (Actually, in 1e, is was more of a square/rectangle). That relationship has not significantly changed since then, though names and some details have been tweaked in various editions and source books. The point already made about the Blood War was added in the 2e AD&D era. Why an imp and a pit fiend are in the same part of a given plane is easily explained: they both had a common interest. Evil doesn't mean stupid, nor inflexible. Plus, a writer of fiction does not have to constrain his muse by some "rules as written" dogma. Rich Burlew makes that point in one of his comments at the GiTP forums regarding his story (Order of the Stick) and what use he makes of D&D 3.5 rules as a backdrop to the story. Salvatore likewise took considerable license with rules and lore when he dreamed up Drizzt Do'Urden ... so he can do the same with an imp and a demon. 1 While the Holmes blue book (OD&D reorganized) included the two axis alignment, itself originally published in Srategic Review, and it noted "demon" in the chaos/evil corner on the lower right (on page 8), that game release didn't have demons in it as a monster, and specifically referred to AD&D as what comes after that brief introduction. Devils weren't in the blue book either. For the purposes of the relationship between devils and demons, only the introduction of AD&D can address the alignment axis in a proper (and complete) context, complete with the monsters being in the published game. It is worth noting that conceptually, there was a place holder for devils as far back as the 1976 Strategic Review; in the lower right hand corner (CE) were demons in the Abyss, and in the lower left corner (LE) there were devils in Hell. (page 3, Illustration I, Strategic Review, Vol II #1, Feb 1976). Thanks to @ZwiQ for pointing this out.
{ "pile_set_name": "StackExchange" }
Q: Getting a Fragment from a DialogPreference? I have a DialogPreference, that I'm trying to get a Fragment that is added to it (Google Maps, if anyone cares). The fragment has an id tag in the XML code, and I'm setting the dialog via setDialogLayoutResource(). However, I'm struggling to get a reference to the fragment (So I can set some settings to it, and get data out from it). I need to get a reference to it before the user can start playing with the data. What I've tried so far is this: @Override protected void onBindDialogView(View view) { ((Fragment) getDialog() .getOwnerActivity() .getFragmentManager() .findFragmentById(R.id.map)); } This doesn't work because getDialog returns null at this point in the lifecycle. If there's a better way to reference the activity or FragmentManager, I'd love to see it. Thanks for the help! A: I managed to get this to work by casting the Context as an Activity. ((Activity) getContext()).getFragmentManager().findFragmentById(R.id.map));
{ "pile_set_name": "StackExchange" }
Q: nice and ionice: which one should come first? I need to run some long and heavy commands but at the same time I'd like to keep my desktop system responsive. Examples: btrfs deduplication, btrfs balance, etc. I don't mind if such commands take longer to finish if I give them a lower priority, but my system should be responsive at all times. Using nice -n 19 and ionice -c 3 should solve my problem, but I'm not sure which command should come first for maximum benefit. Option A: # nice -n 19 ionice -c 3 btrfs balance start --full-balance / Option B: # ionice -c 3 nice -n 19 btrfs balance start --full-balance / Is there some subtle difference between options A and B? Are they equivalent perhaps? A: If nice caused lots of I/O, you would want to do: ionice -c 3 nice ... so that the impact of the I/O would be minimized. Conversely, if ionice performed lots of computation, you would want to do nice -n 19 ionice ... to minimize its CPU impact. But neither of these is true, they're both very simple commands (they just make a system call to change a process parameter, then execute the command). So the difference should be negligible. And just to be complete, if both were true, you can't really win -- the impact of one of them can't be reduced.
{ "pile_set_name": "StackExchange" }
Q: Getting Initialiser error in iOS Swift I am working on Apple Swift Programming . I am taking a variable that is initialised in ViewDidLoad( ) method. But it shows an error like "*Class ABc has no initializer *" . After much searching about this, I got a suggestion to use init() method to initialise the variable which you want use. Yet still, I am getting an error like this . I am not able to make out where am I going wrong here. Kindly guide me on this. Thanks in advance. A: Super.init isn't called before returning from initializer Error is pretty much clear. You are not calling the super class init(). But for UIViewController you should use any designated initialzer i guess. Try to use init(coder aDecoder: NSCoder!) init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) // Your intializations }
{ "pile_set_name": "StackExchange" }
Q: Erro ao executar npm start Fiz a instalação do Node.js seguindo as instruções do site da ionic, a instalação ocorreu normalmente porém quando tento dar o comando "npm start" pego esse erro, ele me fala que o npm não está achando um diretório ou um arquivo, e da uns erros na pasta package.json... não sei como resolver isso galera, segue o passo a passo e os erros que peguei: MacBook-Pro-de-Lucas:~ lucas$ npm start npm ERR! Darwin 15.5.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start" npm ERR! node v6.11.0 npm ERR! npm v3.10.10 npm ERR! path /Users/lucas/package.json npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open '/Users/lucas/package.json' npm ERR! enoent ENOENT: no such file or directory, open '/Users/lucas/package.json' npm ERR! enoent This is most likely not a problem with npm itself npm ERR! enoent and is related to npm not being able to find a file. npm ERR! enoent npm ERR! Please include the following file with any support request: npm ERR! /Users/lucas/npm-debug.log MacBook-Pro-de-Lucas:~ lucas$ A: Me parece que o problema é que você está tentando dar um npm start na sua home. Ao rodar um npm start, o npm tenta encontrar um arquivo package.json, com a definição do que o start deveria fazer. O que você provavelmente quer é rodar esse comando dentro da pasta raiz de algum projeto que contenha um package.json.
{ "pile_set_name": "StackExchange" }
Q: Threads in Web Application ASP.NET I want to use threads in ASP.NET web application. Is it possible to use threads like we use in windows forms application? or what would be the best approach to handle different tasks on the same page which are very time consuming and all the task are inter dependent at the one point. Thanks in advance. A: If .NET 4.0 is an option, I suggest you take a look at the new Task class. Tasks can be short or long running and you can link tasks any way you like or have them run in parallel with no dependencies.
{ "pile_set_name": "StackExchange" }
Q: convert String to Bytes object for hmac.new() in python 3 code example from https://www.mimecast.com/developer/documentation/downloading-siem-logs/ shows a script that can be used to download logs from a service in python 2.7. I am working on updating the script to be compatible with python 3 but cannot figure out how to get a string to pass into the hmac.new section for the hash generation here: SECRET_KEY = 'SECRET KEY FOR YOUR ADMINISTRATOR' secret_key = SECRET_KEY def create_signature(data_to_sign, secret_key): digest = hmac.new(secret_key.decode("base64"), data_to_sign, digestmod=hashlib.sha1).digest() return base64.encodestring(digest).rstrip() trying to run this as-is results in "LookupError, 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs" I was trying to convert the variable to bytes prior to or inside this function by using the base64.b64decode or bytes(secret_key) functions but that results in "TypeError, Unicode-objects must be encoded before hashing" and I'm just not finding a lot of information on how to get a string variable to pass into hmac.new(). I am pretty sure this is related to the change between python 2 and 3 where strings are stored as unicode in 3 where it was raw data in 2, but I'm not familiar enough with these encodings to understand how to properly translate them when passing them around A: Just think what's bytes and what's str: EDIT: according to the docs for hmac.new and the hashlib module, data_to_sign must also be bytes. secret_key is a str -> convert it to bytes data_to_sign is possibly a str as well -> convert it to bytes base64.b64decode accepts and outputs bytes -> do nothing hmac.new accepts bytes too -> we're already ready digest returns bytes -> we want to b64encode it, and b64encode accepts bytes, so we're good You want to output a str (although bytes may be just fine) -> decode the result of b64encode You may also supply an encoding argument to your function, if you want to work with an encoding different from the default (utf-8). Code: import base64 def create_signature(data_to_sign: str, secret_key: str, encoding='utf-8') -> str: secret_key = secret_key.encode(encoding) # convert to bytes data_to_sign = data_to_sign.encode(encoding) # convert to bytes secret_key = base64.b64decode(secret_key) # this is still bytes digest = hmac.new(secret_key, data_to_sign, digestmod=hashlib.sha1).digest() # still bytes digest_b64 = base64.b64encode(digest) # bytes again return digest_b64.decode(encoding) # that's now str
{ "pile_set_name": "StackExchange" }
Q: How to use InternetQueryOption in C# interop? In my C# code I want to use InternetQueryOption which is defined in MSDN such as: BOOL InternetQueryOption( __in HINTERNET hInternet, __in DWORD dwOption, __out LPVOID lpBuffer, __inout LPDWORD lpdwBufferLength ); In my C# code I wrote: [DllImport("wininet.dll", SetLastError = true)] static extern bool InternetQueryOption( IntPtr hInternet, uint dwOption, IntPtr lpBuffer, ref int lpdwBufferLength); My C++ code: ... HINTERNET hRequest = HttpOpenRequest(hConnect, "POST","/BM-Login/auth-cup", NULL, NULL, accept, secureFlags, 0); DWORD dwFlags; DWORD dwBuffLen = sizeof(dwFlags); InternetQueryOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &dwBuffLen); dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; dwFlags |= SECURITY_FLAG_IGNORE_REVOCATION; dwFlags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID; dwFlags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_WRONG_USAGE; InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags) ); ... How to write the same in C#? Thanks. (Sorry for my very bad English) A: I'd recommend using manged code for this instead of doing this via interop. Have a look at the WebRequest Class. Also, have a look at my answer to the stackoverflow question C# https login and download file for a working example of how this class can be used.
{ "pile_set_name": "StackExchange" }
Q: ComboBox default item I'm writing a simple program in VB with WinForms (well, I guess so, as I have never tried anything like that before). My google-driven development attempt was going pretty well until I tried to make a ComboBox control show one of its items by default. So there is ComboBox1 with two items ("Item A" and "Item B") added through graphical interface (property Items in Properties panel). I go to Form1_Load event description in the code window and add the following line: ComboBox1.SelectedItem = 0 That is supposed to make "Item A" the default item preselected when the program starts. But it doesn't work. What am I doing wrong? A: That's because you are using 0(an integer) on ComboBox.SelectedItem, but ComboBox.Selected item is not an index to an element, it's an actual object. This is how you use ComboBox.SelectedItem: Option Strict On Option Explicit On Option Infer Off Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ComboBox1.Items.Add("Item A") ComboBox1.Items.Add("Item B") ComboBox1.SelectedItem = "Item A" End Sub End Class
{ "pile_set_name": "StackExchange" }
Q: Measure 2d positions and tangents I would like to measure two points and tangents of a curve and transfer that information to a computer. Here is a picture of what I would like to measure: Points (x1,y1), (x2,y2) Tangents T1, T2 (or an approximation of the tangents) A: Very possible, and I think not that hard. With a few changes. 1. Hands are 3 dimensional and can point each end not in two directions but in 3-space. 2. Though it is easy to compute if you know the 3D coordinates of each end, you need to know the distance between the two ends of the blade. Therefore I suggest these simplifications for simplicity and cost: Recompute your script to use relative coordinates of only: the distance between the blade ends, the angle of T1 up from 0 pointing to hand 2, and the angle of T2 up from 0 pointing to T1. Build a physical skeleton consisting of a metal ruler with a rotating potentiometer at each end (10k linear). The two pot knobs each hold an end of the blade, and restrict them to rotating in the same plane. The user adjusts the thing with his hands, first reading the distance between the ends. That gets entered into the Arduino program. The program reads the each pot to get the angles T1 and T2. Your script spits out the shape on a screen or little display. Here's an all mechanical solution. Get two of the those metal T-square rulers that have a built in adjustable protractor. Unscrew the knobs and put both smaller protractor arms on the same long arm. Mount a blade end on each knob. You then physically adjust each angle and blade end, visually seeing the tangents since they are pieces and reading off the protractor angles. Enter the two tangent angles and the distance between them, and if you calculated right, voila! Your script prints they shape of the reality you created!
{ "pile_set_name": "StackExchange" }
Q: c# pass file pointer to unmanaged c++ dll to use for stdout Please bear with me - I'm a c# developer with little experience with C++, and this is a steep learning curve! From a c# console app, I'm calling some methods from an unmanaged C++ dll. The DLL writes to the stdout stream, although this was not being picked up by the c# console. I found the following code, which I added to the C++ dll, which now successfully sends the contents of "printf" to the c# console. #include <windows.h> #include <stdio.h> #include <fcntl.h> #include <io.h> void redirect_stdout() { int hConHandle; long lStdHandle; FILE *fp; // allocate a console for this app AllocConsole(); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); } AOK so far: What I'd like to do is capture the stdoutfrom the DLL to a c# stream, rather than send it to the console. I tried the method detailed here (Redirect stdout+stderr on a C# Windows service), which does capture the output, however the app "crashes" when the program closes ("vshost.exe has stopped working"). (Note: setting Console.SetOut() on the stream captures the c# output, not the c++ output). So I thought what if I use the "Filestream.SafeFileHandle.DangerousGetHandle()" method to get a handle to the filestream from c#, and pass this into the C++ method redirect_stdout() method: void redirect_stdout(FILE *passedInHandle) { // allocate a console for this app AllocConsole(); *stdout= *passedInHandle; setvbuf( stdout, NULL, _IONBF, 0 ); } When I run the above version, the output from the DLL is no longer piped to the c# Console, however, the filestream on the c# side is always empty. Can any expert give guidance to have the STDOUT write its output to the c# filestream? I'm sure I've made some stupid error about how to achieve this or I am not understanding how to achieve what I am trying to do. Thank you for your time and input - really appreciated! [EDIT] OK - I've played a bit more and modified the C++ method as such: void redirect_stdout(int passedInHandle) { int hConHandle; long lStdHandle; FILE *fp; // allocate a console for this app AllocConsole(); hConHandle = _open_osfhandle(passedInHandle, _O_TEXT); fp = _fdopen(hConHandle, "w"); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); } This also successfully populates the c# stream, however when the c# Console app closes, the app crashes with the error "vshost.exe has stopped working". This is the same error as when I use the method from Redirect stdout+stderr on a C# Windows service Very odd find: If I run the console app "outside of visual studio" (eg, double click on the .exe in the bin folder), there is no crash! So I guess my next question is: how do I track down the source of this crash? Is it VS related? It occurs in either debug or release mode when running from VS, and no crash when run outside of VS. I am at a loss as to how to debug this one! A: You might consider using named pipes: i.e communication between c++ and c# through pipe http://www.switchonthecode.com/tutorials/interprocess-communication-using-named-pipes-in-csharp Hopefully, that should work...
{ "pile_set_name": "StackExchange" }
Q: Deleting .png File through ListView I am making an application for personal use that will organize .png files and will let me remotely delete them from the directory through the application (through a ListView). I have a snippet that will delete the file from the ListView, but not from the actual file directory. I want to be able to do both when I click delete. private void deleteToolStripMenuItem1_Click(object sender, EventArgs e) { if (MessageBox.Show("This will delete the file from the folder. Are you sure?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes) for (int i = fileDisplayListView.SelectedItems.Count - 1; i >= 0; i--) { ListViewItem item = fileDisplayListView.SelectedItems[i]; fileDisplayListView.Items[item.Index].Remove(); File.Delete(fbd.SelectedPath + fileDisplayListView.Items.ToString()); } } Additional snippet for more information.. private void openToolStripButton_Click(object sender, EventArgs e) { fbd.ShowDialog(); DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath); directoryPath.Text = "Directory: " + fbd.SelectedPath; FileInfo[] Files = di.GetFiles("*.PNG*", SearchOption.AllDirectories); if (Files.Length == 0) MessageBox.Show("No .png files found in directory...", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Question); fileDisplayListView.Items.Clear(); foreach (FileInfo f in Files) { ListViewItem item = new ListViewItem(f.Name); this.fileDisplayListView.Items.Add(f.Name); } this.fileDisplayListView.View = View.Details; this.fileDisplayListView.Refresh(); } The last part of it, File.Delete(fbd.SelectedPath + fileDisplayListView.Items.ToString()); is not functional. Please help! A: This code gets a list of all .jpg files in the directory, adds them to the ListView. By pressing the button it deletes the selected ListView elements and files: private FileInfo[] files; public Form1() { InitializeComponent(); files = new DirectoryInfo(@"C:\Users\User\Pictures").GetFiles("*.jpg", SearchOption.AllDirectories); foreach (var file in files) { listView1.Items.Add(file.Name); } } private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < listView1.SelectedItems.Count; i++) { var curentItem = listView1.SelectedItems[i]; foreach (FileInfo file in files) { if (curentItem.Text == file.Name) { listView1.Items.Remove(curentItem); file.Delete(); i--; } } } }
{ "pile_set_name": "StackExchange" }
Q: NLog not writing to eventlog .NET Core 2.1 I've added NLog to my .NET core console app and it works with file and database targets. However when i try and get it to work with eventviewer it doesn't log anything. When i add the code for the eventviewer target the file and database part doesn't log anything. When I remove it, the logging starts working again. I have added a new event viewer source for the application using Powershell, so that wouldn't be the issue. The application doesn't crash or report an error, it runs fine but doesn't log anything when event viewer is included. <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogFile="c:\temp\console-example-internal.log" internalLogLevel="Info" > <targets> <target xsi:type="File" name="logfile" fileName="c:\temp\console-example.log" layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-e vent-properties}" /> <target xsi:type="Console" name="console" layout="[${longdate}][${machinename}][${level:uppercase=true}] ${message} ${exception}" /> <target xsi:type="EventLog" name="eventlog" source="testlogging" log="Application" layout="${message}${newline}${exception:format=ToString}" /> <target xsi:type="Database" name="database" > <connectionString>Server=test; Database=test; User Id=sa; Password=password;</connectionString> <commandText> INSERT INTO dbo.Log (Application, Logged, Level, Message, Logger, CallSite, Exception ) VALUES (@Application, @Logged, @Level, @Message, @Logger, @Callsite, @Exception); </commandText> <parameter name="@application" layout="TestLoggingApp" /> <parameter name="@logged" layout="${date}" /> <parameter name="@level" layout="${level}" /> <parameter name="@message" layout="url: ${aspnet-request-url} | action: ${aspnet-mvc-action} | ${message}" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@callSite" layout="${callsite:filename=true}" /> <parameter name="@exception" layout="${exception:tostring}" /> </target> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="logfile, console, database" /> </rules> </nlog> Any ideas on how to implement this or if I have missed something? A: For me the answer was adding "NLog.WindowsEventLog" assembly to the extensions area to nlog.config: <extensions> <add assembly="NLog.WindowsEventLog" /> </extensions> I had the default: "NLog.Web.AspNetCore".
{ "pile_set_name": "StackExchange" }
Q: Does a Router use NAT to assign it's own IP to the packet and then the use PAT to figure out where to send the response? Does a router use NAT when receiving a packet from a private IP:PORT to change the source IP on the packet to its own public IP and then when it receives the response packet back, use PAT and the PORT to figure out which private IP the request came from? Why do we have private IP's if this is the case when we could just use the MAC and port to get the packet to the router and then use the public IP from there? A: When most people say "NAT" they really mean what the IETF standards call "NAPT", which in Cisco proprietary jargon is called PAT. NAPT gateways do NAPT in both directions. In some cases the port doesn't need to be changed, and some NAPT implementations choose not to change the port in those cases. We use private IPs behind NAPT gateways because it is convenient to use IP on the LAN rather than invent some way of doing TCP/UDP/ICMP/etc. directly on Ethernet without a network layer (layer 3).
{ "pile_set_name": "StackExchange" }
Q: What's the best way to commit a serialized JQuery sortable result to the database? I am using the JQuery.Sortable() function to create a reorderable list of items like so <script type="text/javascript"> // When the document is ready set up our sortable with it's inherant function(s) $(document).ready(function() { $("#goal-list").sortable({ handle: '.handle', placeholder: 'ui-state-highlight', update: function() { var order = $('#goal-list').sortable('serialize'); $("#info").load("/goals/process?" + order); } }); }); </script> The result that comes back is a comma delimited list of the item ID's (i.e. 1,2,3,4,5,6 and so on) What I want to know what is the best way to commit this to the related item table's sortorder column... I could loop through and update each record but I am thinking that is an awful lot of database writes and could pose a potential bottle neck especially if the list is rather large. I'm using LINQ-to-SQL and ASP.NET MVC A: I recommend you look into deferred execution more if you are working with LINQ to SQL. This can be a common pitfall.. especially when when using associations. Multiple inserts and updates can actually be grouped together .. they will not be written to the db until SaveChanges or SubmitChanges is called on the db context. If you loop through a set of items and modify them.. then call SaveChanges after exiting the loop, the group of update statements should be batched together and sent to the db in one trip..
{ "pile_set_name": "StackExchange" }
Q: PowerBuilder expressions on column controls strange behavior I'm working on a legacy PowerBuilder app, we have upgraded to PowerBuilder 12 but continue to use the "classic" IDE. I have a grid DataWindow sharing data with a freeform DataWindow, both inheriting ancestors that ensure that when the current row changes in the grid, the freeform scrolls to the same row. I have started using expressions on the Protect and Background.Color properties of column controls in the freeform to simulate enabling/disabling, as an alternative to using DataWindow.Modify on rowfocuschanged. So far I have enjoyed this approach, it seems much cleaner, and there is no apparent performance penalty since I am not accessing the database in any of my expressions. The trouble is, for reasons that I am having a hard time pinning down, these expressions are sometimes causing the aforementioned row synchronization functionality to fail. In my test scenario, there are two rows in the grid. Selecting row 2 does not cause the freeform to scroll to row 2, despite the fact that debugging reveals that ScrollToRow is indeed being called normally. Then I select row 1 again, can't be sure if this works or not since the freeform never left row 1 to begin with. Then I select row 2 a second time, and the freeform scrolls to row 2 properly, and henceforth things are dandy. I fixed this problem once already on a different window by moving code around within one particular expression, no clue why this worked, the changes did not affect the result of the expression. Unfortunately I am not having such an easy time fixing it on my current window. So far, I can solve the issue at a loss of functionality by removing the Protect expression from one particular DateTime EditMask column, or by setting the TabOrder of a preceding DateTime EditMask column to a positive value. The first column needs the Protect expression, and the second column needs to be uneditable. I attempted to give the second column a positive TabOrder while setting it's Protect expression to 1 but that did not work. I'm tearing my hair out and hating PowerBuilder something fierce! I'd appreciate it if anyone has any idea what the issue is and how I can continue taking advantage of column expressions while avoiding it. I am loath to going back to manipulating this stuff through Modify from rowfocuschanged. A: Here's the answer in retrospect, taking from and adding to what was developed in comments. When you set a new row, PowerBuilder tries to set the column to the same column that currently has focus in the current row. This works fine in the basic case, but when the Protect attribute has an expression, things can be a little less predictable. I'm not sure if there is a documented or intended behaviour in the case when the column in the destination row is protected, but my position of safety is that the behaviour is unpredictable, and you probably just shouldn't do this. As Mike has proved, explicitly setting the column resolves his issue. The other primary thing to check for if you're trying to solve a similar issue is to be sure RowFocusChanging isn't returning a 1 to prevent the row change from occurring. Good luck, Terry.
{ "pile_set_name": "StackExchange" }
Q: Can sssd provide cross domain group membership? How can I make sssd search for group memberships in all configured domains? Given the configuration below, both alice(@bar) and bob(@foo) should be members of testgroup(@bar). However, only alice is considered a member of testgroup by sssd. Looking at a tcpdump capture it appears that alice only search for (&(&(member=uid=alice,ou=users,dc=bar,dc=example,dc=com)(objectClass=posixGroup))(cn=*)) within scope ou=groups,dc=bar,dc=example,dc=com and bob only searches for (&(&(member=uid=bob,ou=users,dc=foo,dc=example,dc=com)(objectClass=posixGroup))(cn=*)) within scope ou=groups,dc=foo,dc=example,dc=com. How can I alter the behavior of sssd (or my OpenLDAP backend) to allow for cross domain membership? dn: cn=testgroup,ou=groups,dc=bar,dc=example,dc=com objectClass: groupOfNames objectClass: posixGroup cn: testgroup gidNumber: 54321 member: uid=alice,ou=users,dc=bar,dc=example,dc=com member: uid=bob,ou=users,dc=foo,dc=example,dc=com [sssd] config_file_version = 2 services = nss, pam, autofs domains = FOO.EXAMPLE.COM, BAR.EXAMPLE.COM [nss] filter_groups = root filter_users = root reconnection_retries = 3 [pam] reconnection_retries = 3 [autofs] [domain/FOO.EXAMPLE.COM] id_provider = ldap auth_provider = krb5 chpass_provider = krb5 ldap_uri = _srv_ ldap_search_base = dc=foo,dc=example,dc=com ldap_user_search_base = ou=users,dc=foo,dc=example,dc=com?onelevel? ldap_group_search_base = ou=groups,dc=foo,dc=example,dc=com?onelevel? ldap_schema = rfc2307bis ldap_sasl_mech = GSSAPI krb5_realm = FOO.EXAMPLE.COM ldap_autofs_entry_key = automountKey ldap_autofs_map_name = automountMapName ldap_autofs_search_base = ou=automount,dc=foo,dc=example,dc=com [domain/BAR.EXAMPLE.COM] id_provider = ldap auth_provider = ldap chpass_provider = ldap ldap_uri = _srv_ ldap_search_base = dc=bar,dc=example,dc=com ldap_user_search_base = ou=users,dc=bar,dc=example,dc=com?onelevel? ldap_group_search_base = ou=groups,dc=bar,dc=example,dc=com?onelevel? ldap_schema = rfc2307bis ldap_sasl_mech = GSSAPI ldap_autofs_entry_key = automountKey ldap_autofs_map_name = automountMapName ldap_autofs_search_base = ou=automount,dc=bar,dc=example,dc=com A: Use multiple ldap_*_search_bases within a domain. ldap_user_search_base = ou=users,dc=bar,dc=example,dc=com?onelevel??ou=users,dc=foo,dc=example,dc=com?onelevel? ldap_group_search_base = ou=groups,dc=bar,dc=example,dc=com?onelevel??ou=groups,dc=foo,dc=example,dc=com?onelevel?
{ "pile_set_name": "StackExchange" }
Q: How to display values of type 'UserDefinedClass' into jsp from HashMap using JSTL? Here's is the simplified version of my problem, framework is Spring MVC 3.1 and the view is JSP. Simple POJO Class: class User { String userId ; String userName; String age; // getters and setters of the above. } Controller class: @Controller @SessionAttributes(value = {"userObj", "userMap"}) class UserController { HashMap<String, User> userMap = new HashMap<String, User>(); User demoUser = new User(); demoUser.setUserId("1"); demoUser.setUserName("myname"); demoUser.setAge("45"); userMap.put(demoUser.getUserId, demoUser); session.setAttribute("userObj", demoUser); session.setAttribute("userMap", userMap); //adding this objects to a ModelMap object named 'model' model.addAttribute("userMap", userMap); model.addAttribute("userObj", demoUser); return "viewName" ; // name resolved to a jsp page. } In JSP : <form:form method="POST" commandName="userMap" name="statusForm"> <table class="border1"> <tr> <th width=5px>USER ID</th> <th width=15px>USER <br>Name</th> <th width=5px>USER AGE</th> </tr> <c:forEach var="entry" items="${userMap}" varStatus="status"> <tr> <td> ${entry.key} </td> <!-- key alone will get displayed if I comment the 'entry.values' iteration forEach loop--> <c:forEach var="innerLoop" items ="${entry.value}" varStatus="valuestatus"> <td>${innerLoop}</td> </c:forEach> </tr> </c:forEach> </table> </form:form> While reaching the inner forEach loop I get a servlet error saying " Don't know how to iterate over supplied items in forEach". If I comment the second forEach loop, the map displays the keys alone. I've tried many combinations, nothing seems to be working to display the values inside the HashMap. Please advise. Thanks! A: That is expexcted behaviour.You can't iterate over User referenece as this is not collection like List,Set,Map There is no need of inner loop. You can use below code <c:forEach var="entry" items="${userMap}" varStatus="status"> <tr> <td> ${entry.key} </td> <!-- key alone will get displayed if I comment the 'entry.values' iteration forEach loop--> <td> ${entry.value.userId} </td> <td> ${entry.value.userName} </td> <td> ${entry.value.age} </td> </tr> </c:forEach>
{ "pile_set_name": "StackExchange" }
Q: Prove of function is surjective iff it has a right inverse using the well-ordering Theorem As mentioned in the title I should prove that a function $f\colon X\to Y$ is surjective if and only if there exists a function $g\colon Y\to X$ such that $f\circ g=id_Y$ using the well ordering Theorem (i.e. that every set can be well-ordered). Of course the statement is well known and not so difficult to prove but I don't know how to use the well ordering Theorem for the proof. A: By the well-ordering principle, $X$ can be well-ordered. "$\Rightarrow$" For every $y\in Y$, consider $f^{-1}(y)\subset X$ which is a non-empty subset, because $f$ is surjective. Using the well-order it has a least element $x_y$. Now, define $g(y):=x_y$. Then $f(g(y))=f(x_y)=y$, so $f\circ g=id_Y$. "$\Leftarrow$" $id_Y$ is surjective, so $f\circ g$ is surjective, so $f$ must be surjective. No need of the well ordering principle here.
{ "pile_set_name": "StackExchange" }
Q: Login status lost after closing the browser I have a login system using FormsAuthentication that for some reason is logging me out when closing and opening the browser. Here is how I have setup my login code: FormsAuthenticationTicket ticket; ticket = new FormsAuthenticationTicket(1, tbUsername.Text, DateTime.Now, DateTime.Now.AddYears(1), true, string.Empty, FormsAuthentication.FormsCookiePath); string encryptedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.HttpOnly = true; //Add the cookie to the request Context.Response.Cookies.Add(cookie); As you can see I have set the cookie to be persistent across sessions. Here is my web.config part: <authentication mode="Forms"> <forms slidingExpiration="false" loginUrl="~/Login.aspx" name="BOIGAUTH" defaultUrl="~/Admin/Settings.aspx"/> </authentication> Also, SessionState is disabled on this particular application. Anyone know what is wrong? Btw leaving the application browser on for more than 2 hours kept me logged in even though I did not interact with the website. The cookie is only being lost when closing the browser. A: If you don't set expiration on cookie it will be browser-session-only cookie and disappear after you close all instances of browser. You need to set some expiration on your cookie for it to be persistent with Expires property. HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, encryptedTicket); cookie.HttpOnly = true; cookie.Expires = DateTime.Now.AddMinutes(1000); Side note: make sure your browser is not configured to clear all cookies on close.
{ "pile_set_name": "StackExchange" }
Q: How does SSMS connect to a server's database without the instance name? I have a question that I am confused about. I am also new to database stuff as well so this question may be basic. For example, at my work, we use SSMS to connect to our server's databases. When connecting from SSMS, we enter in (server_name\instance). Like for example PC100\SQLexpress. But for some, only the server is entered and not the instance along with it. How does this work? I thought in order to connect, we always need to type an instance after the server name? Like for example, some we need PC100\SQLexpress in order to connect to the server's databases. And then for others we just need to type in PC200 to connect, and not needing to type the instance. Can anyone explain? A: For SQL Server the default instance of a is SQLServerName\MSSQLSERVER. However, since MSSQLSERVER is the default instance name that is never displayed. A SQL Server using the default instance is only referenced by the SQLServerName. Actually, you can install SQL Server Express and give it the instance name of MSSQLSERVER and you will get the default instance. Of course, any server can only have one default instance. That is probably most useful when installing a SQL Server Express and you do not want to have SQLExpress for the part of the name. When installing a default instance of SQL Server Express at the Instance Configuration page, you must choose the Named Instance radio button and type in the default instance name of MSSQLSERVER. Just take the steps to name the default instance name MSSQLServer (which will not appear). Any other instance name on the computer needs a unique name, such as SQLServerName\Alpha, SQLServerName\Beta, et cetera. Note: Installing SQL Server Express will, by default behavior, put the SQLExpress into the server name. But that is not the default name. Whenever there is \Sometext name, then that is called a named instance.
{ "pile_set_name": "StackExchange" }
Q: Issue while creating new multidimensional array I try to create a new multidimensional array from another multidimensional array. The first array looks like the following: array[0][0] = foo array[0][1] = foo2 ...and so on array[1][0] = 123 array[1][1] = 234 ...and so on array[2][0] = blue array[2][1] = red ...and so on array[3][0] = fish array[3][1] = bird ...and so on ...then I have an array called 'results' that contains of numbers (e.g. 1, 20 , 23). What I want to do is to create a new multidimensional array, just like the first, one but only with the elements from the first one that's to be found as numbers in the array 'results'. Below is my try so far that doesn't work. When I run the code I get the following error message: Uncaught TypeError: Cannot set property '0' of undefined) <- line 5 What am I doing wrong? 1: var newArray = []; 2: 3: for (var i = 0; i < results.length; i++) { 4: var index = results[i] 5: newArray[0][i] = array[0][index]; 6: newArray[1][i] = array[1][index]; 7: newArray[2][i] = array[2][index]; 8: newArray[3][i] = array[3][index]; 9: } A: you always need to initialize the array: newArray[0] = []; like in this example: var newArray = []; // newArray[12345] is undefined newArray[12345][2] = 3; // error! newArray[12345] is undefined, and you want to treat undefined element as array. so before you can do that you need to initalize the subarray: var newArray = []; newArray[12345] = []; // now "newArray[12345]" is new subarray newArray[12345][2] = 3; Edit: var newArray = []; for (var i = 0; i <= 3; i++) { newArray[i] = []; //newArray[i] = new Array(); - same thing } for (var i = 0; i < results.length; i++) { var index = results[i] newArray[0][i] = array[0][index]; newArray[1][i] = array[1][index]; newArray[2][i] = array[2][index]; newArray[3][i] = array[3][index]; }
{ "pile_set_name": "StackExchange" }
Q: How did marrying off one's daughter help secure an alliance, in early medieval Europe? Marriage between royal family was often a way to secure / strengthen an alliance between two monarchs. For example, according to Wikipedia Marriage between dynasties could serve to initiate, reinforce or guarantee peace between nations. Alternatively, kinship by marriage could secure an alliance between two dynasties which sought to reduce the sense of threat from or to initiate aggression against the realm of a third dynasty I wonder, how this would work from the point of view of the dynasty that supplied the princess? For example, if you marry off your daughter, and she lives in the other monarch's family, of course it will somewhat restrain you from attacking them. But how does this guarantee (or at least increase the confidence) that the other monarch will not betray you? If anything it seemed the daughter can be used as hostage, a bargaining chip, or even mistreated by the other monarch in future conflicts. A: Such marriages were usually part of wider treaties, including a dowry, non-aggression and/or mutual support agreements. The king didn't just get a queen, he got a chunk of land, possible inheritance rights, not to mention preventing his enemies making the same pact with his wife's family. Foreign princesses were mistreated - Catherine of Aragon after Prince Arthur's death, and when Henry 8 divorced her, but I suspect the possible advantages of your daughter/sister being Queen of a foreign power outweighed, in terms of realpolitik, any potential abuse. Amusingly, when Christiana of Denmark was offered the chance of marrying Henry 8, she replied that, had she two necks, the King of England would have been welcome to one of them! A: If anything it seemed the daughter can be used as hostage or a bargaining chip That could be an option if the sides were not on the equal terms. Say, if you have to show your loyalty to the conditions of some peace treaty after an unsuccessful war, then sending such "a hostage" may save you a couple of fortresses. After all, girls need husbands. On the other hand, if you are on equal terms, then by this marriage you make another monarch to owe you. And this could be of much help, say, if you have both a daughter and a son. But how does this guarantee (or at least increase the confidence) that the other monarch will not betray you? Such marriages may also be the part of formal treaties between countries. And at the very least, just the fact of marriage effectively cancels out any previous casus belli. A: If your daughter is the mother of the monarch's children, that would inhibit most monarchs from attacking you. After all, you're the children's grandparent (and monarch's parent in law). And the monarch hopes that his children will inherit from you, as well as him. Not to mention the likely impact of "pillow talk." Unless the daughter hates you for some reason.
{ "pile_set_name": "StackExchange" }
Q: Divisibility Rule for 9 I'm working through an elementary number theory course right now and I think I've come up with a proof here but wanted some feedback on my logic. Question: If the sum of the digits in base 10 is divisible by 9, then the number itself is divisible by 9. Proof: Suppose that $9|d_1+d_2+...+d_n$ then $d_1+d_2+...+d_n=0\mod9$ Now consider $d_1(10^{n-1})+d_2(10^{n-2})+...+d_{(n-1)}(10^1)+d_n(10^0)$ Each power of $10$ is equivalent to $1\mod9$ therefor $d_1(10^{n-1})+d_2(10^{n-2})+...+d_{(n-1)}(10^1)+d_n(10^0)=(1\mod9)(d_1+d_2+...d_n)$ $9|(d_1+d_2+...d_n)$ by our assumption, thus $9|(1\mod9)(d_1+d_2+...d_n)$ Thus we have shown that if 9 divides the sum of the digits in base 10, 9 divides the number itself. The only question I really have is whether I'm jumping the gun on my assumption concerning the powers of 10 being $1\mod 9$. I think this is fair game here but not 100% confident. Thanks. A: Yes, $\,{\rm mod}\ 9\!:\ \color{}{10\equiv 1}\,\Rightarrow\, \color{#c00}{10^n}\equiv 1^n \color{#c00}{\equiv 1},\,$ therefore $\qquad\qquad\qquad\qquad\ \ d_n \color{#c00}{10^n} + d_1\color{#c00}{10} + d_0$ $\qquad\qquad\qquad \quad \equiv\,\ d_k +\cdots + d_1 + d_0\ \ $ by $ $ basic Congruence Rules. More efficiently, we can observe that the decimal (radix $10)$ representation of an integer $N$ is a polynomial function $\,f(10)\,$ of the radix, with integer coefficients (digits) $\,d_i,\,$ i.e. $$\begin{eqnarray} N\, =\, f(10) \!\!\!&&= d_n 10^n +\,\cdots+d_1 10 + d_0 \\ {\rm where}\ \ f(x) \!\!&&= d_n\, x^n\,+\,\cdots\,+d_1\, x\, + d_0\end{eqnarray}$$ Thus $\ {\rm mod}\ 9\!:\,\ \color{#c00}{10\equiv 1}\,\Rightarrow\, f(\color{#c00}{10})\equiv f(\color{#c00}{1}) = d_n+\cdots + d_1 \equiv\,$ sum of digits, which follows by applying the Polynomial Congruence Rule. The proof works for any polynomial $\,f(x)\,$ with integer coefficients. As such, these tests for divisibility by the radix$\pm1$ (e.g. also casting out nines) may be viewed as special cases of the Polynomial Congruence Rule.
{ "pile_set_name": "StackExchange" }
Q: Issue with regexp substr function in oracle I have a SELECT statement which contains regexp_substr in it SELECT REGEXP_SUBSTR ('hello, main.proc.standarad_name(ename),main.proc.standarad_val(eno)', '[,](.*)[(]eno[)]', 1, 1, 'i', 1 ) FROM DUAL Expected Output: main.proc.standarad_val Actual Output: main.proc.standarad_name(ename),main.proc.standarad_val How do I achieve this? A: changing .* by [^,]* to match any character except ,. can be checked here, rextester
{ "pile_set_name": "StackExchange" }
Q: Distributed singleton service for failover I have an abstract question. I need a service with fault tolerance. The service only can only be running on one node at a time. This is the key. With two connected nodes: A and B. If A is running the service, B must be waiting. If A is turned off, B should detect this and start the service. If A is turned on again, A should wait and don't run the service. etc. (If B is turned off, A starts, if A is turned off B starts) I have think about heartbeat protocol for sync the status of the nodes and detect timeouts, however there are a lot of race conditions. I can add a third node with a global lock, but I'm not sure about how to do this. Anybody know any well-known algorithm to do this? Or better Is there any open source software that lets me control this kind of things? Thanks A: If you can provide some sort of a shared memory between nodes, then there is the classical algorithm that resolves this problem, called Peterson's algorithm. It is based on two additional variables, called flag and turn. Turn is an integer variable whose value represents an index of node that is allowed to be active at the moment. In other words, turn=1 indicates that node no 1 has right to be active, and other node should wait. In other words, it is his turn to be active - that's where the name comes from. Flag is a boolean array where flag[i] indicates that i-th node declares itself as ready for service. In your setup, flag[i]=false means that i-th node is down. Key part of the algorithm is that a node which is ready for service (i.e. flag[i] = true) has to wait until he obtains turn. Algorithm is originally developed for resolving a problem of execution a critical section without conflict. However, in your case a critical section is simply running the service. You just have to ensure that before i-th node is turned off, it sets flag[i] to false. This is definitely a tricky part because if a node crashes, it obviously cannot set any value. I would go here with a some sort of a heartbeat. Regarding the open source software that resolves similar problems, try searching for "cluster failover". Read about Google's Paxos and Google FileSystem. There are plenty of solutions, but if you want to implement something by yourself, I would try Peterson's algorithm.
{ "pile_set_name": "StackExchange" }
Q: Query for unique record on basis of status I need help in writing the sql query for finding the record on the basis of status. I created a table using this query: CREATE TABLE inglogs (id int, mobileno int(10), status varchar(10)); INSERT INTO inglogs (id, mobileno, status) VALUES (1, 1234, 'fail'), (2, 1234, 'fail'), (3, 1234, 'success'), (4, 2345, 'success'), (5, 2345, 'success'), (6, 4326, 'fail'), (7, 4327, 'success') I want to query from the above table where and get distinct mobileno like 1234,2345,4326,4327 with its status like if there is any success with that mobileno , it should return that record with id and status, also if there is not any success for any mobile (in my case it is 4326) then that should also be visible in in the executed query. eg I want some thing like this: +---+ +--------+ +----------+ |id | |mobileno| | status | +---+ +--------+ +----------+ |3 | | 1234 | | success | |5 | | 2345 | | success | |6 | | 4326 | | fail | |7 | | 4327 | | success | +---+ +--------+ +----------+ A: You want an aggregate with a conditional: select max(id) as id, mobileno, (case when sum(status = 'success') > 0 then 'success' else 'fail' end) as status from inglogs group by mobileno see sqlfiddle http://sqlfiddle.com/#!2/e71e7/3
{ "pile_set_name": "StackExchange" }
Q: How to correctly free/finalize an ActiveX DLL in Delphi? We are using a class called ODNCServer here - at initialization, an TAutoObjectFactory object is created: initialization pAutoObjectFactory := TAutoObjectFactory.Create(ComServer, TODNCServer, Class_ODNCServer, ciSingleInstance, tmApartment); Now FastMM is complaining about a memory leak because this object isn't freed anywhere. If I add a finalization statement like this finalization if assigned(pAutoObjectFactory) then TAutoObjectFactory(pAutoObjectFactory).Free; then the object is freed, but after the FastMM dialog about the memory leak pops up, so actually, the OS seems to be unloading the DLL, not the program. Instances of ODNCServer are created like this fODNCServer := TODNCServer.Create(nil); //register into ROT OleCheck( RegisterActiveObject( fODNCServer.DefaultInterface, // instance CLASS_ODNCServer, // class ID ACTIVEOBJECT_STRONG, //strong registration flag fODNCServerGlobalHandle //registration handle result )); and freed like this: if ((assigned(fODNCServer)) and (fODNCServerGlobalHandle <> -1)) then begin Reserved := nil; OleCheck(RevokeActiveObject(fODNCServerGlobalHandle,Reserved)); fDTRODNCServerGlobalHandle := -1; end; FreeAndNil(fODNCServer); So, does anybody know what I have to change to get rid of that memory leak? By the way, I also tried using FastMM's RegisterExpectedMemoryLeaks to register and ignore the leak, but this doesn't seem to work. Additionally, even if, it would just be a workaround and I'd like to know the right way to do this. A: Don't worry about it. It's not a "leak" in the strict sense. Yes you are creating an object that is never free'd, but the keyword is "an". Singular. Your application/DLL will not "leak" memory in the sense that it will create numerous instances of these objects,continually increase it's memory use. Furthermore the memory used by that single factory object (and others like it) will be cleaned up when the process terminates anyway. If you showed the code you are using to call RegisterExpectedMemoryLeak() it might be possible to determine why it is not working your specific case.
{ "pile_set_name": "StackExchange" }
Q: Postgres - How to debug/trace 'Idle in transaction' connection I am using Postgres for one of my applications and sometimes (not very frequently) one of the connection goes into <IDLE> in transaction state and it keeps acquired lock that causes other connections to wait on these locks ultimately causing my application to hang. Following is the output from pg_stat_activity table for that process: select * from pg_stat_activity 24081 | db | 798 | 16384 | db | | 10.112.61.218 | | 59034 | 2013-09-12 23:46:05.132267+00 | 2013-09-12 23:47:31.763084+00 | 2013-09-12 23:47:31.763534+00 | f | <IDLE> in transaction This indicates that PID=798 is in <IDLE> in transaction state. The client process on web server is found as following using the client_port (59034) from above output. sudo netstat -apl | grep 59034 tcp 0 0 ip-10-112-61-218.:59034 db-server:postgresql ESTABLISHED 23843/pgbouncer I know that something is wrong in my application code (I killed one of the running application cron and it freed the locks) that is causing the connection to hang, but I am not able to trace it. This is not very frequent and I can't find any definite reproduction steps either as this only occurs on the production server. I would like to get inputs on how to trace such idle connection, e.g. getting last executed query or some kind of trace-back to identify which part of code is causing this issue. A: If you upgrade to 9.2 or higher, the pg_stat_activity view will show you what the most recent query executed was for idle in transaction connections. select * from pg_stat_activity \x\g\x ... waiting | f state | idle in transaction query | select count(*) from pg_class ; You can also (even in 9.1) look in pg_locks to see what locks are being held by the idle in transaction process. If it only has locks on very commonly used objects, this might not narrow things down much, but if it was a peculiar lock that could tell you exactly where in your code to look. If you are stuck with 9.1, you can perhaps use the debugger to get all but the first 22 characters of the query (the first 22 are overwritten by the <IDLE> in transaction\0 message). For example: (gdb) printf "%s\n", ((MyBEEntry->st_activity)+22)
{ "pile_set_name": "StackExchange" }
Q: In the doubling time formula, what does the a stand for? $A(t) = P(2)^{t/a}$ what does the lower case a stand for? A: The $a$ is the time-to-double or doubling time, analogous to the half-life of radioactive decay. Its unit is the same as the unit of time used in the problem. At time $t=0$ the amount is $A(0)=P$, where $P$ usually stands for Principal. At time $t=a$ the amount is $A(1)=2P$, double the initial amount. So $a$ is the amount of time it takes for the amount to double.
{ "pile_set_name": "StackExchange" }
Q: How do multi-currency bank accounts work? What is the advantage? I've recently read that banks are offering multi-currency accounts to their business customers. How do they actually work? Is it one bank account and the balance is available in, let's say for example, EUR and USD? What exchange rate are they using and which currency is the main currency? What's the advantage of having a multi-currency account vs. two bank accounts at the same bank, one in EUR the other in USD? A: Today typically a Business needs to hold accounts in more than one currency. Banks in certain countries are offering what is called a dual currency account. It is essentially 2 accounts with same account number but different currency. So One can have an account number say 123456 and have it in say AUD and USD. So the balance will always show as X AUD and Y USD. If you deposit funds [electronic, check or cash] in USD; your USD balance goes up. Likewise at the time of withdrawal you have to specify what currency you are withdrawing. Interest rates are calculated at different percentage for different currencies. So in a nutshell it would like operating 2 accounts, with the advantage of remembering only one account number. Designate a particular currency as default currency. So if you don't quote a currency along with the account number, it would be treated as default currency. Otherwise you always quote the account number and currency. Of-course bundled with other services like free Fx Advice etc it makes the entire proposition very attractive. Edit: If you have AUD 100 and USD 100, if you try and withdraw USD 110, it will not be allowed; Unless you also sign up for a auto sweep conversion. If you deposit a GBP check into the account, by default it would get converted into AUD [assuming AUD is the default currency]
{ "pile_set_name": "StackExchange" }
Q: Execute Func with generic type which should return a long value I have a method with a Func<T, long> as parameter. I want to call that method like this: Write(x => x.Id, "Some info"); The method looks like the following. The problem I have is inside that method. I don't know how to execute the function to get the long value. public void Write<TEntity>(Func<TEntity, long> func, string info) { var id = func(); // Doesn't work, func() needs an argument... } How does this work? How can I execute the function? A: Sure it doesn't work, you need n argument. Solution depends on what are you actuyll going to do. 1) You could just give TEntity as a parameter: public void Write<TEntity>(Func<TEntity, long> func, TEntity entity, string info) { var id = func(entity); } 2) If this function is inside of TEntity class you could call it with this argument: class TEntity { public void Write<TEntity>(Func<TEntity, long> func, string info) { var id = func(this); } } 3) Perhaps you don't need any TEntity to get an Id, in that case rewrite your paramter as a func without arguments: public void Write<TEntity>(Func<long> func, string info) { var id = func(); }
{ "pile_set_name": "StackExchange" }
Q: C Programming: how to get normal value of int without using value - 48? So i have this loop the check user input: int ch, num; while ((ch = getchar()) != '\n') { if (isdigit(ch)) { num = ch - 48; } } So according this table: Character Decimal Value 0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57 I am using this way to get my number: num = ch - 48; And if for example i want to multiple my number by 10 ? A: Here's the best way to read input from user till the new line. I'm posting one example you can go through it and implement your code as you need. This example will read for user input in integer untill newLine(\n). Make sure you are not giving space at last. Sample Code: #include <stdio.h> int main(void) { int i=0,size,arr[10000]; char temp; do{ scanf("%d%c", &arr[i], &temp); i++; } while(temp!= '\n'); size=i; for(i=0;i<size;i++){ printf("%d ",arr[i]); } return 0; }
{ "pile_set_name": "StackExchange" }
Q: Connect to MS SQL Server 2008 with PHP running on XP / IIS I'm trying to connect to MSSQL 2008 from a (LAN) XP machine running IIS 5.1 & PHP 5.3. I tried following this answer https://stackoverflow.com/a/5432118 Problems started when I had no snapshot.txt, however as I am running IIS and PHP as FastCGI extension I am fairly confident I need the non-threadsafe dll ? Anyway, I downloaded SQLSRV30.EXE and extracted php_sqlsrv_53_nts.dll to my ext dir and added the extension to my php.ini. I also confirmed the extension_dir was correct & installed Microsoft SQL Server 2008 R2 Native Client before restarting IIS. Unfortunately phpinfo() does not list sqlsrv as a loaded extension and I am now totally lost so any help would be highly appreciated. Thanks A: Ok, so I eventually got the the bottom of it so I thought I'd report back and hopefully save some else a head ache.... In my php.ini I set display_startup_errors = On, restarted IIS and reloaded the page. At this point I got the magic nugget of information that for some reason was not being added to the log Fatal error: Unable to load Library........error: Access is denied. So I navigated to the ext dir and selected the extension Right Click > Properties > Security And added permissions for Users & Power Users - restarted IIS and boom sqlsrv was loaded.
{ "pile_set_name": "StackExchange" }
Q: In Dropwizard's db migration wrapper, is it possible to migrate based on contexts? With liquibase there is the feature to specify contexts on your change sets. For xml its in a tag like context=test (http://www.liquibase.org/documentation/contexts.html). The idea with contexts being, you could have migration that only get applied when you specify certain contexts (like load this test data only when running in qa or test contexts). I can't seem to find a way within Dropwizard's db migrate to utilize this functionality. Does anyone know if this is possible? A: Short answer... No, after digging in I've found that dropwizard only exposes a limited subset the liquibase functionality.
{ "pile_set_name": "StackExchange" }
Q: How to use locally served tiles for interactive maps instead of just a png image of tiles I followed this link and it worked for me.. https://switch2osm.org/serving-tiles/manually-building-a-tile-server-14-04/ I can serve tiles locally but running it and by just typing the link like for instance - localhost/osm_tiles/0/0/0.png and it gives me an image with a particular zoom level, x and y axis. Now I have this advanced localized openstreet map example I saw.. http://openlayers.org/en/v3.2.1/examples/localized-openstreetmap.html which is of course an advanced custom tile server. Taking the tutorial I got from switch2osm, is it possible for me to create that same kind of tile server? A: This example uses open cycle map tiles. So yes, you can create and use your own rendering styles. In switch2osm.org tutorial related section is Stylesheet configuration. You could write mapnik style xml stylesheet or convert it from carto-css project. This step actually converts carto-css to mapnik xml. carto project.mml > OSMBright.xml You could use base OSM style as an example. https://github.com/gravitystorm/openstreetmap-carto And here you could find how OpenCycleMap style looks like https://github.com/tclavier/mapnik
{ "pile_set_name": "StackExchange" }
Q: Is there any advantage to using '<< 1' instead of '* 2'? I've seen this a couple of times, but it seems to me that using the bitwise shift left hinders readability. Why is it used? Is it faster than just multiplying by 2? A: You should use * when you are multiplying, and << when you are bit shifting. They are mathematically equivalent, but have different semantic meanings. If you are building a flag field, for example, use bit shifting. If you are calculating a total, use multiplication. A: It is faster on old compilers that don't optimize the * 2 calls by emitting a left shift instruction. That optimization is really easy to detect and any decent compiler already does. If it affects readability, then don't use it. Always write your code in the most clear and concise fashion first, then if you have speed problems go back and profile and do hand optimizations. A: It's used when you're concerned with the individual bits of the data you're working with. For example, if you want to set the upper byte of a word to 0x9A, you would not write n |= 0x9A * 256 You'd write: n |= 0x9A << 8 This makes it clearer that you're working with bits, rather than the data they represent.
{ "pile_set_name": "StackExchange" }
Q: WordPress po mo file Hi all I have one problem. Po file doesn't work. I use qtransltae-x for translation. And I create custom pot file example # Copyright (C) 2015 Gawatt msgid "" msgstr "" "Project-Id-Version: Gawatt 1.0.0\n" "POT-Creation-Date: 2015-06-03 11:30+0400\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "PO-Revision-Date: 2015-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <[email protected]>\n" "X-Generator: Poedit 1.8.1\n" #: club.php:25 msgid "zibil" msgstr "" after that I generate it` # Copyright (C) 2015 Gawatt msgid "" msgstr "" "Project-Id-Version: Gawatt 1.0.0\n" "POT-Creation-Date: 2015-06-03 11:30+0400\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "PO-Revision-Date: 2015-06-03 12:45+0400\n" "X-Generator: Poedit 1.7.6\n" "Last-Translator: \n" "Language-Team: \n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" "Language: ru_RU\n" #: club.php:25 msgid "zibil" msgstr "sdfsdfsdfsdf" code output ` <?php _e('zibil'); ?> and in wp-config define('WPLANG', 'ru_RU'); but when I switch language to russina it doesn't work, can you please help me thank you. A: If you want to translate your theme you need to tell Wordpress where to find the translation files using: <?php load_theme_textdomain( $domain, $path ) ?>, doc. For example: add_action('after_setup_theme', 'my_theme_setup'); function my_theme_setup(){ load_theme_textdomain('my_theme', get_template_directory() . '/languages'); } And when using the function _e() you have to include the domain, doc Like so: <?php _e('zibil', 'mytheme'); ?>.
{ "pile_set_name": "StackExchange" }
Q: How do I isolate $y$? In the equation $kx - 3y = 10$, how do I isolate the $y$ component? I forgot how to do basic algebra and I am taking a calculus course, lol. I'm not sure if you multiply or subtract, I think you look at the sign next to it? A: Here are the steps \[ kx-3y=10 \] \[ kx-3y +3y=10+3y \] \[ kx=10+3y \] \[ kx-10=10+3y-10 \] \[ kx-10=3y \] \[ \frac{kx-10}{3}=\frac{3y}{3} \] \[ \frac{kx-10}{3}=y \] I hope this helps you understand.
{ "pile_set_name": "StackExchange" }
Q: NullPointer Exception when calling a method from onResume I am setting my selectDate on longPress but why does it say that my selectDate is null in HighlightCalander function? Any ideas. This eventHandler is called in onCreate (Main Activity):- calendarview.setEventHandler(new CalendarView.EventHandler() { @Override public void onDayLongPress(Date date) { DateFormat df = SimpleDateFormat.getDateInstance(); selectDate = date; System.out.println(selectDate); intent1 = new Intent(getApplicationContext(), MakeAppointmentsActivity.class); intent1.putExtra("DATE",df.format(date)); startActivity(intent1); } This function is called in onResume (Main Activity):- public void HighlightCalendar() { intent2 = getIntent(); // get my boolean from save button boolean savedDate = intent2.getBooleanExtra("savedDate", false); // if i pressed my saved button if(savedDate) { Toast.makeText(this,"true",Toast.LENGTH_SHORT).show(); try { DateFormat df = SimpleDateFormat.getDateInstance(); SimpleDateFormat curFormater = new SimpleDateFormat("MMM yyyy"); String dateString = df.format(selectDate); Date dateObj = curFormater.parse(dateString); events.add(dateObj); calendarview.updateCalendar(events); }catch (ParseException e){ e.printStackTrace(); } } else { Toast.makeText(this,"false",Toast.LENGTH_SHORT).show(); } } A: You are assigning a value to selectDate in onDayLongPress but you are using it in onResume. Everytime you create an Activity onCreate() and onResume() are called. You are getting a NUllpointerException because, in onResume() (which is called before onDayLongPress) selectDate is not initalized and therefore null. You could initalize selectDate in one of the 2 methods to avoid the exception.
{ "pile_set_name": "StackExchange" }
Q: Como atualizar BD sqlite java android Como eu faço para adicionar uma coluna no banco de dados da minha aplicação android java sem perder os dados do banco de dados atual? O meu código: public DataBaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT, " + KEY_DESCRICAO + " TEXT)"; db.execSQL(CREATE_CONTACTS_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); // Create tables again onCreate(db); } E quando eu adiciono uma coluna ela não é criada, pois a tabela já existe e mantém as colunas atuais. A: Você pode usar a seguinte DDL: ALTER TABLE tabela ADD COLUMN nova_coluna CHAR(50) https://stackoverflow.com/questions/4253804/insert-new-column-into-table-in-sqlite Adicione este código no método onCreate(), logo após o seu CREATE TABLE. Além disso, adicione à sua query de criação a condição de criar somente se não existir, por exemplo: CREATE TALBE IF NOT EXISTS table ...restante da query Assim, quando uma nova versão do banco (ou a primeira instalação do app) for instalada a tabela será criada somente se não existir, preservando os dados já instalados (quando o app for atualizado), e o ALTER TABLE irá mudar a estrutura da sua tabela. Esses comandos apenas serão executados na primeira vez que o nova versão do banco for instalada (ou a primeira instalação do app). Testei aqui e deu certo.
{ "pile_set_name": "StackExchange" }
Q: How to edit grub2 to use kdump? I was following http://fedoraproject.org/wiki/How_to_use_kdump_to_debug_kernel_crashes and in step 2 I need to add the line to grub.cfg, but grub.cfg is a shell I do not know how to edit it, most available resources tell you only the method to rearrange menu items, can anyone tell me what should be added to the file. I use 64-bit Fedora 18. A: The kernel line in grub should looks like: kernel /vmlinuz-3.1.4-1.fc16.x86_64 ro root=/dev/VolGroup00/LogVol00 rhgb LANG=en_US.UTF-8 crashkernel=128M There's a note in the instructions: (...) An example command line might look like this (for grub2, "kernel" is replaced by "linux"): So, the one you are looking for is how to replace the kernel boot parameters. This is easily achievable modifying the GRUB_CMDLINE_LINUX_DEFAULT in the /etc/default/grub file. Then running su -c 'grub2-mkconfig -o /boot/grub2/grub.cfg' to update the script. Open with an editor /etc/default/grub Look for the GRUB_CMDLINE_LINUX_DEFAULT, add it if it's not present. Append the crashkernel=128M to the line, like this: GRUB_CMDLINE_LINUX_DEFAULT="quiet crashkernel=128M" Save the file. Run su -c 'grub2-mkconfig -o /boot/grub2/grub.cfg' Check the grub.cfg file, that contains the lines correctly: grep -i quiet /boot/grub/grub.cfg linux /vmlinuz-3.12-1-amd64 root=UUID=cead26d6-08f4-4894-ac78-a9a4ce59f773 ro initrd=/install/initrd.gz quiet crashkernel=128M linux /vmlinuz-3.12-1-amd64 root=UUID=cead26d6-08f4-4894-ac78-a9a4ce59f773 ro initrd=/install/initrd.gz quiet crashkernel=128M Restart and done.
{ "pile_set_name": "StackExchange" }
Q: Rotating a view in Android I have a button that I want to put on a 45 degree angle. For some reason I can't get this to work. Can someone please provide the code to accomplish this? A: API 11 added a setRotation() method to all views. A: You could create an animation and apply it to your button view. For example: // Locate view ImageView diskView = (ImageView) findViewById(R.id.imageView3); // Create an animation instance Animation an = new RotateAnimation(0.0f, 360.0f, pivotX, pivotY); // Set the animation's parameters an.setDuration(10000); // duration in ms an.setRepeatCount(0); // -1 = infinite repeated an.setRepeatMode(Animation.REVERSE); // reverses each repeat an.setFillAfter(true); // keep rotation after animation // Aply animation to image view diskView.setAnimation(an); A: Extend the TextView class and override the onDraw() method. Make sure the parent view is large enough to handle the rotated button without clipping it. @Override protected void onDraw(Canvas canvas) { canvas.save(); canvas.rotate(45,<appropriate x pivot value>,<appropriate y pivot value>); super.onDraw(canvas); canvas.restore(); }
{ "pile_set_name": "StackExchange" }
Q: how to link multiple alarmManagers with different notifications in OnReceive? I want to fire different notifications when a specific alarmManager is reached. For example I want to display "independence day" when we reach the date of Independence stored in a certain alarmManager, and to display "Steve jobs died" when we reach the date of his death stored in another Alarm Manager, and so on. So my question is how to link each alarmManager(cal and cal2) with different notification? I did this until now, in MainActivity: Calendar cal = Calendar.getInstance(); cal.set(Calendar.DATE,19); cal.set(Calendar.MONTH,11); cal.set(Calendar.YEAR,2015); cal.set(Calendar.HOUR_OF_DAY, 21); cal.set(Calendar.MINUTE, 42); cal.set(Calendar.SECOND, 30); Calendar cal2 = Calendar.getInstance(); cal2.set(Calendar.DATE,19); cal2.set(Calendar.MONTH,11); cal2.set(Calendar.YEAR,2015); cal2.set(Calendar.HOUR_OF_DAY, 21); cal2.set(Calendar.MINUTE, 43); cal2.set(Calendar.SECOND, 10); Intent alertIntent = new Intent(this, AlertReceiver.class); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT)); alarmManager.set(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), PendingIntent.getBroadcast(this, 2, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT)); notice that I made to dates to fire notification and it is working, the notification in onReceive was fired twice, the first time when I reach "cal" and for the second time when I reach "cal2". But as I mentioned above, I need to fire a different notification when I reach cal2 this is the OnReceive: public class AlertReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { createNotification(context, "title1", "independence day", "event of today"); //here i want to link this notification with AlarmManager containing Cal as a date createNotification(context, "title2", "steve jobs died", "event of today"); //here i want to link this notification with AlarmManager containing Cal2 as a date } public void createNotification(Context context, String msg, String msgText, String msgAlert) { PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.not) .setContentTitle(msg) .setTicker(msgAlert) .setContentText(msgText); //intent to fire when notification clicked on mBuilder.setContentIntent(notificIntent); //how the person will be notified mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND); //cancel notification when clicked in the taskbar mBuilder.setAutoCancel(true); NotificationManager mNotificationManager= (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); mNotificationManager.notify(0,mBuilder.build()); } after applying what mentioned below: i made this 4 events: AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent alertIntent = new Intent(this, AlertReceiver.class); alertIntent.putExtra("title", "event1"); alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT)); Intent alertIntent2 = new Intent(this, AlertReceiver.class); alertIntent2.putExtra("title", "event2"); alarmManager.set(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), PendingIntent.getBroadcast(this, 2, alertIntent2, PendingIntent.FLAG_UPDATE_CURRENT)); Intent alertIntent3 = new Intent(this, AlertReceiver.class); alertIntent3.putExtra("title", "event3"); alarmManager.set(AlarmManager.RTC_WAKEUP, cal3.getTimeInMillis(), PendingIntent.getBroadcast(this, 3, alertIntent3, PendingIntent.FLAG_UPDATE_CURRENT)); Intent alertIntent4 = new Intent(this, AlertReceiver.class); alertIntent4.putExtra("title", "event4"); alarmManager.set(AlarmManager.RTC_WAKEUP, cal4.getTimeInMillis(), PendingIntent.getBroadcast(this, 4, alertIntent3, PendingIntent.FLAG_UPDATE_CURRENT)); and in OnReceive: createNotification(context,intent.getStringExtra("title"), "event", " event"); sometimes for the first time running the application all the events appear, sometimes the 3rd appear twice, and the first two do not appear, sometimes just the last one appear, so there is something wrong or messy in my code, whats the problem? calendar: Calendar cal = Calendar.getInstance(); cal.set(Calendar.DATE,24); cal.set(Calendar.MONTH,11); cal.set(Calendar.YEAR,2015); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 55); cal.set(Calendar.SECOND, 10); Calendar cal2 = Calendar.getInstance(); cal2.set(Calendar.DATE,24); cal2.set(Calendar.MONTH,11); cal2.set(Calendar.YEAR,2015); cal2.set(Calendar.HOUR_OF_DAY, 23); cal2.set(Calendar.MINUTE, 55); cal2.set(Calendar.SECOND, 20); Calendar cal3 = Calendar.getInstance(); cal3.set(Calendar.DATE,24); cal3.set(Calendar.MONTH, 11); cal3.set(Calendar.YEAR,2015); cal3.set(Calendar.HOUR_OF_DAY, 23); cal3.set(Calendar.MINUTE, 55); cal3.set(Calendar.SECOND, 30); Calendar cal4 = Calendar.getInstance(); cal4.set(Calendar.DATE,24); cal4.set(Calendar.MONTH, 11); cal4.set(Calendar.YEAR,2015); cal4.set(Calendar.HOUR_OF_DAY, 23); cal4.set(Calendar.MINUTE, 55); cal4.set(Calendar.SECOND, 40); A: You can pass that information along with the intent while scheduling the alarm. Intent alertIntent = new Intent(this, AlertReceiver.class); alertIntent.putExtra("Notification Key", 1); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT)); And in your onReceive check the value and show the notification based on that: Integer notificationId = intent.getIntExtra("Notification Key", -1); if (notificationId == 1) { // Show indipendente day } else { // do something else } Instead of passing integer value, you can also pass the notification message and show it directly without any if...else condition. Passing string data: alertIntent.putExtra("Notification Key", "Independence day"); Getting string back: String message = intent.getStringExtra("Notification Key"); // Calling the notification createNotification(context, "title1", message, "event of today");
{ "pile_set_name": "StackExchange" }
Q: How to add json object as a type for attributes in sails-mongo Document.js module.exports = { attributes: { type: { type: 'string' }, createdBy: { model: 'User', required: true }, body: { type: 'string' }, comments: { model: 'Comments' }, metaInfo: { type: 'json' } } }; I would like to know if there is any way that I can write a model like the one given above, so that, I can add a json object to metaInfo which contains a name-value pair. Eg: json: { name: 'Project', value: 'MyFirstProject'} Is this possible through waterline? Thanks in advance. A: I believe the comment answers your question. If you need any further help, you can refer the answers in this issue raised in Sails Github page: JSON Array of Strings
{ "pile_set_name": "StackExchange" }
Q: typeerror while retriving cookies in web2py var websites = new Array("http://www.abc.com","http://www.123.com"); //i am writin cookies like this in javascript in view var web=websites[1] ; var exdate=new Date(); exdate.setDate(exdate.getDate() + 24); var visit= web +" ;expires= "+ exdate.toUTCString(); document.cookie= "mycookie =" + visit; now while retriving it in controller print request.cookies i can see my cookies is there if request.cookies.has_key("mycookie"):#geting true value=request.cookies("mycookie").value giving me exception <type 'exceptions.TypeError'> why? A: In this case request.cookies is a dictionary, so you must access it as such. As you did: value=request.cookies("mycookie").value This is treating request.cookies as a function, which is why you get a TypeError since it is not a function. To access a value in a dictionary given the key, you can use: value=request.cookies["mycookie"].value
{ "pile_set_name": "StackExchange" }
Q: Problem adding custom entities to SpaCy's NER I added a new entity called "orgName" to en_core_web_lg using https://spacy.io/usage/training#example-new-entity-type All my training data (26k sentences) have the "orgName" labeled in them. To deal with the catastrophic forgetting problem, I ran en_core_web_lg on those 26k raw sentences and added the ORG, PROD, FAC, etc. entities as labels and not face the colliding entities, I created duplicates. So, for a sentence A which was labeled by "orgName", I created a duplicate A2 which has ORG, PROD, FAC, etc. ending up with about 52k sentences. I trained using 100 iterations. Now, the problem is that testing the model even on the training sentences, it's not showing the ORG, PROD, FAC, etc. but only showing "orgName". Where do you think the problem is? A: In principle the way you're trying to solve the catastrophic forgetting problem, by retraining it on its old predictions, seems like a good approach to me. However, if you are having duplicate versions of the same sentence, but annotated differently, and feeding that to the NER classifier, you may confuse the model. The reason is that it doesn't just look at the positive examples, but also explicitely sees non-annotated words as negative cases. So if you have "Bob lives in London", and you only annotate "London", then it will think Bob is surely not an NE. If then you have a second sentence where you annotate only Bob, it will "unlearn" that London is an NE, because now it's not annotated as such. So consistency really is important. I would suggest to implement a more advanced algorithm to resolve the conflicts. One option is to always just take the annotated entity with the longest Span. But if the Spans are often exactly the same, you may need to reconsider your label scheme. Which entities collide most often? I would assume ORG and OrgName? Do you really need ORG? Perhaps the two can be "merged" as the same entity?
{ "pile_set_name": "StackExchange" }
Q: Should I choose primary or logical, when I use UEFI + GPT to install Ubuntu 16.04 with custom partition? when I install Ubuntu 16.04 with UEFI+ GPT, I feel uncertain! Why I don't select default install? Because it's stupid. When I create a EFI partition, should I select primary or logic? When I create a EXT4 partition, should I select primary or logic? When I create a SWAP partition, should I select primary or logic? And what's the function of "reserve boot area"? A: Legacy BIOS has a limitation of 4 primary partitions and 2.2 TB per drive. With UEFI, this limitation is now 128 primary partitions and 8 ZB (source: Wikipedia). So you can choose either primary or logic partitions, UEFI will deal with them anyway. On my laptop, I have chosen primary partitions, it sounds proper than logic partitions on the same primary partition. Regarding to your question about reserved boot area, the only topics I find on it are this one and this one, both quite old. But both give a similar answer, so I'd like to ask: are you 100% sure you boot in UEFI mode and not legacy mode?
{ "pile_set_name": "StackExchange" }
Q: I can't change the value of a struct variable within a slice in Go this my code is run, but when I m trying change the valeu of slice into atribute count , this value doesn't change. I change values ip because they are internal. How I say this code is run, He have more others functions that send emails but they don't make problems. func testeLink() { naves := []nave{ nave{"SC", "111.11.11.111", 0}, nave{"MA", "222.2.222.2", 0}, nave{"PE", "333.33.33.33", 0}} sliceLength := len(naves) var wg sync.WaitGroup wg.Add(sliceLength) for i := range naves { go func(nave nave) { out, _ := exec.Command("ping", nave.ip, "-c 1 -w 1").Output() //out, _ := exec.Command("ping", "192.168.0.111", "-c 1", "-i 3", "-w 10").Output() if strings.Contains(string(out), "0 received") || strings.Contains(string(out), "Received = 0") { fmt.Print(naves[i].count) nave.count++ fmt.Print(nave.count) fmt.Printf("A nave <%s> está OFFline \n", nave.name) if nave.count >= 3 { enviarEmail(nave.name) } } else { nave.count = 0 fmt.Printf("A nave <%s> está ONline \n", nave.name) } defer wg.Done() }(naves[i]) } wg.Wait() } func main() { for { testeLink() fmt.Println("Aguardando o tempo ...") time.Sleep(5 * time.Second) } } A: Your goroutine is taking naves[i] by value, so a copy of it is being passed to it. Pass a reference to it: go func(nave *nave) {...} (&naves[i]) Alternatively, you can simply pass i: go func(i int) { // use naves[i] in the goroutine } (i)
{ "pile_set_name": "StackExchange" }
Q: ArcGIS Javascript API zoom out? I am using the ArcGIS API for Javascript and am wondering if it comes with functionality for zooming out using a rectangle, similar to the behavior in ArcGIS Desktop? Specifically, the user draws a rectangle and it zooms out based on that rectangle. I can create the functionality myself, but was wondering if it already existed in the API... A: The API has a Navigation toolbar class that uses this functionality. It comes with a zoom out tool that works by drawing a box. There is a sample page here.
{ "pile_set_name": "StackExchange" }
Q: tslint update error "Cannot find module 'tslint/lib/lint'" We recently upgraded our Angular 2 project to @angular/cli version 1.0. We also upgraded tslint from 2.x to 5.x. Now we receive the following tslint error at design time (in VSCode Output terminal). Cannot find module 'tslint/lib/lint' while validating. I've attempted to follow several github thread suggestions including removing deprecated rules and adding new rules, rolling back tslint to a previous version and completely uninstalling and reinstalling @angular/cli and associated modules. However, this error continues to arise and it's preventing tslint from evaluating our code. A previous SO post cited the same error message but apparently for a different reason; the accepted answer did not resolve my issue: Error: Cannot find module 'tslint/lib/lint' when trying to extend tslint-microsoft-contrib A: I found the issue: codelyzer was out of date. I updated it from 0.0.26 to 2.1.1 and now tslint is successfully linting our code. npm update codelyzer --save-dev
{ "pile_set_name": "StackExchange" }
Q: Sending serial signal of HT12A encoder by wire over 25 meters distance This question has been asked many times, but I couldn't find something regarding sending out serial binary pulses from HT12A encoder over long distance. The wire will be running beside of AC 220v wires, so will it work efficiently without noises or voltage loss ?? A: Use a twisted pair (one pair of a cat5e cable) or a shielded twisted pair if you are overly concerned, or convert to optical fiber if you are very overly concerned. 50/60 Hz is hardly ever a problem with unshielded twisted pair in practice. If you are running one of those "data over power lines" devices in the building you might have more reason to be concerned, as those put high frequency signals on the power lines. I haven't bothered to look far enough into the data sheet to find likely data rates, but back in the days of modems (current for some folks, still) data signals ran for many miles on UTP cables at rates up to 56 Kb.
{ "pile_set_name": "StackExchange" }
Q: Building Delphi project from Visual Studio Code I have already set up build and debug environment for Object Pascal inside Visual Studio Code via FPC and GDB, but I just made build process work for programs containing only 1 .pas file via "command": "fpc", "args": [ "-g", "-Px86_64", "helloWorld.pas" ], Now, I need to build quite big Delphi project group (something like solution?) and it contains main project file .groupproj. Is there a way to build the .groupproj via FPC somehow? Or at least some workaround like conversion to .lpi and then build via FPC? Or at least call Delphi compiler/builder from VS Code and build the whole project group via it? (but I don't like this option, because I prefer to not use Delphi) A: To get some facts straight for other people that might stumble on this: FPC supports Delphi source files (.lpr/.dpr, .pp/.pas and .inc). Not Delphi meta information (.dproj/.dof/.bpg/.cfg/.groupproj) which is Delphi version dependent anyway. Lazarus conversion tool also converts .dfms. Basically it is a .dfm cleaner and Uses clause enhancer, just like some conversion tools between Delphi versions. It by default however also does substitutions that change Delphi code (that works in FPC's Delphi (-Sd) mode) into the objfpc dialect (-S2 mode) preferred by Lazarus . Always make a backup before trying, and check the configuration of the conversion tool thoroughly. FPC and Delphi commandline parameters are different. FPC does not support Lazarus metadata formats like .lpi. The Lazarus utility Lazbuild however does support building Lazarus projects from the commandline. But luckily the basics are the same a main program or library file files) a set of unit (.pas files) and include directories (.inc files). FPC differentiates between the two, delphi doesn't. autocreated forms must be added to the project. any additional commandline switches like defines to set, range checking optimization options. So in worst case, examine the Delphi projects (either in IDE or texteditor) for directories and switches and create either a manual buildscript or a lazarus (.lpi) project. However it is vital to keep in mind that the default FPC mode is NOT Delphi mode, so always when executing FPC make sure you manually enable Delphi mode (-Sd) Group project support within Lazarus is very new (as in months), and afaik not even in stable versions yet. Though if you create a bunch of .lpis, a batch file/shellscript with a sequence of lazbuild commands on .lpis might do it. P.s. throw the VSCode under the bus and use Lazarus.
{ "pile_set_name": "StackExchange" }
Q: WPF Specifying How Columns Are Generated When They Are Binded I have a DataGrid that gets binded by various DataTables. The nullable boolean columns get converted into DataGridCheckboxColumn. is there a way to convert this to a text column that shows yes, no, not available? A: If you wanna keep the auto generating behavior you can subscribe to the AutoGeneratingColumn event from the DataGrid and change the generated DataGridColumn private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { if (e.Column is DataGridCheckBoxColumn dataGridCheckBoxColumn) { Binding binding = (Binding)dataGridCheckBoxColumn.Binding; binding.Converter = new BooleanToStringConverter(); //Converter Klaus Gütter mentioned e.Column = new DataGridTextColumn() { Header = dataGridCheckBoxColumn.Header, Binding = binding }; } }
{ "pile_set_name": "StackExchange" }
Q: can't get osd lyrics ubuntu 14.04 I tried to add ppa on my 14.04, but I got this error Fetched 609 kB in 3min 44s (2,711 B/s) W: Failed to fetch http://ppa.launchpad.net/osd-lyrics/ppa/ubuntu/dists/trusty/main/binary-amd64/Packages 404 Not Found W: Failed to fetch http://ppa.launchpad.net/osd-lyrics/ppa/ubuntu/dists/trusty/main/binary-i386/Packages 404 Not Found E: Some index files failed to download. They have been ignored, or old ones used instead. I already try screenlets sth: like that but it doeesn't work either... please help me! guys! A: Here is how I got it installed. I downloaded it from here. Once downloaded I used Gdebi to install it. If you don't have Gdebi installed, just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below: sudo apt-get install gdebi Once installed, just open the file with it, and click install. See images below.
{ "pile_set_name": "StackExchange" }
Q: How do I code my userform to insert the specified number of rows beneath the selected cell? I have a userform that I've created that first asks how many rows I would like to insert. The next part of the userform asks what values I would like in columns 1 and 32 of each newly created row (I've set it up so that a maximum of 6 new rows can be created at one time). My data has 45 columns, and the only data that I want to change in the newly created rows is the data in the two columns i said earlier (1 and 32). I want the data from all the other columns from the original row to be copied down into each new row. My problem is that I can't seem to figure out how to write a code that will do this the way I want it. To provide an example, if I respond to the userform that I want to add 3 rows below the currently active cell, it will then ask me what values i want to enter for columns 1 and 32 for each of these new rows. So I would enter something like this: First New Row Column 1: 8/17/2019 Column 32: 400 Second New Row Column 1: 8/10/2019 Column 32: 500 Third New Row Column 1: 8/3/2019 Column 32: 600 I've tried many different codes but I've only really figured out how to write it so that it inserts one row below the active cell and its completely blank, I don't know how to program it so that it enters he values I selected for columns 1 and 32 and copies all other data down from the original row. I've figured out the code for the clear and cancel button on my userform already, I am now only concerned with writing this code for the "OK" button. Private Sub CancelButton_Click() Unload Me End Sub Private Sub ClearButton_Click() Call UserForm_Initialize End Sub Private Sub OKButton_Click() Dim lRow As Long Dim lRsp As Long On Error Resume Next lRow = Selection.Row() lRsp = MsgBox("Insert New row above " & lRow & "?", _ vbQuestion + vbYesNo) If lRsp <> vbYes Then Exit Sub Rows(lRow).Select Selection.Copy Rows(lRow + 1).Select Selection.Insert Shift:=xlDown Application.CutCopyMode = False Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone End Sub Private Sub UserForm_Initialize() AddRowsTextBox.Value = "" Date1TextBox.Value = "" Date2TextBox.Value = "" Date3TextBox.Value = "" Date4TextBox.Value = "" Date5TextBox.Value = "" Date6TextBox.Value = "" Qty1TextBox.Value = "" Qty2TextBox.Value = "" Qty3TextBox.Value = "" Qty4TextBox.Value = "" Qty5TextBox.Value = "" Qty6TextBox.Value = "" End Sub A: what i understand from your requirement, I would have add one more spin button on the form to make it user friendly. It may look like this. User form Code may please be modified according to control names in your form Option Explicit Public Bal As Double, XQnty As Double, LargeOrder As Double, Sm As Double Private Sub CommandButton1_Click() Dim lRow As Long Dim lRsp As Long lRow = ActiveCell.Row() lRsp = MsgBox("Insert New row Below " & lRow & "?", vbQuestion + vbYesNo) If lRsp <> vbYes Then Exit Sub Dim Ws As Worksheet Dim R As Long, i As Integer, RowtoAdd As Integer Set Ws = ThisWorkbook.ActiveSheet RowtoAdd = Me.SpinButton1.Value R = ActiveCell.Row With Ws .Cells(R, 32).Value = LargeOrder For i = 1 To RowtoAdd .Cells(R + 1, 1).EntireRow.Insert Shift:=xlDown .Cells(R, 1).EntireRow.Copy Destination:=.Cells(R + 1, 1) .Cells(R + 1, 1).Value = Me.Controls("TextBox" & i).Value .Cells(R + 1, 32).Value = Me.Controls("TextBox" & 7 + i).Value R = R + 1 Next i End With Unload Me End Sub Private Sub CommandButton2_Click() Unload Me End Sub Private Sub SpinButton1_Change() Dim x As Integer, i As Integer, Y As Double Me.TextBox7.Value = Me.SpinButton1.Value x = Me.SpinButton1.Value Sm = 0 For i = 1 To 6 Me.Controls("TextBox" & i).BackColor = IIf(i <= x, RGB(255, 100, 100), RGB(255, 2550, 255)) Me.Controls("TextBox" & i + 7).Value = IIf(i <= x, Int(Bal / x), 0) Sm = Sm + IIf(i <= x, Int(Bal / x), 0) Next If Sm <> Bal Then Me.TextBox8.Value = Int(Bal / x) + Bal - Sm End If ManualBal End Sub Private Sub TB_LO_Change() LargeOrder = Val(Me.TB_LO.Value) Bal = XQnty - LargeOrder ManualBal End Sub Private Sub UserForm_Initialize() Dim i As Integer, dx As Variant Me.SpinButton1.Value = 1 Me.TextBox7.Value = 1 Me.TextBox1.BackColor = RGB(255, 100, 100) dx = ThisWorkbook.ActiveSheet.Cells(ActiveCell.Row, 1).Value XQnty = ThisWorkbook.ActiveSheet.Cells(ActiveCell.Row, 32).Value LargeOrder = 575 Bal = XQnty - LargeOrder Sm = 0 If IsDate(dx) = False Then dx = Now() For i = 1 To 6 Me.Controls("TextBox" & i).Value = Format(dx - i * 7, "mm-dd-yyyy") Sm = Sm + Int(Bal / 6) Me.Controls("TextBox" & i + 7).Value = Int(Bal / 6) Next If Sm <> Bal Then Me.TextBox8.Value = Int(Bal / 6) + Bal - Sm End If Me.TB_LO = LargeOrder Me.TB_Bal = 0 End Sub Private Sub ManualBal() Dim x As Integer, i As Integer x = Me.SpinButton1.Value Bal = XQnty - LargeOrder Sm = 0 For i = 1 To 6 ' Or may use 6 insted of X Sm = Sm + Val(Me.Controls("TextBox" & i + 7).Value) Next Me.TB_Bal.Value = Bal - Sm End Sub Private Sub TextBox8_Exit(ByVal Cancel As MSForms.ReturnBoolean) ManualBal End Sub Private Sub TextBox9_Exit(ByVal Cancel As MSForms.ReturnBoolean) ManualBal End Sub Private Sub TextBox10_Exit(ByVal Cancel As MSForms.ReturnBoolean) ManualBal End Sub Private Sub TextBox11_Exit(ByVal Cancel As MSForms.ReturnBoolean) ManualBal End Sub Private Sub TextBox12_Exit(ByVal Cancel As MSForms.ReturnBoolean) ManualBal End Sub Private Sub TextBox13_Exit(ByVal Cancel As MSForms.ReturnBoolean) ManualBal End Sub Here Text Box 1 to 6 for dates, 7 for Spin Button values and Text Box 8 to 13 for quantity. May please either modify code according to control names Or modify Control names according to code. Edit: Two new Text Box added named TB_BAL to show when entering values in manually in Quantity text boxes (balance calculated only at exit event of text boxes) and TB_LO to change LargeOrder during run.
{ "pile_set_name": "StackExchange" }
Q: Can't position items how I want it My "Products" bar isn't where is supposed to be. I am trying to put it near my sidebar in left. I don't want so much distance. I have "float:left". I can't move it to the left using margin-left or right. If I have "float:right", I can do this, but I don't want that. I want to set it with "float:left" option. Photo tast.html <!DOCTYPE html> <html> <!-- START HEAD --> <head> <meta charset="utf-8"> <title>xPeke</title> <link rel="stylesheet" href="test.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="icon" href="images/favicon-16x16.png" sizes="16x16" type="image/png"> </head> <!-- END HEAD --> <!-- START BODY --> <body> <div class="content"> <!-- START TOPBAR --> <div id="program"> <b style="color:black;">Program:</b> Luni-Vineri: 9:00-22:00&nbsp;&nbsp;&nbsp; Sambata: 9:00–20:00 &nbsp;&nbsp;&nbsp;Duminica: Inchis <a href="#" style="float:right">Login <span> / </span> Register</a> </div><br> <!-- END TOPBAR --> <!-- START SLIDESHOW --> <div class="slideshow-container"> <img class="mySlides" src="images/logo1.png" alt="Logo1" width="1500" height="300"> <img class="mySlides" src="images/logo2.png" alt="Logo2" width="1500" height="300"> <img class="mySlides" src="images/logo3.png" alt="Logo3" width="1500" height="300"> <div class="butonpoza"> <button onclick="clearTimeout(timer)">Opreste Animatia</button> <div class="dotts"> <span class="dot" onclick="currentSlide(1)"></span> <span class="dot" onclick="currentSlide(2)"></span> <span class="dot" onclick="currentSlide(3)"></span> </div> </div> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a><br> </div> <!-- END SLIDESHOW --> <!-- START LOGO, SEARCH & SOCIAL BAR --> <div> <img src="images/logo.png" alt="Logo" width="180" height="45" style="float:left"> <input class="search" type="text" name="search" placeholder="Search.."> <div style="float:right"> <a href="https://www.facebook.com/"><img class="socialmedia" src="images/facebook.png" alt="Facebook"></a> <a href="https://www.youtube.com/"><img class="socialmedia" src="images/youtube.png" alt="Youtube"></a> <a href="https://www.reddit.com/"><img class="socialmedia" src="images/reddit.png" alt="Reddit"></a> </div> </div> <!-- END LOGO, SEARCH & SOCIAL BAR --> <!-- START NAVIGATION BAR --> <div style="float:left"><br> <ul> <li class="dropdown"><a class="active" href="#home">Produse</a> <div class="dropdown-content"> <a href="#">Laptop, Telefoane & Tablete</a> <a href="#">Televizoare & Desktop</a> <a href="#">Tehnologii Smart</a> <a href="#">Haine & Accesorii</a> <a href="#">Anime & Manga</a> <a href="#">Carti de Joc</a> <a href="#">Jocuri & Jucarii</a> </div> </li> <li><a href="#news">Articole</a></li> <li><a href="#contact">Promotii</a></li> <li><a href="#about">Wishlist</a></li> <li><a href="#daaaa">FAQ</a></li> <li style="padding: 0px 432.5px;"></li> <li style="float:right"><a href="#daaaa">Cosul meu</a></li> <li style="float:right"><a href="#daaaa">Contul meu</a></li> </ul> </div> <!-- END NAVIGATION BAR --> <!-- START SIDEBAR --> <div style="float:left"><br> <a href="#" class="da">Noutati</a> <a href="#" class="da">Cele mai populare</a> <a href="#" class="da">Cele mai vandute</a> <a href="#" class="da">Precomenzi</a> <a href="#" class="da">Oferte speciale</a> <h3>Anunturi</h3> <aside class="sidebar"> <section class="articles"> <article class="article clearfix"> <img class="article__image" src="images/art1.png" alt="Hello World!"> <div class="article__content"> <h3 class="article__title">Hello Everyone!</h3> <p class="pby">posted by xPeke</p> </div> </article> <article class="article clearfix"> <img class="article__image" src="images/art2.png" alt="Yu-Gi-Oh!"> <div class="article__content"> <h3 class="article__title">We've added the newest Yu-Gi-Oh cards.</h3> <p class="pby">posted by Rekkles</p> </div> </article> <article class="article clearfix"> <img class="article__image" src="images/art3.png" alt="iPhone"> <div class="article__content"> <h3 class="article__title">A aparut noul iphone 8.</h3> <p class="pby">posted by Soaz</p> </div> </article> </section> </aside> <form class="twentyone"> <fieldset> <legend>Newsletter</legend><br> <div> Daca vrei sa afli ultimele promotii si noutați aboneaza-te la newsletter-ul Fnatic! </div><br> <div> <input class="newslt" type="text" name="newslt" placeholder="Email"> </div><br> <div> <button class="fltrgt" type="submit">Aboneaza-te!</button> </div> </fieldset> </form><br> </div> <!-- END SIDEBAR --> <!-- START PRODUSE RECOMANDATE BAR --> <div class="prodrec"> <h2> Products </h2> <table> <tr> <td> <div id="1" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> <td> <div id="2" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> <td> <div id="3" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> </tr> <!-- Spatiu--> <tr> <td></td> <td><br></td> </tr> <!-- pana aici--> <tr> <td> <div id="4" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> <td> <div id="5" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> <td> <div id="6" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> </tr> <!-- Spatiu--> <tr> <td></td> <td><br></td> </tr> <!-- pana aici--> <tr> <td> <div id="7" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> <td> <div id="8" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> <td> <div id="9" class="items"> <img src="img/products/robot1.jpg"/> <span class="desc">Description</span> <span class="price">$100</span> <span class="other">Other</span> <button>BUY</button> </div> </td> </tr> <!-- Spatiu--> <tr> <td></td> <td><br></td> </tr> <!-- pana aici--> </table> </div> <!-- END PRODUSE RECOMANDATE BAR --> <div style="float:right"> <h1> RIGHT! </h1> </div> <!-- START SCRIPT ZONE --> <script> var slideIndex = 1; var timer = null; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); if (n==undefined){n = ++slideIndex} if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active"; timer = setTimeout(showSlides, 10000); } </script> <!-- END SCRIPT ZONE --> <!-- START FOOTER --> <footer style="float:left"> <div class="skills">&copy; Cat e facut din site pana acum: 60%</div> </footer> <!-- END FOOTER --> </div> </body> <!-- END BODY --> </html> test.css .prodrec{ float: left; } /* START BODY */ body{ background-image: url("images/bgd.png"); background-repeat: repeat; } .content { max-width: 1500px; margin: auto; padding: 10px; } /* END BODY */ /* START TOPBAR */ #program{ font-size: 90%; font-family: 'Oswald', sans-serif; color: #2E2EFE; font-style: normal; font-weight: 700; padding: 0; border: 0; text-transform: uppercase; padding-bottom: 0; } a{ color: #2E2EFE; text-decoration: none; font-weight: 700; } /* END TOPBAR */ /* START SLIDESHOW */ .slideshow-container{ position: relative; } .mySlides{ display:none; width:100%; } .butonpoza{ float: right; margin-right: 10px; margin-top: -30px; position:relative; } /* END SLIDESHOW */ /* START SAGETI */ .prev, .next{ cursor: pointer; position: absolute; top: 50%; width: 15px; padding: 16px; margin-top: -50px; color: white; font-weight: bold; font-size: 25px; transition: 0.6s ease; border-radius: 0 3px 3px 0; } .next{ width: 15px; right: 0px; border-radius: 3px 0 0 3px; } .prev:hover, .next:hover{ background-color: rgba(0,0,0,0.8); } /* END SAGETI */ /* START DOTTS */ .dot{ cursor:pointer; height: 17px; width: 17px; margin: 0 10px; background-color: black; border-radius: 50%; display: inline-block; transition: background-color 0.6s ease; } .active, .dot:hover{ background-color: white; } .dotts{ text-align: center; margin-left: -1362px; margin-top: -20px; } /* END DOTTS */ /* START SEARCH AND SOCIAL BAR */ .search{ width: 10px; box-sizing: border-box; border: 2px solid #ccc; border-radius: 4px; font-size: 16px; background-color: white; background-image: url("images/search.png"); background-position: 10px 10px; background-repeat: no-repeat; padding: 12px 20px 12px 40px; -webkit-transition: width 0.4s ease-in-out; transition: width 0.4s ease-in-out; margin-left: 32px; width: 69%; } .socialmedia{ height: 50px; width: 50px; } /* END SEARCH AND SOCIAL BAR */ /* START NAVIGATION BAR */ ul{ list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li{ float: left; } li a{ display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover:not(.active){ background-color: #111; } .dropdown{ float: left; overflow: hidden; } .dropdown .dropbtn{ font-size: 16px; border: none; outline: none; color: white; padding: 14px 16px; background-color: inherit; } .active{ background-color: #4CAF50; } .dropdown-content{ display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a{ float: none; color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; } .dropdown-content a:hover:not(.active){ background-color: #ddd; } .dropdown:hover .dropdown-content{ display: block; } /* END NAVIGATION BAR */ /* START SIDEBAR */ .da{ display: block; float: none; color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: left; box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.2); background-color: #f9f9f9; text-transform: uppercase; box: 5px; width: 250px; border: 1px solid #555; } .da:hover:not(.active){ background-color: #fb2545; } .sidebar{ width: 50%; float: left; } .sidebar .article__image{ float: left; width: 35%; } .sidebar .article__content{ float: right; width: 61%; padding-left: 10px; } .sidebar .article__title{ display: block; text-transform: uppercase !important; line-height: 16px; font-family: 'Oswald' !important; } .pby{ font-family: 'Play', sans-serif; color: #995d08; font-size: 13px; } .clearfix::after{ content: ""; display: table; clear: both; } .twentyone{ display: block; width: 50%; } .newslt{ width: 130px; box-sizing: border-box; border: 2px solid #ccc; border-radius: 4px; font-size: 16px; background-color: white; background-image: url("images/email.png"); background-position: 10px 10px; background-repeat: no-repeat; padding: 12px 20px 12px 40px; -webkit-transition: width 0.4s ease-in-out; transition: width 0.4s ease-in-out; width: 100%; } .fltrgt{ float: right; } /* END SIDEBAR */ /* START PRODUSE RECOMANDATE BAR */ tr{ display: block; } td{ display: inline-block; } .items{ display: inline-block; text-align: center; width: 180px; margin: 0 7px 0 7px; padding-top: 10px; border: 1px solid #999; border-radius: 20px; } .items img{ width: 160px; height: 140px; border: 1px solid rgba(207, 207, 207, .7); } .items button{ background: #666; width: 80px; height: 26px; float: right; border-top: 1px solid #999; border-left: 1px solid #999; border-right: none; border-bottom: none; outline: none; cursor: pointer; border-bottom-right-radius: 20px; transition: background 0.2s ease-in; } .items button:hover{ background: #888; } .desc, .price, .other{ display: block; margin-bottom: 10px; } /* END PRODUSE RECOMANDATE BAR */ /* START FOOTER */ footer{ height: 40px; width: 60%; text-align: center; color: white; background-color: #2196F3; } .skills{ text-align: right; padding-right: 20px; line-height: 40px; color: white; } /* END FOOTER */ A: Have you considered using bootstrap to create your layout? It makes things like this really easy. Check it out here : http://getbootstrap.com/examples/grid/ You can use pull-right and pull-left within your columns to align your content and text-right and text-left for text. I believe pull-right and pull-left have been replaced with float-right and float-left in Bootstrap 4. Have fun experimenting with bootstrap! This site lets you play around with your layouts also http://www.bootply.com
{ "pile_set_name": "StackExchange" }
Q: List View inside a Scroll View I have to implement the screen below. It looks perfectly fine on a 480*800 pixel screen. On a low resolution screen because of the lack of screen size the Scrolling of the Results exposes very small real estate for the user to scroll thru the results. Which is the best way to implement it ? A: I always find trying to put something that scrolls into something else that scrolls is a nightmare so I would probably put the top of your view (results Bangalore to Mysore Date) inside the ListView header,that way it will scroll off the screen listView.addHeaderView(listViewHeader);
{ "pile_set_name": "StackExchange" }
Q: Adding new item to object array in Knockout I've got the following associative array that I made using Knockout.js. self.users = ko.observableArray([{name: "Unassigned", value: null}]); At some point in the application when a button is clicked I have to begin adding more values to this array. However, I'm not quite sure how to do that. Before, I was just using a generic array like so: $.each(data.users, function(index, user) { vm.users.push(user.first_name + " " + user.last_name); }); Now that I've got to deal with multiple values I'm not sure how to push both the item and the value to the array. Is there an easy way to do this? Update: Following Milimetric's suggestion I updated my code to the following: vm.users.push({name: user.first_name + " " + user.last_name, value: index + 1}); I then went back and updated my view to the following: <select id="ticket_assignee" name="ticket[assignee]" data-bind="options: users.name, value: assignee"></select> Prior to updating the view I was getting the correct number of items in the dropdown. After updating the view I just have a single value which says "d". My guess is that the d comes from the last letter in Unassigned. Did I do something wrong that caused the values to not display correctly? A: After talking to CrimsonChris in the chat he concluded than using an object array for what I'm trying to do is overkill. He pointed out that since I'm just trying to create a dropdown list of objects I could use Figure 3 from the Knockout "options" binding documentation as a guide for my current task. After following that example I was able to get everything to work perfectly by using the options, optionsText, and value bindings.
{ "pile_set_name": "StackExchange" }
Q: Spring Security/OAuth: mapping between Principal's authority and role in @RolesAllowed I'm playing around with Spring OAuth, implemented an authorization server and a resource server. The resource server uses user-info-uri to decode a token. Methods (some) in the resource server's controllers are protected by @RolesAllowed (also tried @PreAuthorize, same effect). @RolesAllowed("ROLE_USER") //@PreAuthorize("hasRole('ROLE_USER')") @RequestMapping(value = "/test-user", method = RequestMethod.GET) public String testUser() { return "You are User!"; } There are three users, managed on the authorization server side: user1 with ROLE_ADMIN, user2 and user3 with ROLE_USER. The resource service accepts the token, generated by the authorization server (password grant flow) and asks the user-info-uri about the principal details. So far works as designed. But what then happens, is what I do not understand. The principal structure (say, for user2, having ROLE_USER), contains a correct authority (for the example purpose I made a manual call to the user-info-uri): "principal": { "password": null, "username": "user2", "authorities": [ { "authority": "ROLE_USER" } ], "accountNonExpired": true, "accountNonLocked": true, "credentialsNonExpired": true, "enabled": true }, And it seems to be correctly deserialized at the resource server side: 2016-08-31 12:30:37.530 DEBUG 32992 --- [nio-9998-exec-1] o.s.s.a.i.a.MethodSecurityInterceptor : Secure object: ReflectiveMethodInvocation: public java.lang.String org.cftap.OAuthResourceController.testUser(); target is of class [org.cftap.OAuthResourceController]; Attributes: [ROLE_USER, ROLE_USER] 2016-08-31 12:30:37.530 DEBUG 32992 --- [nio-9998-exec-1] o.s.s.a.i.a.MethodSecurityInterceptor : Previously Authenticated: org.springframework.security.oauth2.provider.OAuth2Authentication@ed03ae2: Principal: user2; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=0:0:0:0:0:0:0:1, tokenType=BearertokenValue=<TOKEN>; Granted Authorities: {authority=ROLE_USER} 2016-08-31 12:30:37.530 DEBUG 32992 --- [nio-9998-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@4cf62e16, returned: 0 2016-08-31 12:30:37.530 DEBUG 32992 --- [nio-9998-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.access.annotation.Jsr250Voter@11e4338f, returned: -1 2016-08-31 12:30:37.530 DEBUG 32992 --- [nio-9998-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.access.vote.RoleVoter@3d5cb07f, returned: -1 2016-08-31 12:30:37.531 DEBUG 32992 --- [nio-9998-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.access.vote.AuthenticatedVoter@2724a21f, returned: 0 2016-08-31 12:30:37.536 DEBUG 32992 --- [nio-9998-exec-1] o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=Wed Aug 31 12:30:37 CEST 2016, principal=user2, type=AUTHORIZATION_FAILURE, data={type=org.springframework.security.access.AccessDeniedException, message=Access is denied}] 2016-08-31 12:30:37.546 DEBUG 32992 --- [nio-9998-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is not anonymous); delegating to AccessDeniedHandler But, as you see in the debug log, the RoleVoter (and JSR250 one) votes against it (although the allowed role and the authority of the principal fit together), hence sending 403 back. Did I miss something important? Thanks in advance. A: Try with @RolesAllowed("USER") instead of @RolesAllowed("ROLE_USER"). Eventually you could use hasAuthority("ROLE_USER") or hasRole("USER") instead of hasRole("ROLE_USER") . These are changes from Spring 4, you are probably using some old Spring 3 documentation / articles.
{ "pile_set_name": "StackExchange" }
Q: I'm getting an invalid syntax error in configparser.py I'm trying to get the pymysql module working with python3 on a Macintosh. Note that I am a beginning python user who decided to switch from ruby and am trying to build a simple (sigh) database project to drive my learning python. In a simple (I thought) test program, I am getting a syntax error in confiparser.py (which is used by the pymysql module) def __init__(self, defaults=None, dict_type=_default_dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=DEFAULTSECT, interpolation=_UNSET): According to Komodo, the error is on the second line. I assume it is related to the asterix but regardless, I don't know why there would be a problem like this with a standard Python module. Anyone seen this before? A: You're most certainly running the code with a 2.x interpreter. I wonder why it even tries to import 3.x libraries, perhaps the answer lies in your installation process - but that's a different question. Anyway, this (before any other imports) import sys print(sys.version) should show which Python version is actually run, as Komodo Edit may be choosing the wrong executable for whatever reason. Alternatively, leave out the parens and it simply fails if run with Python 3.
{ "pile_set_name": "StackExchange" }
Q: SQL server Rollback I created a transaction procedure and it all works except for some reason the rollback keeps displaying its error message and it is not allowing the insert to function properly. So now I am unsure of what I need to do to fix this when I comment out the section it all works perfectly it is only the IF rollback statement Create Proc DP_Transaction @PartNumber Varchar (10)= NULL, @PartDescription Varchar(50) = Null, @ReorderLevel Decimal(5,0) =Null, @StockLevel decimal(5,0)= null, @StockOnOrder decimal(5,0) =null as If @PartNumber IS NULL begin Print 'You must enter something for Partnumber' Print 'Order Not Processed' print ' ' return end If @PartDescription IS NULL begin Print 'You must enter something PartDescription' Print 'Order Not Processed' print ' ' return end If @ReorderLevel IS NULL begin Print 'A number must entered for ReorderLevel' Print 'Order Not Processed' print ' ' return end If @StockLevel is Null Begin print 'A number must be entered for StockLevel' print 'Order Not Processed' Print '' Return End If @StockOnOrder is null Begin Print 'A number must be entered for StockOnOrder' Print 'Order Not Processed' Print '' Return End Begin Transaction Insert into InventoryPart (Partnumber,PartDescription,ReorderLevel,StockLevel,StockOnOrder) Values(@PartNumber,@PartDescription,@ReorderLevel, @StockLevel, @StockOnOrder) //This is where I am having the errors If exists (Select PartNumber from InventoryPart where PartNumber = @PartNumber) Begin Print ' The Partnumber ' + @PartNumber+' is already in the InventoryPart table' print ' you must select a different PartNumber' Print ' Item not inserted' print '' Rollback end else begin Commit Transaction print 'Part has been added' print '' print '' End A: Your query will not add any parts to the table. When you are checking for the existence of a part inserted in the previous statement, it will always be true and so will always Rollback your transaction. There is no point in using a transactions in your example. You can simply do this using IF-ELSE. Transaction, in my opinion, should be used only when they are absolutely needed. Here you are simply trying to INSERT a part IF it does not exist in the table, ELSE you are displaying a message. IF EXISTS (Select 1 from InventoryPart where PartNumber = @PartNumber) BEGIN /*What you need to do*/ END ELSE BEGIN /*What you need to do*/ END
{ "pile_set_name": "StackExchange" }
Q: Backbone.js very simple validate model not working - following webtuts tutorial I am following this tutorials on tutsplus.com and it seems incredibly straightforward but when I run person.set('age', -27); it is NOT returning false and is instead setting the property to the negative value. I looked at the backbone documentation on validate as well as some posts online and it seems like it should work? I know I will not be getting back the return string quite yet. Here is my js which unless I keep missing something is exactly the same as the video: var Person = Backbone.Model.extend({ defaults: { name: 'John Doe', age: 30, occupation: 'worker' }, validate: function(attrs) { if ( attrs.age < 0 ) { return 'Age must be positive, stupid.'; } }, work: function() { return this.get('name') + ' is working.'; } }); A read a few places that said not to pass silent: true and I don't think I am...at least not explicitly in my code.. A: As pointed out by @xat and @mu is too short, the issue was an outdated video - even though a few of the earlier videos were updated to the latest version. The changelog for 9.10 states: Model validation is now only enforced by default in Model#save and no longer enforced by default upon construction or in Model#set, unless the {validate:true} option is passed. So I decided to pass validate:true and also tested with Model#save and each worked. Thanks guys!
{ "pile_set_name": "StackExchange" }
Q: Non-bootable Win 2003 Server--need to find ODBC settings I inherited a problem. I have a Windows 2003 machine that will not boot. I really just need to view the ODBC setttings from this drive (i.e. win 2003 boot drive). I was able to mount and access the drive from Win 7. My plan was to: 1. Launch regedit from Win 7 2. Use Load Hive to access registry on 2003 drive. 3. Find ODBC setting information. However, Win 7's regedit will not let me use load hive. It's disabled. How can I enable load hive? Will load hive allow me to access the win 2003's registry? Is there an easier way to vview the ODBC settings? Thanks! A: Follow instructions here. You can only load onto HKLM (local machine) in win7.
{ "pile_set_name": "StackExchange" }
Q: Restart the go application when the error I have an go application running 24 hours a day. Does anyone have an idea for a separate application that looks up whether the main application is running? If the main application has a bug, an additional application should close the main application and re-run the main application. Or maybe there is something in the style of the destructor, which could be the main application? A: In case of returned errors it's the task of your application to handle them correctly and restart the appropriate parts. It get's harder in case of panics. Here Go provides recover. It's like a catch of exceptions. In https://github.com/tideland/goas I provide loop, a package to run goroutines in a controlled way. Beside a traditional approach with the ability to stop a goroutine and/or retrieve an error value in case it died you can also start a goroutine with GoRecoverable. It provides a way to pass a function that's called in case of a panic and also knows about count and frequency. So it can act or decide if a goroutine shall continue work (e.g. by resetting/re-initializing those parts of your code that are covered by the failure).
{ "pile_set_name": "StackExchange" }
Q: Select Min value from different tables I have this 3 tables: Table_Group /*************************************************/ GROUP_ID | Value_1 | Value_2 | Value_3 | Group_1      | a             | b             | c            | Group_2      | d             | e             | f             | Table_series /*************************************************/ SERIE_ID | L    | W    | H    | Serie_1     | 1.5 | 2.0   | 2.2 | Serie_2     | 1.8 | 3.0   | 3.5 | Serie_3     | 1.1 | 2.5   | 3.7 | Serie_4     | 1.3 | 4.5   | 3.7 | Table_GroupSeries /*************************************************/ GROUP_ID |SERIE_ID Group_1      |Series_1 Group_1      |Series_2 Group_1      |Series_3 Group_2      |Series_4 And I would like to get this table: GROUP_ID |L_min|W_min|H_min Group_1      |1.1     |2.0         |2.2 Group_2      |1.3     |3.7         |4.5 This means, that I'm trying to get the minimum value of L,W and H for each Group. How could I do this? A: You can JOIN and GROUP BY: SELECT t1.GROUP_ID, MIN(L) AS L_min, MIN(W) AS W_min, MIN(H) AS H_min FROM Table_Group AS t1 JOIN Table_GroupSeries AS t2 ON t1.GROUP_ID = t2.GROUP_ID JOIN Table_series AS t3 ON t2.SERIE_ID = t3.SERIE_ID GROUP BY t1.GROUP_ID
{ "pile_set_name": "StackExchange" }