Search is not available for this dataset
qid
int64
1
74.7M
question
stringlengths
16
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
117k
response_k
stringlengths
3
61.5k
3,507,477
It doesn't seem that HttpServletResponse exposes any methods to do this. Right now, I'm adding a bunch of logging code to a crufty and ill-understood servlet, in an attempt to figure out what exactly it does. I know that it sets a bunch of cookies, but I don't know when, why, or what. It would be nice to just log all the cookies in the HttpServletResponse object at the end of the servlet's execution. I know that cookies are typically the browser's responsibility, and I remember that there was no way to do this in .NET. Just hoping that Java may be different... But if this isn't possible -- any other ideas for how to accomplish what I'm trying to do? Thanks, as always.
2010/08/17
[ "https://Stackoverflow.com/questions/3507477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207341/" ]
If logging is all you're after, then I suggest writing an implemention of `javax.servlet.Filter` which wraps the supplied `HttpServletResponse` in a wrapper which allows you to expose the cookies after the filter executes. Something like this: ``` public class CookieLoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException ,ServletException { ResponseWrapper wrappedResponse = new ResponseWrapper((HttpServletResponse) response); filterChain.doFilter(request, wrappedResponse); // use a real logger here, naturally :) System.out.println("Cookies: " + wrappedResponse.cookies); } private class ResponseWrapper extends HttpServletResponseWrapper { private Collection<Cookie> cookies = new ArrayList<Cookie>(); public ResponseWrapper(HttpServletResponse response) { super(response); } @Override public void addCookie(Cookie cookie) { super.addCookie(cookie); cookies.add(cookie); } } // other methods here } ``` One big caveat: This will *not* show you what cookies are sent back to the browser, it will only show you which cookies the application code added to the response. If the container chooses to change, add to, or ignore those cookies (e.g. session cookies are handled by the container, not the application), you won't know using this approach. But that may not matter for your situation. The only way to be sure is to use a browser plugin like [Live Http Headers for Firefox](http://livehttpheaders.mozdev.org/), or a man-in-the-middle HTTP logging proxy.
Your only approach is to wrap the HttpServletResponse object so that the addCookie methods can intercept and log when cookies are set. You can do this by adding a ServletFilter which wraps the existing HttpServletResponse before it is passed into your Servlet.
3,507,477
It doesn't seem that HttpServletResponse exposes any methods to do this. Right now, I'm adding a bunch of logging code to a crufty and ill-understood servlet, in an attempt to figure out what exactly it does. I know that it sets a bunch of cookies, but I don't know when, why, or what. It would be nice to just log all the cookies in the HttpServletResponse object at the end of the servlet's execution. I know that cookies are typically the browser's responsibility, and I remember that there was no way to do this in .NET. Just hoping that Java may be different... But if this isn't possible -- any other ideas for how to accomplish what I'm trying to do? Thanks, as always.
2010/08/17
[ "https://Stackoverflow.com/questions/3507477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207341/" ]
Your only approach is to wrap the HttpServletResponse object so that the addCookie methods can intercept and log when cookies are set. You can do this by adding a ServletFilter which wraps the existing HttpServletResponse before it is passed into your Servlet.
Cookies are sent to the client in the "Set-Cookie" response header. Try this: ``` private static void logResponseHeaders(HttpServletResponse httpServletResponse) { Collection<String> headerNames = httpServletResponse.getHeaderNames(); for (String headerName : headerNames) { if (headerName.equals("Set-Cookie")) { log.info("Response header name={}, header value={}", headerName, httpServletResponse.getHeader(headerName)); } } } ```
3,507,477
It doesn't seem that HttpServletResponse exposes any methods to do this. Right now, I'm adding a bunch of logging code to a crufty and ill-understood servlet, in an attempt to figure out what exactly it does. I know that it sets a bunch of cookies, but I don't know when, why, or what. It would be nice to just log all the cookies in the HttpServletResponse object at the end of the servlet's execution. I know that cookies are typically the browser's responsibility, and I remember that there was no way to do this in .NET. Just hoping that Java may be different... But if this isn't possible -- any other ideas for how to accomplish what I'm trying to do? Thanks, as always.
2010/08/17
[ "https://Stackoverflow.com/questions/3507477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207341/" ]
If logging is all you're after, then I suggest writing an implemention of `javax.servlet.Filter` which wraps the supplied `HttpServletResponse` in a wrapper which allows you to expose the cookies after the filter executes. Something like this: ``` public class CookieLoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException ,ServletException { ResponseWrapper wrappedResponse = new ResponseWrapper((HttpServletResponse) response); filterChain.doFilter(request, wrappedResponse); // use a real logger here, naturally :) System.out.println("Cookies: " + wrappedResponse.cookies); } private class ResponseWrapper extends HttpServletResponseWrapper { private Collection<Cookie> cookies = new ArrayList<Cookie>(); public ResponseWrapper(HttpServletResponse response) { super(response); } @Override public void addCookie(Cookie cookie) { super.addCookie(cookie); cookies.add(cookie); } } // other methods here } ``` One big caveat: This will *not* show you what cookies are sent back to the browser, it will only show you which cookies the application code added to the response. If the container chooses to change, add to, or ignore those cookies (e.g. session cookies are handled by the container, not the application), you won't know using this approach. But that may not matter for your situation. The only way to be sure is to use a browser plugin like [Live Http Headers for Firefox](http://livehttpheaders.mozdev.org/), or a man-in-the-middle HTTP logging proxy.
I had the same problem where I was using a 3rd party library which accepts an HttpServletResponse and I needed to read back the cookies that it set on my response object. To solve that I created an HttpServletResponseWrapper extension which exposes these cookies for me after I make the call: ``` public class CookieAwareHttpServletResponse extends HttpServletResponseWrapper { private List<Cookie> cookies = new ArrayList<Cookie>(); public CookieAwareHttpServletResponse (HttpServletResponse aResponse) { super (aResponse); } @Override public void addCookie (Cookie aCookie) { cookies.add (aCookie); super.addCookie(aCookie); } public List<Cookie> getCookies () { return Collections.unmodifiableList (cookies); } } ``` And the way I use it: ``` // wrap the response object CookieAwareHttpServletResponse response = new CookieAwareHttpServletResponse(aResponse); // make the call to the 3rd party library String order = orderService.getOrder (aRequest, response, String.class); // get the list of cookies set List<Cookie> cookies = response.getCookies(); ```
3,507,477
It doesn't seem that HttpServletResponse exposes any methods to do this. Right now, I'm adding a bunch of logging code to a crufty and ill-understood servlet, in an attempt to figure out what exactly it does. I know that it sets a bunch of cookies, but I don't know when, why, or what. It would be nice to just log all the cookies in the HttpServletResponse object at the end of the servlet's execution. I know that cookies are typically the browser's responsibility, and I remember that there was no way to do this in .NET. Just hoping that Java may be different... But if this isn't possible -- any other ideas for how to accomplish what I'm trying to do? Thanks, as always.
2010/08/17
[ "https://Stackoverflow.com/questions/3507477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207341/" ]
If logging is all you're after, then I suggest writing an implemention of `javax.servlet.Filter` which wraps the supplied `HttpServletResponse` in a wrapper which allows you to expose the cookies after the filter executes. Something like this: ``` public class CookieLoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException ,ServletException { ResponseWrapper wrappedResponse = new ResponseWrapper((HttpServletResponse) response); filterChain.doFilter(request, wrappedResponse); // use a real logger here, naturally :) System.out.println("Cookies: " + wrappedResponse.cookies); } private class ResponseWrapper extends HttpServletResponseWrapper { private Collection<Cookie> cookies = new ArrayList<Cookie>(); public ResponseWrapper(HttpServletResponse response) { super(response); } @Override public void addCookie(Cookie cookie) { super.addCookie(cookie); cookies.add(cookie); } } // other methods here } ``` One big caveat: This will *not* show you what cookies are sent back to the browser, it will only show you which cookies the application code added to the response. If the container chooses to change, add to, or ignore those cookies (e.g. session cookies are handled by the container, not the application), you won't know using this approach. But that may not matter for your situation. The only way to be sure is to use a browser plugin like [Live Http Headers for Firefox](http://livehttpheaders.mozdev.org/), or a man-in-the-middle HTTP logging proxy.
Cookies are sent to the client in the "Set-Cookie" response header. Try this: ``` private static void logResponseHeaders(HttpServletResponse httpServletResponse) { Collection<String> headerNames = httpServletResponse.getHeaderNames(); for (String headerName : headerNames) { if (headerName.equals("Set-Cookie")) { log.info("Response header name={}, header value={}", headerName, httpServletResponse.getHeader(headerName)); } } } ```
3,507,477
It doesn't seem that HttpServletResponse exposes any methods to do this. Right now, I'm adding a bunch of logging code to a crufty and ill-understood servlet, in an attempt to figure out what exactly it does. I know that it sets a bunch of cookies, but I don't know when, why, or what. It would be nice to just log all the cookies in the HttpServletResponse object at the end of the servlet's execution. I know that cookies are typically the browser's responsibility, and I remember that there was no way to do this in .NET. Just hoping that Java may be different... But if this isn't possible -- any other ideas for how to accomplish what I'm trying to do? Thanks, as always.
2010/08/17
[ "https://Stackoverflow.com/questions/3507477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207341/" ]
I had the same problem where I was using a 3rd party library which accepts an HttpServletResponse and I needed to read back the cookies that it set on my response object. To solve that I created an HttpServletResponseWrapper extension which exposes these cookies for me after I make the call: ``` public class CookieAwareHttpServletResponse extends HttpServletResponseWrapper { private List<Cookie> cookies = new ArrayList<Cookie>(); public CookieAwareHttpServletResponse (HttpServletResponse aResponse) { super (aResponse); } @Override public void addCookie (Cookie aCookie) { cookies.add (aCookie); super.addCookie(aCookie); } public List<Cookie> getCookies () { return Collections.unmodifiableList (cookies); } } ``` And the way I use it: ``` // wrap the response object CookieAwareHttpServletResponse response = new CookieAwareHttpServletResponse(aResponse); // make the call to the 3rd party library String order = orderService.getOrder (aRequest, response, String.class); // get the list of cookies set List<Cookie> cookies = response.getCookies(); ```
Cookies are sent to the client in the "Set-Cookie" response header. Try this: ``` private static void logResponseHeaders(HttpServletResponse httpServletResponse) { Collection<String> headerNames = httpServletResponse.getHeaderNames(); for (String headerName : headerNames) { if (headerName.equals("Set-Cookie")) { log.info("Response header name={}, header value={}", headerName, httpServletResponse.getHeader(headerName)); } } } ```
64,822,800
Good Morning, I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below: ``` ════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════ The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca): Null check operator used on a null value ``` and the screen looks like this: [![Screen Fail](https://i.stack.imgur.com/dntBE.jpg)](https://i.stack.imgur.com/dntBE.jpg) After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do? [![Screen Ok](https://i.stack.imgur.com/ILvCb.jpg)](https://i.stack.imgur.com/ILvCb.jpg) HomeManager: ``` import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/models/section.dart'; class HomeManager extends ChangeNotifier{ HomeManager({this.images}){ _loadSections(); images = images ?? []; } void addSection(Section section){ _editingSections.add(section); notifyListeners(); } final List<dynamic> _sections = []; List<String> images; List<dynamic> newImages; List<dynamic> _editingSections = []; bool editing = false; bool loading = false; int index, totalItems; final Firestore firestore = Firestore.instance; Future<void> _loadSections() async{ loading = true; firestore.collection('home').snapshots().listen((snapshot){ _sections.clear(); for(final DocumentSnapshot document in snapshot.documents){ _sections.add( Section.fromDocument(document)); images = List<String>.from(document.data['images'] as List<dynamic>); } }); loading = false; notifyListeners(); } List<dynamic> get sections { if(editing) return _editingSections; else return _sections; } void enterEditing({Section section}){ editing = true; _editingSections = _sections.map((s) => s.clone()).toList(); defineIndex(section: section); notifyListeners(); } void saveEditing() async{ bool valid = true; for(final section in _editingSections){ if(!section.valid()) valid = false; } if(!valid) return; loading = true; notifyListeners(); for(final section in _editingSections){ await section.save(); } for(final section in List.from(_sections)){ if(!_editingSections.any((s) => s.id == section.id)){ await section.delete(); } } loading = false; editing = false; notifyListeners(); } void discardEditing(){ editing = false; notifyListeners(); } void removeSection(Section section){ _editingSections.remove(section); notifyListeners(); } void onMoveUp(Section section){ int index = _editingSections.indexOf(section); if(index != 0) { _editingSections.remove(section); _editingSections.insert(index - 1, section); index = _editingSections.indexOf(section); } notifyListeners(); } HomeManager clone(){ return HomeManager( images: List.from(images), ); } void onMoveDown(Section section){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; if(index < totalItems - 1){ _editingSections.remove(section); _editingSections.insert(index + 1, section); index = _editingSections.indexOf(section); }else{ } notifyListeners(); } void defineIndex({Section section}){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; notifyListeners(); } } ``` HomeScreen: ``` import 'package:carousel_pro/carousel_pro.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/commom/custom_drawer.dart'; import 'package:provantagens_app/commom/custom_icons_icons.dart'; import 'package:provantagens_app/models/home_manager.dart'; import 'package:provantagens_app/models/section.dart'; import 'package:provantagens_app/screens/home/components/home_carousel.dart'; import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class HomeScreen extends StatelessWidget { HomeManager homeManager; Section section; List<Widget> get children => null; String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs'; int index; var _tapPosition; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient(colors: const [ Colors.white, Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Scaffold( backgroundColor: Colors.transparent, drawer: CustomDrawer(), appBar: AppBar( backgroundColor: Colors.transparent, iconTheme: IconThemeData(color: Colors.black), title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))), centerTitle: true, actions: <Widget>[ Divider(), ], ), body: Consumer<HomeManager>( builder: (_, homeManager, __){ return ListView(children: <Widget>[ AspectRatio( aspectRatio: 1, child:HomeCarousel(homeManager), ), Column( children: <Widget>[ Container( height: 50, ), Divider( color: Colors.black, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left:12.0), child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,), ), Padding( padding: const EdgeInsets.only(left:7.0), child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,), ), Padding( padding: const EdgeInsets.only(right:3.0), child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ MenuIconTile(iconData: Icons.assignment, title: 'Dados pessoais', page: 3) , MenuIconTile(iconData: Icons.credit_card_outlined, title: 'Meu cartão', page: 4) , MenuIconTile(iconData: Icons.account_balance_wallet_outlined, title: 'Pagamento', page: 5,) , ], ), Divider( color: Colors.black, ), Container( height: 50, ), Consumer<HomeManager>( builder: (_, sec, __){ return RaisedButton( child: Text('Teste'), onPressed: (){ Navigator.of(context) .pushReplacementNamed('/teste', arguments: sec); }, ); }, ), Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),), Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),), AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp', fit: BoxFit.fill, ), ), Divider(), Container( height: 150, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp', fit: BoxFit.fill, ), ), Padding( padding: const EdgeInsets.only(left:20.0), child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: 'Adquira já o seu', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: '\n\CARTÃO PRÓ VANTAGENS', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), ), ], ), ), Divider(), tableBeneficios(), Divider(), Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( 'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'), FlatButton( onPressed: () { launch( 'https://www.youtube.com/watch?v=VFnDo3JUzjs'); }, child: Text('SAIBA MAIS')), ], ), ), Container( color: Color.fromARGB(255, 105, 190, 90), child: Column( children: <Widget>[ Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( '© 2020 todos os direitos reservados a Cartão Pró Vantagens.', style: TextStyle(fontSize: 10), ), ) ], ), Divider(), Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( 'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)', style: TextStyle(fontSize: 10), ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.facebook), color: Colors.black, onPressed: () { launch( 'https://www.facebook.com/provantagens/'); }, ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.instagram), color: Colors.black, onPressed: () { launch( 'https://www.instagram.com/cartaoprovantagens/'); }, ), ), ], ), ], ), ) ], ), ]); }, ) ), ); } tableBeneficios() { return Table( defaultColumnWidth: FlexColumnWidth(120.0), border: TableBorder( horizontalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), verticalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), ), children: [ _criarTituloTable(",Plus, Premium"), _criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"), _criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"), _criarLinhaTable("Invalidez Total e Parcial,X,X"), _criarLinhaTable("Assistência Residencial,X,X"), _criarLinhaTable("Assistência Funeral,X,X"), _criarLinhaTable("Assistência Pet,X,X"), _criarLinhaTable("Assistência Natalidade,X,X"), _criarLinhaTable("Assistência Eletroassist,X,X"), _criarLinhaTable("Assistência Alimentação,X,X"), _criarLinhaTable("Descontos em Parceiros,X,X"), ], ); } _criarLinhaTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name != "X" ? '' : 'X', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name != 'X' ? name : '', style: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } _criarTituloTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name == "" ? '' : 'Plano ', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } void _storePosition(TapDownDetails details) { _tapPosition = details.globalPosition; } } ```
2020/11/13
[ "https://Stackoverflow.com/questions/64822800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632998/" ]
I forked the library to create a custom carousel for my company's project, and since we updated flutter to 2.x we had the same problem. To fix this just update boolean expressions like ``` if(carouselState.pageController.position.minScrollExtent == null || carouselState.pageController.position.maxScrollExtent == null){ ... } ``` to ``` if(!carouselState.pageController.position.hasContentDimensions){ ... } ``` [Here is flutter's github reference.](https://github.com/flutter/flutter/issues/66250)
Just upgrade to `^3.0.0` Check here <https://pub.dev/packages/carousel_slider>
64,822,800
Good Morning, I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below: ``` ════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════ The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca): Null check operator used on a null value ``` and the screen looks like this: [![Screen Fail](https://i.stack.imgur.com/dntBE.jpg)](https://i.stack.imgur.com/dntBE.jpg) After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do? [![Screen Ok](https://i.stack.imgur.com/ILvCb.jpg)](https://i.stack.imgur.com/ILvCb.jpg) HomeManager: ``` import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/models/section.dart'; class HomeManager extends ChangeNotifier{ HomeManager({this.images}){ _loadSections(); images = images ?? []; } void addSection(Section section){ _editingSections.add(section); notifyListeners(); } final List<dynamic> _sections = []; List<String> images; List<dynamic> newImages; List<dynamic> _editingSections = []; bool editing = false; bool loading = false; int index, totalItems; final Firestore firestore = Firestore.instance; Future<void> _loadSections() async{ loading = true; firestore.collection('home').snapshots().listen((snapshot){ _sections.clear(); for(final DocumentSnapshot document in snapshot.documents){ _sections.add( Section.fromDocument(document)); images = List<String>.from(document.data['images'] as List<dynamic>); } }); loading = false; notifyListeners(); } List<dynamic> get sections { if(editing) return _editingSections; else return _sections; } void enterEditing({Section section}){ editing = true; _editingSections = _sections.map((s) => s.clone()).toList(); defineIndex(section: section); notifyListeners(); } void saveEditing() async{ bool valid = true; for(final section in _editingSections){ if(!section.valid()) valid = false; } if(!valid) return; loading = true; notifyListeners(); for(final section in _editingSections){ await section.save(); } for(final section in List.from(_sections)){ if(!_editingSections.any((s) => s.id == section.id)){ await section.delete(); } } loading = false; editing = false; notifyListeners(); } void discardEditing(){ editing = false; notifyListeners(); } void removeSection(Section section){ _editingSections.remove(section); notifyListeners(); } void onMoveUp(Section section){ int index = _editingSections.indexOf(section); if(index != 0) { _editingSections.remove(section); _editingSections.insert(index - 1, section); index = _editingSections.indexOf(section); } notifyListeners(); } HomeManager clone(){ return HomeManager( images: List.from(images), ); } void onMoveDown(Section section){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; if(index < totalItems - 1){ _editingSections.remove(section); _editingSections.insert(index + 1, section); index = _editingSections.indexOf(section); }else{ } notifyListeners(); } void defineIndex({Section section}){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; notifyListeners(); } } ``` HomeScreen: ``` import 'package:carousel_pro/carousel_pro.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/commom/custom_drawer.dart'; import 'package:provantagens_app/commom/custom_icons_icons.dart'; import 'package:provantagens_app/models/home_manager.dart'; import 'package:provantagens_app/models/section.dart'; import 'package:provantagens_app/screens/home/components/home_carousel.dart'; import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class HomeScreen extends StatelessWidget { HomeManager homeManager; Section section; List<Widget> get children => null; String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs'; int index; var _tapPosition; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient(colors: const [ Colors.white, Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Scaffold( backgroundColor: Colors.transparent, drawer: CustomDrawer(), appBar: AppBar( backgroundColor: Colors.transparent, iconTheme: IconThemeData(color: Colors.black), title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))), centerTitle: true, actions: <Widget>[ Divider(), ], ), body: Consumer<HomeManager>( builder: (_, homeManager, __){ return ListView(children: <Widget>[ AspectRatio( aspectRatio: 1, child:HomeCarousel(homeManager), ), Column( children: <Widget>[ Container( height: 50, ), Divider( color: Colors.black, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left:12.0), child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,), ), Padding( padding: const EdgeInsets.only(left:7.0), child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,), ), Padding( padding: const EdgeInsets.only(right:3.0), child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ MenuIconTile(iconData: Icons.assignment, title: 'Dados pessoais', page: 3) , MenuIconTile(iconData: Icons.credit_card_outlined, title: 'Meu cartão', page: 4) , MenuIconTile(iconData: Icons.account_balance_wallet_outlined, title: 'Pagamento', page: 5,) , ], ), Divider( color: Colors.black, ), Container( height: 50, ), Consumer<HomeManager>( builder: (_, sec, __){ return RaisedButton( child: Text('Teste'), onPressed: (){ Navigator.of(context) .pushReplacementNamed('/teste', arguments: sec); }, ); }, ), Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),), Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),), AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp', fit: BoxFit.fill, ), ), Divider(), Container( height: 150, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp', fit: BoxFit.fill, ), ), Padding( padding: const EdgeInsets.only(left:20.0), child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: 'Adquira já o seu', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: '\n\CARTÃO PRÓ VANTAGENS', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), ), ], ), ), Divider(), tableBeneficios(), Divider(), Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( 'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'), FlatButton( onPressed: () { launch( 'https://www.youtube.com/watch?v=VFnDo3JUzjs'); }, child: Text('SAIBA MAIS')), ], ), ), Container( color: Color.fromARGB(255, 105, 190, 90), child: Column( children: <Widget>[ Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( '© 2020 todos os direitos reservados a Cartão Pró Vantagens.', style: TextStyle(fontSize: 10), ), ) ], ), Divider(), Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( 'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)', style: TextStyle(fontSize: 10), ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.facebook), color: Colors.black, onPressed: () { launch( 'https://www.facebook.com/provantagens/'); }, ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.instagram), color: Colors.black, onPressed: () { launch( 'https://www.instagram.com/cartaoprovantagens/'); }, ), ), ], ), ], ), ) ], ), ]); }, ) ), ); } tableBeneficios() { return Table( defaultColumnWidth: FlexColumnWidth(120.0), border: TableBorder( horizontalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), verticalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), ), children: [ _criarTituloTable(",Plus, Premium"), _criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"), _criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"), _criarLinhaTable("Invalidez Total e Parcial,X,X"), _criarLinhaTable("Assistência Residencial,X,X"), _criarLinhaTable("Assistência Funeral,X,X"), _criarLinhaTable("Assistência Pet,X,X"), _criarLinhaTable("Assistência Natalidade,X,X"), _criarLinhaTable("Assistência Eletroassist,X,X"), _criarLinhaTable("Assistência Alimentação,X,X"), _criarLinhaTable("Descontos em Parceiros,X,X"), ], ); } _criarLinhaTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name != "X" ? '' : 'X', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name != 'X' ? name : '', style: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } _criarTituloTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name == "" ? '' : 'Plano ', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } void _storePosition(TapDownDetails details) { _tapPosition = details.globalPosition; } } ```
2020/11/13
[ "https://Stackoverflow.com/questions/64822800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632998/" ]
I forked the library to create a custom carousel for my company's project, and since we updated flutter to 2.x we had the same problem. To fix this just update boolean expressions like ``` if(carouselState.pageController.position.minScrollExtent == null || carouselState.pageController.position.maxScrollExtent == null){ ... } ``` to ``` if(!carouselState.pageController.position.hasContentDimensions){ ... } ``` [Here is flutter's github reference.](https://github.com/flutter/flutter/issues/66250)
I solved the similar problem as follows. You can take advantage of the Boolean variable. I hope, help you. ``` child: !loading ? HomeCarousel(homeManager) : Center(child:ProgressIndicator()), ``` or ``` child: isLoading ? HomeCarousel(homeManager) : SplashScreen(), ``` ``` class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Loading...') ), ); } } ```
64,822,800
Good Morning, I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below: ``` ════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════ The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca): Null check operator used on a null value ``` and the screen looks like this: [![Screen Fail](https://i.stack.imgur.com/dntBE.jpg)](https://i.stack.imgur.com/dntBE.jpg) After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do? [![Screen Ok](https://i.stack.imgur.com/ILvCb.jpg)](https://i.stack.imgur.com/ILvCb.jpg) HomeManager: ``` import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/models/section.dart'; class HomeManager extends ChangeNotifier{ HomeManager({this.images}){ _loadSections(); images = images ?? []; } void addSection(Section section){ _editingSections.add(section); notifyListeners(); } final List<dynamic> _sections = []; List<String> images; List<dynamic> newImages; List<dynamic> _editingSections = []; bool editing = false; bool loading = false; int index, totalItems; final Firestore firestore = Firestore.instance; Future<void> _loadSections() async{ loading = true; firestore.collection('home').snapshots().listen((snapshot){ _sections.clear(); for(final DocumentSnapshot document in snapshot.documents){ _sections.add( Section.fromDocument(document)); images = List<String>.from(document.data['images'] as List<dynamic>); } }); loading = false; notifyListeners(); } List<dynamic> get sections { if(editing) return _editingSections; else return _sections; } void enterEditing({Section section}){ editing = true; _editingSections = _sections.map((s) => s.clone()).toList(); defineIndex(section: section); notifyListeners(); } void saveEditing() async{ bool valid = true; for(final section in _editingSections){ if(!section.valid()) valid = false; } if(!valid) return; loading = true; notifyListeners(); for(final section in _editingSections){ await section.save(); } for(final section in List.from(_sections)){ if(!_editingSections.any((s) => s.id == section.id)){ await section.delete(); } } loading = false; editing = false; notifyListeners(); } void discardEditing(){ editing = false; notifyListeners(); } void removeSection(Section section){ _editingSections.remove(section); notifyListeners(); } void onMoveUp(Section section){ int index = _editingSections.indexOf(section); if(index != 0) { _editingSections.remove(section); _editingSections.insert(index - 1, section); index = _editingSections.indexOf(section); } notifyListeners(); } HomeManager clone(){ return HomeManager( images: List.from(images), ); } void onMoveDown(Section section){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; if(index < totalItems - 1){ _editingSections.remove(section); _editingSections.insert(index + 1, section); index = _editingSections.indexOf(section); }else{ } notifyListeners(); } void defineIndex({Section section}){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; notifyListeners(); } } ``` HomeScreen: ``` import 'package:carousel_pro/carousel_pro.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/commom/custom_drawer.dart'; import 'package:provantagens_app/commom/custom_icons_icons.dart'; import 'package:provantagens_app/models/home_manager.dart'; import 'package:provantagens_app/models/section.dart'; import 'package:provantagens_app/screens/home/components/home_carousel.dart'; import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class HomeScreen extends StatelessWidget { HomeManager homeManager; Section section; List<Widget> get children => null; String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs'; int index; var _tapPosition; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient(colors: const [ Colors.white, Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Scaffold( backgroundColor: Colors.transparent, drawer: CustomDrawer(), appBar: AppBar( backgroundColor: Colors.transparent, iconTheme: IconThemeData(color: Colors.black), title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))), centerTitle: true, actions: <Widget>[ Divider(), ], ), body: Consumer<HomeManager>( builder: (_, homeManager, __){ return ListView(children: <Widget>[ AspectRatio( aspectRatio: 1, child:HomeCarousel(homeManager), ), Column( children: <Widget>[ Container( height: 50, ), Divider( color: Colors.black, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left:12.0), child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,), ), Padding( padding: const EdgeInsets.only(left:7.0), child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,), ), Padding( padding: const EdgeInsets.only(right:3.0), child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ MenuIconTile(iconData: Icons.assignment, title: 'Dados pessoais', page: 3) , MenuIconTile(iconData: Icons.credit_card_outlined, title: 'Meu cartão', page: 4) , MenuIconTile(iconData: Icons.account_balance_wallet_outlined, title: 'Pagamento', page: 5,) , ], ), Divider( color: Colors.black, ), Container( height: 50, ), Consumer<HomeManager>( builder: (_, sec, __){ return RaisedButton( child: Text('Teste'), onPressed: (){ Navigator.of(context) .pushReplacementNamed('/teste', arguments: sec); }, ); }, ), Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),), Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),), AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp', fit: BoxFit.fill, ), ), Divider(), Container( height: 150, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp', fit: BoxFit.fill, ), ), Padding( padding: const EdgeInsets.only(left:20.0), child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: 'Adquira já o seu', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: '\n\CARTÃO PRÓ VANTAGENS', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), ), ], ), ), Divider(), tableBeneficios(), Divider(), Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( 'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'), FlatButton( onPressed: () { launch( 'https://www.youtube.com/watch?v=VFnDo3JUzjs'); }, child: Text('SAIBA MAIS')), ], ), ), Container( color: Color.fromARGB(255, 105, 190, 90), child: Column( children: <Widget>[ Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( '© 2020 todos os direitos reservados a Cartão Pró Vantagens.', style: TextStyle(fontSize: 10), ), ) ], ), Divider(), Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( 'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)', style: TextStyle(fontSize: 10), ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.facebook), color: Colors.black, onPressed: () { launch( 'https://www.facebook.com/provantagens/'); }, ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.instagram), color: Colors.black, onPressed: () { launch( 'https://www.instagram.com/cartaoprovantagens/'); }, ), ), ], ), ], ), ) ], ), ]); }, ) ), ); } tableBeneficios() { return Table( defaultColumnWidth: FlexColumnWidth(120.0), border: TableBorder( horizontalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), verticalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), ), children: [ _criarTituloTable(",Plus, Premium"), _criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"), _criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"), _criarLinhaTable("Invalidez Total e Parcial,X,X"), _criarLinhaTable("Assistência Residencial,X,X"), _criarLinhaTable("Assistência Funeral,X,X"), _criarLinhaTable("Assistência Pet,X,X"), _criarLinhaTable("Assistência Natalidade,X,X"), _criarLinhaTable("Assistência Eletroassist,X,X"), _criarLinhaTable("Assistência Alimentação,X,X"), _criarLinhaTable("Descontos em Parceiros,X,X"), ], ); } _criarLinhaTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name != "X" ? '' : 'X', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name != 'X' ? name : '', style: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } _criarTituloTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name == "" ? '' : 'Plano ', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } void _storePosition(TapDownDetails details) { _tapPosition = details.globalPosition; } } ```
2020/11/13
[ "https://Stackoverflow.com/questions/64822800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632998/" ]
I forked the library to create a custom carousel for my company's project, and since we updated flutter to 2.x we had the same problem. To fix this just update boolean expressions like ``` if(carouselState.pageController.position.minScrollExtent == null || carouselState.pageController.position.maxScrollExtent == null){ ... } ``` to ``` if(!carouselState.pageController.position.hasContentDimensions){ ... } ``` [Here is flutter's github reference.](https://github.com/flutter/flutter/issues/66250)
This worked for me So I edited scrollposition.dart package from line 133 ``` @override //double get minScrollExtent => _minScrollExtent!; // double? _minScrollExtent; double get minScrollExtent { if (_minScrollExtent == null) { _minScrollExtent = 0.0; } return double.parse(_minScrollExtent.toString()); } double? _minScrollExtent; @override // double get maxScrollExtent => _maxScrollExtent!; // double? _maxScrollExtent; double get maxScrollExtent { if (_maxScrollExtent == null) { _maxScrollExtent = 0.0; } return double.parse(_maxScrollExtent.toString()); } double? _maxScrollExtent; ```
64,822,800
Good Morning, I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below: ``` ════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════ The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca): Null check operator used on a null value ``` and the screen looks like this: [![Screen Fail](https://i.stack.imgur.com/dntBE.jpg)](https://i.stack.imgur.com/dntBE.jpg) After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do? [![Screen Ok](https://i.stack.imgur.com/ILvCb.jpg)](https://i.stack.imgur.com/ILvCb.jpg) HomeManager: ``` import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/models/section.dart'; class HomeManager extends ChangeNotifier{ HomeManager({this.images}){ _loadSections(); images = images ?? []; } void addSection(Section section){ _editingSections.add(section); notifyListeners(); } final List<dynamic> _sections = []; List<String> images; List<dynamic> newImages; List<dynamic> _editingSections = []; bool editing = false; bool loading = false; int index, totalItems; final Firestore firestore = Firestore.instance; Future<void> _loadSections() async{ loading = true; firestore.collection('home').snapshots().listen((snapshot){ _sections.clear(); for(final DocumentSnapshot document in snapshot.documents){ _sections.add( Section.fromDocument(document)); images = List<String>.from(document.data['images'] as List<dynamic>); } }); loading = false; notifyListeners(); } List<dynamic> get sections { if(editing) return _editingSections; else return _sections; } void enterEditing({Section section}){ editing = true; _editingSections = _sections.map((s) => s.clone()).toList(); defineIndex(section: section); notifyListeners(); } void saveEditing() async{ bool valid = true; for(final section in _editingSections){ if(!section.valid()) valid = false; } if(!valid) return; loading = true; notifyListeners(); for(final section in _editingSections){ await section.save(); } for(final section in List.from(_sections)){ if(!_editingSections.any((s) => s.id == section.id)){ await section.delete(); } } loading = false; editing = false; notifyListeners(); } void discardEditing(){ editing = false; notifyListeners(); } void removeSection(Section section){ _editingSections.remove(section); notifyListeners(); } void onMoveUp(Section section){ int index = _editingSections.indexOf(section); if(index != 0) { _editingSections.remove(section); _editingSections.insert(index - 1, section); index = _editingSections.indexOf(section); } notifyListeners(); } HomeManager clone(){ return HomeManager( images: List.from(images), ); } void onMoveDown(Section section){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; if(index < totalItems - 1){ _editingSections.remove(section); _editingSections.insert(index + 1, section); index = _editingSections.indexOf(section); }else{ } notifyListeners(); } void defineIndex({Section section}){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; notifyListeners(); } } ``` HomeScreen: ``` import 'package:carousel_pro/carousel_pro.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/commom/custom_drawer.dart'; import 'package:provantagens_app/commom/custom_icons_icons.dart'; import 'package:provantagens_app/models/home_manager.dart'; import 'package:provantagens_app/models/section.dart'; import 'package:provantagens_app/screens/home/components/home_carousel.dart'; import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class HomeScreen extends StatelessWidget { HomeManager homeManager; Section section; List<Widget> get children => null; String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs'; int index; var _tapPosition; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient(colors: const [ Colors.white, Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Scaffold( backgroundColor: Colors.transparent, drawer: CustomDrawer(), appBar: AppBar( backgroundColor: Colors.transparent, iconTheme: IconThemeData(color: Colors.black), title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))), centerTitle: true, actions: <Widget>[ Divider(), ], ), body: Consumer<HomeManager>( builder: (_, homeManager, __){ return ListView(children: <Widget>[ AspectRatio( aspectRatio: 1, child:HomeCarousel(homeManager), ), Column( children: <Widget>[ Container( height: 50, ), Divider( color: Colors.black, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left:12.0), child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,), ), Padding( padding: const EdgeInsets.only(left:7.0), child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,), ), Padding( padding: const EdgeInsets.only(right:3.0), child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ MenuIconTile(iconData: Icons.assignment, title: 'Dados pessoais', page: 3) , MenuIconTile(iconData: Icons.credit_card_outlined, title: 'Meu cartão', page: 4) , MenuIconTile(iconData: Icons.account_balance_wallet_outlined, title: 'Pagamento', page: 5,) , ], ), Divider( color: Colors.black, ), Container( height: 50, ), Consumer<HomeManager>( builder: (_, sec, __){ return RaisedButton( child: Text('Teste'), onPressed: (){ Navigator.of(context) .pushReplacementNamed('/teste', arguments: sec); }, ); }, ), Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),), Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),), AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp', fit: BoxFit.fill, ), ), Divider(), Container( height: 150, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp', fit: BoxFit.fill, ), ), Padding( padding: const EdgeInsets.only(left:20.0), child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: 'Adquira já o seu', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: '\n\CARTÃO PRÓ VANTAGENS', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), ), ], ), ), Divider(), tableBeneficios(), Divider(), Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( 'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'), FlatButton( onPressed: () { launch( 'https://www.youtube.com/watch?v=VFnDo3JUzjs'); }, child: Text('SAIBA MAIS')), ], ), ), Container( color: Color.fromARGB(255, 105, 190, 90), child: Column( children: <Widget>[ Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( '© 2020 todos os direitos reservados a Cartão Pró Vantagens.', style: TextStyle(fontSize: 10), ), ) ], ), Divider(), Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( 'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)', style: TextStyle(fontSize: 10), ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.facebook), color: Colors.black, onPressed: () { launch( 'https://www.facebook.com/provantagens/'); }, ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.instagram), color: Colors.black, onPressed: () { launch( 'https://www.instagram.com/cartaoprovantagens/'); }, ), ), ], ), ], ), ) ], ), ]); }, ) ), ); } tableBeneficios() { return Table( defaultColumnWidth: FlexColumnWidth(120.0), border: TableBorder( horizontalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), verticalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), ), children: [ _criarTituloTable(",Plus, Premium"), _criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"), _criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"), _criarLinhaTable("Invalidez Total e Parcial,X,X"), _criarLinhaTable("Assistência Residencial,X,X"), _criarLinhaTable("Assistência Funeral,X,X"), _criarLinhaTable("Assistência Pet,X,X"), _criarLinhaTable("Assistência Natalidade,X,X"), _criarLinhaTable("Assistência Eletroassist,X,X"), _criarLinhaTable("Assistência Alimentação,X,X"), _criarLinhaTable("Descontos em Parceiros,X,X"), ], ); } _criarLinhaTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name != "X" ? '' : 'X', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name != 'X' ? name : '', style: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } _criarTituloTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name == "" ? '' : 'Plano ', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } void _storePosition(TapDownDetails details) { _tapPosition = details.globalPosition; } } ```
2020/11/13
[ "https://Stackoverflow.com/questions/64822800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632998/" ]
I forked the library to create a custom carousel for my company's project, and since we updated flutter to 2.x we had the same problem. To fix this just update boolean expressions like ``` if(carouselState.pageController.position.minScrollExtent == null || carouselState.pageController.position.maxScrollExtent == null){ ... } ``` to ``` if(!carouselState.pageController.position.hasContentDimensions){ ... } ``` [Here is flutter's github reference.](https://github.com/flutter/flutter/issues/66250)
I faced the same issue. This is how I solved it ``` class PlansPage extends StatefulWidget { const PlansPage({Key? key}) : super(key: key); @override State<PlansPage> createState() => _PlansPageState(); } class _PlansPageState extends State<PlansPage> { int _currentPage = 1; late CarouselController carouselController; @override void initState() { super.initState(); carouselController = CarouselController(); } } ``` Then put initialization the carouselController inside the initState method I was able to use the methods jumpToPage(\_currentPage ) and animateToPage(\_currentPage) etc. I use animateToPage inside GestureDetector in onTap. ``` onTap: () { setState(() { _currentPage = pageIndex; }); carouselController.animateToPage(_currentPage); }, ``` I apologize in advance if this is inappropriate.
64,822,800
Good Morning, I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below: ``` ════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════ The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca): Null check operator used on a null value ``` and the screen looks like this: [![Screen Fail](https://i.stack.imgur.com/dntBE.jpg)](https://i.stack.imgur.com/dntBE.jpg) After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do? [![Screen Ok](https://i.stack.imgur.com/ILvCb.jpg)](https://i.stack.imgur.com/ILvCb.jpg) HomeManager: ``` import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/models/section.dart'; class HomeManager extends ChangeNotifier{ HomeManager({this.images}){ _loadSections(); images = images ?? []; } void addSection(Section section){ _editingSections.add(section); notifyListeners(); } final List<dynamic> _sections = []; List<String> images; List<dynamic> newImages; List<dynamic> _editingSections = []; bool editing = false; bool loading = false; int index, totalItems; final Firestore firestore = Firestore.instance; Future<void> _loadSections() async{ loading = true; firestore.collection('home').snapshots().listen((snapshot){ _sections.clear(); for(final DocumentSnapshot document in snapshot.documents){ _sections.add( Section.fromDocument(document)); images = List<String>.from(document.data['images'] as List<dynamic>); } }); loading = false; notifyListeners(); } List<dynamic> get sections { if(editing) return _editingSections; else return _sections; } void enterEditing({Section section}){ editing = true; _editingSections = _sections.map((s) => s.clone()).toList(); defineIndex(section: section); notifyListeners(); } void saveEditing() async{ bool valid = true; for(final section in _editingSections){ if(!section.valid()) valid = false; } if(!valid) return; loading = true; notifyListeners(); for(final section in _editingSections){ await section.save(); } for(final section in List.from(_sections)){ if(!_editingSections.any((s) => s.id == section.id)){ await section.delete(); } } loading = false; editing = false; notifyListeners(); } void discardEditing(){ editing = false; notifyListeners(); } void removeSection(Section section){ _editingSections.remove(section); notifyListeners(); } void onMoveUp(Section section){ int index = _editingSections.indexOf(section); if(index != 0) { _editingSections.remove(section); _editingSections.insert(index - 1, section); index = _editingSections.indexOf(section); } notifyListeners(); } HomeManager clone(){ return HomeManager( images: List.from(images), ); } void onMoveDown(Section section){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; if(index < totalItems - 1){ _editingSections.remove(section); _editingSections.insert(index + 1, section); index = _editingSections.indexOf(section); }else{ } notifyListeners(); } void defineIndex({Section section}){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; notifyListeners(); } } ``` HomeScreen: ``` import 'package:carousel_pro/carousel_pro.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/commom/custom_drawer.dart'; import 'package:provantagens_app/commom/custom_icons_icons.dart'; import 'package:provantagens_app/models/home_manager.dart'; import 'package:provantagens_app/models/section.dart'; import 'package:provantagens_app/screens/home/components/home_carousel.dart'; import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class HomeScreen extends StatelessWidget { HomeManager homeManager; Section section; List<Widget> get children => null; String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs'; int index; var _tapPosition; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient(colors: const [ Colors.white, Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Scaffold( backgroundColor: Colors.transparent, drawer: CustomDrawer(), appBar: AppBar( backgroundColor: Colors.transparent, iconTheme: IconThemeData(color: Colors.black), title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))), centerTitle: true, actions: <Widget>[ Divider(), ], ), body: Consumer<HomeManager>( builder: (_, homeManager, __){ return ListView(children: <Widget>[ AspectRatio( aspectRatio: 1, child:HomeCarousel(homeManager), ), Column( children: <Widget>[ Container( height: 50, ), Divider( color: Colors.black, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left:12.0), child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,), ), Padding( padding: const EdgeInsets.only(left:7.0), child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,), ), Padding( padding: const EdgeInsets.only(right:3.0), child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ MenuIconTile(iconData: Icons.assignment, title: 'Dados pessoais', page: 3) , MenuIconTile(iconData: Icons.credit_card_outlined, title: 'Meu cartão', page: 4) , MenuIconTile(iconData: Icons.account_balance_wallet_outlined, title: 'Pagamento', page: 5,) , ], ), Divider( color: Colors.black, ), Container( height: 50, ), Consumer<HomeManager>( builder: (_, sec, __){ return RaisedButton( child: Text('Teste'), onPressed: (){ Navigator.of(context) .pushReplacementNamed('/teste', arguments: sec); }, ); }, ), Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),), Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),), AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp', fit: BoxFit.fill, ), ), Divider(), Container( height: 150, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp', fit: BoxFit.fill, ), ), Padding( padding: const EdgeInsets.only(left:20.0), child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: 'Adquira já o seu', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: '\n\CARTÃO PRÓ VANTAGENS', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), ), ], ), ), Divider(), tableBeneficios(), Divider(), Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( 'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'), FlatButton( onPressed: () { launch( 'https://www.youtube.com/watch?v=VFnDo3JUzjs'); }, child: Text('SAIBA MAIS')), ], ), ), Container( color: Color.fromARGB(255, 105, 190, 90), child: Column( children: <Widget>[ Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( '© 2020 todos os direitos reservados a Cartão Pró Vantagens.', style: TextStyle(fontSize: 10), ), ) ], ), Divider(), Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( 'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)', style: TextStyle(fontSize: 10), ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.facebook), color: Colors.black, onPressed: () { launch( 'https://www.facebook.com/provantagens/'); }, ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.instagram), color: Colors.black, onPressed: () { launch( 'https://www.instagram.com/cartaoprovantagens/'); }, ), ), ], ), ], ), ) ], ), ]); }, ) ), ); } tableBeneficios() { return Table( defaultColumnWidth: FlexColumnWidth(120.0), border: TableBorder( horizontalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), verticalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), ), children: [ _criarTituloTable(",Plus, Premium"), _criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"), _criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"), _criarLinhaTable("Invalidez Total e Parcial,X,X"), _criarLinhaTable("Assistência Residencial,X,X"), _criarLinhaTable("Assistência Funeral,X,X"), _criarLinhaTable("Assistência Pet,X,X"), _criarLinhaTable("Assistência Natalidade,X,X"), _criarLinhaTable("Assistência Eletroassist,X,X"), _criarLinhaTable("Assistência Alimentação,X,X"), _criarLinhaTable("Descontos em Parceiros,X,X"), ], ); } _criarLinhaTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name != "X" ? '' : 'X', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name != 'X' ? name : '', style: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } _criarTituloTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name == "" ? '' : 'Plano ', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } void _storePosition(TapDownDetails details) { _tapPosition = details.globalPosition; } } ```
2020/11/13
[ "https://Stackoverflow.com/questions/64822800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632998/" ]
Just upgrade to `^3.0.0` Check here <https://pub.dev/packages/carousel_slider>
I solved the similar problem as follows. You can take advantage of the Boolean variable. I hope, help you. ``` child: !loading ? HomeCarousel(homeManager) : Center(child:ProgressIndicator()), ``` or ``` child: isLoading ? HomeCarousel(homeManager) : SplashScreen(), ``` ``` class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Loading...') ), ); } } ```
64,822,800
Good Morning, I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below: ``` ════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════ The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca): Null check operator used on a null value ``` and the screen looks like this: [![Screen Fail](https://i.stack.imgur.com/dntBE.jpg)](https://i.stack.imgur.com/dntBE.jpg) After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do? [![Screen Ok](https://i.stack.imgur.com/ILvCb.jpg)](https://i.stack.imgur.com/ILvCb.jpg) HomeManager: ``` import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/models/section.dart'; class HomeManager extends ChangeNotifier{ HomeManager({this.images}){ _loadSections(); images = images ?? []; } void addSection(Section section){ _editingSections.add(section); notifyListeners(); } final List<dynamic> _sections = []; List<String> images; List<dynamic> newImages; List<dynamic> _editingSections = []; bool editing = false; bool loading = false; int index, totalItems; final Firestore firestore = Firestore.instance; Future<void> _loadSections() async{ loading = true; firestore.collection('home').snapshots().listen((snapshot){ _sections.clear(); for(final DocumentSnapshot document in snapshot.documents){ _sections.add( Section.fromDocument(document)); images = List<String>.from(document.data['images'] as List<dynamic>); } }); loading = false; notifyListeners(); } List<dynamic> get sections { if(editing) return _editingSections; else return _sections; } void enterEditing({Section section}){ editing = true; _editingSections = _sections.map((s) => s.clone()).toList(); defineIndex(section: section); notifyListeners(); } void saveEditing() async{ bool valid = true; for(final section in _editingSections){ if(!section.valid()) valid = false; } if(!valid) return; loading = true; notifyListeners(); for(final section in _editingSections){ await section.save(); } for(final section in List.from(_sections)){ if(!_editingSections.any((s) => s.id == section.id)){ await section.delete(); } } loading = false; editing = false; notifyListeners(); } void discardEditing(){ editing = false; notifyListeners(); } void removeSection(Section section){ _editingSections.remove(section); notifyListeners(); } void onMoveUp(Section section){ int index = _editingSections.indexOf(section); if(index != 0) { _editingSections.remove(section); _editingSections.insert(index - 1, section); index = _editingSections.indexOf(section); } notifyListeners(); } HomeManager clone(){ return HomeManager( images: List.from(images), ); } void onMoveDown(Section section){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; if(index < totalItems - 1){ _editingSections.remove(section); _editingSections.insert(index + 1, section); index = _editingSections.indexOf(section); }else{ } notifyListeners(); } void defineIndex({Section section}){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; notifyListeners(); } } ``` HomeScreen: ``` import 'package:carousel_pro/carousel_pro.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/commom/custom_drawer.dart'; import 'package:provantagens_app/commom/custom_icons_icons.dart'; import 'package:provantagens_app/models/home_manager.dart'; import 'package:provantagens_app/models/section.dart'; import 'package:provantagens_app/screens/home/components/home_carousel.dart'; import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class HomeScreen extends StatelessWidget { HomeManager homeManager; Section section; List<Widget> get children => null; String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs'; int index; var _tapPosition; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient(colors: const [ Colors.white, Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Scaffold( backgroundColor: Colors.transparent, drawer: CustomDrawer(), appBar: AppBar( backgroundColor: Colors.transparent, iconTheme: IconThemeData(color: Colors.black), title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))), centerTitle: true, actions: <Widget>[ Divider(), ], ), body: Consumer<HomeManager>( builder: (_, homeManager, __){ return ListView(children: <Widget>[ AspectRatio( aspectRatio: 1, child:HomeCarousel(homeManager), ), Column( children: <Widget>[ Container( height: 50, ), Divider( color: Colors.black, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left:12.0), child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,), ), Padding( padding: const EdgeInsets.only(left:7.0), child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,), ), Padding( padding: const EdgeInsets.only(right:3.0), child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ MenuIconTile(iconData: Icons.assignment, title: 'Dados pessoais', page: 3) , MenuIconTile(iconData: Icons.credit_card_outlined, title: 'Meu cartão', page: 4) , MenuIconTile(iconData: Icons.account_balance_wallet_outlined, title: 'Pagamento', page: 5,) , ], ), Divider( color: Colors.black, ), Container( height: 50, ), Consumer<HomeManager>( builder: (_, sec, __){ return RaisedButton( child: Text('Teste'), onPressed: (){ Navigator.of(context) .pushReplacementNamed('/teste', arguments: sec); }, ); }, ), Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),), Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),), AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp', fit: BoxFit.fill, ), ), Divider(), Container( height: 150, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp', fit: BoxFit.fill, ), ), Padding( padding: const EdgeInsets.only(left:20.0), child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: 'Adquira já o seu', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: '\n\CARTÃO PRÓ VANTAGENS', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), ), ], ), ), Divider(), tableBeneficios(), Divider(), Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( 'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'), FlatButton( onPressed: () { launch( 'https://www.youtube.com/watch?v=VFnDo3JUzjs'); }, child: Text('SAIBA MAIS')), ], ), ), Container( color: Color.fromARGB(255, 105, 190, 90), child: Column( children: <Widget>[ Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( '© 2020 todos os direitos reservados a Cartão Pró Vantagens.', style: TextStyle(fontSize: 10), ), ) ], ), Divider(), Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( 'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)', style: TextStyle(fontSize: 10), ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.facebook), color: Colors.black, onPressed: () { launch( 'https://www.facebook.com/provantagens/'); }, ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.instagram), color: Colors.black, onPressed: () { launch( 'https://www.instagram.com/cartaoprovantagens/'); }, ), ), ], ), ], ), ) ], ), ]); }, ) ), ); } tableBeneficios() { return Table( defaultColumnWidth: FlexColumnWidth(120.0), border: TableBorder( horizontalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), verticalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), ), children: [ _criarTituloTable(",Plus, Premium"), _criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"), _criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"), _criarLinhaTable("Invalidez Total e Parcial,X,X"), _criarLinhaTable("Assistência Residencial,X,X"), _criarLinhaTable("Assistência Funeral,X,X"), _criarLinhaTable("Assistência Pet,X,X"), _criarLinhaTable("Assistência Natalidade,X,X"), _criarLinhaTable("Assistência Eletroassist,X,X"), _criarLinhaTable("Assistência Alimentação,X,X"), _criarLinhaTable("Descontos em Parceiros,X,X"), ], ); } _criarLinhaTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name != "X" ? '' : 'X', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name != 'X' ? name : '', style: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } _criarTituloTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name == "" ? '' : 'Plano ', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } void _storePosition(TapDownDetails details) { _tapPosition = details.globalPosition; } } ```
2020/11/13
[ "https://Stackoverflow.com/questions/64822800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632998/" ]
This worked for me So I edited scrollposition.dart package from line 133 ``` @override //double get minScrollExtent => _minScrollExtent!; // double? _minScrollExtent; double get minScrollExtent { if (_minScrollExtent == null) { _minScrollExtent = 0.0; } return double.parse(_minScrollExtent.toString()); } double? _minScrollExtent; @override // double get maxScrollExtent => _maxScrollExtent!; // double? _maxScrollExtent; double get maxScrollExtent { if (_maxScrollExtent == null) { _maxScrollExtent = 0.0; } return double.parse(_maxScrollExtent.toString()); } double? _maxScrollExtent; ```
I solved the similar problem as follows. You can take advantage of the Boolean variable. I hope, help you. ``` child: !loading ? HomeCarousel(homeManager) : Center(child:ProgressIndicator()), ``` or ``` child: isLoading ? HomeCarousel(homeManager) : SplashScreen(), ``` ``` class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Loading...') ), ); } } ```
64,822,800
Good Morning, I'm trying to put a Carousel on the home page looking for Firebase data, but for some reason, the first time I load the application it appears the message below: ``` ════════ Exception caught by widgets library ═════════════════════════════════════ ══════════════════ The following _CastError was thrown building DotsIndicator (animation: PageController # 734f9 (one client, offset 0.0), dirty, state: _AnimatedState # 636ca): Null check operator used on a null value ``` and the screen looks like this: [![Screen Fail](https://i.stack.imgur.com/dntBE.jpg)](https://i.stack.imgur.com/dntBE.jpg) After giving a hot reload the error continues to appear, but the image is loaded successfully, any tips of what I can do? [![Screen Ok](https://i.stack.imgur.com/ILvCb.jpg)](https://i.stack.imgur.com/ILvCb.jpg) HomeManager: ``` import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/models/section.dart'; class HomeManager extends ChangeNotifier{ HomeManager({this.images}){ _loadSections(); images = images ?? []; } void addSection(Section section){ _editingSections.add(section); notifyListeners(); } final List<dynamic> _sections = []; List<String> images; List<dynamic> newImages; List<dynamic> _editingSections = []; bool editing = false; bool loading = false; int index, totalItems; final Firestore firestore = Firestore.instance; Future<void> _loadSections() async{ loading = true; firestore.collection('home').snapshots().listen((snapshot){ _sections.clear(); for(final DocumentSnapshot document in snapshot.documents){ _sections.add( Section.fromDocument(document)); images = List<String>.from(document.data['images'] as List<dynamic>); } }); loading = false; notifyListeners(); } List<dynamic> get sections { if(editing) return _editingSections; else return _sections; } void enterEditing({Section section}){ editing = true; _editingSections = _sections.map((s) => s.clone()).toList(); defineIndex(section: section); notifyListeners(); } void saveEditing() async{ bool valid = true; for(final section in _editingSections){ if(!section.valid()) valid = false; } if(!valid) return; loading = true; notifyListeners(); for(final section in _editingSections){ await section.save(); } for(final section in List.from(_sections)){ if(!_editingSections.any((s) => s.id == section.id)){ await section.delete(); } } loading = false; editing = false; notifyListeners(); } void discardEditing(){ editing = false; notifyListeners(); } void removeSection(Section section){ _editingSections.remove(section); notifyListeners(); } void onMoveUp(Section section){ int index = _editingSections.indexOf(section); if(index != 0) { _editingSections.remove(section); _editingSections.insert(index - 1, section); index = _editingSections.indexOf(section); } notifyListeners(); } HomeManager clone(){ return HomeManager( images: List.from(images), ); } void onMoveDown(Section section){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; if(index < totalItems - 1){ _editingSections.remove(section); _editingSections.insert(index + 1, section); index = _editingSections.indexOf(section); }else{ } notifyListeners(); } void defineIndex({Section section}){ index = _editingSections.indexOf(section); totalItems = _editingSections.length; notifyListeners(); } } ``` HomeScreen: ``` import 'package:carousel_pro/carousel_pro.dart'; import 'package:flutter/material.dart'; import 'package:provantagens_app/commom/custom_drawer.dart'; import 'package:provantagens_app/commom/custom_icons_icons.dart'; import 'package:provantagens_app/models/home_manager.dart'; import 'package:provantagens_app/models/section.dart'; import 'package:provantagens_app/screens/home/components/home_carousel.dart'; import 'package:provantagens_app/screens/home/components/menu_icon_tile.dart'; import 'package:provider/provider.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class HomeScreen extends StatelessWidget { HomeManager homeManager; Section section; List<Widget> get children => null; String videoUrl = 'https://www.youtube.com/watch?v=VFnDo3JUzjs'; int index; var _tapPosition; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient(colors: const [ Colors.white, Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), child: Scaffold( backgroundColor: Colors.transparent, drawer: CustomDrawer(), appBar: AppBar( backgroundColor: Colors.transparent, iconTheme: IconThemeData(color: Colors.black), title: Text('Página inicial', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8))), centerTitle: true, actions: <Widget>[ Divider(), ], ), body: Consumer<HomeManager>( builder: (_, homeManager, __){ return ListView(children: <Widget>[ AspectRatio( aspectRatio: 1, child:HomeCarousel(homeManager), ), Column( children: <Widget>[ Container( height: 50, ), Divider( color: Colors.black, ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Padding( padding: const EdgeInsets.only(left:12.0), child: MenuIconTile(title: 'Parceiros', iconData: Icons.apartment, page: 1,), ), Padding( padding: const EdgeInsets.only(left:7.0), child: MenuIconTile(title: 'Beneficios', iconData: Icons.card_giftcard, page: 2,), ), Padding( padding: const EdgeInsets.only(right:3.0), child: MenuIconTile(title: 'Suporte', iconData: Icons.help_outline, page: 6,), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ MenuIconTile(iconData: Icons.assignment, title: 'Dados pessoais', page: 3) , MenuIconTile(iconData: Icons.credit_card_outlined, title: 'Meu cartão', page: 4) , MenuIconTile(iconData: Icons.account_balance_wallet_outlined, title: 'Pagamento', page: 5,) , ], ), Divider( color: Colors.black, ), Container( height: 50, ), Consumer<HomeManager>( builder: (_, sec, __){ return RaisedButton( child: Text('Teste'), onPressed: (){ Navigator.of(context) .pushReplacementNamed('/teste', arguments: sec); }, ); }, ), Text('Saiba onde usar o seu', style: TextStyle(color: Colors.black, fontSize: 20),), Text('Cartão Pró Vantagens', style: TextStyle(color: Color.fromARGB(255, 30, 158, 8), fontSize: 30),), AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_80b5f6510f5841c19046f1ed5bca71e4~mv2.png/v1/fill/w_745,h_595,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es.webp', fit: BoxFit.fill, ), ), Divider(), Container( height: 150, child: Row( children: [ AspectRatio( aspectRatio: 1, child: Image.network( 'https://static.wixstatic.com/media/d170e1_486dd638987b4ef48d12a4bafee20e80~mv2.png/v1/fill/w_684,h_547,al_c,q_90,usm_0.66_1.00_0.01/Arte_Cart%C3%83%C2%B5es_2.webp', fit: BoxFit.fill, ), ), Padding( padding: const EdgeInsets.only(left:20.0), child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: 'Adquira já o seu', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: '\n\CARTÃO PRÓ VANTAGENS', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), ), ], ), ), Divider(), tableBeneficios(), Divider(), Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Text( 'O cartão Pró-Vantagens é sediado na cidade de Hortolândia/SP e já está no mercado há mais de 3 anos. Somos um time de profissionais apaixonados por gestão de benefícios e empenhados em gerar o máximo de valor para os conveniados.'), FlatButton( onPressed: () { launch( 'https://www.youtube.com/watch?v=VFnDo3JUzjs'); }, child: Text('SAIBA MAIS')), ], ), ), Container( color: Color.fromARGB(255, 105, 190, 90), child: Column( children: <Widget>[ Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( '© 2020 todos os direitos reservados a Cartão Pró Vantagens.', style: TextStyle(fontSize: 10), ), ) ], ), Divider(), Row( children: [ Padding( padding: const EdgeInsets.all(16), child: Text( 'Rua Luís Camilo de Camargo, 175 -\n\Centro, Hortolândia (piso superior)', style: TextStyle(fontSize: 10), ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.facebook), color: Colors.black, onPressed: () { launch( 'https://www.facebook.com/provantagens/'); }, ), ), Padding( padding: const EdgeInsets.only(left: 16), child: IconButton( icon: Icon(CustomIcons.instagram), color: Colors.black, onPressed: () { launch( 'https://www.instagram.com/cartaoprovantagens/'); }, ), ), ], ), ], ), ) ], ), ]); }, ) ), ); } tableBeneficios() { return Table( defaultColumnWidth: FlexColumnWidth(120.0), border: TableBorder( horizontalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), verticalInside: BorderSide( color: Colors.black, style: BorderStyle.solid, width: 1.0, ), ), children: [ _criarTituloTable(",Plus, Premium"), _criarLinhaTable("Seguro de vida\n\(Morte Acidental),X,X"), _criarLinhaTable("Seguro de Vida\n\(Qualquer natureza),,X"), _criarLinhaTable("Invalidez Total e Parcial,X,X"), _criarLinhaTable("Assistência Residencial,X,X"), _criarLinhaTable("Assistência Funeral,X,X"), _criarLinhaTable("Assistência Pet,X,X"), _criarLinhaTable("Assistência Natalidade,X,X"), _criarLinhaTable("Assistência Eletroassist,X,X"), _criarLinhaTable("Assistência Alimentação,X,X"), _criarLinhaTable("Descontos em Parceiros,X,X"), ], ); } _criarLinhaTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name != "X" ? '' : 'X', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name != 'X' ? name : '', style: TextStyle( fontSize: 10.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } _criarTituloTable(String listaNomes) { return TableRow( children: listaNomes.split(',').map((name) { return Container( alignment: Alignment.center, child: RichText( text: TextSpan(children: <TextSpan>[ TextSpan( text: name == "" ? '' : 'Plano ', style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), TextSpan( text: name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.bold, color: Color.fromARGB(255, 30, 158, 8)), ), ]), ), padding: EdgeInsets.all(8.0), ); }).toList(), ); } void _storePosition(TapDownDetails details) { _tapPosition = details.globalPosition; } } ```
2020/11/13
[ "https://Stackoverflow.com/questions/64822800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14632998/" ]
I faced the same issue. This is how I solved it ``` class PlansPage extends StatefulWidget { const PlansPage({Key? key}) : super(key: key); @override State<PlansPage> createState() => _PlansPageState(); } class _PlansPageState extends State<PlansPage> { int _currentPage = 1; late CarouselController carouselController; @override void initState() { super.initState(); carouselController = CarouselController(); } } ``` Then put initialization the carouselController inside the initState method I was able to use the methods jumpToPage(\_currentPage ) and animateToPage(\_currentPage) etc. I use animateToPage inside GestureDetector in onTap. ``` onTap: () { setState(() { _currentPage = pageIndex; }); carouselController.animateToPage(_currentPage); }, ``` I apologize in advance if this is inappropriate.
I solved the similar problem as follows. You can take advantage of the Boolean variable. I hope, help you. ``` child: !loading ? HomeCarousel(homeManager) : Center(child:ProgressIndicator()), ``` or ``` child: isLoading ? HomeCarousel(homeManager) : SplashScreen(), ``` ``` class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Loading...') ), ); } } ```
24,879,895
Could someone kindly point me to the right direction to seek further or give me any hints regarding the following task? I'd like to list all the distinct values from a MySQL table from column A that don't have a specific value in column B. I mean none of the same A values have this specific value in B in any of there rows. Taking the following table (let this specific value be 1): ``` column A | column B ---------------------- apple | apple | apple | 1 banana | anything banana | lemon | lemon | 1 orange | ``` I'd like to get the following result: ``` banana orange ``` Thanks.
2014/07/22
[ "https://Stackoverflow.com/questions/24879895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3863264/" ]
This might help you: ``` SELECT DISTINCT A FROM MY_TABLE WHERE A NOT IN (SELECT DISTINCT A FROM MY_TABLE WHERE B = 1) ```
Since there are null values, I have also added a nvl condition to column B . **ORACLE:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT COLUMN_A FROM MY_TABLE WHERE nvl(COLUMN_B,'dummy') = '1'); ``` **MYSQL:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT COLUMN_A FROM MY_TABLE WHERE IFNULL(COLUMN_B,'dummy') = '1'); ```
24,879,895
Could someone kindly point me to the right direction to seek further or give me any hints regarding the following task? I'd like to list all the distinct values from a MySQL table from column A that don't have a specific value in column B. I mean none of the same A values have this specific value in B in any of there rows. Taking the following table (let this specific value be 1): ``` column A | column B ---------------------- apple | apple | apple | 1 banana | anything banana | lemon | lemon | 1 orange | ``` I'd like to get the following result: ``` banana orange ``` Thanks.
2014/07/22
[ "https://Stackoverflow.com/questions/24879895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3863264/" ]
Since there are null values, I have also added a nvl condition to column B . **ORACLE:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT COLUMN_A FROM MY_TABLE WHERE nvl(COLUMN_B,'dummy') = '1'); ``` **MYSQL:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT COLUMN_A FROM MY_TABLE WHERE IFNULL(COLUMN_B,'dummy') = '1'); ```
``` SELECT * FROM your_Table WHERE Column_A NOT IN( SELECT Column_A FROM Your_Table WHERE Column_B = '1' ) ```
24,879,895
Could someone kindly point me to the right direction to seek further or give me any hints regarding the following task? I'd like to list all the distinct values from a MySQL table from column A that don't have a specific value in column B. I mean none of the same A values have this specific value in B in any of there rows. Taking the following table (let this specific value be 1): ``` column A | column B ---------------------- apple | apple | apple | 1 banana | anything banana | lemon | lemon | 1 orange | ``` I'd like to get the following result: ``` banana orange ``` Thanks.
2014/07/22
[ "https://Stackoverflow.com/questions/24879895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3863264/" ]
Since there are null values, I have also added a nvl condition to column B . **ORACLE:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT COLUMN_A FROM MY_TABLE WHERE nvl(COLUMN_B,'dummy') = '1'); ``` **MYSQL:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT COLUMN_A FROM MY_TABLE WHERE IFNULL(COLUMN_B,'dummy') = '1'); ```
This statement gives you the expected result: ``` select COLUMNA from myTable where COLUMNA not in (select distinct COLUMNA from myTable where columnB =1) group by COLUMNA; ```
24,879,895
Could someone kindly point me to the right direction to seek further or give me any hints regarding the following task? I'd like to list all the distinct values from a MySQL table from column A that don't have a specific value in column B. I mean none of the same A values have this specific value in B in any of there rows. Taking the following table (let this specific value be 1): ``` column A | column B ---------------------- apple | apple | apple | 1 banana | anything banana | lemon | lemon | 1 orange | ``` I'd like to get the following result: ``` banana orange ``` Thanks.
2014/07/22
[ "https://Stackoverflow.com/questions/24879895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3863264/" ]
This might help you: ``` SELECT DISTINCT A FROM MY_TABLE WHERE A NOT IN (SELECT DISTINCT A FROM MY_TABLE WHERE B = 1) ```
``` SELECT * FROM your_Table WHERE Column_A NOT IN( SELECT Column_A FROM Your_Table WHERE Column_B = '1' ) ```
24,879,895
Could someone kindly point me to the right direction to seek further or give me any hints regarding the following task? I'd like to list all the distinct values from a MySQL table from column A that don't have a specific value in column B. I mean none of the same A values have this specific value in B in any of there rows. Taking the following table (let this specific value be 1): ``` column A | column B ---------------------- apple | apple | apple | 1 banana | anything banana | lemon | lemon | 1 orange | ``` I'd like to get the following result: ``` banana orange ``` Thanks.
2014/07/22
[ "https://Stackoverflow.com/questions/24879895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3863264/" ]
This might help you: ``` SELECT DISTINCT A FROM MY_TABLE WHERE A NOT IN (SELECT DISTINCT A FROM MY_TABLE WHERE B = 1) ```
This statement gives you the expected result: ``` select COLUMNA from myTable where COLUMNA not in (select distinct COLUMNA from myTable where columnB =1) group by COLUMNA; ```
417,648
I've been using [Wakoopa](http://wakoopa.com) recently, and I find it quite amusing. I had no idea ( well I had an idea but never got real data about it ) on how much time I spend in SO until this: [alt text http://img396.imageshack.us/img396/4699/wakoopaim1.png](http://img396.imageshack.us/img396/4699/wakoopaim1.png) So my programming question is: > > *How can I programmatically track the applications being used?* > > > My initial though was to use something like "tasklist" command and "netstat" and pool every 15 minutes or something like that, but I don't think this is the way they're doing this. Is there a library in .NET ( in C# I guess ) to do this? Does windows provides some kind of service like this? What about java? I usually have at least some vague idea on how some programming task could be performed, but for this I don't have a clue. The wakoopa app tracker works on OSX and Linux too, but it is clear to me they are three different apps, one per platform BTW, how much do you used SO? :)
2009/01/06
[ "https://Stackoverflow.com/questions/417648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
Use a Javascript object literal: ``` var obj = { a: 1, b: 2, c: 'hello' }; ``` You can then traverse it like this: ``` for (var key in obj){ console.log(key, obj[key]); } ``` And access properties on the object like this: ``` console.log(obj.a, obj.c); ```
What you could do is something like: ``` var hash = {}; hash.a = 1; hash.b = 2; hash.c = 'hello'; for(key in hash) { // key would be 'a' and hash[key] would be 1, and so on. } ```
417,648
I've been using [Wakoopa](http://wakoopa.com) recently, and I find it quite amusing. I had no idea ( well I had an idea but never got real data about it ) on how much time I spend in SO until this: [alt text http://img396.imageshack.us/img396/4699/wakoopaim1.png](http://img396.imageshack.us/img396/4699/wakoopaim1.png) So my programming question is: > > *How can I programmatically track the applications being used?* > > > My initial though was to use something like "tasklist" command and "netstat" and pool every 15 minutes or something like that, but I don't think this is the way they're doing this. Is there a library in .NET ( in C# I guess ) to do this? Does windows provides some kind of service like this? What about java? I usually have at least some vague idea on how some programming task could be performed, but for this I don't have a clue. The wakoopa app tracker works on OSX and Linux too, but it is clear to me they are three different apps, one per platform BTW, how much do you used SO? :)
2009/01/06
[ "https://Stackoverflow.com/questions/417648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
Use a Javascript object literal: ``` var obj = { a: 1, b: 2, c: 'hello' }; ``` You can then traverse it like this: ``` for (var key in obj){ console.log(key, obj[key]); } ``` And access properties on the object like this: ``` console.log(obj.a, obj.c); ```
Goint off of Triptych's stuff (Which Thanks)... ```js (function(){ (createSingleton = function(name){ // global this[name] = (function(params){ for(var i in params){ this[i] = params[i]; console.log('params[i]: ' + i + ' = ' + params[i]); } return this; })({key: 'val', name: 'param'}); })('singleton'); console.log(singleton.key); })(); ``` Just thought this was a nice little autonomous pattern...hope it helps! Thanks Triptych!
417,648
I've been using [Wakoopa](http://wakoopa.com) recently, and I find it quite amusing. I had no idea ( well I had an idea but never got real data about it ) on how much time I spend in SO until this: [alt text http://img396.imageshack.us/img396/4699/wakoopaim1.png](http://img396.imageshack.us/img396/4699/wakoopaim1.png) So my programming question is: > > *How can I programmatically track the applications being used?* > > > My initial though was to use something like "tasklist" command and "netstat" and pool every 15 minutes or something like that, but I don't think this is the way they're doing this. Is there a library in .NET ( in C# I guess ) to do this? Does windows provides some kind of service like this? What about java? I usually have at least some vague idea on how some programming task could be performed, but for this I don't have a clue. The wakoopa app tracker works on OSX and Linux too, but it is clear to me they are three different apps, one per platform BTW, how much do you used SO? :)
2009/01/06
[ "https://Stackoverflow.com/questions/417648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
What you could do is something like: ``` var hash = {}; hash.a = 1; hash.b = 2; hash.c = 'hello'; for(key in hash) { // key would be 'a' and hash[key] would be 1, and so on. } ```
Goint off of Triptych's stuff (Which Thanks)... ```js (function(){ (createSingleton = function(name){ // global this[name] = (function(params){ for(var i in params){ this[i] = params[i]; console.log('params[i]: ' + i + ' = ' + params[i]); } return this; })({key: 'val', name: 'param'}); })('singleton'); console.log(singleton.key); })(); ``` Just thought this was a nice little autonomous pattern...hope it helps! Thanks Triptych!
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` File file = new File(path); boolean empty = file.exists() && file.length() == 0; ``` I want to stress that if we want to check if the file is empty, then we have to consider that it exists.
According to J2RE javadocs: <http://docs.oracle.com/javase/7/docs/api/java/io/File.html#length>() ``` public long length() Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. ``` So `new File("path to your file").length() > 0` should do the trick. Sorry for bd previous answer. :(
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` File file = new File("file_path"); System.out.println(file.length()); ```
``` File file = new File("path.txt"); if (file.exists()) { FileReader fr = new FileReader(file); if (fr.read() == -1) { System.out.println("EMPTY"); } else { System.out.println("NOT EMPTY"); } } else { System.out.println("DOES NOT EXISTS"); } ```
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` File file = new File("file_path"); System.out.println(file.length()); ```
``` BufferedReader br = new BufferedReader(new FileReader("your_location")); if (br.readLine()) == null ) { System.out.println("No errors, and file empty"); } ``` see [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows)
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` File file = new File("file_path"); System.out.println(file.length()); ```
``` File file = new File(path); boolean empty = file.exists() && file.length() == 0; ``` I want to stress that if we want to check if the file is empty, then we have to consider that it exists.
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` BufferedReader br = new BufferedReader(new FileReader("your_location")); if (br.readLine()) == null ) { System.out.println("No errors, and file empty"); } ``` see [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows)
According to J2RE javadocs: <http://docs.oracle.com/javase/7/docs/api/java/io/File.html#length>() ``` public long length() Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. ``` So `new File("path to your file").length() > 0` should do the trick. Sorry for bd previous answer. :(
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` File file = new File(path); boolean empty = !file.exists() || file.length() == 0; ``` which can shortened to: ``` boolean empty = file.length() == 0; ``` since according to documentation the method returns > > The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist > > >
``` File file = new File(path); boolean empty = file.exists() && file.length() == 0; ``` I want to stress that if we want to check if the file is empty, then we have to consider that it exists.
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` BufferedReader br = new BufferedReader(new FileReader("your_location")); if (br.readLine()) == null ) { System.out.println("No errors, and file empty"); } ``` see [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows)
``` File file = new File("path.txt"); if (file.exists()) { FileReader fr = new FileReader(file); if (fr.read() == -1) { System.out.println("EMPTY"); } else { System.out.println("NOT EMPTY"); } } else { System.out.println("DOES NOT EXISTS"); } ```
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
According to J2RE javadocs: <http://docs.oracle.com/javase/7/docs/api/java/io/File.html#length>() ``` public long length() Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. ``` So `new File("path to your file").length() > 0` should do the trick. Sorry for bd previous answer. :(
``` File file = new File("path.txt"); if (file.exists()) { FileReader fr = new FileReader(file); if (fr.read() == -1) { System.out.println("EMPTY"); } else { System.out.println("NOT EMPTY"); } } else { System.out.println("DOES NOT EXISTS"); } ```
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` File file = new File(path); boolean empty = !file.exists() || file.length() == 0; ``` which can shortened to: ``` boolean empty = file.length() == 0; ``` since according to documentation the method returns > > The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist > > >
``` File file = new File("path.txt"); if (file.exists()) { FileReader fr = new FileReader(file); if (fr.read() == -1) { System.out.println("EMPTY"); } else { System.out.println("NOT EMPTY"); } } else { System.out.println("DOES NOT EXISTS"); } ```
10,281,370
> > **Possible Duplicate:** > > [Most efficient way to check if a file is empty in Java on Windows](https://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows) > > > How to a check if a file is empty in Java 7? I tried it using the available() method from ObjectInputStream, but it returns always zero even if the the file contains data.
2012/04/23
[ "https://Stackoverflow.com/questions/10281370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/570339/" ]
``` File file = new File(path); boolean empty = file.exists() && file.length() == 0; ``` I want to stress that if we want to check if the file is empty, then we have to consider that it exists.
``` File file = new File("path.txt"); if (file.exists()) { FileReader fr = new FileReader(file); if (fr.read() == -1) { System.out.println("EMPTY"); } else { System.out.println("NOT EMPTY"); } } else { System.out.println("DOES NOT EXISTS"); } ```
33,281,167
Following [this tutorial](http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL) to create a safe login system, I came to this problem. In Part 7 of 8: Create HTML Pages, section 1 Create the login form (index.php), it uses: ``` <form action="includes/process_login.php" method="post" name="login_form"> ``` Although earlier on the tutorial it states (Part 3 of 8, section 1, first paragraph): > > In a production environment you'll probably want to locate this file > and all your other include files, outside of the web server's document > root. If you do that, and we strongly suggest that you do, you will > need to alter your include or require statements as necessary, so that > the application can find the include files. > > > So my includes folder is not inside /var/www/html/mysite/ or /var/www/html/, but in /var/www/, and my form became: ``` <form action="../../includes/process_login.php" method="post" name="login_form"> ``` (which works for the php includes). But this one don't work, I get this error: > > <http://localhost/includes/process_login.php> The requested URL > /includes/process\_login.php was not found on this server. > > > Why is it acting as if my includes was inside /var/www/html/ ? I checked all my /var/www/ folders using ``` grep -rnw . -e 'process_login.php' ``` and this is the only occurrence of that string (with the ../../). What am I missing?
2015/10/22
[ "https://Stackoverflow.com/questions/33281167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1086511/" ]
> > Anyway, I still want to understand why this is needed. > > > You have to understand that the html file is "executed" on the client side, meaning that if you link to something in the html file that is higher than the public folder (which the client perceives as root), the client cant reach it, as it is not available to the client. The client just cant send a request to a folder which is not made available to it by the web server. A php script however is executed on the server side, meaning it can access folders that are higher than the html perceived root. Basically: html thinks the root directory is the public folder, php thinks the root directory is the actual server root directory.
I found a workaround by including a file that just includes another, being the first in a public folder and the second in a hidden folder. The form: ``` <form action="process_login.php" method="post" name="login_form"> ``` First file (public\_folder/mysite/process\_login.php): ``` <?php include '../../includes/process_login.php'; ``` Second file (../../includes/process\_login.php): ``` <?php include_once 'db_connect.php'; include_once 'functions.php'; sec_session_start(); // Our custom secure way of starting a PHP session. if (isset($_POST['email'], $_POST['p'])) { $email = $_POST['email']; $pwd = $_POST['p']; // The hashed password. if (login($email, $pwd, $conn) == true) { // Login success header('Location: ../coisas/protected_page.php'); } else { // Login failed header('Location: ../coisas/index.php?error=1'); } } else { // The correct POST variables were not sent to this page. echo 'Invalid Request'; } ``` Anyway, I still want to understand why this is needed.
40,838
[`DMA`](http://www.valassis.com/by-industry/financial/banks-used-in-top-dmas.aspx?r=1) and `MMA` are commonly used to denote a large, metropolitan municipal entity. Is there a difference between the two? Is there a certified definition to these terms? Google is a bit inconclusive about the issue.
2012/11/11
[ "https://gis.stackexchange.com/questions/40838", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/382/" ]
If you look at the tool help you'll note that [Join Field](http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/Join_Field/001700000065000000/) permanently adds 1 or more fields to the input table. The tool you probably want is [Add Join](http://help.arcgis.com/en/arcgisdesktop/10.0/help/0017/001700000064000000.htm), which works more like the interactive join command to create a temporary join. You'll probably want to use [Remove Join](http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/Remove_Join/001700000066000000/) when you're done though to clean up after yourself.
In addition to blah238's answer, you should also use the [Add Attribute Index](http://resources.arcgis.com/en/help/main/10.1/index.html#//00170000005z000000) geoprocessing tool to create an index for the join. This tool accomplishes the same thing as this prompt: ![enter image description here](https://i.stack.imgur.com/odBli.jpg) This will greatly increase performance. Note that some read-only table file types (e.g. CSV) don't support attribute indices, so you'll have to export them to a .dbf file first.
40,838
[`DMA`](http://www.valassis.com/by-industry/financial/banks-used-in-top-dmas.aspx?r=1) and `MMA` are commonly used to denote a large, metropolitan municipal entity. Is there a difference between the two? Is there a certified definition to these terms? Google is a bit inconclusive about the issue.
2012/11/11
[ "https://gis.stackexchange.com/questions/40838", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/382/" ]
If you look at the tool help you'll note that [Join Field](http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/Join_Field/001700000065000000/) permanently adds 1 or more fields to the input table. The tool you probably want is [Add Join](http://help.arcgis.com/en/arcgisdesktop/10.0/help/0017/001700000064000000.htm), which works more like the interactive join command to create a temporary join. You'll probably want to use [Remove Join](http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#/Remove_Join/001700000066000000/) when you're done though to clean up after yourself.
This has been reported to the ArcGIS Ideas forum here: <https://geonet.esri.com/ideas/8679> A python script to automate joining the fast way has been provided here: <http://www.arcgis.com/home/item.html?id=da1540fb59d84b7cb02627856f65a98d>
34,799,907
In my SQL Server stored procedures I want to do this: ``` "hello xxx how are you" ``` where `xxx` is a value of a variable I tried this ``` CREATE PROCEDURE insertToPinTable (@callerID VARCHAR (200), @vAccount VARCHAR (200)) AS BEGIN DECLARE @textEnglish VARCHAR textEnglish = CONCAT ( "hello", @vAccount) INSERT INTO pinData([CallerID], [body], [processed]) VALUES (@callerID, @textEnglish, 0) END ``` I get an error > > Incorrect syntax near 'textEnglish' > > > it seems that using `CONCAT` is not correct, could you help me please (if I can insert the value of vAccount to the `hello` word, then in the same way I can insert the value of textEnglish, to the string `how are you`)
2016/01/14
[ "https://Stackoverflow.com/questions/34799907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2038257/" ]
``` CREATE PROCEDURE insertToPinTable ( @callerID VARCHAR (200), @vAccount VARCHAR (200) ) AS BEGIN DECLARE @textEnglish VARCHAR(255) --missing length previously set @textEnglish = 'hello'+ @vAccount --missing set keyword INSERT INTO pinData([CallerID], [body], [processed]) VALUES (@callerID, @textEnglish, 0) END ```
If you just want to change a string from ``` "hello xxx how are you" ``` to ``` "hello Mr. Smith how are you" ``` You might think about place holder replacement: Define your string as a template: ``` DECLARE @template VARCHAR(100)='hello {Name} how are you?'; ``` And then use ``` SELECT REPLACE(@template,'{Name}','Mr. Smith'); ```
7,682,561
> > **Possible Duplicate:** > > [How to read a CSV line with "?](https://stackoverflow.com/questions/2139750/how-to-read-a-csv-line-with) > > > I have seen a number of related questions but none have directly addressed what I am trying to do. I am reading in lines of text from a CSV file. All the items are in quotes and some have additional commas within the quotes. I would like to split the line along commas, but ignore the commas within quotes. Is there a way to do this within Python that does not require a number of regex statements. An example is: ``` "114111","Planes,Trains,and Automobiles","50","BOOK" ``` which I would like parsed into 4 separate variables of values: ``` "114111" "Planes,Trains,and Automobiles" "50" "Book" ``` Is there a simple option in `line.split()` that I am missing ?
2011/10/07
[ "https://Stackoverflow.com/questions/7682561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442158/" ]
Don't try to re-invent the wheel. If you want to read lines from a CSV file, use Python's [`csv` module](http://docs.python.org/dev/library/csv.html?highlight=csv#csv) from the standard library. **Example:** ``` > cat test.py import csv with open('some.csv') as f: reader = csv.reader(f) for row in reader: print(row) > cat some.csv "114111","Planes,Trains,and Automobiles","50","BOOK" > python test.py ['114111', 'Planes,Trains,and Automobiles', '50', 'BOOK'] [] ``` Job done!
You can probably split on "," that is "[quote][comma][quote]" the other option is coming up with an escape character, so if somebody wants to embed a comma in the string they do \c and if they want a backslash they do \\. Then you have to split the string, then unescape it before processing.
45,748,285
I'm trying to build a site where the user can first login anonymously using firebase and then convert his account to permanent by signing in with facebook. I'm following the instructions given at <https://firebase.google.com/docs/auth/web/anonymous-auth> but i'm getting the following error "Uncaught ReferenceError: response is not defined". I also tried converting the account using Google Sign in but then i get the error "googleUser is not defined". What am i doing wrong? This is my code:- ``` <html> <body> <button onclick = "anonymousLogin()">Anonymous Signin</butto> <button onclick = "facebookSignin()">Facebook Signin</button> <button onclick = "facebookSignout()">Facebook Signout</button> </body> <script> function anonymousLogin(){ firebase.auth().signInAnonymously().catch(function(error) { // Handle Errors here. var errorCode = error.code; console.log(errorCode) var errorMessage = error.message; console.log(errorMessage) }); } function facebookSignin() { var provider = new firebase.auth.FacebookAuthProvider(); var credential = firebase.auth.FacebookAuthProvider.credential( response.authResponse.accessToken); auth.currentUser.link(credential).then(function(user) { console.log("Anonymous account successfully upgraded", user); }, function(error) { console.log("Error upgrading anonymous account", error); }); } </script> </html> ```
2017/08/18
[ "https://Stackoverflow.com/questions/45748285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8481300/" ]
okay i found a solution. Apparently converting from anonymous to facebook user needs you to find the token yourself. I found this workaround. ``` var provider = new firebase.auth.FacebookAuthProvider(); firebase.auth().currentUser.linkWithPopup(provider) ```
I think `response` here refers to the event that Facebook login passes to the callback. [Facebook traditionally calls this `response`](https://developers.facebook.com/docs/facebook-login/web), but [our Github sample](https://github.com/firebase/quickstart-js/blob/master/auth/facebook-credentials.html#L81) calls it `events`. The name of course isn't important, but you're not declaring it for your callback. ``` function facebookSignin(response) { var provider = new firebase.auth.FacebookAuthProvider(); var credential = firebase.auth.FacebookAuthProvider.credential( response.authResponse.accessToken); ``` Also see <https://github.com/firebase/quickstart-js/blob/master/auth/facebook-credentials.html#L81>
298,305
How to do this in Java - passing a collection of subtype to a method requiring a collection of base type? The example below gives: ``` The method foo(Map<String,List>) is not applicable for the arguments (Map<String,MyList>) ``` I can implement by creating a class hierarchy for the typed collections - but is it possible otherwise? ``` public void testStackOverflow() { class MyList extends AbstractList { public Object get(int index) { return null; } public int size() { return 0; } }; Map <String, List> baseColl = null; Map <String, MyList> subColl = null; foo (subColl); } private void foo (Map <String, List> in) { } ``` EDIT: Turns out from the answers that this requires "bounded wildcard" so adding this text for searchability
2008/11/18
[ "https://Stackoverflow.com/questions/298305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2887/" ]
Change `foo` to: ``` private void foo(Map <String, ? extends List> in) { } ``` That will restrict what you can do within `foo`, but that's reasonable. You know that any value you fetch from the map will be a list, but you don't know what kind of value is valid to put into the map.
as jon s says: ``` private void foo (Map <String, ? extends List> in { ... } ``` will fix the errors. you will still have warnings though. take a look the get-put principle at: <http://www.ibm.com/developerworks/java/library/j-jtp07018.html>
15,713,080
I have a usecase for which I would like to know if HTML5's Server-sent-Events is suitable. Multiple clients (Javascript+HTML5 browsers) connect to the web server (with a Java EE backend). Each client could be looking at a different view at any time, depending on what is their object of interest. My **Question** is: How to keep multiple clients (on different views) up-to-date on the updates happening on the server-side, **without** flooding all clients with all updates on all views ? Important points that I need to consider are: 1. Many clients might be interested in the same events. If two clients are looking at the same view, they MUST get identical events. 2. Events to be sent to a client depend on the view that client is currently at. 3. Some clients may not be interested in any events (i.e they might be viewing static data) 4. A given client could be dynamically changing their interest. for ex: close View1 and open View2. 5. A client could be interested in multiple event channels (for ex: two dynamically-changing views could be part of a single page). 6. I can target only browsers with complete support for SSE. 7. There will only be a maximum of 100 clients (browsers) connected to the server at any time. So, I could have the luxury of having more than one connection open (for SSE), per client. I have searched SO/Google for SSE and couldnt (yet) get reliable solution for production quality software. I dont want to go back to old Comet techniques, before fully exploring SSE. Is SSE (by itself) capable of delivering on these requirements ? I am looking into Atmosphere right now, but I dont want to resort to some polyfill that imitates SSE, before deciding that SSE wont be sufficient by itself. **What I plan to do if this is not possible:** The server could broadcast all events to all clients and let the clients figure it out. This would mean, lots of unnecessary traffic from server to client and complex client code.
2013/03/29
[ "https://Stackoverflow.com/questions/15713080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733060/" ]
Unless you can target a specific set of recent browsers you will always have to support some sort of fallback. [Atmosphere](https://github.com/Atmosphere/atmosphere) looks like a good solution for that. As to sending the right events to the right clients: Keep track of the clients and their preferences in either a Session object (check of Atmosphere is configured to support sessions) or your own Map. It looks like you can create multiple session broadcasters in Atmosphere as outlined here: <http://blog.javaforge.net/post/32659151672/atmosphere-per-session-broadcaster> Disclaimer: I've never used this myself.
What you could do is to send parameters via GET when you register an event with `EventSource`. The only problem lies at point #4, for which you should close the connection and re-register the event. I tried that myself and it works pretty well.
5,769,250
I'm using jQuery to show and hide various divs to paginate content. However, immediately after selecting an option that shows or hides the divs (for example, page 1, 2 or 3) and scrolls erratically up and down rather than let me scroll down the page. I have no idea at all what could be doing this, and having searched Stack Overflow and Google it doesn't appear to be a problem that anyone else has faced. Does anyone have advice on what could be causing this problem and how to rectify it?
2011/04/24
[ "https://Stackoverflow.com/questions/5769250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/701279/" ]
You're wanting to do an [svn switch](http://svnbook.red-bean.com/en/1.5/svn.ref.svn.c.switch.html) either via the command line or many SVN clients (i.e. Tortoise), expose this easily through the GUI. However, if you've deleted .svn folders (which help track the base version of files before modification), you may find you need to check out again.
you cant move folders like that in SVN. have you tried to recheck it out ? or you can delete the folder from the svn, and them move it to its parent, and delete the hidden "svn" folder in it, then commit it again .
14,059,704
I've been looking on Google for a solution to this, but I don't even know which words should I use to find it... Anyway, my problem is that Eclipse looks like this in Linux Mint 14 x64: <http://i.stack.imgur.com/BBfyg.png> I'm using Eclipse downloaded from their webpage, not from the repositories. I've tried resetting the perspective, deleting both the eclipse and workspace folders but it keeps looking like this. Any ideas? **EDIT** I finally managed to get rid of it. It looks like it had something to do with GTK. I changed the appearance to Classic in Preferences and it solved it.
2012/12/27
[ "https://Stackoverflow.com/questions/14059704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1846142/" ]
Going to Window > Preferences > General > Appearance and changing the theme to Classic seems to solve the problem.
Changing the Eclipse Preferences from GTK to Classic did not work for me. Only the background of some Eclipse components get displayed in gray then which makes the visual corruptions less visible. Yet it helped to change the GTK theme in Linux Mint from "Mint-X" to "Adwaita", which also looks ok. So this could be a workaround. Update: This is a bit bug/issue/missing feature in the Mint-X theme which can easily be fixed manually. See <http://dentrassi.de/2013/04/23/fixing-the-mint-x-theme-for-eclipseswt/>
81,607
Hi I have been working on a script to update statistics of all tables on all my DBs. The idea is to parametrise it later on, but just as a quick fix, and not wanting to implement [Ola's scripts](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html) today, follow the script below. I have tested it on a few servers, but before I schedule it to run on a live server Sunday morning, would like to get some ideas and share it with you. ``` SET NOCOUNT ON DECLARE @DBS TABLE (I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, DBNAME SYSNAME NOT NULL ) DECLARE @I INT ,@Z INT ,@SQL VARCHAR(1008) ,@j INT ,@Y INT ,@MYDB SYSNAME INSERT INTO @DBS SELECT s.name FROM sys.databases s INNER JOIN SYS.master_files F ON S.DATABASE_ID = F.database_id AND F.data_space_id = 1 WHERE S.STATE = 0 -- online AND S.database_id > 3 -- exclude master, tempdb and model -- I left msdb AND S.is_read_only = 0 -- read/write AND S.user_access = 0 -- multi_user AND S.NAME NOT IN ('TableBackups', 'Troubleshooting') ORDER BY F.SIZE DESC SELECT @Z = @@ROWCOUNT SELECT @I = 1 WHILE @I <= @z BEGIN BEGIN TRY DROP TABLE #T END TRY BEGIN CATCH END CATCH CREATE TABLE #T( I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, MYSQL VARCHAR(1008) NOT NULL ) SELECT @MYDB = QUOTENAME (S.DBNAME ) ,@SQL = 'USE ' + QUOTENAME (S.DBNAME ) + ';' + CHAR(13) + ' ' + CHAR(13) + 'INSERT INTO #T(MYSQL) SELECT ''UPDATE STATISTICS '' + QUOTENAME(NAME) FROM SYS.TABLES WHERE TYPE = ''U'' ' + CHAR(13) FROM @DBS s WHERE s.I = @I PRINT CAST (@SQL AS NTEXT) BEGIN TRY EXEC (@SQL) SELECT @Y = @@ROWCOUNT END TRY BEGIN CATCH SELECT @Y = 0 END CATCH SELECT @J = 1 WHILE @J <= @y BEGIN SELECT @SQL = 'USE ' + @MYDB + ';' + CHAR(13) + MYSQL FROM #T WHERE I= @J BEGIN TRY EXEC (@SQL) END TRY BEGIN CATCH END CATCH PRINT CAST (@SQL AS NTEXT) SELECT @J = @J + 1 END SELECT @I = @I +1 END /*WHILE*/ ```
2014/10/31
[ "https://dba.stackexchange.com/questions/81607", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/22336/" ]
Right off the bat, your script completely ignores schema, so it will fail unless all of your production servers only use `dbo` explicitly as the namespace for all tables (and nobody has a default schema other than `dbo`). You're also using a deprecated data type (`NTEXT`) for seemingly no reason. Also I don't think the `WHERE` clause against sys.tables is necessary (I don't know how anything but a `U` could ever be in there). Not sure why you bother ordering by file size; the job isn't going to finish faster if you handle the biggest databases first (also the join could return multiple rows for a database if it has more than one file in `data_space_id = 1`, which means you would potentially process that database multiple times). Finally, I have to wonder if it is really wise to blindly update stats on every table in every database across your entire instance, regardless of size... and why you don't bother checking for indexed views, which also require maintenance. You could save quite a bit of work if you add some logic to exclude any tables that don't need it. **My partial solution** This code will be slightly harder to maintain, doesn't have the `TRY/CATCH` wrappers yours does, and doesn't add any additional logic about which tables to actually pursue, but since I get a kick out of making automation tasks out of dynamic SQL (and really enjoy solutions that cause no horizontal or vertical scrollbars on this site), here you go. When you're happy with the output, comment the print and uncomment the exec. ``` DECLARE @sql NVARCHAR(MAX) = N'', @stats NVARCHAR(MAX) = N''; SELECT @sql += N'EXEC ' + QUOTENAME(name) + '.sys.sp_executesql @stats;' FROM sys.databases WHERE [state] = 0 AND user_access = 0; -- and your other filters SET @stats = N'DECLARE @inner NVARCHAR(MAX) = N''''; SELECT @inner += CHAR(10) + N''UPDATE STATISTICS '' + QUOTENAME(s.name) + ''.'' + QUOTENAME(t.name) + '';'' FROM sys.tables AS t INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id]; PRINT CHAR(10) + DB_NAME() + CHAR(10) + @inner; --EXEC sys.sp_executesql @inner;' EXEC [master].sys.sp_executesql @sql, N'@stats NVARCHAR(MAX)', @stats; ```
I did notice a couple of things. 1. I highly recommend using more than one character variable & temp table names. It makes it harder to read and next year when you are reading this again (or someone else is) you won't remember what they mean. It's not that hard to use @DBCounter instead of @I for example. 2. Your DB list query at the top will create duplicates (causing duplicate work) if there is more than one data filegroup. Also you won't be looking at the DB size, just the file size in your ordering. I would change the end of the query to this: ``` GROUP BY s.name ORDER BY SUM(F.SIZE) DESC ``` 3. Is there a reason you aren't using [sp\_updatestats](http://msdn.microsoft.com/en-us/library/ms173804.aspx) on each database rather than running UPDATE STATISTICS on each table? It also has the benefit of only updating the statistics on tables that need to have it run. 4. Last thing and not a huge issue. Don't CAST to NTEXT. It's an old data type and will be removed in a future version of SQL Server. Use NVARCHAR(MAX) instead.
81,607
Hi I have been working on a script to update statistics of all tables on all my DBs. The idea is to parametrise it later on, but just as a quick fix, and not wanting to implement [Ola's scripts](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html) today, follow the script below. I have tested it on a few servers, but before I schedule it to run on a live server Sunday morning, would like to get some ideas and share it with you. ``` SET NOCOUNT ON DECLARE @DBS TABLE (I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, DBNAME SYSNAME NOT NULL ) DECLARE @I INT ,@Z INT ,@SQL VARCHAR(1008) ,@j INT ,@Y INT ,@MYDB SYSNAME INSERT INTO @DBS SELECT s.name FROM sys.databases s INNER JOIN SYS.master_files F ON S.DATABASE_ID = F.database_id AND F.data_space_id = 1 WHERE S.STATE = 0 -- online AND S.database_id > 3 -- exclude master, tempdb and model -- I left msdb AND S.is_read_only = 0 -- read/write AND S.user_access = 0 -- multi_user AND S.NAME NOT IN ('TableBackups', 'Troubleshooting') ORDER BY F.SIZE DESC SELECT @Z = @@ROWCOUNT SELECT @I = 1 WHILE @I <= @z BEGIN BEGIN TRY DROP TABLE #T END TRY BEGIN CATCH END CATCH CREATE TABLE #T( I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, MYSQL VARCHAR(1008) NOT NULL ) SELECT @MYDB = QUOTENAME (S.DBNAME ) ,@SQL = 'USE ' + QUOTENAME (S.DBNAME ) + ';' + CHAR(13) + ' ' + CHAR(13) + 'INSERT INTO #T(MYSQL) SELECT ''UPDATE STATISTICS '' + QUOTENAME(NAME) FROM SYS.TABLES WHERE TYPE = ''U'' ' + CHAR(13) FROM @DBS s WHERE s.I = @I PRINT CAST (@SQL AS NTEXT) BEGIN TRY EXEC (@SQL) SELECT @Y = @@ROWCOUNT END TRY BEGIN CATCH SELECT @Y = 0 END CATCH SELECT @J = 1 WHILE @J <= @y BEGIN SELECT @SQL = 'USE ' + @MYDB + ';' + CHAR(13) + MYSQL FROM #T WHERE I= @J BEGIN TRY EXEC (@SQL) END TRY BEGIN CATCH END CATCH PRINT CAST (@SQL AS NTEXT) SELECT @J = @J + 1 END SELECT @I = @I +1 END /*WHILE*/ ```
2014/10/31
[ "https://dba.stackexchange.com/questions/81607", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/22336/" ]
Unless you want to implement some really powerful filters in your logic, the following code will do the job just fine: ``` exec sp_MSforeachdb 'use [?]; if db_name() not in (''master'', ''model'', ''tempdb'', ''msdb'') exec sp_updatestats;'; go ```
I did notice a couple of things. 1. I highly recommend using more than one character variable & temp table names. It makes it harder to read and next year when you are reading this again (or someone else is) you won't remember what they mean. It's not that hard to use @DBCounter instead of @I for example. 2. Your DB list query at the top will create duplicates (causing duplicate work) if there is more than one data filegroup. Also you won't be looking at the DB size, just the file size in your ordering. I would change the end of the query to this: ``` GROUP BY s.name ORDER BY SUM(F.SIZE) DESC ``` 3. Is there a reason you aren't using [sp\_updatestats](http://msdn.microsoft.com/en-us/library/ms173804.aspx) on each database rather than running UPDATE STATISTICS on each table? It also has the benefit of only updating the statistics on tables that need to have it run. 4. Last thing and not a huge issue. Don't CAST to NTEXT. It's an old data type and will be removed in a future version of SQL Server. Use NVARCHAR(MAX) instead.
81,607
Hi I have been working on a script to update statistics of all tables on all my DBs. The idea is to parametrise it later on, but just as a quick fix, and not wanting to implement [Ola's scripts](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html) today, follow the script below. I have tested it on a few servers, but before I schedule it to run on a live server Sunday morning, would like to get some ideas and share it with you. ``` SET NOCOUNT ON DECLARE @DBS TABLE (I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, DBNAME SYSNAME NOT NULL ) DECLARE @I INT ,@Z INT ,@SQL VARCHAR(1008) ,@j INT ,@Y INT ,@MYDB SYSNAME INSERT INTO @DBS SELECT s.name FROM sys.databases s INNER JOIN SYS.master_files F ON S.DATABASE_ID = F.database_id AND F.data_space_id = 1 WHERE S.STATE = 0 -- online AND S.database_id > 3 -- exclude master, tempdb and model -- I left msdb AND S.is_read_only = 0 -- read/write AND S.user_access = 0 -- multi_user AND S.NAME NOT IN ('TableBackups', 'Troubleshooting') ORDER BY F.SIZE DESC SELECT @Z = @@ROWCOUNT SELECT @I = 1 WHILE @I <= @z BEGIN BEGIN TRY DROP TABLE #T END TRY BEGIN CATCH END CATCH CREATE TABLE #T( I INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, MYSQL VARCHAR(1008) NOT NULL ) SELECT @MYDB = QUOTENAME (S.DBNAME ) ,@SQL = 'USE ' + QUOTENAME (S.DBNAME ) + ';' + CHAR(13) + ' ' + CHAR(13) + 'INSERT INTO #T(MYSQL) SELECT ''UPDATE STATISTICS '' + QUOTENAME(NAME) FROM SYS.TABLES WHERE TYPE = ''U'' ' + CHAR(13) FROM @DBS s WHERE s.I = @I PRINT CAST (@SQL AS NTEXT) BEGIN TRY EXEC (@SQL) SELECT @Y = @@ROWCOUNT END TRY BEGIN CATCH SELECT @Y = 0 END CATCH SELECT @J = 1 WHILE @J <= @y BEGIN SELECT @SQL = 'USE ' + @MYDB + ';' + CHAR(13) + MYSQL FROM #T WHERE I= @J BEGIN TRY EXEC (@SQL) END TRY BEGIN CATCH END CATCH PRINT CAST (@SQL AS NTEXT) SELECT @J = @J + 1 END SELECT @I = @I +1 END /*WHILE*/ ```
2014/10/31
[ "https://dba.stackexchange.com/questions/81607", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/22336/" ]
Right off the bat, your script completely ignores schema, so it will fail unless all of your production servers only use `dbo` explicitly as the namespace for all tables (and nobody has a default schema other than `dbo`). You're also using a deprecated data type (`NTEXT`) for seemingly no reason. Also I don't think the `WHERE` clause against sys.tables is necessary (I don't know how anything but a `U` could ever be in there). Not sure why you bother ordering by file size; the job isn't going to finish faster if you handle the biggest databases first (also the join could return multiple rows for a database if it has more than one file in `data_space_id = 1`, which means you would potentially process that database multiple times). Finally, I have to wonder if it is really wise to blindly update stats on every table in every database across your entire instance, regardless of size... and why you don't bother checking for indexed views, which also require maintenance. You could save quite a bit of work if you add some logic to exclude any tables that don't need it. **My partial solution** This code will be slightly harder to maintain, doesn't have the `TRY/CATCH` wrappers yours does, and doesn't add any additional logic about which tables to actually pursue, but since I get a kick out of making automation tasks out of dynamic SQL (and really enjoy solutions that cause no horizontal or vertical scrollbars on this site), here you go. When you're happy with the output, comment the print and uncomment the exec. ``` DECLARE @sql NVARCHAR(MAX) = N'', @stats NVARCHAR(MAX) = N''; SELECT @sql += N'EXEC ' + QUOTENAME(name) + '.sys.sp_executesql @stats;' FROM sys.databases WHERE [state] = 0 AND user_access = 0; -- and your other filters SET @stats = N'DECLARE @inner NVARCHAR(MAX) = N''''; SELECT @inner += CHAR(10) + N''UPDATE STATISTICS '' + QUOTENAME(s.name) + ''.'' + QUOTENAME(t.name) + '';'' FROM sys.tables AS t INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id]; PRINT CHAR(10) + DB_NAME() + CHAR(10) + @inner; --EXEC sys.sp_executesql @inner;' EXEC [master].sys.sp_executesql @sql, N'@stats NVARCHAR(MAX)', @stats; ```
Unless you want to implement some really powerful filters in your logic, the following code will do the job just fine: ``` exec sp_MSforeachdb 'use [?]; if db_name() not in (''master'', ''model'', ''tempdb'', ''msdb'') exec sp_updatestats;'; go ```
25,366
I really dislike the name "NoSQL", because it isn't very descriptive. It tells me what the databases *aren't* where I'm more interested in what the databases *are*. I really think that this category really encompasses several categories of database. I'm just trying to get a general idea of what job each particular database is the best tool for. A few assumptions I'd like to make (and would ask you to make): 1. Assume that you have the capability to hire any number of brilliant engineers who are equally experienced with every database technology that has ever existed. 2. Assume you have the technical infrastructure to support any given database (including available servers and sysadmins who can support said database). 3. Assume that each database has the best support possible for free. 4. Assume you have 100% buy-in from management. 5. Assume you have an infinite amount of money to throw at the problem. Now, I realize that the above assumptions eliminate a lot of valid considerations that are involved in choosing a database, but my focus is on figuring out what database is best for the job on a purely technical level. So, given the above assumptions, the question is: what jobs are each database (including both SQL and NoSQL) the best tool for and why?
2010/12/10
[ "https://softwareengineering.stackexchange.com/questions/25366", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/1626/" ]
SQL --- Relational object. Stable servers with fine grain control over permissions. NoSQL ----- Flexible storage. High scalability and sharding abilities.
There is some very good info on this in this article: [*Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase vs Membase vs Neo4j comparison*](http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis) : > > While SQL databases are insanely useful tools, their monopoly of ~15 > years is coming to an end. And it was just time: I can't even count > the things that were forced into relational databases, but never > really fitted them. > > But the differences between NoSQL databases are > much bigger than it ever was between one SQL database and another. > This means that it is a bigger responsibility on software architects > to choose the appropriate one for a project right at the beginning. > > In this light, here is a comparison of Cassandra, Mongodb, CouchDB, > Redis, Riak, Membase, Neo4j and HBase [...] > > >
25,366
I really dislike the name "NoSQL", because it isn't very descriptive. It tells me what the databases *aren't* where I'm more interested in what the databases *are*. I really think that this category really encompasses several categories of database. I'm just trying to get a general idea of what job each particular database is the best tool for. A few assumptions I'd like to make (and would ask you to make): 1. Assume that you have the capability to hire any number of brilliant engineers who are equally experienced with every database technology that has ever existed. 2. Assume you have the technical infrastructure to support any given database (including available servers and sysadmins who can support said database). 3. Assume that each database has the best support possible for free. 4. Assume you have 100% buy-in from management. 5. Assume you have an infinite amount of money to throw at the problem. Now, I realize that the above assumptions eliminate a lot of valid considerations that are involved in choosing a database, but my focus is on figuring out what database is best for the job on a purely technical level. So, given the above assumptions, the question is: what jobs are each database (including both SQL and NoSQL) the best tool for and why?
2010/12/10
[ "https://softwareengineering.stackexchange.com/questions/25366", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/1626/" ]
SQL --- Relational object. Stable servers with fine grain control over permissions. NoSQL ----- Flexible storage. High scalability and sharding abilities.
I guess this isn't a good question, for example, what kind of vehicles is good? Bugatti, BWM, automobile, mini machine, train, locomotive, airplane? it depends on your situation, > > for a small job with no huge data, sqlight may good. > > for a company who use Microsoft's product, MSSQL is good. > > for web developing, MySql is very easy to use. > > for banks, Oracle or couchbase(if handle trancation issue). > > for a small job with a lot of data, MongoDB is good. > > for a company with huge data and only one kind table, Cassandra. > > for a company with huge data, Couchbase. > > for hadoop ecosystem, HBase. > > for graph, image, in Memory, ... > > >
25,366
I really dislike the name "NoSQL", because it isn't very descriptive. It tells me what the databases *aren't* where I'm more interested in what the databases *are*. I really think that this category really encompasses several categories of database. I'm just trying to get a general idea of what job each particular database is the best tool for. A few assumptions I'd like to make (and would ask you to make): 1. Assume that you have the capability to hire any number of brilliant engineers who are equally experienced with every database technology that has ever existed. 2. Assume you have the technical infrastructure to support any given database (including available servers and sysadmins who can support said database). 3. Assume that each database has the best support possible for free. 4. Assume you have 100% buy-in from management. 5. Assume you have an infinite amount of money to throw at the problem. Now, I realize that the above assumptions eliminate a lot of valid considerations that are involved in choosing a database, but my focus is on figuring out what database is best for the job on a purely technical level. So, given the above assumptions, the question is: what jobs are each database (including both SQL and NoSQL) the best tool for and why?
2010/12/10
[ "https://softwareengineering.stackexchange.com/questions/25366", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/1626/" ]
Relational databases (SQL) are great for data that the underlying model remains stable. Many implementations have been around for a while (Oracle, DB2, SqlServer) and are stable and secure. Also, it's very easy to find experienced people to administrate them - and database admins are a must! The programmers should not have to deal with permissions, setup, and tuning. They should be able to concentrate on programming, and let the administrators worry about keeping the database up. Relational databases are also relatively easy to query, and there are many tools out there to assist with finding data from them.
There is some very good info on this in this article: [*Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase vs Membase vs Neo4j comparison*](http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis) : > > While SQL databases are insanely useful tools, their monopoly of ~15 > years is coming to an end. And it was just time: I can't even count > the things that were forced into relational databases, but never > really fitted them. > > But the differences between NoSQL databases are > much bigger than it ever was between one SQL database and another. > This means that it is a bigger responsibility on software architects > to choose the appropriate one for a project right at the beginning. > > In this light, here is a comparison of Cassandra, Mongodb, CouchDB, > Redis, Riak, Membase, Neo4j and HBase [...] > > >
25,366
I really dislike the name "NoSQL", because it isn't very descriptive. It tells me what the databases *aren't* where I'm more interested in what the databases *are*. I really think that this category really encompasses several categories of database. I'm just trying to get a general idea of what job each particular database is the best tool for. A few assumptions I'd like to make (and would ask you to make): 1. Assume that you have the capability to hire any number of brilliant engineers who are equally experienced with every database technology that has ever existed. 2. Assume you have the technical infrastructure to support any given database (including available servers and sysadmins who can support said database). 3. Assume that each database has the best support possible for free. 4. Assume you have 100% buy-in from management. 5. Assume you have an infinite amount of money to throw at the problem. Now, I realize that the above assumptions eliminate a lot of valid considerations that are involved in choosing a database, but my focus is on figuring out what database is best for the job on a purely technical level. So, given the above assumptions, the question is: what jobs are each database (including both SQL and NoSQL) the best tool for and why?
2010/12/10
[ "https://softwareengineering.stackexchange.com/questions/25366", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/1626/" ]
Relational databases (SQL) are great for data that the underlying model remains stable. Many implementations have been around for a while (Oracle, DB2, SqlServer) and are stable and secure. Also, it's very easy to find experienced people to administrate them - and database admins are a must! The programmers should not have to deal with permissions, setup, and tuning. They should be able to concentrate on programming, and let the administrators worry about keeping the database up. Relational databases are also relatively easy to query, and there are many tools out there to assist with finding data from them.
I guess this isn't a good question, for example, what kind of vehicles is good? Bugatti, BWM, automobile, mini machine, train, locomotive, airplane? it depends on your situation, > > for a small job with no huge data, sqlight may good. > > for a company who use Microsoft's product, MSSQL is good. > > for web developing, MySql is very easy to use. > > for banks, Oracle or couchbase(if handle trancation issue). > > for a small job with a lot of data, MongoDB is good. > > for a company with huge data and only one kind table, Cassandra. > > for a company with huge data, Couchbase. > > for hadoop ecosystem, HBase. > > for graph, image, in Memory, ... > > >
25,366
I really dislike the name "NoSQL", because it isn't very descriptive. It tells me what the databases *aren't* where I'm more interested in what the databases *are*. I really think that this category really encompasses several categories of database. I'm just trying to get a general idea of what job each particular database is the best tool for. A few assumptions I'd like to make (and would ask you to make): 1. Assume that you have the capability to hire any number of brilliant engineers who are equally experienced with every database technology that has ever existed. 2. Assume you have the technical infrastructure to support any given database (including available servers and sysadmins who can support said database). 3. Assume that each database has the best support possible for free. 4. Assume you have 100% buy-in from management. 5. Assume you have an infinite amount of money to throw at the problem. Now, I realize that the above assumptions eliminate a lot of valid considerations that are involved in choosing a database, but my focus is on figuring out what database is best for the job on a purely technical level. So, given the above assumptions, the question is: what jobs are each database (including both SQL and NoSQL) the best tool for and why?
2010/12/10
[ "https://softwareengineering.stackexchange.com/questions/25366", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/1626/" ]
There is some very good info on this in this article: [*Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase vs Membase vs Neo4j comparison*](http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis) : > > While SQL databases are insanely useful tools, their monopoly of ~15 > years is coming to an end. And it was just time: I can't even count > the things that were forced into relational databases, but never > really fitted them. > > But the differences between NoSQL databases are > much bigger than it ever was between one SQL database and another. > This means that it is a bigger responsibility on software architects > to choose the appropriate one for a project right at the beginning. > > In this light, here is a comparison of Cassandra, Mongodb, CouchDB, > Redis, Riak, Membase, Neo4j and HBase [...] > > >
I guess this isn't a good question, for example, what kind of vehicles is good? Bugatti, BWM, automobile, mini machine, train, locomotive, airplane? it depends on your situation, > > for a small job with no huge data, sqlight may good. > > for a company who use Microsoft's product, MSSQL is good. > > for web developing, MySql is very easy to use. > > for banks, Oracle or couchbase(if handle trancation issue). > > for a small job with a lot of data, MongoDB is good. > > for a company with huge data and only one kind table, Cassandra. > > for a company with huge data, Couchbase. > > for hadoop ecosystem, HBase. > > for graph, image, in Memory, ... > > >
22,540,916
My company is very strict when it comes to security. My project, (built using VB.Net and SQL Server 2008) requires that users upload PDF files which then need to be stored into the database along with the associated path. Because the files will be just about 256kb or less, I wanted to insert the files as `Single BLOB`. My table has two columns Path as `varchar(50)` and `File` as `varbinary(max)`. My SQL query looks something like this: ``` INSERT INTO [DBNAME].[dbo].[SOMETABLE](PATH, FILE) values ('C:\Somefile.pdf', (SELECT * FROM OPENROWSET(BULK N'C:\Somefile.pdf', SINGLE_BLOB) AS import )) ``` Unfortunately, I only have read and write permissions on the database, thus yielding the following error: `You do not have permission to use the bulk load statement.` I have read this [post](https://dba.stackexchange.com/questions/23599/bulk-insert-permission-on-a-single-database) but for other security reasons, I will not be granted `Insert` or `ADMINISTER BULK OPERATIONS` permissions. From other posts that I have read, without the permissions this option seems to be a dead end. Now, I am looking into using `FILESTREAM` to insert the files but will not be able to create a new database. Can I accomplish this by enabling `FILESTREAM` on an existing database and database table and work with those? I have been on this for two days, any help or ideas would be much appreciated.
2014/03/20
[ "https://Stackoverflow.com/questions/22540916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2509621/" ]
If you can't create a new database, I'm guessing they won't let you alter an existing database either. You can add FILESTREAM capabilities, but it requires that you at least create a new FILEGROUP. It also requires that the server configuration be changed if it isn't already set up to support FILESTREAM capabilities. Again, this sounds unlikely in the environment you describe. Also, FILESTREAM is generally recommended for larger files (>1 MB) then the 256KB you mention. Since they are so strict in your environment you might try loading the document into your VB front end, encoding it and storing it to the database from there as a byte data insert from there. It won't require the BLOB/BULK insert and sounds like it might be a better alternative in such a restricted environment.
Why do you not just load the file up via normal SQL statements and binary array? The size is small enough for this and it means that you only need access to the files from your app, not the server needs to find and read them.
9,596,807
I am working on a Big Project and i have a lot of GWT code written. Now i am working on making the project fully compatible with Tablets like iPad and Android Tablets. As a part of this, i have noticed that touch devices takes **300ms** delay to handle click events. In this project, writing touch events again is a very tedious task. I have done a lot of researches in this and found the Google Fast Buttons API used in Google Voice Application. I tried that and its working good but requires a lot of coding and JSNI. My question is, Is there anything else available in your knowledge to easily overcome this delay?
2012/03/07
[ "https://Stackoverflow.com/questions/9596807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987492/" ]
Here is a pure java implementation of the fast button.It doesn't include a single line of JNSI ``` package com.apollo.tabletization.shared.util; import java.util.Date; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.dom.client.HasAllTouchHandlers; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; /** Implementation of Google FastButton {@link http://code.google.com/mobile/articles/fast_buttons.html} */ public class FastButton extends Composite { private boolean touchHandled = false; private boolean clickHandled = false; private boolean touchMoved = false; private int startY; private int startX; private int timeStart; public FastButton(Widget child) { // TODO - messages assert (child instanceof HasAllTouchHandlers) : ""; assert (child instanceof HasClickHandlers) : ""; initWidget(child); sinkEvents(Event.TOUCHEVENTS | Event.ONCLICK); } @Override public Widget getWidget() { return super.getWidget(); } @Override public void onBrowserEvent(Event event) { timeStart = getUnixTimeStamp(); switch (DOM.eventGetType(event)) { case Event.ONTOUCHSTART: { onTouchStart(event); break; } case Event.ONTOUCHEND: { onTouchEnd(event); break; } case Event.ONTOUCHMOVE: { onTouchMove(event); break; } case Event.ONCLICK: { onClick(event); return; } } super.onBrowserEvent(event); } private void onClick(Event event) { event.stopPropagation(); int timeEnd = getUnixTimeStamp(); if(touchHandled) { //Window.alert("click via touch: "+ this.toString() + "..." +timeStart+"---"+timeEnd); touchHandled = false; clickHandled = true; super.onBrowserEvent(event); } else { if(clickHandled) { event.preventDefault(); } else { clickHandled = false; //Window.alert("click nativo: "+ this.toString()+ "..." +(timeStart-timeEnd)+"==="+timeStart+"---"+timeEnd); super.onBrowserEvent(event); } } } private void onTouchEnd(Event event) { if (!touchMoved) { touchHandled = true; fireClick(); } } private void onTouchMove(Event event) { if (!touchMoved) { Touch touch = event.getTouches().get(0); int deltaX = Math.abs(startX - touch.getClientX()); int deltaY = Math.abs(startY - touch.getClientY()); if (deltaX > 5 || deltaY > 5) { touchMoved = true; } } } private void onTouchStart(Event event) { Touch touch = event.getTouches().get(0); this.startX = touch.getClientX(); this.startY = touch.getClientY(); touchMoved = false; } private void fireClick() { NativeEvent evt = Document.get().createClickEvent(1, 0, 0, 0, 0, false, false, false, false); getElement().dispatchEvent(evt); } private int getUnixTimeStamp() { Date date = new Date(); int iTimeStamp = (int) (date.getTime() * .001); return iTimeStamp; } } ```
I think the code from the prior answer as written has a few problems, in particular when their are multiple touches. (NOTE: I'm looking at code I wrote using the Elemental library as reference, so some of the calls might be different in the user library). a) The code is not filtering touches aimed at the button; it calls TouchEvent.getTouches(). You want to call TouchEvent.getTargetTouches() on touchstart and touchmove to get the the touches just for your button. You want to call TouchEvent.getChangedTouches() on touchend to get the end touch. b) The code does not take into account multitouch. On touchstart, you can check that a single touch is available and bail out if there is more than one. Also, on touchstart, stash away the id of touch, then use this in touchmove and touchend to find your touch id in the array that is returned (in case the user has touched another finger later on). You can also simplify and check for multiple touches on touchmove and touchend and bail again there. c) I believe you need to call stopPropagation on touchstart, since you are handling the event. I don't see where they call event.stopPropagation on the touchstart event You can see that this happens in the click handlers, but not the touchstart. This prevents the touch from being turned into a click automatically by the browser, which would cause multiple clicks. There is also a simpler way. If you don't care about dragging starting on a button, then you can simply call your click logic in the touchstart event (and make sure you check for single touch, and call event.stopPropagation ) and ignore touchmove and touchend. All the touchmove and touchend stuff is to handle the case of allowing dragging to start on the button.
9,596,807
I am working on a Big Project and i have a lot of GWT code written. Now i am working on making the project fully compatible with Tablets like iPad and Android Tablets. As a part of this, i have noticed that touch devices takes **300ms** delay to handle click events. In this project, writing touch events again is a very tedious task. I have done a lot of researches in this and found the Google Fast Buttons API used in Google Voice Application. I tried that and its working good but requires a lot of coding and JSNI. My question is, Is there anything else available in your knowledge to easily overcome this delay?
2012/03/07
[ "https://Stackoverflow.com/questions/9596807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987492/" ]
Here is a pure java implementation of the fast button.It doesn't include a single line of JNSI ``` package com.apollo.tabletization.shared.util; import java.util.Date; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.dom.client.HasAllTouchHandlers; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; /** Implementation of Google FastButton {@link http://code.google.com/mobile/articles/fast_buttons.html} */ public class FastButton extends Composite { private boolean touchHandled = false; private boolean clickHandled = false; private boolean touchMoved = false; private int startY; private int startX; private int timeStart; public FastButton(Widget child) { // TODO - messages assert (child instanceof HasAllTouchHandlers) : ""; assert (child instanceof HasClickHandlers) : ""; initWidget(child); sinkEvents(Event.TOUCHEVENTS | Event.ONCLICK); } @Override public Widget getWidget() { return super.getWidget(); } @Override public void onBrowserEvent(Event event) { timeStart = getUnixTimeStamp(); switch (DOM.eventGetType(event)) { case Event.ONTOUCHSTART: { onTouchStart(event); break; } case Event.ONTOUCHEND: { onTouchEnd(event); break; } case Event.ONTOUCHMOVE: { onTouchMove(event); break; } case Event.ONCLICK: { onClick(event); return; } } super.onBrowserEvent(event); } private void onClick(Event event) { event.stopPropagation(); int timeEnd = getUnixTimeStamp(); if(touchHandled) { //Window.alert("click via touch: "+ this.toString() + "..." +timeStart+"---"+timeEnd); touchHandled = false; clickHandled = true; super.onBrowserEvent(event); } else { if(clickHandled) { event.preventDefault(); } else { clickHandled = false; //Window.alert("click nativo: "+ this.toString()+ "..." +(timeStart-timeEnd)+"==="+timeStart+"---"+timeEnd); super.onBrowserEvent(event); } } } private void onTouchEnd(Event event) { if (!touchMoved) { touchHandled = true; fireClick(); } } private void onTouchMove(Event event) { if (!touchMoved) { Touch touch = event.getTouches().get(0); int deltaX = Math.abs(startX - touch.getClientX()); int deltaY = Math.abs(startY - touch.getClientY()); if (deltaX > 5 || deltaY > 5) { touchMoved = true; } } } private void onTouchStart(Event event) { Touch touch = event.getTouches().get(0); this.startX = touch.getClientX(); this.startY = touch.getClientY(); touchMoved = false; } private void fireClick() { NativeEvent evt = Document.get().createClickEvent(1, 0, 0, 0, 0, false, false, false, false); getElement().dispatchEvent(evt); } private int getUnixTimeStamp() { Date date = new Date(); int iTimeStamp = (int) (date.getTime() * .001); return iTimeStamp; } } ```
I have tried to use the above answers and comments to take a stab at this implementation. I have also posteds a sample GWT project which can be used for easy comparison: <http://gwt-fast-touch-press.appspot.com/> <https://github.com/ashtonthomas/gwt-fast-touch-press> Please note that you will only be able to see the time saved if you are on a mobile device (or devices that handles the touch events and doesn't just fall back to onClick). I have added 3 fast buttons and 3 normal buttons. You can easily see an improvement when on older mobile devices and sometimes less so on newer (Samsung Galaxy Nexus only showed delays of around 100ms while the 1st gen iPad was over 400ms almost every time). The biggest improvement is when you try to rapidly and consecutively click the boxes (not really buttons here but can be adapted) ``` package io.ashton.fastpress.client.fast; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; /** * * GWT Implementation influenced by Google's FastPressElement: * https://developers.google.com/mobile/articles/fast_buttons * * Using Code examples and comments from: * http://stackoverflow.com/questions/9596807/converting-gwt-click-events-to-touch-events * * The FastPressElement is used to avoid the 300ms delay on mobile devices (Only do this if you want * to ignore the possibility of a double tap - The browser waits to see if we actually want to * double top) * * The "press" event will occur significantly fast (around 300ms faster). However the biggest * improvement is from enabling fast consecutive touches. * * If you try to rapidly touch one or more FastPressElements, you will notice a MUCH great * improvement. * * NOTE: Different browsers will handle quick swipe or long hold/drag touches differently. * This is an edge case if the user is long pressing or pressing while dragging the finger * slightly (but staying on the element) - The browser may or may not fire the event. However, * the browser will always fire the regular tap/press very quickly. * * TODO We should be able to embed fastElements and have the child fastElements NOT bubble the event * So we can embed the elements if needed (???) * * @author ashton * */ public abstract class FastPressElement extends Composite implements HasPressHandlers { private boolean touchHandled = false; private boolean clickHandled = false; private boolean touchMoved = false; private boolean isEnabled = true; private int touchId; private int flashDelay = 75; // Default time delay in ms to flash style change public FastPressElement() { // Sink Click and Touch Events // I am not going to sink Mouse events since // I don't think we will gain anything sinkEvents(Event.ONCLICK | Event.TOUCHEVENTS); // Event.TOUCHEVENTS adds all (Start, End, // Cancel, Change) } public FastPressElement(int msDelay) { this(); if (msDelay >= 0) { flashDelay = msDelay; } } public void setEnabled(boolean enabled) { if (enabled) { onEnablePressStyle(); } else { onDisablePressStyle(); } this.isEnabled = enabled; } /** * Use this method in the same way you would use addClickHandler or addDomHandler * */ @Override public HandlerRegistration addPressHandler(PressHandler handler) { // Use Widget's addHandler to ensureHandlers and add the type/return handler // We don't use addDom/BitlessHandlers since we aren't sinkEvents // We also aren't even dealing with a DomEvent return addHandler(handler, PressEvent.getType()); } /** * * @param event */ private void firePressEvent(Event event) { // This better verify a ClickEvent or TouchEndEvent // TODO might want to verify // (hitting issue with web.bindery vs g.gwt.user package diff) PressEvent pressEvent = new PressEvent(event); fireEvent(pressEvent); } /** * Implement the handler for pressing but NOT releasing the button. Normally you just want to show * some CSS style change to alert the user the element is active but not yet pressed * * ONLY FOR STYLE CHANGE - Will briefly be called onClick * * TIP: Don't make a dramatic style change. Take note that if a user is just trying to scroll, and * start on the element and then scrolls off, we may not want to distract them too much. If a user * does scroll off the element, * */ public abstract void onHoldPressDownStyle(); /** * Implement the handler for release of press. This should just be some CSS or Style change. * * ONLY FOR STYLE CHANGE - Will briefly be called onClick * * TIP: This should just go back to the normal style. */ public abstract void onHoldPressOffStyle(); /** * Change styling to disabled */ public abstract void onDisablePressStyle(); /** * Change styling to enabled * * TIP: */ public abstract void onEnablePressStyle(); @Override public Widget getWidget() { return super.getWidget(); } @Override public void onBrowserEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONTOUCHSTART: { if (isEnabled) { onTouchStart(event); } break; } case Event.ONTOUCHEND: { if (isEnabled) { onTouchEnd(event); } break; } case Event.ONTOUCHMOVE: { if (isEnabled) { onTouchMove(event); } break; } case Event.ONCLICK: { if (isEnabled) { onClick(event); } return; } default: { // Let parent handle event if not one of the above (?) super.onBrowserEvent(event); } } } private void onClick(Event event) { event.stopPropagation(); if (touchHandled) { // if the touch is already handled, we are on a device // that supports touch (so you aren't in the desktop browser) touchHandled = false;// reset for next press clickHandled = true;// super.onBrowserEvent(event); } else { if (clickHandled) { // Not sure how this situation would occur // onClick being called twice.. event.preventDefault(); } else { // Press not handled yet // We still want to briefly fire the style change // To give good user feedback // Show HoldPress when possible Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { // Show hold press onHoldPressDownStyle(); // Now schedule a delay (which will allow the actual // onTouchClickFire to executed Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { @Override public boolean execute() { // Clear the style change onHoldPressOffStyle(); return false; } }, flashDelay); } }); clickHandled = false; firePressEvent(event); } } } private void onTouchStart(Event event) { onHoldPressDownStyle(); // Show style change // Stop the event from bubbling up event.stopPropagation(); // Only handle if we have exactly one touch if (event.getTargetTouches().length() == 1) { Touch start = event.getTargetTouches().get(0); touchId = start.getIdentifier(); touchMoved = false; } } /** * Check to see if the touch has moved off of the element. * * NOTE that in iOS the elasticScroll may make the touch/move cancel more difficult. * * @param event */ private void onTouchMove(Event event) { if (!touchMoved) { Touch move = null; for (int i = 0; i < event.getChangedTouches().length(); i++) { if (event.getChangedTouches().get(i).getIdentifier() == touchId) { move = event.getChangedTouches().get(i); } } // Check to see if we moved off of the original element // Use Page coordinates since we compare with widget's absolute coordinates int yCord = move.getPageY(); int xCord = move.getPageX(); boolean yTop = getWidget().getAbsoluteTop() > yCord; // is y above element boolean yBottom = (getWidget().getAbsoluteTop() + getWidget().getOffsetHeight()) < yCord; // y // below boolean xLeft = getWidget().getAbsoluteLeft() > xCord; // is x to the left of element boolean xRight = (getWidget().getAbsoluteLeft() + getWidget().getOffsetWidth()) < xCord; // x // to // the // right if (yTop || yBottom || xLeft || xRight) { touchMoved = true; onHoldPressOffStyle();// Go back to normal style } } } private void onTouchEnd(Event event) { if (!touchMoved) { touchHandled = true; firePressEvent(event); event.preventDefault(); onHoldPressOffStyle();// Change back the style } } } ```
9,596,807
I am working on a Big Project and i have a lot of GWT code written. Now i am working on making the project fully compatible with Tablets like iPad and Android Tablets. As a part of this, i have noticed that touch devices takes **300ms** delay to handle click events. In this project, writing touch events again is a very tedious task. I have done a lot of researches in this and found the Google Fast Buttons API used in Google Voice Application. I tried that and its working good but requires a lot of coding and JSNI. My question is, Is there anything else available in your knowledge to easily overcome this delay?
2012/03/07
[ "https://Stackoverflow.com/questions/9596807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987492/" ]
Here is a pure java implementation of the fast button.It doesn't include a single line of JNSI ``` package com.apollo.tabletization.shared.util; import java.util.Date; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.dom.client.HasAllTouchHandlers; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; /** Implementation of Google FastButton {@link http://code.google.com/mobile/articles/fast_buttons.html} */ public class FastButton extends Composite { private boolean touchHandled = false; private boolean clickHandled = false; private boolean touchMoved = false; private int startY; private int startX; private int timeStart; public FastButton(Widget child) { // TODO - messages assert (child instanceof HasAllTouchHandlers) : ""; assert (child instanceof HasClickHandlers) : ""; initWidget(child); sinkEvents(Event.TOUCHEVENTS | Event.ONCLICK); } @Override public Widget getWidget() { return super.getWidget(); } @Override public void onBrowserEvent(Event event) { timeStart = getUnixTimeStamp(); switch (DOM.eventGetType(event)) { case Event.ONTOUCHSTART: { onTouchStart(event); break; } case Event.ONTOUCHEND: { onTouchEnd(event); break; } case Event.ONTOUCHMOVE: { onTouchMove(event); break; } case Event.ONCLICK: { onClick(event); return; } } super.onBrowserEvent(event); } private void onClick(Event event) { event.stopPropagation(); int timeEnd = getUnixTimeStamp(); if(touchHandled) { //Window.alert("click via touch: "+ this.toString() + "..." +timeStart+"---"+timeEnd); touchHandled = false; clickHandled = true; super.onBrowserEvent(event); } else { if(clickHandled) { event.preventDefault(); } else { clickHandled = false; //Window.alert("click nativo: "+ this.toString()+ "..." +(timeStart-timeEnd)+"==="+timeStart+"---"+timeEnd); super.onBrowserEvent(event); } } } private void onTouchEnd(Event event) { if (!touchMoved) { touchHandled = true; fireClick(); } } private void onTouchMove(Event event) { if (!touchMoved) { Touch touch = event.getTouches().get(0); int deltaX = Math.abs(startX - touch.getClientX()); int deltaY = Math.abs(startY - touch.getClientY()); if (deltaX > 5 || deltaY > 5) { touchMoved = true; } } } private void onTouchStart(Event event) { Touch touch = event.getTouches().get(0); this.startX = touch.getClientX(); this.startY = touch.getClientY(); touchMoved = false; } private void fireClick() { NativeEvent evt = Document.get().createClickEvent(1, 0, 0, 0, 0, false, false, false, false); getElement().dispatchEvent(evt); } private int getUnixTimeStamp() { Date date = new Date(); int iTimeStamp = (int) (date.getTime() * .001); return iTimeStamp; } } ```
Also Try [FastClick](https://github.com/ftlabs/fastclick) **FastClick** is a simple, easy-to-use library for eliminating the **300ms** delay between a physical tap and the firing of a click event on mobile browsers. The aim is to make your application feel less laggy and more responsive while avoiding any interference with your current logic. FastClick is developed by FT Labs, part of the Financial Times. The library has been deployed as part of the FT Web App and is tried and tested on the following mobile browsers: * Mobile Safari on iOS 3 and upwards * Chrome on iOS 5 and upwards * Chrome on Android (ICS) * Opera Mobile 11.5 and upwards * Android Browser since Android 2 * PlayBook OS 1 and upwards FastClick doesn't attach any listeners on desktop browsers as it is not needed. Those that have been tested are: * Safari * Chrome * Internet Explorer * Firefox * Opera
9,596,807
I am working on a Big Project and i have a lot of GWT code written. Now i am working on making the project fully compatible with Tablets like iPad and Android Tablets. As a part of this, i have noticed that touch devices takes **300ms** delay to handle click events. In this project, writing touch events again is a very tedious task. I have done a lot of researches in this and found the Google Fast Buttons API used in Google Voice Application. I tried that and its working good but requires a lot of coding and JSNI. My question is, Is there anything else available in your knowledge to easily overcome this delay?
2012/03/07
[ "https://Stackoverflow.com/questions/9596807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987492/" ]
I think the code from the prior answer as written has a few problems, in particular when their are multiple touches. (NOTE: I'm looking at code I wrote using the Elemental library as reference, so some of the calls might be different in the user library). a) The code is not filtering touches aimed at the button; it calls TouchEvent.getTouches(). You want to call TouchEvent.getTargetTouches() on touchstart and touchmove to get the the touches just for your button. You want to call TouchEvent.getChangedTouches() on touchend to get the end touch. b) The code does not take into account multitouch. On touchstart, you can check that a single touch is available and bail out if there is more than one. Also, on touchstart, stash away the id of touch, then use this in touchmove and touchend to find your touch id in the array that is returned (in case the user has touched another finger later on). You can also simplify and check for multiple touches on touchmove and touchend and bail again there. c) I believe you need to call stopPropagation on touchstart, since you are handling the event. I don't see where they call event.stopPropagation on the touchstart event You can see that this happens in the click handlers, but not the touchstart. This prevents the touch from being turned into a click automatically by the browser, which would cause multiple clicks. There is also a simpler way. If you don't care about dragging starting on a button, then you can simply call your click logic in the touchstart event (and make sure you check for single touch, and call event.stopPropagation ) and ignore touchmove and touchend. All the touchmove and touchend stuff is to handle the case of allowing dragging to start on the button.
Also Try [FastClick](https://github.com/ftlabs/fastclick) **FastClick** is a simple, easy-to-use library for eliminating the **300ms** delay between a physical tap and the firing of a click event on mobile browsers. The aim is to make your application feel less laggy and more responsive while avoiding any interference with your current logic. FastClick is developed by FT Labs, part of the Financial Times. The library has been deployed as part of the FT Web App and is tried and tested on the following mobile browsers: * Mobile Safari on iOS 3 and upwards * Chrome on iOS 5 and upwards * Chrome on Android (ICS) * Opera Mobile 11.5 and upwards * Android Browser since Android 2 * PlayBook OS 1 and upwards FastClick doesn't attach any listeners on desktop browsers as it is not needed. Those that have been tested are: * Safari * Chrome * Internet Explorer * Firefox * Opera
9,596,807
I am working on a Big Project and i have a lot of GWT code written. Now i am working on making the project fully compatible with Tablets like iPad and Android Tablets. As a part of this, i have noticed that touch devices takes **300ms** delay to handle click events. In this project, writing touch events again is a very tedious task. I have done a lot of researches in this and found the Google Fast Buttons API used in Google Voice Application. I tried that and its working good but requires a lot of coding and JSNI. My question is, Is there anything else available in your knowledge to easily overcome this delay?
2012/03/07
[ "https://Stackoverflow.com/questions/9596807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987492/" ]
I have tried to use the above answers and comments to take a stab at this implementation. I have also posteds a sample GWT project which can be used for easy comparison: <http://gwt-fast-touch-press.appspot.com/> <https://github.com/ashtonthomas/gwt-fast-touch-press> Please note that you will only be able to see the time saved if you are on a mobile device (or devices that handles the touch events and doesn't just fall back to onClick). I have added 3 fast buttons and 3 normal buttons. You can easily see an improvement when on older mobile devices and sometimes less so on newer (Samsung Galaxy Nexus only showed delays of around 100ms while the 1st gen iPad was over 400ms almost every time). The biggest improvement is when you try to rapidly and consecutively click the boxes (not really buttons here but can be adapted) ``` package io.ashton.fastpress.client.fast; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; /** * * GWT Implementation influenced by Google's FastPressElement: * https://developers.google.com/mobile/articles/fast_buttons * * Using Code examples and comments from: * http://stackoverflow.com/questions/9596807/converting-gwt-click-events-to-touch-events * * The FastPressElement is used to avoid the 300ms delay on mobile devices (Only do this if you want * to ignore the possibility of a double tap - The browser waits to see if we actually want to * double top) * * The "press" event will occur significantly fast (around 300ms faster). However the biggest * improvement is from enabling fast consecutive touches. * * If you try to rapidly touch one or more FastPressElements, you will notice a MUCH great * improvement. * * NOTE: Different browsers will handle quick swipe or long hold/drag touches differently. * This is an edge case if the user is long pressing or pressing while dragging the finger * slightly (but staying on the element) - The browser may or may not fire the event. However, * the browser will always fire the regular tap/press very quickly. * * TODO We should be able to embed fastElements and have the child fastElements NOT bubble the event * So we can embed the elements if needed (???) * * @author ashton * */ public abstract class FastPressElement extends Composite implements HasPressHandlers { private boolean touchHandled = false; private boolean clickHandled = false; private boolean touchMoved = false; private boolean isEnabled = true; private int touchId; private int flashDelay = 75; // Default time delay in ms to flash style change public FastPressElement() { // Sink Click and Touch Events // I am not going to sink Mouse events since // I don't think we will gain anything sinkEvents(Event.ONCLICK | Event.TOUCHEVENTS); // Event.TOUCHEVENTS adds all (Start, End, // Cancel, Change) } public FastPressElement(int msDelay) { this(); if (msDelay >= 0) { flashDelay = msDelay; } } public void setEnabled(boolean enabled) { if (enabled) { onEnablePressStyle(); } else { onDisablePressStyle(); } this.isEnabled = enabled; } /** * Use this method in the same way you would use addClickHandler or addDomHandler * */ @Override public HandlerRegistration addPressHandler(PressHandler handler) { // Use Widget's addHandler to ensureHandlers and add the type/return handler // We don't use addDom/BitlessHandlers since we aren't sinkEvents // We also aren't even dealing with a DomEvent return addHandler(handler, PressEvent.getType()); } /** * * @param event */ private void firePressEvent(Event event) { // This better verify a ClickEvent or TouchEndEvent // TODO might want to verify // (hitting issue with web.bindery vs g.gwt.user package diff) PressEvent pressEvent = new PressEvent(event); fireEvent(pressEvent); } /** * Implement the handler for pressing but NOT releasing the button. Normally you just want to show * some CSS style change to alert the user the element is active but not yet pressed * * ONLY FOR STYLE CHANGE - Will briefly be called onClick * * TIP: Don't make a dramatic style change. Take note that if a user is just trying to scroll, and * start on the element and then scrolls off, we may not want to distract them too much. If a user * does scroll off the element, * */ public abstract void onHoldPressDownStyle(); /** * Implement the handler for release of press. This should just be some CSS or Style change. * * ONLY FOR STYLE CHANGE - Will briefly be called onClick * * TIP: This should just go back to the normal style. */ public abstract void onHoldPressOffStyle(); /** * Change styling to disabled */ public abstract void onDisablePressStyle(); /** * Change styling to enabled * * TIP: */ public abstract void onEnablePressStyle(); @Override public Widget getWidget() { return super.getWidget(); } @Override public void onBrowserEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONTOUCHSTART: { if (isEnabled) { onTouchStart(event); } break; } case Event.ONTOUCHEND: { if (isEnabled) { onTouchEnd(event); } break; } case Event.ONTOUCHMOVE: { if (isEnabled) { onTouchMove(event); } break; } case Event.ONCLICK: { if (isEnabled) { onClick(event); } return; } default: { // Let parent handle event if not one of the above (?) super.onBrowserEvent(event); } } } private void onClick(Event event) { event.stopPropagation(); if (touchHandled) { // if the touch is already handled, we are on a device // that supports touch (so you aren't in the desktop browser) touchHandled = false;// reset for next press clickHandled = true;// super.onBrowserEvent(event); } else { if (clickHandled) { // Not sure how this situation would occur // onClick being called twice.. event.preventDefault(); } else { // Press not handled yet // We still want to briefly fire the style change // To give good user feedback // Show HoldPress when possible Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { // Show hold press onHoldPressDownStyle(); // Now schedule a delay (which will allow the actual // onTouchClickFire to executed Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { @Override public boolean execute() { // Clear the style change onHoldPressOffStyle(); return false; } }, flashDelay); } }); clickHandled = false; firePressEvent(event); } } } private void onTouchStart(Event event) { onHoldPressDownStyle(); // Show style change // Stop the event from bubbling up event.stopPropagation(); // Only handle if we have exactly one touch if (event.getTargetTouches().length() == 1) { Touch start = event.getTargetTouches().get(0); touchId = start.getIdentifier(); touchMoved = false; } } /** * Check to see if the touch has moved off of the element. * * NOTE that in iOS the elasticScroll may make the touch/move cancel more difficult. * * @param event */ private void onTouchMove(Event event) { if (!touchMoved) { Touch move = null; for (int i = 0; i < event.getChangedTouches().length(); i++) { if (event.getChangedTouches().get(i).getIdentifier() == touchId) { move = event.getChangedTouches().get(i); } } // Check to see if we moved off of the original element // Use Page coordinates since we compare with widget's absolute coordinates int yCord = move.getPageY(); int xCord = move.getPageX(); boolean yTop = getWidget().getAbsoluteTop() > yCord; // is y above element boolean yBottom = (getWidget().getAbsoluteTop() + getWidget().getOffsetHeight()) < yCord; // y // below boolean xLeft = getWidget().getAbsoluteLeft() > xCord; // is x to the left of element boolean xRight = (getWidget().getAbsoluteLeft() + getWidget().getOffsetWidth()) < xCord; // x // to // the // right if (yTop || yBottom || xLeft || xRight) { touchMoved = true; onHoldPressOffStyle();// Go back to normal style } } } private void onTouchEnd(Event event) { if (!touchMoved) { touchHandled = true; firePressEvent(event); event.preventDefault(); onHoldPressOffStyle();// Change back the style } } } ```
Also Try [FastClick](https://github.com/ftlabs/fastclick) **FastClick** is a simple, easy-to-use library for eliminating the **300ms** delay between a physical tap and the firing of a click event on mobile browsers. The aim is to make your application feel less laggy and more responsive while avoiding any interference with your current logic. FastClick is developed by FT Labs, part of the Financial Times. The library has been deployed as part of the FT Web App and is tried and tested on the following mobile browsers: * Mobile Safari on iOS 3 and upwards * Chrome on iOS 5 and upwards * Chrome on Android (ICS) * Opera Mobile 11.5 and upwards * Android Browser since Android 2 * PlayBook OS 1 and upwards FastClick doesn't attach any listeners on desktop browsers as it is not needed. Those that have been tested are: * Safari * Chrome * Internet Explorer * Firefox * Opera
36,376,184
While I have many years experience programming (in numerous languages), my background is not Javascript. Added to that is the fact that the Javascript of today is not the Javascript I first played with many years ago. It's much more sophisticated and powerful. That said, I'm struggling to understand some function payload dynamics. Function calls where the function actually returns something are intuitive, but Javascript seems to do something with functions that I can't get my head around. I could just copy/paste code, or I could try to work out how to reuse this pattern in my own code. For example, the following Mongoose call does a find of all records in the User model, and somehow the result of the call ends up in the second argument of the passed function (by reference?). ``` User.find({}, function(err, users) { // Get all the users if (err) throw err; console.log(users); // Show the JSON Object }); ``` Here's another example using a simple forEach on an array. Somehow, the forEach populates the 'user' argument. ``` users.forEach(function(user) { console.log(user.username, ': Admin = ', (user.admin ? 'Yes' : 'No')); }); ``` Can anyone explain this, and/or point me to a good guide on how/why this works? I've seen the same pattern across Node.js and it's a bit of a stumbling block. Have I missed something obvious or is this simply a peculiarity around functional programming? Jon
2016/04/02
[ "https://Stackoverflow.com/questions/36376184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3881622/" ]
This is called [Continuation Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style). It is sometimes used to encapsulate asynchronous behaviours, like the Mongoose example you provided, but other times it can be used in synchronous ways, like the `.forEach` example. To see how this works, it's easy if we make up our own forEach. ``` function forEach(xs, f) for (var i=0, len=xs.length; i<len; i++) { f(x[i]); } } forEach([1,2,3], function(x) { console.log(x); }) ``` So the way this works should be pretty easy to see: We can see that `xs` is set to our array `[1,2,3]` where we do a regular `for` loop inside the function. Then we see `f` is called once per element inside the loop. The real power here is that functions are [first-class members](https://en.wikipedia.org/wiki/First-class_citizen) in JavaScript and this enables the use of [higher-order functions](https://en.wikipedia.org/wiki/Higher-order_function). This means `.forEach` is considered a higher-order function because it accepts a function as an argument. As it turns out, `forEach` could be implemented a lot of different ways. here's another. ``` forEach(xs, f) { if (xs.length > 0) { f(xs[0]); forEach(xs.slice(1), f); } } ``` The idea here is you should get comfortable with sending functions around in JavaScript. You can even return functions as the result of applying another function. ``` function add(x) { return function(y) { return x + y; } } function map(xs, f) { function loop(ys, xs) { if (xs.length === 0) return ys; else return loop(ys.concat(f(xs[0])), xs.slice(1)); } return loop([], xs); } map([1,2,3], add(10)); //=> [11,12,13] ``` Before long, you'll be be knee-deep in the [functional paradigm](https://en.wikipedia.org/wiki/Functional_programming) and learning all sorts of other new things. Functions !
You need [javascript callbacks](http://dreamerslab.com/blog/en/javascript-callbacks/) The basic idea is that you pass one function as an argument to another function and then call it whenever you need it. ``` function basic( callback ){ console.log( 'do something here' ); var result = 'i am the result of `do something` to be past to the callback'; // if callback exist execute it callback && callback( result ); } ``` This is one of the core concepts in javascript. But I would recommend you also take a look at [Promises](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) for async operations like ajax http requests. Its not a part of current `ES5` specification but you can find many libraries and polyfils for this. ``` function get(url) { // Return a new promise. return new Promise(function(resolve, reject) { // Do the usual XHR stuff var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { // This is called even on 404 etc // so check the status if (req.status == 200) { // Resolve the promise with the response text resolve(req.response); } else { // Otherwise reject with the status text // which will hopefully be a meaningful error reject(Error(req.statusText)); } }; // Handle network errors req.onerror = function() { reject(Error("Network Error")); }; // Make the request req.send(); }); } // Use it! get('story.json').then(function(response) { console.log("Success!", response); }, function(error) { console.error("Failed!", error); }); ```
36,376,184
While I have many years experience programming (in numerous languages), my background is not Javascript. Added to that is the fact that the Javascript of today is not the Javascript I first played with many years ago. It's much more sophisticated and powerful. That said, I'm struggling to understand some function payload dynamics. Function calls where the function actually returns something are intuitive, but Javascript seems to do something with functions that I can't get my head around. I could just copy/paste code, or I could try to work out how to reuse this pattern in my own code. For example, the following Mongoose call does a find of all records in the User model, and somehow the result of the call ends up in the second argument of the passed function (by reference?). ``` User.find({}, function(err, users) { // Get all the users if (err) throw err; console.log(users); // Show the JSON Object }); ``` Here's another example using a simple forEach on an array. Somehow, the forEach populates the 'user' argument. ``` users.forEach(function(user) { console.log(user.username, ': Admin = ', (user.admin ? 'Yes' : 'No')); }); ``` Can anyone explain this, and/or point me to a good guide on how/why this works? I've seen the same pattern across Node.js and it's a bit of a stumbling block. Have I missed something obvious or is this simply a peculiarity around functional programming? Jon
2016/04/02
[ "https://Stackoverflow.com/questions/36376184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3881622/" ]
In Javascript, functions are also objects and can be stored in variables. A function that is passed to another function is commonly called a "callback" (this is also used in other languages but we won't go there). It may be helpful to look at the [polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill) for `Array.prototype.forEach`, especially the line that triggers the callback. Since, Javascript functions are also objects, they have their own methods, specifically [call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) and [apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), which trigger the function and even set the `this` value for that function. Callback example (it's silly I know... Here's the [fiddle](https://jsfiddle.net/n2k6voej/)): ``` function callIf(val, callbackFn) { // "arguments" is special in javascript, and it's not an array (although it does have an index selector). // I can call Array's slice method passing "arguments" as the "this" of the function var args = Array.prototype.slice.call(arguments, 2); if(val) { callbackFn.apply(this, args); } } var values = [ "Hop", "on", "Pop", "Sam", "I", "Am" ]; values.forEach(function(val) { // note: referencing inner "log" function instead of "console.log" because "console.log" require's the "this" to be "console". callIf(val.length < 3, log, val + " is a small word."); function log(val) { console.log(val); } }); ``` Side note: If you're coming from a static type language background, and are encountering Javascript as a dynamically typed language for the first time, my advice to you is: don't worry and embrace the flexibility that Javascript brings, but still maintain consistency and good programming discipline. Emphasize simplicity and readability. Have fun :)
You need [javascript callbacks](http://dreamerslab.com/blog/en/javascript-callbacks/) The basic idea is that you pass one function as an argument to another function and then call it whenever you need it. ``` function basic( callback ){ console.log( 'do something here' ); var result = 'i am the result of `do something` to be past to the callback'; // if callback exist execute it callback && callback( result ); } ``` This is one of the core concepts in javascript. But I would recommend you also take a look at [Promises](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) for async operations like ajax http requests. Its not a part of current `ES5` specification but you can find many libraries and polyfils for this. ``` function get(url) { // Return a new promise. return new Promise(function(resolve, reject) { // Do the usual XHR stuff var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { // This is called even on 404 etc // so check the status if (req.status == 200) { // Resolve the promise with the response text resolve(req.response); } else { // Otherwise reject with the status text // which will hopefully be a meaningful error reject(Error(req.statusText)); } }; // Handle network errors req.onerror = function() { reject(Error("Network Error")); }; // Make the request req.send(); }); } // Use it! get('story.json').then(function(response) { console.log("Success!", response); }, function(error) { console.error("Failed!", error); }); ```
36,376,184
While I have many years experience programming (in numerous languages), my background is not Javascript. Added to that is the fact that the Javascript of today is not the Javascript I first played with many years ago. It's much more sophisticated and powerful. That said, I'm struggling to understand some function payload dynamics. Function calls where the function actually returns something are intuitive, but Javascript seems to do something with functions that I can't get my head around. I could just copy/paste code, or I could try to work out how to reuse this pattern in my own code. For example, the following Mongoose call does a find of all records in the User model, and somehow the result of the call ends up in the second argument of the passed function (by reference?). ``` User.find({}, function(err, users) { // Get all the users if (err) throw err; console.log(users); // Show the JSON Object }); ``` Here's another example using a simple forEach on an array. Somehow, the forEach populates the 'user' argument. ``` users.forEach(function(user) { console.log(user.username, ': Admin = ', (user.admin ? 'Yes' : 'No')); }); ``` Can anyone explain this, and/or point me to a good guide on how/why this works? I've seen the same pattern across Node.js and it's a bit of a stumbling block. Have I missed something obvious or is this simply a peculiarity around functional programming? Jon
2016/04/02
[ "https://Stackoverflow.com/questions/36376184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3881622/" ]
This is called [Continuation Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style). It is sometimes used to encapsulate asynchronous behaviours, like the Mongoose example you provided, but other times it can be used in synchronous ways, like the `.forEach` example. To see how this works, it's easy if we make up our own forEach. ``` function forEach(xs, f) for (var i=0, len=xs.length; i<len; i++) { f(x[i]); } } forEach([1,2,3], function(x) { console.log(x); }) ``` So the way this works should be pretty easy to see: We can see that `xs` is set to our array `[1,2,3]` where we do a regular `for` loop inside the function. Then we see `f` is called once per element inside the loop. The real power here is that functions are [first-class members](https://en.wikipedia.org/wiki/First-class_citizen) in JavaScript and this enables the use of [higher-order functions](https://en.wikipedia.org/wiki/Higher-order_function). This means `.forEach` is considered a higher-order function because it accepts a function as an argument. As it turns out, `forEach` could be implemented a lot of different ways. here's another. ``` forEach(xs, f) { if (xs.length > 0) { f(xs[0]); forEach(xs.slice(1), f); } } ``` The idea here is you should get comfortable with sending functions around in JavaScript. You can even return functions as the result of applying another function. ``` function add(x) { return function(y) { return x + y; } } function map(xs, f) { function loop(ys, xs) { if (xs.length === 0) return ys; else return loop(ys.concat(f(xs[0])), xs.slice(1)); } return loop([], xs); } map([1,2,3], add(10)); //=> [11,12,13] ``` Before long, you'll be be knee-deep in the [functional paradigm](https://en.wikipedia.org/wiki/Functional_programming) and learning all sorts of other new things. Functions !
Those callbacks look similar but they serves completely different purposes. In the first example, the callback is used for retrieving the result because `User.find` is an asynchronous function. Async nature is also the reason behind the Nodejs convention of callback arguments order. First arguments of callbacks are always for errors. In the second example, the primary reason for using callback is to create a local scope, which is quite useful when you want to execute some asynchronous operations within the loop. For example: ``` users.forEach(function(user) { Model.find({},function(er,rows){ if(er){ return handle(er); } OtherModel.find({userid: user.id},function(er,result){ if(er){ return handle(er); } console.log(result); }); }); }); ``` The above example migth not work with the C-style loop since variables defined with `var` will already be overwrited by the last item of the array when `OtherModle.find` is executed.
36,376,184
While I have many years experience programming (in numerous languages), my background is not Javascript. Added to that is the fact that the Javascript of today is not the Javascript I first played with many years ago. It's much more sophisticated and powerful. That said, I'm struggling to understand some function payload dynamics. Function calls where the function actually returns something are intuitive, but Javascript seems to do something with functions that I can't get my head around. I could just copy/paste code, or I could try to work out how to reuse this pattern in my own code. For example, the following Mongoose call does a find of all records in the User model, and somehow the result of the call ends up in the second argument of the passed function (by reference?). ``` User.find({}, function(err, users) { // Get all the users if (err) throw err; console.log(users); // Show the JSON Object }); ``` Here's another example using a simple forEach on an array. Somehow, the forEach populates the 'user' argument. ``` users.forEach(function(user) { console.log(user.username, ': Admin = ', (user.admin ? 'Yes' : 'No')); }); ``` Can anyone explain this, and/or point me to a good guide on how/why this works? I've seen the same pattern across Node.js and it's a bit of a stumbling block. Have I missed something obvious or is this simply a peculiarity around functional programming? Jon
2016/04/02
[ "https://Stackoverflow.com/questions/36376184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3881622/" ]
In Javascript, functions are also objects and can be stored in variables. A function that is passed to another function is commonly called a "callback" (this is also used in other languages but we won't go there). It may be helpful to look at the [polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill) for `Array.prototype.forEach`, especially the line that triggers the callback. Since, Javascript functions are also objects, they have their own methods, specifically [call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) and [apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), which trigger the function and even set the `this` value for that function. Callback example (it's silly I know... Here's the [fiddle](https://jsfiddle.net/n2k6voej/)): ``` function callIf(val, callbackFn) { // "arguments" is special in javascript, and it's not an array (although it does have an index selector). // I can call Array's slice method passing "arguments" as the "this" of the function var args = Array.prototype.slice.call(arguments, 2); if(val) { callbackFn.apply(this, args); } } var values = [ "Hop", "on", "Pop", "Sam", "I", "Am" ]; values.forEach(function(val) { // note: referencing inner "log" function instead of "console.log" because "console.log" require's the "this" to be "console". callIf(val.length < 3, log, val + " is a small word."); function log(val) { console.log(val); } }); ``` Side note: If you're coming from a static type language background, and are encountering Javascript as a dynamically typed language for the first time, my advice to you is: don't worry and embrace the flexibility that Javascript brings, but still maintain consistency and good programming discipline. Emphasize simplicity and readability. Have fun :)
Those callbacks look similar but they serves completely different purposes. In the first example, the callback is used for retrieving the result because `User.find` is an asynchronous function. Async nature is also the reason behind the Nodejs convention of callback arguments order. First arguments of callbacks are always for errors. In the second example, the primary reason for using callback is to create a local scope, which is quite useful when you want to execute some asynchronous operations within the loop. For example: ``` users.forEach(function(user) { Model.find({},function(er,rows){ if(er){ return handle(er); } OtherModel.find({userid: user.id},function(er,result){ if(er){ return handle(er); } console.log(result); }); }); }); ``` The above example migth not work with the C-style loop since variables defined with `var` will already be overwrited by the last item of the array when `OtherModle.find` is executed.
45,416,949
``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, s, d, p).ToList(); } ``` //repository ``` public List<PostJobListModel> FromSql(string sql, params object[] objects) { return _context.PostJobListModel.FromSql(sql,objects).ToList(); } ``` This code gives "SQLException Must declar scalar variable “@variableName” " How i do create security command string ? Edit Answer `return _repositoryCustom.FromSql(command, parameterS , parameterD , parameterP ).ToList();`
2017/07/31
[ "https://Stackoverflow.com/questions/45416949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5230705/" ]
You don't set parameters by doing a SqlCommand, you need to pass the parameters in to the `FromSql` statement. From [the documention](https://learn.microsoft.com/en-us/ef/core/querying/raw-sql#passing-parameters) > > You can also construct a DbParameter and supply it as a parameter > value. This allows you to use named parameters in the SQL query > string+ > > > > ``` > var user = new SqlParameter("user", "johndoe"); > > var blogs = context.Blogs > .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser @user", user) > .ToList(); > > ``` > > So for your code you would do ``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, parameterS, parameterD, parameterP).ToList(); } ``` You should also make `id` a parameter too.
In .Net Core 2.0+ , below code worked for me. No need to pass through SQLParameter class. ``` public List<XXSearchResult> SearchXXArticles(string searchTerm,bool published=true,bool isXX=true) { var listXXArticles = _dbContext.XXSearchResults.FromSql($"SELECT * FROM [dbo].[udf_textContentSearch] ({searchTerm}, {published}, {isXX})").ToList(); return listXXArticles; } ``` // XXSearchResult declared in DbContext class as: public DbQuery XXSearchResults { get; set; } // udf\_textContentSearch is my legacy function in SQL Server database. SELECT \* FROM [dbo].[udf\_textContentSearch]
45,416,949
``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, s, d, p).ToList(); } ``` //repository ``` public List<PostJobListModel> FromSql(string sql, params object[] objects) { return _context.PostJobListModel.FromSql(sql,objects).ToList(); } ``` This code gives "SQLException Must declar scalar variable “@variableName” " How i do create security command string ? Edit Answer `return _repositoryCustom.FromSql(command, parameterS , parameterD , parameterP ).ToList();`
2017/07/31
[ "https://Stackoverflow.com/questions/45416949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5230705/" ]
You don't set parameters by doing a SqlCommand, you need to pass the parameters in to the `FromSql` statement. From [the documention](https://learn.microsoft.com/en-us/ef/core/querying/raw-sql#passing-parameters) > > You can also construct a DbParameter and supply it as a parameter > value. This allows you to use named parameters in the SQL query > string+ > > > > ``` > var user = new SqlParameter("user", "johndoe"); > > var blogs = context.Blogs > .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser @user", user) > .ToList(); > > ``` > > So for your code you would do ``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, parameterS, parameterD, parameterP).ToList(); } ``` You should also make `id` a parameter too.
While I am calling on SQL stored proc via EF Core, I like to build an array of SqlParameter to help me mash the SQL with params needed in the FromSql call, like this: ``` using (var scope = _services.CreateScope()) { var parameters = new [] { new SqlParameter("param1", System.Data.SqlDbType.VarChar, 10) { Value = someInboundMethodParam }, new SqlParameter("param2", System.Data.SqlDbType.VarChar, 50) { Value = Environment.UserName }, // etc.. }; var sql = new System.Text.StringBuilder("exec YourStoreProc"); sql.Append(string.Join(separator: ",", values: parameters.Select(p => $" @{ p.ParameterName }"))); var ctx = scope.ServiceProvider.GetRequiredService<YourContext>(); return await ctx .Query<SomeView>() .AsNoTracking() .FromSql(sql.ToString(), parameters.ToArray<object>()) .FirstOrDefaultAsync(cancellationToken); } ``` Over some iterations, I built up the following to help me compose the SQL: ``` public static string GetStoredProcSql(string name, SqlParameter[] parameters) { var stringOfParameters = string.Join( separator: ",", values: parameters.Select(GetStringOfParameterNameValuePairs) ); return $"exec [{name}] {stringOfParameters};"; } public static string GetStringOfParameterNameValuePairs(SqlParameter parameter) { var name = parameter.ParameterName; var value = ShouldSqlDbTypeValueRequireQuotes(parameter) ? $"\'{parameter.Value}\'" : parameter.Value; return $" @{name}={value}"; } public static bool ShouldSqlDbTypeValueRequireQuotes(SqlParameter parameter) { return new Enum[] { // SqlDbTypes that require their values be wrapped in single quotes: SqlDbType.VarChar, SqlDbType.NVarChar }.Contains(parameter.SqlDbType); } ``` And to use: ``` public async Task<List<JobView>> GetJobList( CancellationToken cancellationToken, int pageStart = 1, int pageSize = 10 ) { using (var scope = _services.CreateScope()) { var logger = scope.ServiceProvider.GetRequiredService<ILogger<ISomeService>>(); logger.LogInformation($"Getting list of share creation jobs.."); var ctxJob = scope.ServiceProvider.GetRequiredService<JobContext>(); var sql = SqlDataHelper.GetStoredProcSql( // use here! "GetJobList", new[] { new SqlParameter("pageStart", System.Data.SqlDbType.Int) { Value = pageStart }, new SqlParameter("pageSize", System.Data.SqlDbType.Int) { Value = pageSize }, //new SqlParameter("filterFieldValuePairs", System.Data.SqlDbType.VarChar) { Value = filter }, new SqlParameter("itemType", System.Data.SqlDbType.VarChar, 10) { Value = "Share" }, }); return await ctxJob .Query<JobView>() .AsNoTracking() .FromSql(sql) .ToListAsync(cancellationToken); } } ```
45,416,949
``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, s, d, p).ToList(); } ``` //repository ``` public List<PostJobListModel> FromSql(string sql, params object[] objects) { return _context.PostJobListModel.FromSql(sql,objects).ToList(); } ``` This code gives "SQLException Must declar scalar variable “@variableName” " How i do create security command string ? Edit Answer `return _repositoryCustom.FromSql(command, parameterS , parameterD , parameterP ).ToList();`
2017/07/31
[ "https://Stackoverflow.com/questions/45416949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5230705/" ]
You don't set parameters by doing a SqlCommand, you need to pass the parameters in to the `FromSql` statement. From [the documention](https://learn.microsoft.com/en-us/ef/core/querying/raw-sql#passing-parameters) > > You can also construct a DbParameter and supply it as a parameter > value. This allows you to use named parameters in the SQL query > string+ > > > > ``` > var user = new SqlParameter("user", "johndoe"); > > var blogs = context.Blogs > .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser @user", user) > .ToList(); > > ``` > > So for your code you would do ``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, parameterS, parameterD, parameterP).ToList(); } ``` You should also make `id` a parameter too.
ef core supports interpolated queries. using FromSqlInterpolated ``` var productName= "my favourite product"; _dbContext.Products.FromSqlInterpolated<Product>($ "SELECT * FROM Album WHERE Nams ={productName}"); ```
45,416,949
``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, s, d, p).ToList(); } ``` //repository ``` public List<PostJobListModel> FromSql(string sql, params object[] objects) { return _context.PostJobListModel.FromSql(sql,objects).ToList(); } ``` This code gives "SQLException Must declar scalar variable “@variableName” " How i do create security command string ? Edit Answer `return _repositoryCustom.FromSql(command, parameterS , parameterD , parameterP ).ToList();`
2017/07/31
[ "https://Stackoverflow.com/questions/45416949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5230705/" ]
While I am calling on SQL stored proc via EF Core, I like to build an array of SqlParameter to help me mash the SQL with params needed in the FromSql call, like this: ``` using (var scope = _services.CreateScope()) { var parameters = new [] { new SqlParameter("param1", System.Data.SqlDbType.VarChar, 10) { Value = someInboundMethodParam }, new SqlParameter("param2", System.Data.SqlDbType.VarChar, 50) { Value = Environment.UserName }, // etc.. }; var sql = new System.Text.StringBuilder("exec YourStoreProc"); sql.Append(string.Join(separator: ",", values: parameters.Select(p => $" @{ p.ParameterName }"))); var ctx = scope.ServiceProvider.GetRequiredService<YourContext>(); return await ctx .Query<SomeView>() .AsNoTracking() .FromSql(sql.ToString(), parameters.ToArray<object>()) .FirstOrDefaultAsync(cancellationToken); } ``` Over some iterations, I built up the following to help me compose the SQL: ``` public static string GetStoredProcSql(string name, SqlParameter[] parameters) { var stringOfParameters = string.Join( separator: ",", values: parameters.Select(GetStringOfParameterNameValuePairs) ); return $"exec [{name}] {stringOfParameters};"; } public static string GetStringOfParameterNameValuePairs(SqlParameter parameter) { var name = parameter.ParameterName; var value = ShouldSqlDbTypeValueRequireQuotes(parameter) ? $"\'{parameter.Value}\'" : parameter.Value; return $" @{name}={value}"; } public static bool ShouldSqlDbTypeValueRequireQuotes(SqlParameter parameter) { return new Enum[] { // SqlDbTypes that require their values be wrapped in single quotes: SqlDbType.VarChar, SqlDbType.NVarChar }.Contains(parameter.SqlDbType); } ``` And to use: ``` public async Task<List<JobView>> GetJobList( CancellationToken cancellationToken, int pageStart = 1, int pageSize = 10 ) { using (var scope = _services.CreateScope()) { var logger = scope.ServiceProvider.GetRequiredService<ILogger<ISomeService>>(); logger.LogInformation($"Getting list of share creation jobs.."); var ctxJob = scope.ServiceProvider.GetRequiredService<JobContext>(); var sql = SqlDataHelper.GetStoredProcSql( // use here! "GetJobList", new[] { new SqlParameter("pageStart", System.Data.SqlDbType.Int) { Value = pageStart }, new SqlParameter("pageSize", System.Data.SqlDbType.Int) { Value = pageSize }, //new SqlParameter("filterFieldValuePairs", System.Data.SqlDbType.VarChar) { Value = filter }, new SqlParameter("itemType", System.Data.SqlDbType.VarChar, 10) { Value = "Share" }, }); return await ctxJob .Query<JobView>() .AsNoTracking() .FromSql(sql) .ToListAsync(cancellationToken); } } ```
In .Net Core 2.0+ , below code worked for me. No need to pass through SQLParameter class. ``` public List<XXSearchResult> SearchXXArticles(string searchTerm,bool published=true,bool isXX=true) { var listXXArticles = _dbContext.XXSearchResults.FromSql($"SELECT * FROM [dbo].[udf_textContentSearch] ({searchTerm}, {published}, {isXX})").ToList(); return listXXArticles; } ``` // XXSearchResult declared in DbContext class as: public DbQuery XXSearchResults { get; set; } // udf\_textContentSearch is my legacy function in SQL Server database. SELECT \* FROM [dbo].[udf\_textContentSearch]
45,416,949
``` public List<PostJobListModel> GetPostsByCompanyId(int id, int s, int d, int p) { string command = @"select Id,Title,Cities = STUFF( (SELECT ',' + City.Name FROM City where City.Id in (select Id from LocaitonJobRelationship as ljr where ljr.JobId = PostJob.Id) FOR XML PATH ('')), 1, 1, ''), Features = STUFF( (SELECT ',' + Feature.Name FROM Feature where Feature.Id in (select FeatureId from FeatureJobRelationship as fjr where fjr.JobId = PostJob.Id and (fjr.CategoryId in (@s,@d,@p) ) )FOR XML PATH('')), 1, 1, '')from PostJob where CompanyId = " + id + ""; SqlParameter parameterS = new SqlParameter("@s", s); SqlParameter parameterD = new SqlParameter("@d", d); SqlParameter parameterP = new SqlParameter("@p", p); return _repositoryCustom.FromSql(command, s, d, p).ToList(); } ``` //repository ``` public List<PostJobListModel> FromSql(string sql, params object[] objects) { return _context.PostJobListModel.FromSql(sql,objects).ToList(); } ``` This code gives "SQLException Must declar scalar variable “@variableName” " How i do create security command string ? Edit Answer `return _repositoryCustom.FromSql(command, parameterS , parameterD , parameterP ).ToList();`
2017/07/31
[ "https://Stackoverflow.com/questions/45416949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5230705/" ]
While I am calling on SQL stored proc via EF Core, I like to build an array of SqlParameter to help me mash the SQL with params needed in the FromSql call, like this: ``` using (var scope = _services.CreateScope()) { var parameters = new [] { new SqlParameter("param1", System.Data.SqlDbType.VarChar, 10) { Value = someInboundMethodParam }, new SqlParameter("param2", System.Data.SqlDbType.VarChar, 50) { Value = Environment.UserName }, // etc.. }; var sql = new System.Text.StringBuilder("exec YourStoreProc"); sql.Append(string.Join(separator: ",", values: parameters.Select(p => $" @{ p.ParameterName }"))); var ctx = scope.ServiceProvider.GetRequiredService<YourContext>(); return await ctx .Query<SomeView>() .AsNoTracking() .FromSql(sql.ToString(), parameters.ToArray<object>()) .FirstOrDefaultAsync(cancellationToken); } ``` Over some iterations, I built up the following to help me compose the SQL: ``` public static string GetStoredProcSql(string name, SqlParameter[] parameters) { var stringOfParameters = string.Join( separator: ",", values: parameters.Select(GetStringOfParameterNameValuePairs) ); return $"exec [{name}] {stringOfParameters};"; } public static string GetStringOfParameterNameValuePairs(SqlParameter parameter) { var name = parameter.ParameterName; var value = ShouldSqlDbTypeValueRequireQuotes(parameter) ? $"\'{parameter.Value}\'" : parameter.Value; return $" @{name}={value}"; } public static bool ShouldSqlDbTypeValueRequireQuotes(SqlParameter parameter) { return new Enum[] { // SqlDbTypes that require their values be wrapped in single quotes: SqlDbType.VarChar, SqlDbType.NVarChar }.Contains(parameter.SqlDbType); } ``` And to use: ``` public async Task<List<JobView>> GetJobList( CancellationToken cancellationToken, int pageStart = 1, int pageSize = 10 ) { using (var scope = _services.CreateScope()) { var logger = scope.ServiceProvider.GetRequiredService<ILogger<ISomeService>>(); logger.LogInformation($"Getting list of share creation jobs.."); var ctxJob = scope.ServiceProvider.GetRequiredService<JobContext>(); var sql = SqlDataHelper.GetStoredProcSql( // use here! "GetJobList", new[] { new SqlParameter("pageStart", System.Data.SqlDbType.Int) { Value = pageStart }, new SqlParameter("pageSize", System.Data.SqlDbType.Int) { Value = pageSize }, //new SqlParameter("filterFieldValuePairs", System.Data.SqlDbType.VarChar) { Value = filter }, new SqlParameter("itemType", System.Data.SqlDbType.VarChar, 10) { Value = "Share" }, }); return await ctxJob .Query<JobView>() .AsNoTracking() .FromSql(sql) .ToListAsync(cancellationToken); } } ```
ef core supports interpolated queries. using FromSqlInterpolated ``` var productName= "my favourite product"; _dbContext.Products.FromSqlInterpolated<Product>($ "SELECT * FROM Album WHERE Nams ={productName}"); ```
51,193,314
I've an `ASP.NET MVC` application, `C#`, and some numbers into my `Model` in `decimal` type, which treat the fractional part as comma (i.e. 12,5). I serialize them and send to the client using `JSON`, which correctly convert the comma to point: ``` var result = Json(new { Value = myModel.myValue }); // become Value = 12.5 ``` Than I process the data client side, with some math function, getting the number value always with point (i.e. 12.5 \* 3 = 37.5). But, when I need to post back to the server the processed value, if I keep the point and I store the value into my `Model` (which is `decimal`, as said), it truncate the values after the point. Do I really need to do `result.replace('.', ',')` before sending back data client side? Damn not so good. Best practices? The paradox is that for mvc's jquery validator (being `decimal` required) I need to print the value into the input box with comma. The round-trip is crazy...
2018/07/05
[ "https://Stackoverflow.com/questions/51193314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365251/" ]
Probably not, use the framework built-in version where possible like so: ``` <Reference Include="System.Net.Http" /> ``` If something else you depend on (eg: another NuGet package) requires the NuGet version then it will get pulled in automatically, and the above reference will use whichever is available. As said by [the .NET team](https://github.com/dotnet/corefx/issues/29622#issuecomment-388199236): > > In most cases, we don't advise people use the separate System.Net.Http NuGet package anymore. > > > The `System.Net.Http` NuGet package was introduced to provide fast-track/OOB updates to the framework built-in version, particularly performance improvements. Whereas these improvements would usually be made in a new .NET Framework version, the idea here was that developers could use the NuGet package to get the newer benefits without retargeting to a newer framework. It turns out that for various reasons this is an incredibly complicated undertaking, particularly since `System.Net.Http` is used by other parts of the .NET Framework itself. This caused problems when integrating into downstream applications and real production workloads. Going forward, the .NET team has decided not to ship any more OOB packages like this, although they still support and update the existing ones. Further reading: * [Broken System.Net.Http 4.1.1-4.3.0 post-mortem](https://github.com/dotnet/corefx/issues/17522#issuecomment-338418610)
In general, you can replace the framework library with one from NuGet. I would recommend to do it if you have a specific reason to do it. For example, if you need a bug fix, a new API or leverage performance improvements. Specifically, with System.Net.Http it depends on your scenario. If you are making 1000 http calls a minute, use the newest from the NuGet. If you are making 2 calls an hour and you are not facing any issue, stick with the framework version. Between these two numbers, it depends.
45,752,506
I have two components (List and Detail): List.js: ``` export default class List extends React.Component { render() { const {navigate} = this.props.navigation; return ( <View style={styles.container}> <Text style={styles.headerText}>List of Contents</Text> <Button onPress={()=> navigate('Detail')} title="Go to details"/> </View> ) } } ``` Detail.js: ``` export default class Detail extends React.Component { render() { return ( <View> <Text style={styles.headerText}>Details of the content</Text> </View> ) } } ``` I would like to have two screens (NowList and SoonList) which are basically the same type of list, so I am using the same List component for both the screen. And from each of these screens I want to navigate to the Details of the item, also which in this case has the same type of layout so I am using Detail component for both the list items. Finally, when the App starts I want the NowList screen to show. And using the drawer I would like to navigate to SoonList screen. I am not sure how to configure this route. But, this is how I have configured the routes for now: ``` const NowStack = StackNavigator({ NowList: { screen: List, navigationOptions: { title: 'Now', } }, Detail: { screen: Detail, navigationOptions: { title: 'Detail', } } }); const SoonStack = StackNavigator({ SoonList: { screen: List, navigationOptions: { title: 'Soon', } } }); export const Drawer = DrawerNavigator({ Now: { screen: NowStack, }, Soon: { screen: SoonStack, } }); ``` When I navigate from NowList route to Detail route. There's a back button in the Detail route which on press navigates back to the NowList. However, when I go to Soon route, and navigate to Detail route, I go to Detail screen. But, when I press the back button on Detail navigation header, instead of navigating back to the SoonList screen, I am navigated to the NowList screen. I think I am missing something here, or my route layout is not how its suppose to be. Could you help me how to configure the routes so that I can use DrawerNavigator to navigate to different screens, and from those screens navigate to another screen and again back to the screen navigated from?
2017/08/18
[ "https://Stackoverflow.com/questions/45752506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2634889/" ]
You can make a stack navigator that contain your drawer navigator and detail, this way you can access both now list and soon list from drawer and able to navigate to detail screen from both list. ``` const App = StackNavigator({ Drawer: { screen: Drawer, }, Detail: { screen: Detail, navigationOptions: { title: 'Detail', }, }, }); const Drawer = DrawerNavigator({ NowList: { screen: List, }, SoonList: { screen: List, }, }); ```
Your route layout doesn't specify a `Detail` screen in the `SoonStack` navigator. When you navigate to `Detail`, react-navigation navigates to the only screen that is named that way. Since it is in the `NowStack`, going back returns to the first screen in the stack. To solve this, you can add another `Detail` screen to the `SoonStack` navigator, however you'd want to either name it differently, or navigate to each `Detail` screen using its key. In order to be able to navigate to the right `Detail` screen, you can add a parameter to each stack navigator. For example: ``` const SoonStack = StackNavigator({ SoonList: { screen: List, navigationOptions: { title: 'Soon', } }, SoonDetail: { screen: Detail, navigationOptions: { title: 'Detail', } } },{ initialRouteParams: { detailScreen: 'SoonDetail' } }); ``` You can then use the parameter to navigate to the correct screen. Also, it's possible to only use a single `StackNavigator` with the three distinct screens in it, and `reset` the stack to the correct screen when switching with the drawer. You can read more about `reset` [here](https://reactnavigation.org/docs/navigators/navigation-actions#Reset). **how to use reset** If you have a single stack navigator: ``` const TheStack = StackNavigator({ NowList: { screen: List, ... }, SoonList: { screen: List, ... }, Detail: {screen: Details, ... } }); ``` Then the drawer can reset the stack state to be whatever you want. For example, if the first screen was `NowList` and `SoonList` is clicked in the drawer, you can call: ``` const action = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({routeName: 'SoonList'}); ] }); this.props.navigation.dispatch(resetAction); ``` This would cause the stack to reset and have the `SoonList` as the first screen. If Details is opened, then it is the second in the stack, and back will always go back to the correct screen.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
As noted in other answers to the same topic, be sure to watch the [DjangoCon 2008 Schema Evolution Panel](http://www.youtube.com/watch?v=VSq8m00p1FM) on YouTube. Also, two new projects on the map: [Simplemigrations](http://github.com/ricardochimal/simplemigrations/tree/master) and [Migratory](http://www.bitbucket.org/DeadWisdom/migratory/).
So far in my company we have used the manual approach. What works best for you depends very much on your development style. We generally have not so many schema changes in production systems and somewhat formalized rollouts from development to production servers. Whenever we roll out (10-20 times a year) we do a fill diff of the current and the upcoming production branch reviewing all the code and noting what has to be changed on the production server. The required changes might be additional dependencies, changes to the settings file and changes to the database. This works very well for us. Having it all automated is a niche vision but to difficult for us - maybe we could manage migrations but we still would need to handle additional library, server, whatever dependencies.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
As noted in other answers to the same topic, be sure to watch the [DjangoCon 2008 Schema Evolution Panel](http://www.youtube.com/watch?v=VSq8m00p1FM) on YouTube. Also, two new projects on the map: [Simplemigrations](http://github.com/ricardochimal/simplemigrations/tree/master) and [Migratory](http://www.bitbucket.org/DeadWisdom/migratory/).
I've been using django-evolution. Caveats include: * Its automatic suggestions have been uniformly rotten; and * Its fingerprint function returns different values for the same database on different platforms. That said, I find the custom `schema_evolution.py` approach handy. To work around the fingerprint problem, I suggest code like: ``` BEFORE = 'fv1:-436177719' # first fingerprint BEFORE64 = 'fv1:-108578349625146375' # same, but on 64-bit Linux AFTER = 'fv1:-2132605944' AFTER64 = 'fv1:-3559032165562222486' fingerprints = [ BEFORE, AFTER, BEFORE64, AFTER64, ] CHANGESQL = """ /* put your SQL code to make the changes here */ """ evolutions = [ ((BEFORE, AFTER), CHANGESQL), ((BEFORE64, AFTER64), CHANGESQL) ] ``` If I had more fingerprints and changes, I'd re-factor it. Until then, making it cleaner would be stealing development time from something else. **EDIT:** Given that I'm manually constructing my changes anyway, I'll try [dmigrations](http://simonwillison.net/2008/Sep/3/dmigrations/) next time.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
Manually doing the SQL changes and dump/reload are both options, but you may also want to check out some of the schema-evolution packages for Django. The most mature options are [django-evolution](http://code.google.com/p/django-evolution/) and [South](http://south.aeracode.org/). **EDIT**: And hey, here comes [dmigrations](https://code.google.com/p/dmigrations/). **UPDATE**: Since this answer was originally written, [django-evolution](http://code.google.com/p/django-evolution/) and [dmigrations](https://code.google.com/p/dmigrations/) have both ceased active development and [South](http://south.aeracode.org/) has become the de-facto standard for schema migration in Django. Parts of South may even be integrated into Django within the next release or two. **UPDATE**: A schema-migrations framework based on South (and authored by Andrew Godwin, author of South) is included in Django 1.7+.
[django-command-extensions](http://code.google.com/p/django-command-extensions/) is a django library that gives some extra commands to manage.py. One of them is sqldiff, which should give you the sql needed to update to your new model. It is, however, listed as 'very experimental'.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
One good way to do this is via fixtures, particularly the `initial_data` fixtures. A fixture is a collection of files that contain the serialized contents of the database. So it's like having a backup of the database but as it's something Django is aware of it's easier to use and will have additional benefits when you come to do things like unit testing. You can create a fixture from the data currently in your DB using `django-admin.py dumpdata`. By default the data is in JSON format, but other options such as XML are available. A good place to store fixtures is a `fixtures` sub-directory of your application directories. You can load a fixure using `django-admin.py loaddata` but more significantly, if your fixture has a name like `initial_data.json` it will be automatically loaded when you do a `syncdb`, saving the trouble of importing it yourself. Another benefit is that when you run `manage.py test` to run your Unit Tests the temporary test database will also have the Initial Data Fixture loaded. Of course, this will work when when you're adding attributes to models and columns to the DB. If you drop a column from the Database you'll need to update your fixture to remove the data for that column which might not be straightforward. This works best when doing lots of little database changes during development. For updating production DBs a manually generated SQL script can often work best.
So far in my company we have used the manual approach. What works best for you depends very much on your development style. We generally have not so many schema changes in production systems and somewhat formalized rollouts from development to production servers. Whenever we roll out (10-20 times a year) we do a fill diff of the current and the upcoming production branch reviewing all the code and noting what has to be changed on the production server. The required changes might be additional dependencies, changes to the settings file and changes to the database. This works very well for us. Having it all automated is a niche vision but to difficult for us - maybe we could manage migrations but we still would need to handle additional library, server, whatever dependencies.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
As noted in other answers to the same topic, be sure to watch the [DjangoCon 2008 Schema Evolution Panel](http://www.youtube.com/watch?v=VSq8m00p1FM) on YouTube. Also, two new projects on the map: [Simplemigrations](http://github.com/ricardochimal/simplemigrations/tree/master) and [Migratory](http://www.bitbucket.org/DeadWisdom/migratory/).
Django 1.7 (currently in development) is [adding native support](https://docs.djangoproject.com/en/dev/releases/1.7/#what-s-new-in-django-1-7) for schema migration with `manage.py migrate` and `manage.py makemigrations` (`migrate` deprecates `syncdb`).
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
One good way to do this is via fixtures, particularly the `initial_data` fixtures. A fixture is a collection of files that contain the serialized contents of the database. So it's like having a backup of the database but as it's something Django is aware of it's easier to use and will have additional benefits when you come to do things like unit testing. You can create a fixture from the data currently in your DB using `django-admin.py dumpdata`. By default the data is in JSON format, but other options such as XML are available. A good place to store fixtures is a `fixtures` sub-directory of your application directories. You can load a fixure using `django-admin.py loaddata` but more significantly, if your fixture has a name like `initial_data.json` it will be automatically loaded when you do a `syncdb`, saving the trouble of importing it yourself. Another benefit is that when you run `manage.py test` to run your Unit Tests the temporary test database will also have the Initial Data Fixture loaded. Of course, this will work when when you're adding attributes to models and columns to the DB. If you drop a column from the Database you'll need to update your fixture to remove the data for that column which might not be straightforward. This works best when doing lots of little database changes during development. For updating production DBs a manually generated SQL script can often work best.
[django-command-extensions](http://code.google.com/p/django-command-extensions/) is a django library that gives some extra commands to manage.py. One of them is sqldiff, which should give you the sql needed to update to your new model. It is, however, listed as 'very experimental'.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
As noted in other answers to the same topic, be sure to watch the [DjangoCon 2008 Schema Evolution Panel](http://www.youtube.com/watch?v=VSq8m00p1FM) on YouTube. Also, two new projects on the map: [Simplemigrations](http://github.com/ricardochimal/simplemigrations/tree/master) and [Migratory](http://www.bitbucket.org/DeadWisdom/migratory/).
One good way to do this is via fixtures, particularly the `initial_data` fixtures. A fixture is a collection of files that contain the serialized contents of the database. So it's like having a backup of the database but as it's something Django is aware of it's easier to use and will have additional benefits when you come to do things like unit testing. You can create a fixture from the data currently in your DB using `django-admin.py dumpdata`. By default the data is in JSON format, but other options such as XML are available. A good place to store fixtures is a `fixtures` sub-directory of your application directories. You can load a fixure using `django-admin.py loaddata` but more significantly, if your fixture has a name like `initial_data.json` it will be automatically loaded when you do a `syncdb`, saving the trouble of importing it yourself. Another benefit is that when you run `manage.py test` to run your Unit Tests the temporary test database will also have the Initial Data Fixture loaded. Of course, this will work when when you're adding attributes to models and columns to the DB. If you drop a column from the Database you'll need to update your fixture to remove the data for that column which might not be straightforward. This works best when doing lots of little database changes during development. For updating production DBs a manually generated SQL script can often work best.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
As noted in other answers to the same topic, be sure to watch the [DjangoCon 2008 Schema Evolution Panel](http://www.youtube.com/watch?v=VSq8m00p1FM) on YouTube. Also, two new projects on the map: [Simplemigrations](http://github.com/ricardochimal/simplemigrations/tree/master) and [Migratory](http://www.bitbucket.org/DeadWisdom/migratory/).
[django-command-extensions](http://code.google.com/p/django-command-extensions/) is a django library that gives some extra commands to manage.py. One of them is sqldiff, which should give you the sql needed to update to your new model. It is, however, listed as 'very experimental'.
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
Manually doing the SQL changes and dump/reload are both options, but you may also want to check out some of the schema-evolution packages for Django. The most mature options are [django-evolution](http://code.google.com/p/django-evolution/) and [South](http://south.aeracode.org/). **EDIT**: And hey, here comes [dmigrations](https://code.google.com/p/dmigrations/). **UPDATE**: Since this answer was originally written, [django-evolution](http://code.google.com/p/django-evolution/) and [dmigrations](https://code.google.com/p/dmigrations/) have both ceased active development and [South](http://south.aeracode.org/) has become the de-facto standard for schema migration in Django. Parts of South may even be integrated into Django within the next release or two. **UPDATE**: A schema-migrations framework based on South (and authored by Andrew Godwin, author of South) is included in Django 1.7+.
Django 1.7 (currently in development) is [adding native support](https://docs.djangoproject.com/en/dev/releases/1.7/#what-s-new-in-django-1-7) for schema migration with `manage.py migrate` and `manage.py makemigrations` (`migrate` deprecates `syncdb`).
35,991
I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using `syncdb` to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework). I was already thinking this was too good to be true when I saw this in the [documentation](https://docs.djangoproject.com/en/dev/ref/django-admin/): > > Syncdb will not alter existing tables > > > syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. > > > If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes. > > > It seems that altering existing tables will have to be done "by hand". What I would like to know is the best way to do this. Two solutions come to mind: * As the documentation suggests, make the changes manually in the DB; * Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big) Any ideas?
2008/08/30
[ "https://Stackoverflow.com/questions/35991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
Manually doing the SQL changes and dump/reload are both options, but you may also want to check out some of the schema-evolution packages for Django. The most mature options are [django-evolution](http://code.google.com/p/django-evolution/) and [South](http://south.aeracode.org/). **EDIT**: And hey, here comes [dmigrations](https://code.google.com/p/dmigrations/). **UPDATE**: Since this answer was originally written, [django-evolution](http://code.google.com/p/django-evolution/) and [dmigrations](https://code.google.com/p/dmigrations/) have both ceased active development and [South](http://south.aeracode.org/) has become the de-facto standard for schema migration in Django. Parts of South may even be integrated into Django within the next release or two. **UPDATE**: A schema-migrations framework based on South (and authored by Andrew Godwin, author of South) is included in Django 1.7+.
As noted in other answers to the same topic, be sure to watch the [DjangoCon 2008 Schema Evolution Panel](http://www.youtube.com/watch?v=VSq8m00p1FM) on YouTube. Also, two new projects on the map: [Simplemigrations](http://github.com/ricardochimal/simplemigrations/tree/master) and [Migratory](http://www.bitbucket.org/DeadWisdom/migratory/).
31,769,122
In Haskell, lists of type `Ord a => [a]` have a lexicographical ordering. For example, ``` > compare [1, 2, 3] [2, 3, 4] LT > compare [1] [1, 2] LT ``` This is an immediate generalization of the lexicographical ordering most languages have on strings. In Java, for example, ``` "abc".compareTo("bcd") // -1 "a".compareTo("ab") // -1 ``` Is there any Java function in the standard library or other library that implements the lexicographical ordering of lists that Haskell has? I would expect it have a type signature along the lines of ``` <T extends Comparable<T>> int compare(List<T>, List<T>) ``` Implementing it myself wouldn't be difficult, but I'd rather not reinvent the wheel.
2015/08/02
[ "https://Stackoverflow.com/questions/31769122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3645205/" ]
If third-party libraries are fair game, then in [Guava](https://github.com/google/guava) this is just `Ordering.natural().lexicographical()`. There isn't anything for this built into basic Java, though.
There is no such method that I know of. `List` (and its concrete implementations, such as `ArrayList`) do not extend/implement the `Comarable` interface, meaning that they implement no ordering themselves. I think this is a correct language decision, because lists, in my opinion, indeed do not have a canonical ordering. You can implement you own comparator which compares lists, and pass this to objects which need to compare list (for example `Collections.sort(list, comparator)`). For example: ``` class LexicographicalListComparator<T extends Comparable<T>> implements Comparator<List<T>> { @Override public int compare(List<T> o1, List<T> o2) { Iterator<T> i1 = o1.iterator(); Iterator<T> i2 = o2.iterator(); int result; do { if (!i1.hasNext()) { if (!i2.hasNext()) return 0; else return -1; } if (!i2.hasNext()) { return 1; } result = i1.next().compareTo(i2.next()); } while (result == 0); return result; } } ```
31,769,122
In Haskell, lists of type `Ord a => [a]` have a lexicographical ordering. For example, ``` > compare [1, 2, 3] [2, 3, 4] LT > compare [1] [1, 2] LT ``` This is an immediate generalization of the lexicographical ordering most languages have on strings. In Java, for example, ``` "abc".compareTo("bcd") // -1 "a".compareTo("ab") // -1 ``` Is there any Java function in the standard library or other library that implements the lexicographical ordering of lists that Haskell has? I would expect it have a type signature along the lines of ``` <T extends Comparable<T>> int compare(List<T>, List<T>) ``` Implementing it myself wouldn't be difficult, but I'd rather not reinvent the wheel.
2015/08/02
[ "https://Stackoverflow.com/questions/31769122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3645205/" ]
There is no such method that I know of. `List` (and its concrete implementations, such as `ArrayList`) do not extend/implement the `Comarable` interface, meaning that they implement no ordering themselves. I think this is a correct language decision, because lists, in my opinion, indeed do not have a canonical ordering. You can implement you own comparator which compares lists, and pass this to objects which need to compare list (for example `Collections.sort(list, comparator)`). For example: ``` class LexicographicalListComparator<T extends Comparable<T>> implements Comparator<List<T>> { @Override public int compare(List<T> o1, List<T> o2) { Iterator<T> i1 = o1.iterator(); Iterator<T> i2 = o2.iterator(); int result; do { if (!i1.hasNext()) { if (!i2.hasNext()) return 0; else return -1; } if (!i2.hasNext()) { return 1; } result = i1.next().compareTo(i2.next()); } while (result == 0); return result; } } ```
Just as Hoopje said, `List` does not implement the `Comparable` interface. If you want to implement your own comparator to lexicographically compare strings (and after that you could order lists of strings), Java has the [Collator](https://docs.oracle.com/javase/8/docs/api/java/text/Collator.html) class: > > The Collator class performs locale-sensitive String comparison. > > > If that's not enough you could use [RuleBasedCollator](https://docs.oracle.com/javase/8/docs/api/java/text/RuleBasedCollator.html), it works as `Collator` but you can personalize it a lot more. Both of them implement the `Comparable` interface so may use `compare`. ``` import java.text.Collator; ... Collator c = Collator.getInstance(); c.compare(s1, s2); ``` If you want it to follow some locale-sensitive rules, you must do: ``` import java.util.Locale; ... Collator c = Collator.getInstance(new Locale("es", "MX")); c.compare(s1, s2); ``` Here is more info on [Locale](http://www.oracle.com/us/technologies/java/locale-140624.html).
31,769,122
In Haskell, lists of type `Ord a => [a]` have a lexicographical ordering. For example, ``` > compare [1, 2, 3] [2, 3, 4] LT > compare [1] [1, 2] LT ``` This is an immediate generalization of the lexicographical ordering most languages have on strings. In Java, for example, ``` "abc".compareTo("bcd") // -1 "a".compareTo("ab") // -1 ``` Is there any Java function in the standard library or other library that implements the lexicographical ordering of lists that Haskell has? I would expect it have a type signature along the lines of ``` <T extends Comparable<T>> int compare(List<T>, List<T>) ``` Implementing it myself wouldn't be difficult, but I'd rather not reinvent the wheel.
2015/08/02
[ "https://Stackoverflow.com/questions/31769122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3645205/" ]
If third-party libraries are fair game, then in [Guava](https://github.com/google/guava) this is just `Ordering.natural().lexicographical()`. There isn't anything for this built into basic Java, though.
Just as Hoopje said, `List` does not implement the `Comparable` interface. If you want to implement your own comparator to lexicographically compare strings (and after that you could order lists of strings), Java has the [Collator](https://docs.oracle.com/javase/8/docs/api/java/text/Collator.html) class: > > The Collator class performs locale-sensitive String comparison. > > > If that's not enough you could use [RuleBasedCollator](https://docs.oracle.com/javase/8/docs/api/java/text/RuleBasedCollator.html), it works as `Collator` but you can personalize it a lot more. Both of them implement the `Comparable` interface so may use `compare`. ``` import java.text.Collator; ... Collator c = Collator.getInstance(); c.compare(s1, s2); ``` If you want it to follow some locale-sensitive rules, you must do: ``` import java.util.Locale; ... Collator c = Collator.getInstance(new Locale("es", "MX")); c.compare(s1, s2); ``` Here is more info on [Locale](http://www.oracle.com/us/technologies/java/locale-140624.html).
25,912,662
I have a small C# console application that runs some code then checks for a specific executable to complete. The problem I had (I don't normally write console applications) is when I get to the code that checks for the termination of an executable, my Main() returns and the console application closes. The code which checks for the executable is running thru a Timer(). For the moment I've kept the Main alive by adding while(true) { } and that seems to be working except that it (obviously) eats up a ton of excess CPU time. Is there a better way to keep the Main() function from returning? ``` static Timer tmrCheck = new Timer(); static void Main(string[] args) { Initialize(); while (true) ; // If this line is removed, the application will close after // the last line of Initialize() is run. } static void Initialize() { tmrCheck.Elapsed += tmrCheck_Elapsed; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; // After this line, Initialize returns to Main() } static void tmrCheck_Elapsed(object sender, ElapsedEventArgs e) { // Get a list of processes // Check to see if process has exited // If so, run *this* code then exit console application. // If not, keep timer running. } ```
2014/09/18
[ "https://Stackoverflow.com/questions/25912662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3429758/" ]
If you just need to wait until the launched process exits. This could be written in your `Timer.Elapsed` event ``` Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { p[0].WaitForExit(); Console.WriteLine("Finish"); } else { // Do other things } ``` **EDIT** Looks that this could be tried. I am not sure about threading issues here so waiting for someone more expert that points to the weakness of this approach ``` static Timer tmrCheck = new Timer(); static bool waiting = false; static void Main(string[] args) { Initialize(); Console.WriteLine("Press enter to stop the processing...."); Console.ReadLine(); tmrCheck.Stop(); } static void Initialize() { tmrCheck.Elapsed += (s, e) => { Console.WriteLine("Timer event"); if(!waiting) { Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { waiting = true; Console.WriteLine("Waiting for exit"); p[0].WaitForExit(); Timer t = s as Timer; t.Stop(); Console.WriteLine("Press enter to end application"); } } else { // other processing activities } }; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; } ```
Try: Thread.Sleep(1); in your while loop. Even sleeping one millisecond should save you a lot of CPU cycles. Hope that helps
25,912,662
I have a small C# console application that runs some code then checks for a specific executable to complete. The problem I had (I don't normally write console applications) is when I get to the code that checks for the termination of an executable, my Main() returns and the console application closes. The code which checks for the executable is running thru a Timer(). For the moment I've kept the Main alive by adding while(true) { } and that seems to be working except that it (obviously) eats up a ton of excess CPU time. Is there a better way to keep the Main() function from returning? ``` static Timer tmrCheck = new Timer(); static void Main(string[] args) { Initialize(); while (true) ; // If this line is removed, the application will close after // the last line of Initialize() is run. } static void Initialize() { tmrCheck.Elapsed += tmrCheck_Elapsed; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; // After this line, Initialize returns to Main() } static void tmrCheck_Elapsed(object sender, ElapsedEventArgs e) { // Get a list of processes // Check to see if process has exited // If so, run *this* code then exit console application. // If not, keep timer running. } ```
2014/09/18
[ "https://Stackoverflow.com/questions/25912662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3429758/" ]
If you just need to wait until the launched process exits. This could be written in your `Timer.Elapsed` event ``` Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { p[0].WaitForExit(); Console.WriteLine("Finish"); } else { // Do other things } ``` **EDIT** Looks that this could be tried. I am not sure about threading issues here so waiting for someone more expert that points to the weakness of this approach ``` static Timer tmrCheck = new Timer(); static bool waiting = false; static void Main(string[] args) { Initialize(); Console.WriteLine("Press enter to stop the processing...."); Console.ReadLine(); tmrCheck.Stop(); } static void Initialize() { tmrCheck.Elapsed += (s, e) => { Console.WriteLine("Timer event"); if(!waiting) { Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { waiting = true; Console.WriteLine("Waiting for exit"); p[0].WaitForExit(); Timer t = s as Timer; t.Stop(); Console.WriteLine("Press enter to end application"); } } else { // other processing activities } }; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; } ```
Well you can use as others mentioned Thead.Sleep and rewrite your code like this: ``` static void Main(string[] args) { while (true) { // Get a list of processes // Check to see if process has exited // If so, run *this* code then exit console application. // If not, keep timer running. Thread.Sleep(10000); // Wait 10s and retry your previous actions } } ``` Another suggestion (i sometimes using for thread cancellation option) ``` static void Main(string[] args) { int timeout = 10; int timeoutCount = 10; while (true) { //Here you can check cancellation flag if(timeout == timeoutCount) { timeoutCount = 0; // Get a list of processes // Check to see if process has exited // If so, run *this* code then exit console application. // If not, keep timer running. } Thread.Sleep(1000); // Wait 1s and retry your previous actions timeoutCount++; } } ```
25,912,662
I have a small C# console application that runs some code then checks for a specific executable to complete. The problem I had (I don't normally write console applications) is when I get to the code that checks for the termination of an executable, my Main() returns and the console application closes. The code which checks for the executable is running thru a Timer(). For the moment I've kept the Main alive by adding while(true) { } and that seems to be working except that it (obviously) eats up a ton of excess CPU time. Is there a better way to keep the Main() function from returning? ``` static Timer tmrCheck = new Timer(); static void Main(string[] args) { Initialize(); while (true) ; // If this line is removed, the application will close after // the last line of Initialize() is run. } static void Initialize() { tmrCheck.Elapsed += tmrCheck_Elapsed; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; // After this line, Initialize returns to Main() } static void tmrCheck_Elapsed(object sender, ElapsedEventArgs e) { // Get a list of processes // Check to see if process has exited // If so, run *this* code then exit console application. // If not, keep timer running. } ```
2014/09/18
[ "https://Stackoverflow.com/questions/25912662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3429758/" ]
If you just need to wait until the launched process exits. This could be written in your `Timer.Elapsed` event ``` Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { p[0].WaitForExit(); Console.WriteLine("Finish"); } else { // Do other things } ``` **EDIT** Looks that this could be tried. I am not sure about threading issues here so waiting for someone more expert that points to the weakness of this approach ``` static Timer tmrCheck = new Timer(); static bool waiting = false; static void Main(string[] args) { Initialize(); Console.WriteLine("Press enter to stop the processing...."); Console.ReadLine(); tmrCheck.Stop(); } static void Initialize() { tmrCheck.Elapsed += (s, e) => { Console.WriteLine("Timer event"); if(!waiting) { Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { waiting = true; Console.WriteLine("Waiting for exit"); p[0].WaitForExit(); Timer t = s as Timer; t.Stop(); Console.WriteLine("Press enter to end application"); } } else { // other processing activities } }; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; } ```
You could try something like this: ``` static void Main(string[] args) { var procs = Process.GetProcessesByName("LINQPad").ToList(); if (procs.Any()) { procs.ForEach(p => p.EnableRaisingEvents = true); procs.ForEach(p => p.Exited += OnExited); procs.ForEach(p => p.WaitForExit()); } Console.WriteLine("All processes exited..."); Console.ReadKey(); } private static void OnExited(object sender, EventArgs eventArgs) { Console.WriteLine("Process Has Exited"); } ``` You didn't mention if you're monitoring multiple processes or not, but you could just remove the .ForEach statements and do the same logic for a single process, if not. Also, i'm not sure if Console.ReadKey() is what you had in mind for keeping the process from exiting... Or if you only need to keep it from exiting until the process(es) have closed.
25,912,662
I have a small C# console application that runs some code then checks for a specific executable to complete. The problem I had (I don't normally write console applications) is when I get to the code that checks for the termination of an executable, my Main() returns and the console application closes. The code which checks for the executable is running thru a Timer(). For the moment I've kept the Main alive by adding while(true) { } and that seems to be working except that it (obviously) eats up a ton of excess CPU time. Is there a better way to keep the Main() function from returning? ``` static Timer tmrCheck = new Timer(); static void Main(string[] args) { Initialize(); while (true) ; // If this line is removed, the application will close after // the last line of Initialize() is run. } static void Initialize() { tmrCheck.Elapsed += tmrCheck_Elapsed; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; // After this line, Initialize returns to Main() } static void tmrCheck_Elapsed(object sender, ElapsedEventArgs e) { // Get a list of processes // Check to see if process has exited // If so, run *this* code then exit console application. // If not, keep timer running. } ```
2014/09/18
[ "https://Stackoverflow.com/questions/25912662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3429758/" ]
If you just need to wait until the launched process exits. This could be written in your `Timer.Elapsed` event ``` Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { p[0].WaitForExit(); Console.WriteLine("Finish"); } else { // Do other things } ``` **EDIT** Looks that this could be tried. I am not sure about threading issues here so waiting for someone more expert that points to the weakness of this approach ``` static Timer tmrCheck = new Timer(); static bool waiting = false; static void Main(string[] args) { Initialize(); Console.WriteLine("Press enter to stop the processing...."); Console.ReadLine(); tmrCheck.Stop(); } static void Initialize() { tmrCheck.Elapsed += (s, e) => { Console.WriteLine("Timer event"); if(!waiting) { Process[] p = Process.GetProcessesByName("yourprocessname"); if(p.Length > 0) { waiting = true; Console.WriteLine("Waiting for exit"); p[0].WaitForExit(); Timer t = s as Timer; t.Stop(); Console.WriteLine("Press enter to end application"); } } else { // other processing activities } }; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; } ```
You don't say what version of the .Net framework you're using or if the application launches the process, but... If you're using 4.0 or higher and the app does launch the process, then you can use a Task ([System.Threading.Tasks](http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx "System.Threading.Tasks")) to launch the process and Task.Wait. ``` using System.Threading.Tasks; static Timer tmrCheck = new Timer(); Task doWork; static void Main(string[] args) { Initialize(); /// do more work if required doWork.Wait(); } static void Initialize() { tmrCheck.Elapsed += tmrCheck_Elapsed; tmrCheck.Interval = 10000; tmrCheck.Enabled = true; // After this line, Initialize returns to Main() // Initialize() seems the place to do start up, but this code could move to where ever the proocess is started. doWork = Task.Factory.StartNew(() => { startTheProcessHere(); } ); } ``` Pluralsight has a good course: [Introduction to Async and Parallel Programming in .NET 4](http://pluralsight.com/courses/intro-async-parallel-dotnet4)
1,850,790
I am working on a project that requires the parsing of "formatting tags." By using a tag like this: `<b>text</b>`, it modifies the way the text will look (that tag makes the text bold). You can have up to 4 identifiers in one tag (`b` for bold, `i` for italics, `u` for underline, and `s` for strikeout). For example: `<bi>some</b> text</i> here` would produce ***some*** text here. To parse these tags, I'm attempting to use a RegEx to capture any text before the first opening tag, and then capture any tags and their enclosed text after that. Right now, I have this: `<(?<open>[bius]{1,4})>(?<text>.+?)</(?<close>[bius]{1,4})>` That matches a single tag, its enclosed text, and a single corresponding closing tag. Right now, I iterate through every single character and attempt to match the position in the string I'm at to the end of the string, e.g. I attempt to match the whole string at `i = 0`, a substring from position 1 to the end at `i = 1`, etc. However, this approach is incredibly inefficient. It seems like it would be better to match the entire string in one RegEx instead of manually iterating through the string. My actual question is is it possible to match a string that does *not* match a group, such as a tag? I've Googled this without success, but perhaps I've not been using the right words.
2009/12/05
[ "https://Stackoverflow.com/questions/1850790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think trying to parse and validate the entire text in one regular expression is likely to give you problems. The text you are parsing is not a regular language, so regular expressions are not well designed for this purpose. Instead I would recommend that you first tokenize the input to single tags and text between the tags. You can use a simple regular expression to find single tags - this is a much simpler problem that regular expressions can handle quite well. Once you have tokenized it, you can iterate over the tokens with an ordinary loop and apply formatting to the text as appropriate.
Try prefixing your regex with `^(.*?)` (match any characters from the beginning of the string, non-greedy). Thus it will match anything at all that occurs at the start of the string, but it will match as little as it can while still having the rest of the regex match. Thus you'll grab all of the stuff that wasn't matched normally in that first capture group.
1,850,790
I am working on a project that requires the parsing of "formatting tags." By using a tag like this: `<b>text</b>`, it modifies the way the text will look (that tag makes the text bold). You can have up to 4 identifiers in one tag (`b` for bold, `i` for italics, `u` for underline, and `s` for strikeout). For example: `<bi>some</b> text</i> here` would produce ***some*** text here. To parse these tags, I'm attempting to use a RegEx to capture any text before the first opening tag, and then capture any tags and their enclosed text after that. Right now, I have this: `<(?<open>[bius]{1,4})>(?<text>.+?)</(?<close>[bius]{1,4})>` That matches a single tag, its enclosed text, and a single corresponding closing tag. Right now, I iterate through every single character and attempt to match the position in the string I'm at to the end of the string, e.g. I attempt to match the whole string at `i = 0`, a substring from position 1 to the end at `i = 1`, etc. However, this approach is incredibly inefficient. It seems like it would be better to match the entire string in one RegEx instead of manually iterating through the string. My actual question is is it possible to match a string that does *not* match a group, such as a tag? I've Googled this without success, but perhaps I've not been using the right words.
2009/12/05
[ "https://Stackoverflow.com/questions/1850790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think trying to parse and validate the entire text in one regular expression is likely to give you problems. The text you are parsing is not a regular language, so regular expressions are not well designed for this purpose. Instead I would recommend that you first tokenize the input to single tags and text between the tags. You can use a simple regular expression to find single tags - this is a much simpler problem that regular expressions can handle quite well. Once you have tokenized it, you can iterate over the tokens with an ordinary loop and apply formatting to the text as appropriate.
[Why don't you use an HTML parser for this](https://stackoverflow.com/questions/1736706/regex-to-get-value-within-tag/1736756#1736756)? > > **You should be using an [XML parser](http://forums.macrumors.com/showthread.php?t=244288), [not regexes](https://stackoverflow.com/questions/542455/regex-to-indent-an-xml-file/542708#542708). [XML is not a regular language](https://stackoverflow.com/questions/1357357/regexp-to-add-attribute-in-any-xml-tags/1357393#1357393), [hence not easely parseable](https://stackoverflow.com/questions/968919/when-not-to-use-regex-in-c-or-java-c-etc) by [a regular expression](https://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege). [Don't do it](https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not).** > > > > > > > [Never use regular expressions or basic string parsing to process XML](https://stackoverflow.com/questions/357814/when-is-it-best-to-use-regular-expressions-over-basic-string-spliting-substring/357847#357847). Every language in common usage right now has perfectly good XML support. XML is a deceptively complex standard and it's unlikely your code will be correct in the sense that it will properly parse all well-formed XML input, and even it if does, you're wasting your time because (as just mentioned) every language in common usage has XML support. It is unprofessional to use regular expressions to parse XML. > > > > > > > > >
49,105,288
I created a map on my website. User can add multiple markers. And on the other page I created a call to these markers. Here is a string: > > string > '[{"lat":"40.7181193798","lng":"-84.4847297668","label":"A"},{"lat":"40.9530752681","lng":"-83.9779055864","label":"A"}]' > > > How to make it display only the address. Like "USA,NY,gikalo street ..." And created a link to Google maps with this location. Thank you in advance
2018/03/05
[ "https://Stackoverflow.com/questions/49105288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9130446/" ]
``` var z='[{"lat":"40.7181193798","lng":"-84.4847297668","label":"A"},{"lat":"40.9530752681","lng":"-83.9779055864","label":"A"}]' var JSONArray=JSON.parse(z); var lat=JSONArray[0].lat;//For first obj var long=JSONArray[0].long;//For first obj var dataURL="http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&sensor=true"; ``` You can fetch your data by using this url Just you need to parse your JSON in response you wil get appropriate result.
You will need API key inorder to make the Google Map API request everytime.
36,815,199
I am using RubyMine 8.0.3, I have **3 folders and 2 `.rb`** files in `controller/api/v1` , **none out of 3 folders are visible** but **both `.rb` files are visible**. I reopened the the IDE but nothing happened. I also tried the solutions mentioned in the following link: [RubyMine Folder Tree doesn't refresh](https://stackoverflow.com/questions/2796739/rubymine-folder-tree-doesnt-refresh) Note: 1: When I open my project in sublime all folders are visible. 2: I have added .idea/ in my .gitignore file.
2016/04/23
[ "https://Stackoverflow.com/questions/36815199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908141/" ]
I couldn't find the source of the problem, but deleting the `.idea/` folder worked for me.
Perhaps you are using the [Rails view](https://www.jetbrains.com/help/ruby/2016.1/rails-view.html) in the Project tool window? This view can sometimes mask some files. If so, switch the tool back to the Project view. Also, check that you have not excluded the directories in the [Project structure settings](https://www.jetbrains.com/help/ruby/2016.1/project-structure.html#d558390e238).
36,815,199
I am using RubyMine 8.0.3, I have **3 folders and 2 `.rb`** files in `controller/api/v1` , **none out of 3 folders are visible** but **both `.rb` files are visible**. I reopened the the IDE but nothing happened. I also tried the solutions mentioned in the following link: [RubyMine Folder Tree doesn't refresh](https://stackoverflow.com/questions/2796739/rubymine-folder-tree-doesnt-refresh) Note: 1: When I open my project in sublime all folders are visible. 2: I have added .idea/ in my .gitignore file.
2016/04/23
[ "https://Stackoverflow.com/questions/36815199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908141/" ]
Perhaps you are using the [Rails view](https://www.jetbrains.com/help/ruby/2016.1/rails-view.html) in the Project tool window? This view can sometimes mask some files. If so, switch the tool back to the Project view. Also, check that you have not excluded the directories in the [Project structure settings](https://www.jetbrains.com/help/ruby/2016.1/project-structure.html#d558390e238).
In my case folders were empty that is why it was not visible, not sure why. As soon as I added(from terminal) some file to it. It started showing.
36,815,199
I am using RubyMine 8.0.3, I have **3 folders and 2 `.rb`** files in `controller/api/v1` , **none out of 3 folders are visible** but **both `.rb` files are visible**. I reopened the the IDE but nothing happened. I also tried the solutions mentioned in the following link: [RubyMine Folder Tree doesn't refresh](https://stackoverflow.com/questions/2796739/rubymine-folder-tree-doesnt-refresh) Note: 1: When I open my project in sublime all folders are visible. 2: I have added .idea/ in my .gitignore file.
2016/04/23
[ "https://Stackoverflow.com/questions/36815199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908141/" ]
I had a similar incident, but did not want to delete the `.idea` folder. After poking in the Preferences, I found that under Project Structure, the content root had gone missing. After clicking `Add Content Root` and double-clicking the root folder of the code, the subfolders are now visible. Hope this helps others as it looks like you found the solution!
Perhaps you are using the [Rails view](https://www.jetbrains.com/help/ruby/2016.1/rails-view.html) in the Project tool window? This view can sometimes mask some files. If so, switch the tool back to the Project view. Also, check that you have not excluded the directories in the [Project structure settings](https://www.jetbrains.com/help/ruby/2016.1/project-structure.html#d558390e238).
36,815,199
I am using RubyMine 8.0.3, I have **3 folders and 2 `.rb`** files in `controller/api/v1` , **none out of 3 folders are visible** but **both `.rb` files are visible**. I reopened the the IDE but nothing happened. I also tried the solutions mentioned in the following link: [RubyMine Folder Tree doesn't refresh](https://stackoverflow.com/questions/2796739/rubymine-folder-tree-doesnt-refresh) Note: 1: When I open my project in sublime all folders are visible. 2: I have added .idea/ in my .gitignore file.
2016/04/23
[ "https://Stackoverflow.com/questions/36815199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908141/" ]
I couldn't find the source of the problem, but deleting the `.idea/` folder worked for me.
In my case folders were empty that is why it was not visible, not sure why. As soon as I added(from terminal) some file to it. It started showing.
36,815,199
I am using RubyMine 8.0.3, I have **3 folders and 2 `.rb`** files in `controller/api/v1` , **none out of 3 folders are visible** but **both `.rb` files are visible**. I reopened the the IDE but nothing happened. I also tried the solutions mentioned in the following link: [RubyMine Folder Tree doesn't refresh](https://stackoverflow.com/questions/2796739/rubymine-folder-tree-doesnt-refresh) Note: 1: When I open my project in sublime all folders are visible. 2: I have added .idea/ in my .gitignore file.
2016/04/23
[ "https://Stackoverflow.com/questions/36815199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908141/" ]
I couldn't find the source of the problem, but deleting the `.idea/` folder worked for me.
I had a similar incident, but did not want to delete the `.idea` folder. After poking in the Preferences, I found that under Project Structure, the content root had gone missing. After clicking `Add Content Root` and double-clicking the root folder of the code, the subfolders are now visible. Hope this helps others as it looks like you found the solution!
36,815,199
I am using RubyMine 8.0.3, I have **3 folders and 2 `.rb`** files in `controller/api/v1` , **none out of 3 folders are visible** but **both `.rb` files are visible**. I reopened the the IDE but nothing happened. I also tried the solutions mentioned in the following link: [RubyMine Folder Tree doesn't refresh](https://stackoverflow.com/questions/2796739/rubymine-folder-tree-doesnt-refresh) Note: 1: When I open my project in sublime all folders are visible. 2: I have added .idea/ in my .gitignore file.
2016/04/23
[ "https://Stackoverflow.com/questions/36815199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908141/" ]
I had a similar incident, but did not want to delete the `.idea` folder. After poking in the Preferences, I found that under Project Structure, the content root had gone missing. After clicking `Add Content Root` and double-clicking the root folder of the code, the subfolders are now visible. Hope this helps others as it looks like you found the solution!
In my case folders were empty that is why it was not visible, not sure why. As soon as I added(from terminal) some file to it. It started showing.
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
You create an object that holds all three subkeys of the key as attributes. Make sure to implement `equals` and `hashCode` properly. ``` public class MyKey { public MyKey(String subkey1, String subkey2, String subkey3) { ... } } ``` Use such object as a key of your map: ``` Map<MyKey, String> myMap = ....; myMap.get(new MyKey("Thu", "03 Jan 2013 21:50:02 +0100", "Transferts - YBX")); ``` Have fun!
You could create a compound key which contains all of the values you want in the key. A simple way to do this could be to concatenate the together the values that make up your key, delimited by a value you are sure won't appear in the key values. E.g.: ``` String makeCompoundKey(String pubDate, String title) { return pubDate + "|" + title; } HashMap<String,String> map = new HashMap<String,String>(); map.put(makeComoundKey(pubDate,title), link) ``` To avoid the problem of having to choose a character which doesn't appear in any of the key values, to handle non-String keys and likely for better performance, you can declare a new class to contain your key values and override the `equals` and `hashCode` methods: ``` final class DateAndTitle { private final Date pubDate; private final String title; @Overrde boolean equals(Object rhs) { // let eclipse generate this for you, but it will probably look like ... return rhs != null && rhs.getClass() == getClass() && pubDate.equals(rhs.pubDate) && title.equals(rhs.title); } @Overrde int hashCode(Object) { // let eclipse generate this for you... ... } } ``` Then you can define your map like: HashMap and use DateAndTitle object to index your map.
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
You create an object that holds all three subkeys of the key as attributes. Make sure to implement `equals` and `hashCode` properly. ``` public class MyKey { public MyKey(String subkey1, String subkey2, String subkey3) { ... } } ``` Use such object as a key of your map: ``` Map<MyKey, String> myMap = ....; myMap.get(new MyKey("Thu", "03 Jan 2013 21:50:02 +0100", "Transferts - YBX")); ``` Have fun!
You could also try to use a nested hashmap, of the type `HashMap<String, HashMap<String, HashMap<String, String>>>`, where you would then formulate your query as `map.get(date).get(title).get(link)` The best solution would then be to encapsulate this nested hashmap in your own class as such: ``` public class NestedHashmap { private Map<String, Map<String, Map<String, String>>> map; public NestedHashMap() { map = new HashMap<String, HashMap<String, HashMap<String, String>>>; } public put(String date, String title, String link, String value){ if(map.get(date) == null) { map.put(date, new HashMap<String, HashMap<String, String>>; } if(map.get(date).get(title) == null){ map.get(date).put(new HashMap<String, String>); } map.get(date).get(title).put(link, value); } public get(String date, String title, String link) { // ...mostly analogous to put... } } ```
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
You create an object that holds all three subkeys of the key as attributes. Make sure to implement `equals` and `hashCode` properly. ``` public class MyKey { public MyKey(String subkey1, String subkey2, String subkey3) { ... } } ``` Use such object as a key of your map: ``` Map<MyKey, String> myMap = ....; myMap.get(new MyKey("Thu", "03 Jan 2013 21:50:02 +0100", "Transferts - YBX")); ``` Have fun!
In my case, I found another solution: is to create an ArrayList and put on it all the links on every for loop. That's a lot easier.
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
I just faced the same issue and decided to map my key to an [Entry](https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html). This allows for the same indexing features provided by a map while having more than one property associated with a key. I think it's a much neater solution that creating a separate class or nesting maps. ``` Map<String, Entry<Action, Boolean>> actionMap = new HashMap<String, Entry<Action, Boolean>>(); actionMap.put("action_name", new SimpleEntry(action, true)); ``` To use the data later: ``` Entry<Action, Boolean> actionMapEntry = actionMap.get("action_name"); if(actionMapEntry.value()) actionMapEntry.key().applyAction(); ``` My personal use of this was a map of named functions. Having selected the function by name, the function would be run and the boolean would determine whether or not cleanup was needed in processing.
You create an object that holds all three subkeys of the key as attributes. Make sure to implement `equals` and `hashCode` properly. ``` public class MyKey { public MyKey(String subkey1, String subkey2, String subkey3) { ... } } ``` Use such object as a key of your map: ``` Map<MyKey, String> myMap = ....; myMap.get(new MyKey("Thu", "03 Jan 2013 21:50:02 +0100", "Transferts - YBX")); ``` Have fun!
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
You could create a compound key which contains all of the values you want in the key. A simple way to do this could be to concatenate the together the values that make up your key, delimited by a value you are sure won't appear in the key values. E.g.: ``` String makeCompoundKey(String pubDate, String title) { return pubDate + "|" + title; } HashMap<String,String> map = new HashMap<String,String>(); map.put(makeComoundKey(pubDate,title), link) ``` To avoid the problem of having to choose a character which doesn't appear in any of the key values, to handle non-String keys and likely for better performance, you can declare a new class to contain your key values and override the `equals` and `hashCode` methods: ``` final class DateAndTitle { private final Date pubDate; private final String title; @Overrde boolean equals(Object rhs) { // let eclipse generate this for you, but it will probably look like ... return rhs != null && rhs.getClass() == getClass() && pubDate.equals(rhs.pubDate) && title.equals(rhs.title); } @Overrde int hashCode(Object) { // let eclipse generate this for you... ... } } ``` Then you can define your map like: HashMap and use DateAndTitle object to index your map.
In my case, I found another solution: is to create an ArrayList and put on it all the links on every for loop. That's a lot easier.
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
I just faced the same issue and decided to map my key to an [Entry](https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html). This allows for the same indexing features provided by a map while having more than one property associated with a key. I think it's a much neater solution that creating a separate class or nesting maps. ``` Map<String, Entry<Action, Boolean>> actionMap = new HashMap<String, Entry<Action, Boolean>>(); actionMap.put("action_name", new SimpleEntry(action, true)); ``` To use the data later: ``` Entry<Action, Boolean> actionMapEntry = actionMap.get("action_name"); if(actionMapEntry.value()) actionMapEntry.key().applyAction(); ``` My personal use of this was a map of named functions. Having selected the function by name, the function would be run and the boolean would determine whether or not cleanup was needed in processing.
You could create a compound key which contains all of the values you want in the key. A simple way to do this could be to concatenate the together the values that make up your key, delimited by a value you are sure won't appear in the key values. E.g.: ``` String makeCompoundKey(String pubDate, String title) { return pubDate + "|" + title; } HashMap<String,String> map = new HashMap<String,String>(); map.put(makeComoundKey(pubDate,title), link) ``` To avoid the problem of having to choose a character which doesn't appear in any of the key values, to handle non-String keys and likely for better performance, you can declare a new class to contain your key values and override the `equals` and `hashCode` methods: ``` final class DateAndTitle { private final Date pubDate; private final String title; @Overrde boolean equals(Object rhs) { // let eclipse generate this for you, but it will probably look like ... return rhs != null && rhs.getClass() == getClass() && pubDate.equals(rhs.pubDate) && title.equals(rhs.title); } @Overrde int hashCode(Object) { // let eclipse generate this for you... ... } } ``` Then you can define your map like: HashMap and use DateAndTitle object to index your map.
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
You could also try to use a nested hashmap, of the type `HashMap<String, HashMap<String, HashMap<String, String>>>`, where you would then formulate your query as `map.get(date).get(title).get(link)` The best solution would then be to encapsulate this nested hashmap in your own class as such: ``` public class NestedHashmap { private Map<String, Map<String, Map<String, String>>> map; public NestedHashMap() { map = new HashMap<String, HashMap<String, HashMap<String, String>>>; } public put(String date, String title, String link, String value){ if(map.get(date) == null) { map.put(date, new HashMap<String, HashMap<String, String>>; } if(map.get(date).get(title) == null){ map.get(date).put(new HashMap<String, String>); } map.get(date).get(title).put(link, value); } public get(String date, String title, String link) { // ...mostly analogous to put... } } ```
In my case, I found another solution: is to create an ArrayList and put on it all the links on every for loop. That's a lot easier.
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
I just faced the same issue and decided to map my key to an [Entry](https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html). This allows for the same indexing features provided by a map while having more than one property associated with a key. I think it's a much neater solution that creating a separate class or nesting maps. ``` Map<String, Entry<Action, Boolean>> actionMap = new HashMap<String, Entry<Action, Boolean>>(); actionMap.put("action_name", new SimpleEntry(action, true)); ``` To use the data later: ``` Entry<Action, Boolean> actionMapEntry = actionMap.get("action_name"); if(actionMapEntry.value()) actionMapEntry.key().applyAction(); ``` My personal use of this was a map of named functions. Having selected the function by name, the function would be run and the boolean would determine whether or not cleanup was needed in processing.
You could also try to use a nested hashmap, of the type `HashMap<String, HashMap<String, HashMap<String, String>>>`, where you would then formulate your query as `map.get(date).get(title).get(link)` The best solution would then be to encapsulate this nested hashmap in your own class as such: ``` public class NestedHashmap { private Map<String, Map<String, Map<String, String>>> map; public NestedHashMap() { map = new HashMap<String, HashMap<String, HashMap<String, String>>>; } public put(String date, String title, String link, String value){ if(map.get(date) == null) { map.put(date, new HashMap<String, HashMap<String, String>>; } if(map.get(date).get(title) == null){ map.get(date).put(new HashMap<String, String>); } map.get(date).get(title).put(link, value); } public get(String date, String title, String link) { // ...mostly analogous to put... } } ```
14,148,337
I have made an tracking app in android which successfully generates latitude and longitude but I need to store lat and long in my external mySQL database using PHP. I am using value type "decimal(10,7)" for lat and long in DB. Any ideas how to store lat and long generated from android into my external mySQL database using PHP? **My PHP CODE** ``` <?php $lat = $_GET['lat']; $lng = $_GET['lng']; $sender=$_POST['sender']; $hostname = 'localhost'; $username = 'xxxx'; $password = 'xxxxxxx'; $conn = mysql_connect($hostname,$username,$password) or die('Error Please Try Again.'); if ($conn) { mysql_select_db("android track", $conn); $query2 = "INSERT INTO coor VALUES(NULL,'$sender','$lat','$lng')"; if (mysql_query($query2, $conn)) echo "Data Insertion Successful"; else echo "Oops". mysql_error() ; } mysql_close(); ?> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14148337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1910348/" ]
I just faced the same issue and decided to map my key to an [Entry](https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html). This allows for the same indexing features provided by a map while having more than one property associated with a key. I think it's a much neater solution that creating a separate class or nesting maps. ``` Map<String, Entry<Action, Boolean>> actionMap = new HashMap<String, Entry<Action, Boolean>>(); actionMap.put("action_name", new SimpleEntry(action, true)); ``` To use the data later: ``` Entry<Action, Boolean> actionMapEntry = actionMap.get("action_name"); if(actionMapEntry.value()) actionMapEntry.key().applyAction(); ``` My personal use of this was a map of named functions. Having selected the function by name, the function would be run and the boolean would determine whether or not cleanup was needed in processing.
In my case, I found another solution: is to create an ArrayList and put on it all the links on every for loop. That's a lot easier.