qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
42,746,339
I very much new to Node JS and Express Framework & mongodb. I am working on a website which has multiple categories and when we click on category it goes to a view, where based on the category clicked, data gets loaded in the view. please check the link for website [here](http://little-step.bitballoon.com/). I am looking help for navbar links eg. Montessori Premium->Toddler Material As these are static links I can not figure how to pass any parameter or url format for this. I have done the routing for individual products as they have ids coming from database so I am using that id in url. Thanks in advance.
2017/03/12
[ "https://Stackoverflow.com/questions/42746339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7697614/" ]
It seems to me like you're just missing a bit of glue in between the front-end and the back-end database calls. Here's a rough idea of the sequence you might be after and an explanation of what I think you're missing. If I'm wrong, please add a comment and update your question to include the new details and I'll see about editing my answer. In this example I'm creating a website which has a list of "items" in a shop and we're looking to display them all on a single page. Each item should then have an a href clicking through to that specific item where there might be more detail such as a "full description" of the item and maybe some images or something. We're going to look at the flow to build that first page with the list of items. 1. The user makes a HTTP GET call to the root of your website such as "<http://www.mystore.com/>". 2. This request comes through in Express to your controller which takes the `req, res, next` parameters. 3. Your controller makes a call to the database to get a list of all items including their names and ID's. 4. You then use something called templating to inject in the list of items. 5. In this template you iterate through the list doing something like this. . ``` <ul> {{#each items}} <li><a href="/items/{{id}}>{{name}}</a></li> {{/each}} </ul> ``` In this template (which happens to be Handlebars), we're going through the list of items and using the id and name of each to inject them into the HTML to get something a bit like this back. ``` <ul> <li><a href="/items/1>Shoes</a></li> <li><a href="/items/2>Red spotted dress</a></li> <li><a href="/items/3>Jeans</a></li> </ul> ``` 6. This is then served up to the user once the template has been processed. In essence I think you're after some sort of templating engine, I'd highly recommend having a look at Handlebars with something like the [express-hbs](https://npmjs.com/package/express-hbs).
Thank you @Elliot for your time to answer this. Yes I am using handlebars for templating. The solution I found is, because I am using static links, I am passing query string in anchor tag link. eg. <http://localhost:8000/product?category=Toddler_Material> and then using `req.query` for capturing the values (Toddler\_Material) in router ``` var category = req.query.category; ```
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
Try this, ``` require File.join(File.dirname(__FILE__),'MarkModule') ```
``` require 'MakModule' ```
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
It is simply impossible that the code you posted here generates that error message. The error message says that you tried to `require` a file named `makRequire`, but that filename doesn't appear anywhere in the code you posted. Without the actual code that is generating the actual error, it is impossible to answer your question. However, here are a few general tips: Whenever the computer tells you that it cannot find something, in 99% of the cases, the problem is that the thing the computer tells it couldn't find isn't actually there. So, in this case, the computer tells you that it cannot find a file named `makRequire.rb`, and the most likely explanation for that is that `makRequire.rb` doesn't actually exist. So, the first thing you need to check is: *does* `makRequire.rb` (note the capitalization and the file extension) actually exist? Because if it doesn't exist, then the reason why the computer cannot find it, should be rather obvious. In 99% of the *rest* of the cases, the problem is that the thing the computer is looking for *does* exist, but the computer is looking in the wrong place. So, after you have verified that `makRequire.rb` actually *does* exist, you need to make sure that the directory the file is in, is in Ruby's `$LOAD_PATH`, and if it isn't, you need to add that directory to Ruby's `$LOAD_PATH`. Alternatively, if you want to `require` the file relative to the path of the file that is doing the requiring, you need to use `require_relative` instead of `require`. The third thing to check for, is whether the user who own the `ruby` process has sufficient privileges to access the file `makRequire.rb`, the directory it is in and all of its parent directories.
``` require 'MakModule' ```
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
Try `require './MakModule'`, because the `.` is the current directory.
``` require 'MakModule' ```
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
Try this, ``` require File.join(File.dirname(__FILE__),'MarkModule') ```
You can require a file that is in the same directory. To use a module you would typically `include` the module inside a class definition. So you would never require `Display`, you would require the file that contains `Display` (without the .rb extension, usually).
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
It is simply impossible that the code you posted here generates that error message. The error message says that you tried to `require` a file named `makRequire`, but that filename doesn't appear anywhere in the code you posted. Without the actual code that is generating the actual error, it is impossible to answer your question. However, here are a few general tips: Whenever the computer tells you that it cannot find something, in 99% of the cases, the problem is that the thing the computer tells it couldn't find isn't actually there. So, in this case, the computer tells you that it cannot find a file named `makRequire.rb`, and the most likely explanation for that is that `makRequire.rb` doesn't actually exist. So, the first thing you need to check is: *does* `makRequire.rb` (note the capitalization and the file extension) actually exist? Because if it doesn't exist, then the reason why the computer cannot find it, should be rather obvious. In 99% of the *rest* of the cases, the problem is that the thing the computer is looking for *does* exist, but the computer is looking in the wrong place. So, after you have verified that `makRequire.rb` actually *does* exist, you need to make sure that the directory the file is in, is in Ruby's `$LOAD_PATH`, and if it isn't, you need to add that directory to Ruby's `$LOAD_PATH`. Alternatively, if you want to `require` the file relative to the path of the file that is doing the requiring, you need to use `require_relative` instead of `require`. The third thing to check for, is whether the user who own the `ruby` process has sufficient privileges to access the file `makRequire.rb`, the directory it is in and all of its parent directories.
Try this, ``` require File.join(File.dirname(__FILE__),'MarkModule') ```
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
Try this, ``` require File.join(File.dirname(__FILE__),'MarkModule') ```
Try `require './MakModule'`, because the `.` is the current directory.
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
It is simply impossible that the code you posted here generates that error message. The error message says that you tried to `require` a file named `makRequire`, but that filename doesn't appear anywhere in the code you posted. Without the actual code that is generating the actual error, it is impossible to answer your question. However, here are a few general tips: Whenever the computer tells you that it cannot find something, in 99% of the cases, the problem is that the thing the computer tells it couldn't find isn't actually there. So, in this case, the computer tells you that it cannot find a file named `makRequire.rb`, and the most likely explanation for that is that `makRequire.rb` doesn't actually exist. So, the first thing you need to check is: *does* `makRequire.rb` (note the capitalization and the file extension) actually exist? Because if it doesn't exist, then the reason why the computer cannot find it, should be rather obvious. In 99% of the *rest* of the cases, the problem is that the thing the computer is looking for *does* exist, but the computer is looking in the wrong place. So, after you have verified that `makRequire.rb` actually *does* exist, you need to make sure that the directory the file is in, is in Ruby's `$LOAD_PATH`, and if it isn't, you need to add that directory to Ruby's `$LOAD_PATH`. Alternatively, if you want to `require` the file relative to the path of the file that is doing the requiring, you need to use `require_relative` instead of `require`. The third thing to check for, is whether the user who own the `ruby` process has sufficient privileges to access the file `makRequire.rb`, the directory it is in and all of its parent directories.
You can require a file that is in the same directory. To use a module you would typically `include` the module inside a class definition. So you would never require `Display`, you would require the file that contains `Display` (without the .rb extension, usually).
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
Try `require './MakModule'`, because the `.` is the current directory.
You can require a file that is in the same directory. To use a module you would typically `include` the module inside a class definition. So you would never require `Display`, you would require the file that contains `Display` (without the .rb extension, usually).
4,267,662
I'm new to Ruby MakModule.rb ``` module Display class Multiply def Multiply.mul(first, second) return first * second end end end ``` MakRequire1.rb ``` require "Display" puts Multiply.mul 5,6 ``` MakRequire2.rb ``` require "MakModule.rb" puts Multiply.mul 5,6 ``` both file give me the error below ``` ruby: No such file or directory -- makRequire (LoadError) ``` How should I correct my code?
2010/11/24
[ "https://Stackoverflow.com/questions/4267662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456218/" ]
It is simply impossible that the code you posted here generates that error message. The error message says that you tried to `require` a file named `makRequire`, but that filename doesn't appear anywhere in the code you posted. Without the actual code that is generating the actual error, it is impossible to answer your question. However, here are a few general tips: Whenever the computer tells you that it cannot find something, in 99% of the cases, the problem is that the thing the computer tells it couldn't find isn't actually there. So, in this case, the computer tells you that it cannot find a file named `makRequire.rb`, and the most likely explanation for that is that `makRequire.rb` doesn't actually exist. So, the first thing you need to check is: *does* `makRequire.rb` (note the capitalization and the file extension) actually exist? Because if it doesn't exist, then the reason why the computer cannot find it, should be rather obvious. In 99% of the *rest* of the cases, the problem is that the thing the computer is looking for *does* exist, but the computer is looking in the wrong place. So, after you have verified that `makRequire.rb` actually *does* exist, you need to make sure that the directory the file is in, is in Ruby's `$LOAD_PATH`, and if it isn't, you need to add that directory to Ruby's `$LOAD_PATH`. Alternatively, if you want to `require` the file relative to the path of the file that is doing the requiring, you need to use `require_relative` instead of `require`. The third thing to check for, is whether the user who own the `ruby` process has sufficient privileges to access the file `makRequire.rb`, the directory it is in and all of its parent directories.
Try `require './MakModule'`, because the `.` is the current directory.
63,060,644
I'm trying to create a 2x2 grid for displaying some info in cards. Disclaimer: I'm totally new to Dart and Flutter, so expect a lot of ignorance on the topic here. These cards should have a fixed size, have an image, display some text... and be positioned from left to right, from top to bottom. First, I tried to use the Flex widget, but it seems to only work horizontally or vertically. Therefore, my only solution was to use two Flexes, but only showing the second when the amount of elements is higher than 2 (which would only use one row). Then, I tried using GridView, but it doesn't work in any possible way. It doesn't matter which example from the Internet I copy and paste to begin testing: they just won't show up in the screen unless they're the only thing that is shown in the app, with no other widget whatsoever. I still don't understand why that happens. This is my current code: First widgets in "home\_page.dart": ``` return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Padding(padding: EdgeInsets.only(top: 30)), Text( 'App test', style: TextStyle(fontSize: 24), ), EventsList(key: new Key('test')), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); ``` The "EventList" part is a widget that should represent the grid functionality I explained before. This class gets some info from a service (which currently just sends some hardcoded info from a Future), and paints the given widgets ("Card" items, basically) into the EventList view: ``` class _EventsListState extends State<EventsList> { @override Widget build(BuildContext context) { return FutureBuilder<List<Event>>( future: new EventsService().getEventsForCoords(), builder: (context, AsyncSnapshot<List<Event>> snapshot) { if (snapshot.hasData) { return Padding( padding: EdgeInsets.only(left: 20, right: 20), child: Flex( direction: Axis.horizontal, verticalDirection: VerticalDirection.down, mainAxisAlignment: MainAxisAlignment.center, children: generateProximityEventCards(snapshot.data), )); } else { return CircularProgressIndicator(); } }); } List<Card> generateProximityEventCards(List<Event> eventList) { // Load Events from API print(eventList); // Render each card return eventList.map((Event ev) { return Card( child: Padding( padding: EdgeInsets.only(bottom: 15), child: Column( children: <Widget>[ Image( fit: BoxFit.cover, image: ev.imageUrl, height: 100, width: 150, ), Padding( child: Text(ev.name), padding: EdgeInsets.only(left: 10, right: 10), ), Padding( child: Text(ev.address), padding: EdgeInsets.only(left: 10, right: 10), ), ], ), )); }).toList(); } } ``` This is how it currently looks: [![](https://i.stack.imgur.com/KqtX5.png)](https://i.stack.imgur.com/KqtX5.png) As I said before, I understand that the Flex widget can't really get that 2x2 grid look that I'm looking for, which would be something like this (done with Paint): [![](https://i.stack.imgur.com/oNV5B.png)](https://i.stack.imgur.com/oNV5B.png) So, some questions: 1. How can I get a grid like that working? Have in mind that I want to have more stuff below that, so it cannot be an "infinite" grid, nor a full window grid. 2. Is it possible to perform some scrolling to the right in the container of that grid? So in case there are more than 4 elements, I can get to the other ones just scrolling with the finger to the right. 3. As you can see in the first image, the second example is bigger than the first. How to limit the Card's size? Thank you a lot for your help!
2020/07/23
[ "https://Stackoverflow.com/questions/63060644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2903610/" ]
The reason the gridview was not working is because you need to set the shrinkWrap property of theGridView to true, to make it take up as little space as possible. (by default, scrollable widgets like gridview and listview take up as much vertical space as possible, which gives you an error if you put that inside a column widget) Try using the scrollable `GridView.count` widget like this and setting shrinkWrap to true: ``` ... GridView.count( primary: false, padding: /* You can add padding: */ You can add padding const EdgeInsets.all(20), crossAxisCount: /* This makes it 2x2: */ 2, shrinkWrap: true, children: generateProximityEventCards(snapshot.data), ... ```
Is this what you exactly want? do let me know so that I can update the code for you ``` import 'package:flutter/material.dart'; class List extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.white, title: Text('Inicio', style: TextStyle(color: Colors.black, fontSize: 18.0),), ), body: GridView.count( shrinkWrap: true, crossAxisCount: 2, children: List.generate( 50,//this is the total number of cards (index){ return Container( child: Card( color: Colors.blue, ), ); } ), ), ); } } ```
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
The plywood of your roof is typically not as thick as your standard galvanized steel roofing nail, so it is expected for nails to show through this in your attic. The plywood can and is expected to take a bit of damage over time and this is okay as long as the shingle has something firm to hold itself down onto. Over time if the plywood is too damaged to properly hold down new shingles or becomes too dangerous to walk on safely then a roofer should be able to identify such compromised plywood board and replace it as needed. What is worrying about your question is that you specified that the roofing nails have split and damaged the roof trusses. Standard roofing nails should not be long or thick enough to split or crack structurally sound dimensional lumber. ![enter image description here](https://i.stack.imgur.com/D4Czg.jpg) If this is what happened then you may have a problem unrelated to the quality of the roofing job. Your home is over 50 years old in a warm wet climate, so you should inspect for a number of different problems. 1. Dryrot ![enter image description here](https://i.stack.imgur.com/GyuH3.jpg) 2. Termites ![enter image description here](https://i.stack.imgur.com/KzPh4.jpg) 3. Carpenter Ants ![enter image description here](https://i.stack.imgur.com/2GId1.jpg) If you have any of the following indications of current or past damage to any of the three items then that would explain split, cracked or damaged roof trusses during a typical roofing job. On another note: The soffit typically fits into a groove that is known as J Channel when installed on a roof overhang. The roof overhang is typically MUCH too tall for any roofing nails to reach soffit. I imagine instead you might be seeing a roofing nails perforating the fascia, which can be a sign of a sloppy rushed job. Without pictures though we can't tell that for sure.
In the lower areas with exposed boards, the roofing contractor should have used shorter nails or staples in that area. Exposed nail points would not be acceptable to me. They should be clipped off flush to prevent possible injury if working under the eves, such as painting etc. The exposed nails are also going to be susceptible to rusting over time even it they are galvanized.
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
It's Florida, you have hurricanes. The lifting force generated by high winds over a roof can pull 3/4" nails out and peel off large sections of roofing, they used 1 1/4" or longer to ensure penetration through all the shingle layers, underlayment and deep enough into the sheeting to hold up to this abuse. Unless you live in the attic, you have no worries. The heads are covered by the shingles so they don't cause leaks. A neighbor down the street from us had the roof on his garage end up laying in the street from a severe thunderstorm downdraft specifically because of this. It's kind of interesting finding a large 20x40 section of roofing laying in the street with underlay tar paper all over the place. The tar strips on the shingles held quite well. The nails didn't hold. The wind gust was so strong it bent the 70' sycamore in my front yard nearly double and broke off several sweetgum trees. Additional information from **GAF** for impact resistant roofing (tornado alley - wind and hail) as follows: 1. Use only zinc-coated steel or aluminum, 10-12 gauge, barbed, deformed, or smooth shank roofing nails with heads 3/8" (10mm) to 7/16" (12mm) in diameter. 2. Fasteners should be long enough to penetrate at least 3/4" (19mm) into wood decks or just through the plywood decks. 3. Fasteners must be driven flush with the surface of the shingle. 4. Standard nailing pattern is 4 nails per shingle. Depending on local codes and expected wind conditions, 6 nails per shingle is required.
In the lower areas with exposed boards, the roofing contractor should have used shorter nails or staples in that area. Exposed nail points would not be acceptable to me. They should be clipped off flush to prevent possible injury if working under the eves, such as painting etc. The exposed nails are also going to be susceptible to rusting over time even it they are galvanized.
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
In the lower areas with exposed boards, the roofing contractor should have used shorter nails or staples in that area. Exposed nail points would not be acceptable to me. They should be clipped off flush to prevent possible injury if working under the eves, such as painting etc. The exposed nails are also going to be susceptible to rusting over time even it they are galvanized.
3/4" penetration is the law no matter the location on the roof. This is a common thing that CARPENTERS like to say the roofer did it wrong. They should read a code book sometime. The nails need to adequately penetrate for your roof to function properly and to get the full life out of it. If you dont want to see nails then the thickness of the plywood need to increase or the soffits should be enclosed. READ THE INSTRUCTIONS ON THE PACKAGE OF SHINGLES. Its clearly stated with pictures.
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
The plywood of your roof is typically not as thick as your standard galvanized steel roofing nail, so it is expected for nails to show through this in your attic. The plywood can and is expected to take a bit of damage over time and this is okay as long as the shingle has something firm to hold itself down onto. Over time if the plywood is too damaged to properly hold down new shingles or becomes too dangerous to walk on safely then a roofer should be able to identify such compromised plywood board and replace it as needed. What is worrying about your question is that you specified that the roofing nails have split and damaged the roof trusses. Standard roofing nails should not be long or thick enough to split or crack structurally sound dimensional lumber. ![enter image description here](https://i.stack.imgur.com/D4Czg.jpg) If this is what happened then you may have a problem unrelated to the quality of the roofing job. Your home is over 50 years old in a warm wet climate, so you should inspect for a number of different problems. 1. Dryrot ![enter image description here](https://i.stack.imgur.com/GyuH3.jpg) 2. Termites ![enter image description here](https://i.stack.imgur.com/KzPh4.jpg) 3. Carpenter Ants ![enter image description here](https://i.stack.imgur.com/2GId1.jpg) If you have any of the following indications of current or past damage to any of the three items then that would explain split, cracked or damaged roof trusses during a typical roofing job. On another note: The soffit typically fits into a groove that is known as J Channel when installed on a roof overhang. The roof overhang is typically MUCH too tall for any roofing nails to reach soffit. I imagine instead you might be seeing a roofing nails perforating the fascia, which can be a sign of a sloppy rushed job. Without pictures though we can't tell that for sure.
It's Florida, you have hurricanes. The lifting force generated by high winds over a roof can pull 3/4" nails out and peel off large sections of roofing, they used 1 1/4" or longer to ensure penetration through all the shingle layers, underlayment and deep enough into the sheeting to hold up to this abuse. Unless you live in the attic, you have no worries. The heads are covered by the shingles so they don't cause leaks. A neighbor down the street from us had the roof on his garage end up laying in the street from a severe thunderstorm downdraft specifically because of this. It's kind of interesting finding a large 20x40 section of roofing laying in the street with underlay tar paper all over the place. The tar strips on the shingles held quite well. The nails didn't hold. The wind gust was so strong it bent the 70' sycamore in my front yard nearly double and broke off several sweetgum trees. Additional information from **GAF** for impact resistant roofing (tornado alley - wind and hail) as follows: 1. Use only zinc-coated steel or aluminum, 10-12 gauge, barbed, deformed, or smooth shank roofing nails with heads 3/8" (10mm) to 7/16" (12mm) in diameter. 2. Fasteners should be long enough to penetrate at least 3/4" (19mm) into wood decks or just through the plywood decks. 3. Fasteners must be driven flush with the surface of the shingle. 4. Standard nailing pattern is 4 nails per shingle. Depending on local codes and expected wind conditions, 6 nails per shingle is required.
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
The plywood of your roof is typically not as thick as your standard galvanized steel roofing nail, so it is expected for nails to show through this in your attic. The plywood can and is expected to take a bit of damage over time and this is okay as long as the shingle has something firm to hold itself down onto. Over time if the plywood is too damaged to properly hold down new shingles or becomes too dangerous to walk on safely then a roofer should be able to identify such compromised plywood board and replace it as needed. What is worrying about your question is that you specified that the roofing nails have split and damaged the roof trusses. Standard roofing nails should not be long or thick enough to split or crack structurally sound dimensional lumber. ![enter image description here](https://i.stack.imgur.com/D4Czg.jpg) If this is what happened then you may have a problem unrelated to the quality of the roofing job. Your home is over 50 years old in a warm wet climate, so you should inspect for a number of different problems. 1. Dryrot ![enter image description here](https://i.stack.imgur.com/GyuH3.jpg) 2. Termites ![enter image description here](https://i.stack.imgur.com/KzPh4.jpg) 3. Carpenter Ants ![enter image description here](https://i.stack.imgur.com/2GId1.jpg) If you have any of the following indications of current or past damage to any of the three items then that would explain split, cracked or damaged roof trusses during a typical roofing job. On another note: The soffit typically fits into a groove that is known as J Channel when installed on a roof overhang. The roof overhang is typically MUCH too tall for any roofing nails to reach soffit. I imagine instead you might be seeing a roofing nails perforating the fascia, which can be a sign of a sloppy rushed job. Without pictures though we can't tell that for sure.
It is absolutely OK to see nails coming through in the attic. It would be More worrisome to see none. Then you have to be concerned about the nails being too short or possibly having Staples which are an inferior fastener. As to the chipping of trusses or decking/shearing. This is normal especially on older houses. If a 1-1/4" Roofing nail catches the edge of the sheathing it may also catch the edge of a truss and crack or chip either one. On the other hand your roofer screwed up by using too long of a nail on your soffit over-hang. Many older ranch style homes have tongue and groove decking that continues out as the soffit and you must use a shorter nail in those areas. A painter/handyman should be able to grind or cut the exposed nails on the soffit and touch up w paint
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
The plywood of your roof is typically not as thick as your standard galvanized steel roofing nail, so it is expected for nails to show through this in your attic. The plywood can and is expected to take a bit of damage over time and this is okay as long as the shingle has something firm to hold itself down onto. Over time if the plywood is too damaged to properly hold down new shingles or becomes too dangerous to walk on safely then a roofer should be able to identify such compromised plywood board and replace it as needed. What is worrying about your question is that you specified that the roofing nails have split and damaged the roof trusses. Standard roofing nails should not be long or thick enough to split or crack structurally sound dimensional lumber. ![enter image description here](https://i.stack.imgur.com/D4Czg.jpg) If this is what happened then you may have a problem unrelated to the quality of the roofing job. Your home is over 50 years old in a warm wet climate, so you should inspect for a number of different problems. 1. Dryrot ![enter image description here](https://i.stack.imgur.com/GyuH3.jpg) 2. Termites ![enter image description here](https://i.stack.imgur.com/KzPh4.jpg) 3. Carpenter Ants ![enter image description here](https://i.stack.imgur.com/2GId1.jpg) If you have any of the following indications of current or past damage to any of the three items then that would explain split, cracked or damaged roof trusses during a typical roofing job. On another note: The soffit typically fits into a groove that is known as J Channel when installed on a roof overhang. The roof overhang is typically MUCH too tall for any roofing nails to reach soffit. I imagine instead you might be seeing a roofing nails perforating the fascia, which can be a sign of a sloppy rushed job. Without pictures though we can't tell that for sure.
3/4" penetration is the law no matter the location on the roof. This is a common thing that CARPENTERS like to say the roofer did it wrong. They should read a code book sometime. The nails need to adequately penetrate for your roof to function properly and to get the full life out of it. If you dont want to see nails then the thickness of the plywood need to increase or the soffits should be enclosed. READ THE INSTRUCTIONS ON THE PACKAGE OF SHINGLES. Its clearly stated with pictures.
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
It's Florida, you have hurricanes. The lifting force generated by high winds over a roof can pull 3/4" nails out and peel off large sections of roofing, they used 1 1/4" or longer to ensure penetration through all the shingle layers, underlayment and deep enough into the sheeting to hold up to this abuse. Unless you live in the attic, you have no worries. The heads are covered by the shingles so they don't cause leaks. A neighbor down the street from us had the roof on his garage end up laying in the street from a severe thunderstorm downdraft specifically because of this. It's kind of interesting finding a large 20x40 section of roofing laying in the street with underlay tar paper all over the place. The tar strips on the shingles held quite well. The nails didn't hold. The wind gust was so strong it bent the 70' sycamore in my front yard nearly double and broke off several sweetgum trees. Additional information from **GAF** for impact resistant roofing (tornado alley - wind and hail) as follows: 1. Use only zinc-coated steel or aluminum, 10-12 gauge, barbed, deformed, or smooth shank roofing nails with heads 3/8" (10mm) to 7/16" (12mm) in diameter. 2. Fasteners should be long enough to penetrate at least 3/4" (19mm) into wood decks or just through the plywood decks. 3. Fasteners must be driven flush with the surface of the shingle. 4. Standard nailing pattern is 4 nails per shingle. Depending on local codes and expected wind conditions, 6 nails per shingle is required.
It is absolutely OK to see nails coming through in the attic. It would be More worrisome to see none. Then you have to be concerned about the nails being too short or possibly having Staples which are an inferior fastener. As to the chipping of trusses or decking/shearing. This is normal especially on older houses. If a 1-1/4" Roofing nail catches the edge of the sheathing it may also catch the edge of a truss and crack or chip either one. On the other hand your roofer screwed up by using too long of a nail on your soffit over-hang. Many older ranch style homes have tongue and groove decking that continues out as the soffit and you must use a shorter nail in those areas. A painter/handyman should be able to grind or cut the exposed nails on the soffit and touch up w paint
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
It's Florida, you have hurricanes. The lifting force generated by high winds over a roof can pull 3/4" nails out and peel off large sections of roofing, they used 1 1/4" or longer to ensure penetration through all the shingle layers, underlayment and deep enough into the sheeting to hold up to this abuse. Unless you live in the attic, you have no worries. The heads are covered by the shingles so they don't cause leaks. A neighbor down the street from us had the roof on his garage end up laying in the street from a severe thunderstorm downdraft specifically because of this. It's kind of interesting finding a large 20x40 section of roofing laying in the street with underlay tar paper all over the place. The tar strips on the shingles held quite well. The nails didn't hold. The wind gust was so strong it bent the 70' sycamore in my front yard nearly double and broke off several sweetgum trees. Additional information from **GAF** for impact resistant roofing (tornado alley - wind and hail) as follows: 1. Use only zinc-coated steel or aluminum, 10-12 gauge, barbed, deformed, or smooth shank roofing nails with heads 3/8" (10mm) to 7/16" (12mm) in diameter. 2. Fasteners should be long enough to penetrate at least 3/4" (19mm) into wood decks or just through the plywood decks. 3. Fasteners must be driven flush with the surface of the shingle. 4. Standard nailing pattern is 4 nails per shingle. Depending on local codes and expected wind conditions, 6 nails per shingle is required.
3/4" penetration is the law no matter the location on the roof. This is a common thing that CARPENTERS like to say the roofer did it wrong. They should read a code book sometime. The nails need to adequately penetrate for your roof to function properly and to get the full life out of it. If you dont want to see nails then the thickness of the plywood need to increase or the soffits should be enclosed. READ THE INSTRUCTIONS ON THE PACKAGE OF SHINGLES. Its clearly stated with pictures.
22,188
Our home was built in 1954, and is a Florida ranch style home. We have about a two-foot overhanging soffit with trusses that show and with tongue and groove under whatever that’s called. Sorry, I don’t know the proper terms… I had my roof redone. And nails have come through the plywood and show all over the attic and all the way around the soffit overhang on the outside.… Some are just the tips of nail that have come through the tongue and groove and some larger nails come through the trusses and have spilt the wood…My husband said this is normal, but it wasn’t that way before. Should the roofer repair all these nail holes?
2013/01/08
[ "https://diy.stackexchange.com/questions/22188", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/9976/" ]
It is absolutely OK to see nails coming through in the attic. It would be More worrisome to see none. Then you have to be concerned about the nails being too short or possibly having Staples which are an inferior fastener. As to the chipping of trusses or decking/shearing. This is normal especially on older houses. If a 1-1/4" Roofing nail catches the edge of the sheathing it may also catch the edge of a truss and crack or chip either one. On the other hand your roofer screwed up by using too long of a nail on your soffit over-hang. Many older ranch style homes have tongue and groove decking that continues out as the soffit and you must use a shorter nail in those areas. A painter/handyman should be able to grind or cut the exposed nails on the soffit and touch up w paint
3/4" penetration is the law no matter the location on the roof. This is a common thing that CARPENTERS like to say the roofer did it wrong. They should read a code book sometime. The nails need to adequately penetrate for your roof to function properly and to get the full life out of it. If you dont want to see nails then the thickness of the plywood need to increase or the soffits should be enclosed. READ THE INSTRUCTIONS ON THE PACKAGE OF SHINGLES. Its clearly stated with pictures.
15,110,149
I am trying to export the Hive results to a file located on Amazon s3. But the result file has some unrecognized characters like square etc. The type of the result file format is binary/octet-stream and not csv. I am not getting whey it is not able to create a csv file. The version of hive used is hive-0.8.1. I am putting the steps I followed below. By the way the hive is used from an instance launched by Amazon EMR. ``` create table test_csv(employee_id bigint, employee_name string, employee_designation string) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile; insert overwrite table test_csv select employee_id , employee_name , employee_designation from employee_details; INSERT OVERWRITE DIRECTORY 's3n://<path_to_s3_bucket>' SELECT * from test_csv; ``` Can you please let me know what could be the cause of this?
2013/02/27
[ "https://Stackoverflow.com/questions/15110149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954657/" ]
For I know, `INSERT OVERWRITE DIRECTORY` will always use ctrl-A('\001') as delimiter. Direct copy of file with your table data would be the best solution. GL.
Did you try opening the Hive warehouse directory in HDFS to your output so as to check how the data is stored there? I think this line is not required to be executed ``` INSERT OVERWRITE DIRECTORY 's3n://<path_to_s3_bucket>' SELECT * from test_csv; ``` rather you can directly do a **"dfs -get"**
15,110,149
I am trying to export the Hive results to a file located on Amazon s3. But the result file has some unrecognized characters like square etc. The type of the result file format is binary/octet-stream and not csv. I am not getting whey it is not able to create a csv file. The version of hive used is hive-0.8.1. I am putting the steps I followed below. By the way the hive is used from an instance launched by Amazon EMR. ``` create table test_csv(employee_id bigint, employee_name string, employee_designation string) row format delimited fields terminated by ',' lines terminated by '\n' stored as textfile; insert overwrite table test_csv select employee_id , employee_name , employee_designation from employee_details; INSERT OVERWRITE DIRECTORY 's3n://<path_to_s3_bucket>' SELECT * from test_csv; ``` Can you please let me know what could be the cause of this?
2013/02/27
[ "https://Stackoverflow.com/questions/15110149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954657/" ]
You can export data from Hive via the command line: `hive -e 'select * from foo;' > foo.tsv` You could probably pipe through sed or something to transform the tabs into commas, we just used TSVs for everything.
Did you try opening the Hive warehouse directory in HDFS to your output so as to check how the data is stored there? I think this line is not required to be executed ``` INSERT OVERWRITE DIRECTORY 's3n://<path_to_s3_bucket>' SELECT * from test_csv; ``` rather you can directly do a **"dfs -get"**
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
You get on client side the drop down list, and check the index, your code will probably be as: ``` <script> window.onbeforeunload= function() { if(document.getElementById('<%=cbOrderSpareCustomer.ClientID%>').selectedIndex > 0) { return "Custom message here"; } else { return true; } }; </script> ```
I think... ``` window.onbeforeunload = function(e) { if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) { if (!confirm('Are you sure')) { return false; } } } ```
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
You get on client side the drop down list, and check the index, your code will probably be as: ``` <script> window.onbeforeunload= function() { if(document.getElementById('<%=cbOrderSpareCustomer.ClientID%>').selectedIndex > 0) { return "Custom message here"; } else { return true; } }; </script> ```
If you're using JQuery ``` <script type="text/javascript"> $(window).bind('beforeunload', function () { if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) { return 'Your data will be lost.'; } }); </script> ``` You don't want else return true or it will still prompt (at least, IE prompts)
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
You get on client side the drop down list, and check the index, your code will probably be as: ``` <script> window.onbeforeunload= function() { if(document.getElementById('<%=cbOrderSpareCustomer.ClientID%>').selectedIndex > 0) { return "Custom message here"; } else { return true; } }; </script> ```
My solution: ``` <script type="text/javascript" function setDirty() { window.onbeforeunload = function () { return 'The data will be lost if you leave this page!' } } </script> ``` With the attribute onCange="setDirty()" added to the dropdownlist. Thanks all for helping!
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
Follow the below steps to make this work 1. Add `onchange` attribute to the combobox on serve side using the code: `<select id="cbOrderSpareCustomer" onchange="setDirty()">` 2. Define your javascript as below `var isDirty = true; function setDirty() { isDirty = true; } window.onbeforeunload = function () { if (isDirty) { return confirm('Your unsaved changes will be lost'); } }`
I think... ``` window.onbeforeunload = function(e) { if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) { if (!confirm('Are you sure')) { return false; } } } ```
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
I think... ``` window.onbeforeunload = function(e) { if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) { if (!confirm('Are you sure')) { return false; } } } ```
If you're using JQuery ``` <script type="text/javascript"> $(window).bind('beforeunload', function () { if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) { return 'Your data will be lost.'; } }); </script> ``` You don't want else return true or it will still prompt (at least, IE prompts)
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
I think... ``` window.onbeforeunload = function(e) { if (document.getElementById('cbOrderSpareCustomer').selectedIndex > 0) { if (!confirm('Are you sure')) { return false; } } } ```
My solution: ``` <script type="text/javascript" function setDirty() { window.onbeforeunload = function () { return 'The data will be lost if you leave this page!' } } </script> ``` With the attribute onCange="setDirty()" added to the dropdownlist. Thanks all for helping!
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
Follow the below steps to make this work 1. Add `onchange` attribute to the combobox on serve side using the code: `<select id="cbOrderSpareCustomer" onchange="setDirty()">` 2. Define your javascript as below `var isDirty = true; function setDirty() { isDirty = true; } window.onbeforeunload = function () { if (isDirty) { return confirm('Your unsaved changes will be lost'); } }`
If you're using JQuery ``` <script type="text/javascript"> $(window).bind('beforeunload', function () { if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) { return 'Your data will be lost.'; } }); </script> ``` You don't want else return true or it will still prompt (at least, IE prompts)
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
Follow the below steps to make this work 1. Add `onchange` attribute to the combobox on serve side using the code: `<select id="cbOrderSpareCustomer" onchange="setDirty()">` 2. Define your javascript as below `var isDirty = true; function setDirty() { isDirty = true; } window.onbeforeunload = function () { if (isDirty) { return confirm('Your unsaved changes will be lost'); } }`
My solution: ``` <script type="text/javascript" function setDirty() { window.onbeforeunload = function () { return 'The data will be lost if you leave this page!' } } </script> ``` With the attribute onCange="setDirty()" added to the dropdownlist. Thanks all for helping!
23,958,772
On my page I have a combobox called cbOrderSpareCustomer. By default the selected index is set to 0. when the user changes it, I consider the page containing data and when the user decides to leave the page I want to prompt him to let him know data will be lost. I have seen many posts about this but I'm very new to javascript so I could use some help. I understand I have to use: ``` <script> window.onbeforeunload= function() { return "Custom message here"; }; </script> ``` But how do I make it work with the combobox? like `if cbOrderSpareCustomer.selectedIndex > 0 then prompt else just continue.` I also want to prevent it from showing the prompt on each postback. I would like to see an example.
2014/05/30
[ "https://Stackoverflow.com/questions/23958772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743873/" ]
If you're using JQuery ``` <script type="text/javascript"> $(window).bind('beforeunload', function () { if ($("select[name='cbOrderSpareCustomer'] option:selected").index() > 0) { return 'Your data will be lost.'; } }); </script> ``` You don't want else return true or it will still prompt (at least, IE prompts)
My solution: ``` <script type="text/javascript" function setDirty() { window.onbeforeunload = function () { return 'The data will be lost if you leave this page!' } } </script> ``` With the attribute onCange="setDirty()" added to the dropdownlist. Thanks all for helping!
738,823
Is there a place to find a list of the possible values for the PHP predefined constant `PHP_OS` ? I'd like to use this value for a system requirements check, but need to know how different operating systems are named in this variable. Through some searching, so far I've compiled the following list: * CYGWIN\_NT-5.1 * Darwin * FreeBSD * HP-UX * IRIX64 * Linux * NetBSD * OpenBSD * SunOS * Unix * WIN32 * WINNT * Windows If anyone has a more complete list, or knows of any additional values I'd love to hear them!
2009/04/10
[ "https://Stackoverflow.com/questions/738823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
PHP [passes through the uname](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/configure.in#L1300), [except on Windows (`WINNT`)](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/main/main.c#L2022) and [Netware (`Netware`)](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/configure.in#L1292). See [Wikipedia](http://en.wikipedia.org/wiki/Uname#Table_of_standard_uname_output) for a non-exhaustive list of values not mentioned in your question: * CYGWIN\_NT-5.1 * IRIX64 * SunOS * HP-UX * OpenBSD (not in Wikipedia)
I think a better solution to do a 'requirement check' would be to actually use things that you need to know work properly and see what happens. For example, there are constants for directory separators, functions like realpath(), etc to deal with directories on different operating systems. What, specifically, are you trying to do?
738,823
Is there a place to find a list of the possible values for the PHP predefined constant `PHP_OS` ? I'd like to use this value for a system requirements check, but need to know how different operating systems are named in this variable. Through some searching, so far I've compiled the following list: * CYGWIN\_NT-5.1 * Darwin * FreeBSD * HP-UX * IRIX64 * Linux * NetBSD * OpenBSD * SunOS * Unix * WIN32 * WINNT * Windows If anyone has a more complete list, or knows of any additional values I'd love to hear them!
2009/04/10
[ "https://Stackoverflow.com/questions/738823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
PHP [passes through the uname](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/configure.in#L1300), [except on Windows (`WINNT`)](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/main/main.c#L2022) and [Netware (`Netware`)](https://github.com/php/php-src/blob/0d51ebd1a54af59d915c551a240b56bb3f0e26a6/configure.in#L1292). See [Wikipedia](http://en.wikipedia.org/wiki/Uname#Table_of_standard_uname_output) for a non-exhaustive list of values not mentioned in your question: * CYGWIN\_NT-5.1 * IRIX64 * SunOS * HP-UX * OpenBSD (not in Wikipedia)
it seems like the `php_uname("s")` for non-Unix OSes would be a good start, since it looks to me like `uname("s")` and `php_uname("s")` are the same on Unix systems and posix sub systems, such as Cygwin, Mingw, UWin, EMX+GCC, and MKS. Below is a list of OSes that are not Posix-compliant out of the box and that run PHP. OS -- * OS/2 Warp * eComStation * RISC OS * Windows XP 64-bit Keep in mind, this is not at all for Browser detection, but root path detecting, directory separators that may or may not be `\` and `/`, EOL, and a few other things. Examples of root paths ---------------------- * Unix\linux\Mac OS X: `/` * OS/2: `C:\` * Amiga: `dh0:`
738,823
Is there a place to find a list of the possible values for the PHP predefined constant `PHP_OS` ? I'd like to use this value for a system requirements check, but need to know how different operating systems are named in this variable. Through some searching, so far I've compiled the following list: * CYGWIN\_NT-5.1 * Darwin * FreeBSD * HP-UX * IRIX64 * Linux * NetBSD * OpenBSD * SunOS * Unix * WIN32 * WINNT * Windows If anyone has a more complete list, or knows of any additional values I'd love to hear them!
2009/04/10
[ "https://Stackoverflow.com/questions/738823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
I think a better solution to do a 'requirement check' would be to actually use things that you need to know work properly and see what happens. For example, there are constants for directory separators, functions like realpath(), etc to deal with directories on different operating systems. What, specifically, are you trying to do?
it seems like the `php_uname("s")` for non-Unix OSes would be a good start, since it looks to me like `uname("s")` and `php_uname("s")` are the same on Unix systems and posix sub systems, such as Cygwin, Mingw, UWin, EMX+GCC, and MKS. Below is a list of OSes that are not Posix-compliant out of the box and that run PHP. OS -- * OS/2 Warp * eComStation * RISC OS * Windows XP 64-bit Keep in mind, this is not at all for Browser detection, but root path detecting, directory separators that may or may not be `\` and `/`, EOL, and a few other things. Examples of root paths ---------------------- * Unix\linux\Mac OS X: `/` * OS/2: `C:\` * Amiga: `dh0:`
21,301,856
I am following wpf mvvm . Here i want to display the primary key value + 1. ie, when the code executing , if the table is empty,then display the value of primary key as 1. If the table have 1 row,then display 2 and so on. so work this type., How to take the highest value of primary key in a table in wpf mvvm. Can i use Max function? then How?
2014/01/23
[ "https://Stackoverflow.com/questions/21301856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3192678/" ]
In TCP, there's no way to tell that a connection has failed unless you try to send something on the connection. TCP doesn't perform active monitoring of the connection (actually, there are optional "keepalive" packets, but these are not normally sent until the connection has been idle for a couple of hours). When you send something, you'll eventually get an error if there's a timeout waiting for the other machine to return an acknowledgement. But if you're just reading data without sending, you can't tell that the connection has failed -- it just looks like the sender doesn't have anything to send. You can resolve this by designing your application so that the client is required to send something every N seconds. Then set a timer in the server that detects that you haven't received anything for more than N seconds (you should add a little extra time to allow for transient delays).
When the network is broken what happens is that you clients keep sending data and at some point the socket send buffer gets full (I understand from what you show that you are sending 1024 Bytes, 1024 times, 1MB in total). The default for send buffer could be 16KB (surely less than 1MB). Then when the client tries to write, it gets blocked forever. BTW, now I'm answering your question I don't know whether eventually after a number of TCP timeouts, TCP gives up and closes the socket making the socket interface return with error. I think that's not happening ... :) - So, connect fails if there is a problem in the network but write and read do not fail. In the server side, the server gets blocked in read because it never receives the EOF. Solution: In the client side use non-blocking sockets, if the network is broken, at some point write will return with error EWOULDBLOCK. Then you will realize the send buffer is full for some reason. At that point, you could clouse the connection and try to connect again. If the network is broken, you will receive an error. In the server side also use non-blocking sockets and select() function with a timeout. After a few timeouts you may decide there is a problem with the new connection and close it.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
I tried all of the connection types (charge, MTP, PTP) but perhaps not "Internet Connnection, modem"? You can change it by pulling down the system-wide drop down menu and touching "USB connection". This is how I fixed it, but I thought I'd tried this already, so I can't guarantee it wasn't this in conjunction with one of the things done above.
PTP seemed to do the trick. Never had to do that on any other device...
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
I tried all of the connection types (charge, MTP, PTP) but perhaps not "Internet Connnection, modem"? You can change it by pulling down the system-wide drop down menu and touching "USB connection". This is how I fixed it, but I thought I'd tried this already, so I can't guarantee it wasn't this in conjunction with one of the things done above.
I had the exact same problem. Selectin Internet Connection and then Ethernet as the USB connection type fixed it and everything is working as expected now.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
I tried all of the connection types (charge, MTP, PTP) but perhaps not "Internet Connnection, modem"? You can change it by pulling down the system-wide drop down menu and touching "USB connection". This is how I fixed it, but I thought I'd tried this already, so I can't guarantee it wasn't this in conjunction with one of the things done above.
I know this sounds like a stupid answer, but the same thing happened to me. It turns out the micro USB cord was just bad - which is weird, because it still charged the phone perfectly fine. After testing the bad cable unsuccessfully on a phone that had been recognized on my mac before, I switched to a different micro USB cable, and that made all the difference.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
I tried all of the connection types (charge, MTP, PTP) but perhaps not "Internet Connnection, modem"? You can change it by pulling down the system-wide drop down menu and touching "USB connection". This is how I fixed it, but I thought I'd tried this already, so I can't guarantee it wasn't this in conjunction with one of the things done above.
This is late in the game but I had an additional step to all the other suggestions. The phone was showing up in the System Profiler after I switched the usb mode to 'MTP' mode, but I didn't see any usb tethering options. After adding the phone's vendor ID to the usb ini file, enabling the developer and usb debugging, killing and restarting adb, I still didn't see my device in adb devices. I finally had to download the Mac driver for the phone directly from LG.com. After installing and rebooting on the computer, the device showed up in adb devices.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
PTP seemed to do the trick. Never had to do that on any other device...
I had the exact same problem. Selectin Internet Connection and then Ethernet as the USB connection type fixed it and everything is working as expected now.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
PTP seemed to do the trick. Never had to do that on any other device...
I know this sounds like a stupid answer, but the same thing happened to me. It turns out the micro USB cord was just bad - which is weird, because it still charged the phone perfectly fine. After testing the bad cable unsuccessfully on a phone that had been recognized on my mac before, I switched to a different micro USB cable, and that made all the difference.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
PTP seemed to do the trick. Never had to do that on any other device...
This is late in the game but I had an additional step to all the other suggestions. The phone was showing up in the System Profiler after I switched the usb mode to 'MTP' mode, but I didn't see any usb tethering options. After adding the phone's vendor ID to the usb ini file, enabling the developer and usb debugging, killing and restarting adb, I still didn't see my device in adb devices. I finally had to download the Mac driver for the phone directly from LG.com. After installing and rebooting on the computer, the device showed up in adb devices.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
I had the exact same problem. Selectin Internet Connection and then Ethernet as the USB connection type fixed it and everything is working as expected now.
I know this sounds like a stupid answer, but the same thing happened to me. It turns out the micro USB cord was just bad - which is weird, because it still charged the phone perfectly fine. After testing the bad cable unsuccessfully on a phone that had been recognized on my mac before, I switched to a different micro USB cable, and that made all the difference.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
I had the exact same problem. Selectin Internet Connection and then Ethernet as the USB connection type fixed it and everything is working as expected now.
This is late in the game but I had an additional step to all the other suggestions. The phone was showing up in the System Profiler after I switched the usb mode to 'MTP' mode, but I didn't see any usb tethering options. After adding the phone's vendor ID to the usb ini file, enabling the developer and usb debugging, killing and restarting adb, I still didn't see my device in adb devices. I finally had to download the Mac driver for the phone directly from LG.com. After installing and rebooting on the computer, the device showed up in adb devices.
24,434,850
When I run `adb devices` there are no devices showing as connected. My device is a LG Optimus Exceed 2 running 4.4.2 There are many of these posts around, so here's what I've done: * I'm using the cord that came with the phone. It charges and tries to sync photos, so it isn't an issue here. Switching usb ports and trying a powered usb hub doesn't affect it either. * I've added the vendor id (0x1004) to ~/.android/adb\_usb.ini * Restarted and unplugged any combination of things you can think of * USB Debugging is on. And has been restarted. Same with Unknown sources. * I have never used EasyTether, nor is it installed anywhere on my computer. * Updated adb, updated my sdk. * Restarted adb server * Tried installing LG's drivers: <http://www.lg.com/us/support-mobile/lg-VS450PP> (They say they don't support Mac S/W upgrade, yet they have a package to install. No help there) * I have a Nexus S running 4.1 that works, and an old LG phone running Gingerbread that connect. Any wizards out there who've already struggled with this who have advice?
2014/06/26
[ "https://Stackoverflow.com/questions/24434850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669009/" ]
I know this sounds like a stupid answer, but the same thing happened to me. It turns out the micro USB cord was just bad - which is weird, because it still charged the phone perfectly fine. After testing the bad cable unsuccessfully on a phone that had been recognized on my mac before, I switched to a different micro USB cable, and that made all the difference.
This is late in the game but I had an additional step to all the other suggestions. The phone was showing up in the System Profiler after I switched the usb mode to 'MTP' mode, but I didn't see any usb tethering options. After adding the phone's vendor ID to the usb ini file, enabling the developer and usb debugging, killing and restarting adb, I still didn't see my device in adb devices. I finally had to download the Mac driver for the phone directly from LG.com. After installing and rebooting on the computer, the device showed up in adb devices.
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
* newlines are browser dependent? + No. Use `<br>` to get a newline in a browser * newlines are system dependent? (where php runs) + yes : `\n` on OSX, `\n` on Unix/Linux, `\r\n` on Windows * will php apply some implicit conversion? + no * will mysql apply some implicit conversion? + no
You may be interested in [nl2br](http://php.net/manual/en/function.nl2br.php "nl2br"), this takes new line characters like you described and replaces them with a HTML line break (`<br />`).
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
The system independent way is using PHP\_EOL constant. New lines is not browser dependent, outer a tag with CSS [white-space:pre](http://www.w3schools.com/cssref/pr_text_white-space.asp) you must to execute [nl2br()](http://php.net/manual/en/function.nl2br.php) php function to convert newlines to BR tags.
You may be interested in [nl2br](http://php.net/manual/en/function.nl2br.php "nl2br"), this takes new line characters like you described and replaces them with a HTML line break (`<br />`).
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
The system independent way is using PHP\_EOL constant. New lines is not browser dependent, outer a tag with CSS [white-space:pre](http://www.w3schools.com/cssref/pr_text_white-space.asp) you must to execute [nl2br()](http://php.net/manual/en/function.nl2br.php) php function to convert newlines to BR tags.
`<br>` is browser independent, `\n` should be too. Don't know about `\r` MySQL won't convert it
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
Generally, for browser `\r` and `\n` are whitespace chars, like `' '` (whitespace) of `\t` (tab). Inside some tags (script, pre etc.) they are treated as line break symbols. In this case browser will understand any of common line break sequences (`\r`, `\r\n`, `\n`). When data comes from textarea, line breaks will [always](http://blogs.warwick.ac.uk/chrismay/entry/how_are_newlines/) be represented as `\r\n`. Line breaks in php files doesn't depend on system where they're running. It depends on settings of file editor used for creating php files. When you copy a php file to another system, line breaks format will not change. For example, look at this code: ``` print_r(" " === "\r\n"); ``` Its result will depend on settings of the editor used for creating this file. It doesn't depend on current system. But if you're trying to read some other files contained by your system (text files, for example) these files will most probably use system's common line breaks format. No, PHP and MySQL don't apply implicit conversions.
You may be interested in [nl2br](http://php.net/manual/en/function.nl2br.php "nl2br"), this takes new line characters like you described and replaces them with a HTML line break (`<br />`).
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
The system independent way is using PHP\_EOL constant. New lines is not browser dependent, outer a tag with CSS [white-space:pre](http://www.w3schools.com/cssref/pr_text_white-space.asp) you must to execute [nl2br()](http://php.net/manual/en/function.nl2br.php) php function to convert newlines to BR tags.
A big gotcha for me was that in single quoted strings `'like\nthis'` escape sequences (like `\n`) will not be interpreted. You have to use double quotes `"like\nthis"` to get an actual newline.
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
Generally, for browser `\r` and `\n` are whitespace chars, like `' '` (whitespace) of `\t` (tab). Inside some tags (script, pre etc.) they are treated as line break symbols. In this case browser will understand any of common line break sequences (`\r`, `\r\n`, `\n`). When data comes from textarea, line breaks will [always](http://blogs.warwick.ac.uk/chrismay/entry/how_are_newlines/) be represented as `\r\n`. Line breaks in php files doesn't depend on system where they're running. It depends on settings of file editor used for creating php files. When you copy a php file to another system, line breaks format will not change. For example, look at this code: ``` print_r(" " === "\r\n"); ``` Its result will depend on settings of the editor used for creating this file. It doesn't depend on current system. But if you're trying to read some other files contained by your system (text files, for example) these files will most probably use system's common line breaks format. No, PHP and MySQL don't apply implicit conversions.
The system independent way is using PHP\_EOL constant. New lines is not browser dependent, outer a tag with CSS [white-space:pre](http://www.w3schools.com/cssref/pr_text_white-space.asp) you must to execute [nl2br()](http://php.net/manual/en/function.nl2br.php) php function to convert newlines to BR tags.
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
Generally, for browser `\r` and `\n` are whitespace chars, like `' '` (whitespace) of `\t` (tab). Inside some tags (script, pre etc.) they are treated as line break symbols. In this case browser will understand any of common line break sequences (`\r`, `\r\n`, `\n`). When data comes from textarea, line breaks will [always](http://blogs.warwick.ac.uk/chrismay/entry/how_are_newlines/) be represented as `\r\n`. Line breaks in php files doesn't depend on system where they're running. It depends on settings of file editor used for creating php files. When you copy a php file to another system, line breaks format will not change. For example, look at this code: ``` print_r(" " === "\r\n"); ``` Its result will depend on settings of the editor used for creating this file. It doesn't depend on current system. But if you're trying to read some other files contained by your system (text files, for example) these files will most probably use system's common line breaks format. No, PHP and MySQL don't apply implicit conversions.
`<br>` is browser independent, `\n` should be too. Don't know about `\r` MySQL won't convert it
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
Generally, for browser `\r` and `\n` are whitespace chars, like `' '` (whitespace) of `\t` (tab). Inside some tags (script, pre etc.) they are treated as line break symbols. In this case browser will understand any of common line break sequences (`\r`, `\r\n`, `\n`). When data comes from textarea, line breaks will [always](http://blogs.warwick.ac.uk/chrismay/entry/how_are_newlines/) be represented as `\r\n`. Line breaks in php files doesn't depend on system where they're running. It depends on settings of file editor used for creating php files. When you copy a php file to another system, line breaks format will not change. For example, look at this code: ``` print_r(" " === "\r\n"); ``` Its result will depend on settings of the editor used for creating this file. It doesn't depend on current system. But if you're trying to read some other files contained by your system (text files, for example) these files will most probably use system's common line breaks format. No, PHP and MySQL don't apply implicit conversions.
A big gotcha for me was that in single quoted strings `'like\nthis'` escape sequences (like `\n`) will not be interpreted. You have to use double quotes `"like\nthis"` to get an actual newline.
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
* newlines are browser dependent? + No. Use `<br>` to get a newline in a browser * newlines are system dependent? (where php runs) + yes : `\n` on OSX, `\n` on Unix/Linux, `\r\n` on Windows * will php apply some implicit conversion? + no * will mysql apply some implicit conversion? + no
Generally, for browser `\r` and `\n` are whitespace chars, like `' '` (whitespace) of `\t` (tab). Inside some tags (script, pre etc.) they are treated as line break symbols. In this case browser will understand any of common line break sequences (`\r`, `\r\n`, `\n`). When data comes from textarea, line breaks will [always](http://blogs.warwick.ac.uk/chrismay/entry/how_are_newlines/) be represented as `\r\n`. Line breaks in php files doesn't depend on system where they're running. It depends on settings of file editor used for creating php files. When you copy a php file to another system, line breaks format will not change. For example, look at this code: ``` print_r(" " === "\r\n"); ``` Its result will depend on settings of the editor used for creating this file. It doesn't depend on current system. But if you're trying to read some other files contained by your system (text files, for example) these files will most probably use system's common line breaks format. No, PHP and MySQL don't apply implicit conversions.
10,451,211
I have some questions about `\r\n`: * newlines are browser dependent? (not how they are displayed in a browser, but how `<textarea>` sends them to php via http request) * newlines are system dependent? (where php runs) * will php apply some implicit conversion? * will mysql apply some implicit conversion? Thanks in advance!
2012/05/04
[ "https://Stackoverflow.com/questions/10451211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252794/" ]
* newlines are browser dependent? + No. Use `<br>` to get a newline in a browser * newlines are system dependent? (where php runs) + yes : `\n` on OSX, `\n` on Unix/Linux, `\r\n` on Windows * will php apply some implicit conversion? + no * will mysql apply some implicit conversion? + no
A big gotcha for me was that in single quoted strings `'like\nthis'` escape sequences (like `\n`) will not be interpreted. You have to use double quotes `"like\nthis"` to get an actual newline.
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
From the docs: <http://code.google.com/apis/protocolbuffers/docs/techniques.html#streaming> > > Streaming Multiple Messages > > > If you want to write multiple messages to a single file or stream, it > is up to you to keep track of where one message ends and the next > begins. The Protocol Buffer wire format is not self-delimiting, so > protocol buffer parsers cannot determine where a message ends on their > own. The easiest way to solve this problem is to write the size of > each message before you write the message itself. When you read the > messages back in, you read the size, then read the bytes into a > separate buffer, then parse from that buffer. (If you want to avoid > copying bytes to a separate buffer, check out the CodedInputStream > class (in both C++ and Java) which can be told to limit reads to a > certain number of bytes.) > > >
Protobuf does not include a terminator per outermost record, so you need to do that yourself. The simplest approach is to prefix the data with the length of the record that follows. Personally, I tend to use the approach of writing a string-header (for an arbitrary field number), then the length as a "varint" - this means the entire document is then itself a valid protobuf, and could be consumed as an object with a "repeated" element, however, just a fixed-length (typically 32-bit little-endian) marker would do just as well. With any such storage, it is appendable as you require.
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
Protobuf does not include a terminator per outermost record, so you need to do that yourself. The simplest approach is to prefix the data with the length of the record that follows. Personally, I tend to use the approach of writing a string-header (for an arbitrary field number), then the length as a "varint" - this means the entire document is then itself a valid protobuf, and could be consumed as an object with a "repeated" element, however, just a fixed-length (typically 32-bit little-endian) marker would do just as well. With any such storage, it is appendable as you require.
An easier way is to base64 encode each message and store it as a record per line.
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
I would recommend using the `writeDelimitedTo(OutputStream)` and `parseDelimitedFrom(InputStream)` methods on `Message` objects. `writeDelimitedTo` writes the length of the message before the message itself; `parseDelimitedFrom` then uses that length to read only one message and no farther. This allows multiple messages to be written to a single `OutputStream` to then be parsed separately. For more information, see <https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite#writeDelimitedTo(java.io.OutputStream)>
Protobuf does not include a terminator per outermost record, so you need to do that yourself. The simplest approach is to prefix the data with the length of the record that follows. Personally, I tend to use the approach of writing a string-header (for an arbitrary field number), then the length as a "varint" - this means the entire document is then itself a valid protobuf, and could be consumed as an object with a "repeated" element, however, just a fixed-length (typically 32-bit little-endian) marker would do just as well. With any such storage, it is appendable as you require.
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
From the docs: <http://code.google.com/apis/protocolbuffers/docs/techniques.html#streaming> > > Streaming Multiple Messages > > > If you want to write multiple messages to a single file or stream, it > is up to you to keep track of where one message ends and the next > begins. The Protocol Buffer wire format is not self-delimiting, so > protocol buffer parsers cannot determine where a message ends on their > own. The easiest way to solve this problem is to write the size of > each message before you write the message itself. When you read the > messages back in, you read the size, then read the bytes into a > separate buffer, then parse from that buffer. (If you want to avoid > copying bytes to a separate buffer, check out the CodedInputStream > class (in both C++ and Java) which can be told to limit reads to a > certain number of bytes.) > > >
An easier way is to base64 encode each message and store it as a record per line.
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
I would recommend using the `writeDelimitedTo(OutputStream)` and `parseDelimitedFrom(InputStream)` methods on `Message` objects. `writeDelimitedTo` writes the length of the message before the message itself; `parseDelimitedFrom` then uses that length to read only one message and no farther. This allows multiple messages to be written to a single `OutputStream` to then be parsed separately. For more information, see <https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite#writeDelimitedTo(java.io.OutputStream)>
From the docs: <http://code.google.com/apis/protocolbuffers/docs/techniques.html#streaming> > > Streaming Multiple Messages > > > If you want to write multiple messages to a single file or stream, it > is up to you to keep track of where one message ends and the next > begins. The Protocol Buffer wire format is not self-delimiting, so > protocol buffer parsers cannot determine where a message ends on their > own. The easiest way to solve this problem is to write the size of > each message before you write the message itself. When you read the > messages back in, you read the size, then read the bytes into a > separate buffer, then parse from that buffer. (If you want to avoid > copying bytes to a separate buffer, check out the CodedInputStream > class (in both C++ and Java) which can be told to limit reads to a > certain number of bytes.) > > >
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
From the docs: <http://code.google.com/apis/protocolbuffers/docs/techniques.html#streaming> > > Streaming Multiple Messages > > > If you want to write multiple messages to a single file or stream, it > is up to you to keep track of where one message ends and the next > begins. The Protocol Buffer wire format is not self-delimiting, so > protocol buffer parsers cannot determine where a message ends on their > own. The easiest way to solve this problem is to write the size of > each message before you write the message itself. When you read the > messages back in, you read the size, then read the bytes into a > separate buffer, then parse from that buffer. (If you want to avoid > copying bytes to a separate buffer, check out the CodedInputStream > class (in both C++ and Java) which can be told to limit reads to a > certain number of bytes.) > > >
If you're looking for a C++ solution, Kenton Varda [submitted a patch to protobuf around August 2015](https://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja/22927149#22927149) that adds support for writeDelimitedTo() and readDelimitedFrom() calls that will serialize/deserialize a sequence of proto messages to/from a file in a way that's compatible with the Java version of these calls. Unfortunately this patch hasn't been approved yet, so if you want the functionality you'll need to merge it yourself. Another option is Google has open sourced protobuf file reading/writing code through other projects. The [or-tools](https://github.com/google/or-tools) library, for example, contains the classes [RecordReader](https://developers.google.com/optimization/reference/base/recordio/RecordReader/) and [RecordWriter](https://developers.google.com/optimization/reference/base/recordio/RecordWriter/) that serialize/deserialize a proto stream to a file. If you would like stand-alone versions of these classes that have almost no external dependencies, I have a fork of or-tools that contains only these classes. See: <https://github.com/moof2k/recordio> Reading and writing with these classes is straightforward: ``` File* file = File::Open("proto.log", "w"); RecordWriter writer(file); writer.WriteProtocolMessage(msg1); writer.WriteProtocolMessage(msg2); ... writer.Close(); ```
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
I would recommend using the `writeDelimitedTo(OutputStream)` and `parseDelimitedFrom(InputStream)` methods on `Message` objects. `writeDelimitedTo` writes the length of the message before the message itself; `parseDelimitedFrom` then uses that length to read only one message and no farther. This allows multiple messages to be written to a single `OutputStream` to then be parsed separately. For more information, see <https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite#writeDelimitedTo(java.io.OutputStream)>
An easier way is to base64 encode each message and store it as a record per line.
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
If you're looking for a C++ solution, Kenton Varda [submitted a patch to protobuf around August 2015](https://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja/22927149#22927149) that adds support for writeDelimitedTo() and readDelimitedFrom() calls that will serialize/deserialize a sequence of proto messages to/from a file in a way that's compatible with the Java version of these calls. Unfortunately this patch hasn't been approved yet, so if you want the functionality you'll need to merge it yourself. Another option is Google has open sourced protobuf file reading/writing code through other projects. The [or-tools](https://github.com/google/or-tools) library, for example, contains the classes [RecordReader](https://developers.google.com/optimization/reference/base/recordio/RecordReader/) and [RecordWriter](https://developers.google.com/optimization/reference/base/recordio/RecordWriter/) that serialize/deserialize a proto stream to a file. If you would like stand-alone versions of these classes that have almost no external dependencies, I have a fork of or-tools that contains only these classes. See: <https://github.com/moof2k/recordio> Reading and writing with these classes is straightforward: ``` File* file = File::Open("proto.log", "w"); RecordWriter writer(file); writer.WriteProtocolMessage(msg1); writer.WriteProtocolMessage(msg2); ... writer.Close(); ```
An easier way is to base64 encode each message and store it as a record per line.
9,148,878
I'm using google protocol buffer to serialize equity market data (ie. timestamp, bid,ask fields). I can store one message into a file and deserialize it without issue. How can I store multiple messages into a single file? Not sure how I can separate the messages. I need to be able to append new messages to the file on the fly.
2012/02/05
[ "https://Stackoverflow.com/questions/9148878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249571/" ]
I would recommend using the `writeDelimitedTo(OutputStream)` and `parseDelimitedFrom(InputStream)` methods on `Message` objects. `writeDelimitedTo` writes the length of the message before the message itself; `parseDelimitedFrom` then uses that length to read only one message and no farther. This allows multiple messages to be written to a single `OutputStream` to then be parsed separately. For more information, see <https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite#writeDelimitedTo(java.io.OutputStream)>
If you're looking for a C++ solution, Kenton Varda [submitted a patch to protobuf around August 2015](https://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja/22927149#22927149) that adds support for writeDelimitedTo() and readDelimitedFrom() calls that will serialize/deserialize a sequence of proto messages to/from a file in a way that's compatible with the Java version of these calls. Unfortunately this patch hasn't been approved yet, so if you want the functionality you'll need to merge it yourself. Another option is Google has open sourced protobuf file reading/writing code through other projects. The [or-tools](https://github.com/google/or-tools) library, for example, contains the classes [RecordReader](https://developers.google.com/optimization/reference/base/recordio/RecordReader/) and [RecordWriter](https://developers.google.com/optimization/reference/base/recordio/RecordWriter/) that serialize/deserialize a proto stream to a file. If you would like stand-alone versions of these classes that have almost no external dependencies, I have a fork of or-tools that contains only these classes. See: <https://github.com/moof2k/recordio> Reading and writing with these classes is straightforward: ``` File* file = File::Open("proto.log", "w"); RecordWriter writer(file); writer.WriteProtocolMessage(msg1); writer.WriteProtocolMessage(msg2); ... writer.Close(); ```
116,399
A year ago or so, I received a few expired films, among which this roll of Kodak Tri-X 400, expired in 2013. The film was shipped from the US to Europe. I stored the film in my freezer until I shot it last week, but it does not appear like it was stored cooled back in the US. As per the rule of thumb, I exposed for the film at 2/3 under box speed, so ISO 250. I consider myself to be sufficiently proficient with home-development and have had no serious issues before, and so I was rather surprised to see the film come out of the tank with a thick grey base colour. I am aware of expired film being fogged after a considerable amount of time, but I have never seen anything as strong as this and I did not expect the film to be in such a poor state after a mere 7 years, especially since I am still shooting film from 1985 that's in much better shape. So, my question: what is the cause of this grey base colour? Is it fogging indeed, or is something else at play here? For good measure, I've also included a side-by-side with Catlabs X 80, which was developed in the same batch of chemicals just days prior: Rodinal (Adonal) Adox Stopper and Fixer [![enter image description here](https://i.stack.imgur.com/4iIb5.jpg)](https://i.stack.imgur.com/4iIb5.jpg) [![enter image description here](https://i.stack.imgur.com/LV2AQ.jpg)](https://i.stack.imgur.com/LV2AQ.jpg)
2020/04/04
[ "https://photo.stackexchange.com/questions/116399", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/83099/" ]
Using the Godox TT350N as a means to control your other Godox speedlight is a perfectly viable option. If you later decide to buy a dedicated trigger, you can control both of them. The only drawback is that the controls on the flashes themselves are not as straight forward as they are on the Godox X2 or Xpro. Plus you will probably never use the speedlight on the cam as such in studio. While it is mainly a usability thing, I personally would opt for the dedicated remote trigger, as starting with remote flashes tends to be complicated at first. Why not saving you some hassle?
It's a perfectly viable plan to use a TT350-N (or li-on V350-N) as your iTTL transmitter, but it's not just smaller and less powerful than a V860II-N, it also lacks CLS/AWL capability, it only swivels 270º not 360º, it has no sync port, no external battery port, no recycle beep, and it is not designed to do cross-brand TTL as a radio slave like the full-sized Godox TTL speedlights (TT685, V860II, V1). And the wireless master UI is not as nice or easy to operate as the ones on the dedicated transmitters. You have no remote zoom or modelling light control. You are limited to only three group control, not five, and you do not have access to many of the custom functions on the dedicated transmitters (close mode, SHOOT/APP modes, etc.) Unless you need on-camera and off-camera flash at the same time or really want a second speedlight as backup/alternative, consider the Xpro or Flashpoint R2 Pro II instead of the X2T. For just one feature: TCM (TTL-Convert-to-Manual). None of the speedlights can do it as a radio master. And this is the key to using TTL with off-camera flash, because it lets you lock in the power level set by TTL, to eliminate shot-to-shot flash exposure variance or for fine-tuning in M.
116,399
A year ago or so, I received a few expired films, among which this roll of Kodak Tri-X 400, expired in 2013. The film was shipped from the US to Europe. I stored the film in my freezer until I shot it last week, but it does not appear like it was stored cooled back in the US. As per the rule of thumb, I exposed for the film at 2/3 under box speed, so ISO 250. I consider myself to be sufficiently proficient with home-development and have had no serious issues before, and so I was rather surprised to see the film come out of the tank with a thick grey base colour. I am aware of expired film being fogged after a considerable amount of time, but I have never seen anything as strong as this and I did not expect the film to be in such a poor state after a mere 7 years, especially since I am still shooting film from 1985 that's in much better shape. So, my question: what is the cause of this grey base colour? Is it fogging indeed, or is something else at play here? For good measure, I've also included a side-by-side with Catlabs X 80, which was developed in the same batch of chemicals just days prior: Rodinal (Adonal) Adox Stopper and Fixer [![enter image description here](https://i.stack.imgur.com/4iIb5.jpg)](https://i.stack.imgur.com/4iIb5.jpg) [![enter image description here](https://i.stack.imgur.com/LV2AQ.jpg)](https://i.stack.imgur.com/LV2AQ.jpg)
2020/04/04
[ "https://photo.stackexchange.com/questions/116399", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/83099/" ]
Using the Godox TT350N as a means to control your other Godox speedlight is a perfectly viable option. If you later decide to buy a dedicated trigger, you can control both of them. The only drawback is that the controls on the flashes themselves are not as straight forward as they are on the Godox X2 or Xpro. Plus you will probably never use the speedlight on the cam as such in studio. While it is mainly a usability thing, I personally would opt for the dedicated remote trigger, as starting with remote flashes tends to be complicated at first. Why not saving you some hassle?
An alternative to using a trigger-slave arrangement, that might be cheaper, is to use a hotshoe extension cord. I have a wireless setup (though not for portraiture), but still often find that using the cord to get the flash off-camera is effective and easier than setting up master and slave wireless flashguns. In short, getting an extension cable as a short-term measure won't be wasted investment, even if you later buy a transmitter (discrete or as part of another flash). It's worth getting a manufacturer-specific one (matching your camera) if you're using TTL, as there isn't a common standard for communication except for the central (trigger) pin.
116,399
A year ago or so, I received a few expired films, among which this roll of Kodak Tri-X 400, expired in 2013. The film was shipped from the US to Europe. I stored the film in my freezer until I shot it last week, but it does not appear like it was stored cooled back in the US. As per the rule of thumb, I exposed for the film at 2/3 under box speed, so ISO 250. I consider myself to be sufficiently proficient with home-development and have had no serious issues before, and so I was rather surprised to see the film come out of the tank with a thick grey base colour. I am aware of expired film being fogged after a considerable amount of time, but I have never seen anything as strong as this and I did not expect the film to be in such a poor state after a mere 7 years, especially since I am still shooting film from 1985 that's in much better shape. So, my question: what is the cause of this grey base colour? Is it fogging indeed, or is something else at play here? For good measure, I've also included a side-by-side with Catlabs X 80, which was developed in the same batch of chemicals just days prior: Rodinal (Adonal) Adox Stopper and Fixer [![enter image description here](https://i.stack.imgur.com/4iIb5.jpg)](https://i.stack.imgur.com/4iIb5.jpg) [![enter image description here](https://i.stack.imgur.com/LV2AQ.jpg)](https://i.stack.imgur.com/LV2AQ.jpg)
2020/04/04
[ "https://photo.stackexchange.com/questions/116399", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/83099/" ]
It's a perfectly viable plan to use a TT350-N (or li-on V350-N) as your iTTL transmitter, but it's not just smaller and less powerful than a V860II-N, it also lacks CLS/AWL capability, it only swivels 270º not 360º, it has no sync port, no external battery port, no recycle beep, and it is not designed to do cross-brand TTL as a radio slave like the full-sized Godox TTL speedlights (TT685, V860II, V1). And the wireless master UI is not as nice or easy to operate as the ones on the dedicated transmitters. You have no remote zoom or modelling light control. You are limited to only three group control, not five, and you do not have access to many of the custom functions on the dedicated transmitters (close mode, SHOOT/APP modes, etc.) Unless you need on-camera and off-camera flash at the same time or really want a second speedlight as backup/alternative, consider the Xpro or Flashpoint R2 Pro II instead of the X2T. For just one feature: TCM (TTL-Convert-to-Manual). None of the speedlights can do it as a radio master. And this is the key to using TTL with off-camera flash, because it lets you lock in the power level set by TTL, to eliminate shot-to-shot flash exposure variance or for fine-tuning in M.
An alternative to using a trigger-slave arrangement, that might be cheaper, is to use a hotshoe extension cord. I have a wireless setup (though not for portraiture), but still often find that using the cord to get the flash off-camera is effective and easier than setting up master and slave wireless flashguns. In short, getting an extension cable as a short-term measure won't be wasted investment, even if you later buy a transmitter (discrete or as part of another flash). It's worth getting a manufacturer-specific one (matching your camera) if you're using TTL, as there isn't a common standard for communication except for the central (trigger) pin.
43,699,207
I'm trying to write an `Eq` instance for an `EitherT` newtype given by: ``` newtype EitherT e m a = EitherT { runEitherT :: m (Either e a) } ``` I assumed the following `Eq` instance would work: ``` instance (Eq e, Eq a, Eq m) => Eq (EitherT e m a) where a == b = (runEitherT a) == (runEitherT b) ``` However, I'm seeing an error: ``` Expected kind '* -> *', but 'm' has kind '*' ``` What I'm reading from that error is that my typeclass constraint `( ... Eq m) => ...` is confusing the compiler into thinking that I believe `m` to be of kind `*`, when my newtype declaration for `EitherT` expects it to be of kind `* -> *`. I'm wondering what I need to do, to declare that I want an `Eq` instance for some higher kinded type `m` to implement `Eq` for my `EitherT` newtype. **Edit:** As pointed out by @AlexisKing, I can get this to work with: ``` {-# LANGUAGE UndecideableInstances #-} instance (Eq (m (Either e a))) => Eq (EitherT e m a) where a == b = (runEitherT a) == (runEitherT b) ``` However, it seems strange to me to that a language extension is required to write this `Eq` instance. Is there no other way to express such a typeclass constraint in vanilla Haskell? If not, why?
2017/04/29
[ "https://Stackoverflow.com/questions/43699207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173292/" ]
You're looking for `Eq1` which is in [`Data.Functor.Classes`](https://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Functor-Classes.html) since base 4.9.0.0. Before that it was in one of the `-extras` packages or `transformers`? (it's [in transformers now since 0.4.0.0](https://hackage.haskell.org/package/transformers-0.4.0.0/docs/Data-Functor-Classes.html)) `Eq1 f` says that you can compare `f`s as long as you have a way to compare their contents ``` class Eq1 f where liftEq :: (a -> b -> Bool) -> f a -> f b -> Bool ``` In your case you'd use it like ``` instance (Eq e, Eq1 m) => Eq1 (EitherT e m) where liftEq f a b = liftEq (liftEq f) (runEitherT a) (runEitherT b) ``` The `liftEq f` is to use the existing `Eq1` instance for `Either`. And can define an `Eq` instance as ``` instance (Eq e, Eq a, Eq1 m) => Eq (EitherT e m a) where (==) = liftEq (==) ``` --- The old `Eq1` was ``` class Eq1 f where eq1 :: (Eq a) => f a -> f a -> Bool ``` In your case you'd use it like ``` instance (Eq e, Eq1 m) => Eq1 (EitherT e m) where eq1 a b = eq1 (runEitherT a) (runEitherT b) instance (Eq e, Eq a, Eq1 m) => Eq1 (EitherT e m) where a == b = eq1 (runEitherT a) (runEitherT b) ```
It might be worth noting that this instance already exists in current versions of the `either` package (though not the old `EitherT` package, which is considered obsolete): ``` instance Eq (m (Either e a)) => Eq (EitherT e m a) where (==) = (==) on runEitherT ``` Of course, as @Alexis King has noted, it requires `UndecidableInstances`, but the `either` package is authored by Edward Kmett, a notorious dilettante and amateur who can't write proper Haskell98 like us *real* programmers. ;)
36,649,620
I have a fixed tab layout with 3 tabs. I am trying to have a button in tab1 to add items into a listview in tab2 using `ArrayList`, both of them extends `Fragment`. The below code works only when the the activity extends Activity. Can anyone help me out with an answer to the fix of the problem. I did some testing with an independent activity with a button that adds to listview inside that same activity layout, this is the one that works **MainActivty** ``` public class MainActivity extends Activity { private ListView LView; ArrayList <String> arrayList = new ArrayList<String>(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LView = (ListView) findViewById(R.id.listview); } public void sendToListView(View view) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList); //Sets the adapter to hold the List View LView.setAdapter(adapter); //Adds to the List View arrayList.add("Thursday"); } ``` } **activity\_main** ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="add" android:onClick="sendToListView" android:id="@+id/button"/> </RelativeLayout> ``` **This MainActivity extends Fragment and has an error when i try to implement the same operation** ``` public class MainActivity extends Fragment implements View.OnClickListener { private ListView LView; ArrayList <String> arrayList = new ArrayList<String>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_main, container, false); LView = (ListView) view.findViewById(R.id.listview); return view; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button: ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList); //Here is the error LView.setAdapter(adapter); //Adds to the List View arrayList.add("Thursday"); break; } } ``` } How can i get this working for Fragments, and how could i hve this operation be sent to the other Fragment activity tab and saved to SharedPreferences
2016/04/15
[ "https://Stackoverflow.com/questions/36649620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4900187/" ]
json\_encode from php can be accessed easily in a Javascript varible There are many ways of doing this, however consider the simple way first if it works with the array you are sending. in your example - assuming jquery: ``` var valu = []; $.ajax(url: "url.php", success: function(data){ valu=data; }); ``` see: <http://www.dyn-web.com/tutorials/php-js/json/array.php> works for numeric and associative arrays.
I think you want change your code to something like this.. ``` $.each(data.result, function(index,value){ $("ul").append("<li>Name:"+value.name+"</li>"); alert("kj"); }); ```
36,649,620
I have a fixed tab layout with 3 tabs. I am trying to have a button in tab1 to add items into a listview in tab2 using `ArrayList`, both of them extends `Fragment`. The below code works only when the the activity extends Activity. Can anyone help me out with an answer to the fix of the problem. I did some testing with an independent activity with a button that adds to listview inside that same activity layout, this is the one that works **MainActivty** ``` public class MainActivity extends Activity { private ListView LView; ArrayList <String> arrayList = new ArrayList<String>(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LView = (ListView) findViewById(R.id.listview); } public void sendToListView(View view) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList); //Sets the adapter to hold the List View LView.setAdapter(adapter); //Adds to the List View arrayList.add("Thursday"); } ``` } **activity\_main** ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="add" android:onClick="sendToListView" android:id="@+id/button"/> </RelativeLayout> ``` **This MainActivity extends Fragment and has an error when i try to implement the same operation** ``` public class MainActivity extends Fragment implements View.OnClickListener { private ListView LView; ArrayList <String> arrayList = new ArrayList<String>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_main, container, false); LView = (ListView) view.findViewById(R.id.listview); return view; } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button: ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList); //Here is the error LView.setAdapter(adapter); //Adds to the List View arrayList.add("Thursday"); break; } } ``` } How can i get this working for Fragments, and how could i hve this operation be sent to the other Fragment activity tab and saved to SharedPreferences
2016/04/15
[ "https://Stackoverflow.com/questions/36649620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4900187/" ]
json\_encode from php can be accessed easily in a Javascript varible There are many ways of doing this, however consider the simple way first if it works with the array you are sending. in your example - assuming jquery: ``` var valu = []; $.ajax(url: "url.php", success: function(data){ valu=data; }); ``` see: <http://www.dyn-web.com/tutorials/php-js/json/array.php> works for numeric and associative arrays.
Heres what I would do. ``` $.ajax({ url: "url.php", type: "GET", dataType: 'json' }).done(function (data) { $.each(codes, function(key,value){ $("ul").append('<option value="' + key + '">' + key + ' - ' + value + '</option>'); }); }).fail(function (jqXHR, textStatus, error) { alert("error message"); console.log("error message: " + error); }); ```
14,735,666
I am using CodeIgniter and trying to create thumbs of images. I was successful for some but failed for in some cases. I am getting this following error - ``` << A PHP Error was encountered Severity: Notice Message: imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file Filename: libraries/Image_lib.php Line Number: 1155 >> ``` i used this code after 'image\_lib' library load. ``` ini_set('gd.jpeg_ignore_warning', 1); ``` any solution? Thanks in advance!
2013/02/06
[ "https://Stackoverflow.com/questions/14735666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972328/" ]
The problem is that [error suppression](http://php.net/manual/en/language.operators.errorcontrol.php) is not turned on for the function `imagecreatefromjpeg` The best option is to extend the base library and overload the `image_create_gd` method Create a new file `./application/libraries/MY_Image_lib.php` ``` <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); Class MY_Image_lib extends CI_Image_Lib { function image_create_gd($path = '', $image_type = '') { if ($path == '') $path = $this->full_src_path; if ($image_type == '') $image_type = $this->image_type; switch ($image_type) { case 1 : if ( ! function_exists('imagecreatefromgif')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); return FALSE; } return @imagecreatefromgif($path); break; case 2 : if ( ! function_exists('imagecreatefromjpeg')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); return FALSE; } return @imagecreatefromjpeg($path); break; case 3 : if ( ! function_exists('imagecreatefrompng')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); return FALSE; } return @imagecreatefrompng($path); break; } $this->set_error(array('imglib_unsupported_imagecreate')); return FALSE; } } ```
I was having the exactly the same issue. I was first storing the image data on a local HDD before using the function **imagecreatefromjpeg()** to post-process the image further. At certain times the locally stored image was corrupted during the store process and when called by **imagecreatefromjpeg($imagePath);** the PHP Warning: ***imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file occured.*** showed up. So to resolve the PHP warnings and to make up for the corrupted image I used a clearly defined solution in the PHP manual (<http://php.net/manual/en/function.imagecreatefromjpeg.php>) see the function **LoadJpeg($imgname)** To prevent the further failures I have focused on the reason why the data supplied to **imagecreatefromjpeg()** function was not integrious in the first place. In my case it was the network flood issue which was causing some images to arrive corrupted. Long story short, you may want to check what exactly is being supplied into **imagecreatefromjpeg()** function before trying to extend the base library etc..
14,735,666
I am using CodeIgniter and trying to create thumbs of images. I was successful for some but failed for in some cases. I am getting this following error - ``` << A PHP Error was encountered Severity: Notice Message: imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file Filename: libraries/Image_lib.php Line Number: 1155 >> ``` i used this code after 'image\_lib' library load. ``` ini_set('gd.jpeg_ignore_warning', 1); ``` any solution? Thanks in advance!
2013/02/06
[ "https://Stackoverflow.com/questions/14735666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972328/" ]
The problem is that [error suppression](http://php.net/manual/en/language.operators.errorcontrol.php) is not turned on for the function `imagecreatefromjpeg` The best option is to extend the base library and overload the `image_create_gd` method Create a new file `./application/libraries/MY_Image_lib.php` ``` <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); Class MY_Image_lib extends CI_Image_Lib { function image_create_gd($path = '', $image_type = '') { if ($path == '') $path = $this->full_src_path; if ($image_type == '') $image_type = $this->image_type; switch ($image_type) { case 1 : if ( ! function_exists('imagecreatefromgif')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); return FALSE; } return @imagecreatefromgif($path); break; case 2 : if ( ! function_exists('imagecreatefromjpeg')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); return FALSE; } return @imagecreatefromjpeg($path); break; case 3 : if ( ! function_exists('imagecreatefrompng')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); return FALSE; } return @imagecreatefrompng($path); break; } $this->set_error(array('imglib_unsupported_imagecreate')); return FALSE; } } ```
Try Adding @imagecreatefromjpeg($img) instead of imagecreatefromjpeg($img) here @ is error suppressor
14,735,666
I am using CodeIgniter and trying to create thumbs of images. I was successful for some but failed for in some cases. I am getting this following error - ``` << A PHP Error was encountered Severity: Notice Message: imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file Filename: libraries/Image_lib.php Line Number: 1155 >> ``` i used this code after 'image\_lib' library load. ``` ini_set('gd.jpeg_ignore_warning', 1); ``` any solution? Thanks in advance!
2013/02/06
[ "https://Stackoverflow.com/questions/14735666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972328/" ]
The problem is that [error suppression](http://php.net/manual/en/language.operators.errorcontrol.php) is not turned on for the function `imagecreatefromjpeg` The best option is to extend the base library and overload the `image_create_gd` method Create a new file `./application/libraries/MY_Image_lib.php` ``` <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); Class MY_Image_lib extends CI_Image_Lib { function image_create_gd($path = '', $image_type = '') { if ($path == '') $path = $this->full_src_path; if ($image_type == '') $image_type = $this->image_type; switch ($image_type) { case 1 : if ( ! function_exists('imagecreatefromgif')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); return FALSE; } return @imagecreatefromgif($path); break; case 2 : if ( ! function_exists('imagecreatefromjpeg')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); return FALSE; } return @imagecreatefromjpeg($path); break; case 3 : if ( ! function_exists('imagecreatefrompng')) { $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); return FALSE; } return @imagecreatefrompng($path); break; } $this->set_error(array('imglib_unsupported_imagecreate')); return FALSE; } } ```
I checked that my JPG file was corrupted when I got this error. Consider checking yours.
14,735,666
I am using CodeIgniter and trying to create thumbs of images. I was successful for some but failed for in some cases. I am getting this following error - ``` << A PHP Error was encountered Severity: Notice Message: imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file Filename: libraries/Image_lib.php Line Number: 1155 >> ``` i used this code after 'image\_lib' library load. ``` ini_set('gd.jpeg_ignore_warning', 1); ``` any solution? Thanks in advance!
2013/02/06
[ "https://Stackoverflow.com/questions/14735666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972328/" ]
I was having the exactly the same issue. I was first storing the image data on a local HDD before using the function **imagecreatefromjpeg()** to post-process the image further. At certain times the locally stored image was corrupted during the store process and when called by **imagecreatefromjpeg($imagePath);** the PHP Warning: ***imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file occured.*** showed up. So to resolve the PHP warnings and to make up for the corrupted image I used a clearly defined solution in the PHP manual (<http://php.net/manual/en/function.imagecreatefromjpeg.php>) see the function **LoadJpeg($imgname)** To prevent the further failures I have focused on the reason why the data supplied to **imagecreatefromjpeg()** function was not integrious in the first place. In my case it was the network flood issue which was causing some images to arrive corrupted. Long story short, you may want to check what exactly is being supplied into **imagecreatefromjpeg()** function before trying to extend the base library etc..
I checked that my JPG file was corrupted when I got this error. Consider checking yours.
14,735,666
I am using CodeIgniter and trying to create thumbs of images. I was successful for some but failed for in some cases. I am getting this following error - ``` << A PHP Error was encountered Severity: Notice Message: imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file Filename: libraries/Image_lib.php Line Number: 1155 >> ``` i used this code after 'image\_lib' library load. ``` ini_set('gd.jpeg_ignore_warning', 1); ``` any solution? Thanks in advance!
2013/02/06
[ "https://Stackoverflow.com/questions/14735666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972328/" ]
Try Adding @imagecreatefromjpeg($img) instead of imagecreatefromjpeg($img) here @ is error suppressor
I checked that my JPG file was corrupted when I got this error. Consider checking yours.
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
If you really need an implementation that works, you could "cheat" your way arround by testing the second parameter against `undefined`, this also means you could use get to actually set parameter. ``` var foo = { args: {}, __noSuchMethod__ : function(id, args) { if(args === undefined) { return this.args[id] === undefined ? this[id] : this.args[id] } if(this[id] === undefined) { this.args[id] = args; } else { this[id] = args; } } }; ```
This is not exactly an answer to the original question, however [this](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) and [this](https://stackoverflow.com/questions/1441005/pythons-getattr-in-javascript) questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did. Coming from Python, what I was looking for was an equivalent of `obj.__getattr__(key)`and `obj.__hasattr__(key)` methods. What I ended up using is: `obj[key]` for `getattr` and `obj.hasOwnProperty(key)` for `hasattr` ([doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)).
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
`Proxy` can do it! I'm so happy this exists!! An answer is given here: [Is there a javascript equivalent of python's \_\_getattr\_\_ method?](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) . To rephrase in my own words: ```js var x = new Proxy({}, { get(target, name) { return "Its hilarious you think I have " + name } }) console.log(x.hair) // logs: "Its hilarious you think I have hair" ``` Proxy for the win! Check out the MDN docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy> Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
If you're looking for something like PHP's [`__get()`](http://us3.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members) function, I don't think Javascript provides any such construct. The best I can think of doing is looping through the object's non-function members and then creating a corresponding "getXYZ()" function for each. In dodgy pseudo-ish code: ``` for (o in this) { if (this.hasOwnProperty(o)) { this['get_' + o] = function() { // return this.o -- but you'll need to create a closure to // keep the correct reference to "o" }; } } ```
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
If you're looking for something like PHP's [`__get()`](http://us3.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members) function, I don't think Javascript provides any such construct. The best I can think of doing is looping through the object's non-function members and then creating a corresponding "getXYZ()" function for each. In dodgy pseudo-ish code: ``` for (o in this) { if (this.hasOwnProperty(o)) { this['get_' + o] = function() { // return this.o -- but you'll need to create a closure to // keep the correct reference to "o" }; } } ```
This is not exactly an answer to the original question, however [this](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) and [this](https://stackoverflow.com/questions/1441005/pythons-getattr-in-javascript) questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did. Coming from Python, what I was looking for was an equivalent of `obj.__getattr__(key)`and `obj.__hasattr__(key)` methods. What I ended up using is: `obj[key]` for `getattr` and `obj.hasOwnProperty(key)` for `hasattr` ([doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)).
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
[Javascript 1.5](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference) does have [getter/setter](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/get_Operator) [syntactic sugar](http://en.wikipedia.org/wiki/Syntactic_sugar). It's explained very well by John Resig [here](http://ejohn.org/blog/javascript-getters-and-setters/) It's not generic enough for web use, but certainly Firefox has them (also Rhino, if you ever want to use it on the server side).
It is possible to get a similar result simply by wrapping the object in a getter function: ```js const getProp = (key) => { const dictionary = { firstName: 'John', lastName: 'Doe', age: 42, DEFAULT: 'there is no prop like this' } return (typeof dictionary[key] === 'undefined' ? dictionary.DEFAULT : dictionary[key]); } console.log(getProp('age')) // 42 console.log(getProp('Hello World')) // 'there is no prop like this' ```
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
You can combine proxy and class to have a **nice looking code like php**: ``` class Magic { constructor () { return new Proxy(this, this); } get (target, prop) { return this[prop] || 'MAGIC'; } } ``` this binds to the handler, so you can use this instead of target. **Note: unlike PHP, proxy handles all prop access.** ``` let magic = new Magic(); magic.foo = 'NOT MAGIC'; console.log(magic.foo); // NOT MAGIC console.log(magic.bar); // MAGIC ``` You can check which browsers support proxy <http://caniuse.com/#feat=proxy>.
This is not exactly an answer to the original question, however [this](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) and [this](https://stackoverflow.com/questions/1441005/pythons-getattr-in-javascript) questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did. Coming from Python, what I was looking for was an equivalent of `obj.__getattr__(key)`and `obj.__hasattr__(key)` methods. What I ended up using is: `obj[key]` for `getattr` and `obj.hasOwnProperty(key)` for `hasattr` ([doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)).
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
`Proxy` can do it! I'm so happy this exists!! An answer is given here: [Is there a javascript equivalent of python's \_\_getattr\_\_ method?](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) . To rephrase in my own words: ```js var x = new Proxy({}, { get(target, name) { return "Its hilarious you think I have " + name } }) console.log(x.hair) // logs: "Its hilarious you think I have hair" ``` Proxy for the win! Check out the MDN docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy> Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
I ended up using a nickfs' answer to construct my own solution. My solution will automatically create get\_{propname} and set\_{propname} functions for all properties. It does check if the function already exists before adding them. This allows you to override the default get or set method with our own implementation without the risk of it getting overwritten. ``` for (o in this) { if (this.hasOwnProperty(o)) { var creategetter = (typeof this['get_' + o] !== 'function'); var createsetter = (typeof this['set_' + o] !== 'function'); (function () { var propname = o; if (creategetter) { self['get_' + propname] = function () { return self[propname]; }; } if (createsetter) { self['set_' + propname] = function (val) { self[propname] = val; }; } })(); } } ```
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
`Proxy` can do it! I'm so happy this exists!! An answer is given here: [Is there a javascript equivalent of python's \_\_getattr\_\_ method?](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) . To rephrase in my own words: ```js var x = new Proxy({}, { get(target, name) { return "Its hilarious you think I have " + name } }) console.log(x.hair) // logs: "Its hilarious you think I have hair" ``` Proxy for the win! Check out the MDN docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy> Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
The closest you can find is [\_\_noSuchMethod\_\_](https://web.archive.org/web/20210224190946/https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Object.noSuchMethod) ([\_\_noSuchMethod\_\_ is deprecated](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#object_methods)), which is JavaScript's equivalent of PHP's \_\_call(). Unfortunately, there's no equivalent of \_\_get/\_\_set, which is a shame, because with them we could have implemented \_\_noSuchMethod\_\_, but I don't yet see a way to implement properties (as in C#) using \_\_noSuchMethod\_\_. ``` var foo = { __noSuchMethod__ : function(id, args) { alert(id); alert(args); } }; foo.bar(1, 2); ```
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
`Proxy` can do it! I'm so happy this exists!! An answer is given here: [Is there a javascript equivalent of python's \_\_getattr\_\_ method?](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) . To rephrase in my own words: ```js var x = new Proxy({}, { get(target, name) { return "Its hilarious you think I have " + name } }) console.log(x.hair) // logs: "Its hilarious you think I have hair" ``` Proxy for the win! Check out the MDN docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy> Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
[Javascript 1.5](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference) does have [getter/setter](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/get_Operator) [syntactic sugar](http://en.wikipedia.org/wiki/Syntactic_sugar). It's explained very well by John Resig [here](http://ejohn.org/blog/javascript-getters-and-setters/) It's not generic enough for web use, but certainly Firefox has them (also Rhino, if you ever want to use it on the server side).
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
The closest you can find is [\_\_noSuchMethod\_\_](https://web.archive.org/web/20210224190946/https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Object.noSuchMethod) ([\_\_noSuchMethod\_\_ is deprecated](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#object_methods)), which is JavaScript's equivalent of PHP's \_\_call(). Unfortunately, there's no equivalent of \_\_get/\_\_set, which is a shame, because with them we could have implemented \_\_noSuchMethod\_\_, but I don't yet see a way to implement properties (as in C#) using \_\_noSuchMethod\_\_. ``` var foo = { __noSuchMethod__ : function(id, args) { alert(id); alert(args); } }; foo.bar(1, 2); ```
This is not exactly an answer to the original question, however [this](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) and [this](https://stackoverflow.com/questions/1441005/pythons-getattr-in-javascript) questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did. Coming from Python, what I was looking for was an equivalent of `obj.__getattr__(key)`and `obj.__hasattr__(key)` methods. What I ended up using is: `obj[key]` for `getattr` and `obj.hasOwnProperty(key)` for `hasattr` ([doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)).
994,143
Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript. My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me. The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for *all* possible names. I'm not sure if this is possible, but I'd very much like to know.
2009/06/15
[ "https://Stackoverflow.com/questions/994143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91238/" ]
`Proxy` can do it! I'm so happy this exists!! An answer is given here: [Is there a javascript equivalent of python's \_\_getattr\_\_ method?](https://stackoverflow.com/questions/1529496/is-there-a-javascript-equivalent-of-pythons-getattr-method) . To rephrase in my own words: ```js var x = new Proxy({}, { get(target, name) { return "Its hilarious you think I have " + name } }) console.log(x.hair) // logs: "Its hilarious you think I have hair" ``` Proxy for the win! Check out the MDN docs: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy> Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
It is possible to get a similar result simply by wrapping the object in a getter function: ```js const getProp = (key) => { const dictionary = { firstName: 'John', lastName: 'Doe', age: 42, DEFAULT: 'there is no prop like this' } return (typeof dictionary[key] === 'undefined' ? dictionary.DEFAULT : dictionary[key]); } console.log(getProp('age')) // 42 console.log(getProp('Hello World')) // 'there is no prop like this' ```
65,578,085
I am new to working on a MongoDB and Docker, I am working on an application and couldn't find a more subtle way to seed my database using an npm run command. First I created a file called seed.js and then associated it to npm run seed command on the package.json file. On the seed.js file I import Mongoose and the models but two things I will need to do is: * Create roles, if they don’t exist yet * Create capabilities, if they don’t exist yet and associate it to the roles The Roles that i want to create are: * admin (description: Administrator) * viewer (description: Viewer) Capabilities I need to check each endpoint of the Users service that should require authentication and create an adequate capability. Example: updateUser updates the user data. This could be done by the own user (so there must be an updateUserOwn capability) and by an administrator (that will have an updateUsers capability). I will have to analyse each endpoint and judge what is adequate but I cannot still find a way around getting the initial role and capabilities to the database. **UPDATE:** On the seeding itself, the updated solution works, but it requires lot of code and repetition that could probably be fixed by loops. I’d like to start creating the roles first which means creating an array with objects, with the data from the roles to be created. Each role has the fields role and description ```js const userRole = [{ role: admin description: Administrator }, { role: viewer description: Viewer }] ``` The idea is that if the role exist it doesn't need to update but I don't know how do I loop through the array and create a role only if it doesn’t exist. Something like using updateOne, with the upsert: true option, but with the data on $setOnInsert as this will add the data only if a document is inserted. I only need create and not update because in the future I’ll edit roles directly through the API. So, if a change was made on the admin role, for example, the seed will not overwrite it During the loop, I'll need to create an associative array called rolesIds that will store the ObjectId of the created roles. It should result in something like this: ```js [ "admin": "iaufh984whrfj203jref", "viewer": "r9i23jfeow9iefd0ew0", ] ``` Also each capability must have an array of roles it must be associated to. Example: ```js { capability: "updateUsers", description: "Update the data of all users", roles: ["admin"] } ``` How do I loop through the array on each element, prepare it to be inserted using the array with object IDs. Instead of roles: ["admin"]? something like roles: ["iaufh984whrfj203jref"], otherwise there’ll be a cast error. Remember each capability may be associated to more than one role, so I'll probably need to loop through them but I cannot find a way to create that logic. Users Model ```js const userSchema = new mongoose.Schema( { ....... role: { ref: "roles", type: mongoose.Schema.Types.ObjectId, }, ); module.exports = mongoose.model("User", userSchema); ``` Role Model: ```js const roles = new mongoose.Schema({ role: { type: String, required: true, }, capabilities: [ { type: mongoose.Schema.Types.ObjectId, ref: "capabilities", }, ], }); module.exports = mongoose.model("roles", roles); ``` Capabilities Model: ```js const capabilities = new mongoose.Schema({ capability: { type: String, required: true, }, name: { type: String, }, }); module.exports = mongoose.model("capabilities", capabilities); ``` **UPDATED:** seed file: ```js const seedDB = async () => { if (!process.env.DB_URI) { throw new Error("Error connecting to MongoDB: DB_URI is not defined."); } try { await mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); console.log("Connected to MongoDB"); const tasks = [ Capability.findOneAndUpdate( { name: "updateUserOwn" }, { capability: "updateUser" }, { upsert: true } ).exec(), Capability.findOneAndUpdate( { name: "updateUsers" }, { capability: "updateUser" }, { upsert: true } ).exec(), // Seed more... ]; const [updateUserOwn, updateUsers] = await Promise.all(tasks); Role.bulkWrite([ { updateOne: { filter: { role: "Admin" }, update: { capabilities: [updateUsers] }, upsert: true, }, }, { updateOne: { filter: { role: "Viewer" }, update: { capabilities: [updateUserOwn] }, upsert: true, }, }, ]); console.log("seeded data", tasks); } catch (error) { console.log(`Error connecting to MongoDB: ${error}`); } }; seedDB(); ```
2021/01/05
[ "https://Stackoverflow.com/questions/65578085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14944005/" ]
Add redirection along with the `alert()` in js rather than doing in php. ``` echo "<script>alert('The profile has been deleted.'); window.location.href='logout.php';</script>"; ``` This will show alert then redirect to logout.php
try change the following code: From: ``` <?php session_start(); session_unset(); session_destroy(); header("location: ../index.php"); exit(); ``` To: ``` <?php session_start(); session_unset(); session_destroy(); echo "<script>alert('The profile has been deleted.');</script>"; header("location: ../index.php"); exit(); ```
214,469
I tried filling a numpy array with the foreach\_get() method on an image, but get the following error: *foreach\_get/set() takes exactly 1 argument (2 given)* ``` def read_pixels(img): resolution = img.size[0] * img.size[1] colors = np.zeros(resolution*4, dtype=np.float) img.pixels.foreach_get("pixels", colors) colors = np.reshape(colors, (resolution, 4)) return colors img = bpy.data.images['TestImg.png'] print(read_pixels(img)) ``` foreach\_get() should take 2 arguments, doesn't it? The name of the attribute ('pixels') and the array to be filled?!
2021/03/09
[ "https://blender.stackexchange.com/questions/214469", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/18208/" ]
**"The python console check"** In case Markus is busy can get a lot of info using autocomplete `Tab` in the python console, with an image as `img` ``` >>> img.pixels.foreach_get( foreach_get(seq) .. method:: foreach_get(seq) This is a function to give fast access to array data. ``` which is plainly different from, for instance a mesh `me` vertices, which asks for an attribute `attr` , *eg* for vert coordinates `"co"` ``` >>> me.vertices.foreach_get( foreach_get(attr, seq) .. method:: foreach_get(attr, seq) This is a function to give fast access to attributes within a collection. ``` A very slight improvement in speed can be attained by using `np.empty` to initialize the array, since any garbage will be filled by the foreach get. ``` import time import numpy as np REPS = 100 def time_it(func): def wrapper(*arg, **kw): t1 = time.time() for i in range(REPS): func(*arg, **kw) t2 = time.time() print(func.__name__, (t2 - t1)) return wrapper @time_it def read_pixels(img): resolution = img.size[0] * img.size[1] colors = np.zeros(resolution*4, dtype=np.float32) img.pixels.foreach_get(colors) colors = np.reshape(colors, (resolution, 4)) return colors @time_it def read_pixels2(img): x, y = img.size pixels = np.empty(x * y << 2, dtype=np.float32) img.pixels.foreach_get(pixels) return pixels.reshape((x, y, 4)) @time_it def nptest1(img): x, y = img.size return np.array(img.pixels, dtype=np.float32).reshape((x, y, 4)) @time_it def nptest2(img): x, y = img.size return np.array(img.pixels[:], dtype=np.float32).reshape((x, y, 4)) import bpy for img in bpy.data.images: nptest1(img) nptest2(img) read_pixels(img) read_pixels2(img) #break ``` Results ``` nptest1 8.4240 nptest2 7.0605 read_pixels 0.2264 read_pixels2 0.2222 ``` Note on posting noticed I had reshaped to image x, y, 4, however reshape is an almost time "free" method, will get back if otherwise. (Got a squeak more using bitwise shift to quadruple)
as Markus von Broady pointed out, ommiting the attribute name and just passing the numpy array works. Thank you. I was confused, because specifying the the attribute name worked in other areas, e.g. ``` sculpt_vertex_colors[name].data.foreach_get('color', colors) ``` But I guess that's a different structure. Had to change the dtype to float32 instead of just float. Here is the corrected example ``` def read_pixels(img): resolution = img.size[0] * img.size[1] colors = np.zeros(resolution*4, dtype=np.float32) img.pixels.foreach_get(colors) colors = np.reshape(colors, (resolution, 4)) return colors img = bpy.data.images['TestImg.png'] print(read_pixels(img)) ```
43,862,991
``` def letter_case_count(string) char = new Hash char[:lower] = 0 char[:upper] = 0 char[:neither] = 0 string.split("").each do |x| if ('A'..'Z').include?(x) char[:upper]++ elsif ('a'..'z').include?(x) char[:lower]++ else char[:neither]++ end end end puts letter_case_count('abCdef 123') == { lowercase: 5, uppercase: 1, neither: 4 } puts letter_case_count('AbCd +Ef') == { lowercase: 3, uppercase: 3, neither: 2 } puts letter_case_count('123') == { lowercase: 0, uppercase: 0, neither: 3 } puts letter_case_count('') == { lowercase: 0, uppercase: 0, neither: 0 } ``` I get this error. ``` (repl):9: syntax error, unexpected keyword_elsif elsif ('a'..'z').include?(x) ^ (repl):11: syntax error, unexpected keyword_else (repl):13: syntax error, unexpected keyword_end (repl):20: syntax error, unexpected end-of-input, expecting keyword_end ...: 0, uppercase: 0, neither: 0 } ... ^ ``` There are a bunch of unexpected keywords and unexpected end of inputs. Not sure why, I haven't programmed in Ruby in almost a yearn and I can't see what the problem is.
2017/05/09
[ "https://Stackoverflow.com/questions/43862991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6571158/" ]
Ruby doesn't have `pre-increment` or `post-increment` operators. Use `+=1` and it should work. ``` def letter_case_count(string) char = {} char[:lower] = 0 char[:upper] = 0 char[:neither] = 0 string.split('').each do |x| if ('A'..'Z').include?(x) char[:upper] += 1 elsif ('a'..'z').include?(x) char[:lower] += 1 else char[:neither] += 1 end end char #returning the char is also important. end ``` Using different keys for comparison will also return wrong results, it should be.. ``` puts letter_case_count('abCdef 123') == { lower: 5, upper: 1, neither: 4 } puts letter_case_count('AbCd +Ef') == { lower: 3, upper: 3, neither: 2 } puts letter_case_count('123') == { lower: 0, upper: 0, neither: 3 } puts letter_case_count('') == { lower: 0, upper: 0, neither: 0 } ``` **Better Approach:** ``` def letter_case_count(string) { lower: string.scan(/[a-z]/).count, upper: string.scan(/[A-Z]/).count, neither: string.scan(/[^a-z]/i).count } end ```
There are bunch of syntax errors in your code. ``` def letter_case_count(string) char = Hash.new # not new Hash char[:lower] = 0 char[:upper] = 0 char[:neither] = 0 string.split("").each do |x| if ('A'..'Z').include?(x) char[:upper]+=1 # var++ is not valid ruby code elsif ('a'..'z').include?(x) char[:lower]+=1 #same here else char[:neither]+=1 # same here end end end puts letter_case_count('abCdef 123') == { lowercase: 5, uppercase: 1, neither: 4 } puts letter_case_count('AbCd +Ef') == { lowercase: 3, uppercase: 3, neither: 2 } puts letter_case_count('123') == { lowercase: 0, uppercase: 0, neither: 3 } puts letter_case_count('') == { lowercase: 0, uppercase: 0, neither: 0 } ``` **UPDATE** For that kind of tasks, use Ruby's minitest from stdlib. All in one file example (all of them will fail) ``` require 'minitest/autorun' class String def letter_case_count char = Hash.new # not new Hash char[:lower] = 0 char[:upper] = 0 char[:neither] = 0 self.split("").each do |x| if ('A'..'Z').include?(x) char[:upper]+=1 # var++ is not valid ruby code elsif ('a'..'z').include?(x) char[:lower]+=1 #same here else char[:neither]+=1 # same here end end return char end end class TestFoo < MiniTest::Test def setup @w1, @w2, @w3, @w4 = ["abCdef 123", "AbCd +Ef", "123", ""].map {|e| String.new(e)} end def test_some assert_equal @w1.letter_case_count, { lowercase: 3, uppercase: 1, neither: 4 } end def test_some_other assert_equal @w2.letter_case_count, { lowercase: 3, uppercase: 3, neither: 2 } end def test_other assert_equal @w3.letter_case_count, { lowercase: 0, uppercase: 0, neither: 3 } end def test_definitely_other assert_equal @w4.letter_case_count, { lowercase: 0, uppercase: 0, neither: 0 } end end ```
61,016,694
I have the following ``` class Person private String firstName; private String familyName; // Setters and Getters ``` And I have the following method ``` public String getFullName(Optional<Person> persons) { return persons .map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("Invalid"); } ``` I just want to check if either first or last name is `null`, display `"Invalid"` for that person. I was thinking to add a method for validation but I am sure there is an easier way I cannot think about.
2020/04/03
[ "https://Stackoverflow.com/questions/61016694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12051965/" ]
You are looking to [`Optional::filter`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#filter-java.util.function.Predicate-), before the map: ``` return persons .filter(person -> person.getFamilyName() != null && person.getFirstName() != null) .map(person -> person.getFirstName() + " " + person.getFamilyName()) .orElse("Invalid"); ``` Which mean, if the family and first names are not null then create your concatination, otherwise return an Invalid message, or you can even throw an exception by using `orElseThrow`
You can use filter for that: ``` public String getFullName(Optional<Person> persons) { return persons .filter(person -> Objects.nonNull(person.getFirstName()) && Objects.nonNull(person.getFamilyName())) .map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("Invalid"); } ```
61,016,694
I have the following ``` class Person private String firstName; private String familyName; // Setters and Getters ``` And I have the following method ``` public String getFullName(Optional<Person> persons) { return persons .map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("Invalid"); } ``` I just want to check if either first or last name is `null`, display `"Invalid"` for that person. I was thinking to add a method for validation but I am sure there is an easier way I cannot think about.
2020/04/03
[ "https://Stackoverflow.com/questions/61016694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12051965/" ]
You are looking to [`Optional::filter`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#filter-java.util.function.Predicate-), before the map: ``` return persons .filter(person -> person.getFamilyName() != null && person.getFirstName() != null) .map(person -> person.getFirstName() + " " + person.getFamilyName()) .orElse("Invalid"); ``` Which mean, if the family and first names are not null then create your concatination, otherwise return an Invalid message, or you can even throw an exception by using `orElseThrow`
Another functional approach. First create a predicate builder method for required field validation: ``` public static <T, F> Predicate<T> hasRequiredValue(Function<T, F> fieldGetter) { return fieldGetter.andThen(Objects::nonNull)::apply; } ``` And modify the `getFullName` a little bit: ``` public Optional<String> getFullName(Person person) { return Optional.ofNullable(person) .filter(hasRequiredValue(Person::getFamilyName)) .filter(hasRequiredValue(Person::getFirstName)) .map(p -> p.getFirstName() + " " + p.getFamilyName()); } ``` Then use it as follows: ``` Person person = ... String fullName = getFullName(person).orElse("Invalid"); ```
34,228,552
I want to generate an XML of the following format using XmlWriter class in C# -: ``` <?xml version="1.0" ?> <root> <data> <entry Attrib1="" Attrib2="91.3467" Attrib3="95.3052" Attrib4="6.4722" /> <entry Attrib1="" Attrib2="91.3467" Attrib3="95.3052" Attrib4="6.4722" /> </data> </root> ``` I am very new to XmlWriter class and to C# in general and I have tried writing code for generating the file with the above format, but that attempt was unsuccessful ``` var xmlWriter = XmlWriter.Create(filename); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("data"); xmlWriter.WriteStartElement("entry"); xmlWriter.WriteAttributeString("attrib1", "value1"); xmlWriter.WriteAttributeString("attrib2", "value2"); xmlWriter.Close(); ``` also, the name of the attributes can included illegal XML characters and that's why I read up on `XMLWriter` because it seems to remove those illegal characters from the names of the attributes for instance a name like "this is attribute 1" should be reduced to something like "this\_is\_attribute\_1" when written to the resulting XML, how do I go about producing such `XML` using `XmlWriter`. In short a row of the resulting XML is something like this ``` <entry P_B_Pe="" P_E_Pe="91.3467" Custom_Price="95.3052" C_Yield="6.4722" Average_Life="" /> ```
2015/12/11
[ "https://Stackoverflow.com/questions/34228552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/862962/" ]
You've almost got it... ``` var xmlWriter = XmlWriter.Create(filename); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("root"); xmlWriter.WriteStartElement("data"); xmlWriter.WriteStartElement("entry"); xmlWriter.WriteAttributeString("attrib1", "value1"); xmlWriter.WriteAttributeString("attrib2", "value2"); xmlWriter.WriteEndElement(); // entry xmlWriter.WriteStartElement("entry"); xmlWriter.WriteAttributeString("attrib1", "value1"); xmlWriter.WriteAttributeString("attrib2", "value2"); xmlWriter.WriteEndElement(); // entry xmlWriter.WriteEndElement(); // data xmlWriter.WriteEndElement(); // root xmlWriter.WriteEndDocument(); xmlWriter.Close(); ``` By default `XmlWriter` will encode characters that are not normally valid in raw data or in attribute values in such a way that they will come back when you use a reader decode the XML, but attribute and element names must still be valid. If you want to handle invalid characters for those in some special way that's different from that, you'll need to do that yourself according to whatever rules you want to establish, something like: ``` xmlWriter.WriteAttributeString(MyXmlExtensions.EncodeXmlAttributeName("this is normally an invalid attribute name"), "value1"); class MyXmlExtensions { public string EncodeXmlAttributeName(string decoded) { // not that you'll likely need to enhance this with whatever rules you want but haven't specified return decoded.Replace(" ", "_"); } public string DecodeXmlAttributeName(string encoded) { // not that you'll likely need to enhance this with whatever rules you want but haven't specified return encoded.Replace("_", " "); } } ``` You'll also need to use `XmlWriterSettings` in the call to `XmlWriter.Create` if you want the output to look pretty (tabs, multiple lines, etc.).
Try XML Linq ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using System.IO; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { StreamWriter sWriter = new StreamWriter(FILENAME); XmlTextWriter writer = new XmlTextWriter(sWriter); writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteStartElement("data"); double?[] attributes = new double?[] { null, 91.3467, 95.3052, 6.4722 }; XElement entry = new XElement("entry"); int index = 1; foreach (double? attribute in attributes) { if (attribute == null) { entry.Add(new XAttribute("Attrib" + index++.ToString(), "")); } else { entry.Add(new XAttribute("Attrib" + index++.ToString(), attribute)); } } writer.WriteRaw(entry.ToString()); writer.WriteRaw(entry.ToString()); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); writer.Close(); } } } ​ ``` doing without any xml linq then ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using System.IO; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { StreamWriter sWriter = new StreamWriter(FILENAME); XmlTextWriter writer = new XmlTextWriter(sWriter); writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteStartElement("data"); writer.WriteStartElement("entry"); double?[] attributes = new double?[] { null, 91.3467, 95.3052, 6.4722 }; int index = 1; foreach (double? attribute in attributes) { writer.WriteStartAttribute("Attrib" + index++.ToString()); if (attribute == null) { writer.WriteValue(""); } else { writer.WriteValue(attribute); } writer.WriteEndAttribute(); } writer.WriteEndElement(); writer.WriteStartElement("entry"); attributes = new double?[] { null, 91.3467, 95.3052, 6.4722 }; index = 1; foreach (double? attribute in attributes) { writer.WriteStartAttribute("Attrib" + index++.ToString()); if (attribute == null) { writer.WriteValue(""); } else { writer.WriteValue(attribute); } writer.WriteEndAttribute(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); writer.Close(); } } } ​ ```
34,228,552
I want to generate an XML of the following format using XmlWriter class in C# -: ``` <?xml version="1.0" ?> <root> <data> <entry Attrib1="" Attrib2="91.3467" Attrib3="95.3052" Attrib4="6.4722" /> <entry Attrib1="" Attrib2="91.3467" Attrib3="95.3052" Attrib4="6.4722" /> </data> </root> ``` I am very new to XmlWriter class and to C# in general and I have tried writing code for generating the file with the above format, but that attempt was unsuccessful ``` var xmlWriter = XmlWriter.Create(filename); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("data"); xmlWriter.WriteStartElement("entry"); xmlWriter.WriteAttributeString("attrib1", "value1"); xmlWriter.WriteAttributeString("attrib2", "value2"); xmlWriter.Close(); ``` also, the name of the attributes can included illegal XML characters and that's why I read up on `XMLWriter` because it seems to remove those illegal characters from the names of the attributes for instance a name like "this is attribute 1" should be reduced to something like "this\_is\_attribute\_1" when written to the resulting XML, how do I go about producing such `XML` using `XmlWriter`. In short a row of the resulting XML is something like this ``` <entry P_B_Pe="" P_E_Pe="91.3467" Custom_Price="95.3052" C_Yield="6.4722" Average_Life="" /> ```
2015/12/11
[ "https://Stackoverflow.com/questions/34228552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/862962/" ]
You've almost got it... ``` var xmlWriter = XmlWriter.Create(filename); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("root"); xmlWriter.WriteStartElement("data"); xmlWriter.WriteStartElement("entry"); xmlWriter.WriteAttributeString("attrib1", "value1"); xmlWriter.WriteAttributeString("attrib2", "value2"); xmlWriter.WriteEndElement(); // entry xmlWriter.WriteStartElement("entry"); xmlWriter.WriteAttributeString("attrib1", "value1"); xmlWriter.WriteAttributeString("attrib2", "value2"); xmlWriter.WriteEndElement(); // entry xmlWriter.WriteEndElement(); // data xmlWriter.WriteEndElement(); // root xmlWriter.WriteEndDocument(); xmlWriter.Close(); ``` By default `XmlWriter` will encode characters that are not normally valid in raw data or in attribute values in such a way that they will come back when you use a reader decode the XML, but attribute and element names must still be valid. If you want to handle invalid characters for those in some special way that's different from that, you'll need to do that yourself according to whatever rules you want to establish, something like: ``` xmlWriter.WriteAttributeString(MyXmlExtensions.EncodeXmlAttributeName("this is normally an invalid attribute name"), "value1"); class MyXmlExtensions { public string EncodeXmlAttributeName(string decoded) { // not that you'll likely need to enhance this with whatever rules you want but haven't specified return decoded.Replace(" ", "_"); } public string DecodeXmlAttributeName(string encoded) { // not that you'll likely need to enhance this with whatever rules you want but haven't specified return encoded.Replace("_", " "); } } ``` You'll also need to use `XmlWriterSettings` in the call to `XmlWriter.Create` if you want the output to look pretty (tabs, multiple lines, etc.).
Use object serialisation, then you don't have to have object to structure mapping code ``` using System.Xml.Serialization; ... [XmlRoot("root")] public class Example { [XmlElement("data")] public Entries Entries { get; set; } } public class Entries : List<List<string>>, IXmlSerializable { public List<string> Attribs { get; set; } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { reader.MoveToContent(); } public void WriteXml(System.Xml.XmlWriter writer) { foreach (var entry in this) { writer.WriteStartElement("entry", ""); var label = 1; foreach (var attrib in entry) { writer.WriteAttributeString(string.Format("Attrib{0}", label), attrib); label++; } writer.WriteEndElement(); } } } ... var xml = new XmlSerializer(typeof(Example), ""); xml.Serialize(stream, example); ```
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
I tend to agree with the answer Val provided. The simplest way to deal with this is to talk to the person. If talking to the person, for whatever reason, is out of the question or uncomfortable, you could try posting a sign on the door asking that people be cautious when closing the door so as not to disrupt the office. Some might find this to be a bit passive aggressive, but it might raise awareness to your colleague and he may stop on his own. It may also provide the additional benefit of your colleague not feeling singled out.
It's beyond simple: The phrase you're looking for is "Do you mind" or "Would you mind" not letting the door close so noisily. The title of the question is asking for "the right way". This is it. Absent other factors which haven't been mentioned here, like previous interactions which would make this a touchy or difficult subject for conversation, this is a perfectly conventional request format which should convey the standard level of politeness and neutrality. If you say this, you're not making it about the colleague's bad mood, you're not accusing them of being unmannerly, you're just pointing out a disturbance and asking for consideration. "I do not want to offend him" - Right, that's the beauty of these standard conventional phrases which we've inherited from generations past. Unless there's some other history or information here which makes you think that the standard request is going to offend him, go with the conventional standard mannerly phrase. On the other hand, that's usually the best we can do, and we're really not responsible for unreasonable reactions on other people's part. If this person does act offended, that's an unforgivable imposition on **you**.
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
> > excuse me "ColleagueName", the door banging so hard sometimes disturbs my concentration, could you please try and close it more softly? Thank you > > > if he doesn't do it on purpose probably you will have to remind it to him few times because it might happen again.
If you want to avoid conflict and don't mind taking ownership, I would suggest saying something like, "Hi \_\_\_, would you be willing to help me out? Sometimes when you leave the room, and shut the door, the noise of is loud enough that it breaks my concentration and it is a while before I can refocus. Would you be willing to try to close the door more softly? That would really help me concentrate and I would be a more pleasant co-worker to be around." **Key points:** * it's about your need and you're asking for his help * it's his behavior that you are asking him to change * it's not him personally * you are not judging him (as inconsiderate, angry, thoughtless, etc.) I would stick with that, even if he asks questions like "Am I being rude?" I would answer back with "It would really help me if you closed the door softer. Would you be willing to help me out with that?"
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
> > excuse me "ColleagueName", the door banging so hard sometimes disturbs my concentration, could you please try and close it more softly? Thank you > > > if he doesn't do it on purpose probably you will have to remind it to him few times because it might happen again.
Perhaps your colleague "looks really grumpy or depressed. ... talks very little" because of something at home or elsewhere, that's probably not your business. > > "... he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second.". > > > So you object to the way he operates the door. He knows a special way to keep it vibrating. > > "There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly.". > > > That's understandable, but does everyone agree or are only you disturbed? > > "... but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?". > > > You need to figure out the results you want and how quickly you need them. You don't want to come across as trying to portray him as an unsociable oaf, whom doesn't know how to operate a door. If you were friends with this person it should be easy enough, but that doesn't seem the case. You'll need to time your approach and decide how gingerly you want to proceed. * Approach #1: + When he passes through the door ask if everything is OK. + If it is not ask if there's anything you can do, if everything is great even better. + Mention that he seems unhappy and has been slamming the door lately, it's come to the point where you need to bring this up; it's very disturbing. * Approach #2: + Tell the boss, get them to resolve this. Suggest they pay to have the door *repaired*. * Approach #3: + Tell them directly: "Shhhh!, there's no reason to be so noisy". * Approach #4: I tried searching the Internet for 'door operating instructions', I couldn't find anything (except for a dryer door); therein lies the problem ... You could try making a label and printing it on to a clear sticker - calculate his exact eye-height and line it up. Stick it to the door at lunch or after work anonymously. I did manage to find something ***less*** than "Operating Instructions" but it should serve as a polite and anonymous hint: [![Door Sticker](https://i.stack.imgur.com/Hd7YP.jpg)](http://www.pushandpullman.com/)
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
If he enters the room and slams the door, ask him immediately like "don't you think that was too hard?". Or if he isn't afraid to destroy the door. Reminding someone of this shouldn't yet be offending. Start with a hint to make him think about that. If this doesn't help, slowly become more direct. Try to not say that every time at the beginning, see if it develops to get better. It can help to avoid he feels too guilty every time he walks through the door. Such habits need some time to vanish, there is a chance he slams the door and reminds oh next time I should no longer... If he was a funny person you'd have a better position making stupid jokes about that. Such like "**BANGING DOOR** - oh colleague xy has arrived" or "has our next department exploded or is xy here?". But the way you describe him lets assume there is no big sense of humour. It's important to discuss this with your colleagues, each of you should take turn to remind him. This doesn't make one single person the "bad guy" but shows that all of you are affected, this adds more seriousity to the topic.
If you want to avoid conflict and don't mind taking ownership, I would suggest saying something like, "Hi \_\_\_, would you be willing to help me out? Sometimes when you leave the room, and shut the door, the noise of is loud enough that it breaks my concentration and it is a while before I can refocus. Would you be willing to try to close the door more softly? That would really help me concentrate and I would be a more pleasant co-worker to be around." **Key points:** * it's about your need and you're asking for his help * it's his behavior that you are asking him to change * it's not him personally * you are not judging him (as inconsiderate, angry, thoughtless, etc.) I would stick with that, even if he asks questions like "Am I being rude?" I would answer back with "It would really help me if you closed the door softer. Would you be willing to help me out with that?"
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
> > excuse me "ColleagueName", the door banging so hard sometimes disturbs my concentration, could you please try and close it more softly? Thank you > > > if he doesn't do it on purpose probably you will have to remind it to him few times because it might happen again.
If he enters the room and slams the door, ask him immediately like "don't you think that was too hard?". Or if he isn't afraid to destroy the door. Reminding someone of this shouldn't yet be offending. Start with a hint to make him think about that. If this doesn't help, slowly become more direct. Try to not say that every time at the beginning, see if it develops to get better. It can help to avoid he feels too guilty every time he walks through the door. Such habits need some time to vanish, there is a chance he slams the door and reminds oh next time I should no longer... If he was a funny person you'd have a better position making stupid jokes about that. Such like "**BANGING DOOR** - oh colleague xy has arrived" or "has our next department exploded or is xy here?". But the way you describe him lets assume there is no big sense of humour. It's important to discuss this with your colleagues, each of you should take turn to remind him. This doesn't make one single person the "bad guy" but shows that all of you are affected, this adds more seriousity to the topic.
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
If you want to avoid conflict and don't mind taking ownership, I would suggest saying something like, "Hi \_\_\_, would you be willing to help me out? Sometimes when you leave the room, and shut the door, the noise of is loud enough that it breaks my concentration and it is a while before I can refocus. Would you be willing to try to close the door more softly? That would really help me concentrate and I would be a more pleasant co-worker to be around." **Key points:** * it's about your need and you're asking for his help * it's his behavior that you are asking him to change * it's not him personally * you are not judging him (as inconsiderate, angry, thoughtless, etc.) I would stick with that, even if he asks questions like "Am I being rude?" I would answer back with "It would really help me if you closed the door softer. Would you be willing to help me out with that?"
Perhaps your colleague "looks really grumpy or depressed. ... talks very little" because of something at home or elsewhere, that's probably not your business. > > "... he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second.". > > > So you object to the way he operates the door. He knows a special way to keep it vibrating. > > "There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly.". > > > That's understandable, but does everyone agree or are only you disturbed? > > "... but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?". > > > You need to figure out the results you want and how quickly you need them. You don't want to come across as trying to portray him as an unsociable oaf, whom doesn't know how to operate a door. If you were friends with this person it should be easy enough, but that doesn't seem the case. You'll need to time your approach and decide how gingerly you want to proceed. * Approach #1: + When he passes through the door ask if everything is OK. + If it is not ask if there's anything you can do, if everything is great even better. + Mention that he seems unhappy and has been slamming the door lately, it's come to the point where you need to bring this up; it's very disturbing. * Approach #2: + Tell the boss, get them to resolve this. Suggest they pay to have the door *repaired*. * Approach #3: + Tell them directly: "Shhhh!, there's no reason to be so noisy". * Approach #4: I tried searching the Internet for 'door operating instructions', I couldn't find anything (except for a dryer door); therein lies the problem ... You could try making a label and printing it on to a clear sticker - calculate his exact eye-height and line it up. Stick it to the door at lunch or after work anonymously. I did manage to find something ***less*** than "Operating Instructions" but it should serve as a polite and anonymous hint: [![Door Sticker](https://i.stack.imgur.com/Hd7YP.jpg)](http://www.pushandpullman.com/)
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
If he enters the room and slams the door, ask him immediately like "don't you think that was too hard?". Or if he isn't afraid to destroy the door. Reminding someone of this shouldn't yet be offending. Start with a hint to make him think about that. If this doesn't help, slowly become more direct. Try to not say that every time at the beginning, see if it develops to get better. It can help to avoid he feels too guilty every time he walks through the door. Such habits need some time to vanish, there is a chance he slams the door and reminds oh next time I should no longer... If he was a funny person you'd have a better position making stupid jokes about that. Such like "**BANGING DOOR** - oh colleague xy has arrived" or "has our next department exploded or is xy here?". But the way you describe him lets assume there is no big sense of humour. It's important to discuss this with your colleagues, each of you should take turn to remind him. This doesn't make one single person the "bad guy" but shows that all of you are affected, this adds more seriousity to the topic.
It's beyond simple: The phrase you're looking for is "Do you mind" or "Would you mind" not letting the door close so noisily. The title of the question is asking for "the right way". This is it. Absent other factors which haven't been mentioned here, like previous interactions which would make this a touchy or difficult subject for conversation, this is a perfectly conventional request format which should convey the standard level of politeness and neutrality. If you say this, you're not making it about the colleague's bad mood, you're not accusing them of being unmannerly, you're just pointing out a disturbance and asking for consideration. "I do not want to offend him" - Right, that's the beauty of these standard conventional phrases which we've inherited from generations past. Unless there's some other history or information here which makes you think that the standard request is going to offend him, go with the conventional standard mannerly phrase. On the other hand, that's usually the best we can do, and we're really not responsible for unreasonable reactions on other people's part. If this person does act offended, that's an unforgivable imposition on **you**.
14,929
We have the following problem in the office: there is a colleague who, I think is nice enough once you get to know him a bit more closely. The thing is, most of the time he looks really grumpy or depressed. I don't really know how to read his face. He talks very little. We could deal with that (there are seven persons in the room) but he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second. There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly. Now, I do not want to offend him. I think it's just a thing he does without even thinking about it. I just want to ask him in a polite manner to try and close the door a bit more softly but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?
2018/05/25
[ "https://interpersonal.stackexchange.com/questions/14929", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/18238/" ]
I tend to agree with the answer Val provided. The simplest way to deal with this is to talk to the person. If talking to the person, for whatever reason, is out of the question or uncomfortable, you could try posting a sign on the door asking that people be cautious when closing the door so as not to disrupt the office. Some might find this to be a bit passive aggressive, but it might raise awareness to your colleague and he may stop on his own. It may also provide the additional benefit of your colleague not feeling singled out.
Perhaps your colleague "looks really grumpy or depressed. ... talks very little" because of something at home or elsewhere, that's probably not your business. > > "... he has this habit of slamming the door real hard. Not like some people do out of negligence, letting the door fall shut behind them. It's a glass door and he sometimes gives it a jerk in a way that the glass keeps vibrating for a second.". > > > So you object to the way he operates the door. He knows a special way to keep it vibrating. > > "There usually is an atmosphere of concentration in the office, but this behavior disrupts it badly.". > > > That's understandable, but does everyone agree or are only you disturbed? > > "... but can't think of a way that does not come across as rude or as passive aggressive. Any thoughts on how I might go about that?". > > > You need to figure out the results you want and how quickly you need them. You don't want to come across as trying to portray him as an unsociable oaf, whom doesn't know how to operate a door. If you were friends with this person it should be easy enough, but that doesn't seem the case. You'll need to time your approach and decide how gingerly you want to proceed. * Approach #1: + When he passes through the door ask if everything is OK. + If it is not ask if there's anything you can do, if everything is great even better. + Mention that he seems unhappy and has been slamming the door lately, it's come to the point where you need to bring this up; it's very disturbing. * Approach #2: + Tell the boss, get them to resolve this. Suggest they pay to have the door *repaired*. * Approach #3: + Tell them directly: "Shhhh!, there's no reason to be so noisy". * Approach #4: I tried searching the Internet for 'door operating instructions', I couldn't find anything (except for a dryer door); therein lies the problem ... You could try making a label and printing it on to a clear sticker - calculate his exact eye-height and line it up. Stick it to the door at lunch or after work anonymously. I did manage to find something ***less*** than "Operating Instructions" but it should serve as a polite and anonymous hint: [![Door Sticker](https://i.stack.imgur.com/Hd7YP.jpg)](http://www.pushandpullman.com/)