text
stringlengths
64
89.7k
meta
dict
Q: Suggestions on a good way to promote a free resource As a developer, I've learned a heck of a lot from the global community and I believe like any community, you need to participate and contribute. I've worked on several small projects that I want to offer up for free, but I want them to actually be used. For the sincerity of this post, I am not going to promote them here. What are some good ways to offer a free resource like a widget that does x,y, and z, for free. With an honest-to-god intent to just contribute? A: Assuming it's open source, add to freshmeat for example to help people find it. Write really good documentation, with examples etc. There's load of code out there which is lacking documentation making it pretty useless no matter how good the code is. Make it easy for people to report bugs, suggest features, etc.
{ "pile_set_name": "StackExchange" }
Q: php regex to match a single letter after digits I've got the following regex to see if $string contains digits followed by letters. However, I need it to check only that it contains 1 letter after the numeric value. Although the code below works, if $string was to be 28AB then it will also match the regex but it shouldn't, it should only match any numeric value followed by a single letter. $string = "28A"; $containsSpecial = preg_match('/[d\^a-zA-Z]/', $string); A: ^\d+[a-zA-Z]$ Try this.Your code uses [] which can match any character out of the list provided.Also use anchors to make a strict match and no partial matches.See here
{ "pile_set_name": "StackExchange" }
Q: Meteor (mrt) package loaded but "Model is not defined" error occured I installed the models package from Atmosphere via mrt. meteor add models says models: already using. when I insert a console.log statement in the model.js file located at this package it get executed and logged before the error occured. I2036-22:23:13.047(1)? MODEL LOADING <-- (my console.log) W2036-22:23:13.054(1)? (STDERR) /home/user/.meteor/tools/0b2f28e18b/lib/node_modules/fibers/future.js:173 W2036-22:23:13.054(1)? (STDERR) throw(ex); W2036-22:23:13.055(1)? (STDERR) ^ W2036-22:23:13.057(1)? (STDERR) ReferenceError: Model is not defined any idea why this happen? A: The package seems to be not updated to use with Meteor 0.6.5 and later. In that version the smart package API has changed, so older packages can no longer be used without a (simple) update. The package in question seem to be only an experiment, quote: This is a basic proof of concept of the way meteor models could work Are you sure you need it for your task? If so, you should clone that package and update the package.js file to use api.export method. Alternatively, if you just want to experiment, you can specify Meteor release in your project to be less than 0.6.5.
{ "pile_set_name": "StackExchange" }
Q: Angular DataTable bootstrap I am trying to implement a dataTable.net with bootstrap in a Angular app, but the style is a little bit of like in the image below. I am using the a pre-built one that I got the code from: https://datatables.net/examples/styling/bootstrap4 but even so the appearance is different. In angular.json I have this: "scripts": [ "node_modules/jquery/dist/jquery.js", "node_modules/datatables.net/js/jquery.dataTables.js", "node_modules/datatables.net-bs4/js/dataTables.bootstrap4.js", "node_modules/datatables.net-dt/js/dataTables.dataTables.js" ] And anlso trying to aply css to change the colors of the buttons. Picture problem link A: Solved it by doing this in the angular.json file Before: "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css", "src/assets/icons/fontawesome/css/all.css", "node_modules/datatables.net-dt/css/jquery.dataTables.css" ], "scripts": [ "node_modules/jquery/dist/jquery.js", "node_modules/datatables.net/js/jquery.dataTables.js", "node_modules/datatables.net-bs4/js/dataTables.bootstrap4.js", "node_modules/datatables.net-dt/js/dataTables.dataTables.js" ] After: "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css", "src/assets/icons/fontawesome/css/all.css", "node_modules/datatables.net-bs4/css/dataTables.bootstrap4.min.css" ], "scripts": [ "node_modules/jquery/dist/jquery.js", "node_modules/datatables.net/js/jquery.dataTables.js", "node_modules/datatables.net-bs4/js/dataTables.bootstrap4.min.js" ]
{ "pile_set_name": "StackExchange" }
Q: Unexpected strings "botbuilder-location:TitleSuffix" and "botbuilder-location:MultipleResultsFound" when using BotBuilder-Location I have tried using BotBuilder-Location to collect the user's location via the Bing Maps API. I have followed the instructions on BotBuilder-Location's GitHub repository and have managed to be able to display a map fron Bing Maps using the code from the example: var options = { prompt: "Where should I ship your order?", useNativeControl: true, reverseGeocode: true, requiredFields: locationDialog.LocationRequiredFields.streetAddress | locationDialog.LocationRequiredFields.locality | locationDialog.LocationRequiredFields.region | locationDialog.LocationRequiredFields.postalCode | locationDialog.LocationRequiredFields.country }; locationDialog.getLocation(session, options) However, in the prompt for the location the string "botbuilder-location:TitleSuffix" keeps showing, and the dialog does not continue after showing the map but instead displays the string "botbuilder-location:MultipleResultsFound" (Screenshot of unexpected strings). I have tried this in the Emulator as well as on Skype and Facebook Messenger with the same results. Does anybody know how to fix this? Thanks and best regards! A: This is known issue and it's reported here. There you will also find a workaround. The team behind the control is testing a potential fix.
{ "pile_set_name": "StackExchange" }
Q: converting array to object while considering keys of the same value I am trying to figure out an easy way to convert an array of objects to an object I have an array of objects that looks like this: [ { "id": "-LP9_kAbqnsQwXq0oGDT", "value": Object { "date": 1541482236000, "title": "First", }, }, .... more objects here ] And id like to convert it to an object with the timestamps as the keys, and arrays of objects corresponding to that date. If that key already exists, then add the object to the corresponding array associated with that key { 1541482236000: [{ "id": "-LP9_kAbqnsQwXq0oGDT", "value": Object { "date": 1541482236000, "title": "First", }, }, { "id": "-LP9_kAbqnsQwXqZZZZ", "value": Object { "date": 1541482236000, "title": "Some other title", }, }, .... more objects here ], 1541482236001: [{ "id": "-LP9_kAbqnsQ1234", "value": Object { "date": 1541482236001, "title": "Another title", }, }, .... more objects here ] } I was able to achieve something similar using reduce. However it does not handle adding objects to the array when their key already exists. calendarReminders = action.value.reduce((obj, reminder) => { dateKey = moment(reminder.value.date).format('YYYY-MM-DD') obj[dateKey] = [reminder] return obj; }, {}); How can I do this? A: You just need to check whether the object is already a key and if not add it with the value of an array. Then you can just push() into it: let arr = [{"id": "-LP9_kAbqnsQwXq0oGDT","value": {"date": 1541482236000,"title": "First",},},{"id": "SomID","value": {"date": 1541482236000,"title": "Some other title",},},{"id": "A different ID","value": {"date": 1541482236001,"title": "A third title",},}] let calendarReminders = arr.reduce((obj, reminder) => { (obj[reminder.value.date] || (obj[reminder.value.date] = [])).push(reminder) return obj; }, {}); console.log(calendarReminders) If you want to set the keys to a different format with moment, you should be able to do that without changing the basic idea.
{ "pile_set_name": "StackExchange" }
Q: Convert one liner private key to multi-line (original) I have to convert RSA private key to one-line to store in the password manager (Passwordstate). I used tr -d '\n' < id_rsa to convert to single line and cat id_rsa.line | sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&\n/" -e "s/\S\{64\}/&\n/g" to convert back to original multi-line. Conversion back to multi-line worked on Ubuntu, but not on Mac. Why this doesn't work on Macbook A: Please try: LF=$'\\\x0A' cat id_rsa.line | sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&${LF}/" -e "s/-----END RSA PRIVATE KEY-----/${LF}&${LF}/" | sed -e "s/[^[:blank:]]\{64\}/&${LF}/g" or LF=$'\\\x0A' cat id_rsa.line | sed -e "s/-----BEGIN RSA PRIVATE KEY-----/&${LF}/" -e "s/-----END RSA PRIVATE KEY-----/${LF}&${LF}/" | fold -w 64 Non-GNU sed does not interpret "\n" in the replacement as a newline. As a workaround, you can assign a variable to a newline and embed it in the replacement. Note that I've kept the UUC for readability :P.
{ "pile_set_name": "StackExchange" }
Q: what is the difference between doing a class as subclass by inheritance and composition what is the difference between doing a class as subclass by inheritance and composition A: Composition : the new class has the original class as an instance variable. The interface of the new class starts from the scratch. Only the properties and methods that the new class defines are available to the users of the class. The new class internally uses the old class object. Subclass : the new class has all the properties and methods it's superclass defines. Any users can use the properties and methods. If the new class does not override them, the superclass implementation is automatically called. The subclass may add new properties or methods. Usually subclassing is more helpful, but some cases composition can be helpful ( for example when working with class clusters).
{ "pile_set_name": "StackExchange" }
Q: Software RAID, LVM, and Encryption Setup Questions I have 4 hard drives, each with two partitions on them 10.1GB for swap and 990.1GB for the rest. I took this and set up two MD devices with RAID10, one for the set of 4 swap partitions and one for the set of 4 other partitions. I set the 20.2GB Software RAID device as my swap and moved on to LVM. This is as far as this guide takes me using software RAID. I would now like to set up LVM and encryption on it. I created a new volume and logical volume; size 1.5TB. I encrypted the volume and set the remaining 1.4TB within the encrypted volume as the root (f ext4 /). Here are my questions: Should I set up a separate Volume / Logical Volume for the 20.2GB Software RAID device being used as a swap area? Should I encrypt this volume as well if I'm encrypting the ext4 / area? Finish partitioning and write changes to disk gives an error of: You have selected the root file system to be stored on an encrypted partition. This feature requires a separate /boot partition on which the kernel and initrd can be stored. you should go back and setup a /boot partition. Where does this /boot partition need to be setup? (Should each drive have an extra partition for this before setting up RAID?) How much space does it need? Should it be part of LVM? Should it be encrypted? A: /boot needs to not be encrypted otherwise the boot loader (unless I'm behind the times and one of them supports encrypted volumes) will not be able to ready the Kernel and initrd. It does not need to be encrypted as it should never contain anything other than the kernel, the initrd, and perhaps a few other support files. The the device that is your LVM PV is encrypted, then /boot will need to be elsewhere: probably a separate RAID volume. If the device used as the PV is not encrypted (instead you encrypted the LV that is to be /) then /boot could be in the LVM except for the GRUB-can't-boot-off-all-RAID-types issue (see below). Historically /boot had to be near the start of the disk, but modern boot loaders generally remove this requirement. A few hundred Mb should be perfectly sufficient, but with such large drives being standard these days there will be no harm in making it bigger just in case unless you are constrained by trying to fit into a very small device (say, a small SD card in a Pi or similar) as might be the case for an embedded system. Most boot loaders do not support booting off RAID or if they do they only support booting off RAID1 (where every drive has a copy all the data) "by accident", so create the small partition on all the drives and use a RAID1 array over them. This way /boot is readable as long as at least one drive is in a working state. Make sure the boot loaded installs into the MBR of all four drives on install, otherwise if you BIOS boots off another (due to the first being offline for instance) you will have to mess around getting the loader's MBR onto the other drive(s) at that point rather than it already being there. Update: As per Nick's comment below, modern boot loaders can deal directly with some forms of encrypted volumes so depending on your target setup there are now less things to worry about.
{ "pile_set_name": "StackExchange" }
Q: Why is "could" used in “I am glad that you could make it?” Grammar books say don’t use could for past performance. For example, if I ran after a bus and caught it, I can’t say “I ran after a bus and could catch it.” Nevertheless, people say “I am glad that you could make it” to their guests. A: If you are talking directly about something that happened in the past, you just use simple past: I ran after a bus and caught it. If you describe the same event in a that-clause, you have the option of focusing on the ability to do something, rather than on the doing itself, for example: I was pleased that I could run fast enough to catch the bus. - ability I was pleased that I caught the bus. - completion Likewise, when you say I am glad that you could make it I am disappointed that I could not attend the funeral I am happy that I could help. you are focusing on the ability to do it, not actually doing it.
{ "pile_set_name": "StackExchange" }
Q: Pandas left outer join exclusion I have 2 pandas dataframes df1 = pd.DataFrame(data = {'col1' : ['finance', 'finance', 'finance', 'accounting', 'IT'], 'col2' : ['az', 'bh', '', '', '']}) df2 = pd.DataFrame(data = {'col1' : ['finance', 'finance', 'finance', 'finance', 'finance'], 'col2' : ['', 'az', '', '', '']}) df1 col1 col2 0 finance az 1 finance bh 2 finance 3 accounting 4 IT df2 col1 col2 0 finance 1 finance az 2 finance 3 finance 4 finance As you can see the dataframe has blank values as well. I tried using the example and its not giving me the result i want. common = df1.merge(df2,on=['col1','col2']) df3=df1[(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))] I want output something like col1 col2 3 accounting 4 IT A: Pandas left outer join exclusion can be achieved by setting pandas merge's indicator=True. Then filter by the indicator in _merge column. df=pd.merge(df1,df2[['col1']],on=['col1'],how="outer",indicator=True) df=df[df['_merge']=='left_only'] # this following line is just formating df = df.reset_index()[['col1', 'col2']] Output: col1 col2 0 accounting 1 IT ================================== ====The following is an example showing the mechanism==== df1 = pd.DataFrame({'key1': ['0', '1'], 'key2': [-1, -1], 'A': ['A0', 'A1'], }) df2 = pd.DataFrame({'key1': ['0', '1'], 'key2': [1, -1], 'B': ['B0', 'B1'] }) : df1 Output: A key1 key2 0 A0 0 -1 1 A1 1 -1 : df2 Output: B key1 key2 0 B0 0 1 1 B1 1 -1 : df=pd.merge(df1,df2,on=['key1','key2'],how="outer",indicator=True) : Output: A key1 key2 B _merge 0 A0 0 -1 NaN left_only 1 A1 1 -1 B1 both 2 NaN 0 1 B0 right_only :With the above indicators in the _merge column. you can select rows in one dataframe but not in another. df=df[df['_merge']=='left_only'] df Output: A key1 key2 B _merge 0 A0 0 -1 NaN left_only
{ "pile_set_name": "StackExchange" }
Q: Using a UIScrollView to change the alpha of an image My aim is to effectively use a UIScrollView as a UISlider. I've managed to code a UISlider to change the alpha of an image however I want to code a scrollview to change the alpha of an image when it is scrolled. I think I'm on the right lines by using the scroll views content offset to adjust alpha balances in the scroll view delegate but I just can't seem to get the code to work! Any suggestions on how I can get do this? Thanks A: Yes, you have right... use the scroll view offset to modify the alpha: For example: - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if(scrollView.contentOffset.y >= 0 && scrollView.contentOffset.y <= 150.0) { float percent = (scrollView.contentOffset.y / 150.0); self.imageView.alpha = percent; } else if (scrollView.contentOffset.y > 150.0){ self.imageView.alpha = 1; } else if (scrollView.contentOffset.y < 0) { // do other ... ; } } here you have an example: https://dl.dropboxusercontent.com/u/19438780/ScrollView_alpha.zip So... happy coding!
{ "pile_set_name": "StackExchange" }
Q: Functionnal way of writing huge when rlike statement I'm using regex to identify file type based on extension in DataFrame. import org.apache.spark.sql.{Column, DataFrame} val ignoreCase :String = "(?i)" val ignoreExtension :String = "(?:\\.[_\\d]+)*(?:|\\.bck|\\.old|\\.orig|\\.bz2|\\.gz|\\.7z|\\.z|\\.zip)*(?:\\.[_\\d]+)*$" val pictureFileName :String = "image" val pictureFileType :String = ignoreCase + "^.+(?:\\.gif|\\.ico|\\.jpeg|\\.jpg|\\.png|\\.svg|\\.tga|\\.tif|\\.tiff|\\.xmp)" + ignoreExtension val videoFileName :String = "video" val videoFileType :String = ignoreCase + "^.+(?:\\.mod|\\.mp4|\\.mkv|\\.avi|\\.mpg|\\.mpeg|\\.flv)" + ignoreExtension val otherFileName :String = "other" def pathToExtension(cl: Column): Column = { when(cl.rlike( pictureFileType ), pictureFileName ). when(cl.rlike( videoFileType ), videoFileName ). otherwise(otherFileName) } val df = List("file.jpg", "file.avi", "file.jpg", "file3.tIf", "file5.AVI.zip", "file4.mp4","afile" ).toDF("filename") val df2 = df.withColumn("filetype", pathToExtension( col( "filename" ) ) ) df2.show This is only a sample and I have 30 regex and type identified, thus the function pathToExtension() is really long because I have to put a new when statement for each type. I can't find a proper way to write this code the functional way with a list or map containing the regexp and the name like this : val typelist = List((pictureFileName,pictureFileType),(videoFileName,videoFileType)) foreach [need help for this part] All the code I've tried so far won't work properly. A: You can use foldLeft to traverse your list of when conditions and chain them as shown below: import org.apache.spark.sql.Column import org.apache.spark.sql.functions._ import spark.implicits._ val default = "other" def chainedWhen(c: Column, rList: List[(String, String)]): Column = rList.tail. foldLeft(when(c rlike rList.head._2, rList.head._1))( (acc, t) => acc.when(c rlike t._2, t._1) ).otherwise(default) Testing the method: val df = Seq( (1, "a.txt"), (2, "b.gif"), (3, "c.zip"), (4, "d.oth") ).toDF("id", "file_name") val rList = List(("text", ".*\\.txt"), ("gif", ".*\\.gif"), ("zip", ".*\\.zip")) df.withColumn("file_type", chainedWhen($"file_name", rList)).show // +---+---------+---------+ // | id|file_name|file_type| // +---+---------+---------+ // | 1| a.txt| text| // | 2| b.gif| gif| // | 3| c.zip| zip| // | 4| d.oth| other| // +---+---------+---------+
{ "pile_set_name": "StackExchange" }
Q: Golang Parameters conversion Can somebody explain how can this happened? I put interface as parameter in a function. While invoking this function I pass struct into it, but it didn't give me error. Here's the code package main import ( "fmt" "github.com/myusername/gomodel/domain" "github.com/myusername/gomodel/model" ) func main() { db := model.InitDB() newFunc(db) } func newFunc(db domain.IUser) { r, err := db.CreateUserTable() if err != nil { fmt.Println("error", err) } fmt.Println(r) } I've implemented the interface somewhere else in the code, because the program just work as the implemented interface expected to be. IUser is an interface whose member is: type IUser interface { CreateUserTable() (sql.Result, error) } InitDB is a function to open the database and return struct of database: type DB struct { *sql.DB } //InitDB initializes the database func InitDB() *DB { db, err := sql.Open(dbDriver, dbName) if err != nil { log.Fatal("failed to initialize database: ",err) } err2 := db.Ping() if err2 != nil { log.Fatal(err2) } return &DB{db} } My question is: how can a function with a parameter type interface be passed a different type of parameter? And how is this working under the hood? A: As per Golang Spec An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. This is because interface can be implemented as a wrapper to every type. Interface actually points to two things mainly one is the underlying type which is a struct here and other one is the value of that type which is a pointer to DB You see newFunc is actually taking interface{} as an argument, So you can pass anything to it of type T which can be of primitive types too. func main() { db := model.InitDB() newFunc(db) } So In case you want to get the underlying value you need to type assert. Interface works like a wrapper to the struct here and save its type and value which can be get using type assertion.
{ "pile_set_name": "StackExchange" }
Q: Possibilites for Sharkovskii's theorem. Hello I am interested in Sharkovskii's theorem with respect to two aspects: Possibilities of generalization for other spaces with some additional structures or dimensions. Applications in dynamical systems, other branches of mathematics and real life(!?) Some references are appreciated. A: Just quickly, it is not true in the circle. It has been shown in the context of unique beta expansions. See N. Sidorov et al paper Periodic unique beta-expansions: the Sharkovskiĭ ordering. Perhaps, it might hold on some one-dimensional spaces like finite graphs without circles or hereditarly indecomposable continua such as the pseudoarc. Seems difficult to hold for higher dimensional spaces in my opinion. As for applications a quick one is related to the structure of some limit spaces of tent maps. Check W. Ingram's work.
{ "pile_set_name": "StackExchange" }
Q: O que significa o "carica" na banda "Panda e Os Caricas" Meu priminho passou a ouvir um grupo português de música infantil chamado "Panda e Os Caricas", e ele me perguntou o que "carica" significa. Mas não faço ideia. Em Portugal há as "caricas" para aquilo que chamamos "tampinhas" (i.e., as tampas metálicas de garrafas e latinhas de refrigerantes). Mas qual seria a relação com o grupo infantil? Por aqui "tampinha" também é um sinônimo de "baixinho", se referindo a uma pessoa baixa e, mais estritamente, a um garoto ou criança. Há inclusive uma revista em quadrinhos chamada "Os Tampinhas". O "carica" no nome do grupo teria esse mesmo sentido? A: Gente, é só olhar na obra maestra: Priberam Eu sempre dou uma olhada no Priberam: ca·ri·ca (origem obscura) substantivo feminino 1. Tampa circular, metálica e sem rosca, que veda garrafas de refrigerante ou de cerveja (ex.: a pressão é mantida pela carica da garrafa). (Equivalente no português do Brasil: chapinha.)Ver imagem [Jogos] Jogo infantil em que se usam essas tampas (ex.: jogar à carica) carica Tudo bem explicadinho. Tudo bonitinho. As músicas são ótimas. :)
{ "pile_set_name": "StackExchange" }
Q: ObjectMapper ignoring configuration when annotations are present My project is using application.properties file to set the property as following: spring.jackson.deserialization.fail-on-unknown-properties=true, which works in all cases but one: class Model { @JsonUnwrapped public SubModel subModel; } simply commenting out the annotation causes ObjectMapper to fail as intended, but as soon as the annotation is added, the option set seems to be ignored. How can I configure jackson to use annotations along with the config? A: Due to logic needed to pass down unwrapped properties from parent context, there is no way to efficiently verify which properties might be legitimately mapped to child POJOs (ones being unwrapped), and which not. As of now it is not possible to make jackson to fail on unknown property with unwrapping. Issue is still open , https://github.com/FasterXML/jackson-databind/issues/650 How can I configure jackson to use annotations along with the config? It is nothing to do with config or annotations, they are working fine.
{ "pile_set_name": "StackExchange" }
Q: Not Found (#404) Unable to resolve the request "gii/" in Yii2 I am using the alpha version of Yii 2.I can acess the GII module via frontend but not via backend. The url '/advanced/backend/web/index.php?r=gii/' gives me 404 error. Any fix for the issue? A: Found out. I need to add this to the backend config file manually. 'modules' => [ 'gii' => 'yii\gii\Module', ],
{ "pile_set_name": "StackExchange" }
Q: array_shift and print_r behaving wierd in PHP I wanted to test array_shift on a simple example: $a = ['a', 'b', 'c', 'd']; $rem = array_shift($a); print_r($rem); Which only returns me: a, instead of an array of: ['b', 'c', 'd']. php.net docs on array_shift state the following: array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be affected. This function is supposed to remove the first element and return all the rest with re-ordered keys. Now, I copied the example from the docs site as is (tried with both [] and array()): $stack = ["orange", "banana", "apple", "raspberry"]; $fruit = array_shift($stack); print_r($stack); Now this returns as expected: Array ( [0] => banana [1] => apple [2] => raspberry ) I don't understand what just happend here or what I did wrong. My example only differs in variable names and elements in the array. And I hardly don't believe the issue would be because of my usage of single-quotes '. Also, here is a demo on Sandbox. A: array_shift() is a stand-alone function - you don't need to assign it to a value, it automatically unsets it from the given variable: <?php $a = ['a', 'b', 'c', 'd']; array_shift($a); print_r($a); https://3v4l.org/GEr3g
{ "pile_set_name": "StackExchange" }
Q: Is it appropriate to move extra info from my answer to a blog post? I have a answer to this question on Stack Overflow that has generated some good attention, but has grown rather large as I continue to update it and make modifications based on comments. The post currently has 7,763 characters. it is larger than 99% of all other answers on stack overflow, according to this query I made in the Data Explorer: This seems too large to quickly convey the most important information, I have to say that my answers tend to involve a lot of hand holding as I'm often going through that process myself while answering them. They explain exactly what each and every bit of code does. This seems like unnecessary noise for someone who is comfortable enough with the framework/language that they could jump right to the answer. According to How to refer to your blog when answering?, it's okay to mention your own blog so long as it's not done excessively, you've disclosed your affiliation, and the answer is good enough on it's own right. I'd like to trim down the post by just presenting the solution and leaving a lot of the walkthrough to an external resource for people who are interested in being taken through that level of depth. It seems okay to link to an existing blog post when answering, but is it okay to take content originally created (by me) on this site and remove it by placing it on my personal coding blog? A: This seems ideal, but there are dangers. It stops the answer getting too long, keeps the essential parts of the answer on the site and uses the blog post as more information/reference. Rather than remove content I'd add the link at the stage where the answer is getting "too long" (which will vary from answer to answer). The only drawback is that, as you have identified, some people might see it as spam. However, if you only do it once or twice then it should be obvious to people that you're not spamming the site. The other thing going in your favour is that you are editing an old answer to add the link rather than just adding the link to all your answers, so the answer is already complete. Spammers don't tend to include an actual answer along with their link - it's extra work they don't like to do.
{ "pile_set_name": "StackExchange" }
Q: Zsh - Delete current/previous argument entirely I'm using zsh with Macos. Currently, ctrl+w deletes a 'word' but stops at non-word characters. It's kinda odd though because it'll often delete far more than it should or stop at odd places: Examples: open -n https://www.google.com // deletes [com][google.][www.][https://(why so much?)] open -n 'https://www.google.com' // deletes [com'][google.][www.][https://][n '(wtf?)][open -] I just want to delete the current string backwards until a space character, effectively deleting an argument. I've looked online at various bash/zsh hotkeys you can add to .bashrc, but none seem to do what I'm looking for. A: Update: The select-word-style function[0] is available as an easy way to customize the word style: $ select-word-style Usage: select-word-style word-style where word-style is one of the characters in parentheses: (b)ash: Word characters are alphanumerics only (n)ormal: Word characters are alphanumerics plus $WORDCHARS (s)hell: Words are command arguments using shell syntax (w)hitespace: Words are whitespace-delimited (d)efault: Use default, no special handling (usually same as `n') (q)uit: Quit without setting a new style To only stop at argument boundaries, autoload -Uz select-word-style select-word-style shell should suffice. [0] https://github.com/zsh-users/zsh/blob/master/Functions/Zle/select-word-style The original answer below assumes the normal style. ^W is bound to backward-kill-word by default in ZLE[1]. What it considers as word is controlled by WORDCHARS[2]. WORDCHARS <S> A list of non-alphanumeric characters considered part of a word by the line editor. In order to recognize https://www.google.com as a word, you at the very least need WORDCHARS+=':/.' Add this to your ~/.zshrc, and add whatever non-alphanumeric characters you would like to be treated as word chars (all of them if you always want to kill the last argument). [1] http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html [2] http://zsh.sourceforge.net/Doc/Release/Parameters.html#index-WORDCHARS A: I personaly configure zsh to use vim style editing, and then, I add some keybindings similar to emacs style. Examples: <ctrl+w>: delete word backward <escape><d><T><space>: delete back until space (like vim). This might be what you want. My ~/.zshrc: ## editing mode e=emacs v=vim export KEYTIMEOUT=1 bindkey -v ## more keys for easier editing bindkey "^a" beginning-of-line bindkey "^e" end-of-line bindkey "^f" history-incremental-search-forward bindkey "^g" send-break bindkey "^h" backward-delete-char bindkey "^n" down-history bindkey "^p" up-history bindkey "^r" history-incremental-search-backward bindkey "^u" redo bindkey "^w" backward-kill-word bindkey "^?" backward-delete-char My logic, take the good of both vim and emacs styles: The style of <ctrl+a> <ctrl+e> <ctrl-w> ... is so convenient. I've been using it for decades so I keep it. No changes in WORDCHARS or something. However, when I need some more advance editing, then I use vim style, which is better. As for arrows and <home> <end> ... keys: ## create a zkbd compatible hash; ## to add other keys to this hash, see: man 5 terminfo typeset -A key key[Home]=${terminfo[khome]} key[End]=${terminfo[kend]} key[Insert]=${terminfo[kich1]} key[Delete]=${terminfo[kdch1]} key[Up]=${terminfo[kcuu1]} key[Down]=${terminfo[kcud1]} key[Left]=${terminfo[kcub1]} key[Right]=${terminfo[kcuf1]} key[PageUp]=${terminfo[kpp]} key[PageDown]=${terminfo[knp]} ## setup keys accordingly [[ -n "${key[Home]}" ]] && bindkey "${key[Home]}" beginning-of-line [[ -n "${key[End]}" ]] && bindkey "${key[End]}" end-of-line [[ -n "${key[Insert]}" ]] && bindkey "${key[Insert]}" overwrite-mode [[ -n "${key[Delete]}" ]] && bindkey "${key[Delete]}" delete-char [[ -n "${key[Up]}" ]] && bindkey "${key[Up]}" up-line-or-history [[ -n "${key[Down]}" ]] && bindkey "${key[Down]}" down-line-or-history [[ -n "${key[Left]}" ]] && bindkey "${key[Left]}" backward-char [[ -n "${key[Right]}" ]] && bindkey "${key[Right]}" forward-char [[ -n "${key[PageUp]}" ]] && bindkey "${key[PageUp]}" history-beginning-search-backward [[ -n "${key[PageDown]}" ]] && bindkey "${key[PageDown]}" history-beginning-search-forward [[ -n "${key[Home]}" ]] && bindkey -M vicmd "${key[Home]}" beginning-of-line [[ -n "${key[End]}" ]] && bindkey -M vicmd "${key[End]}" end-of-line [[ -n "${key[Insert]}" ]] && bindkey -M vicmd "${key[Insert]}" overwrite-mode [[ -n "${key[Delete]}" ]] && bindkey -M vicmd "${key[Delete]}" delete-char
{ "pile_set_name": "StackExchange" }
Q: Connect to Rest API in R with key this is a simple question, but one that I still can't figure out. I want to connect to a REST API with my API key. I've looked through the documentation on httr, jsonlite and others and still can't figure out how to set the API key. This is the endpoint - https://api.tiingo.com/tiingo/daily//prices?startDate=2012-1-1&endDate=2016-1-1? I've tried using the GET function on this URL and specify my API key as key in the call. I've also tried api_key = key. I always get a 401 error back. Thanks A: The API is expecting a Authorization header with Token yOuRAsSiGnEdT0k3n in it. You should store the token in something like an environment variable so it's not stuck in scripts. I used TIINGO_TOKEN and put it into ~/.Renviron. You can make a helper function to make the calls less mudane: library(httr) library(jsonlite) library(tidyverse) library(hrbrthemes) get_prices <- function(ticker, start_date, end_date, token=Sys.getenv("TIINGO_TOKEN")) { GET( url = sprintf("https://api.tiingo.com/tiingo/daily/%s/prices", ticker), query = list( startDate = start_date, endDate = end_date ), content_type_json(), add_headers(`Authorization` = sprintf("Token %s", token)) ) -> res stop_for_status(res) content(res, as="text", encoding="UTF-8") %>% fromJSON(flatten=TRUE) %>% as_tibble() %>% readr::type_convert() } Now, you can just pass in parameters: xdf <- get_prices("googl", "2012-1-1", "2016-1-1") glimpse(xdf) ## Observations: 1,006 ## Variables: 13 ## $ date <dttm> 2012-01-03, 2012-01-04, 2012-01-05, 2012-01-06, 2... ## $ close <dbl> 665.41, 668.28, 659.01, 650.02, 622.46, 623.14, 62... ## $ high <dbl> 668.15, 670.25, 663.97, 660.00, 647.00, 633.80, 62... ## $ low <dbl> 652.3700, 660.6200, 656.2300, 649.7900, 621.2300, ... ## $ open <dbl> 652.94, 665.03, 662.13, 659.15, 646.50, 629.75, 62... ## $ volume <int> 7345600, 5722200, 6559200, 5380400, 11633500, 8782... ## $ adjClose <dbl> 333.7352, 335.1747, 330.5253, 326.0164, 312.1937, ... ## $ adjHigh <dbl> 335.1095, 336.1627, 333.0130, 331.0218, 324.5017, ... ## $ adjLow <dbl> 327.1950, 331.3328, 329.1310, 325.9010, 311.5768, ... ## $ adjOpen <dbl> 327.4809, 333.5446, 332.0901, 330.5955, 324.2509, ... ## $ adjVolume <int> 3676476, 2863963, 3282882, 2692892, 5822572, 43955... ## $ divCash <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,... ## $ splitFactor <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,... And, it "just works": ggplot(xdf, aes(date, close)) + geom_segment(aes(xend=date, yend=0), size=0.25) + scale_y_comma() + theme_ipsum_rc(grid="Y") You can follow this idiom for the other API endpoints. When done, consider making a package out of it so the community can use what the knowledge you gained. You can go some extra steps and actually make functions that take date or numeric parameters to actually take those type of R objects and validate them on input, too.
{ "pile_set_name": "StackExchange" }
Q: SonataAdminBundle can't see logout in top right all works fine but i can't see logout icon and + icon in top right i followed all step in sonata-project officiel site but i don't know what is happen really. in the officiel site i see in demo in the last step logout but in my project i can't i use symfony 2.8.0 this my config.yml imports: - { resource: parameters.yml } - { resource: security.yml } - { resource: services.yml } - { resource: "@AppBundle/Resources/config/admin.yml" } parameters: locale: en framework: #esi: ~ translator: { fallbacks: ["%locale%"] } secret: "%secret%" router: resource: "%kernel.root_dir%/config/routing.yml" strict_requirements: ~ form: ~ csrf_protection: ~ validation: { enable_annotations: true } #serializer: { enable_annotations: true } templating: engines: ['twig'] #assets_version: SomeVersionScheme default_locale: "%locale%" trusted_hosts: ~ trusted_proxies: ~ session: # handler_id set to null will use default session handler from php.ini handler_id: ~ fragments: ~ http_method_override: true # Twig Configuration twig: debug: "%kernel.debug%" strict_variables: "%kernel.debug%" # Doctrine Configuration doctrine: dbal: driver: pdo_mysql host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%database_password%" charset: UTF8 orm: auto_generate_proxy_classes: "%kernel.debug%" naming_strategy: doctrine.orm.naming_strategy.underscore auto_mapping: true # Swiftmailer Configuration swiftmailer: transport: "%mailer_transport%" host: "%mailer_host%" username: "%mailer_user%" password: "%mailer_password%" spool: { type: memory } # app/config/config.yml sonata_block: default_contexts: [cms] blocks: # enable the SonataAdminBundle block sonata.admin.block.admin_list: contexts: [admin] A: I think that this behaviour is handled by SonataUserBundle, you must to install this, if you see in the Sonata User introduction you can see that this bundle enable the user profile, and I think that this user icon. Sonata User Bundle
{ "pile_set_name": "StackExchange" }
Q: Difference between ActionBarSherlock and ActionBar Compatibility What is the difference between ActionBarSherlock and Action Bar Compatibility Fews days ago Google just released the ActionBar Compatibility that make me so confused. Is that the Action Bar Compatibility works same as the ActionBarSherlock and is the coding same? Example : Does app icon to navigate "up" or ActionBar.Tab supported in Action Bar Compatibility ? A: ActionBarSherlock vs ActionBarCompat: I Just want to put few code difference between ActionBarSherlock vs ActionBarCompat Lib We can migrate some apps from ActionBarSherlock to ActionBarCompat: steps: Import AppCompat project. Replace SherlockFragmentActivity with ActionBarActivity. Replace SherlockFragment with Fragment. Change Menu, MenuItem and getSupportMenuInflater() references. Modify the way you get Action Views. mSearchView = (SearchView)MenuItemCompat.getActionView(mSearchItem) Modify your Themes and Styles. For more info, please refer this slides by +NickButcher (Google) Thanks to Sources: http://gmariotti.blogspot.in/2013/07/actionbarsherlock-vs-actionbarcompat.html http://antonioleiva.com/actionbarcompat-migrating-actionbarsherlock/ Don't forget to read this developer.android for more about ABC! Note: Setting it up for unit tests the same way as ABS is unfortunately not possible with the support library. Output: Credits: Gabriele Mariotti A: ActionBarSherlock gives your application an action bar regardless* of what version of the android API your app is being run on. Action Bar Compatibility gives you the action bar only if the device that you're running on is API level 3.0 or above. *Note that if the device you're running on isn't 3.0 or above, ActionBarSherlock is going to use it's own custom implementation of the action bar, not a native one. --EDIT-- It appears things have changed and there is actually no difference between ActionBarSherlock and the Action Bar Compatibility anymore. Please read the comments below for details. --EDIT-- After having used both now, I can say that I actually prefer ActionBarSherlock to Action Bar Compatibility. ActionBarSherlock is really easy and nice to use. --EDIT-- As LOG_TAG mentioned, there is now support for the action bar in the Android Support Library. I haven't had a chance to use it yet, but I would imagine that's the best one to use. A: Just completing what @Kurtis Nusbaum with a pratical example. UPDATE: as @rudy-s said, with newest android support library (api 18), I saw they already have built-in support for actionbar (called ActionBarCompat class). I built two simple applications to show the visual difference between ActionBarSherlock and ActionBar Compatibility. See the comparatives images: Now the appearance when the menu button is pressed: As you can see, the images just enforce what was said. Action Bar Compatibility gives you the action bar only if the device that you're running on is API level 3.0 or above. While Sherlock is more general. Below you can see the application source. The menu xml file is the same: <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_1" android:orderInCategory="100" android:showAsAction="always" android:title="@string/action1"/> <item android:id="@+id/action_2" android:orderInCategory="100" android:showAsAction="ifRoom" android:title="@string/action2"/> <item android:id="@+id/action_3" android:orderInCategory="100" android:showAsAction="ifRoom" android:title="@string/action3"/> <item android:id="@+id/action_settings" android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_settings"/> </menu> Compatibility's activity: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } } Sherlock's activity: public class MainActivity extends SherlockActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) { getSupportMenuInflater().inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } } An additional config was necessary on sherlock app: <style name="AppBaseTheme" parent="Theme.Sherlock.Light.DarkActionBar"> UPDATE: as @rudy-s said, with newest android support library (api 18), I saw they already have built-in support for actionbar (called ActionBarCompat class).
{ "pile_set_name": "StackExchange" }
Q: Naming the nodes of a Tree Structure I am implementing a tree based on this answer. According to the given simple usage example, the new nodes are named after the position whey will have in the tree, so they are variables. For example: TreeNode<String> node0 = root.addChild("node0"); where node0 is a new TreeNode and the data the new child will have. According to this and this I can not use a string for naming a variable. I intend to have 26 children for each node my tree has. My question is simple, do I have to create the tree by creating by hand all the 26 possible nodes my tree will have, like below? TreeNode<String> node0 = root.addChild("node0"); TreeNode<String> node1 = root.addChild("node1"); TreeNode<String> node2 = root.addChild("node2"); ... TreeNode<String> node25 = root.addChild("node25"); { TreeNode<String> node00 = node0.addChild("node00"); ... { //the above code for all the nodes of the tree } } or am I missing a better solution? Thank you A: First of all, I would store the "name" of every node in a member variable and define a getter for it. I would also add a method to get the number of children the node already has. If you do that, you will name your nodes automatically when you instantiate them. In the class definition, add: public class TreeNode<T> implements Iterable<TreeNode<T>> { T data; TreeNode<T> parent; List<TreeNode<T>> children; ... // A string containing the node name, (e.g. "210") String name; // A name getter method public String getName() { return this.name; } // A method to get the number of children that the node has public int getNumChildren() { return this.children.size(); } } Now, you can name the nodes automatically in the constructor: public TreeNode<T>(T data, TreeNode<T> parent) { ... this.parent = parent; int numParentChildren = parent.getNumChildren(); this.name = parent.getName() + numParentChildren; } Regarding your question about Tree creation, it would be better to encapsulate it in a method: public LinkedList<TreeNode<T>> createTree() { //Root TreeNode TreeNode<T> root = new TreeNode<T>(data, null); //TreeNode on which we currently operate TreeNode<T> current; //List of treenodes holding the result List<TreeNode<T>> treeList = new LinkedList<TreeNode<T>>(); //Queue holding the nodes for which we will create 26 children elements Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>(); treeList.add(root); queue.add(root); for (int i=0; i< (some number); i++) { current = queue.remove(); child = new TreeNode<T>>(data, current); current.addChild(child); queue.add(child); treelist.add(child); } return treeList; } I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Запятая перед "и не зря" Нужна ли запятая в предложении? Я выучил все правила(,) и не зря. A: Да, запятая нужна. Это присоединительный оборот.
{ "pile_set_name": "StackExchange" }
Q: What's the difference between the SharedAccessBlobPermissions values Add, Create and Write? The possible values for SharedAccessBlobPermissions are: None (0) Read (1) Write (2) Delete (4) List (8) Add (16) Create (32) What are the differences between Add, Create and Write? I can't find any documentation that clarifies this. A: You can find information about these permissions here: https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx. From what I understand reading about these permissions: Add: Add permission is only applicable for append blobs. You use this permission to add a block to an append blob. No other operation is possible using this permission. Create: Create permission only allows creation of blobs or in other words you can't update a blob with this permission. This would include writing a new blob, take a snapshot of an existing blob, or copy a blob to a new blob. Write: Write permission allows creation and updation of blobs. This would include create or write content, properties, metadata, or block list, take a snapshot or manage lease on a blob and resize the blob (page blob only). In our application, we use Shared Access Signature extensively and we make use of Write permission almost exclusively on all the blob related operations.
{ "pile_set_name": "StackExchange" }
Q: How would it be possible to distribute a GPL program with an Apache program? A friend and I are making a program licensed under the Apache 2.0 license, and we would like to pull in code from one of his old projects licensed under the GPL 3.0 license, but I don't see a way to. Is this possible? A: If you and your friend are building upon an old project, and the original project completely belongs to you, then there's no issue. Since you own the project, you own the entire intellectual property, and you are free to license it as you wish. However, the issue comes in when there is code from other contributors, or when there are incompatible licensed dependencies in the code: If code is from other contributors: You'll have to ask them to relicense their contributions under a license such as the Apache license. If they refuse, you'll either have to remove their contributions, or you'll have to rewrite the code yourself. If there is incompatible licensed dependencies: For example, if your project relies on an external library such as the GPL, you'll have to respect the terms and conditions of that license, likewise with any other license. If the original project has a dependency with the GPL as its license, then you've got to either remove that dependency, or respect the terms by making your new project under the GPL as well due to its copyleft clause. If you don't have those two issues, then you're free to go!
{ "pile_set_name": "StackExchange" }
Q: Divide an integer by 100 and get value till two decimal points? I have String amount in a TextBox, which I want to divide by 100. The value should round off to two decimal places. I tried and I am not getting a proper value. Here is what I tried: 6766/100 = 67.66 47/100 = .47 98/100 = .98 A: Use Math.Round. This example should get you going string txtText = "78907"; double inputValue; if (double.TryParse(txtText, out inputValue)) double result = Math.Round(inputValue / 100, 2); Output: 789.07 A: Use Math.Round. It has a parameter called precision. Example: Math.Round(1.23456, 2) -> 1.23 A: Use Math.Round, but one of both need to be a decimal type to avoid integer division: double result = Math.Round(6766d / 100, 2);
{ "pile_set_name": "StackExchange" }
Q: How to use .rvmrc or .ruby-version / .ruby-gemset w/ new terminal window that's ALREADY in project dir? Quick question for you guys: According to the RVM docs, using an .rvmrc or .ruby-version / .ruby-gemset files... This will be set when entering project directory My question is, in OSX, you have the ability to Cmd-T to open a new Terminal tab, and when doing that, the directory is already set to the previous directory (which, in my case, is the project dir). When doing this, I'm not changing into the project directory (thus triggering rvm to use the project settings), I'm alredy in the project dir, so RVM is picking up the global defaults, which is different. So I've found myself having to cd ~ then cd project in order to go out then back into the directory and get rvm to play nice. Any way to skip that? Seems like an extra step and somtimes I forgot to do it when quickly opening up terminals, and thus am working with the wrong ruby version and gemset. A: try again after: rvm get stable I was just fixing similar problem in RVM 1.25.15 ... although if you use system installation of rvm this is not fixable.
{ "pile_set_name": "StackExchange" }
Q: Qt Thread Optimization I've tryed to profile one of my application using Qt. The results I found seemed to show that Qt is a big Thread user. It seems to create and destroy threads a lot. Which is the peak of its memory consumption. Is it true ? So I've tryed to do some research on "how to optimize a Qt application" but, well I hadn't found anything relevant for now. So I was wondering if there is any "general way" of programming with Qt that could be optimized. Shall I use the threads in a specific manner ? Can I do anything except respecting C++ standards, -pedantic options in compiler, and so one ? A: Generally speaking, if you create and destroy threads a lot, then that's probably not a very good design. Assuming your threads do the same (or similar) things, then having a fixed "pool" of threads that run for as long as it takes and then get put back in the pool when your current code destroys the thread. Or, let the thread run forever, and feed it data through some suitable IPC. I would also say that unless you are doing something very special, if something takes less than about a quarter of a second to do, then you shouldn't create a thread to do that. That's not a fixed rule. Threads as such don't use that much memory, but the stack of each thread may use quite a bit of memory.
{ "pile_set_name": "StackExchange" }
Q: Large scale application in Angular2 I'm currently planning to develop a large scale app using angular2 my problem is now the architecture, I have tested some Seeds : Github seed Project https://github.com/mgechev/angular2-seed but they aren't good for my large scale app because you pack anything together in on big file(OK minified but still all). An other point is the necessary es6 shims which are to big. is there a good technique to load the necessary components/modules only if the page needs them and only load the es6 shims if the browser (IE) needs them? Example : Example Project includes only code for blue socks I don't want to know the e.g css stuff for red sock. every site should only be like 1Mb doesn't matter if my whole app is big like 1GB A: I think that is what you are looking for: http://blog.mgechev.com/2015/09/30/lazy-loading-components-routes-services-router-angular-2
{ "pile_set_name": "StackExchange" }
Q: Compare 4 columns in two files; and output the line for unique combination (from first file) and line for duplicate combination (from second file) I have two tab separated values file, say File1.txt chr1 894573 rs13303010 GG chr2 18674 rs10195681 **CC** chr3 104972 rs990284 AA <--- Unique Line chr4 111487 rs17802159 AA chr5 200868 rs4956994 **GG** chr5 303686 rs6896163 AA <--- Unique Line chrX 331033 rs4606239 TT chrY 2893277 i4000106 **GG** chrY 2897433 rs9786543 GG chrM 57 i3002191 **TT** File2.txt chr1 894573 rs13303010 GG chr2 18674 rs10195681 AT chr4 111487 rs17802159 AA chr5 200868 rs4956994 CC chrX 331033 rs4606239 TT chrY 2893277 i4000106 GA chrY 2897433 rs9786543 GG chrM 57 i3002191 TA Desired Output: Output.txt chr1 894573 rs13303010 GG chr2 18674 rs10195681 AT chr3 104972 rs990284 AA <--Unique Line from File1.txt chr4 111487 rs17802159 AA chr5 200868 rs4956994 CC chr5 303686 rs6896163 AA <--Unique Line from File1.txt chrX 331033 rs4606239 TT chrY 2893277 i4000106 GA chrY 2897433 rs9786543 GG chrM 57 i3002191 TA File1.txt has total 10 entries while File2.txt has 8 entries. I want to compare the both the file using Column 1 and Column 2. If both the file's first two column values are same, it should print the corresponding line to Output.txt from File2.txt. When File1.txt has unique combination (Column1:column2, which is not present in File2.txt) it should print the corresponding line from File1.txt to the Output.txt. I tried various awk and perl combination available at website, but couldn't get correct answer. Any suggestion will be helpful. Thanks, Amit A: next time, show your awk code tryso we can help on error or missing object awk 'NR==FNR || (NR>=FNR&&($1","$2 in k)){k[$1,$2]=$0}END{for(K in k)print k[K]}' file1 file2
{ "pile_set_name": "StackExchange" }
Q: HTML/CSS: Button aligning bottom when no text? I have a strange problem with buttons that are next to an input field, it seems to be stuck to bottom, and I can't find why or how to modify it. My intention is to put a background image only. In order to identify the button for this question I've added string Text to one button and saw that this problem disappeared. Problem is that I don't want any description there, IE 8 shows it fine (surprisingly). I'm working on Firefox last version. I appreciate any help. http://jsfiddle.net/bmGb5/ Screenshot: http://www.imgx.gxzone.com/images/a/9/a971c01a223.jpg Thanks a lot. A: Try specifying a vertical-align style on the button. bottom will probably work best.
{ "pile_set_name": "StackExchange" }
Q: Google Maps closing infoWindow doesn't work i tried to built up a little Google Maps api in PHP which fetches Circles and Infowindows from a Database. Anything works besides closing an InfoWindow after opening it. The Chrome Developer console throws out the following errors: GET http://maps.googleapis.com/maps/api/js/StaticMapService.GetMapImage?1m2&1i151368577549307460&2i99567197161272770&2e2&3u50&4m2&1u512&2u496&5m3&1e2&2b1&5sde-DE&token=119415 404 (Not Found) main.js:33 <- Onload And on clicking on the Red popup it shows the following error: Uncaught TypeError: Object # has no method 'O' Tried to figure out a solution for hours now, hope you can help me! Thank you! <script type='text/javascript'> var _infoWindow = new Array();var _marker = new Array(); function initialize() { var mapOptions = { zoom: 50, center: new google.maps.LatLng(48.52039, 9.05949), mapTypeId: google.maps.MapTypeId.SATELLITE }; var map = new google.maps.Map(document.getElementById('map'), mapOptions); var circles = [{"color":"fff","center":new google.maps.LatLng(48.5204, 9.05949),"radius":200}]; for(var circle in circles) { new google.maps.Circle({ strokeColor: circles[circle].color, strokeOpacity: 1, strokeWeight: 2, fillColor: circles[circle].color, fillOpacity: 0.35, map: map, center: circles[circle].center, radius: circles[circle].radius }); } var infoWindows = [{"center":new google.maps.LatLng(48.5204, 9.05949),"content":"<h2>Juhu!<\/h2>Html<br>Content <b>erlaubt<\/b>!"}]; var i = 0; for(var infoWindow in infoWindows) { _infoWindow[i] = new google.maps.InfoWindow({ content: infoWindows[infoWindow].content }); _marker[i] = new google.maps.Marker({ position: infoWindows[infoWindow].center, map: map, title:'Test' }); google.maps.event.addListener(_marker[i], 'click', new Function('_infoWindow['+i+'].open(map,_marker['+i+']);')); i++; } } window.onload = function(){ initialize(); } </script> </head> <body> <div id='map' style='height:500px;width:500px;'></div> </body> A: You are defining the map-variable inside a local scope(initialize), it will not be accessible inside the click-handler. Add this to the top of the scripts: var map; And remove the var-keyword from this line: var map = new google.maps.Map(document.getElementById('map'), mapOptions);
{ "pile_set_name": "StackExchange" }
Q: Convert a multidimensional array to JSON with node.js I'm getting a BIG multidimensional array after combining few simple arrays, now I need to convert it in a JSON string right before sending it to Mongodb. Here is the array structure: [ '0', [ [ 'id', 1 ], [ 'country', 0 ], [ 'people', 3 ], [ 'name', 'WELLINGTON ALFRED' ], [ 'location', 'hill' ], [ 'filename', 243245.PDF]]] What's the best practice to do it in Node.js? Thank's in advance! A: you totally can use JSON.stringify string_for_mongo = JSON.stringify(your_array) but you also can use any of these drivers for mongodb if you want to convert these arrays to object you can just use something like this pairs = {} for ( pair in your_array[1] ) { pairs[your_array[1][pair][0]] = your_array[1][pair][1] } objekt = {} objekt[your_array[0]] = pairs I think there is no better solution than not to use such an arrays. Try to form data in objects from the beginning.
{ "pile_set_name": "StackExchange" }
Q: Selecting members to add to a github project My team recently added a software project to github. We are getting requests from some of the users that they would like to become part of the team. What would be a good way to choose whom to add ? A: Don't add any outside contributor right away - make them send pull requests instead. As you review these pull requests, you can: Assess the skill of the contributor from the quality of their code Verify that what they want to add to the project is compatible with your vision See how willing they are to conform to your rules and style Learn to know them a bit by talking to them over the comments in the review-fix cycle After accepting a few of their pull requests, you'll be in a much better position to decide if you want to give to a contributor push access to the project's repository. Note that the contributors also learn during the course of the pull requests, so these parameters can and will improve over time. A contributor can learn from your code review how code submitted to the project should be and match their code to it. So it's not a matter of who but a matter of when (where the answer can be "never", but you don't know that yet) - any contributor might one day be a full member.
{ "pile_set_name": "StackExchange" }
Q: Fix div to make bar above image with CSS This piece of code works fine on firefox. However with everything else it doesnt work as desired. I am trying to make the X on the top right with the image beneath the title/X as it shows in the firefox image below HTML: <div class="CenterImg"> <div class="temp"><div class="fn">namedkfjdjfdjfsjdfijsdifjdsfdfsddsdf.jpg</div><div class="remove">X</div><div class="imgdiv"><img src="http://th960.photobucket.com/albums/ae89/DarkKitteh/Stuffz/th_Avatars_Funny_Cat_With_Headphones.gif"/></div></div> <div class="temp"><div class="fn">name.jpg</div><div class="remove">X</div><div class="imgdiv"><img src="http://th960.photobucket.com/albums/ae89/DarkKitteh/Stuffz/th_Avatars_Funny_Cat_With_Headphones.gif"/></div></div> </div> CSS: .CenterImg > div { border-style:solid; border-width:1px; float: left; } .CenterImg div .imgdiv img { vertical-align: middle; border: none; } .CenterImg div .imgdiv { vertical-align: middle; display: table-cell; text-align: center; width: 150px; height: 150px; } .CenterImg > div > .fn { max-width: 138px; width: 138px; overflow:hidden; height: inherit; float: left; } .remove { float: right; text-decoration:underline; cursor: pointer; } A: You want to make sure the image is underneath the text and the "X". In order to do this, you need to add a div that clears the space as follows: <div style="clear:both;"></div> Place this div under your text and the "X", and above the image div. This will guarantee the image always sits below your text without overlap. In the context of your first box, this code would be: <div class="temp"><div class="fn">namedkfjdjfdjfsjdfijsdifjdsfdfsddsdf.jpg</div> <div class="remove">X</div> <div style="clear:both;"></div> <div class="imgdiv"><img src="http://th960.photobucket.com/albums/ae89/DarkKitteh/Stuffz/th_Avatars_Funny_Cat_With_Headphones.gif"/></div></div>
{ "pile_set_name": "StackExchange" }
Q: Make footer stick to bottom in absolute layout I want the footer to stick to the bottom of the page without overlapping content if the page height is more than 100%. I don't know how to achieve that because i cannot change the following css that every page has becaus if i do the website don't work properly because of the transitions. I know that setting position to relative would fix it, but thats not possible in my case. Here is the css of the page: .pt-page { width: 100%; height: 100%; position: absolute; top: 0; left: 0; visibility: hidden; overflow-y: auto; -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden; backface-visibility: hidden; -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; } #footer{ height: 70px; width: 100%; margin-top: 500px; position: absolute; bottom: 0; z-index: 1; } .pt-wrapper { position: relative; width: 100%; height: 100%; -webkit-perspective: 1200px; -moz-perspective: 1200px; perspective: 1200px; } Now the footer is always on the bottom of the visible window, so it sometimes overlaps the content. And the html: <!-- Page Wrapper --> <div class="pt-wrapper"> <!-- Page 01 --> <div class="pt-page pt-page-01"> <!-- content container --> <div class="container"> <!-- row with 1 columns --> <div class="row"> <div class="col-sm-12 center"> <h1>¡Bienvenido a tu Nueva Web!</h1> <img class="margin-top img-p-01" src="img/36.svg" width="36%" height="36%" alt=""> <p class="margin-top">La unión perfecta: tu logo, tu dominio, nuestra plataforma!<br> Flats2Share esta disponible como software de marca blanca, únicamente para tus propiedades y tus clientes. </p> </div> </div> </div> </div> <!-- Footer --> <div id="footer"> <div class="container"> <div class="row center"> <div class="col-sm-12"> <img class="pt-trigger btn-prev" src="img/back.svg" data-animation="1-45-31-2-42-18-34-53-4-52-19-50-7-48-21-11-65-29-6-66-24-52-58-41-62-65-29-36-2-23-21-10-67-46-1-19-41-56-62" data-goto="-2"> <img class="pt-trigger btn-next" src="img/forward.svg" data-animation="1-45-31-2-42-18-34-53-4-52-19-50-7-48-21-11-65-29-6-66-24-52-58-41-62-65-29-36-2-23-21-10-67-46-1-19-41-56-62" data-goto="-1"> </div> </div> </div> </div> </div> How can I resolve this problem? Thanks in advance! A: Just a quick solution. Add padding-bottom of 70px to your .pt-page element.
{ "pile_set_name": "StackExchange" }
Q: PostgreSQL - Are BEFORE triggers more efficient then AFTER triggers? I just read in the PostgreSQL Documentation - Overview of Trigger behavior, that BEFORE triggers are "more effecient" than AFTER triggers: If you have no specific reason to make a trigger before or after, the before case is more efficient, since the information about the operation doesn't have to be saved until end of statement. I do not understand if this is true or what it means for me. Can someone enlighten me? Is this just a homeopatic performance improvement? A: Due to PostgreSQL's MVCC architecture, each operation increases the amount of data recorded in the system, even DELETE. So if you just need to make checks of your input and rollback the transaction if the checks fail, you better do it before the input data are saved.
{ "pile_set_name": "StackExchange" }
Q: Using Masonry plugin for JSON blog feed JSON code works fine but can't figure out how to get masonry to work in displaying articles. Blog articles display just as if I were not using masonry. I've checked the documentation and there is a similar question here but it is not a duplicate! Any insight would be greatly appreciated. Here is my code: Javascript/jQuery: $(window).load(function() { $.getJSON("http://www.freecodecamp.com/stories/hotStories", function(news){ var length = news.length; // alert(length); for (var i = 0; i<length; i++) { var story = news[i], image = story["image"], link = story["link"]; //number of comments for each article var numComments = story["comments"].length; //assign user profile pic if story has no featured image if (story["image"]===""){ // alert('hi'); image = story["author"]["picture"]; } $("<div class='newsStory'></div>") .append("<a href='"+ link +"'><img class='profile_image' src='" + image + "'></a>") .append("<a href='"+ link +"'><h3 class='headline'>"+ story["headline"] +"</h3></a>") .append("<p class='comment'>Comments: "+ numComments +"</p>") .appendTo("#newsContainer"); }// end for loop });//end getJSON and function //plugin for vertical stacking of stories called masonry $('#newsContainer').masonry({ itemSelector: '.newsStory', columnWidth: '.newsStory' }).imagesLoaded(function() { $('#newsContainer').masonry('reload'); }); });// end document.ready CSS: body { margin: none; padding: none; font-family: 'Almendra', serif; background-color: #8DE2FF; } a { text-decoration: none; } header h1, header p { text-align: center; color: #FF6699; } header h1 { font-weight: 500; font-size: 3em; margin-bottom: -20px; } header p { font-weight: 200; font-size: 2em; margin-bottom: 40px; font-family: 'Satisfy', cursive; } #newsContainer { width: 90%; margin: 5px auto; clear: both; } .newsStory { width: 20%; /* height: 200px;*/ margin: 1.2%; display: inline-block; float: left; background-color: #916C47; border: 10px solid #826140; border-radius: 5px; } .profile_image { display: block; width: 80%; margin: 7px auto; border-bottom: 3px solid #AEEAFF; } .headline { margin: 4px; text-align: center; color: #FFC1D6; } .comment { color: #AEEAFF; margin: 10px; font-family: sans-serif; font-weight: 200; } HTML: <!DOCTYPE html> <html> <head> <title>Code Camp Feed</title> <link href='http://fonts.googleapis.com/css?family=Satisfy|Almendra:400italic,700italic' rel='stylesheet'> <script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.1/masonry.pkgd.min.js"></script> <link rel='stylesheet' href='main.css'> <script src='jquery-1.11.3.min.js'></script> <script src='script.js'></script> </head> <body> <header> <h1>Free Code Camp</h1> <p>Camper News</p> </header> <div id='newsContainer' class='js-masonry clearfix'> </div> </body> </html> A: Maybe you could try $("<div class='newsStory'></div>") .append("<a href='"+ link +"'><img class='profile_image' src='" + image + "'></a>") .append("<a href='"+ link +"'><h3 class='headline'>"+ story["headline"] +"</h3></a>") .append("<p class='comment'>Comments: "+ numComments +"</p>") .appendTo("#newsContainer"); }// end for loop $('#newsContainer').imagesLoaded(function(){ $('#newsContainer').masonry({ itemSelector : '.newsStory' ); }); });//end getJSON and function });// end document.ready In your case,I guess this will be better <script src='jquery.min.js'></script> <script src="jquery.masonry.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: Zipped variable losing value on 2nd iteration I'm pretty new to Python so I'm sure this isn't the most efficient way to code this. The problem I'm having is I have a 2nd For loop that runs inside another for loop. It works fine the first time, but on the second iteration, the second for loop doesn't register the data and skips over it so the it never runs again. I use a zipped tuple and it just looks like it loses the value completely. ` class Model: def predict(self, data): prediction = [] distances = [] for item in data: distances.clear() for trainedItem in self.Train_Data: distances.append([(abs((item[0] - trainedItem[0][3])) + abs((item[1] - trainedItem[0][1])) + abs((item[2] - trainedItem[0][2])) + abs((item[3] - trainedItem[0][3]))), trainedItem[1]]) distances.sort() targetNeighbors = [] for closest in distances[:self.K]: targetNeighbors.append(closest[1]) prediction.append(Counter(targetNeighbors).most_common()[0][0]) return prediction class HardcodedClassifier: def fit(X_Train, Y_Train, k): Model.Train_Data = zip(X_Train, Y_Train) Model.K = k return Model` A: The iterator was depleted. Try Model.Train_Data = list(zip(X_Train, Y_Train)) so it will iterate every time in the inner for loop.
{ "pile_set_name": "StackExchange" }
Q: Is there a reliable way to activate / set focus to a window using C#? I'm trying to find a reliable way to activate / set focus to a window of an external application using C#. Currently I'm attempting to achieve this using the following Windows API calls: SetActiveWindow(handle); SwitchToThisWindow(handle, true); Previously I also had ShowWindow(handle, SW_SHOWMAXIMIZED); executing before the other 2, but removed it because it was causing strange behavior. The problem I'm having with my current implementation is that occasionally the focus will not be set correctly. The window will become visible but the top part of it will still appear grayed out as if it wasn't in focus. Is there a way to reliably do this which works 100% of the time, or is the inconsistent behavior a side-effect I can't escape? Please let me know if you have any suggestions or implementations that always work. A: You need to use AttachThreadInput Windows created in different threads typically process input independently of each other. That is, they have their own input states (focus, active, capture windows, key state, queue status, and so on), and they are not synchronized with the input processing of other threads. By using the AttachThreadInput function, a thread can attach its input processing to another thread. This also allows threads to share their input states, so they can call the SetFocus function to set the keyboard focus to a window of a different thread. This also allows threads to get key-state information. These capabilities are not generally possible. I am not sure of the ramifications of using this API from (presumably) Windows Forms. That said, I've used it in C++ to get this effect. Code would be something like as follows: DWORD currentThreadId = GetCurrentThreadId(); DWORD otherThreadId = GetWindowThreadProcessId(targetHwnd, NULL); if( otherThreadId == 0 ) return 1; if( otherThreadId != currentThreadId ) { AttachThreadInput(currentThreadId, otherThreadId, TRUE); } SetActiveWindow(targetHwnd); if( otherThreadId != currentThreadId ) { AttachThreadInput(currentThreadId, otherThreadId, FALSE); } targetHwnd being the HWND of the window you want to set focus to. I assume you can work out the P/Invoke signature(s) since you're already using native APIs. A: [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); This one worked for me
{ "pile_set_name": "StackExchange" }
Q: Domain Controller error after removing legacy SBS server from the local network I am migrating a Windows SBS 2008 to a Windows Server 2016 and thought I was on the last mile, shtting down the source SBS server. It seems my domain still depends on the legacy SBS though. When I remove the old server from the network (either by shutting it down or just pulling the network cable) I am getting 2 problems: Error when starting the "Dashboard" on the target server Windows Server Essentials: Networking domain controller server ist not accessible, some operations in Dashboard may not succeed. Please check your network and make sure you can access the domain controller server. Error when starting starting "Active Directory Users & Computers" on target server Active Directory Domain Services: Naming information can not be located because the specified domain either does not exist or could not be contacted. Practically this results into not being able to see any Domain User Accounts once the source server is cut off from the local network. Maybe other stuff running in the background may be affected as well which I am not aware of. thus far I have removed some entries in the DNS Manager on the source server, pointing at itself. But that neither has helped yet, nor does googleing the results return any solutions really. I still find one entry for the source Server in the target server @ >Active Directory Users and Computers >[domain] >Domain Controllers. Any idea how to get over these 2 issues? EDIT: C:\Users\admin>netdom query fsmo Schema master [newserver].[mydomain].local Domain naming master [newserver].[mydomain].local PDC [newserver].[mydomain].local RID pool manager [newserver].[mydomain].local Infrastructure master [newserver].[mydomain].local The command completed successfully. Moving the fsmo roles over to the [newserver] was a pretty bumpy ride though because nothing worked as lined out in the how-to we where trying to use. But in the end the netdom query output was like posted above (which is how it should be as I understand) EDIT 2: I got a hint for looking at entries in the target Servers DNS Manager and actually get soome references to the source server >Forward-Lookupzones >myDomain>_msdcs has a Name Server (NS) entry which still refers to the SBS - I guess I change the ip address here, so it points to the new server, right? >Forward-Lookupzones>[myDomain] >/sites >/Default-First-Site-Name >/_tcp has 2 entries (one for the old, one for the new server) for _gc, _kerbereos & _ldap >Forward-Lookupzones>[myDomain] >/_tcp has 2 entries (one for the old, one for the new server) for _gc, _kerbereos, _ldap and additionally _kpasswd similar situation (doublette entries for [oldserver] & [newserver] for _udp<& other entries in the DNS Manager - shall I remove the Versions pointing to the old SBS Server? EDIT 3: I can ping the 2 servers mutually with ping [hostname].local (which returns the IPv6 address, where ping (hostname) returns the IPv4 address) but not via ping [domain].[hostname].local. If I understand it correctly this is another indicator for the same sort of problems. Does that point to a solution? EDIT 4: @expx Searching the system log with an equivalent German term, the server acutually returned 3 entries (of which 2 where just confirmations, not errors) Protokollname: System Quelle: Microsoft-Windows-GroupPolicy Datum: 06.07.2018 11:12:48 Ereignis-ID: 1058 Aufgabenkategorie:Keine Level: Error keywords: User: SYSTEM Computer: [oldserver].[domain].local Description: Error while processing the Group policy. The attempt to read the file "\so6.local\SysVol\so6.local\Policies{3474E153-5F07-4EC3-B816-9C0405CCF68F}\gpt.ini" from a Domaincontroller was not successful. Group policiy settings can't be applied until this event is resolved. This could be a temporay problem which could have at least one of the following causes: a) name resolution/network connection with the current Domaincontroller b) Waiting period of the File Replication Service c) the DFS-Clilent has been deactivated Event-XML: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Microsoft-Windows-GroupPolicy" Guid="{aea1b4fa-97d1-45f2-a64c-4d69fffd92c9}" /> <EventID>1058</EventID> <Version>0</Version> <Level>2</Level> <Task>0</Task> <Opcode>1</Opcode> <Keywords>0x8000000000000000</Keywords> <TimeCreated SystemTime="2018-07-06T09:12:48.941Z" /> <EventRecordID>1643448</EventRecordID> <Correlation ActivityID="{C8828C15-D9E9-4FC6-8DE1-927F01129AB1}" /> <Execution ProcessID="520" ThreadID="1260" /> <Channel>System</Channel> <Computer>SO6SERVER.so6.local</Computer> <Security UserID="S-1-5-18" /> </System> <EventData> <Data Name="SupportInfo1">4</Data> <Data Name="SupportInfo2">840</Data> <Data Name="ProcessingMode">1</Data> <Data Name="ProcessingTimeInMilliseconds">3027</Data> <Data Name="ErrorCode">53</Data> <Data Name="ErrorDescription">Der Netzwerkpfad wurde nicht gefunden. </Data> <Data Name="DCName">\SO6SERVER.so6.local</Data> <Data Name="GPOCNName">cn={3474E153-5F07-4EC3-B816-9C0405CCF68F},cn=policies,cn=system,DC=so6,DC=local</Data> <Data Name="FilePath">\so6.local\SysVol\so6.local\Policies{3474E153-5F07-4EC3-B816-9C0405CCF68F}\gpt.ini</Data> </EventData> </Event> practically I can read the file mentioned when I am accessing (as the Domain admin) A: AD is multi-master environment able to determine which DC is alive and which is dead. In general, you should remove all those DNS records in the end but that shouldn't prevent you to use new DC if old DC is simply off network. This seems like some kind of replication issue to me. if you navigate to \\newserver do you see all shares (NETLOGON and SYSVOL)? Also, is old server 2008 or 2008 R2. If it's plain 2008 it may uses FRS instead of DFSR which can cause issues with new versions of DCs (2012 and later). Login to old DC, open Event Viewer and see if you can find any errors pointing to FRS (for instance JOURNAL_WRAP errors).
{ "pile_set_name": "StackExchange" }
Q: How do I resize the td of a table styled with bootstrap? I read http://getbootstrap.com/css/#tables which didn't mention resizing tds in any specific way, so I tried the following css: .cbCell { width: 25px; } .smallerCell { width: 240px; } .textfield { width: 230px; } with this html <thead> <tr> <th class="cbCell"><input type='checkbox' class='form-control' id='selectall'></th> <th class="text-center smallerCell">Employee Name</th> <th class="text-center smallerCell">Mail</th> </tr> </thead> <tbody> <tr id='addr0'> <td class="cbCell"><input type='checkbox' class='form-control case'></td> <td class="smallerCell"><input type="text" name='name0' placeholder='Name' class="form-control textfield"/></td> <td class="smallerCell"><input type="text" name='mail0' placeholder='Mail' class="form-control textfield"/></td> </tr> <tr id='addr1'> </tr> </tbody> The textfields have been resized but the td has not, the 'smallerCell' style isn't applied I tried Change column width bootstrap tables which didn't work for me. I used the grid system to float the establishment info to the right, I ultimately want the name and mail columns to fit the smaller textfield size, and for there to be a margin and vertical rule dividing the People and Establishment columns. A: Change table width to auto. In boot strap table width is set to 100% .table { width: 100%; margin-bottom: 20px; } so make it .table { width: auto; } in you css.
{ "pile_set_name": "StackExchange" }
Q: How to retrieve data from multiple arrays I have two arrays that was converted from csv file. The first csv line looks like this: franchise_id,franchise_name,phone,website,email,region_codes; 1,"Abbott, Hackett and O`Conner",1-648-177-9510,auto-service.co/bw-319-x,[email protected],"36101,36055,36071"; The second csv line looks like this: postal_code,region_code,city,state,region; 14410,36055,Adams Basin,NY,Monroe; I converted these lines to arrays like this: //Region Array $region_lines = explode(PHP_EOL, $region_mappings_string); $region_array = array(); foreach ($region_lines as $region_line) { $region_array[] = str_getcsv($region_line); } //Franchise Array $franchise_lines = explode(PHP_EOL, $franchises_string); $franchise_array = array(); foreach ($franchise_lines as $franchise_line) { $franchise_array[] = str_getcsv($franchise_line); } After that I got the result like this for Region: Array ( [0] => Array ( [0] => postal_code [1] => region_code [2] => city [3] => state [4] => region; ) [111] => Array ( [0] => 14410 [1] => 36055 [2] => Adams Basin [3] => NY [4] => Monroe; ) [112] => Array ( [0] => 14617 [1] => 36055 [2] => Rochester [3] => NY [4] => Monroe; ) And for franchise: Array ( [0] => Array ( [0] => franchise_id [1] => franchise_name [2] => phone [3] => website [4] => email [5] => region_codes; ) [1] => Array ( [0] => 1 [1] => Abbott, Hackett and O`Conner [2] => 1-648-177-9510 [3] => auto-service.co/bw-319-x [4] => [email protected] [5] => 36101,36055,36071; ) What I need to do is to look for 14410 postal code from the first array, get the region_code and look for this region_code in second array and then output the results in PHP. How can this be done? A: Will have to loop over franchises array and run simple comparison function getDataByRegionCode($code, $franchiseArray) { foreach ($franchiseArray as $key => $data) { if(isset($data[5])){ $codes = explode(',',$data[5]); if(in_array($code,$codes)) return $data; } } return NULL; } print_r(getDataByRegionCode(14410,$franchiseArray));
{ "pile_set_name": "StackExchange" }
Q: UIImageView is not scrolling inside a scrollView I am creating a scrollview with a page control. I have a scrollview added to my viewcontroller and inside the scrollview there is a UIImageView. But for some reason I cannot scroll it to the left or right side. Can anyone help me out to fix this problem? My Code: var tutorialImages: [String] = ["1", "2", "3"] var frame = CGRect.zero func pageControll() { pageControllTutorial.numberOfPages = tutorialImages.count for i in 0..<tutorialImages.count { imageViewTutorial.frame = frame imageViewTutorial.image = UIImage(named: tutorialImages[i]) scrollViewTutorial.addSubview(imageViewTutorial) } scrollViewTutorial.contentSize = CGSize(width: imageViewTutorial.frame.size.width * CGFloat(tutorialImages.count), height: imageViewTutorial.frame.size.height) scrollViewTutorial.delegate = self } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { var pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width pageControllTutorial.currentPage = Int(pageNumber) } A: With the little bit of code you've shown, you're doing a number of things wrong. Based on this line: imageViewTutorial.image = UIImage(named: tutorialImages[I]) it looks like you have one UIImageView and you are setting its .image property 3 times, instead of creating 3 different image views. Also, there is nothing in your code indicating how you are setting the frames of the image views. I highly recommend using auto-layout instead of explicit frames - makes things much, much easier going forward. Here is a complete example. It will create a square (1:1 ratio) scroll view 20-pts from the top with 20-pts padding on each side, and a UIPageControl below. It then adds a horizontal UIStackView to the scroll view. That stack view will hold the image views. Once the image views are added, the stack view will automatically define the "scrollable area" -- no need for calculating .contentSize. Here's what it will look like: Everything is done in code, so just assign the class of an empty view controller to SlidesExampleViewController ... no @IBOutlet or @IBAction connections needed. class SlidesExampleViewController: UIViewController, UIScrollViewDelegate { lazy var pageControl: UIPageControl = { let v = UIPageControl() v.backgroundColor = .brown return v }() lazy var scrollView: UIScrollView = { let v = UIScrollView(frame: .zero) v.backgroundColor = .yellow v.delegate = self return v }() lazy var stackView: UIStackView = { let v = UIStackView() v.axis = .horizontal v.alignment = .fill v.distribution = .fill v.spacing = 0 return v }() let tutorialImages: [String] = ["1", "2", "3"] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white scrollView.translatesAutoresizingMaskIntoConstraints = false stackView.translatesAutoresizingMaskIntoConstraints = false pageControl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) view.addSubview(pageControl) scrollView.addSubview(stackView) let v = view.safeAreaLayoutGuide let g = scrollView.contentLayoutGuide NSLayoutConstraint.activate([ // constrain scroll view to top, leading, trailing with 20-pts "padding" scrollView.topAnchor.constraint(equalTo: v.topAnchor, constant: 20.0), scrollView.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: 20.0), scrollView.trailingAnchor.constraint(equalTo: v.trailingAnchor, constant: -20.0), // constrain scroll view height equal to scroll view width scrollView.heightAnchor.constraint(equalTo: scrollView.widthAnchor), // constrain stack view to all 4 sides of scroll view's contentLayoutGuide stackView.topAnchor.constraint(equalTo: g.topAnchor), stackView.bottomAnchor.constraint(equalTo: g.bottomAnchor), stackView.leadingAnchor.constraint(equalTo: g.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: g.trailingAnchor), // constrain stack view height equal to scroll view height stackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor), // constrain page control width to 80% of scroll view width pageControl.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 0.8), // constrain page control top to 8-pts below scroll view bottom pageControl.topAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 8.0), // constrain page control centerX to centerX of scroll view pageControl.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor, constant: 0.0), ]) tutorialImages.forEach { name in if let img = UIImage(named: name) { let imgView = UIImageView(image: img) stackView.addArrangedSubview(imgView) imgView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true } } pageControl.numberOfPages = tutorialImages.count scrollView.isPagingEnabled = true } func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageIndex = round(scrollView.contentOffset.x/view.frame.width) pageControl.currentPage = Int(pageIndex) } }
{ "pile_set_name": "StackExchange" }
Q: Android - Listener/Callback for when number of View children changes In Android can one use/implement a listener that fires a callback when the number of children for a given View changes dynamically? Say for example a View has 3 immediate children, and one is removed through code, I need an event to fire to say that the number of immediate children has changed. To clarify, I don't need to perform a depth traversal on the View tree to count children, I'm just interested in counting the number of children at the first layer of a given View. Many thanks A: I believe that you want to use the OnHierarchyChangeListener: Interface definition for a callback to be invoked when the hierarchy within this view changed. The hierarchy changes whenever a child is added to or removed from this view. It has two callbacks: onChildViewAdded() onChildViewRemoved() A: Its simple to trick down. Just extend the View Group Your adding View Into and override remove and optionally the addView method. Provide Your Callback Interface Implementation to the any of Your ViewGroup class method to set listener. Call its delegate from within the overridden remove and addView method. Make your Callback Interface delegate to receive current size. Something like this public class MyViewGroup extends LinearLayout { // provide constructor implmentation to justify super constructor requirement private OnSizeChangeListener callback; public void setOnSizeChangeListener(OnSizeChangeListener callback) { this.callback = callback; } @Override public void remove(View view) { super.remove(view); if(callback != null) { callback.sizeChanged(getChildCount); } } }
{ "pile_set_name": "StackExchange" }
Q: Understanding this Lambda expression Found this while learning on a tutorial, having trouble understanding it, as the source code gives no comment on what it is doing. I passed many different byte[] values to it to see if I can figure it out, I can't. And most Lambda tutorials only show a single variable type - not 2. using System.Linq; using System.Numerics; private string DoLamdaExpression(byte[] data) { var intData = data.Aggregate<byte, BigInteger>(0, (current, t) => current * 256 + t); string result = intData.ToString(); return result; } current and t are not defined anywhere previously so honestly, I do not know what the role of "byte[] data" is being used other than calling the .Aggregate function. additionally data.Aggregate = the Accumulate function... my gut feeling is that "byte" is taking the role of current, and "BigInteger" is taking the role of t. public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func); A: The lambda expression defines an anonymous Func that aggregates the data byte array, where each element of the array is processed. current represents the result so far and t is the element being processed. In this example, the function iterates the array, and for each element, multiplies the current result by 256 and adds the element being handled.
{ "pile_set_name": "StackExchange" }
Q: OpenCV c++ Assertion I've been struggling with some assertion in opencv project. First I'm converting Mat objects to be sure about their types: gray_im.convertTo(gray_im, CV_8U); diff_im.convertTo(diff_im, CV_8U); Then I do a subtraction. This line is where I got the assertion: diff_im = gray_im - prev_im; And here is the assertion: OpenCV Error: Bad argument (When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified) in arithm_op, file /build/buildd/opencv-2.4.8+dfsg1/modules/core/src/arithm.cpp, line 1313 When I print info about images I'm using in subtraction; diff_im. type: 5 rows: 600 cols 800 gray_im. type: 5 rows: 600 cols 800 prev_im. type: 0 rows: 600 cols 800 I think that I'm explicitly specifying output array (and if I'm correct, here diff_im is output array, right?) by converting it to CV_8U. Also when I print the type information of diff_im in runtime, it says it is "5" which means that I have explicitly specified the type of "diff_im". Am I wrong here? Any suggestions? OpenCV version: 2.4.8 Thanks in advance. A: gray_im has type 5 and prev_im has type 0. You may forgot to initialize prev_im correctly, i.e.: prev_im = cv::Mat::zeros(gray_im.size(), gray_im.type()); Update #1: Well, dst = src1 - src2 is equivalent to subtract(dst, src1, dst). The parameter dst is OutputArray and used for output function parameter only. The type of dst cannot be defined by operator- only subtract() provides possibility for that by its parameter dtype, see here. If dtype is not given and both of the input parameters are arrays then src1.type() must be equal to src2.type(), see here. So you should overwrite operator- as below: cv::Mat src1(600, 800, CV_8U); cv::Mat src2(600, 800, CV_32F); cv::Mat dst; //dst = src1 - src2; // --> this will give the same assert cv::subtract(src1, src2, dst, cv::noArray(), CV_32F); // type of dst is CV_32F
{ "pile_set_name": "StackExchange" }
Q: how many max join table at mysql? and how to count it? Maybe this question is related with this one. I have Question.. My friend said that mysql has limitation on max join table. And I get this : The maximum number of tables that can be referenced in a single join is 61. This also applies to the number of tables that can be referenced in the definition of a view. Is that true? Then, for example: I have select query and join 2 table: left join a on b.id = a.b_id So, how to count the number of joined table? Per table? or Per join? so, that query marked as 1 (per join) or 2(per table)? 61 (max limit) is per table or per join? A: The text is clear on that: "The maximum number of tables [...] is 61". Followed by "This also applies to the number of tables [in] a view".
{ "pile_set_name": "StackExchange" }
Q: How to create an empty KeyEvent and SetKeyCode(keyCode) in Java? In my project, I'm trying to receive a dataInputStream which is readInt() from another computer that sends writeInt(e.getKeyCode()) to this computer, but when I receives the keyCode, how do I put it into a KeyEvent object? Here's a part of my coding: KeyEvent enemyKey; try{ key = inputFromClient.readInt(); if(key!=0) { enemyKey.setKeyCode(key); player2.keyPressed(enemyKey); } }catch(Exception ex){ System.out.println(ex); } By executing the code above, I get NullPointerException because KeyEvent enemyKey is null. What can I do to resolve this issue? A: You haven't initialized KeyEvent enemyKey; You can initialize it with this constructor public KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar) source - The Component that originated the event id - An integer indicating the type of event. For information on allowable values, see the class description for KeyEvent when - A long integer that specifies the time the event occurred. Passing negative or zero value is not recommended modifiers - The modifier keys down during event (shift, ctrl, alt, meta). Passing negative value is not recommended. Zero value means that no modifiers were passed. Use either an extended _DOWN_MASK or old _MASK modifiers, however do not mix models in the one event. The extended modifiers are preferred for using keyCode - The integer code for an actual key, or VK_UNDEFINED (for a key-typed event) keyChar - The Unicode character generated by this event, or CHAR_UNDEFINED (for key-pressed and key-released events which do not map to a valid Unicode character) See KeyEvent javadoc for more information on values you can pass to the constructor Also, take a look at Javabeans
{ "pile_set_name": "StackExchange" }
Q: Is there a problem if one forgets to sanitize caps? I bottle about a third of my batches in longnecks with crown caps. On my most recent brew (that's carbing up now) I forgot to sanitize the caps. Didn't realize this until I had bottled everything and was getting ready to cap the bottles and reached into my bucket of sanitized gear to grab a few caps and... oops! I normally sanitize more than the needed number of caps, and had enough caps that were sanitized months ago to cap everything up. My question is that if the beer stays upright (in cases/crates) and the beer doesn't sit on the caps, do I need to worry about infection, or should I just meditate to the mantra Charlie Papazian gave us all? A: Unlikely to be a problem. In an earlier question I found that some pro-brewers don't sanitize their caps at all. Neither do some home brewers.
{ "pile_set_name": "StackExchange" }
Q: JTextPane - a phrase with TWO styles I just faced an interesting thing. I was changing selected text style. The thing is when I change style for ONE WORD one by one it's fine but next if I select a whole styled phrase and change its font color the whole phrase becomes ONE styled (the first style within the selected text) only :( Here is the problem snippet private void setFontColorStyle() { JTextPane editor=this.getTextPane(); String text=this.getTextPane().getSelectedText(); StyledDocument doc=(StyledDocument) editor.getDocument(); int selectionEnd=this.getTextPane().getSelectionEnd(); int selectionStart=this.getTextPane().getSelectionStart(); Element element=doc.getCharacterElement(selectionStart); AttributeSet as = element.getAttributes(); String family = StyleConstants.getFontFamily(as); int fontSize = StyleConstants.getFontSize(as); boolean isBold=StyleConstants.isBold(as); boolean isItalic=StyleConstants.isItalic(as); boolean isUnderlined=StyleConstants.isUnderline(as); StyleContext context = new StyleContext(); Style style; this.getTextPane().replaceSelection(""); style = context.addStyle("mystyle", null); style.addAttribute(StyleConstants.FontSize, fontSize); style.addAttribute(StyleConstants.FontFamily, family); style.addAttribute(StyleConstants.Foreground, this.fontColor); style.addAttribute(StyleConstants.Bold, isBold); style.addAttribute(StyleConstants.Italic, isItalic); style.addAttribute(StyleConstants.Underline, isUnderlined); this.getTextPane().replaceSelection(""); try { this.getTextPane().getStyledDocument().insertString(selectionEnd - text.length(), text, style); } catch (BadLocationException ex) { } } And here is the bold making method code... () Italic and underlined all the same logic so I guess it is quite clear private void setFontBoldStyle() { if(this.getTextPane().getSelectedText()!=null) { String text = this.getTextPane().getSelectedText(); int selectionStart=this.getTextPane().getSelectionStart(); int selectionEnd=this.getTextPane().getSelectionEnd(); StyleContext context = new StyleContext(); Style style; Element element=doc.getCharacterElement(selectionStart); Enumeration en=doc.getStyleNames(); AttributeSet as = element.getAttributes(); /** * Get style from history... */ String family = StyleConstants.getFontFamily(as); int fontSize = StyleConstants.getFontSize(as); Color currentColor=StyleConstants.getForeground(as); boolean isBold=StyleConstants.isBold(as)?false:true; boolean isItalic=StyleConstants.isItalic(as); boolean isUnderlined=StyleConstants.isUnderline(as); String styleName=String.valueOf(Math.random()); style = context.addStyle(styleName, null); // style.addAttribute(StyleConstants.FontSize, fontSize); // style.addAttribute(StyleConstants.FontFamily, family); style.addAttribute(StyleConstants.Foreground, currentColor); style.addAttribute(StyleConstants.FontFamily, family); style.addAttribute(StyleConstants.FontSize, fontSize); style.addAttribute(StyleConstants.Bold, isBold); style.addAttribute(StyleConstants.Italic, isItalic); style.addAttribute(StyleConstants.Underline, isUnderlined); this.getTextPane().replaceSelection(""); try { this.getTextPane().getStyledDocument().insertString(selectionEnd - text.length(), text, style); } catch (BadLocationException ex) { } }//if end... } Here is the bold method invokation code: private void setFontBold() { this.setFontBoldStyle(); } ... and color method invokation private void setFontColor(Color fontColor) { this.fontColor=fontColor; this.setFontColorStyle(); } ... and action listeners (for bold)... private void boldButtonActionPerformed(java.awt.event.ActionEvent evt) { this.getTextPane().requestFocusInWindow(); this.setFontBold(); } ... and for color private void colorButtonActionPerformed(java.awt.event.ActionEvent evt) { this.getTextPane().requestFocusInWindow(); ColorDialog colorEditor=new ColorDialog(); //returns rgb color... Color color=colorEditor.getSelectedColor(this.getDialog(), true,false); if(color==null){ JOptionPane.showMessageDialog(this.getDialog(), "null color"); return; } this.setFontColor(color); } I dearly need your advice about how to keep selected text styles unchanged (like bold or font family) when I want to change a whole different styled selected text color for example? To be more clear... For example I have text My Hello World is not pretty :) Next I select the whole phrase and change its color from black to lets say red. Next text becomes red but the whole phrase becomes bold according to first style. But the thing is it would be interesting to keep bold and italic styles but at the same time have the phrase red :) So quite simple but I have just confused how to control more than one style in the frames of selected text area? Any useful comment is much appreciated A: TextComponentDemo, discussed in How to Use Editor Panes and Text Panes, is a good example of how to manage this as well as other text component features. Addendum: TextComponentDemo relies on pre-defined Action objects to handle editing tasks. Conveniently, StyledEditorKit contains a series of nested classes that derive from StyledTextAction. As a concrete example, here's how one might add an AlignmentAction to the Style menu of TextComponentDemo in the method createStyleMenu(): protected JMenu createStyleMenu() { JMenu menu = new JMenu("Style"); Action action = new StyledEditorKit.AlignmentAction( "left-justify", StyleConstants.ALIGN_LEFT); action.putValue(Action.NAME, "Left"); menu.add(action); menu.addSeparator(); ... } The remaining (arbitrary) alignment action names are defined privately in StyledEditorKit. Addendum: setCharacterAttributes() is the common routine used by the nested editing actions. It invokes a method of the same name in StyledDocument, as proposed by @StanislavL. Addendum: I am unable to reproduce the effect you describe. When I set the color of the selection, the style attributes remain unchanged. Addendum: The StyledEditorKit actions work just as well with a JButton or JToolBar. new JButton(new StyledEditorKit.ForegroundAction("Red", Color.red)) A: Use this.getTextPane().getStyledDocument().setCharacterAttributes()
{ "pile_set_name": "StackExchange" }
Q: SELECT within SELECT with TOP I have two tables. Table one is Channels and Table two is Datum. The Datum is a many to one to Channels. I would like to get the latest Value and Date Time from the Datum table while looping through each of the channels. I have a SELECT statement that is working but I don't think this is the correct way to do it. SELECT (SELECT TOP(1) NumericValue FROM Datum WHERE ChannelId = test.ChannelId ORDER BY [DateTime] DESC) AS NumericValue, (SELECT TOP(1) [DateTime] FROM Datum WHERE ChannelId = test.ChannelId ORDER BY [DateTime] DESC) AS DataTime, ChannelId, Diag, ChannelDescription FROM Channel as test WHERE InstrumentID = 3 I have tried SELECT (SELECT Top(1) NumericValue, [DateTime] FROM Datum WHERE ChannelId = test.ChannelId ORDER BY [DateTime] DESC), ChannelId, Diag, ChannelDescription FROM Channel as test WHERE InstrumentID = 3 How ever it errors with Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. A: Use MAX built in function to get latest value and time of channel: SELECT Value, _DateTime, ChannelId FROM Channel [test] JOIN (SELECT MAX(NumericValue) Value, MAX(DateTime) _DateTime , ChannelId FROM Datum GROUP BY ChannelId) A ON A.ChannelId = test.ChannelId WHERE InstrumentID = 3
{ "pile_set_name": "StackExchange" }
Q: Mysql 5.6 is not working in Mac OS Mysql 5.6 is constantly creating problem in Mac OSX. Its constantly disconnecting the server. And throwing certain errors like /tmp/mysql.sock doesn't exist The same with Mysql 5.6.14 installed via DMG: $ mysql ERROR 2013 (HY000): Lost connection to MySQL server at 'sending authentication information', system error: 32 And authentication packet lost errors. I have to kill the process id every time and then had to run the mysql -u root -p all over again. But same thing happens again and again. A: Don't worry even if none of the online answers in any website doesn't work. Try this, It worked for me and my all my team mates like a charm. 1). Install the atom in mac. 2). Run sudo atom /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist You might see code something like this <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Disabled</key> <false/> <key>ExitTimeOut</key> <integer>600</integer> <key>GroupName</key> <string>_mysql</string> <key>KeepAlive</key> <true/> <key>Label</key> <string>com.oracle.oss.mysql.mysqld</string> <key>LaunchOnlyOnce</key> <false/> <key>ProcessType</key> <string>Interactive</string> <key>Program</key> <string>/usr/local/mysql/bin/mysqld</string> <key>ProgramArguments</key> <array> <string>/usr/local/mysql/bin/mysqld</string> <string>--user=_mysql</string> <string>--basedir=/usr/local/mysql</string> <string>--datadir=/usr/local/mysql/data</string> <string>--plugin-dir=/usr/local/mysql/lib/plugin</string> <string>--log-error=/usr/local/mysql/data/mysqld.local.err</string> <string>--pid-file=/usr/local/mysql/data/mysqld.local.pid</string> </array> <key>RunAtLoad</key> <true/> <key>SessionCreate</key> <true/> <key>UserName</key> <string>_mysql</string> <key>WorkingDirectory</key> <string>/usr/local/mysql</string> </dict> </plist> Then add these two lines just above </array> <string>--port=3306</string> <string>--innodb_file_per_table=0</string> Then restart the mysql server. That's it.
{ "pile_set_name": "StackExchange" }
Q: Blog Site RSS Web Part not shown In Sharepoint 2013 a Blog Site RSS Web Part is not showed until the SC Admin account(s) navigates to the landing page for the first time. Any idea why this way? Or if it's possible to force it. Regards A: Before site admin access the landing page, the Blog Notifications Web Part (RSS WP) has not ListId associated, but after access is automatically set and within the RSS WebPart shows the corresponding ‘Posts’ List contents. Workaround: Set on RSS Web Part the corresponding ‘Posts’ ListId Guid try{ $PostsList = $oWeb.Lists[$ListName] if(!$PostsList){ throw ("Posts List not found with name: {0}" -f $ListName) } $ofile = $oWeb.GetFile($oWeb.Url + "/default.aspx") $wpm = $ofile.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared) $RSSWP = $wpm.WebParts | where {$_.WebBrowsableObject.ToString() -eq "Microsoft.SharePoint.WebPartPages.BlogLinksWebPart"} if(!$RSSWP) { throw ("RSS Web Part not found. {0}" -f $SiteName) } $RSSWP.ListId = $PostsList.Id $wpm.SaveChanges($RSSWP) Write-Host ("<div>[Info] RSS Web Part updated with List ID value: {0}</div>" -f $PostsList.Id) } catch [Exception]{ $catchError = ("Updating RSS Web Part List Id with the following error message: {0}" -f $_) Write-Host $catchError -ForegroundColor "Red" }
{ "pile_set_name": "StackExchange" }
Q: Android Black Screen after Unlocking I'm having trouble with resuming an app's activity after locking the device screen. Here's the typical situation: 1. App is running. 2. Lock device. 3. Unlock device. 4. Instead of returning to running app, it shows a black screen. I checked how the activity lifecycle is running and it seems this is what's happening when it unlocks: 1. Create 2. Start 3. Resume 4. Pause Why is it stuck on pause? I'm sure this is really simple but as I'm still learning Android I'm super confused. Thanks for any help given! EDIT: I don't think I'm doing anything out of the ordinary but here's the basic code I'm using... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("Java", "Create"); // Initialize NDK audio properties here // Initialize the Content View setContentView(R.layout.activity_main); // Setup toolbar Toolbar myToolbar = (Toolbar) findViewById(R.id.toolBar); setSupportActionBar(myToolbar); // Start thread thread = new Thread() { public void run() { setPriority(Thread.MAX_PRIORITY); // Audio Thread is running here } }; thread.start(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } @Override protected void onStart() { super.onStart(); } @Override protected void onPause() { super.onPause(); if (thread != null) { try { thread.join(); } catch (InterruptedException e) { // e.printStackTrace(); } thread = null; } } @Override protected void onResume() { super.onResume(); } @Override protected void onStop() { super.onStop(); } A: I am not thread expert. but here it seems you are blocking ui thread in onpause. thread.join causes the current thread(in this case ui thread) to pause execution until thread terminates.
{ "pile_set_name": "StackExchange" }
Q: Choosing between two video cards: nVidia GTS240/250 vs. ATI HD4870 This is for a Dell gaming PC (XPS 630) but it's primarily used for work stuff (software development, video editing) not so much for high end gaming (I'm still playing Star Craft ) My main criteria is NOISE and secondarily performance for the above types of applications. -nVidia GeForce GTS 240,1 1024MB (concensus is this is just a supercharged GT 9800) and not as fast as the GTS 250. view Specs. vs. -ATI Radeon HD 4870 1024MB I've read opinions that the Radeon is a bit loud (but they weren't comparing it to the GeForce). A: This article treats how the GTS 250 stacks against the Radeon HD 4870 (and others). It contains this comparison chart that tells you everything technical that you ever wanted to know and were afraid to ask about. More importantly, it contains detailed performance analysis for different screen resolutions in the section First-Person 3D Shooters. My personal conclusion is that performance-wise there are only slight differences between the models. Which probably means that the lower model of GTS 240 is inferior to the Radeon.
{ "pile_set_name": "StackExchange" }
Q: Two SQLite queries at one go I have two queries: SELECT word FROM dictionary WHERE lang = 'english' AND word LIKE 'k%' LIMIT 10; SELECT word FROM dictionary WHERE lang = 'english' AND word LIKE 's%' LIMIT 10; Because the database is huge, each query takes time. So, my question is that can I merge the above queries into one with a LIMIT of 5 each? If yes, then how to do it? Any help is appreciated. Thanks. A: Try like this: SELECT * from (select word FROM dictionary WHERE lang = 'english' AND word LIKE 'k%' LIMIT 5) UNION ALL SELECT * from (select word FROM dictionary WHERE lang = 'english' AND word LIKE 's%' LIMIT 5); Also to retrieve the data in a faster way you can create index on your column.
{ "pile_set_name": "StackExchange" }
Q: On creating div element give ordered class name By clicking Create I want to give continuing class name: For example now if you click Create button, it should create the following <div class="div_3">Div 3</div>: <div id="container"> <div class="div_1">Div 1</div> <div class="div_2">Div 2</div> </div> <input type="button" onclick="add()" value="Create"/> Here is JS function add(){ $("#container").append("<div>Div 3</div>") } https://jsfiddle.net/5gmr5j8z/ A: One way is to count the existing elements (and add 1): $("#container").append("<div>Div " + ($("#container div").length+1) + "</div>"); Simple JSFiddle: https://jsfiddle.net/TrueBlueAussie/5gmr5j8z/2/ You need to apply the same to the class, but this gets a little messy, so neater version below. You are also better off using jQuery to connect events. Inline event handlers do not have the power of jQuery handlers (and separate event registration from the event handler for no good reason): $('#add').click(function () { var count = $("#container div").length + 1; var $div = $("<div>", { class: "div_" + count, text: "Div " + count }); $("#container").append($div); }); JSFiddle: https://jsfiddle.net/TrueBlueAussie/5gmr5j8z/3/ There are usually neater ways to do this sort of thing, but you need to explain the overall aim first
{ "pile_set_name": "StackExchange" }
Q: Hard resetting an STM32 My STM32 is behaving weirdly, to say the least. What is the best way to "hard reset" an STM32? I've tried pressing the "reset" button, and unplugging/replugging everything, but it seems like the weirdness remains. How can I make a hard reset to restore all the registers and all the memory back to their reset values? A: Everything else except flash and EEPROM should reset on reset or power off. Hard to say what is your exact problem unless you specify what kind of "weirdness" it is doing.
{ "pile_set_name": "StackExchange" }
Q: Using Variables in Variable definition I am trying to get variables into variables but it wont work. I searched google and tried a lot of stuff but it did not wor out. I hope this question ist not "dumb": What am I doing wrong ? *** Settings *** Library SeleniumLibrary Library OperatingSystem *** Variable *** ${year} Get Time return year ${month} Get Time return month ${day} Get Time return day ${output} ${CURDIR}\Testing\Tests\SRV\csdb_@{year}-@{month}-@{day}.log *** Testcases *** Textfile should have a line saying the service is started ${errors} = Grep File ${output} Test A: From the robot framework user's guide: The most common source for variables are Variable tables in test case files and resource files. Variable tables are convenient, because they allow creating variables in the same place as the rest of the test data, and the needed syntax is very simple. Their main disadvantages are that values are always strings and they cannot be created dynamically. In order to do what you want, you'll need to define the variables in a keyword. For example: *** Keywords *** Get Output ${year}= Get Time year ${month}= Get Time month ${day}= Get Time day ${output}= Set variable ${CURDIR}/Testing/Tests/SRV/csdb_${year}-${month}-${day}.log [Return] ${output} *** Testcases *** Textfile should have a line saying the service is started ${output}= Get Output ${errors} = Grep File ${output} Test Note: you can fetch all three parts of the data in a single call to the keyword, like so: ${year} ${month} ${day}= Get Time year month day It's a bit hard to read with the space-separated format, but the variable names must each be separated by two or more spaces, but "year month day" should have only one.
{ "pile_set_name": "StackExchange" }
Q: How can I use German umlauts in DeclareMathOperator? I would like to define a math operator Homöo, but when I try \DeclareMathOperator{\Homoo}{Homöo} \DeclareMathOperator{\Homoo}{Hom\"oo} I get Homo. How can I use German umlauts in DeclareMathOperator? (If it's not possible at all: What should I do instead?) A: The text in the second argument of \DeclareMathOperator is typeset in a special variety of \mathrm, so - produce a hyphen, for instance, not a minus sign. Fragments of words like yours can be dealt with by saying \DeclareMathOperator{\Homoo}{\textnormal{Homöo}} assuming a non fancy setup for fonts.
{ "pile_set_name": "StackExchange" }
Q: Failed to generate the sample for media type 'application/x-www-form-urlencoded' I recently started creating a ASP.net Web API For some reason I keep receiving this error when viewing the auto generated help documentation: This is for a POST method Samples show up fine for application/json and application/xml I'm not quite sure but the application/-x-www-form-urlencoded keeps showing up I've googled the error quite a bit but can't quite find what might be causing this I truly appreciate any help that can be provided, also please let me know if you have any questions. A: This is an expected behavior. HelpPage sample generation uses the actual formatters present on the HttpConfiguration to 'write' the sample objects. FormUrlEncodedMediaTypeFormatter cannot 'write' any type, hence HelpPage cannot generate samples for it. As a workaround you could explicitly supply a sample for a particular type (as shown in the Areas\HelpPage\App_Start\HelpPageConfig.cs's commented code). config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); A: The answer helped me out but i got bored of writing an example for each type that the system didn't know about... what i ended up doing is this Type[] types = { typeof(MyType), typeof(AnotherType), *add more here* }; foreach(Type t in types) { List<string> propExample = new List<string>(); foreach(var p in t.GetProperties()) { propExample.Add(p.Name + "=value"); } config.SetSampleForType(string.Join("&", propExample), new MediaTypeHeaderValue("application/x-www-form-urlencoded"), t); } Someone could get clever and extend it so that it puts in default values based on type of property but this was enough for my purposes.
{ "pile_set_name": "StackExchange" }
Q: Rxjs call another subscription in pipe and change a varible from root subscription in angular Using another subscription, I want to set a property which comes from a root subscription. So I have a subscription like this: this.repository.getData(`api/cards/list`) .subscribe( res => { this.data = res as EmployeeCard[]; } ); My EmployeeCard model like this: export class EmployeeCard { id: number; employeeId: number; employeeFullName: string; companyId: number; cardId: number; cardNumber: string; currentSpendingLimit: string; limitResetDate: Date; cardUsageStatu: boolean; cardActiveDays: string; balance:string; } So I have to get balance from another api request.This request needs card barcode value. I can get the barcode with calling another request that returns card informations.Card request should be call with cardId value which returns with in EmployeeCard model. So my new subscription should be like this: this.repository.getData(`api/cards/list`) .pipe( //get card information with cardId (needs another request using EmployeeCard cardId property) //get balance using card barcode (needs another http request with using barcode) //set employeecard balance propery //return employeecard model's balance to subscription ) .subscribe( res => { this.data = res as EmployeeCard[]; } ); How can I do this with Rxjs? Thanks A: You have to use switchMap with selector function argument. function getData() { getEmpData() .pipe( switchMap( emp => getBalanlanceInfo(emp.cardId), (emp, balanceInfo) => { /** * Selector function variation of switchMap * perform logic with both source and inner observable values */ emp.balance = balanceInfo.balance; return emp; } ) ) .subscribe(emp => { console.log(emp); // Perform your logic here }); } You can find the complete example here in Stackblitz. More on switchMap can be found here.
{ "pile_set_name": "StackExchange" }
Q: 502 bad gateway on customising wordpress search to include ACF custom taxonomies My requirement is that I have to modify wordpress custom search to include custom taxonomies. You can find below Code that I am using for same in my functions.php. But when I am trying to execute this code on my staging environment URL is http://panolam.staging.wpengine.com/?s=metal I am getting 502 Bad Gateway nginx error. When I checked error logs on wpengine what I found this: PHP Warning: mysqli_query(): MySQL server has gone away in /nas/content/staging/panolam/wp-includes/wp-db.php on line 1931 It shows that some query taking so much time or anything else it can be. I looked for solution for this on google and found that to change the max_allowed_packet to 16M instead of 1M in the my.ini MySQL settings, but I dont want to do this. Can anybody tell what I can improve in my code to prevent this issue? add_filter('posts_join', 'websmart_search_join' ); add_filter('posts_groupby', 'websmart_search_groupby' ); add_filter('posts_where', 'websmart_search_where' ); function websmart_search_join( $join ) { global $wpdb; if( is_search() && !is_admin()) { $join .= "LEFT JOIN $wpdb->postmeta AS m ON ($wpdb->posts.ID = m.post_id) "; } return $join; } function websmart_search_groupby( $groupby ) { global $wpdb; if( is_search() && !is_admin()) { $groupby = "$wpdb->posts.ID"; } return $groupby; } function websmart_search_where( $where ) { global $wpdb, $wp_query; if( is_search() && !is_admin()) { $where = ""; $search_terms = se_get_search_terms(); $n = !empty($wp_query->query_vars['exact']) ? '' : '%'; $searchand = ''; if (count($search_terms) < 1) { // no search term provided: so return no results $search = "1=0"; } else { foreach( $search_terms as $term ) { //$term = esc_sql( like_escape( $term ) ); $term = $wpdb->esc_like( $term ); // Get term by name in Custom taxonomy. $term_details = get_term_by('name', $term, 'pattern_type'); //echo '<pre>'; print_r($term_details) ; die(); $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR (m.meta_value LIKE '{$n}{$term_details->term_id}{$n}'))"; $searchand = ' AND '; } } $where .= " AND ${search} "; $where .= " AND (m.meta_key IN ('pattern_type')) "; $where .= " AND ($wpdb->posts.post_type IN ( 'post', 'page', 'product')) "; $where .= " AND ($wpdb->posts.post_status = 'publish') "; } return $where; } // Code from Search Everywhere plugin function se_get_search_terms() { global $wpdb, $wp_query; $s = isset($wp_query->query_vars['s']) ? $wp_query->query_vars['s'] : ''; $sentence = isset($wp_query->query_vars['sentence']) ? $wp_query->query_vars['sentence'] : false; $search_terms = array(); if ( !empty($s) ) { // added slashes screw with quote grouping when done early, so done later $s = stripslashes($s); if ($sentence) { $search_terms = array($s); } else { preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches); $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]); } } return $search_terms; } A: I have done few of changes to my code , though it seems lot of code but its working fine as per my requirement. add_filter('posts_join', 'websmart_search_join' ); add_filter('posts_groupby', 'websmart_search_groupby' ); add_filter('posts_where', 'websmart_search_where' ); function websmart_search_join( $join ) { global $wpdb; if( is_search() && !is_admin()) { $join .= "LEFT JOIN $wpdb->postmeta AS m ON ($wpdb->posts.ID = m.post_id) "; $join .= "LEFT JOIN $wpdb->term_relationships AS tr ON ($wpdb->posts.ID = tr.object_id) "; $join .= "LEFT JOIN $wpdb->term_taxonomy AS tt ON (tt.term_taxonomy_id=tr.term_taxonomy_id) "; $join .= "LEFT JOIN $wpdb->terms AS t ON (t.term_id = tt.term_id) "; } return $join; } function websmart_search_groupby( $groupby ) { global $wpdb; if( is_search() && !is_admin()) { $groupby = "$wpdb->posts.ID"; } return $groupby; } function websmart_search_where( $where ) { global $wpdb, $wp_query; if( is_search() && !is_admin()) { $where = ""; $search_terms = se_get_search_terms(); $n = !empty($wp_query->query_vars['exact']) ? '' : '%'; $searchand = ''; if (count($search_terms) < 1) { // no search term provided: so return no results $search = "1=0"; } else { foreach( $search_terms as $term ) { //$term = esc_sql( like_escape( $term ) ); $term = $wpdb->esc_like( $term ); // Get term by name in Custom taxonomy. $term_details = get_term_by('name', $term, 'pattern_type'); $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR (m.meta_value LIKE '{$n}{$term_details->term_id}{$n}'))"; $searchand = ' AND '; } } $where .= " AND {$search} "; $where .= " AND (m.meta_key IN ('pattern_type')) "; $where .= " AND ($wpdb->posts.post_type IN ( 'post', 'page', 'portfolio_page', 'product', 'cptbc', 'technical_doc', 'whats_new')) "; $where .= " AND ($wpdb->posts.post_status = 'publish') "; } return $where; } // Code from Search Everywhere plugin function se_get_search_terms() { global $wpdb, $wp_query; $s = isset($wp_query->query_vars['s']) ? $wp_query->query_vars['s'] : ''; $sentence = isset($wp_query->query_vars['sentence']) ? $wp_query->query_vars['sentence'] : false; $search_terms = array(); if ( !empty($s) ) { // added slashes screw with quote grouping when done early, so done later $s = stripslashes($s); if ($sentence) { $search_terms = array($s); } else { preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches); $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]); } } return $search_terms; }
{ "pile_set_name": "StackExchange" }
Q: Parse.com runtime crash - android i am getting a lot of reports from users about my app crashing. The constant error appears to be associated with my parse.com initialisation, however, i have set it up as outlined in the parse tutorial. here is the Stack Trace: java.lang.RuntimeException: Unable to start receiver com.parse.ParseBroadcastReceiver: java.lang.RuntimeException: applicationContext is null. You must call Parse.initialize(context, applicationId, clientKey) before using the Parse library. at android.app.ActivityThread.handleReceiver(ActivityThread.java:2580) at android.app.ActivityThread.access$1700(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397) at android.os.Handler.dispatchMessage(Handler.java:110) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5292) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.RuntimeException: applicationContext is null. You must call Parse.initialize(context, applicationId, clientKey) before using the Parse library. at com.parse.Parse.checkContext(Parse.java:606) at com.parse.Parse.getApplicationContext(Parse.java:214) at com.parse.ManifestInfo.getContext(ManifestInfo.java:322) at com.parse.ManifestInfo.getPackageManager(ManifestInfo.java:330) at com.parse.ManifestInfo.getPackageInfo(ManifestInfo.java:356) at com.parse.ManifestInfo.deviceSupportsGcm(ManifestInfo.java:441) at com.parse.ManifestInfo.getPushType(ManifestInfo.java:210) at com.parse.PushService.startServiceIfRequired(PushService.java:168) at com.parse.ParseBroadcastReceiver.onReceive(ParseBroadcastReceiver.java:19) at android.app.ActivityThread.handleReceiver(ActivityThread.java:2573) ... 10 more and here is my initialisation code: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_screen); Parse.initialize(this, "hGG5RdgNVdI7eCeZynV32lWYXywQRHkpp5zLdY7Q", "TwmNbpBYEt4u3euE3lzNIgwyroSl8RPGF2dJFsPv"); ParseInstallation.getCurrentInstallation().saveInBackground(); Can anybody see what is causing this error, and how to fix it? below is my receiver code: public static class Receiver extends ParsePushBroadcastReceiver { private String notificationText; private Boolean notificationreceived = false; public Receiver(){ } private static final String TAG = "MyNotificationsReceiver"; @Override public void onPushOpen(Context context, Intent intent) { Log.e("Push", "Clicked"); Intent i = new Intent(context, HomeScreen.class); notificationreceived = true; i.putExtra("alert",notificationText); i.putExtra("alertreceived", notificationreceived); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); Scb998.scb988b=true; try { JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data")); Scb998.msg = json.getString("alert"); } catch (JSONException e) { Log.d(TAG, "JSONException: " + e.getMessage()); } } } A: Move you Parse initialization into your App class (extended from Application) public class App extends Application { @Override public void onCreate() { super.onCreate(); Parse.initialize(this, "hGG5RdgNVdI7eCeZynV32lWYXywQRHkpp5zLdY7Q", "TwmNbpBYEt4u3euE3lzNIgwyroSl8RPGF2dJFsPv"); ParseInstallation.getCurrentInstallation().saveInBackground(); } } And of course refer to it your AndroidManifest.xml <application android:name=".app.App" .... </application> Reason of crash is next. When your app is at background, it can be killed by system. From Google guide A process holding an activity that's not currently visible to the user (the activity's onStop() method has been called). These processes have no direct impact on the user experience, and the system can kill them at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and saves its current state, killing its process will not have a visible effect on the user experience, because when the user navigates back to the activity, the activity restores all of its visible state. See the Activities document for information about saving and restoring state. When you app receives push notification, then parse will not be initialized, because you initialize it at activity onCreate method, which won't be called.
{ "pile_set_name": "StackExchange" }
Q: How to prevent ScrollView to hide footer? There is a header and footer on the screen while the center of the screen (Content Area) is occupied by ScrollView. When I start the app, the footer is shown. But, when I click on element "A", it reveals more elements on the screen, pushing other elements below. The ScrollView does make the central part scrollable, but it also hides the footer (a gray LinearLayout on the bottom of the screen). How can I make footer remains on the bottom of the screen? I want Content Area to scroll only. Header and Footer XMLs are outside of the ScrollView element. I tried using RelativeLayout for the footer instead of LinearLayout, but without any success. Here is the look before and after the click on the element "A". I may provide the code, XML and Java, if needed, but it's pretty much of the code. A: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ScrollView android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:fillViewport="true"> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" > </LinearLayout> </ScrollView> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout> </LinearLayout> use weight for layout
{ "pile_set_name": "StackExchange" }
Q: Defining LIMIT by unique number of values Having following SQL query SELECT service_id, service_box_id FROM table1 WHERE 1 LIMIT 10 which results into following table service_id | service_box_id 12 | 1 12 | 2 12 | 3 21 | 1 21 | 2 33 | 1 33 | 2 33 | 3 33 | 4 33 | 5 So, query shows 10 rows, which, in this case, have 3 unique service_id values - 12, 21, 33. Is it possible to define "LIMIT" in query to show 10 unique service_id values, without running another sql query before it? Or any other method which limits output of query. Desired output: service_id | service_box_id 12 | 1 12 | 2 12 | 3 21 | 1 21 | 2 33 | 1 33 | 2 33 | 3 33 | 4 33 | 5 34 | 1 34 | 2 38 | 1 43 | 1 43 | 2 43 | 3 44 | 1 44 | 2 45 | 1 45 | 2 46 | 1 46 | 2 48 | 1 48 | 2 So, 10 unique service_id - 12, 21, 33, 34, 38, 43, 44, 45, 46, 48, but in total 24 rows. A: If I understand correctly you can try to use Distinct with LIMIT in where subquery. SELECT service_id, service_box_id FROM table1 WHERE service_id in ( SELECT service_id FROM ( SELECT Distinct service_id FROM table1 ORDER BY service_id LIMIT 10 ) t1 ) | service_id | service_box_id | | ---------- | -------------- | | 12 | 1 | | 12 | 2 | | 12 | 3 | | 21 | 1 | | 21 | 2 | | 33 | 1 | | 33 | 2 | | 33 | 3 | | 33 | 4 | | 33 | 5 | | 34 | 1 | | 34 | 2 | | 38 | 1 | | 43 | 1 | | 43 | 2 | | 43 | 3 | | 44 | 1 | | 44 | 2 | | 45 | 1 | | 45 | 2 | | 46 | 1 | | 46 | 2 | | 48 | 1 | | 48 | 2 | View on DB Fiddle
{ "pile_set_name": "StackExchange" }
Q: Responsive Google Maps v3 - Cannot get 100% height Been on this for a while now, I need to make the map height 100% of its container. And also keep it centred when its resizing. I have tried nearly all of the examples on here with no avail.. The code example below shows what I am using, there's markers and infowindows in there and also custom marker symbols too. I don't get any errors in the console. <script type="text/javascript"> var markers = [ { "title": 'xxxxx School', "lat": '53.004758', "lng": '-2.241232', "description": '<br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' }, { "title": 'xxxxx Prep', "lat": '51.470123', "lng": '-0.209838', "description": '<br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' }, { "title": 'xxxxxx', "lat": '46.709741', "lng": '9.159625', "description": '<br/><a href="http://www.google.com">View more info</a>', "type": 'Swiss Boarding School' }, { "title": 'xxxxxxx independent College', "lat": '51.512103', "lng": '-0.308055', "description": '83 New Broadway, <br/>London W5 5AL, <br/>United Kingdom <br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' }, { "title": 'xxxxxxx Hill', "lat": '51.007720', "lng": '0.217913', "description": 'Five Ashes, <br/>Mayfield, <br/>East Sussex <br/>TN20 6HR, <br/>United Kingdom <br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' } ]; var map; function initMap() { var mapOptions = { center: new google.maps.LatLng(51.507351, -0.127758), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP, styles: [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}] }; var infoWindow = new google.maps.InfoWindow(); var latlngbounds = new google.maps.LatLngBounds(); var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); var i = 0; var interval = setInterval(function () { var data = markers[i] var myLatlng = new google.maps.LatLng(data.lat, data.lng); var icon = ""; switch (data.type) { case "UK Independent School": icon = "orange"; break; case "Swiss Boarding School": icon = "green"; break; } icon = "http://fokn.temp-dns.com/images/site/icon-" + icon + ".png"; var marker = new google.maps.Marker({ position: myLatlng, map: map, title: data.title, animation: google.maps.Animation.DROP, icon: new google.maps.MarkerImage(icon) }); (function (marker, data) { google.maps.event.addListener(marker, "click", function (e) { infoWindow.setContent("<div style = 'width:200px;min-height:40px'><strong>" + data.title + "</strong><br/>" + data.description + "</div>"); infoWindow.open(map, marker); }); })(marker, data); latlngbounds.extend(marker.position); i++; if (i == markers.length) { clearInterval(interval); var bounds = new google.maps.LatLngBounds(); map.setCenter(latlngbounds.getCenter()); map.fitBounds(latlngbounds); } }, 80); } </script> <div style="width:100%; height:100%;"> <div id="dvMap" style="width:100%; height:100%;"></div> </div> <script async defer src="https://maps.googleapis.com/maps/api/js?key=MY-API&callback=initMap"></script> A: You need to give sizes to all the elements up to the <html> element: html, body, #dvMap { height: 100%; width: 100%; margin: 0px; padding: 0px } Mike Williams' Google Maps Javascript API v2 page on this subject: Using a percentage height for the map div proof of concept fiddle code snippet: var markers = [{ "title": 'xxxxx School', "lat": '53.004758', "lng": '-2.241232', "description": '<br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' }, { "title": 'xxxxx Prep', "lat": '51.470123', "lng": '-0.209838', "description": '<br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' }, { "title": 'xxxxxx', "lat": '46.709741', "lng": '9.159625', "description": '<br/><a href="http://www.google.com">View more info</a>', "type": 'Swiss Boarding School' }, { "title": 'xxxxxxx independent College', "lat": '51.512103', "lng": '-0.308055', "description": '83 New Broadway, <br/>London W5 5AL, <br/>United Kingdom <br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' }, { "title": 'xxxxxxx Hill', "lat": '51.007720', "lng": '0.217913', "description": 'Five Ashes, <br/>Mayfield, <br/>East Sussex <br/>TN20 6HR, <br/>United Kingdom <br/><a href="http://www.google.com">View more info</a>', "type": 'UK Independent School' }]; var map; function initMap() { var mapOptions = { center: new google.maps.LatLng(51.507351, -0.127758), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP, styles: [{ "featureType": "landscape", "stylers": [{ "saturation": -100 }, { "lightness": 65 }, { "visibility": "on" }] }, { "featureType": "poi", "stylers": [{ "saturation": -100 }, { "lightness": 51 }, { "visibility": "simplified" }] }, { "featureType": "road.highway", "stylers": [{ "saturation": -100 }, { "visibility": "simplified" }] }, { "featureType": "road.arterial", "stylers": [{ "saturation": -100 }, { "lightness": 30 }, { "visibility": "on" }] }, { "featureType": "road.local", "stylers": [{ "saturation": -100 }, { "lightness": 40 }, { "visibility": "on" }] }, { "featureType": "transit", "stylers": [{ "saturation": -100 }, { "visibility": "simplified" }] }, { "featureType": "administrative.province", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "elementType": "labels", "stylers": [{ "visibility": "on" }, { "lightness": -25 }, { "saturation": -100 }] }, { "featureType": "water", "elementType": "geometry", "stylers": [{ "hue": "#ffff00" }, { "lightness": -25 }, { "saturation": -97 }] }] }; var infoWindow = new google.maps.InfoWindow(); var latlngbounds = new google.maps.LatLngBounds(); var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); var i = 0; var interval = setInterval(function() { var data = markers[i] var myLatlng = new google.maps.LatLng(data.lat, data.lng); var icon = ""; switch (data.type) { case "UK Independent School": icon = "orange"; break; case "Swiss Boarding School": icon = "green"; break; } icon = "http://maps.google.com/mapfiles/ms/micons/" + icon + ".png"; var marker = new google.maps.Marker({ position: myLatlng, map: map, title: data.title, animation: google.maps.Animation.DROP, icon: icon }); (function(marker, data) { google.maps.event.addListener(marker, "click", function(e) { infoWindow.setContent("<div style = 'width:200px;min-height:40px'><strong>" + data.title + "</strong><br/>" + data.description + "</div>"); infoWindow.open(map, marker); }); })(marker, data); latlngbounds.extend(marker.position); i++; if (i == markers.length) { clearInterval(interval); var bounds = new google.maps.LatLngBounds(); map.setCenter(latlngbounds.getCenter()); map.fitBounds(latlngbounds); } }, 80); } google.maps.event.addDomListener(window, 'load', initMap); html, body, #dvMap { height: 100%; width: 100%; margin: 0px; padding: 0px } <script src="https://maps.googleapis.com/maps/api/js"></script> <div style="width:100%; height:100%;"> <div id="dvMap"></div> </div>
{ "pile_set_name": "StackExchange" }
Q: HTML text with onclicklistener I need to display a string programmatically in a textview with html formatting eg. "find more information"+here" , where "here" can listen to onclick. Is this possible or any other suggestions? A: You can use SpannableString with ClickableSpan. Here is an example. SpannableString span= new SpannableString("Find more information "+here""); ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View textView) { // Perform action here } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }; span.setSpan(clickableSpan, 23, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(span); textView.setMovementMethod(LinkMovementMethod.getInstance());
{ "pile_set_name": "StackExchange" }
Q: Instead of setting height:100%; can I just go height:2000px; I have col-sm-1 and col-sm-9 and col-sm-3. I want them to have a full height. When I do height:100%, the height goes full only when I have contents inside them. I want the height to be full even when it's just empty. So I just did height:2000px; background-color:grey; and now this looks like the way I want. However even a beginner like me know this isn't the best way to do it. Am I allowed to go height:2000px; and deal with it? A: Just use the Flexbox. Assign their parent a class .flexbox, set the CSS as below. .flexbox .col { flex: 1; }
{ "pile_set_name": "StackExchange" }
Q: Illegal start of a expression JAVA constant.java:31: error: illegal start of expression min = sNum.chars().map(c -> c-'0').toArray(); ^ 1 error I uploaded my code to a page where it gives you a problem and you upload it and checks that it does what it should. I'm using Apache Netbeans IDE 11.1 and gives me no error but the page gives me this error. I'm new in JAVA and I do not fully understand it. Could someone explain me why this is happening and how could I fix this? My code pretty much starts like this, it just asks for a number then calls a function that does this to put the number entered to array. A: The code is completely fine. You should change your language settings in your IDE. Your language level must be set below 8 and therefor the old compiler doesn't understand lambdas.
{ "pile_set_name": "StackExchange" }
Q: How to rank sql query I have a set of results that I want to rank: I am not sure what to partition by. Query: SELECT DISTINCT TFormSectionID AS FormSectionID, TFSSortOrder AS SectionSortOrder, TSectionItemID AS SectionItemID, TrendType FROM Report.TrendData WHERE (ProgramID = 1) AND (TrendType > 0) AND tformid = 34 AND TFormSectionID = 12 Results: FormSectionID SectionSortOrder SectionItemID TrendType 12 7 90 1 12 7 91 1 12 7 154 1 12 7 528 1 12 9 154 1 12 9 528 1 I want the results with section sort order 9 to be ranked as 2 and the section sort order 7 to be ranked as 1 A: It seems like you can get what you want using DENSE_RANK: SELECT DISTINCT TFormSectionID AS FormSectionID, TFSSortOrder AS SectionSortOrder, TSectionItemID AS SectionItemID, TrendType, DENSE_RANK() OVER (ORDER BY SectionSortOrder) AS rn FROM Report.TrendData WHERE (ProgramID = 1) AND (TrendType > 0) AND tformid = 34 and TFormSectionID = 12
{ "pile_set_name": "StackExchange" }
Q: How many comment votes do we each get in a day? Today I ran out of comment votes, I did not even know this could happen. This is not attached to my Q&A votes, I still have 10 of them left. So I can make sure I don't waste my votes, it was annoying not to be able to vote on an important comment, how many do I get? A: According to How does comment voting and flagging work? over on Meta Stack Exchange you get 30 comment upvotes per UTC day: Comment votes ... You get 30 comment upvotes per day.
{ "pile_set_name": "StackExchange" }
Q: Almeno and perlomeno Collins Dictionary, and others I have checked, translate almeno and perlomeno as at least. It seems to me that the two words are used interchangeably in Italian writing. Am I missing any nuances? A: The Treccani dictionary indicates perlomeno as a synonym of almeno and viceversa, the two words can be used interchangeably. almeno /al'meno/ avv. [grafia unita della locuz. al meno]. - 1. [se non altro, se non di più: concedimi a. questo; vale a. mille euro] ≈ a dir poco, come minimo, perlomeno, quanto meno perlomeno /perlo'meno/ (o per lo meno) avv. [grafia unita di per lo meno]. - 1. [con valore restrittivo: il paese più vicino dista p. quindici chilometri] ≈ a dir poco, almeno, al minimo, quanto meno. 2. [con valore limitativo: era molto seccato, o p. così mi sembrava] ≈ almeno, quanto meno, se non altro. In the definition of almeno: Vale almeno/perlomeno mille euro It's worth at least a thousand euro In the definition of perlomeno: Il paese più vicino dista perlomeno/almeno quindici chilometri The nearest village is at least fifteen kilometers far.
{ "pile_set_name": "StackExchange" }
Q: Excel VBA - worksheet.calculate doesn't calculate all of my formulas Private Sub Worksheet_Activate() If Worksheets("Input").Range("S5").Value = "Yes" Then MsgBox "Please make sure you've completed the historical deductible amounts for EL" End If Worksheets("Input").Calculate Worksheets("EL").Calculate Worksheets("PPL").Calculate Worksheets("Auto").Calculate Worksheets("AL").Calculate Worksheets("APD").Calculate Worksheets("Loss Layering").Calculate Worksheets("Sheet2").Calculate Worksheets("Premium").Calculate End Sub In an effort to speed up a very large workbook I have switched off auto calculate and have created a hierarchy in which I calculate sheets as I move through my workbook. My issue is that with any heavy duty formulas such as sumif or sumproduct, the values are not calculated within my active sheet, they stay as zeroes. I have tried application.calculate and CalculateFull, these both work but I find they take up way too much time. I'm trying to find a way to do this while keeping my template as quick, simple and user friendly as possible. Any suggestions? A: It is not clear which worksheet is the active sheet and contains this code, but I can think of 2 possible reasons for your problem. 1) You have not called worksheet.calculate on the active sheet. 2) Since worksheet.calculate ignores dependencies on other worksheets the calculation sequence you are using will only work as you want if the formulas on the sheets always refer to other sheets that have already been calculated. In other words the sheet calculation sequence must exactly match the inter-sheet references sequence and there must be NO forward inter-sheet references whatsoever (including defined names etc). as a general point I would not usually expect using worksheet.calculate to calculate an entire workbook would be faster than using Application.Calculate (although I am sure sometimes It will be faster)
{ "pile_set_name": "StackExchange" }
Q: Resized ubuntu partition not showing properly in VMWare I have installed ubuntu 14.04 in windows under vmware workstation 11. I ran out of diskspace on the VM (I had it set it to 30GB). Within the VM Properties - I have expanded the diskspace to 60GB. I ran gparted on boot and resized the partition /dev/sda2 (ext) to use the unallocated space. and then resize /dev/sda5 (lvm) to take up the space. When I rebooted the VM I ran df -h and it not showing the proper diskspace increase. Filesystem Size Used Avail Use% Mounted on /dev/mapper/ubuntu--vg-root 26G 14G 11G 56% / none 4.0K 0 4.0K 0% /sys/fs/cgroup udev 2.0G 4.0K 2.0G 1% /dev tmpfs 394M 3.3M 391M 1% /run none 5.0M 0 5.0M 0% /run/lock none 2.0G 0 2.0G 0% /run/shm none 100M 0 100M 0% /run/user /dev/sda1 236M 78M 146M 35% /boot I have ran lvextend --size +30G /dev/mapper/ubuntu--vg-root - then lvdisplay --- Logical volume --- LV Path /dev/ubuntu-vg/root LV Name root VG Name ubuntu-vg LV UUID wCuSu5-h5eH-3Gvy-IB9N-F1CE-Vrv7-jD6jHm LV Write Access read/write LV Creation host, time ubuntu, 2015-06-16 11:09:09 -0400 LV Status available # open 1 LV Size 55.76 GiB Current LE 14274 Segments 2 Allocation inherit Read ahead sectors auto - currently set to 256 Block device 252:0 I have rebooted. Still no volume change. I'm lost. A: The step you've missed is that after you've resized the Logical Volume, you need to then resize the filesystem that is in that LV. For ext[234] filesystems, you can do this "online" (with the filesystem mounted) by running ext2resize /dev/ubuntu-vg/root If the LV is formatted with another filesystem, check its documentation for the correct way to resize it.
{ "pile_set_name": "StackExchange" }
Q: omniauth OAuthException & OAuth::Unauthorized I have installed omniauth 1.0. Also I have oauth-0.4.5, oauth2-0.5.1, omniauth-facebook-1.0.0, omniauth-twitter-0.0.6. omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do provider :developer unless Rails.env.production? provider :facebook, ENV['167257285348131'], ENV['c8c722f697scb2afcf1600286c6212a9'], :scope => 'email,offline_access,read_stream', :display => 'popup' provider :twitter, ENV['fma2L22ObJCW52QrL7uew'], ENV['4aZfhCAOdiS7ap8pHJ7I1OZslFwVWWLiAMVpYUI'] end session_controller.rb class SessionsController < ApplicationController require 'omniauth-facebook' require 'omniauth-twitter' require 'omniauth' def create @user = User.find_or_create_from_auth_hash(auth_hash) self.current_user = @user redirect_to '/' end def auth_hash request.env['omniauth.auth'] end end Also I add 'omniauth' 'omniauth-facebook' 'omniauth-twitter' gems to gemfile There are two problems: When I go http://localhost:3000/auth/facebook I get { "error": { "message": "Missing client_id parameter.", "type": "OAuthException" } } And the link graph.facebook.com/oauth/authorize?response_type=code&client_id=&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Ffacebook%2Fcallback&parse=query&scope=email%2Coffline_access%2Cread_stream&display=popup And there is no client_id!!! When I go to http://localhost:3000/auth/twitter I get OAuth::Unauthorized 401 Unauthorized Any ideas? A: Alex D. is correct in that the ENV[] breaks it. To create omniauth.rb so that it uses different keys in different environments just put: provider :twitter, TWITTER_KEY, TWITTER_SECRET in omniauth.rb and then in your environment config files (config/environments/development.rb, etc.) put the key you want to use for that environment. config/environments/development.rb: TWITTER_KEY = 'aaaaaaa' TWITTER_SECRET = 'aaaabbbbbb' config/environments/production.rb: TWITTER_KEY = 'ccccccc' TWITTER_SECRET = 'ccccdddddd'
{ "pile_set_name": "StackExchange" }
Q: C++ class exposed to QML error in fashion TypeError: Property '...' of object is not a function I've successfully exposed a C++ class to QML. It is registered and found in Qt Creator. It's purpose is to connect to a database, as shown in following code: #ifndef UESQLDATABASE_H #define UESQLDATABASE_H #include <QObject> #include <QtSql/QSqlDatabase> class UeSqlDatabase : public QObject { Q_OBJECT Q_PROPERTY(bool m_ueConnected READ isConnected WRITE setConnected NOTIFY ueConnectedChanged) private: bool m_ueConneted; inline void setConnected(const bool& ueConnected) { this->m_ueConneted=ueConnected; } public: explicit UeSqlDatabase(QObject *parent = 0); Q_INVOKABLE inline const bool& isConnected() const { return this->m_ueConneted; } ~UeSqlDatabase(); signals: void ueConnectedChanged(); public slots: void ueConnectToDatabase (const QString& ueStrHost, const QString& ueStrDatabase, const QString& ueStrUsername, const QString& ueStrPassword); }; #endif // UESQLDATABASE_H However, when I try to call method isConnected() from the following QML code import QtQuick 2.0 Rectangle { id: ueMenuButton property string ueText; width: 192 height: 64 radius: 8 states: [ State { name: "ueStateSelected" PropertyChanges { target: gradientStop1 color: "#000000" } PropertyChanges { target: gradientStop2 color: "#3fe400" } } ] gradient: Gradient { GradientStop { id: gradientStop1 position: 0 color: "#000000" } GradientStop { position: 0.741 color: "#363636" } GradientStop { id: gradientStop2 position: 1 color: "#868686" } } border.color: "#ffffff" border.width: 2 antialiasing: true Text { id: ueButtonText color: "#ffffff" text: qsTr(ueText) clip: false z: 0 scale: 1 rotation: 0 font.strikeout: false anchors.fill: parent font.bold: true style: Text.Outline textFormat: Text.RichText verticalAlignment: Text.AlignVCenter horizontalAlignment: Text.AlignHCenter font.pixelSize: 16 } MouseArea { id: ueClickArea antialiasing: true anchors.fill: parent onClicked: { uePosDatabase.ueConnectToDatabase("127.0.0.1", "testDb", "testUser", "testPassword"); if(uePosDatabase.isConnected()==true) { ueMenuButton.state="ueStateSelected"; } else { ueMenuButton.state="base state" } } } } I get the following error: qrc:/UeMenuButton.qml:92: TypeError: Property 'isConnected' of object UeSqlDatabase(0x1772060) is not a function What am I doing wrong? A: You have this error because you have declared the property isConnected in C++ but you're calling it from QML in the wrong way: uePosDatabase.isConnected is the correct way, not uePosDatabase.isConnected(). If you want to call the function isConnected() you should change its name to differate it from the property, like getIsConnected(). Given your property declaration, you neither need to call this function directly nor you need to make it callable from QML with the Q_INVOKABLE macro.
{ "pile_set_name": "StackExchange" }
Q: fxml giving url is not registered resource error in intellij Hi I'm new to javafx fxml, but the following line is giving me an error stating url is not registered. <VBox xmlns:fx="http://javafx.com/fxml"> That is directly from the oracle tutorial. A: I'm guessing that IntelliJ is looking for an XSD file at that URL, but it isn't finding one. Open Preferences and go to Languages and Frameworks > Schemas and DTDs. Under "Ignored Schemas and DTDs", add "http://javafx.com/fxml".
{ "pile_set_name": "StackExchange" }
Q: HTML5 Canvas Text Stroke for Large Font Size Not Drawn Properly I want to write a large text on HTML5 canvas with a red border color (stroke color) and green fill color. I give the stroke width to 5px. It was fine when I set the font size to less than 260px. Here is my first code http://jsfiddle.net/8Zd7G/: var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.font="240px Calibri"; ctx.strokeStyle = "F00"; //Red ctx.fillStyle = "0F0"; //Green ctx.lineWidth = 5; ctx.fillText("Big smile!",0,200); ctx.strokeText("Big smile!",0,200); But when I set the font size to larger or equal than 260 px, the text border/stroke is not properly colored. It just had a red border not filled by red color. Here is my second code http://jsfiddle.net/Pdr7q/: var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.font="260px Calibri"; ctx.strokeStyle = "F00"; ctx.fillStyle = "0F0"; ctx.lineWidth = 5; ctx.fillText("Big smile!",0,200); ctx.strokeText("Big smile!",0,200); My question is how to get the proper text stoke fill with a large font size (like the first picture rather than the second one)? Thanks in advance :) A: It's a known issue with Chrome where font sizes are above 256 pixels (incl. scaling): https://code.google.com/p/chromium/issues/detail?id=280221 At the moment there does not seem to be a solution for the issue but follow the thread (link above) to see status at a later time (last update 25. Oct). You can reduce the problem by reducing line-width although the problem will still be there. Another option is to draw half the size (so that size < 256) into a temporary canvas, then draw this canvas into the main scaled to the size you need. It will make the text more blurry but it will look better than the curly version I believe. Firefox has a related bug (misalignment at big sizes): https://bugzilla.mozilla.org/show_bug.cgi?id=909873
{ "pile_set_name": "StackExchange" }
Q: How do I properly print a multi-line variable in an e-mail sent from a BASH script? I have a BASH script that runs various sysadmin functions and system checks. If a check fails, a variable is set to 1. There are only a couple types of errors that can happen, so I have variables named to describe the error such as $login_error and $timeout. At the end of the script, if an error was encountered, an e-mail is sent to my team. In the e-mail, I include a brief error message describing what the error was. The problem I'm getting is that the error messages contain a \n character, but my embedded e-mail doesn't preserve the newlines. I'll show you what I mean. Here's the function that checks for failures and e-mails me: checkFailure () { if [[ $error_encountered -eq 1 ]]; then [[ $timeout -eq 1 ]] && msg="Error 1: The device timed out\n" [[ $login_error -eq 1 ]] && msg="${msg}Error 2: Failed to login to device\n" [[ $sky_fall -eq 1 ]] && msg="${msg}Error 3: The sky is falling\n" { /usr/bin/nc <ip_of_my_sendmail_box> << EOF mail from: [email protected] rcpt to: [email protected] data to: [email protected] subject: Error during systems check Content-Type: text/plain $(printf "%b" "$msg") Sent on: $(date) . quit EOF } 1>/dev/null } Now, every thing here works as intended except that the newlines in $msg get seemingly stripped from my e-mail. If I wasn't e-mailing this text, then printf will happily interpret the newlines and show me two lines with text. Let's say that an error 1 and an error 2 happened, I'll get this in my e-mail: Error 1: The device timed outError 2: Failed to login to device Why no new line? If I change the $msg texts to have two \n\n characters at the end, like so: [[ $timeout -eq 1 ]] && msg="Error 1: The device timed out\n\n" [[ $login_error -eq 1 ]] && msg="${msg}Error 2: Failed to login to device\n\n" then I get this in the e-mail: Error 1: The device timed out Error 2: Failed to login to device Notice the extra new line between them now. Does anyone know why I either get no newline or two newlines, but never the desired one newline. A: Try ANSI-C quoting: msg="" [[ $timeout -eq 1 ]] && msg+=$'Error 1: The device timed out\n' [[ $login_error -eq 1 ]] && msg+=$'Error 2: Failed to login to device\n' [[ $sky_fall -eq 1 ]] && msg+=$'Error 3: The sky is falling\n'
{ "pile_set_name": "StackExchange" }
Q: Python pandas - blank out entire cell if part of text matches pattern Is it possible to blank out the entire content of a cell in a csv column if some of it's text matches a pattern list, and then output the result to a csv? I can replace the matched text with blank but would like to replace the whole cell with blank (NOT deleting the row). csv raw data looks like this: date id subject description 9/1/19 342 New customer message 5:23 p.m. blah blah blah 9/4/19 356 need more info blah blah blah 9/7/19 378 SCRUBBED review blah blah blah import pandas as pd df = pd.read_csv('C:/Documents/sample.csv', 'r', encoding = 'ISO-8859-1', delimiter=',', usecols=[2]) pattern = '|'.join(['SCRUBBED','New customer message’, 'HELLO']) df['subject'] = df['subject'].str.replace(pattern, '') df.to_csv('C:/Documents/sample_removed.csv', encoding = 'ISO-8859-1', index=False) Expected result is: date id subject description 9/1/19 342 blah blah blah 9/4/19 356 need more info blah blah blah 9/7/19 378 blah blah blah A: The problem here is with your regex. If you replace the line: pattern = '|'.join(['SCRUBBED','New customer message’, 'HELLO']) with: pattern = '.*' + '.*|.*'.join(['SCRUBBED','New customer message’, 'HELLO']) + '.*' It should work. str.replace will only replace the matched part of string, by adding .* to the front and end of your target text it will now match the whole cell (this might do unwanted things like replace the line "OTHELLO" with "" since it contains "HELLO", in this case you need to think more carefully about your regex).
{ "pile_set_name": "StackExchange" }
Q: Flatten array-valued properties up into their single element value In my Node.js app, I have some ugly data: {"rn":["801"],"destSt":["30089"],"destNm":["95th/Dan Ryan"],"trDr":["5"],"nextStaId":["41430"],"nextStpId":["30276"],"nextStaNm":["87th"],"prdt":["20151003 12:36:48"],"arrT":["20151003 12:38:48"],"isApp":["0"],"isDly":["0"],"flags":[""],"lat":["41.75042"],"lon":["-87.62518"],"heading":["179"]} As you can see, each object property inexplicably contains an array with the value that should be directly the value of that propety. I'd like to move everything up one level so that it looks like: {"rn":"801","destSt":"30089","destNm":"95th/Dan Ryan"} (etc) In no case will any of those arrays contain any more than one value. What's the best way to do this? I've tried underscore's flatten to no avail. And I'm not sure how to go about Googling this. :) A: I may have misled about the sophistication of the data (I assumed I could just for-each into each one and pick things out.) Really my data is set of routes which contains an set of trains which contain properties. The data I posted was just the data from train one one route. So I did this: _.each(routes,function(route, rt_index, list) { _.each(route, function (train, train_index,list){ _.each(train, function (property, property_index,list){ routes[rt_index][train_index][property_index] = property[0]; }); }); }); Though I'm sure there's a cleaner way.
{ "pile_set_name": "StackExchange" }
Q: "The Parameter Is Incorrect" MFC exception This is native C++. No .NET framework involved. I am trying to figure out which exception is thrown when the CListBox gets an invalid parameter. Turns out MFC uses this exception quite a lot but I can't determine the actual exception type thrown. I have tried a lot of different types on the catch (int, const char , std:) but the only one besides catch(...) that catches it is the (const void *). Looking the memory structure, I still don't have a clue what is actually thrown. Does any one know what it is or how to determine what it thrown? This is a sample MFC application. ListBox is a CListBox. The application is nothing more than the default DialogBox based MFC application that VS builds automatically. The only change is that I added a list box and the code you see below in the OK button handler. void CMFCApplication1Dlg::OnBnClickedOk() { try { CString Value; ListBox.GetText( -1, Value ); Value = "none"; } catch ( CException & exception ) { exception.Delete(); } catch ( const void * e ) { } catch (...) { } CDialogEx::OnOK(); } A: To explain why you get the exception, it looks like when you use the CString version of CListBox::GetText() it will throw an E_INVALIDARG exception if the passed index is not valid. Tracing through the MFC code is a bit of work but CListBox::GetText() looks like: void CListBox::GetText(int nIndex, CString& rString) const { ASSERT(::IsWindow(m_hWnd)); GetText(nIndex, rString.GetBufferSetLength(GetTextLen(nIndex))); rString.ReleaseBuffer(); } CListBox::GetTextLen(-1) will return LB_ERR which is -1. If you follow the code for CString::GetBufferSetLength() you eventually end up in CString::SetLength(): void SetLength(_In_ int nLength) { ATLASSERT( nLength >= 0 ); ATLASSERT( nLength <= GetData()->nAllocLength ); if( nLength < 0 || nLength > GetData()->nAllocLength) AtlThrow(E_INVALIDARG); GetData()->nDataLength = nLength; m_pszData[nLength] = 0; } with nLength == -1 and thus the exception.
{ "pile_set_name": "StackExchange" }
Q: On DataGridView CellDoubleClick Return Data From Another Row My method: private void dgvProveedores_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { _tbProveedorCodigo.Text = dgvProveedores.SelectedCells[0].Value.ToString(); _tbProveedorNombre.Text = dgvProveedores.SelectedCells[1].Value.ToString(); _indice.Text = dgvProveedores.SelectedCells[2].Value.ToString(); _grid.Visible = false; this.Close(); } Row Example: CODE Name index | 012 | AVIPECUARIA | 3 | But Return: | 012 | HECTOR JAVIER |214| THIS DATA EXIST WITH THIS CODE: | PM012 | HECTOR JAVIER |214| This code works on all DB that i tested, but i found this issue on this. A: Your code works with selected cells which can cause the issue. Try alternative solution and use 'e' argument property: private void dgvProveedores_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; _tbProveedorCodigo.Text = dgvProveedores.Rows[e.RowIndex].Cells["Codigo"].Value.ToString(); _tbProveedorNombre.Text = dgvProveedores.Rows[e.RowIndex].Cells["Nombre"].Value.ToString(); _indice.Text = dgvProveedores.Rows[e.RowIndex].Cells["Indice"].Value.ToString(); } I used column names inside Cells brackets. You should use your column names. If there are null values in the grid cells it should be properly handled to avoid null reference exception.
{ "pile_set_name": "StackExchange" }
Q: regex starting with number 5 looking for help applying a regex function that finds a string that starts with 5 and is 7 digits long. this is what i have so far based on my searches but doesn't work: import re string = "234324, 5604020, 45309, 45, 55, 5102903" re.findall(r'^5[0-9]\d{5}', string) not sure what i'm missing. thanks A: You are using a ^, which asserts position at the start of the string. Use a word boundary instead. Also, you don't need both the [0-9] and the \d. Use \b5[0-9]{6}\b (or \b5\d{6}\b) instead: >>> re.findall(r'\b5\d{6}\b', s) ['5604020', '5102903'] A: The ^ at the start of the regular expression forbids any matches that aren't at the very beginning of the string. Replacing it with a negative lookbehind for \d to match non-digits or the beginning, and add a negative lookahead to forbid extra following digits: import re string = "234324, 5604020, 45309, 45, 55, 5102903" re.findall(r'(?<!\d)5\d{6}(?!\d)', string)
{ "pile_set_name": "StackExchange" }
Q: Magento 2 : Swatches not display when use plugin around I used around plugin to call custom phtml in category list page. It's working proper. But, In configurable product it's hide to display swatches. I upload here my files code. Which function should I need to use in plugin to working perfectly ? di.xml : <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Catalog\Block\Product\ListProduct"> <plugin name="custom-module-category" type="Vendor\Module\Plugin\File" sortOrder="16"/> </type> <virtualType name="Magento\CatalogSearch\Block\SearchResult\ListProduct"> <plugin name="custom-module-search" type="Vendor\Module\Plugin\File" sortOrder="17" /> </virtualType> </config> File.php : public function aroundGetProductDetailsHtml( \Magento\Catalog\Block\Product\ListProduct $subject, \Closure $proceed, \Magento\Catalog\Model\Product $product ) { $data = $this->_productDocFactory->create()->load($product->getId(), 'product_id'); if(count($data->getData())){ return $this->layout->createBlock('Vendor\Module\Block\File')->setProduct($data_id)->setTemplate('Vendor_Module::file.phtml')->toHtml(); } else { return ''; } } A: You didn't anything in else condition. So, it was display blank. Use this below code : public function aroundGetProductDetailsHtml( \Magento\Catalog\Block\Product\ListProduct $subject, \Closure $proceed, \Magento\Catalog\Model\Product $product ) { $data = $this->_producyFactory->create()->load($product->getId(), 'product_id'); if (count($data->getData())) { return $this->layout->createBlock('Vendor\Module\Block\File')->setProduct($data)->setTemplate('Vendor_Module::file.phtml')->toHtml(); } else { $result = $proceed($product); return $result; } }
{ "pile_set_name": "StackExchange" }
Q: Force user to fill in at least text area or file A registered user is creating a node with a body and file field. I want to force the user to either fill the body with 300 chars or select a file. At least one needs to be selected/filled. How can I do it? Can I do this using the Rules module? A: I don't know how you could achieve this with rules. You could however create a small custom module that adds a form validation function to the node edit form. The validator would check that the appropriate conditions are met. Edit: something like this would work I think for content type page. /** * Implements hook_form_FORM_ID_alter for page_node_form. * * @see module_validate */ function module_form_page_node_form_alter(&$form, &$form_state) { $form['#validate'][] = 'module_validate'; } /** * Form validator for page_node_form. */ function module_validate($form, &$form_state) { // This strips HTML tags - to disable, remove the filter_xss() call. $body_length = drupal_strlen(filter_xss($form_state['values']['body'], array())); // We're assuming the field is called 'file' and we're checking the first file. $file = $form_state['values']['field_file'][0]; // Rather than checking against 300, we should perhaps call node_get_types() // and find the configured word limit. if (body_length < 300 && !$file['fid']) { form_set_error('body', t('Please ensure that you either enter 300 characters into the body field, or upload a file.')); } }
{ "pile_set_name": "StackExchange" }
Q: Is there an inject equivalent for Haskell in the context of free monads I'm trying to translate this Scala's cats example about composing free monads. The gist of the example seems to be the decomposition of separate concerns into separate data types: data Interact a = Ask (String -> a) | Tell String a deriving (Functor) data DataOp = AddCat String | GetAllCats [String] deriving (Functor) type CatsApp = Sum Interact DataOp Without having these two separate concerns, I would build the "language" for Interact operations as follows: ask :: Free Interact String ask = liftF $ Ask id tell :: String -> Free Interact () tell str = liftF $ Tell str () However, if I want to use ask and tell in a program that also uses DataOp I cannot define them with the types above, since such a program will have type: program :: Free CatsApp a In cats, for the definition of the tell and ask operations they use an InjectK class, and an inject method from Free: class Interacts[F[_]](implicit I: InjectK[Interact, F]) { def tell(msg: String): Free[F, Unit] = Free.inject[Interact, F](Tell(msg)) def ask(prompt: String): Free[F, String] = Free.inject[Interact, F](Ask(prompt)) } What puzzles me is that somehow the positional information of the functors (DataOp is on the left, Interact is on the right) seems to be irrelevant (which is quite nice). Are there similar type-classes and functions that could be used to solve this problem in an elegant manner using Haskell? A: This is covered in Data Types à la Carte. The Scala library you demonstrated looks like a fairly faithful translation of the original Haskell. The gist of it is, you write a class representing a relationship between a functor sup which "contains" a functor sub: class (Functor sub, Functor sup) => sub :-<: sup where inj :: sub a -> sup a (These days you might use a Prism, because they can both inject and project.) Then you can use the usual technique of composing the base functors of your free monads using the functor coproduct, implement :-<: for the two cases of Sum, instance Functor f => f :-<: f where inj = id instance (Functor f, Functor g) => f :-<: (Sum f g) where inj = InL instance (Functor f, Functor g, Functor h, f :-<: g) => f :-<: (Sum h g) where inj = InR . inj and make instruction sets composable by abstracting over the base functor. ask :: Interact :-<: f => Free f String ask = liftF $ inj $ Ask id tell :: Interact :-<: f => String -> Free f () tell str = liftF $ inj $ Tell str () addCat :: DataOp :-<: f => String -> Free f () addCat cat = liftF $ inj $ AddCat cat () getCats :: DataOp :-<: f => Free f [String] getCats = liftF $ inj $ GetCats id Now you can write a program which uses both Interact and DataOp without making reference to a particular sum type. myProgram :: (Interact :-< f, DataOp :-< f) => Free f () myProgram = ask >>= addCat None of this is particularly better than the standard MTL approach, though.
{ "pile_set_name": "StackExchange" }
Q: How to specify a message on a method "throws" in Java? Im trying to return a JOptionePane message dialog for each one of the possible throws on my method: public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException{ ... content ... } Is there any way to do this? A: You could try something like : public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException { try { ...content... } catch(FileNotFoundException fnfEx) { throw new FileNotFoundException("File was not found"); } catch(IOException ioEx) { throw new FileNotFoundException("I/O exception"); } catch(InvalidFormatException invEx) { throw new FileNotFoundException("Invalid format errror"); } } Where you put the message you want in the new exceptions and you print the exception message in the JOptionPane.
{ "pile_set_name": "StackExchange" }
Q: "@" sign in startup commands In my ~/.config/lxsession/LXDE/autostart file I have lines like: @lxpanel --profile LXDE @pcmanfm --desktop --profile LXDE Other lines (that I added using the Preferences/Default Applications for LX Session/Autostart menu) are not prefaced with the @. What does the @ do? A: From LXDE Lxsession: Each line in ~/.config/lxsession/LXDE/autostart represents a command to be executed. If a line starts with @, and the command following it crashes, the command is automatically re-executed.
{ "pile_set_name": "StackExchange" }
Q: Calories in (cooked) pasta I bought a 500g pack of Tesco penne pasta recently – https://www.tesco.com/groceries/en-GB/products/254878482 As you can see on the website, it states that 100g of the pasta contains around 176 calories. But after cooking the pasta, I noticed it weighed a lot more. I found that around 1/6 of the pack weighed around 225g instead of the 80 or so grams that I was expecting. So when the packet states the nutritional information for 100g of the pasta, is it referring to cooked or uncooked pasta? I imagine it is referring to 100g of cooked pasta... I'm hoping that's the case anyway, I want as many calories as possible. A: The best way to be confident is to check some clear nutrition facts directly. The USDA reports that "Pasta, dry, unenriched" has 371 calories per 100g, and "Pasta, cooked, unenriched, without added salt" has 158 calories per 100g. So your 176 calories per 100g seems to be for cooked pasta; it's way too few calories for 100g dry, even if your pasta is slightly different from the USDA's default. Calories per gram when cooked is going to vary a bit, because if you cook it a bit more or less, it'll take on a bit more or less water. So the same amount of dry pasta, with the same amount of calories, may weigh slightly different amounts. Also, I looked at the page you linked. Down at the bottom it says: When cooked according to instructions. 75g of uncooked pasta weighs approximately 170g when cooked. And indeed, along with per 100g nutrition facts, it has a per 170g column. So yes, it appears that those nutrition facts are for cooked pasta.
{ "pile_set_name": "StackExchange" }
Q: d3: color a line based on another dataset I would like to color a rectangle by the value of a dataset. Here is an example where I plot a sine-wave and color the line by the y-value (from red to blue as the y-value changes from 1 to -1). What I would like is to have a bar that is colored by that y-value. Here is a fiddle: https://jsfiddle.net/sanandak/m2jryr22/11/ (apologies for my prior post where the fiddle was missing!) var svg = d3.select('body').append('svg') svg.attr('width', 300).attr('height', 300) data = d3.range(0, 2 * Math.PI, 0.1) .map(function(t) { return { x: t, y: Math.sin(t) }; }); var xScale = d3.scaleLinear() .domain([0, 2 * Math.PI]) .range([10, 290]) var yScale = d3.scaleLinear() .domain([-1, 1]) .range([150, 10]) var line = d3.line() .x(function(d, i) { return xScale(d.x); }) .y(function(d, i) { return yScale(d.y); }); svg.append("linearGradient") .attr("id", "line-gradient") .attr("gradientUnits", "userSpaceOnUse") .attr("x1", 0).attr("y1", yScale(-1)) .attr("x2", 0).attr("y2", yScale(1)) .selectAll("stop") .data([{ "offset": "0%", color: "blue" }, { "offset": "100%", color: "red" }]) .enter() .append("stop") .attr("offset", function(d) { return d.offset; }) .attr("stop-color", function(d) { return d.color; }) svg.append('g') .datum(data) .append('path') .attr('d', line) .attr('class', 'line') .attr('stroke', 'url(#line-gradient)') svg.append('g') .datum(data) .append('rect') .attr('x', 10) .attr('y', 160) .attr('width', 280) .attr('height', 20) .attr('fill', 'url(#line-gradient)') A: I understand now. I would define a complex gradient matching your y values across the x domain: var c = d3.scaleLinear() .domain([-1,1]) .range(['blue', 'red']) svg.append("linearGradient") .attr("id", "line-gradient2") .attr("gradientUnits", "userSpaceOnUse") .attr("x1", 10).attr("y1", 0) .attr("x2", 280).attr("y2", 0) .selectAll("stop") .data(data) .enter() .append('stop') .attr('stop-color', function(d){ return c(d.y); }) .attr('offset',function(d){ return (d.x/xScale.domain()[1] * 100) + '%'; }); Here's it is in action: var svg = d3.select('body').append('svg') svg.attr('width', 300).attr('height', 300) data = d3.range(0, 2 * Math.PI, 0.1) .map(function(t) { return { x: t, y: Math.sin(t) }; }); var xScale = d3.scaleLinear() .domain([0, 2 * Math.PI]) .range([10, 290]) var yScale = d3.scaleLinear() .domain([-1, 1]) .range([150, 10]) var line = d3.line() .x(function(d, i) { return xScale(d.x); }) .y(function(d, i) { return yScale(d.y); }); svg.append("linearGradient") .attr("id", "line-gradient") .attr("gradientUnits", "userSpaceOnUse") .attr("x1", 0).attr("y1", yScale(-1)) .attr("x2", 0).attr("y2", yScale(1)) .selectAll("stop") .data([{ "offset": "0%", color: "blue" }, { "offset": "100%", color: "red" }]) .enter() .append("stop") .attr("offset", function(d) { return d.offset; }) .attr("stop-color", function(d) { return d.color; }) var c = d3.scaleLinear() .domain([-1,1]) .range(['blue', 'red']) svg.append("linearGradient") .attr("id", "line-gradient2") .attr("gradientUnits", "userSpaceOnUse") .attr("x1", 10).attr("y1", 0) .attr("x2", 280).attr("y2", 0) .selectAll("stop") .data(data) .enter() .append('stop') .attr('stop-color', function(d){ return c(d.y); }) .attr('offset',function(d){ return (d.x/xScale.domain()[1] * 100) + '%'; }); svg.append('g') .datum(data) .append('path') .attr('d', line) .attr('class', 'line') .attr('stroke', 'url(#line-gradient)') svg.append('g') .datum(data) .append('rect') .attr('x', 10) .attr('y', 160) .attr('width', 280) .attr('height', 20) .attr('fill', 'url(#line-gradient2)') var rWidth = 280 / (data.length -1); svg.append('g') .selectAll('rect') .data(data) .enter() .append('rect') .attr('x', function(d) {return xScale(d.x);}) .attr('y', 200) .attr('width', rWidth) .attr('height', 20) .attr('stroke', 'none') .attr('fill', function(d) {return c(d.y);}) .line { fill: none; stroke-width: 2; } <script src="//d3js.org/d3.v4.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: menu no Wordpress com 3 níveis Eu quero construir um menu no Wordpress com 3 níveis. Este exemplo tem 2 níveis, o pai e o filho. Eu quero que o menu tenha mais um nível, para que eu possa criar um menu de 3 níveis com o Wordpress. Abaixo, à esquerda, um código que se refere a dois níveis de menu. Exemplo do menu neste Link <?php $menu_name = 'main_nav'; $locations = get_nav_menu_locations(); $menu = wp_get_nav_menu_object( $locations[ $menu_name ] ); $menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) ); ?> <nav> <ul class="main-nav"> <?php $count = 0; $submenu = false; foreach( $menuitems as $item ): $link = $item->url; $title = $item->title; // item does not have a parent so menu_item_parent equals 0 (false) if ( !$item->menu_item_parent ): // save this id for later comparison with sub-menu items $parent_id = $item->ID; ?> <li class="item"> <a href="<?php echo $link; ?>" class="title"> <?php echo $title; ?> </a> <?php endif; ?> <?php if ( $parent_id == $item->menu_item_parent ): ?> <?php if ( !$submenu ): $submenu = true; ?> <ul class="sub-menu"> <?php endif; ?> <li class="item"> <a href="<?php echo $link; ?>" class="title"><?php echo $title; ?></a> </li> <?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu ): ?> </ul> <?php $submenu = false; endif; ?> <?php endif; ?> <?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id ): ?> </li> <?php $submenu = false; endif; ?> <?php $count++; endforeach; ?> </ul> </nav> A: O Wordpress não tem uma função simples pronta para criar submenus de 3 níveis. Porém com esta classe que eu criei ele permite que você possa criar um menu de 3 níveis facilmente. O arquivo da classe pode ser salvo como menu.php ou o nome que desejar. Lembrando que será necessário trocar o nome do menu de acordo com o nome do seu menu utilizado, pois senão não conseguirá buscar os dados do menu. $menu_name = 'header-menu'; Esta classe vai servir como uma espécie de back end do Wordpress para poder criar um menu de 3 níveis. <?php // classe com as variáveis que você quer puxar do back end class Menu { public $titulo; public $id; public $url; public $submenu; } $menu_name = 'header-menu'; $locations = get_nav_menu_locations(); $menu = wp_get_nav_menu_object($locations[ $menu_name ]); $menuitems = wp_get_nav_menu_items($menu->term_id, array('order' => 'DESC')); $submenu = false; $id_anterior = 0; $set_menu = false; foreach( $menuitems as $item ): //adiciona o menu if (!$item->menu_item_parent){ // o menu precisa ser adicionado depois de setar seus filhos logo //a variavel setmenu vai certificar que você consiga setar os //filhos do menu corretamente if ($set_menu == true) { $menus[] = $myMenu; $set_menu = false;} if ($set_menu == false) { $set_menu = true;} $myMenu = new Menu(); $myMenu->titulo = $item->title; $myMenu->id = $item->ID; $myMenu->url = $item->url; } else { //adiciona o submenu if ($id_anterior != $item->menu_item_parent) { $mySubmenu = new Menu(); $mySubmenu->titulo = $item->title; $mySubmenu->id = $item->ID; $mySubmenu->url = $item->url; $myMenu->submenu[] = $mySubmenu; } //adiciona o submenu //adiciona o subsubmenu if ($id_anterior == $item->menu_item_parent) { $mySubSubmenu = new Menu(); $mySubSubmenu->titulo = $item->title; $mySubSubmenu->id = $item->ID; $mySubSubmenu->url = $item->url; $mySubmenu->submenu[] = $mySubSubmenu; } if ($id_anterior != $item->menu_item_parent){ $id_anterior = $item->ID; } //adiciona o subsubmenu } endforeach; //necessário para adicionar o último ítem do menu $menus[] = $myMenu; ?> Como utilizar o código no front end depois de ter feito a classe? Primeiramente você deverá dar um include ou require_once ou alguma função semelhante de criação de template do wordpress para poder incluir a classe, no exemplo eu coloquei o require_once(); <?php require_once (TEMPLATEPATH . '/menu.php'); ?> Depois a criação do menu será fácil, você poderá fazer qualquer tipo de menu customizado com 3 níveis com esta classe, basta aplicar a lógica do menu, no caso eu coloquei um exemplo simples utilizando as tags "UL" "LI" e "A" <ul> <?php foreach ($menus as $menu) { ?> <li> <a href="<?= $menu->url; ?>"> <?= $menu->titulo; ?> </a> </li> <!-- se houver submenu --> <?php if ($menu->submenu){ ?> <ul> <?php foreach ($menu->submenu as $submenu) { ?> <li> <a href="<?= $submenu->url; ?>"> <?= $submenu->titulo; ?> </a> </li> <!-- se for menu de terceiro nível --> <?php if ($submenu->submenu){ ?> <ul> <?php foreach ($submenu->submenu as $submenu) { ?> <li> <a href="<?= $submenu->url; ?>"> <?= $submenu->titulo; ?> </a> </li> <?php } ?> </ul> <?php } ?> <!-- se for menu de terceiro nível --> <?php } ?> </ul> <?php } ?> <!-- se houver submenu --> <?php } ?> Resultado: Assim quando você poderá trabalhar com menu de 3 níveis com o painel de admin do Wordpress e aplicar em seu menu customizado facilmente, como mostrado no exemplo.
{ "pile_set_name": "StackExchange" }
Q: PermissionError: [Errno 13] Permission denied (after multiple successful writting attemps in the file) I wrote a code which query a mongo database and write results in a file. My code create the file and start to write in it succesfully. But after multiple iterations (not sure if the number of iteration is fix or not) I got a PermissionError. I've search about it but I only found answers about people who got the error at first attempt because they don't have permission. I will precise that I am not doing anything on my computer during the execution so I really don't understand how it can happen. Here is parts of the code: def query(self, query_date_part, query_actKey_part, filepath): empty = True print("0.0 %") for i in range(len(query_date_part)): query = {"dt": query_date_part[i], "actKey": query_actKey_part} cursor = self.collection.find(query) while cursor.alive: try: if empty: with open(filepath, 'w') as fp: json.dump(cursor.next(), fp, default=json_util.default) empty = False else: append_to_json(filepath, cursor.next()) except StopIteration: print("Stop Iteration") print(str(round(float(i+1) / len(query_date_part) * 100, ndigits=2)) + " %") return 0 def append_to_json(filepath, data): """ Append data in JSON format to the end of a JSON file. NOTE: Assumes file contains a JSON object (like a Python dict) ending in '}'. :param filepath: path to file :param data: dict to append """ # construct JSON fragment as new file ending new_ending = ", " + json.dumps(data, default=json_util.default)[1:-1] + "}\n" # edit the file in situ - first open it in read/write mode with open(filepath, 'r+') as f: f.seek(0, 2) # move to end of file index = f.tell() # find index of last byte # walking back from the end of file, find the index # of the original JSON's closing '}' while not f.read().startswith('}'): index -= 1 if index == 0: raise ValueError("can't find JSON object in {!r}".format(filepath)) f.seek(index) # starting at the original ending } position, write out # the new ending f.seek(index) f.write(new_ending)` Part of the output: 6.75 % Stop Iteration 6.76 % Traceback (most recent call last): File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 237, in <module> mdbc.query(split_date(2017,5,6,1,0,2017,5,16,10,0,step=2), {"$in": ["aFeature"]}, 'test.json') File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 141, in query append_to_json(filepath, cursor.next()) File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 212, in append_to_json with open(filepath, 'r+') as f: PermissionError: [Errno 13] Permission denied: 'test.json' Process finished with exit code 1 Note: The size of the file increase during the execution. When it crash it is about 300 Mo, I still have a lot of space on my hard drive but maybe the size of the file can be an issue ? Config: I use Windows 7, Python 3.6 and my IDE is PyCharm Community Edition 2016.3.2 A: I had the same issue, and after testing it out, it seems like there might be some "bug" when trying to write to the same file too "often", multiple times in each sec. I'll provide a very small code snippet what you can test with: import csv text = "dfkjghdfkljghflkjghjkdfdfgsktjgrhsleiuthsl uirghuircbl iawehcg uygbc sgygerh" FIELD_NAMES = ['asd', 'qwe'] with open('test.txt', 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=FIELD_NAMES) writer.writeheader() max = 10000 i = 0 while i <= max: print(str(i)) with open('test.txt', 'a', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=FIELD_NAMES) rowData = {'asd': text, 'qwe': text} writer.writerow(rowData) i += 1 The code I think is pretty self explanatory. I got the error very randomly, sometimes it happens after the ~75th iteration, sometimes it can get to even ~750, but it looks like the code can't reach the limit. So I recommend you to try to write more data a few times rather than few data very often. I hope it helps.
{ "pile_set_name": "StackExchange" }
Q: install ipython for current python version 2.x The python version is 2.7.6 but when I install IPython sudo pip install ipython ipython it points to python 3.4.0. This leads to many syntax errors in modules that I commonly use due to python 3.x incompatibility. I try editing the first line of the script /usr/local/bin/ipython: #!/usr/bin/python3.4 becomes #!/usr/bin/python But then I get an error: ImportError: No module named IPython How can I get Ipython and my default python version (2.7.6) to work together? A: Use ipython2 to start a ipython2 shell, if you need to install for python2 use pip2 install ipython. pip obviously points to python3 on your system so specifying pip2 will install ipython for python2. Whatever the shebang points to will mean typing just ipython will start a shell for that version of python so if you had #!/usr/bin/python3.4 then ipython will start an ipython3 shell and vice-versa. Unless you have Ipython actually installed for python2 then changing the shebang won't do anything but error.
{ "pile_set_name": "StackExchange" }
Q: Include a version control tag in VSS I was reading Code Complete 2 and it mentions this: Many version-control tools wil insert version information into a file. In CVS, for exmple the characters // $id$ Will Automaticly expand to // $id: ClassName.java, v 1.1 2004/02/05 00:36:42 ismene Exp $ So now I would like to do something similar with VSS for our SQL scripts I have been googling around for the answer but can't find it. Is this possible? can someone maybe point me in the right direction? A: I've found it myself @ http://msdn.microsoft.com/en-us/library/d826hy97(VS.80).aspx
{ "pile_set_name": "StackExchange" }